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.
 
 
 

402 lines
13 KiB

  1. /*
  2. *
  3. * Copyright 2016 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. //go:generate ./regenerate.sh
  19. // Package grpclb defines a grpclb balancer.
  20. //
  21. // To install grpclb balancer, import this package as:
  22. // import _ "google.golang.org/grpc/balancer/grpclb"
  23. package grpclb
  24. import (
  25. "context"
  26. "errors"
  27. "strconv"
  28. "strings"
  29. "sync"
  30. "time"
  31. durationpb "github.com/golang/protobuf/ptypes/duration"
  32. "google.golang.org/grpc"
  33. "google.golang.org/grpc/balancer"
  34. lbpb "google.golang.org/grpc/balancer/grpclb/grpc_lb_v1"
  35. "google.golang.org/grpc/connectivity"
  36. "google.golang.org/grpc/credentials"
  37. "google.golang.org/grpc/grpclog"
  38. "google.golang.org/grpc/internal"
  39. "google.golang.org/grpc/internal/backoff"
  40. "google.golang.org/grpc/resolver"
  41. )
  42. const (
  43. lbTokeyKey = "lb-token"
  44. defaultFallbackTimeout = 10 * time.Second
  45. grpclbName = "grpclb"
  46. )
  47. var (
  48. // defaultBackoffConfig configures the backoff strategy that's used when the
  49. // init handshake in the RPC is unsuccessful. It's not for the clientconn
  50. // reconnect backoff.
  51. //
  52. // It has the same value as the default grpc.DefaultBackoffConfig.
  53. //
  54. // TODO: make backoff configurable.
  55. defaultBackoffConfig = backoff.Exponential{
  56. MaxDelay: 120 * time.Second,
  57. }
  58. errServerTerminatedConnection = errors.New("grpclb: failed to recv server list: server terminated connection")
  59. )
  60. func convertDuration(d *durationpb.Duration) time.Duration {
  61. if d == nil {
  62. return 0
  63. }
  64. return time.Duration(d.Seconds)*time.Second + time.Duration(d.Nanos)*time.Nanosecond
  65. }
  66. // Client API for LoadBalancer service.
  67. // Mostly copied from generated pb.go file.
  68. // To avoid circular dependency.
  69. type loadBalancerClient struct {
  70. cc *grpc.ClientConn
  71. }
  72. func (c *loadBalancerClient) BalanceLoad(ctx context.Context, opts ...grpc.CallOption) (*balanceLoadClientStream, error) {
  73. desc := &grpc.StreamDesc{
  74. StreamName: "BalanceLoad",
  75. ServerStreams: true,
  76. ClientStreams: true,
  77. }
  78. stream, err := c.cc.NewStream(ctx, desc, "/grpc.lb.v1.LoadBalancer/BalanceLoad", opts...)
  79. if err != nil {
  80. return nil, err
  81. }
  82. x := &balanceLoadClientStream{stream}
  83. return x, nil
  84. }
  85. type balanceLoadClientStream struct {
  86. grpc.ClientStream
  87. }
  88. func (x *balanceLoadClientStream) Send(m *lbpb.LoadBalanceRequest) error {
  89. return x.ClientStream.SendMsg(m)
  90. }
  91. func (x *balanceLoadClientStream) Recv() (*lbpb.LoadBalanceResponse, error) {
  92. m := new(lbpb.LoadBalanceResponse)
  93. if err := x.ClientStream.RecvMsg(m); err != nil {
  94. return nil, err
  95. }
  96. return m, nil
  97. }
  98. func init() {
  99. balancer.Register(newLBBuilder())
  100. }
  101. // newLBBuilder creates a builder for grpclb.
  102. func newLBBuilder() balancer.Builder {
  103. return newLBBuilderWithFallbackTimeout(defaultFallbackTimeout)
  104. }
  105. // newLBBuilderWithFallbackTimeout creates a grpclb builder with the given
  106. // fallbackTimeout. If no response is received from the remote balancer within
  107. // fallbackTimeout, the backend addresses from the resolved address list will be
  108. // used.
  109. //
  110. // Only call this function when a non-default fallback timeout is needed.
  111. func newLBBuilderWithFallbackTimeout(fallbackTimeout time.Duration) balancer.Builder {
  112. return &lbBuilder{
  113. fallbackTimeout: fallbackTimeout,
  114. }
  115. }
  116. type lbBuilder struct {
  117. fallbackTimeout time.Duration
  118. }
  119. func (b *lbBuilder) Name() string {
  120. return grpclbName
  121. }
  122. func (b *lbBuilder) Build(cc balancer.ClientConn, opt balancer.BuildOptions) balancer.Balancer {
  123. // This generates a manual resolver builder with a random scheme. This
  124. // scheme will be used to dial to remote LB, so we can send filtered address
  125. // updates to remote LB ClientConn using this manual resolver.
  126. scheme := "grpclb_internal_" + strconv.FormatInt(time.Now().UnixNano(), 36)
  127. r := &lbManualResolver{scheme: scheme, ccb: cc}
  128. var target string
  129. targetSplitted := strings.Split(cc.Target(), ":///")
  130. if len(targetSplitted) < 2 {
  131. target = cc.Target()
  132. } else {
  133. target = targetSplitted[1]
  134. }
  135. lb := &lbBalancer{
  136. cc: newLBCacheClientConn(cc),
  137. target: target,
  138. opt: opt,
  139. fallbackTimeout: b.fallbackTimeout,
  140. doneCh: make(chan struct{}),
  141. manualResolver: r,
  142. csEvltr: &balancer.ConnectivityStateEvaluator{},
  143. subConns: make(map[resolver.Address]balancer.SubConn),
  144. scStates: make(map[balancer.SubConn]connectivity.State),
  145. picker: &errPicker{err: balancer.ErrNoSubConnAvailable},
  146. clientStats: newRPCStats(),
  147. backoff: defaultBackoffConfig, // TODO: make backoff configurable.
  148. }
  149. var err error
  150. if opt.CredsBundle != nil {
  151. lb.grpclbClientConnCreds, err = opt.CredsBundle.NewWithMode(internal.CredsBundleModeBalancer)
  152. if err != nil {
  153. grpclog.Warningf("lbBalancer: client connection creds NewWithMode failed: %v", err)
  154. }
  155. lb.grpclbBackendCreds, err = opt.CredsBundle.NewWithMode(internal.CredsBundleModeBackendFromBalancer)
  156. if err != nil {
  157. grpclog.Warningf("lbBalancer: backend creds NewWithMode failed: %v", err)
  158. }
  159. }
  160. return lb
  161. }
  162. type lbBalancer struct {
  163. cc *lbCacheClientConn
  164. target string
  165. opt balancer.BuildOptions
  166. // grpclbClientConnCreds is the creds bundle to be used to connect to grpclb
  167. // servers. If it's nil, use the TransportCredentials from BuildOptions
  168. // instead.
  169. grpclbClientConnCreds credentials.Bundle
  170. // grpclbBackendCreds is the creds bundle to be used for addresses that are
  171. // returned by grpclb server. If it's nil, don't set anything when creating
  172. // SubConns.
  173. grpclbBackendCreds credentials.Bundle
  174. fallbackTimeout time.Duration
  175. doneCh chan struct{}
  176. // manualResolver is used in the remote LB ClientConn inside grpclb. When
  177. // resolved address updates are received by grpclb, filtered updates will be
  178. // send to remote LB ClientConn through this resolver.
  179. manualResolver *lbManualResolver
  180. // The ClientConn to talk to the remote balancer.
  181. ccRemoteLB *grpc.ClientConn
  182. // backoff for calling remote balancer.
  183. backoff backoff.Strategy
  184. // Support client side load reporting. Each picker gets a reference to this,
  185. // and will update its content.
  186. clientStats *rpcStats
  187. mu sync.Mutex // guards everything following.
  188. // The full server list including drops, used to check if the newly received
  189. // serverList contains anything new. Each generate picker will also have
  190. // reference to this list to do the first layer pick.
  191. fullServerList []*lbpb.Server
  192. // All backends addresses, with metadata set to nil. This list contains all
  193. // backend addresses in the same order and with the same duplicates as in
  194. // serverlist. When generating picker, a SubConn slice with the same order
  195. // but with only READY SCs will be gerenated.
  196. backendAddrs []resolver.Address
  197. // Roundrobin functionalities.
  198. csEvltr *balancer.ConnectivityStateEvaluator
  199. state connectivity.State
  200. subConns map[resolver.Address]balancer.SubConn // Used to new/remove SubConn.
  201. scStates map[balancer.SubConn]connectivity.State // Used to filter READY SubConns.
  202. picker balancer.Picker
  203. // Support fallback to resolved backend addresses if there's no response
  204. // from remote balancer within fallbackTimeout.
  205. fallbackTimerExpired bool
  206. serverListReceived bool
  207. // resolvedBackendAddrs is resolvedAddrs minus remote balancers. It's set
  208. // when resolved address updates are received, and read in the goroutine
  209. // handling fallback.
  210. resolvedBackendAddrs []resolver.Address
  211. }
  212. // regeneratePicker takes a snapshot of the balancer, and generates a picker from
  213. // it. The picker
  214. // - always returns ErrTransientFailure if the balancer is in TransientFailure,
  215. // - does two layer roundrobin pick otherwise.
  216. // Caller must hold lb.mu.
  217. func (lb *lbBalancer) regeneratePicker(resetDrop bool) {
  218. if lb.state == connectivity.TransientFailure {
  219. lb.picker = &errPicker{err: balancer.ErrTransientFailure}
  220. return
  221. }
  222. var readySCs []balancer.SubConn
  223. for _, a := range lb.backendAddrs {
  224. if sc, ok := lb.subConns[a]; ok {
  225. if st, ok := lb.scStates[sc]; ok && st == connectivity.Ready {
  226. readySCs = append(readySCs, sc)
  227. }
  228. }
  229. }
  230. if len(readySCs) <= 0 {
  231. // If there's no ready SubConns, always re-pick. This is to avoid drops
  232. // unless at least one SubConn is ready. Otherwise we may drop more
  233. // often than want because of drops + re-picks(which become re-drops).
  234. lb.picker = &errPicker{err: balancer.ErrNoSubConnAvailable}
  235. return
  236. }
  237. if len(lb.fullServerList) <= 0 {
  238. lb.picker = newRRPicker(readySCs)
  239. return
  240. }
  241. if resetDrop {
  242. lb.picker = newLBPicker(lb.fullServerList, readySCs, lb.clientStats)
  243. return
  244. }
  245. prevLBPicker, ok := lb.picker.(*lbPicker)
  246. if !ok {
  247. lb.picker = newLBPicker(lb.fullServerList, readySCs, lb.clientStats)
  248. return
  249. }
  250. prevLBPicker.updateReadySCs(readySCs)
  251. }
  252. func (lb *lbBalancer) HandleSubConnStateChange(sc balancer.SubConn, s connectivity.State) {
  253. grpclog.Infof("lbBalancer: handle SubConn state change: %p, %v", sc, s)
  254. lb.mu.Lock()
  255. defer lb.mu.Unlock()
  256. oldS, ok := lb.scStates[sc]
  257. if !ok {
  258. grpclog.Infof("lbBalancer: got state changes for an unknown SubConn: %p, %v", sc, s)
  259. return
  260. }
  261. lb.scStates[sc] = s
  262. switch s {
  263. case connectivity.Idle:
  264. sc.Connect()
  265. case connectivity.Shutdown:
  266. // When an address was removed by resolver, b called RemoveSubConn but
  267. // kept the sc's state in scStates. Remove state for this sc here.
  268. delete(lb.scStates, sc)
  269. }
  270. oldAggrState := lb.state
  271. lb.state = lb.csEvltr.RecordTransition(oldS, s)
  272. // Regenerate picker when one of the following happens:
  273. // - this sc became ready from not-ready
  274. // - this sc became not-ready from ready
  275. // - the aggregated state of balancer became TransientFailure from non-TransientFailure
  276. // - the aggregated state of balancer became non-TransientFailure from TransientFailure
  277. if (oldS == connectivity.Ready) != (s == connectivity.Ready) ||
  278. (lb.state == connectivity.TransientFailure) != (oldAggrState == connectivity.TransientFailure) {
  279. lb.regeneratePicker(false)
  280. }
  281. lb.cc.UpdateBalancerState(lb.state, lb.picker)
  282. }
  283. // fallbackToBackendsAfter blocks for fallbackTimeout and falls back to use
  284. // resolved backends (backends received from resolver, not from remote balancer)
  285. // if no connection to remote balancers was successful.
  286. func (lb *lbBalancer) fallbackToBackendsAfter(fallbackTimeout time.Duration) {
  287. timer := time.NewTimer(fallbackTimeout)
  288. defer timer.Stop()
  289. select {
  290. case <-timer.C:
  291. case <-lb.doneCh:
  292. return
  293. }
  294. lb.mu.Lock()
  295. if lb.serverListReceived {
  296. lb.mu.Unlock()
  297. return
  298. }
  299. lb.fallbackTimerExpired = true
  300. lb.refreshSubConns(lb.resolvedBackendAddrs, false)
  301. lb.mu.Unlock()
  302. }
  303. // HandleResolvedAddrs sends the updated remoteLB addresses to remoteLB
  304. // clientConn. The remoteLB clientConn will handle creating/removing remoteLB
  305. // connections.
  306. func (lb *lbBalancer) HandleResolvedAddrs(addrs []resolver.Address, err error) {
  307. grpclog.Infof("lbBalancer: handleResolvedResult: %+v", addrs)
  308. if len(addrs) <= 0 {
  309. return
  310. }
  311. var remoteBalancerAddrs, backendAddrs []resolver.Address
  312. for _, a := range addrs {
  313. if a.Type == resolver.GRPCLB {
  314. a.Type = resolver.Backend
  315. remoteBalancerAddrs = append(remoteBalancerAddrs, a)
  316. } else {
  317. backendAddrs = append(backendAddrs, a)
  318. }
  319. }
  320. if lb.ccRemoteLB == nil {
  321. if len(remoteBalancerAddrs) <= 0 {
  322. grpclog.Errorf("grpclb: no remote balancer address is available, should never happen")
  323. return
  324. }
  325. // First time receiving resolved addresses, create a cc to remote
  326. // balancers.
  327. lb.dialRemoteLB(remoteBalancerAddrs[0].ServerName)
  328. // Start the fallback goroutine.
  329. go lb.fallbackToBackendsAfter(lb.fallbackTimeout)
  330. }
  331. // cc to remote balancers uses lb.manualResolver. Send the updated remote
  332. // balancer addresses to it through manualResolver.
  333. lb.manualResolver.NewAddress(remoteBalancerAddrs)
  334. lb.mu.Lock()
  335. lb.resolvedBackendAddrs = backendAddrs
  336. // If serverListReceived is true, connection to remote balancer was
  337. // successful and there's no need to do fallback anymore.
  338. // If fallbackTimerExpired is false, fallback hasn't happened yet.
  339. if !lb.serverListReceived && lb.fallbackTimerExpired {
  340. // This means we received a new list of resolved backends, and we are
  341. // still in fallback mode. Need to update the list of backends we are
  342. // using to the new list of backends.
  343. lb.refreshSubConns(lb.resolvedBackendAddrs, false)
  344. }
  345. lb.mu.Unlock()
  346. }
  347. func (lb *lbBalancer) Close() {
  348. select {
  349. case <-lb.doneCh:
  350. return
  351. default:
  352. }
  353. close(lb.doneCh)
  354. if lb.ccRemoteLB != nil {
  355. lb.ccRemoteLB.Close()
  356. }
  357. lb.cc.close()
  358. }