client.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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. defaultBalancer balancer.Balancer
  43. )
  44. func init() {
  45. defaultBalancer = balancer.New(balancer.Config{
  46. Policy: picker.RoundrobinBalanced,
  47. Name: fmt.Sprintf("etcd-%s", picker.RoundrobinBalanced.String()),
  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. c.mu.Lock()
  125. c.cfg.Endpoints = eps
  126. c.mu.Unlock()
  127. var addrs []resolver.Address
  128. for _, ep := range eps {
  129. addrs = append(addrs, resolver.Address{Addr: ep})
  130. }
  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(host string, t time.Duration) (net.Conn, error) {
  221. // TODO: eliminate this ParseEndpoint call, the endpoint is already parsed by the resolver.
  222. proto, host, _ := endpoint.ParseEndpoint(c.resolver.Endpoint(host))
  223. if host == "" && ep != "" {
  224. // dialing an endpoint not in the balancer; use
  225. // endpoint passed into dial
  226. proto, host, _ = endpoint.ParseEndpoint(ep)
  227. }
  228. if proto == "" {
  229. return nil, fmt.Errorf("unknown scheme for %q", host)
  230. }
  231. select {
  232. case <-c.ctx.Done():
  233. return nil, c.ctx.Err()
  234. default:
  235. }
  236. dialer := &net.Dialer{Timeout: t}
  237. conn, err := dialer.DialContext(c.ctx, proto, host)
  238. if err != nil {
  239. select {
  240. case c.dialerrc <- err:
  241. default:
  242. }
  243. }
  244. return conn, err
  245. }
  246. opts = append(opts, grpc.WithDialer(f))
  247. creds := c.creds
  248. if _, _, scheme := endpoint.ParseEndpoint(ep); len(scheme) != 0 {
  249. creds = c.processCreds(scheme)
  250. }
  251. if creds != nil {
  252. opts = append(opts, grpc.WithTransportCredentials(*creds))
  253. } else {
  254. opts = append(opts, grpc.WithInsecure())
  255. }
  256. return opts, nil
  257. }
  258. // Dial connects to a single endpoint using the client's config.
  259. func (c *Client) Dial(endpoint string) (*grpc.ClientConn, error) {
  260. return c.dial(endpoint)
  261. }
  262. func (c *Client) getToken(ctx context.Context) error {
  263. var err error // return last error in a case of fail
  264. var auth *authenticator
  265. for i := 0; i < len(c.cfg.Endpoints); i++ {
  266. endpoint := c.cfg.Endpoints[i]
  267. host := getHost(endpoint)
  268. // use dial options without dopts to avoid reusing the client balancer
  269. var dOpts []grpc.DialOption
  270. dOpts, err = c.dialSetupOpts(c.resolver.Target(endpoint))
  271. if err != nil {
  272. continue
  273. }
  274. auth, err = newAuthenticator(host, dOpts, c)
  275. if err != nil {
  276. continue
  277. }
  278. defer auth.close()
  279. var resp *AuthenticateResponse
  280. resp, err = auth.authenticate(ctx, c.Username, c.Password)
  281. if err != nil {
  282. continue
  283. }
  284. c.tokenCred.tokenMu.Lock()
  285. c.tokenCred.token = resp.Token
  286. c.tokenCred.tokenMu.Unlock()
  287. return nil
  288. }
  289. return err
  290. }
  291. func (c *Client) dial(endpoint string, dopts ...grpc.DialOption) (*grpc.ClientConn, error) {
  292. opts, err := c.dialSetupOpts(endpoint, dopts...)
  293. if err != nil {
  294. return nil, err
  295. }
  296. if c.Username != "" && c.Password != "" {
  297. c.tokenCred = &authTokenCredential{
  298. tokenMu: &sync.RWMutex{},
  299. }
  300. ctx := c.ctx
  301. if c.cfg.DialTimeout > 0 {
  302. cctx, cancel := context.WithTimeout(ctx, c.cfg.DialTimeout)
  303. defer cancel()
  304. ctx = cctx
  305. }
  306. err = c.getToken(ctx)
  307. if err != nil {
  308. if toErr(ctx, err) != rpctypes.ErrAuthNotEnabled {
  309. if err == ctx.Err() && ctx.Err() != c.ctx.Err() {
  310. err = context.DeadlineExceeded
  311. }
  312. return nil, err
  313. }
  314. } else {
  315. opts = append(opts, grpc.WithPerRPCCredentials(c.tokenCred))
  316. }
  317. }
  318. opts = append(opts, c.cfg.DialOptions...)
  319. // TODO: The hosts check doesn't really make sense for a load balanced endpoint url for the new grpc load balancer interface.
  320. // Is it safe/sane to use the provided endpoint here?
  321. //host := getHost(endpoint)
  322. //conn, err := grpc.DialContext(c.ctx, host, opts...)
  323. conn, err := grpc.DialContext(c.ctx, endpoint, 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. dialerrc: make(chan error, 1),
  353. cfg: *cfg,
  354. creds: creds,
  355. ctx: ctx,
  356. cancel: cancel,
  357. mu: new(sync.Mutex),
  358. callOpts: defaultCallOpts,
  359. }
  360. if cfg.Username != "" && cfg.Password != "" {
  361. client.Username = cfg.Username
  362. client.Password = cfg.Password
  363. }
  364. if cfg.MaxCallSendMsgSize > 0 || cfg.MaxCallRecvMsgSize > 0 {
  365. if cfg.MaxCallRecvMsgSize > 0 && cfg.MaxCallSendMsgSize > cfg.MaxCallRecvMsgSize {
  366. return nil, fmt.Errorf("gRPC message recv limit (%d bytes) must be greater than send limit (%d bytes)", cfg.MaxCallRecvMsgSize, cfg.MaxCallSendMsgSize)
  367. }
  368. callOpts := []grpc.CallOption{
  369. defaultFailFast,
  370. defaultMaxCallSendMsgSize,
  371. defaultMaxCallRecvMsgSize,
  372. }
  373. if cfg.MaxCallSendMsgSize > 0 {
  374. callOpts[1] = grpc.MaxCallSendMsgSize(cfg.MaxCallSendMsgSize)
  375. }
  376. if cfg.MaxCallRecvMsgSize > 0 {
  377. callOpts[2] = grpc.MaxCallRecvMsgSize(cfg.MaxCallRecvMsgSize)
  378. }
  379. client.callOpts = callOpts
  380. }
  381. clientId := fmt.Sprintf("client-%s", strconv.FormatInt(time.Now().UnixNano(), 36))
  382. rsv := endpoint.EndpointResolver(clientId)
  383. rsv.InitialEndpoints(cfg.Endpoints)
  384. targets := []string{}
  385. for _, ep := range cfg.Endpoints {
  386. targets = append(targets, fmt.Sprintf("endpoint://%s/%s", clientId, ep))
  387. }
  388. client.resolver = rsv
  389. client.balancer = defaultBalancer // TODO: allow alternate balancers to be passed in via config?
  390. // use Endpoints[0] so that for https:// without any tls config given, then
  391. // grpc will assume the certificate server name is the endpoint host.
  392. conn, err := client.dial(targets[0], grpc.WithBalancerName(client.balancer.Name()))
  393. if err != nil {
  394. client.cancel()
  395. rsv.Close()
  396. return nil, err
  397. }
  398. // TODO: With the old grpc balancer interface, we waited until the dial timeout
  399. // for the balancer to be ready. Is there an equivalent wait we should do with the new grpc balancer interface?
  400. client.conn = conn
  401. client.Cluster = NewCluster(client)
  402. client.KV = NewKV(client)
  403. client.Lease = NewLease(client)
  404. client.Watcher = NewWatcher(client)
  405. client.Auth = NewAuth(client)
  406. client.Maintenance = NewMaintenance(client)
  407. if cfg.RejectOldCluster {
  408. if err := client.checkVersion(); err != nil {
  409. client.Close()
  410. return nil, err
  411. }
  412. }
  413. go client.autoSync()
  414. return client, nil
  415. }
  416. func (c *Client) checkVersion() (err error) {
  417. var wg sync.WaitGroup
  418. errc := make(chan error, len(c.cfg.Endpoints))
  419. ctx, cancel := context.WithCancel(c.ctx)
  420. if c.cfg.DialTimeout > 0 {
  421. ctx, cancel = context.WithTimeout(ctx, c.cfg.DialTimeout)
  422. }
  423. wg.Add(len(c.cfg.Endpoints))
  424. for _, ep := range c.cfg.Endpoints {
  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. maj, _ = strconv.Atoi(vs[0])
  437. min, rerr = strconv.Atoi(vs[1])
  438. }
  439. if maj < 3 || (maj == 3 && min < 2) {
  440. rerr = ErrOldCluster
  441. }
  442. errc <- rerr
  443. }(ep)
  444. }
  445. // wait for success
  446. for i := 0; i < len(c.cfg.Endpoints); i++ {
  447. if err = <-errc; err == nil {
  448. break
  449. }
  450. }
  451. cancel()
  452. wg.Wait()
  453. return err
  454. }
  455. // ActiveConnection returns the current in-use connection
  456. func (c *Client) ActiveConnection() *grpc.ClientConn { return c.conn }
  457. // isHaltErr returns true if the given error and context indicate no forward
  458. // progress can be made, even after reconnecting.
  459. func isHaltErr(ctx context.Context, err error) bool {
  460. if ctx != nil && ctx.Err() != nil {
  461. return true
  462. }
  463. if err == nil {
  464. return false
  465. }
  466. ev, _ := status.FromError(err)
  467. // Unavailable codes mean the system will be right back.
  468. // (e.g., can't connect, lost leader)
  469. // Treat Internal codes as if something failed, leaving the
  470. // system in an inconsistent state, but retrying could make progress.
  471. // (e.g., failed in middle of send, corrupted frame)
  472. // TODO: are permanent Internal errors possible from grpc?
  473. return ev.Code() != codes.Unavailable && ev.Code() != codes.Internal
  474. }
  475. // isUnavailableErr returns true if the given error is an unavailable error
  476. func isUnavailableErr(ctx context.Context, err error) bool {
  477. if ctx != nil && ctx.Err() != nil {
  478. return false
  479. }
  480. if err == nil {
  481. return false
  482. }
  483. ev, _ := status.FromError(err)
  484. // Unavailable codes mean the system will be right back.
  485. // (e.g., can't connect, lost leader)
  486. return ev.Code() == codes.Unavailable
  487. }
  488. func toErr(ctx context.Context, err error) error {
  489. if err == nil {
  490. return nil
  491. }
  492. err = rpctypes.Error(err)
  493. if _, ok := err.(rpctypes.EtcdError); ok {
  494. return err
  495. }
  496. if ev, ok := status.FromError(err); ok {
  497. code := ev.Code()
  498. switch code {
  499. case codes.DeadlineExceeded:
  500. fallthrough
  501. case codes.Canceled:
  502. if ctx.Err() != nil {
  503. err = ctx.Err()
  504. }
  505. case codes.Unavailable:
  506. case codes.FailedPrecondition:
  507. err = grpc.ErrClientConnClosing
  508. }
  509. }
  510. return err
  511. }
  512. func canceledByCaller(stopCtx context.Context, err error) bool {
  513. if stopCtx.Err() == nil || err == nil {
  514. return false
  515. }
  516. return err == context.Canceled || err == context.DeadlineExceeded
  517. }
  518. func getHost(ep string) string {
  519. url, uerr := url.Parse(ep)
  520. if uerr != nil || !strings.Contains(ep, "://") {
  521. return ep
  522. }
  523. return url.Host
  524. }