3 * Copyright 2017 gRPC authors.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
26 "google.golang.org/grpc/balancer"
27 "google.golang.org/grpc/connectivity"
28 "google.golang.org/grpc/grpclog"
29 "google.golang.org/grpc/resolver"
32 type balancerWrapperBuilder struct {
33 b Balancer // The v1 balancer.
36 func (bwb *balancerWrapperBuilder) Build(cc balancer.ClientConn, opts balancer.BuildOptions) balancer.Balancer {
37 targetAddr := cc.Target()
38 targetSplitted := strings.Split(targetAddr, ":///")
39 if len(targetSplitted) >= 2 {
40 targetAddr = targetSplitted[1]
43 bwb.b.Start(targetAddr, BalancerConfig{
44 DialCreds: opts.DialCreds,
47 _, pickfirst := bwb.b.(*pickFirst)
48 bw := &balancerWrapper{
52 targetAddr: targetAddr,
53 startCh: make(chan struct{}),
54 conns: make(map[resolver.Address]balancer.SubConn),
55 connSt: make(map[balancer.SubConn]*scState),
56 csEvltr: &balancer.ConnectivityStateEvaluator{},
57 state: connectivity.Idle,
59 cc.UpdateBalancerState(connectivity.Idle, bw)
64 func (bwb *balancerWrapperBuilder) Name() string {
69 addr Address // The v1 address type.
74 type balancerWrapper struct {
75 balancer Balancer // The v1 balancer.
78 cc balancer.ClientConn
79 targetAddr string // Target without the scheme.
82 conns map[resolver.Address]balancer.SubConn
83 connSt map[balancer.SubConn]*scState
84 // This channel is closed when handling the first resolver result.
85 // lbWatcher blocks until this is closed, to avoid race between
86 // - NewSubConn is created, cc wants to notify balancer of state changes;
87 // - Build hasn't return, cc doesn't have access to balancer.
90 // To aggregate the connectivity state.
91 csEvltr *balancer.ConnectivityStateEvaluator
92 state connectivity.State
95 // lbWatcher watches the Notify channel of the balancer and manages
96 // connections accordingly.
97 func (bw *balancerWrapper) lbWatcher() {
99 notifyCh := bw.balancer.Notify()
101 // There's no resolver in the balancer. Connect directly.
102 a := resolver.Address{
104 Type: resolver.Backend,
106 sc, err := bw.cc.NewSubConn([]resolver.Address{a}, balancer.NewSubConnOptions{})
108 grpclog.Warningf("Error creating connection to %v. Err: %v", a, err)
112 bw.connSt[sc] = &scState{
113 addr: Address{Addr: bw.targetAddr},
114 s: connectivity.Idle,
122 for addrs := range notifyCh {
123 grpclog.Infof("balancerWrapper: got update addr from Notify: %v\n", addrs)
126 oldA resolver.Address
127 oldSC balancer.SubConn
130 for oldA, oldSC = range bw.conns {
138 delete(bw.conns, oldA)
139 delete(bw.connSt, oldSC)
141 bw.cc.RemoveSubConn(oldSC)
146 var newAddrs []resolver.Address
147 for _, a := range addrs {
148 newAddr := resolver.Address{
150 Type: resolver.Backend, // All addresses from balancer are all backends.
152 Metadata: a.Metadata,
154 newAddrs = append(newAddrs, newAddr)
158 sc, err := bw.cc.NewSubConn(newAddrs, balancer.NewSubConnOptions{})
160 grpclog.Warningf("Error creating connection to %v. Err: %v", newAddrs, err)
163 // For pickfirst, there should be only one SubConn, so the
164 // address doesn't matter. All states updating (up and down)
165 // and picking should all happen on that only SubConn.
166 bw.conns[resolver.Address{}] = sc
167 bw.connSt[sc] = &scState{
168 addr: addrs[0], // Use the first address.
169 s: connectivity.Idle,
176 bw.connSt[oldSC].addr = addrs[0]
178 oldSC.UpdateAddresses(newAddrs)
182 add []resolver.Address // Addresses need to setup connections.
183 del []balancer.SubConn // Connections need to tear down.
185 resAddrs := make(map[resolver.Address]Address)
186 for _, a := range addrs {
187 resAddrs[resolver.Address{
189 Type: resolver.Backend, // All addresses from balancer are all backends.
191 Metadata: a.Metadata,
195 for a := range resAddrs {
196 if _, ok := bw.conns[a]; !ok {
200 for a, c := range bw.conns {
201 if _, ok := resAddrs[a]; !ok {
204 // Keep the state of this sc in bw.connSt until its state becomes Shutdown.
208 for _, a := range add {
209 sc, err := bw.cc.NewSubConn([]resolver.Address{a}, balancer.NewSubConnOptions{})
211 grpclog.Warningf("Error creating connection to %v. Err: %v", a, err)
215 bw.connSt[sc] = &scState{
217 s: connectivity.Idle,
223 for _, c := range del {
224 bw.cc.RemoveSubConn(c)
230 func (bw *balancerWrapper) HandleSubConnStateChange(sc balancer.SubConn, s connectivity.State) {
233 scSt, ok := bw.connSt[sc]
237 if s == connectivity.Idle {
242 if oldS != connectivity.Ready && s == connectivity.Ready {
243 scSt.down = bw.balancer.Up(scSt.addr)
244 } else if oldS == connectivity.Ready && s != connectivity.Ready {
245 if scSt.down != nil {
246 scSt.down(errConnClosing)
249 sa := bw.csEvltr.RecordTransition(oldS, s)
253 bw.cc.UpdateBalancerState(bw.state, bw)
254 if s == connectivity.Shutdown {
255 // Remove state for this sc.
256 delete(bw.connSt, sc)
260 func (bw *balancerWrapper) HandleResolvedAddrs([]resolver.Address, error) {
268 // There should be a resolver inside the balancer.
269 // All updates here, if any, are ignored.
272 func (bw *balancerWrapper) Close() {
283 // The picker is the balancerWrapper itself.
284 // It either blocks or returns error, consistent with v1 balancer Get().
285 func (bw *balancerWrapper) Pick(ctx context.Context, opts balancer.PickOptions) (sc balancer.SubConn, done func(balancer.DoneInfo), err error) {
286 failfast := true // Default failfast is true.
287 if ss, ok := rpcInfoFromContext(ctx); ok {
288 failfast = ss.failfast
290 a, p, err := bw.balancer.Get(ctx, BalancerGetOptions{BlockingWait: !failfast})
295 done = func(balancer.DoneInfo) { p() }
306 // Get the first sc in conns.
307 for _, sc := range bw.conns {
310 return nil, nil, balancer.ErrNoSubConnAvailable
312 sc, ok1 := bw.conns[resolver.Address{
314 Type: resolver.Backend,
316 Metadata: a.Metadata,
318 s, ok2 := bw.connSt[sc]
320 // This can only happen due to a race where Get() returned an address
321 // that was subsequently removed by Notify. In this case we should
323 return nil, nil, balancer.ErrNoSubConnAvailable
326 case connectivity.Ready, connectivity.Idle:
328 case connectivity.Shutdown, connectivity.TransientFailure:
329 // If the returned sc has been shut down or is in transient failure,
330 // return error, and this RPC will fail or wait for another picker (if
332 return nil, nil, balancer.ErrTransientFailure
334 // For other states (connecting or unknown), the v1 balancer would
335 // traditionally wait until ready and then issue the RPC. Returning
336 // ErrNoSubConnAvailable will be a slight improvement in that it will
337 // allow the balancer to choose another address in case others are
339 return nil, nil, balancer.ErrNoSubConnAvailable