client.go 6.1 KB

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