client.go 9.0 KB

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