-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
watcher.go
1924 lines (1704 loc) · 55.1 KB
/
watcher.go
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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2019 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or collectoried.
See the License for the specific language governing permissions and
limitations under the License.
*/
package services
import (
"context"
"sync"
"time"
"github.com/gravitational/trace"
"github.com/jonboulle/clockwork"
"github.com/sirupsen/logrus"
"github.com/gravitational/teleport/api/constants"
apidefaults "github.com/gravitational/teleport/api/defaults"
"github.com/gravitational/teleport/api/types"
"github.com/gravitational/teleport/api/utils/retryutils"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/utils"
)
// resourceCollector is a generic interface for maintaining an up-to-date view
// of a resource set being monitored. Used in conjunction with resourceWatcher.
type resourceCollector interface {
// resourceKind specifies the resource kind to watch.
resourceKind() string
// getResourcesAndUpdateCurrent is called when the resources should be
// (re-)fetched directly.
getResourcesAndUpdateCurrent(context.Context) error
// processEventAndUpdateCurrent is called when a watcher event is received.
processEventAndUpdateCurrent(context.Context, types.Event)
// notifyStale is called when the maximum acceptable staleness (if specified)
// is exceeded.
notifyStale()
// initializationChan is used to check if the initial state sync has
// been completed.
initializationChan() <-chan struct{}
}
// ResourceWatcherConfig configures resource watcher.
type ResourceWatcherConfig struct {
// Component is a component used in logs.
Component string
// Log is a logger.
Log logrus.FieldLogger
// MaxRetryPeriod is the maximum retry period on failed watchers.
MaxRetryPeriod time.Duration
// Clock is used to control time.
Clock clockwork.Clock
// Client is used to create new watchers.
Client types.Events
// MaxStaleness is a maximum acceptable staleness for the locally maintained
// resources, zero implies no staleness detection.
MaxStaleness time.Duration
// ResetC is a channel to notify of internal watcher reset (used in tests).
ResetC chan time.Duration
}
// CheckAndSetDefaults checks parameters and sets default values.
func (cfg *ResourceWatcherConfig) CheckAndSetDefaults() error {
if cfg.Component == "" {
return trace.BadParameter("missing parameter Component")
}
if cfg.Log == nil {
cfg.Log = logrus.StandardLogger()
}
if cfg.MaxRetryPeriod == 0 {
cfg.MaxRetryPeriod = defaults.MaxWatcherBackoff
}
if cfg.Clock == nil {
cfg.Clock = clockwork.NewRealClock()
}
if cfg.Client == nil {
return trace.BadParameter("missing parameter Client")
}
if cfg.ResetC == nil {
cfg.ResetC = make(chan time.Duration, 1)
}
return nil
}
// newResourceWatcher returns a new instance of resourceWatcher.
// It is the caller's responsibility to verify the inputs' validity
// incl. cfg.CheckAndSetDefaults.
func newResourceWatcher(ctx context.Context, collector resourceCollector, cfg ResourceWatcherConfig) (*resourceWatcher, error) {
retry, err := retryutils.NewLinear(retryutils.LinearConfig{
First: utils.FullJitter(cfg.MaxRetryPeriod / 10),
Step: cfg.MaxRetryPeriod / 5,
Max: cfg.MaxRetryPeriod,
Jitter: retryutils.NewHalfJitter(),
Clock: cfg.Clock,
})
if err != nil {
return nil, trace.Wrap(err)
}
cfg.Log = cfg.Log.WithField("resource-kind", collector.resourceKind())
ctx, cancel := context.WithCancel(ctx)
p := &resourceWatcher{
ResourceWatcherConfig: cfg,
collector: collector,
ctx: ctx,
cancel: cancel,
retry: retry,
LoopC: make(chan struct{}),
StaleC: make(chan struct{}, 1),
}
go p.runWatchLoop()
return p, nil
}
// resourceWatcher monitors additions, updates and deletions
// to a set of resources.
type resourceWatcher struct {
ResourceWatcherConfig
collector resourceCollector
// ctx is a context controlling the lifetime of this resourceWatcher
// instance.
ctx context.Context
cancel context.CancelFunc
// retry is used to manage backoff logic for watchers.
retry retryutils.Retry
// failureStartedAt records when the current sync failures were first
// detected, zero if there are no failures present.
failureStartedAt time.Time
// LoopC is a channel to check whether the watch loop is running
// (used in tests).
LoopC chan struct{}
// StaleC is a channel that can trigger the condition of resource staleness
// (used in tests).
StaleC chan struct{}
}
// Done returns a channel that signals resource watcher closure.
func (p *resourceWatcher) Done() <-chan struct{} {
return p.ctx.Done()
}
// Close closes the resource watcher and cancels all the functions.
func (p *resourceWatcher) Close() {
p.cancel()
}
// IsInitialized is a non-blocking way to check if resource watcher is already
// initialized.
func (p *resourceWatcher) IsInitialized() bool {
select {
case <-p.collector.initializationChan():
return true
default:
return false
}
}
// WaitInitialization blocks until resource watcher is fully initialized with
// the resources presented in auth server.
func (p *resourceWatcher) WaitInitialization() error {
// wait for resourceWatcher to complete initialization.
t := time.NewTicker(5 * time.Second)
defer t.Stop()
for {
select {
case <-p.collector.initializationChan():
return nil
case <-t.C:
p.Log.Debugf("ResourceWatcher %s is not yet initialized.", p.collector.resourceKind())
case <-p.ctx.Done():
return trace.BadParameter("ResourceWatcher %s failed to initialize.", p.collector.resourceKind())
}
}
}
// hasStaleView returns true when the local view has failed to be updated
// for longer than the MaxStaleness bound.
func (p *resourceWatcher) hasStaleView() bool {
// Used for testing stale lock views.
select {
case <-p.StaleC:
return true
default:
}
if p.MaxStaleness == 0 || p.failureStartedAt.IsZero() {
return false
}
return p.Clock.Since(p.failureStartedAt) > p.MaxStaleness
}
// runWatchLoop runs a watch loop.
func (p *resourceWatcher) runWatchLoop() {
for {
p.Log.Debug("Starting watch.")
err := p.watch()
select {
case <-p.ctx.Done():
return
default:
}
if err != nil && p.failureStartedAt.IsZero() {
// Note that failureStartedAt is zeroed in the watch routine immediately
// after the local resource set has been successfully updated.
p.failureStartedAt = p.Clock.Now()
}
if p.hasStaleView() {
p.Log.Warningf("Maximum staleness of %v exceeded, failure started at %v.", p.MaxStaleness, p.failureStartedAt)
p.collector.notifyStale()
}
// Used for testing that the watch routine has exited and is about
// to be restarted.
select {
case p.ResetC <- p.retry.Duration():
default:
}
startedWaiting := p.Clock.Now()
select {
case t := <-p.retry.After():
p.Log.Debugf("Attempting to restart watch after waiting %v.", t.Sub(startedWaiting))
p.retry.Inc()
case <-p.ctx.Done():
p.Log.Debug("Closed, returning from watch loop.")
return
}
if err != nil {
p.Log.Warningf("Restart watch on error: %v.", err)
}
}
}
// watch monitors new resource updates, maintains a local view and broadcasts
// notifications to connected agents.
func (p *resourceWatcher) watch() error {
watcher, err := p.Client.NewWatcher(p.ctx, types.Watch{
Name: p.Component,
MetricComponent: p.Component,
Kinds: []types.WatchKind{{Kind: p.collector.resourceKind()}},
})
if err != nil {
return trace.Wrap(err)
}
defer watcher.Close()
// before fetch, make sure watcher is synced by receiving init event,
// to avoid the scenario:
// 1. Cache process: w = NewWatcher()
// 2. Cache process: c.fetch()
// 3. Backend process: addItem()
// 4. Cache process: <- w.Events()
//
// If there is a way that NewWatcher() on line 1 could
// return without subscription established first,
// Code line 3 could execute and line 4 could miss event,
// wrapping up with out of sync replica.
// To avoid this, before doing fetch,
// cache process makes sure the connection is established
// by receiving init event first.
select {
case <-watcher.Done():
return trace.ConnectionProblem(watcher.Error(), "watcher is closed: %v", watcher.Error())
case <-p.ctx.Done():
return trace.ConnectionProblem(p.ctx.Err(), "context is closing")
case event := <-watcher.Events():
if event.Type != types.OpInit {
return trace.BadParameter("expected init event, got %v instead", event.Type)
}
}
if err := p.collector.getResourcesAndUpdateCurrent(p.ctx); err != nil {
return trace.Wrap(err)
}
p.retry.Reset()
p.failureStartedAt = time.Time{}
for {
select {
case <-watcher.Done():
return trace.ConnectionProblem(watcher.Error(), "watcher is closed: %v", watcher.Error())
case <-p.ctx.Done():
return trace.ConnectionProblem(p.ctx.Err(), "context is closing")
case event := <-watcher.Events():
p.collector.processEventAndUpdateCurrent(p.ctx, event)
case p.LoopC <- struct{}{}:
// Used in tests to detect the watch loop is running.
}
}
}
// ProxyWatcherConfig is a ProxyWatcher configuration.
type ProxyWatcherConfig struct {
ResourceWatcherConfig
// ProxyGetter is used to directly fetch the list of active proxies.
ProxyGetter
// ProxyDiffer is used to decide whether a put operation on an existing proxy should
// trigger a event.
ProxyDiffer func(old, new types.Server) bool
// ProxiesC is a channel used to report the current proxy set. It receives
// a fresh list at startup and subsequently a list of all known proxies
// whenever an addition or deletion is detected.
ProxiesC chan []types.Server
}
// CheckAndSetDefaults checks parameters and sets default values.
func (cfg *ProxyWatcherConfig) CheckAndSetDefaults() error {
if err := cfg.ResourceWatcherConfig.CheckAndSetDefaults(); err != nil {
return trace.Wrap(err)
}
if cfg.ProxyGetter == nil {
getter, ok := cfg.Client.(ProxyGetter)
if !ok {
return trace.BadParameter("missing parameter ProxyGetter and Client not usable as ProxyGetter")
}
cfg.ProxyGetter = getter
}
if cfg.ProxiesC == nil {
cfg.ProxiesC = make(chan []types.Server)
}
return nil
}
// NewProxyWatcher returns a new instance of ProxyWatcher.
func NewProxyWatcher(ctx context.Context, cfg ProxyWatcherConfig) (*ProxyWatcher, error) {
if err := cfg.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
collector := &proxyCollector{
ProxyWatcherConfig: cfg,
initializationC: make(chan struct{}),
}
watcher, err := newResourceWatcher(ctx, collector, cfg.ResourceWatcherConfig)
if err != nil {
return nil, trace.Wrap(err)
}
return &ProxyWatcher{watcher, collector}, nil
}
// ProxyWatcher is built on top of resourceWatcher to monitor additions
// and deletions to the set of proxies.
type ProxyWatcher struct {
*resourceWatcher
*proxyCollector
}
// proxyCollector accompanies resourceWatcher when monitoring proxies.
type proxyCollector struct {
ProxyWatcherConfig
// current holds a map of the currently known proxies (keyed by server name,
// RWMutex protected).
current map[string]types.Server
rw sync.RWMutex
initializationC chan struct{}
once sync.Once
}
// GetCurrent returns the currently stored proxies.
func (p *proxyCollector) GetCurrent() []types.Server {
p.rw.RLock()
defer p.rw.RUnlock()
return serverMapValues(p.current)
}
// resourceKind specifies the resource kind to watch.
func (p *proxyCollector) resourceKind() string {
return types.KindProxy
}
// getResourcesAndUpdateCurrent is called when the resources should be
// (re-)fetched directly.
func (p *proxyCollector) getResourcesAndUpdateCurrent(ctx context.Context) error {
proxies, err := p.ProxyGetter.GetProxies()
if err != nil {
return trace.Wrap(err)
}
newCurrent := make(map[string]types.Server, len(proxies))
for _, proxy := range proxies {
newCurrent[proxy.GetName()] = proxy
}
p.rw.Lock()
defer p.rw.Unlock()
p.current = newCurrent
// only emit an empty proxy list if the collector has already been initialized
// to prevent an empty slice being sent out on creation of the watcher
if len(proxies) > 0 || (len(proxies) == 0 && p.isInitialized()) {
p.broadcastUpdate(ctx)
}
p.defineCollectorAsInitialized()
return nil
}
func (p *proxyCollector) defineCollectorAsInitialized() {
p.once.Do(func() {
// mark watcher as initialized.
close(p.initializationC)
})
}
// processEventAndUpdateCurrent is called when a watcher event is received.
func (p *proxyCollector) processEventAndUpdateCurrent(ctx context.Context, event types.Event) {
if event.Resource == nil || event.Resource.GetKind() != types.KindProxy {
p.Log.Warningf("Unexpected event: %v.", event)
return
}
p.rw.Lock()
defer p.rw.Unlock()
switch event.Type {
case types.OpDelete:
delete(p.current, event.Resource.GetName())
// Always broadcast when a proxy is deleted.
p.broadcastUpdate(ctx)
case types.OpPut:
server, ok := event.Resource.(types.Server)
if !ok {
p.Log.Warningf("Unexpected type %T.", event.Resource)
return
}
current, exists := p.current[server.GetName()]
p.current[server.GetName()] = server
if !exists || (p.ProxyDiffer != nil && p.ProxyDiffer(current, server)) {
p.broadcastUpdate(ctx)
}
default:
p.Log.Warningf("Skipping unsupported event type %s.", event.Type)
}
}
// broadcastUpdate broadcasts information about updating the proxy set.
func (p *proxyCollector) broadcastUpdate(ctx context.Context) {
names := make([]string, 0, len(p.current))
for k := range p.current {
names = append(names, k)
}
p.Log.Debugf("List of known proxies updated: %q.", names)
select {
case p.ProxiesC <- serverMapValues(p.current):
case <-ctx.Done():
}
}
// isInitialized is used to check that the cache has done its initial
// sync
func (p *proxyCollector) initializationChan() <-chan struct{} {
return p.initializationC
}
func (p *proxyCollector) isInitialized() bool {
select {
case <-p.initializationC:
return true
default:
return false
}
}
func (p *proxyCollector) notifyStale() {}
func serverMapValues(serverMap map[string]types.Server) []types.Server {
servers := make([]types.Server, 0, len(serverMap))
for _, server := range serverMap {
servers = append(servers, server)
}
return servers
}
// LockWatcherConfig is a LockWatcher configuration.
type LockWatcherConfig struct {
ResourceWatcherConfig
LockGetter
}
// CheckAndSetDefaults checks parameters and sets default values.
func (cfg *LockWatcherConfig) CheckAndSetDefaults() error {
if err := cfg.ResourceWatcherConfig.CheckAndSetDefaults(); err != nil {
return trace.Wrap(err)
}
if cfg.MaxStaleness == 0 {
cfg.MaxStaleness = defaults.LockMaxStaleness
}
if cfg.LockGetter == nil {
getter, ok := cfg.Client.(LockGetter)
if !ok {
return trace.BadParameter("missing parameter LockGetter and Client not usable as LockGetter")
}
cfg.LockGetter = getter
}
return nil
}
// NewLockWatcher returns a new instance of LockWatcher.
func NewLockWatcher(ctx context.Context, cfg LockWatcherConfig) (*LockWatcher, error) {
if err := cfg.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
collector := &lockCollector{
LockWatcherConfig: cfg,
fanout: NewFanout(),
initializationC: make(chan struct{}),
}
// Resource watcher require the fanout to be initialized before passing in.
// Otherwise, Emit() may fail due to a race condition mentioned in https://github.com/gravitational/teleport/issues/19289
collector.fanout.SetInit()
watcher, err := newResourceWatcher(ctx, collector, cfg.ResourceWatcherConfig)
if err != nil {
return nil, trace.Wrap(err)
}
return &LockWatcher{watcher, collector}, nil
}
// LockWatcher is built on top of resourceWatcher to monitor changes to locks.
type LockWatcher struct {
*resourceWatcher
*lockCollector
}
// lockCollector accompanies resourceWatcher when monitoring locks.
type lockCollector struct {
LockWatcherConfig
// current holds a map of the currently known locks (keyed by lock name).
current map[string]types.Lock
// isStale indicates whether the local lock view (current) is stale.
isStale bool
// currentRW is a mutex protecting both current and isStale.
currentRW sync.RWMutex
// fanout provides support for multiple subscribers to the lock updates.
fanout *Fanout
// initializationC is used to check whether the initial sync has completed
initializationC chan struct{}
once sync.Once
}
// Subscribe is used to subscribe to the lock updates.
func (p *lockCollector) Subscribe(ctx context.Context, targets ...types.LockTarget) (types.Watcher, error) {
watchKinds, err := lockTargetsToWatchKinds(targets)
if err != nil {
return nil, trace.Wrap(err)
}
sub, err := p.fanout.NewWatcher(ctx, types.Watch{Kinds: watchKinds})
if err != nil {
return nil, trace.Wrap(err)
}
select {
case event := <-sub.Events():
if event.Type != types.OpInit {
return nil, trace.BadParameter("expected init event, got %v instead", event.Type)
}
case <-sub.Done():
return nil, trace.Wrap(sub.Error())
}
return sub, nil
}
// CheckLockInForce returns an AccessDenied error if there is a lock in force
// matching at least one of the targets.
func (p *lockCollector) CheckLockInForce(mode constants.LockingMode, targets ...types.LockTarget) error {
p.currentRW.RLock()
defer p.currentRW.RUnlock()
if p.isStale && mode == constants.LockingModeStrict {
return StrictLockingModeAccessDenied
}
if lock := p.findLockInForceUnderMutex(targets); lock != nil {
return LockInForceAccessDenied(lock)
}
return nil
}
func (p *lockCollector) findLockInForceUnderMutex(targets []types.LockTarget) types.Lock {
for _, lock := range p.current {
if !lock.IsInForce(p.Clock.Now()) {
continue
}
if len(targets) == 0 {
return lock
}
for _, target := range targets {
if target.Match(lock) {
return lock
}
}
}
return nil
}
// GetCurrent returns the currently stored locks.
func (p *lockCollector) GetCurrent() []types.Lock {
p.currentRW.RLock()
defer p.currentRW.RUnlock()
return lockMapValues(p.current)
}
// resourceKind specifies the resource kind to watch.
func (p *lockCollector) resourceKind() string {
return types.KindLock
}
// initializationChan is used to check that the cache has done its initial
// sync
func (p *lockCollector) initializationChan() <-chan struct{} {
return p.initializationC
}
// getResourcesAndUpdateCurrent is called when the resources should be
// (re-)fetched directly.
func (p *lockCollector) getResourcesAndUpdateCurrent(ctx context.Context) error {
locks, err := p.LockGetter.GetLocks(ctx, true)
if err != nil {
return trace.Wrap(err)
}
newCurrent := map[string]types.Lock{}
for _, lock := range locks {
newCurrent[lock.GetName()] = lock
}
p.currentRW.Lock()
defer p.currentRW.Unlock()
p.current = newCurrent
p.isStale = false
p.defineCollectorAsInitialized()
for _, lock := range p.current {
p.fanout.Emit(types.Event{Type: types.OpPut, Resource: lock})
}
return nil
}
func (p *lockCollector) defineCollectorAsInitialized() {
p.once.Do(func() {
// mark watcher as initialized.
close(p.initializationC)
})
}
// processEventAndUpdateCurrent is called when a watcher event is received.
func (p *lockCollector) processEventAndUpdateCurrent(ctx context.Context, event types.Event) {
if event.Resource == nil || event.Resource.GetKind() != types.KindLock {
p.Log.Warningf("Unexpected event: %v.", event)
return
}
p.currentRW.Lock()
defer p.currentRW.Unlock()
switch event.Type {
case types.OpDelete:
delete(p.current, event.Resource.GetName())
p.fanout.Emit(event)
case types.OpPut:
lock, ok := event.Resource.(types.Lock)
if !ok {
p.Log.Warningf("Unexpected resource type %T.", event.Resource)
return
}
if lock.IsInForce(p.Clock.Now()) {
p.current[lock.GetName()] = lock
p.fanout.Emit(event)
} else {
delete(p.current, lock.GetName())
}
default:
p.Log.Warningf("Skipping unsupported event type %s.", event.Type)
}
}
// notifyStale is called when the maximum acceptable staleness (if specified)
// is exceeded.
func (p *lockCollector) notifyStale() {
p.currentRW.Lock()
defer p.currentRW.Unlock()
p.fanout.Emit(types.Event{Type: types.OpUnreliable})
// Do not clear p.current here, the most recent lock set may still be used
// with LockingModeBestEffort.
p.isStale = true
}
func lockTargetsToWatchKinds(targets []types.LockTarget) ([]types.WatchKind, error) {
watchKinds := make([]types.WatchKind, 0, len(targets))
for _, target := range targets {
if target.IsEmpty() {
continue
}
filter, err := target.IntoMap()
if err != nil {
return nil, trace.Wrap(err)
}
watchKinds = append(watchKinds, types.WatchKind{
Kind: types.KindLock,
Filter: filter,
})
}
if len(watchKinds) == 0 {
watchKinds = []types.WatchKind{{Kind: types.KindLock}}
}
return watchKinds, nil
}
func lockMapValues(lockMap map[string]types.Lock) []types.Lock {
locks := make([]types.Lock, 0, len(lockMap))
for _, lock := range lockMap {
locks = append(locks, lock)
}
return locks
}
// DatabaseWatcherConfig is a DatabaseWatcher configuration.
type DatabaseWatcherConfig struct {
// ResourceWatcherConfig is the resource watcher configuration.
ResourceWatcherConfig
// DatabaseGetter is responsible for fetching database resources.
DatabaseGetter
// DatabasesC receives up-to-date list of all database resources.
DatabasesC chan types.Databases
}
// CheckAndSetDefaults checks parameters and sets default values.
func (cfg *DatabaseWatcherConfig) CheckAndSetDefaults() error {
if err := cfg.ResourceWatcherConfig.CheckAndSetDefaults(); err != nil {
return trace.Wrap(err)
}
if cfg.DatabaseGetter == nil {
getter, ok := cfg.Client.(DatabaseGetter)
if !ok {
return trace.BadParameter("missing parameter DatabaseGetter and Client not usable as DatabaseGetter")
}
cfg.DatabaseGetter = getter
}
if cfg.DatabasesC == nil {
cfg.DatabasesC = make(chan types.Databases)
}
return nil
}
// NewDatabaseWatcher returns a new instance of DatabaseWatcher.
func NewDatabaseWatcher(ctx context.Context, cfg DatabaseWatcherConfig) (*DatabaseWatcher, error) {
if err := cfg.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
collector := &databaseCollector{
DatabaseWatcherConfig: cfg,
initializationC: make(chan struct{}),
}
watcher, err := newResourceWatcher(ctx, collector, cfg.ResourceWatcherConfig)
if err != nil {
return nil, trace.Wrap(err)
}
return &DatabaseWatcher{watcher, collector}, nil
}
// DatabaseWatcher is built on top of resourceWatcher to monitor database resources.
type DatabaseWatcher struct {
*resourceWatcher
*databaseCollector
}
// databaseCollector accompanies resourceWatcher when monitoring database resources.
type databaseCollector struct {
// DatabaseWatcherConfig is the watcher configuration.
DatabaseWatcherConfig
// current holds a map of the currently known database resources.
current map[string]types.Database
// lock protects the "current" map.
lock sync.RWMutex
// initializationC is used to check that the
initializationC chan struct{}
once sync.Once
}
// resourceKind specifies the resource kind to watch.
func (p *databaseCollector) resourceKind() string {
return types.KindDatabase
}
// isInitialized is used to check that the cache has done its initial
// sync
func (p *databaseCollector) initializationChan() <-chan struct{} {
return p.initializationC
}
// getResourcesAndUpdateCurrent refreshes the list of current resources.
func (p *databaseCollector) getResourcesAndUpdateCurrent(ctx context.Context) error {
databases, err := p.DatabaseGetter.GetDatabases(ctx)
if err != nil {
return trace.Wrap(err)
}
newCurrent := make(map[string]types.Database, len(databases))
for _, database := range databases {
newCurrent[database.GetName()] = database
}
p.lock.Lock()
defer p.lock.Unlock()
p.current = newCurrent
p.defineCollectorAsInitialized()
select {
case <-ctx.Done():
return trace.Wrap(ctx.Err())
case p.DatabasesC <- databases:
}
return nil
}
func (p *databaseCollector) defineCollectorAsInitialized() {
p.once.Do(func() {
// mark watcher as initialized.
close(p.initializationC)
})
}
// processEventAndUpdateCurrent is called when a watcher event is received.
func (p *databaseCollector) processEventAndUpdateCurrent(ctx context.Context, event types.Event) {
if event.Resource == nil || event.Resource.GetKind() != types.KindDatabase {
p.Log.Warnf("Unexpected event: %v.", event)
return
}
p.lock.Lock()
defer p.lock.Unlock()
switch event.Type {
case types.OpDelete:
delete(p.current, event.Resource.GetName())
select {
case <-ctx.Done():
case p.DatabasesC <- resourcesToSlice(p.current):
}
case types.OpPut:
database, ok := event.Resource.(types.Database)
if !ok {
p.Log.Warnf("Unexpected resource type %T.", event.Resource)
return
}
p.current[database.GetName()] = database
select {
case <-ctx.Done():
case p.DatabasesC <- resourcesToSlice(p.current):
}
default:
p.Log.Warnf("Unsupported event type %s.", event.Type)
return
}
}
func (*databaseCollector) notifyStale() {}
// AppWatcherConfig is an AppWatcher configuration.
type AppWatcherConfig struct {
// ResourceWatcherConfig is the resource watcher configuration.
ResourceWatcherConfig
// AppGetter is responsible for fetching application resources.
AppGetter
// AppsC receives up-to-date list of all application resources.
AppsC chan types.Apps
}
// CheckAndSetDefaults checks parameters and sets default values.
func (cfg *AppWatcherConfig) CheckAndSetDefaults() error {
if err := cfg.ResourceWatcherConfig.CheckAndSetDefaults(); err != nil {
return trace.Wrap(err)
}
if cfg.AppGetter == nil {
getter, ok := cfg.Client.(AppGetter)
if !ok {
return trace.BadParameter("missing parameter AppGetter and Client not usable as AppGetter")
}
cfg.AppGetter = getter
}
if cfg.AppsC == nil {
cfg.AppsC = make(chan types.Apps)
}
return nil
}
// NewAppWatcher returns a new instance of AppWatcher.
func NewAppWatcher(ctx context.Context, cfg AppWatcherConfig) (*AppWatcher, error) {
if err := cfg.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
collector := &appCollector{
AppWatcherConfig: cfg,
initializationC: make(chan struct{}),
}
watcher, err := newResourceWatcher(ctx, collector, cfg.ResourceWatcherConfig)
if err != nil {
return nil, trace.Wrap(err)
}
return &AppWatcher{watcher, collector}, nil
}
// AppWatcher is built on top of resourceWatcher to monitor application resources.
type AppWatcher struct {
*resourceWatcher
*appCollector
}
// appCollector accompanies resourceWatcher when monitoring application resources.
type appCollector struct {
// AppWatcherConfig is the watcher configuration.
AppWatcherConfig
// current holds a map of the currently known application resources.
current map[string]types.Application
// lock protects the "current" map.
lock sync.RWMutex
// initializationC is used to check whether the initial sync has completed
initializationC chan struct{}
once sync.Once
}
// resourceKind specifies the resource kind to watch.
func (p *appCollector) resourceKind() string {
return types.KindApp
}
// isInitialized is used to check that the cache has done its initial
// sync
func (p *appCollector) initializationChan() <-chan struct{} {
return p.initializationC
}
// getResourcesAndUpdateCurrent refreshes the list of current resources.
func (p *appCollector) getResourcesAndUpdateCurrent(ctx context.Context) error {
apps, err := p.AppGetter.GetApps(ctx)
if err != nil {
return trace.Wrap(err)
}
newCurrent := make(map[string]types.Application, len(apps))
for _, app := range apps {
newCurrent[app.GetName()] = app
}
p.lock.Lock()
defer p.lock.Unlock()
p.current = newCurrent
p.defineCollectorAsInitialized()
select {
case <-ctx.Done():
return trace.Wrap(ctx.Err())
case p.AppsC <- apps:
}
return nil
}
func (p *appCollector) defineCollectorAsInitialized() {
p.once.Do(func() {
// mark watcher as initialized.
close(p.initializationC)
})
}
// processEventAndUpdateCurrent is called when a watcher event is received.
func (p *appCollector) processEventAndUpdateCurrent(ctx context.Context, event types.Event) {
if event.Resource == nil || event.Resource.GetKind() != types.KindApp {
p.Log.Warnf("Unexpected event: %v.", event)
return
}
p.lock.Lock()
defer p.lock.Unlock()
switch event.Type {
case types.OpDelete:
delete(p.current, event.Resource.GetName())
p.AppsC <- resourcesToSlice(p.current)
select {
case <-ctx.Done():
case p.AppsC <- resourcesToSlice(p.current):
}
case types.OpPut:
app, ok := event.Resource.(types.Application)
if !ok {
p.Log.Warnf("Unexpected resource type %T.", event.Resource)
return
}
p.current[app.GetName()] = app
select {
case <-ctx.Done():
case p.AppsC <- resourcesToSlice(p.current):
}
default:
p.Log.Warnf("Unsupported event type %s.", event.Type)