client.go 8.4 KB

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