client.go 11 KB

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