client.go 13 KB

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