clientconn.go 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403
  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. network, addr := parseDialTarget(addr)
  400. return dialContext(ctx, network, addr)
  401. },
  402. )
  403. }
  404. if cc.dopts.copts.UserAgent != "" {
  405. cc.dopts.copts.UserAgent += " " + grpcUA
  406. } else {
  407. cc.dopts.copts.UserAgent = grpcUA
  408. }
  409. if cc.dopts.timeout > 0 {
  410. var cancel context.CancelFunc
  411. ctx, cancel = context.WithTimeout(ctx, cc.dopts.timeout)
  412. defer cancel()
  413. }
  414. defer func() {
  415. select {
  416. case <-ctx.Done():
  417. conn, err = nil, ctx.Err()
  418. default:
  419. }
  420. if err != nil {
  421. cc.Close()
  422. }
  423. }()
  424. scSet := false
  425. if cc.dopts.scChan != nil {
  426. // Try to get an initial service config.
  427. select {
  428. case sc, ok := <-cc.dopts.scChan:
  429. if ok {
  430. cc.sc = sc
  431. scSet = true
  432. }
  433. default:
  434. }
  435. }
  436. if cc.dopts.bs == nil {
  437. cc.dopts.bs = DefaultBackoffConfig
  438. }
  439. if cc.dopts.resolverBuilder == nil {
  440. // Only try to parse target when resolver builder is not already set.
  441. cc.parsedTarget = parseTarget(cc.target)
  442. grpclog.Infof("parsed scheme: %q", cc.parsedTarget.Scheme)
  443. cc.dopts.resolverBuilder = resolver.Get(cc.parsedTarget.Scheme)
  444. if cc.dopts.resolverBuilder == nil {
  445. // If resolver builder is still nil, the parse target's scheme is
  446. // not registered. Fallback to default resolver and set Endpoint to
  447. // the original unparsed target.
  448. grpclog.Infof("scheme %q not registered, fallback to default scheme", cc.parsedTarget.Scheme)
  449. cc.parsedTarget = resolver.Target{
  450. Scheme: resolver.GetDefaultScheme(),
  451. Endpoint: target,
  452. }
  453. cc.dopts.resolverBuilder = resolver.Get(cc.parsedTarget.Scheme)
  454. }
  455. } else {
  456. cc.parsedTarget = resolver.Target{Endpoint: target}
  457. }
  458. creds := cc.dopts.copts.TransportCredentials
  459. if creds != nil && creds.Info().ServerName != "" {
  460. cc.authority = creds.Info().ServerName
  461. } else if cc.dopts.insecure && cc.dopts.copts.Authority != "" {
  462. cc.authority = cc.dopts.copts.Authority
  463. } else {
  464. // Use endpoint from "scheme://authority/endpoint" as the default
  465. // authority for ClientConn.
  466. cc.authority = cc.parsedTarget.Endpoint
  467. }
  468. if cc.dopts.scChan != nil && !scSet {
  469. // Blocking wait for the initial service config.
  470. select {
  471. case sc, ok := <-cc.dopts.scChan:
  472. if ok {
  473. cc.sc = sc
  474. }
  475. case <-ctx.Done():
  476. return nil, ctx.Err()
  477. }
  478. }
  479. if cc.dopts.scChan != nil {
  480. go cc.scWatcher()
  481. }
  482. var credsClone credentials.TransportCredentials
  483. if creds := cc.dopts.copts.TransportCredentials; creds != nil {
  484. credsClone = creds.Clone()
  485. }
  486. cc.balancerBuildOpts = balancer.BuildOptions{
  487. DialCreds: credsClone,
  488. Dialer: cc.dopts.copts.Dialer,
  489. }
  490. // Build the resolver.
  491. cc.resolverWrapper, err = newCCResolverWrapper(cc)
  492. if err != nil {
  493. return nil, fmt.Errorf("failed to build resolver: %v", err)
  494. }
  495. // Start the resolver wrapper goroutine after resolverWrapper is created.
  496. //
  497. // If the goroutine is started before resolverWrapper is ready, the
  498. // following may happen: The goroutine sends updates to cc. cc forwards
  499. // those to balancer. Balancer creates new addrConn. addrConn fails to
  500. // connect, and calls resolveNow(). resolveNow() tries to use the non-ready
  501. // resolverWrapper.
  502. cc.resolverWrapper.start()
  503. // A blocking dial blocks until the clientConn is ready.
  504. if cc.dopts.block {
  505. for {
  506. s := cc.GetState()
  507. if s == connectivity.Ready {
  508. break
  509. }
  510. if !cc.WaitForStateChange(ctx, s) {
  511. // ctx got timeout or canceled.
  512. return nil, ctx.Err()
  513. }
  514. }
  515. }
  516. return cc, nil
  517. }
  518. // connectivityStateManager keeps the connectivity.State of ClientConn.
  519. // This struct will eventually be exported so the balancers can access it.
  520. type connectivityStateManager struct {
  521. mu sync.Mutex
  522. state connectivity.State
  523. notifyChan chan struct{}
  524. }
  525. // updateState updates the connectivity.State of ClientConn.
  526. // If there's a change it notifies goroutines waiting on state change to
  527. // happen.
  528. func (csm *connectivityStateManager) updateState(state connectivity.State) {
  529. csm.mu.Lock()
  530. defer csm.mu.Unlock()
  531. if csm.state == connectivity.Shutdown {
  532. return
  533. }
  534. if csm.state == state {
  535. return
  536. }
  537. csm.state = state
  538. if csm.notifyChan != nil {
  539. // There are other goroutines waiting on this channel.
  540. close(csm.notifyChan)
  541. csm.notifyChan = nil
  542. }
  543. }
  544. func (csm *connectivityStateManager) getState() connectivity.State {
  545. csm.mu.Lock()
  546. defer csm.mu.Unlock()
  547. return csm.state
  548. }
  549. func (csm *connectivityStateManager) getNotifyChan() <-chan struct{} {
  550. csm.mu.Lock()
  551. defer csm.mu.Unlock()
  552. if csm.notifyChan == nil {
  553. csm.notifyChan = make(chan struct{})
  554. }
  555. return csm.notifyChan
  556. }
  557. // ClientConn represents a client connection to an RPC server.
  558. type ClientConn struct {
  559. ctx context.Context
  560. cancel context.CancelFunc
  561. target string
  562. parsedTarget resolver.Target
  563. authority string
  564. dopts dialOptions
  565. csMgr *connectivityStateManager
  566. balancerBuildOpts balancer.BuildOptions
  567. resolverWrapper *ccResolverWrapper
  568. blockingpicker *pickerWrapper
  569. mu sync.RWMutex
  570. sc ServiceConfig
  571. scRaw string
  572. conns map[*addrConn]struct{}
  573. // Keepalive parameter can be updated if a GoAway is received.
  574. mkp keepalive.ClientParameters
  575. curBalancerName string
  576. preBalancerName string // previous balancer name.
  577. curAddresses []resolver.Address
  578. balancerWrapper *ccBalancerWrapper
  579. }
  580. // WaitForStateChange waits until the connectivity.State of ClientConn changes from sourceState or
  581. // ctx expires. A true value is returned in former case and false in latter.
  582. // This is an EXPERIMENTAL API.
  583. func (cc *ClientConn) WaitForStateChange(ctx context.Context, sourceState connectivity.State) bool {
  584. ch := cc.csMgr.getNotifyChan()
  585. if cc.csMgr.getState() != sourceState {
  586. return true
  587. }
  588. select {
  589. case <-ctx.Done():
  590. return false
  591. case <-ch:
  592. return true
  593. }
  594. }
  595. // GetState returns the connectivity.State of ClientConn.
  596. // This is an EXPERIMENTAL API.
  597. func (cc *ClientConn) GetState() connectivity.State {
  598. return cc.csMgr.getState()
  599. }
  600. func (cc *ClientConn) scWatcher() {
  601. for {
  602. select {
  603. case sc, ok := <-cc.dopts.scChan:
  604. if !ok {
  605. return
  606. }
  607. cc.mu.Lock()
  608. // TODO: load balance policy runtime change is ignored.
  609. // We may revist this decision in the future.
  610. cc.sc = sc
  611. cc.scRaw = ""
  612. cc.mu.Unlock()
  613. case <-cc.ctx.Done():
  614. return
  615. }
  616. }
  617. }
  618. func (cc *ClientConn) handleResolvedAddrs(addrs []resolver.Address, err error) {
  619. cc.mu.Lock()
  620. defer cc.mu.Unlock()
  621. if cc.conns == nil {
  622. // cc was closed.
  623. return
  624. }
  625. if reflect.DeepEqual(cc.curAddresses, addrs) {
  626. return
  627. }
  628. cc.curAddresses = addrs
  629. if cc.dopts.balancerBuilder == nil {
  630. // Only look at balancer types and switch balancer if balancer dial
  631. // option is not set.
  632. var isGRPCLB bool
  633. for _, a := range addrs {
  634. if a.Type == resolver.GRPCLB {
  635. isGRPCLB = true
  636. break
  637. }
  638. }
  639. var newBalancerName string
  640. if isGRPCLB {
  641. newBalancerName = grpclbName
  642. } else {
  643. // Address list doesn't contain grpclb address. Try to pick a
  644. // non-grpclb balancer.
  645. newBalancerName = cc.curBalancerName
  646. // If current balancer is grpclb, switch to the previous one.
  647. if newBalancerName == grpclbName {
  648. newBalancerName = cc.preBalancerName
  649. }
  650. // The following could be true in two cases:
  651. // - the first time handling resolved addresses
  652. // (curBalancerName="")
  653. // - the first time handling non-grpclb addresses
  654. // (curBalancerName="grpclb", preBalancerName="")
  655. if newBalancerName == "" {
  656. newBalancerName = PickFirstBalancerName
  657. }
  658. }
  659. cc.switchBalancer(newBalancerName)
  660. } else if cc.balancerWrapper == nil {
  661. // Balancer dial option was set, and this is the first time handling
  662. // resolved addresses. Build a balancer with dopts.balancerBuilder.
  663. cc.balancerWrapper = newCCBalancerWrapper(cc, cc.dopts.balancerBuilder, cc.balancerBuildOpts)
  664. }
  665. cc.balancerWrapper.handleResolvedAddrs(addrs, nil)
  666. }
  667. // switchBalancer starts the switching from current balancer to the balancer
  668. // with the given name.
  669. //
  670. // It will NOT send the current address list to the new balancer. If needed,
  671. // caller of this function should send address list to the new balancer after
  672. // this function returns.
  673. //
  674. // Caller must hold cc.mu.
  675. func (cc *ClientConn) switchBalancer(name string) {
  676. if cc.conns == nil {
  677. return
  678. }
  679. if strings.ToLower(cc.curBalancerName) == strings.ToLower(name) {
  680. return
  681. }
  682. grpclog.Infof("ClientConn switching balancer to %q", name)
  683. if cc.dopts.balancerBuilder != nil {
  684. grpclog.Infoln("ignoring balancer switching: Balancer DialOption used instead")
  685. return
  686. }
  687. // TODO(bar switching) change this to two steps: drain and close.
  688. // Keep track of sc in wrapper.
  689. if cc.balancerWrapper != nil {
  690. cc.balancerWrapper.close()
  691. }
  692. builder := balancer.Get(name)
  693. if builder == nil {
  694. grpclog.Infof("failed to get balancer builder for: %v, using pick_first instead", name)
  695. builder = newPickfirstBuilder()
  696. }
  697. cc.preBalancerName = cc.curBalancerName
  698. cc.curBalancerName = builder.Name()
  699. cc.balancerWrapper = newCCBalancerWrapper(cc, builder, cc.balancerBuildOpts)
  700. }
  701. func (cc *ClientConn) handleSubConnStateChange(sc balancer.SubConn, s connectivity.State) {
  702. cc.mu.Lock()
  703. if cc.conns == nil {
  704. cc.mu.Unlock()
  705. return
  706. }
  707. // TODO(bar switching) send updates to all balancer wrappers when balancer
  708. // gracefully switching is supported.
  709. cc.balancerWrapper.handleSubConnStateChange(sc, s)
  710. cc.mu.Unlock()
  711. }
  712. // newAddrConn creates an addrConn for addrs and adds it to cc.conns.
  713. //
  714. // Caller needs to make sure len(addrs) > 0.
  715. func (cc *ClientConn) newAddrConn(addrs []resolver.Address) (*addrConn, error) {
  716. ac := &addrConn{
  717. cc: cc,
  718. addrs: addrs,
  719. dopts: cc.dopts,
  720. }
  721. ac.ctx, ac.cancel = context.WithCancel(cc.ctx)
  722. // Track ac in cc. This needs to be done before any getTransport(...) is called.
  723. cc.mu.Lock()
  724. if cc.conns == nil {
  725. cc.mu.Unlock()
  726. return nil, ErrClientConnClosing
  727. }
  728. cc.conns[ac] = struct{}{}
  729. cc.mu.Unlock()
  730. return ac, nil
  731. }
  732. // removeAddrConn removes the addrConn in the subConn from clientConn.
  733. // It also tears down the ac with the given error.
  734. func (cc *ClientConn) removeAddrConn(ac *addrConn, err error) {
  735. cc.mu.Lock()
  736. if cc.conns == nil {
  737. cc.mu.Unlock()
  738. return
  739. }
  740. delete(cc.conns, ac)
  741. cc.mu.Unlock()
  742. ac.tearDown(err)
  743. }
  744. // connect starts to creating transport and also starts the transport monitor
  745. // goroutine for this ac.
  746. // It does nothing if the ac is not IDLE.
  747. // TODO(bar) Move this to the addrConn section.
  748. // This was part of resetAddrConn, keep it here to make the diff look clean.
  749. func (ac *addrConn) connect() error {
  750. ac.mu.Lock()
  751. if ac.state == connectivity.Shutdown {
  752. ac.mu.Unlock()
  753. return errConnClosing
  754. }
  755. if ac.state != connectivity.Idle {
  756. ac.mu.Unlock()
  757. return nil
  758. }
  759. ac.state = connectivity.Connecting
  760. ac.cc.handleSubConnStateChange(ac.acbw, ac.state)
  761. ac.mu.Unlock()
  762. // Start a goroutine connecting to the server asynchronously.
  763. go func() {
  764. if err := ac.resetTransport(); err != nil {
  765. grpclog.Warningf("Failed to dial %s: %v; please retry.", ac.addrs[0].Addr, err)
  766. if err != errConnClosing {
  767. // Keep this ac in cc.conns, to get the reason it's torn down.
  768. ac.tearDown(err)
  769. }
  770. return
  771. }
  772. ac.transportMonitor()
  773. }()
  774. return nil
  775. }
  776. // tryUpdateAddrs tries to update ac.addrs with the new addresses list.
  777. //
  778. // It checks whether current connected address of ac is in the new addrs list.
  779. // - If true, it updates ac.addrs and returns true. The ac will keep using
  780. // the existing connection.
  781. // - If false, it does nothing and returns false.
  782. func (ac *addrConn) tryUpdateAddrs(addrs []resolver.Address) bool {
  783. ac.mu.Lock()
  784. defer ac.mu.Unlock()
  785. grpclog.Infof("addrConn: tryUpdateAddrs curAddr: %v, addrs: %v", ac.curAddr, addrs)
  786. if ac.state == connectivity.Shutdown {
  787. ac.addrs = addrs
  788. return true
  789. }
  790. var curAddrFound bool
  791. for _, a := range addrs {
  792. if reflect.DeepEqual(ac.curAddr, a) {
  793. curAddrFound = true
  794. break
  795. }
  796. }
  797. grpclog.Infof("addrConn: tryUpdateAddrs curAddrFound: %v", curAddrFound)
  798. if curAddrFound {
  799. ac.addrs = addrs
  800. ac.reconnectIdx = 0 // Start reconnecting from beginning in the new list.
  801. }
  802. return curAddrFound
  803. }
  804. // GetMethodConfig gets the method config of the input method.
  805. // If there's an exact match for input method (i.e. /service/method), we return
  806. // the corresponding MethodConfig.
  807. // If there isn't an exact match for the input method, we look for the default config
  808. // under the service (i.e /service/). If there is a default MethodConfig for
  809. // the service, we return it.
  810. // Otherwise, we return an empty MethodConfig.
  811. func (cc *ClientConn) GetMethodConfig(method string) MethodConfig {
  812. // TODO: Avoid the locking here.
  813. cc.mu.RLock()
  814. defer cc.mu.RUnlock()
  815. m, ok := cc.sc.Methods[method]
  816. if !ok {
  817. i := strings.LastIndex(method, "/")
  818. m, _ = cc.sc.Methods[method[:i+1]]
  819. }
  820. return m
  821. }
  822. func (cc *ClientConn) getTransport(ctx context.Context, failfast bool) (transport.ClientTransport, func(balancer.DoneInfo), error) {
  823. t, done, err := cc.blockingpicker.pick(ctx, failfast, balancer.PickOptions{})
  824. if err != nil {
  825. return nil, nil, toRPCErr(err)
  826. }
  827. return t, done, nil
  828. }
  829. // handleServiceConfig parses the service config string in JSON format to Go native
  830. // struct ServiceConfig, and store both the struct and the JSON string in ClientConn.
  831. func (cc *ClientConn) handleServiceConfig(js string) error {
  832. sc, err := parseServiceConfig(js)
  833. if err != nil {
  834. return err
  835. }
  836. cc.mu.Lock()
  837. cc.scRaw = js
  838. cc.sc = sc
  839. if sc.LB != nil && *sc.LB != grpclbName { // "grpclb" is not a valid balancer option in service config.
  840. if cc.curBalancerName == grpclbName {
  841. // If current balancer is grpclb, there's at least one grpclb
  842. // balancer address in the resolved list. Don't switch the balancer,
  843. // but change the previous balancer name, so if a new resolved
  844. // address list doesn't contain grpclb address, balancer will be
  845. // switched to *sc.LB.
  846. cc.preBalancerName = *sc.LB
  847. } else {
  848. cc.switchBalancer(*sc.LB)
  849. cc.balancerWrapper.handleResolvedAddrs(cc.curAddresses, nil)
  850. }
  851. }
  852. cc.mu.Unlock()
  853. return nil
  854. }
  855. func (cc *ClientConn) resolveNow(o resolver.ResolveNowOption) {
  856. cc.mu.Lock()
  857. r := cc.resolverWrapper
  858. cc.mu.Unlock()
  859. if r == nil {
  860. return
  861. }
  862. go r.resolveNow(o)
  863. }
  864. // Close tears down the ClientConn and all underlying connections.
  865. func (cc *ClientConn) Close() error {
  866. defer cc.cancel()
  867. cc.mu.Lock()
  868. if cc.conns == nil {
  869. cc.mu.Unlock()
  870. return ErrClientConnClosing
  871. }
  872. conns := cc.conns
  873. cc.conns = nil
  874. cc.csMgr.updateState(connectivity.Shutdown)
  875. rWrapper := cc.resolverWrapper
  876. cc.resolverWrapper = nil
  877. bWrapper := cc.balancerWrapper
  878. cc.balancerWrapper = nil
  879. cc.mu.Unlock()
  880. cc.blockingpicker.close()
  881. if rWrapper != nil {
  882. rWrapper.close()
  883. }
  884. if bWrapper != nil {
  885. bWrapper.close()
  886. }
  887. for ac := range conns {
  888. ac.tearDown(ErrClientConnClosing)
  889. }
  890. return nil
  891. }
  892. // addrConn is a network connection to a given address.
  893. type addrConn struct {
  894. ctx context.Context
  895. cancel context.CancelFunc
  896. cc *ClientConn
  897. addrs []resolver.Address
  898. dopts dialOptions
  899. events trace.EventLog
  900. acbw balancer.SubConn
  901. mu sync.Mutex
  902. curAddr resolver.Address
  903. reconnectIdx int // The index in addrs list to start reconnecting from.
  904. state connectivity.State
  905. // ready is closed and becomes nil when a new transport is up or failed
  906. // due to timeout.
  907. ready chan struct{}
  908. transport transport.ClientTransport
  909. // The reason this addrConn is torn down.
  910. tearDownErr error
  911. connectRetryNum int
  912. // backoffDeadline is the time until which resetTransport needs to
  913. // wait before increasing connectRetryNum count.
  914. backoffDeadline time.Time
  915. // connectDeadline is the time by which all connection
  916. // negotiations must complete.
  917. connectDeadline time.Time
  918. }
  919. // adjustParams updates parameters used to create transports upon
  920. // receiving a GoAway.
  921. func (ac *addrConn) adjustParams(r transport.GoAwayReason) {
  922. switch r {
  923. case transport.GoAwayTooManyPings:
  924. v := 2 * ac.dopts.copts.KeepaliveParams.Time
  925. ac.cc.mu.Lock()
  926. if v > ac.cc.mkp.Time {
  927. ac.cc.mkp.Time = v
  928. }
  929. ac.cc.mu.Unlock()
  930. }
  931. }
  932. // printf records an event in ac's event log, unless ac has been closed.
  933. // REQUIRES ac.mu is held.
  934. func (ac *addrConn) printf(format string, a ...interface{}) {
  935. if ac.events != nil {
  936. ac.events.Printf(format, a...)
  937. }
  938. }
  939. // errorf records an error in ac's event log, unless ac has been closed.
  940. // REQUIRES ac.mu is held.
  941. func (ac *addrConn) errorf(format string, a ...interface{}) {
  942. if ac.events != nil {
  943. ac.events.Errorf(format, a...)
  944. }
  945. }
  946. // resetTransport recreates a transport to the address for ac. The old
  947. // transport will close itself on error or when the clientconn is closed.
  948. // The created transport must receive initial settings frame from the server.
  949. // In case that doesnt happen, transportMonitor will kill the newly created
  950. // transport after connectDeadline has expired.
  951. // In case there was an error on the transport before the settings frame was
  952. // received, resetTransport resumes connecting to backends after the one that
  953. // was previously connected to. In case end of the list is reached, resetTransport
  954. // backs off until the original deadline.
  955. // If the DialOption WithWaitForHandshake was set, resetTrasport returns
  956. // successfully only after server settings are received.
  957. //
  958. // TODO(bar) make sure all state transitions are valid.
  959. func (ac *addrConn) resetTransport() error {
  960. ac.mu.Lock()
  961. if ac.state == connectivity.Shutdown {
  962. ac.mu.Unlock()
  963. return errConnClosing
  964. }
  965. if ac.ready != nil {
  966. close(ac.ready)
  967. ac.ready = nil
  968. }
  969. ac.transport = nil
  970. ridx := ac.reconnectIdx
  971. ac.mu.Unlock()
  972. ac.cc.mu.RLock()
  973. ac.dopts.copts.KeepaliveParams = ac.cc.mkp
  974. ac.cc.mu.RUnlock()
  975. var backoffDeadline, connectDeadline time.Time
  976. for connectRetryNum := 0; ; connectRetryNum++ {
  977. ac.mu.Lock()
  978. if ac.backoffDeadline.IsZero() {
  979. // This means either a successful HTTP2 connection was established
  980. // or this is the first time this addrConn is trying to establish a
  981. // connection.
  982. backoffFor := ac.dopts.bs.backoff(connectRetryNum) // time.Duration.
  983. // This will be the duration that dial gets to finish.
  984. dialDuration := getMinConnectTimeout()
  985. if backoffFor > dialDuration {
  986. // Give dial more time as we keep failing to connect.
  987. dialDuration = backoffFor
  988. }
  989. start := time.Now()
  990. backoffDeadline = start.Add(backoffFor)
  991. connectDeadline = start.Add(dialDuration)
  992. ridx = 0 // Start connecting from the beginning.
  993. } else {
  994. // Continue trying to conect with the same deadlines.
  995. connectRetryNum = ac.connectRetryNum
  996. backoffDeadline = ac.backoffDeadline
  997. connectDeadline = ac.connectDeadline
  998. ac.backoffDeadline = time.Time{}
  999. ac.connectDeadline = time.Time{}
  1000. ac.connectRetryNum = 0
  1001. }
  1002. if ac.state == connectivity.Shutdown {
  1003. ac.mu.Unlock()
  1004. return errConnClosing
  1005. }
  1006. ac.printf("connecting")
  1007. if ac.state != connectivity.Connecting {
  1008. ac.state = connectivity.Connecting
  1009. ac.cc.handleSubConnStateChange(ac.acbw, ac.state)
  1010. }
  1011. // copy ac.addrs in case of race
  1012. addrsIter := make([]resolver.Address, len(ac.addrs))
  1013. copy(addrsIter, ac.addrs)
  1014. copts := ac.dopts.copts
  1015. ac.mu.Unlock()
  1016. connected, err := ac.createTransport(connectRetryNum, ridx, backoffDeadline, connectDeadline, addrsIter, copts)
  1017. if err != nil {
  1018. return err
  1019. }
  1020. if connected {
  1021. return nil
  1022. }
  1023. }
  1024. }
  1025. // createTransport creates a connection to one of the backends in addrs.
  1026. // It returns true if a connection was established.
  1027. func (ac *addrConn) createTransport(connectRetryNum, ridx int, backoffDeadline, connectDeadline time.Time, addrs []resolver.Address, copts transport.ConnectOptions) (bool, error) {
  1028. for i := ridx; i < len(addrs); i++ {
  1029. addr := addrs[i]
  1030. target := transport.TargetInfo{
  1031. Addr: addr.Addr,
  1032. Metadata: addr.Metadata,
  1033. Authority: ac.cc.authority,
  1034. }
  1035. done := make(chan struct{})
  1036. onPrefaceReceipt := func() {
  1037. ac.mu.Lock()
  1038. close(done)
  1039. if !ac.backoffDeadline.IsZero() {
  1040. // If we haven't already started reconnecting to
  1041. // other backends.
  1042. // Note, this can happen when writer notices an error
  1043. // and triggers resetTransport while at the same time
  1044. // reader receives the preface and invokes this closure.
  1045. ac.backoffDeadline = time.Time{}
  1046. ac.connectDeadline = time.Time{}
  1047. ac.connectRetryNum = 0
  1048. }
  1049. ac.mu.Unlock()
  1050. }
  1051. // Do not cancel in the success path because of
  1052. // this issue in Go1.6: https://github.com/golang/go/issues/15078.
  1053. connectCtx, cancel := context.WithDeadline(ac.ctx, connectDeadline)
  1054. newTr, err := transport.NewClientTransport(connectCtx, ac.cc.ctx, target, copts, onPrefaceReceipt)
  1055. if err != nil {
  1056. cancel()
  1057. ac.cc.blockingpicker.updateConnectionError(err)
  1058. ac.mu.Lock()
  1059. if ac.state == connectivity.Shutdown {
  1060. // ac.tearDown(...) has been invoked.
  1061. ac.mu.Unlock()
  1062. return false, errConnClosing
  1063. }
  1064. ac.mu.Unlock()
  1065. grpclog.Warningf("grpc: addrConn.createTransport failed to connect to %v. Err :%v. Reconnecting...", addr, err)
  1066. continue
  1067. }
  1068. if ac.dopts.waitForHandshake {
  1069. select {
  1070. case <-done:
  1071. case <-connectCtx.Done():
  1072. // Didn't receive server preface, must kill this new transport now.
  1073. grpclog.Warningf("grpc: addrConn.createTransport failed to receive server preface before deadline.")
  1074. newTr.Close()
  1075. break
  1076. case <-ac.ctx.Done():
  1077. }
  1078. }
  1079. ac.mu.Lock()
  1080. if ac.state == connectivity.Shutdown {
  1081. ac.mu.Unlock()
  1082. // ac.tearDonn(...) has been invoked.
  1083. newTr.Close()
  1084. return false, errConnClosing
  1085. }
  1086. ac.printf("ready")
  1087. ac.state = connectivity.Ready
  1088. ac.cc.handleSubConnStateChange(ac.acbw, ac.state)
  1089. ac.transport = newTr
  1090. ac.curAddr = addr
  1091. if ac.ready != nil {
  1092. close(ac.ready)
  1093. ac.ready = nil
  1094. }
  1095. select {
  1096. case <-done:
  1097. // If the server has responded back with preface already,
  1098. // don't set the reconnect parameters.
  1099. default:
  1100. ac.connectRetryNum = connectRetryNum
  1101. ac.backoffDeadline = backoffDeadline
  1102. ac.connectDeadline = connectDeadline
  1103. ac.reconnectIdx = i + 1 // Start reconnecting from the next backend in the list.
  1104. }
  1105. ac.mu.Unlock()
  1106. return true, nil
  1107. }
  1108. ac.mu.Lock()
  1109. ac.state = connectivity.TransientFailure
  1110. ac.cc.handleSubConnStateChange(ac.acbw, ac.state)
  1111. ac.cc.resolveNow(resolver.ResolveNowOption{})
  1112. if ac.ready != nil {
  1113. close(ac.ready)
  1114. ac.ready = nil
  1115. }
  1116. ac.mu.Unlock()
  1117. timer := time.NewTimer(backoffDeadline.Sub(time.Now()))
  1118. select {
  1119. case <-timer.C:
  1120. case <-ac.ctx.Done():
  1121. timer.Stop()
  1122. return false, ac.ctx.Err()
  1123. }
  1124. return false, nil
  1125. }
  1126. // Run in a goroutine to track the error in transport and create the
  1127. // new transport if an error happens. It returns when the channel is closing.
  1128. func (ac *addrConn) transportMonitor() {
  1129. for {
  1130. var timer *time.Timer
  1131. var cdeadline <-chan time.Time
  1132. ac.mu.Lock()
  1133. t := ac.transport
  1134. if !ac.connectDeadline.IsZero() {
  1135. timer = time.NewTimer(ac.connectDeadline.Sub(time.Now()))
  1136. cdeadline = timer.C
  1137. }
  1138. ac.mu.Unlock()
  1139. // Block until we receive a goaway or an error occurs.
  1140. select {
  1141. case <-t.GoAway():
  1142. case <-t.Error():
  1143. case <-cdeadline:
  1144. ac.mu.Lock()
  1145. // This implies that client received server preface.
  1146. if ac.backoffDeadline.IsZero() {
  1147. ac.mu.Unlock()
  1148. continue
  1149. }
  1150. ac.mu.Unlock()
  1151. timer = nil
  1152. // No server preface received until deadline.
  1153. // Kill the connection.
  1154. grpclog.Warningf("grpc: addrConn.transportMonitor didn't get server preface after waiting. Closing the new transport now.")
  1155. t.Close()
  1156. }
  1157. if timer != nil {
  1158. timer.Stop()
  1159. }
  1160. // If a GoAway happened, regardless of error, adjust our keepalive
  1161. // parameters as appropriate.
  1162. select {
  1163. case <-t.GoAway():
  1164. ac.adjustParams(t.GetGoAwayReason())
  1165. default:
  1166. }
  1167. ac.mu.Lock()
  1168. if ac.state == connectivity.Shutdown {
  1169. ac.mu.Unlock()
  1170. return
  1171. }
  1172. // Set connectivity state to TransientFailure before calling
  1173. // resetTransport. Transition READY->CONNECTING is not valid.
  1174. ac.state = connectivity.TransientFailure
  1175. ac.cc.handleSubConnStateChange(ac.acbw, ac.state)
  1176. ac.cc.resolveNow(resolver.ResolveNowOption{})
  1177. ac.curAddr = resolver.Address{}
  1178. ac.mu.Unlock()
  1179. if err := ac.resetTransport(); err != nil {
  1180. ac.mu.Lock()
  1181. ac.printf("transport exiting: %v", err)
  1182. ac.mu.Unlock()
  1183. grpclog.Warningf("grpc: addrConn.transportMonitor exits due to: %v", err)
  1184. if err != errConnClosing {
  1185. // Keep this ac in cc.conns, to get the reason it's torn down.
  1186. ac.tearDown(err)
  1187. }
  1188. return
  1189. }
  1190. }
  1191. }
  1192. // wait blocks until i) the new transport is up or ii) ctx is done or iii) ac is closed or
  1193. // iv) transport is in connectivity.TransientFailure and there is a balancer/failfast is true.
  1194. func (ac *addrConn) wait(ctx context.Context, hasBalancer, failfast bool) (transport.ClientTransport, error) {
  1195. for {
  1196. ac.mu.Lock()
  1197. switch {
  1198. case ac.state == connectivity.Shutdown:
  1199. if failfast || !hasBalancer {
  1200. // RPC is failfast or balancer is nil. This RPC should fail with ac.tearDownErr.
  1201. err := ac.tearDownErr
  1202. ac.mu.Unlock()
  1203. return nil, err
  1204. }
  1205. ac.mu.Unlock()
  1206. return nil, errConnClosing
  1207. case ac.state == connectivity.Ready:
  1208. ct := ac.transport
  1209. ac.mu.Unlock()
  1210. return ct, nil
  1211. case ac.state == connectivity.TransientFailure:
  1212. if failfast || hasBalancer {
  1213. ac.mu.Unlock()
  1214. return nil, errConnUnavailable
  1215. }
  1216. }
  1217. ready := ac.ready
  1218. if ready == nil {
  1219. ready = make(chan struct{})
  1220. ac.ready = ready
  1221. }
  1222. ac.mu.Unlock()
  1223. select {
  1224. case <-ctx.Done():
  1225. return nil, toRPCErr(ctx.Err())
  1226. // Wait until the new transport is ready or failed.
  1227. case <-ready:
  1228. }
  1229. }
  1230. }
  1231. // getReadyTransport returns the transport if ac's state is READY.
  1232. // Otherwise it returns nil, false.
  1233. // If ac's state is IDLE, it will trigger ac to connect.
  1234. func (ac *addrConn) getReadyTransport() (transport.ClientTransport, bool) {
  1235. ac.mu.Lock()
  1236. if ac.state == connectivity.Ready {
  1237. t := ac.transport
  1238. ac.mu.Unlock()
  1239. return t, true
  1240. }
  1241. var idle bool
  1242. if ac.state == connectivity.Idle {
  1243. idle = true
  1244. }
  1245. ac.mu.Unlock()
  1246. // Trigger idle ac to connect.
  1247. if idle {
  1248. ac.connect()
  1249. }
  1250. return nil, false
  1251. }
  1252. // tearDown starts to tear down the addrConn.
  1253. // TODO(zhaoq): Make this synchronous to avoid unbounded memory consumption in
  1254. // some edge cases (e.g., the caller opens and closes many addrConn's in a
  1255. // tight loop.
  1256. // tearDown doesn't remove ac from ac.cc.conns.
  1257. func (ac *addrConn) tearDown(err error) {
  1258. ac.cancel()
  1259. ac.mu.Lock()
  1260. defer ac.mu.Unlock()
  1261. if ac.state == connectivity.Shutdown {
  1262. return
  1263. }
  1264. ac.curAddr = resolver.Address{}
  1265. if err == errConnDrain && ac.transport != nil {
  1266. // GracefulClose(...) may be executed multiple times when
  1267. // i) receiving multiple GoAway frames from the server; or
  1268. // ii) there are concurrent name resolver/Balancer triggered
  1269. // address removal and GoAway.
  1270. ac.transport.GracefulClose()
  1271. }
  1272. ac.state = connectivity.Shutdown
  1273. ac.tearDownErr = err
  1274. ac.cc.handleSubConnStateChange(ac.acbw, ac.state)
  1275. if ac.events != nil {
  1276. ac.events.Finish()
  1277. ac.events = nil
  1278. }
  1279. if ac.ready != nil {
  1280. close(ac.ready)
  1281. ac.ready = nil
  1282. }
  1283. return
  1284. }
  1285. func (ac *addrConn) getState() connectivity.State {
  1286. ac.mu.Lock()
  1287. defer ac.mu.Unlock()
  1288. return ac.state
  1289. }
  1290. // ErrClientConnTimeout indicates that the ClientConn cannot establish the
  1291. // underlying connections within the specified timeout.
  1292. //
  1293. // Deprecated: This error is never returned by grpc and should not be
  1294. // referenced by users.
  1295. var ErrClientConnTimeout = errors.New("grpc: timed out when dialing")