No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 

1352 líneas
40 KiB

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