client.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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() (err error) {
  88. c.mu.Lock()
  89. defer c.mu.Unlock()
  90. // acquire the cancel
  91. if c.cancel == nil {
  92. // already canceled
  93. if c.lastConnErr != c.ctx.Err() {
  94. err = c.lastConnErr
  95. }
  96. return
  97. }
  98. cancel := c.cancel
  99. c.cancel = nil
  100. c.mu.Unlock()
  101. // close watcher and lease before terminating connection
  102. // so they don't retry on a closed client
  103. c.Watcher.Close()
  104. c.Lease.Close()
  105. // cancel reconnection loop
  106. cancel()
  107. c.mu.Lock()
  108. connc := c.newconnc
  109. c.mu.Unlock()
  110. // connc on cancel() is left closed
  111. <-connc
  112. c.mu.Lock()
  113. if c.lastConnErr != c.ctx.Err() {
  114. err = c.lastConnErr
  115. }
  116. return
  117. }
  118. // Ctx is a context for "out of band" messages (e.g., for sending
  119. // "clean up" message when another context is canceled). It is
  120. // canceled on client Close().
  121. func (c *Client) Ctx() context.Context { return c.ctx }
  122. // Endpoints lists the registered endpoints for the client.
  123. func (c *Client) Endpoints() []string { return c.cfg.Endpoints }
  124. // Errors returns all errors that have been observed since called last.
  125. func (c *Client) Errors() (errs []error) {
  126. c.mu.Lock()
  127. defer c.mu.Unlock()
  128. errs = c.errors
  129. c.errors = nil
  130. return errs
  131. }
  132. type authTokenCredential struct {
  133. token string
  134. }
  135. func (cred authTokenCredential) RequireTransportSecurity() bool {
  136. return false
  137. }
  138. func (cred authTokenCredential) GetRequestMetadata(ctx context.Context, s ...string) (map[string]string, error) {
  139. return map[string]string{
  140. "token": cred.token,
  141. }, nil
  142. }
  143. // Dial establishes a connection for a given endpoint using the client's config
  144. func (c *Client) Dial(endpoint string) (*grpc.ClientConn, error) {
  145. opts := []grpc.DialOption{
  146. grpc.WithBlock(),
  147. grpc.WithTimeout(c.cfg.DialTimeout),
  148. }
  149. proto := "tcp"
  150. creds := c.creds
  151. if url, uerr := url.Parse(endpoint); uerr == nil && strings.Contains(endpoint, "://") {
  152. switch url.Scheme {
  153. case "unix":
  154. proto = "unix"
  155. case "http":
  156. creds = nil
  157. case "https":
  158. if creds == nil {
  159. tlsconfig := &tls.Config{InsecureSkipVerify: true}
  160. emptyCreds := credentials.NewTLS(tlsconfig)
  161. creds = &emptyCreds
  162. }
  163. default:
  164. return nil, fmt.Errorf("unknown scheme %q for %q", url.Scheme, endpoint)
  165. }
  166. // strip scheme:// prefix since grpc dials by host
  167. endpoint = url.Host
  168. }
  169. f := func(a string, t time.Duration) (net.Conn, error) {
  170. select {
  171. case <-c.ctx.Done():
  172. return nil, c.ctx.Err()
  173. default:
  174. }
  175. return net.DialTimeout(proto, a, t)
  176. }
  177. opts = append(opts, grpc.WithDialer(f))
  178. if creds != nil {
  179. opts = append(opts, grpc.WithTransportCredentials(*creds))
  180. } else {
  181. opts = append(opts, grpc.WithInsecure())
  182. }
  183. if c.Username != "" && c.Password != "" {
  184. auth, err := newAuthenticator(endpoint, opts)
  185. if err != nil {
  186. return nil, err
  187. }
  188. defer auth.close()
  189. resp, err := auth.authenticate(c.ctx, c.Username, c.Password)
  190. if err != nil {
  191. return nil, err
  192. }
  193. opts = append(opts, grpc.WithPerRPCCredentials(authTokenCredential{token: resp.Token}))
  194. }
  195. conn, err := grpc.Dial(endpoint, opts...)
  196. if err != nil {
  197. return nil, err
  198. }
  199. return conn, nil
  200. }
  201. // WithRequireLeader requires client requests to only succeed
  202. // when the cluster has a leader.
  203. func WithRequireLeader(ctx context.Context) context.Context {
  204. md := metadata.Pairs(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
  205. return metadata.NewContext(ctx, md)
  206. }
  207. func newClient(cfg *Config) (*Client, error) {
  208. if cfg == nil {
  209. cfg = &Config{retryDialer: dialEndpointList}
  210. }
  211. var creds *credentials.TransportAuthenticator
  212. if cfg.TLS != nil {
  213. c := credentials.NewTLS(cfg.TLS)
  214. creds = &c
  215. }
  216. // use a temporary skeleton client to bootstrap first connection
  217. ctx, cancel := context.WithCancel(context.TODO())
  218. conn, err := cfg.retryDialer(&Client{cfg: *cfg, creds: creds, ctx: ctx, Username: cfg.Username, Password: cfg.Password})
  219. if err != nil {
  220. return nil, err
  221. }
  222. client := &Client{
  223. conn: conn,
  224. cfg: *cfg,
  225. creds: creds,
  226. ctx: ctx,
  227. cancel: cancel,
  228. reconnc: make(chan error, 1),
  229. newconnc: make(chan struct{}),
  230. }
  231. if cfg.Username != "" && cfg.Password != "" {
  232. client.Username = cfg.Username
  233. client.Password = cfg.Password
  234. }
  235. go client.connMonitor()
  236. client.Cluster = NewCluster(client)
  237. client.KV = NewKV(client)
  238. client.Lease = NewLease(client)
  239. client.Watcher = NewWatcher(client)
  240. client.Auth = NewAuth(client)
  241. client.Maintenance = NewMaintenance(client)
  242. if cfg.Logger != nil {
  243. logger.Set(cfg.Logger)
  244. } else {
  245. // disable client side grpc by default
  246. logger.Set(log.New(ioutil.Discard, "", 0))
  247. }
  248. return client, nil
  249. }
  250. // ActiveConnection returns the current in-use connection
  251. func (c *Client) ActiveConnection() *grpc.ClientConn {
  252. c.mu.RLock()
  253. defer c.mu.RUnlock()
  254. if c.conn == nil {
  255. panic("trying to return nil active connection")
  256. }
  257. return c.conn
  258. }
  259. // retryConnection establishes a new connection
  260. func (c *Client) retryConnection(err error) {
  261. oldconn := c.conn
  262. // return holding lock so old connection can be cleaned up in this defer
  263. defer func() {
  264. if oldconn != nil {
  265. oldconn.Close()
  266. if st, _ := oldconn.State(); st != grpc.Shutdown {
  267. // wait so grpc doesn't leak sleeping goroutines
  268. oldconn.WaitForStateChange(context.Background(), st)
  269. }
  270. }
  271. c.mu.Unlock()
  272. }()
  273. c.mu.Lock()
  274. if err != nil {
  275. c.errors = append(c.errors, err)
  276. }
  277. if c.cancel == nil {
  278. // client has called Close() so don't try to dial out
  279. return
  280. }
  281. c.mu.Unlock()
  282. nc, dialErr := c.cfg.retryDialer(c)
  283. c.mu.Lock()
  284. if nc != nil {
  285. c.conn = nc
  286. }
  287. if dialErr != nil {
  288. c.errors = append(c.errors, dialErr)
  289. }
  290. c.lastConnErr = dialErr
  291. }
  292. // connStartRetry schedules a reconnect if one is not already running
  293. func (c *Client) connStartRetry(err error) {
  294. c.mu.Lock()
  295. ch := c.reconnc
  296. defer c.mu.Unlock()
  297. select {
  298. case ch <- err:
  299. default:
  300. }
  301. }
  302. // connWait waits for a reconnect to be processed
  303. func (c *Client) connWait(ctx context.Context, err error) (*grpc.ClientConn, error) {
  304. c.mu.RLock()
  305. ch := c.newconnc
  306. c.mu.RUnlock()
  307. c.connStartRetry(err)
  308. select {
  309. case <-ctx.Done():
  310. return nil, ctx.Err()
  311. case <-ch:
  312. }
  313. c.mu.RLock()
  314. defer c.mu.RUnlock()
  315. if c.cancel == nil {
  316. return c.conn, rpctypes.ErrConnClosed
  317. }
  318. return c.conn, c.lastConnErr
  319. }
  320. // connMonitor monitors the connection and handles retries
  321. func (c *Client) connMonitor() {
  322. var err error
  323. defer func() {
  324. c.retryConnection(c.ctx.Err())
  325. close(c.newconnc)
  326. }()
  327. limiter := rate.NewLimiter(rate.Every(minConnRetryWait), 1)
  328. for limiter.Wait(c.ctx) == nil {
  329. select {
  330. case err = <-c.reconnc:
  331. case <-c.ctx.Done():
  332. return
  333. }
  334. c.retryConnection(err)
  335. c.mu.Lock()
  336. close(c.newconnc)
  337. c.newconnc = make(chan struct{})
  338. c.reconnc = make(chan error, 1)
  339. c.mu.Unlock()
  340. }
  341. }
  342. // dialEndpointList attempts to connect to each endpoint in order until a
  343. // connection is established.
  344. func dialEndpointList(c *Client) (*grpc.ClientConn, error) {
  345. var err error
  346. for _, ep := range c.Endpoints() {
  347. conn, curErr := c.Dial(ep)
  348. if curErr != nil {
  349. err = curErr
  350. } else {
  351. return conn, nil
  352. }
  353. }
  354. return nil, err
  355. }
  356. // isHaltErr returns true if the given error and context indicate no forward
  357. // progress can be made, even after reconnecting.
  358. func isHaltErr(ctx context.Context, err error) bool {
  359. isRPCError := strings.HasPrefix(grpc.ErrorDesc(err), "etcdserver: ")
  360. return isRPCError || ctx.Err() != nil || err == rpctypes.ErrConnClosed
  361. }