client.go 19 KB

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