Repository navigation
Expand file tree
/
Copy pathgittarget_controller.go
More file actions
1751 lines (1617 loc) · 76.8 KB
/
Copy pathgittarget_controller.go
File metadata and controls
1751 lines (1617 loc) · 76.8 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
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
// SPDX-License-Identifier: Apache-2.0
package controller
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"time"
"filippo.io/age"
fluxmeta "github.com/fluxcd/pkg/apis/meta"
"github.com/go-logr/logr"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
k8stypes "k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/record"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/handler"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/predicate"
ctrlreconcile "sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
configbutleraiv1alpha3 "github.com/ConfigButler/gitops-reverser/api/v1alpha3"
"github.com/ConfigButler/gitops-reverser/internal/authz"
"github.com/ConfigButler/gitops-reverser/internal/git"
"github.com/ConfigButler/gitops-reverser/internal/reconcile"
"github.com/ConfigButler/gitops-reverser/internal/telemetry"
"github.com/ConfigButler/gitops-reverser/internal/types"
"github.com/ConfigButler/gitops-reverser/internal/watch"
)
const (
GitTargetConditionReady = ConditionTypeReady
GitTargetConditionReconciling = ConditionTypeReconciling
GitTargetConditionStalled = ConditionTypeStalled
GitTargetConditionValidated = "Validated"
GitTargetConditionEncryptionConfigured = "EncryptionConfigured"
GitTargetConditionGitPathAccepted = ConditionTypeGitPathAccepted
GitTargetConditionRenderMatchesLive = ConditionTypeRenderMatchesLive
// GitTargetConditionStreamsRunning is the source data-plane axis: True when every tracked type's
// watch has crossed its replay watermark or resumed from a durable cursor.
GitTargetConditionStreamsRunning = ConditionTypeStreamsRunning
)
const (
// GitTargetReasonOK is the healthy reason. It is the shared Succeeded vocabulary rather than
// a per-kind spelling; the name is kept for call-site stability.
GitTargetReasonOK = ReasonSucceeded
// GitTargetReasonGitBranchNotFound is the Validated=False reason for a GitTarget whose
// spec.gitBranchRef names no GitBranch, or is not set.
GitTargetReasonGitBranchNotFound = "GitBranchNotFound"
GitTargetReasonTargetConflict = "TargetConflict"
GitTargetReasonNotChecked = "NotChecked"
GitTargetReasonBlocked = "Blocked"
GitTargetReasonNotStarted = "NotStarted"
GitTargetReasonNotRequired = "NotRequired"
GitTargetReasonMissingSecret = "MissingSecret"
GitTargetReasonInvalidConfig = "InvalidConfig"
GitTargetReasonSecretCreateDisabled = "SecretCreateDisabled"
GitTargetReasonUnsupportedContent = "UnsupportedContent"
// GitTargetReasonIgnoreShadowsManagedPath is the terminal reason for the one
// unrecoverable .gittargetignore footgun (docs/spec/gitpath-foreign-content-stringency.md
// §4.3): an ignore pattern matches a path the operator writes, which would blind it to its
// own file. The writer's write-plan precondition refuses the flush before any byte is
// written and the GitTarget is failed with this reason. The string must stay in sync with
// the watch package's gitPathRefusalReason.
GitTargetReasonIgnoreShadowsManagedPath = "IgnoreShadowsManagedPath"
// GitTargetReasonWriteBoundaryRefused is the reason for a write the operator refused
// because it had nowhere safe to land, rather than because the folder holds content the
// operator cannot manage
// (docs/design/support-boundary/gittarget-granularity-and-cross-environment-edits.md §1): a
// planned write escaping spec.path (L1), or an in-place edit of a source file more than
// one kustomize render root reaches (L2, write-fan-in > 1). Nothing was committed. The
// string must stay in sync with the watch package's gitPathRefusalReason.
GitTargetReasonWriteBoundaryRefused = "WriteBoundaryRefused"
// GitTargetReasonMultipleSourceNamespaces is the terminal reason for a target that declared
// its folder namespace-free (spec.serializeNamespace: false) and that more than one source
// namespace reaches. Two namespaces produce documents whose identities are equal once the
// namespace is stripped, so each write flips one document between two live objects; the writer
// refuses the flush before any byte is written. The remedy is a GitTarget or WatchRule edit.
// The string must stay in sync with manifestanalyzer.GitPathRefusalReason.
GitTargetReasonMultipleSourceNamespaces = "MultipleSourceNamespaces"
// GitTargetReasonUnrenderedPlacement is the terminal reason for a placement under
// spec.placement.useKustomize that no kustomization would render: the folder already has a
// render root and the resolved path is outside it. Nothing is written, because a document in
// Git that nothing applies looks mirrored and is not. The remedy is the target's own template
// or path. The string must stay in sync with manifestanalyzer.GitPathRefusalReason.
GitTargetReasonUnrenderedPlacement = "UnrenderedPlacement"
GitTargetReasonRenderDoesNotMatchLive = "RenderDoesNotMatchLive"
GitTargetReasonRenderRechecking = "Rechecking"
GitTargetReadyReasonValidationFailed = "ValidationFailed"
GitTargetReadyReasonEncryptionNotConfigured = "EncryptionNotConfigured"
GitTargetReadyReasonWorkerUnavailable = "WorkerUnavailable"
// GitTargetReasonWatchPlanFailing is Ready=False/Reconciling=True while the watch-plane
// owner's pass for this GitTarget keeps failing and being retried on its backoff ladder. It
// is deliberately a PROGRESSING reason rather than a stall: a pass fails on a source cluster
// that is unreachable or a catalog that is not observable yet, both of which recover on their
// own. What it buys is that such a target does not read as idle.
GitTargetReasonWatchPlanFailing = "WatchPlanFailing"
GitTargetStreamsRunningReasonNotReady = "NotReady"
// GitTargetReasonSuspended is Ready=True on a target whose spec.suspend stops it writing. It
// is True on purpose: suppressing writes on request is a configured outcome, not ill health.
GitTargetReasonSuspended = fluxmeta.SuspendedReason
)
const (
encryptionSecretRecipientAnnoKey = "configbutler.ai/age-recipient"
encryptionSecretBackupWarningAnno = "configbutler.ai/backup-warning"
encryptionSecretBackupWarningValue = "REMOVE_AFTER_BACKUP"
)
// GitTargetReconciler reconciles a GitTarget object.
type GitTargetReconciler struct {
client.Client
Scheme *runtime.Scheme
WorkerManager *git.WorkerManager
EventRouter *watch.EventRouter
// GitRefreshInterval is how often an idle branch is asked to re-prove where its remote is,
// and the quantizer status.remote's clock is written against. Zero or less turns the
// refresher OFF, which buys back the property that nothing here holds a timer against the
// Git host; status.remote still works in that mode, because pushes still renew it.
GitRefreshInterval time.Duration
// Recorder emits a Kubernetes Event on every persisted Ready transition. It may be nil in
// tests, in which case no Event is recorded and nothing else changes.
Recorder record.EventRecorder
// reconcileRequests remembers which reconcile-request annotation values have been acted on,
// so a standing annotation forces one re-read rather than one per reconcile forever. Its zero
// value is usable.
reconcileRequests reconcileRequestTracker
}
// +kubebuilder:rbac:groups=configbutler.ai,resources=gittargets,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=configbutler.ai,resources=gittargets/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=configbutler.ai,resources=gitproviders,verbs=get;list;watch
// +kubebuilder:rbac:groups=configbutler.ai,resources=gitbranches,verbs=get;list;watch
// +kubebuilder:rbac:groups=configbutler.ai,resources=fluxclaims;argocdclaims,verbs=get;list;watch
// +kubebuilder:rbac:groups="",resources=secrets,verbs=get;create;update
// +kubebuilder:rbac:groups="",resources=events,verbs=create;patch
// The Flux and Argo CD kinds an applier claim holds are NOT granted here: nothing needs them until an
// applier claim names an applier, and an install that does not use Flux or Argo CD should not hold
// write rights on their objects. config/rbac/flux-applier-role.yaml and argocd-applier-role.yaml,
// and the chart's applierAccess.flux and applierAccess.argocd, grant them.
// newGitTargetReadiness starts the accumulator that owns this kind's kstatus trio. Its converged
// outcome is what Ready reports when no gate objected.
func newGitTargetReadiness() *readiness {
return newReadiness("GitTarget is fully reconciled", "GitTarget is not stalled")
}
// Reconcile validates GitTarget references and drives startup lifecycle gates.
func (r *GitTargetReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
log := logf.FromContext(ctx).WithName("GitTargetReconciler")
var target configbutleraiv1alpha3.GitTarget
if err := r.Get(ctx, req.NamespacedName, &target); err != nil {
return r.handleFetchError(ctx, err, log, req.NamespacedName)
}
st := beginStatus(r.Client, r.Recorder, &target)
gitPathWasRefused := conditionIsFalse(target.Status.Conditions, GitTargetConditionGitPathAccepted)
publication := r.branchPublication(&target)
// One read of the GitBranch and its GitProvider for everything below it; see resolveDestination.
dest, destErr := r.resolveDestination(ctx, &target)
if destErr != nil {
return ctrl.Result{}, destErr
}
r.publishAheadOfGates(st, &target, dest)
validated, validationMsg, validationErr := r.evaluateValidatedGate(ctx, st, &target, dest)
if validationErr != nil {
return ctrl.Result{}, validationErr
}
if !validated {
// A GitTarget that stopped validating (its KubeProvider deleted, no longer admitting this
// namespace, or reading another namespace's audit route) must have its data plane STOPPED,
// not merely marked blocked. Otherwise its watches keep mirroring on the cached credential
// while status claims Validated=False. Forgetting the declaration cancels those watches and
// releases the source-cluster context; a later recovery re-declares and re-snapshots.
r.stopSourceClusterMirror(&target)
st.set(
GitTargetConditionEncryptionConfigured,
metav1.ConditionUnknown,
GitTargetReasonBlocked,
"Blocked by Validated=False",
)
return r.stall(ctx, st, blockedGate{
reason: GitTargetReadyReasonValidationFailed,
message: validationMsg,
blocked: "Blocked by Validated=False",
})
}
encryptionReady, encryptionMessage, encryptionRequeueAfter := r.evaluateEncryptionGate(ctx, st, &target, log)
if !encryptionReady {
return r.stall(ctx, st, blockedGate{
reason: GitTargetReadyReasonEncryptionNotConfigured,
message: encryptionMessage,
blocked: "Blocked by EncryptionConfigured=False",
requeueAfter: encryptionRequeueAfter,
})
}
// The branch is written only by the GitBranch holding its claim, so a target whose GitBranch does
// not hold it has no worker to be wired to. That clears on its own once the GitBranch proves
// itself, so it is progress, not a stall.
if blocked, result, err := r.blockOnGitBranch(ctx, st, dest); blocked {
return result, err
}
// Ensure the branch worker exists and register the GitTarget's event stream before declaring
// streams. The watch data plane can route live events as soon as it reaches Streaming, so the
// destination worker must already be wired.
wired, wiringMessage := r.evaluateWorkerWiringGate(ctx, &target, dest, log)
if !wired {
return r.stall(ctx, st, blockedGate{
reason: GitTargetReadyReasonWorkerUnavailable,
message: wiringMessage,
blocked: "Blocked by worker wiring failure",
})
}
// The refresher's applier claim is this reconcile, which is already a scheduled tick looking for a
// job: a converged GitTarget requeues on RequeueSteadyInterval and those passes publish
// status without touching Git. Nothing new schedules anything, and the request is ENQUEUED
// rather than run here — the reconcile must not block on a network round trip, and the work
// belongs on the one goroutine allowed to touch the repository.
r.requestRemoteRefresh(&target)
// One read of the source KubeProvider serves everything below it: the audit route captured on
// Declare and the KubeProviderReady projection. Reading it twice invited the two to disagree.
sourceProvider, sourceProviderErr := r.resolveSourceKubeProvider(ctx, &target)
if sourceProviderErr != nil {
return ctrl.Result{}, sourceProviderErr
}
// A standing reconcile request forces the same re-check a refused Git path does: the watch
// plane re-anchors the target's streams, which is what makes it re-read the folder rather than
// wait for the periodic pass. Taken once per distinct annotation value.
forceRecheck := gitPathWasRefused || r.reconcileRequests.take(
types.NewResourceReference(target.Name, target.Namespace), reconcileRequestedAt(&target))
observed := r.observeDataPlane(&target, sourceProvider, forceRecheck, log)
st.setValue(GitTargetConditionStreamsRunning, observed.axes.Streams)
st.setValue(GitTargetConditionGitPathAccepted, observed.axes.GitPath)
st.setValue(GitTargetConditionRenderMatchesLive, observed.axes.Render)
refs := r.publishReferenceReadiness(st, &target, gitBranchReadiness(dest, true), sourceProvider)
claimVerdict, hasClaim := r.observeApplierClaim(ctx, st, &target, dest)
rd := newGitTargetReadiness()
convergeAsSuspended(rd, &target)
gitTargetReadinessGates(rd, observed,
refs.gitBranch, refs.kubeProvider, refs.sourceCluster, publicationCondition(publication))
applierClaimReadiness(rd, claimVerdict, hasClaim)
st.applyReadiness(rd)
if err := st.commit(ctx); err != nil {
return ctrl.Result{}, err
}
// requeueAfter shortens the cadence when the status write lost a race: the object then holds
// the WINNER's older answer and nothing re-enqueues it, because the For() predicate filters
// status-only updates by design.
requeue := st.requeueAfter(gitTargetRequeue(rd))
// This is the only place that publishes the axis, so it is the only place that can say what it
// published and how long it intends to wait before saying anything again (the diagnostic that
// named Failure A in docs/design/watch-plane-status-convergence-failures.md).
log.V(1).Info("GitTarget status published",
"writeLost", st.writeLost(),
"gitTarget", target.Namespace+"/"+target.Name,
"render", string(observed.axes.Render.Status)+"/"+observed.axes.Render.Reason,
"streams", observed.streams.Summary(),
"converged", rd.converged(),
"requeueAfter", requeue.String())
return ctrl.Result{RequeueAfter: requeue}, nil
}
// publishAheadOfGates writes what holds whether or not any gate passes. The folder's layout is
// published ahead of every gate, so a target held unready still shows what the last scan resolved:
// it exists to explain a refused or surprising write.
//
// The branch-target join series is published here for the same reason: it has to carry the targets
// that are NOT working. git_pushes_total names a branch that stopped advancing and cannot name the
// GitTargets behind it, and a mapping published only on the happy path would go missing exactly
// when that question is being asked. It is a statement about configuration, so it holds whether or
// not a worker ever started. See telemetry/branch_targets.go.
func (r *GitTargetReconciler) publishAheadOfGates(
st *reconcileStatus, target *configbutleraiv1alpha3.GitTarget, dest gitDestination,
) {
layout, scanned := r.observeLayout(target)
publishLayout(st, target, layout, scanned)
// The GitBranch labels join git_pushes_total, which the worker labels with the GitBranch it
// writes for. They come from spec.gitBranchRef alone, so a GitBranch that does not exist yet is
// still named.
telemetry.RecordBranchTarget(
target.Namespace, target.Name, dest.key.Namespace, dest.key.Name, target.SourceCluster())
}
// convergeAsSuspended gives a suspended GitTarget the converged outcome, under its own reason.
//
// A suspended target is healthy, not faulty: not writing is the configured outcome, and no
// condition may go False for one — that is what trains operators to ignore the conditions that
// mean the mirror is genuinely broken. status.retention is the precedent. So Ready stays True and
// only its reason changes, which is what makes the state legible without making it look like a
// fault. Every real gate still applies afterwards: a suspended target with a broken provider is
// still not Ready.
func convergeAsSuspended(rd *readiness, target *configbutleraiv1alpha3.GitTarget) {
if !target.Spec.Suspend {
return
}
rd.convergesAs(conditionValue{
Status: metav1.ConditionTrue,
Reason: GitTargetReasonSuspended,
Message: "GitTarget is suspended: it scans and publishes what it resolved, and writes nothing",
})
}
// gitTargetRequeue picks the periodic cadence. Only a converged GitTarget earns the steady interval.
//
// A STALLED target gets the fast loop too, which is deliberate and specific to this kind: its
// terminal states clear when the Git FOLDER changes (someone removes the unsupported file, someone
// fixes the diverged value), and that produces no Kubernetes event at all. The data-plane
// acceptance channel is best-effort, so the periodic re-check is what actually recovers a refused
// target. It is cheap now that a re-check which finds nothing new writes nothing.
func gitTargetRequeue(rd *readiness) time.Duration {
if rd.converged() {
return RequeueSteadyInterval
}
return RequeueStreamSettleInterval
}
// blockedGate describes a control-plane gate that failed before the data plane could be evaluated.
type blockedGate struct {
// reason and message are the terminal outcome published on the trio.
reason, message string
// blocked explains, on each data-plane condition, why it was not evaluated at all.
blocked string
// requeueAfter overrides the steady cadence this gate would otherwise get. Zero means take it.
requeueAfter time.Duration
// progressing publishes the outcome as progress (Ready=False, Reconciling=True) rather than a
// stall: the gate clears on its own, and a watch re-runs this reconcile when it does.
progressing bool
}
// stall publishes a terminal control-plane outcome and ends the reconcile.
//
// The three early-return gates used to repeat this block verbatim: mark the data plane
// not-evaluated, stamp the trio, write status with retry, choose a requeue. They differ only in the
// values blockedGate carries.
func (r *GitTargetReconciler) stall(
ctx context.Context,
st *reconcileStatus,
gate blockedGate,
) (ctrl.Result, error) {
st.set(GitTargetConditionStreamsRunning, metav1.ConditionUnknown,
GitTargetStreamsRunningReasonNotReady, gate.blocked+"; streams not evaluated")
st.set(GitTargetConditionRenderMatchesLive, metav1.ConditionUnknown,
GitTargetReasonRenderRechecking, gate.blocked+"; render fidelity not evaluated")
st.set(GitTargetConditionGitPathAccepted, metav1.ConditionUnknown,
GitTargetReasonNotChecked, gate.blocked)
rd := newGitTargetReadiness()
if gate.progressing {
rd.progressing(metav1.ConditionFalse, gate.reason, gate.message)
} else {
rd.stalled(gate.reason, gate.message)
}
st.applyReadiness(rd)
if err := st.commit(ctx); err != nil {
return ctrl.Result{}, err
}
// Through st.requeueAfter, exactly like the converged path below: a stalled reconcile whose
// status write lost the race has published nothing, so leaving it on the gate's own cadence
// strands the object on the previous answer for five minutes. This path returned gate.result
// directly and was the one place that skipped the check.
cadence := gate.requeueAfter
switch {
case cadence != 0:
case gate.progressing:
// Not converged, so the not-Ready cadence: a gate that clears on its own is looked at again
// soon, as gitTargetRequeue does for every other progressing target.
cadence = RequeueStreamSettleInterval
default:
cadence = RequeueSteadyInterval
}
return ctrl.Result{RequeueAfter: st.requeueAfter(cadence)}, nil
}
// observeSourceReachable projects the source cluster's runtime reachability.
//
// A GitTarget whose KubeProvider sets spec.inCluster mirrors the cluster the operator runs in, which
// is reachable by definition — so the default (used when no watch manager is wired, e.g. in tests)
// is True/LocalCluster for an inCluster provider and Unknown only for a remote one.
func (r *GitTargetReconciler) observeSourceReachable(
target *configbutleraiv1alpha3.GitTarget,
provider *configbutleraiv1alpha3.KubeProvider,
) conditionValue {
reach := watch.SourceClusterReachableStatus{State: "True", Reason: "LocalCluster"}
if !provider.IsInCluster() {
reach = watch.SourceClusterReachableStatus{State: "Unknown", Reason: "AwaitingDiscovery"}
}
if r.EventRouter != nil && r.EventRouter.WatchManager != nil {
reach = r.EventRouter.WatchManager.SourceClusterReachable(target.SourceCluster())
}
return conditionValue{
Status: conditionStatusFromString(reach.State),
Reason: reach.Reason,
Message: reach.Message,
}
}
func (r *GitTargetReconciler) evaluateValidatedGate(
ctx context.Context,
st *reconcileStatus,
target *configbutleraiv1alpha3.GitTarget,
dest gitDestination,
) (bool, string, error) {
if dest.branch == nil {
message := fmt.Sprintf("Referenced GitBranch '%s' not found", dest.key)
if dest.key.Name == "" {
message = "spec.gitBranchRef is not set"
}
st.set(GitTargetConditionValidated, metav1.ConditionFalse, GitTargetReasonGitBranchNotFound, message)
return false, fmt.Sprintf("Validated gate failed: %s", GitTargetReasonGitBranchNotFound), nil
}
conflict, conflictMsg, conflictReason, conflictErr := r.checkForConflicts(ctx, target)
if conflictErr != nil {
return false, "", conflictErr
}
if conflict {
st.set(GitTargetConditionValidated, metav1.ConditionFalse, conflictReason, conflictMsg)
return false, fmt.Sprintf("Validated gate failed: %s", conflictReason), nil
}
if placementOK, placementMsg := validatePlacementPolicy(target.Spec.Placement); !placementOK {
st.set(GitTargetConditionValidated,
metav1.ConditionFalse,
GitTargetReasonInvalidConfig,
placementMsg,
)
return false, fmt.Sprintf("Validated gate failed: %s", GitTargetReasonInvalidConfig), nil
}
if commitOK, commitMsg := validateCommitConfig(target); !commitOK {
st.set(GitTargetConditionValidated,
metav1.ConditionFalse,
GitTargetReasonInvalidConfig,
commitMsg,
)
return false, fmt.Sprintf("Validated gate failed: %s", GitTargetReasonInvalidConfig), nil
}
// The source cluster's credential is validated on the referenced
// KubeProvider now, not here — the GitTarget only NAMES its source cluster. The
// KubeProvider's readiness is projected onto the GitTarget as a separate condition.
// Namespace authorization: a GitTarget may reference a KubeProvider only while a grant in its
// spec.allowedGitTargets admits the GitTarget's namespace, and only while the provider holds its
// audit route. Enforced HERE and only here, on every reconcile — which also covers a policy
// tightened after the GitTarget was created. Failing this gate returns
// before DeclareForGitTarget below, so an unauthorized target starts no watch and writes no Git.
authorized, authReason, authMsg, authErr := r.checkSourceAuthorization(ctx, target)
if authErr != nil {
return false, "", authErr
}
if !authorized {
st.set(GitTargetConditionValidated, metav1.ConditionFalse, authReason, authMsg)
return false, fmt.Sprintf("Validated gate failed: %s", authReason), nil
}
st.set(GitTargetConditionValidated,
metav1.ConditionTrue,
GitTargetReasonOK,
"GitBranch, placement and commit validation passed",
)
return true, "", nil
}
func (r *GitTargetReconciler) evaluateEncryptionGate(
ctx context.Context,
st *reconcileStatus,
target *configbutleraiv1alpha3.GitTarget,
log logr.Logger,
) (bool, string, time.Duration) {
if !isTargetAgeEncryptionEnabled(target) {
st.set(GitTargetConditionEncryptionConfigured,
metav1.ConditionTrue,
GitTargetReasonNotRequired,
"SOPS age encryption is not enabled for this GitTarget",
)
return true, "", 0
}
if err := r.ensureEncryptionSecret(ctx, target, log); err != nil {
reason := GitTargetReasonInvalidConfig
if strings.Contains(err.Error(), "missing and generateWhenMissing is disabled") {
reason = GitTargetReasonSecretCreateDisabled
}
if strings.Contains(err.Error(), "failed to fetch encryption secret") {
reason = GitTargetReasonMissingSecret
}
st.set(GitTargetConditionEncryptionConfigured, metav1.ConditionFalse, reason, err.Error())
return false, fmt.Sprintf("EncryptionConfigured gate failed: %s", reason), RequeueSteadyInterval
}
if _, err := git.ResolveTargetEncryption(ctx, r.Client, target); err != nil {
reason := GitTargetReasonInvalidConfig
if strings.Contains(err.Error(), "failed to fetch encryption secret") {
reason = GitTargetReasonMissingSecret
}
st.set(GitTargetConditionEncryptionConfigured, metav1.ConditionFalse, reason, err.Error())
return false, fmt.Sprintf("EncryptionConfigured gate failed: %s", reason), RequeueSteadyInterval
}
st.set(GitTargetConditionEncryptionConfigured,
metav1.ConditionTrue,
GitTargetReasonOK,
"Encryption configuration is valid",
)
return true, "", 0
}
// blockOnGitBranch publishes GitBranchReady, and ends the reconcile as progress while the target
// cannot be wired: its GitBranch does not hold the branch, or names a GitProvider that does not exist.
func (r *GitTargetReconciler) blockOnGitBranch(
ctx context.Context, st *reconcileStatus, dest gitDestination,
) (bool, ctrl.Result, error) {
held := r.holdsBranch(dest)
branchReady := gitBranchReadiness(dest, held)
st.setValue(GitTargetConditionGitBranchReady, branchReady)
if held && dest.provider != nil {
return false, ctrl.Result{}, nil
}
result, err := r.stall(ctx, st, blockedGate{
reason: GitTargetReasonGitBranchNotReady,
message: branchReady.Message,
blocked: "Blocked by GitBranchReady=False",
progressing: true,
})
return true, result, err
}
// evaluateWorkerWiringGate ensures the GitTarget's branch worker exists and registers its
// GitTargetEventStream, the route live watch events use to reach the branch worker. This is
// internal plumbing rather than a status condition of its own: rare failures fold into Ready
// with reason WorkerUnavailable. A nil EventRouter (test/standalone) is trivially wired.
func (r *GitTargetReconciler) evaluateWorkerWiringGate(
ctx context.Context,
target *configbutleraiv1alpha3.GitTarget,
dest gitDestination,
log logr.Logger,
) (bool, string) {
if r.EventRouter == nil {
return true, ""
}
if _, err := r.ensureEventStream(ctx, target, dest.workerRequest(), log); err != nil {
return false, fmt.Sprintf("Failed to wire branch worker/event stream for %s/%s: %v",
target.Namespace, target.Name, err)
}
return true, ""
}
// setBlockedDataPlane marks stream readiness as not-yet-evaluated when a control-plane gate
// blocked the reconcile before watches could be declared.
// stopSourceClusterMirror tears down the data plane of a GitTarget that is no longer Validated, so
// a dead credential — or a source KubeProvider that was deleted — can never keep an active mirror
// running behind a Validated=False status. It applies to inCluster AND remote providers alike: if
// an inCluster provider is gone the local mirror must stop too, never falling back to an implicit
// in-cluster identity that bypasses the authorization policy. It is
// idempotent across requeues while the target stays blocked; a later recovery re-declares the
// watches and re-snapshots.
func (r *GitTargetReconciler) stopSourceClusterMirror(target *configbutleraiv1alpha3.GitTarget) {
if r.EventRouter == nil || r.EventRouter.WatchManager == nil {
return
}
gitDest := types.NewResourceReference(target.Name, target.Namespace)
r.EventRouter.WatchManager.ForgetGitTargetDeclaration(gitDest)
}
// gitTargetAxes are the three data-plane observations a GitTarget publishes as conditions in their
// own right: what its watch streams are doing, whether its Git folder is safe to materialize, and
// whether what was rendered still matches live.
//
// They are OBSERVATIONS. None of them writes Ready, Reconciling or Stalled — that is
// gitTargetReadinessGates' job, and splitting the two is what stopped a later gate from silently
// overwriting an earlier gate's terminal verdict.
type gitTargetAxes struct {
Streams conditionValue
GitPath conditionValue
Render conditionValue
}
// dataPlaneObservation is everything one reconcile learned from the watch manager.
type dataPlaneObservation struct {
axes gitTargetAxes
streams watch.StreamSummary
// declare records whether the watch-plane owner has applied a plan for this GitTarget yet and
// how its last pass ended, so a target whose passes keep failing reads as failing rather than
// as an idle one whose axes happen to describe a surface nothing has observed.
declare watch.DeclareStatus
}
// observeDataPlane declares this GitTarget's streams, reads back what the watch manager knows, and
// projects the three data-plane axes. It mutates only the roll-up fields of status.
func (r *GitTargetReconciler) observeDataPlane(
target *configbutleraiv1alpha3.GitTarget,
sourceProvider *configbutleraiv1alpha3.KubeProvider,
forceRecheck bool,
log logr.Logger,
) dataPlaneObservation {
if r.EventRouter == nil || r.EventRouter.WatchManager == nil {
// No data plane is wired (tests, standalone). Nothing has been OBSERVED, which is not the
// same as "observed to be empty": the streams axis stays False and holds the target below
// Ready, and it says Progressing rather than NoResolvedTypes so the two are never confused.
streams := noResolvedStreamsSummary()
target.Status.Streams = streamsStatus(streams)
return dataPlaneObservation{
axes: gitTargetAxes{
Streams: conditionValue{
Status: metav1.ConditionFalse,
Reason: ReasonProgressing,
Message: "Data plane is not wired; streams have not been evaluated",
},
GitPath: gitPathAxis(watch.GitPathAcceptanceStatus{Accepted: true}),
Render: renderAxis(watch.RenderFidelityStatus{State: git.RenderFidelityTrue}),
},
streams: streams,
}
}
manager := r.EventRouter.WatchManager
gitDest := types.NewResourceReference(target.Name, target.Namespace).WithUID(string(target.UID))
// Submitting the declaration is all this does. The watch-plane owner runs the pass once the
// target has been quiet for its settle window, so this reconcile has no result to wait for —
// it reads back the LAST pass's outcome, which is the honest thing to project: the reconcile
// has never observed its own effect, it previously observed an intermediate state that merely
// looked more immediate.
manager.DeclareForGitTarget(
gitDest,
target.SourceCluster(),
sourceProvider.AuditRoute(),
target.EffectivePruneMode(),
forceRecheck,
)
observation := dataPlaneObservation{declare: manager.DeclareStatusForGitTarget(gitDest)}
if observation.declare.Failures > 0 {
log.V(1).Info("the last watch-plan pass for this GitTarget failed; it is dirty and will retry",
"gitDest", gitDest.String(), "failures", observation.declare.Failures,
"err", observation.declare.LastError)
}
observation.streams = manager.StreamSummaryForGitTarget(gitDest)
observation.axes = gitTargetAxes{
Streams: streamsAxis(observation.streams),
GitPath: gitPathAxis(manager.GitPathAcceptanceForGitTarget(gitDest)),
Render: renderAxis(manager.RenderFidelityForGitTarget(gitDest)),
}
target.Status.Streams = streamsStatus(observation.streams)
// Retention is read beside the others and projected the same way, but it feeds NO condition: a
// document kept by policy is the configured outcome, not a degraded target.
//
// A SUSPENDED target publishes none of it. The resync stops before the mark-and-sweep, so
// nothing is swept and nothing is counted — and a published zero would read as "converged"
// when it means "not measured". Absent already means "no resync has reported", which is
// exactly the truth here.
if target.Spec.Suspend {
target.Status.Retention = nil
} else {
target.Status.Retention = gitTargetRetentionStatus(manager.RetentionForGitTarget(gitDest))
}
return observation
}
// streamsAxis renders StreamsRunning.
//
// Zero resolved types reports TRUE — vacuously, and deliberately. It used to report
// False/NoResolvedTypes, which pinned the GitTarget at Reconciling=True with nothing left that
// could ever resolve. That is not an exotic state: it is step 3 of the documented setup flow
// (create the GitTarget, THEN the WatchRules) and the steady state of any target whose rules were
// deleted. kstatus never reached Current, `kubectl wait --for=condition=Ready` never returned, and
// the reconcile burned a pass plus a status write every 10 seconds for the life of the object.
// "I have nothing to mirror" is converged — Flux's Kustomization with an empty path reports the
// same. The count stays visible: status.streams.summary still reads "0/0" and the condition's
// reason is still NoResolvedTypes, so the zero is legible without being reported as a failure.
func streamsAxis(streams watch.StreamSummary) conditionValue {
status := metav1.ConditionFalse
if streams.Ready == streams.Total {
status = metav1.ConditionTrue
}
return conditionValue{Status: status, Reason: streams.Reason, Message: streams.Message}
}
// gitPathAxis renders GitPathAccepted from the data plane's write-plan verdict.
func gitPathAxis(gitPath watch.GitPathAcceptanceStatus) conditionValue {
if gitPath.Accepted {
message := gitPath.Message
if message == "" {
message = "GitTarget path accepted"
}
return conditionValue{
Status: metav1.ConditionTrue,
Reason: ReasonSucceeded,
Message: message,
}
}
value := conditionValue{Status: metav1.ConditionFalse, Reason: gitPath.Reason, Message: gitPath.Message}
if value.Reason == "" {
value.Reason = GitTargetReasonUnsupportedContent
}
if value.Message == "" {
value.Message = "GitTarget path refused"
}
return value
}
// renderAxis renders RenderMatchesLive. A divergence is terminal; an incomplete epoch is progress.
func renderAxis(renderFidelity watch.RenderFidelityStatus) conditionValue {
value := conditionValue{
Status: metav1.ConditionTrue,
Reason: ReasonSucceeded,
Message: "Every rendered token matches live",
}
switch renderFidelity.State {
case git.RenderFidelityFalse:
value = conditionValue{
Status: metav1.ConditionFalse,
Reason: GitTargetReasonRenderDoesNotMatchLive,
Message: renderFidelity.Message,
}
case git.RenderFidelityUnknown:
value = conditionValue{
Status: metav1.ConditionUnknown,
Reason: GitTargetReasonRenderRechecking,
Message: renderFidelity.Message,
}
case git.RenderFidelityTrue:
}
if renderFidelity.Reason != "" {
value.Reason = renderFidelity.Reason
}
if value.Message == "" {
value.Message = "Waiting for render-vs-live verification"
}
return value
}
// referenceReadiness is what the three objects a GitTarget REFERENCES say about themselves:
// destination-side (the GitBranch), source-config side (the KubeProvider), and the runtime
// reachability of the source cluster.
type referenceReadiness struct {
gitBranch conditionValue
kubeProvider conditionValue
sourceCluster conditionValue
}
// publishReferenceReadiness writes those three as conditions of their own and returns them, so the
// readiness trio can also take them into account. Publishing is all this does: nothing here
// writes Ready.
func (r *GitTargetReconciler) publishReferenceReadiness(
st *reconcileStatus,
target *configbutleraiv1alpha3.GitTarget,
gitBranch conditionValue,
sourceProvider *configbutleraiv1alpha3.KubeProvider,
) referenceReadiness {
refs := referenceReadiness{
gitBranch: gitBranch,
kubeProvider: kubeProviderReadiness(sourceProvider),
sourceCluster: r.observeSourceReachable(target, sourceProvider),
}
st.setValue(GitTargetConditionSourceClusterReachable, refs.sourceCluster)
st.setValue(GitTargetConditionGitBranchReady, refs.gitBranch)
st.setValue(GitTargetConditionKubeProviderReady, refs.kubeProvider)
return refs
}
// gitTargetReadinessGates contributes every GitTarget gate to the accumulator that owns the trio.
//
// THIS FUNCTION IS THE PRECEDENCE. Read it top to bottom: a stall always beats a progressing gate
// whatever the order, and within each group the first contributor wins, so the order of these calls
// is the order in which competing explanations are preferred. Adding a gate means adding a line
// here, in the position where its answer should outrank the ones below it — not calling a setter
// from wherever the gate happens to be evaluated.
func gitTargetReadinessGates(
rd *readiness,
observed dataPlaneObservation,
gitBranch, kubeProvider, sourceReach, publication conditionValue,
) {
// Terminal, most specific first. Each of these needs a human: the folder holds content the
// operator will not manage, a watch is refused, or what was written no longer matches live.
rd.stalledIf(observed.axes.GitPath.Status == metav1.ConditionFalse,
observed.axes.GitPath.Reason, observed.axes.GitPath.Message)
rd.stalledIf(observed.streams.Blocked > 0, observed.streams.Reason, observed.streams.Message)
rd.stalledIf(observed.axes.Render.Status == metav1.ConditionFalse,
observed.axes.Render.Reason, observed.axes.Render.Message)
// Transient. Each of these clears on its own and each has a Watches() edge that re-runs this
// reconcile when it does, so they are progress, never a stall. Dependencies before this
// object's own data plane: "your GitBranch is down" is a more actionable answer than
// "streams are still replaying", and it is usually the cause of the latter.
rd.progressingIf(gitBranch.Status == metav1.ConditionFalse, metav1.ConditionFalse,
gitBranch.Reason, gitBranch.Message)
rd.progressingIf(kubeProvider.Status == metav1.ConditionFalse, metav1.ConditionFalse,
kubeProvider.Reason, kubeProvider.Message)
rd.progressingIf(sourceReach.Status == metav1.ConditionFalse, metav1.ConditionFalse,
sourceReach.Reason, sourceReach.Message)
// An unconfirmed source has not been established at all, so Ready is Unknown rather than False.
rd.progressingIf(sourceReach.Status == metav1.ConditionUnknown, metav1.ConditionUnknown,
sourceReach.Reason, sourceReach.Message)
// The branch cannot publish. Ahead of this target's own data plane, because it explains it: a
// branch that paused intake keeps its streams waiting, and they say only that they wait.
rd.progressingIf(publication.Status == metav1.ConditionFalse, metav1.ConditionFalse,
publication.Reason, publication.Message)
rd.progressingIf(observed.axes.Render.Status == metav1.ConditionUnknown, metav1.ConditionFalse,
observed.axes.Render.Reason, observed.axes.Render.Message)
rd.progressingIf(observed.axes.Streams.Status != metav1.ConditionTrue, metav1.ConditionFalse,
observed.axes.Streams.Reason, observed.axes.Streams.Message)
// Last: the declaration has not landed, so every axis above describes a surface that has not
// been observed under the current configuration. Nothing else objected, but this target is not
// converged either. A pass that keeps FAILING says so — and says why — instead of reading as a
// target that is merely still settling, which is the difference between a mirror that is
// converging and one whose source cluster has been unreachable for an hour.
rd.progressingIf(observed.declare.Failures > 0, metav1.ConditionFalse,
GitTargetReasonWatchPlanFailing,
fmt.Sprintf("The watch plan for this GitTarget has failed %d time(s) and is being retried: %s",
observed.declare.Failures, observed.declare.LastError))
rd.progressingIf(observed.declare.Pending && observed.declare.Failures == 0,
metav1.ConditionFalse, ReasonProgressing,
"Stream declaration has not landed yet; the data-plane surface is not observable")
}
// requestRemoteRefresh asks this target's branch worker to re-prove where the branch is, if
// nothing has proved it within the interval.
//
// The worker decides whether to spend a connection: the age test is its own, because only it
// knows when it last pushed. A target sharing a branch with a busy one therefore costs nothing
// here, and what the worker learns reaches the GitBranch's status.remote.
//
// A suspended target refreshes too, for the reason its layout is still scanned: a stopped valve
// that also stopped looking would freeze what an operator reads at whatever Git looked like when
// someone panicked. Refreshing writes nothing, so there is no valve to respect.
func (r *GitTargetReconciler) requestRemoteRefresh(target *configbutleraiv1alpha3.GitTarget) {
if r.GitRefreshInterval <= 0 || r.WorkerManager == nil {
return
}
worker, exists := r.WorkerManager.WorkerForTarget(target)
if !exists || worker == nil {
// Nothing has been published for this target yet, so there is no checkout to refresh and
// the first publication reads the remote anyway.
return
}
worker.EnqueueRefresh(&git.RefreshRequest{
Target: types.NewResourceReference(target.Name, target.Namespace),
Path: target.Spec.Path,
MaxAge: r.GitRefreshInterval,
})
}
// ensureEventStream wires this GitTarget to the branch worker for the repository its GitProvider
// names NOW, and wires the route live events take to reach it.
//
// EnsureWorker is called on EVERY reconcile rather than only when no worker is in the slot: it is
// the one place that compares the slot's repository against repo, and a lookup that found a worker
// says nothing about WHICH repository that worker is about. It is a map read and a lock when
// nothing has changed.
func (r *GitTargetReconciler) ensureEventStream(
ctx context.Context,
target *configbutleraiv1alpha3.GitTarget,
req git.WorkerRequest,
log logr.Logger,
) (*reconcile.GitTargetEventStream, error) {
if r.WorkerManager == nil {
return nil, errors.New("worker manager is not configured")
}
if err := r.WorkerManager.EnsureWorker(context.Background(), req); err != nil {
return nil, fmt.Errorf("failed to ensure branch worker for GitBranch %s: %w", req.GitBranch, err)
}
// Asked on EVERY reconcile, not only on the one that did the replacing. The recovery is held
// by the worker manager until it has been delivered, so a delivery that failed is retried by
// whichever GitTarget on the branch reconciles next.
branch := git.BranchKeyFor(req.Repo.URL, req.Branch)
if r.WorkerManager.ReplacementPending(branch) &&
r.recoverBranchAfterReplacement(ctx, branch, req.GitBranch, log) {
r.WorkerManager.AcknowledgeReplacement(branch)
}
worker, ensured := r.WorkerManager.WorkerForGitBranch(req.GitBranch)
if !ensured {
return nil, fmt.Errorf("branch worker not found for GitBranch %s", req.GitBranch)
}
gitDest := types.NewResourceReference(target.Name, target.Namespace)
// A stream holds its worker directly, so one registered against a REPLACED worker would keep
// handing live events to a stopped goroutine's queue — accepted, never written, and silently
// dropped once it filled. The stream is thin and holds no state of its own, so re-pointing it
// is a fresh registration.
if existingStream := r.EventRouter.GetGitTargetEventStream(gitDest); existingStream != nil &&
existingStream.ServesWorker(worker) {
return existingStream, nil
}
stream := reconcile.NewGitTargetEventStream(target.Name, target.Namespace, worker, log)
r.EventRouter.RegisterGitTargetEventStream(gitDest, stream)
return stream, nil
}
// recoverBranchAfterReplacement re-establishes every GitTarget on a branch whose worker was just
// replaced, because the replacement leaves that branch's state describing a repository that is no
// longer the destination.
//
// The new worker starts with no clone, no base trust and an empty queue: whatever the old one held
// was computed against the old repository and is deliberately dropped. Nothing else asks for it
// back. The declaration is level-triggered and its inputs did not change, so the next pass is a
// no-op, the streams keep running, and an IDLE target would leave the new repository empty for as
// long as nothing happened to it. Forcing a recheck re-anchors the streams, and a stream that
// starts replays, which is what drives the mark-and-sweep that rebuilds the folder.
//
// It runs for every target on the branch and not only the one whose reconcile noticed. A worker
// serves them all, and the siblings have no reason of their own to reconcile.
//
// The record of which collections' snapshots settled goes the same way: the old worker published
// them, into the old repository, and the new worker's appliers must not be asked for anything until
// its own snapshots are in the new one. The worker holds them until this recovery is acknowledged.
//
// The render-fidelity verdicts go the same way and for the same reason: they say a folder matches
// live, about a folder in the other repository. They are INVALIDATED rather than forgotten —
// forgetting a target leaves it unregistered, which the gate reads as writable, so the writes
// would be admitted against the new repository before anything had looked at it.
//
// It reports whether the recovery was DELIVERED. A list that fails delivers nothing, and the
// request it was serving stays pending on the worker manager for the next reconcile to pick up:
// the alternative, spending the notification on an attempt that reached nobody, left the new
// repository with no target ever asked to populate it.
func (r *GitTargetReconciler) recoverBranchAfterReplacement(
ctx context.Context,
branch git.BranchKey,
gitBranch k8stypes.NamespacedName,
log logr.Logger,
) bool {
if r.EventRouter == nil || r.EventRouter.WatchManager == nil {
return false
}
var targets configbutleraiv1alpha3.GitTargetList
if err := r.List(ctx, &targets); err != nil {
log.Error(err, "Could not re-establish the branch after its worker was replaced; it stays pending",
"branch", branch.String(), "gitBranch", gitBranch.String())
return false
}
gate := r.WorkerManager.RenderFidelityGate()
recovered := 0
for i := range targets.Items {
affected := &targets.Items[i]
if !git.WritesThrough(affected, gitBranch) {
continue
}
if !affected.DeletionTimestamp.IsZero() {
continue
}
ref := types.NewResourceReference(affected.Name, affected.Namespace).WithUID(string(affected.UID))
gate.Invalidate(ref)
r.EventRouter.WatchManager.RestartInitialSnapshots(ref)
r.EventRouter.WatchManager.RequestRecheckForGitTarget(ref)
recovered++
}
log.Info("Branch worker replaced; re-establishing every GitTarget on the branch",
"branch", branch.String(), "gitBranch", gitBranch.String(), "gitTargets", recovered)
return true
}
// gitDestination is what a GitTarget's spec.gitBranchRef resolves to, read ONCE for the whole
// reconcile: the GitBranch, and that GitBranch's GitProvider. That one pair answers the Validated
// gate, projects GitBranchReady, names the repository the branch worker has to be about, and the
// binding the applier claim is checked against. Reading them several times let those disagree about
// which repository this target points at, which is the disagreement the worker's repository
// identity exists to prevent.
type gitDestination struct {
// key is the referenced GitBranch; zero when spec.gitBranchRef is not set.
key k8stypes.NamespacedName