client.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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 prior to any authentication
  121. func (c *Client) dialSetupOpts(endpoint string, dopts ...grpc.DialOption) (opts []grpc.DialOption) {
  122. if c.cfg.DialTimeout > 0 {
  123. opts = []grpc.DialOption{
  124. grpc.WithTimeout(c.cfg.DialTimeout),
  125. grpc.WithBlock(),
  126. }
  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. b := newSimpleBalancer(cfg.Endpoints)
  213. conn, err := client.dial(cfg.Endpoints[0], grpc.WithBalancer(b))
  214. if err != nil {
  215. return nil, err
  216. }
  217. client.conn = conn
  218. client.Cluster = NewCluster(client)
  219. client.KV = NewKV(client)
  220. client.Lease = NewLease(client)
  221. client.Watcher = NewWatcher(client)
  222. client.Auth = NewAuth(client)
  223. client.Maintenance = NewMaintenance(client)
  224. if cfg.Logger != nil {
  225. logger.Set(cfg.Logger)
  226. } else {
  227. // disable client side grpc by default
  228. logger.Set(log.New(ioutil.Discard, "", 0))
  229. }
  230. return client, nil
  231. }
  232. // ActiveConnection returns the current in-use connection
  233. func (c *Client) ActiveConnection() *grpc.ClientConn { return c.conn }
  234. // isHaltErr returns true if the given error and context indicate no forward
  235. // progress can be made, even after reconnecting.
  236. func isHaltErr(ctx context.Context, err error) bool {
  237. if ctx != nil && ctx.Err() != nil {
  238. return true
  239. }
  240. if err == nil {
  241. return false
  242. }
  243. eErr := rpctypes.Error(err)
  244. if _, ok := eErr.(rpctypes.EtcdError); ok {
  245. return eErr != rpctypes.ErrStopped && eErr != rpctypes.ErrNoLeader
  246. }
  247. // treat etcdserver errors not recognized by the client as halting
  248. return strings.Contains(err.Error(), grpc.ErrClientConnClosing.Error()) ||
  249. strings.Contains(err.Error(), "etcdserver:")
  250. }
  251. func toErr(ctx context.Context, err error) error {
  252. if err == nil {
  253. return nil
  254. }
  255. err = rpctypes.Error(err)
  256. if ctx.Err() != nil && strings.Contains(err.Error(), "context") {
  257. err = ctx.Err()
  258. } else if strings.Contains(err.Error(), grpc.ErrClientConnClosing.Error()) {
  259. err = grpc.ErrClientConnClosing
  260. }
  261. return err
  262. }