client.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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. "crypto/tls"
  17. "errors"
  18. "io/ioutil"
  19. "log"
  20. "net"
  21. "net/url"
  22. "strings"
  23. "sync"
  24. "time"
  25. "golang.org/x/net/context"
  26. "google.golang.org/grpc"
  27. "google.golang.org/grpc/credentials"
  28. )
  29. var (
  30. ErrNoAvailableEndpoints = errors.New("etcdclient: no available endpoints")
  31. )
  32. // Client provides and manages an etcd v3 client session.
  33. type Client struct {
  34. Cluster
  35. KV
  36. Lease
  37. Watcher
  38. Auth
  39. Maintenance
  40. conn *grpc.ClientConn
  41. cfg Config
  42. creds *credentials.TransportAuthenticator
  43. mu sync.RWMutex // protects connection selection and error list
  44. errors []error // errors passed to retryConnection
  45. ctx context.Context
  46. cancel context.CancelFunc
  47. }
  48. // EndpointDialer is a policy for choosing which endpoint to dial next
  49. type EndpointDialer func(*Client) (*grpc.ClientConn, error)
  50. type Config struct {
  51. // Endpoints is a list of URLs
  52. Endpoints []string
  53. // RetryDialer chooses the next endpoint to use
  54. RetryDialer EndpointDialer
  55. // DialTimeout is the timeout for failing to establish a connection.
  56. DialTimeout time.Duration
  57. // TLS holds the client secure credentials, if any.
  58. TLS *tls.Config
  59. // Logger is the logger used by client library.
  60. Logger Logger
  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. // Close shuts down the client's etcd connections.
  77. func (c *Client) Close() error {
  78. c.mu.Lock()
  79. if c.cancel == nil {
  80. c.mu.Unlock()
  81. return nil
  82. }
  83. c.cancel()
  84. c.cancel = nil
  85. c.mu.Unlock()
  86. c.Watcher.Close()
  87. c.Lease.Close()
  88. return c.conn.Close()
  89. }
  90. // Ctx is a context for "out of band" messages (e.g., for sending
  91. // "clean up" message when another context is canceled). It is
  92. // canceled on client Close().
  93. func (c *Client) Ctx() context.Context { return c.ctx }
  94. // Endpoints lists the registered endpoints for the client.
  95. func (c *Client) Endpoints() []string { return c.cfg.Endpoints }
  96. // Errors returns all errors that have been observed since called last.
  97. func (c *Client) Errors() (errs []error) {
  98. c.mu.Lock()
  99. defer c.mu.Unlock()
  100. errs = c.errors
  101. c.errors = nil
  102. return errs
  103. }
  104. // Dial establishes a connection for a given endpoint using the client's config
  105. func (c *Client) Dial(endpoint string) (*grpc.ClientConn, error) {
  106. opts := []grpc.DialOption{
  107. grpc.WithBlock(),
  108. grpc.WithTimeout(c.cfg.DialTimeout),
  109. }
  110. if c.creds != nil {
  111. opts = append(opts, grpc.WithTransportCredentials(*c.creds))
  112. } else {
  113. opts = append(opts, grpc.WithInsecure())
  114. }
  115. proto := "tcp"
  116. if url, uerr := url.Parse(endpoint); uerr == nil && url.Scheme == "unix" {
  117. proto = "unix"
  118. // strip unix:// prefix so certs work
  119. endpoint = url.Host
  120. }
  121. f := func(a string, t time.Duration) (net.Conn, error) {
  122. select {
  123. case <-c.ctx.Done():
  124. return nil, c.ctx.Err()
  125. default:
  126. }
  127. return net.DialTimeout(proto, a, t)
  128. }
  129. opts = append(opts, grpc.WithDialer(f))
  130. conn, err := grpc.Dial(endpoint, opts...)
  131. if err != nil {
  132. return nil, err
  133. }
  134. return conn, nil
  135. }
  136. func newClient(cfg *Config) (*Client, error) {
  137. if cfg == nil {
  138. cfg = &Config{RetryDialer: dialEndpointList}
  139. }
  140. var creds *credentials.TransportAuthenticator
  141. if cfg.TLS != nil {
  142. c := credentials.NewTLS(cfg.TLS)
  143. creds = &c
  144. }
  145. // use a temporary skeleton client to bootstrap first connection
  146. ctx, cancel := context.WithCancel(context.TODO())
  147. conn, err := cfg.RetryDialer(&Client{cfg: *cfg, creds: creds, ctx: ctx})
  148. if err != nil {
  149. return nil, err
  150. }
  151. client := &Client{
  152. conn: conn,
  153. cfg: *cfg,
  154. creds: creds,
  155. ctx: ctx,
  156. cancel: cancel,
  157. }
  158. client.Cluster = NewCluster(client)
  159. client.KV = NewKV(client)
  160. client.Lease = NewLease(client)
  161. client.Watcher = NewWatcher(client)
  162. client.Auth = NewAuth(client)
  163. client.Maintenance = NewMaintenance(client)
  164. if cfg.Logger != nil {
  165. logger.Set(cfg.Logger)
  166. } else {
  167. // disable client side grpc by default
  168. logger.Set(log.New(ioutil.Discard, "", 0))
  169. }
  170. return client, nil
  171. }
  172. // ActiveConnection returns the current in-use connection
  173. func (c *Client) ActiveConnection() *grpc.ClientConn {
  174. c.mu.RLock()
  175. defer c.mu.RUnlock()
  176. return c.conn
  177. }
  178. // retryConnection establishes a new connection
  179. func (c *Client) retryConnection(oldConn *grpc.ClientConn, err error) (*grpc.ClientConn, error) {
  180. c.mu.Lock()
  181. defer c.mu.Unlock()
  182. if err != nil {
  183. c.errors = append(c.errors, err)
  184. }
  185. if c.cancel == nil {
  186. return nil, c.ctx.Err()
  187. }
  188. if oldConn != c.conn {
  189. // conn has already been updated
  190. return c.conn, nil
  191. }
  192. oldConn.Close()
  193. if st, _ := oldConn.State(); st != grpc.Shutdown {
  194. // wait for shutdown so grpc doesn't leak sleeping goroutines
  195. oldConn.WaitForStateChange(c.ctx, st)
  196. }
  197. conn, dialErr := c.cfg.RetryDialer(c)
  198. if dialErr != nil {
  199. c.errors = append(c.errors, dialErr)
  200. return nil, dialErr
  201. }
  202. c.conn = conn
  203. return c.conn, nil
  204. }
  205. // dialEndpointList attempts to connect to each endpoint in order until a
  206. // connection is established.
  207. func dialEndpointList(c *Client) (*grpc.ClientConn, error) {
  208. var err error
  209. for _, ep := range c.Endpoints() {
  210. conn, curErr := c.Dial(ep)
  211. if curErr != nil {
  212. err = curErr
  213. } else {
  214. return conn, nil
  215. }
  216. }
  217. return nil, err
  218. }
  219. // isHalted returns true if the given error and context indicate no forward
  220. // progress can be made, even after reconnecting.
  221. func isHalted(ctx context.Context, err error) bool {
  222. isRPCError := strings.HasPrefix(grpc.ErrorDesc(err), "etcdserver: ")
  223. return isRPCError || ctx.Err() != nil
  224. }