clientconn.go 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556
  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. "context"
  21. "errors"
  22. "fmt"
  23. "math"
  24. "net"
  25. "reflect"
  26. "strings"
  27. "sync"
  28. "sync/atomic"
  29. "time"
  30. "google.golang.org/grpc/balancer"
  31. "google.golang.org/grpc/balancer/base"
  32. "google.golang.org/grpc/codes"
  33. "google.golang.org/grpc/connectivity"
  34. "google.golang.org/grpc/credentials"
  35. "google.golang.org/grpc/internal/backoff"
  36. "google.golang.org/grpc/internal/channelz"
  37. "google.golang.org/grpc/internal/grpcsync"
  38. "google.golang.org/grpc/internal/grpcutil"
  39. "google.golang.org/grpc/internal/transport"
  40. "google.golang.org/grpc/keepalive"
  41. "google.golang.org/grpc/resolver"
  42. "google.golang.org/grpc/serviceconfig"
  43. "google.golang.org/grpc/status"
  44. _ "google.golang.org/grpc/balancer/roundrobin" // To register roundrobin.
  45. _ "google.golang.org/grpc/internal/resolver/dns" // To register dns resolver.
  46. _ "google.golang.org/grpc/internal/resolver/passthrough" // To register passthrough resolver.
  47. )
  48. const (
  49. // minimum time to give a connection to complete
  50. minConnectTimeout = 20 * time.Second
  51. // must match grpclbName in grpclb/grpclb.go
  52. grpclbName = "grpclb"
  53. )
  54. var (
  55. // ErrClientConnClosing indicates that the operation is illegal because
  56. // the ClientConn is closing.
  57. //
  58. // Deprecated: this error should not be relied upon by users; use the status
  59. // code of Canceled instead.
  60. ErrClientConnClosing = status.Error(codes.Canceled, "grpc: the client connection is closing")
  61. // errConnDrain indicates that the connection starts to be drained and does not accept any new RPCs.
  62. errConnDrain = errors.New("grpc: the connection is drained")
  63. // errConnClosing indicates that the connection is closing.
  64. errConnClosing = errors.New("grpc: the connection is closing")
  65. // invalidDefaultServiceConfigErrPrefix is used to prefix the json parsing error for the default
  66. // service config.
  67. invalidDefaultServiceConfigErrPrefix = "grpc: the provided default service config is invalid"
  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. // errTransportCredsAndBundle indicates that creds bundle is used together
  76. // with other individual Transport Credentials.
  77. errTransportCredsAndBundle = errors.New("grpc: credentials.Bundle may not be used with individual TransportCredentials")
  78. // errTransportCredentialsMissing indicates that users want to transmit security
  79. // information (e.g., OAuth2 token) which requires secure connection on an insecure
  80. // connection.
  81. errTransportCredentialsMissing = errors.New("grpc: the credentials require transport level security (use grpc.WithTransportCredentials() to set)")
  82. // errCredentialsConflict indicates that grpc.WithTransportCredentials()
  83. // and grpc.WithInsecure() are both called for a connection.
  84. errCredentialsConflict = errors.New("grpc: transport credentials are set for an insecure connection (grpc.WithTransportCredentials() and grpc.WithInsecure() are both called)")
  85. )
  86. const (
  87. defaultClientMaxReceiveMessageSize = 1024 * 1024 * 4
  88. defaultClientMaxSendMessageSize = math.MaxInt32
  89. // http2IOBufSize specifies the buffer size for sending frames.
  90. defaultWriteBufSize = 32 * 1024
  91. defaultReadBufSize = 32 * 1024
  92. )
  93. // Dial creates a client connection to the given target.
  94. func Dial(target string, opts ...DialOption) (*ClientConn, error) {
  95. return DialContext(context.Background(), target, opts...)
  96. }
  97. // DialContext creates a client connection to the given target. By default, it's
  98. // a non-blocking dial (the function won't wait for connections to be
  99. // established, and connecting happens in the background). To make it a blocking
  100. // dial, use WithBlock() dial option.
  101. //
  102. // In the non-blocking case, the ctx does not act against the connection. It
  103. // only controls the setup steps.
  104. //
  105. // In the blocking case, ctx can be used to cancel or expire the pending
  106. // connection. Once this function returns, the cancellation and expiration of
  107. // ctx will be noop. Users should call ClientConn.Close to terminate all the
  108. // pending operations after this function returns.
  109. //
  110. // The target name syntax is defined in
  111. // https://github.com/grpc/grpc/blob/master/doc/naming.md.
  112. // e.g. to use dns resolver, a "dns:///" prefix should be applied to the target.
  113. func DialContext(ctx context.Context, target string, opts ...DialOption) (conn *ClientConn, err error) {
  114. cc := &ClientConn{
  115. target: target,
  116. csMgr: &connectivityStateManager{},
  117. conns: make(map[*addrConn]struct{}),
  118. dopts: defaultDialOptions(),
  119. blockingpicker: newPickerWrapper(),
  120. czData: new(channelzData),
  121. firstResolveEvent: grpcsync.NewEvent(),
  122. }
  123. cc.retryThrottler.Store((*retryThrottler)(nil))
  124. cc.ctx, cc.cancel = context.WithCancel(context.Background())
  125. for _, opt := range opts {
  126. opt.apply(&cc.dopts)
  127. }
  128. chainUnaryClientInterceptors(cc)
  129. chainStreamClientInterceptors(cc)
  130. defer func() {
  131. if err != nil {
  132. cc.Close()
  133. }
  134. }()
  135. if channelz.IsOn() {
  136. if cc.dopts.channelzParentID != 0 {
  137. cc.channelzID = channelz.RegisterChannel(&channelzChannel{cc}, cc.dopts.channelzParentID, target)
  138. channelz.AddTraceEvent(logger, cc.channelzID, 0, &channelz.TraceEventDesc{
  139. Desc: "Channel Created",
  140. Severity: channelz.CtINFO,
  141. Parent: &channelz.TraceEventDesc{
  142. Desc: fmt.Sprintf("Nested Channel(id:%d) created", cc.channelzID),
  143. Severity: channelz.CtINFO,
  144. },
  145. })
  146. } else {
  147. cc.channelzID = channelz.RegisterChannel(&channelzChannel{cc}, 0, target)
  148. channelz.Info(logger, cc.channelzID, "Channel Created")
  149. }
  150. cc.csMgr.channelzID = cc.channelzID
  151. }
  152. if !cc.dopts.insecure {
  153. if cc.dopts.copts.TransportCredentials == nil && cc.dopts.copts.CredsBundle == nil {
  154. return nil, errNoTransportSecurity
  155. }
  156. if cc.dopts.copts.TransportCredentials != nil && cc.dopts.copts.CredsBundle != nil {
  157. return nil, errTransportCredsAndBundle
  158. }
  159. } else {
  160. if cc.dopts.copts.TransportCredentials != nil || cc.dopts.copts.CredsBundle != nil {
  161. return nil, errCredentialsConflict
  162. }
  163. for _, cd := range cc.dopts.copts.PerRPCCredentials {
  164. if cd.RequireTransportSecurity() {
  165. return nil, errTransportCredentialsMissing
  166. }
  167. }
  168. }
  169. if cc.dopts.defaultServiceConfigRawJSON != nil {
  170. scpr := parseServiceConfig(*cc.dopts.defaultServiceConfigRawJSON)
  171. if scpr.Err != nil {
  172. return nil, fmt.Errorf("%s: %v", invalidDefaultServiceConfigErrPrefix, scpr.Err)
  173. }
  174. cc.dopts.defaultServiceConfig, _ = scpr.Config.(*ServiceConfig)
  175. }
  176. cc.mkp = cc.dopts.copts.KeepaliveParams
  177. if cc.dopts.copts.Dialer == nil {
  178. cc.dopts.copts.Dialer = func(ctx context.Context, addr string) (net.Conn, error) {
  179. network, addr := parseDialTarget(addr)
  180. return (&net.Dialer{}).DialContext(ctx, network, addr)
  181. }
  182. if cc.dopts.withProxy {
  183. cc.dopts.copts.Dialer = newProxyDialer(cc.dopts.copts.Dialer)
  184. }
  185. }
  186. if cc.dopts.copts.UserAgent != "" {
  187. cc.dopts.copts.UserAgent += " " + grpcUA
  188. } else {
  189. cc.dopts.copts.UserAgent = grpcUA
  190. }
  191. if cc.dopts.timeout > 0 {
  192. var cancel context.CancelFunc
  193. ctx, cancel = context.WithTimeout(ctx, cc.dopts.timeout)
  194. defer cancel()
  195. }
  196. defer func() {
  197. select {
  198. case <-ctx.Done():
  199. switch {
  200. case ctx.Err() == err:
  201. conn = nil
  202. case err == nil || !cc.dopts.returnLastError:
  203. conn, err = nil, ctx.Err()
  204. default:
  205. conn, err = nil, fmt.Errorf("%v: %v", ctx.Err(), err)
  206. }
  207. default:
  208. }
  209. }()
  210. scSet := false
  211. if cc.dopts.scChan != nil {
  212. // Try to get an initial service config.
  213. select {
  214. case sc, ok := <-cc.dopts.scChan:
  215. if ok {
  216. cc.sc = &sc
  217. scSet = true
  218. }
  219. default:
  220. }
  221. }
  222. if cc.dopts.bs == nil {
  223. cc.dopts.bs = backoff.DefaultExponential
  224. }
  225. // Determine the resolver to use.
  226. cc.parsedTarget = grpcutil.ParseTarget(cc.target)
  227. unixScheme := strings.HasPrefix(cc.target, "unix:")
  228. channelz.Infof(logger, cc.channelzID, "parsed scheme: %q", cc.parsedTarget.Scheme)
  229. resolverBuilder := cc.getResolver(cc.parsedTarget.Scheme)
  230. if resolverBuilder == nil {
  231. // If resolver builder is still nil, the parsed target's scheme is
  232. // not registered. Fallback to default resolver and set Endpoint to
  233. // the original target.
  234. channelz.Infof(logger, cc.channelzID, "scheme %q not registered, fallback to default scheme", cc.parsedTarget.Scheme)
  235. cc.parsedTarget = resolver.Target{
  236. Scheme: resolver.GetDefaultScheme(),
  237. Endpoint: target,
  238. }
  239. resolverBuilder = cc.getResolver(cc.parsedTarget.Scheme)
  240. if resolverBuilder == nil {
  241. return nil, fmt.Errorf("could not get resolver for default scheme: %q", cc.parsedTarget.Scheme)
  242. }
  243. }
  244. creds := cc.dopts.copts.TransportCredentials
  245. if creds != nil && creds.Info().ServerName != "" {
  246. cc.authority = creds.Info().ServerName
  247. } else if cc.dopts.insecure && cc.dopts.authority != "" {
  248. cc.authority = cc.dopts.authority
  249. } else if unixScheme {
  250. cc.authority = "localhost"
  251. } else {
  252. // Use endpoint from "scheme://authority/endpoint" as the default
  253. // authority for ClientConn.
  254. cc.authority = cc.parsedTarget.Endpoint
  255. }
  256. if cc.dopts.scChan != nil && !scSet {
  257. // Blocking wait for the initial service config.
  258. select {
  259. case sc, ok := <-cc.dopts.scChan:
  260. if ok {
  261. cc.sc = &sc
  262. }
  263. case <-ctx.Done():
  264. return nil, ctx.Err()
  265. }
  266. }
  267. if cc.dopts.scChan != nil {
  268. go cc.scWatcher()
  269. }
  270. var credsClone credentials.TransportCredentials
  271. if creds := cc.dopts.copts.TransportCredentials; creds != nil {
  272. credsClone = creds.Clone()
  273. }
  274. cc.balancerBuildOpts = balancer.BuildOptions{
  275. DialCreds: credsClone,
  276. CredsBundle: cc.dopts.copts.CredsBundle,
  277. Dialer: cc.dopts.copts.Dialer,
  278. ChannelzParentID: cc.channelzID,
  279. Target: cc.parsedTarget,
  280. }
  281. // Build the resolver.
  282. rWrapper, err := newCCResolverWrapper(cc, resolverBuilder)
  283. if err != nil {
  284. return nil, fmt.Errorf("failed to build resolver: %v", err)
  285. }
  286. cc.mu.Lock()
  287. cc.resolverWrapper = rWrapper
  288. cc.mu.Unlock()
  289. // A blocking dial blocks until the clientConn is ready.
  290. if cc.dopts.block {
  291. for {
  292. s := cc.GetState()
  293. if s == connectivity.Ready {
  294. break
  295. } else if cc.dopts.copts.FailOnNonTempDialError && s == connectivity.TransientFailure {
  296. if err = cc.connectionError(); err != nil {
  297. terr, ok := err.(interface {
  298. Temporary() bool
  299. })
  300. if ok && !terr.Temporary() {
  301. return nil, err
  302. }
  303. }
  304. }
  305. if !cc.WaitForStateChange(ctx, s) {
  306. // ctx got timeout or canceled.
  307. if err = cc.connectionError(); err != nil && cc.dopts.returnLastError {
  308. return nil, err
  309. }
  310. return nil, ctx.Err()
  311. }
  312. }
  313. }
  314. return cc, nil
  315. }
  316. // chainUnaryClientInterceptors chains all unary client interceptors into one.
  317. func chainUnaryClientInterceptors(cc *ClientConn) {
  318. interceptors := cc.dopts.chainUnaryInts
  319. // Prepend dopts.unaryInt to the chaining interceptors if it exists, since unaryInt will
  320. // be executed before any other chained interceptors.
  321. if cc.dopts.unaryInt != nil {
  322. interceptors = append([]UnaryClientInterceptor{cc.dopts.unaryInt}, interceptors...)
  323. }
  324. var chainedInt UnaryClientInterceptor
  325. if len(interceptors) == 0 {
  326. chainedInt = nil
  327. } else if len(interceptors) == 1 {
  328. chainedInt = interceptors[0]
  329. } else {
  330. chainedInt = func(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, invoker UnaryInvoker, opts ...CallOption) error {
  331. return interceptors[0](ctx, method, req, reply, cc, getChainUnaryInvoker(interceptors, 0, invoker), opts...)
  332. }
  333. }
  334. cc.dopts.unaryInt = chainedInt
  335. }
  336. // getChainUnaryInvoker recursively generate the chained unary invoker.
  337. func getChainUnaryInvoker(interceptors []UnaryClientInterceptor, curr int, finalInvoker UnaryInvoker) UnaryInvoker {
  338. if curr == len(interceptors)-1 {
  339. return finalInvoker
  340. }
  341. return func(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, opts ...CallOption) error {
  342. return interceptors[curr+1](ctx, method, req, reply, cc, getChainUnaryInvoker(interceptors, curr+1, finalInvoker), opts...)
  343. }
  344. }
  345. // chainStreamClientInterceptors chains all stream client interceptors into one.
  346. func chainStreamClientInterceptors(cc *ClientConn) {
  347. interceptors := cc.dopts.chainStreamInts
  348. // Prepend dopts.streamInt to the chaining interceptors if it exists, since streamInt will
  349. // be executed before any other chained interceptors.
  350. if cc.dopts.streamInt != nil {
  351. interceptors = append([]StreamClientInterceptor{cc.dopts.streamInt}, interceptors...)
  352. }
  353. var chainedInt StreamClientInterceptor
  354. if len(interceptors) == 0 {
  355. chainedInt = nil
  356. } else if len(interceptors) == 1 {
  357. chainedInt = interceptors[0]
  358. } else {
  359. chainedInt = func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, streamer Streamer, opts ...CallOption) (ClientStream, error) {
  360. return interceptors[0](ctx, desc, cc, method, getChainStreamer(interceptors, 0, streamer), opts...)
  361. }
  362. }
  363. cc.dopts.streamInt = chainedInt
  364. }
  365. // getChainStreamer recursively generate the chained client stream constructor.
  366. func getChainStreamer(interceptors []StreamClientInterceptor, curr int, finalStreamer Streamer) Streamer {
  367. if curr == len(interceptors)-1 {
  368. return finalStreamer
  369. }
  370. return func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error) {
  371. return interceptors[curr+1](ctx, desc, cc, method, getChainStreamer(interceptors, curr+1, finalStreamer), opts...)
  372. }
  373. }
  374. // connectivityStateManager keeps the connectivity.State of ClientConn.
  375. // This struct will eventually be exported so the balancers can access it.
  376. type connectivityStateManager struct {
  377. mu sync.Mutex
  378. state connectivity.State
  379. notifyChan chan struct{}
  380. channelzID int64
  381. }
  382. // updateState updates the connectivity.State of ClientConn.
  383. // If there's a change it notifies goroutines waiting on state change to
  384. // happen.
  385. func (csm *connectivityStateManager) updateState(state connectivity.State) {
  386. csm.mu.Lock()
  387. defer csm.mu.Unlock()
  388. if csm.state == connectivity.Shutdown {
  389. return
  390. }
  391. if csm.state == state {
  392. return
  393. }
  394. csm.state = state
  395. channelz.Infof(logger, csm.channelzID, "Channel Connectivity change to %v", state)
  396. if csm.notifyChan != nil {
  397. // There are other goroutines waiting on this channel.
  398. close(csm.notifyChan)
  399. csm.notifyChan = nil
  400. }
  401. }
  402. func (csm *connectivityStateManager) getState() connectivity.State {
  403. csm.mu.Lock()
  404. defer csm.mu.Unlock()
  405. return csm.state
  406. }
  407. func (csm *connectivityStateManager) getNotifyChan() <-chan struct{} {
  408. csm.mu.Lock()
  409. defer csm.mu.Unlock()
  410. if csm.notifyChan == nil {
  411. csm.notifyChan = make(chan struct{})
  412. }
  413. return csm.notifyChan
  414. }
  415. // ClientConnInterface defines the functions clients need to perform unary and
  416. // streaming RPCs. It is implemented by *ClientConn, and is only intended to
  417. // be referenced by generated code.
  418. type ClientConnInterface interface {
  419. // Invoke performs a unary RPC and returns after the response is received
  420. // into reply.
  421. Invoke(ctx context.Context, method string, args interface{}, reply interface{}, opts ...CallOption) error
  422. // NewStream begins a streaming RPC.
  423. NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error)
  424. }
  425. // Assert *ClientConn implements ClientConnInterface.
  426. var _ ClientConnInterface = (*ClientConn)(nil)
  427. // ClientConn represents a virtual connection to a conceptual endpoint, to
  428. // perform RPCs.
  429. //
  430. // A ClientConn is free to have zero or more actual connections to the endpoint
  431. // based on configuration, load, etc. It is also free to determine which actual
  432. // endpoints to use and may change it every RPC, permitting client-side load
  433. // balancing.
  434. //
  435. // A ClientConn encapsulates a range of functionality including name
  436. // resolution, TCP connection establishment (with retries and backoff) and TLS
  437. // handshakes. It also handles errors on established connections by
  438. // re-resolving the name and reconnecting.
  439. type ClientConn struct {
  440. ctx context.Context
  441. cancel context.CancelFunc
  442. target string
  443. parsedTarget resolver.Target
  444. authority string
  445. dopts dialOptions
  446. csMgr *connectivityStateManager
  447. balancerBuildOpts balancer.BuildOptions
  448. blockingpicker *pickerWrapper
  449. mu sync.RWMutex
  450. resolverWrapper *ccResolverWrapper
  451. sc *ServiceConfig
  452. conns map[*addrConn]struct{}
  453. // Keepalive parameter can be updated if a GoAway is received.
  454. mkp keepalive.ClientParameters
  455. curBalancerName string
  456. balancerWrapper *ccBalancerWrapper
  457. retryThrottler atomic.Value
  458. firstResolveEvent *grpcsync.Event
  459. channelzID int64 // channelz unique identification number
  460. czData *channelzData
  461. lceMu sync.Mutex // protects lastConnectionError
  462. lastConnectionError error
  463. }
  464. // WaitForStateChange waits until the connectivity.State of ClientConn changes from sourceState or
  465. // ctx expires. A true value is returned in former case and false in latter.
  466. // This is an EXPERIMENTAL API.
  467. func (cc *ClientConn) WaitForStateChange(ctx context.Context, sourceState connectivity.State) bool {
  468. ch := cc.csMgr.getNotifyChan()
  469. if cc.csMgr.getState() != sourceState {
  470. return true
  471. }
  472. select {
  473. case <-ctx.Done():
  474. return false
  475. case <-ch:
  476. return true
  477. }
  478. }
  479. // GetState returns the connectivity.State of ClientConn.
  480. // This is an EXPERIMENTAL API.
  481. func (cc *ClientConn) GetState() connectivity.State {
  482. return cc.csMgr.getState()
  483. }
  484. func (cc *ClientConn) scWatcher() {
  485. for {
  486. select {
  487. case sc, ok := <-cc.dopts.scChan:
  488. if !ok {
  489. return
  490. }
  491. cc.mu.Lock()
  492. // TODO: load balance policy runtime change is ignored.
  493. // We may revisit this decision in the future.
  494. cc.sc = &sc
  495. cc.mu.Unlock()
  496. case <-cc.ctx.Done():
  497. return
  498. }
  499. }
  500. }
  501. // waitForResolvedAddrs blocks until the resolver has provided addresses or the
  502. // context expires. Returns nil unless the context expires first; otherwise
  503. // returns a status error based on the context.
  504. func (cc *ClientConn) waitForResolvedAddrs(ctx context.Context) error {
  505. // This is on the RPC path, so we use a fast path to avoid the
  506. // more-expensive "select" below after the resolver has returned once.
  507. if cc.firstResolveEvent.HasFired() {
  508. return nil
  509. }
  510. select {
  511. case <-cc.firstResolveEvent.Done():
  512. return nil
  513. case <-ctx.Done():
  514. return status.FromContextError(ctx.Err()).Err()
  515. case <-cc.ctx.Done():
  516. return ErrClientConnClosing
  517. }
  518. }
  519. var emptyServiceConfig *ServiceConfig
  520. func init() {
  521. cfg := parseServiceConfig("{}")
  522. if cfg.Err != nil {
  523. panic(fmt.Sprintf("impossible error parsing empty service config: %v", cfg.Err))
  524. }
  525. emptyServiceConfig = cfg.Config.(*ServiceConfig)
  526. }
  527. func (cc *ClientConn) maybeApplyDefaultServiceConfig(addrs []resolver.Address) {
  528. if cc.sc != nil {
  529. cc.applyServiceConfigAndBalancer(cc.sc, addrs)
  530. return
  531. }
  532. if cc.dopts.defaultServiceConfig != nil {
  533. cc.applyServiceConfigAndBalancer(cc.dopts.defaultServiceConfig, addrs)
  534. } else {
  535. cc.applyServiceConfigAndBalancer(emptyServiceConfig, addrs)
  536. }
  537. }
  538. func (cc *ClientConn) updateResolverState(s resolver.State, err error) error {
  539. defer cc.firstResolveEvent.Fire()
  540. cc.mu.Lock()
  541. // Check if the ClientConn is already closed. Some fields (e.g.
  542. // balancerWrapper) are set to nil when closing the ClientConn, and could
  543. // cause nil pointer panic if we don't have this check.
  544. if cc.conns == nil {
  545. cc.mu.Unlock()
  546. return nil
  547. }
  548. if err != nil {
  549. // May need to apply the initial service config in case the resolver
  550. // doesn't support service configs, or doesn't provide a service config
  551. // with the new addresses.
  552. cc.maybeApplyDefaultServiceConfig(nil)
  553. if cc.balancerWrapper != nil {
  554. cc.balancerWrapper.resolverError(err)
  555. }
  556. // No addresses are valid with err set; return early.
  557. cc.mu.Unlock()
  558. return balancer.ErrBadResolverState
  559. }
  560. var ret error
  561. if cc.dopts.disableServiceConfig || s.ServiceConfig == nil {
  562. cc.maybeApplyDefaultServiceConfig(s.Addresses)
  563. // TODO: do we need to apply a failing LB policy if there is no
  564. // default, per the error handling design?
  565. } else {
  566. if sc, ok := s.ServiceConfig.Config.(*ServiceConfig); s.ServiceConfig.Err == nil && ok {
  567. cc.applyServiceConfigAndBalancer(sc, s.Addresses)
  568. } else {
  569. ret = balancer.ErrBadResolverState
  570. if cc.balancerWrapper == nil {
  571. var err error
  572. if s.ServiceConfig.Err != nil {
  573. err = status.Errorf(codes.Unavailable, "error parsing service config: %v", s.ServiceConfig.Err)
  574. } else {
  575. err = status.Errorf(codes.Unavailable, "illegal service config type: %T", s.ServiceConfig.Config)
  576. }
  577. cc.blockingpicker.updatePicker(base.NewErrPicker(err))
  578. cc.csMgr.updateState(connectivity.TransientFailure)
  579. cc.mu.Unlock()
  580. return ret
  581. }
  582. }
  583. }
  584. var balCfg serviceconfig.LoadBalancingConfig
  585. if cc.dopts.balancerBuilder == nil && cc.sc != nil && cc.sc.lbConfig != nil {
  586. balCfg = cc.sc.lbConfig.cfg
  587. }
  588. cbn := cc.curBalancerName
  589. bw := cc.balancerWrapper
  590. cc.mu.Unlock()
  591. if cbn != grpclbName {
  592. // Filter any grpclb addresses since we don't have the grpclb balancer.
  593. for i := 0; i < len(s.Addresses); {
  594. if s.Addresses[i].Type == resolver.GRPCLB {
  595. copy(s.Addresses[i:], s.Addresses[i+1:])
  596. s.Addresses = s.Addresses[:len(s.Addresses)-1]
  597. continue
  598. }
  599. i++
  600. }
  601. }
  602. uccsErr := bw.updateClientConnState(&balancer.ClientConnState{ResolverState: s, BalancerConfig: balCfg})
  603. if ret == nil {
  604. ret = uccsErr // prefer ErrBadResolver state since any other error is
  605. // currently meaningless to the caller.
  606. }
  607. return ret
  608. }
  609. // switchBalancer starts the switching from current balancer to the balancer
  610. // with the given name.
  611. //
  612. // It will NOT send the current address list to the new balancer. If needed,
  613. // caller of this function should send address list to the new balancer after
  614. // this function returns.
  615. //
  616. // Caller must hold cc.mu.
  617. func (cc *ClientConn) switchBalancer(name string) {
  618. if strings.EqualFold(cc.curBalancerName, name) {
  619. return
  620. }
  621. channelz.Infof(logger, cc.channelzID, "ClientConn switching balancer to %q", name)
  622. if cc.dopts.balancerBuilder != nil {
  623. channelz.Info(logger, cc.channelzID, "ignoring balancer switching: Balancer DialOption used instead")
  624. return
  625. }
  626. if cc.balancerWrapper != nil {
  627. cc.balancerWrapper.close()
  628. }
  629. builder := balancer.Get(name)
  630. if builder == nil {
  631. channelz.Warningf(logger, cc.channelzID, "Channel switches to new LB policy %q due to fallback from invalid balancer name", PickFirstBalancerName)
  632. channelz.Infof(logger, cc.channelzID, "failed to get balancer builder for: %v, using pick_first instead", name)
  633. builder = newPickfirstBuilder()
  634. } else {
  635. channelz.Infof(logger, cc.channelzID, "Channel switches to new LB policy %q", name)
  636. }
  637. cc.curBalancerName = builder.Name()
  638. cc.balancerWrapper = newCCBalancerWrapper(cc, builder, cc.balancerBuildOpts)
  639. }
  640. func (cc *ClientConn) handleSubConnStateChange(sc balancer.SubConn, s connectivity.State, err error) {
  641. cc.mu.Lock()
  642. if cc.conns == nil {
  643. cc.mu.Unlock()
  644. return
  645. }
  646. // TODO(bar switching) send updates to all balancer wrappers when balancer
  647. // gracefully switching is supported.
  648. cc.balancerWrapper.handleSubConnStateChange(sc, s, err)
  649. cc.mu.Unlock()
  650. }
  651. // newAddrConn creates an addrConn for addrs and adds it to cc.conns.
  652. //
  653. // Caller needs to make sure len(addrs) > 0.
  654. func (cc *ClientConn) newAddrConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (*addrConn, error) {
  655. ac := &addrConn{
  656. state: connectivity.Idle,
  657. cc: cc,
  658. addrs: addrs,
  659. scopts: opts,
  660. dopts: cc.dopts,
  661. czData: new(channelzData),
  662. resetBackoff: make(chan struct{}),
  663. }
  664. ac.ctx, ac.cancel = context.WithCancel(cc.ctx)
  665. // Track ac in cc. This needs to be done before any getTransport(...) is called.
  666. cc.mu.Lock()
  667. if cc.conns == nil {
  668. cc.mu.Unlock()
  669. return nil, ErrClientConnClosing
  670. }
  671. if channelz.IsOn() {
  672. ac.channelzID = channelz.RegisterSubChannel(ac, cc.channelzID, "")
  673. channelz.AddTraceEvent(logger, ac.channelzID, 0, &channelz.TraceEventDesc{
  674. Desc: "Subchannel Created",
  675. Severity: channelz.CtINFO,
  676. Parent: &channelz.TraceEventDesc{
  677. Desc: fmt.Sprintf("Subchannel(id:%d) created", ac.channelzID),
  678. Severity: channelz.CtINFO,
  679. },
  680. })
  681. }
  682. cc.conns[ac] = struct{}{}
  683. cc.mu.Unlock()
  684. return ac, nil
  685. }
  686. // removeAddrConn removes the addrConn in the subConn from clientConn.
  687. // It also tears down the ac with the given error.
  688. func (cc *ClientConn) removeAddrConn(ac *addrConn, err error) {
  689. cc.mu.Lock()
  690. if cc.conns == nil {
  691. cc.mu.Unlock()
  692. return
  693. }
  694. delete(cc.conns, ac)
  695. cc.mu.Unlock()
  696. ac.tearDown(err)
  697. }
  698. func (cc *ClientConn) channelzMetric() *channelz.ChannelInternalMetric {
  699. return &channelz.ChannelInternalMetric{
  700. State: cc.GetState(),
  701. Target: cc.target,
  702. CallsStarted: atomic.LoadInt64(&cc.czData.callsStarted),
  703. CallsSucceeded: atomic.LoadInt64(&cc.czData.callsSucceeded),
  704. CallsFailed: atomic.LoadInt64(&cc.czData.callsFailed),
  705. LastCallStartedTimestamp: time.Unix(0, atomic.LoadInt64(&cc.czData.lastCallStartedTime)),
  706. }
  707. }
  708. // Target returns the target string of the ClientConn.
  709. // This is an EXPERIMENTAL API.
  710. func (cc *ClientConn) Target() string {
  711. return cc.target
  712. }
  713. func (cc *ClientConn) incrCallsStarted() {
  714. atomic.AddInt64(&cc.czData.callsStarted, 1)
  715. atomic.StoreInt64(&cc.czData.lastCallStartedTime, time.Now().UnixNano())
  716. }
  717. func (cc *ClientConn) incrCallsSucceeded() {
  718. atomic.AddInt64(&cc.czData.callsSucceeded, 1)
  719. }
  720. func (cc *ClientConn) incrCallsFailed() {
  721. atomic.AddInt64(&cc.czData.callsFailed, 1)
  722. }
  723. // connect starts creating a transport.
  724. // It does nothing if the ac is not IDLE.
  725. // TODO(bar) Move this to the addrConn section.
  726. func (ac *addrConn) connect() error {
  727. ac.mu.Lock()
  728. if ac.state == connectivity.Shutdown {
  729. ac.mu.Unlock()
  730. return errConnClosing
  731. }
  732. if ac.state != connectivity.Idle {
  733. ac.mu.Unlock()
  734. return nil
  735. }
  736. // Update connectivity state within the lock to prevent subsequent or
  737. // concurrent calls from resetting the transport more than once.
  738. ac.updateConnectivityState(connectivity.Connecting, nil)
  739. ac.mu.Unlock()
  740. // Start a goroutine connecting to the server asynchronously.
  741. go ac.resetTransport()
  742. return nil
  743. }
  744. // tryUpdateAddrs tries to update ac.addrs with the new addresses list.
  745. //
  746. // If ac is Connecting, it returns false. The caller should tear down the ac and
  747. // create a new one. Note that the backoff will be reset when this happens.
  748. //
  749. // If ac is TransientFailure, it updates ac.addrs and returns true. The updated
  750. // addresses will be picked up by retry in the next iteration after backoff.
  751. //
  752. // If ac is Shutdown or Idle, it updates ac.addrs and returns true.
  753. //
  754. // If ac is Ready, it checks whether current connected address of ac is in the
  755. // new addrs list.
  756. // - If true, it updates ac.addrs and returns true. The ac will keep using
  757. // the existing connection.
  758. // - If false, it does nothing and returns false.
  759. func (ac *addrConn) tryUpdateAddrs(addrs []resolver.Address) bool {
  760. ac.mu.Lock()
  761. defer ac.mu.Unlock()
  762. channelz.Infof(logger, ac.channelzID, "addrConn: tryUpdateAddrs curAddr: %v, addrs: %v", ac.curAddr, addrs)
  763. if ac.state == connectivity.Shutdown ||
  764. ac.state == connectivity.TransientFailure ||
  765. ac.state == connectivity.Idle {
  766. ac.addrs = addrs
  767. return true
  768. }
  769. if ac.state == connectivity.Connecting {
  770. return false
  771. }
  772. // ac.state is Ready, try to find the connected address.
  773. var curAddrFound bool
  774. for _, a := range addrs {
  775. if reflect.DeepEqual(ac.curAddr, a) {
  776. curAddrFound = true
  777. break
  778. }
  779. }
  780. channelz.Infof(logger, ac.channelzID, "addrConn: tryUpdateAddrs curAddrFound: %v", curAddrFound)
  781. if curAddrFound {
  782. ac.addrs = addrs
  783. }
  784. return curAddrFound
  785. }
  786. // GetMethodConfig gets the method config of the input method.
  787. // If there's an exact match for input method (i.e. /service/method), we return
  788. // the corresponding MethodConfig.
  789. // If there isn't an exact match for the input method, we look for the service's default
  790. // config under the service (i.e /service/) and then for the default for all services (empty string).
  791. //
  792. // If there is a default MethodConfig for the service, we return it.
  793. // Otherwise, we return an empty MethodConfig.
  794. func (cc *ClientConn) GetMethodConfig(method string) MethodConfig {
  795. // TODO: Avoid the locking here.
  796. cc.mu.RLock()
  797. defer cc.mu.RUnlock()
  798. if cc.sc == nil {
  799. return MethodConfig{}
  800. }
  801. if m, ok := cc.sc.Methods[method]; ok {
  802. return m
  803. }
  804. i := strings.LastIndex(method, "/")
  805. if m, ok := cc.sc.Methods[method[:i+1]]; ok {
  806. return m
  807. }
  808. return cc.sc.Methods[""]
  809. }
  810. func (cc *ClientConn) healthCheckConfig() *healthCheckConfig {
  811. cc.mu.RLock()
  812. defer cc.mu.RUnlock()
  813. if cc.sc == nil {
  814. return nil
  815. }
  816. return cc.sc.healthCheckConfig
  817. }
  818. func (cc *ClientConn) getTransport(ctx context.Context, failfast bool, method string) (transport.ClientTransport, func(balancer.DoneInfo), error) {
  819. t, done, err := cc.blockingpicker.pick(ctx, failfast, balancer.PickInfo{
  820. Ctx: ctx,
  821. FullMethodName: method,
  822. })
  823. if err != nil {
  824. return nil, nil, toRPCErr(err)
  825. }
  826. return t, done, nil
  827. }
  828. func (cc *ClientConn) applyServiceConfigAndBalancer(sc *ServiceConfig, addrs []resolver.Address) {
  829. if sc == nil {
  830. // should never reach here.
  831. return
  832. }
  833. cc.sc = sc
  834. if cc.sc.retryThrottling != nil {
  835. newThrottler := &retryThrottler{
  836. tokens: cc.sc.retryThrottling.MaxTokens,
  837. max: cc.sc.retryThrottling.MaxTokens,
  838. thresh: cc.sc.retryThrottling.MaxTokens / 2,
  839. ratio: cc.sc.retryThrottling.TokenRatio,
  840. }
  841. cc.retryThrottler.Store(newThrottler)
  842. } else {
  843. cc.retryThrottler.Store((*retryThrottler)(nil))
  844. }
  845. if cc.dopts.balancerBuilder == nil {
  846. // Only look at balancer types and switch balancer if balancer dial
  847. // option is not set.
  848. var newBalancerName string
  849. if cc.sc != nil && cc.sc.lbConfig != nil {
  850. newBalancerName = cc.sc.lbConfig.name
  851. } else {
  852. var isGRPCLB bool
  853. for _, a := range addrs {
  854. if a.Type == resolver.GRPCLB {
  855. isGRPCLB = true
  856. break
  857. }
  858. }
  859. if isGRPCLB {
  860. newBalancerName = grpclbName
  861. } else if cc.sc != nil && cc.sc.LB != nil {
  862. newBalancerName = *cc.sc.LB
  863. } else {
  864. newBalancerName = PickFirstBalancerName
  865. }
  866. }
  867. cc.switchBalancer(newBalancerName)
  868. } else if cc.balancerWrapper == nil {
  869. // Balancer dial option was set, and this is the first time handling
  870. // resolved addresses. Build a balancer with dopts.balancerBuilder.
  871. cc.curBalancerName = cc.dopts.balancerBuilder.Name()
  872. cc.balancerWrapper = newCCBalancerWrapper(cc, cc.dopts.balancerBuilder, cc.balancerBuildOpts)
  873. }
  874. }
  875. func (cc *ClientConn) resolveNow(o resolver.ResolveNowOptions) {
  876. cc.mu.RLock()
  877. r := cc.resolverWrapper
  878. cc.mu.RUnlock()
  879. if r == nil {
  880. return
  881. }
  882. go r.resolveNow(o)
  883. }
  884. // ResetConnectBackoff wakes up all subchannels in transient failure and causes
  885. // them to attempt another connection immediately. It also resets the backoff
  886. // times used for subsequent attempts regardless of the current state.
  887. //
  888. // In general, this function should not be used. Typical service or network
  889. // outages result in a reasonable client reconnection strategy by default.
  890. // However, if a previously unavailable network becomes available, this may be
  891. // used to trigger an immediate reconnect.
  892. //
  893. // This API is EXPERIMENTAL.
  894. func (cc *ClientConn) ResetConnectBackoff() {
  895. cc.mu.Lock()
  896. conns := cc.conns
  897. cc.mu.Unlock()
  898. for ac := range conns {
  899. ac.resetConnectBackoff()
  900. }
  901. }
  902. // Close tears down the ClientConn and all underlying connections.
  903. func (cc *ClientConn) Close() error {
  904. defer cc.cancel()
  905. cc.mu.Lock()
  906. if cc.conns == nil {
  907. cc.mu.Unlock()
  908. return ErrClientConnClosing
  909. }
  910. conns := cc.conns
  911. cc.conns = nil
  912. cc.csMgr.updateState(connectivity.Shutdown)
  913. rWrapper := cc.resolverWrapper
  914. cc.resolverWrapper = nil
  915. bWrapper := cc.balancerWrapper
  916. cc.balancerWrapper = nil
  917. cc.mu.Unlock()
  918. cc.blockingpicker.close()
  919. if rWrapper != nil {
  920. rWrapper.close()
  921. }
  922. if bWrapper != nil {
  923. bWrapper.close()
  924. }
  925. for ac := range conns {
  926. ac.tearDown(ErrClientConnClosing)
  927. }
  928. if channelz.IsOn() {
  929. ted := &channelz.TraceEventDesc{
  930. Desc: "Channel Deleted",
  931. Severity: channelz.CtINFO,
  932. }
  933. if cc.dopts.channelzParentID != 0 {
  934. ted.Parent = &channelz.TraceEventDesc{
  935. Desc: fmt.Sprintf("Nested channel(id:%d) deleted", cc.channelzID),
  936. Severity: channelz.CtINFO,
  937. }
  938. }
  939. channelz.AddTraceEvent(logger, cc.channelzID, 0, ted)
  940. // TraceEvent needs to be called before RemoveEntry, as TraceEvent may add trace reference to
  941. // the entity being deleted, and thus prevent it from being deleted right away.
  942. channelz.RemoveEntry(cc.channelzID)
  943. }
  944. return nil
  945. }
  946. // addrConn is a network connection to a given address.
  947. type addrConn struct {
  948. ctx context.Context
  949. cancel context.CancelFunc
  950. cc *ClientConn
  951. dopts dialOptions
  952. acbw balancer.SubConn
  953. scopts balancer.NewSubConnOptions
  954. // transport is set when there's a viable transport (note: ac state may not be READY as LB channel
  955. // health checking may require server to report healthy to set ac to READY), and is reset
  956. // to nil when the current transport should no longer be used to create a stream (e.g. after GoAway
  957. // is received, transport is closed, ac has been torn down).
  958. transport transport.ClientTransport // The current transport.
  959. mu sync.Mutex
  960. curAddr resolver.Address // The current address.
  961. addrs []resolver.Address // All addresses that the resolver resolved to.
  962. // Use updateConnectivityState for updating addrConn's connectivity state.
  963. state connectivity.State
  964. backoffIdx int // Needs to be stateful for resetConnectBackoff.
  965. resetBackoff chan struct{}
  966. channelzID int64 // channelz unique identification number.
  967. czData *channelzData
  968. }
  969. // Note: this requires a lock on ac.mu.
  970. func (ac *addrConn) updateConnectivityState(s connectivity.State, lastErr error) {
  971. if ac.state == s {
  972. return
  973. }
  974. ac.state = s
  975. channelz.Infof(logger, ac.channelzID, "Subchannel Connectivity change to %v", s)
  976. ac.cc.handleSubConnStateChange(ac.acbw, s, lastErr)
  977. }
  978. // adjustParams updates parameters used to create transports upon
  979. // receiving a GoAway.
  980. func (ac *addrConn) adjustParams(r transport.GoAwayReason) {
  981. switch r {
  982. case transport.GoAwayTooManyPings:
  983. v := 2 * ac.dopts.copts.KeepaliveParams.Time
  984. ac.cc.mu.Lock()
  985. if v > ac.cc.mkp.Time {
  986. ac.cc.mkp.Time = v
  987. }
  988. ac.cc.mu.Unlock()
  989. }
  990. }
  991. func (ac *addrConn) resetTransport() {
  992. for i := 0; ; i++ {
  993. if i > 0 {
  994. ac.cc.resolveNow(resolver.ResolveNowOptions{})
  995. }
  996. ac.mu.Lock()
  997. if ac.state == connectivity.Shutdown {
  998. ac.mu.Unlock()
  999. return
  1000. }
  1001. addrs := ac.addrs
  1002. backoffFor := ac.dopts.bs.Backoff(ac.backoffIdx)
  1003. // This will be the duration that dial gets to finish.
  1004. dialDuration := minConnectTimeout
  1005. if ac.dopts.minConnectTimeout != nil {
  1006. dialDuration = ac.dopts.minConnectTimeout()
  1007. }
  1008. if dialDuration < backoffFor {
  1009. // Give dial more time as we keep failing to connect.
  1010. dialDuration = backoffFor
  1011. }
  1012. // We can potentially spend all the time trying the first address, and
  1013. // if the server accepts the connection and then hangs, the following
  1014. // addresses will never be tried.
  1015. //
  1016. // The spec doesn't mention what should be done for multiple addresses.
  1017. // https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md#proposed-backoff-algorithm
  1018. connectDeadline := time.Now().Add(dialDuration)
  1019. ac.updateConnectivityState(connectivity.Connecting, nil)
  1020. ac.transport = nil
  1021. ac.mu.Unlock()
  1022. newTr, addr, reconnect, err := ac.tryAllAddrs(addrs, connectDeadline)
  1023. if err != nil {
  1024. // After exhausting all addresses, the addrConn enters
  1025. // TRANSIENT_FAILURE.
  1026. ac.mu.Lock()
  1027. if ac.state == connectivity.Shutdown {
  1028. ac.mu.Unlock()
  1029. return
  1030. }
  1031. ac.updateConnectivityState(connectivity.TransientFailure, err)
  1032. // Backoff.
  1033. b := ac.resetBackoff
  1034. ac.mu.Unlock()
  1035. timer := time.NewTimer(backoffFor)
  1036. select {
  1037. case <-timer.C:
  1038. ac.mu.Lock()
  1039. ac.backoffIdx++
  1040. ac.mu.Unlock()
  1041. case <-b:
  1042. timer.Stop()
  1043. case <-ac.ctx.Done():
  1044. timer.Stop()
  1045. return
  1046. }
  1047. continue
  1048. }
  1049. ac.mu.Lock()
  1050. if ac.state == connectivity.Shutdown {
  1051. ac.mu.Unlock()
  1052. newTr.Close()
  1053. return
  1054. }
  1055. ac.curAddr = addr
  1056. ac.transport = newTr
  1057. ac.backoffIdx = 0
  1058. hctx, hcancel := context.WithCancel(ac.ctx)
  1059. ac.startHealthCheck(hctx)
  1060. ac.mu.Unlock()
  1061. // Block until the created transport is down. And when this happens,
  1062. // we restart from the top of the addr list.
  1063. <-reconnect.Done()
  1064. hcancel()
  1065. // restart connecting - the top of the loop will set state to
  1066. // CONNECTING. This is against the current connectivity semantics doc,
  1067. // however it allows for graceful behavior for RPCs not yet dispatched
  1068. // - unfortunate timing would otherwise lead to the RPC failing even
  1069. // though the TRANSIENT_FAILURE state (called for by the doc) would be
  1070. // instantaneous.
  1071. //
  1072. // Ideally we should transition to Idle here and block until there is
  1073. // RPC activity that leads to the balancer requesting a reconnect of
  1074. // the associated SubConn.
  1075. }
  1076. }
  1077. // tryAllAddrs tries to creates a connection to the addresses, and stop when at the
  1078. // first successful one. It returns the transport, the address and a Event in
  1079. // the successful case. The Event fires when the returned transport disconnects.
  1080. func (ac *addrConn) tryAllAddrs(addrs []resolver.Address, connectDeadline time.Time) (transport.ClientTransport, resolver.Address, *grpcsync.Event, error) {
  1081. var firstConnErr error
  1082. for _, addr := range addrs {
  1083. ac.mu.Lock()
  1084. if ac.state == connectivity.Shutdown {
  1085. ac.mu.Unlock()
  1086. return nil, resolver.Address{}, nil, errConnClosing
  1087. }
  1088. ac.cc.mu.RLock()
  1089. ac.dopts.copts.KeepaliveParams = ac.cc.mkp
  1090. ac.cc.mu.RUnlock()
  1091. copts := ac.dopts.copts
  1092. if ac.scopts.CredsBundle != nil {
  1093. copts.CredsBundle = ac.scopts.CredsBundle
  1094. }
  1095. ac.mu.Unlock()
  1096. channelz.Infof(logger, ac.channelzID, "Subchannel picks a new address %q to connect", addr.Addr)
  1097. newTr, reconnect, err := ac.createTransport(addr, copts, connectDeadline)
  1098. if err == nil {
  1099. return newTr, addr, reconnect, nil
  1100. }
  1101. if firstConnErr == nil {
  1102. firstConnErr = err
  1103. }
  1104. ac.cc.updateConnectionError(err)
  1105. }
  1106. // Couldn't connect to any address.
  1107. return nil, resolver.Address{}, nil, firstConnErr
  1108. }
  1109. // createTransport creates a connection to addr. It returns the transport and a
  1110. // Event in the successful case. The Event fires when the returned transport
  1111. // disconnects.
  1112. func (ac *addrConn) createTransport(addr resolver.Address, copts transport.ConnectOptions, connectDeadline time.Time) (transport.ClientTransport, *grpcsync.Event, error) {
  1113. prefaceReceived := make(chan struct{})
  1114. onCloseCalled := make(chan struct{})
  1115. reconnect := grpcsync.NewEvent()
  1116. // addr.ServerName takes precedent over ClientConn authority, if present.
  1117. if addr.ServerName == "" {
  1118. addr.ServerName = ac.cc.authority
  1119. }
  1120. once := sync.Once{}
  1121. onGoAway := func(r transport.GoAwayReason) {
  1122. ac.mu.Lock()
  1123. ac.adjustParams(r)
  1124. once.Do(func() {
  1125. if ac.state == connectivity.Ready {
  1126. // Prevent this SubConn from being used for new RPCs by setting its
  1127. // state to Connecting.
  1128. //
  1129. // TODO: this should be Idle when grpc-go properly supports it.
  1130. ac.updateConnectivityState(connectivity.Connecting, nil)
  1131. }
  1132. })
  1133. ac.mu.Unlock()
  1134. reconnect.Fire()
  1135. }
  1136. onClose := func() {
  1137. ac.mu.Lock()
  1138. once.Do(func() {
  1139. if ac.state == connectivity.Ready {
  1140. // Prevent this SubConn from being used for new RPCs by setting its
  1141. // state to Connecting.
  1142. //
  1143. // TODO: this should be Idle when grpc-go properly supports it.
  1144. ac.updateConnectivityState(connectivity.Connecting, nil)
  1145. }
  1146. })
  1147. ac.mu.Unlock()
  1148. close(onCloseCalled)
  1149. reconnect.Fire()
  1150. }
  1151. onPrefaceReceipt := func() {
  1152. close(prefaceReceived)
  1153. }
  1154. connectCtx, cancel := context.WithDeadline(ac.ctx, connectDeadline)
  1155. defer cancel()
  1156. if channelz.IsOn() {
  1157. copts.ChannelzParentID = ac.channelzID
  1158. }
  1159. newTr, err := transport.NewClientTransport(connectCtx, ac.cc.ctx, addr, copts, onPrefaceReceipt, onGoAway, onClose)
  1160. if err != nil {
  1161. // newTr is either nil, or closed.
  1162. channelz.Warningf(logger, ac.channelzID, "grpc: addrConn.createTransport failed to connect to %v. Err: %v. Reconnecting...", addr, err)
  1163. return nil, nil, err
  1164. }
  1165. select {
  1166. case <-time.After(time.Until(connectDeadline)):
  1167. // We didn't get the preface in time.
  1168. newTr.Close()
  1169. channelz.Warningf(logger, ac.channelzID, "grpc: addrConn.createTransport failed to connect to %v: didn't receive server preface in time. Reconnecting...", addr)
  1170. return nil, nil, errors.New("timed out waiting for server handshake")
  1171. case <-prefaceReceived:
  1172. // We got the preface - huzzah! things are good.
  1173. case <-onCloseCalled:
  1174. // The transport has already closed - noop.
  1175. return nil, nil, errors.New("connection closed")
  1176. // TODO(deklerk) this should bail on ac.ctx.Done(). Add a test and fix.
  1177. }
  1178. return newTr, reconnect, nil
  1179. }
  1180. // startHealthCheck starts the health checking stream (RPC) to watch the health
  1181. // stats of this connection if health checking is requested and configured.
  1182. //
  1183. // LB channel health checking is enabled when all requirements below are met:
  1184. // 1. it is not disabled by the user with the WithDisableHealthCheck DialOption
  1185. // 2. internal.HealthCheckFunc is set by importing the grpc/health package
  1186. // 3. a service config with non-empty healthCheckConfig field is provided
  1187. // 4. the load balancer requests it
  1188. //
  1189. // It sets addrConn to READY if the health checking stream is not started.
  1190. //
  1191. // Caller must hold ac.mu.
  1192. func (ac *addrConn) startHealthCheck(ctx context.Context) {
  1193. var healthcheckManagingState bool
  1194. defer func() {
  1195. if !healthcheckManagingState {
  1196. ac.updateConnectivityState(connectivity.Ready, nil)
  1197. }
  1198. }()
  1199. if ac.cc.dopts.disableHealthCheck {
  1200. return
  1201. }
  1202. healthCheckConfig := ac.cc.healthCheckConfig()
  1203. if healthCheckConfig == nil {
  1204. return
  1205. }
  1206. if !ac.scopts.HealthCheckEnabled {
  1207. return
  1208. }
  1209. healthCheckFunc := ac.cc.dopts.healthCheckFunc
  1210. if healthCheckFunc == nil {
  1211. // The health package is not imported to set health check function.
  1212. //
  1213. // TODO: add a link to the health check doc in the error message.
  1214. channelz.Error(logger, ac.channelzID, "Health check is requested but health check function is not set.")
  1215. return
  1216. }
  1217. healthcheckManagingState = true
  1218. // Set up the health check helper functions.
  1219. currentTr := ac.transport
  1220. newStream := func(method string) (interface{}, error) {
  1221. ac.mu.Lock()
  1222. if ac.transport != currentTr {
  1223. ac.mu.Unlock()
  1224. return nil, status.Error(codes.Canceled, "the provided transport is no longer valid to use")
  1225. }
  1226. ac.mu.Unlock()
  1227. return newNonRetryClientStream(ctx, &StreamDesc{ServerStreams: true}, method, currentTr, ac)
  1228. }
  1229. setConnectivityState := func(s connectivity.State, lastErr error) {
  1230. ac.mu.Lock()
  1231. defer ac.mu.Unlock()
  1232. if ac.transport != currentTr {
  1233. return
  1234. }
  1235. ac.updateConnectivityState(s, lastErr)
  1236. }
  1237. // Start the health checking stream.
  1238. go func() {
  1239. err := ac.cc.dopts.healthCheckFunc(ctx, newStream, setConnectivityState, healthCheckConfig.ServiceName)
  1240. if err != nil {
  1241. if status.Code(err) == codes.Unimplemented {
  1242. channelz.Error(logger, ac.channelzID, "Subchannel health check is unimplemented at server side, thus health check is disabled")
  1243. } else {
  1244. channelz.Errorf(logger, ac.channelzID, "HealthCheckFunc exits with unexpected error %v", err)
  1245. }
  1246. }
  1247. }()
  1248. }
  1249. func (ac *addrConn) resetConnectBackoff() {
  1250. ac.mu.Lock()
  1251. close(ac.resetBackoff)
  1252. ac.backoffIdx = 0
  1253. ac.resetBackoff = make(chan struct{})
  1254. ac.mu.Unlock()
  1255. }
  1256. // getReadyTransport returns the transport if ac's state is READY.
  1257. // Otherwise it returns nil, false.
  1258. // If ac's state is IDLE, it will trigger ac to connect.
  1259. func (ac *addrConn) getReadyTransport() (transport.ClientTransport, bool) {
  1260. ac.mu.Lock()
  1261. if ac.state == connectivity.Ready && ac.transport != nil {
  1262. t := ac.transport
  1263. ac.mu.Unlock()
  1264. return t, true
  1265. }
  1266. var idle bool
  1267. if ac.state == connectivity.Idle {
  1268. idle = true
  1269. }
  1270. ac.mu.Unlock()
  1271. // Trigger idle ac to connect.
  1272. if idle {
  1273. ac.connect()
  1274. }
  1275. return nil, false
  1276. }
  1277. // tearDown starts to tear down the addrConn.
  1278. // TODO(zhaoq): Make this synchronous to avoid unbounded memory consumption in
  1279. // some edge cases (e.g., the caller opens and closes many addrConn's in a
  1280. // tight loop.
  1281. // tearDown doesn't remove ac from ac.cc.conns.
  1282. func (ac *addrConn) tearDown(err error) {
  1283. ac.mu.Lock()
  1284. if ac.state == connectivity.Shutdown {
  1285. ac.mu.Unlock()
  1286. return
  1287. }
  1288. curTr := ac.transport
  1289. ac.transport = nil
  1290. // We have to set the state to Shutdown before anything else to prevent races
  1291. // between setting the state and logic that waits on context cancellation / etc.
  1292. ac.updateConnectivityState(connectivity.Shutdown, nil)
  1293. ac.cancel()
  1294. ac.curAddr = resolver.Address{}
  1295. if err == errConnDrain && curTr != nil {
  1296. // GracefulClose(...) may be executed multiple times when
  1297. // i) receiving multiple GoAway frames from the server; or
  1298. // ii) there are concurrent name resolver/Balancer triggered
  1299. // address removal and GoAway.
  1300. // We have to unlock and re-lock here because GracefulClose => Close => onClose, which requires locking ac.mu.
  1301. ac.mu.Unlock()
  1302. curTr.GracefulClose()
  1303. ac.mu.Lock()
  1304. }
  1305. if channelz.IsOn() {
  1306. channelz.AddTraceEvent(logger, ac.channelzID, 0, &channelz.TraceEventDesc{
  1307. Desc: "Subchannel Deleted",
  1308. Severity: channelz.CtINFO,
  1309. Parent: &channelz.TraceEventDesc{
  1310. Desc: fmt.Sprintf("Subchanel(id:%d) deleted", ac.channelzID),
  1311. Severity: channelz.CtINFO,
  1312. },
  1313. })
  1314. // TraceEvent needs to be called before RemoveEntry, as TraceEvent may add trace reference to
  1315. // the entity being deleted, and thus prevent it from being deleted right away.
  1316. channelz.RemoveEntry(ac.channelzID)
  1317. }
  1318. ac.mu.Unlock()
  1319. }
  1320. func (ac *addrConn) getState() connectivity.State {
  1321. ac.mu.Lock()
  1322. defer ac.mu.Unlock()
  1323. return ac.state
  1324. }
  1325. func (ac *addrConn) ChannelzMetric() *channelz.ChannelInternalMetric {
  1326. ac.mu.Lock()
  1327. addr := ac.curAddr.Addr
  1328. ac.mu.Unlock()
  1329. return &channelz.ChannelInternalMetric{
  1330. State: ac.getState(),
  1331. Target: addr,
  1332. CallsStarted: atomic.LoadInt64(&ac.czData.callsStarted),
  1333. CallsSucceeded: atomic.LoadInt64(&ac.czData.callsSucceeded),
  1334. CallsFailed: atomic.LoadInt64(&ac.czData.callsFailed),
  1335. LastCallStartedTimestamp: time.Unix(0, atomic.LoadInt64(&ac.czData.lastCallStartedTime)),
  1336. }
  1337. }
  1338. func (ac *addrConn) incrCallsStarted() {
  1339. atomic.AddInt64(&ac.czData.callsStarted, 1)
  1340. atomic.StoreInt64(&ac.czData.lastCallStartedTime, time.Now().UnixNano())
  1341. }
  1342. func (ac *addrConn) incrCallsSucceeded() {
  1343. atomic.AddInt64(&ac.czData.callsSucceeded, 1)
  1344. }
  1345. func (ac *addrConn) incrCallsFailed() {
  1346. atomic.AddInt64(&ac.czData.callsFailed, 1)
  1347. }
  1348. type retryThrottler struct {
  1349. max float64
  1350. thresh float64
  1351. ratio float64
  1352. mu sync.Mutex
  1353. tokens float64 // TODO(dfawley): replace with atomic and remove lock.
  1354. }
  1355. // throttle subtracts a retry token from the pool and returns whether a retry
  1356. // should be throttled (disallowed) based upon the retry throttling policy in
  1357. // the service config.
  1358. func (rt *retryThrottler) throttle() bool {
  1359. if rt == nil {
  1360. return false
  1361. }
  1362. rt.mu.Lock()
  1363. defer rt.mu.Unlock()
  1364. rt.tokens--
  1365. if rt.tokens < 0 {
  1366. rt.tokens = 0
  1367. }
  1368. return rt.tokens <= rt.thresh
  1369. }
  1370. func (rt *retryThrottler) successfulRPC() {
  1371. if rt == nil {
  1372. return
  1373. }
  1374. rt.mu.Lock()
  1375. defer rt.mu.Unlock()
  1376. rt.tokens += rt.ratio
  1377. if rt.tokens > rt.max {
  1378. rt.tokens = rt.max
  1379. }
  1380. }
  1381. type channelzChannel struct {
  1382. cc *ClientConn
  1383. }
  1384. func (c *channelzChannel) ChannelzMetric() *channelz.ChannelInternalMetric {
  1385. return c.cc.channelzMetric()
  1386. }
  1387. // ErrClientConnTimeout indicates that the ClientConn cannot establish the
  1388. // underlying connections within the specified timeout.
  1389. //
  1390. // Deprecated: This error is never returned by grpc and should not be
  1391. // referenced by users.
  1392. var ErrClientConnTimeout = errors.New("grpc: timed out when dialing")
  1393. func (cc *ClientConn) getResolver(scheme string) resolver.Builder {
  1394. for _, rb := range cc.dopts.resolvers {
  1395. if scheme == rb.Scheme() {
  1396. return rb
  1397. }
  1398. }
  1399. return resolver.Get(scheme)
  1400. }
  1401. func (cc *ClientConn) updateConnectionError(err error) {
  1402. cc.lceMu.Lock()
  1403. cc.lastConnectionError = err
  1404. cc.lceMu.Unlock()
  1405. }
  1406. func (cc *ClientConn) connectionError() error {
  1407. cc.lceMu.Lock()
  1408. defer cc.lceMu.Unlock()
  1409. return cc.lastConnectionError
  1410. }