client.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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. "go.uber.org/zap"
  31. "google.golang.org/grpc"
  32. "google.golang.org/grpc/codes"
  33. "google.golang.org/grpc/credentials"
  34. "google.golang.org/grpc/keepalive"
  35. "google.golang.org/grpc/metadata"
  36. "google.golang.org/grpc/resolver"
  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. Logger: zap.NewNop(), // zap.NewExample(),
  49. })
  50. }
  51. // Client provides and manages an etcd v3 client session.
  52. type Client struct {
  53. Cluster
  54. KV
  55. Lease
  56. Watcher
  57. Auth
  58. Maintenance
  59. conn *grpc.ClientConn
  60. dialerrc chan error
  61. cfg Config
  62. creds *credentials.TransportCredentials
  63. balancer balancer.Balancer
  64. resolver *endpoint.Resolver
  65. mu *sync.Mutex
  66. ctx context.Context
  67. cancel context.CancelFunc
  68. // Username is a user name for authentication.
  69. Username string
  70. // Password is a password for authentication.
  71. Password string
  72. // tokenCred is an instance of WithPerRPCCredentials()'s argument
  73. tokenCred *authTokenCredential
  74. callOpts []grpc.CallOption
  75. }
  76. // New creates a new etcdv3 client from a given configuration.
  77. func New(cfg Config) (*Client, error) {
  78. if len(cfg.Endpoints) == 0 {
  79. return nil, ErrNoAvailableEndpoints
  80. }
  81. return newClient(&cfg)
  82. }
  83. // NewCtxClient creates a client with a context but no underlying grpc
  84. // connection. This is useful for embedded cases that override the
  85. // service interface implementations and do not need connection management.
  86. func NewCtxClient(ctx context.Context) *Client {
  87. cctx, cancel := context.WithCancel(ctx)
  88. return &Client{ctx: cctx, cancel: cancel}
  89. }
  90. // NewFromURL creates a new etcdv3 client from a URL.
  91. func NewFromURL(url string) (*Client, error) {
  92. return New(Config{Endpoints: []string{url}})
  93. }
  94. // NewFromURLs creates a new etcdv3 client from URLs.
  95. func NewFromURLs(urls []string) (*Client, error) {
  96. return New(Config{Endpoints: urls})
  97. }
  98. // Close shuts down the client's etcd connections.
  99. func (c *Client) Close() error {
  100. c.cancel()
  101. c.Watcher.Close()
  102. c.Lease.Close()
  103. if c.conn != nil {
  104. return toErr(c.ctx, c.conn.Close())
  105. }
  106. if c.resolver != nil {
  107. c.resolver.Close()
  108. }
  109. return c.ctx.Err()
  110. }
  111. // Ctx is a context for "out of band" messages (e.g., for sending
  112. // "clean up" message when another context is canceled). It is
  113. // canceled on client Close().
  114. func (c *Client) Ctx() context.Context { return c.ctx }
  115. // Endpoints lists the registered endpoints for the client.
  116. func (c *Client) Endpoints() (eps []string) {
  117. // copy the slice; protect original endpoints from being changed
  118. eps = make([]string, len(c.cfg.Endpoints))
  119. copy(eps, c.cfg.Endpoints)
  120. return
  121. }
  122. // SetEndpoints updates client's endpoints.
  123. func (c *Client) SetEndpoints(eps ...string) {
  124. var addrs []resolver.Address
  125. for _, ep := range eps {
  126. addrs = append(addrs, resolver.Address{Addr: ep})
  127. }
  128. c.mu.Lock()
  129. defer c.mu.Unlock()
  130. c.cfg.Endpoints = eps
  131. c.resolver.NewAddress(addrs)
  132. // TODO: Does the new grpc balancer provide a way to block until the endpoint changes are propagated?
  133. /*if c.balancer.NeedUpdate() {
  134. select {
  135. case c.balancer.UpdateAddrsC() <- balancer.NotifyNext:
  136. case <-c.balancer.StopC():
  137. }
  138. }*/
  139. }
  140. // Sync synchronizes client's endpoints with the known endpoints from the etcd membership.
  141. func (c *Client) Sync(ctx context.Context) error {
  142. mresp, err := c.MemberList(ctx)
  143. if err != nil {
  144. return err
  145. }
  146. var eps []string
  147. for _, m := range mresp.Members {
  148. eps = append(eps, m.ClientURLs...)
  149. }
  150. c.SetEndpoints(eps...)
  151. return nil
  152. }
  153. func (c *Client) autoSync() {
  154. if c.cfg.AutoSyncInterval == time.Duration(0) {
  155. return
  156. }
  157. for {
  158. select {
  159. case <-c.ctx.Done():
  160. return
  161. case <-time.After(c.cfg.AutoSyncInterval):
  162. ctx, cancel := context.WithTimeout(c.ctx, 5*time.Second)
  163. err := c.Sync(ctx)
  164. cancel()
  165. if err != nil && err != c.ctx.Err() {
  166. lg.Lvl(4).Infof("Auto sync endpoints failed: %v", err)
  167. }
  168. }
  169. }
  170. }
  171. type authTokenCredential struct {
  172. token string
  173. tokenMu *sync.RWMutex
  174. }
  175. func (cred authTokenCredential) RequireTransportSecurity() bool {
  176. return false
  177. }
  178. func (cred authTokenCredential) GetRequestMetadata(ctx context.Context, s ...string) (map[string]string, error) {
  179. cred.tokenMu.RLock()
  180. defer cred.tokenMu.RUnlock()
  181. return map[string]string{
  182. rpctypes.TokenFieldNameGRPC: cred.token,
  183. }, nil
  184. }
  185. func (c *Client) processCreds(scheme string) (creds *credentials.TransportCredentials) {
  186. creds = c.creds
  187. switch scheme {
  188. case "unix":
  189. case "http":
  190. creds = nil
  191. case "https", "unixs":
  192. if creds != nil {
  193. break
  194. }
  195. tlsconfig := &tls.Config{}
  196. emptyCreds := credentials.NewTLS(tlsconfig)
  197. creds = &emptyCreds
  198. default:
  199. creds = nil
  200. }
  201. return creds
  202. }
  203. // dialSetupOpts gives the dial opts prior to any authentication
  204. func (c *Client) dialSetupOpts(target string, dopts ...grpc.DialOption) (opts []grpc.DialOption, err error) {
  205. _, ep, err := endpoint.ParseTarget(target)
  206. if err != nil {
  207. return nil, fmt.Errorf("unable to parse target: %v", err)
  208. }
  209. if c.cfg.DialTimeout > 0 {
  210. opts = []grpc.DialOption{grpc.WithTimeout(c.cfg.DialTimeout)}
  211. }
  212. if c.cfg.DialKeepAliveTime > 0 {
  213. params := keepalive.ClientParameters{
  214. Time: c.cfg.DialKeepAliveTime,
  215. Timeout: c.cfg.DialKeepAliveTimeout,
  216. }
  217. opts = append(opts, grpc.WithKeepaliveParams(params))
  218. }
  219. opts = append(opts, dopts...)
  220. f := func(dialEp string, t time.Duration) (net.Conn, error) {
  221. proto, host, _ := endpoint.ParseEndpoint(dialEp)
  222. if host == "" && ep != "" {
  223. // dialing an endpoint not in the balancer; use
  224. // endpoint passed into dial
  225. proto, host, _ = endpoint.ParseEndpoint(ep)
  226. }
  227. if proto == "" {
  228. return nil, fmt.Errorf("unknown scheme for %q", host)
  229. }
  230. select {
  231. case <-c.ctx.Done():
  232. return nil, c.ctx.Err()
  233. default:
  234. }
  235. dialer := &net.Dialer{Timeout: t}
  236. conn, err := dialer.DialContext(c.ctx, proto, host)
  237. if err != nil {
  238. select {
  239. case c.dialerrc <- err:
  240. default:
  241. }
  242. }
  243. return conn, err
  244. }
  245. opts = append(opts, grpc.WithDialer(f))
  246. creds := c.creds
  247. if _, _, scheme := endpoint.ParseEndpoint(ep); len(scheme) != 0 {
  248. creds = c.processCreds(scheme)
  249. }
  250. if creds != nil {
  251. opts = append(opts, grpc.WithTransportCredentials(*creds))
  252. } else {
  253. opts = append(opts, grpc.WithInsecure())
  254. }
  255. return opts, nil
  256. }
  257. // Dial connects to a single endpoint using the client's config.
  258. func (c *Client) Dial(endpoint string) (*grpc.ClientConn, error) {
  259. return c.dial(endpoint)
  260. }
  261. func (c *Client) getToken(ctx context.Context) error {
  262. var err error // return last error in a case of fail
  263. var auth *authenticator
  264. for i := 0; i < len(c.cfg.Endpoints); i++ {
  265. endpoint := c.cfg.Endpoints[i]
  266. host := getHost(endpoint)
  267. // use dial options without dopts to avoid reusing the client balancer
  268. var dOpts []grpc.DialOption
  269. dOpts, err = c.dialSetupOpts(c.resolver.Target(endpoint))
  270. if err != nil {
  271. continue
  272. }
  273. auth, err = newAuthenticator(host, dOpts, c)
  274. if err != nil {
  275. continue
  276. }
  277. defer auth.close()
  278. var resp *AuthenticateResponse
  279. resp, err = auth.authenticate(ctx, c.Username, c.Password)
  280. if err != nil {
  281. continue
  282. }
  283. c.tokenCred.tokenMu.Lock()
  284. c.tokenCred.token = resp.Token
  285. c.tokenCred.tokenMu.Unlock()
  286. return nil
  287. }
  288. return err
  289. }
  290. func (c *Client) dial(endpoint string, dopts ...grpc.DialOption) (*grpc.ClientConn, error) {
  291. opts, err := c.dialSetupOpts(endpoint, dopts...)
  292. if err != nil {
  293. return nil, err
  294. }
  295. if c.Username != "" && c.Password != "" {
  296. c.tokenCred = &authTokenCredential{
  297. tokenMu: &sync.RWMutex{},
  298. }
  299. ctx := c.ctx
  300. if c.cfg.DialTimeout > 0 {
  301. cctx, cancel := context.WithTimeout(ctx, c.cfg.DialTimeout)
  302. defer cancel()
  303. ctx = cctx
  304. }
  305. err = c.getToken(ctx)
  306. if err != nil {
  307. if toErr(ctx, err) != rpctypes.ErrAuthNotEnabled {
  308. if err == ctx.Err() && ctx.Err() != c.ctx.Err() {
  309. err = context.DeadlineExceeded
  310. }
  311. return nil, err
  312. }
  313. } else {
  314. opts = append(opts, grpc.WithPerRPCCredentials(c.tokenCred))
  315. }
  316. }
  317. opts = append(opts, c.cfg.DialOptions...)
  318. // TODO: The hosts check doesn't really make sense for a load balanced endpoint url for the new grpc load balancer interface.
  319. // Is it safe/sane to use the provided endpoint here?
  320. //host := getHost(endpoint)
  321. //conn, err := grpc.DialContext(c.ctx, host, opts...)
  322. conn, err := grpc.DialContext(c.ctx, endpoint, opts...)
  323. if err != nil {
  324. return nil, err
  325. }
  326. return conn, nil
  327. }
  328. // WithRequireLeader requires client requests to only succeed
  329. // when the cluster has a leader.
  330. func WithRequireLeader(ctx context.Context) context.Context {
  331. md := metadata.Pairs(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
  332. return metadata.NewOutgoingContext(ctx, md)
  333. }
  334. func newClient(cfg *Config) (*Client, error) {
  335. if cfg == nil {
  336. cfg = &Config{}
  337. }
  338. var creds *credentials.TransportCredentials
  339. if cfg.TLS != nil {
  340. c := credentials.NewTLS(cfg.TLS)
  341. creds = &c
  342. }
  343. // use a temporary skeleton client to bootstrap first connection
  344. baseCtx := context.TODO()
  345. if cfg.Context != nil {
  346. baseCtx = cfg.Context
  347. }
  348. ctx, cancel := context.WithCancel(baseCtx)
  349. client := &Client{
  350. conn: nil,
  351. dialerrc: make(chan error, 1),
  352. cfg: *cfg,
  353. creds: creds,
  354. ctx: ctx,
  355. cancel: cancel,
  356. mu: new(sync.Mutex),
  357. callOpts: defaultCallOpts,
  358. }
  359. if cfg.Username != "" && cfg.Password != "" {
  360. client.Username = cfg.Username
  361. client.Password = cfg.Password
  362. }
  363. if cfg.MaxCallSendMsgSize > 0 || cfg.MaxCallRecvMsgSize > 0 {
  364. if cfg.MaxCallRecvMsgSize > 0 && cfg.MaxCallSendMsgSize > cfg.MaxCallRecvMsgSize {
  365. return nil, fmt.Errorf("gRPC message recv limit (%d bytes) must be greater than send limit (%d bytes)", cfg.MaxCallRecvMsgSize, cfg.MaxCallSendMsgSize)
  366. }
  367. callOpts := []grpc.CallOption{
  368. defaultFailFast,
  369. defaultMaxCallSendMsgSize,
  370. defaultMaxCallRecvMsgSize,
  371. }
  372. if cfg.MaxCallSendMsgSize > 0 {
  373. callOpts[1] = grpc.MaxCallSendMsgSize(cfg.MaxCallSendMsgSize)
  374. }
  375. if cfg.MaxCallRecvMsgSize > 0 {
  376. callOpts[2] = grpc.MaxCallRecvMsgSize(cfg.MaxCallRecvMsgSize)
  377. }
  378. client.callOpts = callOpts
  379. }
  380. // Prepare a 'endpoint://<unique-client-id>/' resolver for the client and create a endpoint target to pass
  381. // to dial so the client knows to use this resolver.
  382. client.resolver = endpoint.EndpointResolver(fmt.Sprintf("client-%s", strconv.FormatInt(time.Now().UnixNano(), 36)))
  383. target, err := client.resolver.InitialEndpoints(cfg.Endpoints)
  384. if err != nil {
  385. client.cancel()
  386. client.resolver.Close()
  387. return nil, err
  388. }
  389. // Use an provided endpoint target so that for https:// without any tls config given, then
  390. // grpc will assume the certificate server name is the endpoint host.
  391. conn, err := client.dial(target, grpc.WithBalancerName(roundRobinBalancerName))
  392. if err != nil {
  393. client.cancel()
  394. client.resolver.Close()
  395. return nil, err
  396. }
  397. // TODO: With the old grpc balancer interface, we waited until the dial timeout
  398. // for the balancer to be ready. Is there an equivalent wait we should do with the new grpc balancer interface?
  399. client.conn = conn
  400. client.Cluster = NewCluster(client)
  401. client.KV = NewKV(client)
  402. client.Lease = NewLease(client)
  403. client.Watcher = NewWatcher(client)
  404. client.Auth = NewAuth(client)
  405. client.Maintenance = NewMaintenance(client)
  406. if cfg.RejectOldCluster {
  407. if err := client.checkVersion(); err != nil {
  408. client.Close()
  409. return nil, err
  410. }
  411. }
  412. go client.autoSync()
  413. return client, nil
  414. }
  415. func (c *Client) checkVersion() (err error) {
  416. var wg sync.WaitGroup
  417. errc := make(chan error, len(c.cfg.Endpoints))
  418. ctx, cancel := context.WithCancel(c.ctx)
  419. if c.cfg.DialTimeout > 0 {
  420. ctx, cancel = context.WithTimeout(ctx, c.cfg.DialTimeout)
  421. }
  422. wg.Add(len(c.cfg.Endpoints))
  423. for _, ep := range c.cfg.Endpoints {
  424. // if cluster is current, any endpoint gives a recent version
  425. go func(e string) {
  426. defer wg.Done()
  427. resp, rerr := c.Status(ctx, e)
  428. if rerr != nil {
  429. errc <- rerr
  430. return
  431. }
  432. vs := strings.Split(resp.Version, ".")
  433. maj, min := 0, 0
  434. if len(vs) >= 2 {
  435. maj, _ = strconv.Atoi(vs[0])
  436. min, rerr = strconv.Atoi(vs[1])
  437. }
  438. if maj < 3 || (maj == 3 && min < 2) {
  439. rerr = ErrOldCluster
  440. }
  441. errc <- rerr
  442. }(ep)
  443. }
  444. // wait for success
  445. for i := 0; i < len(c.cfg.Endpoints); i++ {
  446. if err = <-errc; err == nil {
  447. break
  448. }
  449. }
  450. cancel()
  451. wg.Wait()
  452. return err
  453. }
  454. // ActiveConnection returns the current in-use connection
  455. func (c *Client) ActiveConnection() *grpc.ClientConn { return c.conn }
  456. // isHaltErr returns true if the given error and context indicate no forward
  457. // progress can be made, even after reconnecting.
  458. func isHaltErr(ctx context.Context, err error) bool {
  459. if ctx != nil && ctx.Err() != nil {
  460. return true
  461. }
  462. if err == nil {
  463. return false
  464. }
  465. ev, _ := status.FromError(err)
  466. // Unavailable codes mean the system will be right back.
  467. // (e.g., can't connect, lost leader)
  468. // Treat Internal codes as if something failed, leaving the
  469. // system in an inconsistent state, but retrying could make progress.
  470. // (e.g., failed in middle of send, corrupted frame)
  471. // TODO: are permanent Internal errors possible from grpc?
  472. return ev.Code() != codes.Unavailable && ev.Code() != codes.Internal
  473. }
  474. // isUnavailableErr returns true if the given error is an unavailable error
  475. func isUnavailableErr(ctx context.Context, err error) bool {
  476. if ctx != nil && ctx.Err() != nil {
  477. return false
  478. }
  479. if err == nil {
  480. return false
  481. }
  482. ev, _ := status.FromError(err)
  483. // Unavailable codes mean the system will be right back.
  484. // (e.g., can't connect, lost leader)
  485. return ev.Code() == codes.Unavailable
  486. }
  487. func toErr(ctx context.Context, err error) error {
  488. if err == nil {
  489. return nil
  490. }
  491. err = rpctypes.Error(err)
  492. if _, ok := err.(rpctypes.EtcdError); ok {
  493. return err
  494. }
  495. if ev, ok := status.FromError(err); ok {
  496. code := ev.Code()
  497. switch code {
  498. case codes.DeadlineExceeded:
  499. fallthrough
  500. case codes.Canceled:
  501. if ctx.Err() != nil {
  502. err = ctx.Err()
  503. }
  504. case codes.Unavailable:
  505. case codes.FailedPrecondition:
  506. err = grpc.ErrClientConnClosing
  507. }
  508. }
  509. return err
  510. }
  511. func canceledByCaller(stopCtx context.Context, err error) bool {
  512. if stopCtx.Err() == nil || err == nil {
  513. return false
  514. }
  515. return err == context.Canceled || err == context.DeadlineExceeded
  516. }
  517. func getHost(ep string) string {
  518. url, uerr := url.Parse(ep)
  519. if uerr != nil || !strings.Contains(ep, "://") {
  520. return ep
  521. }
  522. return url.Host
  523. }