clientconn.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. /*
  2. *
  3. * Copyright 2014, Google Inc.
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are
  8. * met:
  9. *
  10. * * Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * * Redistributions in binary form must reproduce the above
  13. * copyright notice, this list of conditions and the following disclaimer
  14. * in the documentation and/or other materials provided with the
  15. * distribution.
  16. * * Neither the name of Google Inc. nor the names of its
  17. * contributors may be used to endorse or promote products derived from
  18. * this software without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. *
  32. */
  33. package grpc
  34. import (
  35. "errors"
  36. "fmt"
  37. "net"
  38. "strings"
  39. "sync"
  40. "time"
  41. "golang.org/x/net/context"
  42. "golang.org/x/net/trace"
  43. "google.golang.org/grpc/codes"
  44. "google.golang.org/grpc/credentials"
  45. "google.golang.org/grpc/grpclog"
  46. "google.golang.org/grpc/transport"
  47. )
  48. var (
  49. // ErrClientConnClosing indicates that the operation is illegal because
  50. // the ClientConn is closing.
  51. ErrClientConnClosing = errors.New("grpc: the client connection is closing")
  52. // ErrClientConnTimeout indicates that the ClientConn cannot establish the
  53. // underlying connections within the specified timeout.
  54. ErrClientConnTimeout = errors.New("grpc: timed out when dialing")
  55. // errNoTransportSecurity indicates that there is no transport security
  56. // being set for ClientConn. Users should either set one or explicitly
  57. // call WithInsecure DialOption to disable security.
  58. errNoTransportSecurity = errors.New("grpc: no transport security set (use grpc.WithInsecure() explicitly or set credentials)")
  59. // errCredentialsMisuse indicates that users want to transmit security information
  60. // (e.g., oauth2 token) which requires secure connection on an insecure
  61. // connection.
  62. errCredentialsMisuse = errors.New("grpc: the credentials require transport level security (use grpc.WithTransportAuthenticator() to set)")
  63. // errNetworkIP 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. errNoAddr = errors.New("grpc: there is no address available to dial")
  70. // minimum time to give a connection to complete
  71. minConnectTimeout = 20 * time.Second
  72. )
  73. // dialOptions configure a Dial call. dialOptions are set by the DialOption
  74. // values passed to Dial.
  75. type dialOptions struct {
  76. codec Codec
  77. cp Compressor
  78. dc Decompressor
  79. bs backoffStrategy
  80. balancer Balancer
  81. block bool
  82. insecure bool
  83. timeout time.Duration
  84. copts transport.ConnectOptions
  85. }
  86. // DialOption configures how we set up the connection.
  87. type DialOption func(*dialOptions)
  88. // WithCodec returns a DialOption which sets a codec for message marshaling and unmarshaling.
  89. func WithCodec(c Codec) DialOption {
  90. return func(o *dialOptions) {
  91. o.codec = c
  92. }
  93. }
  94. // WithCompressor returns a DialOption which sets a CompressorGenerator for generating message
  95. // compressor.
  96. func WithCompressor(cp Compressor) DialOption {
  97. return func(o *dialOptions) {
  98. o.cp = cp
  99. }
  100. }
  101. // WithDecompressor returns a DialOption which sets a DecompressorGenerator for generating
  102. // message decompressor.
  103. func WithDecompressor(dc Decompressor) DialOption {
  104. return func(o *dialOptions) {
  105. o.dc = dc
  106. }
  107. }
  108. // WithBalancer returns a DialOption which sets a load balancer.
  109. func WithBalancer(b Balancer) DialOption {
  110. return func(o *dialOptions) {
  111. o.balancer = b
  112. }
  113. }
  114. // WithBackoffMaxDelay configures the dialer to use the provided maximum delay
  115. // when backing off after failed connection attempts.
  116. func WithBackoffMaxDelay(md time.Duration) DialOption {
  117. return WithBackoffConfig(BackoffConfig{MaxDelay: md})
  118. }
  119. // WithBackoffConfig configures the dialer to use the provided backoff
  120. // parameters after connection failures.
  121. //
  122. // Use WithBackoffMaxDelay until more parameters on BackoffConfig are opened up
  123. // for use.
  124. func WithBackoffConfig(b BackoffConfig) DialOption {
  125. // Set defaults to ensure that provided BackoffConfig is valid and
  126. // unexported fields get default values.
  127. setDefaults(&b)
  128. return withBackoff(b)
  129. }
  130. // withBackoff sets the backoff strategy used for retries after a
  131. // failed connection attempt.
  132. //
  133. // This can be exported if arbitrary backoff strategies are allowed by gRPC.
  134. func withBackoff(bs backoffStrategy) DialOption {
  135. return func(o *dialOptions) {
  136. o.bs = bs
  137. }
  138. }
  139. // WithBlock returns a DialOption which makes caller of Dial blocks until the underlying
  140. // connection is up. Without this, Dial returns immediately and connecting the server
  141. // happens in background.
  142. func WithBlock() DialOption {
  143. return func(o *dialOptions) {
  144. o.block = true
  145. }
  146. }
  147. // WithInsecure returns a DialOption which disables transport security for this ClientConn.
  148. // Note that transport security is required unless WithInsecure is set.
  149. func WithInsecure() DialOption {
  150. return func(o *dialOptions) {
  151. o.insecure = true
  152. }
  153. }
  154. // WithTransportCredentials returns a DialOption which configures a
  155. // connection level security credentials (e.g., TLS/SSL).
  156. func WithTransportCredentials(creds credentials.TransportAuthenticator) DialOption {
  157. return func(o *dialOptions) {
  158. o.copts.AuthOptions = append(o.copts.AuthOptions, creds)
  159. }
  160. }
  161. // WithPerRPCCredentials returns a DialOption which sets
  162. // credentials which will place auth state on each outbound RPC.
  163. func WithPerRPCCredentials(creds credentials.Credentials) DialOption {
  164. return func(o *dialOptions) {
  165. o.copts.AuthOptions = append(o.copts.AuthOptions, creds)
  166. }
  167. }
  168. // WithTimeout returns a DialOption that configures a timeout for dialing a ClientConn
  169. // initially. This is valid if and only if WithBlock() is present.
  170. func WithTimeout(d time.Duration) DialOption {
  171. return func(o *dialOptions) {
  172. o.timeout = d
  173. }
  174. }
  175. // WithDialer returns a DialOption that specifies a function to use for dialing network addresses.
  176. func WithDialer(f func(addr string, timeout time.Duration) (net.Conn, error)) DialOption {
  177. return func(o *dialOptions) {
  178. o.copts.Dialer = f
  179. }
  180. }
  181. // WithUserAgent returns a DialOption that specifies a user agent string for all the RPCs.
  182. func WithUserAgent(s string) DialOption {
  183. return func(o *dialOptions) {
  184. o.copts.UserAgent = s
  185. }
  186. }
  187. // Dial creates a client connection the given target.
  188. func Dial(target string, opts ...DialOption) (*ClientConn, error) {
  189. cc := &ClientConn{
  190. target: target,
  191. conns: make(map[Address]*addrConn),
  192. }
  193. for _, opt := range opts {
  194. opt(&cc.dopts)
  195. }
  196. if cc.dopts.codec == nil {
  197. // Set the default codec.
  198. cc.dopts.codec = protoCodec{}
  199. }
  200. if cc.dopts.bs == nil {
  201. cc.dopts.bs = DefaultBackoffConfig
  202. }
  203. cc.balancer = cc.dopts.balancer
  204. if cc.balancer == nil {
  205. cc.balancer = RoundRobin(nil)
  206. }
  207. if err := cc.balancer.Start(target); err != nil {
  208. return nil, err
  209. }
  210. var (
  211. ok bool
  212. addrs []Address
  213. )
  214. ch := cc.balancer.Notify()
  215. if ch == nil {
  216. // There is no name resolver installed.
  217. addrs = append(addrs, Address{Addr: target})
  218. } else {
  219. addrs, ok = <-ch
  220. if !ok || len(addrs) == 0 {
  221. return nil, errNoAddr
  222. }
  223. }
  224. waitC := make(chan error, 1)
  225. go func() {
  226. for _, a := range addrs {
  227. if err := cc.newAddrConn(a, false); err != nil {
  228. waitC <- err
  229. return
  230. }
  231. }
  232. close(waitC)
  233. }()
  234. var timeoutCh <-chan time.Time
  235. if cc.dopts.timeout > 0 {
  236. timeoutCh = time.After(cc.dopts.timeout)
  237. }
  238. select {
  239. case err := <-waitC:
  240. if err != nil {
  241. cc.Close()
  242. return nil, err
  243. }
  244. case <-timeoutCh:
  245. cc.Close()
  246. return nil, ErrClientConnTimeout
  247. }
  248. if ok {
  249. go cc.lbWatcher()
  250. }
  251. colonPos := strings.LastIndex(target, ":")
  252. if colonPos == -1 {
  253. colonPos = len(target)
  254. }
  255. cc.authority = target[:colonPos]
  256. return cc, nil
  257. }
  258. // ConnectivityState indicates the state of a client connection.
  259. type ConnectivityState int
  260. const (
  261. // Idle indicates the ClientConn is idle.
  262. Idle ConnectivityState = iota
  263. // Connecting indicates the ClienConn is connecting.
  264. Connecting
  265. // Ready indicates the ClientConn is ready for work.
  266. Ready
  267. // TransientFailure indicates the ClientConn has seen a failure but expects to recover.
  268. TransientFailure
  269. // Shutdown indicates the ClientConn has started shutting down.
  270. Shutdown
  271. )
  272. func (s ConnectivityState) String() string {
  273. switch s {
  274. case Idle:
  275. return "IDLE"
  276. case Connecting:
  277. return "CONNECTING"
  278. case Ready:
  279. return "READY"
  280. case TransientFailure:
  281. return "TRANSIENT_FAILURE"
  282. case Shutdown:
  283. return "SHUTDOWN"
  284. default:
  285. panic(fmt.Sprintf("unknown connectivity state: %d", s))
  286. }
  287. }
  288. // ClientConn represents a client connection to an RPC server.
  289. type ClientConn struct {
  290. target string
  291. balancer Balancer
  292. authority string
  293. dopts dialOptions
  294. mu sync.RWMutex
  295. conns map[Address]*addrConn
  296. }
  297. func (cc *ClientConn) lbWatcher() {
  298. for addrs := range cc.balancer.Notify() {
  299. var (
  300. add []Address // Addresses need to setup connections.
  301. del []*addrConn // Connections need to tear down.
  302. )
  303. cc.mu.Lock()
  304. for _, a := range addrs {
  305. if _, ok := cc.conns[a]; !ok {
  306. add = append(add, a)
  307. }
  308. }
  309. for k, c := range cc.conns {
  310. var keep bool
  311. for _, a := range addrs {
  312. if k == a {
  313. keep = true
  314. break
  315. }
  316. }
  317. if !keep {
  318. del = append(del, c)
  319. }
  320. }
  321. cc.mu.Unlock()
  322. for _, a := range add {
  323. cc.newAddrConn(a, true)
  324. }
  325. for _, c := range del {
  326. c.tearDown(errConnDrain)
  327. }
  328. }
  329. }
  330. func (cc *ClientConn) newAddrConn(addr Address, skipWait bool) error {
  331. ac := &addrConn{
  332. cc: cc,
  333. addr: addr,
  334. dopts: cc.dopts,
  335. shutdownChan: make(chan struct{}),
  336. }
  337. if EnableTracing {
  338. ac.events = trace.NewEventLog("grpc.ClientConn", ac.addr.Addr)
  339. }
  340. if !ac.dopts.insecure {
  341. var ok bool
  342. for _, cd := range ac.dopts.copts.AuthOptions {
  343. if _, ok = cd.(credentials.TransportAuthenticator); ok {
  344. break
  345. }
  346. }
  347. if !ok {
  348. return errNoTransportSecurity
  349. }
  350. } else {
  351. for _, cd := range ac.dopts.copts.AuthOptions {
  352. if cd.RequireTransportSecurity() {
  353. return errCredentialsMisuse
  354. }
  355. }
  356. }
  357. // Insert ac into ac.cc.conns. This needs to be done before any getTransport(...) is called.
  358. ac.cc.mu.Lock()
  359. if ac.cc.conns == nil {
  360. ac.cc.mu.Unlock()
  361. return ErrClientConnClosing
  362. }
  363. stale := ac.cc.conns[ac.addr]
  364. ac.cc.conns[ac.addr] = ac
  365. ac.cc.mu.Unlock()
  366. if stale != nil {
  367. // There is an addrConn alive on ac.addr already. This could be due to
  368. // i) stale's Close is undergoing;
  369. // ii) a buggy Balancer notifies duplicated Addresses.
  370. stale.tearDown(errConnDrain)
  371. }
  372. ac.stateCV = sync.NewCond(&ac.mu)
  373. // skipWait may overwrite the decision in ac.dopts.block.
  374. if ac.dopts.block && !skipWait {
  375. if err := ac.resetTransport(false); err != nil {
  376. ac.tearDown(err)
  377. return err
  378. }
  379. // Start to monitor the error status of transport.
  380. go ac.transportMonitor()
  381. } else {
  382. // Start a goroutine connecting to the server asynchronously.
  383. go func() {
  384. if err := ac.resetTransport(false); err != nil {
  385. grpclog.Printf("Failed to dial %s: %v; please retry.", ac.addr.Addr, err)
  386. ac.tearDown(err)
  387. return
  388. }
  389. ac.transportMonitor()
  390. }()
  391. }
  392. return nil
  393. }
  394. func (cc *ClientConn) getTransport(ctx context.Context, opts BalancerGetOptions) (transport.ClientTransport, func(), error) {
  395. // TODO(zhaoq): Implement fail-fast logic.
  396. addr, put, err := cc.balancer.Get(ctx, opts)
  397. if err != nil {
  398. return nil, nil, err
  399. }
  400. cc.mu.RLock()
  401. if cc.conns == nil {
  402. cc.mu.RUnlock()
  403. return nil, nil, ErrClientConnClosing
  404. }
  405. ac, ok := cc.conns[addr]
  406. cc.mu.RUnlock()
  407. if !ok {
  408. if put != nil {
  409. put()
  410. }
  411. return nil, nil, transport.StreamErrorf(codes.Internal, "grpc: failed to find the transport to send the rpc")
  412. }
  413. t, err := ac.wait(ctx)
  414. if err != nil {
  415. if put != nil {
  416. put()
  417. }
  418. return nil, nil, err
  419. }
  420. return t, put, nil
  421. }
  422. // Close tears down the ClientConn and all underlying connections.
  423. func (cc *ClientConn) Close() error {
  424. cc.mu.Lock()
  425. if cc.conns == nil {
  426. cc.mu.Unlock()
  427. return ErrClientConnClosing
  428. }
  429. conns := cc.conns
  430. cc.conns = nil
  431. cc.mu.Unlock()
  432. cc.balancer.Close()
  433. for _, ac := range conns {
  434. ac.tearDown(ErrClientConnClosing)
  435. }
  436. return nil
  437. }
  438. // addrConn is a network connection to a given address.
  439. type addrConn struct {
  440. cc *ClientConn
  441. addr Address
  442. dopts dialOptions
  443. shutdownChan chan struct{}
  444. events trace.EventLog
  445. mu sync.Mutex
  446. state ConnectivityState
  447. stateCV *sync.Cond
  448. down func(error) // the handler called when a connection is down.
  449. // ready is closed and becomes nil when a new transport is up or failed
  450. // due to timeout.
  451. ready chan struct{}
  452. transport transport.ClientTransport
  453. }
  454. // printf records an event in ac's event log, unless ac has been closed.
  455. // REQUIRES ac.mu is held.
  456. func (ac *addrConn) printf(format string, a ...interface{}) {
  457. if ac.events != nil {
  458. ac.events.Printf(format, a...)
  459. }
  460. }
  461. // errorf records an error in ac's event log, unless ac has been closed.
  462. // REQUIRES ac.mu is held.
  463. func (ac *addrConn) errorf(format string, a ...interface{}) {
  464. if ac.events != nil {
  465. ac.events.Errorf(format, a...)
  466. }
  467. }
  468. // getState returns the connectivity state of the Conn
  469. func (ac *addrConn) getState() ConnectivityState {
  470. ac.mu.Lock()
  471. defer ac.mu.Unlock()
  472. return ac.state
  473. }
  474. // waitForStateChange blocks until the state changes to something other than the sourceState.
  475. func (ac *addrConn) waitForStateChange(ctx context.Context, sourceState ConnectivityState) (ConnectivityState, error) {
  476. ac.mu.Lock()
  477. defer ac.mu.Unlock()
  478. if sourceState != ac.state {
  479. return ac.state, nil
  480. }
  481. done := make(chan struct{})
  482. var err error
  483. go func() {
  484. select {
  485. case <-ctx.Done():
  486. ac.mu.Lock()
  487. err = ctx.Err()
  488. ac.stateCV.Broadcast()
  489. ac.mu.Unlock()
  490. case <-done:
  491. }
  492. }()
  493. defer close(done)
  494. for sourceState == ac.state {
  495. ac.stateCV.Wait()
  496. if err != nil {
  497. return ac.state, err
  498. }
  499. }
  500. return ac.state, nil
  501. }
  502. func (ac *addrConn) resetTransport(closeTransport bool) error {
  503. var retries int
  504. for {
  505. ac.mu.Lock()
  506. ac.printf("connecting")
  507. if ac.state == Shutdown {
  508. // ac.tearDown(...) has been invoked.
  509. ac.mu.Unlock()
  510. return errConnClosing
  511. }
  512. if ac.down != nil {
  513. ac.down(downErrorf(false, true, "%v", errNetworkIO))
  514. ac.down = nil
  515. }
  516. ac.state = Connecting
  517. ac.stateCV.Broadcast()
  518. t := ac.transport
  519. ac.mu.Unlock()
  520. if closeTransport && t != nil {
  521. t.Close()
  522. }
  523. sleepTime := ac.dopts.bs.backoff(retries)
  524. ac.dopts.copts.Timeout = sleepTime
  525. if sleepTime < minConnectTimeout {
  526. ac.dopts.copts.Timeout = minConnectTimeout
  527. }
  528. connectTime := time.Now()
  529. newTransport, err := transport.NewClientTransport(ac.addr.Addr, &ac.dopts.copts)
  530. if err != nil {
  531. ac.mu.Lock()
  532. if ac.state == Shutdown {
  533. // ac.tearDown(...) has been invoked.
  534. ac.mu.Unlock()
  535. return errConnClosing
  536. }
  537. ac.errorf("transient failure: %v", err)
  538. ac.state = TransientFailure
  539. ac.stateCV.Broadcast()
  540. if ac.ready != nil {
  541. close(ac.ready)
  542. ac.ready = nil
  543. }
  544. ac.mu.Unlock()
  545. sleepTime -= time.Since(connectTime)
  546. if sleepTime < 0 {
  547. sleepTime = 0
  548. }
  549. closeTransport = false
  550. select {
  551. case <-time.After(sleepTime):
  552. case <-ac.shutdownChan:
  553. }
  554. retries++
  555. grpclog.Printf("grpc: addrConn.resetTransport failed to create client transport: %v; Reconnecting to %q", err, ac.addr)
  556. continue
  557. }
  558. ac.mu.Lock()
  559. ac.printf("ready")
  560. if ac.state == Shutdown {
  561. // ac.tearDown(...) has been invoked.
  562. ac.mu.Unlock()
  563. newTransport.Close()
  564. return errConnClosing
  565. }
  566. ac.state = Ready
  567. ac.stateCV.Broadcast()
  568. ac.transport = newTransport
  569. if ac.ready != nil {
  570. close(ac.ready)
  571. ac.ready = nil
  572. }
  573. ac.down = ac.cc.balancer.Up(ac.addr)
  574. ac.mu.Unlock()
  575. return nil
  576. }
  577. }
  578. // Run in a goroutine to track the error in transport and create the
  579. // new transport if an error happens. It returns when the channel is closing.
  580. func (ac *addrConn) transportMonitor() {
  581. for {
  582. ac.mu.Lock()
  583. t := ac.transport
  584. ac.mu.Unlock()
  585. select {
  586. // shutdownChan is needed to detect the teardown when
  587. // the addrConn is idle (i.e., no RPC in flight).
  588. case <-ac.shutdownChan:
  589. return
  590. case <-t.Error():
  591. ac.mu.Lock()
  592. if ac.state == Shutdown {
  593. // ac.tearDown(...) has been invoked.
  594. ac.mu.Unlock()
  595. return
  596. }
  597. ac.state = TransientFailure
  598. ac.stateCV.Broadcast()
  599. ac.mu.Unlock()
  600. if err := ac.resetTransport(true); err != nil {
  601. ac.mu.Lock()
  602. ac.printf("transport exiting: %v", err)
  603. ac.mu.Unlock()
  604. grpclog.Printf("grpc: addrConn.transportMonitor exits due to: %v", err)
  605. return
  606. }
  607. }
  608. }
  609. }
  610. // wait blocks until i) the new transport is up or ii) ctx is done or iii) ac is closed.
  611. func (ac *addrConn) wait(ctx context.Context) (transport.ClientTransport, error) {
  612. for {
  613. ac.mu.Lock()
  614. switch {
  615. case ac.state == Shutdown:
  616. ac.mu.Unlock()
  617. return nil, errConnClosing
  618. case ac.state == Ready:
  619. ct := ac.transport
  620. ac.mu.Unlock()
  621. return ct, nil
  622. default:
  623. ready := ac.ready
  624. if ready == nil {
  625. ready = make(chan struct{})
  626. ac.ready = ready
  627. }
  628. ac.mu.Unlock()
  629. select {
  630. case <-ctx.Done():
  631. return nil, transport.ContextErr(ctx.Err())
  632. // Wait until the new transport is ready or failed.
  633. case <-ready:
  634. }
  635. }
  636. }
  637. }
  638. // tearDown starts to tear down the addrConn.
  639. // TODO(zhaoq): Make this synchronous to avoid unbounded memory consumption in
  640. // some edge cases (e.g., the caller opens and closes many addrConn's in a
  641. // tight loop.
  642. func (ac *addrConn) tearDown(err error) {
  643. ac.mu.Lock()
  644. defer func() {
  645. ac.mu.Unlock()
  646. ac.cc.mu.Lock()
  647. if ac.cc.conns != nil {
  648. delete(ac.cc.conns, ac.addr)
  649. }
  650. ac.cc.mu.Unlock()
  651. }()
  652. if ac.state == Shutdown {
  653. return
  654. }
  655. ac.state = Shutdown
  656. if ac.down != nil {
  657. ac.down(downErrorf(false, false, "%v", err))
  658. ac.down = nil
  659. }
  660. ac.stateCV.Broadcast()
  661. if ac.events != nil {
  662. ac.events.Finish()
  663. ac.events = nil
  664. }
  665. if ac.ready != nil {
  666. close(ac.ready)
  667. ac.ready = nil
  668. }
  669. if ac.transport != nil {
  670. if err == errConnDrain {
  671. ac.transport.GracefulClose()
  672. } else {
  673. ac.transport.Close()
  674. }
  675. }
  676. if ac.shutdownChan != nil {
  677. close(ac.shutdownChan)
  678. }
  679. return
  680. }