client.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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. "sync"
  17. "time"
  18. "github.com/coreos/etcd/Godeps/_workspace/src/google.golang.org/grpc"
  19. "github.com/coreos/etcd/Godeps/_workspace/src/google.golang.org/grpc/codes"
  20. "github.com/coreos/etcd/Godeps/_workspace/src/google.golang.org/grpc/credentials"
  21. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  22. "github.com/coreos/etcd/pkg/transport"
  23. )
  24. // Client provides and manages an etcd v3 client session.
  25. type Client struct {
  26. // KV is the keyvalue API for the client's connection.
  27. KV pb.KVClient
  28. // Lease is the lease API for the client's connection.
  29. Lease pb.LeaseClient
  30. // Watch is the watch API for the client's connection.
  31. Watch pb.WatchClient
  32. // Cluster is the cluster API for the client's connection.
  33. Cluster pb.ClusterClient
  34. conn *grpc.ClientConn
  35. cfg Config
  36. creds *credentials.TransportAuthenticator
  37. mu sync.RWMutex // protects connection selection and error list
  38. errors []error // errors passed to retryConnection
  39. }
  40. // EndpointDialer is a policy for choosing which endpoint to dial next
  41. type EndpointDialer func(*Client) (*grpc.ClientConn, error)
  42. type Config struct {
  43. // Endpoints is a list of URLs
  44. Endpoints []string
  45. // RetryDialer chooses the next endpoint to use
  46. RetryDialer EndpointDialer
  47. // DialTimeout is the timeout for failing to establish a connection.
  48. DialTimeout time.Duration
  49. // TLS holds the client secure credentials, if any.
  50. TLS *transport.TLSInfo
  51. }
  52. // New creates a new etcdv3 client from a given configuration.
  53. func New(cfg Config) (*Client, error) {
  54. if cfg.RetryDialer == nil {
  55. cfg.RetryDialer = dialEndpointList
  56. }
  57. // use a temporary skeleton client to bootstrap first connection
  58. conn, err := cfg.RetryDialer(&Client{cfg: cfg})
  59. if err != nil {
  60. return nil, err
  61. }
  62. return newClient(conn, &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. // NewFromConn creates a new etcdv3 client from an established grpc Connection.
  69. func NewFromConn(conn *grpc.ClientConn) *Client { return mustNewClient(conn, nil) }
  70. // Clone creates a copy of client with the old connection and new API clients.
  71. func (c *Client) Clone() *Client { return mustNewClient(c.conn, &c.cfg) }
  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. conn, err := grpc.Dial(endpoint, opts...)
  98. if err != nil {
  99. return nil, err
  100. }
  101. return conn, nil
  102. }
  103. func mustNewClient(conn *grpc.ClientConn, cfg *Config) *Client {
  104. c, err := newClient(conn, cfg)
  105. if err != nil {
  106. panic("expected no error")
  107. }
  108. return c
  109. }
  110. func newClient(conn *grpc.ClientConn, cfg *Config) (*Client, error) {
  111. if cfg == nil {
  112. cfg = &Config{RetryDialer: dialEndpointList}
  113. }
  114. var creds *credentials.TransportAuthenticator
  115. if cfg.TLS != nil {
  116. tlscfg, err := cfg.TLS.ClientConfig()
  117. if err != nil {
  118. return nil, err
  119. }
  120. c := credentials.NewTLS(tlscfg)
  121. creds = &c
  122. }
  123. return &Client{
  124. KV: pb.NewKVClient(conn),
  125. Lease: pb.NewLeaseClient(conn),
  126. Watch: pb.NewWatchClient(conn),
  127. Cluster: pb.NewClusterClient(conn),
  128. conn: conn,
  129. cfg: *cfg,
  130. creds: creds,
  131. }, nil
  132. }
  133. // activeConnection returns the current in-use connection
  134. func (c *Client) ActiveConnection() *grpc.ClientConn {
  135. c.mu.RLock()
  136. defer c.mu.RUnlock()
  137. return c.conn
  138. }
  139. // refreshConnection establishes a new connection
  140. func (c *Client) retryConnection(oldConn *grpc.ClientConn, err error) (*grpc.ClientConn, error) {
  141. c.mu.Lock()
  142. defer c.mu.Unlock()
  143. if err != nil {
  144. c.errors = append(c.errors, err)
  145. }
  146. if oldConn != c.conn {
  147. // conn has already been updated
  148. return c.conn, nil
  149. }
  150. conn, dialErr := c.cfg.RetryDialer(c)
  151. if dialErr != nil {
  152. c.errors = append(c.errors, dialErr)
  153. return nil, dialErr
  154. }
  155. c.conn = conn
  156. return c.conn, nil
  157. }
  158. // dialEndpoints attempts to connect to each endpoint in order until a
  159. // connection is established.
  160. func dialEndpointList(c *Client) (*grpc.ClientConn, error) {
  161. var err error
  162. for _, ep := range c.Endpoints() {
  163. conn, curErr := c.Dial(ep)
  164. if curErr != nil {
  165. err = curErr
  166. } else {
  167. return conn, nil
  168. }
  169. }
  170. return nil, err
  171. }
  172. func isRPCError(err error) bool {
  173. return grpc.Code(err) != codes.Unknown
  174. }