forked from rancher/fleet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitjob_controller.go
More file actions
1378 lines (1201 loc) · 44.9 KB
/
gitjob_controller.go
File metadata and controls
1378 lines (1201 loc) · 44.9 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
package reconciler
import (
"context"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"reflect"
"sort"
"strings"
"time"
"github.com/go-logr/logr"
"github.com/reugn/go-quartz/quartz"
"github.com/rancher/fleet/internal/cmd/controller/finalize"
"github.com/rancher/fleet/internal/cmd/controller/imagescan"
ctrlquartz "github.com/rancher/fleet/internal/cmd/controller/quartz"
"github.com/rancher/fleet/internal/cmd/controller/reconciler"
"github.com/rancher/fleet/internal/config"
"github.com/rancher/fleet/internal/metrics"
v1alpha1 "github.com/rancher/fleet/pkg/apis/fleet.cattle.io/v1alpha1"
"github.com/rancher/fleet/pkg/durations"
"github.com/rancher/fleet/pkg/sharding"
"github.com/rancher/wrangler/v3/pkg/condition"
"github.com/rancher/wrangler/v3/pkg/genericcondition"
"github.com/rancher/wrangler/v3/pkg/kstatus"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
errutil "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/client-go/tools/events"
"k8s.io/client-go/util/retry"
"sigs.k8s.io/cli-utils/pkg/kstatus/status"
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/controller"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)
const (
defaultPollingSyncInterval = 15 * time.Second
gitPollingCondition = "GitPolling"
generationLabel = "fleet.cattle.io/gitrepo-generation"
forceSyncGenerationLabel = "fleet.cattle.io/force-sync-generation"
// The TTL is the grace period for short-lived metrics to be kept alive to
// make sure Prometheus scrapes them.
ShortLivedMetricsTTL = 120 * time.Second
gitJobPollingJitterPercent = 10
// period after which the GitRepo reconciler is re-scheduled,
// in order to wait for the dependent resources cleanup to finish
requeueAfterResourceCleanup = 2 * time.Second
// Annotation keys for tracking secret data hashes
clientSecretHashAnnotation = "fleet.cattle.io/client-secret-hash" //nolint:gosec // not a credential
helmSecretHashAnnotation = "fleet.cattle.io/helm-secret-hash" //nolint:gosec // not a credential
helmSecretForPathsHashAnnotation = "fleet.cattle.io/helm-secret-for-paths-hash" //nolint:gosec // not a credential
)
var (
GitJobDurationBuckets = []float64{1, 2, 5, 10, 30, 60, 180, 300, 600, 1200, 1800, 3600}
gitjobsCreatedSuccess = metrics.ObjCounter(
"gitjobs_created_success_total",
"Total number of successfully created git jobs",
)
gitjobsCreatedFailure = metrics.ObjCounter(
"gitjobs_created_failure_total",
"Total number of failed git job creations",
)
gitjobDuration = metrics.ObjHistogram(
"gitjob_duration_seconds",
"Duration to complete a Git job in seconds. Includes the time to fetch the git repo and to create the bundle.",
GitJobDurationBuckets,
)
gitjobDurationGauge = metrics.ObjGauge(
"gitjob_duration_seconds_gauge",
"Duration to complete a Git job in seconds. Includes the time to fetch the git repo and to create the bundle.",
)
fetchLatestCommitSuccess = metrics.ObjCounter(
"gitrepo_fetch_latest_commit_success_total",
"Total number of successful fetches of latest commit",
)
fetchLatestCommitFailure = metrics.ObjCounter(
"gitrepo_fetch_latest_commit_failure_total",
"Total number of failed attempts to retrieve the latest commit, for any reason",
)
timeToFetchLatestCommit = metrics.ObjHistogram(
"gitrepo_fetch_latest_commit_duration_seconds",
"Duration in seconds to fetch the latest commit",
metrics.BucketsLatency,
)
)
type GitFetcher interface {
LatestCommit(ctx context.Context, gitrepo *v1alpha1.GitRepo, client client.Client) (string, error)
}
// TimeGetter interface is used to mock the time.Now() call in unit tests
type TimeGetter interface {
Now() time.Time
Since(t time.Time) time.Duration
}
type RealClock struct{}
func (RealClock) Now() time.Time { return time.Now() }
func (RealClock) Since(t time.Time) time.Duration { return time.Since(t) }
type KnownHostsGetter interface {
Get(ctx context.Context, client client.Client, namespace, secretName string) (string, error)
IsStrict() bool
}
// GitJobReconciler reconciles a GitRepo resource to create a git cloning k8s job
type GitJobReconciler struct {
client.Client
Scheme *runtime.Scheme
Image string
Scheduler quartz.Scheduler
Workers int
ShardID string
JobNodeSelector string
GitFetcher GitFetcher
Clock TimeGetter
Recorder events.EventRecorder
SystemNamespace string
KnownHosts KnownHostsGetter
WithImagescan bool
}
func (r *GitJobReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&v1alpha1.GitRepo{},
builder.WithPredicates(
// do not trigger for GitRepo status changes (except for commit changes and cache sync)
predicate.Or(
reconciler.TypedResourceVersionUnchangedPredicate[client.Object]{},
predicate.GenerationChangedPredicate{},
// Use nonSecretAnnotationChangedPredicate instead of predicate.AnnotationChangedPredicate
// to avoid redundant reconciles when the controller updates secret data hash
// tracking annotations (e.g., fleet.cattle.io/client-secret-hash).
nonSecretAnnotationChangedPredicate(),
predicate.LabelChangedPredicate{},
commitChangedPredicate(),
),
),
).
Owns(&batchv1.Job{}, builder.WithPredicates(jobUpdatedPredicate())).
Watches(
// Fan out from secret to gitrepo, reconcile gitrepos when a secret
// referenced in ClientSecretName, HelmSecretName, or HelmSecretNameForPaths changes.
&corev1.Secret{},
handler.EnqueueRequestsFromMapFunc(r.secretMapFunc()),
builder.WithPredicates(secretDataChangedPredicate()),
).
WithEventFilter(sharding.FilterByShardID(r.ShardID)).
WithOptions(controller.Options{MaxConcurrentReconciles: r.Workers}).
Complete(r)
}
// Reconcile compares the state specified by the GitRepo object against the
// actual cluster state. It checks the Git repository for new commits and
// creates a job to clone the repository if a new commit is found. In case of
// an error, the output of the job is stored in the status.
func (r *GitJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
logger := log.FromContext(ctx).WithName("gitjob")
gitrepo := &v1alpha1.GitRepo{}
if err := r.Get(ctx, req.NamespacedName, gitrepo); err != nil && !apierrors.IsNotFound(err) {
return ctrl.Result{}, err
} else if apierrors.IsNotFound(err) {
gitjobsCreatedSuccess.DeleteByReq(req)
gitjobsCreatedFailure.DeleteByReq(req)
gitjobDuration.DeleteByReq(req)
fetchLatestCommitSuccess.DeleteByReq(req)
fetchLatestCommitFailure.DeleteByReq(req)
timeToFetchLatestCommit.DeleteByReq(req)
logger.V(1).Info("Gitrepo deleted, cleaning up pull jobs")
return ctrl.Result{}, nil
}
// Restrictions / Overrides, gitrepo reconciler is responsible for setting error in status
oldStatus := gitrepo.Status.DeepCopy()
if err := AuthorizeAndAssignDefaults(ctx, r.Client, gitrepo); err != nil {
r.Recorder.Eventf(
gitrepo,
nil,
corev1.EventTypeWarning,
"FailedToApplyRestrictions",
"ApplyGitRepoRestrictions",
"%v",
err,
)
return ctrl.Result{}, updateErrorStatus(ctx, r.Client, req.NamespacedName, *oldStatus, err)
}
if !gitrepo.DeletionTimestamp.IsZero() {
if controllerutil.ContainsFinalizer(gitrepo, finalize.GitRepoFinalizer) {
return r.handleDelete(ctx, logger, gitrepo)
}
return ctrl.Result{}, nil
}
if err := finalize.EnsureFinalizer(ctx, r.Client, gitrepo, finalize.GitRepoFinalizer); err != nil {
return ctrl.Result{}, err
}
// Migration: Remove the obsolete created-by-display-name label if it exists
if err := r.removeDisplayNameLabel(ctx, req.NamespacedName); err != nil {
logger.V(1).Error(err, "Failed to remove display name label")
return ctrl.Result{}, err
}
logger = logger.WithValues("generation", gitrepo.Generation, "commit", gitrepo.Status.Commit).WithValues("conditions", gitrepo.Status.Conditions)
if userID := gitrepo.Labels[v1alpha1.CreatedByUserIDLabel]; userID != "" {
logger = logger.WithValues("userID", userID)
}
ctx = log.IntoContext(ctx, logger)
logger.V(1).Info("Reconciling GitRepo")
if gitrepo.Spec.Repo == "" {
if err := r.deletePollingJob(*gitrepo); err != nil {
return ctrl.Result{}, updateErrorStatus(ctx, r.Client, req.NamespacedName, gitrepo.Status, err)
}
// TODO: return an error here, similar to what we already do for HelmOps
return ctrl.Result{}, nil
}
jobUpdatedOrCreated, err := r.managePollingJob(logger, *gitrepo)
if err != nil {
return ctrl.Result{}, updateErrorStatus(ctx, r.Client, req.NamespacedName, gitrepo.Status, err)
}
if jobUpdatedOrCreated {
// Maybe an update from the polling job will come next
// Requeue and stop this reconcile now as moving on to gitJob creation would
// possibly lead to conflicts.
return ctrl.Result{RequeueAfter: durations.DefaultRequeueAfter}, nil
}
oldCommit := gitrepo.Status.Commit
// maybe update the commit from webhooks or polling
gitrepo.Status.Commit = getNextCommit(gitrepo.Status)
res, err := r.manageGitJob(ctx, logger, gitrepo, oldCommit)
if err != nil || res.RequeueAfter > 0 {
return res, updateErrorStatus(ctx, r.Client, req.NamespacedName, gitrepo.Status, err)
}
// Update secret data hash annotations after successful job management
if err := r.updateSecretDataHashes(ctx, gitrepo); err != nil {
logger.V(1).Error(err, "Failed to update secret data hash annotations")
return ctrl.Result{}, err
}
reconciler.SetCondition(v1alpha1.GitRepoAcceptedCondition, &gitrepo.Status, nil)
err = updateStatus(ctx, r.Client, req.NamespacedName, gitrepo.Status)
if err != nil {
logger.Error(err, "Reconcile failed final update to git repo status", "status", gitrepo.Status)
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}
func monitorLatestCommit(obj metav1.Object, fetch func() (string, error)) (string, error) {
start := time.Now()
commit, err := fetch()
if err != nil {
fetchLatestCommitFailure.Inc(obj)
return "", err
}
fetchLatestCommitSuccess.Inc(obj)
timeToFetchLatestCommit.Observe(obj, time.Since(start).Seconds())
return commit, nil
}
// manageGitJob is responsible for creating, updating and deleting the GitJob and setting the GitRepo's status accordingly
func (r *GitJobReconciler) manageGitJob(ctx context.Context, logger logr.Logger, gitrepo *v1alpha1.GitRepo, oldCommit string) (ctrl.Result, error) {
if err := r.deletePreviousJob(ctx, logger, *gitrepo, oldCommit); err != nil {
return ctrl.Result{}, err
}
var job batchv1.Job
err := r.Get(ctx, types.NamespacedName{
Namespace: gitrepo.Namespace,
Name: jobName(gitrepo),
}, &job)
if err != nil && !apierrors.IsNotFound(err) {
err = fmt.Errorf("error retrieving git job: %w", err)
r.Recorder.Eventf(
gitrepo,
nil,
corev1.EventTypeWarning,
"FailedToGetGitJob",
"GetGitJob",
"%v",
err,
)
return ctrl.Result{}, err
}
if apierrors.IsNotFound(err) {
clientSecretChanged, helmSecretChanged, err := r.hasReferencedSecretChanged(ctx, gitrepo)
if err != nil {
r.Recorder.Eventf(
gitrepo,
nil,
corev1.EventTypeWarning,
"FailedValidatingSecret",
"ValidateSecret",
"%v",
err,
)
return ctrl.Result{}, fmt.Errorf("error validating external secrets: %w", err)
}
// In cases where we have a very large polling interval and the first commit
// could not be retrieved because the secret was incorrect, the gitRepo does
// not show any commit.
// If the client secret has changed, we now retrieve the latest commit.
// If the secret is still incorrect, we will not need to create
// the gitJob (which is more expensive) and we will return an error earlier.
if gitrepo.Spec.DisablePolling || clientSecretChanged {
commit, err := monitorLatestCommit(gitrepo, func() (string, error) {
return r.GitFetcher.LatestCommit(ctx, gitrepo, r.Client)
})
condition.Cond(gitPollingCondition).SetError(&gitrepo.Status, "", err)
if err == nil && commit != "" {
gitrepo.Status.Commit = commit
}
if err != nil {
r.Recorder.Eventf(
gitrepo,
nil,
corev1.EventTypeWarning,
"Failed",
"MonitorLatestCommit",
"%v",
err,
)
} else if oldCommit != gitrepo.Status.Commit {
r.Recorder.Eventf(
gitrepo,
nil,
corev1.EventTypeNormal,
"GotNewCommit",
"GetNewCommit",
gitrepo.Status.Commit,
)
}
}
if r.shouldCreateJob(gitrepo, oldCommit, helmSecretChanged) {
r.updateGenerationValuesIfNeeded(gitrepo)
if err := r.validateExternalSecretExist(ctx, gitrepo); err != nil {
r.Recorder.Eventf(
gitrepo,
nil,
corev1.EventTypeWarning,
"FailedValidatingSecret",
"ValidateSecret",
"%v",
err,
)
return ctrl.Result{}, fmt.Errorf("error validating external secrets: %w", err)
}
if err := r.createJobAndResources(ctx, gitrepo, logger); err != nil {
gitjobsCreatedFailure.Inc(gitrepo)
return ctrl.Result{}, err
}
gitjobsCreatedSuccess.Inc(gitrepo)
}
} else if gitrepo.Status.Commit != "" && gitrepo.Status.Commit == oldCommit {
err, recreateGitJob := r.deleteJobIfNeeded(ctx, gitrepo, &job)
if err != nil {
return ctrl.Result{}, fmt.Errorf("error deleting git job: %w", err)
}
// job was deleted and we need to recreate it
// Requeue so the reconciler creates the job again
if recreateGitJob {
return ctrl.Result{RequeueAfter: durations.DefaultRequeueAfter}, nil
}
}
gitrepo.Status.ObservedGeneration = gitrepo.Generation
if err = setStatusFromGitjob(ctx, r.Client, gitrepo, &job); err != nil {
return ctrl.Result{}, fmt.Errorf("error setting GitRepo status from git job: %w", err)
}
return ctrl.Result{}, nil
}
func (r *GitJobReconciler) deletePreviousJob(ctx context.Context, logger logr.Logger, gitrepo v1alpha1.GitRepo, oldCommit string) error {
if oldCommit == "" || oldCommit == gitrepo.Status.Commit {
return nil
}
// the GitRepo is passed by value, just use the old commit
// to calculate the job Name
gitrepo.Status.Commit = oldCommit
var job batchv1.Job
err := r.Get(ctx, types.NamespacedName{
Namespace: gitrepo.Namespace,
Name: jobName(&gitrepo),
}, &job)
if err != nil {
if !apierrors.IsNotFound(err) {
return err
}
return nil
}
// At this point we know the previous job still exists and the commit already changed.
// Delete the previous one so we don't incur in conflicts
logger.Info("Deleting previous job to avoid conflicts")
return r.Delete(ctx, &job)
}
func (r *GitJobReconciler) handleDelete(ctx context.Context, logger logr.Logger, gitrepo *v1alpha1.GitRepo) (ctrl.Result, error) {
logger.Info("Gitrepo deleted, deleting bundle, image scans")
_ = r.deletePollingJob(*gitrepo)
if !controllerutil.ContainsFinalizer(gitrepo, finalize.GitRepoFinalizer) {
return ctrl.Result{}, nil
}
bundles, err := r.listBundlesForGitrepo(ctx, gitrepo)
if err != nil {
return ctrl.Result{}, err
}
// Bundle deletion happens asynchronously: mark them for deletion and requeue
// This ensures the Gitrepo is kept around until all its Bundles are completely deleted.
if len(bundles.Items) > 0 {
logger.V(1).Info("GitRepo deleted, purging bundles")
return ctrl.Result{RequeueAfter: requeueAfterResourceCleanup}, batchDeleteDependentResources(ctx, r.Client, bundles)
}
// remove the job scheduled by imagescan, if any
if r.WithImagescan {
_ = r.Scheduler.DeleteJob(imagescan.GitCommitKey(gitrepo.Namespace, gitrepo.Name))
images, err := r.listImageScansForGitrepo(ctx, gitrepo)
if err != nil {
return ctrl.Result{}, err
}
if len(images.Items) > 0 {
logger.V(1).Info("GitRepo deleted, purging imagescans")
return ctrl.Result{RequeueAfter: requeueAfterResourceCleanup}, batchDeleteDependentResources(ctx, r.Client, images)
}
}
// Delete the target namespace if DeleteNamespace is true
if err := finalize.PurgeTargetNamespaceIfNeeded(ctx, r.Client, gitrepo); err != nil {
return ctrl.Result{}, err
}
metrics.GitRepoCollector.Delete(gitrepo.Name, gitrepo.Namespace)
// we don't have pending Bundles nor ImageScans, we can remove the finalizer
nsName := types.NamespacedName{Name: gitrepo.Name, Namespace: gitrepo.Namespace}
err = retry.RetryOnConflict(retry.DefaultRetry, func() error {
if err := r.Get(ctx, nsName, gitrepo); err != nil {
return err
}
controllerutil.RemoveFinalizer(gitrepo, finalize.GitRepoFinalizer)
return r.Update(ctx, gitrepo)
})
if client.IgnoreNotFound(err) != nil {
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}
// shouldCreateJob checks if the conditions to create a new job are met.
// It checks for all the conditions so, in case more than one is met, it sets all the
// values related in one single reconciler loop
func (r *GitJobReconciler) shouldCreateJob(gitrepo *v1alpha1.GitRepo, oldCommit string, helmSecretsChanged bool) bool {
if gitrepo.Status.Commit != "" && gitrepo.Status.Commit != oldCommit {
return true
}
if gitrepo.Spec.ForceSyncGeneration != gitrepo.Status.UpdateGeneration {
return true
}
// k8s Jobs are immutable. Recreate the job if the GitRepo Spec has changed.
// Avoid deleting the job twice
if generationChanged(gitrepo) {
return true
}
// Finally check if any of the referenced secrets changed
return helmSecretsChanged
}
func (r *GitJobReconciler) updateGenerationValuesIfNeeded(gitrepo *v1alpha1.GitRepo) {
if gitrepo.Spec.ForceSyncGeneration != gitrepo.Status.UpdateGeneration {
gitrepo.Status.UpdateGeneration = gitrepo.Spec.ForceSyncGeneration
}
if generationChanged(gitrepo) {
gitrepo.Status.ObservedGeneration = gitrepo.Generation
}
}
// removeDisplayNameLabel removes the obsolete created-by-display-name label from the gitrepo if it exists.
func (r *GitJobReconciler) removeDisplayNameLabel(ctx context.Context, nsName types.NamespacedName) error {
return retry.RetryOnConflict(retry.DefaultRetry, func() error {
gitrepo := &v1alpha1.GitRepo{}
if err := r.Get(ctx, nsName, gitrepo); err != nil {
return err
}
if gitrepo.Labels == nil {
return nil
}
const deprecatedLabel = "fleet.cattle.io/created-by-display-name"
if _, exists := gitrepo.Labels[deprecatedLabel]; !exists {
return nil
}
delete(gitrepo.Labels, deprecatedLabel)
return r.Update(ctx, gitrepo)
})
}
func (r *GitJobReconciler) validateExternalSecretExist(ctx context.Context, gitrepo *v1alpha1.GitRepo) error {
if gitrepo.Spec.HelmSecretNameForPaths != "" {
if err := r.Get(ctx, types.NamespacedName{Namespace: gitrepo.Namespace, Name: gitrepo.Spec.HelmSecretNameForPaths}, &corev1.Secret{}); err != nil {
return fmt.Errorf("failed to look up HelmSecretNameForPaths, error: %w", err)
}
} else if gitrepo.Spec.HelmSecretName != "" {
if err := r.Get(ctx, types.NamespacedName{Namespace: gitrepo.Namespace, Name: gitrepo.Spec.HelmSecretName}, &corev1.Secret{}); err != nil {
return fmt.Errorf("failed to look up helmSecretName, error: %w", err)
}
}
return nil
}
func (r *GitJobReconciler) deleteJobIfNeeded(ctx context.Context, gitRepo *v1alpha1.GitRepo, job *batchv1.Job) (error, bool) {
logger := log.FromContext(ctx)
// the following cases imply that the job is still running but we need to stop it and
// create a new one
if gitRepo.Spec.ForceSyncGeneration != gitRepo.Status.UpdateGeneration {
if forceSync, ok := job.Labels[forceSyncGenerationLabel]; ok {
t := fmt.Sprintf("%d", gitRepo.Spec.ForceSyncGeneration)
if t != forceSync {
jobDeletedMessage := "job deletion triggered because of ForceUpdateGeneration"
logger.V(1).Info(jobDeletedMessage)
if err := r.Delete(ctx, job, client.PropagationPolicy(metav1.DeletePropagationBackground)); err != nil && !apierrors.IsNotFound(err) {
return err, true
}
return nil, true
}
}
}
// k8s Jobs are immutable. Recreate the job if the GitRepo Spec has changed.
// Avoid deleting the job twice
if generationChanged(gitRepo) {
if gen, ok := job.Labels[generationLabel]; ok {
t := fmt.Sprintf("%d", gitRepo.Generation)
if t != gen {
jobDeletedMessage := "job deletion triggered because of generation change"
logger.V(1).Info(jobDeletedMessage)
if err := r.Delete(ctx, job, client.PropagationPolicy(metav1.DeletePropagationBackground)); err != nil && !apierrors.IsNotFound(err) {
return err, true
}
return nil, true
}
}
}
// check if the job finished and was successful
if job.Status.Succeeded == 1 {
if job.Status.StartTime != nil && job.Status.CompletionTime != nil {
duration := job.Status.CompletionTime.Sub(job.Status.StartTime.Time)
gitjobDuration.Observe(gitRepo, duration.Seconds())
gitjobDurationGauge.Set(gitRepo, duration.Seconds())
go func() {
time.Sleep(ShortLivedMetricsTTL)
gitjobDurationGauge.Delete(gitRepo)
}()
}
jobDeletedMessage := "job deletion triggered because job succeeded"
logger.Info(jobDeletedMessage)
if err := r.Delete(ctx, job, client.PropagationPolicy(metav1.DeletePropagationBackground)); err != nil && !apierrors.IsNotFound(err) {
return err, false
}
r.Recorder.Eventf(
gitRepo,
nil,
corev1.EventTypeNormal,
"JobDeleted",
"DeleteJob",
jobDeletedMessage,
)
}
// finally if there's a job and any of the secrets related to the gitrepo changed,
// we need to delete the job so it gets recreated
clientSecretChanged, helmSecretChanged, err := r.hasReferencedSecretChanged(ctx, gitRepo)
if err != nil {
return err, false
}
if clientSecretChanged || helmSecretChanged {
jobDeletedMessage := "job deletion triggered because referenced secret changed"
logger.Info(jobDeletedMessage)
if err := r.Delete(ctx, job, client.PropagationPolicy(metav1.DeletePropagationBackground)); err != nil && !apierrors.IsNotFound(err) {
return err, true
}
return nil, true
}
return nil, false
}
func jobKey(g v1alpha1.GitRepo) *quartz.JobKey {
return quartz.NewJobKey(string(g.UID))
}
// deletePollingJob deletes the polling job scheduled for the provided gitrepo, if any, and returns any error that may
// have happened in the process.
// Returns a nil error if the job could be deleted or if none existed.
func (r *GitJobReconciler) deletePollingJob(gitrepo v1alpha1.GitRepo) error {
if r.Scheduler == nil {
return nil
}
jobKey := jobKey(gitrepo)
if _, err := r.Scheduler.GetScheduledJob(jobKey); err == nil {
if err = r.Scheduler.DeleteJob(jobKey); err != nil {
return fmt.Errorf("failed to delete outdated polling job: %w", err)
}
} else if !errors.Is(err, quartz.ErrJobNotFound) {
return fmt.Errorf("failed to get outdated polling job for deletion: %w", err)
}
return nil
}
// managePollingJob creates, updates or deletes a polling job for the provided GitRepo.
func (r *GitJobReconciler) managePollingJob(logger logr.Logger, gitrepo v1alpha1.GitRepo) (bool, error) {
jobUpdatedOrCreated := false
if r.Scheduler == nil {
logger.V(1).Info("Scheduler is not set; this should only happen in tests")
return jobUpdatedOrCreated, nil
}
jobKey := jobKey(gitrepo)
scheduled, err := r.Scheduler.GetScheduledJob(jobKey)
if err != nil && !errors.Is(err, quartz.ErrJobNotFound) {
return jobUpdatedOrCreated, fmt.Errorf("an unknown error occurred when looking for a polling job: %w", err)
}
if !gitrepo.Spec.DisablePolling {
scheduledJobDescription := ""
if err == nil {
if detail := scheduled.JobDetail(); detail != nil {
scheduledJobDescription = detail.Job().Description()
}
}
newJob := newGitPollingJob(r.Client, r.Recorder, gitrepo, r.GitFetcher)
currentTrigger := ctrlquartz.NewControllerTrigger(
GetPollingIntervalDuration(&gitrepo),
gitJobPollingJitterPercent,
)
if errors.Is(err, quartz.ErrJobNotFound) ||
scheduled.Trigger().Description() != currentTrigger.Description() ||
scheduledJobDescription != newJob.Description() {
err = r.Scheduler.ScheduleJob(
quartz.NewJobDetailWithOptions(
newJob,
jobKey,
&quartz.JobDetailOptions{
Replace: true,
},
),
currentTrigger,
)
if err != nil {
return jobUpdatedOrCreated, fmt.Errorf("failed to schedule polling job: %w", err)
}
logger.V(1).Info("Scheduled new polling job")
jobUpdatedOrCreated = true
}
} else if err == nil {
// A job still exists, but is no longer needed; delete it.
if err = r.Scheduler.DeleteJob(jobKey); err != nil {
return jobUpdatedOrCreated, fmt.Errorf("failed to delete polling job: %w", err)
}
}
return jobUpdatedOrCreated, nil
}
func (r *GitJobReconciler) listBundlesForGitrepo(ctx context.Context, gitrepo *v1alpha1.GitRepo) (*v1alpha1.BundleList, error) {
list := &v1alpha1.BundleList{}
err := r.List(ctx, list, client.MatchingLabels{v1alpha1.RepoLabel: gitrepo.Name}, client.InNamespace(gitrepo.Namespace))
if err != nil {
return nil, err
}
return list, nil
}
func (r *GitJobReconciler) listImageScansForGitrepo(ctx context.Context, gitrepo *v1alpha1.GitRepo) (*v1alpha1.ImageScanList, error) {
list := &v1alpha1.ImageScanList{}
if err := r.List(ctx, list,
client.InNamespace(gitrepo.Namespace),
client.MatchingFields{
config.ImageScanGitRepoIndex: gitrepo.Name,
},
); err != nil {
return nil, err
}
return list, nil
}
// secretMapFunc returns a function that maps a Secret to GitRepos that reference it
// in ClientSecretName, HelmSecretName, or HelmSecretNameForPaths fields.
func (r *GitJobReconciler) secretMapFunc() func(ctx context.Context, obj client.Object) []reconcile.Request {
return func(ctx context.Context, obj client.Object) []reconcile.Request {
logger := log.FromContext(ctx).WithName("secret-watch")
secretName := obj.GetName()
namespace := obj.GetNamespace()
// Use a map to deduplicate requests (same GitRepo might reference secret in multiple fields)
seen := make(map[types.NamespacedName]struct{})
requests := make([]reconcile.Request, 0)
addRequest := func(gitRepo *v1alpha1.GitRepo) {
if !sharding.ShouldProcess(gitRepo, r.ShardID) {
return
}
key := types.NamespacedName{
Namespace: gitRepo.Namespace,
Name: gitRepo.Name,
}
if _, exists := seen[key]; !exists {
seen[key] = struct{}{}
requests = append(requests, reconcile.Request{NamespacedName: key})
}
}
// Find GitRepos using this secret as ClientSecretName
gitRepoList := &v1alpha1.GitRepoList{}
if err := r.List(ctx, gitRepoList,
client.InNamespace(namespace),
client.MatchingFields{config.GitRepoClientSecretNameIndex: secretName},
); err != nil {
logger.V(1).Error(err, "Failed to list GitRepos by ClientSecretName", "secret", secretName)
} else {
for _, gr := range gitRepoList.Items {
addRequest(&gr)
}
}
// Find GitRepos using this secret as HelmSecretName
gitRepoList = &v1alpha1.GitRepoList{}
if err := r.List(ctx, gitRepoList,
client.InNamespace(namespace),
client.MatchingFields{config.GitRepoHelmSecretNameIndex: secretName},
); err != nil {
logger.V(1).Error(err, "Failed to list GitRepos by HelmSecretName", "secret", secretName)
} else {
for _, gr := range gitRepoList.Items {
addRequest(&gr)
}
}
// Find GitRepos using this secret as HelmSecretNameForPaths
gitRepoList = &v1alpha1.GitRepoList{}
if err := r.List(ctx, gitRepoList,
client.InNamespace(namespace),
client.MatchingFields{config.GitRepoHelmSecretNameForPathsIndex: secretName},
); err != nil {
logger.V(1).Error(err, "Failed to list GitRepos by HelmSecretNameForPaths", "secret", secretName)
} else {
for _, gr := range gitRepoList.Items {
addRequest(&gr)
}
}
return requests
}
}
// hasReferencedSecretChanged checks if any of the secrets referenced by the GitRepo
// (ClientSecretName, HelmSecretName, or HelmSecretNameForPaths) has been modified.
// It compares a hash of the current secret Data with the one stored in the GitRepo's annotations.
// Returns two booleans: clientSecretChanged (true if ClientSecretName changed) and
// helmSecretChanged (true if HelmSecretName or HelmSecretNameForPaths changed).
//
// This function returns true in the following cases:
// - The secret exists and was not previously tracked (no annotation) - newly available secret
// - The secret's data hash differs from the stored annotation - secret data was updated
// - The secret was deleted but we had a previous version recorded - secret was removed
func (r *GitJobReconciler) hasReferencedSecretChanged(ctx context.Context, gitrepo *v1alpha1.GitRepo) (bool, bool, error) {
// Check ClientSecretName
clientSecretChanged, err := r.hasSecretChanged(ctx, gitrepo, gitrepo.Spec.ClientSecretName, clientSecretHashAnnotation, "ClientSecretName")
if err != nil {
return false, false, err
}
// Check HelmSecretName
helmSecretChanged, err := r.hasSecretChanged(ctx, gitrepo, gitrepo.Spec.HelmSecretName, helmSecretHashAnnotation, "helmSecretName")
if err != nil {
return false, false, err
}
// return early if helmSecretChanged is true
if helmSecretChanged {
return clientSecretChanged, true, nil
}
// Check HelmSecretNameForPaths
helmSecretForPathsChanged, err := r.hasSecretChanged(ctx, gitrepo, gitrepo.Spec.HelmSecretNameForPaths, helmSecretForPathsHashAnnotation, "HelmSecretNameForPaths")
if err != nil {
return false, false, err
}
return clientSecretChanged, helmSecretChanged || helmSecretForPathsChanged, nil
}
// hasSecretChanged checks if a single secret has changed by comparing a hash of its current Data
// with the one stored in the GitRepo's annotations.
func (r *GitJobReconciler) hasSecretChanged(ctx context.Context, gitrepo *v1alpha1.GitRepo, secretName, annotationKey, fieldName string) (bool, error) {
if secretName == "" {
return false, nil
}
secret := &corev1.Secret{}
err := r.Get(ctx, types.NamespacedName{
Namespace: gitrepo.Namespace,
Name: secretName,
}, secret)
if err != nil {
if apierrors.IsNotFound(err) {
// Secret doesn't exist, check if we had a previous version recorded
if gitrepo.Annotations != nil && gitrepo.Annotations[annotationKey] != "" {
// Secret was deleted, consider this as changed
return true, nil
}
return false, nil
}
return false, fmt.Errorf("failed to look up %s, error: %w", fieldName, err)
}
// Compute hash of current secret data
currentHash := hashSecretData(secret.Data)
// Check if data hash has changed or if this is a new secret (no previous annotation)
previousHash := ""
if gitrepo.Annotations != nil {
previousHash = gitrepo.Annotations[annotationKey]
}
// If there was no previous annotation, the secret is newly available - treat as changed
if previousHash == "" {
return true, nil
}
// If there was a previous hash and it differs, the secret data changed
if previousHash != currentHash {
return true, nil
}
return false, nil
}
// updateSecretDataHashes updates the GitRepo's annotations with a hash of the current Data
// of each referenced secret. This allows hasReferencedSecretChanged to detect changes.
func (r *GitJobReconciler) updateSecretDataHashes(ctx context.Context, gitrepo *v1alpha1.GitRepo) error {
return retry.RetryOnConflict(retry.DefaultRetry, func() error {
// Fetch the latest version of the GitRepo
current := &v1alpha1.GitRepo{}
if err := r.Get(ctx, types.NamespacedName{
Namespace: gitrepo.Namespace,
Name: gitrepo.Name,
}, current); err != nil {
return err
}
secretRefs := []struct {
name string
annotationKey string
}{
{current.Spec.ClientSecretName, clientSecretHashAnnotation},
{current.Spec.HelmSecretName, helmSecretHashAnnotation},
{current.Spec.HelmSecretNameForPaths, helmSecretForPathsHashAnnotation},
}
annotations := make(map[string]string)
hasChanges := false
var errs []error
for _, secretRef := range secretRefs {
if secretRef.name == "" {
// Mark annotation for deletion if secret is no longer referenced
if current.Annotations != nil && current.Annotations[secretRef.annotationKey] != "" {
annotations[secretRef.annotationKey] = ""
hasChanges = true
}
continue
}
secret := &corev1.Secret{}
err := r.Get(ctx, types.NamespacedName{
Namespace: current.Namespace,
Name: secretRef.name,
}, secret)
if err != nil {
if apierrors.IsNotFound(err) {
// Secret doesn't exist, mark annotation for deletion
if current.Annotations != nil && current.Annotations[secretRef.annotationKey] != "" {
annotations[secretRef.annotationKey] = ""
hasChanges = true
}
continue
}
// Collect the error but continue processing other secrets
errs = append(errs, fmt.Errorf("failed to get secret %s: %w", secretRef.name, err))
continue
}
// Compute hash of secret data
dataHash := hashSecretData(secret.Data)
// Check if the annotation needs to be updated
if current.Annotations == nil || current.Annotations[secretRef.annotationKey] != dataHash {
annotations[secretRef.annotationKey] = dataHash
hasChanges = true
}
}
// Return aggregated errors if any occurred
if len(errs) > 0 {
return errors.Join(errs...)
}
// Only patch if there are changes
if !hasChanges {
return nil
}
patch := client.MergeFrom(current.DeepCopy())
if current.Annotations == nil {
current.Annotations = make(map[string]string)
}
for key, value := range annotations {
if value == "" {
delete(current.Annotations, key)