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.

283 lines
9.2 KiB

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