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. // errTransportCredentialsMissing indicates that users want to transmit security
  60. // information (e.g., oauth2 token) which requires secure connection on an insecure
  61. // connection.
  62. errTransportCredentialsMissing = errors.New("grpc: the credentials require transport level security (use grpc.WithTransportCredentials() to set)")
  63. // errCredentialsConflict indicates that grpc.WithTransportCredentials()
  64. // and grpc.WithInsecure() are both called for a connection.
  65. errCredentialsConflict = errors.New("grpc: transport credentials are set for an insecure connection (grpc.WithTransportCredentials() and grpc.WithInsecure() are both called)")
  66. // errNetworkIP indicates that the connection is down due to some network I/O error.
  67. errNetworkIO = errors.New("grpc: failed with network I/O error")
  68. // errConnDrain indicates that the connection starts to be drained and does not accept any new RPCs.
  69. errConnDrain = errors.New("grpc: the connection is drained")
  70. // errConnClosing indicates that the connection is closing.
  71. errConnClosing = errors.New("grpc: the connection is closing")
  72. errNoAddr = errors.New("grpc: there is no address available to dial")
  73. // minimum time to give a connection to complete
  74. minConnectTimeout = 20 * time.Second
  75. )
  76. // dialOptions configure a Dial call. dialOptions are set by the DialOption
  77. // values passed to Dial.
  78. type dialOptions struct {
  79. codec Codec
  80. cp Compressor
  81. dc Decompressor
  82. bs backoffStrategy
  83. balancer Balancer
  84. block bool
  85. insecure bool
  86. timeout time.Duration
  87. copts transport.ConnectOptions
  88. }
  89. // DialOption configures how we set up the connection.
  90. type DialOption func(*dialOptions)
  91. // WithCodec returns a DialOption which sets a codec for message marshaling and unmarshaling.
  92. func WithCodec(c Codec) DialOption {
  93. return func(o *dialOptions) {
  94. o.codec = c
  95. }
  96. }
  97. // WithCompressor returns a DialOption which sets a CompressorGenerator for generating message
  98. // compressor.
  99. func WithCompressor(cp Compressor) DialOption {
  100. return func(o *dialOptions) {
  101. o.cp = cp
  102. }
  103. }
  104. // WithDecompressor returns a DialOption which sets a DecompressorGenerator for generating
  105. // message decompressor.
  106. func WithDecompressor(dc Decompressor) DialOption {
  107. return func(o *dialOptions) {
  108. o.dc = dc
  109. }
  110. }
  111. // WithBalancer returns a DialOption which sets a load balancer.
  112. func WithBalancer(b Balancer) DialOption {
  113. return func(o *dialOptions) {
  114. o.balancer = b
  115. }
  116. }
  117. // WithBackoffMaxDelay configures the dialer to use the provided maximum delay
  118. // when backing off after failed connection attempts.
  119. func WithBackoffMaxDelay(md time.Duration) DialOption {
  120. return WithBackoffConfig(BackoffConfig{MaxDelay: md})
  121. }
  122. // WithBackoffConfig configures the dialer to use the provided backoff
  123. // parameters after connection failures.
  124. //
  125. // Use WithBackoffMaxDelay until more parameters on BackoffConfig are opened up
  126. // for use.
  127. func WithBackoffConfig(b BackoffConfig) DialOption {
  128. // Set defaults to ensure that provided BackoffConfig is valid and
  129. // unexported fields get default values.
  130. setDefaults(&b)
  131. return withBackoff(b)
  132. }
  133. // withBackoff sets the backoff strategy used for retries after a
  134. // failed connection attempt.
  135. //
  136. // This can be exported if arbitrary backoff strategies are allowed by gRPC.
  137. func withBackoff(bs backoffStrategy) DialOption {
  138. return func(o *dialOptions) {
  139. o.bs = bs
  140. }
  141. }
  142. // WithBlock returns a DialOption which makes caller of Dial blocks until the underlying
  143. // connection is up. Without this, Dial returns immediately and connecting the server
  144. // happens in background.
  145. func WithBlock() DialOption {
  146. return func(o *dialOptions) {
  147. o.block = true
  148. }
  149. }
  150. // WithInsecure returns a DialOption which disables transport security for this ClientConn.
  151. // Note that transport security is required unless WithInsecure is set.
  152. func WithInsecure() DialOption {
  153. return func(o *dialOptions) {
  154. o.insecure = true
  155. }
  156. }
  157. // WithTransportCredentials returns a DialOption which configures a
  158. // connection level security credentials (e.g., TLS/SSL).
  159. func WithTransportCredentials(creds credentials.TransportCredentials) DialOption {
  160. return func(o *dialOptions) {
  161. o.copts.TransportCredentials = creds
  162. }
  163. }
  164. // WithPerRPCCredentials returns a DialOption which sets
  165. // credentials which will place auth state on each outbound RPC.
  166. func WithPerRPCCredentials(creds credentials.PerRPCCredentials) DialOption {
  167. return func(o *dialOptions) {
  168. o.copts.PerRPCCredentials = append(o.copts.PerRPCCredentials, creds)
  169. }
  170. }
  171. // WithTimeout returns a DialOption that configures a timeout for dialing a ClientConn
  172. // initially. This is valid if and only if WithBlock() is present.
  173. func WithTimeout(d time.Duration) DialOption {
  174. return func(o *dialOptions) {
  175. o.timeout = d
  176. }
  177. }
  178. // WithDialer returns a DialOption that specifies a function to use for dialing network addresses.
  179. func WithDialer(f func(addr string, timeout time.Duration) (net.Conn, error)) DialOption {
  180. return func(o *dialOptions) {
  181. o.copts.Dialer = f
  182. }
  183. }
  184. // WithUserAgent returns a DialOption that specifies a user agent string for all the RPCs.
  185. func WithUserAgent(s string) DialOption {
  186. return func(o *dialOptions) {
  187. o.copts.UserAgent = s
  188. }
  189. }
  190. // Dial creates a client connection the given target.
  191. func Dial(target string, opts ...DialOption) (*ClientConn, error) {
  192. cc := &ClientConn{
  193. target: target,
  194. conns: make(map[Address]*addrConn),
  195. }
  196. for _, opt := range opts {
  197. opt(&cc.dopts)
  198. }
  199. if cc.dopts.codec == nil {
  200. // Set the default codec.
  201. cc.dopts.codec = protoCodec{}
  202. }
  203. if cc.dopts.bs == nil {
  204. cc.dopts.bs = DefaultBackoffConfig
  205. }
  206. cc.balancer = cc.dopts.balancer
  207. if cc.balancer == nil {
  208. cc.balancer = RoundRobin(nil)
  209. }
  210. if err := cc.balancer.Start(target); err != nil {
  211. return nil, err
  212. }
  213. var (
  214. ok bool
  215. addrs []Address
  216. )
  217. ch := cc.balancer.Notify()
  218. if ch == nil {
  219. // There is no name resolver installed.
  220. addrs = append(addrs, Address{Addr: target})
  221. } else {
  222. addrs, ok = <-ch
  223. if !ok || len(addrs) == 0 {
  224. return nil, errNoAddr
  225. }
  226. }
  227. waitC := make(chan error, 1)
  228. go func() {
  229. for _, a := range addrs {
  230. if err := cc.newAddrConn(a, false); err != nil {
  231. waitC <- err
  232. return
  233. }
  234. }
  235. close(waitC)
  236. }()
  237. var timeoutCh <-chan time.Time
  238. if cc.dopts.timeout > 0 {
  239. timeoutCh = time.After(cc.dopts.timeout)
  240. }
  241. select {
  242. case err := <-waitC:
  243. if err != nil {
  244. cc.Close()
  245. return nil, err
  246. }
  247. case <-timeoutCh:
  248. cc.Close()
  249. return nil, ErrClientConnTimeout
  250. }
  251. if ok {
  252. go cc.lbWatcher()
  253. }
  254. colonPos := strings.LastIndex(target, ":")
  255. if colonPos == -1 {
  256. colonPos = len(target)
  257. }
  258. cc.authority = target[:colonPos]
  259. return cc, nil
  260. }
  261. // ConnectivityState indicates the state of a client connection.
  262. type ConnectivityState int
  263. const (
  264. // Idle indicates the ClientConn is idle.
  265. Idle ConnectivityState = iota
  266. // Connecting indicates the ClienConn is connecting.
  267. Connecting
  268. // Ready indicates the ClientConn is ready for work.
  269. Ready
  270. // TransientFailure indicates the ClientConn has seen a failure but expects to recover.
  271. TransientFailure
  272. // Shutdown indicates the ClientConn has started shutting down.
  273. Shutdown
  274. )
  275. func (s ConnectivityState) String() string {
  276. switch s {
  277. case Idle:
  278. return "IDLE"
  279. case Connecting:
  280. return "CONNECTING"
  281. case Ready:
  282. return "READY"
  283. case TransientFailure:
  284. return "TRANSIENT_FAILURE"
  285. case Shutdown:
  286. return "SHUTDOWN"
  287. default:
  288. panic(fmt.Sprintf("unknown connectivity state: %d", s))
  289. }
  290. }
  291. // ClientConn represents a client connection to an RPC server.
  292. type ClientConn struct {
  293. target string
  294. balancer Balancer
  295. authority string
  296. dopts dialOptions
  297. mu sync.RWMutex
  298. conns map[Address]*addrConn
  299. }
  300. func (cc *ClientConn) lbWatcher() {
  301. for addrs := range cc.balancer.Notify() {
  302. var (
  303. add []Address // Addresses need to setup connections.
  304. del []*addrConn // Connections need to tear down.
  305. )
  306. cc.mu.Lock()
  307. for _, a := range addrs {
  308. if _, ok := cc.conns[a]; !ok {
  309. add = append(add, a)
  310. }
  311. }
  312. for k, c := range cc.conns {
  313. var keep bool
  314. for _, a := range addrs {
  315. if k == a {
  316. keep = true
  317. break
  318. }
  319. }
  320. if !keep {
  321. del = append(del, c)
  322. }
  323. }
  324. cc.mu.Unlock()
  325. for _, a := range add {
  326. cc.newAddrConn(a, true)
  327. }
  328. for _, c := range del {
  329. c.tearDown(errConnDrain)
  330. }
  331. }
  332. }
  333. func (cc *ClientConn) newAddrConn(addr Address, skipWait bool) error {
  334. ac := &addrConn{
  335. cc: cc,
  336. addr: addr,
  337. dopts: cc.dopts,
  338. shutdownChan: make(chan struct{}),
  339. }
  340. if EnableTracing {
  341. ac.events = trace.NewEventLog("grpc.ClientConn", ac.addr.Addr)
  342. }
  343. if !ac.dopts.insecure {
  344. if ac.dopts.copts.TransportCredentials == nil {
  345. return errNoTransportSecurity
  346. }
  347. } else {
  348. if ac.dopts.copts.TransportCredentials != nil {
  349. return errCredentialsConflict
  350. }
  351. for _, cd := range ac.dopts.copts.PerRPCCredentials {
  352. if cd.RequireTransportSecurity() {
  353. return errTransportCredentialsMissing
  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. }