clientconn.go 45 KB

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