client.go 7.1 KB

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