client.go 19 KB

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