balancer_v1_wrapper.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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. "strings"
  21. "sync"
  22. "golang.org/x/net/context"
  23. "google.golang.org/grpc/balancer"
  24. "google.golang.org/grpc/codes"
  25. "google.golang.org/grpc/connectivity"
  26. "google.golang.org/grpc/grpclog"
  27. "google.golang.org/grpc/resolver"
  28. "google.golang.org/grpc/status"
  29. )
  30. type balancerWrapperBuilder struct {
  31. b Balancer // The v1 balancer.
  32. }
  33. func (bwb *balancerWrapperBuilder) Build(cc balancer.ClientConn, opts balancer.BuildOptions) balancer.Balancer {
  34. targetAddr := cc.Target()
  35. targetSplitted := strings.Split(targetAddr, ":///")
  36. if len(targetSplitted) >= 2 {
  37. targetAddr = targetSplitted[1]
  38. }
  39. bwb.b.Start(targetAddr, BalancerConfig{
  40. DialCreds: opts.DialCreds,
  41. Dialer: opts.Dialer,
  42. })
  43. _, pickfirst := bwb.b.(*pickFirst)
  44. bw := &balancerWrapper{
  45. balancer: bwb.b,
  46. pickfirst: pickfirst,
  47. cc: cc,
  48. targetAddr: targetAddr,
  49. startCh: make(chan struct{}),
  50. conns: make(map[resolver.Address]balancer.SubConn),
  51. connSt: make(map[balancer.SubConn]*scState),
  52. csEvltr: &connectivityStateEvaluator{},
  53. state: connectivity.Idle,
  54. }
  55. cc.UpdateBalancerState(connectivity.Idle, bw)
  56. go bw.lbWatcher()
  57. return bw
  58. }
  59. func (bwb *balancerWrapperBuilder) Name() string {
  60. return "wrapper"
  61. }
  62. type scState struct {
  63. addr Address // The v1 address type.
  64. s connectivity.State
  65. down func(error)
  66. }
  67. type balancerWrapper struct {
  68. balancer Balancer // The v1 balancer.
  69. pickfirst bool
  70. cc balancer.ClientConn
  71. targetAddr string // Target without the scheme.
  72. // To aggregate the connectivity state.
  73. csEvltr *connectivityStateEvaluator
  74. state connectivity.State
  75. mu sync.Mutex
  76. conns map[resolver.Address]balancer.SubConn
  77. connSt map[balancer.SubConn]*scState
  78. // This channel is closed when handling the first resolver result.
  79. // lbWatcher blocks until this is closed, to avoid race between
  80. // - NewSubConn is created, cc wants to notify balancer of state changes;
  81. // - Build hasn't return, cc doesn't have access to balancer.
  82. startCh chan struct{}
  83. }
  84. // lbWatcher watches the Notify channel of the balancer and manages
  85. // connections accordingly.
  86. func (bw *balancerWrapper) lbWatcher() {
  87. <-bw.startCh
  88. notifyCh := bw.balancer.Notify()
  89. if notifyCh == nil {
  90. // There's no resolver in the balancer. Connect directly.
  91. a := resolver.Address{
  92. Addr: bw.targetAddr,
  93. Type: resolver.Backend,
  94. }
  95. sc, err := bw.cc.NewSubConn([]resolver.Address{a}, balancer.NewSubConnOptions{})
  96. if err != nil {
  97. grpclog.Warningf("Error creating connection to %v. Err: %v", a, err)
  98. } else {
  99. bw.mu.Lock()
  100. bw.conns[a] = sc
  101. bw.connSt[sc] = &scState{
  102. addr: Address{Addr: bw.targetAddr},
  103. s: connectivity.Idle,
  104. }
  105. bw.mu.Unlock()
  106. sc.Connect()
  107. }
  108. return
  109. }
  110. for addrs := range notifyCh {
  111. grpclog.Infof("balancerWrapper: got update addr from Notify: %v\n", addrs)
  112. if bw.pickfirst {
  113. var (
  114. oldA resolver.Address
  115. oldSC balancer.SubConn
  116. )
  117. bw.mu.Lock()
  118. for oldA, oldSC = range bw.conns {
  119. break
  120. }
  121. bw.mu.Unlock()
  122. if len(addrs) <= 0 {
  123. if oldSC != nil {
  124. // Teardown old sc.
  125. bw.mu.Lock()
  126. delete(bw.conns, oldA)
  127. delete(bw.connSt, oldSC)
  128. bw.mu.Unlock()
  129. bw.cc.RemoveSubConn(oldSC)
  130. }
  131. continue
  132. }
  133. var newAddrs []resolver.Address
  134. for _, a := range addrs {
  135. newAddr := resolver.Address{
  136. Addr: a.Addr,
  137. Type: resolver.Backend, // All addresses from balancer are all backends.
  138. ServerName: "",
  139. Metadata: a.Metadata,
  140. }
  141. newAddrs = append(newAddrs, newAddr)
  142. }
  143. if oldSC == nil {
  144. // Create new sc.
  145. sc, err := bw.cc.NewSubConn(newAddrs, balancer.NewSubConnOptions{})
  146. if err != nil {
  147. grpclog.Warningf("Error creating connection to %v. Err: %v", newAddrs, err)
  148. } else {
  149. bw.mu.Lock()
  150. // For pickfirst, there should be only one SubConn, so the
  151. // address doesn't matter. All states updating (up and down)
  152. // and picking should all happen on that only SubConn.
  153. bw.conns[resolver.Address{}] = sc
  154. bw.connSt[sc] = &scState{
  155. addr: addrs[0], // Use the first address.
  156. s: connectivity.Idle,
  157. }
  158. bw.mu.Unlock()
  159. sc.Connect()
  160. }
  161. } else {
  162. bw.mu.Lock()
  163. bw.connSt[oldSC].addr = addrs[0]
  164. bw.mu.Unlock()
  165. oldSC.UpdateAddresses(newAddrs)
  166. }
  167. } else {
  168. var (
  169. add []resolver.Address // Addresses need to setup connections.
  170. del []balancer.SubConn // Connections need to tear down.
  171. )
  172. resAddrs := make(map[resolver.Address]Address)
  173. for _, a := range addrs {
  174. resAddrs[resolver.Address{
  175. Addr: a.Addr,
  176. Type: resolver.Backend, // All addresses from balancer are all backends.
  177. ServerName: "",
  178. Metadata: a.Metadata,
  179. }] = a
  180. }
  181. bw.mu.Lock()
  182. for a := range resAddrs {
  183. if _, ok := bw.conns[a]; !ok {
  184. add = append(add, a)
  185. }
  186. }
  187. for a, c := range bw.conns {
  188. if _, ok := resAddrs[a]; !ok {
  189. del = append(del, c)
  190. delete(bw.conns, a)
  191. // Keep the state of this sc in bw.connSt until its state becomes Shutdown.
  192. }
  193. }
  194. bw.mu.Unlock()
  195. for _, a := range add {
  196. sc, err := bw.cc.NewSubConn([]resolver.Address{a}, balancer.NewSubConnOptions{})
  197. if err != nil {
  198. grpclog.Warningf("Error creating connection to %v. Err: %v", a, err)
  199. } else {
  200. bw.mu.Lock()
  201. bw.conns[a] = sc
  202. bw.connSt[sc] = &scState{
  203. addr: resAddrs[a],
  204. s: connectivity.Idle,
  205. }
  206. bw.mu.Unlock()
  207. sc.Connect()
  208. }
  209. }
  210. for _, c := range del {
  211. bw.cc.RemoveSubConn(c)
  212. }
  213. }
  214. }
  215. }
  216. func (bw *balancerWrapper) HandleSubConnStateChange(sc balancer.SubConn, s connectivity.State) {
  217. bw.mu.Lock()
  218. defer bw.mu.Unlock()
  219. scSt, ok := bw.connSt[sc]
  220. if !ok {
  221. return
  222. }
  223. if s == connectivity.Idle {
  224. sc.Connect()
  225. }
  226. oldS := scSt.s
  227. scSt.s = s
  228. if oldS != connectivity.Ready && s == connectivity.Ready {
  229. scSt.down = bw.balancer.Up(scSt.addr)
  230. } else if oldS == connectivity.Ready && s != connectivity.Ready {
  231. if scSt.down != nil {
  232. scSt.down(errConnClosing)
  233. }
  234. }
  235. sa := bw.csEvltr.recordTransition(oldS, s)
  236. if bw.state != sa {
  237. bw.state = sa
  238. }
  239. bw.cc.UpdateBalancerState(bw.state, bw)
  240. if s == connectivity.Shutdown {
  241. // Remove state for this sc.
  242. delete(bw.connSt, sc)
  243. }
  244. return
  245. }
  246. func (bw *balancerWrapper) HandleResolvedAddrs([]resolver.Address, error) {
  247. bw.mu.Lock()
  248. defer bw.mu.Unlock()
  249. select {
  250. case <-bw.startCh:
  251. default:
  252. close(bw.startCh)
  253. }
  254. // There should be a resolver inside the balancer.
  255. // All updates here, if any, are ignored.
  256. return
  257. }
  258. func (bw *balancerWrapper) Close() {
  259. bw.mu.Lock()
  260. defer bw.mu.Unlock()
  261. select {
  262. case <-bw.startCh:
  263. default:
  264. close(bw.startCh)
  265. }
  266. bw.balancer.Close()
  267. return
  268. }
  269. // The picker is the balancerWrapper itself.
  270. // Pick should never return ErrNoSubConnAvailable.
  271. // It either blocks or returns error, consistent with v1 balancer Get().
  272. func (bw *balancerWrapper) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) {
  273. failfast := true // Default failfast is true.
  274. if ss, ok := rpcInfoFromContext(ctx); ok {
  275. failfast = ss.failfast
  276. }
  277. a, p, err := bw.balancer.Get(ctx, BalancerGetOptions{BlockingWait: !failfast})
  278. if err != nil {
  279. return nil, nil, err
  280. }
  281. var done func(balancer.DoneInfo)
  282. if p != nil {
  283. done = func(i balancer.DoneInfo) { p() }
  284. }
  285. var sc balancer.SubConn
  286. bw.mu.Lock()
  287. defer bw.mu.Unlock()
  288. if bw.pickfirst {
  289. // Get the first sc in conns.
  290. for _, sc = range bw.conns {
  291. break
  292. }
  293. } else {
  294. var ok bool
  295. sc, ok = bw.conns[resolver.Address{
  296. Addr: a.Addr,
  297. Type: resolver.Backend,
  298. ServerName: "",
  299. Metadata: a.Metadata,
  300. }]
  301. if !ok && failfast {
  302. return nil, nil, status.Errorf(codes.Unavailable, "there is no connection available")
  303. }
  304. if s, ok := bw.connSt[sc]; failfast && (!ok || s.s != connectivity.Ready) {
  305. // If the returned sc is not ready and RPC is failfast,
  306. // return error, and this RPC will fail.
  307. return nil, nil, status.Errorf(codes.Unavailable, "there is no connection available")
  308. }
  309. }
  310. return sc, done, nil
  311. }
  312. // connectivityStateEvaluator gets updated by addrConns when their
  313. // states transition, based on which it evaluates the state of
  314. // ClientConn.
  315. type connectivityStateEvaluator struct {
  316. mu sync.Mutex
  317. numReady uint64 // Number of addrConns in ready state.
  318. numConnecting uint64 // Number of addrConns in connecting state.
  319. numTransientFailure uint64 // Number of addrConns in transientFailure.
  320. }
  321. // recordTransition records state change happening in every subConn and based on
  322. // that it evaluates what aggregated state should be.
  323. // It can only transition between Ready, Connecting and TransientFailure. Other states,
  324. // Idle and Shutdown are transitioned into by ClientConn; in the beginning of the connection
  325. // before any subConn is created ClientConn is in idle state. In the end when ClientConn
  326. // closes it is in Shutdown state.
  327. // TODO Note that in later releases, a ClientConn with no activity will be put into an Idle state.
  328. func (cse *connectivityStateEvaluator) recordTransition(oldState, newState connectivity.State) connectivity.State {
  329. cse.mu.Lock()
  330. defer cse.mu.Unlock()
  331. // Update counters.
  332. for idx, state := range []connectivity.State{oldState, newState} {
  333. updateVal := 2*uint64(idx) - 1 // -1 for oldState and +1 for new.
  334. switch state {
  335. case connectivity.Ready:
  336. cse.numReady += updateVal
  337. case connectivity.Connecting:
  338. cse.numConnecting += updateVal
  339. case connectivity.TransientFailure:
  340. cse.numTransientFailure += updateVal
  341. }
  342. }
  343. // Evaluate.
  344. if cse.numReady > 0 {
  345. return connectivity.Ready
  346. }
  347. if cse.numConnecting > 0 {
  348. return connectivity.Connecting
  349. }
  350. return connectivity.TransientFailure
  351. }