client.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. "crypto/tls"
  17. "errors"
  18. "io/ioutil"
  19. "log"
  20. "net"
  21. "net/url"
  22. "strings"
  23. "sync"
  24. "time"
  25. "golang.org/x/net/context"
  26. "google.golang.org/grpc"
  27. "google.golang.org/grpc/credentials"
  28. "google.golang.org/grpc/grpclog"
  29. )
  30. var (
  31. ErrNoAvailableEndpoints = errors.New("etcdclient: no available endpoints")
  32. )
  33. type Logger grpclog.Logger
  34. // Client provides and manages an etcd v3 client session.
  35. type Client struct {
  36. Cluster
  37. KV
  38. Lease
  39. Watcher
  40. Auth
  41. Maintenance
  42. conn *grpc.ClientConn
  43. cfg Config
  44. creds *credentials.TransportAuthenticator
  45. mu sync.RWMutex // protects connection selection and error list
  46. errors []error // errors passed to retryConnection
  47. ctx context.Context
  48. cancel context.CancelFunc
  49. logger Logger
  50. }
  51. // EndpointDialer is a policy for choosing which endpoint to dial next
  52. type EndpointDialer func(*Client) (*grpc.ClientConn, error)
  53. type Config struct {
  54. // Endpoints is a list of URLs
  55. Endpoints []string
  56. // RetryDialer chooses the next endpoint to use
  57. RetryDialer EndpointDialer
  58. // DialTimeout is the timeout for failing to establish a connection.
  59. DialTimeout time.Duration
  60. // TLS holds the client secure credentials, if any.
  61. TLS *tls.Config
  62. // Logger is the logger used by client library.
  63. Logger Logger
  64. }
  65. // New creates a new etcdv3 client from a given configuration.
  66. func New(cfg Config) (*Client, error) {
  67. if cfg.RetryDialer == nil {
  68. cfg.RetryDialer = dialEndpointList
  69. }
  70. if len(cfg.Endpoints) == 0 {
  71. return nil, ErrNoAvailableEndpoints
  72. }
  73. return newClient(&cfg)
  74. }
  75. // NewFromURL creates a new etcdv3 client from a URL.
  76. func NewFromURL(url string) (*Client, error) {
  77. return New(Config{Endpoints: []string{url}})
  78. }
  79. // Close shuts down the client's etcd connections.
  80. func (c *Client) Close() error {
  81. c.mu.Lock()
  82. if c.cancel == nil {
  83. c.mu.Unlock()
  84. return nil
  85. }
  86. c.cancel()
  87. c.cancel = nil
  88. c.mu.Unlock()
  89. c.Watcher.Close()
  90. c.Lease.Close()
  91. return c.conn.Close()
  92. }
  93. // Ctx is a context for "out of band" messages (e.g., for sending
  94. // "clean up" message when another context is canceled). It is
  95. // canceled on client Close().
  96. func (c *Client) Ctx() context.Context { return c.ctx }
  97. // Endpoints lists the registered endpoints for the client.
  98. func (c *Client) Endpoints() []string { return c.cfg.Endpoints }
  99. // Errors returns all errors that have been observed since called last.
  100. func (c *Client) Errors() (errs []error) {
  101. c.mu.Lock()
  102. defer c.mu.Unlock()
  103. errs = c.errors
  104. c.errors = nil
  105. return errs
  106. }
  107. // Dial establishes a connection for a given endpoint using the client's config
  108. func (c *Client) Dial(endpoint string) (*grpc.ClientConn, error) {
  109. opts := []grpc.DialOption{
  110. grpc.WithBlock(),
  111. grpc.WithTimeout(c.cfg.DialTimeout),
  112. }
  113. if c.creds != nil {
  114. opts = append(opts, grpc.WithTransportCredentials(*c.creds))
  115. } else {
  116. opts = append(opts, grpc.WithInsecure())
  117. }
  118. proto := "tcp"
  119. if url, uerr := url.Parse(endpoint); uerr == nil && url.Scheme == "unix" {
  120. proto = "unix"
  121. // strip unix:// prefix so certs work
  122. endpoint = url.Host
  123. }
  124. f := func(a string, t time.Duration) (net.Conn, error) {
  125. select {
  126. case <-c.ctx.Done():
  127. return nil, c.ctx.Err()
  128. default:
  129. }
  130. return net.DialTimeout(proto, a, t)
  131. }
  132. opts = append(opts, grpc.WithDialer(f))
  133. conn, err := grpc.Dial(endpoint, opts...)
  134. if err != nil {
  135. return nil, err
  136. }
  137. return conn, nil
  138. }
  139. func newClient(cfg *Config) (*Client, error) {
  140. if cfg == nil {
  141. cfg = &Config{RetryDialer: dialEndpointList}
  142. }
  143. var creds *credentials.TransportAuthenticator
  144. if cfg.TLS != nil {
  145. c := credentials.NewTLS(cfg.TLS)
  146. creds = &c
  147. }
  148. // use a temporary skeleton client to bootstrap first connection
  149. ctx, cancel := context.WithCancel(context.TODO())
  150. conn, err := cfg.RetryDialer(&Client{cfg: *cfg, creds: creds, ctx: ctx})
  151. if err != nil {
  152. return nil, err
  153. }
  154. client := &Client{
  155. conn: conn,
  156. cfg: *cfg,
  157. creds: creds,
  158. ctx: ctx,
  159. cancel: cancel,
  160. }
  161. client.Cluster = NewCluster(client)
  162. client.KV = NewKV(client)
  163. client.Lease = NewLease(client)
  164. client.Watcher = NewWatcher(client)
  165. client.Auth = NewAuth(client)
  166. client.Maintenance = &maintenance{c: client}
  167. if cfg.Logger == nil {
  168. client.logger = log.New(ioutil.Discard, "", 0)
  169. // disable client side grpc by default
  170. grpclog.SetLogger(log.New(ioutil.Discard, "", 0))
  171. } else {
  172. client.logger = cfg.Logger
  173. grpclog.SetLogger(cfg.Logger)
  174. }
  175. return client, nil
  176. }
  177. // ActiveConnection returns the current in-use connection
  178. func (c *Client) ActiveConnection() *grpc.ClientConn {
  179. c.mu.RLock()
  180. defer c.mu.RUnlock()
  181. return c.conn
  182. }
  183. // retryConnection establishes a new connection
  184. func (c *Client) retryConnection(oldConn *grpc.ClientConn, err error) (*grpc.ClientConn, error) {
  185. c.mu.Lock()
  186. defer c.mu.Unlock()
  187. if err != nil {
  188. c.errors = append(c.errors, err)
  189. }
  190. if c.cancel == nil {
  191. return nil, c.ctx.Err()
  192. }
  193. if oldConn != c.conn {
  194. // conn has already been updated
  195. return c.conn, nil
  196. }
  197. oldConn.Close()
  198. if st, _ := oldConn.State(); st != grpc.Shutdown {
  199. // wait for shutdown so grpc doesn't leak sleeping goroutines
  200. oldConn.WaitForStateChange(c.ctx, st)
  201. }
  202. conn, dialErr := c.cfg.RetryDialer(c)
  203. if dialErr != nil {
  204. c.errors = append(c.errors, dialErr)
  205. return nil, dialErr
  206. }
  207. c.conn = conn
  208. return c.conn, nil
  209. }
  210. // dialEndpointList attempts to connect to each endpoint in order until a
  211. // connection is established.
  212. func dialEndpointList(c *Client) (*grpc.ClientConn, error) {
  213. var err error
  214. for _, ep := range c.Endpoints() {
  215. conn, curErr := c.Dial(ep)
  216. if curErr != nil {
  217. err = curErr
  218. } else {
  219. return conn, nil
  220. }
  221. }
  222. return nil, err
  223. }
  224. // isHalted returns true if the given error and context indicate no forward
  225. // progress can be made, even after reconnecting.
  226. func isHalted(ctx context.Context, err error) bool {
  227. isRPCError := strings.HasPrefix(grpc.ErrorDesc(err), "etcdserver: ")
  228. return isRPCError || ctx.Err() != nil
  229. }