client.go 10.0 KB

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