clientconn.go 42 KB

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