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.

435 lines
14 KiB

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