client.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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. ctx := c.ctx
  259. if c.cfg.DialTimeout > 0 {
  260. cctx, cancel := context.WithTimeout(ctx, c.cfg.DialTimeout)
  261. defer cancel()
  262. ctx = cctx
  263. }
  264. if err := c.getToken(ctx); err != nil {
  265. if err == ctx.Err() && ctx.Err() != c.ctx.Err() {
  266. err = grpc.ErrClientConnTimeout
  267. }
  268. return nil, err
  269. }
  270. opts = append(opts, grpc.WithPerRPCCredentials(c.tokenCred))
  271. }
  272. opts = append(opts, c.cfg.DialOptions...)
  273. conn, err := grpc.Dial(host, opts...)
  274. if err != nil {
  275. return nil, err
  276. }
  277. return conn, nil
  278. }
  279. // WithRequireLeader requires client requests to only succeed
  280. // when the cluster has a leader.
  281. func WithRequireLeader(ctx context.Context) context.Context {
  282. md := metadata.Pairs(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
  283. return metadata.NewContext(ctx, md)
  284. }
  285. func newClient(cfg *Config) (*Client, error) {
  286. if cfg == nil {
  287. cfg = &Config{}
  288. }
  289. var creds *credentials.TransportCredentials
  290. if cfg.TLS != nil {
  291. c := credentials.NewTLS(cfg.TLS)
  292. creds = &c
  293. }
  294. // use a temporary skeleton client to bootstrap first connection
  295. baseCtx := context.TODO()
  296. if cfg.Context != nil {
  297. baseCtx = cfg.Context
  298. }
  299. ctx, cancel := context.WithCancel(baseCtx)
  300. client := &Client{
  301. conn: nil,
  302. dialerrc: make(chan error, 1),
  303. cfg: *cfg,
  304. creds: creds,
  305. ctx: ctx,
  306. cancel: cancel,
  307. }
  308. if cfg.Username != "" && cfg.Password != "" {
  309. client.Username = cfg.Username
  310. client.Password = cfg.Password
  311. }
  312. client.balancer = newSimpleBalancer(cfg.Endpoints)
  313. conn, err := client.dial(cfg.Endpoints[0], grpc.WithBalancer(client.balancer))
  314. if err != nil {
  315. client.cancel()
  316. client.balancer.Close()
  317. return nil, err
  318. }
  319. client.conn = conn
  320. client.retryWrapper = client.newRetryWrapper()
  321. client.retryAuthWrapper = client.newAuthRetryWrapper()
  322. // wait for a connection
  323. if cfg.DialTimeout > 0 {
  324. hasConn := false
  325. waitc := time.After(cfg.DialTimeout)
  326. select {
  327. case <-client.balancer.readyc:
  328. hasConn = true
  329. case <-ctx.Done():
  330. case <-waitc:
  331. }
  332. if !hasConn {
  333. err := grpc.ErrClientConnTimeout
  334. select {
  335. case err = <-client.dialerrc:
  336. default:
  337. }
  338. client.cancel()
  339. client.balancer.Close()
  340. conn.Close()
  341. return nil, err
  342. }
  343. }
  344. client.Cluster = NewCluster(client)
  345. client.KV = NewKV(client)
  346. client.Lease = NewLease(client)
  347. client.Watcher = NewWatcher(client)
  348. client.Auth = NewAuth(client)
  349. client.Maintenance = NewMaintenance(client)
  350. if cfg.RejectOldCluster {
  351. if err := client.checkVersion(); err != nil {
  352. client.Close()
  353. return nil, err
  354. }
  355. }
  356. go client.autoSync()
  357. return client, nil
  358. }
  359. func (c *Client) checkVersion() (err error) {
  360. var wg sync.WaitGroup
  361. errc := make(chan error, len(c.cfg.Endpoints))
  362. ctx, cancel := context.WithCancel(c.ctx)
  363. if c.cfg.DialTimeout > 0 {
  364. ctx, _ = context.WithTimeout(ctx, c.cfg.DialTimeout)
  365. }
  366. wg.Add(len(c.cfg.Endpoints))
  367. for _, ep := range c.cfg.Endpoints {
  368. // if cluster is current, any endpoint gives a recent version
  369. go func(e string) {
  370. defer wg.Done()
  371. resp, rerr := c.Status(ctx, e)
  372. if rerr != nil {
  373. errc <- rerr
  374. return
  375. }
  376. vs := strings.Split(resp.Version, ".")
  377. maj, min := 0, 0
  378. if len(vs) >= 2 {
  379. maj, rerr = strconv.Atoi(vs[0])
  380. min, rerr = strconv.Atoi(vs[1])
  381. }
  382. if maj < 3 || (maj == 3 && min < 2) {
  383. rerr = ErrOldCluster
  384. }
  385. errc <- rerr
  386. }(ep)
  387. }
  388. // wait for success
  389. for i := 0; i < len(c.cfg.Endpoints); i++ {
  390. if err = <-errc; err == nil {
  391. break
  392. }
  393. }
  394. cancel()
  395. wg.Wait()
  396. return err
  397. }
  398. // ActiveConnection returns the current in-use connection
  399. func (c *Client) ActiveConnection() *grpc.ClientConn { return c.conn }
  400. // isHaltErr returns true if the given error and context indicate no forward
  401. // progress can be made, even after reconnecting.
  402. func isHaltErr(ctx context.Context, err error) bool {
  403. if ctx != nil && ctx.Err() != nil {
  404. return true
  405. }
  406. if err == nil {
  407. return false
  408. }
  409. code := grpc.Code(err)
  410. // Unavailable codes mean the system will be right back.
  411. // (e.g., can't connect, lost leader)
  412. // Treat Internal codes as if something failed, leaving the
  413. // system in an inconsistent state, but retrying could make progress.
  414. // (e.g., failed in middle of send, corrupted frame)
  415. // TODO: are permanent Internal errors possible from grpc?
  416. return code != codes.Unavailable && code != codes.Internal
  417. }
  418. func toErr(ctx context.Context, err error) error {
  419. if err == nil {
  420. return nil
  421. }
  422. err = rpctypes.Error(err)
  423. if _, ok := err.(rpctypes.EtcdError); ok {
  424. return err
  425. }
  426. code := grpc.Code(err)
  427. switch code {
  428. case codes.DeadlineExceeded:
  429. fallthrough
  430. case codes.Canceled:
  431. if ctx.Err() != nil {
  432. err = ctx.Err()
  433. }
  434. case codes.Unavailable:
  435. err = ErrNoAvailableEndpoints
  436. case codes.FailedPrecondition:
  437. err = grpc.ErrClientConnClosing
  438. }
  439. return err
  440. }