clientconn.go 48 KB

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