Debian Codegraph @

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

raw
1 /*
2 *
3 * Copyright 2014 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 "errors"
23 "fmt"
24 "math"
25 "net"
26 "reflect"
27 "strings"
28 "sync"
29 "time"
30
31 "golang.org/x/net/context"
32 "golang.org/x/net/trace"
33 "google.golang.org/grpc/balancer"
34 "google.golang.org/grpc/connectivity"
35 "google.golang.org/grpc/credentials"
36 "google.golang.org/grpc/grpclog"
37 "google.golang.org/grpc/keepalive"
38 "google.golang.org/grpc/resolver"
39 "google.golang.org/grpc/stats"
40 "google.golang.org/grpc/transport"
41 )
42
43 var (
44 // ErrClientConnClosing indicates that the operation is illegal because
45 // the ClientConn is closing.
46 ErrClientConnClosing = errors.New("grpc: the client connection is closing")
47 // ErrClientConnTimeout indicates that the ClientConn cannot establish the
48 // underlying connections within the specified timeout.
49 // DEPRECATED: Please use context.DeadlineExceeded instead.
50 ErrClientConnTimeout = errors.New("grpc: timed out when dialing")
51
52 // errNoTransportSecurity indicates that there is no transport security
53 // being set for ClientConn. Users should either set one or explicitly
54 // call WithInsecure DialOption to disable security.
55 errNoTransportSecurity = errors.New("grpc: no transport security set (use grpc.WithInsecure() explicitly or set credentials)")
56 // errTransportCredentialsMissing indicates that users want to transmit security
57 // information (e.g., oauth2 token) which requires secure connection on an insecure
58 // connection.
59 errTransportCredentialsMissing = errors.New("grpc: the credentials require transport level security (use grpc.WithTransportCredentials() to set)")
60 // errCredentialsConflict indicates that grpc.WithTransportCredentials()
61 // and grpc.WithInsecure() are both called for a connection.
62 errCredentialsConflict = errors.New("grpc: transport credentials are set for an insecure connection (grpc.WithTransportCredentials() and grpc.WithInsecure() are both called)")
63 // errNetworkIO indicates that the connection is down due to some network I/O error.
64 errNetworkIO = errors.New("grpc: failed with network I/O error")
65 // errConnDrain indicates that the connection starts to be drained and does not accept any new RPCs.
66 errConnDrain = errors.New("grpc: the connection is drained")
67 // errConnClosing indicates that the connection is closing.
68 errConnClosing = errors.New("grpc: the connection is closing")
69 // errConnUnavailable indicates that the connection is unavailable.
70 errConnUnavailable = errors.New("grpc: the connection is unavailable")
71 // errBalancerClosed indicates that the balancer is closed.
72 errBalancerClosed = errors.New("grpc: balancer is closed")
73 // minimum time to give a connection to complete
74 minConnectTimeout = 20 * time.Second
75 )
76
77 // dialOptions configure a Dial call. dialOptions are set by the DialOption
78 // values passed to Dial.
79 type dialOptions struct {
80 unaryInt UnaryClientInterceptor
81 streamInt StreamClientInterceptor
82 codec Codec
83 cp Compressor
84 dc Decompressor
85 bs backoffStrategy
86 block bool
87 insecure bool
88 timeout time.Duration
89 scChan <-chan ServiceConfig
90 copts transport.ConnectOptions
91 callOptions []CallOption
92 // This is to support v1 balancer.
93 balancerBuilder balancer.Builder
94 }
95
96 const (
97 defaultClientMaxReceiveMessageSize = 1024 * 1024 * 4
98 defaultClientMaxSendMessageSize = math.MaxInt32
99 )
100
101 // DialOption configures how we set up the connection.
102 type DialOption func(*dialOptions)
103
104 // WithWriteBufferSize lets you set the size of write buffer, this determines how much data can be batched
105 // before doing a write on the wire.
106 func WithWriteBufferSize(s int) DialOption {
107 return func(o *dialOptions) {
108 o.copts.WriteBufferSize = s
109 }
110 }
111
112 // WithReadBufferSize lets you set the size of read buffer, this determines how much data can be read at most
113 // for each read syscall.
114 func WithReadBufferSize(s int) DialOption {
115 return func(o *dialOptions) {
116 o.copts.ReadBufferSize = s
117 }
118 }
119
120 // WithInitialWindowSize returns a DialOption which sets the value for initial window size on a stream.
121 // The lower bound for window size is 64K and any value smaller than that will be ignored.
122 func WithInitialWindowSize(s int32) DialOption {
123 return func(o *dialOptions) {
124 o.copts.InitialWindowSize = s
125 }
126 }
127
128 // WithInitialConnWindowSize returns a DialOption which sets the value for initial window size on a connection.
129 // The lower bound for window size is 64K and any value smaller than that will be ignored.
130 func WithInitialConnWindowSize(s int32) DialOption {
131 return func(o *dialOptions) {
132 o.copts.InitialConnWindowSize = s
133 }
134 }
135
136 // WithMaxMsgSize returns a DialOption which sets the maximum message size the client can receive. Deprecated: use WithDefaultCallOptions(MaxCallRecvMsgSize(s)) instead.
137 func WithMaxMsgSize(s int) DialOption {
138 return WithDefaultCallOptions(MaxCallRecvMsgSize(s))
139 }
140
141 // WithDefaultCallOptions returns a DialOption which sets the default CallOptions for calls over the connection.
142 func WithDefaultCallOptions(cos ...CallOption) DialOption {
143 return func(o *dialOptions) {
144 o.callOptions = append(o.callOptions, cos...)
145 }
146 }
147
148 // WithCodec returns a DialOption which sets a codec for message marshaling and unmarshaling.
149 func WithCodec(c Codec) DialOption {
150 return func(o *dialOptions) {
151 o.codec = c
152 }
153 }
154
155 // WithCompressor returns a DialOption which sets a CompressorGenerator for generating message
156 // compressor.
157 func WithCompressor(cp Compressor) DialOption {
158 return func(o *dialOptions) {
159 o.cp = cp
160 }
161 }
162
163 // WithDecompressor returns a DialOption which sets a DecompressorGenerator for generating
164 // message decompressor.
165 func WithDecompressor(dc Decompressor) DialOption {
166 return func(o *dialOptions) {
167 o.dc = dc
168 }
169 }
170
171 // WithBalancer returns a DialOption which sets a load balancer with the v1 API.
172 // Name resolver will be ignored if this DialOption is specified.
173 // Deprecated: use the new balancer APIs in balancer package instead.
174 func WithBalancer(b Balancer) DialOption {
175 return func(o *dialOptions) {
176 o.balancerBuilder = &balancerWrapperBuilder{
177 b: b,
178 }
179 }
180 }
181
182 // WithBalancerBuilder is for testing only. Users using custom balancers should
183 // register their balancer and use service config to choose the balancer to use.
184 func WithBalancerBuilder(b balancer.Builder) DialOption {
185 // TODO(bar) remove this when switching balancer is done.
186 return func(o *dialOptions) {
187 o.balancerBuilder = b
188 }
189 }
190
191 // WithServiceConfig returns a DialOption which has a channel to read the service configuration.
192 func WithServiceConfig(c <-chan ServiceConfig) DialOption {
193 return func(o *dialOptions) {
194 o.scChan = c
195 }
196 }
197
198 // WithBackoffMaxDelay configures the dialer to use the provided maximum delay
199 // when backing off after failed connection attempts.
200 func WithBackoffMaxDelay(md time.Duration) DialOption {
201 return WithBackoffConfig(BackoffConfig{MaxDelay: md})
202 }
203
204 // WithBackoffConfig configures the dialer to use the provided backoff
205 // parameters after connection failures.
206 //
207 // Use WithBackoffMaxDelay until more parameters on BackoffConfig are opened up
208 // for use.
209 func WithBackoffConfig(b BackoffConfig) DialOption {
210 // Set defaults to ensure that provided BackoffConfig is valid and
211 // unexported fields get default values.
212 setDefaults(&b)
213 return withBackoff(b)
214 }
215
216 // withBackoff sets the backoff strategy used for retries after a
217 // failed connection attempt.
218 //
219 // This can be exported if arbitrary backoff strategies are allowed by gRPC.
220 func withBackoff(bs backoffStrategy) DialOption {
221 return func(o *dialOptions) {
222 o.bs = bs
223 }
224 }
225
226 // WithBlock returns a DialOption which makes caller of Dial blocks until the underlying
227 // connection is up. Without this, Dial returns immediately and connecting the server
228 // happens in background.
229 func WithBlock() DialOption {
230 return func(o *dialOptions) {
231 o.block = true
232 }
233 }
234
235 // WithInsecure returns a DialOption which disables transport security for this ClientConn.
236 // Note that transport security is required unless WithInsecure is set.
237 func WithInsecure() DialOption {
238 return func(o *dialOptions) {
239 o.insecure = true
240 }
241 }
242
243 // WithTransportCredentials returns a DialOption which configures a
244 // connection level security credentials (e.g., TLS/SSL).
245 func WithTransportCredentials(creds credentials.TransportCredentials) DialOption {
246 return func(o *dialOptions) {
247 o.copts.TransportCredentials = creds
248 }
249 }
250
251 // WithPerRPCCredentials returns a DialOption which sets
252 // credentials and places auth state on each outbound RPC.
253 func WithPerRPCCredentials(creds credentials.PerRPCCredentials) DialOption {
254 return func(o *dialOptions) {
255 o.copts.PerRPCCredentials = append(o.copts.PerRPCCredentials, creds)
256 }
257 }
258
259 // WithTimeout returns a DialOption that configures a timeout for dialing a ClientConn
260 // initially. This is valid if and only if WithBlock() is present.
261 // Deprecated: use DialContext and context.WithTimeout instead.
262 func WithTimeout(d time.Duration) DialOption {
263 return func(o *dialOptions) {
264 o.timeout = d
265 }
266 }
267
268 // WithDialer returns a DialOption that specifies a function to use for dialing network addresses.
269 // If FailOnNonTempDialError() is set to true, and an error is returned by f, gRPC checks the error's
270 // Temporary() method to decide if it should try to reconnect to the network address.
271 func WithDialer(f func(string, time.Duration) (net.Conn, error)) DialOption {
272 return func(o *dialOptions) {
273 o.copts.Dialer = func(ctx context.Context, addr string) (net.Conn, error) {
274 if deadline, ok := ctx.Deadline(); ok {
275 return f(addr, deadline.Sub(time.Now()))
276 }
277 return f(addr, 0)
278 }
279 }
280 }
281
282 // WithStatsHandler returns a DialOption that specifies the stats handler
283 // for all the RPCs and underlying network connections in this ClientConn.
284 func WithStatsHandler(h stats.Handler) DialOption {
285 return func(o *dialOptions) {
286 o.copts.StatsHandler = h
287 }
288 }
289
290 // FailOnNonTempDialError returns a DialOption that specifies if gRPC fails on non-temporary dial errors.
291 // If f is true, and dialer returns a non-temporary error, gRPC will fail the connection to the network
292 // address and won't try to reconnect.
293 // The default value of FailOnNonTempDialError is false.
294 // This is an EXPERIMENTAL API.
295 func FailOnNonTempDialError(f bool) DialOption {
296 return func(o *dialOptions) {
297 o.copts.FailOnNonTempDialError = f
298 }
299 }
300
301 // WithUserAgent returns a DialOption that specifies a user agent string for all the RPCs.
302 func WithUserAgent(s string) DialOption {
303 return func(o *dialOptions) {
304 o.copts.UserAgent = s
305 }
306 }
307
308 // WithKeepaliveParams returns a DialOption that specifies keepalive parameters for the client transport.
309 func WithKeepaliveParams(kp keepalive.ClientParameters) DialOption {
310 return func(o *dialOptions) {
311 o.copts.KeepaliveParams = kp
312 }
313 }
314
315 // WithUnaryInterceptor returns a DialOption that specifies the interceptor for unary RPCs.
316 func WithUnaryInterceptor(f UnaryClientInterceptor) DialOption {
317 return func(o *dialOptions) {
318 o.unaryInt = f
319 }
320 }
321
322 // WithStreamInterceptor returns a DialOption that specifies the interceptor for streaming RPCs.
323 func WithStreamInterceptor(f StreamClientInterceptor) DialOption {
324 return func(o *dialOptions) {
325 o.streamInt = f
326 }
327 }
328
329 // WithAuthority returns a DialOption that specifies the value to be used as
330 // the :authority pseudo-header. This value only works with WithInsecure and
331 // has no effect if TransportCredentials are present.
332 func WithAuthority(a string) DialOption {
333 return func(o *dialOptions) {
334 o.copts.Authority = a
335 }
336 }
337
338 // Dial creates a client connection to the given target.
339 func Dial(target string, opts ...DialOption) (*ClientConn, error) {
340 return DialContext(context.Background(), target, opts...)
341 }
342
343 // DialContext creates a client connection to the given target. ctx can be used to
344 // cancel or expire the pending connection. Once this function returns, the
345 // cancellation and expiration of ctx will be noop. Users should call ClientConn.Close
346 // to terminate all the pending operations after this function returns.
347 func DialContext(ctx context.Context, target string, opts ...DialOption) (conn *ClientConn, err error) {
348 cc := &ClientConn{
349 target: target,
350 csMgr: &connectivityStateManager{},
351 conns: make(map[*addrConn]struct{}),
352
353 blockingpicker: newPickerWrapper(),
354 }
355 cc.ctx, cc.cancel = context.WithCancel(context.Background())
356
357 for _, opt := range opts {
358 opt(&cc.dopts)
359 }
360
361 if !cc.dopts.insecure {
362 if cc.dopts.copts.TransportCredentials == nil {
363 return nil, errNoTransportSecurity
364 }
365 } else {
366 if cc.dopts.copts.TransportCredentials != nil {
367 return nil, errCredentialsConflict
368 }
369 for _, cd := range cc.dopts.copts.PerRPCCredentials {
370 if cd.RequireTransportSecurity() {
371 return nil, errTransportCredentialsMissing
372 }
373 }
374 }
375
376 cc.mkp = cc.dopts.copts.KeepaliveParams
377
378 if cc.dopts.copts.Dialer == nil {
379 cc.dopts.copts.Dialer = newProxyDialer(
380 func(ctx context.Context, addr string) (net.Conn, error) {
381 return (&net.Dialer{}).DialContext(ctx, "tcp", addr)
382 },
383 )
384 }
385
386 if cc.dopts.copts.UserAgent != "" {
387 cc.dopts.copts.UserAgent += " " + grpcUA
388 } else {
389 cc.dopts.copts.UserAgent = grpcUA
390 }
391
392 if cc.dopts.timeout > 0 {
393 var cancel context.CancelFunc
394 ctx, cancel = context.WithTimeout(ctx, cc.dopts.timeout)
395 defer cancel()
396 }
397
398 defer func() {
399 select {
400 case <-ctx.Done():
401 conn, err = nil, ctx.Err()
402 default:
403 }
404
405 if err != nil {
406 cc.Close()
407 }
408 }()
409
410 scSet := false
411 if cc.dopts.scChan != nil {
412 // Try to get an initial service config.
413 select {
414 case sc, ok := <-cc.dopts.scChan:
415 if ok {
416 cc.sc = sc
417 scSet = true
418 }
419 default:
420 }
421 }
422 // Set defaults.
423 if cc.dopts.codec == nil {
424 cc.dopts.codec = protoCodec{}
425 }
426 if cc.dopts.bs == nil {
427 cc.dopts.bs = DefaultBackoffConfig
428 }
429 creds := cc.dopts.copts.TransportCredentials
430 if creds != nil && creds.Info().ServerName != "" {
431 cc.authority = creds.Info().ServerName
432 } else if cc.dopts.insecure && cc.dopts.copts.Authority != "" {
433 cc.authority = cc.dopts.copts.Authority
434 } else {
435 cc.authority = target
436 }
437
438 if cc.dopts.balancerBuilder != nil {
439 var credsClone credentials.TransportCredentials
440 if creds != nil {
441 credsClone = creds.Clone()
442 }
443 buildOpts := balancer.BuildOptions{
444 DialCreds: credsClone,
445 Dialer: cc.dopts.copts.Dialer,
446 }
447 // Build should not take long time. So it's ok to not have a goroutine for it.
448 // TODO(bar) init balancer after first resolver result to support service config balancer.
449 cc.balancerWrapper = newCCBalancerWrapper(cc, cc.dopts.balancerBuilder, buildOpts)
450 } else {
451 waitC := make(chan error, 1)
452 go func() {
453 defer close(waitC)
454 // No balancer, or no resolver within the balancer. Connect directly.
455 ac, err := cc.newAddrConn([]resolver.Address{{Addr: target}})
456 if err != nil {
457 waitC <- err
458 return
459 }
460 if err := ac.connect(cc.dopts.block); err != nil {
461 waitC <- err
462 return
463 }
464 }()
465 select {
466 case <-ctx.Done():
467 return nil, ctx.Err()
468 case err := <-waitC:
469 if err != nil {
470 return nil, err
471 }
472 }
473 }
474 if cc.dopts.scChan != nil && !scSet {
475 // Blocking wait for the initial service config.
476 select {
477 case sc, ok := <-cc.dopts.scChan:
478 if ok {
479 cc.sc = sc
480 }
481 case <-ctx.Done():
482 return nil, ctx.Err()
483 }
484 }
485 if cc.dopts.scChan != nil {
486 go cc.scWatcher()
487 }
488
489 // Build the resolver.
490 cc.resolverWrapper, err = newCCResolverWrapper(cc)
491 if err != nil {
492 return nil, fmt.Errorf("failed to build resolver: %v", err)
493 }
494
495 if cc.balancerWrapper != nil && cc.resolverWrapper == nil {
496 // TODO(bar) there should always be a resolver (DNS as the default).
497 // Unblock balancer initialization with a fake resolver update if there's no resolver.
498 // The balancer wrapper will not read the addresses, so an empty list works.
499 // TODO(bar) remove this after the real resolver is started.
500 cc.balancerWrapper.handleResolvedAddrs([]resolver.Address{}, nil)
501 }
502
503 // A blocking dial blocks until the clientConn is ready.
504 if cc.dopts.block {
505 for {
506 s := cc.GetState()
507 if s == connectivity.Ready {
508 break
509 }
510 if !cc.WaitForStateChange(ctx, s) {
511 // ctx got timeout or canceled.
512 return nil, ctx.Err()
513 }
514 }
515 }
516
517 return cc, nil
518 }
519
520 // connectivityStateManager keeps the connectivity.State of ClientConn.
521 // This struct will eventually be exported so the balancers can access it.
522 type connectivityStateManager struct {
523 mu sync.Mutex
524 state connectivity.State
525 notifyChan chan struct{}
526 }
527
528 // updateState updates the connectivity.State of ClientConn.
529 // If there's a change it notifies goroutines waiting on state change to
530 // happen.
531 func (csm *connectivityStateManager) updateState(state connectivity.State) {
532 csm.mu.Lock()
533 defer csm.mu.Unlock()
534 if csm.state == connectivity.Shutdown {
535 return
536 }
537 if csm.state == state {
538 return
539 }
540 csm.state = state
541 if csm.notifyChan != nil {
542 // There are other goroutines waiting on this channel.
543 close(csm.notifyChan)
544 csm.notifyChan = nil
545 }
546 }
547
548 func (csm *connectivityStateManager) getState() connectivity.State {
549 csm.mu.Lock()
550 defer csm.mu.Unlock()
551 return csm.state
552 }
553
554 func (csm *connectivityStateManager) getNotifyChan() <-chan struct{} {
555 csm.mu.Lock()
556 defer csm.mu.Unlock()
557 if csm.notifyChan == nil {
558 csm.notifyChan = make(chan struct{})
559 }
560 return csm.notifyChan
561 }
562
563 // ClientConn represents a client connection to an RPC server.
564 type ClientConn struct {
565 ctx context.Context
566 cancel context.CancelFunc
567
568 target string
569 authority string
570 dopts dialOptions
571 csMgr *connectivityStateManager
572
573 balancerWrapper *ccBalancerWrapper
574 resolverWrapper *ccResolverWrapper
575
576 blockingpicker *pickerWrapper
577
578 mu sync.RWMutex
579 sc ServiceConfig
580 conns map[*addrConn]struct{}
581 // Keepalive parameter can be updated if a GoAway is received.
582 mkp keepalive.ClientParameters
583 }
584
585 // WaitForStateChange waits until the connectivity.State of ClientConn changes from sourceState or
586 // ctx expires. A true value is returned in former case and false in latter.
587 // This is an EXPERIMENTAL API.
588 func (cc *ClientConn) WaitForStateChange(ctx context.Context, sourceState connectivity.State) bool {
589 ch := cc.csMgr.getNotifyChan()
590 if cc.csMgr.getState() != sourceState {
591 return true
592 }
593 select {
594 case <-ctx.Done():
595 return false
596 case <-ch:
597 return true
598 }
599 }
600
601 // GetState returns the connectivity.State of ClientConn.
602 // This is an EXPERIMENTAL API.
603 func (cc *ClientConn) GetState() connectivity.State {
604 return cc.csMgr.getState()
605 }
606
607 func (cc *ClientConn) scWatcher() {
608 for {
609 select {
610 case sc, ok := <-cc.dopts.scChan:
611 if !ok {
612 return
613 }
614 cc.mu.Lock()
615 // TODO: load balance policy runtime change is ignored.
616 // We may revist this decision in the future.
617 cc.sc = sc
618 cc.mu.Unlock()
619 case <-cc.ctx.Done():
620 return
621 }
622 }
623 }
624
625 // newAddrConn creates an addrConn for addrs and adds it to cc.conns.
626 func (cc *ClientConn) newAddrConn(addrs []resolver.Address) (*addrConn, error) {
627 ac := &addrConn{
628 cc: cc,
629 addrs: addrs,
630 dopts: cc.dopts,
631 }
632 ac.ctx, ac.cancel = context.WithCancel(cc.ctx)
633 // Track ac in cc. This needs to be done before any getTransport(...) is called.
634 cc.mu.Lock()
635 if cc.conns == nil {
636 cc.mu.Unlock()
637 return nil, ErrClientConnClosing
638 }
639 cc.conns[ac] = struct{}{}
640 cc.mu.Unlock()
641 return ac, nil
642 }
643
644 // removeAddrConn removes the addrConn in the subConn from clientConn.
645 // It also tears down the ac with the given error.
646 func (cc *ClientConn) removeAddrConn(ac *addrConn, err error) {
647 cc.mu.Lock()
648 if cc.conns == nil {
649 cc.mu.Unlock()
650 return
651 }
652 delete(cc.conns, ac)
653 cc.mu.Unlock()
654 ac.tearDown(err)
655 }
656
657 // connect starts to creating transport and also starts the transport monitor
658 // goroutine for this ac.
659 // It does nothing if the ac is not IDLE.
660 // TODO(bar) Move this to the addrConn section.
661 // This was part of resetAddrConn, keep it here to make the diff look clean.
662 func (ac *addrConn) connect(block bool) error {
663 ac.mu.Lock()
664 if ac.state == connectivity.Shutdown {
665 ac.mu.Unlock()
666 return errConnClosing
667 }
668 if ac.state != connectivity.Idle {
669 ac.mu.Unlock()
670 return nil
671 }
672 ac.state = connectivity.Connecting
673 if ac.cc.balancerWrapper != nil {
674 ac.cc.balancerWrapper.handleSubConnStateChange(ac.acbw, ac.state)
675 } else {
676 ac.cc.csMgr.updateState(ac.state)
677 }
678 ac.mu.Unlock()
679
680 if block {
681 if err := ac.resetTransport(); err != nil {
682 if err != errConnClosing {
683 ac.tearDown(err)
684 }
685 if e, ok := err.(transport.ConnectionError); ok && !e.Temporary() {
686 return e.Origin()
687 }
688 return err
689 }
690 // Start to monitor the error status of transport.
691 go ac.transportMonitor()
692 } else {
693 // Start a goroutine connecting to the server asynchronously.
694 go func() {
695 if err := ac.resetTransport(); err != nil {
696 grpclog.Warningf("Failed to dial %s: %v; please retry.", ac.addrs[0].Addr, err)
697 if err != errConnClosing {
698 // Keep this ac in cc.conns, to get the reason it's torn down.
699 ac.tearDown(err)
700 }
701 return
702 }
703 ac.transportMonitor()
704 }()
705 }
706 return nil
707 }
708
709 // tryUpdateAddrs tries to update ac.addrs with the new addresses list.
710 //
711 // It checks whether current connected address of ac is in the new addrs list.
712 // - If true, it updates ac.addrs and returns true. The ac will keep using
713 // the existing connection.
714 // - If false, it does nothing and returns false.
715 func (ac *addrConn) tryUpdateAddrs(addrs []resolver.Address) bool {
716 ac.mu.Lock()
717 defer ac.mu.Unlock()
718 grpclog.Infof("addrConn: tryUpdateAddrs curAddr: %v, addrs: %v", ac.curAddr, addrs)
719 if ac.state == connectivity.Shutdown {
720 ac.addrs = addrs
721 return true
722 }
723
724 var curAddrFound bool
725 for _, a := range addrs {
726 if reflect.DeepEqual(ac.curAddr, a) {
727 curAddrFound = true
728 break
729 }
730 }
731 grpclog.Infof("addrConn: tryUpdateAddrs curAddrFound: %v", curAddrFound)
732 if curAddrFound {
733 ac.addrs = addrs
734 }
735
736 return curAddrFound
737 }
738
739 // GetMethodConfig gets the method config of the input method.
740 // If there's an exact match for input method (i.e. /service/method), we return
741 // the corresponding MethodConfig.
742 // If there isn't an exact match for the input method, we look for the default config
743 // under the service (i.e /service/). If there is a default MethodConfig for
744 // the serivce, we return it.
745 // Otherwise, we return an empty MethodConfig.
746 func (cc *ClientConn) GetMethodConfig(method string) MethodConfig {
747 // TODO: Avoid the locking here.
748 cc.mu.RLock()
749 defer cc.mu.RUnlock()
750 m, ok := cc.sc.Methods[method]
751 if !ok {
752 i := strings.LastIndex(method, "/")
753 m, _ = cc.sc.Methods[method[:i+1]]
754 }
755 return m
756 }
757
758 func (cc *ClientConn) getTransport(ctx context.Context, failfast bool) (transport.ClientTransport, func(balancer.DoneInfo), error) {
759 if cc.balancerWrapper == nil {
760 // If balancer is nil, there should be only one addrConn available.
761 cc.mu.RLock()
762 if cc.conns == nil {
763 cc.mu.RUnlock()
764 // TODO this function returns toRPCErr and non-toRPCErr. Clean up
765 // the errors in ClientConn.
766 return nil, nil, toRPCErr(ErrClientConnClosing)
767 }
768 var ac *addrConn
769 for ac = range cc.conns {
770 // Break after the first iteration to get the first addrConn.
771 break
772 }
773 cc.mu.RUnlock()
774 if ac == nil {
775 return nil, nil, errConnClosing
776 }
777 t, err := ac.wait(ctx, false /*hasBalancer*/, failfast)
778 if err != nil {
779 return nil, nil, err
780 }
781 return t, nil, nil
782 }
783
784 t, done, err := cc.blockingpicker.pick(ctx, failfast, balancer.PickOptions{})
785 if err != nil {
786 return nil, nil, toRPCErr(err)
787 }
788 return t, done, nil
789 }
790
791 // Close tears down the ClientConn and all underlying connections.
792 func (cc *ClientConn) Close() error {
793 cc.cancel()
794
795 cc.mu.Lock()
796 if cc.conns == nil {
797 cc.mu.Unlock()
798 return ErrClientConnClosing
799 }
800 conns := cc.conns
801 cc.conns = nil
802 cc.csMgr.updateState(connectivity.Shutdown)
803 cc.mu.Unlock()
804 cc.blockingpicker.close()
805 if cc.resolverWrapper != nil {
806 cc.resolverWrapper.close()
807 }
808 if cc.balancerWrapper != nil {
809 cc.balancerWrapper.close()
810 }
811 for ac := range conns {
812 ac.tearDown(ErrClientConnClosing)
813 }
814 return nil
815 }
816
817 // addrConn is a network connection to a given address.
818 type addrConn struct {
819 ctx context.Context
820 cancel context.CancelFunc
821
822 cc *ClientConn
823 curAddr resolver.Address
824 addrs []resolver.Address
825 dopts dialOptions
826 events trace.EventLog
827 acbw balancer.SubConn
828
829 mu sync.Mutex
830 state connectivity.State
831 // ready is closed and becomes nil when a new transport is up or failed
832 // due to timeout.
833 ready chan struct{}
834 transport transport.ClientTransport
835
836 // The reason this addrConn is torn down.
837 tearDownErr error
838 }
839
840 // adjustParams updates parameters used to create transports upon
841 // receiving a GoAway.
842 func (ac *addrConn) adjustParams(r transport.GoAwayReason) {
843 switch r {
844 case transport.TooManyPings:
845 v := 2 * ac.dopts.copts.KeepaliveParams.Time
846 ac.cc.mu.Lock()
847 if v > ac.cc.mkp.Time {
848 ac.cc.mkp.Time = v
849 }
850 ac.cc.mu.Unlock()
851 }
852 }
853
854 // printf records an event in ac's event log, unless ac has been closed.
855 // REQUIRES ac.mu is held.
856 func (ac *addrConn) printf(format string, a ...interface{}) {
857 if ac.events != nil {
858 ac.events.Printf(format, a...)
859 }
860 }
861
862 // errorf records an error in ac's event log, unless ac has been closed.
863 // REQUIRES ac.mu is held.
864 func (ac *addrConn) errorf(format string, a ...interface{}) {
865 if ac.events != nil {
866 ac.events.Errorf(format, a...)
867 }
868 }
869
870 // resetTransport recreates a transport to the address for ac. The old
871 // transport will close itself on error or when the clientconn is closed.
872 //
873 // TODO(bar) make sure all state transitions are valid.
874 func (ac *addrConn) resetTransport() error {
875 ac.mu.Lock()
876 if ac.state == connectivity.Shutdown {
877 ac.mu.Unlock()
878 return errConnClosing
879 }
880 if ac.ready != nil {
881 close(ac.ready)
882 ac.ready = nil
883 }
884 ac.transport = nil
885 ac.curAddr = resolver.Address{}
886 ac.mu.Unlock()
887 ac.cc.mu.RLock()
888 ac.dopts.copts.KeepaliveParams = ac.cc.mkp
889 ac.cc.mu.RUnlock()
890 for retries := 0; ; retries++ {
891 sleepTime := ac.dopts.bs.backoff(retries)
892 timeout := minConnectTimeout
893 ac.mu.Lock()
894 if timeout < time.Duration(int(sleepTime)/len(ac.addrs)) {
895 timeout = time.Duration(int(sleepTime) / len(ac.addrs))
896 }
897 connectTime := time.Now()
898 if ac.state == connectivity.Shutdown {
899 ac.mu.Unlock()
900 return errConnClosing
901 }
902 ac.printf("connecting")
903 if ac.state != connectivity.Connecting {
904 ac.state = connectivity.Connecting
905 // TODO(bar) remove condition once we always have a balancer.
906 if ac.cc.balancerWrapper != nil {
907 ac.cc.balancerWrapper.handleSubConnStateChange(ac.acbw, ac.state)
908 } else {
909 ac.cc.csMgr.updateState(ac.state)
910 }
911 }
912 // copy ac.addrs in case of race
913 addrsIter := make([]resolver.Address, len(ac.addrs))
914 copy(addrsIter, ac.addrs)
915 copts := ac.dopts.copts
916 ac.mu.Unlock()
917 for _, addr := range addrsIter {
918 ac.mu.Lock()
919 if ac.state == connectivity.Shutdown {
920 // ac.tearDown(...) has been invoked.
921 ac.mu.Unlock()
922 return errConnClosing
923 }
924 ac.mu.Unlock()
925 sinfo := transport.TargetInfo{
926 Addr: addr.Addr,
927 Metadata: addr.Metadata,
928 }
929 newTransport, err := transport.NewClientTransport(ac.cc.ctx, sinfo, copts, timeout)
930 if err != nil {
931 if e, ok := err.(transport.ConnectionError); ok && !e.Temporary() {
932 ac.mu.Lock()
933 if ac.state != connectivity.Shutdown {
934 ac.state = connectivity.TransientFailure
935 if ac.cc.balancerWrapper != nil {
936 ac.cc.balancerWrapper.handleSubConnStateChange(ac.acbw, ac.state)
937 } else {
938 ac.cc.csMgr.updateState(ac.state)
939 }
940 }
941 ac.mu.Unlock()
942 return err
943 }
944 grpclog.Warningf("grpc: addrConn.resetTransport failed to create client transport: %v; Reconnecting to %v", err, addr)
945 ac.mu.Lock()
946 if ac.state == connectivity.Shutdown {
947 // ac.tearDown(...) has been invoked.
948 ac.mu.Unlock()
949 return errConnClosing
950 }
951 ac.mu.Unlock()
952 continue
953 }
954 ac.mu.Lock()
955 ac.printf("ready")
956 if ac.state == connectivity.Shutdown {
957 // ac.tearDown(...) has been invoked.
958 ac.mu.Unlock()
959 newTransport.Close()
960 return errConnClosing
961 }
962 ac.state = connectivity.Ready
963 if ac.cc.balancerWrapper != nil {
964 ac.cc.balancerWrapper.handleSubConnStateChange(ac.acbw, ac.state)
965 } else {
966 ac.cc.csMgr.updateState(ac.state)
967 }
968 t := ac.transport
969 ac.transport = newTransport
970 if t != nil {
971 t.Close()
972 }
973 ac.curAddr = addr
974 if ac.ready != nil {
975 close(ac.ready)
976 ac.ready = nil
977 }
978 ac.mu.Unlock()
979 return nil
980 }
981 ac.mu.Lock()
982 ac.state = connectivity.TransientFailure
983 if ac.cc.balancerWrapper != nil {
984 ac.cc.balancerWrapper.handleSubConnStateChange(ac.acbw, ac.state)
985 } else {
986 ac.cc.csMgr.updateState(ac.state)
987 }
988 if ac.ready != nil {
989 close(ac.ready)
990 ac.ready = nil
991 }
992 ac.mu.Unlock()
993 timer := time.NewTimer(sleepTime - time.Since(connectTime))
994 select {
995 case <-timer.C:
996 case <-ac.ctx.Done():
997 timer.Stop()
998 return ac.ctx.Err()
999 }
1000 timer.Stop()
1001 }
1002 }
1003
1004 // Run in a goroutine to track the error in transport and create the
1005 // new transport if an error happens. It returns when the channel is closing.
1006 func (ac *addrConn) transportMonitor() {
1007 for {
1008 ac.mu.Lock()
1009 t := ac.transport
1010 ac.mu.Unlock()
1011 // Block until we receive a goaway or an error occurs.
1012 select {
1013 case <-t.GoAway():
1014 case <-t.Error():
1015 }
1016 // If a GoAway happened, regardless of error, adjust our keepalive
1017 // parameters as appropriate.
1018 select {
1019 case <-t.GoAway():
1020 ac.adjustParams(t.GetGoAwayReason())
1021 default:
1022 }
1023 ac.mu.Lock()
1024 if ac.state == connectivity.Shutdown {
1025 ac.mu.Unlock()
1026 return
1027 }
1028 // Set connectivity state to TransientFailure before calling
1029 // resetTransport. Transition READY->CONNECTING is not valid.
1030 ac.state = connectivity.TransientFailure
1031 if ac.cc.balancerWrapper != nil {
1032 ac.cc.balancerWrapper.handleSubConnStateChange(ac.acbw, ac.state)
1033 } else {
1034 ac.cc.csMgr.updateState(ac.state)
1035 }
1036 ac.curAddr = resolver.Address{}
1037 ac.mu.Unlock()
1038 if err := ac.resetTransport(); err != nil {
1039 ac.mu.Lock()
1040 ac.printf("transport exiting: %v", err)
1041 ac.mu.Unlock()
1042 grpclog.Warningf("grpc: addrConn.transportMonitor exits due to: %v", err)
1043 if err != errConnClosing {
1044 // Keep this ac in cc.conns, to get the reason it's torn down.
1045 ac.tearDown(err)
1046 }
1047 return
1048 }
1049 }
1050 }
1051
1052 // wait blocks until i) the new transport is up or ii) ctx is done or iii) ac is closed or
1053 // iv) transport is in connectivity.TransientFailure and there is a balancer/failfast is true.
1054 func (ac *addrConn) wait(ctx context.Context, hasBalancer, failfast bool) (transport.ClientTransport, error) {
1055 for {
1056 ac.mu.Lock()
1057 switch {
1058 case ac.state == connectivity.Shutdown:
1059 if failfast || !hasBalancer {
1060 // RPC is failfast or balancer is nil. This RPC should fail with ac.tearDownErr.
1061 err := ac.tearDownErr
1062 ac.mu.Unlock()
1063 return nil, err
1064 }
1065 ac.mu.Unlock()
1066 return nil, errConnClosing
1067 case ac.state == connectivity.Ready:
1068 ct := ac.transport
1069 ac.mu.Unlock()
1070 return ct, nil
1071 case ac.state == connectivity.TransientFailure:
1072 if failfast || hasBalancer {
1073 ac.mu.Unlock()
1074 return nil, errConnUnavailable
1075 }
1076 }
1077 ready := ac.ready
1078 if ready == nil {
1079 ready = make(chan struct{})
1080 ac.ready = ready
1081 }
1082 ac.mu.Unlock()
1083 select {
1084 case <-ctx.Done():
1085 return nil, toRPCErr(ctx.Err())
1086 // Wait until the new transport is ready or failed.
1087 case <-ready:
1088 }
1089 }
1090 }
1091
1092 // getReadyTransport returns the transport if ac's state is READY.
1093 // Otherwise it returns nil, false.
1094 // If ac's state is IDLE, it will trigger ac to connect.
1095 func (ac *addrConn) getReadyTransport() (transport.ClientTransport, bool) {
1096 ac.mu.Lock()
1097 if ac.state == connectivity.Ready {
1098 t := ac.transport
1099 ac.mu.Unlock()
1100 return t, true
1101 }
1102 var idle bool
1103 if ac.state == connectivity.Idle {
1104 idle = true
1105 }
1106 ac.mu.Unlock()
1107 // Trigger idle ac to connect.
1108 if idle {
1109 ac.connect(false)
1110 }
1111 return nil, false
1112 }
1113
1114 // tearDown starts to tear down the addrConn.
1115 // TODO(zhaoq): Make this synchronous to avoid unbounded memory consumption in
1116 // some edge cases (e.g., the caller opens and closes many addrConn's in a
1117 // tight loop.
1118 // tearDown doesn't remove ac from ac.cc.conns.
1119 func (ac *addrConn) tearDown(err error) {
1120 ac.cancel()
1121 ac.mu.Lock()
1122 ac.curAddr = resolver.Address{}
1123 defer ac.mu.Unlock()
1124 if err == errConnDrain && ac.transport != nil {
1125 // GracefulClose(...) may be executed multiple times when
1126 // i) receiving multiple GoAway frames from the server; or
1127 // ii) there are concurrent name resolver/Balancer triggered
1128 // address removal and GoAway.
1129 ac.transport.GracefulClose()
1130 }
1131 if ac.state == connectivity.Shutdown {
1132 return
1133 }
1134 ac.state = connectivity.Shutdown
1135 ac.tearDownErr = err
1136 if ac.cc.balancerWrapper != nil {
1137 ac.cc.balancerWrapper.handleSubConnStateChange(ac.acbw, ac.state)
1138 } else {
1139 ac.cc.csMgr.updateState(ac.state)
1140 }
1141 if ac.events != nil {
1142 ac.events.Finish()
1143 ac.events = nil
1144 }
1145 if ac.ready != nil {
1146 close(ac.ready)
1147 ac.ready = nil
1148 }
1149 return
1150 }
1151
1152 func (ac *addrConn) getState() connectivity.State {
1153 ac.mu.Lock()
1154 defer ac.mu.Unlock()
1155 return ac.state
1156 }