client.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. return toErr(c.ctx, c.conn.Close())
  78. }
  79. // Ctx is a context for "out of band" messages (e.g., for sending
  80. // "clean up" message when another context is canceled). It is
  81. // canceled on client Close().
  82. func (c *Client) Ctx() context.Context { return c.ctx }
  83. // Endpoints lists the registered endpoints for the client.
  84. func (c *Client) Endpoints() (eps []string) {
  85. // copy the slice; protect original endpoints from being changed
  86. eps = make([]string, len(c.cfg.Endpoints))
  87. copy(eps, c.cfg.Endpoints)
  88. return
  89. }
  90. // SetEndpoints updates client's endpoints.
  91. func (c *Client) SetEndpoints(eps ...string) {
  92. c.cfg.Endpoints = eps
  93. c.balancer.updateAddrs(eps)
  94. }
  95. // Sync synchronizes client's endpoints with the known endpoints from the etcd membership.
  96. func (c *Client) Sync(ctx context.Context) error {
  97. mresp, err := c.MemberList(ctx)
  98. if err != nil {
  99. return err
  100. }
  101. var eps []string
  102. for _, m := range mresp.Members {
  103. eps = append(eps, m.ClientURLs...)
  104. }
  105. c.SetEndpoints(eps...)
  106. return nil
  107. }
  108. func (c *Client) autoSync() {
  109. if c.cfg.AutoSyncInterval == time.Duration(0) {
  110. return
  111. }
  112. for {
  113. select {
  114. case <-c.ctx.Done():
  115. return
  116. case <-time.After(c.cfg.AutoSyncInterval):
  117. ctx, _ := context.WithTimeout(c.ctx, 5*time.Second)
  118. if err := c.Sync(ctx); err != nil && err != c.ctx.Err() {
  119. logger.Println("Auto sync endpoints failed:", err)
  120. }
  121. }
  122. }
  123. }
  124. type authTokenCredential struct {
  125. token string
  126. }
  127. func (cred authTokenCredential) RequireTransportSecurity() bool {
  128. return false
  129. }
  130. func (cred authTokenCredential) GetRequestMetadata(ctx context.Context, s ...string) (map[string]string, error) {
  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. return net.DialTimeout(proto, host, t)
  189. }
  190. opts = append(opts, grpc.WithDialer(f))
  191. creds := c.creds
  192. if _, _, scheme := parseEndpoint(endpoint); len(scheme) != 0 {
  193. creds = c.processCreds(scheme)
  194. }
  195. if creds != nil {
  196. opts = append(opts, grpc.WithTransportCredentials(*creds))
  197. } else {
  198. opts = append(opts, grpc.WithInsecure())
  199. }
  200. return opts
  201. }
  202. // Dial connects to a single endpoint using the client's config.
  203. func (c *Client) Dial(endpoint string) (*grpc.ClientConn, error) {
  204. return c.dial(endpoint)
  205. }
  206. func (c *Client) dial(endpoint string, dopts ...grpc.DialOption) (*grpc.ClientConn, error) {
  207. opts := c.dialSetupOpts(endpoint, dopts...)
  208. host := getHost(endpoint)
  209. if c.Username != "" && c.Password != "" {
  210. // use dial options without dopts to avoid reusing the client balancer
  211. auth, err := newAuthenticator(host, c.dialSetupOpts(endpoint))
  212. if err != nil {
  213. return nil, err
  214. }
  215. defer auth.close()
  216. resp, err := auth.authenticate(c.ctx, c.Username, c.Password)
  217. if err != nil {
  218. return nil, err
  219. }
  220. opts = append(opts, grpc.WithPerRPCCredentials(authTokenCredential{token: resp.Token}))
  221. }
  222. // add metrics options
  223. opts = append(opts, grpc.WithUnaryInterceptor(prometheus.UnaryClientInterceptor))
  224. opts = append(opts, grpc.WithStreamInterceptor(prometheus.StreamClientInterceptor))
  225. conn, err := grpc.Dial(host, opts...)
  226. if err != nil {
  227. return nil, err
  228. }
  229. return conn, nil
  230. }
  231. // WithRequireLeader requires client requests to only succeed
  232. // when the cluster has a leader.
  233. func WithRequireLeader(ctx context.Context) context.Context {
  234. md := metadata.Pairs(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
  235. return metadata.NewContext(ctx, md)
  236. }
  237. func newClient(cfg *Config) (*Client, error) {
  238. if cfg == nil {
  239. cfg = &Config{}
  240. }
  241. var creds *credentials.TransportCredentials
  242. if cfg.TLS != nil {
  243. c := credentials.NewTLS(cfg.TLS)
  244. creds = &c
  245. }
  246. // use a temporary skeleton client to bootstrap first connection
  247. ctx, cancel := context.WithCancel(context.TODO())
  248. client := &Client{
  249. conn: nil,
  250. cfg: *cfg,
  251. creds: creds,
  252. ctx: ctx,
  253. cancel: cancel,
  254. }
  255. if cfg.Username != "" && cfg.Password != "" {
  256. client.Username = cfg.Username
  257. client.Password = cfg.Password
  258. }
  259. client.balancer = newSimpleBalancer(cfg.Endpoints)
  260. conn, err := client.dial(cfg.Endpoints[0], grpc.WithBalancer(client.balancer))
  261. if err != nil {
  262. return nil, err
  263. }
  264. client.conn = conn
  265. client.retryWrapper = client.newRetryWrapper()
  266. // wait for a connection
  267. if cfg.DialTimeout > 0 {
  268. hasConn := false
  269. waitc := time.After(cfg.DialTimeout)
  270. select {
  271. case <-client.balancer.readyc:
  272. hasConn = true
  273. case <-ctx.Done():
  274. case <-waitc:
  275. }
  276. if !hasConn {
  277. client.cancel()
  278. conn.Close()
  279. return nil, grpc.ErrClientConnTimeout
  280. }
  281. }
  282. client.Cluster = NewCluster(client)
  283. client.KV = NewKV(client)
  284. client.Lease = NewLease(client)
  285. client.Watcher = NewWatcher(client)
  286. client.Auth = NewAuth(client)
  287. client.Maintenance = NewMaintenance(client)
  288. go client.autoSync()
  289. return client, nil
  290. }
  291. // ActiveConnection returns the current in-use connection
  292. func (c *Client) ActiveConnection() *grpc.ClientConn { return c.conn }
  293. // isHaltErr returns true if the given error and context indicate no forward
  294. // progress can be made, even after reconnecting.
  295. func isHaltErr(ctx context.Context, err error) bool {
  296. if ctx != nil && ctx.Err() != nil {
  297. return true
  298. }
  299. if err == nil {
  300. return false
  301. }
  302. code := grpc.Code(err)
  303. // Unavailable codes mean the system will be right back.
  304. // (e.g., can't connect, lost leader)
  305. // Treat Internal codes as if something failed, leaving the
  306. // system in an inconsistent state, but retrying could make progress.
  307. // (e.g., failed in middle of send, corrupted frame)
  308. // TODO: are permanent Internal errors possible from grpc?
  309. return code != codes.Unavailable && code != codes.Internal
  310. }
  311. func toErr(ctx context.Context, err error) error {
  312. if err == nil {
  313. return nil
  314. }
  315. err = rpctypes.Error(err)
  316. if _, ok := err.(rpctypes.EtcdError); ok {
  317. return err
  318. }
  319. code := grpc.Code(err)
  320. switch code {
  321. case codes.DeadlineExceeded:
  322. fallthrough
  323. case codes.Canceled:
  324. if ctx.Err() != nil {
  325. err = ctx.Err()
  326. }
  327. case codes.Unavailable:
  328. err = ErrNoAvailableEndpoints
  329. case codes.FailedPrecondition:
  330. err = grpc.ErrClientConnClosing
  331. }
  332. return err
  333. }