-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathwatchrule_controller.go
More file actions
533 lines (482 loc) · 18.2 KB
/
Copy pathwatchrule_controller.go
File metadata and controls
533 lines (482 loc) · 18.2 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
// SPDX-License-Identifier: Apache-2.0
package controller
import (
"context"
"fmt"
"time"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/wait"
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/handler"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/predicate"
ctrlreconcile "sigs.k8s.io/controller-runtime/pkg/reconcile"
configbutleraiv1alpha3 "github.com/ConfigButler/gitops-reverser/api/v1alpha3"
"github.com/ConfigButler/gitops-reverser/internal/rulestore"
"github.com/ConfigButler/gitops-reverser/internal/watch"
)
// WatchRule status condition reasons.
const (
WatchRuleReasonValidating = "Validating"
WatchRuleReasonGitProviderNotFound = "GitRepoConfigNotFound"
WatchRuleReasonGitRepoConfigNotReady = "GitRepoConfigNotReady"
WatchRuleReasonAccessDenied = "AccessDenied"
WatchRuleReasonGitTargetNotFound = "GitTargetNotFound"
WatchRuleReasonGitDestinationInvalid = "GitDestinationInvalid"
WatchRuleReasonReady = "Ready"
WatchRuleReasonResourcesResolved = "Resolved"
WatchRuleReasonUnresolvedResources = "UnresolvedResources"
)
// WatchRuleReconciler reconciles a WatchRule object.
type WatchRuleReconciler struct {
client.Client
Scheme *runtime.Scheme
RuleStore *rulestore.RuleStore
WatchManager WatchManagerInterface
}
// +kubebuilder:rbac:groups=configbutler.ai,resources=watchrules,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=configbutler.ai,resources=watchrules/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=configbutler.ai,resources=gittargets,verbs=get;list;watch
// +kubebuilder:rbac:groups=configbutler.ai,resources=gitproviders,verbs=get;list;watch
// +kubebuilder:rbac:groups="",resources=namespaces,verbs=get;list;watch
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
func (r *WatchRuleReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
log := logf.FromContext(ctx).WithName("WatchRuleReconciler")
log.Info("Starting reconciliation", "namespacedName", req.NamespacedName)
// Fetch the WatchRule instance
var watchRule configbutleraiv1alpha3.WatchRule
//nolint:nestif // Deletion handling requires nested error checks
if err := r.Get(ctx, req.NamespacedName, &watchRule); err != nil {
if client.IgnoreNotFound(err) == nil {
log.Info("WatchRule not found, was likely deleted", "namespacedName", req.NamespacedName)
// Resource was deleted. Remove it from the store.
r.RuleStore.Delete(req.NamespacedName)
log.Info("WatchRule deleted, removed from store", "name", req.Name, "namespace", req.Namespace)
// Trigger WatchManager reconciliation for deletion
if r.WatchManager != nil {
if err := r.WatchManager.ReconcileForRuleChange(ctx); err != nil {
log.Error(err, "Failed to reconcile watch manager after rule deletion")
// Don't fail the reconciliation - log and continue
}
}
return ctrl.Result{}, nil
}
log.Error(err, "unable to fetch WatchRule", "namespacedName", req.NamespacedName)
return ctrl.Result{}, err
}
log.Info("Starting WatchRule validation",
"name", watchRule.Name,
"namespace", watchRule.Namespace,
"target", watchRule.Spec.TargetRef,
"generation", watchRule.Generation,
"resourceVersion", watchRule.ResourceVersion)
watchRule.Status.ObservedGeneration = watchRule.Generation
// Set initial validating status
log.Info("Setting initial validating status")
r.setCondition(&watchRule, metav1.ConditionUnknown, //nolint:lll // Descriptive message
WatchRuleReasonValidating, "Validating WatchRule configuration...")
r.setTypedCondition(
&watchRule,
ConditionTypeStreamsRunning,
metav1.ConditionUnknown,
GitTargetStreamsRunningReasonNotReady,
"Blocked by validation; streams not evaluated",
)
r.setTypedCondition(
&watchRule,
ConditionTypeGitTargetReady,
metav1.ConditionUnknown,
ReasonProgressing,
"Blocked by validation; GitTarget not evaluated",
)
r.setTypedCondition(
&watchRule,
ConditionTypeReconciling,
metav1.ConditionTrue,
ReasonChecking,
"Validating WatchRule",
)
r.setTypedCondition(
&watchRule,
ConditionTypeStalled,
metav1.ConditionFalse,
ReasonChecking,
"WatchRule is not stalled",
)
// Route by configuration surface (Target is required now)
if watchRule.Spec.TargetRef.Name == "" {
r.setCondition(
&watchRule,
metav1.ConditionFalse,
WatchRuleReasonGitDestinationInvalid,
"Target.name must be specified",
)
r.setTypedCondition(
&watchRule,
ConditionTypeGitTargetReady,
metav1.ConditionFalse,
WatchRuleReasonGitDestinationInvalid,
"Target.name must be specified",
)
r.setRuleStalled(&watchRule, WatchRuleReasonGitDestinationInvalid, "Target.name must be specified")
return r.updateStatusAndRequeue(ctx, &watchRule, RequeueShortInterval)
}
return r.reconcileWatchRuleViaTarget(ctx, &watchRule)
}
// reconcileWatchRuleViaTarget validates and stores a WatchRule that references a GitTarget.
func (r *WatchRuleReconciler) reconcileWatchRuleViaTarget(
ctx context.Context,
watchRule *configbutleraiv1alpha3.WatchRule,
) (ctrl.Result, error) {
log := logf.FromContext(ctx).WithName("reconcileWatchRuleViaTarget")
// Determine target namespace (same as WatchRule's namespace)
targetNS := watchRule.Namespace
// Fetch GitTarget
var target configbutleraiv1alpha3.GitTarget
targetKey := types.NamespacedName{Name: watchRule.Spec.TargetRef.Name, Namespace: targetNS}
if err := r.Get(ctx, targetKey, &target); err != nil {
log.Error(err, "Failed to get referenced GitTarget",
"gitTargetName", watchRule.Spec.TargetRef.Name,
"gitTargetNamespace", targetNS)
r.setCondition(
watchRule,
metav1.ConditionFalse,
WatchRuleReasonGitTargetNotFound,
fmt.Sprintf(
"Referenced GitTarget '%s/%s' not found: %v",
targetNS,
watchRule.Spec.TargetRef.Name,
err,
),
)
r.setTypedCondition(
watchRule,
ConditionTypeGitTargetReady,
metav1.ConditionFalse,
WatchRuleReasonGitTargetNotFound,
"Referenced GitTarget not found",
)
r.setRuleStalled(watchRule, WatchRuleReasonGitTargetNotFound, "Referenced GitTarget not found")
return r.updateStatusAndRequeue(ctx, watchRule, RequeueShortInterval)
}
r.setGitTargetReadyCondition(watchRule, target)
// Resolve the GitProvider named by the target. A GitProviderReference is a
// name-only reference to a GitProvider in the GitTarget's own namespace.
providerName := target.Spec.ProviderRef.Name
providerNS := target.Namespace // GitProvider is namespace-local to the GitTarget
var provider configbutleraiv1alpha3.GitProvider
providerKey := types.NamespacedName{Name: providerName, Namespace: providerNS}
if err := r.Get(ctx, providerKey, &provider); err != nil {
log.Error(err, "Failed to resolve GitProvider from GitTarget",
"gitProviderName", providerName, "gitProviderNamespace", providerNS)
r.setCondition(
watchRule,
metav1.ConditionFalse,
WatchRuleReasonGitProviderNotFound, // Reuse reason for now
fmt.Sprintf(
"GitProvider '%s/%s' (from GitTarget) not found: %v",
providerNS,
providerName,
err,
),
)
r.setTypedCondition(
watchRule,
ConditionTypeGitTargetReady,
metav1.ConditionFalse,
WatchRuleReasonGitProviderNotFound,
"Referenced GitProvider not found",
)
r.setRuleStalled(watchRule, WatchRuleReasonGitProviderNotFound, "Referenced GitProvider not found")
return r.updateStatusAndRequeue(ctx, watchRule, RequeueShortInterval)
}
// Ready check (GitProvider doesn't have status conditions yet in my implementation? I added them)
// I added GitProviderStatus with Conditions.
// TODO: Check GitProvider readiness. For now assume ready if found.
// Add rule to store with GitTarget reference and resolved values
r.RuleStore.AddOrUpdateWatchRule(
*watchRule,
target.Name, targetNS, // GitTarget reference (replaces GitDestination)
provider.Name, providerNS, // GitProvider reference (replaces GitRepoConfig)
target.Spec.Branch,
target.Spec.Path,
)
// Trigger WatchManager reconciliation for new/updated rule
if r.WatchManager != nil {
if err := r.WatchManager.ReconcileForRuleChange(ctx); err != nil {
log.Error(err, "Failed to reconcile watch manager after rule update")
// Don't fail the reconciliation - the rule is valid, just log the watch manager issue
}
r.setResourceResolutionCondition(ctx, watchRule)
r.setStreamsReadyCondition(watchRule, r.WatchManager.StreamSummaryForWatchRule(*watchRule))
} else {
r.setStreamsReadyCondition(watchRule, noResolvedStreamsSummary())
}
log.Info("WatchRule reconciliation via GitTarget successful", "name", watchRule.Name)
return r.setReadyAndUpdateStatusWithTarget(ctx, watchRule, targetNS)
}
// setReadyAndUpdateStatusWithTarget sets Ready with target message and updates status with retry.
func (r *WatchRuleReconciler) setReadyAndUpdateStatusWithTarget(
ctx context.Context,
watchRule *configbutleraiv1alpha3.WatchRule,
targetNS string,
) (ctrl.Result, error) {
msg := fmt.Sprintf(
"WatchRule is ready and monitoring resources via GitTarget '%s/%s'",
targetNS,
watchRule.Spec.TargetRef.Name,
)
r.setRuleKstatus(watchRule, msg)
if err := r.updateStatusWithRetry(ctx, watchRule); err != nil {
return ctrl.Result{}, err
}
if conditionIsFalse(watchRule.Status.Conditions, ConditionTypeResourcesResolved) {
return ctrl.Result{RequeueAfter: RequeueShortInterval}, nil
}
if !conditionIsTrue(watchRule.Status.Conditions, ConditionTypeGitTargetReady) {
return ctrl.Result{RequeueAfter: RequeueStreamSettleInterval}, nil
}
if !conditionIsTrue(watchRule.Status.Conditions, ConditionTypeStreamsRunning) {
return ctrl.Result{RequeueAfter: RequeueStreamSettleInterval}, nil
}
return ctrl.Result{RequeueAfter: RequeueMediumInterval}, nil
}
// setCondition sets or updates the Ready condition.
func (r *WatchRuleReconciler) setCondition( //nolint:lll // Function signature
watchRule *configbutleraiv1alpha3.WatchRule, status metav1.ConditionStatus, reason, message string) {
r.setTypedCondition(watchRule, ConditionTypeReady, status, reason, message)
}
func (r *WatchRuleReconciler) setGitTargetReadyCondition(
watchRule *configbutleraiv1alpha3.WatchRule,
target configbutleraiv1alpha3.GitTarget,
) {
ready := gitTargetReadyCondition(target)
r.setTypedCondition(watchRule, ConditionTypeGitTargetReady, ready.Status, ready.Reason, ready.Message)
}
func (r *WatchRuleReconciler) setResourceResolutionCondition(
ctx context.Context,
watchRule *configbutleraiv1alpha3.WatchRule,
) {
resolved, message := r.WatchManager.ResolveWatchRuleResources(ctx, *watchRule)
status := metav1.ConditionFalse
reason := WatchRuleReasonUnresolvedResources
if resolved {
status = metav1.ConditionTrue
reason = WatchRuleReasonResourcesResolved
}
r.setTypedCondition(watchRule, ConditionTypeResourcesResolved, status, reason, message)
}
func (r *WatchRuleReconciler) setStreamsReadyCondition(
watchRule *configbutleraiv1alpha3.WatchRule,
streams watch.StreamSummary,
) {
watchRule.Status.Streams = watchRuleStreamsStatus(streams)
r.setTypedCondition(
watchRule,
ConditionTypeStreamsRunning,
streamConditionStatus(streams),
streams.Reason,
streams.Message,
)
}
func (r *WatchRuleReconciler) setRuleStalled(
watchRule *configbutleraiv1alpha3.WatchRule,
reason string,
message string,
) {
r.setTypedCondition(watchRule, ConditionTypeReady, metav1.ConditionFalse, reason, message)
r.setTypedCondition(watchRule, ConditionTypeReconciling, metav1.ConditionFalse, reason, "Reconciliation is stalled")
r.setTypedCondition(watchRule, ConditionTypeStalled, metav1.ConditionTrue, reason, message)
}
func (r *WatchRuleReconciler) setRuleKstatus(
watchRule *configbutleraiv1alpha3.WatchRule,
readyMessage string,
) {
applyRuleKstatus(
watchRule.Status.Conditions,
readyMessage,
WatchRuleReasonReady,
"WatchRule is not stalled",
func(conditionType string, status metav1.ConditionStatus, reason, message string) {
r.setTypedCondition(watchRule, conditionType, status, reason, message)
},
func(reason, message string) {
r.setRuleStalled(watchRule, reason, message)
},
)
}
func (r *WatchRuleReconciler) setTypedCondition(
watchRule *configbutleraiv1alpha3.WatchRule,
conditionType string,
status metav1.ConditionStatus,
reason string,
message string,
) {
watchRule.Status.Conditions = upsertCondition(
watchRule.Status.Conditions,
conditionType,
status,
reason,
message,
watchRule.Generation,
)
}
func conditionIsFalse(conditions []metav1.Condition, conditionType string) bool {
for _, condition := range conditions {
if condition.Type == conditionType {
return condition.Status == metav1.ConditionFalse
}
}
return false
}
// updateStatusAndRequeue updates the status and returns requeue result.
func (r *WatchRuleReconciler) updateStatusAndRequeue( //nolint:lll // Function signature
ctx context.Context, watchRule *configbutleraiv1alpha3.WatchRule, requeueAfter time.Duration) (ctrl.Result, error) {
if err := r.updateStatusWithRetry(ctx, watchRule); err != nil {
return ctrl.Result{}, err
}
return ctrl.Result{RequeueAfter: requeueAfter}, nil
}
// updateStatusWithRetry updates the status with retry logic to handle race conditions
//
//nolint:dupl // Similar retry logic pattern used across controllers
func (r *WatchRuleReconciler) updateStatusWithRetry(
ctx context.Context,
watchRule *configbutleraiv1alpha3.WatchRule,
) error {
log := logf.FromContext(ctx).WithName("updateStatusWithRetry")
log.Info("Starting status update with retry",
"name", watchRule.Name,
"namespace", watchRule.Namespace,
"conditionsCount", len(watchRule.Status.Conditions))
return wait.ExponentialBackoff(wait.Backoff{
Duration: RetryInitialDuration,
Factor: RetryBackoffFactor,
Jitter: RetryBackoffJitter,
Steps: RetryMaxSteps,
}, func() (bool, error) {
log.Info("Attempting status update")
// Get the latest version of the resource
latest := &configbutleraiv1alpha3.WatchRule{}
key := client.ObjectKeyFromObject(watchRule)
if err := r.Get(ctx, key, latest); err != nil {
if apierrors.IsNotFound(err) {
log.Info("Resource was deleted, nothing to update")
return true, nil
}
log.Error(err, "Failed to get latest resource version")
return false, err
}
log.Info("Got latest resource version",
"generation", latest.Generation,
"resourceVersion", latest.ResourceVersion)
// Copy our status to the latest version
latest.Status = watchRule.Status
log.Info("Attempting to update status",
"conditionsCount", len(latest.Status.Conditions))
// Attempt to update
if err := r.Status().Update(ctx, latest); err != nil {
if apierrors.IsConflict(err) {
log.Info("Resource version conflict, retrying")
return false, nil
}
log.Error(err, "Failed to update status")
return false, err
}
log.Info("Status update successful")
return true, nil
})
}
// SetupWithManager sets up the controller with the Manager.
func (r *WatchRuleReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&configbutleraiv1alpha3.WatchRule{}).
// GenerationChangedPredicate keeps these watches reacting to a freshly
// applied or spec-changed dependency while ignoring the status-only
// updates the controllers write themselves — without it every GitTarget
// or GitProvider heartbeat would re-list and re-enqueue all WatchRules.
Watches(
&configbutleraiv1alpha3.GitTarget{},
handler.EnqueueRequestsFromMapFunc(r.gitTargetToWatchRules),
builder.WithPredicates(predicate.GenerationChangedPredicate{}),
).
Watches(
&configbutleraiv1alpha3.GitProvider{},
handler.EnqueueRequestsFromMapFunc(r.gitProviderToWatchRules),
builder.WithPredicates(predicate.GenerationChangedPredicate{}),
).
Named("watchrule").
Complete(r)
}
// gitTargetToWatchRules maps a GitTarget event to every WatchRule in the
// GitTarget's namespace that references it. WatchRule.spec.targetRef is a
// LocalTargetReference, so candidates only live in the same namespace as the
// GitTarget.
func (r *WatchRuleReconciler) gitTargetToWatchRules(
ctx context.Context,
obj client.Object,
) []ctrlreconcile.Request {
var rules configbutleraiv1alpha3.WatchRuleList
if err := r.List(ctx, &rules, client.InNamespace(obj.GetNamespace())); err != nil {
logDependencyListError(ctx, err, "WatchRules", obj)
return nil
}
var requests []ctrlreconcile.Request
for i := range rules.Items {
rule := &rules.Items[i]
if rule.Spec.TargetRef.Name != obj.GetName() {
continue
}
requests = append(requests, ctrlreconcile.Request{
NamespacedName: types.NamespacedName{Name: rule.Name, Namespace: rule.Namespace},
})
}
return requests
}
// gitProviderToWatchRules maps a GitProvider event to every WatchRule (in the
// GitProvider's namespace) whose referenced GitTarget points at this provider.
// Mirrors the equivalent helper on ClusterWatchRuleReconciler so that an
// arriving provider doesn't have to wait for a separate GitTarget event to
// reach the rule.
func (r *WatchRuleReconciler) gitProviderToWatchRules(
ctx context.Context,
obj client.Object,
) []ctrlreconcile.Request {
var targets configbutleraiv1alpha3.GitTargetList
if err := r.List(ctx, &targets, client.InNamespace(obj.GetNamespace())); err != nil {
logDependencyListError(ctx, err, "GitTargets", obj)
return nil
}
matchingTargets := make(map[string]struct{})
for i := range targets.Items {
t := &targets.Items[i]
if t.Spec.ProviderRef.Name == obj.GetName() {
matchingTargets[t.Name] = struct{}{}
}
}
if len(matchingTargets) == 0 {
return nil
}
var rules configbutleraiv1alpha3.WatchRuleList
if err := r.List(ctx, &rules, client.InNamespace(obj.GetNamespace())); err != nil {
logDependencyListError(ctx, err, "WatchRules", obj)
return nil
}
var requests []ctrlreconcile.Request
for i := range rules.Items {
rule := &rules.Items[i]
if _, ok := matchingTargets[rule.Spec.TargetRef.Name]; !ok {
continue
}
requests = append(requests, ctrlreconcile.Request{
NamespacedName: types.NamespacedName{Name: rule.Name, Namespace: rule.Namespace},
})
}
return requests
}