client.go 19 KB

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