client.go 18 KB

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