balancer_conn_wrappers.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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. "sync"
  22. "google.golang.org/grpc/balancer"
  23. "google.golang.org/grpc/connectivity"
  24. "google.golang.org/grpc/internal/buffer"
  25. "google.golang.org/grpc/internal/channelz"
  26. "google.golang.org/grpc/internal/grpcsync"
  27. "google.golang.org/grpc/resolver"
  28. )
  29. // scStateUpdate contains the subConn and the new state it changed to.
  30. type scStateUpdate struct {
  31. sc balancer.SubConn
  32. state connectivity.State
  33. err error
  34. }
  35. // ccBalancerWrapper is a wrapper on top of cc for balancers.
  36. // It implements balancer.ClientConn interface.
  37. type ccBalancerWrapper struct {
  38. cc *ClientConn
  39. balancerMu sync.Mutex // synchronizes calls to the balancer
  40. balancer balancer.Balancer
  41. scBuffer *buffer.Unbounded
  42. done *grpcsync.Event
  43. mu sync.Mutex
  44. subConns map[*acBalancerWrapper]struct{}
  45. }
  46. func newCCBalancerWrapper(cc *ClientConn, b balancer.Builder, bopts balancer.BuildOptions) *ccBalancerWrapper {
  47. ccb := &ccBalancerWrapper{
  48. cc: cc,
  49. scBuffer: buffer.NewUnbounded(),
  50. done: grpcsync.NewEvent(),
  51. subConns: make(map[*acBalancerWrapper]struct{}),
  52. }
  53. go ccb.watcher()
  54. ccb.balancer = b.Build(ccb, bopts)
  55. return ccb
  56. }
  57. // watcher balancer functions sequentially, so the balancer can be implemented
  58. // lock-free.
  59. func (ccb *ccBalancerWrapper) watcher() {
  60. for {
  61. select {
  62. case t := <-ccb.scBuffer.Get():
  63. ccb.scBuffer.Load()
  64. if ccb.done.HasFired() {
  65. break
  66. }
  67. ccb.balancerMu.Lock()
  68. su := t.(*scStateUpdate)
  69. ccb.balancer.UpdateSubConnState(su.sc, balancer.SubConnState{ConnectivityState: su.state, ConnectionError: su.err})
  70. ccb.balancerMu.Unlock()
  71. case <-ccb.done.Done():
  72. }
  73. if ccb.done.HasFired() {
  74. ccb.balancer.Close()
  75. ccb.mu.Lock()
  76. scs := ccb.subConns
  77. ccb.subConns = nil
  78. ccb.mu.Unlock()
  79. for acbw := range scs {
  80. ccb.cc.removeAddrConn(acbw.getAddrConn(), errConnDrain)
  81. }
  82. ccb.UpdateState(balancer.State{ConnectivityState: connectivity.Connecting, Picker: nil})
  83. return
  84. }
  85. }
  86. }
  87. func (ccb *ccBalancerWrapper) close() {
  88. ccb.done.Fire()
  89. }
  90. func (ccb *ccBalancerWrapper) handleSubConnStateChange(sc balancer.SubConn, s connectivity.State, err error) {
  91. // When updating addresses for a SubConn, if the address in use is not in
  92. // the new addresses, the old ac will be tearDown() and a new ac will be
  93. // created. tearDown() generates a state change with Shutdown state, we
  94. // don't want the balancer to receive this state change. So before
  95. // tearDown() on the old ac, ac.acbw (acWrapper) will be set to nil, and
  96. // this function will be called with (nil, Shutdown). We don't need to call
  97. // balancer method in this case.
  98. if sc == nil {
  99. return
  100. }
  101. ccb.scBuffer.Put(&scStateUpdate{
  102. sc: sc,
  103. state: s,
  104. err: err,
  105. })
  106. }
  107. func (ccb *ccBalancerWrapper) updateClientConnState(ccs *balancer.ClientConnState) error {
  108. ccb.balancerMu.Lock()
  109. defer ccb.balancerMu.Unlock()
  110. return ccb.balancer.UpdateClientConnState(*ccs)
  111. }
  112. func (ccb *ccBalancerWrapper) resolverError(err error) {
  113. ccb.balancerMu.Lock()
  114. ccb.balancer.ResolverError(err)
  115. ccb.balancerMu.Unlock()
  116. }
  117. func (ccb *ccBalancerWrapper) NewSubConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error) {
  118. if len(addrs) <= 0 {
  119. return nil, fmt.Errorf("grpc: cannot create SubConn with empty address list")
  120. }
  121. ccb.mu.Lock()
  122. defer ccb.mu.Unlock()
  123. if ccb.subConns == nil {
  124. return nil, fmt.Errorf("grpc: ClientConn balancer wrapper was closed")
  125. }
  126. ac, err := ccb.cc.newAddrConn(addrs, opts)
  127. if err != nil {
  128. return nil, err
  129. }
  130. acbw := &acBalancerWrapper{ac: ac}
  131. acbw.ac.mu.Lock()
  132. ac.acbw = acbw
  133. acbw.ac.mu.Unlock()
  134. ccb.subConns[acbw] = struct{}{}
  135. return acbw, nil
  136. }
  137. func (ccb *ccBalancerWrapper) RemoveSubConn(sc balancer.SubConn) {
  138. acbw, ok := sc.(*acBalancerWrapper)
  139. if !ok {
  140. return
  141. }
  142. ccb.mu.Lock()
  143. defer ccb.mu.Unlock()
  144. if ccb.subConns == nil {
  145. return
  146. }
  147. delete(ccb.subConns, acbw)
  148. ccb.cc.removeAddrConn(acbw.getAddrConn(), errConnDrain)
  149. }
  150. func (ccb *ccBalancerWrapper) UpdateState(s balancer.State) {
  151. ccb.mu.Lock()
  152. defer ccb.mu.Unlock()
  153. if ccb.subConns == nil {
  154. return
  155. }
  156. // Update picker before updating state. Even though the ordering here does
  157. // not matter, it can lead to multiple calls of Pick in the common start-up
  158. // case where we wait for ready and then perform an RPC. If the picker is
  159. // updated later, we could call the "connecting" picker when the state is
  160. // updated, and then call the "ready" picker after the picker gets updated.
  161. ccb.cc.blockingpicker.updatePicker(s.Picker)
  162. ccb.cc.csMgr.updateState(s.ConnectivityState)
  163. }
  164. func (ccb *ccBalancerWrapper) ResolveNow(o resolver.ResolveNowOptions) {
  165. ccb.cc.resolveNow(o)
  166. }
  167. func (ccb *ccBalancerWrapper) Target() string {
  168. return ccb.cc.target
  169. }
  170. // acBalancerWrapper is a wrapper on top of ac for balancers.
  171. // It implements balancer.SubConn interface.
  172. type acBalancerWrapper struct {
  173. mu sync.Mutex
  174. ac *addrConn
  175. }
  176. func (acbw *acBalancerWrapper) UpdateAddresses(addrs []resolver.Address) {
  177. acbw.mu.Lock()
  178. defer acbw.mu.Unlock()
  179. if len(addrs) <= 0 {
  180. acbw.ac.tearDown(errConnDrain)
  181. return
  182. }
  183. if !acbw.ac.tryUpdateAddrs(addrs) {
  184. cc := acbw.ac.cc
  185. opts := acbw.ac.scopts
  186. acbw.ac.mu.Lock()
  187. // Set old ac.acbw to nil so the Shutdown state update will be ignored
  188. // by balancer.
  189. //
  190. // TODO(bar) the state transition could be wrong when tearDown() old ac
  191. // and creating new ac, fix the transition.
  192. acbw.ac.acbw = nil
  193. acbw.ac.mu.Unlock()
  194. acState := acbw.ac.getState()
  195. acbw.ac.tearDown(errConnDrain)
  196. if acState == connectivity.Shutdown {
  197. return
  198. }
  199. ac, err := cc.newAddrConn(addrs, opts)
  200. if err != nil {
  201. channelz.Warningf(logger, acbw.ac.channelzID, "acBalancerWrapper: UpdateAddresses: failed to newAddrConn: %v", err)
  202. return
  203. }
  204. acbw.ac = ac
  205. ac.mu.Lock()
  206. ac.acbw = acbw
  207. ac.mu.Unlock()
  208. if acState != connectivity.Idle {
  209. ac.connect()
  210. }
  211. }
  212. }
  213. func (acbw *acBalancerWrapper) Connect() {
  214. acbw.mu.Lock()
  215. defer acbw.mu.Unlock()
  216. acbw.ac.connect()
  217. }
  218. func (acbw *acBalancerWrapper) getAddrConn() *addrConn {
  219. acbw.mu.Lock()
  220. defer acbw.mu.Unlock()
  221. return acbw.ac
  222. }