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.

287 lines
9.3 KiB

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