client.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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. "net"
  20. "net/url"
  21. "strings"
  22. "sync"
  23. "time"
  24. "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  25. "golang.org/x/net/context"
  26. "google.golang.org/grpc"
  27. "google.golang.org/grpc/codes"
  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. retryAuthWrapper 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. // tokenCred is an instance of WithPerRPCCredentials()'s argument
  55. tokenCred *authTokenCredential
  56. }
  57. // New creates a new etcdv3 client from a given configuration.
  58. func New(cfg Config) (*Client, error) {
  59. if len(cfg.Endpoints) == 0 {
  60. return nil, ErrNoAvailableEndpoints
  61. }
  62. return newClient(&cfg)
  63. }
  64. // NewFromURL creates a new etcdv3 client from a URL.
  65. func NewFromURL(url string) (*Client, error) {
  66. return New(Config{Endpoints: []string{url}})
  67. }
  68. // Close shuts down the client's etcd connections.
  69. func (c *Client) Close() error {
  70. c.cancel()
  71. c.Watcher.Close()
  72. c.Lease.Close()
  73. return toErr(c.ctx, c.conn.Close())
  74. }
  75. // Ctx is a context for "out of band" messages (e.g., for sending
  76. // "clean up" message when another context is canceled). It is
  77. // canceled on client Close().
  78. func (c *Client) Ctx() context.Context { return c.ctx }
  79. // Endpoints lists the registered endpoints for the client.
  80. func (c *Client) Endpoints() (eps []string) {
  81. // copy the slice; protect original endpoints from being changed
  82. eps = make([]string, len(c.cfg.Endpoints))
  83. copy(eps, c.cfg.Endpoints)
  84. return
  85. }
  86. // SetEndpoints updates client's endpoints.
  87. func (c *Client) SetEndpoints(eps ...string) {
  88. c.cfg.Endpoints = eps
  89. c.balancer.updateAddrs(eps)
  90. }
  91. // Sync synchronizes client's endpoints with the known endpoints from the etcd membership.
  92. func (c *Client) Sync(ctx context.Context) error {
  93. mresp, err := c.MemberList(ctx)
  94. if err != nil {
  95. return err
  96. }
  97. var eps []string
  98. for _, m := range mresp.Members {
  99. eps = append(eps, m.ClientURLs...)
  100. }
  101. c.SetEndpoints(eps...)
  102. return nil
  103. }
  104. func (c *Client) autoSync() {
  105. if c.cfg.AutoSyncInterval == time.Duration(0) {
  106. return
  107. }
  108. for {
  109. select {
  110. case <-c.ctx.Done():
  111. return
  112. case <-time.After(c.cfg.AutoSyncInterval):
  113. ctx, _ := context.WithTimeout(c.ctx, 5*time.Second)
  114. if err := c.Sync(ctx); err != nil && err != c.ctx.Err() {
  115. logger.Println("Auto sync endpoints failed:", err)
  116. }
  117. }
  118. }
  119. }
  120. type authTokenCredential struct {
  121. token string
  122. tokenMu *sync.RWMutex
  123. }
  124. func (cred authTokenCredential) RequireTransportSecurity() bool {
  125. return false
  126. }
  127. func (cred authTokenCredential) GetRequestMetadata(ctx context.Context, s ...string) (map[string]string, error) {
  128. cred.tokenMu.RLock()
  129. defer cred.tokenMu.RUnlock()
  130. return map[string]string{
  131. "token": cred.token,
  132. }, nil
  133. }
  134. func parseEndpoint(endpoint string) (proto string, host string, scheme string) {
  135. proto = "tcp"
  136. host = endpoint
  137. url, uerr := url.Parse(endpoint)
  138. if uerr != nil || !strings.Contains(endpoint, "://") {
  139. return
  140. }
  141. scheme = url.Scheme
  142. // strip scheme:// prefix since grpc dials by host
  143. host = url.Host
  144. switch url.Scheme {
  145. case "http", "https":
  146. case "unix":
  147. proto = "unix"
  148. default:
  149. proto, host = "", ""
  150. }
  151. return
  152. }
  153. func (c *Client) processCreds(scheme string) (creds *credentials.TransportCredentials) {
  154. creds = c.creds
  155. switch scheme {
  156. case "unix":
  157. case "http":
  158. creds = nil
  159. case "https":
  160. if creds != nil {
  161. break
  162. }
  163. tlsconfig := &tls.Config{}
  164. emptyCreds := credentials.NewTLS(tlsconfig)
  165. creds = &emptyCreds
  166. default:
  167. creds = nil
  168. }
  169. return
  170. }
  171. // dialSetupOpts gives the dial opts prior to any authentication
  172. func (c *Client) dialSetupOpts(endpoint string, dopts ...grpc.DialOption) (opts []grpc.DialOption) {
  173. if c.cfg.DialTimeout > 0 {
  174. opts = []grpc.DialOption{grpc.WithTimeout(c.cfg.DialTimeout)}
  175. }
  176. opts = append(opts, dopts...)
  177. f := func(host string, t time.Duration) (net.Conn, error) {
  178. proto, host, _ := parseEndpoint(c.balancer.getEndpoint(host))
  179. if proto == "" {
  180. return nil, fmt.Errorf("unknown scheme for %q", host)
  181. }
  182. select {
  183. case <-c.ctx.Done():
  184. return nil, c.ctx.Err()
  185. default:
  186. }
  187. dialer := &net.Dialer{Timeout: t}
  188. return dialer.DialContext(c.ctx, proto, host)
  189. }
  190. opts = append(opts, grpc.WithDialer(f))
  191. creds := c.creds
  192. if _, _, scheme := parseEndpoint(endpoint); len(scheme) != 0 {
  193. creds = c.processCreds(scheme)
  194. }
  195. if creds != nil {
  196. opts = append(opts, grpc.WithTransportCredentials(*creds))
  197. } else {
  198. opts = append(opts, grpc.WithInsecure())
  199. }
  200. return opts
  201. }
  202. // Dial connects to a single endpoint using the client's config.
  203. func (c *Client) Dial(endpoint string) (*grpc.ClientConn, error) {
  204. return c.dial(endpoint)
  205. }
  206. func (c *Client) getToken(ctx context.Context) error {
  207. var err error // return last error in a case of fail
  208. var auth *authenticator
  209. for i := 0; i < len(c.cfg.Endpoints); i++ {
  210. endpoint := c.cfg.Endpoints[i]
  211. host := getHost(endpoint)
  212. // use dial options without dopts to avoid reusing the client balancer
  213. auth, err = newAuthenticator(host, c.dialSetupOpts(endpoint))
  214. if err != nil {
  215. continue
  216. }
  217. defer auth.close()
  218. var resp *AuthenticateResponse
  219. resp, err = auth.authenticate(ctx, c.Username, c.Password)
  220. if err != nil {
  221. continue
  222. }
  223. c.tokenCred.tokenMu.Lock()
  224. c.tokenCred.token = resp.Token
  225. c.tokenCred.tokenMu.Unlock()
  226. return nil
  227. }
  228. return err
  229. }
  230. func (c *Client) dial(endpoint string, dopts ...grpc.DialOption) (*grpc.ClientConn, error) {
  231. opts := c.dialSetupOpts(endpoint, dopts...)
  232. host := getHost(endpoint)
  233. if c.Username != "" && c.Password != "" {
  234. c.tokenCred = &authTokenCredential{
  235. tokenMu: &sync.RWMutex{},
  236. }
  237. err := c.getToken(context.TODO())
  238. if err != nil {
  239. return nil, err
  240. }
  241. opts = append(opts, grpc.WithPerRPCCredentials(c.tokenCred))
  242. }
  243. opts = append(opts, c.cfg.DialOptions...)
  244. conn, err := grpc.Dial(host, opts...)
  245. if err != nil {
  246. return nil, err
  247. }
  248. return conn, nil
  249. }
  250. // WithRequireLeader requires client requests to only succeed
  251. // when the cluster has a leader.
  252. func WithRequireLeader(ctx context.Context) context.Context {
  253. md := metadata.Pairs(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
  254. return metadata.NewContext(ctx, md)
  255. }
  256. func newClient(cfg *Config) (*Client, error) {
  257. if cfg == nil {
  258. cfg = &Config{}
  259. }
  260. var creds *credentials.TransportCredentials
  261. if cfg.TLS != nil {
  262. c := credentials.NewTLS(cfg.TLS)
  263. creds = &c
  264. }
  265. // use a temporary skeleton client to bootstrap first connection
  266. ctx, cancel := context.WithCancel(context.TODO())
  267. client := &Client{
  268. conn: nil,
  269. cfg: *cfg,
  270. creds: creds,
  271. ctx: ctx,
  272. cancel: cancel,
  273. }
  274. if cfg.Username != "" && cfg.Password != "" {
  275. client.Username = cfg.Username
  276. client.Password = cfg.Password
  277. }
  278. client.balancer = newSimpleBalancer(cfg.Endpoints)
  279. conn, err := client.dial(cfg.Endpoints[0], grpc.WithBalancer(client.balancer))
  280. if err != nil {
  281. return nil, err
  282. }
  283. client.conn = conn
  284. client.retryWrapper = client.newRetryWrapper()
  285. client.retryAuthWrapper = client.newAuthRetryWrapper()
  286. // wait for a connection
  287. if cfg.DialTimeout > 0 {
  288. hasConn := false
  289. waitc := time.After(cfg.DialTimeout)
  290. select {
  291. case <-client.balancer.readyc:
  292. hasConn = true
  293. case <-ctx.Done():
  294. case <-waitc:
  295. }
  296. if !hasConn {
  297. client.cancel()
  298. conn.Close()
  299. return nil, grpc.ErrClientConnTimeout
  300. }
  301. }
  302. client.Cluster = NewCluster(client)
  303. client.KV = NewKV(client)
  304. client.Lease = NewLease(client)
  305. client.Watcher = NewWatcher(client)
  306. client.Auth = NewAuth(client)
  307. client.Maintenance = NewMaintenance(client)
  308. go client.autoSync()
  309. return client, nil
  310. }
  311. // ActiveConnection returns the current in-use connection
  312. func (c *Client) ActiveConnection() *grpc.ClientConn { return c.conn }
  313. // isHaltErr returns true if the given error and context indicate no forward
  314. // progress can be made, even after reconnecting.
  315. func isHaltErr(ctx context.Context, err error) bool {
  316. if ctx != nil && ctx.Err() != nil {
  317. return true
  318. }
  319. if err == nil {
  320. return false
  321. }
  322. code := grpc.Code(err)
  323. // Unavailable codes mean the system will be right back.
  324. // (e.g., can't connect, lost leader)
  325. // Treat Internal codes as if something failed, leaving the
  326. // system in an inconsistent state, but retrying could make progress.
  327. // (e.g., failed in middle of send, corrupted frame)
  328. // TODO: are permanent Internal errors possible from grpc?
  329. return code != codes.Unavailable && code != codes.Internal
  330. }
  331. func toErr(ctx context.Context, err error) error {
  332. if err == nil {
  333. return nil
  334. }
  335. err = rpctypes.Error(err)
  336. if _, ok := err.(rpctypes.EtcdError); ok {
  337. return err
  338. }
  339. code := grpc.Code(err)
  340. switch code {
  341. case codes.DeadlineExceeded:
  342. fallthrough
  343. case codes.Canceled:
  344. if ctx.Err() != nil {
  345. err = ctx.Err()
  346. }
  347. case codes.Unavailable:
  348. err = ErrNoAvailableEndpoints
  349. case codes.FailedPrecondition:
  350. err = grpc.ErrClientConnClosing
  351. }
  352. return err
  353. }