client.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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.Mutex
  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. }
  61. // New creates a new etcdv3 client from a given configuration.
  62. func New(cfg Config) (*Client, error) {
  63. if len(cfg.Endpoints) == 0 {
  64. return nil, ErrNoAvailableEndpoints
  65. }
  66. return newClient(&cfg)
  67. }
  68. // NewCtxClient creates a client with a context but no underlying grpc
  69. // connection. This is useful for embedded cases that override the
  70. // service interface implementations and do not need connection management.
  71. func NewCtxClient(ctx context.Context) *Client {
  72. cctx, cancel := context.WithCancel(ctx)
  73. return &Client{ctx: cctx, cancel: cancel}
  74. }
  75. // NewFromURL creates a new etcdv3 client from a URL.
  76. func NewFromURL(url string) (*Client, error) {
  77. return New(Config{Endpoints: []string{url}})
  78. }
  79. // Close shuts down the client's etcd connections.
  80. func (c *Client) Close() error {
  81. c.cancel()
  82. c.Watcher.Close()
  83. c.Lease.Close()
  84. if c.conn != nil {
  85. return toErr(c.ctx, c.conn.Close())
  86. }
  87. return c.ctx.Err()
  88. }
  89. // Ctx is a context for "out of band" messages (e.g., for sending
  90. // "clean up" message when another context is canceled). It is
  91. // canceled on client Close().
  92. func (c *Client) Ctx() context.Context { return c.ctx }
  93. // Endpoints lists the registered endpoints for the client.
  94. func (c *Client) Endpoints() (eps []string) {
  95. // copy the slice; protect original endpoints from being changed
  96. eps = make([]string, len(c.cfg.Endpoints))
  97. copy(eps, c.cfg.Endpoints)
  98. return
  99. }
  100. // SetEndpoints updates client's endpoints.
  101. func (c *Client) SetEndpoints(eps ...string) {
  102. c.mu.Lock()
  103. c.cfg.Endpoints = eps
  104. c.mu.Unlock()
  105. c.balancer.updateAddrs(eps...)
  106. // updating notifyCh can trigger new connections,
  107. // need update addrs if all connections are down
  108. // or addrs does not include pinAddr.
  109. c.balancer.mu.RLock()
  110. update := !hasAddr(c.balancer.addrs, c.balancer.pinAddr)
  111. c.balancer.mu.RUnlock()
  112. if update {
  113. select {
  114. case c.balancer.updateAddrsC <- 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. logger.Println("Auto sync endpoints failed:", 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. "token": 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))
  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. }
  342. if cfg.Username != "" && cfg.Password != "" {
  343. client.Username = cfg.Username
  344. client.Password = cfg.Password
  345. }
  346. client.balancer = newHealthBalancer(cfg.Endpoints, cfg.DialTimeout, func(ep string) (bool, error) {
  347. return grpcHealthCheck(client, ep)
  348. })
  349. // use Endpoints[0] so that for https:// without any tls config given, then
  350. // grpc will assume the certificate server name is the endpoint host.
  351. conn, err := client.dial(cfg.Endpoints[0], grpc.WithBalancer(client.balancer))
  352. if err != nil {
  353. client.cancel()
  354. client.balancer.Close()
  355. return nil, err
  356. }
  357. client.conn = conn
  358. // wait for a connection
  359. if cfg.DialTimeout > 0 {
  360. hasConn := false
  361. waitc := time.After(cfg.DialTimeout)
  362. select {
  363. case <-client.balancer.ready():
  364. hasConn = true
  365. case <-ctx.Done():
  366. case <-waitc:
  367. }
  368. if !hasConn {
  369. err := context.DeadlineExceeded
  370. select {
  371. case err = <-client.dialerrc:
  372. default:
  373. }
  374. client.cancel()
  375. client.balancer.Close()
  376. conn.Close()
  377. return nil, err
  378. }
  379. }
  380. client.Cluster = NewCluster(client)
  381. client.KV = NewKV(client)
  382. client.Lease = NewLease(client)
  383. client.Watcher = NewWatcher(client)
  384. client.Auth = NewAuth(client)
  385. client.Maintenance = NewMaintenance(client)
  386. if cfg.RejectOldCluster {
  387. if err := client.checkVersion(); err != nil {
  388. client.Close()
  389. return nil, err
  390. }
  391. }
  392. go client.autoSync()
  393. return client, nil
  394. }
  395. func (c *Client) checkVersion() (err error) {
  396. var wg sync.WaitGroup
  397. errc := make(chan error, len(c.cfg.Endpoints))
  398. ctx, cancel := context.WithCancel(c.ctx)
  399. if c.cfg.DialTimeout > 0 {
  400. ctx, cancel = context.WithTimeout(ctx, c.cfg.DialTimeout)
  401. }
  402. wg.Add(len(c.cfg.Endpoints))
  403. for _, ep := range c.cfg.Endpoints {
  404. // if cluster is current, any endpoint gives a recent version
  405. go func(e string) {
  406. defer wg.Done()
  407. resp, rerr := c.Status(ctx, e)
  408. if rerr != nil {
  409. errc <- rerr
  410. return
  411. }
  412. vs := strings.Split(resp.Version, ".")
  413. maj, min := 0, 0
  414. if len(vs) >= 2 {
  415. maj, _ = strconv.Atoi(vs[0])
  416. min, rerr = strconv.Atoi(vs[1])
  417. }
  418. if maj < 3 || (maj == 3 && min < 2) {
  419. rerr = ErrOldCluster
  420. }
  421. errc <- rerr
  422. }(ep)
  423. }
  424. // wait for success
  425. for i := 0; i < len(c.cfg.Endpoints); i++ {
  426. if err = <-errc; err == nil {
  427. break
  428. }
  429. }
  430. cancel()
  431. wg.Wait()
  432. return err
  433. }
  434. // ActiveConnection returns the current in-use connection
  435. func (c *Client) ActiveConnection() *grpc.ClientConn { return c.conn }
  436. // isHaltErr returns true if the given error and context indicate no forward
  437. // progress can be made, even after reconnecting.
  438. func isHaltErr(ctx context.Context, err error) bool {
  439. if ctx != nil && ctx.Err() != nil {
  440. return true
  441. }
  442. if err == nil {
  443. return false
  444. }
  445. ev, _ := status.FromError(err)
  446. // Unavailable codes mean the system will be right back.
  447. // (e.g., can't connect, lost leader)
  448. // Treat Internal codes as if something failed, leaving the
  449. // system in an inconsistent state, but retrying could make progress.
  450. // (e.g., failed in middle of send, corrupted frame)
  451. // TODO: are permanent Internal errors possible from grpc?
  452. return ev.Code() != codes.Unavailable && ev.Code() != codes.Internal
  453. }
  454. func toErr(ctx context.Context, err error) error {
  455. if err == nil {
  456. return nil
  457. }
  458. err = rpctypes.Error(err)
  459. if _, ok := err.(rpctypes.EtcdError); ok {
  460. return err
  461. }
  462. ev, _ := status.FromError(err)
  463. code := ev.Code()
  464. switch code {
  465. case codes.DeadlineExceeded:
  466. fallthrough
  467. case codes.Canceled:
  468. if ctx.Err() != nil {
  469. err = ctx.Err()
  470. }
  471. case codes.Unavailable:
  472. case codes.FailedPrecondition:
  473. err = grpc.ErrClientConnClosing
  474. }
  475. return err
  476. }
  477. func canceledByCaller(stopCtx context.Context, err error) bool {
  478. if stopCtx.Err() == nil || err == nil {
  479. return false
  480. }
  481. return err == context.Canceled || err == context.DeadlineExceeded
  482. }