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.

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