client.go 7.6 KB

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