mirror of
https://github.com/cozystack/cozystack.git
synced 2026-11-30 04:06:34 +09:00
fix(backups): delete the Velero backup of a failed BackupJob (#5364)
<!-- Thank you for making a contribution! Here are some tips for you: - Use Conventional Commits for the PR title: `type(scope): description` - Types: feat, fix, security (a fix that comes through a security advisory), docs, style, refactor, perf, test, build, ci, chore - Scopes are not an exhaustive list — pick the most specific scope for the change and extend the list when a genuinely new area appears. Examples: - System components: dashboard, platform, operator, cilium, kube-ovn, linstor, fluxcd, cluster-api - Managed apps: postgres, mariadb, redis, kafka, clickhouse, virtual-machine, kubernetes - Development and maintenance: api, hack, tests, ci, docs, maintenance - Breaking changes: append `!` after type/scope (`feat(api)!: ...`) or add a `BREAKING CHANGE:` footer - If it's a work in progress, consider creating this PR as a draft. - Don't hesistate to ask for opinion and review in the community chats, even if it's still a draft. - Fixes merged to `main` reach the release lines the backport batch runs for automatically, so do not open backport PRs by hand: https://github.com/cozystack/cozystack/blob/main/docs/release/backports.md --> ## What this PR does <!-- Link the issues this PR addresses. For a complete fix targeting the default branch, use Closes #N (Closes owner/repository#N for another repository). Otherwise use a non-closing reference; release-branch PRs need manual issue linking and closure when appropriate. --> Closes #5355 A BackupJob whose Velero backup ends `Failed` or `PartiallyFailed` leaves that `backup.velero.io` object and its data in the backup bucket (partial resources, logs) until Velero's TTL expires it, 720h by default. No `Backup` is created for a failed run, and the `Backup` finalizer was the only code that asked Velero to delete backup data; deleting the BackupJob does not remove it either, because the Velero backup is only labelled for the job, not owned by it. The first commit requests deletion of the failed Velero backup through a `DeleteBackupRequest`, and turns the reconcile of a `Failed` BackupJob, which returned at once, into a sweep over the Velero backups still labelled for the job. That sweep also cleans up backups leaked by earlier versions after an upgrade. The request creation is shared with the `Backup` finalizer and named after the Velero backup, so repeated reconciles converge on one request. The failure message is unchanged. The second commit narrows that sweep and makes it converge: - Only `Failed`, `PartiallyFailed` and `FailedValidation` Velero backups are deleted. A `Completed` one is never touched from a job-level failure: a job can fail after Velero completed (creating or recording the `Backup` failed), and that Velero backup may be the only copy of good data. - Deletion is requested only after `Failed` is persisted. The strategy no longer sends the request inline, so a failed status write cannot leave a retried run without the backup it reports the failure from. The BackupJob watch has no predicate, so the `Failed` status update itself triggers the sweep. - While a failed backup still exists, the job is requeued every 5 minutes. Nothing watches `DeleteBackupRequest`, so this is how a request Velero processed with errors is noticed and replaced. A backup that is still running is rechecked every minute. - Backups that reference the Velero backup are read through the uncached API reader before anything is deleted. - The ClusterRole of `backupstrategy-controller` gains `delete` on `deletebackuprequests`, needed to replace a processed-with-errors request. The `Backup` finalizer shares the helper, and without the verb that path would fail with 403. The third commit makes a deletion that Velero could not finish converge, and makes it visible: - A Velero backup in `Deleting` goes through the same request path. Velero sets that phase before it removes the data and leaves it there when removal fails, so skipping it left the data in place until the TTL. - Our own request that Velero processed while the backup still exists is replaced, whether it carries errors or not. The second case is a backup that the BSL sync brought back. - Each replacement emits a `VeleroBackupDeletionFailed` Warning event on the BackupJob with Velero's `status.errors`, and doubles the wait before the next replacement, 5 minutes up to 1 hour (enforced from the recorded attempt time since the fourth commit). The count is kept in the `backups.cozystack.io/velero-deletion-retries` annotation on the BackupJob. A missing, read-only or unavailable BSL therefore shows up in `kubectl describe` instead of being retried silently every 5 minutes. The fourth commit makes the backoff binding rather than advisory: - Each request the sweep creates records its time in the `backups.cozystack.io/velero-deletion-attempted-at` annotation, next to the retry counter. A request Velero has processed is replaced only once the backoff for the current retry count has passed since that time. Writing the annotations triggers a reconcile at once, because the BackupJob watch has no predicate; that reconcile now only computes the remaining wait. Before, with a BSL that fails instantly, it could replace the request again right away. - A request Velero has not processed yet, and a Velero backup still in `New` or with no phase, are checked again after as long as they have already waited: between 5 minutes (1 minute for a running backup) and 1 hour. Waiting emits no event. - If the job was deleted before the annotations are written, the sweep stops quietly. Any other error writing them is logged, and the computed requeue is kept, because the request already exists. Points for the reviewer: - The sweep matches on the BackupJob labels, not on the strategy kind, because a `Failed` job's BackupClass may be gone. The Kubernetes strategy labels its Velero backup the same way and has the same leak on failure, so a failed Kubernetes strategy run is cleaned up by the sweep as well. - The Velero strategy still treats a `FailedValidation` Velero backup as in progress and requeues the BackupJob indefinitely. That is unchanged here; the sweep already treats `FailedValidation` as deletable. - After the upgrade, the Velero backups of BackupJobs that already failed are deleted. An operator who wants one of them for a manual `velero restore` must copy it first. ### Screenshots <!-- REQUIRED for UI changes: attach screenshots or screen recordings demonstrating the visual impact of your changes. PRs with UI changes without screenshots will not be merged. --> N/A — no UI changes. ### Downstream repositories <!-- Cozystack is upstream for repositories that are NOT kept in sync with it automatically, and nothing in CI compares the two sides, so a change here can break them silently. Which change forces what, and which file to touch, is the trigger map in docs/agents/contributing.md under "Downstream Repositories". Walk it before you tick anything. IF YOU ARE AN AI AGENT OR AN LLM, THIS IS PART OF THE TASK, NOT A FORM TO FILL IN: 1. Walk the trigger map against the actual diff of this PR, file by file. Do not decide from the PR title or from your memory of what you changed. 2. For every repository you tick, open the follow-up PR there and link it on the same line. A ticked box with no link claims work that does not exist, which is worse than an empty box. Search that repository for an open PR or issue covering it first, and link that instead of filing a duplicate. 3. When the follow-up is out of scope, or needs a decision that is not yours to make, open an issue in that repository instead, link that, and say so in the PR body. Do not push a speculative PR into another repository just to fill a line here. 4. Do not tick "No downstream repository is affected" to make the checklist go away. If you are unsure, leave every box empty and say so in the PR body, so a human decides. --> The diff touches Go code in `internal/backupcontroller/` and one chart file, `packages/system/backupstrategy-controller/templates/rbac.yaml`, which adds the `delete` verb on `deletebackuprequests` to the controller's ClusterRole. Walked against the trigger map: - website: no package, platform value, variant, component, release asset, ApplicationDefinition, Talos or tooling change. The ClusterRole is not documented there. - terraform-provider-cozystack: no app, schema field, enum, default, `kind`/`plural`, prefix, or `Package`/`Plan`/`RestoreJob` CRD change. - ansible-cozystack, talm, examples: no installer value, namespace, variant, platform value, node prerequisite, or object the role waits on. - ccp, external-apps-example: nothing under `hack/`, no package layout, `-rd` path, variant, `tags.yaml`, `ApplicationDefinition` CRD or commit-convention change. - cozyhr, cozy-proxy, cozystack-telemetry-server, community: none of their annotations, labels, metrics, `hack/package.mk` targets, PR template or commit convention change. No entry applies. - [x] No downstream repository is affected by this change - [ ] [cozystack/website](https://github.com/cozystack/website) - follow-up: - [ ] [cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack) - follow-up: - [ ] [cozystack/ansible-cozystack](https://github.com/cozystack/ansible-cozystack) - follow-up: - [ ] [cozystack/ccp](https://github.com/cozystack/ccp) - follow-up: - [ ] [cozystack/talm](https://github.com/cozystack/talm) - follow-up: - [ ] [cozystack/cozyhr](https://github.com/cozystack/cozyhr) - follow-up: - [ ] [cozystack/cozy-proxy](https://github.com/cozystack/cozy-proxy) - follow-up: - [ ] [cozystack/cozystack-telemetry-server](https://github.com/cozystack/cozystack-telemetry-server) - follow-up: - [ ] [cozystack/external-apps-example](https://github.com/cozystack/external-apps-example) - follow-up: - [ ] [cozystack/examples](https://github.com/cozystack/examples) - follow-up: - [ ] [cozystack/community](https://github.com/cozystack/community) - follow-up: ### Release note <!-- Write a release note: - Explain what has changed internally and for users. - Start with the same `type(scope):` prefix as in the PR title - Follow the guidelines at https://github.com/kubernetes/community/blob/master/contributors/guide/release-notes.md. --> ```release-note fix(backups): a BackupJob whose Velero backup ends Failed, PartiallyFailed or FailedValidation now asks Velero to delete that backup and its data in the bucket, instead of leaving them until Velero's TTL expires. A Velero backup that completed is never deleted this way. If Velero cannot carry out the deletion (for example, the backup storage location is missing, read-only or unavailable), the BackupJob gets a `VeleroBackupDeletionFailed` Warning event with Velero's errors, and the deletion is retried at a growing interval of up to one hour. After upgrading, the Velero backups of BackupJobs that already failed are deleted as well; to keep one for a manual `velero restore`, copy it before the upgrade. The backupstrategy-controller ClusterRole gains `delete` on `deletebackuprequests`. ```
This commit is contained in:
6 files changed
+961
-33
No files matched your search
@@ -248,28 +248,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,
|
||||
},
|
||||
req, err := requestVeleroBackupDeletion(ctx, r.Client, veleroBackupNamespace, veleroBackupName, true)
|
||||
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 req.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
|
||||
}
|
||||
|
||||
|
||||
@@ -43,6 +43,9 @@ type BackupJobReconciler struct {
|
||||
// newS3ObjectLister overrides the S3 client used to measure artifact
|
||||
// sizes; nil means a real minio client. Set by unit tests.
|
||||
newS3ObjectLister func(conn s3Connection) (s3ObjectLister, error)
|
||||
|
||||
// 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) {
|
||||
@@ -60,12 +63,17 @@ 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.
|
||||
if j.Status.Phase == backupsv1alpha1.BackupJobPhaseSucceeded || j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed {
|
||||
// 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)
|
||||
}
|
||||
if j.Status.Phase == backupsv1alpha1.BackupJobPhaseSucceeded {
|
||||
logger.V(1).Info("BackupJob already terminal, skipping", "phase", j.Status.Phase)
|
||||
return ctrl.Result{}, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
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"
|
||||
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"
|
||||
)
|
||||
|
||||
// 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
|
||||
// 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. 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. 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 {
|
||||
return res, fmt.Errorf("failed to list DeleteBackupRequests in %s: %w", namespace, err)
|
||||
}
|
||||
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 {
|
||||
res.pending = dbr
|
||||
return res, nil
|
||||
}
|
||||
if dbr.Name == name {
|
||||
own = dbr
|
||||
}
|
||||
}
|
||||
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})
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
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 res, nil
|
||||
}
|
||||
return res, fmt.Errorf("failed to create DeleteBackupRequest for %s/%s: %w", namespace, name, err)
|
||||
}
|
||||
res.created = true
|
||||
return res, nil
|
||||
}
|
||||
|
||||
const (
|
||||
// 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 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
|
||||
// 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)
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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 attempted, replaced bool
|
||||
for i := range veleroBackups.Items {
|
||||
vb := &veleroBackups.Items[i]
|
||||
switch vb.Status.Phase {
|
||||
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, 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,
|
||||
waitingRequeue(now, vb.CreationTimestamp.Time, 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
|
||||
}
|
||||
|
||||
req, err := requestVeleroBackupDeletion(ctx, r.Client, vb.Namespace, vb.Name, replaceDue)
|
||||
if err != nil {
|
||||
return ctrl.Result{}, err
|
||||
}
|
||||
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 !attempted {
|
||||
return ctrl.Result{RequeueAfter: requeueAfter}, nil
|
||||
}
|
||||
|
||||
if replaced {
|
||||
retries++
|
||||
}
|
||||
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) {
|
||||
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 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++ {
|
||||
d *= 2
|
||||
}
|
||||
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
|
||||
}
|
||||
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.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{}
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,603 @@
|
||||
package backupcontroller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"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"
|
||||
"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"
|
||||
velerov1 "github.com/vmware-tanzu/velero/pkg/apis/velero/v1"
|
||||
)
|
||||
|
||||
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 := newVeleroCleanupClient(t, nil, objs...)
|
||||
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 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{
|
||||
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 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},
|
||||
})
|
||||
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. 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) {
|
||||
j := veleroCleanupJob(backupsv1alpha1.BackupJobPhaseRunning)
|
||||
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)
|
||||
}
|
||||
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)
|
||||
}
|
||||
if dbrs := listDeleteBackupRequests(t, c); len(dbrs) != 0 {
|
||||
t.Fatalf("deletion must wait for the next reconcile, got %+v", dbrs)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
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)
|
||||
}
|
||||
if got := getCleanupJob(t, c); got.Status.Phase != backupsv1alpha1.BackupJobPhaseSucceeded {
|
||||
t.Fatalf("expected BackupJob Succeeded, got %q (%s)", got.Status.Phase, got.Status.Message)
|
||||
}
|
||||
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_SeveralVeleroBackupsKeepCompletedOne(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)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
wantRequests map[string]velerov1.DeleteBackupRequestPhase
|
||||
wantRequeue time.Duration
|
||||
wantEvent bool
|
||||
}{
|
||||
{
|
||||
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,
|
||||
wantRequests: map[string]velerov1.DeleteBackupRequestPhase{failedVeleroBackup: ""},
|
||||
wantRequeue: failedJobSweepRequeue,
|
||||
},
|
||||
{
|
||||
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(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")},
|
||||
wantRequests: map[string]velerov1.DeleteBackupRequestPhase{failedVeleroBackup: ""},
|
||||
wantRequeue: 2 * failedJobSweepRequeue,
|
||||
wantEvent: true,
|
||||
},
|
||||
{
|
||||
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: "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: failedJobRunningBackupRequeue,
|
||||
},
|
||||
{
|
||||
name: "new backup",
|
||||
veleroPhase: "",
|
||||
jobPhase: backupsv1alpha1.BackupJobPhaseFailed,
|
||||
wantRequeue: failedJobRunningBackupRequeue,
|
||||
},
|
||||
{
|
||||
name: "succeeded job",
|
||||
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(failedVeleroBackup, tc.veleroPhase)}, tc.existing...)
|
||||
r, c := newVeleroCleanupReconciler(t, objs...)
|
||||
if tc.uncached != nil {
|
||||
r.APIReader = newVeleroCleanupClient(t, nil, tc.uncached...)
|
||||
}
|
||||
|
||||
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.wantRequests) {
|
||||
t.Fatalf("expected requests %v, got %+v", tc.wantRequests, dbrs)
|
||||
}
|
||||
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 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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
expectEvent("first request", false)
|
||||
|
||||
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)
|
||||
}
|
||||
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("%s: expected one request, got %d", step, n)
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
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
|
||||
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)
|
||||
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)
|
||||
}
|
||||
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"))
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
@@ -360,6 +360,8 @@ 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)
|
||||
return r.markBackupJobFailed(ctx, j, message)
|
||||
}
|
||||
|
||||
@@ -108,10 +108,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: [""]
|
||||
|
||||
Reference in new issue
Block a user