client.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  21. )
  22. // Client provides and manages an etcd v3 client session.
  23. type Client struct {
  24. // KV is the keyvalue API for the client's connection.
  25. KV pb.KVClient
  26. // Lease is the lease API for the client's connection.
  27. Lease pb.LeaseClient
  28. // Watch is the watch API for the client's connection.
  29. Watch pb.WatchClient
  30. // Cluster is the cluster API for the client's connection.
  31. Cluster pb.ClusterClient
  32. conn *grpc.ClientConn
  33. cfg Config
  34. mu sync.RWMutex // protects connection selection and error list
  35. errors []error // errors passed to retryConnection
  36. }
  37. // EndpointDialer is a policy for choosing which endpoint to dial next
  38. type EndpointDialer func(*Client) (*grpc.ClientConn, error)
  39. type Config struct {
  40. // Endpoints is a list of URLs
  41. Endpoints []string
  42. // RetryDialer chooses the next endpoint to use
  43. RetryDialer EndpointDialer
  44. // DialTimeout is the timeout for failing to establish a connection.
  45. DialTimeout time.Duration
  46. // TODO TLS options
  47. }
  48. // New creates a new etcdv3 client from a given configuration.
  49. func New(cfg Config) (*Client, error) {
  50. if cfg.RetryDialer == nil {
  51. cfg.RetryDialer = dialEndpointList
  52. }
  53. // use a temporary skeleton client to bootstrap first connection
  54. conn, err := cfg.RetryDialer(&Client{cfg: cfg})
  55. if err != nil {
  56. return nil, err
  57. }
  58. return newClient(conn, &cfg), nil
  59. }
  60. // NewFromURL creates a new etcdv3 client from a URL.
  61. func NewFromURL(url string) (*Client, error) {
  62. return New(Config{Endpoints: []string{url}})
  63. }
  64. // NewFromConn creates a new etcdv3 client from an established grpc Connection.
  65. func NewFromConn(conn *grpc.ClientConn) *Client { return newClient(conn, nil) }
  66. // Clone creates a copy of client with the old connection and new API clients.
  67. func (c *Client) Clone() *Client { return newClient(c.conn, &c.cfg) }
  68. // Close shuts down the client's etcd connections.
  69. func (c *Client) Close() error {
  70. return c.conn.Close()
  71. }
  72. // Endpoints lists the registered endpoints for the client.
  73. func (c *Client) Endpoints() []string { return c.cfg.Endpoints }
  74. // Errors returns all errors that have been observed since called last.
  75. func (c *Client) Errors() (errs []error) {
  76. c.mu.Lock()
  77. defer c.mu.Unlock()
  78. errs = c.errors
  79. c.errors = nil
  80. return errs
  81. }
  82. // Dial establishes a connection for a given endpoint using the client's config
  83. func (c *Client) Dial(endpoint string) (*grpc.ClientConn, error) {
  84. // TODO: enable grpc.WithTransportCredentials(creds)
  85. conn, err := grpc.Dial(
  86. endpoint,
  87. grpc.WithBlock(),
  88. grpc.WithTimeout(c.cfg.DialTimeout),
  89. grpc.WithInsecure())
  90. if err != nil {
  91. return nil, err
  92. }
  93. return conn, nil
  94. }
  95. func newClient(conn *grpc.ClientConn, cfg *Config) *Client {
  96. if cfg == nil {
  97. cfg = &Config{RetryDialer: dialEndpointList}
  98. }
  99. return &Client{
  100. KV: pb.NewKVClient(conn),
  101. Lease: pb.NewLeaseClient(conn),
  102. Watch: pb.NewWatchClient(conn),
  103. Cluster: pb.NewClusterClient(conn),
  104. conn: conn,
  105. cfg: *cfg,
  106. }
  107. }
  108. // activeConnection returns the current in-use connection
  109. func (c *Client) activeConnection() *grpc.ClientConn {
  110. c.mu.RLock()
  111. defer c.mu.RUnlock()
  112. return c.conn
  113. }
  114. // refreshConnection establishes a new connection
  115. func (c *Client) retryConnection(oldConn *grpc.ClientConn, err error) (*grpc.ClientConn, error) {
  116. c.mu.Lock()
  117. defer c.mu.Unlock()
  118. if err != nil {
  119. c.errors = append(c.errors, err)
  120. }
  121. if oldConn != c.conn {
  122. // conn has already been updated
  123. return c.conn, nil
  124. }
  125. conn, dialErr := c.cfg.RetryDialer(c)
  126. if dialErr != nil {
  127. c.errors = append(c.errors, dialErr)
  128. return nil, dialErr
  129. }
  130. c.conn = conn
  131. return c.conn, nil
  132. }
  133. // dialEndpoints attempts to connect to each endpoint in order until a
  134. // connection is established.
  135. func dialEndpointList(c *Client) (*grpc.ClientConn, error) {
  136. var err error
  137. for _, ep := range c.Endpoints() {
  138. conn, curErr := c.Dial(ep)
  139. if curErr != nil {
  140. err = curErr
  141. } else {
  142. return conn, nil
  143. }
  144. }
  145. return nil, err
  146. }
  147. func isRPCError(err error) bool {
  148. return grpc.Code(err) != codes.Unknown
  149. }