balancer_v1_wrapper.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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. "sync"
  21. "golang.org/x/net/context"
  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. type balancerWrapperBuilder struct {
  28. b Balancer // The v1 balancer.
  29. }
  30. func (bwb *balancerWrapperBuilder) Build(cc balancer.ClientConn, opts balancer.BuildOptions) balancer.Balancer {
  31. bwb.b.Start(cc.Target(), BalancerConfig{
  32. DialCreds: opts.DialCreds,
  33. Dialer: opts.Dialer,
  34. })
  35. _, pickfirst := bwb.b.(*pickFirst)
  36. bw := &balancerWrapper{
  37. balancer: bwb.b,
  38. pickfirst: pickfirst,
  39. cc: cc,
  40. startCh: make(chan struct{}),
  41. conns: make(map[resolver.Address]balancer.SubConn),
  42. connSt: make(map[balancer.SubConn]*scState),
  43. }
  44. cc.UpdateBalancerState(connectivity.Idle, bw)
  45. go bw.lbWatcher()
  46. return bw
  47. }
  48. func (bwb *balancerWrapperBuilder) Name() string {
  49. return "wrapper"
  50. }
  51. type scState struct {
  52. addr Address // The v1 address type.
  53. s connectivity.State
  54. down func(error)
  55. }
  56. type balancerWrapper struct {
  57. balancer Balancer // The v1 balancer.
  58. pickfirst bool
  59. cc balancer.ClientConn
  60. mu sync.Mutex
  61. conns map[resolver.Address]balancer.SubConn
  62. connSt map[balancer.SubConn]*scState
  63. // This channel is closed when handling the first resolver result.
  64. // lbWatcher blocks until this is closed, to avoid race between
  65. // - NewSubConn is created, cc wants to notify balancer of state changes;
  66. // - Build hasn't return, cc doesn't have access to balancer.
  67. startCh chan struct{}
  68. }
  69. // lbWatcher watches the Notify channel of the balancer and manages
  70. // connections accordingly.
  71. func (bw *balancerWrapper) lbWatcher() {
  72. <-bw.startCh
  73. grpclog.Infof("balancerWrapper: is pickfirst: %v\n", bw.pickfirst)
  74. notifyCh := bw.balancer.Notify()
  75. if notifyCh == nil {
  76. // There's no resolver in the balancer. Connect directly.
  77. a := resolver.Address{
  78. Addr: bw.cc.Target(),
  79. Type: resolver.Backend,
  80. }
  81. sc, err := bw.cc.NewSubConn([]resolver.Address{a}, balancer.NewSubConnOptions{})
  82. if err != nil {
  83. grpclog.Warningf("Error creating connection to %v. Err: %v", a, err)
  84. } else {
  85. bw.mu.Lock()
  86. bw.conns[a] = sc
  87. bw.connSt[sc] = &scState{
  88. addr: Address{Addr: bw.cc.Target()},
  89. s: connectivity.Idle,
  90. }
  91. bw.mu.Unlock()
  92. sc.Connect()
  93. }
  94. return
  95. }
  96. for addrs := range notifyCh {
  97. grpclog.Infof("balancerWrapper: got update addr from Notify: %v\n", addrs)
  98. if bw.pickfirst {
  99. var (
  100. oldA resolver.Address
  101. oldSC balancer.SubConn
  102. )
  103. bw.mu.Lock()
  104. for oldA, oldSC = range bw.conns {
  105. break
  106. }
  107. bw.mu.Unlock()
  108. if len(addrs) <= 0 {
  109. if oldSC != nil {
  110. // Teardown old sc.
  111. bw.mu.Lock()
  112. delete(bw.conns, oldA)
  113. delete(bw.connSt, oldSC)
  114. bw.mu.Unlock()
  115. bw.cc.RemoveSubConn(oldSC)
  116. }
  117. continue
  118. }
  119. var newAddrs []resolver.Address
  120. for _, a := range addrs {
  121. newAddr := resolver.Address{
  122. Addr: a.Addr,
  123. Type: resolver.Backend, // All addresses from balancer are all backends.
  124. ServerName: "", // TODO(bar) support servername.
  125. Metadata: a.Metadata,
  126. }
  127. newAddrs = append(newAddrs, newAddr)
  128. }
  129. if oldSC == nil {
  130. // Create new sc.
  131. sc, err := bw.cc.NewSubConn(newAddrs, balancer.NewSubConnOptions{})
  132. if err != nil {
  133. grpclog.Warningf("Error creating connection to %v. Err: %v", newAddrs, err)
  134. } else {
  135. bw.mu.Lock()
  136. // For pickfirst, there should be only one SubConn, so the
  137. // address doesn't matter. All states updating (up and down)
  138. // and picking should all happen on that only SubConn.
  139. bw.conns[resolver.Address{}] = sc
  140. bw.connSt[sc] = &scState{
  141. addr: addrs[0], // Use the first address.
  142. s: connectivity.Idle,
  143. }
  144. bw.mu.Unlock()
  145. sc.Connect()
  146. }
  147. } else {
  148. oldSC.UpdateAddresses(newAddrs)
  149. bw.mu.Lock()
  150. bw.connSt[oldSC].addr = addrs[0]
  151. bw.mu.Unlock()
  152. }
  153. } else {
  154. var (
  155. add []resolver.Address // Addresses need to setup connections.
  156. del []balancer.SubConn // Connections need to tear down.
  157. )
  158. resAddrs := make(map[resolver.Address]Address)
  159. for _, a := range addrs {
  160. resAddrs[resolver.Address{
  161. Addr: a.Addr,
  162. Type: resolver.Backend, // All addresses from balancer are all backends.
  163. ServerName: "", // TODO(bar) support servername.
  164. Metadata: a.Metadata,
  165. }] = a
  166. }
  167. bw.mu.Lock()
  168. for a := range resAddrs {
  169. if _, ok := bw.conns[a]; !ok {
  170. add = append(add, a)
  171. }
  172. }
  173. for a, c := range bw.conns {
  174. if _, ok := resAddrs[a]; !ok {
  175. del = append(del, c)
  176. delete(bw.conns, a)
  177. delete(bw.connSt, c)
  178. }
  179. }
  180. bw.mu.Unlock()
  181. for _, a := range add {
  182. sc, err := bw.cc.NewSubConn([]resolver.Address{a}, balancer.NewSubConnOptions{})
  183. if err != nil {
  184. grpclog.Warningf("Error creating connection to %v. Err: %v", a, err)
  185. } else {
  186. bw.mu.Lock()
  187. bw.conns[a] = sc
  188. bw.connSt[sc] = &scState{
  189. addr: resAddrs[a],
  190. s: connectivity.Idle,
  191. }
  192. bw.mu.Unlock()
  193. sc.Connect()
  194. }
  195. }
  196. for _, c := range del {
  197. bw.cc.RemoveSubConn(c)
  198. }
  199. }
  200. }
  201. }
  202. func (bw *balancerWrapper) HandleSubConnStateChange(sc balancer.SubConn, s connectivity.State) {
  203. grpclog.Infof("balancerWrapper: handle subconn state change: %p, %v", sc, s)
  204. bw.mu.Lock()
  205. defer bw.mu.Unlock()
  206. scSt, ok := bw.connSt[sc]
  207. if !ok {
  208. return
  209. }
  210. if s == connectivity.Idle {
  211. sc.Connect()
  212. }
  213. oldS := scSt.s
  214. scSt.s = s
  215. if oldS != connectivity.Ready && s == connectivity.Ready {
  216. scSt.down = bw.balancer.Up(scSt.addr)
  217. } else if oldS == connectivity.Ready && s != connectivity.Ready {
  218. if scSt.down != nil {
  219. scSt.down(errConnClosing) // TODO(bar) what error to use?
  220. }
  221. }
  222. // The connectivity state is ignored by clientConn now.
  223. // TODO(bar) use the aggregated connectivity state.
  224. bw.cc.UpdateBalancerState(connectivity.Ready, bw)
  225. return
  226. }
  227. func (bw *balancerWrapper) HandleResolvedAddrs([]resolver.Address, error) {
  228. bw.mu.Lock()
  229. defer bw.mu.Unlock()
  230. select {
  231. case <-bw.startCh:
  232. default:
  233. close(bw.startCh)
  234. }
  235. // There should be a resolver inside the balancer.
  236. // All updates here, if any, are ignored.
  237. return
  238. }
  239. func (bw *balancerWrapper) Close() {
  240. bw.mu.Lock()
  241. defer bw.mu.Unlock()
  242. select {
  243. case <-bw.startCh:
  244. default:
  245. close(bw.startCh)
  246. }
  247. bw.balancer.Close()
  248. return
  249. }
  250. // The picker is the balancerWrapper itself.
  251. // Pick should never return ErrNoSubConnAvailable.
  252. // It either blocks or returns error, consistent with v1 balancer Get().
  253. func (bw *balancerWrapper) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) {
  254. failfast := true // Default failfast is true.
  255. if ss, ok := rpcInfoFromContext(ctx); ok {
  256. failfast = ss.failfast
  257. }
  258. a, p, err := bw.balancer.Get(ctx, BalancerGetOptions{BlockingWait: !failfast})
  259. if err != nil {
  260. return nil, nil, err
  261. }
  262. var put func(balancer.DoneInfo)
  263. if p != nil {
  264. put = func(i balancer.DoneInfo) { p() }
  265. }
  266. var sc balancer.SubConn
  267. if bw.pickfirst {
  268. bw.mu.Lock()
  269. // Get the first sc in conns.
  270. for _, sc = range bw.conns {
  271. break
  272. }
  273. bw.mu.Unlock()
  274. } else {
  275. bw.mu.Lock()
  276. sc = bw.conns[resolver.Address{
  277. Addr: a.Addr,
  278. Type: resolver.Backend,
  279. ServerName: "", // TODO(bar) support servername.
  280. Metadata: a.Metadata,
  281. }]
  282. bw.mu.Unlock()
  283. }
  284. return sc, put, nil
  285. }