client.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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/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. 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. type authTokenCredential struct {
  85. token string
  86. }
  87. func (cred authTokenCredential) RequireTransportSecurity() bool {
  88. return false
  89. }
  90. func (cred authTokenCredential) GetRequestMetadata(ctx context.Context, s ...string) (map[string]string, error) {
  91. return map[string]string{
  92. "token": cred.token,
  93. }, nil
  94. }
  95. func (c *Client) dialTarget(endpoint string) (proto string, host string, creds *credentials.TransportCredentials) {
  96. proto = "tcp"
  97. host = endpoint
  98. creds = c.creds
  99. url, uerr := url.Parse(endpoint)
  100. if uerr != nil || !strings.Contains(endpoint, "://") {
  101. return
  102. }
  103. // strip scheme:// prefix since grpc dials by host
  104. host = url.Host
  105. switch url.Scheme {
  106. case "unix":
  107. proto = "unix"
  108. case "http":
  109. creds = nil
  110. case "https":
  111. if creds != nil {
  112. break
  113. }
  114. tlsconfig := &tls.Config{}
  115. emptyCreds := credentials.NewTLS(tlsconfig)
  116. creds = &emptyCreds
  117. default:
  118. return "", "", nil
  119. }
  120. return
  121. }
  122. // dialSetupOpts gives the dial opts prior to any authentication
  123. func (c *Client) dialSetupOpts(endpoint string, dopts ...grpc.DialOption) (opts []grpc.DialOption) {
  124. if c.cfg.DialTimeout > 0 {
  125. opts = []grpc.DialOption{grpc.WithTimeout(c.cfg.DialTimeout)}
  126. }
  127. opts = append(opts, dopts...)
  128. // grpc issues TLS cert checks using the string passed into dial so
  129. // that string must be the host. To recover the full scheme://host URL,
  130. // have a map from hosts to the original endpoint.
  131. host2ep := make(map[string]string)
  132. for i := range c.cfg.Endpoints {
  133. _, host, _ := c.dialTarget(c.cfg.Endpoints[i])
  134. host2ep[host] = c.cfg.Endpoints[i]
  135. }
  136. f := func(host string, t time.Duration) (net.Conn, error) {
  137. proto, host, _ := c.dialTarget(host2ep[host])
  138. if proto == "" {
  139. return nil, fmt.Errorf("unknown scheme for %q", host)
  140. }
  141. select {
  142. case <-c.ctx.Done():
  143. return nil, c.ctx.Err()
  144. default:
  145. }
  146. return net.DialTimeout(proto, host, t)
  147. }
  148. opts = append(opts, grpc.WithDialer(f))
  149. _, _, creds := c.dialTarget(endpoint)
  150. if creds != nil {
  151. opts = append(opts, grpc.WithTransportCredentials(*creds))
  152. } else {
  153. opts = append(opts, grpc.WithInsecure())
  154. }
  155. return opts
  156. }
  157. // Dial connects to a single endpoint using the client's config.
  158. func (c *Client) Dial(endpoint string) (*grpc.ClientConn, error) {
  159. return c.dial(endpoint)
  160. }
  161. func (c *Client) dial(endpoint string, dopts ...grpc.DialOption) (*grpc.ClientConn, error) {
  162. opts := c.dialSetupOpts(endpoint, dopts...)
  163. host := getHost(endpoint)
  164. if c.Username != "" && c.Password != "" {
  165. // use dial options without dopts to avoid reusing the client balancer
  166. auth, err := newAuthenticator(host, c.dialSetupOpts(endpoint))
  167. if err != nil {
  168. return nil, err
  169. }
  170. defer auth.close()
  171. resp, err := auth.authenticate(c.ctx, c.Username, c.Password)
  172. if err != nil {
  173. return nil, err
  174. }
  175. opts = append(opts, grpc.WithPerRPCCredentials(authTokenCredential{token: resp.Token}))
  176. }
  177. conn, err := grpc.Dial(host, opts...)
  178. if err != nil {
  179. return nil, err
  180. }
  181. return conn, nil
  182. }
  183. // WithRequireLeader requires client requests to only succeed
  184. // when the cluster has a leader.
  185. func WithRequireLeader(ctx context.Context) context.Context {
  186. md := metadata.Pairs(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
  187. return metadata.NewContext(ctx, md)
  188. }
  189. func newClient(cfg *Config) (*Client, error) {
  190. if cfg == nil {
  191. cfg = &Config{}
  192. }
  193. var creds *credentials.TransportCredentials
  194. if cfg.TLS != nil {
  195. c := credentials.NewTLS(cfg.TLS)
  196. creds = &c
  197. }
  198. // use a temporary skeleton client to bootstrap first connection
  199. ctx, cancel := context.WithCancel(context.TODO())
  200. client := &Client{
  201. conn: nil,
  202. cfg: *cfg,
  203. creds: creds,
  204. ctx: ctx,
  205. cancel: cancel,
  206. }
  207. if cfg.Username != "" && cfg.Password != "" {
  208. client.Username = cfg.Username
  209. client.Password = cfg.Password
  210. }
  211. client.balancer = newSimpleBalancer(cfg.Endpoints)
  212. conn, err := client.dial(cfg.Endpoints[0], grpc.WithBalancer(client.balancer))
  213. if err != nil {
  214. return nil, err
  215. }
  216. client.conn = conn
  217. client.retryWrapper = client.newRetryWrapper()
  218. // wait for a connection
  219. if cfg.DialTimeout > 0 {
  220. hasConn := false
  221. waitc := time.After(cfg.DialTimeout)
  222. select {
  223. case <-client.balancer.readyc:
  224. hasConn = true
  225. case <-ctx.Done():
  226. case <-waitc:
  227. }
  228. if !hasConn {
  229. client.cancel()
  230. conn.Close()
  231. return nil, grpc.ErrClientConnTimeout
  232. }
  233. }
  234. client.Cluster = NewCluster(client)
  235. client.KV = NewKV(client)
  236. client.Lease = NewLease(client)
  237. client.Watcher = NewWatcher(client)
  238. client.Auth = NewAuth(client)
  239. client.Maintenance = NewMaintenance(client)
  240. if cfg.Logger != nil {
  241. logger.Set(cfg.Logger)
  242. } else {
  243. // disable client side grpc by default
  244. logger.Set(log.New(ioutil.Discard, "", 0))
  245. }
  246. return client, nil
  247. }
  248. // ActiveConnection returns the current in-use connection
  249. func (c *Client) ActiveConnection() *grpc.ClientConn { return c.conn }
  250. // isHaltErr returns true if the given error and context indicate no forward
  251. // progress can be made, even after reconnecting.
  252. func isHaltErr(ctx context.Context, err error) bool {
  253. if ctx != nil && ctx.Err() != nil {
  254. return true
  255. }
  256. if err == nil {
  257. return false
  258. }
  259. eErr := rpctypes.Error(err)
  260. if _, ok := eErr.(rpctypes.EtcdError); ok {
  261. return eErr != rpctypes.ErrStopped && eErr != rpctypes.ErrNoLeader
  262. }
  263. // treat etcdserver errors not recognized by the client as halting
  264. return isConnClosing(err) || strings.Contains(err.Error(), "etcdserver:")
  265. }
  266. // isConnClosing returns true if the error matches a grpc client closing error
  267. func isConnClosing(err error) bool {
  268. return strings.Contains(err.Error(), grpc.ErrClientConnClosing.Error())
  269. }
  270. func toErr(ctx context.Context, err error) error {
  271. if err == nil {
  272. return nil
  273. }
  274. err = rpctypes.Error(err)
  275. switch {
  276. case ctx.Err() != nil && strings.Contains(err.Error(), "context"):
  277. err = ctx.Err()
  278. case strings.Contains(err.Error(), ErrNoAvailableEndpoints.Error()):
  279. err = ErrNoAvailableEndpoints
  280. case strings.Contains(err.Error(), grpc.ErrClientConnClosing.Error()):
  281. err = grpc.ErrClientConnClosing
  282. }
  283. return err
  284. }