client.go 14 KB

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