master_grpc_server.go 11 KB

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