client.go 18 KB

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