client.go 12 KB

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