grpclb_remote_balancer.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. /*
  2. *
  3. * Copyright 2017 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package grpc
  19. import (
  20. "fmt"
  21. "net"
  22. "reflect"
  23. "time"
  24. "golang.org/x/net/context"
  25. "google.golang.org/grpc/balancer"
  26. "google.golang.org/grpc/connectivity"
  27. lbpb "google.golang.org/grpc/grpclb/grpc_lb_v1/messages"
  28. "google.golang.org/grpc/grpclog"
  29. "google.golang.org/grpc/metadata"
  30. "google.golang.org/grpc/resolver"
  31. )
  32. // processServerList updates balaner's internal state, create/remove SubConns
  33. // and regenerates picker using the received serverList.
  34. func (lb *lbBalancer) processServerList(l *lbpb.ServerList) {
  35. grpclog.Infof("lbBalancer: processing server list: %+v", l)
  36. lb.mu.Lock()
  37. defer lb.mu.Unlock()
  38. // Set serverListReceived to true so fallback will not take effect if it has
  39. // not hit timeout.
  40. lb.serverListReceived = true
  41. // If the new server list == old server list, do nothing.
  42. if reflect.DeepEqual(lb.fullServerList, l.Servers) {
  43. grpclog.Infof("lbBalancer: new serverlist same as the previous one, ignoring")
  44. return
  45. }
  46. lb.fullServerList = l.Servers
  47. var backendAddrs []resolver.Address
  48. for _, s := range l.Servers {
  49. if s.DropForLoadBalancing || s.DropForRateLimiting {
  50. continue
  51. }
  52. md := metadata.Pairs(lbTokeyKey, s.LoadBalanceToken)
  53. ip := net.IP(s.IpAddress)
  54. ipStr := ip.String()
  55. if ip.To4() == nil {
  56. // Add square brackets to ipv6 addresses, otherwise net.Dial() and
  57. // net.SplitHostPort() will return too many colons error.
  58. ipStr = fmt.Sprintf("[%s]", ipStr)
  59. }
  60. addr := resolver.Address{
  61. Addr: fmt.Sprintf("%s:%d", ipStr, s.Port),
  62. Metadata: &md,
  63. }
  64. backendAddrs = append(backendAddrs, addr)
  65. }
  66. // Call refreshSubConns to create/remove SubConns.
  67. backendsUpdated := lb.refreshSubConns(backendAddrs)
  68. // If no backend was updated, no SubConn will be newed/removed. But since
  69. // the full serverList was different, there might be updates in drops or
  70. // pick weights(different number of duplicates). We need to update picker
  71. // with the fulllist.
  72. if !backendsUpdated {
  73. lb.regeneratePicker()
  74. lb.cc.UpdateBalancerState(lb.state, lb.picker)
  75. }
  76. }
  77. // refreshSubConns creates/removes SubConns with backendAddrs. It returns a bool
  78. // indicating whether the backendAddrs are different from the cached
  79. // backendAddrs (whether any SubConn was newed/removed).
  80. // Caller must hold lb.mu.
  81. func (lb *lbBalancer) refreshSubConns(backendAddrs []resolver.Address) bool {
  82. lb.backendAddrs = nil
  83. var backendsUpdated bool
  84. // addrsSet is the set converted from backendAddrs, it's used to quick
  85. // lookup for an address.
  86. addrsSet := make(map[resolver.Address]struct{})
  87. // Create new SubConns.
  88. for _, addr := range backendAddrs {
  89. addrWithoutMD := addr
  90. addrWithoutMD.Metadata = nil
  91. addrsSet[addrWithoutMD] = struct{}{}
  92. lb.backendAddrs = append(lb.backendAddrs, addrWithoutMD)
  93. if _, ok := lb.subConns[addrWithoutMD]; !ok {
  94. backendsUpdated = true
  95. // Use addrWithMD to create the SubConn.
  96. sc, err := lb.cc.NewSubConn([]resolver.Address{addr}, balancer.NewSubConnOptions{})
  97. if err != nil {
  98. grpclog.Warningf("roundrobinBalancer: failed to create new SubConn: %v", err)
  99. continue
  100. }
  101. lb.subConns[addrWithoutMD] = sc // Use the addr without MD as key for the map.
  102. lb.scStates[sc] = connectivity.Idle
  103. sc.Connect()
  104. }
  105. }
  106. for a, sc := range lb.subConns {
  107. // a was removed by resolver.
  108. if _, ok := addrsSet[a]; !ok {
  109. backendsUpdated = true
  110. lb.cc.RemoveSubConn(sc)
  111. delete(lb.subConns, a)
  112. // Keep the state of this sc in b.scStates until sc's state becomes Shutdown.
  113. // The entry will be deleted in HandleSubConnStateChange.
  114. }
  115. }
  116. return backendsUpdated
  117. }
  118. func (lb *lbBalancer) readServerList(s *balanceLoadClientStream) error {
  119. for {
  120. reply, err := s.Recv()
  121. if err != nil {
  122. return fmt.Errorf("grpclb: failed to recv server list: %v", err)
  123. }
  124. if serverList := reply.GetServerList(); serverList != nil {
  125. lb.processServerList(serverList)
  126. }
  127. }
  128. }
  129. func (lb *lbBalancer) sendLoadReport(s *balanceLoadClientStream, interval time.Duration) {
  130. ticker := time.NewTicker(interval)
  131. defer ticker.Stop()
  132. for {
  133. select {
  134. case <-ticker.C:
  135. case <-s.Context().Done():
  136. return
  137. }
  138. stats := lb.clientStats.toClientStats()
  139. t := time.Now()
  140. stats.Timestamp = &lbpb.Timestamp{
  141. Seconds: t.Unix(),
  142. Nanos: int32(t.Nanosecond()),
  143. }
  144. if err := s.Send(&lbpb.LoadBalanceRequest{
  145. LoadBalanceRequestType: &lbpb.LoadBalanceRequest_ClientStats{
  146. ClientStats: stats,
  147. },
  148. }); err != nil {
  149. return
  150. }
  151. }
  152. }
  153. func (lb *lbBalancer) callRemoteBalancer() error {
  154. lbClient := &loadBalancerClient{cc: lb.ccRemoteLB}
  155. ctx, cancel := context.WithCancel(context.Background())
  156. defer cancel()
  157. stream, err := lbClient.BalanceLoad(ctx, FailFast(false))
  158. if err != nil {
  159. return fmt.Errorf("grpclb: failed to perform RPC to the remote balancer %v", err)
  160. }
  161. // grpclb handshake on the stream.
  162. initReq := &lbpb.LoadBalanceRequest{
  163. LoadBalanceRequestType: &lbpb.LoadBalanceRequest_InitialRequest{
  164. InitialRequest: &lbpb.InitialLoadBalanceRequest{
  165. Name: lb.target,
  166. },
  167. },
  168. }
  169. if err := stream.Send(initReq); err != nil {
  170. return fmt.Errorf("grpclb: failed to send init request: %v", err)
  171. }
  172. reply, err := stream.Recv()
  173. if err != nil {
  174. return fmt.Errorf("grpclb: failed to recv init response: %v", err)
  175. }
  176. initResp := reply.GetInitialResponse()
  177. if initResp == nil {
  178. return fmt.Errorf("grpclb: reply from remote balancer did not include initial response")
  179. }
  180. if initResp.LoadBalancerDelegate != "" {
  181. return fmt.Errorf("grpclb: Delegation is not supported")
  182. }
  183. go func() {
  184. if d := convertDuration(initResp.ClientStatsReportInterval); d > 0 {
  185. lb.sendLoadReport(stream, d)
  186. }
  187. }()
  188. return lb.readServerList(stream)
  189. }
  190. func (lb *lbBalancer) watchRemoteBalancer() {
  191. for {
  192. err := lb.callRemoteBalancer()
  193. select {
  194. case <-lb.doneCh:
  195. return
  196. default:
  197. if err != nil {
  198. grpclog.Error(err)
  199. }
  200. }
  201. }
  202. }
  203. func (lb *lbBalancer) dialRemoteLB(remoteLBName string) {
  204. var dopts []DialOption
  205. if creds := lb.opt.DialCreds; creds != nil {
  206. if err := creds.OverrideServerName(remoteLBName); err == nil {
  207. dopts = append(dopts, WithTransportCredentials(creds))
  208. } else {
  209. grpclog.Warningf("grpclb: failed to override the server name in the credentials: %v, using Insecure", err)
  210. dopts = append(dopts, WithInsecure())
  211. }
  212. } else {
  213. dopts = append(dopts, WithInsecure())
  214. }
  215. if lb.opt.Dialer != nil {
  216. // WithDialer takes a different type of function, so we instead use a
  217. // special DialOption here.
  218. dopts = append(dopts, withContextDialer(lb.opt.Dialer))
  219. }
  220. // Explicitly set pickfirst as the balancer.
  221. dopts = append(dopts, WithBalancerName(PickFirstBalancerName))
  222. dopts = append(dopts, withResolverBuilder(lb.manualResolver))
  223. // Dial using manualResolver.Scheme, which is a random scheme generated
  224. // when init grpclb. The target name is not important.
  225. cc, err := Dial("grpclb:///grpclb.server", dopts...)
  226. if err != nil {
  227. grpclog.Fatalf("failed to dial: %v", err)
  228. }
  229. lb.ccRemoteLB = cc
  230. go lb.watchRemoteBalancer()
  231. }