client.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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 balancer
  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. }
  107. // Sync synchronizes client's endpoints with the known endpoints from the etcd membership.
  108. func (c *Client) Sync(ctx context.Context) error {
  109. mresp, err := c.MemberList(ctx)
  110. if err != nil {
  111. return err
  112. }
  113. var eps []string
  114. for _, m := range mresp.Members {
  115. eps = append(eps, m.ClientURLs...)
  116. }
  117. c.SetEndpoints(eps...)
  118. return nil
  119. }
  120. func (c *Client) autoSync() {
  121. if c.cfg.AutoSyncInterval == time.Duration(0) {
  122. return
  123. }
  124. for {
  125. select {
  126. case <-c.ctx.Done():
  127. return
  128. case <-time.After(c.cfg.AutoSyncInterval):
  129. ctx, cancel := context.WithTimeout(c.ctx, 5*time.Second)
  130. err := c.Sync(ctx)
  131. cancel()
  132. if err != nil && err != c.ctx.Err() {
  133. logger.Println("Auto sync endpoints failed:", err)
  134. }
  135. }
  136. }
  137. }
  138. type authTokenCredential struct {
  139. token string
  140. tokenMu *sync.RWMutex
  141. }
  142. func (cred authTokenCredential) RequireTransportSecurity() bool {
  143. return false
  144. }
  145. func (cred authTokenCredential) GetRequestMetadata(ctx context.Context, s ...string) (map[string]string, error) {
  146. cred.tokenMu.RLock()
  147. defer cred.tokenMu.RUnlock()
  148. return map[string]string{
  149. "token": cred.token,
  150. }, nil
  151. }
  152. func parseEndpoint(endpoint string) (proto string, host string, scheme string) {
  153. proto = "tcp"
  154. host = endpoint
  155. url, uerr := url.Parse(endpoint)
  156. if uerr != nil || !strings.Contains(endpoint, "://") {
  157. return
  158. }
  159. scheme = url.Scheme
  160. // strip scheme:// prefix since grpc dials by host
  161. host = url.Host
  162. switch url.Scheme {
  163. case "http", "https":
  164. case "unix", "unixs":
  165. proto = "unix"
  166. host = url.Host + url.Path
  167. default:
  168. proto, host = "", ""
  169. }
  170. return
  171. }
  172. func (c *Client) processCreds(scheme string) (creds *credentials.TransportCredentials) {
  173. creds = c.creds
  174. switch scheme {
  175. case "unix":
  176. case "http":
  177. creds = nil
  178. case "https", "unixs":
  179. if creds != nil {
  180. break
  181. }
  182. tlsconfig := &tls.Config{}
  183. emptyCreds := credentials.NewTLS(tlsconfig)
  184. creds = &emptyCreds
  185. default:
  186. creds = nil
  187. }
  188. return
  189. }
  190. // dialSetupOpts gives the dial opts prior to any authentication
  191. func (c *Client) dialSetupOpts(endpoint string, dopts ...grpc.DialOption) (opts []grpc.DialOption) {
  192. if c.cfg.DialTimeout > 0 {
  193. opts = []grpc.DialOption{grpc.WithTimeout(c.cfg.DialTimeout)}
  194. }
  195. if c.cfg.DialKeepAliveTime > 0 {
  196. params := keepalive.ClientParameters{
  197. Time: c.cfg.DialKeepAliveTime,
  198. Timeout: c.cfg.DialKeepAliveTimeout,
  199. }
  200. opts = append(opts, grpc.WithKeepaliveParams(params))
  201. }
  202. opts = append(opts, dopts...)
  203. f := func(host string, t time.Duration) (net.Conn, error) {
  204. proto, host, _ := parseEndpoint(c.balancer.endpoint(host))
  205. if host == "" && endpoint != "" {
  206. // dialing an endpoint not in the balancer; use
  207. // endpoint passed into dial
  208. proto, host, _ = parseEndpoint(endpoint)
  209. }
  210. if proto == "" {
  211. return nil, fmt.Errorf("unknown scheme for %q", host)
  212. }
  213. select {
  214. case <-c.ctx.Done():
  215. return nil, c.ctx.Err()
  216. default:
  217. }
  218. dialer := &net.Dialer{Timeout: t}
  219. conn, err := dialer.DialContext(c.ctx, proto, host)
  220. if err != nil {
  221. select {
  222. case c.dialerrc <- err:
  223. default:
  224. }
  225. }
  226. return conn, err
  227. }
  228. opts = append(opts, grpc.WithDialer(f))
  229. creds := c.creds
  230. if _, _, scheme := parseEndpoint(endpoint); len(scheme) != 0 {
  231. creds = c.processCreds(scheme)
  232. }
  233. if creds != nil {
  234. opts = append(opts, grpc.WithTransportCredentials(*creds))
  235. } else {
  236. opts = append(opts, grpc.WithInsecure())
  237. }
  238. return opts
  239. }
  240. // Dial connects to a single endpoint using the client's config.
  241. func (c *Client) Dial(endpoint string) (*grpc.ClientConn, error) {
  242. return c.dial(endpoint)
  243. }
  244. func (c *Client) getToken(ctx context.Context) error {
  245. var err error // return last error in a case of fail
  246. var auth *authenticator
  247. for i := 0; i < len(c.cfg.Endpoints); i++ {
  248. endpoint := c.cfg.Endpoints[i]
  249. host := getHost(endpoint)
  250. // use dial options without dopts to avoid reusing the client balancer
  251. auth, err = newAuthenticator(host, c.dialSetupOpts(endpoint))
  252. if err != nil {
  253. continue
  254. }
  255. defer auth.close()
  256. var resp *AuthenticateResponse
  257. resp, err = auth.authenticate(ctx, c.Username, c.Password)
  258. if err != nil {
  259. continue
  260. }
  261. c.tokenCred.tokenMu.Lock()
  262. c.tokenCred.token = resp.Token
  263. c.tokenCred.tokenMu.Unlock()
  264. return nil
  265. }
  266. return err
  267. }
  268. func (c *Client) dial(endpoint string, dopts ...grpc.DialOption) (*grpc.ClientConn, error) {
  269. opts := c.dialSetupOpts(endpoint, dopts...)
  270. host := getHost(endpoint)
  271. if c.Username != "" && c.Password != "" {
  272. c.tokenCred = &authTokenCredential{
  273. tokenMu: &sync.RWMutex{},
  274. }
  275. ctx := c.ctx
  276. if c.cfg.DialTimeout > 0 {
  277. cctx, cancel := context.WithTimeout(ctx, c.cfg.DialTimeout)
  278. defer cancel()
  279. ctx = cctx
  280. }
  281. err := c.getToken(ctx)
  282. if err != nil {
  283. if toErr(ctx, err) != rpctypes.ErrAuthNotEnabled {
  284. if err == ctx.Err() && ctx.Err() != c.ctx.Err() {
  285. err = context.DeadlineExceeded
  286. }
  287. return nil, err
  288. }
  289. } else {
  290. opts = append(opts, grpc.WithPerRPCCredentials(c.tokenCred))
  291. }
  292. }
  293. opts = append(opts, c.cfg.DialOptions...)
  294. conn, err := grpc.DialContext(c.ctx, host, opts...)
  295. if err != nil {
  296. return nil, err
  297. }
  298. return conn, nil
  299. }
  300. // WithRequireLeader requires client requests to only succeed
  301. // when the cluster has a leader.
  302. func WithRequireLeader(ctx context.Context) context.Context {
  303. md := metadata.Pairs(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
  304. return metadata.NewOutgoingContext(ctx, md)
  305. }
  306. func newClient(cfg *Config) (*Client, error) {
  307. if cfg == nil {
  308. cfg = &Config{}
  309. }
  310. var creds *credentials.TransportCredentials
  311. if cfg.TLS != nil {
  312. c := credentials.NewTLS(cfg.TLS)
  313. creds = &c
  314. }
  315. // use a temporary skeleton client to bootstrap first connection
  316. baseCtx := context.TODO()
  317. if cfg.Context != nil {
  318. baseCtx = cfg.Context
  319. }
  320. ctx, cancel := context.WithCancel(baseCtx)
  321. client := &Client{
  322. conn: nil,
  323. dialerrc: make(chan error, 1),
  324. cfg: *cfg,
  325. creds: creds,
  326. ctx: ctx,
  327. cancel: cancel,
  328. }
  329. if cfg.Username != "" && cfg.Password != "" {
  330. client.Username = cfg.Username
  331. client.Password = cfg.Password
  332. }
  333. sb := newSimpleBalancer(cfg.Endpoints)
  334. hc := func(ep string) (bool, error) { return grpcHealthCheck(client, ep) }
  335. client.balancer = newHealthBalancer(sb, cfg.DialTimeout, hc)
  336. // use Endpoints[0] so that for https:// without any tls config given, then
  337. // grpc will assume the certificate server name is the endpoint host.
  338. conn, err := client.dial(cfg.Endpoints[0], grpc.WithBalancer(client.balancer))
  339. if err != nil {
  340. client.cancel()
  341. client.balancer.Close()
  342. return nil, err
  343. }
  344. client.conn = conn
  345. // wait for a connection
  346. if cfg.DialTimeout > 0 {
  347. hasConn := false
  348. waitc := time.After(cfg.DialTimeout)
  349. select {
  350. case <-client.balancer.ready():
  351. hasConn = true
  352. case <-ctx.Done():
  353. case <-waitc:
  354. }
  355. if !hasConn {
  356. err := context.DeadlineExceeded
  357. select {
  358. case err = <-client.dialerrc:
  359. default:
  360. }
  361. client.cancel()
  362. client.balancer.Close()
  363. conn.Close()
  364. return nil, err
  365. }
  366. }
  367. client.Cluster = NewCluster(client)
  368. client.KV = NewKV(client)
  369. client.Lease = NewLease(client)
  370. client.Watcher = NewWatcher(client)
  371. client.Auth = NewAuth(client)
  372. client.Maintenance = NewMaintenance(client)
  373. if cfg.RejectOldCluster {
  374. if err := client.checkVersion(); err != nil {
  375. client.Close()
  376. return nil, err
  377. }
  378. }
  379. go client.autoSync()
  380. return client, nil
  381. }
  382. func (c *Client) checkVersion() (err error) {
  383. var wg sync.WaitGroup
  384. errc := make(chan error, len(c.cfg.Endpoints))
  385. ctx, cancel := context.WithCancel(c.ctx)
  386. if c.cfg.DialTimeout > 0 {
  387. ctx, cancel = context.WithTimeout(ctx, c.cfg.DialTimeout)
  388. }
  389. wg.Add(len(c.cfg.Endpoints))
  390. for _, ep := range c.cfg.Endpoints {
  391. // if cluster is current, any endpoint gives a recent version
  392. go func(e string) {
  393. defer wg.Done()
  394. resp, rerr := c.Status(ctx, e)
  395. if rerr != nil {
  396. errc <- rerr
  397. return
  398. }
  399. vs := strings.Split(resp.Version, ".")
  400. maj, min := 0, 0
  401. if len(vs) >= 2 {
  402. maj, rerr = strconv.Atoi(vs[0])
  403. min, rerr = strconv.Atoi(vs[1])
  404. }
  405. if maj < 3 || (maj == 3 && min < 2) {
  406. rerr = ErrOldCluster
  407. }
  408. errc <- rerr
  409. }(ep)
  410. }
  411. // wait for success
  412. for i := 0; i < len(c.cfg.Endpoints); i++ {
  413. if err = <-errc; err == nil {
  414. break
  415. }
  416. }
  417. cancel()
  418. wg.Wait()
  419. return err
  420. }
  421. // ActiveConnection returns the current in-use connection
  422. func (c *Client) ActiveConnection() *grpc.ClientConn { return c.conn }
  423. // isHaltErr returns true if the given error and context indicate no forward
  424. // progress can be made, even after reconnecting.
  425. func isHaltErr(ctx context.Context, err error) bool {
  426. if ctx != nil && ctx.Err() != nil {
  427. return true
  428. }
  429. if err == nil {
  430. return false
  431. }
  432. ev, _ := status.FromError(err)
  433. // Unavailable codes mean the system will be right back.
  434. // (e.g., can't connect, lost leader)
  435. // Treat Internal codes as if something failed, leaving the
  436. // system in an inconsistent state, but retrying could make progress.
  437. // (e.g., failed in middle of send, corrupted frame)
  438. // TODO: are permanent Internal errors possible from grpc?
  439. return ev.Code() != codes.Unavailable && ev.Code() != codes.Internal
  440. }
  441. func toErr(ctx context.Context, err error) error {
  442. if err == nil {
  443. return nil
  444. }
  445. err = rpctypes.Error(err)
  446. if _, ok := err.(rpctypes.EtcdError); ok {
  447. return err
  448. }
  449. ev, _ := status.FromError(err)
  450. code := ev.Code()
  451. switch code {
  452. case codes.DeadlineExceeded:
  453. fallthrough
  454. case codes.Canceled:
  455. if ctx.Err() != nil {
  456. err = ctx.Err()
  457. }
  458. case codes.Unavailable:
  459. case codes.FailedPrecondition:
  460. err = grpc.ErrClientConnClosing
  461. }
  462. return err
  463. }
  464. func canceledByCaller(stopCtx context.Context, err error) bool {
  465. if stopCtx.Err() == nil || err == nil {
  466. return false
  467. }
  468. return err == context.Canceled || err == context.DeadlineExceeded
  469. }