You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

302 lines
8.4 KiB

6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
  1. package weed_server
  2. import (
  3. "context"
  4. "fmt"
  5. "net"
  6. "strings"
  7. "time"
  8. "github.com/chrislusf/raft"
  9. "google.golang.org/grpc/peer"
  10. "github.com/chrislusf/seaweedfs/weed/glog"
  11. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  12. "github.com/chrislusf/seaweedfs/weed/storage/backend"
  13. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  14. "github.com/chrislusf/seaweedfs/weed/topology"
  15. )
  16. func (ms *MasterServer) SendHeartbeat(stream master_pb.Seaweed_SendHeartbeatServer) error {
  17. var dn *topology.DataNode
  18. t := ms.Topo
  19. defer func() {
  20. if dn != nil {
  21. glog.V(0).Infof("unregister disconnected volume server %s:%d", dn.Ip, dn.Port)
  22. t.UnRegisterDataNode(dn)
  23. message := &master_pb.VolumeLocation{
  24. Url: dn.Url(),
  25. PublicUrl: dn.PublicUrl,
  26. }
  27. for _, v := range dn.GetVolumes() {
  28. message.DeletedVids = append(message.DeletedVids, uint32(v.Id))
  29. }
  30. for _, s := range dn.GetEcShards() {
  31. message.DeletedVids = append(message.DeletedVids, uint32(s.VolumeId))
  32. }
  33. if len(message.DeletedVids) > 0 {
  34. ms.clientChansLock.RLock()
  35. for _, ch := range ms.clientChans {
  36. ch <- message
  37. }
  38. ms.clientChansLock.RUnlock()
  39. }
  40. }
  41. }()
  42. for {
  43. heartbeat, err := stream.Recv()
  44. if err != nil {
  45. if dn != nil {
  46. glog.Warningf("SendHeartbeat.Recv server %s:%d : %v", dn.Ip, dn.Port, err)
  47. } else {
  48. glog.Warningf("SendHeartbeat.Recv: %v", err)
  49. }
  50. return err
  51. }
  52. t.Sequence.SetMax(heartbeat.MaxFileKey)
  53. if dn == nil {
  54. dcName, rackName := t.Configuration.Locate(heartbeat.Ip, heartbeat.DataCenter, heartbeat.Rack)
  55. dc := t.GetOrCreateDataCenter(dcName)
  56. rack := dc.GetOrCreateRack(rackName)
  57. dn = rack.GetOrCreateDataNode(heartbeat.Ip,
  58. int(heartbeat.Port), heartbeat.PublicUrl,
  59. int64(heartbeat.MaxVolumeCount))
  60. glog.V(0).Infof("added volume server %v:%d", heartbeat.GetIp(), heartbeat.GetPort())
  61. if err := stream.Send(&master_pb.HeartbeatResponse{
  62. VolumeSizeLimit: uint64(ms.option.VolumeSizeLimitMB) * 1024 * 1024,
  63. MetricsAddress: ms.option.MetricsAddress,
  64. MetricsIntervalSeconds: uint32(ms.option.MetricsIntervalSec),
  65. StorageBackends: backend.ToPbStorageBackends(),
  66. }); err != nil {
  67. glog.Warningf("SendHeartbeat.Send volume size to %s:%d %v", dn.Ip, dn.Port, err)
  68. return err
  69. }
  70. }
  71. if heartbeat.MaxVolumeCount != 0 && dn.GetMaxVolumeCount() != int64(heartbeat.MaxVolumeCount) {
  72. delta := int64(heartbeat.MaxVolumeCount) - dn.GetMaxVolumeCount()
  73. dn.UpAdjustMaxVolumeCountDelta(delta)
  74. }
  75. glog.V(4).Infof("master received heartbeat %s", heartbeat.String())
  76. message := &master_pb.VolumeLocation{
  77. Url: dn.Url(),
  78. PublicUrl: dn.PublicUrl,
  79. }
  80. if len(heartbeat.NewVolumes) > 0 || len(heartbeat.DeletedVolumes) > 0 {
  81. // process delta volume ids if exists for fast volume id updates
  82. for _, volInfo := range heartbeat.NewVolumes {
  83. message.NewVids = append(message.NewVids, volInfo.Id)
  84. }
  85. for _, volInfo := range heartbeat.DeletedVolumes {
  86. message.DeletedVids = append(message.DeletedVids, volInfo.Id)
  87. }
  88. // update master internal volume layouts
  89. t.IncrementalSyncDataNodeRegistration(heartbeat.NewVolumes, heartbeat.DeletedVolumes, dn)
  90. }
  91. if len(heartbeat.Volumes) > 0 || heartbeat.HasNoVolumes {
  92. // process heartbeat.Volumes
  93. newVolumes, deletedVolumes := t.SyncDataNodeRegistration(heartbeat.Volumes, dn)
  94. for _, v := range newVolumes {
  95. glog.V(0).Infof("master see new volume %d from %s", uint32(v.Id), dn.Url())
  96. message.NewVids = append(message.NewVids, uint32(v.Id))
  97. }
  98. for _, v := range deletedVolumes {
  99. glog.V(0).Infof("master see deleted volume %d from %s", uint32(v.Id), dn.Url())
  100. message.DeletedVids = append(message.DeletedVids, uint32(v.Id))
  101. }
  102. }
  103. if len(heartbeat.NewEcShards) > 0 || len(heartbeat.DeletedEcShards) > 0 {
  104. // update master internal volume layouts
  105. t.IncrementalSyncDataNodeEcShards(heartbeat.NewEcShards, heartbeat.DeletedEcShards, dn)
  106. for _, s := range heartbeat.NewEcShards {
  107. message.NewVids = append(message.NewVids, s.Id)
  108. }
  109. for _, s := range heartbeat.DeletedEcShards {
  110. if dn.HasVolumesById(needle.VolumeId(s.Id)) {
  111. continue
  112. }
  113. message.DeletedVids = append(message.DeletedVids, s.Id)
  114. }
  115. }
  116. if len(heartbeat.EcShards) > 0 || heartbeat.HasNoEcShards {
  117. glog.V(1).Infof("master recieved ec shards from %s: %+v", dn.Url(), heartbeat.EcShards)
  118. newShards, deletedShards := t.SyncDataNodeEcShards(heartbeat.EcShards, dn)
  119. // broadcast the ec vid changes to master clients
  120. for _, s := range newShards {
  121. message.NewVids = append(message.NewVids, uint32(s.VolumeId))
  122. }
  123. for _, s := range deletedShards {
  124. if dn.HasVolumesById(s.VolumeId) {
  125. continue
  126. }
  127. message.DeletedVids = append(message.DeletedVids, uint32(s.VolumeId))
  128. }
  129. }
  130. if len(message.NewVids) > 0 || len(message.DeletedVids) > 0 {
  131. ms.clientChansLock.RLock()
  132. for host, ch := range ms.clientChans {
  133. glog.V(0).Infof("master send to %s: %s", host, message.String())
  134. ch <- message
  135. }
  136. ms.clientChansLock.RUnlock()
  137. }
  138. // tell the volume servers about the leader
  139. newLeader, err := t.Leader()
  140. if err != nil {
  141. glog.Warningf("SendHeartbeat find leader: %v", err)
  142. return err
  143. }
  144. if err := stream.Send(&master_pb.HeartbeatResponse{
  145. Leader: newLeader,
  146. }); err != nil {
  147. glog.Warningf("SendHeartbeat.Send response to to %s:%d %v", dn.Ip, dn.Port, err)
  148. return err
  149. }
  150. }
  151. }
  152. // KeepConnected keep a stream gRPC call to the master. Used by clients to know the master is up.
  153. // And clients gets the up-to-date list of volume locations
  154. func (ms *MasterServer) KeepConnected(stream master_pb.Seaweed_KeepConnectedServer) error {
  155. req, err := stream.Recv()
  156. if err != nil {
  157. return err
  158. }
  159. if !ms.Topo.IsLeader() {
  160. return ms.informNewLeader(stream)
  161. }
  162. peerAddress := findClientAddress(stream.Context(), req.GrpcPort)
  163. stopChan := make(chan bool)
  164. clientName, messageChan := ms.addClient(req.Name, peerAddress)
  165. defer ms.deleteClient(clientName)
  166. for _, message := range ms.Topo.ToVolumeLocations() {
  167. if err := stream.Send(message); err != nil {
  168. return err
  169. }
  170. }
  171. go func() {
  172. for {
  173. _, err := stream.Recv()
  174. if err != nil {
  175. glog.V(2).Infof("- client %v: %v", clientName, err)
  176. stopChan <- true
  177. break
  178. }
  179. }
  180. }()
  181. ticker := time.NewTicker(5 * time.Second)
  182. for {
  183. select {
  184. case message := <-messageChan:
  185. if err := stream.Send(message); err != nil {
  186. glog.V(0).Infof("=> client %v: %+v", clientName, message)
  187. return err
  188. }
  189. case <-ticker.C:
  190. if !ms.Topo.IsLeader() {
  191. return ms.informNewLeader(stream)
  192. }
  193. case <-stopChan:
  194. return nil
  195. }
  196. }
  197. return nil
  198. }
  199. func (ms *MasterServer) informNewLeader(stream master_pb.Seaweed_KeepConnectedServer) error {
  200. leader, err := ms.Topo.Leader()
  201. if err != nil {
  202. glog.Errorf("topo leader: %v", err)
  203. return raft.NotLeaderError
  204. }
  205. if err := stream.Send(&master_pb.VolumeLocation{
  206. Leader: leader,
  207. }); err != nil {
  208. return err
  209. }
  210. return nil
  211. }
  212. func (ms *MasterServer) addClient(clientType string, clientAddress string) (clientName string, messageChan chan *master_pb.VolumeLocation) {
  213. clientName = clientType + "@" + clientAddress
  214. glog.V(0).Infof("+ client %v", clientName)
  215. messageChan = make(chan *master_pb.VolumeLocation)
  216. ms.clientChansLock.Lock()
  217. ms.clientChans[clientName] = messageChan
  218. ms.clientChansLock.Unlock()
  219. return
  220. }
  221. func (ms *MasterServer) deleteClient(clientName string) {
  222. glog.V(0).Infof("- client %v", clientName)
  223. ms.clientChansLock.Lock()
  224. delete(ms.clientChans, clientName)
  225. ms.clientChansLock.Unlock()
  226. }
  227. func findClientAddress(ctx context.Context, grpcPort uint32) string {
  228. // fmt.Printf("FromContext %+v\n", ctx)
  229. pr, ok := peer.FromContext(ctx)
  230. if !ok {
  231. glog.Error("failed to get peer from ctx")
  232. return ""
  233. }
  234. if pr.Addr == net.Addr(nil) {
  235. glog.Error("failed to get peer address")
  236. return ""
  237. }
  238. if grpcPort == 0 {
  239. return pr.Addr.String()
  240. }
  241. if tcpAddr, ok := pr.Addr.(*net.TCPAddr); ok {
  242. externalIP := tcpAddr.IP
  243. return fmt.Sprintf("%s:%d", externalIP, grpcPort)
  244. }
  245. return pr.Addr.String()
  246. }
  247. func (ms *MasterServer) ListMasterClients(ctx context.Context, req *master_pb.ListMasterClientsRequest) (*master_pb.ListMasterClientsResponse, error) {
  248. resp := &master_pb.ListMasterClientsResponse{}
  249. ms.clientChansLock.RLock()
  250. defer ms.clientChansLock.RUnlock()
  251. for k := range ms.clientChans {
  252. if strings.HasPrefix(k, req.ClientType+"@") {
  253. resp.GrpcAddresses = append(resp.GrpcAddresses, k[len(req.ClientType)+1:])
  254. }
  255. }
  256. return resp, nil
  257. }