master_grpc_server.go 9.2 KB

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