From c7dc37258041aa27c9d6851f2f38246ae27f5934 Mon Sep 17 00:00:00 2001 From: Mattia Eleuteri Date: Wed, 7 Oct 2026 11:32:06 +0200 Subject: [PATCH] fix(backups): create no driver object for a job that already finished The BackupJob and RestoreJob reconcilers decide a job is still active from the informer cache, and the cache can trail their own writes. A driver's first pass stamps StartedAt, which requeues the job, and may then fail the job in the same pass on a transient error, such as a 503 from the aggregated apps.cozystack.io API while it reads the application. The requeued pass can start before the informer has seen Failed: it retries the step that failed and, once the error has cleared, creates the driver object anyway. Its own status write then conflicts, the pass after it sees Failed and skips the job, and a Velero Backup is left running that no Backup artifact will reference and nothing tracks. Against a real apiserver and the manager's cache, with one 503 on the first application read of each job, 5 to 10 BackupJobs out of 40 ended Failed with a Velero Backup. A restore pass that starts on such a stale copy does worse, since the step it retries can be destructive: suspending the VM's HelmRelease and halting the VM before creating a Velero Restore, or patching the Postgres application and purging its cluster. Both reconcilers now re-read the job through the manager's uncached reader when the cached copy says it is still active, and skip it when the apiserver holds it as finished. The check sits ahead of the dispatch, so it covers every driver, and a job the cache already reports as finished costs no extra request. Assisted-by: LLM Signed-off-by: Mattia Eleuteri (cherry picked from commit eafa441b9c36cf44ce17237de1e8b2bd7e1f70ea) Signed-off-by: cozystack-ci[bot] <274107086+cozystack-ci[bot]@users.noreply.github.com> --- .../backupcontroller/backupjob_controller.go | 33 +++ .../backupcontroller/restorejob_controller.go | 23 ++- internal/backupcontroller/stale_cache_test.go | 193 ++++++++++++++++++ 3 files changed, 246 insertions(+), 3 deletions(-) create mode 100644 internal/backupcontroller/stale_cache_test.go diff --git a/internal/backupcontroller/backupjob_controller.go b/internal/backupcontroller/backupjob_controller.go index e7145eec0..3908c77ee 100644 --- a/internal/backupcontroller/backupjob_controller.go +++ b/internal/backupcontroller/backupjob_controller.go @@ -34,6 +34,10 @@ type BackupJobReconciler struct { Scheme *runtime.Scheme Recorder record.EventRecorder CredentialsConfig BackupCredentialsConfig + // APIReader is the manager's uncached reader, through which Reconcile + // re-reads the BackupJob before dispatching to a driver. Wired in + // SetupWithManager. + APIReader client.Reader } func (r *BackupJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { @@ -61,6 +65,24 @@ func (r *BackupJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) ( return ctrl.Result{}, nil } + // The cache can trail this reconciler's own writes. A pass that stamps + // StartedAt and then fails the job has already requeued it through the + // first write, so the next pass can start before the informer has seen + // Failed, retry the step that failed, and create a driver object for a + // job that is over and that nothing will track. Re-read the job past the + // cache; the check above only spares finished jobs the extra request. + if err := r.apiReader().Get(ctx, req.NamespacedName, j); err != nil { + if apierrors.IsNotFound(err) { + return ctrl.Result{}, nil + } + logger.Error(err, "failed to re-read BackupJob") + return ctrl.Result{}, err + } + if j.Status.Phase == backupsv1alpha1.BackupJobPhaseSucceeded || j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + logger.V(1).Info("BackupJob terminal on the apiserver ahead of the cache, skipping", "phase", j.Status.Phase) + return ctrl.Result{}, nil + } + // Normalize ApplicationRef (default apiGroup if not specified) normalizedAppRef := NormalizeApplicationRef(j.Spec.ApplicationRef) @@ -223,6 +245,7 @@ func (r *BackupJobReconciler) SetupWithManager(mgr ctrl.Manager) error { return err } + r.APIReader = mgr.GetAPIReader() cfg := mgr.GetConfig() var err error if r.Interface, err = dynamic.NewForConfig(cfg); err != nil { @@ -240,6 +263,16 @@ func (r *BackupJobReconciler) SetupWithManager(mgr ctrl.Manager) error { Complete(r) } +// apiReader returns the uncached reader. Reconcilers built by hand in unit +// tests have none and fall back to their fake Client, which has no cache to +// bypass. +func (r *BackupJobReconciler) apiReader() client.Reader { + if r.APIReader != nil { + return r.APIReader + } + return r.Client +} + // handleProjectionError classifies a credentials-projection error as // transient (requeue) or terminal (mark Failed). Transient errors record // a Ready=False condition without setting Phase=Failed so the BackupJob diff --git a/internal/backupcontroller/restorejob_controller.go b/internal/backupcontroller/restorejob_controller.go index def91c382..17855d41d 100644 --- a/internal/backupcontroller/restorejob_controller.go +++ b/internal/backupcontroller/restorejob_controller.go @@ -37,9 +37,10 @@ type RestoreJobReconciler struct { Scheme *runtime.Scheme Recorder record.EventRecorder CredentialsConfig BackupCredentialsConfig - // APIReader is the manager's uncached reader. The keepOriginalPVC rename - // reads back objects it has just written, which the cache may not have - // seen yet. Wired in SetupWithManager. + // APIReader is the manager's uncached reader. Reconcile re-reads the + // RestoreJob through it before dispatching to a driver, and the + // keepOriginalPVC rename reads back objects it has just written, which + // the cache may not have seen yet. Wired in SetupWithManager. APIReader client.Reader } @@ -92,6 +93,22 @@ func (r *RestoreJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) return ctrl.Result{}, nil } + // Re-read past the cache for the reason BackupJobReconciler.Reconcile + // gives. Here the step retried for a job already over can be destructive: + // halting the VM, renaming its PVCs, deleting the Postgres cluster. + if err := r.apiReader().Get(ctx, req.NamespacedName, restoreJob); err != nil { + if apierrors.IsNotFound(err) { + return ctrl.Result{}, nil + } + logger.Error(err, "failed to re-read RestoreJob") + return ctrl.Result{}, err + } + if restoreJob.Status.Phase == backupsv1alpha1.RestoreJobPhaseSucceeded || + restoreJob.Status.Phase == backupsv1alpha1.RestoreJobPhaseFailed { + logger.V(1).Info("RestoreJob terminal on the apiserver ahead of the cache, skipping", "phase", restoreJob.Status.Phase) + return ctrl.Result{}, nil + } + // Step 1: Fetch the referenced Backup backup := &backupsv1alpha1.Backup{} backupKey := types.NamespacedName{Namespace: req.Namespace, Name: restoreJob.Spec.BackupRef.Name} diff --git a/internal/backupcontroller/stale_cache_test.go b/internal/backupcontroller/stale_cache_test.go new file mode 100644 index 000000000..897e0fb05 --- /dev/null +++ b/internal/backupcontroller/stale_cache_test.go @@ -0,0 +1,193 @@ +// SPDX-License-Identifier: Apache-2.0 +package backupcontroller + +import ( + "context" + "testing" + "time" + + corev1 "k8s.io/api/core/v1" + "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/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + dynamicfake "k8s.io/client-go/dynamic/fake" + "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/tools/record" + "sigs.k8s.io/controller-runtime/pkg/client" + clientfake "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + + strategyv1alpha1 "github.com/cozystack/cozystack/api/backups/strategy/v1alpha1" + backupsv1alpha1 "github.com/cozystack/cozystack/api/backups/v1alpha1" + velerov1 "github.com/vmware-tanzu/velero/pkg/apis/velero/v1" +) + +// staleCacheScheme registers what both the cache and the apiserver stand-in +// hold. +func staleCacheScheme() *runtime.Scheme { + s := runtime.NewScheme() + _ = scheme.AddToScheme(s) + _ = backupsv1alpha1.AddToScheme(s) + _ = strategyv1alpha1.AddToScheme(s) + _ = velerov1.AddToScheme(s) + return s +} + +// apiServerHolding stands in for the apiserver: it holds job as the cache +// does, except for its phase. +func apiServerHolding(s *runtime.Scheme, job client.Object, phase string) client.Reader { + onAPI := job.DeepCopyObject().(client.Object) + switch j := onAPI.(type) { + case *backupsv1alpha1.BackupJob: + j.Status.Phase = backupsv1alpha1.BackupJobPhase(phase) + case *backupsv1alpha1.RestoreJob: + j.Status.Phase = backupsv1alpha1.RestoreJobPhase(phase) + } + onAPI.SetResourceVersion("") + return clientfake.NewClientBuilder().WithScheme(s).WithObjects(onAPI).Build() +} + +func countIn(t *testing.T, c client.Client, list client.ObjectList) int { + t.Helper() + if err := c.List(context.Background(), list); err != nil { + t.Fatalf("list %T: %v", list, err) + } + return meta.LenList(list) +} + +// TestReconcile_DoesNotRetryAJobItAlreadyFailed reproduces a pass that +// starts on a cache trailing the controller's own writes: the previous pass +// stamped StartedAt, which requeued the job, then failed it on a transient +// error. The cache holds the job with StartedAt and no phase; the apiserver +// holds it Failed. Before the re-read, the pass retried the Velero Backup +// creation and the job ended Failed with a Velero Backup nothing tracks. +func TestReconcile_DoesNotRetryAJobItAlreadyFailed(t *testing.T) { + appsGroup := "apps.cozystack.io" + strategyGroup := strategyv1alpha1.GroupVersion.Group + started := metav1.NewTime(time.Now().Add(-time.Second).Truncate(time.Second)) + + run := func(t *testing.T, apiPhase backupsv1alpha1.BackupJobPhase) (created int, cached backupsv1alpha1.BackupJobPhase) { + s := staleCacheScheme() + bc := &backupsv1alpha1.BackupClass{ + ObjectMeta: metav1.ObjectMeta{Name: "bc"}, + Spec: backupsv1alpha1.BackupClassSpec{Strategies: []backupsv1alpha1.BackupClassStrategy{{ + Application: backupsv1alpha1.ApplicationSelector{APIGroup: &appsGroup, Kind: "Bucket"}, + StrategyRef: corev1.TypedLocalObjectReference{APIGroup: &strategyGroup, Kind: strategyv1alpha1.VeleroStrategyKind, Name: "velero"}, + }}}, + } + j := &backupsv1alpha1.BackupJob{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "bj"}, + Spec: backupsv1alpha1.BackupJobSpec{ + BackupClassName: "bc", + ApplicationRef: corev1.TypedLocalObjectReference{APIGroup: &appsGroup, Kind: "Bucket", Name: "app"}, + }, + Status: backupsv1alpha1.BackupJobStatus{StartedAt: &started}, + } + strategy := &strategyv1alpha1.Velero{ObjectMeta: metav1.ObjectMeta{Name: "velero"}} + c := clientfake.NewClientBuilder().WithScheme(s).WithObjects(j, bc, strategy). + WithStatusSubresource(&backupsv1alpha1.BackupJob{}).Build() + gvr := schema.GroupVersionResource{Group: appsGroup, Version: "v1alpha1", Resource: "buckets"} + app := &unstructured.Unstructured{} + app.SetGroupVersionKind(gvr.GroupVersion().WithKind("Bucket")) + app.SetNamespace("tenant") + app.SetName("app") + r := &BackupJobReconciler{ + Client: c, + APIReader: apiServerHolding(s, j, string(apiPhase)), + Interface: dynamicfake.NewSimpleDynamicClientWithCustomListKinds(runtime.NewScheme(), map[schema.GroupVersionResource]string{gvr: "BucketList"}, app), + RESTMapper: &mockRESTMapper{mapping: &meta.RESTMapping{ + Resource: gvr, + GroupVersionKind: gvr.GroupVersion().WithKind("Bucket"), + Scope: meta.RESTScopeNamespace, + }}, + Scheme: s, + Recorder: record.NewFakeRecorder(10), + } + if _, err := r.Reconcile(context.Background(), reconcile.Request{NamespacedName: client.ObjectKeyFromObject(j)}); err != nil { + t.Fatalf("Reconcile: %v", err) + } + got := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(j), got); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + return countIn(t, c, &velerov1.BackupList{}), got.Status.Phase + } + + if created, _ := run(t, ""); created != 1 { + t.Fatalf("job still active on the apiserver: %d Velero Backups created, want 1", created) + } + created, cached := run(t, backupsv1alpha1.BackupJobPhaseFailed) + if created != 0 { + t.Errorf("job Failed on the apiserver: %d Velero Backups created, want 0", created) + } + if cached != "" { + t.Errorf("the pass wrote phase %q over a job it should have left alone", cached) + } +} + +// TestReconcileRestore_DoesNotRetryAJobItAlreadyFailed is the restore-side +// counterpart. The retried step is destructive there: before creating the +// Velero Restore, the pass suspends the VM's HelmRelease and halts the VM. +func TestReconcileRestore_DoesNotRetryAJobItAlreadyFailed(t *testing.T) { + const ns = "tenant" + strategyGroup := strategyv1alpha1.GroupVersion.Group + hrName := vmNamePrefix + "vm" + started := metav1.NewTime(time.Now().Add(-time.Second).Truncate(time.Second)) + + run := func(t *testing.T, apiPhase backupsv1alpha1.RestoreJobPhase) (restores int, hrSuspended bool, cached backupsv1alpha1.RestoreJobPhase) { + s := staleCacheScheme() + backup := &backupsv1alpha1.Backup{ + ObjectMeta: metav1.ObjectMeta{Name: "bk", Namespace: ns}, + Spec: backupsv1alpha1.BackupSpec{ + ApplicationRef: corev1.TypedLocalObjectReference{APIGroup: new("apps.cozystack.io"), Kind: vmInstanceKind, Name: "vm"}, + StrategyRef: corev1.TypedLocalObjectReference{APIGroup: &strategyGroup, Kind: strategyv1alpha1.VeleroStrategyKind, Name: "velero"}, + DriverMetadata: map[string]string{veleroBackupNameMetadataKey: "vb"}, + }, + } + rj := &backupsv1alpha1.RestoreJob{ + ObjectMeta: metav1.ObjectMeta{Name: "rj", Namespace: ns, Finalizers: []string{restoreJobFinalizer}}, + Spec: backupsv1alpha1.RestoreJobSpec{BackupRef: corev1.LocalObjectReference{Name: "bk"}}, + Status: backupsv1alpha1.RestoreJobStatus{StartedAt: &started, Phase: backupsv1alpha1.RestoreJobPhaseRunning}, + } + strategy := &strategyv1alpha1.Velero{ObjectMeta: metav1.ObjectMeta{Name: "velero"}} + c := clientfake.NewClientBuilder().WithScheme(s).WithObjects(rj, backup, strategy). + WithStatusSubresource(&backupsv1alpha1.RestoreJob{}).Build() + dyn := dynamicfake.NewSimpleDynamicClient(testCNPGScheme(t), makeUnstructuredHelmRelease(hrName, ns, nil)) + r := &RestoreJobReconciler{ + Client: c, + APIReader: apiServerHolding(s, rj, string(apiPhase)), + Interface: dyn, + Scheme: s, + Recorder: record.NewFakeRecorder(100), + } + if _, err := r.Reconcile(context.Background(), reconcile.Request{NamespacedName: client.ObjectKeyFromObject(rj)}); err != nil { + t.Fatalf("Reconcile: %v", err) + } + hr, err := dyn.Resource(helmReleaseGVR).Namespace(ns).Get(context.Background(), hrName, metav1.GetOptions{}) + if err != nil { + t.Fatalf("get HelmRelease: %v", err) + } + hrSuspended, _, _ = unstructured.NestedBool(hr.Object, "spec", "suspend") + got := &backupsv1alpha1.RestoreJob{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(rj), got); err != nil { + t.Fatalf("get RestoreJob: %v", err) + } + return countIn(t, c, &velerov1.RestoreList{}), hrSuspended, got.Status.Phase + } + + if restores, suspended, _ := run(t, backupsv1alpha1.RestoreJobPhaseRunning); restores != 1 || !suspended { + t.Fatalf("job still active on the apiserver: %d Velero Restores, HelmRelease suspended=%v; want 1 and true", restores, suspended) + } + restores, suspended, cached := run(t, backupsv1alpha1.RestoreJobPhaseFailed) + if suspended { + t.Error("job Failed on the apiserver: the pass suspended the VM's HelmRelease") + } + if restores != 0 { + t.Errorf("job Failed on the apiserver: %d Velero Restores created, want 0", restores) + } + if cached != backupsv1alpha1.RestoreJobPhaseRunning { + t.Errorf("the pass wrote phase %q over a job it should have left alone", cached) + } +}