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.

327 lines
9.8 KiB

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