client.go 9.0 KB

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