master_grpc_server.go 13 KB

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