master_grpc_server.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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. 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,
  59. int(heartbeat.Port), heartbeat.PublicUrl,
  60. int64(heartbeat.MaxVolumeCount))
  61. glog.V(0).Infof("added volume server %v:%d", heartbeat.GetIp(), heartbeat.GetPort())
  62. if err := stream.Send(&master_pb.HeartbeatResponse{
  63. VolumeSizeLimit: uint64(ms.option.VolumeSizeLimitMB) * 1024 * 1024,
  64. MetricsAddress: ms.option.MetricsAddress,
  65. MetricsIntervalSeconds: uint32(ms.option.MetricsIntervalSec),
  66. StorageBackends: backend.ToPbStorageBackends(),
  67. }); err != nil {
  68. glog.Warningf("SendHeartbeat.Send volume size to %s:%d %v", dn.Ip, dn.Port, err)
  69. return err
  70. }
  71. }
  72. if heartbeat.MaxVolumeCount != 0 && dn.GetMaxVolumeCount() != int64(heartbeat.MaxVolumeCount) {
  73. delta := int64(heartbeat.MaxVolumeCount) - dn.GetMaxVolumeCount()
  74. dn.UpAdjustMaxVolumeCountDelta(delta)
  75. }
  76. glog.V(5).Infof("master received heartbeat %s", heartbeat.String())
  77. message := &master_pb.VolumeLocation{
  78. Url: dn.Url(),
  79. PublicUrl: dn.PublicUrl,
  80. }
  81. if len(heartbeat.NewVolumes) > 0 || len(heartbeat.DeletedVolumes) > 0 {
  82. // process delta volume ids if exists for fast volume id updates
  83. for _, volInfo := range heartbeat.NewVolumes {
  84. message.NewVids = append(message.NewVids, volInfo.Id)
  85. }
  86. for _, volInfo := range heartbeat.DeletedVolumes {
  87. message.DeletedVids = append(message.DeletedVids, volInfo.Id)
  88. }
  89. // update master internal volume layouts
  90. ms.Topo.IncrementalSyncDataNodeRegistration(heartbeat.NewVolumes, heartbeat.DeletedVolumes, dn)
  91. }
  92. if len(heartbeat.Volumes) > 0 || heartbeat.HasNoVolumes {
  93. // process heartbeat.Volumes
  94. newVolumes, deletedVolumes := ms.Topo.SyncDataNodeRegistration(heartbeat.Volumes, dn)
  95. for _, v := range newVolumes {
  96. glog.V(0).Infof("master see new volume %d from %s", uint32(v.Id), dn.Url())
  97. message.NewVids = append(message.NewVids, uint32(v.Id))
  98. }
  99. for _, v := range deletedVolumes {
  100. glog.V(0).Infof("master see deleted volume %d from %s", uint32(v.Id), dn.Url())
  101. message.DeletedVids = append(message.DeletedVids, uint32(v.Id))
  102. }
  103. }
  104. if len(heartbeat.NewEcShards) > 0 || len(heartbeat.DeletedEcShards) > 0 {
  105. // update master internal volume layouts
  106. ms.Topo.IncrementalSyncDataNodeEcShards(heartbeat.NewEcShards, heartbeat.DeletedEcShards, dn)
  107. for _, s := range heartbeat.NewEcShards {
  108. message.NewVids = append(message.NewVids, s.Id)
  109. }
  110. for _, s := range heartbeat.DeletedEcShards {
  111. if dn.HasVolumesById(needle.VolumeId(s.Id)) {
  112. continue
  113. }
  114. message.DeletedVids = append(message.DeletedVids, s.Id)
  115. }
  116. }
  117. if len(heartbeat.EcShards) > 0 || heartbeat.HasNoEcShards {
  118. glog.V(1).Infof("master recieved ec shards from %s: %+v", dn.Url(), heartbeat.EcShards)
  119. newShards, deletedShards := ms.Topo.SyncDataNodeEcShards(heartbeat.EcShards, dn)
  120. // broadcast the ec vid changes to master clients
  121. for _, s := range newShards {
  122. message.NewVids = append(message.NewVids, uint32(s.VolumeId))
  123. }
  124. for _, s := range deletedShards {
  125. if dn.HasVolumesById(s.VolumeId) {
  126. continue
  127. }
  128. message.DeletedVids = append(message.DeletedVids, uint32(s.VolumeId))
  129. }
  130. }
  131. if len(message.NewVids) > 0 || len(message.DeletedVids) > 0 {
  132. ms.clientChansLock.RLock()
  133. for host, ch := range ms.clientChans {
  134. glog.V(0).Infof("master send to %s: %s", host, message.String())
  135. ch <- message
  136. }
  137. ms.clientChansLock.RUnlock()
  138. }
  139. // tell the volume servers about the leader
  140. newLeader, err := ms.Topo.Leader()
  141. if err != nil {
  142. glog.Warningf("SendHeartbeat find leader: %v", err)
  143. return err
  144. }
  145. if err := stream.Send(&master_pb.HeartbeatResponse{
  146. Leader: newLeader,
  147. }); err != nil {
  148. glog.Warningf("SendHeartbeat.Send response to to %s:%d %v", dn.Ip, dn.Port, err)
  149. return err
  150. }
  151. }
  152. }
  153. // KeepConnected keep a stream gRPC call to the master. Used by clients to know the master is up.
  154. // And clients gets the up-to-date list of volume locations
  155. func (ms *MasterServer) KeepConnected(stream master_pb.Seaweed_KeepConnectedServer) error {
  156. req, err := stream.Recv()
  157. if err != nil {
  158. return err
  159. }
  160. if !ms.Topo.IsLeader() {
  161. return ms.informNewLeader(stream)
  162. }
  163. peerAddress := findClientAddress(stream.Context(), req.GrpcPort)
  164. stopChan := make(chan bool)
  165. clientName, messageChan := ms.addClient(req.Name, peerAddress)
  166. defer ms.deleteClient(clientName)
  167. for _, message := range ms.Topo.ToVolumeLocations() {
  168. if err := stream.Send(message); err != nil {
  169. return err
  170. }
  171. }
  172. go func() {
  173. for {
  174. _, err := stream.Recv()
  175. if err != nil {
  176. glog.V(2).Infof("- client %v: %v", clientName, err)
  177. stopChan <- true
  178. break
  179. }
  180. }
  181. }()
  182. ticker := time.NewTicker(5 * time.Second)
  183. for {
  184. select {
  185. case message := <-messageChan:
  186. if err := stream.Send(message); err != nil {
  187. glog.V(0).Infof("=> client %v: %+v", clientName, message)
  188. return err
  189. }
  190. case <-ticker.C:
  191. if !ms.Topo.IsLeader() {
  192. return ms.informNewLeader(stream)
  193. }
  194. case <-stopChan:
  195. return nil
  196. }
  197. }
  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. }