client.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. err := c.getToken(context.TODO())
  247. if err != nil {
  248. return nil, err
  249. }
  250. opts = append(opts, grpc.WithPerRPCCredentials(c.tokenCred))
  251. }
  252. // add metrics options
  253. opts = append(opts, grpc.WithUnaryInterceptor(prometheus.UnaryClientInterceptor))
  254. opts = append(opts, grpc.WithStreamInterceptor(prometheus.StreamClientInterceptor))
  255. conn, err := grpc.Dial(host, opts...)
  256. if err != nil {
  257. return nil, err
  258. }
  259. return conn, nil
  260. }
  261. // WithRequireLeader requires client requests to only succeed
  262. // when the cluster has a leader.
  263. func WithRequireLeader(ctx context.Context) context.Context {
  264. md := metadata.Pairs(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
  265. return metadata.NewContext(ctx, md)
  266. }
  267. func newClient(cfg *Config) (*Client, error) {
  268. if cfg == nil {
  269. cfg = &Config{}
  270. }
  271. var creds *credentials.TransportCredentials
  272. if cfg.TLS != nil {
  273. c := credentials.NewTLS(cfg.TLS)
  274. creds = &c
  275. }
  276. // use a temporary skeleton client to bootstrap first connection
  277. ctx, cancel := context.WithCancel(context.TODO())
  278. client := &Client{
  279. conn: nil,
  280. cfg: *cfg,
  281. creds: creds,
  282. ctx: ctx,
  283. cancel: cancel,
  284. }
  285. if cfg.Username != "" && cfg.Password != "" {
  286. client.Username = cfg.Username
  287. client.Password = cfg.Password
  288. }
  289. client.balancer = newSimpleBalancer(cfg.Endpoints)
  290. conn, err := client.dial(cfg.Endpoints[0], grpc.WithBalancer(client.balancer))
  291. if err != nil {
  292. return nil, err
  293. }
  294. client.conn = conn
  295. client.retryWrapper = client.newRetryWrapper()
  296. client.retryAuthWrapper = client.newAuthRetryWrapper()
  297. // wait for a connection
  298. if cfg.DialTimeout > 0 {
  299. hasConn := false
  300. waitc := time.After(cfg.DialTimeout)
  301. select {
  302. case <-client.balancer.readyc:
  303. hasConn = true
  304. case <-ctx.Done():
  305. case <-waitc:
  306. }
  307. if !hasConn {
  308. client.cancel()
  309. conn.Close()
  310. return nil, grpc.ErrClientConnTimeout
  311. }
  312. }
  313. client.Cluster = NewCluster(client)
  314. client.KV = NewKV(client)
  315. client.Lease = NewLease(client)
  316. client.Watcher = NewWatcher(client)
  317. client.Auth = NewAuth(client)
  318. client.Maintenance = NewMaintenance(client)
  319. go client.autoSync()
  320. return client, nil
  321. }
  322. // ActiveConnection returns the current in-use connection
  323. func (c *Client) ActiveConnection() *grpc.ClientConn { return c.conn }
  324. // isHaltErr returns true if the given error and context indicate no forward
  325. // progress can be made, even after reconnecting.
  326. func isHaltErr(ctx context.Context, err error) bool {
  327. if ctx != nil && ctx.Err() != nil {
  328. return true
  329. }
  330. if err == nil {
  331. return false
  332. }
  333. code := grpc.Code(err)
  334. // Unavailable codes mean the system will be right back.
  335. // (e.g., can't connect, lost leader)
  336. // Treat Internal codes as if something failed, leaving the
  337. // system in an inconsistent state, but retrying could make progress.
  338. // (e.g., failed in middle of send, corrupted frame)
  339. // TODO: are permanent Internal errors possible from grpc?
  340. return code != codes.Unavailable && code != codes.Internal
  341. }
  342. func toErr(ctx context.Context, err error) error {
  343. if err == nil {
  344. return nil
  345. }
  346. err = rpctypes.Error(err)
  347. if _, ok := err.(rpctypes.EtcdError); ok {
  348. return err
  349. }
  350. code := grpc.Code(err)
  351. switch code {
  352. case codes.DeadlineExceeded:
  353. fallthrough
  354. case codes.Canceled:
  355. if ctx.Err() != nil {
  356. err = ctx.Err()
  357. }
  358. case codes.Unavailable:
  359. err = ErrNoAvailableEndpoints
  360. case codes.FailedPrecondition:
  361. err = grpc.ErrClientConnClosing
  362. }
  363. return err
  364. }