client.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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/coreos/etcd/clientv3/balancer"
  28. "github.com/coreos/etcd/clientv3/balancer/picker"
  29. "github.com/coreos/etcd/clientv3/balancer/resolver/endpoint"
  30. "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  31. "github.com/grpc-ecosystem/go-grpc-middleware/util/backoffutils"
  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.Mutex
  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() (eps []string) {
  126. // copy the slice; protect original endpoints from being changed
  127. eps = make([]string, len(c.cfg.Endpoints))
  128. copy(eps, c.cfg.Endpoints)
  129. return
  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. type authTokenCredential struct {
  170. token string
  171. tokenMu *sync.RWMutex
  172. }
  173. func (cred authTokenCredential) RequireTransportSecurity() bool {
  174. return false
  175. }
  176. func (cred authTokenCredential) GetRequestMetadata(ctx context.Context, s ...string) (map[string]string, error) {
  177. cred.tokenMu.RLock()
  178. defer cred.tokenMu.RUnlock()
  179. return map[string]string{
  180. rpctypes.TokenFieldNameGRPC: cred.token,
  181. }, nil
  182. }
  183. func (c *Client) processCreds(scheme string) (creds *credentials.TransportCredentials) {
  184. creds = c.creds
  185. switch scheme {
  186. case "unix":
  187. case "http":
  188. creds = nil
  189. case "https", "unixs":
  190. if creds != nil {
  191. break
  192. }
  193. tlsconfig := &tls.Config{}
  194. emptyCreds := credentials.NewTLS(tlsconfig)
  195. creds = &emptyCreds
  196. default:
  197. creds = nil
  198. }
  199. return creds
  200. }
  201. // dialSetupOpts gives the dial opts prior to any authentication
  202. func (c *Client) dialSetupOpts(target string, dopts ...grpc.DialOption) (opts []grpc.DialOption, err error) {
  203. _, ep, err := endpoint.ParseTarget(target)
  204. if err != nil {
  205. return nil, fmt.Errorf("unable to parse target: %v", err)
  206. }
  207. if c.cfg.DialKeepAliveTime > 0 {
  208. params := keepalive.ClientParameters{
  209. Time: c.cfg.DialKeepAliveTime,
  210. Timeout: c.cfg.DialKeepAliveTimeout,
  211. }
  212. opts = append(opts, grpc.WithKeepaliveParams(params))
  213. }
  214. opts = append(opts, dopts...)
  215. f := func(dialEp string, t time.Duration) (net.Conn, error) {
  216. proto, host, _ := endpoint.ParseEndpoint(dialEp)
  217. if host == "" && ep != "" {
  218. // dialing an endpoint not in the balancer; use
  219. // endpoint passed into dial
  220. proto, host, _ = endpoint.ParseEndpoint(ep)
  221. }
  222. if proto == "" {
  223. return nil, fmt.Errorf("unknown scheme for %q", host)
  224. }
  225. select {
  226. case <-c.ctx.Done():
  227. return nil, c.ctx.Err()
  228. default:
  229. }
  230. dialer := &net.Dialer{Timeout: t}
  231. return dialer.DialContext(c.ctx, proto, host)
  232. }
  233. opts = append(opts, grpc.WithDialer(f))
  234. creds := c.creds
  235. if _, _, scheme := endpoint.ParseEndpoint(ep); len(scheme) != 0 {
  236. creds = c.processCreds(scheme)
  237. }
  238. if creds != nil {
  239. opts = append(opts, grpc.WithTransportCredentials(*creds))
  240. } else {
  241. opts = append(opts, grpc.WithInsecure())
  242. }
  243. // Interceptor retry and backoff.
  244. // TODO: Replace all of clientv3/retry.go with interceptor based retry, or with
  245. // https://github.com/grpc/proposal/blob/master/A6-client-retries.md#retry-policy
  246. // once it is available.
  247. rrBackoff := withBackoff(c.roundRobinQuorumBackoff(defaultBackoffWaitBetween, defaultBackoffJitterFraction))
  248. opts = append(opts,
  249. // Disable stream retry by default since go-grpc-middleware/retry does not support client streams.
  250. // Streams that are safe to retry are enabled individually.
  251. grpc.WithStreamInterceptor(c.streamClientInterceptor(c.lg, withMax(0), rrBackoff)),
  252. grpc.WithUnaryInterceptor(c.unaryClientInterceptor(c.lg, withMax(defaultUnaryMaxRetries), rrBackoff)),
  253. )
  254. return opts, nil
  255. }
  256. // Dial connects to a single endpoint using the client's config.
  257. func (c *Client) Dial(endpoint string) (*grpc.ClientConn, error) {
  258. return c.dial(endpoint)
  259. }
  260. func (c *Client) getToken(ctx context.Context) error {
  261. var err error // return last error in a case of fail
  262. var auth *authenticator
  263. for i := 0; i < len(c.cfg.Endpoints); i++ {
  264. ep := c.cfg.Endpoints[i]
  265. // use dial options without dopts to avoid reusing the client balancer
  266. var dOpts []grpc.DialOption
  267. _, host, _ := endpoint.ParseEndpoint(ep)
  268. target := c.resolverGroup.Target(host)
  269. dOpts, err = c.dialSetupOpts(target, c.cfg.DialOptions...)
  270. if err != nil {
  271. err = fmt.Errorf("failed to configure auth dialer: %v", err)
  272. continue
  273. }
  274. dOpts = append(dOpts, grpc.WithBalancerName(roundRobinBalancerName))
  275. auth, err = newAuthenticator(ctx, target, dOpts, c)
  276. if err != nil {
  277. continue
  278. }
  279. defer auth.close()
  280. var resp *AuthenticateResponse
  281. resp, err = auth.authenticate(ctx, c.Username, c.Password)
  282. if err != nil {
  283. continue
  284. }
  285. c.tokenCred.tokenMu.Lock()
  286. c.tokenCred.token = resp.Token
  287. c.tokenCred.tokenMu.Unlock()
  288. return nil
  289. }
  290. return err
  291. }
  292. func (c *Client) dial(ep string, dopts ...grpc.DialOption) (*grpc.ClientConn, error) {
  293. // We pass a target to DialContext of the form: endpoint://<clusterName>/<host-part> that
  294. // does not include scheme (http/https/unix/unixs) or path parts.
  295. _, host, _ := endpoint.ParseEndpoint(ep)
  296. target := c.resolverGroup.Target(host)
  297. opts, err := c.dialSetupOpts(target, dopts...)
  298. if err != nil {
  299. return nil, fmt.Errorf("failed to configure dialer: %v", err)
  300. }
  301. if c.Username != "" && c.Password != "" {
  302. c.tokenCred = &authTokenCredential{
  303. tokenMu: &sync.RWMutex{},
  304. }
  305. ctx, cancel := c.ctx, func() {}
  306. if c.cfg.DialTimeout > 0 {
  307. ctx, cancel = context.WithTimeout(ctx, c.cfg.DialTimeout)
  308. }
  309. err = c.getToken(ctx)
  310. if err != nil {
  311. if toErr(ctx, err) != rpctypes.ErrAuthNotEnabled {
  312. if err == ctx.Err() && ctx.Err() != c.ctx.Err() {
  313. err = context.DeadlineExceeded
  314. }
  315. cancel()
  316. return nil, err
  317. }
  318. } else {
  319. opts = append(opts, grpc.WithPerRPCCredentials(c.tokenCred))
  320. }
  321. cancel()
  322. }
  323. opts = append(opts, c.cfg.DialOptions...)
  324. dctx := c.ctx
  325. if c.cfg.DialTimeout > 0 {
  326. var cancel context.CancelFunc
  327. dctx, cancel = context.WithTimeout(c.ctx, c.cfg.DialTimeout)
  328. defer cancel() // TODO: Is this right for cases where grpc.WithBlock() is not set on the dial options?
  329. }
  330. conn, err := grpc.DialContext(dctx, target, opts...)
  331. if err != nil {
  332. return nil, err
  333. }
  334. return conn, nil
  335. }
  336. // WithRequireLeader requires client requests to only succeed
  337. // when the cluster has a leader.
  338. func WithRequireLeader(ctx context.Context) context.Context {
  339. md := metadata.Pairs(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
  340. return metadata.NewOutgoingContext(ctx, md)
  341. }
  342. func newClient(cfg *Config) (*Client, error) {
  343. if cfg == nil {
  344. cfg = &Config{}
  345. }
  346. var creds *credentials.TransportCredentials
  347. if cfg.TLS != nil {
  348. c := credentials.NewTLS(cfg.TLS)
  349. creds = &c
  350. }
  351. // use a temporary skeleton client to bootstrap first connection
  352. baseCtx := context.TODO()
  353. if cfg.Context != nil {
  354. baseCtx = cfg.Context
  355. }
  356. ctx, cancel := context.WithCancel(baseCtx)
  357. client := &Client{
  358. conn: nil,
  359. cfg: *cfg,
  360. creds: creds,
  361. ctx: ctx,
  362. cancel: cancel,
  363. mu: new(sync.Mutex),
  364. callOpts: defaultCallOpts,
  365. }
  366. lcfg := DefaultLogConfig
  367. if cfg.LogConfig != nil {
  368. lcfg = *cfg.LogConfig
  369. }
  370. var err error
  371. client.lg, err = lcfg.Build()
  372. if err != nil {
  373. return nil, err
  374. }
  375. if cfg.Username != "" && cfg.Password != "" {
  376. client.Username = cfg.Username
  377. client.Password = cfg.Password
  378. }
  379. if cfg.MaxCallSendMsgSize > 0 || cfg.MaxCallRecvMsgSize > 0 {
  380. if cfg.MaxCallRecvMsgSize > 0 && cfg.MaxCallSendMsgSize > cfg.MaxCallRecvMsgSize {
  381. return nil, fmt.Errorf("gRPC message recv limit (%d bytes) must be greater than send limit (%d bytes)", cfg.MaxCallRecvMsgSize, cfg.MaxCallSendMsgSize)
  382. }
  383. callOpts := []grpc.CallOption{
  384. defaultFailFast,
  385. defaultMaxCallSendMsgSize,
  386. defaultMaxCallRecvMsgSize,
  387. }
  388. if cfg.MaxCallSendMsgSize > 0 {
  389. callOpts[1] = grpc.MaxCallSendMsgSize(cfg.MaxCallSendMsgSize)
  390. }
  391. if cfg.MaxCallRecvMsgSize > 0 {
  392. callOpts[2] = grpc.MaxCallRecvMsgSize(cfg.MaxCallRecvMsgSize)
  393. }
  394. client.callOpts = callOpts
  395. }
  396. // Prepare a 'endpoint://<unique-client-id>/' resolver for the client and create a endpoint target to pass
  397. // to dial so the client knows to use this resolver.
  398. client.resolverGroup, err = endpoint.NewResolverGroup(fmt.Sprintf("client-%s", strconv.FormatInt(time.Now().UnixNano(), 36)))
  399. if err != nil {
  400. client.cancel()
  401. return nil, err
  402. }
  403. client.resolverGroup.SetEndpoints(cfg.Endpoints)
  404. if len(cfg.Endpoints) < 1 {
  405. return nil, fmt.Errorf("at least one Endpoint must is required in client config")
  406. }
  407. dialEndpoint := cfg.Endpoints[0]
  408. // Use an provided endpoint target so that for https:// without any tls config given, then
  409. // grpc will assume the certificate server name is the endpoint host.
  410. conn, err := client.dial(dialEndpoint, grpc.WithBalancerName(roundRobinBalancerName))
  411. if err != nil {
  412. client.cancel()
  413. client.resolverGroup.Close()
  414. return nil, err
  415. }
  416. // TODO: With the old grpc balancer interface, we waited until the dial timeout
  417. // for the balancer to be ready. Is there an equivalent wait we should do with the new grpc balancer interface?
  418. client.conn = conn
  419. client.Cluster = NewCluster(client)
  420. client.KV = NewKV(client)
  421. client.Lease = NewLease(client)
  422. client.Watcher = NewWatcher(client)
  423. client.Auth = NewAuth(client)
  424. client.Maintenance = NewMaintenance(client)
  425. if cfg.RejectOldCluster {
  426. if err := client.checkVersion(); err != nil {
  427. client.Close()
  428. return nil, err
  429. }
  430. }
  431. go client.autoSync()
  432. return client, nil
  433. }
  434. // roundRobinQuorumBackoff retries against quorum between each backoff.
  435. // This is intended for use with a round robin load balancer.
  436. func (c *Client) roundRobinQuorumBackoff(waitBetween time.Duration, jitterFraction float64) backoffFunc {
  437. return func(attempt uint) time.Duration {
  438. // after each round robin across quorum, backoff for our wait between duration
  439. n := uint(len(c.Endpoints()))
  440. quorum := (n/2 + 1)
  441. if attempt%quorum == 0 {
  442. c.lg.Info("backoff", zap.Uint("attempt", attempt), zap.Uint("quorum", quorum), zap.Duration("waitBetween", waitBetween), zap.Float64("jitterFraction", jitterFraction))
  443. return backoffutils.JitterUp(waitBetween, jitterFraction)
  444. }
  445. c.lg.Info("backoff skipped", zap.Uint("attempt", attempt), zap.Uint("quorum", quorum))
  446. return 0
  447. }
  448. }
  449. func (c *Client) checkVersion() (err error) {
  450. var wg sync.WaitGroup
  451. errc := make(chan error, len(c.cfg.Endpoints))
  452. ctx, cancel := context.WithCancel(c.ctx)
  453. if c.cfg.DialTimeout > 0 {
  454. ctx, cancel = context.WithTimeout(ctx, c.cfg.DialTimeout)
  455. }
  456. wg.Add(len(c.cfg.Endpoints))
  457. for _, ep := range c.cfg.Endpoints {
  458. // if cluster is current, any endpoint gives a recent version
  459. go func(e string) {
  460. defer wg.Done()
  461. resp, rerr := c.Status(ctx, e)
  462. if rerr != nil {
  463. errc <- rerr
  464. return
  465. }
  466. vs := strings.Split(resp.Version, ".")
  467. maj, min := 0, 0
  468. if len(vs) >= 2 {
  469. maj, _ = strconv.Atoi(vs[0])
  470. min, rerr = strconv.Atoi(vs[1])
  471. }
  472. if maj < 3 || (maj == 3 && min < 2) {
  473. rerr = ErrOldCluster
  474. }
  475. errc <- rerr
  476. }(ep)
  477. }
  478. // wait for success
  479. for i := 0; i < len(c.cfg.Endpoints); i++ {
  480. if err = <-errc; err == nil {
  481. break
  482. }
  483. }
  484. cancel()
  485. wg.Wait()
  486. return err
  487. }
  488. // ActiveConnection returns the current in-use connection
  489. func (c *Client) ActiveConnection() *grpc.ClientConn { return c.conn }
  490. // isHaltErr returns true if the given error and context indicate no forward
  491. // progress can be made, even after reconnecting.
  492. func isHaltErr(ctx context.Context, err error) bool {
  493. if ctx != nil && ctx.Err() != nil {
  494. return true
  495. }
  496. if err == nil {
  497. return false
  498. }
  499. ev, _ := status.FromError(err)
  500. // Unavailable codes mean the system will be right back.
  501. // (e.g., can't connect, lost leader)
  502. // Treat Internal codes as if something failed, leaving the
  503. // system in an inconsistent state, but retrying could make progress.
  504. // (e.g., failed in middle of send, corrupted frame)
  505. // TODO: are permanent Internal errors possible from grpc?
  506. return ev.Code() != codes.Unavailable && ev.Code() != codes.Internal
  507. }
  508. // isUnavailableErr returns true if the given error is an unavailable error
  509. func isUnavailableErr(ctx context.Context, err error) bool {
  510. if ctx != nil && ctx.Err() != nil {
  511. return false
  512. }
  513. if err == nil {
  514. return false
  515. }
  516. ev, _ := status.FromError(err)
  517. // Unavailable codes mean the system will be right back.
  518. // (e.g., can't connect, lost leader)
  519. return ev.Code() == codes.Unavailable
  520. }
  521. func toErr(ctx context.Context, err error) error {
  522. if err == nil {
  523. return nil
  524. }
  525. err = rpctypes.Error(err)
  526. if _, ok := err.(rpctypes.EtcdError); ok {
  527. return err
  528. }
  529. if ev, ok := status.FromError(err); ok {
  530. code := ev.Code()
  531. switch code {
  532. case codes.DeadlineExceeded:
  533. fallthrough
  534. case codes.Canceled:
  535. if ctx.Err() != nil {
  536. err = ctx.Err()
  537. }
  538. case codes.Unavailable:
  539. case codes.FailedPrecondition:
  540. err = grpc.ErrClientConnClosing
  541. }
  542. }
  543. return err
  544. }
  545. func canceledByCaller(stopCtx context.Context, err error) bool {
  546. if stopCtx.Err() == nil || err == nil {
  547. return false
  548. }
  549. return err == context.Canceled || err == context.DeadlineExceeded
  550. }
  551. // IsConnCanceled returns true, if error is from a closed gRPC connection.
  552. // ref. https://github.com/grpc/grpc-go/pull/1854
  553. func IsConnCanceled(err error) bool {
  554. if err == nil {
  555. return false
  556. }
  557. // >= gRPC v1.10.x
  558. s, ok := status.FromError(err)
  559. if ok {
  560. // connection is canceled or server has already closed the connection
  561. return s.Code() == codes.Canceled || s.Message() == "transport is closing"
  562. }
  563. // >= gRPC v1.10.x
  564. if err == context.Canceled {
  565. return true
  566. }
  567. // <= gRPC v1.7.x returns 'errors.New("grpc: the client connection is closing")'
  568. return strings.Contains(err.Error(), "grpc: the client connection is closing")
  569. }
  570. func getHost(ep string) string {
  571. url, uerr := url.Parse(ep)
  572. if uerr != nil || !strings.Contains(ep, "://") {
  573. return ep
  574. }
  575. return url.Host
  576. }