client.go 9.1 KB

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