You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

balancer_conn_wrappers.go 8.1 kB

4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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/grpclog"
  25. "google.golang.org/grpc/resolver"
  26. )
  27. // scStateUpdate contains the subConn and the new state it changed to.
  28. type scStateUpdate struct {
  29. sc balancer.SubConn
  30. state connectivity.State
  31. }
  32. // scStateUpdateBuffer is an unbounded channel for scStateChangeTuple.
  33. // TODO make a general purpose buffer that uses interface{}.
  34. type scStateUpdateBuffer struct {
  35. c chan *scStateUpdate
  36. mu sync.Mutex
  37. backlog []*scStateUpdate
  38. }
  39. func newSCStateUpdateBuffer() *scStateUpdateBuffer {
  40. return &scStateUpdateBuffer{
  41. c: make(chan *scStateUpdate, 1),
  42. }
  43. }
  44. func (b *scStateUpdateBuffer) put(t *scStateUpdate) {
  45. b.mu.Lock()
  46. defer b.mu.Unlock()
  47. if len(b.backlog) == 0 {
  48. select {
  49. case b.c <- t:
  50. return
  51. default:
  52. }
  53. }
  54. b.backlog = append(b.backlog, t)
  55. }
  56. func (b *scStateUpdateBuffer) load() {
  57. b.mu.Lock()
  58. defer b.mu.Unlock()
  59. if len(b.backlog) > 0 {
  60. select {
  61. case b.c <- b.backlog[0]:
  62. b.backlog[0] = nil
  63. b.backlog = b.backlog[1:]
  64. default:
  65. }
  66. }
  67. }
  68. // get returns the channel that the scStateUpdate will be sent to.
  69. //
  70. // Upon receiving, the caller should call load to send another
  71. // scStateChangeTuple onto the channel if there is any.
  72. func (b *scStateUpdateBuffer) get() <-chan *scStateUpdate {
  73. return b.c
  74. }
  75. // ccBalancerWrapper is a wrapper on top of cc for balancers.
  76. // It implements balancer.ClientConn interface.
  77. type ccBalancerWrapper struct {
  78. cc *ClientConn
  79. balancer balancer.Balancer
  80. stateChangeQueue *scStateUpdateBuffer
  81. resolverUpdateCh chan *resolver.State
  82. done chan struct{}
  83. mu sync.Mutex
  84. subConns map[*acBalancerWrapper]struct{}
  85. }
  86. func newCCBalancerWrapper(cc *ClientConn, b balancer.Builder, bopts balancer.BuildOptions) *ccBalancerWrapper {
  87. ccb := &ccBalancerWrapper{
  88. cc: cc,
  89. stateChangeQueue: newSCStateUpdateBuffer(),
  90. resolverUpdateCh: make(chan *resolver.State, 1),
  91. done: make(chan struct{}),
  92. subConns: make(map[*acBalancerWrapper]struct{}),
  93. }
  94. go ccb.watcher()
  95. ccb.balancer = b.Build(ccb, bopts)
  96. return ccb
  97. }
  98. // watcher balancer functions sequentially, so the balancer can be implemented
  99. // lock-free.
  100. func (ccb *ccBalancerWrapper) watcher() {
  101. for {
  102. select {
  103. case t := <-ccb.stateChangeQueue.get():
  104. ccb.stateChangeQueue.load()
  105. select {
  106. case <-ccb.done:
  107. ccb.balancer.Close()
  108. return
  109. default:
  110. }
  111. if ub, ok := ccb.balancer.(balancer.V2Balancer); ok {
  112. ub.UpdateSubConnState(t.sc, balancer.SubConnState{ConnectivityState: t.state})
  113. } else {
  114. ccb.balancer.HandleSubConnStateChange(t.sc, t.state)
  115. }
  116. case s := <-ccb.resolverUpdateCh:
  117. select {
  118. case <-ccb.done:
  119. ccb.balancer.Close()
  120. return
  121. default:
  122. }
  123. if ub, ok := ccb.balancer.(balancer.V2Balancer); ok {
  124. ub.UpdateResolverState(*s)
  125. } else {
  126. ccb.balancer.HandleResolvedAddrs(s.Addresses, nil)
  127. }
  128. case <-ccb.done:
  129. }
  130. select {
  131. case <-ccb.done:
  132. ccb.balancer.Close()
  133. ccb.mu.Lock()
  134. scs := ccb.subConns
  135. ccb.subConns = nil
  136. ccb.mu.Unlock()
  137. for acbw := range scs {
  138. ccb.cc.removeAddrConn(acbw.getAddrConn(), errConnDrain)
  139. }
  140. return
  141. default:
  142. }
  143. }
  144. }
  145. func (ccb *ccBalancerWrapper) close() {
  146. close(ccb.done)
  147. }
  148. func (ccb *ccBalancerWrapper) handleSubConnStateChange(sc balancer.SubConn, s connectivity.State) {
  149. // When updating addresses for a SubConn, if the address in use is not in
  150. // the new addresses, the old ac will be tearDown() and a new ac will be
  151. // created. tearDown() generates a state change with Shutdown state, we
  152. // don't want the balancer to receive this state change. So before
  153. // tearDown() on the old ac, ac.acbw (acWrapper) will be set to nil, and
  154. // this function will be called with (nil, Shutdown). We don't need to call
  155. // balancer method in this case.
  156. if sc == nil {
  157. return
  158. }
  159. ccb.stateChangeQueue.put(&scStateUpdate{
  160. sc: sc,
  161. state: s,
  162. })
  163. }
  164. func (ccb *ccBalancerWrapper) updateResolverState(s resolver.State) {
  165. if ccb.cc.curBalancerName != grpclbName {
  166. // Filter any grpclb addresses since we don't have the grpclb balancer.
  167. for i := 0; i < len(s.Addresses); {
  168. if s.Addresses[i].Type == resolver.GRPCLB {
  169. copy(s.Addresses[i:], s.Addresses[i+1:])
  170. s.Addresses = s.Addresses[:len(s.Addresses)-1]
  171. continue
  172. }
  173. i++
  174. }
  175. }
  176. select {
  177. case <-ccb.resolverUpdateCh:
  178. default:
  179. }
  180. ccb.resolverUpdateCh <- &s
  181. }
  182. func (ccb *ccBalancerWrapper) NewSubConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error) {
  183. if len(addrs) <= 0 {
  184. return nil, fmt.Errorf("grpc: cannot create SubConn with empty address list")
  185. }
  186. ccb.mu.Lock()
  187. defer ccb.mu.Unlock()
  188. if ccb.subConns == nil {
  189. return nil, fmt.Errorf("grpc: ClientConn balancer wrapper was closed")
  190. }
  191. ac, err := ccb.cc.newAddrConn(addrs, opts)
  192. if err != nil {
  193. return nil, err
  194. }
  195. acbw := &acBalancerWrapper{ac: ac}
  196. acbw.ac.mu.Lock()
  197. ac.acbw = acbw
  198. acbw.ac.mu.Unlock()
  199. ccb.subConns[acbw] = struct{}{}
  200. return acbw, nil
  201. }
  202. func (ccb *ccBalancerWrapper) RemoveSubConn(sc balancer.SubConn) {
  203. acbw, ok := sc.(*acBalancerWrapper)
  204. if !ok {
  205. return
  206. }
  207. ccb.mu.Lock()
  208. defer ccb.mu.Unlock()
  209. if ccb.subConns == nil {
  210. return
  211. }
  212. delete(ccb.subConns, acbw)
  213. ccb.cc.removeAddrConn(acbw.getAddrConn(), errConnDrain)
  214. }
  215. func (ccb *ccBalancerWrapper) UpdateBalancerState(s connectivity.State, p balancer.Picker) {
  216. ccb.mu.Lock()
  217. defer ccb.mu.Unlock()
  218. if ccb.subConns == nil {
  219. return
  220. }
  221. // Update picker before updating state. Even though the ordering here does
  222. // not matter, it can lead to multiple calls of Pick in the common start-up
  223. // case where we wait for ready and then perform an RPC. If the picker is
  224. // updated later, we could call the "connecting" picker when the state is
  225. // updated, and then call the "ready" picker after the picker gets updated.
  226. ccb.cc.blockingpicker.updatePicker(p)
  227. ccb.cc.csMgr.updateState(s)
  228. }
  229. func (ccb *ccBalancerWrapper) ResolveNow(o resolver.ResolveNowOption) {
  230. ccb.cc.resolveNow(o)
  231. }
  232. func (ccb *ccBalancerWrapper) Target() string {
  233. return ccb.cc.target
  234. }
  235. // acBalancerWrapper is a wrapper on top of ac for balancers.
  236. // It implements balancer.SubConn interface.
  237. type acBalancerWrapper struct {
  238. mu sync.Mutex
  239. ac *addrConn
  240. }
  241. func (acbw *acBalancerWrapper) UpdateAddresses(addrs []resolver.Address) {
  242. acbw.mu.Lock()
  243. defer acbw.mu.Unlock()
  244. if len(addrs) <= 0 {
  245. acbw.ac.tearDown(errConnDrain)
  246. return
  247. }
  248. if !acbw.ac.tryUpdateAddrs(addrs) {
  249. cc := acbw.ac.cc
  250. opts := acbw.ac.scopts
  251. acbw.ac.mu.Lock()
  252. // Set old ac.acbw to nil so the Shutdown state update will be ignored
  253. // by balancer.
  254. //
  255. // TODO(bar) the state transition could be wrong when tearDown() old ac
  256. // and creating new ac, fix the transition.
  257. acbw.ac.acbw = nil
  258. acbw.ac.mu.Unlock()
  259. acState := acbw.ac.getState()
  260. acbw.ac.tearDown(errConnDrain)
  261. if acState == connectivity.Shutdown {
  262. return
  263. }
  264. ac, err := cc.newAddrConn(addrs, opts)
  265. if err != nil {
  266. grpclog.Warningf("acBalancerWrapper: UpdateAddresses: failed to newAddrConn: %v", err)
  267. return
  268. }
  269. acbw.ac = ac
  270. ac.mu.Lock()
  271. ac.acbw = acbw
  272. ac.mu.Unlock()
  273. if acState != connectivity.Idle {
  274. ac.connect()
  275. }
  276. }
  277. }
  278. func (acbw *acBalancerWrapper) Connect() {
  279. acbw.mu.Lock()
  280. defer acbw.mu.Unlock()
  281. acbw.ac.connect()
  282. }
  283. func (acbw *acBalancerWrapper) getAddrConn() *addrConn {
  284. acbw.mu.Lock()
  285. defer acbw.mu.Unlock()
  286. return acbw.ac
  287. }