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 <androndo@gmail.com>
(cherry picked from commit 887453c008)
Signed-off-by: Myasnikov Daniil <myasnikovdaniil2001@gmail.com>
This commit is contained in:
Andrey Kolkov authored and Myasnikov Daniil committed 2026-11-25 10:15:41 +00:00
1 parent eeab99ae1a
commit e1d3161e75
4 files changed
+263 -107

No files matched your search

@@ -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{}
@@ -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)
}
})
}
}
@@ -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)
}
@@ -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: [""]