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.

297 lines
9.7 KiB

7 years ago
5 years ago
3 years ago
7 years ago
3 years ago
3 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. DataCenter: vidLoc.DataCenter,
  60. }
  61. mc.vidMap.addLocation(uint32(vid), loc)
  62. httpUrl := "http://" + loc.Url + "/" + fileId
  63. // Prefer same data center
  64. if mc.DataCenter != "" && mc.DataCenter == loc.DataCenter {
  65. fullUrls = append([]string{httpUrl}, fullUrls...)
  66. } else {
  67. fullUrls = append(fullUrls, httpUrl)
  68. }
  69. }
  70. }
  71. return nil
  72. })
  73. return
  74. }
  75. func (mc *MasterClient) GetMaster() pb.ServerAddress {
  76. mc.WaitUntilConnected()
  77. return mc.currentMaster
  78. }
  79. func (mc *MasterClient) GetMasters() map[string]pb.ServerAddress {
  80. mc.WaitUntilConnected()
  81. return mc.masters
  82. }
  83. func (mc *MasterClient) WaitUntilConnected() {
  84. for mc.currentMaster == "" {
  85. time.Sleep(time.Duration(rand.Int31n(200)) * time.Millisecond)
  86. }
  87. }
  88. func (mc *MasterClient) KeepConnectedToMaster() {
  89. glog.V(1).Infof("%s.%s masterClient bootstraps with masters %v", mc.FilerGroup, mc.clientType, mc.masters)
  90. for {
  91. mc.tryAllMasters()
  92. time.Sleep(time.Second)
  93. }
  94. }
  95. func (mc *MasterClient) FindLeaderFromOtherPeers(myMasterAddress pb.ServerAddress) (leader string) {
  96. for _, master := range mc.masters {
  97. if master == myMasterAddress {
  98. continue
  99. }
  100. if grpcErr := pb.WithMasterClient(false, master, mc.grpcDialOption, func(client master_pb.SeaweedClient) error {
  101. ctx, cancel := context.WithTimeout(context.Background(), 120*time.Millisecond)
  102. defer cancel()
  103. resp, err := client.GetMasterConfiguration(ctx, &master_pb.GetMasterConfigurationRequest{})
  104. if err != nil {
  105. return err
  106. }
  107. leader = resp.Leader
  108. return nil
  109. }); grpcErr != nil {
  110. glog.V(0).Infof("connect to %s: %v", master, grpcErr)
  111. }
  112. if leader != "" {
  113. glog.V(0).Infof("existing leader is %s", leader)
  114. return
  115. }
  116. }
  117. glog.V(0).Infof("No existing leader found!")
  118. return
  119. }
  120. func (mc *MasterClient) tryAllMasters() {
  121. var nextHintedLeader pb.ServerAddress
  122. for _, master := range mc.masters {
  123. nextHintedLeader = mc.tryConnectToMaster(master)
  124. for nextHintedLeader != "" {
  125. nextHintedLeader = mc.tryConnectToMaster(nextHintedLeader)
  126. }
  127. mc.currentMaster = ""
  128. }
  129. }
  130. func (mc *MasterClient) tryConnectToMaster(master pb.ServerAddress) (nextHintedLeader pb.ServerAddress) {
  131. glog.V(1).Infof("%s.%s masterClient Connecting to master %v", mc.FilerGroup, mc.clientType, master)
  132. stats.MasterClientConnectCounter.WithLabelValues("total").Inc()
  133. gprcErr := pb.WithMasterClient(true, master, mc.grpcDialOption, func(client master_pb.SeaweedClient) error {
  134. ctx, cancel := context.WithCancel(context.Background())
  135. defer cancel()
  136. stream, err := client.KeepConnected(ctx)
  137. if err != nil {
  138. glog.V(1).Infof("%s.%s masterClient failed to keep connected to %s: %v", mc.FilerGroup, mc.clientType, master, err)
  139. stats.MasterClientConnectCounter.WithLabelValues(stats.FailedToKeepConnected).Inc()
  140. return err
  141. }
  142. if err = stream.Send(&master_pb.KeepConnectedRequest{
  143. FilerGroup: mc.FilerGroup,
  144. DataCenter: mc.DataCenter,
  145. Rack: mc.rack,
  146. ClientType: mc.clientType,
  147. ClientAddress: string(mc.clientHost),
  148. Version: util.Version(),
  149. }); err != nil {
  150. glog.V(0).Infof("%s.%s masterClient failed to send to %s: %v", mc.FilerGroup, mc.clientType, master, err)
  151. stats.MasterClientConnectCounter.WithLabelValues(stats.FailedToSend).Inc()
  152. return err
  153. }
  154. glog.V(1).Infof("%s.%s masterClient Connected to %v", mc.FilerGroup, mc.clientType, master)
  155. resp, err := stream.Recv()
  156. if err != nil {
  157. glog.V(0).Infof("%s.%s masterClient failed to receive from %s: %v", mc.FilerGroup, mc.clientType, master, err)
  158. stats.MasterClientConnectCounter.WithLabelValues(stats.FailedToReceive).Inc()
  159. return err
  160. }
  161. // check if it is the leader to determine whether to reset the vidMap
  162. if resp.VolumeLocation != nil {
  163. if resp.VolumeLocation.Leader != "" && string(master) != resp.VolumeLocation.Leader {
  164. glog.V(0).Infof("master %v redirected to leader %v", master, resp.VolumeLocation.Leader)
  165. nextHintedLeader = pb.ServerAddress(resp.VolumeLocation.Leader)
  166. stats.MasterClientConnectCounter.WithLabelValues(stats.RedirectedToLeader).Inc()
  167. return nil
  168. }
  169. mc.resetVidMap()
  170. mc.updateVidMap(resp)
  171. } else {
  172. mc.resetVidMap()
  173. }
  174. mc.currentMaster = master
  175. for {
  176. resp, err := stream.Recv()
  177. if err != nil {
  178. glog.V(0).Infof("%s.%s masterClient failed to receive from %s: %v", mc.FilerGroup, mc.clientType, master, err)
  179. stats.MasterClientConnectCounter.WithLabelValues(stats.FailedToReceive).Inc()
  180. return err
  181. }
  182. if resp.VolumeLocation != nil {
  183. // maybe the leader is changed
  184. if resp.VolumeLocation.Leader != "" && string(mc.currentMaster) != resp.VolumeLocation.Leader {
  185. glog.V(0).Infof("currentMaster %v redirected to leader %v", mc.currentMaster, resp.VolumeLocation.Leader)
  186. nextHintedLeader = pb.ServerAddress(resp.VolumeLocation.Leader)
  187. stats.MasterClientConnectCounter.WithLabelValues(stats.RedirectedToLeader).Inc()
  188. return nil
  189. }
  190. mc.updateVidMap(resp)
  191. }
  192. if resp.ClusterNodeUpdate != nil {
  193. update := resp.ClusterNodeUpdate
  194. if mc.OnPeerUpdate != nil {
  195. if update.FilerGroup == mc.FilerGroup {
  196. if update.IsAdd {
  197. glog.V(0).Infof("+ %s.%s %s leader:%v\n", update.FilerGroup, update.NodeType, update.Address, update.IsLeader)
  198. } else {
  199. glog.V(0).Infof("- %s.%s %s leader:%v\n", update.FilerGroup, update.NodeType, update.Address, update.IsLeader)
  200. }
  201. stats.MasterClientConnectCounter.WithLabelValues(stats.OnPeerUpdate).Inc()
  202. mc.OnPeerUpdate(update, time.Now())
  203. }
  204. }
  205. }
  206. }
  207. })
  208. if gprcErr != nil {
  209. stats.MasterClientConnectCounter.WithLabelValues(stats.Failed).Inc()
  210. glog.V(1).Infof("%s.%s masterClient failed to connect with master %v: %v", mc.FilerGroup, mc.clientType, master, gprcErr)
  211. }
  212. return
  213. }
  214. func (mc *MasterClient) updateVidMap(resp *master_pb.KeepConnectedResponse) {
  215. // process new volume location
  216. glog.V(1).Infof("updateVidMap() resp.VolumeLocation.DataCenter %v", resp.VolumeLocation.DataCenter)
  217. loc := Location{
  218. Url: resp.VolumeLocation.Url,
  219. PublicUrl: resp.VolumeLocation.PublicUrl,
  220. DataCenter: resp.VolumeLocation.DataCenter,
  221. GrpcPort: int(resp.VolumeLocation.GrpcPort),
  222. }
  223. for _, newVid := range resp.VolumeLocation.NewVids {
  224. glog.V(1).Infof("%s.%s: %s masterClient adds volume %d", mc.FilerGroup, mc.clientType, loc.Url, newVid)
  225. mc.addLocation(newVid, loc)
  226. }
  227. for _, deletedVid := range resp.VolumeLocation.DeletedVids {
  228. glog.V(1).Infof("%s.%s: %s masterClient removes volume %d", mc.FilerGroup, mc.clientType, loc.Url, deletedVid)
  229. mc.deleteLocation(deletedVid, loc)
  230. }
  231. for _, newEcVid := range resp.VolumeLocation.NewEcVids {
  232. glog.V(1).Infof("%s.%s: %s masterClient adds ec volume %d", mc.FilerGroup, mc.clientType, loc.Url, newEcVid)
  233. mc.addEcLocation(newEcVid, loc)
  234. }
  235. for _, deletedEcVid := range resp.VolumeLocation.DeletedEcVids {
  236. glog.V(1).Infof("%s.%s: %s masterClient removes ec volume %d", mc.FilerGroup, mc.clientType, loc.Url, deletedEcVid)
  237. mc.deleteEcLocation(deletedEcVid, loc)
  238. }
  239. }
  240. func (mc *MasterClient) WithClient(streamingMode bool, fn func(client master_pb.SeaweedClient) error) error {
  241. return util.Retry("master grpc", func() error {
  242. for mc.currentMaster == "" {
  243. time.Sleep(3 * time.Second)
  244. }
  245. return pb.WithMasterClient(streamingMode, mc.currentMaster, mc.grpcDialOption, func(client master_pb.SeaweedClient) error {
  246. return fn(client)
  247. })
  248. })
  249. }
  250. func (mc *MasterClient) resetVidMap() {
  251. tail := &vidMap{
  252. vid2Locations: mc.vid2Locations,
  253. ecVid2Locations: mc.ecVid2Locations,
  254. DataCenter: mc.DataCenter,
  255. cache: mc.cache,
  256. }
  257. mc.vidMap = newVidMap(mc.DataCenter)
  258. mc.vidMap.cache = tail
  259. for i := 0; i < mc.vidMapCacheSize && tail.cache != nil; i++ {
  260. if i == mc.vidMapCacheSize-1 {
  261. tail.cache = nil
  262. } else {
  263. tail = tail.cache
  264. }
  265. }
  266. }