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

6 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
4 years ago
3 years ago
2 years ago
2 years ago
6 years ago
  1. package wdclient
  2. import (
  3. "context"
  4. "fmt"
  5. "math/rand"
  6. "sync"
  7. "time"
  8. "github.com/seaweedfs/seaweedfs/weed/stats"
  9. "github.com/seaweedfs/seaweedfs/weed/util"
  10. "google.golang.org/grpc"
  11. "github.com/seaweedfs/seaweedfs/weed/glog"
  12. "github.com/seaweedfs/seaweedfs/weed/pb"
  13. "github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
  14. )
  15. type MasterClient struct {
  16. FilerGroup string
  17. clientType string
  18. clientHost pb.ServerAddress
  19. rack string
  20. currentMaster pb.ServerAddress
  21. currentMasterLock sync.RWMutex
  22. masters map[string]pb.ServerAddress
  23. grpcDialOption grpc.DialOption
  24. *vidMap
  25. vidMapCacheSize int
  26. OnPeerUpdate func(update *master_pb.ClusterNodeUpdate, startFrom time.Time)
  27. OnPeerUpdateLock sync.RWMutex
  28. }
  29. func NewMasterClient(grpcDialOption grpc.DialOption, filerGroup string, clientType string, clientHost pb.ServerAddress, clientDataCenter string, rack string, masters map[string]pb.ServerAddress) *MasterClient {
  30. return &MasterClient{
  31. FilerGroup: filerGroup,
  32. clientType: clientType,
  33. clientHost: clientHost,
  34. rack: rack,
  35. masters: masters,
  36. grpcDialOption: grpcDialOption,
  37. vidMap: newVidMap(clientDataCenter),
  38. vidMapCacheSize: 5,
  39. }
  40. }
  41. func (mc *MasterClient) SetOnPeerUpdateFn(onPeerUpdate func(update *master_pb.ClusterNodeUpdate, startFrom time.Time)) {
  42. mc.OnPeerUpdateLock.Lock()
  43. mc.OnPeerUpdate = onPeerUpdate
  44. mc.OnPeerUpdateLock.Unlock()
  45. }
  46. func (mc *MasterClient) GetLookupFileIdFunction() LookupFileIdFunctionType {
  47. return mc.LookupFileIdWithFallback
  48. }
  49. func (mc *MasterClient) LookupFileIdWithFallback(fileId string) (fullUrls []string, err error) {
  50. fullUrls, err = mc.vidMap.LookupFileId(fileId)
  51. if err == nil && len(fullUrls) > 0 {
  52. return
  53. }
  54. err = pb.WithMasterClient(false, mc.GetMaster(), mc.grpcDialOption, false, func(client master_pb.SeaweedClient) error {
  55. resp, err := client.LookupVolume(context.Background(), &master_pb.LookupVolumeRequest{
  56. VolumeOrFileIds: []string{fileId},
  57. })
  58. if err != nil {
  59. return fmt.Errorf("LookupVolume %s failed: %v", fileId, err)
  60. }
  61. for vid, vidLocation := range resp.VolumeIdLocations {
  62. for _, vidLoc := range vidLocation.Locations {
  63. loc := Location{
  64. Url: vidLoc.Url,
  65. PublicUrl: vidLoc.PublicUrl,
  66. GrpcPort: int(vidLoc.GrpcPort),
  67. DataCenter: vidLoc.DataCenter,
  68. }
  69. mc.vidMap.addLocation(uint32(vid), loc)
  70. httpUrl := "http://" + loc.Url + "/" + fileId
  71. // Prefer same data center
  72. if mc.DataCenter != "" && mc.DataCenter == loc.DataCenter {
  73. fullUrls = append([]string{httpUrl}, fullUrls...)
  74. } else {
  75. fullUrls = append(fullUrls, httpUrl)
  76. }
  77. }
  78. }
  79. return nil
  80. })
  81. return
  82. }
  83. func (mc *MasterClient) getCurrentMaster() pb.ServerAddress {
  84. mc.currentMasterLock.RLock()
  85. defer mc.currentMasterLock.RUnlock()
  86. return mc.currentMaster
  87. }
  88. func (mc *MasterClient) setCurrentMaster(master pb.ServerAddress) {
  89. mc.currentMasterLock.Lock()
  90. mc.currentMaster = master
  91. mc.currentMasterLock.Unlock()
  92. }
  93. func (mc *MasterClient) GetMaster() pb.ServerAddress {
  94. mc.WaitUntilConnected()
  95. return mc.getCurrentMaster()
  96. }
  97. func (mc *MasterClient) GetMasters() map[string]pb.ServerAddress {
  98. mc.WaitUntilConnected()
  99. return mc.masters
  100. }
  101. func (mc *MasterClient) WaitUntilConnected() {
  102. for {
  103. if mc.getCurrentMaster() != "" {
  104. return
  105. }
  106. time.Sleep(time.Duration(rand.Int31n(200)) * time.Millisecond)
  107. print(".")
  108. }
  109. }
  110. func (mc *MasterClient) KeepConnectedToMaster() {
  111. glog.V(1).Infof("%s.%s masterClient bootstraps with masters %v", mc.FilerGroup, mc.clientType, mc.masters)
  112. for {
  113. mc.tryAllMasters()
  114. time.Sleep(time.Second)
  115. }
  116. }
  117. func (mc *MasterClient) FindLeaderFromOtherPeers(myMasterAddress pb.ServerAddress) (leader string) {
  118. for _, master := range mc.masters {
  119. if master == myMasterAddress {
  120. continue
  121. }
  122. if grpcErr := pb.WithMasterClient(false, master, mc.grpcDialOption, false, func(client master_pb.SeaweedClient) error {
  123. ctx, cancel := context.WithTimeout(context.Background(), 120*time.Millisecond)
  124. defer cancel()
  125. resp, err := client.GetMasterConfiguration(ctx, &master_pb.GetMasterConfigurationRequest{})
  126. if err != nil {
  127. return err
  128. }
  129. leader = resp.Leader
  130. return nil
  131. }); grpcErr != nil {
  132. glog.V(0).Infof("connect to %s: %v", master, grpcErr)
  133. }
  134. if leader != "" {
  135. glog.V(0).Infof("existing leader is %s", leader)
  136. return
  137. }
  138. }
  139. glog.V(0).Infof("No existing leader found!")
  140. return
  141. }
  142. func (mc *MasterClient) tryAllMasters() {
  143. var nextHintedLeader pb.ServerAddress
  144. for _, master := range mc.masters {
  145. nextHintedLeader = mc.tryConnectToMaster(master)
  146. for nextHintedLeader != "" {
  147. nextHintedLeader = mc.tryConnectToMaster(nextHintedLeader)
  148. }
  149. mc.setCurrentMaster("")
  150. }
  151. }
  152. func (mc *MasterClient) tryConnectToMaster(master pb.ServerAddress) (nextHintedLeader pb.ServerAddress) {
  153. glog.V(1).Infof("%s.%s masterClient Connecting to master %v", mc.FilerGroup, mc.clientType, master)
  154. stats.MasterClientConnectCounter.WithLabelValues("total").Inc()
  155. gprcErr := pb.WithMasterClient(true, master, mc.grpcDialOption, false, func(client master_pb.SeaweedClient) error {
  156. ctx, cancel := context.WithCancel(context.Background())
  157. defer cancel()
  158. stream, err := client.KeepConnected(ctx)
  159. if err != nil {
  160. glog.V(1).Infof("%s.%s masterClient failed to keep connected to %s: %v", mc.FilerGroup, mc.clientType, master, err)
  161. stats.MasterClientConnectCounter.WithLabelValues(stats.FailedToKeepConnected).Inc()
  162. return err
  163. }
  164. if err = stream.Send(&master_pb.KeepConnectedRequest{
  165. FilerGroup: mc.FilerGroup,
  166. DataCenter: mc.DataCenter,
  167. Rack: mc.rack,
  168. ClientType: mc.clientType,
  169. ClientAddress: string(mc.clientHost),
  170. Version: util.Version(),
  171. }); err != nil {
  172. glog.V(0).Infof("%s.%s masterClient failed to send to %s: %v", mc.FilerGroup, mc.clientType, master, err)
  173. stats.MasterClientConnectCounter.WithLabelValues(stats.FailedToSend).Inc()
  174. return err
  175. }
  176. glog.V(1).Infof("%s.%s masterClient Connected to %v", mc.FilerGroup, mc.clientType, master)
  177. resp, err := stream.Recv()
  178. if err != nil {
  179. glog.V(0).Infof("%s.%s masterClient failed to receive from %s: %v", mc.FilerGroup, mc.clientType, master, err)
  180. stats.MasterClientConnectCounter.WithLabelValues(stats.FailedToReceive).Inc()
  181. return err
  182. }
  183. // check if it is the leader to determine whether to reset the vidMap
  184. if resp.VolumeLocation != nil {
  185. if resp.VolumeLocation.Leader != "" && string(master) != resp.VolumeLocation.Leader {
  186. glog.V(0).Infof("master %v redirected to leader %v", master, resp.VolumeLocation.Leader)
  187. nextHintedLeader = pb.ServerAddress(resp.VolumeLocation.Leader)
  188. stats.MasterClientConnectCounter.WithLabelValues(stats.RedirectedToLeader).Inc()
  189. return nil
  190. }
  191. mc.resetVidMap()
  192. mc.updateVidMap(resp)
  193. } else {
  194. mc.resetVidMap()
  195. }
  196. mc.setCurrentMaster(master)
  197. for {
  198. resp, err := stream.Recv()
  199. if err != nil {
  200. glog.V(0).Infof("%s.%s masterClient failed to receive from %s: %v", mc.FilerGroup, mc.clientType, master, err)
  201. stats.MasterClientConnectCounter.WithLabelValues(stats.FailedToReceive).Inc()
  202. return err
  203. }
  204. if resp.VolumeLocation != nil {
  205. // maybe the leader is changed
  206. if resp.VolumeLocation.Leader != "" && string(mc.GetMaster()) != resp.VolumeLocation.Leader {
  207. glog.V(0).Infof("currentMaster %v redirected to leader %v", mc.GetMaster(), resp.VolumeLocation.Leader)
  208. nextHintedLeader = pb.ServerAddress(resp.VolumeLocation.Leader)
  209. stats.MasterClientConnectCounter.WithLabelValues(stats.RedirectedToLeader).Inc()
  210. return nil
  211. }
  212. mc.updateVidMap(resp)
  213. }
  214. if resp.ClusterNodeUpdate != nil {
  215. update := resp.ClusterNodeUpdate
  216. mc.OnPeerUpdateLock.RLock()
  217. if mc.OnPeerUpdate != nil {
  218. if update.FilerGroup == mc.FilerGroup {
  219. if update.IsAdd {
  220. glog.V(0).Infof("+ %s.%s %s\n", update.FilerGroup, update.NodeType, update.Address)
  221. } else {
  222. glog.V(0).Infof("- %s.%s %s\n", update.FilerGroup, update.NodeType, update.Address)
  223. }
  224. stats.MasterClientConnectCounter.WithLabelValues(stats.OnPeerUpdate).Inc()
  225. mc.OnPeerUpdate(update, time.Now())
  226. }
  227. }
  228. mc.OnPeerUpdateLock.RUnlock()
  229. }
  230. }
  231. })
  232. if gprcErr != nil {
  233. stats.MasterClientConnectCounter.WithLabelValues(stats.Failed).Inc()
  234. glog.V(1).Infof("%s.%s masterClient failed to connect with master %v: %v", mc.FilerGroup, mc.clientType, master, gprcErr)
  235. }
  236. return
  237. }
  238. func (mc *MasterClient) updateVidMap(resp *master_pb.KeepConnectedResponse) {
  239. if resp.VolumeLocation.IsEmptyUrl() {
  240. glog.V(0).Infof("updateVidMap ignore short heartbeat: %+v", resp)
  241. return
  242. }
  243. // process new volume location
  244. loc := Location{
  245. Url: resp.VolumeLocation.Url,
  246. PublicUrl: resp.VolumeLocation.PublicUrl,
  247. DataCenter: resp.VolumeLocation.DataCenter,
  248. GrpcPort: int(resp.VolumeLocation.GrpcPort),
  249. }
  250. for _, newVid := range resp.VolumeLocation.NewVids {
  251. glog.V(2).Infof("%s.%s: %s masterClient adds volume %d", mc.FilerGroup, mc.clientType, loc.Url, newVid)
  252. mc.addLocation(newVid, loc)
  253. }
  254. for _, deletedVid := range resp.VolumeLocation.DeletedVids {
  255. glog.V(2).Infof("%s.%s: %s masterClient removes volume %d", mc.FilerGroup, mc.clientType, loc.Url, deletedVid)
  256. mc.deleteLocation(deletedVid, loc)
  257. }
  258. for _, newEcVid := range resp.VolumeLocation.NewEcVids {
  259. glog.V(2).Infof("%s.%s: %s masterClient adds ec volume %d", mc.FilerGroup, mc.clientType, loc.Url, newEcVid)
  260. mc.addEcLocation(newEcVid, loc)
  261. }
  262. for _, deletedEcVid := range resp.VolumeLocation.DeletedEcVids {
  263. glog.V(2).Infof("%s.%s: %s masterClient removes ec volume %d", mc.FilerGroup, mc.clientType, loc.Url, deletedEcVid)
  264. mc.deleteEcLocation(deletedEcVid, loc)
  265. }
  266. glog.V(1).Infof("updateVidMap(%s) %s.%s: %s volume add: %d, del: %d, add ec: %d del ec: %d",
  267. resp.VolumeLocation.DataCenter, mc.FilerGroup, mc.clientType, loc.Url,
  268. len(resp.VolumeLocation.NewVids), len(resp.VolumeLocation.DeletedVids),
  269. len(resp.VolumeLocation.NewEcVids), len(resp.VolumeLocation.DeletedEcVids))
  270. }
  271. func (mc *MasterClient) WithClient(streamingMode bool, fn func(client master_pb.SeaweedClient) error) error {
  272. return util.Retry("master grpc", func() error {
  273. return pb.WithMasterClient(streamingMode, mc.GetMaster(), mc.grpcDialOption, false, func(client master_pb.SeaweedClient) error {
  274. return fn(client)
  275. })
  276. })
  277. }
  278. func (mc *MasterClient) resetVidMap() {
  279. tail := &vidMap{
  280. vid2Locations: mc.vid2Locations,
  281. ecVid2Locations: mc.ecVid2Locations,
  282. DataCenter: mc.DataCenter,
  283. cache: mc.cache,
  284. }
  285. nvm := newVidMap(mc.DataCenter)
  286. nvm.cache = tail
  287. mc.vidMap = nvm
  288. //trim
  289. for i := 0; i < mc.vidMapCacheSize && tail.cache != nil; i++ {
  290. if i == mc.vidMapCacheSize-1 {
  291. tail.cache = nil
  292. } else {
  293. tail = tail.cache
  294. }
  295. }
  296. }