balancer_conn_wrappers.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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) UpdateAddresses(sc balancer.SubConn, addrs []resolver.Address) {
  151. acbw, ok := sc.(*acBalancerWrapper)
  152. if !ok {
  153. return
  154. }
  155. acbw.UpdateAddresses(addrs)
  156. }
  157. func (ccb *ccBalancerWrapper) UpdateState(s balancer.State) {
  158. ccb.mu.Lock()
  159. defer ccb.mu.Unlock()
  160. if ccb.subConns == nil {
  161. return
  162. }
  163. // Update picker before updating state. Even though the ordering here does
  164. // not matter, it can lead to multiple calls of Pick in the common start-up
  165. // case where we wait for ready and then perform an RPC. If the picker is
  166. // updated later, we could call the "connecting" picker when the state is
  167. // updated, and then call the "ready" picker after the picker gets updated.
  168. ccb.cc.blockingpicker.updatePicker(s.Picker)
  169. ccb.cc.csMgr.updateState(s.ConnectivityState)
  170. }
  171. func (ccb *ccBalancerWrapper) ResolveNow(o resolver.ResolveNowOptions) {
  172. ccb.cc.resolveNow(o)
  173. }
  174. func (ccb *ccBalancerWrapper) Target() string {
  175. return ccb.cc.target
  176. }
  177. // acBalancerWrapper is a wrapper on top of ac for balancers.
  178. // It implements balancer.SubConn interface.
  179. type acBalancerWrapper struct {
  180. mu sync.Mutex
  181. ac *addrConn
  182. }
  183. func (acbw *acBalancerWrapper) UpdateAddresses(addrs []resolver.Address) {
  184. acbw.mu.Lock()
  185. defer acbw.mu.Unlock()
  186. if len(addrs) <= 0 {
  187. acbw.ac.tearDown(errConnDrain)
  188. return
  189. }
  190. if !acbw.ac.tryUpdateAddrs(addrs) {
  191. cc := acbw.ac.cc
  192. opts := acbw.ac.scopts
  193. acbw.ac.mu.Lock()
  194. // Set old ac.acbw to nil so the Shutdown state update will be ignored
  195. // by balancer.
  196. //
  197. // TODO(bar) the state transition could be wrong when tearDown() old ac
  198. // and creating new ac, fix the transition.
  199. acbw.ac.acbw = nil
  200. acbw.ac.mu.Unlock()
  201. acState := acbw.ac.getState()
  202. acbw.ac.tearDown(errConnDrain)
  203. if acState == connectivity.Shutdown {
  204. return
  205. }
  206. ac, err := cc.newAddrConn(addrs, opts)
  207. if err != nil {
  208. channelz.Warningf(logger, acbw.ac.channelzID, "acBalancerWrapper: UpdateAddresses: failed to newAddrConn: %v", err)
  209. return
  210. }
  211. acbw.ac = ac
  212. ac.mu.Lock()
  213. ac.acbw = acbw
  214. ac.mu.Unlock()
  215. if acState != connectivity.Idle {
  216. ac.connect()
  217. }
  218. }
  219. }
  220. func (acbw *acBalancerWrapper) Connect() {
  221. acbw.mu.Lock()
  222. defer acbw.mu.Unlock()
  223. acbw.ac.connect()
  224. }
  225. func (acbw *acBalancerWrapper) getAddrConn() *addrConn {
  226. acbw.mu.Lock()
  227. defer acbw.mu.Unlock()
  228. return acbw.ac
  229. }