client.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. defer c.mu.Unlock()
  75. if c.cancel == nil {
  76. return nil
  77. }
  78. c.cancel()
  79. c.cancel = nil
  80. c.Watcher.Close()
  81. c.Lease.Close()
  82. return c.conn.Close()
  83. }
  84. // Ctx is a context for "out of band" messages (e.g., for sending
  85. // "clean up" message when another context is canceled). It is
  86. // canceled on client Close().
  87. func (c *Client) Ctx() context.Context { return c.ctx }
  88. // Endpoints lists the registered endpoints for the client.
  89. func (c *Client) Endpoints() []string { return c.cfg.Endpoints }
  90. // Errors returns all errors that have been observed since called last.
  91. func (c *Client) Errors() (errs []error) {
  92. c.mu.Lock()
  93. defer c.mu.Unlock()
  94. errs = c.errors
  95. c.errors = nil
  96. return errs
  97. }
  98. // Dial establishes a connection for a given endpoint using the client's config
  99. func (c *Client) Dial(endpoint string) (*grpc.ClientConn, error) {
  100. opts := []grpc.DialOption{
  101. grpc.WithBlock(),
  102. grpc.WithTimeout(c.cfg.DialTimeout),
  103. }
  104. if c.creds != nil {
  105. opts = append(opts, grpc.WithTransportCredentials(*c.creds))
  106. } else {
  107. opts = append(opts, grpc.WithInsecure())
  108. }
  109. if url, uerr := url.Parse(endpoint); uerr == nil && url.Scheme == "unix" {
  110. f := func(a string, t time.Duration) (net.Conn, error) {
  111. return net.DialTimeout("unix", a, t)
  112. }
  113. // strip unix:// prefix so certs work
  114. endpoint = url.Host
  115. opts = append(opts, grpc.WithDialer(f))
  116. }
  117. conn, err := grpc.Dial(endpoint, opts...)
  118. if err != nil {
  119. return nil, err
  120. }
  121. return conn, nil
  122. }
  123. func newClient(cfg *Config) (*Client, error) {
  124. if cfg == nil {
  125. cfg = &Config{RetryDialer: dialEndpointList}
  126. }
  127. var creds *credentials.TransportAuthenticator
  128. if cfg.TLS != nil {
  129. tlscfg, err := cfg.TLS.ClientConfig()
  130. if err != nil {
  131. return nil, err
  132. }
  133. c := credentials.NewTLS(tlscfg)
  134. creds = &c
  135. }
  136. // use a temporary skeleton client to bootstrap first connection
  137. conn, err := cfg.RetryDialer(&Client{cfg: *cfg, creds: creds})
  138. if err != nil {
  139. return nil, err
  140. }
  141. ctx, cancel := context.WithCancel(context.TODO())
  142. client := &Client{
  143. conn: conn,
  144. cfg: *cfg,
  145. creds: creds,
  146. ctx: ctx,
  147. cancel: cancel,
  148. }
  149. client.Cluster = NewCluster(client)
  150. client.KV = NewKV(client)
  151. client.Lease = NewLease(client)
  152. client.Watcher = NewWatcher(client)
  153. client.Auth = NewAuth(client)
  154. return client, nil
  155. }
  156. // ActiveConnection returns the current in-use connection
  157. func (c *Client) ActiveConnection() *grpc.ClientConn {
  158. c.mu.RLock()
  159. defer c.mu.RUnlock()
  160. return c.conn
  161. }
  162. // retryConnection establishes a new connection
  163. func (c *Client) retryConnection(oldConn *grpc.ClientConn, err error) (*grpc.ClientConn, error) {
  164. c.mu.Lock()
  165. defer c.mu.Unlock()
  166. if err != nil {
  167. c.errors = append(c.errors, err)
  168. }
  169. if c.cancel == nil {
  170. return nil, c.ctx.Err()
  171. }
  172. if oldConn != c.conn {
  173. // conn has already been updated
  174. return c.conn, nil
  175. }
  176. conn, dialErr := c.cfg.RetryDialer(c)
  177. if dialErr != nil {
  178. c.errors = append(c.errors, dialErr)
  179. return nil, dialErr
  180. }
  181. c.conn = conn
  182. return c.conn, nil
  183. }
  184. // dialEndpointList attempts to connect to each endpoint in order until a
  185. // connection is established.
  186. func dialEndpointList(c *Client) (*grpc.ClientConn, error) {
  187. var err error
  188. for _, ep := range c.Endpoints() {
  189. conn, curErr := c.Dial(ep)
  190. if curErr != nil {
  191. err = curErr
  192. } else {
  193. return conn, nil
  194. }
  195. }
  196. return nil, err
  197. }
  198. // isHalted returns true if the given error and context indicate no forward
  199. // progress can be made, even after reconnecting.
  200. func isHalted(ctx context.Context, err error) bool {
  201. isRPCError := strings.HasPrefix(grpc.ErrorDesc(err), "etcdserver: ")
  202. return isRPCError || ctx.Err() != nil
  203. }