client.go 6.2 KB

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