client.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. "sync"
  25. "time"
  26. "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  27. "golang.org/x/net/context"
  28. "golang.org/x/time/rate"
  29. "google.golang.org/grpc"
  30. "google.golang.org/grpc/credentials"
  31. "google.golang.org/grpc/metadata"
  32. )
  33. var (
  34. ErrNoAvailableEndpoints = errors.New("etcdclient: no available endpoints")
  35. // minConnRetryWait is the minimum time between reconnects to avoid flooding
  36. minConnRetryWait = time.Second
  37. )
  38. // Client provides and manages an etcd v3 client session.
  39. type Client struct {
  40. Cluster
  41. KV
  42. Lease
  43. Watcher
  44. Auth
  45. Maintenance
  46. conn *grpc.ClientConn
  47. cfg Config
  48. creds *credentials.TransportAuthenticator
  49. mu sync.RWMutex // protects connection selection and error list
  50. errors []error // errors passed to retryConnection
  51. ctx context.Context
  52. cancel context.CancelFunc
  53. // fields below are managed by connMonitor
  54. // reconnc accepts writes which signal the client should reconnect
  55. reconnc chan error
  56. // newconnc is closed on successful connect and set to a fresh channel
  57. newconnc chan struct{}
  58. lastConnErr error
  59. // Username is a username for authentication
  60. Username string
  61. // Password is a password for authentication
  62. Password string
  63. }
  64. // New creates a new etcdv3 client from a given configuration.
  65. func New(cfg Config) (*Client, error) {
  66. if cfg.RetryDialer == nil {
  67. cfg.RetryDialer = dialEndpointList
  68. }
  69. if len(cfg.Endpoints) == 0 {
  70. return nil, ErrNoAvailableEndpoints
  71. }
  72. return newClient(&cfg)
  73. }
  74. // NewFromURL creates a new etcdv3 client from a URL.
  75. func NewFromURL(url string) (*Client, error) {
  76. return New(Config{Endpoints: []string{url}})
  77. }
  78. // NewFromConfigFile creates a new etcdv3 client from a configuration file.
  79. func NewFromConfigFile(path string) (*Client, error) {
  80. cfg, err := configFromFile(path)
  81. if err != nil {
  82. return nil, err
  83. }
  84. return New(*cfg)
  85. }
  86. // Close shuts down the client's etcd connections.
  87. func (c *Client) Close() error {
  88. c.mu.Lock()
  89. defer c.mu.Unlock()
  90. if c.cancel == nil {
  91. return nil
  92. }
  93. c.cancel()
  94. c.cancel = nil
  95. connc := c.newconnc
  96. c.mu.Unlock()
  97. c.connStartRetry(nil)
  98. c.Watcher.Close()
  99. c.Lease.Close()
  100. <-connc
  101. c.mu.Lock()
  102. if c.lastConnErr != c.ctx.Err() {
  103. return c.lastConnErr
  104. }
  105. return nil
  106. }
  107. // Ctx is a context for "out of band" messages (e.g., for sending
  108. // "clean up" message when another context is canceled). It is
  109. // canceled on client Close().
  110. func (c *Client) Ctx() context.Context { return c.ctx }
  111. // Endpoints lists the registered endpoints for the client.
  112. func (c *Client) Endpoints() []string { return c.cfg.Endpoints }
  113. // Errors returns all errors that have been observed since called last.
  114. func (c *Client) Errors() (errs []error) {
  115. c.mu.Lock()
  116. defer c.mu.Unlock()
  117. errs = c.errors
  118. c.errors = nil
  119. return errs
  120. }
  121. type authTokenCredential struct {
  122. token string
  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. return map[string]string{
  129. "token": cred.token,
  130. }, nil
  131. }
  132. // Dial establishes a connection for a given endpoint using the client's config
  133. func (c *Client) Dial(endpoint string) (*grpc.ClientConn, error) {
  134. opts := []grpc.DialOption{
  135. grpc.WithBlock(),
  136. grpc.WithTimeout(c.cfg.DialTimeout),
  137. }
  138. proto := "tcp"
  139. creds := c.creds
  140. if url, uerr := url.Parse(endpoint); uerr == nil && strings.Contains(endpoint, "://") {
  141. switch url.Scheme {
  142. case "unix":
  143. proto = "unix"
  144. case "http":
  145. creds = nil
  146. case "https":
  147. if creds == nil {
  148. tlsconfig := &tls.Config{InsecureSkipVerify: true}
  149. emptyCreds := credentials.NewTLS(tlsconfig)
  150. creds = &emptyCreds
  151. }
  152. default:
  153. return nil, fmt.Errorf("unknown scheme %q for %q", url.Scheme, endpoint)
  154. }
  155. // strip scheme:// prefix since grpc dials by host
  156. endpoint = url.Host
  157. }
  158. f := func(a string, t time.Duration) (net.Conn, error) {
  159. select {
  160. case <-c.ctx.Done():
  161. return nil, c.ctx.Err()
  162. default:
  163. }
  164. return net.DialTimeout(proto, a, t)
  165. }
  166. opts = append(opts, grpc.WithDialer(f))
  167. if creds != nil {
  168. opts = append(opts, grpc.WithTransportCredentials(*creds))
  169. } else {
  170. opts = append(opts, grpc.WithInsecure())
  171. }
  172. if c.Username != "" && c.Password != "" {
  173. auth, err := newAuthenticator(endpoint, opts)
  174. if err != nil {
  175. return nil, err
  176. }
  177. defer auth.close()
  178. resp, err := auth.authenticate(c.ctx, c.Username, c.Password)
  179. if err != nil {
  180. return nil, err
  181. }
  182. opts = append(opts, grpc.WithPerRPCCredentials(authTokenCredential{token: resp.Token}))
  183. }
  184. conn, err := grpc.Dial(endpoint, opts...)
  185. if err != nil {
  186. return nil, err
  187. }
  188. return conn, nil
  189. }
  190. // WithRequireLeader requires client requests to only succeed
  191. // when the cluster has a leader.
  192. func WithRequireLeader(ctx context.Context) context.Context {
  193. md := metadata.Pairs(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
  194. return metadata.NewContext(ctx, md)
  195. }
  196. func newClient(cfg *Config) (*Client, error) {
  197. if cfg == nil {
  198. cfg = &Config{RetryDialer: dialEndpointList}
  199. }
  200. var creds *credentials.TransportAuthenticator
  201. if cfg.TLS != nil {
  202. c := credentials.NewTLS(cfg.TLS)
  203. creds = &c
  204. }
  205. // use a temporary skeleton client to bootstrap first connection
  206. ctx, cancel := context.WithCancel(context.TODO())
  207. conn, err := cfg.RetryDialer(&Client{cfg: *cfg, creds: creds, ctx: ctx, Username: cfg.Username, Password: cfg.Password})
  208. if err != nil {
  209. return nil, err
  210. }
  211. client := &Client{
  212. conn: conn,
  213. cfg: *cfg,
  214. creds: creds,
  215. ctx: ctx,
  216. cancel: cancel,
  217. reconnc: make(chan error, 1),
  218. newconnc: make(chan struct{}),
  219. }
  220. if cfg.Username != "" && cfg.Password != "" {
  221. client.Username = cfg.Username
  222. client.Password = cfg.Password
  223. }
  224. go client.connMonitor()
  225. client.Cluster = NewCluster(client)
  226. client.KV = NewKV(client)
  227. client.Lease = NewLease(client)
  228. client.Watcher = NewWatcher(client)
  229. client.Auth = NewAuth(client)
  230. client.Maintenance = NewMaintenance(client)
  231. if cfg.Logger != nil {
  232. logger.Set(cfg.Logger)
  233. } else {
  234. // disable client side grpc by default
  235. logger.Set(log.New(ioutil.Discard, "", 0))
  236. }
  237. return client, nil
  238. }
  239. // ActiveConnection returns the current in-use connection
  240. func (c *Client) ActiveConnection() *grpc.ClientConn {
  241. c.mu.RLock()
  242. defer c.mu.RUnlock()
  243. return c.conn
  244. }
  245. // retryConnection establishes a new connection
  246. func (c *Client) retryConnection(err error) (newConn *grpc.ClientConn, dialErr error) {
  247. c.mu.Lock()
  248. defer c.mu.Unlock()
  249. if err != nil {
  250. c.errors = append(c.errors, err)
  251. }
  252. if c.conn != nil {
  253. c.conn.Close()
  254. if st, _ := c.conn.State(); st != grpc.Shutdown {
  255. // wait so grpc doesn't leak sleeping goroutines
  256. c.conn.WaitForStateChange(context.Background(), st)
  257. }
  258. c.conn = nil
  259. }
  260. if c.cancel == nil {
  261. // client has called Close() so don't try to dial out
  262. return nil, c.ctx.Err()
  263. }
  264. c.conn, dialErr = c.cfg.RetryDialer(c)
  265. if dialErr != nil {
  266. c.errors = append(c.errors, dialErr)
  267. }
  268. return c.conn, dialErr
  269. }
  270. // connStartRetry schedules a reconnect if one is not already running
  271. func (c *Client) connStartRetry(err error) {
  272. c.mu.Lock()
  273. ch := c.reconnc
  274. defer c.mu.Unlock()
  275. select {
  276. case ch <- err:
  277. default:
  278. }
  279. }
  280. // connWait waits for a reconnect to be processed
  281. func (c *Client) connWait(ctx context.Context, err error) (*grpc.ClientConn, error) {
  282. c.mu.Lock()
  283. ch := c.newconnc
  284. c.mu.Unlock()
  285. c.connStartRetry(err)
  286. select {
  287. case <-ctx.Done():
  288. return nil, ctx.Err()
  289. case <-ch:
  290. }
  291. c.mu.Lock()
  292. defer c.mu.Unlock()
  293. return c.conn, c.lastConnErr
  294. }
  295. // connMonitor monitors the connection and handles retries
  296. func (c *Client) connMonitor() {
  297. var err error
  298. defer func() {
  299. _, err = c.retryConnection(c.ctx.Err())
  300. c.mu.Lock()
  301. c.lastConnErr = err
  302. close(c.newconnc)
  303. c.mu.Unlock()
  304. }()
  305. limiter := rate.NewLimiter(rate.Every(minConnRetryWait), 1)
  306. for limiter.Wait(c.ctx) == nil {
  307. select {
  308. case err = <-c.reconnc:
  309. case <-c.ctx.Done():
  310. return
  311. }
  312. conn, connErr := c.retryConnection(err)
  313. c.mu.Lock()
  314. c.lastConnErr = connErr
  315. c.conn = conn
  316. close(c.newconnc)
  317. c.newconnc = make(chan struct{})
  318. c.reconnc = make(chan error, 1)
  319. c.mu.Unlock()
  320. }
  321. }
  322. // dialEndpointList attempts to connect to each endpoint in order until a
  323. // connection is established.
  324. func dialEndpointList(c *Client) (*grpc.ClientConn, error) {
  325. var err error
  326. for _, ep := range c.Endpoints() {
  327. conn, curErr := c.Dial(ep)
  328. if curErr != nil {
  329. err = curErr
  330. } else {
  331. return conn, nil
  332. }
  333. }
  334. return nil, err
  335. }
  336. // isHaltErr returns true if the given error and context indicate no forward
  337. // progress can be made, even after reconnecting.
  338. func isHaltErr(ctx context.Context, err error) bool {
  339. isRPCError := strings.HasPrefix(grpc.ErrorDesc(err), "etcdserver: ")
  340. return isRPCError || ctx.Err() != nil || err == rpctypes.ErrConnClosed
  341. }