client.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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. "time"
  23. "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  24. prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
  25. "golang.org/x/net/context"
  26. "google.golang.org/grpc"
  27. "google.golang.org/grpc/codes"
  28. "google.golang.org/grpc/credentials"
  29. "google.golang.org/grpc/metadata"
  30. )
  31. var (
  32. ErrNoAvailableEndpoints = errors.New("etcdclient: no available endpoints")
  33. )
  34. // Client provides and manages an etcd v3 client session.
  35. type Client struct {
  36. Cluster
  37. KV
  38. Lease
  39. Watcher
  40. Auth
  41. Maintenance
  42. conn *grpc.ClientConn
  43. cfg Config
  44. creds *credentials.TransportCredentials
  45. balancer *simpleBalancer
  46. retryWrapper retryRpcFunc
  47. ctx context.Context
  48. cancel context.CancelFunc
  49. // Username is a username for authentication
  50. Username string
  51. // Password is a password for authentication
  52. Password string
  53. }
  54. // New creates a new etcdv3 client from a given configuration.
  55. func New(cfg Config) (*Client, error) {
  56. if len(cfg.Endpoints) == 0 {
  57. return nil, ErrNoAvailableEndpoints
  58. }
  59. return newClient(&cfg)
  60. }
  61. // NewFromURL creates a new etcdv3 client from a URL.
  62. func NewFromURL(url string) (*Client, error) {
  63. return New(Config{Endpoints: []string{url}})
  64. }
  65. // NewFromConfigFile creates a new etcdv3 client from a configuration file.
  66. func NewFromConfigFile(path string) (*Client, error) {
  67. cfg, err := configFromFile(path)
  68. if err != nil {
  69. return nil, err
  70. }
  71. return New(*cfg)
  72. }
  73. // Close shuts down the client's etcd connections.
  74. func (c *Client) Close() error {
  75. c.cancel()
  76. c.Watcher.Close()
  77. c.Lease.Close()
  78. return toErr(c.ctx, c.conn.Close())
  79. }
  80. // Ctx is a context for "out of band" messages (e.g., for sending
  81. // "clean up" message when another context is canceled). It is
  82. // canceled on client Close().
  83. func (c *Client) Ctx() context.Context { return c.ctx }
  84. // Endpoints lists the registered endpoints for the client.
  85. func (c *Client) Endpoints() (eps []string) {
  86. // copy the slice; protect original endpoints from being changed
  87. eps = make([]string, len(c.cfg.Endpoints))
  88. copy(eps, c.cfg.Endpoints)
  89. return
  90. }
  91. // SetEndpoints updates client's endpoints.
  92. func (c *Client) SetEndpoints(eps ...string) {
  93. c.cfg.Endpoints = eps
  94. c.balancer.updateAddrs(eps)
  95. }
  96. // Sync synchronizes client's endpoints with the known endpoints from the etcd membership.
  97. func (c *Client) Sync(ctx context.Context) error {
  98. mresp, err := c.MemberList(ctx)
  99. if err != nil {
  100. return err
  101. }
  102. var eps []string
  103. for _, m := range mresp.Members {
  104. eps = append(eps, m.ClientURLs...)
  105. }
  106. c.SetEndpoints(eps...)
  107. return nil
  108. }
  109. func (c *Client) autoSync() {
  110. if c.cfg.AutoSyncInterval == time.Duration(0) {
  111. return
  112. }
  113. for {
  114. select {
  115. case <-c.ctx.Done():
  116. return
  117. case <-time.After(c.cfg.AutoSyncInterval):
  118. ctx, _ := context.WithTimeout(c.ctx, 5*time.Second)
  119. if err := c.Sync(ctx); err != nil && err != c.ctx.Err() {
  120. logger.Println("Auto sync endpoints failed:", err)
  121. }
  122. }
  123. }
  124. }
  125. type authTokenCredential struct {
  126. token string
  127. }
  128. func (cred authTokenCredential) RequireTransportSecurity() bool {
  129. return false
  130. }
  131. func (cred authTokenCredential) GetRequestMetadata(ctx context.Context, s ...string) (map[string]string, error) {
  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. return net.DialTimeout(proto, host, t)
  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) dial(endpoint string, dopts ...grpc.DialOption) (*grpc.ClientConn, error) {
  208. opts := c.dialSetupOpts(endpoint, dopts...)
  209. host := getHost(endpoint)
  210. if c.Username != "" && c.Password != "" {
  211. // use dial options without dopts to avoid reusing the client balancer
  212. auth, err := newAuthenticator(host, c.dialSetupOpts(endpoint))
  213. if err != nil {
  214. return nil, err
  215. }
  216. defer auth.close()
  217. resp, err := auth.authenticate(c.ctx, c.Username, c.Password)
  218. if err != nil {
  219. return nil, err
  220. }
  221. opts = append(opts, grpc.WithPerRPCCredentials(authTokenCredential{token: resp.Token}))
  222. }
  223. // add metrics options
  224. opts = append(opts, grpc.WithUnaryInterceptor(prometheus.UnaryClientInterceptor))
  225. opts = append(opts, grpc.WithStreamInterceptor(prometheus.StreamClientInterceptor))
  226. conn, err := grpc.Dial(host, opts...)
  227. if err != nil {
  228. return nil, err
  229. }
  230. return conn, nil
  231. }
  232. // WithRequireLeader requires client requests to only succeed
  233. // when the cluster has a leader.
  234. func WithRequireLeader(ctx context.Context) context.Context {
  235. md := metadata.Pairs(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
  236. return metadata.NewContext(ctx, md)
  237. }
  238. func newClient(cfg *Config) (*Client, error) {
  239. if cfg == nil {
  240. cfg = &Config{}
  241. }
  242. var creds *credentials.TransportCredentials
  243. if cfg.TLS != nil {
  244. c := credentials.NewTLS(cfg.TLS)
  245. creds = &c
  246. }
  247. // use a temporary skeleton client to bootstrap first connection
  248. ctx, cancel := context.WithCancel(context.TODO())
  249. client := &Client{
  250. conn: nil,
  251. cfg: *cfg,
  252. creds: creds,
  253. ctx: ctx,
  254. cancel: cancel,
  255. }
  256. if cfg.Username != "" && cfg.Password != "" {
  257. client.Username = cfg.Username
  258. client.Password = cfg.Password
  259. }
  260. client.balancer = newSimpleBalancer(cfg.Endpoints)
  261. conn, err := client.dial(cfg.Endpoints[0], grpc.WithBalancer(client.balancer))
  262. if err != nil {
  263. return nil, err
  264. }
  265. client.conn = conn
  266. client.retryWrapper = client.newRetryWrapper()
  267. // wait for a connection
  268. if cfg.DialTimeout > 0 {
  269. hasConn := false
  270. waitc := time.After(cfg.DialTimeout)
  271. select {
  272. case <-client.balancer.readyc:
  273. hasConn = true
  274. case <-ctx.Done():
  275. case <-waitc:
  276. }
  277. if !hasConn {
  278. client.cancel()
  279. conn.Close()
  280. return nil, grpc.ErrClientConnTimeout
  281. }
  282. }
  283. client.Cluster = NewCluster(client)
  284. client.KV = NewKV(client)
  285. client.Lease = NewLease(client)
  286. client.Watcher = NewWatcher(client)
  287. client.Auth = NewAuth(client)
  288. client.Maintenance = NewMaintenance(client)
  289. go client.autoSync()
  290. return client, nil
  291. }
  292. // ActiveConnection returns the current in-use connection
  293. func (c *Client) ActiveConnection() *grpc.ClientConn { return c.conn }
  294. // isHaltErr returns true if the given error and context indicate no forward
  295. // progress can be made, even after reconnecting.
  296. func isHaltErr(ctx context.Context, err error) bool {
  297. if ctx != nil && ctx.Err() != nil {
  298. return true
  299. }
  300. if err == nil {
  301. return false
  302. }
  303. code := grpc.Code(err)
  304. // Unavailable codes mean the system will be right back.
  305. // (e.g., can't connect, lost leader)
  306. // Treat Internal codes as if something failed, leaving the
  307. // system in an inconsistent state, but retrying could make progress.
  308. // (e.g., failed in middle of send, corrupted frame)
  309. // TODO: are permanent Internal errors possible from grpc?
  310. return code != codes.Unavailable && code != codes.Internal
  311. }
  312. func toErr(ctx context.Context, err error) error {
  313. if err == nil {
  314. return nil
  315. }
  316. err = rpctypes.Error(err)
  317. if _, ok := err.(rpctypes.EtcdError); ok {
  318. return err
  319. }
  320. code := grpc.Code(err)
  321. switch code {
  322. case codes.DeadlineExceeded:
  323. fallthrough
  324. case codes.Canceled:
  325. if ctx.Err() != nil {
  326. err = ctx.Err()
  327. }
  328. case codes.Unavailable:
  329. err = ErrNoAvailableEndpoints
  330. case codes.FailedPrecondition:
  331. err = grpc.ErrClientConnClosing
  332. }
  333. return err
  334. }