Repository navigation
Expand file tree
/
Copy pathgittarget_controller.go
More file actions
1765 lines (1627 loc) · 78.1 KB
/
Copy pathgittarget_controller.go
File metadata and controls
1765 lines (1627 loc) · 78.1 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"
"path/filepath"
"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/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
GitTargetReasonProviderNotFound = "ProviderNotFound"
GitTargetReasonBranchNotAllowed = "BranchNotAllowed"
// GitTargetReasonParentBranchNotFound is the Ready reason for a write branch that cannot be
// created: the remote carries neither it nor the spec.parentBranch it would start from.
GitTargetReasonParentBranchNotFound = "ParentBranchNotFound"
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
// remotePublications is what each GitTarget last wrote to status.remote: when, and about which
// repository. It is internal by design; see remotePublicationLedger.
remotePublications remotePublicationLedger
// clock is the source of "now" for the publication ledger, so a test can hold time still
// across a reconcile that is measured in wall clock. Nil means time.Now.
clock func() time.Time
}
// clockNow is the reconciler's wall clock.
func (r *GitTargetReconciler) clockNow() time.Time {
if r.clock != nil {
return r.clock()
}
return time.Now()
}
// +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="",resources=secrets,verbs=get;create;update
// +kubebuilder:rbac:groups="",resources=events,verbs=create;patch
// 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)
// The branch worker keeps the writes decided while the parent is missing and publishes them when
// it returns, so nothing has to be re-derived; this only reports the progress.
recoveringParent := r.parentRecovering(&target, target.Namespace)
publication := r.branchPublication(&target, target.Namespace)
providerNS := target.Namespace
// One read of the GitProvider for everything below it; see getGitProvider.
gitProvider, providerErr := r.getGitProvider(ctx, providerNS, target.Spec.GitProviderRef.Name)
if providerErr != nil {
return ctrl.Result{}, providerErr
}
// awaitingAnswer: this reconcile is about to ask the remote where the branch is, so the answer
// lands after the status write below. See requeueForRemoteAnswer.
awaitingAnswer := r.publishGitObservations(st, &target, providerNS, repoIdentityOf(gitProvider))
// Ahead of every gate, for the reason the layout stanza above is: the join series 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.
telemetry.RecordBranchTarget(
target.Namespace, target.Name, providerNS, target.Spec.GitProviderRef.Name, target.Spec.Branch,
target.SourceCluster())
validated, validationMsg, validationErr := r.evaluateValidatedGate(ctx, st, &target, providerNS, gitProvider)
if validationErr != nil {
return ctrl.Result{}, validationErr
}
if !validated {
// A remote-source GitTarget whose kubeConfig stopped validating (Secret deleted, key gone,
// or contents now unsafe/unparseable) must have its data plane STOPPED, not merely marked
// blocked. Otherwise its watches keep mirroring the remote 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. A
// local GitTarget names no source cluster, so its streams are left untouched.
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,
})
}
// 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, providerNS, repoIdentityOf(gitProvider), log)
if !wired {
return r.stall(ctx, st, blockedGate{
reason: GitTargetReadyReasonWorkerUnavailable,
message: wiringMessage,
blocked: "Blocked by worker wiring failure",
})
}
// The refresher's trigger 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, providerNS)
// One read of the source ClusterProvider serves everything below it: the audit route captured on
// Declare and the ClusterProviderReady projection. Reading it twice invited the two to disagree.
sourceProvider, sourceProviderErr := r.resolveSourceClusterProvider(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, providerNS, gitProvider, sourceProvider)
rd := newGitTargetReadiness()
convergeAsSuspended(rd, &target)
gitTargetReadinessGates(rd, observed, r.parentBranchReadiness(&target, providerNS, repoIdentityOf(gitProvider)),
refs.gitProvider, refs.clusterProvider, refs.sourceCluster, publicationCondition(publication))
parentRecoveryReadiness(rd, recoveringParent)
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(requeueForRemoteAnswer(gitTargetRequeue(rd), awaitingAnswer))
// TEMPORARY at Info, while Failure A is open. The data plane can converge and this status not
// follow it: a run has shown the render gate reaching True and both this GitTarget and every
// WatchRule on it still publishing "Rechecking" two minutes later, with no dropped reconcile
// request to explain it. 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.
log.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
}
// 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
}
// 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()
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
if cadence == 0 {
cadence = RequeueSteadyInterval
}
return ctrl.Result{RequeueAfter: st.requeueAfter(cadence)}, nil
}
// observeSourceReachable projects the source cluster's runtime reachability.
//
// A GitTarget with no source cluster 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 a local target and Unknown only for a remote one.
func (r *GitTargetReconciler) observeSourceReachable(
target *configbutleraiv1alpha3.GitTarget,
) conditionValue {
reach := watch.SourceClusterReachableStatus{State: "True", Reason: "LocalCluster"}
if !target.IsLocalSource() {
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,
providerNS string,
provider *configbutleraiv1alpha3.GitProvider,
) (bool, string, error) {
validated, message, reason := validateProviderAndBranch(target, providerNS, provider)
if !validated {
st.set(GitTargetConditionValidated, metav1.ConditionFalse, reason, message)
return false, fmt.Sprintf("Validated gate failed: %s", reason), nil
}
conflict, conflictMsg, conflictReason, conflictErr := r.checkForConflicts(ctx, target, providerNS)
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 connectivity inputs (kubeConfig) are validated on the referenced
// ClusterProvider now, not here — the GitTarget only NAMES its source cluster. The
// ClusterProvider's readiness is projected onto the GitTarget as a separate condition.
// Namespace authorization: a GitTarget may reference a ClusterProvider only from a namespace
// its spec.accessFrom admits. 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,
"Provider, branch, 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
}
// 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,
providerNS string,
repo git.RepoIdentity,
log logr.Logger,
) (bool, string) {
if r.EventRouter == nil {
return true, ""
}
if _, err := r.ensureEventStream(ctx, target, providerNS, repo, 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 ClusterProvider that was deleted (including the reserved
// "default" for the LOCAL cluster) — can never keep an active mirror running behind a
// Validated=False status. It applies to local AND remote targets: a local target references the
// "default" ClusterProvider, so if that 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.ClusterProvider,
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 GitProvider), source-config side (the ClusterProvider), and the runtime
// reachability of the source cluster.
type referenceReadiness struct {
gitProvider conditionValue
clusterProvider 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,
providerNS string,
gitProvider *configbutleraiv1alpha3.GitProvider,
sourceProvider *configbutleraiv1alpha3.ClusterProvider,
) referenceReadiness {
refs := referenceReadiness{
gitProvider: gitProviderReadiness(target, providerNS, gitProvider),
clusterProvider: clusterProviderReadiness(sourceProvider),
sourceCluster: r.observeSourceReachable(target),
}
st.setValue(GitTargetConditionSourceClusterReachable, refs.sourceCluster)
st.setValue(GitTargetConditionGitProviderReady, refs.gitProvider)
st.setValue(GitTargetConditionClusterProviderReady, refs.clusterProvider)
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,
parent, provider, clusterProvider, sourceReach, publication conditionValue,
) {
// Terminal, most specific first. Each of these needs a human: the folder holds content the
// operator will not manage, the write branch has no parent to be created from, 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(parent.Status == metav1.ConditionFalse, parent.Reason, parent.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 GitProvider is down" is a more actionable answer than
// "streams are still replaying", and it is usually the cause of the latter.
rd.progressingIf(provider.Status == metav1.ConditionFalse, metav1.ConditionFalse,
provider.Reason, provider.Message)
rd.progressingIf(clusterProvider.Status == metav1.ConditionFalse, metav1.ConditionFalse,
clusterProvider.Reason, clusterProvider.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")
}
// parentBranchReadiness reports whether the write branch can be created: False when the last
// look at the remote found neither the write branch nor the parent it would be created from. That
// parent is the configured spec.parentBranch, or, when it is omitted, the remote's default branch:
// a repository that is not empty but whose HEAD names no branch it carries refuses as well, because
// starting there would make an orphan.
//
// It is read from the branch worker's remote observation, so it costs no round trip and holds
// with periodic refresh disabled: every fetch on the write path records the same observation. The
// observation counts only when it was made under the parent configured now, and only for the
// repository the GitProvider names now (a repoint proves nothing about the new one).
func (r *GitTargetReconciler) parentBranchReadiness(
target *configbutleraiv1alpha3.GitTarget,
providerNS string,
repo git.RepoIdentity,
) conditionValue {
ok := conditionValue{Status: metav1.ConditionTrue, Reason: GitTargetReasonOK}
observed, seen := r.observeRemote(target, providerNS)
if !seen || observed.ParentState != git.ParentMissing ||
observed.ParentRequested != target.Spec.ParentBranch || differentRepository(observed.Repo, repo) {
return ok
}
return conditionValue{
Status: metav1.ConditionFalse,
Reason: GitTargetReasonParentBranchNotFound,
Message: parentBranchNotFoundMessage(target, observed.ParentBranch),
}
}
// parentBranchNotFoundMessage says which parent is missing and what fixes it.
func parentBranchNotFoundMessage(target *configbutleraiv1alpha3.GitTarget, missing string) string {
switch {
case target.Spec.ParentBranch != "":
return fmt.Sprintf(
"Branch '%s' does not exist on the remote, and neither does its parent branch '%s' to create "+
"it from; nothing is written until one of them exists",
target.Spec.Branch, target.Spec.ParentBranch)
case missing != "":
return fmt.Sprintf(
"Branch '%s' does not exist on the remote, and the remote's default branch (HEAD -> '%s') does "+
"not exist either; fix the remote's HEAD or set spec.parentBranch. Nothing is written until then",
target.Spec.Branch, missing)
default:
return fmt.Sprintf(
"Branch '%s' does not exist on the remote, and the remote has no default branch to create it "+
"from; set the remote's HEAD or spec.parentBranch. Nothing is written until then",
target.Spec.Branch)
}
}
// 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 still gets its status renewed, because the worker reports what it knows before it
// skips.
//
// 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,
providerNS string,
) {
if r.GitRefreshInterval <= 0 || r.WorkerManager == nil {
return
}
worker, exists := r.WorkerManager.GetWorkerForTarget(
target.Spec.GitProviderRef.Name, providerNS, target.Spec.Branch)
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,
})
}
// publishGitObservations writes what the data plane last read about this target's folder and
// about its branch on the remote: status.placement with the LayoutResolved condition, and
// status.remote.
//
// It runs ahead of every gate, so a target held unready still shows both. That ordering is the
// point rather than a convenience: these stanzas exist to explain a refused or surprising write,
// and a projection that ran only on the happy path would be missing exactly when it is wanted.
func (r *GitTargetReconciler) publishGitObservations(
st *reconcileStatus,
target *configbutleraiv1alpha3.GitTarget,
providerNS string,
repo git.RepoIdentity,
) bool {
layout, scanned := r.observeLayout(target)
publishLayout(st, target, layout, scanned)
now := r.clockNow()
remote, remoteSeen := r.observeRemote(target, providerNS)
r.publishRemote(st, target, remote, remoteSeen, repo, now)
// Whether the refresh this reconcile goes on to enqueue will actually reach the remote: the
// worker spends a connection only when what it holds is older than the interval configured.
return r.GitRefreshInterval > 0 && (!remoteSeen || remote.Age(now) >= r.GitRefreshInterval)
}
// requeueForRemoteAnswer shortens the cadence for a target that has just ASKED the remote where
// its branch is.
//
// It is the one piece of scheduling this status field gets, and it exists because the refresh is
// enqueued during the reconcile: the worker answers moments later, after the status write, so the
// answer would otherwise sit undelivered until the next steady tick. An idle target would then
// spend a connection every interval and publish what it learned a whole tick late — visible to an
// operator as a target that follows a foreign push ten minutes after noticing it.
//
// Nothing else is threaded anywhere. A reconcile that asked nothing keeps its own cadence, and no
// early return has to carry a deadline.
func requeueForRemoteAnswer(cadence time.Duration, asked bool) time.Duration {
if asked && RemotePublicationInterval < cadence {
return RemotePublicationInterval
}
return cadence
}
// 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,
providerNS string,
repo git.RepoIdentity,
log logr.Logger,
) (*reconcile.GitTargetEventStream, error) {
if r.WorkerManager == nil {
return nil, errors.New("worker manager is not configured")
}
err := r.WorkerManager.EnsureWorker(
context.Background(),
target.Spec.GitProviderRef.Name,
providerNS,
target.Spec.Branch,
repo,
target.Spec.ParentBranch,
)
if err != nil {
return nil, fmt.Errorf(
"failed to ensure branch worker for provider=%s/%s branch=%s: %w",
providerNS,
target.Spec.GitProviderRef.Name,
target.Spec.Branch,
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.BranchKey{
RepoNamespace: providerNS,
RepoName: target.Spec.GitProviderRef.Name,
Branch: target.Spec.Branch,
}
if r.WorkerManager.ReplacementPending(branch) &&
r.recoverBranchAfterReplacement(ctx, branch, log) {
r.WorkerManager.AcknowledgeReplacement(branch)
}
worker, ensured := r.WorkerManager.GetWorkerForTarget(
target.Spec.GitProviderRef.Name,
providerNS,
target.Spec.Branch,
)
if !ensured {
return nil, fmt.Errorf(
"branch worker not found for provider=%s/%s branch=%s",