client.go 12 KB

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