client.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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/google.golang.org/grpc"
  23. "github.com/coreos/etcd/Godeps/_workspace/src/google.golang.org/grpc/credentials"
  24. "github.com/coreos/etcd/pkg/transport"
  25. )
  26. var (
  27. ErrNoAvailableEndpoints = errors.New("etcdclient: no available endpoints")
  28. )
  29. // Client provides and manages an etcd v3 client session.
  30. type Client struct {
  31. Cluster
  32. KV
  33. Lease
  34. Watcher
  35. conn *grpc.ClientConn
  36. cfg Config
  37. creds *credentials.TransportAuthenticator
  38. mu sync.RWMutex // protects connection selection and error list
  39. errors []error // errors passed to retryConnection
  40. }
  41. // EndpointDialer is a policy for choosing which endpoint to dial next
  42. type EndpointDialer func(*Client) (*grpc.ClientConn, error)
  43. type Config struct {
  44. // Endpoints is a list of URLs
  45. Endpoints []string
  46. // RetryDialer chooses the next endpoint to use
  47. RetryDialer EndpointDialer
  48. // DialTimeout is the timeout for failing to establish a connection.
  49. DialTimeout time.Duration
  50. // TLS holds the client secure credentials, if any.
  51. TLS *transport.TLSInfo
  52. }
  53. // New creates a new etcdv3 client from a given configuration.
  54. func New(cfg Config) (*Client, error) {
  55. if cfg.RetryDialer == nil {
  56. cfg.RetryDialer = dialEndpointList
  57. }
  58. if len(cfg.Endpoints) == 0 {
  59. return nil, ErrNoAvailableEndpoints
  60. }
  61. return newClient(&cfg)
  62. }
  63. // NewFromURL creates a new etcdv3 client from a URL.
  64. func NewFromURL(url string) (*Client, error) {
  65. return New(Config{Endpoints: []string{url}})
  66. }
  67. // Close shuts down the client's etcd connections.
  68. func (c *Client) Close() error {
  69. c.Watcher.Close()
  70. c.Lease.Close()
  71. return c.conn.Close()
  72. }
  73. // Endpoints lists the registered endpoints for the client.
  74. func (c *Client) Endpoints() []string { return c.cfg.Endpoints }
  75. // Errors returns all errors that have been observed since called last.
  76. func (c *Client) Errors() (errs []error) {
  77. c.mu.Lock()
  78. defer c.mu.Unlock()
  79. errs = c.errors
  80. c.errors = nil
  81. return errs
  82. }
  83. // Dial establishes a connection for a given endpoint using the client's config
  84. func (c *Client) Dial(endpoint string) (*grpc.ClientConn, error) {
  85. opts := []grpc.DialOption{
  86. grpc.WithBlock(),
  87. grpc.WithTimeout(c.cfg.DialTimeout),
  88. }
  89. if c.creds != nil {
  90. opts = append(opts, grpc.WithTransportCredentials(*c.creds))
  91. } else {
  92. opts = append(opts, grpc.WithInsecure())
  93. }
  94. if url, uerr := url.Parse(endpoint); uerr == nil && url.Scheme == "unix" {
  95. f := func(a string, t time.Duration) (net.Conn, error) {
  96. return net.DialTimeout("unix", a, t)
  97. }
  98. // strip unix:// prefix so certs work
  99. endpoint = url.Host
  100. opts = append(opts, grpc.WithDialer(f))
  101. }
  102. conn, err := grpc.Dial(endpoint, opts...)
  103. if err != nil {
  104. return nil, err
  105. }
  106. return conn, nil
  107. }
  108. func newClient(cfg *Config) (*Client, error) {
  109. if cfg == nil {
  110. cfg = &Config{RetryDialer: dialEndpointList}
  111. }
  112. var creds *credentials.TransportAuthenticator
  113. if cfg.TLS != nil {
  114. tlscfg, err := cfg.TLS.ClientConfig()
  115. if err != nil {
  116. return nil, err
  117. }
  118. c := credentials.NewTLS(tlscfg)
  119. creds = &c
  120. }
  121. // use a temporary skeleton client to bootstrap first connection
  122. conn, err := cfg.RetryDialer(&Client{cfg: *cfg, creds: creds})
  123. if err != nil {
  124. return nil, err
  125. }
  126. client := &Client{
  127. conn: conn,
  128. cfg: *cfg,
  129. creds: creds,
  130. }
  131. client.Cluster = NewCluster(client)
  132. client.KV = NewKV(client)
  133. client.Lease = NewLease(client)
  134. client.Watcher = NewWatcher(client)
  135. return client, nil
  136. }
  137. // ActiveConnection returns the current in-use connection
  138. func (c *Client) ActiveConnection() *grpc.ClientConn {
  139. c.mu.RLock()
  140. defer c.mu.RUnlock()
  141. return c.conn
  142. }
  143. // retryConnection establishes a new connection
  144. func (c *Client) retryConnection(oldConn *grpc.ClientConn, err error) (*grpc.ClientConn, error) {
  145. c.mu.Lock()
  146. defer c.mu.Unlock()
  147. if err != nil {
  148. c.errors = append(c.errors, err)
  149. }
  150. if oldConn != c.conn {
  151. // conn has already been updated
  152. return c.conn, nil
  153. }
  154. conn, dialErr := c.cfg.RetryDialer(c)
  155. if dialErr != nil {
  156. c.errors = append(c.errors, dialErr)
  157. return nil, dialErr
  158. }
  159. c.conn = conn
  160. return c.conn, nil
  161. }
  162. // dialEndpointList attempts to connect to each endpoint in order until a
  163. // connection is established.
  164. func dialEndpointList(c *Client) (*grpc.ClientConn, error) {
  165. var err error
  166. for _, ep := range c.Endpoints() {
  167. conn, curErr := c.Dial(ep)
  168. if curErr != nil {
  169. err = curErr
  170. } else {
  171. return conn, nil
  172. }
  173. }
  174. return nil, err
  175. }
  176. func isRPCError(err error) bool {
  177. return strings.HasPrefix(grpc.ErrorDesc(err), "etcdserver: ")
  178. }