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