client.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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. "crypto/tls"
  17. "errors"
  18. "fmt"
  19. "net"
  20. "net/url"
  21. "strconv"
  22. "strings"
  23. "sync"
  24. "time"
  25. "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  26. "golang.org/x/net/context"
  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. )
  33. var (
  34. ErrNoAvailableEndpoints = errors.New("etcdclient: no available endpoints")
  35. ErrOldCluster = errors.New("etcdclient: old cluster version")
  36. )
  37. // Client provides and manages an etcd v3 client session.
  38. type Client struct {
  39. Cluster
  40. KV
  41. Lease
  42. Watcher
  43. Auth
  44. Maintenance
  45. conn *grpc.ClientConn
  46. dialerrc chan error
  47. cfg Config
  48. creds *credentials.TransportCredentials
  49. balancer *simpleBalancer
  50. ctx context.Context
  51. cancel context.CancelFunc
  52. // Username is a username for authentication
  53. Username string
  54. // Password is a password for authentication
  55. Password string
  56. // tokenCred is an instance of WithPerRPCCredentials()'s argument
  57. tokenCred *authTokenCredential
  58. }
  59. // New creates a new etcdv3 client from a given configuration.
  60. func New(cfg Config) (*Client, error) {
  61. if len(cfg.Endpoints) == 0 {
  62. return nil, ErrNoAvailableEndpoints
  63. }
  64. return newClient(&cfg)
  65. }
  66. // NewCtxClient creates a client with a context but no underlying grpc
  67. // connection. This is useful for embedded cases that override the
  68. // service interface implementations and do not need connection management.
  69. func NewCtxClient(ctx context.Context) *Client {
  70. cctx, cancel := context.WithCancel(ctx)
  71. return &Client{ctx: cctx, cancel: cancel}
  72. }
  73. // NewFromURL creates a new etcdv3 client from a URL.
  74. func NewFromURL(url string) (*Client, error) {
  75. return New(Config{Endpoints: []string{url}})
  76. }
  77. // Close shuts down the client's etcd connections.
  78. func (c *Client) Close() error {
  79. c.cancel()
  80. c.Watcher.Close()
  81. c.Lease.Close()
  82. if c.conn != nil {
  83. return toErr(c.ctx, c.conn.Close())
  84. }
  85. return c.ctx.Err()
  86. }
  87. // Ctx is a context for "out of band" messages (e.g., for sending
  88. // "clean up" message when another context is canceled). It is
  89. // canceled on client Close().
  90. func (c *Client) Ctx() context.Context { return c.ctx }
  91. // Endpoints lists the registered endpoints for the client.
  92. func (c *Client) Endpoints() (eps []string) {
  93. // copy the slice; protect original endpoints from being changed
  94. eps = make([]string, len(c.cfg.Endpoints))
  95. copy(eps, c.cfg.Endpoints)
  96. return
  97. }
  98. // SetEndpoints updates client's endpoints.
  99. func (c *Client) SetEndpoints(eps ...string) {
  100. c.cfg.Endpoints = eps
  101. c.balancer.updateAddrs(eps)
  102. }
  103. // Sync synchronizes client's endpoints with the known endpoints from the etcd membership.
  104. func (c *Client) Sync(ctx context.Context) error {
  105. mresp, err := c.MemberList(ctx)
  106. if err != nil {
  107. return err
  108. }
  109. var eps []string
  110. for _, m := range mresp.Members {
  111. eps = append(eps, m.ClientURLs...)
  112. }
  113. c.SetEndpoints(eps...)
  114. return nil
  115. }
  116. func (c *Client) autoSync() {
  117. if c.cfg.AutoSyncInterval == time.Duration(0) {
  118. return
  119. }
  120. for {
  121. select {
  122. case <-c.ctx.Done():
  123. return
  124. case <-time.After(c.cfg.AutoSyncInterval):
  125. ctx, _ := context.WithTimeout(c.ctx, 5*time.Second)
  126. if err := c.Sync(ctx); err != nil && err != c.ctx.Err() {
  127. logger.Println("Auto sync endpoints failed:", err)
  128. }
  129. }
  130. }
  131. }
  132. type authTokenCredential struct {
  133. token string
  134. tokenMu *sync.RWMutex
  135. }
  136. func (cred authTokenCredential) RequireTransportSecurity() bool {
  137. return false
  138. }
  139. func (cred authTokenCredential) GetRequestMetadata(ctx context.Context, s ...string) (map[string]string, error) {
  140. cred.tokenMu.RLock()
  141. defer cred.tokenMu.RUnlock()
  142. return map[string]string{
  143. "token": cred.token,
  144. }, nil
  145. }
  146. func parseEndpoint(endpoint string) (proto string, host string, scheme string) {
  147. proto = "tcp"
  148. host = endpoint
  149. url, uerr := url.Parse(endpoint)
  150. if uerr != nil || !strings.Contains(endpoint, "://") {
  151. return
  152. }
  153. scheme = url.Scheme
  154. // strip scheme:// prefix since grpc dials by host
  155. host = url.Host
  156. switch url.Scheme {
  157. case "http", "https":
  158. case "unix", "unixs":
  159. proto = "unix"
  160. host = url.Host + url.Path
  161. default:
  162. proto, host = "", ""
  163. }
  164. return
  165. }
  166. func (c *Client) processCreds(scheme string) (creds *credentials.TransportCredentials) {
  167. creds = c.creds
  168. switch scheme {
  169. case "unix":
  170. case "http":
  171. creds = nil
  172. case "https", "unixs":
  173. if creds != nil {
  174. break
  175. }
  176. tlsconfig := &tls.Config{}
  177. emptyCreds := credentials.NewTLS(tlsconfig)
  178. creds = &emptyCreds
  179. default:
  180. creds = nil
  181. }
  182. return
  183. }
  184. // dialSetupOpts gives the dial opts prior to any authentication
  185. func (c *Client) dialSetupOpts(endpoint string, dopts ...grpc.DialOption) (opts []grpc.DialOption) {
  186. if c.cfg.DialTimeout > 0 {
  187. opts = []grpc.DialOption{grpc.WithTimeout(c.cfg.DialTimeout)}
  188. }
  189. if c.cfg.DialKeepAliveTime > 0 {
  190. params := keepalive.ClientParameters{
  191. Time: c.cfg.DialKeepAliveTime,
  192. }
  193. // Only relevant when KeepAliveTime is non-zero
  194. if c.cfg.DialKeepAliveTimeout > 0 {
  195. params.Timeout = c.cfg.DialKeepAliveTimeout
  196. }
  197. opts = append(opts, grpc.WithKeepaliveParams(params))
  198. }
  199. opts = append(opts, dopts...)
  200. f := func(host string, t time.Duration) (net.Conn, error) {
  201. proto, host, _ := parseEndpoint(c.balancer.getEndpoint(host))
  202. if host == "" && endpoint != "" {
  203. // dialing an endpoint not in the balancer; use
  204. // endpoint passed into dial
  205. proto, host, _ = parseEndpoint(endpoint)
  206. }
  207. if proto == "" {
  208. return nil, fmt.Errorf("unknown scheme for %q", host)
  209. }
  210. select {
  211. case <-c.ctx.Done():
  212. return nil, c.ctx.Err()
  213. default:
  214. }
  215. dialer := &net.Dialer{Timeout: t}
  216. conn, err := dialer.DialContext(c.ctx, proto, host)
  217. if err != nil {
  218. select {
  219. case c.dialerrc <- err:
  220. default:
  221. }
  222. }
  223. return conn, err
  224. }
  225. opts = append(opts, grpc.WithDialer(f))
  226. creds := c.creds
  227. if _, _, scheme := parseEndpoint(endpoint); len(scheme) != 0 {
  228. creds = c.processCreds(scheme)
  229. }
  230. if creds != nil {
  231. opts = append(opts, grpc.WithTransportCredentials(*creds))
  232. } else {
  233. opts = append(opts, grpc.WithInsecure())
  234. }
  235. return opts
  236. }
  237. // Dial connects to a single endpoint using the client's config.
  238. func (c *Client) Dial(endpoint string) (*grpc.ClientConn, error) {
  239. return c.dial(endpoint)
  240. }
  241. func (c *Client) getToken(ctx context.Context) error {
  242. var err error // return last error in a case of fail
  243. var auth *authenticator
  244. for i := 0; i < len(c.cfg.Endpoints); i++ {
  245. endpoint := c.cfg.Endpoints[i]
  246. host := getHost(endpoint)
  247. // use dial options without dopts to avoid reusing the client balancer
  248. auth, err = newAuthenticator(host, c.dialSetupOpts(endpoint))
  249. if err != nil {
  250. continue
  251. }
  252. defer auth.close()
  253. var resp *AuthenticateResponse
  254. resp, err = auth.authenticate(ctx, c.Username, c.Password)
  255. if err != nil {
  256. continue
  257. }
  258. c.tokenCred.tokenMu.Lock()
  259. c.tokenCred.token = resp.Token
  260. c.tokenCred.tokenMu.Unlock()
  261. return nil
  262. }
  263. return err
  264. }
  265. func (c *Client) dial(endpoint string, dopts ...grpc.DialOption) (*grpc.ClientConn, error) {
  266. opts := c.dialSetupOpts(endpoint, dopts...)
  267. host := getHost(endpoint)
  268. if c.Username != "" && c.Password != "" {
  269. c.tokenCred = &authTokenCredential{
  270. tokenMu: &sync.RWMutex{},
  271. }
  272. ctx := c.ctx
  273. if c.cfg.DialTimeout > 0 {
  274. cctx, cancel := context.WithTimeout(ctx, c.cfg.DialTimeout)
  275. defer cancel()
  276. ctx = cctx
  277. }
  278. err := c.getToken(ctx)
  279. if err != nil {
  280. if toErr(ctx, err) != rpctypes.ErrAuthNotEnabled {
  281. if err == ctx.Err() && ctx.Err() != c.ctx.Err() {
  282. err = grpc.ErrClientConnTimeout
  283. }
  284. return nil, err
  285. }
  286. } else {
  287. opts = append(opts, grpc.WithPerRPCCredentials(c.tokenCred))
  288. }
  289. }
  290. opts = append(opts, c.cfg.DialOptions...)
  291. conn, err := grpc.DialContext(c.ctx, host, opts...)
  292. if err != nil {
  293. return nil, err
  294. }
  295. return conn, nil
  296. }
  297. // WithRequireLeader requires client requests to only succeed
  298. // when the cluster has a leader.
  299. func WithRequireLeader(ctx context.Context) context.Context {
  300. md := metadata.Pairs(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
  301. return metadata.NewOutgoingContext(ctx, md)
  302. }
  303. func newClient(cfg *Config) (*Client, error) {
  304. if cfg == nil {
  305. cfg = &Config{}
  306. }
  307. var creds *credentials.TransportCredentials
  308. if cfg.TLS != nil {
  309. c := credentials.NewTLS(cfg.TLS)
  310. creds = &c
  311. }
  312. // use a temporary skeleton client to bootstrap first connection
  313. baseCtx := context.TODO()
  314. if cfg.Context != nil {
  315. baseCtx = cfg.Context
  316. }
  317. ctx, cancel := context.WithCancel(baseCtx)
  318. client := &Client{
  319. conn: nil,
  320. dialerrc: make(chan error, 1),
  321. cfg: *cfg,
  322. creds: creds,
  323. ctx: ctx,
  324. cancel: cancel,
  325. }
  326. if cfg.Username != "" && cfg.Password != "" {
  327. client.Username = cfg.Username
  328. client.Password = cfg.Password
  329. }
  330. client.balancer = newSimpleBalancer(cfg.Endpoints)
  331. // use Endpoints[0] so that for https:// without any tls config given, then
  332. // grpc will assume the ServerName is in the endpoint.
  333. conn, err := client.dial(cfg.Endpoints[0], grpc.WithBalancer(client.balancer))
  334. if err != nil {
  335. client.cancel()
  336. client.balancer.Close()
  337. return nil, err
  338. }
  339. client.conn = conn
  340. // wait for a connection
  341. if cfg.DialTimeout > 0 {
  342. hasConn := false
  343. waitc := time.After(cfg.DialTimeout)
  344. select {
  345. case <-client.balancer.readyc:
  346. hasConn = true
  347. case <-ctx.Done():
  348. case <-waitc:
  349. }
  350. if !hasConn {
  351. err := grpc.ErrClientConnTimeout
  352. select {
  353. case err = <-client.dialerrc:
  354. default:
  355. }
  356. client.cancel()
  357. client.balancer.Close()
  358. conn.Close()
  359. return nil, err
  360. }
  361. }
  362. client.Cluster = NewCluster(client)
  363. client.KV = NewKV(client)
  364. client.Lease = NewLease(client)
  365. client.Watcher = NewWatcher(client)
  366. client.Auth = NewAuth(client)
  367. client.Maintenance = NewMaintenance(client)
  368. if cfg.RejectOldCluster {
  369. if err := client.checkVersion(); err != nil {
  370. client.Close()
  371. return nil, err
  372. }
  373. }
  374. go client.autoSync()
  375. return client, nil
  376. }
  377. func (c *Client) checkVersion() (err error) {
  378. var wg sync.WaitGroup
  379. errc := make(chan error, len(c.cfg.Endpoints))
  380. ctx, cancel := context.WithCancel(c.ctx)
  381. if c.cfg.DialTimeout > 0 {
  382. ctx, _ = context.WithTimeout(ctx, c.cfg.DialTimeout)
  383. }
  384. wg.Add(len(c.cfg.Endpoints))
  385. for _, ep := range c.cfg.Endpoints {
  386. // if cluster is current, any endpoint gives a recent version
  387. go func(e string) {
  388. defer wg.Done()
  389. resp, rerr := c.Status(ctx, e)
  390. if rerr != nil {
  391. errc <- rerr
  392. return
  393. }
  394. vs := strings.Split(resp.Version, ".")
  395. maj, min := 0, 0
  396. if len(vs) >= 2 {
  397. maj, rerr = strconv.Atoi(vs[0])
  398. min, rerr = strconv.Atoi(vs[1])
  399. }
  400. if maj < 3 || (maj == 3 && min < 2) {
  401. rerr = ErrOldCluster
  402. }
  403. errc <- rerr
  404. }(ep)
  405. }
  406. // wait for success
  407. for i := 0; i < len(c.cfg.Endpoints); i++ {
  408. if err = <-errc; err == nil {
  409. break
  410. }
  411. }
  412. cancel()
  413. wg.Wait()
  414. return err
  415. }
  416. // ActiveConnection returns the current in-use connection
  417. func (c *Client) ActiveConnection() *grpc.ClientConn { return c.conn }
  418. // isHaltErr returns true if the given error and context indicate no forward
  419. // progress can be made, even after reconnecting.
  420. func isHaltErr(ctx context.Context, err error) bool {
  421. if ctx != nil && ctx.Err() != nil {
  422. return true
  423. }
  424. if err == nil {
  425. return false
  426. }
  427. code := grpc.Code(err)
  428. // Unavailable codes mean the system will be right back.
  429. // (e.g., can't connect, lost leader)
  430. // Treat Internal codes as if something failed, leaving the
  431. // system in an inconsistent state, but retrying could make progress.
  432. // (e.g., failed in middle of send, corrupted frame)
  433. // TODO: are permanent Internal errors possible from grpc?
  434. return code != codes.Unavailable && code != codes.Internal
  435. }
  436. func toErr(ctx context.Context, err error) error {
  437. if err == nil {
  438. return nil
  439. }
  440. err = rpctypes.Error(err)
  441. if _, ok := err.(rpctypes.EtcdError); ok {
  442. return err
  443. }
  444. code := grpc.Code(err)
  445. switch code {
  446. case codes.DeadlineExceeded:
  447. fallthrough
  448. case codes.Canceled:
  449. if ctx.Err() != nil {
  450. err = ctx.Err()
  451. }
  452. case codes.Unavailable:
  453. case codes.FailedPrecondition:
  454. err = grpc.ErrClientConnClosing
  455. }
  456. return err
  457. }
  458. func canceledByCaller(stopCtx context.Context, err error) bool {
  459. if stopCtx.Err() == nil || err == nil {
  460. return false
  461. }
  462. return err == context.Canceled || err == context.DeadlineExceeded
  463. }