clientconn.go 48 KB

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