-
Notifications
You must be signed in to change notification settings - Fork 117
/
controller.go
1516 lines (1338 loc) · 46.8 KB
/
controller.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
package runtime
import (
"context"
"errors"
"fmt"
"runtime"
"strings"
"sync"
"sync/atomic"
"time"
runtimev1 "github.com/rilldata/rill/proto/gen/rill/runtime/v1"
"github.com/rilldata/rill/runtime/drivers"
"github.com/rilldata/rill/runtime/pkg/activity"
"github.com/rilldata/rill/runtime/pkg/dag"
"github.com/rilldata/rill/runtime/pkg/schedule"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"go.uber.org/zap"
"go.uber.org/zap/exp/zapslog"
"golang.org/x/exp/maps"
"golang.org/x/exp/slog"
"google.golang.org/protobuf/proto"
)
// errCyclicDependency is set as the error on resources that can't be reconciled due to a cyclic dependency
var errCyclicDependency = errors.New("cannot be reconciled due to cyclic dependency")
// errControllerClosed is returned from controller functions that require the controller to be running
var errControllerClosed = errors.New("controller is closed")
// Reconciler implements reconciliation logic for all resources of a specific kind.
// Reconcilers are managed and invoked by a Controller.
type Reconciler interface {
Close(ctx context.Context) error
AssignSpec(from, to *runtimev1.Resource) error
AssignState(from, to *runtimev1.Resource) error
ResetState(r *runtimev1.Resource) error
Reconcile(ctx context.Context, n *runtimev1.ResourceName) ReconcileResult
}
// ReconcileResult propagates results from a reconciler invocation
type ReconcileResult struct {
Err error
Retrigger time.Time
}
// ReconcilerInitializer is a function that initializes a new reconciler for a specific controller
type ReconcilerInitializer func(*Controller) Reconciler
// ReconcilerInitializers is a registry of reconciler initializers for different resource kinds.
// There can be only one reconciler per resource kind.
var ReconcilerInitializers = make(map[string]ReconcilerInitializer)
// RegisterReconciler registers a reconciler initializer for a specific resource kind
func RegisterReconcilerInitializer(resourceKind string, initializer ReconcilerInitializer) {
if ReconcilerInitializers[resourceKind] != nil {
panic(fmt.Errorf("reconciler already registered for resource kind %q", resourceKind))
}
ReconcilerInitializers[resourceKind] = initializer
}
// Controller manages the catalog for a single instance and runs reconcilers to migrate the catalog (and related resources in external databases) into the desired state.
// For information about how the controller schedules reconcilers, see `runtime/reconcilers/README.md`.
type Controller struct {
Runtime *Runtime
InstanceID string
Logger *slog.Logger
Activity activity.Client
mu sync.RWMutex
reconcilers map[string]Reconciler
catalog *catalogCache
// Status indicators
closed atomic.Bool // Indicates if the controller is running
closedCh chan struct{} // Closed when the controller is closed
// subscribers tracks subscribers to catalog events.
subscribers map[int]SubscribeCallback
nextSubscriberID int
// idleWaits tracks goroutines waiting for the controller to become idle.
idleWaits map[int]idleWait
nextIdleWaitID int
// queue contains names waiting to be scheduled.
// It's not a real queue because we usually schedule the whole queue on each call to processQueue.
queue map[string]*runtimev1.ResourceName
queueUpdated bool
queueUpdatedCh chan struct{}
// timeline tracks resources to be scheduled in the future.
timeline *schedule.Schedule[string, *runtimev1.ResourceName]
// invocations tracks currently running reconciler invocations.
invocations map[string]*invocation
// completed receives invocations that have finished running.
completed chan *invocation
}
// NewController creates a new Controller
func NewController(ctx context.Context, rt *Runtime, instanceID string, logger *zap.Logger, ac activity.Client) (*Controller, error) {
c := &Controller{
Runtime: rt,
InstanceID: instanceID,
Activity: ac,
closedCh: make(chan struct{}),
reconcilers: make(map[string]Reconciler),
subscribers: make(map[int]SubscribeCallback),
idleWaits: make(map[int]idleWait),
queue: make(map[string]*runtimev1.ResourceName),
queueUpdatedCh: make(chan struct{}, 1),
timeline: schedule.New[string, *runtimev1.ResourceName](nameStr),
invocations: make(map[string]*invocation),
completed: make(chan *invocation),
}
// Hacky way to customize the logger for local vs. hosted
// TODO: Setup the logger to duplicate logs to a) the Zap logger, b) an in-memory buffer that exposes the logs over the API
if !rt.AllowHostAccess() {
logger = logger.With(zap.String("instance_id", instanceID))
logger = logger.Named("console")
}
c.Logger = slog.New(zapslog.HandlerOptions{LoggerName: "console"}.New(logger.Core()))
cc, err := newCatalogCache(ctx, c, c.InstanceID)
if err != nil {
return nil, fmt.Errorf("failed to create catalog cache: %w", err)
}
c.catalog = cc
return c, nil
}
// Run starts and runs the controller's event loop.
// It returns when ctx is cancelled or an unrecoverable error occurs. Before returning, it closes the controller, so it must only be called once.
// The event loop schedules/invokes resource reconciliation and periodically flushes catalog changes to persistent storage.
// The implementation centers around these internal functions: enqueue, processQueue (uses markPending, trySchedule, invoke), and processCompletedInvocation.
// See their docstrings for further details.
func (c *Controller) Run(ctx context.Context) error {
// Initially enqueue all resources
c.mu.Lock()
for _, rs := range c.catalog.resources {
for _, r := range rs {
c.enqueue(r.Meta.Name)
}
}
c.mu.Unlock()
// Ticker for periodically flushing catalog changes
flushTicker := time.NewTicker(10 * time.Second)
defer flushTicker.Stop()
// Timer for scheduling resources added to c.timeline.
// Call resetTimelineTimer whenever the timeline may have been changed (must hold mu).
timelineTimer := time.NewTimer(time.Second)
defer timelineTimer.Stop()
timelineTimer.Stop() // We want it stopped initially
nextTime := time.Time{}
resetTimelineTimer := func() {
_, t := c.timeline.Peek()
if t == nextTime {
return
}
nextTime = t
timelineTimer.Stop()
if t.IsZero() {
return
}
d := time.Until(t)
if d <= 0 {
// must be positive
d = time.Nanosecond
}
d += time.Second // Add a second to avoid rapid cancellations due to micro differences in schedule time
timelineTimer.Reset(d)
}
// Run event loop
var stop bool
var loopErr error
for !stop {
select {
case <-c.queueUpdatedCh: // There are resources we should schedule
c.mu.Lock()
err := c.processQueue()
if err != nil {
loopErr = err
stop = true
} else {
resetTimelineTimer()
}
c.checkIdleWaits()
c.mu.Unlock()
case inv := <-c.completed: // A reconciler invocation has completed
c.mu.Lock()
err := c.processCompletedInvocation(inv)
if err != nil {
loopErr = err
stop = true
} else {
resetTimelineTimer()
}
c.checkIdleWaits()
c.mu.Unlock()
case <-timelineTimer.C: // A previous reconciler invocation asked to be re-scheduled now
c.mu.Lock()
for c.timeline.Len() > 0 {
n, t := c.timeline.Peek()
if t.After(time.Now()) {
break
}
c.timeline.Pop()
c.enqueue(n)
}
resetTimelineTimer()
c.mu.Unlock()
case <-flushTicker.C: // It's time to flush the catalog to persistent storage
c.mu.RLock()
err := c.catalog.flush(ctx)
c.mu.RUnlock()
if err != nil {
loopErr = err
stop = true
}
case <-c.catalog.hasEventsCh: // The catalog has events to process
// Need a write lock to call resetEvents.
c.mu.Lock()
events := c.catalog.events
c.catalog.resetEvents()
c.mu.Unlock()
// Need a read lock to prevent c.subscribers from being modified while we're iterating over it.
c.mu.RLock()
for _, fn := range c.subscribers {
for _, e := range events {
fn(e.event, e.name, e.resource)
}
}
c.mu.RUnlock()
case <-ctx.Done(): // We've been asked to stop
stop = true
break
}
}
// Cleanup time
loopCtxErr := ctx.Err()
var closeErr error
if loopErr != nil {
closeErr = fmt.Errorf("controller event loop failed: %w", loopErr)
}
// Cancel all running invocations
c.mu.RLock()
for _, inv := range c.invocations {
inv.cancel(false)
}
c.mu.RUnlock()
// Allow 10 seconds for closing invocations and reconcilers
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Need to consume all the cancelled invocation completions (otherwise, they will hang on sending to c.completed)
for {
c.mu.RLock()
if len(c.invocations) == 0 {
c.mu.RUnlock()
break
}
c.mu.RUnlock()
stop := false
select {
case inv := <-c.completed:
c.mu.Lock()
err := c.processCompletedInvocation(inv)
if err != nil {
c.Logger.Warn("failed to process completed invocation during shutdown", slog.Any("error", err))
}
c.mu.Unlock()
case <-ctx.Done():
err := fmt.Errorf("timed out waiting for reconcile to finish for resources: %v", maps.Keys(c.invocations))
closeErr = errors.Join(closeErr, err)
stop = true // can't use break inside a select
}
if stop {
break
}
}
// Close all reconcilers
c.mu.Lock()
for k, r := range c.reconcilers {
err := r.Close(ctx)
if err != nil {
err = fmt.Errorf("failed to close reconciler for %q: %w", k, err)
closeErr = errors.Join(closeErr, err)
}
}
c.mu.Unlock()
// Mark closed (no more catalog writes after this)
c.closed.Store(true)
close(c.closedCh)
// Ensure anything waiting for WaitUntilIdle is notified (not calling checkIdleWaits because the queue may not be empty when closing)
c.mu.Lock()
for _, iw := range c.idleWaits {
close(iw.ch)
}
c.mu.Unlock()
// Allow 10 seconds for flushing the catalog
ctx, cancel = context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Close catalog cache (will call flush)
c.mu.Lock()
err := c.catalog.close(ctx)
if err != nil {
err = fmt.Errorf("failed to close catalog: %w", err)
closeErr = errors.Join(closeErr, err)
}
c.mu.Unlock()
if closeErr != nil {
c.Logger.Error("controller closed with error", slog.Any("error", closeErr))
}
closeErr = errors.Join(loopCtxErr, closeErr)
return closeErr
}
// WaitUntilIdle returns when the controller is idle (i.e. no reconcilers are pending or running).
func (c *Controller) WaitUntilIdle(ctx context.Context, ignoreHidden bool) error {
if err := c.checkRunning(); err != nil {
return err
}
ch := make(chan struct{})
c.mu.Lock()
id := c.nextIdleWaitID
c.nextIdleWaitID++
c.idleWaits[id] = idleWait{ch: ch, ignoreHidden: ignoreHidden}
c.checkIdleWaits() // we might be idle already, in which case this will immediately close the channel
c.mu.Unlock()
select {
case <-ch:
// No cleanup necessary - checkIdleWaits removes the wait from idleWaits
case <-ctx.Done():
// NOTE: Can't deadlock because ch is never sent to, only closed.
c.mu.Lock()
delete(c.idleWaits, id)
c.mu.Unlock()
}
return ctx.Err()
}
// Get returns a resource by name.
// Soft-deleted resources (i.e. resources where DeletedOn != nil) are not returned.
func (c *Controller) Get(ctx context.Context, name *runtimev1.ResourceName, clone bool) (*runtimev1.Resource, error) {
ctx, span := tracer.Start(ctx, "Controller.Get", trace.WithAttributes(attribute.String("instance_id", c.InstanceID), attribute.String("kind", name.Kind), attribute.String("name", name.Name)))
defer span.End()
if err := c.checkRunning(); err != nil {
return nil, err
}
if ctx.Err() != nil {
return nil, ctx.Err()
}
c.lock(ctx, true)
defer c.unlock(ctx, true)
// We don't return soft-deleted resources, unless the lookup is from the reconciler itself (which may be executing the delete).
withDeleted := c.isReconcilerForResource(ctx, name)
return c.catalog.get(name, withDeleted, clone)
}
// List returns a list of resources of the specified kind.
// If kind is empty, all resources are returned.
// Soft-deleted resources (i.e. resources where DeletedOn != nil) are not returned.
func (c *Controller) List(ctx context.Context, kind string, clone bool) ([]*runtimev1.Resource, error) {
ctx, span := tracer.Start(ctx, "Controller.List", trace.WithAttributes(attribute.String("instance_id", c.InstanceID), attribute.String("kind", kind)))
defer span.End()
if err := c.checkRunning(); err != nil {
return nil, err
}
if ctx.Err() != nil {
return nil, ctx.Err()
}
c.lock(ctx, true)
defer c.unlock(ctx, true)
return c.catalog.list(kind, false, clone)
}
// SubscribeCallback is the callback type passed to Subscribe.
type SubscribeCallback func(e runtimev1.ResourceEvent, n *runtimev1.ResourceName, r *runtimev1.Resource)
// Subscribe registers a callback that will receive resource update events.
// The same callback function will not be invoked concurrently.
// The callback function is invoked under a lock and must not call the controller.
func (c *Controller) Subscribe(ctx context.Context, fn SubscribeCallback) error {
if err := c.checkRunning(); err != nil {
return err
}
c.mu.Lock()
id := c.nextSubscriberID
c.nextSubscriberID++
c.subscribers[id] = fn
c.mu.Unlock()
defer func() {
c.mu.Lock()
delete(c.subscribers, id)
c.mu.Unlock()
}()
for {
select {
case <-c.closedCh:
return errControllerClosed
case <-ctx.Done():
return ctx.Err()
}
}
}
// Create creates a resource and enqueues it for reconciliation.
// If a resource with the same name is currently being deleted, the deletion will be cancelled.
func (c *Controller) Create(ctx context.Context, name *runtimev1.ResourceName, refs []*runtimev1.ResourceName, owner *runtimev1.ResourceName, paths []string, hidden bool, r *runtimev1.Resource) error {
if err := c.checkRunning(); err != nil {
return err
}
if ctx.Err() != nil {
return ctx.Err()
}
c.lock(ctx, false)
defer c.unlock(ctx, false)
// A deleted resource with the same name may exist and be running. If so, we first cancel it.
requeued := false
if inv, ok := c.invocations[nameStr(name)]; ok && !inv.deletedSelf {
r, err := c.catalog.get(name, true, false)
if err != nil {
return fmt.Errorf("internal: got catalog error for reconciling resource: %w", err)
}
if r.Meta.DeletedOn == nil {
// If a non-deleted resource exists with the same name, we should return an error instead of cancelling.
return drivers.ErrResourceAlreadyExists
}
inv.cancel(true)
requeued = true
}
err := c.catalog.create(name, refs, owner, paths, hidden, r)
if err != nil {
return err
}
if !requeued {
c.enqueue(name)
}
return nil
}
// UpdateMeta updates a resource's meta fields and enqueues it for reconciliation.
// If called from outside the resource's reconciler and the resource is currently reconciling, the current reconciler will be cancelled first.
func (c *Controller) UpdateMeta(ctx context.Context, name *runtimev1.ResourceName, refs []*runtimev1.ResourceName, owner *runtimev1.ResourceName, paths []string) error {
if err := c.checkRunning(); err != nil {
return err
}
if ctx.Err() != nil {
return ctx.Err()
}
c.lock(ctx, false)
defer c.unlock(ctx, false)
if !c.isReconcilerForResource(ctx, name) {
c.cancelIfRunning(name, false)
c.enqueue(name)
}
err := c.safeMutateRenamed(name)
if err != nil {
return err
}
err = c.catalog.updateMeta(name, refs, owner, paths)
if err != nil {
return err
}
// We updated refs, so it may have broken previous cyclic references
ns := c.catalog.retryCyclicRefs()
for _, n := range ns {
c.enqueue(n)
}
return nil
}
// UpdateName renames a resource and updates annotations, and enqueues it for reconciliation.
// If called from outside the resource's reconciler and the resource is currently reconciling, the current reconciler will be cancelled first.
func (c *Controller) UpdateName(ctx context.Context, name, newName, owner *runtimev1.ResourceName, paths []string) error {
if err := c.checkRunning(); err != nil {
return err
}
if ctx.Err() != nil {
return ctx.Err()
}
c.lock(ctx, false)
defer c.unlock(ctx, false)
if !c.isReconcilerForResource(ctx, name) {
c.cancelIfRunning(name, false)
c.enqueue(name)
}
// Check resource exists (otherwise, DAG lookup may panic)
r, err := c.catalog.get(name, false, false)
if err != nil {
return err
}
// All resources pointing to the old name need to be reconciled (they'll pointing to a void resource after this)
if !c.catalog.isCyclic(name) {
ns := c.catalog.dag.Children(name)
for _, n := range ns {
c.enqueue(n)
}
}
err = c.safeRename(name, newName)
if err != nil {
return err
}
c.enqueue(newName)
err = c.catalog.updateMeta(newName, r.Meta.Refs, owner, paths)
if err != nil {
return err
}
// We updated a name, so it may have broken previous cyclic references
ns := c.catalog.retryCyclicRefs()
for _, n := range ns {
c.enqueue(n)
}
return nil
}
// UpdateSpec updates a resource's spec and enqueues it for reconciliation.
// If called from outside the resource's reconciler and the resource is currently reconciling, the current reconciler will be cancelled first.
func (c *Controller) UpdateSpec(ctx context.Context, name *runtimev1.ResourceName, r *runtimev1.Resource) error {
if err := c.checkRunning(); err != nil {
return err
}
if ctx.Err() != nil {
return ctx.Err()
}
c.lock(ctx, false)
defer c.unlock(ctx, false)
if !c.isReconcilerForResource(ctx, name) {
c.cancelIfRunning(name, false)
c.enqueue(name)
}
err := c.safeMutateRenamed(name)
if err != nil {
return err
}
err = c.catalog.updateSpec(name, r)
if err != nil {
return err
}
return nil
}
// UpdateState updates a resource's state.
// It can only be called from within the resource's reconciler.
// NOTE: Calls to UpdateState succeed even if ctx is cancelled. This enables cancelled reconcilers to update state before finishing.
func (c *Controller) UpdateState(ctx context.Context, name *runtimev1.ResourceName, r *runtimev1.Resource) error {
if err := c.checkRunning(); err != nil {
return err
}
// Must not check ctx.Err(). See NOTE above.
c.lock(ctx, false)
defer c.unlock(ctx, false)
if !c.isReconcilerForResource(ctx, name) {
return fmt.Errorf("can't update resource state from outside of reconciler")
}
err := c.catalog.updateState(name, r)
if err != nil {
return err
}
return nil
}
// UpdateError updates a resource's error.
// Unlike UpdateMeta and UpdateSpec, it does not cancel or enqueue reconciliation for the resource.
func (c *Controller) UpdateError(ctx context.Context, name *runtimev1.ResourceName, reconcileErr error) error {
if err := c.checkRunning(); err != nil {
return err
}
if ctx.Err() != nil {
return ctx.Err()
}
c.lock(ctx, false)
defer c.unlock(ctx, false)
err := c.catalog.updateError(name, reconcileErr)
if err != nil {
return err
}
return nil
}
// Delete soft-deletes a resource and enqueues it for reconciliation (with DeletedOn != nil).
// Once the deleting reconciliation has been completed, the resource will be hard deleted.
// If Delete is called from the resource's own reconciler, the resource will be hard deleted immediately (and the calling reconcile's ctx will be canceled immediately).
func (c *Controller) Delete(ctx context.Context, name *runtimev1.ResourceName) error {
if err := c.checkRunning(); err != nil {
return err
}
if ctx.Err() != nil {
return ctx.Err()
}
c.lock(ctx, false)
defer c.unlock(ctx, false)
c.cancelIfRunning(name, false)
// Check resource exists (otherwise, DAG lookup may panic)
_, err := c.catalog.get(name, false, false)
if err != nil {
return err
}
// All resources pointing to deleted resource need to be reconciled (they'll pointing to a void resource after this)
if !c.catalog.isCyclic(name) {
ns := c.catalog.dag.Children(name)
for _, n := range ns {
c.enqueue(n)
}
}
if c.isReconcilerForResource(ctx, name) {
inv := invocationFromContext(ctx)
inv.deletedSelf = true
err := c.catalog.delete(name)
if err != nil {
return err
}
} else {
err := c.catalog.clearRenamedFrom(name) // Avoid resource being marked both deleted and renamed
if err != nil {
return err
}
err = c.catalog.updateDeleted(name)
if err != nil {
return err
}
c.enqueue(name)
}
// We removed a name, so it may have broken previous cyclic references
ns := c.catalog.retryCyclicRefs()
for _, n := range ns {
c.enqueue(n)
}
return nil
}
// Flush forces a flush of the controller's catalog changes to persistent storage.
func (c *Controller) Flush(ctx context.Context) error {
if err := c.checkRunning(); err != nil {
return err
}
if ctx.Err() != nil {
return ctx.Err()
}
c.lock(ctx, false)
defer c.unlock(ctx, false)
return c.catalog.flush(ctx)
}
// Reconcile enqueues a resource for reconciliation.
// If the resource is currently reconciling, the current reconciler will be cancelled first.
func (c *Controller) Reconcile(ctx context.Context, name *runtimev1.ResourceName) error {
if err := c.checkRunning(); err != nil {
return err
}
if ctx.Err() != nil {
return ctx.Err()
}
c.lock(ctx, false)
defer c.unlock(ctx, false)
c.enqueue(name)
return nil
}
// Cancel cancels the current invocation of a resource's reconciler (if it's running).
// It does not re-enqueue the resource for reconciliation.
func (c *Controller) Cancel(ctx context.Context, name *runtimev1.ResourceName) error {
if err := c.checkRunning(); err != nil {
return err
}
if ctx.Err() != nil {
return ctx.Err()
}
c.lock(ctx, false)
defer c.unlock(ctx, false)
c.cancelIfRunning(name, false)
return nil
}
// AcquireOLAP gets a handle for a connector in the controller's instance.
func (c *Controller) AcquireConn(ctx context.Context, connector string) (drivers.Handle, func(), error) {
return c.Runtime.AcquireHandle(ctx, c.InstanceID, connector)
}
// AcquireOLAP gets an OLAP handle for a connector in the controller's instance.
func (c *Controller) AcquireOLAP(ctx context.Context, connector string) (drivers.OLAPStore, func(), error) {
conn, release, err := c.AcquireConn(ctx, connector)
if err != nil {
return nil, nil, err
}
olap, ok := conn.AsOLAP(c.InstanceID)
if !ok {
release()
return nil, nil, fmt.Errorf("connector %q is not an OLAP", connector)
}
return olap, release, nil
}
// Lock locks the controller's catalog and delays scheduling of new reconciliations until the lock is released.
// It can only be called from within a reconciler invocation.
// While the lock is held, resources can only be edited by a caller using the ctx passed to Lock.
func (c *Controller) Lock(ctx context.Context) {
inv := invocationFromContext(ctx)
if inv == nil {
panic("Lock called outside of a reconciler invocation")
}
if inv.holdsLock {
panic("Lock called by invocation that already holds the lock")
}
inv.holdsLock = true
c.mu.Lock()
}
// Unlock releases the lock acquired by Lock.
func (c *Controller) Unlock(ctx context.Context) {
inv := invocationFromContext(ctx)
if inv == nil {
panic("Unlock called outside of a reconciler invocation")
}
if !inv.holdsLock {
panic("Unlock called by invocation that does not hold the lock")
}
inv.holdsLock = false
c.mu.Unlock()
}
// reconciler gets or lazily initializes a reconciler.
// reconciler is not thread-safe and must be called while c.mu is held.
func (c *Controller) reconciler(resourceKind string) Reconciler {
reconciler := c.reconcilers[resourceKind]
if reconciler != nil {
return reconciler
}
initializer := ReconcilerInitializers[resourceKind]
if initializer == nil {
panic(fmt.Errorf("no reconciler registered for resource kind %q", resourceKind))
}
reconciler = initializer(c)
c.reconcilers[resourceKind] = reconciler
return reconciler
}
// checkRunning panics if called when the Controller is not running.
func (c *Controller) checkRunning() error {
if c.closed.Load() {
return errControllerClosed
}
return nil
}
// idleWait represents a caller waiting for the controller to become idle.
// If ignoreHidden is true, the controller will be considered idle if all running invocations are for hidden resources.
type idleWait struct {
ch chan struct{}
ignoreHidden bool
}
// checkIdleWaits checks registered idleWaits and removes any that can be satisfied.
// It must be called with c.mu held.
func (c *Controller) checkIdleWaits() {
if len(c.idleWaits) == 0 {
return
}
// Generally, we're idle if: len(c.queue) == 0 && len(c.invocations) == 0
// But we need to do some other extra checks to handle ignoreHidden.
// The queue is processed rapidly, so we don't check ignoreHidden against it.
if len(c.queue) != 0 {
return // Not idle
}
// Look for non-hidden invocations
found := false
for _, inv := range c.invocations {
if inv.isHidden {
continue
}
found = true
break
}
if found {
return // Not idle
}
// We now know that all invocations (if any) are hidden.
// Check individual waits
for k, iw := range c.idleWaits {
if !iw.ignoreHidden && len(c.invocations) != 0 {
continue
}
delete(c.idleWaits, k)
close(iw.ch)
}
}
// lock locks the controller's mutex, unless ctx belongs to a reconciler invocation that already holds the lock (by having called c.Lock).
func (c *Controller) lock(ctx context.Context, read bool) {
inv := invocationFromContext(ctx)
if inv != nil && inv.holdsLock {
return
}
if read {
c.mu.RLock()
} else {
c.mu.Lock()
}
}
// unlock unlocks the controller's mutex, unless ctx belongs to a reconciler invocation that holds the lock (by having called c.Lock).
func (c *Controller) unlock(ctx context.Context, read bool) {
inv := invocationFromContext(ctx)
if inv != nil && inv.holdsLock {
return
}
if read {
c.mu.RUnlock()
} else {
c.mu.Unlock()
}
}
// isReconcilerForResource returns true if ctx belongs to a reconciler invocation for the given resource.
func (c *Controller) isReconcilerForResource(ctx context.Context, n *runtimev1.ResourceName) bool {
inv := invocationFromContext(ctx)
if inv == nil {
return false
}
return inv.name.Kind == n.Kind && strings.EqualFold(inv.name.Name, n.Name) // NOTE: More efficient, but equivalent to: nameStr(inv.name) == nameStr(n)
}
// safeMutateRenamed makes it safe to mutate a resource that's currently being renamed by changing the rename to a delete+create.
// It does nothing if the resource is not currently being renamed (RenamedFrom == nil).
// It must be called while c.mu is held.
func (c *Controller) safeMutateRenamed(n *runtimev1.ResourceName) error {
r, err := c.catalog.get(n, true, false)
if err != nil {
if errors.Is(err, drivers.ErrResourceNotFound) {
return nil
}
return err
}
renamedFrom := r.Meta.RenamedFrom
if renamedFrom == nil {
return nil
}
err = c.catalog.clearRenamedFrom(n)
if err != nil {
return err
}
_, err = c.catalog.get(renamedFrom, true, false)
if err == nil {
// Either a new resource with the name of the old one has been created in the mean time,
// or the rename just changed the casing of the name.
// In either case, no delete is necessary (reconciler will bring to desired state).
return nil
}
// Create a new resource with the old name, so we can delete it separately.
err = c.catalog.create(renamedFrom, r.Meta.Refs, r.Meta.Owner, r.Meta.FilePaths, r.Meta.Hidden, r)
if err != nil {
return err
}
err = c.catalog.updateDeleted(renamedFrom)
if err != nil {
return err
}
c.enqueue(renamedFrom)
return nil
}
// safeRename safely renames a resource, handling the case where multiple resources are renamed at the same time with collisions between old and new names.
// For example, imagine there are resources A and B, and then A is renamed to B and B is renamed to C simultaneously.
// safeRename resolves collisions by changing some renames to deletes+creates, which works because processQueue ensures deletes are run before creates and renames.
// It must be called while c.mu is held.
func (c *Controller) safeRename(from, to *runtimev1.ResourceName) error {
// Just to be safe.
// NOTE: Not a case insensitive comparison, since we actually want to rename in cases where the casing changed.
if proto.Equal(from, to) {
return nil
}
// There's a collision if to matches RenamedFrom of another resource.
collision := false
for _, n := range c.catalog.renamed {
r, err := c.catalog.get(n, true, false)
if err != nil {
return fmt.Errorf("internal: failed to get renamed resource %v: %w", n, err)
}
if nameStr(to) == nameStr(r.Meta.RenamedFrom) {
collision = true
break
}
}
// No collision, do a normal rename
if !collision {
return c.catalog.rename(from, to)
}
// There's a collision.
// Handle the case where a resource was renamed from e.g. Aa to AA, and then while reconciling, is again renamed from AA to aA.
// In this case, we still do a normal rename and rely on the reconciler to sort it out.
if nameStr(from) == nameStr(to) {
return c.catalog.rename(from, to)
}
// Do a create+delete instead of a rename.
// This is safe because processQueue ensures deletes are run before creates.
// NOTE: Doing the create first, since creation might fail if the name is taken, whereas the delete is almost certain to succeed.
r, err := c.catalog.get(from, true, false)
if err != nil {
return err
}
err = c.catalog.create(to, r.Meta.Refs, r.Meta.Owner, r.Meta.FilePaths, r.Meta.Hidden, r)
if err != nil {
return err
}
err = c.catalog.updateDeleted(from)
if err != nil {
return err
}
c.enqueue(from)
// The caller of safeRename will enqueue the new name
return nil
}
// enqueue marks a resource to be scheduled in the next iteration of the event loop.
// It does so by adding it to c.queue, which will be processed by processQueue().
// It must be called while c.mu is held.
func (c *Controller) enqueue(name *runtimev1.ResourceName) {
c.queue[nameStr(name)] = name
c.setQueueUpdated()