client.go 11 KB

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