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.

323 lines
9.7 KiB

6 years ago
6 years ago
4 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
4 years ago
6 years ago
6 years ago
6 years ago
4 years ago
4 years ago
6 years ago
4 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
  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, int64(heartbeat.MaxVolumeCount), int64(heartbeat.MaxSsdVolumeCount))
  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. if heartbeat.MaxVolumeCount != 0 && dn.GetMaxVolumeCount() != int64(heartbeat.MaxVolumeCount) {
  68. delta := int64(heartbeat.MaxVolumeCount) - dn.GetMaxVolumeCount()
  69. dn.UpAdjustMaxVolumeCountDelta(delta)
  70. }
  71. if heartbeat.MaxSsdVolumeCount != 0 && dn.GetMaxSsdVolumeCount() != int64(heartbeat.MaxSsdVolumeCount) {
  72. delta := int64(heartbeat.MaxSsdVolumeCount) - dn.GetMaxSsdVolumeCount()
  73. dn.UpAdjustMaxSsdVolumeCountDelta(delta)
  74. }
  75. glog.V(4).Infof("master received heartbeat %s", heartbeat.String())
  76. message := &master_pb.VolumeLocation{
  77. Url: dn.Url(),
  78. PublicUrl: dn.PublicUrl,
  79. DataCenter: string(dn.GetDataCenter().Id()),
  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 received 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. // buffer by 1 so we don't end up getting stuck writing to stopChan forever
  165. stopChan := make(chan bool, 1)
  166. clientName, messageChan := ms.addClient(req.Name, peerAddress)
  167. defer ms.deleteClient(clientName)
  168. for _, message := range ms.Topo.ToVolumeLocations() {
  169. if err := stream.Send(message); err != nil {
  170. return err
  171. }
  172. }
  173. go func() {
  174. for {
  175. _, err := stream.Recv()
  176. if err != nil {
  177. glog.V(2).Infof("- client %v: %v", clientName, err)
  178. stopChan <- true
  179. break
  180. }
  181. }
  182. }()
  183. ticker := time.NewTicker(5 * time.Second)
  184. for {
  185. select {
  186. case message := <-messageChan:
  187. if err := stream.Send(message); err != nil {
  188. glog.V(0).Infof("=> client %v: %+v", clientName, message)
  189. return err
  190. }
  191. case <-ticker.C:
  192. if !ms.Topo.IsLeader() {
  193. return ms.informNewLeader(stream)
  194. }
  195. case <-stopChan:
  196. return nil
  197. }
  198. }
  199. }
  200. func (ms *MasterServer) informNewLeader(stream master_pb.Seaweed_KeepConnectedServer) error {
  201. leader, err := ms.Topo.Leader()
  202. if err != nil {
  203. glog.Errorf("topo leader: %v", err)
  204. return raft.NotLeaderError
  205. }
  206. if err := stream.Send(&master_pb.VolumeLocation{
  207. Leader: leader,
  208. }); err != nil {
  209. return err
  210. }
  211. return nil
  212. }
  213. func (ms *MasterServer) addClient(clientType string, clientAddress string) (clientName string, messageChan chan *master_pb.VolumeLocation) {
  214. clientName = clientType + "@" + clientAddress
  215. glog.V(0).Infof("+ client %v", clientName)
  216. // we buffer this because otherwise we end up in a potential deadlock where
  217. // the KeepConnected loop is no longer listening on this channel but we're
  218. // trying to send to it in SendHeartbeat and so we can't lock the
  219. // clientChansLock to remove the channel and we're stuck writing to it
  220. // 100 is probably overkill
  221. messageChan = make(chan *master_pb.VolumeLocation, 100)
  222. ms.clientChansLock.Lock()
  223. ms.clientChans[clientName] = messageChan
  224. ms.clientChansLock.Unlock()
  225. return
  226. }
  227. func (ms *MasterServer) deleteClient(clientName string) {
  228. glog.V(0).Infof("- client %v", clientName)
  229. ms.clientChansLock.Lock()
  230. delete(ms.clientChans, clientName)
  231. ms.clientChansLock.Unlock()
  232. }
  233. func findClientAddress(ctx context.Context, grpcPort uint32) string {
  234. // fmt.Printf("FromContext %+v\n", ctx)
  235. pr, ok := peer.FromContext(ctx)
  236. if !ok {
  237. glog.Error("failed to get peer from ctx")
  238. return ""
  239. }
  240. if pr.Addr == net.Addr(nil) {
  241. glog.Error("failed to get peer address")
  242. return ""
  243. }
  244. if grpcPort == 0 {
  245. return pr.Addr.String()
  246. }
  247. if tcpAddr, ok := pr.Addr.(*net.TCPAddr); ok {
  248. externalIP := tcpAddr.IP
  249. return fmt.Sprintf("%s:%d", externalIP, grpcPort)
  250. }
  251. return pr.Addr.String()
  252. }
  253. func (ms *MasterServer) ListMasterClients(ctx context.Context, req *master_pb.ListMasterClientsRequest) (*master_pb.ListMasterClientsResponse, error) {
  254. resp := &master_pb.ListMasterClientsResponse{}
  255. ms.clientChansLock.RLock()
  256. defer ms.clientChansLock.RUnlock()
  257. for k := range ms.clientChans {
  258. if strings.HasPrefix(k, req.ClientType+"@") {
  259. resp.GrpcAddresses = append(resp.GrpcAddresses, k[len(req.ClientType)+1:])
  260. }
  261. }
  262. return resp, nil
  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. Leader: leader,
  273. }
  274. return resp, nil
  275. }