client.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. ctx context.Context
  46. cancel context.CancelFunc
  47. // Username is a username for authentication
  48. Username string
  49. // Password is a password for authentication
  50. Password string
  51. }
  52. // New creates a new etcdv3 client from a given configuration.
  53. func New(cfg Config) (*Client, error) {
  54. if len(cfg.Endpoints) == 0 {
  55. return nil, ErrNoAvailableEndpoints
  56. }
  57. return newClient(&cfg)
  58. }
  59. // NewFromURL creates a new etcdv3 client from a URL.
  60. func NewFromURL(url string) (*Client, error) {
  61. return New(Config{Endpoints: []string{url}})
  62. }
  63. // NewFromConfigFile creates a new etcdv3 client from a configuration file.
  64. func NewFromConfigFile(path string) (*Client, error) {
  65. cfg, err := configFromFile(path)
  66. if err != nil {
  67. return nil, err
  68. }
  69. return New(*cfg)
  70. }
  71. // Close shuts down the client's etcd connections.
  72. func (c *Client) Close() error {
  73. c.cancel()
  74. return toErr(c.ctx, c.conn.Close())
  75. }
  76. // Ctx is a context for "out of band" messages (e.g., for sending
  77. // "clean up" message when another context is canceled). It is
  78. // canceled on client Close().
  79. func (c *Client) Ctx() context.Context { return c.ctx }
  80. // Endpoints lists the registered endpoints for the client.
  81. func (c *Client) Endpoints() []string { return c.cfg.Endpoints }
  82. type authTokenCredential struct {
  83. token string
  84. }
  85. func (cred authTokenCredential) RequireTransportSecurity() bool {
  86. return false
  87. }
  88. func (cred authTokenCredential) GetRequestMetadata(ctx context.Context, s ...string) (map[string]string, error) {
  89. return map[string]string{
  90. "token": cred.token,
  91. }, nil
  92. }
  93. func (c *Client) dialTarget(endpoint string) (proto string, host string, creds *credentials.TransportCredentials) {
  94. proto = "tcp"
  95. host = endpoint
  96. creds = c.creds
  97. url, uerr := url.Parse(endpoint)
  98. if uerr != nil || !strings.Contains(endpoint, "://") {
  99. return
  100. }
  101. // strip scheme:// prefix since grpc dials by host
  102. host = url.Host
  103. switch url.Scheme {
  104. case "unix":
  105. proto = "unix"
  106. case "http":
  107. creds = nil
  108. case "https":
  109. if creds != nil {
  110. break
  111. }
  112. tlsconfig := &tls.Config{}
  113. emptyCreds := credentials.NewTLS(tlsconfig)
  114. creds = &emptyCreds
  115. default:
  116. return "", "", nil
  117. }
  118. return
  119. }
  120. // dialSetupOpts gives the dial opts prioer to any authentication
  121. func (c *Client) dialSetupOpts(endpoint string, dopts ...grpc.DialOption) []grpc.DialOption {
  122. opts := []grpc.DialOption{
  123. grpc.WithBlock(),
  124. grpc.WithTimeout(c.cfg.DialTimeout),
  125. }
  126. opts = append(opts, dopts...)
  127. // grpc issues TLS cert checks using the string passed into dial so
  128. // that string must be the host. To recover the full scheme://host URL,
  129. // have a map from hosts to the original endpoint.
  130. host2ep := make(map[string]string)
  131. for i := range c.cfg.Endpoints {
  132. _, host, _ := c.dialTarget(c.cfg.Endpoints[i])
  133. host2ep[host] = c.cfg.Endpoints[i]
  134. }
  135. f := func(host string, t time.Duration) (net.Conn, error) {
  136. proto, host, _ := c.dialTarget(host2ep[host])
  137. if proto == "" {
  138. return nil, fmt.Errorf("unknown scheme for %q", host)
  139. }
  140. select {
  141. case <-c.ctx.Done():
  142. return nil, c.ctx.Err()
  143. default:
  144. }
  145. return net.DialTimeout(proto, host, t)
  146. }
  147. opts = append(opts, grpc.WithDialer(f))
  148. _, _, creds := c.dialTarget(endpoint)
  149. if creds != nil {
  150. opts = append(opts, grpc.WithTransportCredentials(*creds))
  151. } else {
  152. opts = append(opts, grpc.WithInsecure())
  153. }
  154. return opts
  155. }
  156. // Dial connects to a single endpoint using the client's config.
  157. func (c *Client) Dial(endpoint string) (*grpc.ClientConn, error) {
  158. return c.dial(endpoint)
  159. }
  160. func (c *Client) dial(endpoint string, dopts ...grpc.DialOption) (*grpc.ClientConn, error) {
  161. opts := c.dialSetupOpts(endpoint, dopts...)
  162. host := getHost(endpoint)
  163. if c.Username != "" && c.Password != "" {
  164. // use dial options without dopts to avoid reusing the client balancer
  165. auth, err := newAuthenticator(host, c.dialSetupOpts(endpoint))
  166. if err != nil {
  167. return nil, err
  168. }
  169. defer auth.close()
  170. resp, err := auth.authenticate(c.ctx, c.Username, c.Password)
  171. if err != nil {
  172. return nil, err
  173. }
  174. opts = append(opts, grpc.WithPerRPCCredentials(authTokenCredential{token: resp.Token}))
  175. }
  176. conn, err := grpc.Dial(host, opts...)
  177. if err != nil {
  178. return nil, err
  179. }
  180. return conn, nil
  181. }
  182. // WithRequireLeader requires client requests to only succeed
  183. // when the cluster has a leader.
  184. func WithRequireLeader(ctx context.Context) context.Context {
  185. md := metadata.Pairs(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
  186. return metadata.NewContext(ctx, md)
  187. }
  188. func newClient(cfg *Config) (*Client, error) {
  189. if cfg == nil {
  190. cfg = &Config{}
  191. }
  192. var creds *credentials.TransportCredentials
  193. if cfg.TLS != nil {
  194. c := credentials.NewTLS(cfg.TLS)
  195. creds = &c
  196. }
  197. // use a temporary skeleton client to bootstrap first connection
  198. ctx, cancel := context.WithCancel(context.TODO())
  199. client := &Client{
  200. conn: nil,
  201. cfg: *cfg,
  202. creds: creds,
  203. ctx: ctx,
  204. cancel: cancel,
  205. }
  206. if cfg.Username != "" && cfg.Password != "" {
  207. client.Username = cfg.Username
  208. client.Password = cfg.Password
  209. }
  210. b := newSimpleBalancer(cfg.Endpoints)
  211. conn, err := client.dial(cfg.Endpoints[0], grpc.WithBalancer(b))
  212. if err != nil {
  213. return nil, err
  214. }
  215. client.conn = conn
  216. client.Cluster = NewCluster(client)
  217. client.KV = NewKV(client)
  218. client.Lease = NewLease(client)
  219. client.Watcher = NewWatcher(client)
  220. client.Auth = NewAuth(client)
  221. client.Maintenance = NewMaintenance(client)
  222. if cfg.Logger != nil {
  223. logger.Set(cfg.Logger)
  224. } else {
  225. // disable client side grpc by default
  226. logger.Set(log.New(ioutil.Discard, "", 0))
  227. }
  228. return client, nil
  229. }
  230. // ActiveConnection returns the current in-use connection
  231. func (c *Client) ActiveConnection() *grpc.ClientConn { return c.conn }
  232. // isHaltErr returns true if the given error and context indicate no forward
  233. // progress can be made, even after reconnecting.
  234. func isHaltErr(ctx context.Context, err error) bool {
  235. if ctx != nil && ctx.Err() != nil {
  236. return true
  237. }
  238. if err == nil {
  239. return false
  240. }
  241. eErr := rpctypes.Error(err)
  242. if _, ok := eErr.(rpctypes.EtcdError); ok {
  243. return eErr != rpctypes.ErrStopped && eErr != rpctypes.ErrNoLeader
  244. }
  245. // treat etcdserver errors not recognized by the client as halting
  246. return strings.Contains(err.Error(), grpc.ErrClientConnClosing.Error()) ||
  247. strings.Contains(err.Error(), "etcdserver:")
  248. }
  249. func toErr(ctx context.Context, err error) error {
  250. if err == nil {
  251. return nil
  252. }
  253. err = rpctypes.Error(err)
  254. if ctx.Err() != nil && strings.Contains(err.Error(), "context") {
  255. err = ctx.Err()
  256. } else if strings.Contains(err.Error(), grpc.ErrClientConnClosing.Error()) {
  257. err = grpc.ErrClientConnClosing
  258. }
  259. return err
  260. }