client.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. // Copyright 2016 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package clientv3
  15. import (
  16. "context"
  17. "errors"
  18. "fmt"
  19. "net"
  20. "os"
  21. "strconv"
  22. "strings"
  23. "sync"
  24. "time"
  25. "github.com/google/uuid"
  26. "go.etcd.io/etcd/clientv3/balancer"
  27. "go.etcd.io/etcd/clientv3/balancer/picker"
  28. "go.etcd.io/etcd/clientv3/balancer/resolver/endpoint"
  29. "go.etcd.io/etcd/clientv3/credentials"
  30. "go.etcd.io/etcd/etcdserver/api/v3rpc/rpctypes"
  31. "go.etcd.io/etcd/pkg/logutil"
  32. "go.uber.org/zap"
  33. "google.golang.org/grpc"
  34. "google.golang.org/grpc/codes"
  35. grpccredentials "google.golang.org/grpc/credentials"
  36. "google.golang.org/grpc/keepalive"
  37. "google.golang.org/grpc/metadata"
  38. "google.golang.org/grpc/status"
  39. )
  40. var (
  41. ErrNoAvailableEndpoints = errors.New("etcdclient: no available endpoints")
  42. ErrOldCluster = errors.New("etcdclient: old cluster version")
  43. roundRobinBalancerName = fmt.Sprintf("etcd-%s", picker.RoundrobinBalanced.String())
  44. )
  45. func init() {
  46. lg := zap.NewNop()
  47. if os.Getenv("ETCD_CLIENT_DEBUG") != "" {
  48. lcfg := logutil.DefaultZapLoggerConfig
  49. lcfg.Level = zap.NewAtomicLevelAt(zap.DebugLevel)
  50. var err error
  51. lg, err = lcfg.Build() // info level logging
  52. if err != nil {
  53. panic(err)
  54. }
  55. }
  56. // TODO: support custom balancer
  57. balancer.RegisterBuilder(balancer.Config{
  58. Policy: picker.RoundrobinBalanced,
  59. Name: roundRobinBalancerName,
  60. Logger: lg,
  61. })
  62. }
  63. // Client provides and manages an etcd v3 client session.
  64. type Client struct {
  65. Cluster
  66. KV
  67. Lease
  68. Watcher
  69. Auth
  70. Maintenance
  71. conn *grpc.ClientConn
  72. cfg Config
  73. creds grpccredentials.TransportCredentials
  74. resolverGroup *endpoint.ResolverGroup
  75. mu *sync.RWMutex
  76. ctx context.Context
  77. cancel context.CancelFunc
  78. // Username is a user name for authentication.
  79. Username string
  80. // Password is a password for authentication.
  81. Password string
  82. authTokenBundle credentials.Bundle
  83. callOpts []grpc.CallOption
  84. lg *zap.Logger
  85. }
  86. // New creates a new etcdv3 client from a given configuration.
  87. func New(cfg Config) (*Client, error) {
  88. if len(cfg.Endpoints) == 0 {
  89. return nil, ErrNoAvailableEndpoints
  90. }
  91. return newClient(&cfg)
  92. }
  93. // NewCtxClient creates a client with a context but no underlying grpc
  94. // connection. This is useful for embedded cases that override the
  95. // service interface implementations and do not need connection management.
  96. func NewCtxClient(ctx context.Context) *Client {
  97. cctx, cancel := context.WithCancel(ctx)
  98. return &Client{ctx: cctx, cancel: cancel}
  99. }
  100. // NewFromURL creates a new etcdv3 client from a URL.
  101. func NewFromURL(url string) (*Client, error) {
  102. return New(Config{Endpoints: []string{url}})
  103. }
  104. // NewFromURLs creates a new etcdv3 client from URLs.
  105. func NewFromURLs(urls []string) (*Client, error) {
  106. return New(Config{Endpoints: urls})
  107. }
  108. // Close shuts down the client's etcd connections.
  109. func (c *Client) Close() error {
  110. c.cancel()
  111. if c.Watcher != nil {
  112. c.Watcher.Close()
  113. }
  114. if c.Lease != nil {
  115. c.Lease.Close()
  116. }
  117. if c.resolverGroup != nil {
  118. c.resolverGroup.Close()
  119. }
  120. if c.conn != nil {
  121. return toErr(c.ctx, c.conn.Close())
  122. }
  123. return c.ctx.Err()
  124. }
  125. // Ctx is a context for "out of band" messages (e.g., for sending
  126. // "clean up" message when another context is canceled). It is
  127. // canceled on client Close().
  128. func (c *Client) Ctx() context.Context { return c.ctx }
  129. // Endpoints lists the registered endpoints for the client.
  130. func (c *Client) Endpoints() []string {
  131. // copy the slice; protect original endpoints from being changed
  132. c.mu.RLock()
  133. defer c.mu.RUnlock()
  134. eps := make([]string, len(c.cfg.Endpoints))
  135. copy(eps, c.cfg.Endpoints)
  136. return eps
  137. }
  138. // SetEndpoints updates client's endpoints.
  139. func (c *Client) SetEndpoints(eps ...string) {
  140. c.mu.Lock()
  141. defer c.mu.Unlock()
  142. c.cfg.Endpoints = eps
  143. c.resolverGroup.SetEndpoints(eps)
  144. }
  145. // Sync synchronizes client's endpoints with the known endpoints from the etcd membership.
  146. func (c *Client) Sync(ctx context.Context) error {
  147. mresp, err := c.MemberList(ctx)
  148. if err != nil {
  149. return err
  150. }
  151. var eps []string
  152. for _, m := range mresp.Members {
  153. eps = append(eps, m.ClientURLs...)
  154. }
  155. c.SetEndpoints(eps...)
  156. return nil
  157. }
  158. func (c *Client) autoSync() {
  159. if c.cfg.AutoSyncInterval == time.Duration(0) {
  160. return
  161. }
  162. for {
  163. select {
  164. case <-c.ctx.Done():
  165. return
  166. case <-time.After(c.cfg.AutoSyncInterval):
  167. ctx, cancel := context.WithTimeout(c.ctx, 5*time.Second)
  168. err := c.Sync(ctx)
  169. cancel()
  170. if err != nil && err != c.ctx.Err() {
  171. lg.Lvl(4).Infof("Auto sync endpoints failed: %v", err)
  172. }
  173. }
  174. }
  175. }
  176. func (c *Client) processCreds(scheme string) (creds grpccredentials.TransportCredentials) {
  177. creds = c.creds
  178. switch scheme {
  179. case "unix":
  180. case "http":
  181. creds = nil
  182. case "https", "unixs":
  183. if creds != nil {
  184. break
  185. }
  186. creds = credentials.NewBundle(credentials.Config{}).TransportCredentials()
  187. default:
  188. creds = nil
  189. }
  190. return creds
  191. }
  192. // dialSetupOpts gives the dial opts prior to any authentication.
  193. func (c *Client) dialSetupOpts(creds grpccredentials.TransportCredentials, dopts ...grpc.DialOption) (opts []grpc.DialOption, err error) {
  194. if c.cfg.DialKeepAliveTime > 0 {
  195. params := keepalive.ClientParameters{
  196. Time: c.cfg.DialKeepAliveTime,
  197. Timeout: c.cfg.DialKeepAliveTimeout,
  198. PermitWithoutStream: c.cfg.PermitWithoutStream,
  199. }
  200. opts = append(opts, grpc.WithKeepaliveParams(params))
  201. }
  202. opts = append(opts, dopts...)
  203. // Provide a net dialer that supports cancelation and timeout.
  204. f := func(dialEp string, t time.Duration) (net.Conn, error) {
  205. proto, host, _ := endpoint.ParseEndpoint(dialEp)
  206. select {
  207. case <-c.ctx.Done():
  208. return nil, c.ctx.Err()
  209. default:
  210. }
  211. dialer := &net.Dialer{Timeout: t}
  212. return dialer.DialContext(c.ctx, proto, host)
  213. }
  214. opts = append(opts, grpc.WithDialer(f))
  215. if creds != nil {
  216. opts = append(opts, grpc.WithTransportCredentials(creds))
  217. } else {
  218. opts = append(opts, grpc.WithInsecure())
  219. }
  220. // Interceptor retry and backoff.
  221. // TODO: Replace all of clientv3/retry.go with interceptor based retry, or with
  222. // https://github.com/grpc/proposal/blob/master/A6-client-retries.md#retry-policy
  223. // once it is available.
  224. rrBackoff := withBackoff(c.roundRobinQuorumBackoff(defaultBackoffWaitBetween, defaultBackoffJitterFraction))
  225. opts = append(opts,
  226. // Disable stream retry by default since go-grpc-middleware/retry does not support client streams.
  227. // Streams that are safe to retry are enabled individually.
  228. grpc.WithStreamInterceptor(c.streamClientInterceptor(c.lg, withMax(0), rrBackoff)),
  229. grpc.WithUnaryInterceptor(c.unaryClientInterceptor(c.lg, withMax(defaultUnaryMaxRetries), rrBackoff)),
  230. )
  231. return opts, nil
  232. }
  233. // Dial connects to a single endpoint using the client's config.
  234. func (c *Client) Dial(ep string) (*grpc.ClientConn, error) {
  235. creds := c.directDialCreds(ep)
  236. // Use the grpc passthrough resolver to directly dial a single endpoint.
  237. // This resolver passes through the 'unix' and 'unixs' endpoints schemes used
  238. // by etcd without modification, allowing us to directly dial endpoints and
  239. // using the same dial functions that we use for load balancer dialing.
  240. return c.dial(fmt.Sprintf("passthrough:///%s", ep), creds)
  241. }
  242. func (c *Client) getToken(ctx context.Context) error {
  243. var err error // return last error in a case of fail
  244. var auth *authenticator
  245. eps := c.Endpoints()
  246. for _, ep := range eps {
  247. // use dial options without dopts to avoid reusing the client balancer
  248. var dOpts []grpc.DialOption
  249. _, host, _ := endpoint.ParseEndpoint(ep)
  250. target := c.resolverGroup.Target(host)
  251. creds := c.dialWithBalancerCreds(ep)
  252. dOpts, err = c.dialSetupOpts(creds, c.cfg.DialOptions...)
  253. if err != nil {
  254. err = fmt.Errorf("failed to configure auth dialer: %v", err)
  255. continue
  256. }
  257. dOpts = append(dOpts, grpc.WithBalancerName(roundRobinBalancerName))
  258. auth, err = newAuthenticator(ctx, target, dOpts, c)
  259. if err != nil {
  260. continue
  261. }
  262. defer auth.close()
  263. var resp *AuthenticateResponse
  264. resp, err = auth.authenticate(ctx, c.Username, c.Password)
  265. if err != nil {
  266. // return err without retrying other endpoints
  267. if err == rpctypes.ErrAuthNotEnabled {
  268. return err
  269. }
  270. continue
  271. }
  272. c.authTokenBundle.UpdateAuthToken(resp.Token)
  273. return nil
  274. }
  275. return err
  276. }
  277. // dialWithBalancer dials the client's current load balanced resolver group. The scheme of the host
  278. // of the provided endpoint determines the scheme used for all endpoints of the client connection.
  279. func (c *Client) dialWithBalancer(ep string, dopts ...grpc.DialOption) (*grpc.ClientConn, error) {
  280. _, host, _ := endpoint.ParseEndpoint(ep)
  281. target := c.resolverGroup.Target(host)
  282. creds := c.dialWithBalancerCreds(ep)
  283. return c.dial(target, creds, dopts...)
  284. }
  285. // dial configures and dials any grpc balancer target.
  286. func (c *Client) dial(target string, creds grpccredentials.TransportCredentials, dopts ...grpc.DialOption) (*grpc.ClientConn, error) {
  287. opts, err := c.dialSetupOpts(creds, dopts...)
  288. if err != nil {
  289. return nil, fmt.Errorf("failed to configure dialer: %v", err)
  290. }
  291. if c.Username != "" && c.Password != "" {
  292. c.authTokenBundle = credentials.NewBundle(credentials.Config{})
  293. ctx, cancel := c.ctx, func() {}
  294. if c.cfg.DialTimeout > 0 {
  295. ctx, cancel = context.WithTimeout(ctx, c.cfg.DialTimeout)
  296. }
  297. err = c.getToken(ctx)
  298. if err != nil {
  299. if toErr(ctx, err) != rpctypes.ErrAuthNotEnabled {
  300. if err == ctx.Err() && ctx.Err() != c.ctx.Err() {
  301. err = context.DeadlineExceeded
  302. }
  303. cancel()
  304. return nil, err
  305. }
  306. } else {
  307. opts = append(opts, grpc.WithPerRPCCredentials(c.authTokenBundle.PerRPCCredentials()))
  308. }
  309. cancel()
  310. }
  311. opts = append(opts, c.cfg.DialOptions...)
  312. dctx := c.ctx
  313. if c.cfg.DialTimeout > 0 {
  314. var cancel context.CancelFunc
  315. dctx, cancel = context.WithTimeout(c.ctx, c.cfg.DialTimeout)
  316. defer cancel() // TODO: Is this right for cases where grpc.WithBlock() is not set on the dial options?
  317. }
  318. conn, err := grpc.DialContext(dctx, target, opts...)
  319. if err != nil {
  320. return nil, err
  321. }
  322. return conn, nil
  323. }
  324. func (c *Client) directDialCreds(ep string) grpccredentials.TransportCredentials {
  325. _, hostPort, scheme := endpoint.ParseEndpoint(ep)
  326. creds := c.creds
  327. if len(scheme) != 0 {
  328. creds = c.processCreds(scheme)
  329. if creds != nil {
  330. clone := creds.Clone()
  331. // Set the server name must to the endpoint hostname without port since grpc
  332. // otherwise attempts to check if x509 cert is valid for the full endpoint
  333. // including the scheme and port, which fails.
  334. host, _ := endpoint.ParseHostPort(hostPort)
  335. clone.OverrideServerName(host)
  336. creds = clone
  337. }
  338. }
  339. return creds
  340. }
  341. func (c *Client) dialWithBalancerCreds(ep string) grpccredentials.TransportCredentials {
  342. _, _, scheme := endpoint.ParseEndpoint(ep)
  343. creds := c.creds
  344. if len(scheme) != 0 {
  345. creds = c.processCreds(scheme)
  346. }
  347. return creds
  348. }
  349. // WithRequireLeader requires client requests to only succeed
  350. // when the cluster has a leader.
  351. func WithRequireLeader(ctx context.Context) context.Context {
  352. md := metadata.Pairs(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
  353. return metadata.NewOutgoingContext(ctx, md)
  354. }
  355. func newClient(cfg *Config) (*Client, error) {
  356. if cfg == nil {
  357. cfg = &Config{}
  358. }
  359. var creds grpccredentials.TransportCredentials
  360. if cfg.TLS != nil {
  361. creds = credentials.NewBundle(credentials.Config{TLSConfig: cfg.TLS}).TransportCredentials()
  362. }
  363. // use a temporary skeleton client to bootstrap first connection
  364. baseCtx := context.TODO()
  365. if cfg.Context != nil {
  366. baseCtx = cfg.Context
  367. }
  368. ctx, cancel := context.WithCancel(baseCtx)
  369. client := &Client{
  370. conn: nil,
  371. cfg: *cfg,
  372. creds: creds,
  373. ctx: ctx,
  374. cancel: cancel,
  375. mu: new(sync.RWMutex),
  376. callOpts: defaultCallOpts,
  377. }
  378. lcfg := logutil.DefaultZapLoggerConfig
  379. if cfg.LogConfig != nil {
  380. lcfg = *cfg.LogConfig
  381. }
  382. var err error
  383. client.lg, err = lcfg.Build()
  384. if err != nil {
  385. return nil, err
  386. }
  387. if cfg.Username != "" && cfg.Password != "" {
  388. client.Username = cfg.Username
  389. client.Password = cfg.Password
  390. }
  391. if cfg.MaxCallSendMsgSize > 0 || cfg.MaxCallRecvMsgSize > 0 {
  392. if cfg.MaxCallRecvMsgSize > 0 && cfg.MaxCallSendMsgSize > cfg.MaxCallRecvMsgSize {
  393. return nil, fmt.Errorf("gRPC message recv limit (%d bytes) must be greater than send limit (%d bytes)", cfg.MaxCallRecvMsgSize, cfg.MaxCallSendMsgSize)
  394. }
  395. callOpts := []grpc.CallOption{
  396. defaultFailFast,
  397. defaultMaxCallSendMsgSize,
  398. defaultMaxCallRecvMsgSize,
  399. }
  400. if cfg.MaxCallSendMsgSize > 0 {
  401. callOpts[1] = grpc.MaxCallSendMsgSize(cfg.MaxCallSendMsgSize)
  402. }
  403. if cfg.MaxCallRecvMsgSize > 0 {
  404. callOpts[2] = grpc.MaxCallRecvMsgSize(cfg.MaxCallRecvMsgSize)
  405. }
  406. client.callOpts = callOpts
  407. }
  408. // Prepare a 'endpoint://<unique-client-id>/' resolver for the client and create a endpoint target to pass
  409. // to dial so the client knows to use this resolver.
  410. client.resolverGroup, err = endpoint.NewResolverGroup(fmt.Sprintf("client-%s", uuid.New().String()))
  411. if err != nil {
  412. client.cancel()
  413. return nil, err
  414. }
  415. client.resolverGroup.SetEndpoints(cfg.Endpoints)
  416. if len(cfg.Endpoints) < 1 {
  417. return nil, fmt.Errorf("at least one Endpoint must is required in client config")
  418. }
  419. dialEndpoint := cfg.Endpoints[0]
  420. // Use a provided endpoint target so that for https:// without any tls config given, then
  421. // grpc will assume the certificate server name is the endpoint host.
  422. conn, err := client.dialWithBalancer(dialEndpoint, grpc.WithBalancerName(roundRobinBalancerName))
  423. if err != nil {
  424. client.cancel()
  425. client.resolverGroup.Close()
  426. return nil, err
  427. }
  428. // TODO: With the old grpc balancer interface, we waited until the dial timeout
  429. // for the balancer to be ready. Is there an equivalent wait we should do with the new grpc balancer interface?
  430. client.conn = conn
  431. client.Cluster = NewCluster(client)
  432. client.KV = NewKV(client)
  433. client.Lease = NewLease(client)
  434. client.Watcher = NewWatcher(client)
  435. client.Auth = NewAuth(client)
  436. client.Maintenance = NewMaintenance(client)
  437. if cfg.RejectOldCluster {
  438. if err := client.checkVersion(); err != nil {
  439. client.Close()
  440. return nil, err
  441. }
  442. }
  443. go client.autoSync()
  444. return client, nil
  445. }
  446. // roundRobinQuorumBackoff retries against quorum between each backoff.
  447. // This is intended for use with a round robin load balancer.
  448. func (c *Client) roundRobinQuorumBackoff(waitBetween time.Duration, jitterFraction float64) backoffFunc {
  449. return func(attempt uint) time.Duration {
  450. // after each round robin across quorum, backoff for our wait between duration
  451. n := uint(len(c.Endpoints()))
  452. quorum := (n/2 + 1)
  453. if attempt%quorum == 0 {
  454. c.lg.Debug("backoff", zap.Uint("attempt", attempt), zap.Uint("quorum", quorum), zap.Duration("waitBetween", waitBetween), zap.Float64("jitterFraction", jitterFraction))
  455. return jitterUp(waitBetween, jitterFraction)
  456. }
  457. c.lg.Debug("backoff skipped", zap.Uint("attempt", attempt), zap.Uint("quorum", quorum))
  458. return 0
  459. }
  460. }
  461. func (c *Client) checkVersion() (err error) {
  462. var wg sync.WaitGroup
  463. eps := c.Endpoints()
  464. errc := make(chan error, len(eps))
  465. ctx, cancel := context.WithCancel(c.ctx)
  466. if c.cfg.DialTimeout > 0 {
  467. cancel()
  468. ctx, cancel = context.WithTimeout(c.ctx, c.cfg.DialTimeout)
  469. }
  470. wg.Add(len(eps))
  471. for _, ep := range eps {
  472. // if cluster is current, any endpoint gives a recent version
  473. go func(e string) {
  474. defer wg.Done()
  475. resp, rerr := c.Status(ctx, e)
  476. if rerr != nil {
  477. errc <- rerr
  478. return
  479. }
  480. vs := strings.Split(resp.Version, ".")
  481. maj, min := 0, 0
  482. if len(vs) >= 2 {
  483. var serr error
  484. if maj, serr = strconv.Atoi(vs[0]); serr != nil {
  485. errc <- serr
  486. return
  487. }
  488. if min, serr = strconv.Atoi(vs[1]); serr != nil {
  489. errc <- serr
  490. return
  491. }
  492. }
  493. if maj < 3 || (maj == 3 && min < 2) {
  494. rerr = ErrOldCluster
  495. }
  496. errc <- rerr
  497. }(ep)
  498. }
  499. // wait for success
  500. for range eps {
  501. if err = <-errc; err == nil {
  502. break
  503. }
  504. }
  505. cancel()
  506. wg.Wait()
  507. return err
  508. }
  509. // ActiveConnection returns the current in-use connection
  510. func (c *Client) ActiveConnection() *grpc.ClientConn { return c.conn }
  511. // isHaltErr returns true if the given error and context indicate no forward
  512. // progress can be made, even after reconnecting.
  513. func isHaltErr(ctx context.Context, err error) bool {
  514. if ctx != nil && ctx.Err() != nil {
  515. return true
  516. }
  517. if err == nil {
  518. return false
  519. }
  520. ev, _ := status.FromError(err)
  521. // Unavailable codes mean the system will be right back.
  522. // (e.g., can't connect, lost leader)
  523. // Treat Internal codes as if something failed, leaving the
  524. // system in an inconsistent state, but retrying could make progress.
  525. // (e.g., failed in middle of send, corrupted frame)
  526. // TODO: are permanent Internal errors possible from grpc?
  527. return ev.Code() != codes.Unavailable && ev.Code() != codes.Internal
  528. }
  529. // isUnavailableErr returns true if the given error is an unavailable error
  530. func isUnavailableErr(ctx context.Context, err error) bool {
  531. if ctx != nil && ctx.Err() != nil {
  532. return false
  533. }
  534. if err == nil {
  535. return false
  536. }
  537. ev, ok := status.FromError(err)
  538. if ok {
  539. // Unavailable codes mean the system will be right back.
  540. // (e.g., can't connect, lost leader)
  541. return ev.Code() == codes.Unavailable
  542. }
  543. return false
  544. }
  545. func toErr(ctx context.Context, err error) error {
  546. if err == nil {
  547. return nil
  548. }
  549. err = rpctypes.Error(err)
  550. if _, ok := err.(rpctypes.EtcdError); ok {
  551. return err
  552. }
  553. if ev, ok := status.FromError(err); ok {
  554. code := ev.Code()
  555. switch code {
  556. case codes.DeadlineExceeded:
  557. fallthrough
  558. case codes.Canceled:
  559. if ctx.Err() != nil {
  560. err = ctx.Err()
  561. }
  562. }
  563. }
  564. return err
  565. }
  566. func canceledByCaller(stopCtx context.Context, err error) bool {
  567. if stopCtx.Err() == nil || err == nil {
  568. return false
  569. }
  570. return err == context.Canceled || err == context.DeadlineExceeded
  571. }
  572. // IsConnCanceled returns true, if error is from a closed gRPC connection.
  573. // ref. https://github.com/grpc/grpc-go/pull/1854
  574. func IsConnCanceled(err error) bool {
  575. if err == nil {
  576. return false
  577. }
  578. // >= gRPC v1.23.x
  579. s, ok := status.FromError(err)
  580. if ok {
  581. // connection is canceled or server has already closed the connection
  582. return s.Code() == codes.Canceled || s.Message() == "transport is closing"
  583. }
  584. // >= gRPC v1.10.x
  585. if err == context.Canceled {
  586. return true
  587. }
  588. // <= gRPC v1.7.x returns 'errors.New("grpc: the client connection is closing")'
  589. return strings.Contains(err.Error(), "grpc: the client connection is closing")
  590. }