Debian Codegraph @

vendor/google.golang.org/grpc/balancer_v1_wrapper.go

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