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

342 lines
9.0 KiB

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