client.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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. return net.DialTimeout(proto, host, t)
  197. }
  198. opts = append(opts, grpc.WithDialer(f))
  199. creds := c.creds
  200. if _, _, scheme := parseEndpoint(endpoint); len(scheme) != 0 {
  201. creds = c.processCreds(scheme)
  202. }
  203. if creds != nil {
  204. opts = append(opts, grpc.WithTransportCredentials(*creds))
  205. } else {
  206. opts = append(opts, grpc.WithInsecure())
  207. }
  208. return opts
  209. }
  210. // Dial connects to a single endpoint using the client's config.
  211. func (c *Client) Dial(endpoint string) (*grpc.ClientConn, error) {
  212. return c.dial(endpoint)
  213. }
  214. func (c *Client) getToken(ctx context.Context) error {
  215. var err error // return last error in a case of fail
  216. var auth *authenticator
  217. for i := 0; i < len(c.cfg.Endpoints); i++ {
  218. endpoint := c.cfg.Endpoints[i]
  219. host := getHost(endpoint)
  220. // use dial options without dopts to avoid reusing the client balancer
  221. auth, err = newAuthenticator(host, c.dialSetupOpts(endpoint))
  222. if err != nil {
  223. continue
  224. }
  225. defer auth.close()
  226. var resp *AuthenticateResponse
  227. resp, err = auth.authenticate(ctx, c.Username, c.Password)
  228. if err != nil {
  229. continue
  230. }
  231. c.tokenCred.tokenMu.Lock()
  232. c.tokenCred.token = resp.Token
  233. c.tokenCred.tokenMu.Unlock()
  234. return nil
  235. }
  236. return err
  237. }
  238. func (c *Client) dial(endpoint string, dopts ...grpc.DialOption) (*grpc.ClientConn, error) {
  239. opts := c.dialSetupOpts(endpoint, dopts...)
  240. host := getHost(endpoint)
  241. if c.Username != "" && c.Password != "" {
  242. c.tokenCred = &authTokenCredential{
  243. tokenMu: &sync.RWMutex{},
  244. }
  245. err := c.getToken(context.TODO())
  246. if err != nil {
  247. return nil, err
  248. }
  249. opts = append(opts, grpc.WithPerRPCCredentials(c.tokenCred))
  250. }
  251. // add metrics options
  252. opts = append(opts, grpc.WithUnaryInterceptor(prometheus.UnaryClientInterceptor))
  253. opts = append(opts, grpc.WithStreamInterceptor(prometheus.StreamClientInterceptor))
  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. ctx, cancel := context.WithCancel(context.TODO())
  277. client := &Client{
  278. conn: nil,
  279. cfg: *cfg,
  280. creds: creds,
  281. ctx: ctx,
  282. cancel: cancel,
  283. }
  284. if cfg.Username != "" && cfg.Password != "" {
  285. client.Username = cfg.Username
  286. client.Password = cfg.Password
  287. }
  288. client.balancer = newSimpleBalancer(cfg.Endpoints)
  289. conn, err := client.dial(cfg.Endpoints[0], grpc.WithBalancer(client.balancer))
  290. if err != nil {
  291. return nil, err
  292. }
  293. client.conn = conn
  294. client.retryWrapper = client.newRetryWrapper()
  295. client.retryAuthWrapper = client.newAuthRetryWrapper()
  296. // wait for a connection
  297. if cfg.DialTimeout > 0 {
  298. hasConn := false
  299. waitc := time.After(cfg.DialTimeout)
  300. select {
  301. case <-client.balancer.readyc:
  302. hasConn = true
  303. case <-ctx.Done():
  304. case <-waitc:
  305. }
  306. if !hasConn {
  307. client.cancel()
  308. conn.Close()
  309. return nil, grpc.ErrClientConnTimeout
  310. }
  311. }
  312. client.Cluster = NewCluster(client)
  313. client.KV = NewKV(client)
  314. client.Lease = NewLease(client)
  315. client.Watcher = NewWatcher(client)
  316. client.Auth = NewAuth(client)
  317. client.Maintenance = NewMaintenance(client)
  318. go client.autoSync()
  319. return client, nil
  320. }
  321. // ActiveConnection returns the current in-use connection
  322. func (c *Client) ActiveConnection() *grpc.ClientConn { return c.conn }
  323. // isHaltErr returns true if the given error and context indicate no forward
  324. // progress can be made, even after reconnecting.
  325. func isHaltErr(ctx context.Context, err error) bool {
  326. if ctx != nil && ctx.Err() != nil {
  327. return true
  328. }
  329. if err == nil {
  330. return false
  331. }
  332. code := grpc.Code(err)
  333. // Unavailable codes mean the system will be right back.
  334. // (e.g., can't connect, lost leader)
  335. // Treat Internal codes as if something failed, leaving the
  336. // system in an inconsistent state, but retrying could make progress.
  337. // (e.g., failed in middle of send, corrupted frame)
  338. // TODO: are permanent Internal errors possible from grpc?
  339. return code != codes.Unavailable && code != codes.Internal
  340. }
  341. func toErr(ctx context.Context, err error) error {
  342. if err == nil {
  343. return nil
  344. }
  345. err = rpctypes.Error(err)
  346. if _, ok := err.(rpctypes.EtcdError); ok {
  347. return err
  348. }
  349. code := grpc.Code(err)
  350. switch code {
  351. case codes.DeadlineExceeded:
  352. fallthrough
  353. case codes.Canceled:
  354. if ctx.Err() != nil {
  355. err = ctx.Err()
  356. }
  357. case codes.Unavailable:
  358. err = ErrNoAvailableEndpoints
  359. case codes.FailedPrecondition:
  360. err = grpc.ErrClientConnClosing
  361. }
  362. return err
  363. }