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.

394 lines
13 KiB

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