client.go 8.9 KB

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