client.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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/etcdserver/api/v3rpc/rpctypes"
  27. "google.golang.org/grpc"
  28. "google.golang.org/grpc/codes"
  29. "google.golang.org/grpc/credentials"
  30. "google.golang.org/grpc/keepalive"
  31. "google.golang.org/grpc/metadata"
  32. "google.golang.org/grpc/status"
  33. )
  34. var (
  35. ErrNoAvailableEndpoints = errors.New("etcdclient: no available endpoints")
  36. ErrOldCluster = errors.New("etcdclient: old cluster version")
  37. )
  38. // Client provides and manages an etcd v3 client session.
  39. type Client struct {
  40. Cluster
  41. KV
  42. Lease
  43. Watcher
  44. Auth
  45. Maintenance
  46. conn *grpc.ClientConn
  47. dialerrc chan error
  48. cfg Config
  49. creds *credentials.TransportCredentials
  50. balancer *healthBalancer
  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. // tokenCred is an instance of WithPerRPCCredentials()'s argument
  59. tokenCred *authTokenCredential
  60. callOpts []grpc.CallOption
  61. }
  62. // New creates a new etcdv3 client from a given configuration.
  63. func New(cfg Config) (*Client, error) {
  64. if len(cfg.Endpoints) == 0 {
  65. return nil, ErrNoAvailableEndpoints
  66. }
  67. return newClient(&cfg)
  68. }
  69. // NewCtxClient creates a client with a context but no underlying grpc
  70. // connection. This is useful for embedded cases that override the
  71. // service interface implementations and do not need connection management.
  72. func NewCtxClient(ctx context.Context) *Client {
  73. cctx, cancel := context.WithCancel(ctx)
  74. return &Client{ctx: cctx, cancel: cancel}
  75. }
  76. // NewFromURL creates a new etcdv3 client from a URL.
  77. func NewFromURL(url string) (*Client, error) {
  78. return New(Config{Endpoints: []string{url}})
  79. }
  80. // Close shuts down the client's etcd connections.
  81. func (c *Client) Close() error {
  82. c.cancel()
  83. c.Watcher.Close()
  84. c.Lease.Close()
  85. if c.conn != nil {
  86. return toErr(c.ctx, c.conn.Close())
  87. }
  88. return c.ctx.Err()
  89. }
  90. // Ctx is a context for "out of band" messages (e.g., for sending
  91. // "clean up" message when another context is canceled). It is
  92. // canceled on client Close().
  93. func (c *Client) Ctx() context.Context { return c.ctx }
  94. // Endpoints lists the registered endpoints for the client.
  95. func (c *Client) Endpoints() []string {
  96. c.mu.RLock()
  97. defer c.mu.RUnlock()
  98. // copy the slice; protect original endpoints from being changed
  99. eps := make([]string, len(c.cfg.Endpoints))
  100. copy(eps, c.cfg.Endpoints)
  101. return eps
  102. }
  103. // SetEndpoints updates client's endpoints.
  104. func (c *Client) SetEndpoints(eps ...string) {
  105. c.mu.Lock()
  106. c.cfg.Endpoints = eps
  107. c.mu.Unlock()
  108. c.balancer.updateAddrs(eps...)
  109. // updating notifyCh can trigger new connections,
  110. // need update addrs if all connections are down
  111. // or addrs does not include pinAddr.
  112. c.balancer.mu.RLock()
  113. update := !hasAddr(c.balancer.addrs, c.balancer.pinAddr)
  114. c.balancer.mu.RUnlock()
  115. if update {
  116. select {
  117. case c.balancer.updateAddrsC <- notifyNext:
  118. case <-c.balancer.stopc:
  119. }
  120. }
  121. }
  122. // Sync synchronizes client's endpoints with the known endpoints from the etcd membership.
  123. func (c *Client) Sync(ctx context.Context) error {
  124. mresp, err := c.MemberList(ctx)
  125. if err != nil {
  126. return err
  127. }
  128. var eps []string
  129. for _, m := range mresp.Members {
  130. eps = append(eps, m.ClientURLs...)
  131. }
  132. c.SetEndpoints(eps...)
  133. return nil
  134. }
  135. func (c *Client) autoSync() {
  136. if c.cfg.AutoSyncInterval == time.Duration(0) {
  137. return
  138. }
  139. for {
  140. select {
  141. case <-c.ctx.Done():
  142. return
  143. case <-time.After(c.cfg.AutoSyncInterval):
  144. ctx, cancel := context.WithTimeout(c.ctx, 5*time.Second)
  145. err := c.Sync(ctx)
  146. cancel()
  147. if err != nil && err != c.ctx.Err() {
  148. logger.Println("Auto sync endpoints failed:", err)
  149. }
  150. }
  151. }
  152. }
  153. type authTokenCredential struct {
  154. token string
  155. tokenMu *sync.RWMutex
  156. }
  157. func (cred authTokenCredential) RequireTransportSecurity() bool {
  158. return false
  159. }
  160. func (cred authTokenCredential) GetRequestMetadata(ctx context.Context, s ...string) (map[string]string, error) {
  161. cred.tokenMu.RLock()
  162. defer cred.tokenMu.RUnlock()
  163. return map[string]string{
  164. "token": cred.token,
  165. }, nil
  166. }
  167. func parseEndpoint(endpoint string) (proto string, host string, scheme string) {
  168. proto = "tcp"
  169. host = endpoint
  170. url, uerr := url.Parse(endpoint)
  171. if uerr != nil || !strings.Contains(endpoint, "://") {
  172. return proto, host, scheme
  173. }
  174. scheme = url.Scheme
  175. // strip scheme:// prefix since grpc dials by host
  176. host = url.Host
  177. switch url.Scheme {
  178. case "http", "https":
  179. case "unix", "unixs":
  180. proto = "unix"
  181. host = url.Host + url.Path
  182. default:
  183. proto, host = "", ""
  184. }
  185. return proto, host, scheme
  186. }
  187. func (c *Client) processCreds(scheme string) (creds *credentials.TransportCredentials) {
  188. creds = c.creds
  189. switch scheme {
  190. case "unix":
  191. case "http":
  192. creds = nil
  193. case "https", "unixs":
  194. if creds != nil {
  195. break
  196. }
  197. tlsconfig := &tls.Config{}
  198. emptyCreds := credentials.NewTLS(tlsconfig)
  199. creds = &emptyCreds
  200. default:
  201. creds = nil
  202. }
  203. return creds
  204. }
  205. // dialSetupOpts gives the dial opts prior to any authentication
  206. func (c *Client) dialSetupOpts(endpoint string, dopts ...grpc.DialOption) (opts []grpc.DialOption) {
  207. if c.cfg.DialTimeout > 0 {
  208. opts = []grpc.DialOption{grpc.WithTimeout(c.cfg.DialTimeout)}
  209. }
  210. if c.cfg.DialKeepAliveTime > 0 {
  211. params := keepalive.ClientParameters{
  212. Time: c.cfg.DialKeepAliveTime,
  213. Timeout: c.cfg.DialKeepAliveTimeout,
  214. }
  215. opts = append(opts, grpc.WithKeepaliveParams(params))
  216. }
  217. opts = append(opts, dopts...)
  218. f := func(host string, t time.Duration) (net.Conn, error) {
  219. proto, host, _ := parseEndpoint(c.balancer.endpoint(host))
  220. if host == "" && endpoint != "" {
  221. // dialing an endpoint not in the balancer; use
  222. // endpoint passed into dial
  223. proto, host, _ = parseEndpoint(endpoint)
  224. }
  225. if proto == "" {
  226. return nil, fmt.Errorf("unknown scheme for %q", host)
  227. }
  228. select {
  229. case <-c.ctx.Done():
  230. return nil, c.ctx.Err()
  231. default:
  232. }
  233. dialer := &net.Dialer{Timeout: t}
  234. conn, err := dialer.DialContext(c.ctx, proto, host)
  235. if err != nil {
  236. select {
  237. case c.dialerrc <- err:
  238. default:
  239. }
  240. }
  241. return conn, err
  242. }
  243. opts = append(opts, grpc.WithDialer(f))
  244. creds := c.creds
  245. if _, _, scheme := parseEndpoint(endpoint); len(scheme) != 0 {
  246. creds = c.processCreds(scheme)
  247. }
  248. if creds != nil {
  249. opts = append(opts, grpc.WithTransportCredentials(*creds))
  250. } else {
  251. opts = append(opts, grpc.WithInsecure())
  252. }
  253. return opts
  254. }
  255. // Dial connects to a single endpoint using the client's config.
  256. func (c *Client) Dial(endpoint string) (*grpc.ClientConn, error) {
  257. return c.dial(endpoint)
  258. }
  259. func (c *Client) getToken(ctx context.Context) error {
  260. var err error // return last error in a case of fail
  261. var auth *authenticator
  262. for i := 0; i < len(c.cfg.Endpoints); i++ {
  263. endpoint := c.cfg.Endpoints[i]
  264. host := getHost(endpoint)
  265. // use dial options without dopts to avoid reusing the client balancer
  266. auth, err = newAuthenticator(host, c.dialSetupOpts(endpoint), c)
  267. if err != nil {
  268. continue
  269. }
  270. defer auth.close()
  271. var resp *AuthenticateResponse
  272. resp, err = auth.authenticate(ctx, c.Username, c.Password)
  273. if err != nil {
  274. continue
  275. }
  276. c.tokenCred.tokenMu.Lock()
  277. c.tokenCred.token = resp.Token
  278. c.tokenCred.tokenMu.Unlock()
  279. return nil
  280. }
  281. return err
  282. }
  283. func (c *Client) dial(endpoint string, dopts ...grpc.DialOption) (*grpc.ClientConn, error) {
  284. opts := c.dialSetupOpts(endpoint, dopts...)
  285. host := getHost(endpoint)
  286. if c.Username != "" && c.Password != "" {
  287. c.tokenCred = &authTokenCredential{
  288. tokenMu: &sync.RWMutex{},
  289. }
  290. ctx := c.ctx
  291. if c.cfg.DialTimeout > 0 {
  292. cctx, cancel := context.WithTimeout(ctx, c.cfg.DialTimeout)
  293. defer cancel()
  294. ctx = cctx
  295. }
  296. err := c.getToken(ctx)
  297. if err != nil {
  298. if toErr(ctx, err) != rpctypes.ErrAuthNotEnabled {
  299. if err == ctx.Err() && ctx.Err() != c.ctx.Err() {
  300. err = context.DeadlineExceeded
  301. }
  302. return nil, err
  303. }
  304. } else {
  305. opts = append(opts, grpc.WithPerRPCCredentials(c.tokenCred))
  306. }
  307. }
  308. opts = append(opts, c.cfg.DialOptions...)
  309. conn, err := grpc.DialContext(c.ctx, host, opts...)
  310. if err != nil {
  311. return nil, err
  312. }
  313. return conn, nil
  314. }
  315. // WithRequireLeader requires client requests to only succeed
  316. // when the cluster has a leader.
  317. func WithRequireLeader(ctx context.Context) context.Context {
  318. md := metadata.Pairs(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
  319. return metadata.NewOutgoingContext(ctx, md)
  320. }
  321. func newClient(cfg *Config) (*Client, error) {
  322. if cfg == nil {
  323. cfg = &Config{}
  324. }
  325. var creds *credentials.TransportCredentials
  326. if cfg.TLS != nil {
  327. c := credentials.NewTLS(cfg.TLS)
  328. creds = &c
  329. }
  330. // use a temporary skeleton client to bootstrap first connection
  331. baseCtx := context.TODO()
  332. if cfg.Context != nil {
  333. baseCtx = cfg.Context
  334. }
  335. ctx, cancel := context.WithCancel(baseCtx)
  336. client := &Client{
  337. conn: nil,
  338. dialerrc: make(chan error, 1),
  339. cfg: *cfg,
  340. creds: creds,
  341. ctx: ctx,
  342. cancel: cancel,
  343. mu: new(sync.RWMutex),
  344. callOpts: defaultCallOpts,
  345. }
  346. if cfg.Username != "" && cfg.Password != "" {
  347. client.Username = cfg.Username
  348. client.Password = cfg.Password
  349. }
  350. if cfg.MaxCallSendMsgSize > 0 || cfg.MaxCallRecvMsgSize > 0 {
  351. if cfg.MaxCallRecvMsgSize > 0 && cfg.MaxCallSendMsgSize > cfg.MaxCallRecvMsgSize {
  352. return nil, fmt.Errorf("gRPC message recv limit (%d bytes) must be greater than send limit (%d bytes)", cfg.MaxCallRecvMsgSize, cfg.MaxCallSendMsgSize)
  353. }
  354. callOpts := []grpc.CallOption{
  355. defaultFailFast,
  356. defaultMaxCallSendMsgSize,
  357. defaultMaxCallRecvMsgSize,
  358. }
  359. if cfg.MaxCallSendMsgSize > 0 {
  360. callOpts[1] = grpc.MaxCallSendMsgSize(cfg.MaxCallSendMsgSize)
  361. }
  362. if cfg.MaxCallRecvMsgSize > 0 {
  363. callOpts[2] = grpc.MaxCallRecvMsgSize(cfg.MaxCallRecvMsgSize)
  364. }
  365. client.callOpts = callOpts
  366. }
  367. client.balancer = newHealthBalancer(cfg.Endpoints, cfg.DialTimeout, func(ep string) (bool, error) {
  368. return grpcHealthCheck(client, ep)
  369. })
  370. // use Endpoints[0] so that for https:// without any tls config given, then
  371. // grpc will assume the certificate server name is the endpoint host.
  372. conn, err := client.dial(cfg.Endpoints[0], grpc.WithBalancer(client.balancer))
  373. if err != nil {
  374. client.cancel()
  375. client.balancer.Close()
  376. return nil, err
  377. }
  378. client.conn = conn
  379. // wait for a connection
  380. if cfg.DialTimeout > 0 {
  381. hasConn := false
  382. waitc := time.After(cfg.DialTimeout)
  383. select {
  384. case <-client.balancer.ready():
  385. hasConn = true
  386. case <-ctx.Done():
  387. case <-waitc:
  388. }
  389. if !hasConn {
  390. err := context.DeadlineExceeded
  391. select {
  392. case err = <-client.dialerrc:
  393. default:
  394. }
  395. client.cancel()
  396. client.balancer.Close()
  397. conn.Close()
  398. return nil, err
  399. }
  400. }
  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. ev, _ := status.FromError(err)
  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. 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. }