client.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. 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 *tls.Config
  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. c := credentials.NewTLS(cfg.TLS)
  138. creds = &c
  139. }
  140. // use a temporary skeleton client to bootstrap first connection
  141. ctx, cancel := context.WithCancel(context.TODO())
  142. conn, err := cfg.RetryDialer(&Client{cfg: *cfg, creds: creds, ctx: ctx})
  143. if err != nil {
  144. return nil, err
  145. }
  146. client := &Client{
  147. conn: conn,
  148. cfg: *cfg,
  149. creds: creds,
  150. ctx: ctx,
  151. cancel: cancel,
  152. }
  153. client.Cluster = NewCluster(client)
  154. client.KV = NewKV(client)
  155. client.Lease = NewLease(client)
  156. client.Watcher = NewWatcher(client)
  157. client.Auth = NewAuth(client)
  158. return client, nil
  159. }
  160. // ActiveConnection returns the current in-use connection
  161. func (c *Client) ActiveConnection() *grpc.ClientConn {
  162. c.mu.RLock()
  163. defer c.mu.RUnlock()
  164. return c.conn
  165. }
  166. // retryConnection establishes a new connection
  167. func (c *Client) retryConnection(oldConn *grpc.ClientConn, err error) (*grpc.ClientConn, error) {
  168. c.mu.Lock()
  169. defer c.mu.Unlock()
  170. if err != nil {
  171. c.errors = append(c.errors, err)
  172. }
  173. if c.cancel == nil {
  174. return nil, c.ctx.Err()
  175. }
  176. if oldConn != c.conn {
  177. // conn has already been updated
  178. return c.conn, nil
  179. }
  180. oldConn.Close()
  181. if st, _ := oldConn.State(); st != grpc.Shutdown {
  182. // wait for shutdown so grpc doesn't leak sleeping goroutines
  183. oldConn.WaitForStateChange(c.ctx, st)
  184. }
  185. conn, dialErr := c.cfg.RetryDialer(c)
  186. if dialErr != nil {
  187. c.errors = append(c.errors, dialErr)
  188. return nil, dialErr
  189. }
  190. c.conn = conn
  191. return c.conn, nil
  192. }
  193. // dialEndpointList attempts to connect to each endpoint in order until a
  194. // connection is established.
  195. func dialEndpointList(c *Client) (*grpc.ClientConn, error) {
  196. var err error
  197. for _, ep := range c.Endpoints() {
  198. conn, curErr := c.Dial(ep)
  199. if curErr != nil {
  200. err = curErr
  201. } else {
  202. return conn, nil
  203. }
  204. }
  205. return nil, err
  206. }
  207. // isHalted returns true if the given error and context indicate no forward
  208. // progress can be made, even after reconnecting.
  209. func isHalted(ctx context.Context, err error) bool {
  210. isRPCError := strings.HasPrefix(grpc.ErrorDesc(err), "etcdserver: ")
  211. return isRPCError || ctx.Err() != nil
  212. }