blob: d6000a85c6fe68283a20d41cba2ac27603be8231 [file] [log] [blame]
khenaidooac637102019-01-14 15:44:34 -05001// Copyright 2016 The etcd Authors
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
15package clientv3
16
17import (
18 "context"
khenaidooac637102019-01-14 15:44:34 -050019 "errors"
20 "fmt"
21 "net"
Stephane Barbarie260a5632019-02-26 16:12:49 -050022 "os"
khenaidooac637102019-01-14 15:44:34 -050023 "strconv"
24 "strings"
25 "sync"
26 "time"
27
Stephane Barbarie260a5632019-02-26 16:12:49 -050028 "github.com/google/uuid"
29 "go.etcd.io/etcd/clientv3/balancer"
30 "go.etcd.io/etcd/clientv3/balancer/picker"
31 "go.etcd.io/etcd/clientv3/balancer/resolver/endpoint"
Scott Baker8461e152019-10-01 14:44:30 -070032 "go.etcd.io/etcd/clientv3/credentials"
Stephane Barbarie260a5632019-02-26 16:12:49 -050033 "go.etcd.io/etcd/etcdserver/api/v3rpc/rpctypes"
William Kurkiandaa6bb22019-03-07 12:26:28 -050034 "go.etcd.io/etcd/pkg/logutil"
Stephane Barbarie260a5632019-02-26 16:12:49 -050035 "go.uber.org/zap"
khenaidooac637102019-01-14 15:44:34 -050036 "google.golang.org/grpc"
37 "google.golang.org/grpc/codes"
Scott Baker8461e152019-10-01 14:44:30 -070038 grpccredentials "google.golang.org/grpc/credentials"
khenaidooac637102019-01-14 15:44:34 -050039 "google.golang.org/grpc/keepalive"
40 "google.golang.org/grpc/metadata"
41 "google.golang.org/grpc/status"
42)
43
44var (
45 ErrNoAvailableEndpoints = errors.New("etcdclient: no available endpoints")
46 ErrOldCluster = errors.New("etcdclient: old cluster version")
Stephane Barbarie260a5632019-02-26 16:12:49 -050047
48 roundRobinBalancerName = fmt.Sprintf("etcd-%s", picker.RoundrobinBalanced.String())
khenaidooac637102019-01-14 15:44:34 -050049)
50
Stephane Barbarie260a5632019-02-26 16:12:49 -050051func init() {
52 lg := zap.NewNop()
53 if os.Getenv("ETCD_CLIENT_DEBUG") != "" {
Scott Baker8461e152019-10-01 14:44:30 -070054 lcfg := logutil.DefaultZapLoggerConfig
55 lcfg.Level = zap.NewAtomicLevelAt(zap.DebugLevel)
56
Stephane Barbarie260a5632019-02-26 16:12:49 -050057 var err error
Scott Baker8461e152019-10-01 14:44:30 -070058 lg, err = lcfg.Build() // info level logging
Stephane Barbarie260a5632019-02-26 16:12:49 -050059 if err != nil {
60 panic(err)
61 }
62 }
Scott Baker8461e152019-10-01 14:44:30 -070063
64 // TODO: support custom balancer
Stephane Barbarie260a5632019-02-26 16:12:49 -050065 balancer.RegisterBuilder(balancer.Config{
66 Policy: picker.RoundrobinBalanced,
67 Name: roundRobinBalancerName,
68 Logger: lg,
69 })
70}
71
khenaidooac637102019-01-14 15:44:34 -050072// Client provides and manages an etcd v3 client session.
73type Client struct {
74 Cluster
75 KV
76 Lease
77 Watcher
78 Auth
79 Maintenance
80
Stephane Barbarie260a5632019-02-26 16:12:49 -050081 conn *grpc.ClientConn
khenaidooac637102019-01-14 15:44:34 -050082
Stephane Barbarie260a5632019-02-26 16:12:49 -050083 cfg Config
Scott Baker8461e152019-10-01 14:44:30 -070084 creds grpccredentials.TransportCredentials
Stephane Barbarie260a5632019-02-26 16:12:49 -050085 resolverGroup *endpoint.ResolverGroup
Scott Baker8461e152019-10-01 14:44:30 -070086 mu *sync.RWMutex
khenaidooac637102019-01-14 15:44:34 -050087
88 ctx context.Context
89 cancel context.CancelFunc
90
91 // Username is a user name for authentication.
92 Username string
93 // Password is a password for authentication.
Scott Baker8461e152019-10-01 14:44:30 -070094 Password string
95 authTokenBundle credentials.Bundle
khenaidooac637102019-01-14 15:44:34 -050096
97 callOpts []grpc.CallOption
Stephane Barbarie260a5632019-02-26 16:12:49 -050098
99 lg *zap.Logger
khenaidooac637102019-01-14 15:44:34 -0500100}
101
102// New creates a new etcdv3 client from a given configuration.
103func New(cfg Config) (*Client, error) {
104 if len(cfg.Endpoints) == 0 {
105 return nil, ErrNoAvailableEndpoints
106 }
107
108 return newClient(&cfg)
109}
110
111// NewCtxClient creates a client with a context but no underlying grpc
112// connection. This is useful for embedded cases that override the
113// service interface implementations and do not need connection management.
114func NewCtxClient(ctx context.Context) *Client {
115 cctx, cancel := context.WithCancel(ctx)
116 return &Client{ctx: cctx, cancel: cancel}
117}
118
119// NewFromURL creates a new etcdv3 client from a URL.
120func NewFromURL(url string) (*Client, error) {
121 return New(Config{Endpoints: []string{url}})
122}
123
Stephane Barbarie260a5632019-02-26 16:12:49 -0500124// NewFromURLs creates a new etcdv3 client from URLs.
125func NewFromURLs(urls []string) (*Client, error) {
126 return New(Config{Endpoints: urls})
127}
128
khenaidooac637102019-01-14 15:44:34 -0500129// Close shuts down the client's etcd connections.
130func (c *Client) Close() error {
131 c.cancel()
Scott Baker8461e152019-10-01 14:44:30 -0700132 if c.Watcher != nil {
133 c.Watcher.Close()
134 }
135 if c.Lease != nil {
136 c.Lease.Close()
137 }
Stephane Barbarie260a5632019-02-26 16:12:49 -0500138 if c.resolverGroup != nil {
139 c.resolverGroup.Close()
140 }
khenaidooac637102019-01-14 15:44:34 -0500141 if c.conn != nil {
142 return toErr(c.ctx, c.conn.Close())
143 }
144 return c.ctx.Err()
145}
146
147// Ctx is a context for "out of band" messages (e.g., for sending
148// "clean up" message when another context is canceled). It is
149// canceled on client Close().
150func (c *Client) Ctx() context.Context { return c.ctx }
151
152// Endpoints lists the registered endpoints for the client.
Scott Baker8461e152019-10-01 14:44:30 -0700153func (c *Client) Endpoints() []string {
khenaidooac637102019-01-14 15:44:34 -0500154 // copy the slice; protect original endpoints from being changed
Scott Baker8461e152019-10-01 14:44:30 -0700155 c.mu.RLock()
156 defer c.mu.RUnlock()
157 eps := make([]string, len(c.cfg.Endpoints))
khenaidooac637102019-01-14 15:44:34 -0500158 copy(eps, c.cfg.Endpoints)
Scott Baker8461e152019-10-01 14:44:30 -0700159 return eps
khenaidooac637102019-01-14 15:44:34 -0500160}
161
162// SetEndpoints updates client's endpoints.
163func (c *Client) SetEndpoints(eps ...string) {
164 c.mu.Lock()
Stephane Barbarie260a5632019-02-26 16:12:49 -0500165 defer c.mu.Unlock()
khenaidooac637102019-01-14 15:44:34 -0500166 c.cfg.Endpoints = eps
Stephane Barbarie260a5632019-02-26 16:12:49 -0500167 c.resolverGroup.SetEndpoints(eps)
khenaidooac637102019-01-14 15:44:34 -0500168}
169
170// Sync synchronizes client's endpoints with the known endpoints from the etcd membership.
171func (c *Client) Sync(ctx context.Context) error {
172 mresp, err := c.MemberList(ctx)
173 if err != nil {
174 return err
175 }
176 var eps []string
177 for _, m := range mresp.Members {
178 eps = append(eps, m.ClientURLs...)
179 }
180 c.SetEndpoints(eps...)
181 return nil
182}
183
184func (c *Client) autoSync() {
185 if c.cfg.AutoSyncInterval == time.Duration(0) {
186 return
187 }
188
189 for {
190 select {
191 case <-c.ctx.Done():
192 return
193 case <-time.After(c.cfg.AutoSyncInterval):
194 ctx, cancel := context.WithTimeout(c.ctx, 5*time.Second)
195 err := c.Sync(ctx)
196 cancel()
197 if err != nil && err != c.ctx.Err() {
Stephane Barbarie260a5632019-02-26 16:12:49 -0500198 lg.Lvl(4).Infof("Auto sync endpoints failed: %v", err)
khenaidooac637102019-01-14 15:44:34 -0500199 }
200 }
201 }
202}
203
Scott Baker8461e152019-10-01 14:44:30 -0700204func (c *Client) processCreds(scheme string) (creds grpccredentials.TransportCredentials) {
khenaidooac637102019-01-14 15:44:34 -0500205 creds = c.creds
206 switch scheme {
207 case "unix":
208 case "http":
209 creds = nil
210 case "https", "unixs":
211 if creds != nil {
212 break
213 }
Scott Baker8461e152019-10-01 14:44:30 -0700214 creds = credentials.NewBundle(credentials.Config{}).TransportCredentials()
khenaidooac637102019-01-14 15:44:34 -0500215 default:
216 creds = nil
217 }
218 return creds
219}
220
Stephane Barbarie260a5632019-02-26 16:12:49 -0500221// dialSetupOpts gives the dial opts prior to any authentication.
Scott Baker8461e152019-10-01 14:44:30 -0700222func (c *Client) dialSetupOpts(creds grpccredentials.TransportCredentials, dopts ...grpc.DialOption) (opts []grpc.DialOption, err error) {
khenaidooac637102019-01-14 15:44:34 -0500223 if c.cfg.DialKeepAliveTime > 0 {
224 params := keepalive.ClientParameters{
Stephane Barbarie260a5632019-02-26 16:12:49 -0500225 Time: c.cfg.DialKeepAliveTime,
226 Timeout: c.cfg.DialKeepAliveTimeout,
227 PermitWithoutStream: c.cfg.PermitWithoutStream,
khenaidooac637102019-01-14 15:44:34 -0500228 }
229 opts = append(opts, grpc.WithKeepaliveParams(params))
230 }
231 opts = append(opts, dopts...)
232
Stephane Barbarie260a5632019-02-26 16:12:49 -0500233 // Provide a net dialer that supports cancelation and timeout.
234 f := func(dialEp string, t time.Duration) (net.Conn, error) {
235 proto, host, _ := endpoint.ParseEndpoint(dialEp)
khenaidooac637102019-01-14 15:44:34 -0500236 select {
237 case <-c.ctx.Done():
238 return nil, c.ctx.Err()
239 default:
240 }
241 dialer := &net.Dialer{Timeout: t}
Stephane Barbarie260a5632019-02-26 16:12:49 -0500242 return dialer.DialContext(c.ctx, proto, host)
khenaidooac637102019-01-14 15:44:34 -0500243 }
244 opts = append(opts, grpc.WithDialer(f))
245
khenaidooac637102019-01-14 15:44:34 -0500246 if creds != nil {
Scott Baker8461e152019-10-01 14:44:30 -0700247 opts = append(opts, grpc.WithTransportCredentials(creds))
khenaidooac637102019-01-14 15:44:34 -0500248 } else {
249 opts = append(opts, grpc.WithInsecure())
250 }
251
Stephane Barbarie260a5632019-02-26 16:12:49 -0500252 // Interceptor retry and backoff.
253 // TODO: Replace all of clientv3/retry.go with interceptor based retry, or with
254 // https://github.com/grpc/proposal/blob/master/A6-client-retries.md#retry-policy
255 // once it is available.
256 rrBackoff := withBackoff(c.roundRobinQuorumBackoff(defaultBackoffWaitBetween, defaultBackoffJitterFraction))
257 opts = append(opts,
258 // Disable stream retry by default since go-grpc-middleware/retry does not support client streams.
259 // Streams that are safe to retry are enabled individually.
260 grpc.WithStreamInterceptor(c.streamClientInterceptor(c.lg, withMax(0), rrBackoff)),
261 grpc.WithUnaryInterceptor(c.unaryClientInterceptor(c.lg, withMax(defaultUnaryMaxRetries), rrBackoff)),
262 )
263
264 return opts, nil
khenaidooac637102019-01-14 15:44:34 -0500265}
266
267// Dial connects to a single endpoint using the client's config.
Stephane Barbarie260a5632019-02-26 16:12:49 -0500268func (c *Client) Dial(ep string) (*grpc.ClientConn, error) {
269 creds := c.directDialCreds(ep)
270 // Use the grpc passthrough resolver to directly dial a single endpoint.
271 // This resolver passes through the 'unix' and 'unixs' endpoints schemes used
272 // by etcd without modification, allowing us to directly dial endpoints and
273 // using the same dial functions that we use for load balancer dialing.
274 return c.dial(fmt.Sprintf("passthrough:///%s", ep), creds)
khenaidooac637102019-01-14 15:44:34 -0500275}
276
277func (c *Client) getToken(ctx context.Context) error {
278 var err error // return last error in a case of fail
279 var auth *authenticator
280
Scott Baker8461e152019-10-01 14:44:30 -0700281 eps := c.Endpoints()
282 for _, ep := range eps {
khenaidooac637102019-01-14 15:44:34 -0500283 // use dial options without dopts to avoid reusing the client balancer
Stephane Barbarie260a5632019-02-26 16:12:49 -0500284 var dOpts []grpc.DialOption
285 _, host, _ := endpoint.ParseEndpoint(ep)
286 target := c.resolverGroup.Target(host)
287 creds := c.dialWithBalancerCreds(ep)
288 dOpts, err = c.dialSetupOpts(creds, c.cfg.DialOptions...)
289 if err != nil {
290 err = fmt.Errorf("failed to configure auth dialer: %v", err)
291 continue
292 }
293 dOpts = append(dOpts, grpc.WithBalancerName(roundRobinBalancerName))
294 auth, err = newAuthenticator(ctx, target, dOpts, c)
khenaidooac637102019-01-14 15:44:34 -0500295 if err != nil {
296 continue
297 }
298 defer auth.close()
299
300 var resp *AuthenticateResponse
301 resp, err = auth.authenticate(ctx, c.Username, c.Password)
302 if err != nil {
Stephane Barbarie260a5632019-02-26 16:12:49 -0500303 // return err without retrying other endpoints
304 if err == rpctypes.ErrAuthNotEnabled {
305 return err
306 }
khenaidooac637102019-01-14 15:44:34 -0500307 continue
308 }
309
Scott Baker8461e152019-10-01 14:44:30 -0700310 c.authTokenBundle.UpdateAuthToken(resp.Token)
khenaidooac637102019-01-14 15:44:34 -0500311 return nil
312 }
313
314 return err
315}
316
Stephane Barbarie260a5632019-02-26 16:12:49 -0500317// dialWithBalancer dials the client's current load balanced resolver group. The scheme of the host
318// of the provided endpoint determines the scheme used for all endpoints of the client connection.
319func (c *Client) dialWithBalancer(ep string, dopts ...grpc.DialOption) (*grpc.ClientConn, error) {
320 _, host, _ := endpoint.ParseEndpoint(ep)
321 target := c.resolverGroup.Target(host)
322 creds := c.dialWithBalancerCreds(ep)
323 return c.dial(target, creds, dopts...)
324}
325
326// dial configures and dials any grpc balancer target.
Scott Baker8461e152019-10-01 14:44:30 -0700327func (c *Client) dial(target string, creds grpccredentials.TransportCredentials, dopts ...grpc.DialOption) (*grpc.ClientConn, error) {
Stephane Barbarie260a5632019-02-26 16:12:49 -0500328 opts, err := c.dialSetupOpts(creds, dopts...)
329 if err != nil {
330 return nil, fmt.Errorf("failed to configure dialer: %v", err)
331 }
332
khenaidooac637102019-01-14 15:44:34 -0500333 if c.Username != "" && c.Password != "" {
Scott Baker8461e152019-10-01 14:44:30 -0700334 c.authTokenBundle = credentials.NewBundle(credentials.Config{})
khenaidooac637102019-01-14 15:44:34 -0500335
Stephane Barbarie260a5632019-02-26 16:12:49 -0500336 ctx, cancel := c.ctx, func() {}
khenaidooac637102019-01-14 15:44:34 -0500337 if c.cfg.DialTimeout > 0 {
Stephane Barbarie260a5632019-02-26 16:12:49 -0500338 ctx, cancel = context.WithTimeout(ctx, c.cfg.DialTimeout)
khenaidooac637102019-01-14 15:44:34 -0500339 }
340
Stephane Barbarie260a5632019-02-26 16:12:49 -0500341 err = c.getToken(ctx)
khenaidooac637102019-01-14 15:44:34 -0500342 if err != nil {
343 if toErr(ctx, err) != rpctypes.ErrAuthNotEnabled {
344 if err == ctx.Err() && ctx.Err() != c.ctx.Err() {
345 err = context.DeadlineExceeded
346 }
Stephane Barbarie260a5632019-02-26 16:12:49 -0500347 cancel()
khenaidooac637102019-01-14 15:44:34 -0500348 return nil, err
349 }
350 } else {
Scott Baker8461e152019-10-01 14:44:30 -0700351 opts = append(opts, grpc.WithPerRPCCredentials(c.authTokenBundle.PerRPCCredentials()))
khenaidooac637102019-01-14 15:44:34 -0500352 }
Stephane Barbarie260a5632019-02-26 16:12:49 -0500353 cancel()
khenaidooac637102019-01-14 15:44:34 -0500354 }
355
356 opts = append(opts, c.cfg.DialOptions...)
357
Stephane Barbarie260a5632019-02-26 16:12:49 -0500358 dctx := c.ctx
359 if c.cfg.DialTimeout > 0 {
360 var cancel context.CancelFunc
361 dctx, cancel = context.WithTimeout(c.ctx, c.cfg.DialTimeout)
362 defer cancel() // TODO: Is this right for cases where grpc.WithBlock() is not set on the dial options?
363 }
364
365 conn, err := grpc.DialContext(dctx, target, opts...)
khenaidooac637102019-01-14 15:44:34 -0500366 if err != nil {
367 return nil, err
368 }
369 return conn, nil
370}
371
Scott Baker8461e152019-10-01 14:44:30 -0700372func (c *Client) directDialCreds(ep string) grpccredentials.TransportCredentials {
Stephane Barbarie260a5632019-02-26 16:12:49 -0500373 _, hostPort, scheme := endpoint.ParseEndpoint(ep)
374 creds := c.creds
375 if len(scheme) != 0 {
376 creds = c.processCreds(scheme)
377 if creds != nil {
Scott Baker8461e152019-10-01 14:44:30 -0700378 clone := creds.Clone()
Stephane Barbarie260a5632019-02-26 16:12:49 -0500379 // Set the server name must to the endpoint hostname without port since grpc
380 // otherwise attempts to check if x509 cert is valid for the full endpoint
381 // including the scheme and port, which fails.
382 host, _ := endpoint.ParseHostPort(hostPort)
383 clone.OverrideServerName(host)
Scott Baker8461e152019-10-01 14:44:30 -0700384 creds = clone
Stephane Barbarie260a5632019-02-26 16:12:49 -0500385 }
386 }
387 return creds
388}
389
Scott Baker8461e152019-10-01 14:44:30 -0700390func (c *Client) dialWithBalancerCreds(ep string) grpccredentials.TransportCredentials {
Stephane Barbarie260a5632019-02-26 16:12:49 -0500391 _, _, scheme := endpoint.ParseEndpoint(ep)
392 creds := c.creds
393 if len(scheme) != 0 {
394 creds = c.processCreds(scheme)
395 }
396 return creds
397}
398
khenaidooac637102019-01-14 15:44:34 -0500399// WithRequireLeader requires client requests to only succeed
400// when the cluster has a leader.
401func WithRequireLeader(ctx context.Context) context.Context {
402 md := metadata.Pairs(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
403 return metadata.NewOutgoingContext(ctx, md)
404}
405
406func newClient(cfg *Config) (*Client, error) {
407 if cfg == nil {
408 cfg = &Config{}
409 }
Scott Baker8461e152019-10-01 14:44:30 -0700410 var creds grpccredentials.TransportCredentials
khenaidooac637102019-01-14 15:44:34 -0500411 if cfg.TLS != nil {
Scott Baker8461e152019-10-01 14:44:30 -0700412 creds = credentials.NewBundle(credentials.Config{TLSConfig: cfg.TLS}).TransportCredentials()
khenaidooac637102019-01-14 15:44:34 -0500413 }
414
415 // use a temporary skeleton client to bootstrap first connection
416 baseCtx := context.TODO()
417 if cfg.Context != nil {
418 baseCtx = cfg.Context
419 }
420
421 ctx, cancel := context.WithCancel(baseCtx)
422 client := &Client{
423 conn: nil,
khenaidooac637102019-01-14 15:44:34 -0500424 cfg: *cfg,
425 creds: creds,
426 ctx: ctx,
427 cancel: cancel,
Scott Baker8461e152019-10-01 14:44:30 -0700428 mu: new(sync.RWMutex),
khenaidooac637102019-01-14 15:44:34 -0500429 callOpts: defaultCallOpts,
430 }
Stephane Barbarie260a5632019-02-26 16:12:49 -0500431
William Kurkiandaa6bb22019-03-07 12:26:28 -0500432 lcfg := logutil.DefaultZapLoggerConfig
Stephane Barbarie260a5632019-02-26 16:12:49 -0500433 if cfg.LogConfig != nil {
434 lcfg = *cfg.LogConfig
435 }
436 var err error
437 client.lg, err = lcfg.Build()
438 if err != nil {
439 return nil, err
440 }
441
khenaidooac637102019-01-14 15:44:34 -0500442 if cfg.Username != "" && cfg.Password != "" {
443 client.Username = cfg.Username
444 client.Password = cfg.Password
445 }
446 if cfg.MaxCallSendMsgSize > 0 || cfg.MaxCallRecvMsgSize > 0 {
447 if cfg.MaxCallRecvMsgSize > 0 && cfg.MaxCallSendMsgSize > cfg.MaxCallRecvMsgSize {
448 return nil, fmt.Errorf("gRPC message recv limit (%d bytes) must be greater than send limit (%d bytes)", cfg.MaxCallRecvMsgSize, cfg.MaxCallSendMsgSize)
449 }
450 callOpts := []grpc.CallOption{
451 defaultFailFast,
452 defaultMaxCallSendMsgSize,
453 defaultMaxCallRecvMsgSize,
454 }
455 if cfg.MaxCallSendMsgSize > 0 {
456 callOpts[1] = grpc.MaxCallSendMsgSize(cfg.MaxCallSendMsgSize)
457 }
458 if cfg.MaxCallRecvMsgSize > 0 {
459 callOpts[2] = grpc.MaxCallRecvMsgSize(cfg.MaxCallRecvMsgSize)
460 }
461 client.callOpts = callOpts
462 }
463
Stephane Barbarie260a5632019-02-26 16:12:49 -0500464 // Prepare a 'endpoint://<unique-client-id>/' resolver for the client and create a endpoint target to pass
465 // to dial so the client knows to use this resolver.
466 client.resolverGroup, err = endpoint.NewResolverGroup(fmt.Sprintf("client-%s", uuid.New().String()))
khenaidooac637102019-01-14 15:44:34 -0500467 if err != nil {
468 client.cancel()
khenaidooac637102019-01-14 15:44:34 -0500469 return nil, err
470 }
Stephane Barbarie260a5632019-02-26 16:12:49 -0500471 client.resolverGroup.SetEndpoints(cfg.Endpoints)
khenaidooac637102019-01-14 15:44:34 -0500472
Stephane Barbarie260a5632019-02-26 16:12:49 -0500473 if len(cfg.Endpoints) < 1 {
474 return nil, fmt.Errorf("at least one Endpoint must is required in client config")
khenaidooac637102019-01-14 15:44:34 -0500475 }
Stephane Barbarie260a5632019-02-26 16:12:49 -0500476 dialEndpoint := cfg.Endpoints[0]
477
478 // Use a provided endpoint target so that for https:// without any tls config given, then
479 // grpc will assume the certificate server name is the endpoint host.
480 conn, err := client.dialWithBalancer(dialEndpoint, grpc.WithBalancerName(roundRobinBalancerName))
481 if err != nil {
482 client.cancel()
483 client.resolverGroup.Close()
484 return nil, err
485 }
486 // TODO: With the old grpc balancer interface, we waited until the dial timeout
487 // for the balancer to be ready. Is there an equivalent wait we should do with the new grpc balancer interface?
488 client.conn = conn
khenaidooac637102019-01-14 15:44:34 -0500489
490 client.Cluster = NewCluster(client)
491 client.KV = NewKV(client)
492 client.Lease = NewLease(client)
493 client.Watcher = NewWatcher(client)
494 client.Auth = NewAuth(client)
495 client.Maintenance = NewMaintenance(client)
496
497 if cfg.RejectOldCluster {
498 if err := client.checkVersion(); err != nil {
499 client.Close()
500 return nil, err
501 }
502 }
503
504 go client.autoSync()
505 return client, nil
506}
507
Stephane Barbarie260a5632019-02-26 16:12:49 -0500508// roundRobinQuorumBackoff retries against quorum between each backoff.
509// This is intended for use with a round robin load balancer.
510func (c *Client) roundRobinQuorumBackoff(waitBetween time.Duration, jitterFraction float64) backoffFunc {
511 return func(attempt uint) time.Duration {
512 // after each round robin across quorum, backoff for our wait between duration
513 n := uint(len(c.Endpoints()))
514 quorum := (n/2 + 1)
515 if attempt%quorum == 0 {
William Kurkiandaa6bb22019-03-07 12:26:28 -0500516 c.lg.Debug("backoff", zap.Uint("attempt", attempt), zap.Uint("quorum", quorum), zap.Duration("waitBetween", waitBetween), zap.Float64("jitterFraction", jitterFraction))
Stephane Barbarie260a5632019-02-26 16:12:49 -0500517 return jitterUp(waitBetween, jitterFraction)
518 }
William Kurkiandaa6bb22019-03-07 12:26:28 -0500519 c.lg.Debug("backoff skipped", zap.Uint("attempt", attempt), zap.Uint("quorum", quorum))
Stephane Barbarie260a5632019-02-26 16:12:49 -0500520 return 0
521 }
522}
523
khenaidooac637102019-01-14 15:44:34 -0500524func (c *Client) checkVersion() (err error) {
525 var wg sync.WaitGroup
Scott Baker8461e152019-10-01 14:44:30 -0700526
527 eps := c.Endpoints()
528 errc := make(chan error, len(eps))
khenaidooac637102019-01-14 15:44:34 -0500529 ctx, cancel := context.WithCancel(c.ctx)
530 if c.cfg.DialTimeout > 0 {
Scott Baker8461e152019-10-01 14:44:30 -0700531 cancel()
532 ctx, cancel = context.WithTimeout(c.ctx, c.cfg.DialTimeout)
khenaidooac637102019-01-14 15:44:34 -0500533 }
Scott Baker8461e152019-10-01 14:44:30 -0700534
535 wg.Add(len(eps))
536 for _, ep := range eps {
khenaidooac637102019-01-14 15:44:34 -0500537 // if cluster is current, any endpoint gives a recent version
538 go func(e string) {
539 defer wg.Done()
540 resp, rerr := c.Status(ctx, e)
541 if rerr != nil {
542 errc <- rerr
543 return
544 }
545 vs := strings.Split(resp.Version, ".")
546 maj, min := 0, 0
547 if len(vs) >= 2 {
Scott Baker8461e152019-10-01 14:44:30 -0700548 var serr error
549 if maj, serr = strconv.Atoi(vs[0]); serr != nil {
550 errc <- serr
551 return
552 }
553 if min, serr = strconv.Atoi(vs[1]); serr != nil {
554 errc <- serr
555 return
556 }
khenaidooac637102019-01-14 15:44:34 -0500557 }
558 if maj < 3 || (maj == 3 && min < 2) {
559 rerr = ErrOldCluster
560 }
561 errc <- rerr
562 }(ep)
563 }
564 // wait for success
Scott Baker8461e152019-10-01 14:44:30 -0700565 for range eps {
khenaidooac637102019-01-14 15:44:34 -0500566 if err = <-errc; err == nil {
567 break
568 }
569 }
570 cancel()
571 wg.Wait()
572 return err
573}
574
575// ActiveConnection returns the current in-use connection
576func (c *Client) ActiveConnection() *grpc.ClientConn { return c.conn }
577
578// isHaltErr returns true if the given error and context indicate no forward
579// progress can be made, even after reconnecting.
580func isHaltErr(ctx context.Context, err error) bool {
581 if ctx != nil && ctx.Err() != nil {
582 return true
583 }
584 if err == nil {
585 return false
586 }
587 ev, _ := status.FromError(err)
588 // Unavailable codes mean the system will be right back.
589 // (e.g., can't connect, lost leader)
590 // Treat Internal codes as if something failed, leaving the
591 // system in an inconsistent state, but retrying could make progress.
592 // (e.g., failed in middle of send, corrupted frame)
593 // TODO: are permanent Internal errors possible from grpc?
594 return ev.Code() != codes.Unavailable && ev.Code() != codes.Internal
595}
596
597// isUnavailableErr returns true if the given error is an unavailable error
598func isUnavailableErr(ctx context.Context, err error) bool {
599 if ctx != nil && ctx.Err() != nil {
600 return false
601 }
602 if err == nil {
603 return false
604 }
Scott Baker8461e152019-10-01 14:44:30 -0700605 ev, ok := status.FromError(err)
606 if ok {
607 // Unavailable codes mean the system will be right back.
608 // (e.g., can't connect, lost leader)
609 return ev.Code() == codes.Unavailable
610 }
611 return false
khenaidooac637102019-01-14 15:44:34 -0500612}
613
614func toErr(ctx context.Context, err error) error {
615 if err == nil {
616 return nil
617 }
618 err = rpctypes.Error(err)
619 if _, ok := err.(rpctypes.EtcdError); ok {
620 return err
621 }
Stephane Barbarie260a5632019-02-26 16:12:49 -0500622 if ev, ok := status.FromError(err); ok {
623 code := ev.Code()
624 switch code {
625 case codes.DeadlineExceeded:
626 fallthrough
627 case codes.Canceled:
628 if ctx.Err() != nil {
629 err = ctx.Err()
630 }
khenaidooac637102019-01-14 15:44:34 -0500631 }
khenaidooac637102019-01-14 15:44:34 -0500632 }
633 return err
634}
635
636func canceledByCaller(stopCtx context.Context, err error) bool {
637 if stopCtx.Err() == nil || err == nil {
638 return false
639 }
640
641 return err == context.Canceled || err == context.DeadlineExceeded
642}
Stephane Barbarie260a5632019-02-26 16:12:49 -0500643
644// IsConnCanceled returns true, if error is from a closed gRPC connection.
645// ref. https://github.com/grpc/grpc-go/pull/1854
646func IsConnCanceled(err error) bool {
647 if err == nil {
648 return false
649 }
Scott Baker8461e152019-10-01 14:44:30 -0700650
651 // >= gRPC v1.23.x
Stephane Barbarie260a5632019-02-26 16:12:49 -0500652 s, ok := status.FromError(err)
653 if ok {
654 // connection is canceled or server has already closed the connection
655 return s.Code() == codes.Canceled || s.Message() == "transport is closing"
656 }
Scott Baker8461e152019-10-01 14:44:30 -0700657
Stephane Barbarie260a5632019-02-26 16:12:49 -0500658 // >= gRPC v1.10.x
659 if err == context.Canceled {
660 return true
661 }
Scott Baker8461e152019-10-01 14:44:30 -0700662
Stephane Barbarie260a5632019-02-26 16:12:49 -0500663 // <= gRPC v1.7.x returns 'errors.New("grpc: the client connection is closing")'
664 return strings.Contains(err.Error(), "grpc: the client connection is closing")
665}