balancer_wrapper.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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. "context"
  21. "fmt"
  22. "strings"
  23. "sync"
  24. "google.golang.org/grpc/balancer"
  25. "google.golang.org/grpc/connectivity"
  26. "google.golang.org/grpc/internal/balancer/gracefulswitch"
  27. "google.golang.org/grpc/internal/channelz"
  28. "google.golang.org/grpc/internal/grpcsync"
  29. "google.golang.org/grpc/resolver"
  30. )
  31. // ccBalancerWrapper sits between the ClientConn and the Balancer.
  32. //
  33. // ccBalancerWrapper implements methods corresponding to the ones on the
  34. // balancer.Balancer interface. The ClientConn is free to call these methods
  35. // concurrently and the ccBalancerWrapper ensures that calls from the ClientConn
  36. // to the Balancer happen in order by performing them in the serializer, without
  37. // any mutexes held.
  38. //
  39. // ccBalancerWrapper also implements the balancer.ClientConn interface and is
  40. // passed to the Balancer implementations. It invokes unexported methods on the
  41. // ClientConn to handle these calls from the Balancer.
  42. //
  43. // It uses the gracefulswitch.Balancer internally to ensure that balancer
  44. // switches happen in a graceful manner.
  45. type ccBalancerWrapper struct {
  46. // The following fields are initialized when the wrapper is created and are
  47. // read-only afterwards, and therefore can be accessed without a mutex.
  48. cc *ClientConn
  49. opts balancer.BuildOptions
  50. serializer *grpcsync.CallbackSerializer
  51. serializerCancel context.CancelFunc
  52. // The following fields are only accessed within the serializer or during
  53. // initialization.
  54. curBalancerName string
  55. balancer *gracefulswitch.Balancer
  56. // The following field is protected by mu. Caller must take cc.mu before
  57. // taking mu.
  58. mu sync.Mutex
  59. closed bool
  60. }
  61. // newCCBalancerWrapper creates a new balancer wrapper in idle state. The
  62. // underlying balancer is not created until the switchTo() method is invoked.
  63. func newCCBalancerWrapper(cc *ClientConn) *ccBalancerWrapper {
  64. ctx, cancel := context.WithCancel(cc.ctx)
  65. ccb := &ccBalancerWrapper{
  66. cc: cc,
  67. opts: balancer.BuildOptions{
  68. DialCreds: cc.dopts.copts.TransportCredentials,
  69. CredsBundle: cc.dopts.copts.CredsBundle,
  70. Dialer: cc.dopts.copts.Dialer,
  71. Authority: cc.authority,
  72. CustomUserAgent: cc.dopts.copts.UserAgent,
  73. ChannelzParentID: cc.channelzID,
  74. Target: cc.parsedTarget,
  75. },
  76. serializer: grpcsync.NewCallbackSerializer(ctx),
  77. serializerCancel: cancel,
  78. }
  79. ccb.balancer = gracefulswitch.NewBalancer(ccb, ccb.opts)
  80. return ccb
  81. }
  82. // updateClientConnState is invoked by grpc to push a ClientConnState update to
  83. // the underlying balancer. This is always executed from the serializer, so
  84. // it is safe to call into the balancer here.
  85. func (ccb *ccBalancerWrapper) updateClientConnState(ccs *balancer.ClientConnState) error {
  86. errCh := make(chan error)
  87. ok := ccb.serializer.Schedule(func(ctx context.Context) {
  88. defer close(errCh)
  89. if ctx.Err() != nil || ccb.balancer == nil {
  90. return
  91. }
  92. err := ccb.balancer.UpdateClientConnState(*ccs)
  93. if logger.V(2) && err != nil {
  94. logger.Infof("error from balancer.UpdateClientConnState: %v", err)
  95. }
  96. errCh <- err
  97. })
  98. if !ok {
  99. return nil
  100. }
  101. return <-errCh
  102. }
  103. // resolverError is invoked by grpc to push a resolver error to the underlying
  104. // balancer. The call to the balancer is executed from the serializer.
  105. func (ccb *ccBalancerWrapper) resolverError(err error) {
  106. ccb.serializer.Schedule(func(ctx context.Context) {
  107. if ctx.Err() != nil || ccb.balancer == nil {
  108. return
  109. }
  110. ccb.balancer.ResolverError(err)
  111. })
  112. }
  113. // switchTo is invoked by grpc to instruct the balancer wrapper to switch to the
  114. // LB policy identified by name.
  115. //
  116. // ClientConn calls newCCBalancerWrapper() at creation time. Upon receipt of the
  117. // first good update from the name resolver, it determines the LB policy to use
  118. // and invokes the switchTo() method. Upon receipt of every subsequent update
  119. // from the name resolver, it invokes this method.
  120. //
  121. // the ccBalancerWrapper keeps track of the current LB policy name, and skips
  122. // the graceful balancer switching process if the name does not change.
  123. func (ccb *ccBalancerWrapper) switchTo(name string) {
  124. ccb.serializer.Schedule(func(ctx context.Context) {
  125. if ctx.Err() != nil || ccb.balancer == nil {
  126. return
  127. }
  128. // TODO: Other languages use case-sensitive balancer registries. We should
  129. // switch as well. See: https://github.com/grpc/grpc-go/issues/5288.
  130. if strings.EqualFold(ccb.curBalancerName, name) {
  131. return
  132. }
  133. ccb.buildLoadBalancingPolicy(name)
  134. })
  135. }
  136. // buildLoadBalancingPolicy performs the following:
  137. // - retrieve a balancer builder for the given name. Use the default LB
  138. // policy, pick_first, if no LB policy with name is found in the registry.
  139. // - instruct the gracefulswitch balancer to switch to the above builder. This
  140. // will actually build the new balancer.
  141. // - update the `curBalancerName` field
  142. //
  143. // Must be called from a serializer callback.
  144. func (ccb *ccBalancerWrapper) buildLoadBalancingPolicy(name string) {
  145. builder := balancer.Get(name)
  146. if builder == nil {
  147. channelz.Warningf(logger, ccb.cc.channelzID, "Channel switches to new LB policy %q, since the specified LB policy %q was not registered", PickFirstBalancerName, name)
  148. builder = newPickfirstBuilder()
  149. } else {
  150. channelz.Infof(logger, ccb.cc.channelzID, "Channel switches to new LB policy %q", name)
  151. }
  152. if err := ccb.balancer.SwitchTo(builder); err != nil {
  153. channelz.Errorf(logger, ccb.cc.channelzID, "Channel failed to build new LB policy %q: %v", name, err)
  154. return
  155. }
  156. ccb.curBalancerName = builder.Name()
  157. }
  158. // close initiates async shutdown of the wrapper. cc.mu must be held when
  159. // calling this function. To determine the wrapper has finished shutting down,
  160. // the channel should block on ccb.serializer.Done() without cc.mu held.
  161. func (ccb *ccBalancerWrapper) close() {
  162. ccb.mu.Lock()
  163. ccb.closed = true
  164. ccb.mu.Unlock()
  165. channelz.Info(logger, ccb.cc.channelzID, "ccBalancerWrapper: closing")
  166. ccb.serializer.Schedule(func(context.Context) {
  167. if ccb.balancer == nil {
  168. return
  169. }
  170. ccb.balancer.Close()
  171. ccb.balancer = nil
  172. })
  173. ccb.serializerCancel()
  174. }
  175. // exitIdle invokes the balancer's exitIdle method in the serializer.
  176. func (ccb *ccBalancerWrapper) exitIdle() {
  177. ccb.serializer.Schedule(func(ctx context.Context) {
  178. if ctx.Err() != nil || ccb.balancer == nil {
  179. return
  180. }
  181. ccb.balancer.ExitIdle()
  182. })
  183. }
  184. func (ccb *ccBalancerWrapper) NewSubConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error) {
  185. ccb.cc.mu.Lock()
  186. defer ccb.cc.mu.Unlock()
  187. ccb.mu.Lock()
  188. if ccb.closed {
  189. ccb.mu.Unlock()
  190. return nil, fmt.Errorf("balancer is being closed; no new SubConns allowed")
  191. }
  192. ccb.mu.Unlock()
  193. if len(addrs) == 0 {
  194. return nil, fmt.Errorf("grpc: cannot create SubConn with empty address list")
  195. }
  196. ac, err := ccb.cc.newAddrConnLocked(addrs, opts)
  197. if err != nil {
  198. channelz.Warningf(logger, ccb.cc.channelzID, "acBalancerWrapper: NewSubConn: failed to newAddrConn: %v", err)
  199. return nil, err
  200. }
  201. acbw := &acBalancerWrapper{
  202. ccb: ccb,
  203. ac: ac,
  204. producers: make(map[balancer.ProducerBuilder]*refCountedProducer),
  205. stateListener: opts.StateListener,
  206. }
  207. ac.acbw = acbw
  208. return acbw, nil
  209. }
  210. func (ccb *ccBalancerWrapper) RemoveSubConn(sc balancer.SubConn) {
  211. // The graceful switch balancer will never call this.
  212. logger.Errorf("ccb RemoveSubConn(%v) called unexpectedly, sc")
  213. }
  214. func (ccb *ccBalancerWrapper) UpdateAddresses(sc balancer.SubConn, addrs []resolver.Address) {
  215. acbw, ok := sc.(*acBalancerWrapper)
  216. if !ok {
  217. return
  218. }
  219. acbw.UpdateAddresses(addrs)
  220. }
  221. func (ccb *ccBalancerWrapper) UpdateState(s balancer.State) {
  222. ccb.cc.mu.Lock()
  223. defer ccb.cc.mu.Unlock()
  224. ccb.mu.Lock()
  225. if ccb.closed {
  226. ccb.mu.Unlock()
  227. return
  228. }
  229. ccb.mu.Unlock()
  230. // Update picker before updating state. Even though the ordering here does
  231. // not matter, it can lead to multiple calls of Pick in the common start-up
  232. // case where we wait for ready and then perform an RPC. If the picker is
  233. // updated later, we could call the "connecting" picker when the state is
  234. // updated, and then call the "ready" picker after the picker gets updated.
  235. // Note that there is no need to check if the balancer wrapper was closed,
  236. // as we know the graceful switch LB policy will not call cc if it has been
  237. // closed.
  238. ccb.cc.pickerWrapper.updatePicker(s.Picker)
  239. ccb.cc.csMgr.updateState(s.ConnectivityState)
  240. }
  241. func (ccb *ccBalancerWrapper) ResolveNow(o resolver.ResolveNowOptions) {
  242. ccb.cc.mu.RLock()
  243. defer ccb.cc.mu.RUnlock()
  244. ccb.mu.Lock()
  245. if ccb.closed {
  246. ccb.mu.Unlock()
  247. return
  248. }
  249. ccb.mu.Unlock()
  250. ccb.cc.resolveNowLocked(o)
  251. }
  252. func (ccb *ccBalancerWrapper) Target() string {
  253. return ccb.cc.target
  254. }
  255. // acBalancerWrapper is a wrapper on top of ac for balancers.
  256. // It implements balancer.SubConn interface.
  257. type acBalancerWrapper struct {
  258. ac *addrConn // read-only
  259. ccb *ccBalancerWrapper // read-only
  260. stateListener func(balancer.SubConnState)
  261. mu sync.Mutex
  262. producers map[balancer.ProducerBuilder]*refCountedProducer
  263. }
  264. // updateState is invoked by grpc to push a subConn state update to the
  265. // underlying balancer.
  266. func (acbw *acBalancerWrapper) updateState(s connectivity.State, err error) {
  267. acbw.ccb.serializer.Schedule(func(ctx context.Context) {
  268. if ctx.Err() != nil || acbw.ccb.balancer == nil {
  269. return
  270. }
  271. // Even though it is optional for balancers, gracefulswitch ensures
  272. // opts.StateListener is set, so this cannot ever be nil.
  273. // TODO: delete this comment when UpdateSubConnState is removed.
  274. acbw.stateListener(balancer.SubConnState{ConnectivityState: s, ConnectionError: err})
  275. })
  276. }
  277. func (acbw *acBalancerWrapper) String() string {
  278. return fmt.Sprintf("SubConn(id:%d)", acbw.ac.channelzID.Int())
  279. }
  280. func (acbw *acBalancerWrapper) UpdateAddresses(addrs []resolver.Address) {
  281. acbw.ac.updateAddrs(addrs)
  282. }
  283. func (acbw *acBalancerWrapper) Connect() {
  284. go acbw.ac.connect()
  285. }
  286. func (acbw *acBalancerWrapper) Shutdown() {
  287. acbw.ccb.cc.removeAddrConn(acbw.ac, errConnDrain)
  288. }
  289. // NewStream begins a streaming RPC on the addrConn. If the addrConn is not
  290. // ready, blocks until it is or ctx expires. Returns an error when the context
  291. // expires or the addrConn is shut down.
  292. func (acbw *acBalancerWrapper) NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error) {
  293. transport, err := acbw.ac.getTransport(ctx)
  294. if err != nil {
  295. return nil, err
  296. }
  297. return newNonRetryClientStream(ctx, desc, method, transport, acbw.ac, opts...)
  298. }
  299. // Invoke performs a unary RPC. If the addrConn is not ready, returns
  300. // errSubConnNotReady.
  301. func (acbw *acBalancerWrapper) Invoke(ctx context.Context, method string, args any, reply any, opts ...CallOption) error {
  302. cs, err := acbw.NewStream(ctx, unaryStreamDesc, method, opts...)
  303. if err != nil {
  304. return err
  305. }
  306. if err := cs.SendMsg(args); err != nil {
  307. return err
  308. }
  309. return cs.RecvMsg(reply)
  310. }
  311. type refCountedProducer struct {
  312. producer balancer.Producer
  313. refs int // number of current refs to the producer
  314. close func() // underlying producer's close function
  315. }
  316. func (acbw *acBalancerWrapper) GetOrBuildProducer(pb balancer.ProducerBuilder) (balancer.Producer, func()) {
  317. acbw.mu.Lock()
  318. defer acbw.mu.Unlock()
  319. // Look up existing producer from this builder.
  320. pData := acbw.producers[pb]
  321. if pData == nil {
  322. // Not found; create a new one and add it to the producers map.
  323. p, close := pb.Build(acbw)
  324. pData = &refCountedProducer{producer: p, close: close}
  325. acbw.producers[pb] = pData
  326. }
  327. // Account for this new reference.
  328. pData.refs++
  329. // Return a cleanup function wrapped in a OnceFunc to remove this reference
  330. // and delete the refCountedProducer from the map if the total reference
  331. // count goes to zero.
  332. unref := func() {
  333. acbw.mu.Lock()
  334. pData.refs--
  335. if pData.refs == 0 {
  336. defer pData.close() // Run outside the acbw mutex
  337. delete(acbw.producers, pb)
  338. }
  339. acbw.mu.Unlock()
  340. }
  341. return pData.producer, grpcsync.OnceFunc(unref)
  342. }