client.go 5.1 KB

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