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.

322 lines
9.8 KiB

6 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
3 years ago
3 years ago
4 years ago
5 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.broadcastToClients(&master_pb.KeepConnectedResponse{VolumeLocation: message})
  41. }
  42. }
  43. }()
  44. for {
  45. heartbeat, err := stream.Recv()
  46. if err != nil {
  47. if dn != nil {
  48. glog.Warningf("SendHeartbeat.Recv server %s:%d : %v", dn.Ip, dn.Port, err)
  49. } else {
  50. glog.Warningf("SendHeartbeat.Recv: %v", err)
  51. }
  52. return err
  53. }
  54. ms.Topo.Sequence.SetMax(heartbeat.MaxFileKey)
  55. if dn == nil {
  56. dcName, rackName := ms.Topo.Configuration.Locate(heartbeat.Ip, heartbeat.DataCenter, heartbeat.Rack)
  57. dc := ms.Topo.GetOrCreateDataCenter(dcName)
  58. rack := dc.GetOrCreateRack(rackName)
  59. dn = rack.GetOrCreateDataNode(heartbeat.Ip, int(heartbeat.Port), int(heartbeat.GrpcPort), heartbeat.PublicUrl, heartbeat.MaxVolumeCounts)
  60. glog.V(0).Infof("added volume server %d: %v:%d", dn.Counter, heartbeat.GetIp(), heartbeat.GetPort())
  61. if err := stream.Send(&master_pb.HeartbeatResponse{
  62. VolumeSizeLimit: uint64(ms.option.VolumeSizeLimitMB) * 1024 * 1024,
  63. }); err != nil {
  64. glog.Warningf("SendHeartbeat.Send volume size to %s:%d %v", dn.Ip, dn.Port, err)
  65. return err
  66. }
  67. dn.Counter++
  68. }
  69. dn.AdjustMaxVolumeCounts(heartbeat.MaxVolumeCounts)
  70. glog.V(4).Infof("master received heartbeat %s", heartbeat.String())
  71. var dataCenter string
  72. if dc := dn.GetDataCenter(); dc != nil {
  73. dataCenter = string(dc.Id())
  74. }
  75. message := &master_pb.VolumeLocation{
  76. Url: dn.Url(),
  77. PublicUrl: dn.PublicUrl,
  78. DataCenter: dataCenter,
  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. ms.Topo.IncrementalSyncDataNodeRegistration(heartbeat.NewVolumes, heartbeat.DeletedVolumes, dn)
  90. }
  91. if len(heartbeat.Volumes) > 0 || heartbeat.HasNoVolumes {
  92. // process heartbeat.Volumes
  93. newVolumes, deletedVolumes := ms.Topo.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. ms.Topo.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 received ec shards from %s: %+v", dn.Url(), heartbeat.EcShards)
  118. newShards, deletedShards := ms.Topo.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.broadcastToClients(&master_pb.KeepConnectedResponse{VolumeLocation: message})
  132. }
  133. // tell the volume servers about the leader
  134. newLeader, err := ms.Topo.Leader()
  135. if err != nil {
  136. glog.Warningf("SendHeartbeat find leader: %v", err)
  137. return err
  138. }
  139. if err := stream.Send(&master_pb.HeartbeatResponse{
  140. Leader: string(newLeader),
  141. }); err != nil {
  142. glog.Warningf("SendHeartbeat.Send response to to %s:%d %v", dn.Ip, dn.Port, err)
  143. return err
  144. }
  145. }
  146. }
  147. // KeepConnected keep a stream gRPC call to the master. Used by clients to know the master is up.
  148. // And clients gets the up-to-date list of volume locations
  149. func (ms *MasterServer) KeepConnected(stream master_pb.Seaweed_KeepConnectedServer) error {
  150. req, recvErr := stream.Recv()
  151. if recvErr != nil {
  152. return recvErr
  153. }
  154. if !ms.Topo.IsLeader() {
  155. return ms.informNewLeader(stream)
  156. }
  157. peerAddress := pb.ServerAddress(req.ClientAddress)
  158. // buffer by 1 so we don't end up getting stuck writing to stopChan forever
  159. stopChan := make(chan bool, 1)
  160. clientName, messageChan := ms.addClient(req.ClientType, peerAddress)
  161. for _, update := range ms.Cluster.AddClusterNode(req.ClientType, peerAddress, req.Version) {
  162. ms.broadcastToClients(update)
  163. }
  164. defer func() {
  165. for _, update := range ms.Cluster.RemoveClusterNode(req.ClientType, peerAddress) {
  166. ms.broadcastToClients(update)
  167. }
  168. ms.deleteClient(clientName)
  169. }()
  170. for _, message := range ms.Topo.ToVolumeLocations() {
  171. if sendErr := stream.Send(&master_pb.KeepConnectedResponse{VolumeLocation: message}); sendErr != nil {
  172. return sendErr
  173. }
  174. }
  175. go func() {
  176. for {
  177. _, err := stream.Recv()
  178. if err != nil {
  179. glog.V(2).Infof("- client %v: %v", clientName, err)
  180. close(stopChan)
  181. return
  182. }
  183. }
  184. }()
  185. ticker := time.NewTicker(5 * time.Second)
  186. for {
  187. select {
  188. case message := <-messageChan:
  189. if err := stream.Send(message); err != nil {
  190. glog.V(0).Infof("=> client %v: %+v", clientName, message)
  191. return err
  192. }
  193. case <-ticker.C:
  194. if !ms.Topo.IsLeader() {
  195. return ms.informNewLeader(stream)
  196. }
  197. case <-stopChan:
  198. return nil
  199. }
  200. }
  201. }
  202. func (ms *MasterServer) broadcastToClients(message *master_pb.KeepConnectedResponse) {
  203. ms.clientChansLock.RLock()
  204. for _, ch := range ms.clientChans {
  205. ch <- message
  206. }
  207. ms.clientChansLock.RUnlock()
  208. }
  209. func (ms *MasterServer) informNewLeader(stream master_pb.Seaweed_KeepConnectedServer) error {
  210. leader, err := ms.Topo.Leader()
  211. if err != nil {
  212. glog.Errorf("topo leader: %v", err)
  213. return raft.NotLeaderError
  214. }
  215. if err := stream.Send(&master_pb.KeepConnectedResponse{
  216. VolumeLocation: &master_pb.VolumeLocation{
  217. Leader: string(leader),
  218. },
  219. }); err != nil {
  220. return err
  221. }
  222. return nil
  223. }
  224. func (ms *MasterServer) addClient(clientType string, clientAddress pb.ServerAddress) (clientName string, messageChan chan *master_pb.KeepConnectedResponse) {
  225. clientName = clientType + "@" + string(clientAddress)
  226. glog.V(0).Infof("+ client %v", clientName)
  227. // we buffer this because otherwise we end up in a potential deadlock where
  228. // the KeepConnected loop is no longer listening on this channel but we're
  229. // trying to send to it in SendHeartbeat and so we can't lock the
  230. // clientChansLock to remove the channel and we're stuck writing to it
  231. // 100 is probably overkill
  232. messageChan = make(chan *master_pb.KeepConnectedResponse, 100)
  233. ms.clientChansLock.Lock()
  234. ms.clientChans[clientName] = messageChan
  235. ms.clientChansLock.Unlock()
  236. return
  237. }
  238. func (ms *MasterServer) deleteClient(clientName string) {
  239. glog.V(0).Infof("- client %v", clientName)
  240. ms.clientChansLock.Lock()
  241. delete(ms.clientChans, clientName)
  242. ms.clientChansLock.Unlock()
  243. }
  244. func findClientAddress(ctx context.Context, grpcPort uint32) string {
  245. // fmt.Printf("FromContext %+v\n", ctx)
  246. pr, ok := peer.FromContext(ctx)
  247. if !ok {
  248. glog.Error("failed to get peer from ctx")
  249. return ""
  250. }
  251. if pr.Addr == net.Addr(nil) {
  252. glog.Error("failed to get peer address")
  253. return ""
  254. }
  255. if grpcPort == 0 {
  256. return pr.Addr.String()
  257. }
  258. if tcpAddr, ok := pr.Addr.(*net.TCPAddr); ok {
  259. externalIP := tcpAddr.IP
  260. return util.JoinHostPort(externalIP.String(), int(grpcPort))
  261. }
  262. return pr.Addr.String()
  263. }
  264. func (ms *MasterServer) GetMasterConfiguration(ctx context.Context, req *master_pb.GetMasterConfigurationRequest) (*master_pb.GetMasterConfigurationResponse, error) {
  265. // tell the volume servers about the leader
  266. leader, _ := ms.Topo.Leader()
  267. resp := &master_pb.GetMasterConfigurationResponse{
  268. MetricsAddress: ms.option.MetricsAddress,
  269. MetricsIntervalSeconds: uint32(ms.option.MetricsIntervalSec),
  270. StorageBackends: backend.ToPbStorageBackends(),
  271. DefaultReplication: ms.option.DefaultReplicaPlacement,
  272. VolumeSizeLimitMB: uint32(ms.option.VolumeSizeLimitMB),
  273. VolumePreallocate: ms.option.VolumePreallocate,
  274. Leader: string(leader),
  275. }
  276. return resp, nil
  277. }