client.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  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. // KV is the keyvalue API for the client's connection.
  33. KV pb.KVClient
  34. // Lease is the lease API for the client's connection.
  35. Lease pb.LeaseClient
  36. // Watch is the watch API for the client's connection.
  37. Watch pb.WatchClient
  38. // Cluster is the cluster API for the client's connection.
  39. Cluster pb.ClusterClient
  40. conn *grpc.ClientConn
  41. cfg Config
  42. creds *credentials.TransportAuthenticator
  43. mu sync.RWMutex // protects connection selection and error list
  44. errors []error // errors passed to retryConnection
  45. }
  46. // EndpointDialer is a policy for choosing which endpoint to dial next
  47. type EndpointDialer func(*Client) (*grpc.ClientConn, error)
  48. type Config struct {
  49. // Endpoints is a list of URLs
  50. Endpoints []string
  51. // RetryDialer chooses the next endpoint to use
  52. RetryDialer EndpointDialer
  53. // DialTimeout is the timeout for failing to establish a connection.
  54. DialTimeout time.Duration
  55. // TLS holds the client secure credentials, if any.
  56. TLS *transport.TLSInfo
  57. }
  58. // New creates a new etcdv3 client from a given configuration.
  59. func New(cfg Config) (*Client, error) {
  60. if cfg.RetryDialer == nil {
  61. cfg.RetryDialer = dialEndpointList
  62. }
  63. if len(cfg.Endpoints) == 0 {
  64. return nil, ErrNoAvailableEndpoints
  65. }
  66. return newClient(&cfg)
  67. }
  68. // NewFromURL creates a new etcdv3 client from a URL.
  69. func NewFromURL(url string) (*Client, error) {
  70. return New(Config{Endpoints: []string{url}})
  71. }
  72. // Close shuts down the client's etcd connections.
  73. func (c *Client) Close() error {
  74. return c.conn.Close()
  75. }
  76. // Endpoints lists the registered endpoints for the client.
  77. func (c *Client) Endpoints() []string { return c.cfg.Endpoints }
  78. // Errors returns all errors that have been observed since called last.
  79. func (c *Client) Errors() (errs []error) {
  80. c.mu.Lock()
  81. defer c.mu.Unlock()
  82. errs = c.errors
  83. c.errors = nil
  84. return errs
  85. }
  86. // Dial establishes a connection for a given endpoint using the client's config
  87. func (c *Client) Dial(endpoint string) (*grpc.ClientConn, error) {
  88. opts := []grpc.DialOption{
  89. grpc.WithBlock(),
  90. grpc.WithTimeout(c.cfg.DialTimeout),
  91. }
  92. if c.creds != nil {
  93. opts = append(opts, grpc.WithTransportCredentials(*c.creds))
  94. } else {
  95. opts = append(opts, grpc.WithInsecure())
  96. }
  97. if url, uerr := url.Parse(endpoint); uerr == nil && url.Scheme == "unix" {
  98. f := func(a string, t time.Duration) (net.Conn, error) {
  99. return net.DialTimeout("unix", a, t)
  100. }
  101. // strip unix:// prefix so certs work
  102. endpoint = url.Host
  103. opts = append(opts, grpc.WithDialer(f))
  104. }
  105. conn, err := grpc.Dial(endpoint, opts...)
  106. if err != nil {
  107. return nil, err
  108. }
  109. return conn, nil
  110. }
  111. func newClient(cfg *Config) (*Client, error) {
  112. if cfg == nil {
  113. cfg = &Config{RetryDialer: dialEndpointList}
  114. }
  115. var creds *credentials.TransportAuthenticator
  116. if cfg.TLS != nil {
  117. tlscfg, err := cfg.TLS.ClientConfig()
  118. if err != nil {
  119. return nil, err
  120. }
  121. c := credentials.NewTLS(tlscfg)
  122. creds = &c
  123. }
  124. // use a temporary skeleton client to bootstrap first connection
  125. conn, err := cfg.RetryDialer(&Client{cfg: *cfg, creds: creds})
  126. if err != nil {
  127. return nil, err
  128. }
  129. return &Client{
  130. KV: pb.NewKVClient(conn),
  131. Lease: pb.NewLeaseClient(conn),
  132. Watch: pb.NewWatchClient(conn),
  133. Cluster: pb.NewClusterClient(conn),
  134. conn: conn,
  135. cfg: *cfg,
  136. creds: creds,
  137. }, 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. }