client.go 8.0 KB

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