client.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. }
  47. // New creates a new etcdv3 client from a given configuration.
  48. func New(cfg Config) (*Client, error) {
  49. if cfg.RetryDialer == nil {
  50. cfg.RetryDialer = dialEndpointList
  51. }
  52. if len(cfg.Endpoints) == 0 {
  53. return nil, ErrNoAvailableEndpoints
  54. }
  55. return newClient(&cfg)
  56. }
  57. // NewFromURL creates a new etcdv3 client from a URL.
  58. func NewFromURL(url string) (*Client, error) {
  59. return New(Config{Endpoints: []string{url}})
  60. }
  61. // NewFromConfigFile creates a new etcdv3 client from a configuration file.
  62. func NewFromConfigFile(path string) (*Client, error) {
  63. cfg, err := configFromFile(path)
  64. if err != nil {
  65. return nil, err
  66. }
  67. return New(*cfg)
  68. }
  69. // Close shuts down the client's etcd connections.
  70. func (c *Client) Close() error {
  71. c.mu.Lock()
  72. if c.cancel == nil {
  73. c.mu.Unlock()
  74. return nil
  75. }
  76. c.cancel()
  77. c.cancel = nil
  78. c.mu.Unlock()
  79. c.Watcher.Close()
  80. c.Lease.Close()
  81. return c.conn.Close()
  82. }
  83. // Ctx is a context for "out of band" messages (e.g., for sending
  84. // "clean up" message when another context is canceled). It is
  85. // canceled on client Close().
  86. func (c *Client) Ctx() context.Context { return c.ctx }
  87. // Endpoints lists the registered endpoints for the client.
  88. func (c *Client) Endpoints() []string { return c.cfg.Endpoints }
  89. // Errors returns all errors that have been observed since called last.
  90. func (c *Client) Errors() (errs []error) {
  91. c.mu.Lock()
  92. defer c.mu.Unlock()
  93. errs = c.errors
  94. c.errors = nil
  95. return errs
  96. }
  97. // Dial establishes a connection for a given endpoint using the client's config
  98. func (c *Client) Dial(endpoint string) (*grpc.ClientConn, error) {
  99. opts := []grpc.DialOption{
  100. grpc.WithBlock(),
  101. grpc.WithTimeout(c.cfg.DialTimeout),
  102. }
  103. if c.creds != nil {
  104. opts = append(opts, grpc.WithTransportCredentials(*c.creds))
  105. } else {
  106. opts = append(opts, grpc.WithInsecure())
  107. }
  108. proto := "tcp"
  109. if url, uerr := url.Parse(endpoint); uerr == nil && url.Scheme == "unix" {
  110. proto = "unix"
  111. // strip unix:// prefix so certs work
  112. endpoint = url.Host
  113. }
  114. f := func(a string, t time.Duration) (net.Conn, error) {
  115. select {
  116. case <-c.ctx.Done():
  117. return nil, c.ctx.Err()
  118. default:
  119. }
  120. return net.DialTimeout(proto, a, t)
  121. }
  122. opts = append(opts, grpc.WithDialer(f))
  123. conn, err := grpc.Dial(endpoint, opts...)
  124. if err != nil {
  125. return nil, err
  126. }
  127. return conn, nil
  128. }
  129. func newClient(cfg *Config) (*Client, error) {
  130. if cfg == nil {
  131. cfg = &Config{RetryDialer: dialEndpointList}
  132. }
  133. var creds *credentials.TransportAuthenticator
  134. if cfg.TLS != nil {
  135. c := credentials.NewTLS(cfg.TLS)
  136. creds = &c
  137. }
  138. // use a temporary skeleton client to bootstrap first connection
  139. ctx, cancel := context.WithCancel(context.TODO())
  140. conn, err := cfg.RetryDialer(&Client{cfg: *cfg, creds: creds, ctx: ctx})
  141. if err != nil {
  142. return nil, err
  143. }
  144. client := &Client{
  145. conn: conn,
  146. cfg: *cfg,
  147. creds: creds,
  148. ctx: ctx,
  149. cancel: cancel,
  150. }
  151. client.Cluster = NewCluster(client)
  152. client.KV = NewKV(client)
  153. client.Lease = NewLease(client)
  154. client.Watcher = NewWatcher(client)
  155. client.Auth = NewAuth(client)
  156. client.Maintenance = NewMaintenance(client)
  157. if cfg.Logger != nil {
  158. logger.Set(cfg.Logger)
  159. } else {
  160. // disable client side grpc by default
  161. logger.Set(log.New(ioutil.Discard, "", 0))
  162. }
  163. return client, nil
  164. }
  165. // ActiveConnection returns the current in-use connection
  166. func (c *Client) ActiveConnection() *grpc.ClientConn {
  167. c.mu.RLock()
  168. defer c.mu.RUnlock()
  169. return c.conn
  170. }
  171. // retryConnection establishes a new connection
  172. func (c *Client) retryConnection(oldConn *grpc.ClientConn, err error) (*grpc.ClientConn, error) {
  173. c.mu.Lock()
  174. defer c.mu.Unlock()
  175. if err != nil {
  176. c.errors = append(c.errors, err)
  177. }
  178. if c.cancel == nil {
  179. return nil, c.ctx.Err()
  180. }
  181. if oldConn != c.conn {
  182. // conn has already been updated
  183. return c.conn, nil
  184. }
  185. oldConn.Close()
  186. if st, _ := oldConn.State(); st != grpc.Shutdown {
  187. // wait for shutdown so grpc doesn't leak sleeping goroutines
  188. oldConn.WaitForStateChange(c.ctx, st)
  189. }
  190. conn, dialErr := c.cfg.RetryDialer(c)
  191. if dialErr != nil {
  192. c.errors = append(c.errors, dialErr)
  193. return nil, dialErr
  194. }
  195. c.conn = conn
  196. return c.conn, nil
  197. }
  198. // dialEndpointList attempts to connect to each endpoint in order until a
  199. // connection is established.
  200. func dialEndpointList(c *Client) (*grpc.ClientConn, error) {
  201. var err error
  202. for _, ep := range c.Endpoints() {
  203. conn, curErr := c.Dial(ep)
  204. if curErr != nil {
  205. err = curErr
  206. } else {
  207. return conn, nil
  208. }
  209. }
  210. return nil, err
  211. }
  212. // isHalted returns true if the given error and context indicate no forward
  213. // progress can be made, even after reconnecting.
  214. func isHalted(ctx context.Context, err error) bool {
  215. isRPCError := strings.HasPrefix(grpc.ErrorDesc(err), "etcdserver: ")
  216. return isRPCError || ctx.Err() != nil
  217. }