diff --git a/examples/backups/clickhouse/92-scenario-user-restore.md b/examples/backups/clickhouse/92-scenario-user-restore.md index 288d1f1b0..ef0ad4072 100644 --- a/examples/backups/clickhouse/92-scenario-user-restore.md +++ b/examples/backups/clickhouse/92-scenario-user-restore.md @@ -51,5 +51,5 @@ The script: - Both flows assume the strategy template uses `.Mode` to switch between `create_remote` and `restore_remote`. See `01-create-strategy.sh`. -- On `backup.useSystemBucket: true`, deleting the Cozystack `Backup` deletes its archive through the sidecar and the `Backup` stays until that delete finished. When the ClickHouse application is already gone or no longer uses the system bucket, the platform's system bucket is no longer the one the `Backup` records its archive in (also when it changes while the delete runs), or the archive is named without its BackupJob's UID (a backup still running when the controller was upgraded, whose name another run of the same second may share), the `Backup` is released with an `ArtifactNotDeleted` Warning Event naming the archive left in the bucket; a delete that fails is retried, after a wait that starts at 30 seconds and doubles with each failure up to 30 minutes, and each failure is reported as an `ArtifactCleanupFailed` Warning Event; the `backups.cozystack.io/skip-artifact-cleanup: "true"` annotation releases it without starting a delete, though a delete the sidecar already accepted still runs to the end. A `Backup` taken before the archive name was recorded, or by a strategy that does not use `.ArchiveName`, does not name its archive and leaves it behind. So does a `Backup` that names its archive but not the bucket setting, as one recorded by a controller older than this behaviour does; it is released without an Event. +- On `backup.useSystemBucket: true`, deleting the Cozystack `Backup` deletes its archive through the sidecar and the `Backup` stays until that delete finished. When the ClickHouse application is already gone or no longer uses the system bucket, the platform's system bucket is no longer the one the `Backup` records its archive in (also when it changes while the delete runs), or the archive is named without its BackupJob's UID (a backup still running when the controller was upgraded, whose name another run of the same second may share), the `Backup` is released with an `ArtifactNotDeleted` Warning Event naming the archive left in the bucket; a delete that fails is retried, after a wait that starts at 30 seconds and doubles with each failure up to 30 minutes, and each failure is reported as an `ArtifactCleanupFailed` Warning Event; a cleanup Job a ResourceQuota refuses is reported the same way, and the `Backup` stays while the quota refuses the Job, unless the annotation below releases it; the `backups.cozystack.io/skip-artifact-cleanup: "true"` annotation releases it without creating another cleanup Job; a cleanup Pod that already exists can still start a delete until it is removed, and a delete the sidecar already accepted still runs to the end. A `Backup` taken before the archive name was recorded, or by a strategy that does not use `.ArchiveName`, does not name its archive and leaves it behind. So does a `Backup` that names its archive but not the bucket setting, as one recorded by a controller older than this behaviour does; it is released without an Event. - On the tenant's own bucket the archive's lifecycle stays the tenant's: deleting the `Backup` leaves it, and `POST /backup/delete/remote/` on the sidecar (port 7171, basic auth from the `-backup-api-auth` Secret) deletes one by hand. diff --git a/internal/backupcontroller/altinitystrategy_archive_test.go b/internal/backupcontroller/altinitystrategy_archive_test.go index 7649aff2c..b8865c71a 100644 --- a/internal/backupcontroller/altinitystrategy_archive_test.go +++ b/internal/backupcontroller/altinitystrategy_archive_test.go @@ -21,6 +21,7 @@ import ( "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/util/validation/field" "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/tools/record" ctrl "sigs.k8s.io/controller-runtime" @@ -565,6 +566,101 @@ func TestCleanupAltinityBackup_FailedJobBacksOff(t *testing.T) { } } +// Recording the failure updates the Backup, which starts the next reconcile +// at once, and the Job cache can still hold the failed Job the controller has +// just deleted. That Job is counted once: seen again, it is deleted without a +// second Event and without doubling the wait. +func TestCleanupAltinityBackup_CountsAFailedJobOnce(t *testing.T) { + backup := altinityCleanupBackup("ch-bk") + retryAt := time.Now().Add(altinityCleanupRetryBase).UTC().Format(time.RFC3339) + backup.Annotations = map[string]string{ + altinityCleanupFailuresAnnotation: "1", + altinityCleanupRetryAfterAnnotation: retryAt, + altinityCleanupFailedJobAnnotation: "failed-job-uid", + } + failed := ownCleanupJob(backup) + failed.UID = "failed-job-uid" + failed.Status.Conditions = []batchv1.JobCondition{{Type: batchv1.JobFailed, Status: corev1.ConditionTrue, Reason: "BackoffLimitExceeded"}} + c, s := newAltinityCleanupClient(append(altinityCleanupFixtures(backup), failed)...) + rec := record.NewFakeRecorder(10) + r := &BackupReconciler{Client: c, Scheme: s, Recorder: rec} + res, err := r.cleanupOnDelete(context.Background(), backup) + if err != nil { + t.Fatalf("cleanupOnDelete: %v", err) + } + if res.RequeueAfter <= 0 || res.RequeueAfter > altinityCleanupRetryBase { + t.Errorf("RequeueAfter = %s, want what is left of the wait already set", res.RequeueAfter) + } + got := &backupsv1alpha1.Backup{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(backup), got); err != nil { + t.Fatalf("get Backup: %v", err) + } + if f := got.Annotations[altinityCleanupFailuresAnnotation]; f != "1" { + t.Errorf("failures = %q, want the one failure counted once", f) + } + if at := got.Annotations[altinityCleanupRetryAfterAnnotation]; at != retryAt { + t.Errorf("retry-after = %q, want the one already set, %q", at, retryAt) + } + if len(rec.Events) != 0 { + t.Errorf("unexpected event %q for a failure already reported", <-rec.Events) + } + if left := listJobs(t, c); len(left) != 0 { + t.Errorf("expected the failed Job collected, %d left", len(left)) + } +} + +// A counted Job seen again after its wait has run out still holds the Backup: +// releasing it there would drop the finalizer with the archive undeleted. +func TestCleanupAltinityBackup_KeepsTheBackupWhenACountedJobOutlivesItsWait(t *testing.T) { + backup := altinityCleanupBackup("ch-bk") + backup.Annotations = map[string]string{ + altinityCleanupFailuresAnnotation: "1", + altinityCleanupRetryAfterAnnotation: time.Now().Add(-time.Minute).UTC().Format(time.RFC3339), + altinityCleanupFailedJobAnnotation: "failed-job-uid", + } + failed := ownCleanupJob(backup) + failed.UID = "failed-job-uid" + failed.Status.Conditions = []batchv1.JobCondition{{Type: batchv1.JobFailed, Status: corev1.ConditionTrue, Reason: "BackoffLimitExceeded"}} + c, s := newAltinityCleanupClient(append(altinityCleanupFixtures(backup), failed)...) + r := &BackupReconciler{Client: c, Scheme: s, Recorder: record.NewFakeRecorder(10)} + res, err := r.cleanupOnDelete(context.Background(), backup) + if err != nil { + t.Fatalf("cleanupOnDelete: %v", err) + } + if res.RequeueAfter <= 0 { + t.Errorf("RequeueAfter = %s: the Backup must stay until a delete succeeds", res.RequeueAfter) + } +} + +// A new failed Job, under the same name, is counted even when an earlier one +// was: its UID is not the one recorded. +func TestCleanupAltinityBackup_CountsANewFailedJob(t *testing.T) { + backup := altinityCleanupBackup("ch-bk") + backup.Annotations = map[string]string{ + altinityCleanupFailuresAnnotation: "1", + altinityCleanupFailedJobAnnotation: "earlier-job-uid", + } + failed := ownCleanupJob(backup) + failed.UID = "new-job-uid" + failed.Status.Conditions = []batchv1.JobCondition{{Type: batchv1.JobFailed, Status: corev1.ConditionTrue, Reason: "BackoffLimitExceeded"}} + c, s := newAltinityCleanupClient(append(altinityCleanupFixtures(backup), failed)...) + rec := record.NewFakeRecorder(10) + r := &BackupReconciler{Client: c, Scheme: s, Recorder: rec} + if _, err := r.cleanupOnDelete(context.Background(), backup); err != nil { + t.Fatalf("cleanupOnDelete: %v", err) + } + got := &backupsv1alpha1.Backup{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(backup), got); err != nil { + t.Fatalf("get Backup: %v", err) + } + if f, j := got.Annotations[altinityCleanupFailuresAnnotation], got.Annotations[altinityCleanupFailedJobAnnotation]; f != "2" || j != "new-job-uid" { + t.Errorf("failures = %q, counted Job = %q; want 2 and new-job-uid", f, j) + } + if len(rec.Events) != 1 { + t.Errorf("events = %d, want one for the new failure", len(rec.Events)) + } +} + // The wait is recorded before the failed Job is deleted, so a delete that // fails leaves the Backup waiting rather than free to start the next Job at // once. @@ -1374,6 +1470,9 @@ func TestCleanupAltinityBackup_ReleasesWhenTheJobIsRefused(t *testing.T) { for name, refuse := range map[string]error{ "invalid": apierrors.NewInvalid(batchv1.SchemeGroupVersion.WithKind("Job").GroupKind(), "ch-bk-cleanup", nil), "forbidden": apierrors.NewForbidden(batchv1.Resource("jobs"), "ch-bk-cleanup", errors.New("service account cannot create jobs")), + // Only a Forbidden is a quota refusal, whatever an Invalid's text says. + "invalid naming a quota": apierrors.NewInvalid(batchv1.SchemeGroupVersion.WithKind("Job").GroupKind(), "ch-bk-cleanup", + field.ErrorList{field.Invalid(field.NewPath("metadata", "name"), "ch-bk-cleanup", "exceeded quota: jobs-quota")}), } { t.Run(name, func(t *testing.T) { backup := altinityCleanupBackup("ch-bk") @@ -1404,6 +1503,44 @@ func TestCleanupAltinityBackup_ReleasesWhenTheJobIsRefused(t *testing.T) { } } +// A namespace ResourceQuota on Jobs refuses the cleanup Job with Forbidden while +// the quota is used up, or before its usage is known. That clears once other +// Jobs go or the quota controller has computed the usage, and releasing the +// Backup on it would leave the archive for good, so the Backup is held and the +// create retried. The messages are the ones the ResourceQuota admission plugin +// of k8s.io/apiserver returns. +func TestCleanupAltinityBackup_RetriesAJobRefusedByAQuota(t *testing.T) { + for name, msg := range map[string]string{ + "quota used up": "exceeded quota: jobs-quota, requested: count/jobs.batch=1, used: count/jobs.batch=5, limited: count/jobs.batch=5", + "quota usage unknown": "status unknown for quota: jobs-quota, resources: count/jobs.batch", + } { + t.Run(name, func(t *testing.T) { + backup := altinityCleanupBackup("ch-bk") + c, s := newAltinityCleanupClientWith(interceptor.Funcs{ + Create: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.CreateOption) error { + if _, ok := obj.(*batchv1.Job); ok { + return apierrors.NewForbidden(batchv1.Resource("jobs"), "ch-bk-cleanup", errors.New(msg)) + } + return c.Create(ctx, obj, opts...) + }, + }, altinityCleanupFixtures(backup)...) + rec := record.NewFakeRecorder(10) + r := &BackupReconciler{Client: c, Scheme: s, Recorder: rec} + if _, err := r.cleanupOnDelete(context.Background(), backup); err == nil { + t.Fatal("a cleanup Job refused by a quota must go back to the work queue with the Backup held, not release it") + } + // The Backup stays terminating, so the refusal is named on it + // rather than only in the controller log. + if len(rec.Events) == 0 { + t.Fatal("a cleanup Job refused by a quota must surface as a Warning Event") + } + if ev := <-rec.Events; !strings.Contains(ev, "Warning ArtifactCleanupFailed") || !strings.Contains(ev, "quota") || strings.Contains(ev, "ArtifactNotDeleted") { + t.Errorf("event %q must be an ArtifactCleanupFailed Warning naming the quota", ev) + } + }) + } +} + // Any other Create error is transient and goes back to the work queue with the // Backup held. func TestCleanupAltinityBackup_RetriesATransientCreateError(t *testing.T) { diff --git a/internal/backupcontroller/altinitystrategy_controller.go b/internal/backupcontroller/altinitystrategy_controller.go index accff2f70..ff45a910a 100644 --- a/internal/backupcontroller/altinitystrategy_controller.go +++ b/internal/backupcontroller/altinitystrategy_controller.go @@ -75,9 +75,11 @@ const ( // The cleanup Job that failed is deleted to make room for the next one, // so the count of failed attempts and the time the next may start are - // kept on the Backup. + // kept on the Backup, with the UID of the Job last counted, so that one + // still served from the cache is not counted twice. altinityCleanupFailuresAnnotation = "altinity.strategy.backups.cozystack.io/cleanup-failures" altinityCleanupRetryAfterAnnotation = "altinity.strategy.backups.cozystack.io/cleanup-retry-after" + altinityCleanupFailedJobAnnotation = "altinity.strategy.backups.cozystack.io/cleanup-failed-job" // altinityCleanupRetryBase is the wait after the first failed cleanup // Job; it doubles with each further failure up to altinityCleanupRetryMax. @@ -1157,8 +1159,11 @@ func (r *BackupReconciler) cleanupAltinityBackup(ctx context.Context, backup *ba rendered.Spec, fmt.Sprintf("chi-clickhouse-%s-clickhouse-0-0.%s.svc", release, backup.Namespace), authSecret, archive) if cerr := r.Create(ctx, desired); cerr != nil && !apierrors.IsAlreadyExists(cerr) { - // ResourceQuota also returns Forbidden. Once a Job slot frees up the same cleanup can run. - if apierrors.IsForbidden(cerr) && strings.Contains(cerr.Error(), "exceeded quota: ") { + if altinityQuotaRefusal(cerr) { + if r.Recorder != nil { + r.Recorder.Eventf(backup, corev1.EventTypeWarning, "ArtifactCleanupFailed", + "cleanup Job %s for archive %s was refused by a ResourceQuota (%v); retrying", jobKey.Name, archive, cerr) + } return ctrl.Result{}, cerr } if apierrors.IsForbidden(cerr) || apierrors.IsInvalid(cerr) { @@ -1210,6 +1215,19 @@ func (r *BackupReconciler) cleanupAltinityBackup(ctx context.Context, backup *ba logger.Debug("Altinity archive deleted", "backup", backup.Name, "archive", archive) return ctrl.Result{}, nil case batchv1.JobFailed: + // Recording a failure updates the Backup, which starts the next + // reconcile while the Job cache may still hold the Job just deleted; + // a failure already counted is not counted or reported again. + if job.UID != "" && backup.Annotations[altinityCleanupFailedJobAnnotation] == string(job.UID) { + if derr := r.deleteAltinityCleanupJob(ctx, job); derr != nil { + return ctrl.Result{}, derr + } + wait := altinityCleanupRetryWait(ctx, backup, time.Now()) + if wait <= 0 { + wait = altinityPollInterval + } + return ctrl.Result{RequeueAfter: wait}, nil + } failures := altinityCleanupFailures(ctx, backup) + 1 delay := altinityCleanupRetryDelay(failures) logger.Debug("Altinity cleanup Job failed; retrying", "backup", backup.Name, "job", job.Name, "failures", failures, "delay", delay) @@ -1220,7 +1238,7 @@ func (r *BackupReconciler) cleanupAltinityBackup(ctx context.Context, backup *ba "cleanup Job %s did not delete archive %s (%s: %s); retrying in %s", job.Name, archive, c.Reason, c.Message, delay) } // Recorded before the Job goes: should the delete below fail, the next - // reconcile counts this failure again and waits longer, rather than + // reconcile finds this Job counted and keeps waiting, rather than // starting the next Job at once. base := backup.DeepCopy() if backup.Annotations == nil { @@ -1228,6 +1246,7 @@ func (r *BackupReconciler) cleanupAltinityBackup(ctx context.Context, backup *ba } backup.Annotations[altinityCleanupFailuresAnnotation] = strconv.Itoa(failures) backup.Annotations[altinityCleanupRetryAfterAnnotation] = time.Now().Add(delay).UTC().Format(time.RFC3339) + backup.Annotations[altinityCleanupFailedJobAnnotation] = string(job.UID) if perr := r.Patch(ctx, backup, client.MergeFrom(base)); perr != nil { return ctrl.Result{}, perr } @@ -1271,6 +1290,19 @@ func (r *BackupReconciler) altinityAppOnSystemBucket(ctx context.Context, backup return app, v, true, nil } +// altinityQuotaRefusal tells the Forbidden a namespace ResourceQuota returns +// while it is used up or its usage is not yet known, by the messages of the +// ResourceQuota admission plugin in k8s.io/apiserver. It clears once other +// Jobs go or the quota controller has computed the usage, so the create is +// retried instead of the Backup being released. +func altinityQuotaRefusal(err error) bool { + if !apierrors.IsForbidden(err) { + return false + } + msg := err.Error() + return strings.Contains(msg, "exceeded quota:") || strings.Contains(msg, "status unknown for quota:") +} + // altinitySystemBucket reads the bucket the projected credentials name in the // namespace, the one the sidecar of a system-bucket application reads. It is // empty when no credentials are projected there or they name no bucket.