-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathkvclientbabysitter.go
More file actions
559 lines (457 loc) · 13 KB
/
kvclientbabysitter.go
File metadata and controls
559 lines (457 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
package gocbcorex
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"sync"
"sync/atomic"
"time"
"github.com/couchbase/gocbcorex/memdx"
"github.com/google/uuid"
"go.uber.org/zap"
"golang.org/x/exp/slices"
)
type KvTargetTlsConfig struct {
RootCAs *x509.CertPool
InsecureSkipVerify bool
CipherSuites []uint16
}
func (v KvTargetTlsConfig) Equals(o *KvTargetTlsConfig) bool {
return v.RootCAs.Equal(o.RootCAs) &&
v.InsecureSkipVerify == o.InsecureSkipVerify &&
slices.Equal(v.CipherSuites, o.CipherSuites)
}
type KvTarget struct {
Address string
TLSConfig *KvTargetTlsConfig
}
func (v KvTarget) Equals(o KvTarget) bool {
if v.Address != o.Address {
return false
}
if v.TLSConfig == nil && o.TLSConfig == nil {
// both nil, so equal
} else if v.TLSConfig != nil && o.TLSConfig != nil {
if !v.TLSConfig.Equals(o.TLSConfig) {
// both not nil, but not equal
return false
}
// both not nil, and equal
} else {
// one is nil and the other is not, not equal
return false
}
return true
}
type KvClientAuth interface {
GetAuth(address string) (username, password string, clientCert *tls.Certificate, err error)
}
type kvClientBabysitterClientConfig struct {
Target KvTarget
Auth KvClientAuth
SelectedBucket string
}
func (v kvClientBabysitterClientConfig) Equals(o kvClientBabysitterClientConfig) bool {
return v.Target.Equals(o.Target) &&
v.Auth == o.Auth &&
v.SelectedBucket == o.SelectedBucket
}
type KvClientBabysitter interface {
KvClientProvider
UpdateTarget(newTarget KvTarget)
UpdateAuth(newAuth KvClientAuth)
UpdateSelectedBucket(newBucket string)
Close() error
}
type KvClientBabysitterStateChangeFn func(KvClientBabysitter, KvClient, error)
type NewKvClientFunc func(context.Context, *KvClientOptions) (KvClient, error)
type kvClientBabysitterState struct {
Err error
Client KvClient
}
type kvClientBabysitter struct {
logger *zap.Logger
newKvClient NewKvClientFunc
connectTimeout time.Duration
connectErrThrottlePeriod time.Duration
onDemandConnect bool
bootstrapOpts KvClientBootstrapOptions
stateChangeHandler KvClientBabysitterStateChangeFn
client atomic.Pointer[kvClientBabysitterState]
lock sync.Mutex
isBuilding bool
isClosed bool
stateChangeWaitCh chan struct{}
buildCancelFn func()
buildDoneCh chan struct{}
currentClient KvClient
currentConfig *kvClientBabysitterClientConfig
desiredConfig *kvClientBabysitterClientConfig
connectErr error
activeClient KvClient
}
var _ KvClientBabysitter = (*kvClientBabysitter)(nil)
type KvClientBabysitterOptions struct {
Logger *zap.Logger
NewKvClient NewKvClientFunc
OnDemandConnect bool
ConnectTimeout time.Duration
ConnectErrThrottlePeriod time.Duration
StateChangeHandler KvClientBabysitterStateChangeFn
BootstrapOpts KvClientBootstrapOptions
Target KvTarget
Auth KvClientAuth
SelectedBucket string
}
func NewKvClientBabysitter(opts *KvClientBabysitterOptions) KvClientBabysitter {
if opts == nil {
opts = &KvClientBabysitterOptions{}
}
logger := loggerOrNop(opts.Logger)
// We namespace the pool to improve debugging,
logger = logger.With(
zap.String("providerId", uuid.NewString()[:8]),
)
connectTimeout := opts.ConnectTimeout
if connectTimeout == 0 {
connectTimeout = 10 * time.Second
}
connectErrThrottlePeriod := opts.ConnectErrThrottlePeriod
if connectErrThrottlePeriod == 0 {
connectErrThrottlePeriod = 1 * time.Second
}
newKvClient := opts.NewKvClient
if opts.NewKvClient == nil {
newKvClient = NewKvClient
}
p := &kvClientBabysitter{
logger: logger,
newKvClient: newKvClient,
connectTimeout: connectTimeout,
connectErrThrottlePeriod: connectErrThrottlePeriod,
onDemandConnect: opts.OnDemandConnect,
bootstrapOpts: opts.BootstrapOpts,
stateChangeHandler: opts.StateChangeHandler,
stateChangeWaitCh: make(chan struct{}),
desiredConfig: &kvClientBabysitterClientConfig{
Target: opts.Target,
Auth: opts.Auth,
SelectedBucket: opts.SelectedBucket,
},
}
if !p.onDemandConnect {
p.maybeBeginClientBuildLocked()
}
return p
}
func (p *kvClientBabysitter) UpdateTarget(newTarget KvTarget) {
p.lock.Lock()
defer p.lock.Unlock()
if p.desiredConfig.Target.Equals(newTarget) {
return
}
p.desiredConfig.Target = newTarget
p.updateActiveClientLocked()
p.rebuildFastLookupLocked()
p.maybeBeginClientBuildLocked()
}
func (p *kvClientBabysitter) UpdateAuth(newAuth KvClientAuth) {
p.lock.Lock()
defer p.lock.Unlock()
if p.desiredConfig.Auth == newAuth {
return
}
p.desiredConfig.Auth = newAuth
p.updateActiveClientLocked()
p.rebuildFastLookupLocked()
p.maybeBeginClientBuildLocked()
}
func (p *kvClientBabysitter) UpdateSelectedBucket(newBucket string) {
p.lock.Lock()
defer p.lock.Unlock()
if p.desiredConfig.SelectedBucket == newBucket {
return
}
p.desiredConfig.SelectedBucket = newBucket
p.updateActiveClientLocked()
p.rebuildFastLookupLocked()
p.maybeBeginClientBuildLocked()
}
func (p *kvClientBabysitter) updateActiveClientLocked() {
// if there is no current client, we obviously can't use it
if p.currentClient == nil {
p.activeClient = nil
return
}
// if we previously had no bucket selected, but now do, we cannot use
// the client to prevent a race condition where the bucket is not
// actually selected yet. Note that the converse is not true, if we
// had a bucket selected, but now do not, that is safe to use still.
if p.currentConfig.SelectedBucket == "" && p.desiredConfig.SelectedBucket != "" {
p.activeClient = nil
return
}
p.activeClient = p.currentClient
}
func (p *kvClientBabysitter) rebuildFastLookupLocked() {
p.client.Store(&kvClientBabysitterState{
Err: p.connectErr,
Client: p.activeClient,
})
}
func (p *kvClientBabysitter) maybeBeginClientBuildLocked() {
if p.isClosed {
return
}
if p.isBuilding {
return
}
if p.activeClient != nil &&
p.currentConfig.Equals(*p.desiredConfig) {
// already have a client with the desired config
return
}
buildCtx, buildCancelFn := context.WithCancel(context.Background())
buildDoneCh := make(chan struct{}, 1)
p.isBuilding = true
p.buildCancelFn = buildCancelFn
p.buildDoneCh = buildDoneCh
go func() {
p.clientBuildThread(buildCtx)
p.lock.Lock()
p.isBuilding = false
p.buildCancelFn = nil
p.buildDoneCh = nil
p.lock.Unlock()
buildCancelFn()
close(buildDoneCh)
}()
}
func (p *kvClientBabysitter) clientBuildThread(
ctx context.Context,
) {
p.logger.Info("client build thread started")
lastErrTime := time.Time{}
// we are the only writer to these values, so it is safe to read them
// without a lock, and we do not need to refresh them while we are working.
currentConfig := p.currentConfig
currentClient := p.currentClient
p.lock.Lock()
desiredConfig := p.desiredConfig
p.lock.Unlock()
ClientBuildLoop:
for {
if desiredConfig == nil {
p.logger.DPanic("desired config is nil in client build thread")
}
if currentClient != nil && currentConfig == nil {
p.logger.DPanic("current client is non-nil but current config is nil in client build thread")
}
if ctx.Err() != nil {
p.logger.Debug("client build thread exiting due to context done", zap.Error(ctx.Err()))
return
}
if currentConfig != nil && desiredConfig.Equals(*currentConfig) {
// we have reached the desired config
break
}
if currentClient != nil {
bucketChangeConfig := *currentConfig
bucketChangeConfig.SelectedBucket = desiredConfig.SelectedBucket
if desiredConfig.Equals(bucketChangeConfig) {
// if changing the bucket is enough to match the desired config, do that
err := currentClient.SelectBucket(ctx, desiredConfig.SelectedBucket)
if err == nil {
currentConfig = desiredConfig
p.lock.Lock()
p.currentConfig = currentConfig
p.updateActiveClientLocked()
p.rebuildFastLookupLocked()
p.lock.Unlock()
continue
} else {
p.logger.Warn("failed to reconfigure existing kv client", zap.Error(err))
}
}
}
p.logger.Info("creating new client kv client",
zap.Any("config", desiredConfig))
for {
connectWaitPeriod := p.connectErrThrottlePeriod - time.Since(lastErrTime)
if connectWaitPeriod > 0 {
p.logger.Debug("throttling client connection due to recent error",
zap.Duration("throttlePeriod", p.connectErrThrottlePeriod),
zap.Duration("waitPeriod", connectWaitPeriod))
select {
case <-ctx.Done():
break ClientBuildLoop
case <-time.After(connectWaitPeriod):
}
continue
}
break
}
handleError := func(err error) {
if !errors.Is(err, context.Canceled) {
p.logger.Warn("failed to create new kv client", zap.Error(err))
}
p.lock.Lock()
p.connectErr = err
p.rebuildFastLookupLocked()
p.sendStateChangeLocked()
desiredConfig = p.desiredConfig
p.lock.Unlock()
lastErrTime = time.Now()
}
username, password, clientCert, err := desiredConfig.Auth.GetAuth(desiredConfig.Target.Address)
if err != nil {
handleError(err)
continue
}
var tlsConfig *tls.Config
if desiredConfig.Target.TLSConfig != nil {
tlsConfig = &tls.Config{
RootCAs: desiredConfig.Target.TLSConfig.RootCAs,
InsecureSkipVerify: desiredConfig.Target.TLSConfig.InsecureSkipVerify,
CipherSuites: desiredConfig.Target.TLSConfig.CipherSuites,
}
if clientCert != nil {
tlsConfig.Certificates = []tls.Certificate{*clientCert}
}
}
timeoutCtx, timeoutCancel := context.WithTimeout(ctx, p.connectTimeout)
newClient, err := p.newKvClient(timeoutCtx, &KvClientOptions{
Logger: p.logger,
Address: desiredConfig.Target.Address,
TlsConfig: tlsConfig,
Auth: &memdx.SaslAuthAutoOptions{
Username: username,
Password: password,
EnabledMechs: []memdx.AuthMechanism{
memdx.ScramSha512AuthMechanism,
memdx.ScramSha256AuthMechanism},
},
SelectedBucket: desiredConfig.SelectedBucket,
BootstrapOpts: p.bootstrapOpts,
CloseHandler: p.handleClientClosed,
})
timeoutCancel()
if err != nil {
handleError(err)
continue
}
existingClient := currentClient
currentClient = newClient
currentConfig = desiredConfig
p.lock.Lock()
p.currentClient = currentClient
p.currentConfig = currentConfig
p.connectErr = nil
p.updateActiveClientLocked()
p.rebuildFastLookupLocked()
p.sendStateChangeLocked()
desiredConfig = p.desiredConfig
p.lock.Unlock()
if existingClient != nil {
err = existingClient.Close()
if err != nil {
p.logger.Warn("failed to close old kv client", zap.Error(err))
}
}
}
}
func (p *kvClientBabysitter) sendStateChangeLocked() {
if p.stateChangeHandler != nil {
p.stateChangeHandler(p, p.activeClient, p.connectErr)
}
// state channel is basically a constant event feed
close(p.stateChangeWaitCh)
p.stateChangeWaitCh = make(chan struct{})
}
func (p *kvClientBabysitter) handleClientClosed(client KvClient, err error) {
p.lock.Lock()
defer p.lock.Unlock()
if client != p.currentClient {
return
}
p.currentConfig = nil
p.currentClient = nil
p.activeClient = nil
if !p.onDemandConnect {
p.maybeBeginClientBuildLocked()
}
p.rebuildFastLookupLocked()
p.sendStateChangeLocked()
}
// GetClient will wait until a client is available to use, or an explicit
// failure to connect to the client is known (in which case, the error is returned).
func (p *kvClientBabysitter) GetClient(ctx context.Context) (KvClient, error) {
wrapper := p.client.Load()
if wrapper != nil {
if wrapper.Client != nil {
return wrapper.Client, nil
} else if wrapper.Err != nil {
return nil, wrapper.Err
}
}
for {
p.lock.Lock()
isClosed := p.isClosed
client := p.activeClient
connectErr := p.connectErr
p.maybeBeginClientBuildLocked()
waitCh := p.stateChangeWaitCh
p.lock.Unlock()
if isClosed {
return nil, errors.New("client provider is closed")
}
if client != nil {
return client, nil
}
if connectErr != nil {
return nil, connectErr
}
select {
case <-waitCh:
// continue
case <-ctx.Done():
ctxErr := ctx.Err()
p.logger.Debug("context Done triggered during get client slow", zap.Error(ctxErr))
if errors.Is(ctxErr, context.DeadlineExceeded) {
return nil, ErrClientStillConnecting
} else {
return nil, ctxErr
}
}
}
}
func (p *kvClientBabysitter) Close() error {
p.logger.Debug("closing kv client manager")
p.lock.Lock()
p.isClosed = true
p.activeClient = nil
isBuilding := p.isBuilding
buildCancelFn := p.buildCancelFn
buildDoneCh := p.buildDoneCh
if isBuilding {
p.lock.Unlock()
if buildCancelFn == nil || buildDoneCh == nil {
p.logger.DPanic("inconsistent state in kv client manager close")
}
buildCancelFn()
<-buildDoneCh
p.lock.Lock()
}
currentClient := p.currentClient
p.currentConfig = nil
p.currentClient = nil
p.lock.Unlock()
if currentClient != nil {
closeErr := currentClient.Close()
if closeErr != nil {
return closeErr
}
}
return nil
}