balancer_v1_wrapper.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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: &balancer.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. mu sync.Mutex
  73. conns map[resolver.Address]balancer.SubConn
  74. connSt map[balancer.SubConn]*scState
  75. // This channel is closed when handling the first resolver result.
  76. // lbWatcher blocks until this is closed, to avoid race between
  77. // - NewSubConn is created, cc wants to notify balancer of state changes;
  78. // - Build hasn't return, cc doesn't have access to balancer.
  79. startCh chan struct{}
  80. // To aggregate the connectivity state.
  81. csEvltr *balancer.ConnectivityStateEvaluator
  82. state connectivity.State
  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. }
  245. func (bw *balancerWrapper) HandleResolvedAddrs([]resolver.Address, error) {
  246. bw.mu.Lock()
  247. defer bw.mu.Unlock()
  248. select {
  249. case <-bw.startCh:
  250. default:
  251. close(bw.startCh)
  252. }
  253. // There should be a resolver inside the balancer.
  254. // All updates here, if any, are ignored.
  255. }
  256. func (bw *balancerWrapper) Close() {
  257. bw.mu.Lock()
  258. defer bw.mu.Unlock()
  259. select {
  260. case <-bw.startCh:
  261. default:
  262. close(bw.startCh)
  263. }
  264. bw.balancer.Close()
  265. }
  266. // The picker is the balancerWrapper itself.
  267. // Pick should never return ErrNoSubConnAvailable.
  268. // It either blocks or returns error, consistent with v1 balancer Get().
  269. func (bw *balancerWrapper) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) {
  270. failfast := true // Default failfast is true.
  271. if ss, ok := rpcInfoFromContext(ctx); ok {
  272. failfast = ss.failfast
  273. }
  274. a, p, err := bw.balancer.Get(ctx, BalancerGetOptions{BlockingWait: !failfast})
  275. if err != nil {
  276. return nil, nil, err
  277. }
  278. var done func(balancer.DoneInfo)
  279. if p != nil {
  280. done = func(i balancer.DoneInfo) { p() }
  281. }
  282. var sc balancer.SubConn
  283. bw.mu.Lock()
  284. defer bw.mu.Unlock()
  285. if bw.pickfirst {
  286. // Get the first sc in conns.
  287. for _, sc = range bw.conns {
  288. break
  289. }
  290. } else {
  291. var ok bool
  292. sc, ok = bw.conns[resolver.Address{
  293. Addr: a.Addr,
  294. Type: resolver.Backend,
  295. ServerName: "",
  296. Metadata: a.Metadata,
  297. }]
  298. if !ok && failfast {
  299. return nil, nil, status.Errorf(codes.Unavailable, "there is no connection available")
  300. }
  301. if s, ok := bw.connSt[sc]; failfast && (!ok || s.s != connectivity.Ready) {
  302. // If the returned sc is not ready and RPC is failfast,
  303. // return error, and this RPC will fail.
  304. return nil, nil, status.Errorf(codes.Unavailable, "there is no connection available")
  305. }
  306. }
  307. return sc, done, nil
  308. }