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.

317 lines
9.6 KiB

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