clientconn.go 47 KB

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