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.7 KiB

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