client.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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. "strconv"
  20. "strings"
  21. "sync"
  22. "time"
  23. "go.etcd.io/etcd/api/v3/v3rpc/rpctypes"
  24. "go.etcd.io/etcd/client/pkg/v3/logutil"
  25. "go.etcd.io/etcd/client/v3/credentials"
  26. "go.etcd.io/etcd/client/v3/internal/endpoint"
  27. "go.etcd.io/etcd/client/v3/internal/resolver"
  28. "go.uber.org/zap"
  29. "google.golang.org/grpc"
  30. "google.golang.org/grpc/codes"
  31. grpccredentials "google.golang.org/grpc/credentials"
  32. "google.golang.org/grpc/keepalive"
  33. "google.golang.org/grpc/status"
  34. )
  35. var (
  36. ErrNoAvailableEndpoints = errors.New("etcdclient: no available endpoints")
  37. ErrOldCluster = errors.New("etcdclient: old cluster version")
  38. )
  39. // Client provides and manages an etcd v3 client session.
  40. type Client struct {
  41. Cluster
  42. KV
  43. Lease
  44. Watcher
  45. Auth
  46. Maintenance
  47. conn *grpc.ClientConn
  48. cfg Config
  49. creds grpccredentials.TransportCredentials
  50. resolver *resolver.EtcdManualResolver
  51. mu *sync.RWMutex
  52. ctx context.Context
  53. cancel context.CancelFunc
  54. // Username is a user name for authentication.
  55. Username string
  56. // Password is a password for authentication.
  57. Password string
  58. authTokenBundle credentials.Bundle
  59. callOpts []grpc.CallOption
  60. lgMu *sync.RWMutex
  61. lg *zap.Logger
  62. }
  63. // New creates a new etcdv3 client from a given configuration.
  64. func New(cfg Config) (*Client, error) {
  65. if len(cfg.Endpoints) == 0 {
  66. return nil, ErrNoAvailableEndpoints
  67. }
  68. return newClient(&cfg)
  69. }
  70. // NewCtxClient creates a client with a context but no underlying grpc
  71. // connection. This is useful for embedded cases that override the
  72. // service interface implementations and do not need connection management.
  73. func NewCtxClient(ctx context.Context, opts ...Option) *Client {
  74. cctx, cancel := context.WithCancel(ctx)
  75. c := &Client{ctx: cctx, cancel: cancel, lgMu: new(sync.RWMutex)}
  76. for _, opt := range opts {
  77. opt(c)
  78. }
  79. if c.lg == nil {
  80. c.lg = zap.NewNop()
  81. }
  82. return c
  83. }
  84. // Option is a function type that can be passed as argument to NewCtxClient to configure client
  85. type Option func(*Client)
  86. // NewFromURL creates a new etcdv3 client from a URL.
  87. func NewFromURL(url string) (*Client, error) {
  88. return New(Config{Endpoints: []string{url}})
  89. }
  90. // NewFromURLs creates a new etcdv3 client from URLs.
  91. func NewFromURLs(urls []string) (*Client, error) {
  92. return New(Config{Endpoints: urls})
  93. }
  94. // WithZapLogger is a NewCtxClient option that overrides the logger
  95. func WithZapLogger(lg *zap.Logger) Option {
  96. return func(c *Client) {
  97. c.lg = lg
  98. }
  99. }
  100. // WithLogger overrides the logger.
  101. //
  102. // Deprecated: Please use WithZapLogger or Logger field in clientv3.Config
  103. //
  104. // Does not changes grpcLogger, that can be explicitly configured
  105. // using grpc_zap.ReplaceGrpcLoggerV2(..) method.
  106. func (c *Client) WithLogger(lg *zap.Logger) *Client {
  107. c.lgMu.Lock()
  108. c.lg = lg
  109. c.lgMu.Unlock()
  110. return c
  111. }
  112. // GetLogger gets the logger.
  113. // NOTE: This method is for internal use of etcd-client library and should not be used as general-purpose logger.
  114. func (c *Client) GetLogger() *zap.Logger {
  115. c.lgMu.RLock()
  116. l := c.lg
  117. c.lgMu.RUnlock()
  118. return l
  119. }
  120. // Close shuts down the client's etcd connections.
  121. func (c *Client) Close() error {
  122. c.cancel()
  123. if c.Watcher != nil {
  124. c.Watcher.Close()
  125. }
  126. if c.Lease != nil {
  127. c.Lease.Close()
  128. }
  129. if c.conn != nil {
  130. return toErr(c.ctx, c.conn.Close())
  131. }
  132. return c.ctx.Err()
  133. }
  134. // Ctx is a context for "out of band" messages (e.g., for sending
  135. // "clean up" message when another context is canceled). It is
  136. // canceled on client Close().
  137. func (c *Client) Ctx() context.Context { return c.ctx }
  138. // Endpoints lists the registered endpoints for the client.
  139. func (c *Client) Endpoints() []string {
  140. // copy the slice; protect original endpoints from being changed
  141. c.mu.RLock()
  142. defer c.mu.RUnlock()
  143. eps := make([]string, len(c.cfg.Endpoints))
  144. copy(eps, c.cfg.Endpoints)
  145. return eps
  146. }
  147. // SetEndpoints updates client's endpoints.
  148. func (c *Client) SetEndpoints(eps ...string) {
  149. c.mu.Lock()
  150. defer c.mu.Unlock()
  151. c.cfg.Endpoints = eps
  152. c.resolver.SetEndpoints(eps)
  153. }
  154. // Sync synchronizes client's endpoints with the known endpoints from the etcd membership.
  155. func (c *Client) Sync(ctx context.Context) error {
  156. mresp, err := c.MemberList(ctx)
  157. if err != nil {
  158. return err
  159. }
  160. var eps []string
  161. for _, m := range mresp.Members {
  162. if len(m.Name) != 0 && !m.IsLearner {
  163. eps = append(eps, m.ClientURLs...)
  164. }
  165. }
  166. c.SetEndpoints(eps...)
  167. return nil
  168. }
  169. func (c *Client) autoSync() {
  170. if c.cfg.AutoSyncInterval == time.Duration(0) {
  171. return
  172. }
  173. for {
  174. select {
  175. case <-c.ctx.Done():
  176. return
  177. case <-time.After(c.cfg.AutoSyncInterval):
  178. ctx, cancel := context.WithTimeout(c.ctx, 5*time.Second)
  179. err := c.Sync(ctx)
  180. cancel()
  181. if err != nil && err != c.ctx.Err() {
  182. c.lg.Info("Auto sync endpoints failed.", zap.Error(err))
  183. }
  184. }
  185. }
  186. }
  187. // dialSetupOpts gives the dial opts prior to any authentication.
  188. func (c *Client) dialSetupOpts(creds grpccredentials.TransportCredentials, dopts ...grpc.DialOption) (opts []grpc.DialOption, err error) {
  189. if c.cfg.DialKeepAliveTime > 0 {
  190. params := keepalive.ClientParameters{
  191. Time: c.cfg.DialKeepAliveTime,
  192. Timeout: c.cfg.DialKeepAliveTimeout,
  193. PermitWithoutStream: c.cfg.PermitWithoutStream,
  194. }
  195. opts = append(opts, grpc.WithKeepaliveParams(params))
  196. }
  197. opts = append(opts, dopts...)
  198. if creds != nil {
  199. opts = append(opts, grpc.WithTransportCredentials(creds))
  200. } else {
  201. opts = append(opts, grpc.WithInsecure())
  202. }
  203. // Interceptor retry and backoff.
  204. // TODO: Replace all of clientv3/retry.go with RetryPolicy:
  205. // https://github.com/grpc/grpc-proto/blob/cdd9ed5c3d3f87aef62f373b93361cf7bddc620d/grpc/service_config/service_config.proto#L130
  206. rrBackoff := withBackoff(c.roundRobinQuorumBackoff(defaultBackoffWaitBetween, defaultBackoffJitterFraction))
  207. opts = append(opts,
  208. // Disable stream retry by default since go-grpc-middleware/retry does not support client streams.
  209. // Streams that are safe to retry are enabled individually.
  210. grpc.WithStreamInterceptor(c.streamClientInterceptor(withMax(0), rrBackoff)),
  211. grpc.WithUnaryInterceptor(c.unaryClientInterceptor(withMax(defaultUnaryMaxRetries), rrBackoff)),
  212. )
  213. return opts, nil
  214. }
  215. // Dial connects to a single endpoint using the client's config.
  216. func (c *Client) Dial(ep string) (*grpc.ClientConn, error) {
  217. creds := c.credentialsForEndpoint(ep)
  218. // Using ad-hoc created resolver, to guarantee only explicitly given
  219. // endpoint is used.
  220. return c.dial(creds, grpc.WithResolvers(resolver.New(ep)))
  221. }
  222. func (c *Client) getToken(ctx context.Context) error {
  223. var err error // return last error in a case of fail
  224. if c.Username == "" || c.Password == "" {
  225. return nil
  226. }
  227. resp, err := c.Auth.Authenticate(ctx, c.Username, c.Password)
  228. if err != nil {
  229. if err == rpctypes.ErrAuthNotEnabled {
  230. return nil
  231. }
  232. return err
  233. }
  234. c.authTokenBundle.UpdateAuthToken(resp.Token)
  235. return nil
  236. }
  237. // dialWithBalancer dials the client's current load balanced resolver group. The scheme of the host
  238. // of the provided endpoint determines the scheme used for all endpoints of the client connection.
  239. func (c *Client) dialWithBalancer(dopts ...grpc.DialOption) (*grpc.ClientConn, error) {
  240. creds := c.credentialsForEndpoint(c.Endpoints()[0])
  241. opts := append(dopts, grpc.WithResolvers(c.resolver))
  242. return c.dial(creds, opts...)
  243. }
  244. // dial configures and dials any grpc balancer target.
  245. func (c *Client) dial(creds grpccredentials.TransportCredentials, dopts ...grpc.DialOption) (*grpc.ClientConn, error) {
  246. opts, err := c.dialSetupOpts(creds, dopts...)
  247. if err != nil {
  248. return nil, fmt.Errorf("failed to configure dialer: %v", err)
  249. }
  250. if c.authTokenBundle != nil {
  251. opts = append(opts, grpc.WithPerRPCCredentials(c.authTokenBundle.PerRPCCredentials()))
  252. }
  253. opts = append(opts, c.cfg.DialOptions...)
  254. dctx := c.ctx
  255. if c.cfg.DialTimeout > 0 {
  256. var cancel context.CancelFunc
  257. dctx, cancel = context.WithTimeout(c.ctx, c.cfg.DialTimeout)
  258. defer cancel() // TODO: Is this right for cases where grpc.WithBlock() is not set on the dial options?
  259. }
  260. target := fmt.Sprintf("%s://%p/%s", resolver.Schema, c, authority(c.Endpoints()[0]))
  261. conn, err := grpc.DialContext(dctx, target, opts...)
  262. if err != nil {
  263. return nil, err
  264. }
  265. return conn, nil
  266. }
  267. func authority(endpoint string) string {
  268. spl := strings.SplitN(endpoint, "://", 2)
  269. if len(spl) < 2 {
  270. if strings.HasPrefix(endpoint, "unix:") {
  271. return endpoint[len("unix:"):]
  272. }
  273. if strings.HasPrefix(endpoint, "unixs:") {
  274. return endpoint[len("unixs:"):]
  275. }
  276. return endpoint
  277. }
  278. return spl[1]
  279. }
  280. func (c *Client) credentialsForEndpoint(ep string) grpccredentials.TransportCredentials {
  281. r := endpoint.RequiresCredentials(ep)
  282. switch r {
  283. case endpoint.CREDS_DROP:
  284. return nil
  285. case endpoint.CREDS_OPTIONAL:
  286. return c.creds
  287. case endpoint.CREDS_REQUIRE:
  288. if c.creds != nil {
  289. return c.creds
  290. }
  291. return credentials.NewBundle(credentials.Config{}).TransportCredentials()
  292. default:
  293. panic(fmt.Errorf("unsupported CredsRequirement: %v", r))
  294. }
  295. }
  296. func newClient(cfg *Config) (*Client, error) {
  297. if cfg == nil {
  298. cfg = &Config{}
  299. }
  300. var creds grpccredentials.TransportCredentials
  301. if cfg.TLS != nil {
  302. creds = credentials.NewBundle(credentials.Config{TLSConfig: cfg.TLS}).TransportCredentials()
  303. }
  304. // use a temporary skeleton client to bootstrap first connection
  305. baseCtx := context.TODO()
  306. if cfg.Context != nil {
  307. baseCtx = cfg.Context
  308. }
  309. ctx, cancel := context.WithCancel(baseCtx)
  310. client := &Client{
  311. conn: nil,
  312. cfg: *cfg,
  313. creds: creds,
  314. ctx: ctx,
  315. cancel: cancel,
  316. mu: new(sync.RWMutex),
  317. callOpts: defaultCallOpts,
  318. lgMu: new(sync.RWMutex),
  319. }
  320. var err error
  321. if cfg.Logger != nil {
  322. client.lg = cfg.Logger
  323. } else if cfg.LogConfig != nil {
  324. client.lg, err = cfg.LogConfig.Build()
  325. } else {
  326. client.lg, err = logutil.CreateDefaultZapLogger(etcdClientDebugLevel())
  327. if client.lg != nil {
  328. client.lg = client.lg.Named("etcd-client")
  329. }
  330. }
  331. if err != nil {
  332. return nil, err
  333. }
  334. if cfg.Username != "" && cfg.Password != "" {
  335. client.Username = cfg.Username
  336. client.Password = cfg.Password
  337. client.authTokenBundle = credentials.NewBundle(credentials.Config{})
  338. }
  339. if cfg.MaxCallSendMsgSize > 0 || cfg.MaxCallRecvMsgSize > 0 {
  340. if cfg.MaxCallRecvMsgSize > 0 && cfg.MaxCallSendMsgSize > cfg.MaxCallRecvMsgSize {
  341. return nil, fmt.Errorf("gRPC message recv limit (%d bytes) must be greater than send limit (%d bytes)", cfg.MaxCallRecvMsgSize, cfg.MaxCallSendMsgSize)
  342. }
  343. callOpts := []grpc.CallOption{
  344. defaultWaitForReady,
  345. defaultMaxCallSendMsgSize,
  346. defaultMaxCallRecvMsgSize,
  347. }
  348. if cfg.MaxCallSendMsgSize > 0 {
  349. callOpts[1] = grpc.MaxCallSendMsgSize(cfg.MaxCallSendMsgSize)
  350. }
  351. if cfg.MaxCallRecvMsgSize > 0 {
  352. callOpts[2] = grpc.MaxCallRecvMsgSize(cfg.MaxCallRecvMsgSize)
  353. }
  354. client.callOpts = callOpts
  355. }
  356. client.resolver = resolver.New(cfg.Endpoints...)
  357. if len(cfg.Endpoints) < 1 {
  358. client.cancel()
  359. return nil, fmt.Errorf("at least one Endpoint is required in client config")
  360. }
  361. // Use a provided endpoint target so that for https:// without any tls config given, then
  362. // grpc will assume the certificate server name is the endpoint host.
  363. conn, err := client.dialWithBalancer()
  364. if err != nil {
  365. client.cancel()
  366. client.resolver.Close()
  367. // TODO: Error like `fmt.Errorf(dialing [%s] failed: %v, strings.Join(cfg.Endpoints, ";"), err)` would help with debugging a lot.
  368. return nil, err
  369. }
  370. client.conn = conn
  371. client.Cluster = NewCluster(client)
  372. client.KV = NewKV(client)
  373. client.Lease = NewLease(client)
  374. client.Watcher = NewWatcher(client)
  375. client.Auth = NewAuth(client)
  376. client.Maintenance = NewMaintenance(client)
  377. //get token with established connection
  378. ctx, cancel = client.ctx, func() {}
  379. if client.cfg.DialTimeout > 0 {
  380. ctx, cancel = context.WithTimeout(ctx, client.cfg.DialTimeout)
  381. }
  382. err = client.getToken(ctx)
  383. if err != nil {
  384. client.Close()
  385. cancel()
  386. //TODO: Consider fmt.Errorf("communicating with [%s] failed: %v", strings.Join(cfg.Endpoints, ";"), err)
  387. return nil, err
  388. }
  389. cancel()
  390. if cfg.RejectOldCluster {
  391. if err := client.checkVersion(); err != nil {
  392. client.Close()
  393. return nil, err
  394. }
  395. }
  396. go client.autoSync()
  397. return client, nil
  398. }
  399. // roundRobinQuorumBackoff retries against quorum between each backoff.
  400. // This is intended for use with a round robin load balancer.
  401. func (c *Client) roundRobinQuorumBackoff(waitBetween time.Duration, jitterFraction float64) backoffFunc {
  402. return func(attempt uint) time.Duration {
  403. // after each round robin across quorum, backoff for our wait between duration
  404. n := uint(len(c.Endpoints()))
  405. quorum := (n/2 + 1)
  406. if attempt%quorum == 0 {
  407. c.lg.Debug("backoff", zap.Uint("attempt", attempt), zap.Uint("quorum", quorum), zap.Duration("waitBetween", waitBetween), zap.Float64("jitterFraction", jitterFraction))
  408. return jitterUp(waitBetween, jitterFraction)
  409. }
  410. c.lg.Debug("backoff skipped", zap.Uint("attempt", attempt), zap.Uint("quorum", quorum))
  411. return 0
  412. }
  413. }
  414. func (c *Client) checkVersion() (err error) {
  415. var wg sync.WaitGroup
  416. eps := c.Endpoints()
  417. errc := make(chan error, len(eps))
  418. ctx, cancel := context.WithCancel(c.ctx)
  419. if c.cfg.DialTimeout > 0 {
  420. cancel()
  421. ctx, cancel = context.WithTimeout(c.ctx, c.cfg.DialTimeout)
  422. }
  423. wg.Add(len(eps))
  424. for _, ep := range eps {
  425. // if cluster is current, any endpoint gives a recent version
  426. go func(e string) {
  427. defer wg.Done()
  428. resp, rerr := c.Status(ctx, e)
  429. if rerr != nil {
  430. errc <- rerr
  431. return
  432. }
  433. vs := strings.Split(resp.Version, ".")
  434. maj, min := 0, 0
  435. if len(vs) >= 2 {
  436. var serr error
  437. if maj, serr = strconv.Atoi(vs[0]); serr != nil {
  438. errc <- serr
  439. return
  440. }
  441. if min, serr = strconv.Atoi(vs[1]); serr != nil {
  442. errc <- serr
  443. return
  444. }
  445. }
  446. if maj < 3 || (maj == 3 && min < 2) {
  447. rerr = ErrOldCluster
  448. }
  449. errc <- rerr
  450. }(ep)
  451. }
  452. // wait for success
  453. for range eps {
  454. if err = <-errc; err == nil {
  455. break
  456. }
  457. }
  458. cancel()
  459. wg.Wait()
  460. return err
  461. }
  462. // ActiveConnection returns the current in-use connection
  463. func (c *Client) ActiveConnection() *grpc.ClientConn { return c.conn }
  464. // isHaltErr returns true if the given error and context indicate no forward
  465. // progress can be made, even after reconnecting.
  466. func isHaltErr(ctx context.Context, err error) bool {
  467. if ctx != nil && ctx.Err() != nil {
  468. return true
  469. }
  470. if err == nil {
  471. return false
  472. }
  473. ev, _ := status.FromError(err)
  474. // Unavailable codes mean the system will be right back.
  475. // (e.g., can't connect, lost leader)
  476. // Treat Internal codes as if something failed, leaving the
  477. // system in an inconsistent state, but retrying could make progress.
  478. // (e.g., failed in middle of send, corrupted frame)
  479. // TODO: are permanent Internal errors possible from grpc?
  480. return ev.Code() != codes.Unavailable && ev.Code() != codes.Internal
  481. }
  482. // isUnavailableErr returns true if the given error is an unavailable error
  483. func isUnavailableErr(ctx context.Context, err error) bool {
  484. if ctx != nil && ctx.Err() != nil {
  485. return false
  486. }
  487. if err == nil {
  488. return false
  489. }
  490. ev, ok := status.FromError(err)
  491. if ok {
  492. // Unavailable codes mean the system will be right back.
  493. // (e.g., can't connect, lost leader)
  494. return ev.Code() == codes.Unavailable
  495. }
  496. return false
  497. }
  498. func toErr(ctx context.Context, err error) error {
  499. if err == nil {
  500. return nil
  501. }
  502. err = rpctypes.Error(err)
  503. if _, ok := err.(rpctypes.EtcdError); ok {
  504. return err
  505. }
  506. if ev, ok := status.FromError(err); ok {
  507. code := ev.Code()
  508. switch code {
  509. case codes.DeadlineExceeded:
  510. fallthrough
  511. case codes.Canceled:
  512. if ctx.Err() != nil {
  513. err = ctx.Err()
  514. }
  515. }
  516. }
  517. return err
  518. }
  519. func canceledByCaller(stopCtx context.Context, err error) bool {
  520. if stopCtx.Err() == nil || err == nil {
  521. return false
  522. }
  523. return err == context.Canceled || err == context.DeadlineExceeded
  524. }
  525. // IsConnCanceled returns true, if error is from a closed gRPC connection.
  526. // ref. https://github.com/grpc/grpc-go/pull/1854
  527. func IsConnCanceled(err error) bool {
  528. if err == nil {
  529. return false
  530. }
  531. // >= gRPC v1.23.x
  532. s, ok := status.FromError(err)
  533. if ok {
  534. // connection is canceled or server has already closed the connection
  535. return s.Code() == codes.Canceled || s.Message() == "transport is closing"
  536. }
  537. // >= gRPC v1.10.x
  538. if err == context.Canceled {
  539. return true
  540. }
  541. // <= gRPC v1.7.x returns 'errors.New("grpc: the client connection is closing")'
  542. return strings.Contains(err.Error(), "grpc: the client connection is closing")
  543. }