From eeab99ae1ae05903075e4f6deb4611061fcf4e09 Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Thu, 19 Nov 2026 20:31:34 +0700 Subject: [PATCH 1/4] fix(backups): delete the Velero backup of a failed BackupJob When a Velero strategy run ended Failed or PartiallyFailed, no Backup was created, and the Backup finalizer was the only code that asked Velero to delete backup data. The failed backup.velero.io object, labelled for the BackupJob but not owned by it, stayed in the bucket with its partial resources and logs until Velero's TTL (720h by default) expired it, and deleting the BackupJob did not remove it. The strategy now requests the deletion through a DeleteBackupRequest before it marks the job Failed, and the failure message is still read from the Velero backup first. A direct delete is not enough, because the BSL sync recreates the object from the object store. A reconcile of a Failed BackupJob, which used to return at once, now requests deletion of every Velero backup still labelled for the job. That retries a request that could not be created and removes backups that earlier versions leaked, after an upgrade. A Velero backup that a Backup references (the job failed after its Backup was created) is left alone, and one still running is polled until Velero accepts a request for it. The sweep matches on the job labels, so it also covers the Velero backup of a failed Kubernetes strategy run. The request is named after the Velero backup, and the Backup finalizer uses the same helper, so repeated reconciles converge on one request. Nothing is created while another request for the backup is pending. A request that Velero processed with errors is replaced, because Velero keeps it for a day and its name would block the retry until then. A job with more than one Velero backup now fails with a message that names them, not with an empty one. Fake-client unit tests cover Failed and PartiallyFailed runs, a repeated reconcile, leftovers of already Failed jobs (no request, a pending request, a request processed with errors, a Backup-referenced backup, a running backup) and the unchanged Succeeded path. Closes: #5355 Assisted-by: LLM Signed-off-by: Andrey Kolkov (cherry picked from commit 5fbf7e9a38061dae585a944a5b520b70321507a2) Signed-off-by: Myasnikov Daniil --- .../backupcontroller/backup_controller.go | 28 +- .../backupcontroller/backupjob_controller.go | 6 +- .../velero_backup_deletion.go | 154 ++++++++++ .../velero_backup_deletion_test.go | 267 ++++++++++++++++++ .../velerostrategy_controller.go | 16 +- 5 files changed, 445 insertions(+), 26 deletions(-) create mode 100644 internal/backupcontroller/velero_backup_deletion.go create mode 100644 internal/backupcontroller/velero_backup_deletion_test.go diff --git a/internal/backupcontroller/backup_controller.go b/internal/backupcontroller/backup_controller.go index 1a8ec0b40..91076aaf9 100644 --- a/internal/backupcontroller/backup_controller.go +++ b/internal/backupcontroller/backup_controller.go @@ -234,28 +234,16 @@ func (r *BackupReconciler) cleanupVeleroBackup(ctx context.Context, backup *back return fmt.Errorf("failed to get Velero backup %s/%s: %w", veleroBackupNamespace, veleroBackupName, err) } - // Create a DeleteBackupRequest so Velero removes backup data from storage. - // Without this, BSL sync will recreate the backup.velero.io resource. - dbr := &velerov1.DeleteBackupRequest{ - ObjectMeta: metav1.ObjectMeta{ - GenerateName: veleroBackupName + "-", - Namespace: veleroBackupNamespace, - }, - Spec: velerov1.DeleteBackupRequestSpec{ - BackupName: veleroBackupName, - }, + created, err := requestVeleroBackupDeletion(ctx, r.Client, veleroBackupNamespace, veleroBackupName) + if err != nil { + return err } - if err := r.Create(ctx, dbr); err != nil { - if apierrors.IsAlreadyExists(err) { - logger.V(1).Info("DeleteBackupRequest already exists", "backup", veleroBackupName) - return nil - } - return fmt.Errorf("failed to create DeleteBackupRequest for %s/%s: %w", veleroBackupNamespace, veleroBackupName, err) + if created { + logger.Info("created DeleteBackupRequest for Velero backup", + "name", veleroBackupName, "namespace", veleroBackupNamespace) + } else { + logger.V(1).Info("deletion of Velero backup already requested", "backup", veleroBackupName) } - - logger.Info("created DeleteBackupRequest for Velero backup", - "name", veleroBackupName, "namespace", veleroBackupNamespace, - "deleteRequest", dbr.Name) return nil } diff --git a/internal/backupcontroller/backupjob_controller.go b/internal/backupcontroller/backupjob_controller.go index 791524240..1714dea46 100644 --- a/internal/backupcontroller/backupjob_controller.go +++ b/internal/backupcontroller/backupjob_controller.go @@ -61,7 +61,11 @@ func (r *BackupJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) ( // would otherwise materialise cozy-backups-creds in tenant namespaces // long after the BackupJob is done and pin needless work on the // apiserver. - if j.Status.Phase == backupsv1alpha1.BackupJobPhaseSucceeded || j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + if j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + logger.V(1).Info("BackupJob already terminal, cleaning up its Velero Backups", "phase", j.Status.Phase) + return r.deleteFailedJobVeleroBackups(ctx, j) + } + if j.Status.Phase == backupsv1alpha1.BackupJobPhaseSucceeded { logger.V(1).Info("BackupJob already terminal, skipping", "phase", j.Status.Phase) return ctrl.Result{}, nil } diff --git a/internal/backupcontroller/velero_backup_deletion.go b/internal/backupcontroller/velero_backup_deletion.go new file mode 100644 index 000000000..e93e6eee3 --- /dev/null +++ b/internal/backupcontroller/velero_backup_deletion.go @@ -0,0 +1,154 @@ +package backupcontroller + +import ( + "context" + "fmt" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + + backupsv1alpha1 "github.com/cozystack/cozystack/api/backups/v1alpha1" + + velerov1 "github.com/vmware-tanzu/velero/pkg/apis/velero/v1" +) + +// requestVeleroBackupDeletion asks Velero to delete a backup together with its +// data in the object store. Deleting the backup.velero.io object directly only +// removes the Kubernetes object, and the BSL sync recreates it from the object +// store. +// +// The request is named after the backup, so repeated calls converge on one +// request. Nothing is created while any request for the backup is unprocessed, +// or once one was processed without errors (Velero then removes the backup and +// the remaining requests). A request of ours that Velero processed with errors +// is replaced: Velero keeps it for a day, and until then its name would block +// the retry. +func requestVeleroBackupDeletion(ctx context.Context, c client.Client, namespace, name string) (bool, error) { + requests := &velerov1.DeleteBackupRequestList{} + if err := c.List(ctx, requests, client.InNamespace(namespace)); err != nil { + return false, fmt.Errorf("failed to list DeleteBackupRequests in %s: %w", namespace, err) + } + var failed *velerov1.DeleteBackupRequest + for i := range requests.Items { + dbr := &requests.Items[i] + if dbr.Spec.BackupName != name { + continue + } + if dbr.Status.Phase != velerov1.DeleteBackupRequestPhaseProcessed || len(dbr.Status.Errors) == 0 { + return false, nil + } + if dbr.Name == name { + failed = dbr + } + } + if failed != nil { + // The UID precondition keeps a stale cache from deleting a request + // that has already been replaced. + err := c.Delete(ctx, failed, client.Preconditions{UID: &failed.UID}) + if err != nil && !apierrors.IsNotFound(err) && !apierrors.IsConflict(err) { + return false, fmt.Errorf("failed to delete failed DeleteBackupRequest %s/%s: %w", namespace, name, err) + } + } + + dbr := &velerov1.DeleteBackupRequest{ + ObjectMeta: metav1.ObjectMeta{ + Name: name, + Namespace: namespace, + }, + Spec: velerov1.DeleteBackupRequestSpec{ + BackupName: name, + }, + } + if err := c.Create(ctx, dbr); err != nil { + if apierrors.IsAlreadyExists(err) { + return false, nil + } + return false, fmt.Errorf("failed to create DeleteBackupRequest for %s/%s: %w", namespace, name, err) + } + return true, nil +} + +// deleteFailedJobVeleroBackups requests deletion of the Velero backups a Failed +// BackupJob left behind. A failed run creates no Backup, and the Backup +// finalizer is the only other path that deletes Velero data, so without this +// the backup and its objects stay in the bucket until Velero's TTL expires +// them. It runs on every reconcile of a Failed job, which also clears backups +// left by controller versions that did not request the deletion. +func (r *BackupJobReconciler) deleteFailedJobVeleroBackups(ctx context.Context, j *backupsv1alpha1.BackupJob) (ctrl.Result, error) { + logger := getLogger(ctx) + + veleroBackups := &velerov1.BackupList{} + if err := r.List(ctx, veleroBackups, client.InNamespace(veleroNamespace), client.MatchingLabels{ + backupsv1alpha1.OwningJobNamespaceLabel: j.Namespace, + backupsv1alpha1.OwningJobNameLabel: j.Name, + }); err != nil { + if meta.IsNoMatchError(err) { + return ctrl.Result{}, nil + } + return ctrl.Result{}, fmt.Errorf("failed to list Velero Backups of BackupJob %s/%s: %w", j.Namespace, j.Name, err) + } + if len(veleroBackups.Items) == 0 { + return ctrl.Result{}, nil + } + + // A job can fail after its Backup was created: the status update that + // records the Backup is lost, and the retried create hits AlreadyExists. + // That Backup owns the Velero backup and deletes it itself. + referenced, err := r.veleroBackupsReferencedByBackups(ctx, j.Namespace) + if err != nil { + return ctrl.Result{}, err + } + + var running bool + for i := range veleroBackups.Items { + vb := &veleroBackups.Items[i] + if referenced[client.ObjectKeyFromObject(vb)] { + continue + } + switch vb.Status.Phase { + case velerov1.BackupPhaseCompleted, velerov1.BackupPhasePartiallyFailed, + velerov1.BackupPhaseFailed, velerov1.BackupPhaseFailedValidation: + case velerov1.BackupPhaseDeleting: + continue + default: + // Velero rejects a request for a backup that is still running. + running = true + continue + } + created, err := requestVeleroBackupDeletion(ctx, r.Client, vb.Namespace, vb.Name) + if err != nil { + return ctrl.Result{}, err + } + if created { + logger.Info("requested deletion of the Velero Backup of a failed BackupJob", + "backupjob", j.Name, "namespace", j.Namespace, "veleroBackup", vb.Name) + } + } + if running { + return ctrl.Result{RequeueAfter: defaultActiveJobPollingInterval}, nil + } + return ctrl.Result{}, nil +} + +func (r *BackupJobReconciler) veleroBackupsReferencedByBackups(ctx context.Context, namespace string) (map[client.ObjectKey]bool, error) { + backups := &backupsv1alpha1.BackupList{} + if err := r.List(ctx, backups, client.InNamespace(namespace)); err != nil { + return nil, fmt.Errorf("failed to list Backups in %s: %w", namespace, err) + } + referenced := map[client.ObjectKey]bool{} + for _, b := range backups.Items { + name := b.Spec.DriverMetadata[veleroBackupNameMetadataKey] + if name == "" { + continue + } + ns := b.Spec.DriverMetadata[veleroBackupNamespaceMetadataKey] + if ns == "" { + ns = veleroNamespace + } + referenced[client.ObjectKey{Namespace: ns, Name: name}] = true + } + return referenced, nil +} diff --git a/internal/backupcontroller/velero_backup_deletion_test.go b/internal/backupcontroller/velero_backup_deletion_test.go new file mode 100644 index 000000000..f69606556 --- /dev/null +++ b/internal/backupcontroller/velero_backup_deletion_test.go @@ -0,0 +1,267 @@ +package backupcontroller + +import ( + "context" + "testing" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/tools/record" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + 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" +) + +const ( + failedJobNamespace = "tenant-acme" + failedJobName = "vm-backup" +) + +func newVeleroCleanupReconciler(t *testing.T, objs ...client.Object) (*BackupJobReconciler, client.Client) { + t.Helper() + c := fake.NewClientBuilder(). + WithScheme(newReconcilerScheme(t)). + WithObjects(objs...). + WithStatusSubresource(&backupsv1alpha1.BackupJob{}). + Build() + return &BackupJobReconciler{Client: c, Recorder: record.NewFakeRecorder(16)}, c +} + +func veleroCleanupJob(phase backupsv1alpha1.BackupJobPhase) *backupsv1alpha1.BackupJob { + started := metav1.Now() + return &backupsv1alpha1.BackupJob{ + ObjectMeta: metav1.ObjectMeta{Namespace: failedJobNamespace, Name: failedJobName}, + Status: backupsv1alpha1.BackupJobStatus{ + Phase: phase, + StartedAt: &started, + }, + } +} + +func ownedVeleroBackup(name string, phase velerov1.BackupPhase) *velerov1.Backup { + return &velerov1.Backup{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: veleroNamespace, + Name: name, + Labels: map[string]string{ + backupsv1alpha1.OwningJobNameLabel: failedJobName, + backupsv1alpha1.OwningJobNamespaceLabel: failedJobNamespace, + }, + }, + Status: velerov1.BackupStatus{Phase: phase, FailureReason: "object store unreachable"}, + } +} + +func veleroCleanupResolved() *ResolvedBackupConfig { + apiGroup := strategyv1alpha1.GroupVersion.Group + return &ResolvedBackupConfig{StrategyRef: corev1.TypedLocalObjectReference{ + APIGroup: &apiGroup, Kind: strategyv1alpha1.VeleroStrategyKind, Name: "velero", + }} +} + +func veleroCleanupStrategy() *strategyv1alpha1.Velero { + return &strategyv1alpha1.Velero{ObjectMeta: metav1.ObjectMeta{Name: "velero"}} +} + +func listDeleteBackupRequests(t *testing.T, c client.Client) []velerov1.DeleteBackupRequest { + t.Helper() + l := &velerov1.DeleteBackupRequestList{} + if err := c.List(context.Background(), l, client.InNamespace(veleroNamespace)); err != nil { + t.Fatalf("list DeleteBackupRequests: %v", err) + } + return l.Items +} + +func reconcileFailedJob(t *testing.T, r *BackupJobReconciler) ctrl.Result { + t.Helper() + res, err := r.Reconcile(context.Background(), ctrl.Request{ + NamespacedName: types.NamespacedName{Namespace: failedJobNamespace, Name: failedJobName}, + }) + if err != nil { + t.Fatalf("Reconcile: %v", err) + } + return res +} + +func getCleanupJob(t *testing.T, c client.Client) *backupsv1alpha1.BackupJob { + t.Helper() + j := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: failedJobNamespace, Name: failedJobName}, j); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + return j +} + +// A Velero backup that ends Failed or PartiallyFailed produces no Backup, so +// the strategy must request its deletion itself, keep the failure message, and +// converge on a single request across reconciles. +func TestReconcileVelero_FailedBackupRequestsDeletion(t *testing.T) { + for _, phase := range []velerov1.BackupPhase{velerov1.BackupPhaseFailed, velerov1.BackupPhasePartiallyFailed} { + t.Run(string(phase), func(t *testing.T) { + vb := ownedVeleroBackup("tenant-acme.vm-backup-x7k2p", phase) + j := veleroCleanupJob(backupsv1alpha1.BackupJobPhaseRunning) + r, c := newVeleroCleanupReconciler(t, j, vb, veleroCleanupStrategy()) + + if _, err := r.reconcileVelero(context.Background(), j, veleroCleanupResolved()); err != nil { + t.Fatalf("reconcileVelero: %v", err) + } + + got := getCleanupJob(t, c) + if got.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("expected BackupJob Failed, got %q", got.Status.Phase) + } + wantMsg := "Velero Backup failed with phase " + string(phase) + ": object store unreachable" + if got.Status.Message != wantMsg { + t.Errorf("message = %q, want %q", got.Status.Message, wantMsg) + } + + dbrs := listDeleteBackupRequests(t, c) + if len(dbrs) != 1 || dbrs[0].Spec.BackupName != vb.Name { + t.Fatalf("expected one DeleteBackupRequest for %s, got %+v", vb.Name, dbrs) + } + + reconcileFailedJob(t, r) + if n := len(listDeleteBackupRequests(t, c)); n != 1 { + t.Fatalf("a second reconcile must not add a request, got %d", n) + } + }) + } +} + +func TestReconcileVelero_CompletedBackupRequestsNoDeletion(t *testing.T) { + vb := ownedVeleroBackup("tenant-acme.vm-backup-x7k2p", velerov1.BackupPhaseCompleted) + j := veleroCleanupJob(backupsv1alpha1.BackupJobPhaseRunning) + r, c := newVeleroCleanupReconciler(t, j, vb, veleroCleanupStrategy()) + + if _, err := r.reconcileVelero(context.Background(), j, veleroCleanupResolved()); err != nil { + t.Fatalf("reconcileVelero: %v", err) + } + if got := getCleanupJob(t, c); got.Status.Phase != backupsv1alpha1.BackupJobPhaseSucceeded { + t.Fatalf("expected BackupJob Succeeded, got %q (%s)", got.Status.Phase, got.Status.Message) + } + reconcileFailedJob(t, r) + if dbrs := listDeleteBackupRequests(t, c); len(dbrs) != 0 { + t.Fatalf("a succeeded run must not request deletion, got %+v", dbrs) + } +} + +func TestReconcileVelero_SeveralVeleroBackupsFailWithMessage(t *testing.T) { + j := veleroCleanupJob(backupsv1alpha1.BackupJobPhaseRunning) + r, c := newVeleroCleanupReconciler(t, j, veleroCleanupStrategy(), + ownedVeleroBackup("vb-b", velerov1.BackupPhaseFailed), + ownedVeleroBackup("vb-a", velerov1.BackupPhaseCompleted)) + + if _, err := r.reconcileVelero(context.Background(), j, veleroCleanupResolved()); err != nil { + t.Fatalf("reconcileVelero: %v", err) + } + got := getCleanupJob(t, c) + if got.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed || got.Status.CompletedAt == nil { + t.Fatalf("expected BackupJob Failed with completedAt, got %+v", got.Status) + } + if want := "more than one Velero Backup references this BackupJob: vb-a, vb-b"; got.Status.Message != want { + t.Errorf("message = %q, want %q", got.Status.Message, want) + } + + reconcileFailedJob(t, r) + if n := len(listDeleteBackupRequests(t, c)); n != 2 { + t.Fatalf("expected a request for each Velero backup, got %d", n) + } +} + +// A job that failed under a controller version without the cleanup still +// holds its Velero backup; reconciling it must request the deletion. +func TestReconcile_FailedJobLeftoverVeleroBackup(t *testing.T) { + vbName := "tenant-acme.vm-backup-x7k2p" + cases := []struct { + name string + veleroPhase velerov1.BackupPhase + jobPhase backupsv1alpha1.BackupJobPhase + existing []client.Object + wantNames []string + wantRequeue bool + }{ + { + name: "no request yet", + veleroPhase: velerov1.BackupPhasePartiallyFailed, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + wantNames: []string{vbName}, + }, + { + name: "pending request from elsewhere", + veleroPhase: velerov1.BackupPhaseFailed, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + existing: []client.Object{&velerov1.DeleteBackupRequest{ + ObjectMeta: metav1.ObjectMeta{Namespace: veleroNamespace, Name: vbName + "-abcde"}, + Spec: velerov1.DeleteBackupRequestSpec{BackupName: vbName}, + Status: velerov1.DeleteBackupRequestStatus{Phase: velerov1.DeleteBackupRequestPhaseInProgress}, + }}, + wantNames: []string{vbName + "-abcde"}, + }, + { + name: "own request processed with errors is replaced", + veleroPhase: velerov1.BackupPhaseFailed, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + existing: []client.Object{&velerov1.DeleteBackupRequest{ + ObjectMeta: metav1.ObjectMeta{Namespace: veleroNamespace, Name: vbName}, + Spec: velerov1.DeleteBackupRequestSpec{BackupName: vbName}, + Status: velerov1.DeleteBackupRequestStatus{ + Phase: velerov1.DeleteBackupRequestPhaseProcessed, + Errors: []string{"backup is still in progress"}, + }, + }}, + wantNames: []string{vbName}, + }, + { + name: "completed backup owned by a Backup", + veleroPhase: velerov1.BackupPhaseCompleted, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + existing: []client.Object{&backupsv1alpha1.Backup{ + ObjectMeta: metav1.ObjectMeta{Namespace: failedJobNamespace, Name: failedJobName}, + Spec: backupsv1alpha1.BackupSpec{DriverMetadata: map[string]string{ + veleroBackupNameMetadataKey: vbName, + veleroBackupNamespaceMetadataKey: veleroNamespace, + }}, + }}, + }, + { + name: "backup still running", + veleroPhase: velerov1.BackupPhaseInProgress, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + wantRequeue: true, + }, + { + name: "succeeded job", + veleroPhase: velerov1.BackupPhaseCompleted, + jobPhase: backupsv1alpha1.BackupJobPhaseSucceeded, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + objs := append([]client.Object{veleroCleanupJob(tc.jobPhase), ownedVeleroBackup(vbName, tc.veleroPhase)}, tc.existing...) + r, c := newVeleroCleanupReconciler(t, objs...) + + res := reconcileFailedJob(t, r) + if (res.RequeueAfter > 0) != tc.wantRequeue { + t.Errorf("RequeueAfter = %v, want requeue %v", res.RequeueAfter, tc.wantRequeue) + } + + dbrs := listDeleteBackupRequests(t, c) + if len(dbrs) != len(tc.wantNames) { + t.Fatalf("expected requests %v, got %+v", tc.wantNames, dbrs) + } + for i, want := range tc.wantNames { + if dbrs[i].Name != want || dbrs[i].Spec.BackupName != vbName { + t.Errorf("request %d = %s for %s, want %s for %s", i, dbrs[i].Name, dbrs[i].Spec.BackupName, want, vbName) + } + if dbrs[i].Status.Phase == velerov1.DeleteBackupRequestPhaseProcessed { + t.Errorf("request %s is the processed one, expected a fresh request", dbrs[i].Name) + } + } + }) + } +} diff --git a/internal/backupcontroller/velerostrategy_controller.go b/internal/backupcontroller/velerostrategy_controller.go index e08b2f818..f4e11bc87 100644 --- a/internal/backupcontroller/velerostrategy_controller.go +++ b/internal/backupcontroller/velerostrategy_controller.go @@ -307,12 +307,12 @@ func (r *BackupJobReconciler) reconcileVelero(ctx context.Context, j *backupsv1a } if len(veleroBackupList.Items) > 1 { - logger.Error(fmt.Errorf("too many Velero backups for BackupJob"), "found more than one Velero Backup referencing a single BackupJob as owner") - j.Status.Phase = backupsv1alpha1.BackupJobPhaseFailed - if err := r.Status().Update(ctx, j); err != nil { - logger.Error(err, "failed to update BackupJob status") + names := make([]string, 0, len(veleroBackupList.Items)) + for _, vb := range veleroBackupList.Items { + names = append(names, vb.Name) } - return ctrl.Result{}, nil + sort.Strings(names) + return r.markBackupJobFailed(ctx, j, fmt.Sprintf("more than one Velero Backup references this BackupJob: %s", strings.Join(names, ", "))) } veleroBackup := veleroBackupList.Items[0].DeepCopy() @@ -361,6 +361,12 @@ func (r *BackupJobReconciler) reconcileVelero(ctx context.Context, j *backupsv1a // Step 5: On failure if phase == "Failed" || phase == "PartiallyFailed" { message := formatVeleroBackupFailureMessageForBackupJob(ctx, r.Client, veleroBackup) + // No Backup is created for a failed run, so nothing else deletes this + // Velero backup. A failed request is retried by + // deleteFailedJobVeleroBackups once the job is Failed. + if _, err := requestVeleroBackupDeletion(ctx, r.Client, veleroBackup.Namespace, veleroBackup.Name); err != nil { + logger.Error(err, "failed to request deletion of the failed Velero Backup", "name", veleroBackup.Name) + } return r.markBackupJobFailed(ctx, j, message) } From e1d3161e7556a68aa5fb2c1858d53827d5d755d2 Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Thu, 19 Nov 2026 20:44:11 +0700 Subject: [PATCH 2/4] fix(backups): keep completed Velero backups of failed BackupJobs The failed-job sweep treated a Completed Velero backup as deletable. A BackupJob can fail after Velero completed, when creating or recording its Backup fails transiently, and that Velero backup may be the only copy of a good backup. The sweep now deletes only Failed, PartiallyFailed and FailedValidation backups, also when several Velero backups reference one job, and it reads the Backups that may reference them through the uncached API reader, so a Backup the cache has not seen yet still protects its data. The Velero strategy no longer requests the deletion before it records the failure. If that status write failed, Velero removed the backup and the retried run created a new one, so the failure was lost. The deletion now comes only from the sweep, which runs on the reconcile that the persisted Failed phase triggers; the BackupJob watch has no predicate that drops status updates. Replacing a request that Velero processed with errors deletes it, and the backupstrategy-controller ClusterRole only allowed create, get, list and watch on deletebackuprequests. That Delete failed with 403, and since the Backup finalizer uses the same helper, a Backup deletion could get stuck on it. The rule now includes delete. Nothing watches DeleteBackupRequests, so the sweep did not run again after Velero processed a request with errors. A Failed job now requeues every 5 minutes while a failed Velero backup of it remains, which replaces such a request, and every minute while one is still running, instead of every 5 seconds. Unit tests cover a rejected Failed status write, Completed, Deleting and FailedValidation backups, a request processed with and without errors, the UID precondition on the replacement, a Backup visible only to the uncached reader, and API errors from the helper. Refs: #5355 Assisted-by: LLM Signed-off-by: Andrey Kolkov (cherry picked from commit 887453c008f9e2b06a018b3456768dc1b93bdf9f) Signed-off-by: Myasnikov Daniil --- .../velero_backup_deletion.go | 91 +++--- .../velero_backup_deletion_test.go | 266 +++++++++++++----- .../velerostrategy_controller.go | 8 +- .../templates/rbac.yaml | 5 +- 4 files changed, 263 insertions(+), 107 deletions(-) diff --git a/internal/backupcontroller/velero_backup_deletion.go b/internal/backupcontroller/velero_backup_deletion.go index e93e6eee3..0e9de24b2 100644 --- a/internal/backupcontroller/velero_backup_deletion.go +++ b/internal/backupcontroller/velero_backup_deletion.go @@ -3,6 +3,7 @@ package backupcontroller import ( "context" "fmt" + "time" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" @@ -24,8 +25,9 @@ import ( // request. Nothing is created while any request for the backup is unprocessed, // or once one was processed without errors (Velero then removes the backup and // the remaining requests). A request of ours that Velero processed with errors -// is replaced: Velero keeps it for a day, and until then its name would block -// the retry. +// is deleted and created again: Velero keeps it for a day, and until then its +// name would block a new attempt. Velero does not retry a processed request, +// so a caller that needs the deletion to happen must call again later. func requestVeleroBackupDeletion(ctx context.Context, c client.Client, namespace, name string) (bool, error) { requests := &velerov1.DeleteBackupRequestList{} if err := c.List(ctx, requests, client.InNamespace(namespace)); err != nil { @@ -71,12 +73,27 @@ func requestVeleroBackupDeletion(ctx context.Context, c client.Client, namespace return true, nil } -// deleteFailedJobVeleroBackups requests deletion of the Velero backups a Failed -// BackupJob left behind. A failed run creates no Backup, and the Backup -// finalizer is the only other path that deletes Velero data, so without this -// the backup and its objects stay in the bucket until Velero's TTL expires -// them. It runs on every reconcile of a Failed job, which also clears backups -// left by controller versions that did not request the deletion. +const ( + // failedJobSweepRequeue is how often a Failed BackupJob is reconciled + // again while one of its Velero backups still waits for deletion. Nothing + // watches DeleteBackupRequests, so a request Velero processed with errors + // is only noticed, and replaced, on this requeue. + failedJobSweepRequeue = 5 * time.Minute + // failedJobRunningBackupRequeue is how often a Failed BackupJob is + // reconciled again while one of its Velero backups is still running. + // Velero rejects a deletion request for a running backup. + failedJobRunningBackupRequeue = time.Minute +) + +// deleteFailedJobVeleroBackups requests deletion of the failed Velero backups +// a Failed BackupJob left behind. A failed run creates no Backup, and the +// Backup finalizer is the only other path that deletes Velero data, so without +// this the backup and its objects stay in the bucket until Velero's TTL +// expires them. It runs on every reconcile of a Failed job, which also clears +// backups left by controller versions that did not request the deletion, and +// it requests the deletion only once the Failed phase is persisted: a request +// sent before that write would let a retried run start over with the failure +// already gone. func (r *BackupJobReconciler) deleteFailedJobVeleroBackups(ctx context.Context, j *backupsv1alpha1.BackupJob) (ctrl.Result, error) { logger := getLogger(ctx) @@ -94,30 +111,33 @@ func (r *BackupJobReconciler) deleteFailedJobVeleroBackups(ctx context.Context, return ctrl.Result{}, nil } - // A job can fail after its Backup was created: the status update that - // records the Backup is lost, and the retried create hits AlreadyExists. - // That Backup owns the Velero backup and deletes it itself. - referenced, err := r.veleroBackupsReferencedByBackups(ctx, j.Namespace) - if err != nil { - return ctrl.Result{}, err - } - - var running bool + var referenced map[client.ObjectKey]bool + var requeueAfter time.Duration for i := range veleroBackups.Items { vb := &veleroBackups.Items[i] + switch vb.Status.Phase { + case velerov1.BackupPhasePartiallyFailed, velerov1.BackupPhaseFailed, velerov1.BackupPhaseFailedValidation: + case velerov1.BackupPhaseCompleted, velerov1.BackupPhaseDeleting: + // A job can fail after Velero completed, when creating or + // recording its Backup fails. That Velero backup may be the only + // copy of good data, and a Backup that already references it + // deletes it itself, so a job-level failure never removes it. + continue + default: + requeueAfter = shorterRequeue(requeueAfter, failedJobRunningBackupRequeue) + continue + } + + if referenced == nil { + var err error + if referenced, err = r.veleroBackupsReferencedByBackups(ctx, j.Namespace); err != nil { + return ctrl.Result{}, err + } + } if referenced[client.ObjectKeyFromObject(vb)] { continue } - switch vb.Status.Phase { - case velerov1.BackupPhaseCompleted, velerov1.BackupPhasePartiallyFailed, - velerov1.BackupPhaseFailed, velerov1.BackupPhaseFailedValidation: - case velerov1.BackupPhaseDeleting: - continue - default: - // Velero rejects a request for a backup that is still running. - running = true - continue - } + created, err := requestVeleroBackupDeletion(ctx, r.Client, vb.Namespace, vb.Name) if err != nil { return ctrl.Result{}, err @@ -126,16 +146,23 @@ func (r *BackupJobReconciler) deleteFailedJobVeleroBackups(ctx context.Context, logger.Info("requested deletion of the Velero Backup of a failed BackupJob", "backupjob", j.Name, "namespace", j.Namespace, "veleroBackup", vb.Name) } + requeueAfter = shorterRequeue(requeueAfter, failedJobSweepRequeue) } - if running { - return ctrl.Result{RequeueAfter: defaultActiveJobPollingInterval}, nil - } - return ctrl.Result{}, nil + return ctrl.Result{RequeueAfter: requeueAfter}, nil } +func shorterRequeue(current, next time.Duration) time.Duration { + if current == 0 || next < current { + return next + } + return current +} + +// veleroBackupsReferencedByBackups reads Backups past the cache: a Backup the +// cache has not seen yet must still protect its Velero backup from deletion. func (r *BackupJobReconciler) veleroBackupsReferencedByBackups(ctx context.Context, namespace string) (map[client.ObjectKey]bool, error) { backups := &backupsv1alpha1.BackupList{} - if err := r.List(ctx, backups, client.InNamespace(namespace)); err != nil { + if err := r.apiReader().List(ctx, backups, client.InNamespace(namespace)); err != nil { return nil, fmt.Errorf("failed to list Backups in %s: %w", namespace, err) } referenced := map[client.ObjectKey]bool{} diff --git a/internal/backupcontroller/velero_backup_deletion_test.go b/internal/backupcontroller/velero_backup_deletion_test.go index f69606556..d283e6262 100644 --- a/internal/backupcontroller/velero_backup_deletion_test.go +++ b/internal/backupcontroller/velero_backup_deletion_test.go @@ -2,15 +2,19 @@ package backupcontroller import ( "context" + "errors" "testing" 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/schema" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/tools/record" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" strategyv1alpha1 "github.com/cozystack/cozystack/api/backups/strategy/v1alpha1" backupsv1alpha1 "github.com/cozystack/cozystack/api/backups/v1alpha1" @@ -20,15 +24,24 @@ import ( const ( failedJobNamespace = "tenant-acme" failedJobName = "vm-backup" + failedVeleroBackup = "tenant-acme.vm-backup-x7k2p" ) +func newVeleroCleanupClient(t *testing.T, funcs *interceptor.Funcs, objs ...client.Object) client.Client { + t.Helper() + b := fake.NewClientBuilder(). + WithScheme(newReconcilerScheme(t)). + WithObjects(objs...). + WithStatusSubresource(&backupsv1alpha1.BackupJob{}) + if funcs != nil { + b = b.WithInterceptorFuncs(*funcs) + } + return b.Build() +} + func newVeleroCleanupReconciler(t *testing.T, objs ...client.Object) (*BackupJobReconciler, client.Client) { t.Helper() - c := fake.NewClientBuilder(). - WithScheme(newReconcilerScheme(t)). - WithObjects(objs...). - WithStatusSubresource(&backupsv1alpha1.BackupJob{}). - Build() + c := newVeleroCleanupClient(t, nil, objs...) return &BackupJobReconciler{Client: c, Recorder: record.NewFakeRecorder(16)}, c } @@ -57,6 +70,24 @@ func ownedVeleroBackup(name string, phase velerov1.BackupPhase) *velerov1.Backup } } +func referencingBackup(veleroBackupName string) *backupsv1alpha1.Backup { + return &backupsv1alpha1.Backup{ + ObjectMeta: metav1.ObjectMeta{Namespace: failedJobNamespace, Name: failedJobName}, + Spec: backupsv1alpha1.BackupSpec{DriverMetadata: map[string]string{ + veleroBackupNameMetadataKey: veleroBackupName, + veleroBackupNamespaceMetadataKey: veleroNamespace, + }}, + } +} + +func deleteRequest(name string, phase velerov1.DeleteBackupRequestPhase, errs ...string) *velerov1.DeleteBackupRequest { + return &velerov1.DeleteBackupRequest{ + ObjectMeta: metav1.ObjectMeta{Namespace: veleroNamespace, Name: name, UID: types.UID(name + "-uid")}, + Spec: velerov1.DeleteBackupRequestSpec{BackupName: failedVeleroBackup}, + Status: velerov1.DeleteBackupRequestStatus{Phase: phase, Errors: errs}, + } +} + func veleroCleanupResolved() *ResolvedBackupConfig { apiGroup := strategyv1alpha1.GroupVersion.Group return &ResolvedBackupConfig{StrategyRef: corev1.TypedLocalObjectReference{ @@ -77,7 +108,7 @@ func listDeleteBackupRequests(t *testing.T, c client.Client) []velerov1.DeleteBa return l.Items } -func reconcileFailedJob(t *testing.T, r *BackupJobReconciler) ctrl.Result { +func reconcileCleanupJob(t *testing.T, r *BackupJobReconciler) ctrl.Result { t.Helper() res, err := r.Reconcile(context.Background(), ctrl.Request{ NamespacedName: types.NamespacedName{Namespace: failedJobNamespace, Name: failedJobName}, @@ -97,20 +128,18 @@ func getCleanupJob(t *testing.T, c client.Client) *backupsv1alpha1.BackupJob { return j } -// A Velero backup that ends Failed or PartiallyFailed produces no Backup, so -// the strategy must request its deletion itself, keep the failure message, and -// converge on a single request across reconciles. -func TestReconcileVelero_FailedBackupRequestsDeletion(t *testing.T) { +// A Velero backup that ends Failed or PartiallyFailed produces no Backup. The +// run keeps its failure message, and the deletion is requested by the +// reconcile that follows the persisted Failed phase, once. +func TestReconcileVelero_FailedBackupRequestsDeletionAfterFailedIsPersisted(t *testing.T) { for _, phase := range []velerov1.BackupPhase{velerov1.BackupPhaseFailed, velerov1.BackupPhasePartiallyFailed} { t.Run(string(phase), func(t *testing.T) { - vb := ownedVeleroBackup("tenant-acme.vm-backup-x7k2p", phase) j := veleroCleanupJob(backupsv1alpha1.BackupJobPhaseRunning) - r, c := newVeleroCleanupReconciler(t, j, vb, veleroCleanupStrategy()) + r, c := newVeleroCleanupReconciler(t, j, ownedVeleroBackup(failedVeleroBackup, phase), veleroCleanupStrategy()) if _, err := r.reconcileVelero(context.Background(), j, veleroCleanupResolved()); err != nil { t.Fatalf("reconcileVelero: %v", err) } - got := getCleanupJob(t, c) if got.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { t.Fatalf("expected BackupJob Failed, got %q", got.Status.Phase) @@ -119,13 +148,19 @@ func TestReconcileVelero_FailedBackupRequestsDeletion(t *testing.T) { if got.Status.Message != wantMsg { t.Errorf("message = %q, want %q", got.Status.Message, wantMsg) } - - dbrs := listDeleteBackupRequests(t, c) - if len(dbrs) != 1 || dbrs[0].Spec.BackupName != vb.Name { - t.Fatalf("expected one DeleteBackupRequest for %s, got %+v", vb.Name, dbrs) + if dbrs := listDeleteBackupRequests(t, c); len(dbrs) != 0 { + t.Fatalf("deletion must wait for the next reconcile, got %+v", dbrs) } - reconcileFailedJob(t, r) + if res := reconcileCleanupJob(t, r); res.RequeueAfter != failedJobSweepRequeue { + t.Errorf("RequeueAfter = %v, want %v", res.RequeueAfter, failedJobSweepRequeue) + } + dbrs := listDeleteBackupRequests(t, c) + if len(dbrs) != 1 || dbrs[0].Name != failedVeleroBackup || dbrs[0].Spec.BackupName != failedVeleroBackup { + t.Fatalf("expected one DeleteBackupRequest for %s, got %+v", failedVeleroBackup, dbrs) + } + + reconcileCleanupJob(t, r) if n := len(listDeleteBackupRequests(t, c)); n != 1 { t.Fatalf("a second reconcile must not add a request, got %d", n) } @@ -133,10 +168,35 @@ func TestReconcileVelero_FailedBackupRequestsDeletion(t *testing.T) { } } -func TestReconcileVelero_CompletedBackupRequestsNoDeletion(t *testing.T) { - vb := ownedVeleroBackup("tenant-acme.vm-backup-x7k2p", velerov1.BackupPhaseCompleted) +// If the Failed phase cannot be written, the run is retried and must still +// find its Velero backup to report the failure from. +func TestReconcileVelero_FailedStatusWriteErrorRequestsNoDeletion(t *testing.T) { j := veleroCleanupJob(backupsv1alpha1.BackupJobPhaseRunning) - r, c := newVeleroCleanupReconciler(t, j, vb, veleroCleanupStrategy()) + funcs := &interceptor.Funcs{ + SubResourceUpdate: func(ctx context.Context, c client.Client, sub string, obj client.Object, opts ...client.SubResourceUpdateOption) error { + if bj, ok := obj.(*backupsv1alpha1.BackupJob); ok && bj.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + return apierrors.NewServiceUnavailable("etcd timeout") + } + return c.SubResource(sub).Update(ctx, obj, opts...) + }, + } + c := newVeleroCleanupClient(t, funcs, j, ownedVeleroBackup(failedVeleroBackup, velerov1.BackupPhaseFailed), veleroCleanupStrategy()) + r := &BackupJobReconciler{Client: c, Recorder: record.NewFakeRecorder(16)} + + if _, err := r.reconcileVelero(context.Background(), j, veleroCleanupResolved()); err == nil { + t.Fatal("expected the status write error to be returned") + } + if got := getCleanupJob(t, c); got.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("status write was rejected, got phase %q", got.Status.Phase) + } + if dbrs := listDeleteBackupRequests(t, c); len(dbrs) != 0 { + t.Fatalf("no deletion may be requested before Failed is persisted, got %+v", dbrs) + } +} + +func TestReconcileVelero_CompletedBackupRequestsNoDeletion(t *testing.T) { + j := veleroCleanupJob(backupsv1alpha1.BackupJobPhaseRunning) + r, c := newVeleroCleanupReconciler(t, j, ownedVeleroBackup(failedVeleroBackup, velerov1.BackupPhaseCompleted), veleroCleanupStrategy()) if _, err := r.reconcileVelero(context.Background(), j, veleroCleanupResolved()); err != nil { t.Fatalf("reconcileVelero: %v", err) @@ -144,13 +204,13 @@ func TestReconcileVelero_CompletedBackupRequestsNoDeletion(t *testing.T) { if got := getCleanupJob(t, c); got.Status.Phase != backupsv1alpha1.BackupJobPhaseSucceeded { t.Fatalf("expected BackupJob Succeeded, got %q (%s)", got.Status.Phase, got.Status.Message) } - reconcileFailedJob(t, r) + reconcileCleanupJob(t, r) if dbrs := listDeleteBackupRequests(t, c); len(dbrs) != 0 { t.Fatalf("a succeeded run must not request deletion, got %+v", dbrs) } } -func TestReconcileVelero_SeveralVeleroBackupsFailWithMessage(t *testing.T) { +func TestReconcileVelero_SeveralVeleroBackupsKeepCompletedOne(t *testing.T) { j := veleroCleanupJob(backupsv1alpha1.BackupJobPhaseRunning) r, c := newVeleroCleanupReconciler(t, j, veleroCleanupStrategy(), ownedVeleroBackup("vb-b", velerov1.BackupPhaseFailed), @@ -167,87 +227,111 @@ func TestReconcileVelero_SeveralVeleroBackupsFailWithMessage(t *testing.T) { t.Errorf("message = %q, want %q", got.Status.Message, want) } - reconcileFailedJob(t, r) - if n := len(listDeleteBackupRequests(t, c)); n != 2 { - t.Fatalf("expected a request for each Velero backup, got %d", n) + reconcileCleanupJob(t, r) + dbrs := listDeleteBackupRequests(t, c) + if len(dbrs) != 1 || dbrs[0].Spec.BackupName != "vb-b" { + t.Fatalf("expected a request for the failed vb-b only, got %+v", dbrs) } } -// A job that failed under a controller version without the cleanup still -// holds its Velero backup; reconciling it must request the deletion. -func TestReconcile_FailedJobLeftoverVeleroBackup(t *testing.T) { - vbName := "tenant-acme.vm-backup-x7k2p" +// Reconciling a Failed BackupJob, including one that failed under a version +// without the cleanup, requests deletion of its failed Velero backups only. +func TestReconcile_FailedJobVeleroBackupSweep(t *testing.T) { cases := []struct { name string veleroPhase velerov1.BackupPhase jobPhase backupsv1alpha1.BackupJobPhase existing []client.Object + // Backups visible to the uncached reader only. + uncached []client.Object wantNames []string - wantRequeue bool + wantPhase velerov1.DeleteBackupRequestPhase + wantRequeue ctrl.Result }{ { - name: "no request yet", + name: "PartiallyFailed without a request", veleroPhase: velerov1.BackupPhasePartiallyFailed, jobPhase: backupsv1alpha1.BackupJobPhaseFailed, - wantNames: []string{vbName}, + wantNames: []string{failedVeleroBackup}, + wantRequeue: ctrl.Result{RequeueAfter: failedJobSweepRequeue}, + }, + { + name: "FailedValidation is deleted", + veleroPhase: velerov1.BackupPhaseFailedValidation, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + wantNames: []string{failedVeleroBackup}, + wantRequeue: ctrl.Result{RequeueAfter: failedJobSweepRequeue}, }, { name: "pending request from elsewhere", veleroPhase: velerov1.BackupPhaseFailed, jobPhase: backupsv1alpha1.BackupJobPhaseFailed, - existing: []client.Object{&velerov1.DeleteBackupRequest{ - ObjectMeta: metav1.ObjectMeta{Namespace: veleroNamespace, Name: vbName + "-abcde"}, - Spec: velerov1.DeleteBackupRequestSpec{BackupName: vbName}, - Status: velerov1.DeleteBackupRequestStatus{Phase: velerov1.DeleteBackupRequestPhaseInProgress}, - }}, - wantNames: []string{vbName + "-abcde"}, + existing: []client.Object{deleteRequest(failedVeleroBackup+"-abcde", velerov1.DeleteBackupRequestPhaseInProgress)}, + wantNames: []string{failedVeleroBackup + "-abcde"}, + wantPhase: velerov1.DeleteBackupRequestPhaseInProgress, + wantRequeue: ctrl.Result{RequeueAfter: failedJobSweepRequeue}, }, { name: "own request processed with errors is replaced", veleroPhase: velerov1.BackupPhaseFailed, jobPhase: backupsv1alpha1.BackupJobPhaseFailed, - existing: []client.Object{&velerov1.DeleteBackupRequest{ - ObjectMeta: metav1.ObjectMeta{Namespace: veleroNamespace, Name: vbName}, - Spec: velerov1.DeleteBackupRequestSpec{BackupName: vbName}, - Status: velerov1.DeleteBackupRequestStatus{ - Phase: velerov1.DeleteBackupRequestPhaseProcessed, - Errors: []string{"backup is still in progress"}, - }, - }}, - wantNames: []string{vbName}, + existing: []client.Object{deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed, "backup is still in progress")}, + wantNames: []string{failedVeleroBackup}, + wantRequeue: ctrl.Result{RequeueAfter: failedJobSweepRequeue}, }, { - name: "completed backup owned by a Backup", + name: "request processed without errors is kept", + veleroPhase: velerov1.BackupPhaseFailed, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + existing: []client.Object{deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed)}, + wantNames: []string{failedVeleroBackup}, + wantPhase: velerov1.DeleteBackupRequestPhaseProcessed, + wantRequeue: ctrl.Result{RequeueAfter: failedJobSweepRequeue}, + }, + { + name: "Completed is never deleted", veleroPhase: velerov1.BackupPhaseCompleted, jobPhase: backupsv1alpha1.BackupJobPhaseFailed, - existing: []client.Object{&backupsv1alpha1.Backup{ - ObjectMeta: metav1.ObjectMeta{Namespace: failedJobNamespace, Name: failedJobName}, - Spec: backupsv1alpha1.BackupSpec{DriverMetadata: map[string]string{ - veleroBackupNameMetadataKey: vbName, - veleroBackupNamespaceMetadataKey: veleroNamespace, - }}, - }}, }, { - name: "backup still running", + name: "Deleting is skipped", + veleroPhase: velerov1.BackupPhaseDeleting, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + }, + { + name: "failed backup referenced by a Backup the cache has not seen", + veleroPhase: velerov1.BackupPhaseFailed, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + uncached: []client.Object{referencingBackup(failedVeleroBackup)}, + }, + { + name: "running backup", veleroPhase: velerov1.BackupPhaseInProgress, jobPhase: backupsv1alpha1.BackupJobPhaseFailed, - wantRequeue: true, + wantRequeue: ctrl.Result{RequeueAfter: failedJobRunningBackupRequeue}, + }, + { + name: "new backup", + veleroPhase: "", + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + wantRequeue: ctrl.Result{RequeueAfter: failedJobRunningBackupRequeue}, }, { name: "succeeded job", - veleroPhase: velerov1.BackupPhaseCompleted, + veleroPhase: velerov1.BackupPhaseFailed, jobPhase: backupsv1alpha1.BackupJobPhaseSucceeded, }, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - objs := append([]client.Object{veleroCleanupJob(tc.jobPhase), ownedVeleroBackup(vbName, tc.veleroPhase)}, tc.existing...) + objs := append([]client.Object{veleroCleanupJob(tc.jobPhase), ownedVeleroBackup(failedVeleroBackup, tc.veleroPhase)}, tc.existing...) r, c := newVeleroCleanupReconciler(t, objs...) + if tc.uncached != nil { + r.APIReader = newVeleroCleanupClient(t, nil, tc.uncached...) + } - res := reconcileFailedJob(t, r) - if (res.RequeueAfter > 0) != tc.wantRequeue { - t.Errorf("RequeueAfter = %v, want requeue %v", res.RequeueAfter, tc.wantRequeue) + if res := reconcileCleanupJob(t, r); res != tc.wantRequeue { + t.Errorf("Result = %+v, want %+v", res, tc.wantRequeue) } dbrs := listDeleteBackupRequests(t, c) @@ -255,13 +339,61 @@ func TestReconcile_FailedJobLeftoverVeleroBackup(t *testing.T) { t.Fatalf("expected requests %v, got %+v", tc.wantNames, dbrs) } for i, want := range tc.wantNames { - if dbrs[i].Name != want || dbrs[i].Spec.BackupName != vbName { - t.Errorf("request %d = %s for %s, want %s for %s", i, dbrs[i].Name, dbrs[i].Spec.BackupName, want, vbName) + if dbrs[i].Name != want || dbrs[i].Spec.BackupName != failedVeleroBackup { + t.Errorf("request %d = %s for %s, want %s for %s", i, dbrs[i].Name, dbrs[i].Spec.BackupName, want, failedVeleroBackup) } - if dbrs[i].Status.Phase == velerov1.DeleteBackupRequestPhaseProcessed { - t.Errorf("request %s is the processed one, expected a fresh request", dbrs[i].Name) + if dbrs[i].Status.Phase != tc.wantPhase { + t.Errorf("request %s phase = %q, want %q", dbrs[i].Name, dbrs[i].Status.Phase, tc.wantPhase) } } }) } } + +func TestRequestVeleroBackupDeletion_ReplacesByUID(t *testing.T) { + stale := deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed, "backup storage location unavailable") + var preconditionUID types.UID + funcs := &interceptor.Funcs{ + Delete: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.DeleteOption) error { + do := &client.DeleteOptions{} + do.ApplyOptions(opts) + if do.Preconditions != nil && do.Preconditions.UID != nil { + preconditionUID = *do.Preconditions.UID + } + return c.Delete(ctx, obj, opts...) + }, + } + c := newVeleroCleanupClient(t, funcs, stale) + created, err := requestVeleroBackupDeletion(context.Background(), c, veleroNamespace, failedVeleroBackup) + if err != nil || !created { + t.Fatalf("requestVeleroBackupDeletion = (%v, %v), want (true, nil)", created, err) + } + if preconditionUID != stale.UID { + t.Errorf("Delete precondition UID = %q, want %q", preconditionUID, stale.UID) + } +} + +func TestRequestVeleroBackupDeletion_ReturnsAPIErrors(t *testing.T) { + forbidden := apierrors.NewForbidden(schema.GroupResource{Group: "velero.io", Resource: "deletebackuprequests"}, failedVeleroBackup, errors.New("denied")) + cases := map[string]interceptor.Funcs{ + "list": {List: func(context.Context, client.WithWatch, client.ObjectList, ...client.ListOption) error { + return forbidden + }}, + "create": {Create: func(context.Context, client.WithWatch, client.Object, ...client.CreateOption) error { + return forbidden + }}, + "delete": {Delete: func(context.Context, client.WithWatch, client.Object, ...client.DeleteOption) error { + return forbidden + }}, + } + for name, funcs := range cases { + t.Run(name, func(t *testing.T) { + c := newVeleroCleanupClient(t, &funcs, + deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed, "backup storage location unavailable")) + created, err := requestVeleroBackupDeletion(context.Background(), c, veleroNamespace, failedVeleroBackup) + if created || !apierrors.IsForbidden(err) { + t.Fatalf("requestVeleroBackupDeletion = (%v, %v), want a Forbidden error", created, err) + } + }) + } +} diff --git a/internal/backupcontroller/velerostrategy_controller.go b/internal/backupcontroller/velerostrategy_controller.go index f4e11bc87..7db5b5a19 100644 --- a/internal/backupcontroller/velerostrategy_controller.go +++ b/internal/backupcontroller/velerostrategy_controller.go @@ -360,13 +360,9 @@ func (r *BackupJobReconciler) reconcileVelero(ctx context.Context, j *backupsv1a // Step 5: On failure if phase == "Failed" || phase == "PartiallyFailed" { + // The Velero backup is deleted by deleteFailedJobVeleroBackups once + // the Failed phase written here triggers the next reconcile. message := formatVeleroBackupFailureMessageForBackupJob(ctx, r.Client, veleroBackup) - // No Backup is created for a failed run, so nothing else deletes this - // Velero backup. A failed request is retried by - // deleteFailedJobVeleroBackups once the job is Failed. - if _, err := requestVeleroBackupDeletion(ctx, r.Client, veleroBackup.Namespace, veleroBackup.Name); err != nil { - logger.Error(err, "failed to request deletion of the failed Velero Backup", "name", veleroBackup.Name) - } return r.markBackupJobFailed(ctx, j, message) } diff --git a/packages/system/backupstrategy-controller/templates/rbac.yaml b/packages/system/backupstrategy-controller/templates/rbac.yaml index ac9124392..10217b03c 100644 --- a/packages/system/backupstrategy-controller/templates/rbac.yaml +++ b/packages/system/backupstrategy-controller/templates/rbac.yaml @@ -90,10 +90,11 @@ rules: - apiGroups: ["velero.io"] resources: ["backupstoragelocations"] verbs: ["get"] -# Velero DeleteBackupRequest: used by BackupReconciler to delete Velero backups with their storage data +# Velero DeleteBackupRequest: used to delete Velero backups with their storage +# data. delete replaces a request Velero processed with errors. - apiGroups: ["velero.io"] resources: ["deletebackuprequests"] - verbs: ["create", "get", "list", "watch"] + verbs: ["create", "get", "list", "watch", "delete"] # Namespaces: validate target namespace exists for cross-namespace restore # controller-runtime cache requires list/watch for any resource accessed via r.Get() - apiGroups: [""] From e8cec9262676e9f4e884d45dc24c86117cf9eeae Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Thu, 19 Nov 2026 20:56:45 +0700 Subject: [PATCH 3/4] fix(backups): retry stuck Velero deletions of failed BackupJobs and report them Velero marks a backup Deleting before it removes the data and leaves it in that phase when removing the data fails, with the deletion request processed with errors. The failed-job sweep skipped Deleting backups and did not requeue for them, so their data stayed in the bucket until Velero's TTL. Deleting backups now go through the same request path: a pending request is left alone, and a processed one of ours is replaced. A request of ours that Velero processed without errors is also replaced when the backup still exists, for example after the BSL sync brought it back. Otherwise the request name blocked a new attempt until Velero garbage-collects processed requests a day later. When Velero can never carry out the deletion, because the backup storage location is missing, read-only or unavailable, the sweep replaced the request every 5 minutes without any sign of it. Each replacement now emits a VeleroBackupDeletionFailed Warning event on the BackupJob with Velero's status.errors, and doubles the requeue interval from 5 minutes up to 1 hour. The count is kept in the backups.cozystack.io/velero-deletion-retries annotation, because the replaced request is gone and a requeue carries no state. The controller's ClusterRole already allows patching BackupJobs. Unit tests cover a Deleting backup with a pending request and with an errored one, a cleanly processed request whose backup still exists, an errored request under a foreign name that is left alone, three consecutive failed deletions (three events, 10m, 20m and 40m requeues, the 1h cap), and a cluster without the Velero CRDs. Refs: #5355 Assisted-by: LLM Signed-off-by: Andrey Kolkov (cherry picked from commit 73df99b77d4cb44c94f9c9b716751073b511e417) Signed-off-by: Myasnikov Daniil --- .../backupcontroller/backup_controller.go | 4 +- .../backupcontroller/backupjob_controller.go | 11 +- .../velero_backup_deletion.go | 141 +++++++++--- .../velero_backup_deletion_test.go | 209 +++++++++++++----- 4 files changed, 273 insertions(+), 92 deletions(-) diff --git a/internal/backupcontroller/backup_controller.go b/internal/backupcontroller/backup_controller.go index 91076aaf9..3f4f9fc42 100644 --- a/internal/backupcontroller/backup_controller.go +++ b/internal/backupcontroller/backup_controller.go @@ -234,11 +234,11 @@ func (r *BackupReconciler) cleanupVeleroBackup(ctx context.Context, backup *back return fmt.Errorf("failed to get Velero backup %s/%s: %w", veleroBackupNamespace, veleroBackupName, err) } - created, err := requestVeleroBackupDeletion(ctx, r.Client, veleroBackupNamespace, veleroBackupName) + req, err := requestVeleroBackupDeletion(ctx, r.Client, veleroBackupNamespace, veleroBackupName) if err != nil { return err } - if created { + if req.created { logger.Info("created DeleteBackupRequest for Velero backup", "name", veleroBackupName, "namespace", veleroBackupNamespace) } else { diff --git a/internal/backupcontroller/backupjob_controller.go b/internal/backupcontroller/backupjob_controller.go index 1714dea46..49a7205f9 100644 --- a/internal/backupcontroller/backupjob_controller.go +++ b/internal/backupcontroller/backupjob_controller.go @@ -56,11 +56,12 @@ func (r *BackupJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) ( return ctrl.Result{}, err } - // Skip terminal BackupJobs: a Succeeded/Failed run must not keep - // projecting Secrets or re-running dispatch on every requeue, which - // would otherwise materialise cozy-backups-creds in tenant namespaces - // long after the BackupJob is done and pin needless work on the - // apiserver. + // A terminal BackupJob never reaches credentials projection or strategy + // dispatch: a finished run must not keep projecting Secrets or + // re-running dispatch on every requeue, which would otherwise + // materialise cozy-backups-creds in tenant namespaces long after the + // BackupJob is done and pin needless work on the apiserver. A Failed + // one only has the failed Velero backups it left behind deleted. if j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { logger.V(1).Info("BackupJob already terminal, cleaning up its Velero Backups", "phase", j.Status.Phase) return r.deleteFailedJobVeleroBackups(ctx, j) diff --git a/internal/backupcontroller/velero_backup_deletion.go b/internal/backupcontroller/velero_backup_deletion.go index 0e9de24b2..b22ba9e5c 100644 --- a/internal/backupcontroller/velero_backup_deletion.go +++ b/internal/backupcontroller/velero_backup_deletion.go @@ -3,8 +3,12 @@ package backupcontroller import ( "context" "fmt" + "strconv" + "strings" "time" + 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" @@ -16,42 +20,56 @@ import ( velerov1 "github.com/vmware-tanzu/velero/pkg/apis/velero/v1" ) +// veleroDeletionRequest is what requestVeleroBackupDeletion did. +type veleroDeletionRequest struct { + created bool + // replaced is a request of ours that Velero had processed and that this + // call deleted before creating a new one. + replaced *velerov1.DeleteBackupRequest +} + // requestVeleroBackupDeletion asks Velero to delete a backup together with its // data in the object store. Deleting the backup.velero.io object directly only // removes the Kubernetes object, and the BSL sync recreates it from the object -// store. +// store. Callers call it only for a backup that still exists. // // The request is named after the backup, so repeated calls converge on one -// request. Nothing is created while any request for the backup is unprocessed, -// or once one was processed without errors (Velero then removes the backup and -// the remaining requests). A request of ours that Velero processed with errors -// is deleted and created again: Velero keeps it for a day, and until then its -// name would block a new attempt. Velero does not retry a processed request, -// so a caller that needs the deletion to happen must call again later. -func requestVeleroBackupDeletion(ctx context.Context, c client.Client, namespace, name string) (bool, error) { +// request. Nothing is created while any request for the backup is +// unprocessed. A request of ours that Velero has processed is deleted and +// created again: the backup still exists, so the deletion failed, or the BSL +// sync brought the backup back, and Velero keeps a processed request for a +// day, during which its name would block a new attempt. Velero does not retry +// a processed request, so a caller that needs the deletion to happen must +// call again later. +func requestVeleroBackupDeletion(ctx context.Context, c client.Client, namespace, name string) (veleroDeletionRequest, error) { + var res veleroDeletionRequest requests := &velerov1.DeleteBackupRequestList{} if err := c.List(ctx, requests, client.InNamespace(namespace)); err != nil { - return false, fmt.Errorf("failed to list DeleteBackupRequests in %s: %w", namespace, err) + return res, fmt.Errorf("failed to list DeleteBackupRequests in %s: %w", namespace, err) } - var failed *velerov1.DeleteBackupRequest + var own *velerov1.DeleteBackupRequest for i := range requests.Items { dbr := &requests.Items[i] if dbr.Spec.BackupName != name { continue } - if dbr.Status.Phase != velerov1.DeleteBackupRequestPhaseProcessed || len(dbr.Status.Errors) == 0 { - return false, nil + if dbr.Status.Phase != velerov1.DeleteBackupRequestPhaseProcessed { + return res, nil } if dbr.Name == name { - failed = dbr + own = dbr } } - if failed != nil { + if own != nil { // The UID precondition keeps a stale cache from deleting a request // that has already been replaced. - err := c.Delete(ctx, failed, client.Preconditions{UID: &failed.UID}) - if err != nil && !apierrors.IsNotFound(err) && !apierrors.IsConflict(err) { - return false, fmt.Errorf("failed to delete failed DeleteBackupRequest %s/%s: %w", namespace, name, err) + err := c.Delete(ctx, own, client.Preconditions{UID: &own.UID}) + switch { + case err == nil: + res.replaced = own + case apierrors.IsNotFound(err), apierrors.IsConflict(err): + default: + return res, fmt.Errorf("failed to delete processed DeleteBackupRequest %s/%s: %w", namespace, name, err) } } @@ -66,23 +84,31 @@ func requestVeleroBackupDeletion(ctx context.Context, c client.Client, namespace } if err := c.Create(ctx, dbr); err != nil { if apierrors.IsAlreadyExists(err) { - return false, nil + return res, nil } - return false, fmt.Errorf("failed to create DeleteBackupRequest for %s/%s: %w", namespace, name, err) + return res, fmt.Errorf("failed to create DeleteBackupRequest for %s/%s: %w", namespace, name, err) } - return true, nil + res.created = true + return res, nil } const ( // failedJobSweepRequeue is how often a Failed BackupJob is reconciled // again while one of its Velero backups still waits for deletion. Nothing - // watches DeleteBackupRequests, so a request Velero processed with errors - // is only noticed, and replaced, on this requeue. - failedJobSweepRequeue = 5 * time.Minute + // watches DeleteBackupRequests, so a request Velero processed is only + // noticed, and replaced, on this requeue. Every replacement doubles it, up + // to failedJobSweepMaxRequeue, so a deletion Velero can never carry out + // (a missing, read-only or unavailable BSL) is retried rarely. + failedJobSweepRequeue = 5 * time.Minute + failedJobSweepMaxRequeue = time.Hour // failedJobRunningBackupRequeue is how often a Failed BackupJob is // reconciled again while one of its Velero backups is still running. // Velero rejects a deletion request for a running backup. failedJobRunningBackupRequeue = time.Minute + + // veleroDeletionRetriesAnnotation counts, on a Failed BackupJob, the + // deletion requests that Velero processed while the backup survived. + veleroDeletionRetriesAnnotation = "backups.cozystack.io/velero-deletion-retries" ) // deleteFailedJobVeleroBackups requests deletion of the failed Velero backups @@ -113,15 +139,20 @@ func (r *BackupJobReconciler) deleteFailedJobVeleroBackups(ctx context.Context, var referenced map[client.ObjectKey]bool var requeueAfter time.Duration + var waiting, replaced bool for i := range veleroBackups.Items { vb := &veleroBackups.Items[i] switch vb.Status.Phase { - case velerov1.BackupPhasePartiallyFailed, velerov1.BackupPhaseFailed, velerov1.BackupPhaseFailedValidation: - case velerov1.BackupPhaseCompleted, velerov1.BackupPhaseDeleting: + case velerov1.BackupPhasePartiallyFailed, velerov1.BackupPhaseFailed, velerov1.BackupPhaseFailedValidation, + // Velero marks the backup Deleting before it removes the data and + // leaves it so when that fails, so the request may need replacing. + velerov1.BackupPhaseDeleting: + case velerov1.BackupPhaseCompleted: // A job can fail after Velero completed, when creating or // recording its Backup fails. That Velero backup may be the only - // copy of good data, and a Backup that already references it - // deletes it itself, so a job-level failure never removes it. + // copy of good data, so a job-level failure never removes it: a + // Backup that references it deletes it with the Backup, and one + // that no Backup references stays until Velero's TTL expires it. continue default: requeueAfter = shorterRequeue(requeueAfter, failedJobRunningBackupRequeue) @@ -138,17 +169,65 @@ func (r *BackupJobReconciler) deleteFailedJobVeleroBackups(ctx context.Context, continue } - created, err := requestVeleroBackupDeletion(ctx, r.Client, vb.Namespace, vb.Name) + req, err := requestVeleroBackupDeletion(ctx, r.Client, vb.Namespace, vb.Name) if err != nil { return ctrl.Result{}, err } - if created { + waiting = true + if req.replaced != nil { + replaced = true + r.warnVeleroDeletionRetried(j, vb.Name, req.replaced) + } else if req.created { logger.Info("requested deletion of the Velero Backup of a failed BackupJob", "backupjob", j.Name, "namespace", j.Namespace, "veleroBackup", vb.Name) } - requeueAfter = shorterRequeue(requeueAfter, failedJobSweepRequeue) } - return ctrl.Result{RequeueAfter: requeueAfter}, nil + if !waiting { + return ctrl.Result{RequeueAfter: requeueAfter}, nil + } + + retries := veleroDeletionRetries(j) + if replaced { + retries++ + patch := client.MergeFrom(j.DeepCopy()) + if j.Annotations == nil { + j.Annotations = map[string]string{} + } + j.Annotations[veleroDeletionRetriesAnnotation] = strconv.Itoa(retries) + if err := r.Patch(ctx, j, patch); err != nil { + return ctrl.Result{}, fmt.Errorf("failed to record Velero deletion retries on BackupJob %s/%s: %w", j.Namespace, j.Name, err) + } + } + return ctrl.Result{RequeueAfter: shorterRequeue(requeueAfter, failedJobSweepBackoff(retries))}, nil +} + +func (r *BackupJobReconciler) warnVeleroDeletionRetried(j *backupsv1alpha1.BackupJob, veleroBackup string, processed *velerov1.DeleteBackupRequest) { + if r.Recorder == nil { + return + } + reason := "Velero reported no error, but the backup still exists" + if len(processed.Status.Errors) > 0 { + reason = strings.Join(processed.Status.Errors, "; ") + } + r.Recorder.Eventf(j, corev1.EventTypeWarning, "VeleroBackupDeletionFailed", + "Velero did not delete backup %s/%s: %s; requesting the deletion again", + veleroNamespace, veleroBackup, reason) +} + +func veleroDeletionRetries(j *backupsv1alpha1.BackupJob) int { + n, err := strconv.Atoi(j.Annotations[veleroDeletionRetriesAnnotation]) + if err != nil || n < 0 { + return 0 + } + return n +} + +func failedJobSweepBackoff(retries int) time.Duration { + d := failedJobSweepRequeue + for i := 0; i < retries && d < failedJobSweepMaxRequeue; i++ { + d *= 2 + } + return min(d, failedJobSweepMaxRequeue) } func shorterRequeue(current, next time.Duration) time.Duration { diff --git a/internal/backupcontroller/velero_backup_deletion_test.go b/internal/backupcontroller/velero_backup_deletion_test.go index d283e6262..dd806faa8 100644 --- a/internal/backupcontroller/velero_backup_deletion_test.go +++ b/internal/backupcontroller/velero_backup_deletion_test.go @@ -3,10 +3,13 @@ package backupcontroller import ( "context" "errors" + "strings" "testing" + "time" 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/runtime/schema" "k8s.io/apimachinery/pkg/types" @@ -237,67 +240,91 @@ func TestReconcileVelero_SeveralVeleroBackupsKeepCompletedOne(t *testing.T) { // Reconciling a Failed BackupJob, including one that failed under a version // without the cleanup, requests deletion of its failed Velero backups only. func TestReconcile_FailedJobVeleroBackupSweep(t *testing.T) { + foreign := failedVeleroBackup + "-abcde" cases := []struct { name string veleroPhase velerov1.BackupPhase jobPhase backupsv1alpha1.BackupJobPhase existing []client.Object // Backups visible to the uncached reader only. - uncached []client.Object - wantNames []string - wantPhase velerov1.DeleteBackupRequestPhase - wantRequeue ctrl.Result + uncached []client.Object + wantRequests map[string]velerov1.DeleteBackupRequestPhase + wantRequeue time.Duration + wantEvent bool }{ { - name: "PartiallyFailed without a request", - veleroPhase: velerov1.BackupPhasePartiallyFailed, - jobPhase: backupsv1alpha1.BackupJobPhaseFailed, - wantNames: []string{failedVeleroBackup}, - wantRequeue: ctrl.Result{RequeueAfter: failedJobSweepRequeue}, + name: "PartiallyFailed without a request", + veleroPhase: velerov1.BackupPhasePartiallyFailed, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + wantRequests: map[string]velerov1.DeleteBackupRequestPhase{failedVeleroBackup: ""}, + wantRequeue: failedJobSweepRequeue, }, { - name: "FailedValidation is deleted", - veleroPhase: velerov1.BackupPhaseFailedValidation, - jobPhase: backupsv1alpha1.BackupJobPhaseFailed, - wantNames: []string{failedVeleroBackup}, - wantRequeue: ctrl.Result{RequeueAfter: failedJobSweepRequeue}, + name: "FailedValidation is deleted", + veleroPhase: velerov1.BackupPhaseFailedValidation, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + wantRequests: map[string]velerov1.DeleteBackupRequestPhase{failedVeleroBackup: ""}, + wantRequeue: failedJobSweepRequeue, }, { - name: "pending request from elsewhere", + name: "pending request from elsewhere", + veleroPhase: velerov1.BackupPhaseFailed, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + existing: []client.Object{deleteRequest(foreign, velerov1.DeleteBackupRequestPhaseInProgress)}, + wantRequests: map[string]velerov1.DeleteBackupRequestPhase{foreign: velerov1.DeleteBackupRequestPhaseInProgress}, + wantRequeue: failedJobSweepRequeue, + }, + { + name: "errored request from elsewhere is left alone", veleroPhase: velerov1.BackupPhaseFailed, jobPhase: backupsv1alpha1.BackupJobPhaseFailed, - existing: []client.Object{deleteRequest(failedVeleroBackup+"-abcde", velerov1.DeleteBackupRequestPhaseInProgress)}, - wantNames: []string{failedVeleroBackup + "-abcde"}, - wantPhase: velerov1.DeleteBackupRequestPhaseInProgress, - wantRequeue: ctrl.Result{RequeueAfter: failedJobSweepRequeue}, + existing: []client.Object{deleteRequest(foreign, velerov1.DeleteBackupRequestPhaseProcessed, "backup storage location unavailable")}, + wantRequests: map[string]velerov1.DeleteBackupRequestPhase{ + failedVeleroBackup: "", + foreign: velerov1.DeleteBackupRequestPhaseProcessed, + }, + wantRequeue: failedJobSweepRequeue, }, { - name: "own request processed with errors is replaced", - veleroPhase: velerov1.BackupPhaseFailed, - jobPhase: backupsv1alpha1.BackupJobPhaseFailed, - existing: []client.Object{deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed, "backup is still in progress")}, - wantNames: []string{failedVeleroBackup}, - wantRequeue: ctrl.Result{RequeueAfter: failedJobSweepRequeue}, + name: "own request processed with errors is replaced", + veleroPhase: velerov1.BackupPhaseFailed, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + existing: []client.Object{deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed, "backup is still in progress")}, + wantRequests: map[string]velerov1.DeleteBackupRequestPhase{failedVeleroBackup: ""}, + wantRequeue: 2 * failedJobSweepRequeue, + wantEvent: true, }, { - name: "request processed without errors is kept", - veleroPhase: velerov1.BackupPhaseFailed, - jobPhase: backupsv1alpha1.BackupJobPhaseFailed, - existing: []client.Object{deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed)}, - wantNames: []string{failedVeleroBackup}, - wantPhase: velerov1.DeleteBackupRequestPhaseProcessed, - wantRequeue: ctrl.Result{RequeueAfter: failedJobSweepRequeue}, + name: "own request processed without errors while the backup exists is replaced", + veleroPhase: velerov1.BackupPhaseFailed, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + existing: []client.Object{deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed)}, + wantRequests: map[string]velerov1.DeleteBackupRequestPhase{failedVeleroBackup: ""}, + wantRequeue: 2 * failedJobSweepRequeue, + wantEvent: true, + }, + { + name: "Deleting with a request in progress", + veleroPhase: velerov1.BackupPhaseDeleting, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + existing: []client.Object{deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseInProgress)}, + wantRequests: map[string]velerov1.DeleteBackupRequestPhase{failedVeleroBackup: velerov1.DeleteBackupRequestPhaseInProgress}, + wantRequeue: failedJobSweepRequeue, + }, + { + name: "Deleting left by an errored request", + veleroPhase: velerov1.BackupPhaseDeleting, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + existing: []client.Object{deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed, "error deleting backup from object storage")}, + wantRequests: map[string]velerov1.DeleteBackupRequestPhase{failedVeleroBackup: ""}, + wantRequeue: 2 * failedJobSweepRequeue, + wantEvent: true, }, { name: "Completed is never deleted", veleroPhase: velerov1.BackupPhaseCompleted, jobPhase: backupsv1alpha1.BackupJobPhaseFailed, }, - { - name: "Deleting is skipped", - veleroPhase: velerov1.BackupPhaseDeleting, - jobPhase: backupsv1alpha1.BackupJobPhaseFailed, - }, { name: "failed backup referenced by a Backup the cache has not seen", veleroPhase: velerov1.BackupPhaseFailed, @@ -308,13 +335,13 @@ func TestReconcile_FailedJobVeleroBackupSweep(t *testing.T) { name: "running backup", veleroPhase: velerov1.BackupPhaseInProgress, jobPhase: backupsv1alpha1.BackupJobPhaseFailed, - wantRequeue: ctrl.Result{RequeueAfter: failedJobRunningBackupRequeue}, + wantRequeue: failedJobRunningBackupRequeue, }, { name: "new backup", veleroPhase: "", jobPhase: backupsv1alpha1.BackupJobPhaseFailed, - wantRequeue: ctrl.Result{RequeueAfter: failedJobRunningBackupRequeue}, + wantRequeue: failedJobRunningBackupRequeue, }, { name: "succeeded job", @@ -330,26 +357,100 @@ func TestReconcile_FailedJobVeleroBackupSweep(t *testing.T) { r.APIReader = newVeleroCleanupClient(t, nil, tc.uncached...) } - if res := reconcileCleanupJob(t, r); res != tc.wantRequeue { - t.Errorf("Result = %+v, want %+v", res, tc.wantRequeue) + if res := reconcileCleanupJob(t, r); res.RequeueAfter != tc.wantRequeue { + t.Errorf("RequeueAfter = %v, want %v", res.RequeueAfter, tc.wantRequeue) } dbrs := listDeleteBackupRequests(t, c) - if len(dbrs) != len(tc.wantNames) { - t.Fatalf("expected requests %v, got %+v", tc.wantNames, dbrs) + if len(dbrs) != len(tc.wantRequests) { + t.Fatalf("expected requests %v, got %+v", tc.wantRequests, dbrs) } - for i, want := range tc.wantNames { - if dbrs[i].Name != want || dbrs[i].Spec.BackupName != failedVeleroBackup { - t.Errorf("request %d = %s for %s, want %s for %s", i, dbrs[i].Name, dbrs[i].Spec.BackupName, want, failedVeleroBackup) + for _, dbr := range dbrs { + wantPhase, ok := tc.wantRequests[dbr.Name] + if !ok || dbr.Spec.BackupName != failedVeleroBackup { + t.Errorf("unexpected request %s for %s", dbr.Name, dbr.Spec.BackupName) + continue } - if dbrs[i].Status.Phase != tc.wantPhase { - t.Errorf("request %s phase = %q, want %q", dbrs[i].Name, dbrs[i].Status.Phase, tc.wantPhase) + if dbr.Status.Phase != wantPhase { + t.Errorf("request %s phase = %q, want %q", dbr.Name, dbr.Status.Phase, wantPhase) } } + + events := r.Recorder.(*record.FakeRecorder).Events + if got := len(events); (got > 0) != tc.wantEvent { + t.Errorf("got %d events, want an event: %v", got, tc.wantEvent) + } }) } } +// A deletion Velero keeps failing is retried with a growing interval, and +// every failed attempt is reported on the BackupJob with Velero's errors. +func TestReconcile_FailedJobVeleroDeletionBacksOff(t *testing.T) { + r, c := newVeleroCleanupReconciler(t, + veleroCleanupJob(backupsv1alpha1.BackupJobPhaseFailed), + ownedVeleroBackup(failedVeleroBackup, velerov1.BackupPhaseFailed)) + events := r.Recorder.(*record.FakeRecorder).Events + + if res := reconcileCleanupJob(t, r); res.RequeueAfter != failedJobSweepRequeue { + t.Fatalf("first request: RequeueAfter = %v, want %v", res.RequeueAfter, failedJobSweepRequeue) + } + for i, want := range []time.Duration{10 * time.Minute, 20 * time.Minute, 40 * time.Minute} { + dbr := &velerov1.DeleteBackupRequest{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: veleroNamespace, Name: failedVeleroBackup}, dbr); err != nil { + t.Fatalf("get request: %v", err) + } + dbr.Status = velerov1.DeleteBackupRequestStatus{ + Phase: velerov1.DeleteBackupRequestPhaseProcessed, + Errors: []string{"backup storage location default is currently in read-only mode"}, + } + if err := c.Update(context.Background(), dbr); err != nil { + t.Fatalf("mark request processed: %v", err) + } + + if res := reconcileCleanupJob(t, r); res.RequeueAfter != want { + t.Errorf("retry %d: RequeueAfter = %v, want %v", i+1, res.RequeueAfter, want) + } + select { + case ev := <-events: + if !strings.Contains(ev, "Warning VeleroBackupDeletionFailed") || !strings.Contains(ev, "read-only mode") { + t.Errorf("retry %d: unexpected event %q", i+1, ev) + } + default: + t.Fatalf("retry %d: no Warning event", i+1) + } + if n := len(listDeleteBackupRequests(t, c)); n != 1 { + t.Fatalf("retry %d: expected one request, got %d", i+1, n) + } + } + if res := reconcileCleanupJob(t, r); res.RequeueAfter != 40*time.Minute { + t.Errorf("a pending request must keep the backoff, got %v", res.RequeueAfter) + } + if len(events) != 0 { + t.Errorf("a pending request must not emit an event, got %q", <-events) + } + + if got := failedJobSweepBackoff(10); got != failedJobSweepMaxRequeue { + t.Errorf("backoff after 10 retries = %v, want the %v cap", got, failedJobSweepMaxRequeue) + } +} + +func TestReconcile_FailedJobWithoutVeleroCRDs(t *testing.T) { + funcs := &interceptor.Funcs{ + List: func(ctx context.Context, c client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + if _, ok := list.(*velerov1.BackupList); ok { + return &meta.NoKindMatchError{GroupKind: schema.GroupKind{Group: "velero.io", Kind: "Backup"}} + } + return c.List(ctx, list, opts...) + }, + } + c := newVeleroCleanupClient(t, funcs, veleroCleanupJob(backupsv1alpha1.BackupJobPhaseFailed)) + r := &BackupJobReconciler{Client: c, Recorder: record.NewFakeRecorder(16)} + if res := reconcileCleanupJob(t, r); res.RequeueAfter != 0 { + t.Errorf("RequeueAfter = %v, want none", res.RequeueAfter) + } +} + func TestRequestVeleroBackupDeletion_ReplacesByUID(t *testing.T) { stale := deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed, "backup storage location unavailable") var preconditionUID types.UID @@ -364,9 +465,9 @@ func TestRequestVeleroBackupDeletion_ReplacesByUID(t *testing.T) { }, } c := newVeleroCleanupClient(t, funcs, stale) - created, err := requestVeleroBackupDeletion(context.Background(), c, veleroNamespace, failedVeleroBackup) - if err != nil || !created { - t.Fatalf("requestVeleroBackupDeletion = (%v, %v), want (true, nil)", created, err) + req, err := requestVeleroBackupDeletion(context.Background(), c, veleroNamespace, failedVeleroBackup) + if err != nil || !req.created || req.replaced == nil { + t.Fatalf("requestVeleroBackupDeletion = (%+v, %v), want a replaced and a created request", req, err) } if preconditionUID != stale.UID { t.Errorf("Delete precondition UID = %q, want %q", preconditionUID, stale.UID) @@ -390,9 +491,9 @@ func TestRequestVeleroBackupDeletion_ReturnsAPIErrors(t *testing.T) { t.Run(name, func(t *testing.T) { c := newVeleroCleanupClient(t, &funcs, deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed, "backup storage location unavailable")) - created, err := requestVeleroBackupDeletion(context.Background(), c, veleroNamespace, failedVeleroBackup) - if created || !apierrors.IsForbidden(err) { - t.Fatalf("requestVeleroBackupDeletion = (%v, %v), want a Forbidden error", created, err) + req, err := requestVeleroBackupDeletion(context.Background(), c, veleroNamespace, failedVeleroBackup) + if req.created || !apierrors.IsForbidden(err) { + t.Fatalf("requestVeleroBackupDeletion = (%+v, %v), want a Forbidden error", req, err) } }) } From 0bd46bc0149e9953515535bf63da5135238becff Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Thu, 19 Nov 2026 21:07:17 +0700 Subject: [PATCH 4/4] fix(backups): enforce the Velero deletion backoff of failed BackupJobs The retry backoff of the failed-job sweep only set RequeueAfter. Writing the retry counter onto the BackupJob triggers a reconcile at once, since the BackupJob watch has no predicate. When Velero processes a request instantly, as it does when the backup storage location is missing or read-only, that reconcile replaced the request again, emitted another event and raised the counter without any wait. The sweep now records when it last created a request, in the backups.cozystack.io/velero-deletion-attempted-at annotation, and replaces a processed request only after the backoff for the current count has passed since then. Before that, it requeues for the remaining time. A request Velero never processes, because Velero is down, and a Velero backup stuck in New or with no phase were checked at a fixed interval, each check with an uncached list of Backups. They are now checked again after as long as they have already waited, from the request's or the backup's creation time, capped at one hour. Waiting emits no event. Recording the attempt can fail after the request was created. If the job was deleted meanwhile, the sweep ends without an error. Any other error is logged and the computed requeue is kept, because failing the reconcile would only retry sooner. Unit tests drive the clock through two back-to-back reconciles of an instantly processed request (one replacement, one event), then three retries at 10, 20 and 40 minutes. They also check the waiting intervals for requests and backups of different ages, and both annotation write errors. Refs: #5355 Assisted-by: LLM Signed-off-by: Andrey Kolkov (cherry picked from commit dbc088f8629339058eb024ef9fc7de7f4fa1e805) Signed-off-by: Myasnikov Daniil --- .../backupcontroller/backup_controller.go | 2 +- .../backupcontroller/backupjob_controller.go | 3 + .../velero_backup_deletion.go | 142 +++++++++++---- .../velero_backup_deletion_test.go | 167 ++++++++++++++---- 4 files changed, 243 insertions(+), 71 deletions(-) diff --git a/internal/backupcontroller/backup_controller.go b/internal/backupcontroller/backup_controller.go index 3f4f9fc42..4f94dc427 100644 --- a/internal/backupcontroller/backup_controller.go +++ b/internal/backupcontroller/backup_controller.go @@ -234,7 +234,7 @@ func (r *BackupReconciler) cleanupVeleroBackup(ctx context.Context, backup *back return fmt.Errorf("failed to get Velero backup %s/%s: %w", veleroBackupNamespace, veleroBackupName, err) } - req, err := requestVeleroBackupDeletion(ctx, r.Client, veleroBackupNamespace, veleroBackupName) + req, err := requestVeleroBackupDeletion(ctx, r.Client, veleroBackupNamespace, veleroBackupName, true) if err != nil { return err } diff --git a/internal/backupcontroller/backupjob_controller.go b/internal/backupcontroller/backupjob_controller.go index 49a7205f9..aeba0958d 100644 --- a/internal/backupcontroller/backupjob_controller.go +++ b/internal/backupcontroller/backupjob_controller.go @@ -39,6 +39,9 @@ type BackupJobReconciler struct { // re-reads the BackupJob before dispatching to a driver. Wired in // SetupWithManager. APIReader client.Reader + + // now is a test seam for the clock that paces Velero deletion retries. + now func() time.Time } func (r *BackupJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { diff --git a/internal/backupcontroller/velero_backup_deletion.go b/internal/backupcontroller/velero_backup_deletion.go index b22ba9e5c..5e4a51c20 100644 --- a/internal/backupcontroller/velero_backup_deletion.go +++ b/internal/backupcontroller/velero_backup_deletion.go @@ -20,12 +20,17 @@ import ( velerov1 "github.com/vmware-tanzu/velero/pkg/apis/velero/v1" ) -// veleroDeletionRequest is what requestVeleroBackupDeletion did. +// veleroDeletionRequest is what requestVeleroBackupDeletion found and did. type veleroDeletionRequest struct { created bool // replaced is a request of ours that Velero had processed and that this // call deleted before creating a new one. replaced *velerov1.DeleteBackupRequest + // pending is a request for the backup that Velero has not processed yet. + pending *velerov1.DeleteBackupRequest + // processed is a request of ours that Velero has processed and that was + // left in place because the caller did not allow a replacement. + processed *velerov1.DeleteBackupRequest } // requestVeleroBackupDeletion asks Velero to delete a backup together with its @@ -35,13 +40,13 @@ type veleroDeletionRequest struct { // // The request is named after the backup, so repeated calls converge on one // request. Nothing is created while any request for the backup is -// unprocessed. A request of ours that Velero has processed is deleted and -// created again: the backup still exists, so the deletion failed, or the BSL -// sync brought the backup back, and Velero keeps a processed request for a -// day, during which its name would block a new attempt. Velero does not retry -// a processed request, so a caller that needs the deletion to happen must -// call again later. -func requestVeleroBackupDeletion(ctx context.Context, c client.Client, namespace, name string) (veleroDeletionRequest, error) { +// unprocessed. A request of ours that Velero has processed means the backup +// survived it: the deletion failed, or the BSL sync brought the backup back. +// With replace set, such a request is deleted and created again, because +// Velero keeps a processed request for a day and its name would block a new +// attempt until then. Velero does not retry a processed request, so a caller +// that needs the deletion to happen must call again later. +func requestVeleroBackupDeletion(ctx context.Context, c client.Client, namespace, name string, replace bool) (veleroDeletionRequest, error) { var res veleroDeletionRequest requests := &velerov1.DeleteBackupRequestList{} if err := c.List(ctx, requests, client.InNamespace(namespace)); err != nil { @@ -54,6 +59,7 @@ func requestVeleroBackupDeletion(ctx context.Context, c client.Client, namespace continue } if dbr.Status.Phase != velerov1.DeleteBackupRequestPhaseProcessed { + res.pending = dbr return res, nil } if dbr.Name == name { @@ -61,6 +67,10 @@ func requestVeleroBackupDeletion(ctx context.Context, c client.Client, namespace } } if own != nil { + if !replace { + res.processed = own + return res, nil + } // The UID precondition keeps a stale cache from deleting a request // that has already been replaced. err := c.Delete(ctx, own, client.Preconditions{UID: &own.UID}) @@ -93,22 +103,28 @@ func requestVeleroBackupDeletion(ctx context.Context, c client.Client, namespace } const ( - // failedJobSweepRequeue is how often a Failed BackupJob is reconciled - // again while one of its Velero backups still waits for deletion. Nothing - // watches DeleteBackupRequests, so a request Velero processed is only - // noticed, and replaced, on this requeue. Every replacement doubles it, up - // to failedJobSweepMaxRequeue, so a deletion Velero can never carry out - // (a missing, read-only or unavailable BSL) is retried rarely. + // failedJobSweepRequeue is the first interval at which a Failed + // BackupJob is reconciled again while one of its Velero backups waits + // for deletion; failedJobSweepMaxRequeue caps every interval below. + // Nothing watches DeleteBackupRequests, so a request Velero processed is + // only noticed on such a requeue. A processed request is replaced once + // failedJobSweepBackoff(retries) has passed since the last attempt, so a + // deletion Velero can never carry out (a missing, read-only or + // unavailable BSL) is attempted at most once an hour, and the annotation + // writes that record each attempt cannot cut the wait short. failedJobSweepRequeue = 5 * time.Minute failedJobSweepMaxRequeue = time.Hour - // failedJobRunningBackupRequeue is how often a Failed BackupJob is - // reconciled again while one of its Velero backups is still running. - // Velero rejects a deletion request for a running backup. + // failedJobRunningBackupRequeue is the first interval at which a Failed + // BackupJob is reconciled again while one of its Velero backups is still + // running. Velero rejects a deletion request for a running backup. failedJobRunningBackupRequeue = time.Minute // veleroDeletionRetriesAnnotation counts, on a Failed BackupJob, the // deletion requests that Velero processed while the backup survived. veleroDeletionRetriesAnnotation = "backups.cozystack.io/velero-deletion-retries" + // veleroDeletionAttemptAnnotation is when the sweep last created a + // deletion request for a Failed BackupJob, in RFC 3339. + veleroDeletionAttemptAnnotation = "backups.cozystack.io/velero-deletion-attempted-at" ) // deleteFailedJobVeleroBackups requests deletion of the failed Velero backups @@ -137,9 +153,15 @@ func (r *BackupJobReconciler) deleteFailedJobVeleroBackups(ctx context.Context, return ctrl.Result{}, nil } + now := r.clock() + retries := veleroDeletionRetries(j) + lastAttempt := veleroDeletionAttempt(j) + nextAttempt := lastAttempt.Add(failedJobSweepBackoff(retries)) + replaceDue := lastAttempt.IsZero() || !now.Before(nextAttempt) + var referenced map[client.ObjectKey]bool var requeueAfter time.Duration - var waiting, replaced bool + var attempted, replaced bool for i := range veleroBackups.Items { vb := &veleroBackups.Items[i] switch vb.Status.Phase { @@ -155,7 +177,8 @@ func (r *BackupJobReconciler) deleteFailedJobVeleroBackups(ctx context.Context, // that no Backup references stays until Velero's TTL expires it. continue default: - requeueAfter = shorterRequeue(requeueAfter, failedJobRunningBackupRequeue) + requeueAfter = shorterRequeue(requeueAfter, + waitingRequeue(now, vb.CreationTimestamp.Time, failedJobRunningBackupRequeue)) continue } @@ -169,36 +192,60 @@ func (r *BackupJobReconciler) deleteFailedJobVeleroBackups(ctx context.Context, continue } - req, err := requestVeleroBackupDeletion(ctx, r.Client, vb.Namespace, vb.Name) + req, err := requestVeleroBackupDeletion(ctx, r.Client, vb.Namespace, vb.Name, replaceDue) if err != nil { return ctrl.Result{}, err } - waiting = true - if req.replaced != nil { - replaced = true - r.warnVeleroDeletionRetried(j, vb.Name, req.replaced) - } else if req.created { - logger.Info("requested deletion of the Velero Backup of a failed BackupJob", - "backupjob", j.Name, "namespace", j.Namespace, "veleroBackup", vb.Name) + switch { + case req.pending != nil: + requeueAfter = shorterRequeue(requeueAfter, + waitingRequeue(now, req.pending.CreationTimestamp.Time, failedJobSweepRequeue)) + case req.processed != nil: + requeueAfter = shorterRequeue(requeueAfter, nextAttempt.Sub(now)) + case req.created: + attempted = true + if req.replaced != nil { + replaced = true + r.warnVeleroDeletionRetried(j, vb.Name, req.replaced) + } else { + logger.Info("requested deletion of the Velero Backup of a failed BackupJob", + "backupjob", j.Name, "namespace", j.Namespace, "veleroBackup", vb.Name) + } + default: + requeueAfter = shorterRequeue(requeueAfter, failedJobSweepRequeue) } } - if !waiting { + if !attempted { return ctrl.Result{RequeueAfter: requeueAfter}, nil } - retries := veleroDeletionRetries(j) if replaced { retries++ - patch := client.MergeFrom(j.DeepCopy()) - if j.Annotations == nil { - j.Annotations = map[string]string{} - } - j.Annotations[veleroDeletionRetriesAnnotation] = strconv.Itoa(retries) - if err := r.Patch(ctx, j, patch); err != nil { - return ctrl.Result{}, fmt.Errorf("failed to record Velero deletion retries on BackupJob %s/%s: %w", j.Namespace, j.Name, err) - } } - return ctrl.Result{RequeueAfter: shorterRequeue(requeueAfter, failedJobSweepBackoff(retries))}, nil + requeueAfter = shorterRequeue(requeueAfter, failedJobSweepBackoff(retries)) + patch := client.MergeFrom(j.DeepCopy()) + if j.Annotations == nil { + j.Annotations = map[string]string{} + } + j.Annotations[veleroDeletionRetriesAnnotation] = strconv.Itoa(retries) + j.Annotations[veleroDeletionAttemptAnnotation] = now.UTC().Format(time.RFC3339) + if err := r.Patch(ctx, j, patch); err != nil { + if apierrors.IsNotFound(err) { + return ctrl.Result{}, nil + } + // The request is already in place; without the record the next + // attempt only comes sooner than the backoff asks for. + logger.Error(err, "failed to record the Velero deletion attempt on the BackupJob", + "backupjob", j.Name, "namespace", j.Namespace) + } + return ctrl.Result{RequeueAfter: requeueAfter}, nil +} + +func (r *BackupJobReconciler) clock() time.Time { + if r.now != nil { + return r.now() + } + return time.Now() } func (r *BackupJobReconciler) warnVeleroDeletionRetried(j *backupsv1alpha1.BackupJob, veleroBackup string, processed *velerov1.DeleteBackupRequest) { @@ -222,6 +269,14 @@ func veleroDeletionRetries(j *backupsv1alpha1.BackupJob) int { return n } +func veleroDeletionAttempt(j *backupsv1alpha1.BackupJob) time.Time { + t, err := time.Parse(time.RFC3339, j.Annotations[veleroDeletionAttemptAnnotation]) + if err != nil { + return time.Time{} + } + return t +} + func failedJobSweepBackoff(retries int) time.Duration { d := failedJobSweepRequeue for i := 0; i < retries && d < failedJobSweepMaxRequeue; i++ { @@ -230,6 +285,17 @@ func failedJobSweepBackoff(retries int) time.Duration { return min(d, failedJobSweepMaxRequeue) } +// waitingRequeue paces the checks on something Velero has not acted on yet: +// the next check comes after as long as it has already waited, between floor +// and failedJobSweepMaxRequeue, so a Velero that is down is not polled at a +// fixed rate. +func waitingRequeue(now, since time.Time, floor time.Duration) time.Duration { + if since.IsZero() { + return floor + } + return min(max(now.Sub(since), floor), failedJobSweepMaxRequeue) +} + func shorterRequeue(current, next time.Duration) time.Duration { if current == 0 || next < current { return next diff --git a/internal/backupcontroller/velero_backup_deletion_test.go b/internal/backupcontroller/velero_backup_deletion_test.go index dd806faa8..f375bbb17 100644 --- a/internal/backupcontroller/velero_backup_deletion_test.go +++ b/internal/backupcontroller/velero_backup_deletion_test.go @@ -3,6 +3,7 @@ package backupcontroller import ( "context" "errors" + "fmt" "strings" "testing" "time" @@ -384,57 +385,159 @@ func TestReconcile_FailedJobVeleroBackupSweep(t *testing.T) { } } -// A deletion Velero keeps failing is retried with a growing interval, and -// every failed attempt is reported on the BackupJob with Velero's errors. +func markOwnRequestProcessed(t *testing.T, c client.Client, errs ...string) { + t.Helper() + dbr := &velerov1.DeleteBackupRequest{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: veleroNamespace, Name: failedVeleroBackup}, dbr); err != nil { + t.Fatalf("get request: %v", err) + } + dbr.Status = velerov1.DeleteBackupRequestStatus{Phase: velerov1.DeleteBackupRequestPhaseProcessed, Errors: errs} + if err := c.Update(context.Background(), dbr); err != nil { + t.Fatalf("mark request processed: %v", err) + } +} + +// A deletion Velero keeps failing at once is retried only after a growing +// wait, even though recording each attempt triggers a new reconcile, and +// every retry is reported on the BackupJob with Velero's errors. func TestReconcile_FailedJobVeleroDeletionBacksOff(t *testing.T) { + const readOnly = "backup storage location default is currently in read-only mode" r, c := newVeleroCleanupReconciler(t, veleroCleanupJob(backupsv1alpha1.BackupJobPhaseFailed), ownedVeleroBackup(failedVeleroBackup, velerov1.BackupPhaseFailed)) + now := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + r.now = func() time.Time { return now } events := r.Recorder.(*record.FakeRecorder).Events + expectEvent := func(step string, want bool) { + t.Helper() + select { + case ev := <-events: + if !want { + t.Fatalf("%s: unexpected event %q", step, ev) + } + if !strings.Contains(ev, "Warning VeleroBackupDeletionFailed") || !strings.Contains(ev, readOnly) { + t.Errorf("%s: unexpected event %q", step, ev) + } + default: + if want { + t.Fatalf("%s: no Warning event", step) + } + } + } if res := reconcileCleanupJob(t, r); res.RequeueAfter != failedJobSweepRequeue { t.Fatalf("first request: RequeueAfter = %v, want %v", res.RequeueAfter, failedJobSweepRequeue) } - for i, want := range []time.Duration{10 * time.Minute, 20 * time.Minute, 40 * time.Minute} { - dbr := &velerov1.DeleteBackupRequest{} - if err := c.Get(context.Background(), types.NamespacedName{Namespace: veleroNamespace, Name: failedVeleroBackup}, dbr); err != nil { - t.Fatalf("get request: %v", err) - } - dbr.Status = velerov1.DeleteBackupRequestStatus{ - Phase: velerov1.DeleteBackupRequestPhaseProcessed, - Errors: []string{"backup storage location default is currently in read-only mode"}, - } - if err := c.Update(context.Background(), dbr); err != nil { - t.Fatalf("mark request processed: %v", err) - } + expectEvent("first request", false) - if res := reconcileCleanupJob(t, r); res.RequeueAfter != want { - t.Errorf("retry %d: RequeueAfter = %v, want %v", i+1, res.RequeueAfter, want) + markOwnRequestProcessed(t, c, readOnly) + if res := reconcileCleanupJob(t, r); res.RequeueAfter != failedJobSweepRequeue { + t.Errorf("before the backoff: RequeueAfter = %v, want %v", res.RequeueAfter, failedJobSweepRequeue) + } + expectEvent("before the backoff", false) + + for i, wait := range []time.Duration{5 * time.Minute, 10 * time.Minute, 20 * time.Minute} { + now = now.Add(wait) + step := fmt.Sprintf("retry %d", i+1) + if res := reconcileCleanupJob(t, r); res.RequeueAfter != 2*wait { + t.Errorf("%s: RequeueAfter = %v, want %v", step, res.RequeueAfter, 2*wait) } - select { - case ev := <-events: - if !strings.Contains(ev, "Warning VeleroBackupDeletionFailed") || !strings.Contains(ev, "read-only mode") { - t.Errorf("retry %d: unexpected event %q", i+1, ev) - } - default: - t.Fatalf("retry %d: no Warning event", i+1) + expectEvent(step, true) + + markOwnRequestProcessed(t, c, readOnly) + if res := reconcileCleanupJob(t, r); res.RequeueAfter != 2*wait { + t.Errorf("%s, reconcile right after: RequeueAfter = %v, want %v", step, res.RequeueAfter, 2*wait) } + expectEvent(step+", reconcile right after", false) if n := len(listDeleteBackupRequests(t, c)); n != 1 { - t.Fatalf("retry %d: expected one request, got %d", i+1, n) + t.Fatalf("%s: expected one request, got %d", step, n) } } - if res := reconcileCleanupJob(t, r); res.RequeueAfter != 40*time.Minute { - t.Errorf("a pending request must keep the backoff, got %v", res.RequeueAfter) - } - if len(events) != 0 { - t.Errorf("a pending request must not emit an event, got %q", <-events) - } if got := failedJobSweepBackoff(10); got != failedJobSweepMaxRequeue { t.Errorf("backoff after 10 retries = %v, want the %v cap", got, failedJobSweepMaxRequeue) } } +// Requests and backups Velero has not acted on yet are checked less often the +// longer they wait, and waiting is not reported. +func TestReconcile_FailedJobWaitingOnVeleroBacksOff(t *testing.T) { + now := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC) + cases := []struct { + name string + veleroPhase velerov1.BackupPhase + existing []client.Object + backupAge time.Duration + want time.Duration + }{ + {name: "request waiting 20m", veleroPhase: velerov1.BackupPhaseFailed, want: 20 * time.Minute, + existing: []client.Object{agedRequest(now.Add(-20 * time.Minute))}}, + {name: "request waiting 3h", veleroPhase: velerov1.BackupPhaseFailed, want: failedJobSweepMaxRequeue, + existing: []client.Object{agedRequest(now.Add(-3 * time.Hour))}}, + {name: "request just created", veleroPhase: velerov1.BackupPhaseFailed, want: failedJobSweepRequeue, + existing: []client.Object{agedRequest(now)}}, + {name: "backup new for 3h", veleroPhase: velerov1.BackupPhaseNew, backupAge: 3 * time.Hour, want: failedJobSweepMaxRequeue}, + {name: "backup new for 10m", veleroPhase: "", backupAge: 10 * time.Minute, want: 10 * time.Minute}, + {name: "backup just started", veleroPhase: velerov1.BackupPhaseInProgress, want: failedJobRunningBackupRequeue}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + vb := ownedVeleroBackup(failedVeleroBackup, tc.veleroPhase) + vb.CreationTimestamp = metav1.NewTime(now.Add(-tc.backupAge)) + r, c := newVeleroCleanupReconciler(t, append([]client.Object{veleroCleanupJob(backupsv1alpha1.BackupJobPhaseFailed), vb}, tc.existing...)...) + r.now = func() time.Time { return now } + + if res := reconcileCleanupJob(t, r); res.RequeueAfter != tc.want { + t.Errorf("RequeueAfter = %v, want %v", res.RequeueAfter, tc.want) + } + if n := len(listDeleteBackupRequests(t, c)); n != len(tc.existing) { + t.Errorf("waiting must not create requests, got %d", n) + } + if events := r.Recorder.(*record.FakeRecorder).Events; len(events) != 0 { + t.Errorf("waiting must not be reported, got %q", <-events) + } + }) + } +} + +func agedRequest(created time.Time) *velerov1.DeleteBackupRequest { + dbr := deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseInProgress) + dbr.CreationTimestamp = metav1.NewTime(created) + return dbr +} + +// Recording the attempt can fail after the request was created: a job deleted +// meanwhile ends the sweep, any other error still keeps the backoff requeue. +func TestReconcile_FailedJobAttemptRecordErrors(t *testing.T) { + for name, patchErr := range map[string]error{ + "job deleted": apierrors.NewNotFound(schema.GroupResource{Group: "backups.cozystack.io", Resource: "backupjobs"}, failedJobName), + "apiserver": apierrors.NewServiceUnavailable("etcd timeout"), + } { + t.Run(name, func(t *testing.T) { + funcs := &interceptor.Funcs{ + Patch: func(context.Context, client.WithWatch, client.Object, client.Patch, ...client.PatchOption) error { + return patchErr + }, + } + c := newVeleroCleanupClient(t, funcs, + veleroCleanupJob(backupsv1alpha1.BackupJobPhaseFailed), + ownedVeleroBackup(failedVeleroBackup, velerov1.BackupPhaseFailed)) + r := &BackupJobReconciler{Client: c, Recorder: record.NewFakeRecorder(16)} + + want := failedJobSweepRequeue + if apierrors.IsNotFound(patchErr) { + want = 0 + } + if res := reconcileCleanupJob(t, r); res.RequeueAfter != want { + t.Errorf("RequeueAfter = %v, want %v", res.RequeueAfter, want) + } + if n := len(listDeleteBackupRequests(t, c)); n != 1 { + t.Errorf("expected the request to stay, got %d", n) + } + }) + } +} + func TestReconcile_FailedJobWithoutVeleroCRDs(t *testing.T) { funcs := &interceptor.Funcs{ List: func(ctx context.Context, c client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { @@ -465,7 +568,7 @@ func TestRequestVeleroBackupDeletion_ReplacesByUID(t *testing.T) { }, } c := newVeleroCleanupClient(t, funcs, stale) - req, err := requestVeleroBackupDeletion(context.Background(), c, veleroNamespace, failedVeleroBackup) + req, err := requestVeleroBackupDeletion(context.Background(), c, veleroNamespace, failedVeleroBackup, true) if err != nil || !req.created || req.replaced == nil { t.Fatalf("requestVeleroBackupDeletion = (%+v, %v), want a replaced and a created request", req, err) } @@ -491,7 +594,7 @@ func TestRequestVeleroBackupDeletion_ReturnsAPIErrors(t *testing.T) { t.Run(name, func(t *testing.T) { c := newVeleroCleanupClient(t, &funcs, deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed, "backup storage location unavailable")) - req, err := requestVeleroBackupDeletion(context.Background(), c, veleroNamespace, failedVeleroBackup) + req, err := requestVeleroBackupDeletion(context.Background(), c, veleroNamespace, failedVeleroBackup, true) if req.created || !apierrors.IsForbidden(err) { t.Fatalf("requestVeleroBackupDeletion = (%+v, %v), want a Forbidden error", req, err) }