clientconn.go 41 KB

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