client.go 10 KB

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