From b62f2f385fe0dd322bc84cbab22c5ef0ab16eebf Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Mon, 23 Nov 2026 12:14:54 +0300 Subject: [PATCH 1/7] fix(clickhouse): record the bucket setting a ClickHouse backup was taken with A ClickHouse application writes its archives either to the system bucket, which nothing prunes, or to its own bucket, whose lifecycle is the tenant's. A Backup did not say which applied, so nothing deciding the fate of the archive when the Backup goes could tell them apart. The application's useSystemBucket is read when the backup Job is created, stamped on the Job and copied onto the Backup from there, because the application may switch before the controller sees the Job complete. It is the setting, not an observation of the bucket: the sidecar uploads to the bucket it was last restarted with, so a switch made just before the backup can be recorded while the sidecar still writes to the previous bucket. A Job created before the stamp existed falls back to the application as it reads then. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- .../altinitystrategy_archive_test.go | 163 ++++++++++++++++++ .../altinitystrategy_controller.go | 30 +++- 2 files changed, 189 insertions(+), 4 deletions(-) create mode 100644 internal/backupcontroller/altinitystrategy_archive_test.go diff --git a/internal/backupcontroller/altinitystrategy_archive_test.go b/internal/backupcontroller/altinitystrategy_archive_test.go new file mode 100644 index 000000000..df230abae --- /dev/null +++ b/internal/backupcontroller/altinitystrategy_archive_test.go @@ -0,0 +1,163 @@ +// SPDX-License-Identifier: Apache-2.0 +package backupcontroller + +import ( + "context" + "fmt" + "testing" + "time" + + batchv1 "k8s.io/api/batch/v1" + 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/apis/meta/v1/unstructured" + "sigs.k8s.io/controller-runtime/pkg/client" + clientfake "sigs.k8s.io/controller-runtime/pkg/client/fake" + + strategyv1alpha1 "github.com/cozystack/cozystack/api/backups/strategy/v1alpha1" + backupsv1alpha1 "github.com/cozystack/cozystack/api/backups/v1alpha1" +) + +func withUseSystemBucket(app *unstructured.Unstructured, v bool) *unstructured.Unstructured { + if err := unstructured.SetNestedField(app.Object, v, "spec", "backup", "useSystemBucket"); err != nil { + panic(err) + } + return app +} + +func altinityResolved(strategyName string) *ResolvedBackupConfig { + return &ResolvedBackupConfig{ + StrategyRef: corev1.TypedLocalObjectReference{ + APIGroup: new(strategyv1alpha1.GroupVersion.Group), + Kind: strategyv1alpha1.AltinityStrategyKind, + Name: strategyName, + }, + } +} + +func runningAltinityBackupJob() *backupsv1alpha1.BackupJob { + startedAt := metav1.NewTime(time.Date(2026, 3, 4, 5, 6, 7, 0, time.UTC)) + return &backupsv1alpha1.BackupJob{ + ObjectMeta: metav1.ObjectMeta{Name: "test-bj", Namespace: "tenant-test"}, + Spec: backupsv1alpha1.BackupJobSpec{ + ApplicationRef: newAltinityClickHouseRef("ch-test"), + BackupClassName: "clickhouse-backup", + }, + Status: backupsv1alpha1.BackupJobStatus{StartedAt: &startedAt, Phase: backupsv1alpha1.BackupJobPhaseRunning}, + } +} + +// completedAltinityK8sJob is a finished backup Job whose Pod was given the +// BackupJob's archive name. +func completedAltinityK8sJob(j *backupsv1alpha1.BackupJob) *batchv1.Job { + return &batchv1.Job{ + ObjectMeta: metav1.ObjectMeta{Name: jobNameForBackupJob(j), Namespace: j.Namespace}, + Spec: batchv1.JobSpec{Template: corev1.PodTemplateSpec{Spec: corev1.PodSpec{ + Containers: []corev1.Container{{Name: "c", Args: []string{"--archive=" + altinityArchiveName(j)}}}, + }}}, + Status: batchv1.JobStatus{Conditions: []batchv1.JobCondition{ + {Type: batchv1.JobComplete, Status: corev1.ConditionTrue}, + }}, + } +} + +// completeAltinityBackup drives a BackupJob whose batch Job already completed +// through reconcileAltinity and returns the Backup it produced. +func completeAltinityBackup(t *testing.T, app *unstructured.Unstructured, job func(*backupsv1alpha1.BackupJob) *batchv1.Job) *backupsv1alpha1.Backup { + t.Helper() + bj := runningAltinityBackupJob() + strategy := newAltinityArchiveStrategy("clickhouse-strategy") + r, _, _ := newAltinityTestEnv(t, app, clientfake.NewClientBuilder().WithObjects(bj, strategy, job(bj))) + ctx := context.Background() + if _, err := r.reconcileAltinity(ctx, bj, altinityResolved(strategy.Name)); err != nil { + t.Fatalf("reconcileAltinity: %v", err) + } + got := &backupsv1alpha1.Backup{} + if err := r.Get(ctx, client.ObjectKey{Namespace: bj.Namespace, Name: bj.Name}, got); err != nil { + t.Fatalf("get Backup: %v", err) + } + return got +} + +// Cleanup deletes only the archive of a Backup taken while the application +// was set to the system bucket, so the Backup records that setting. +func TestReconcileAltinity_RecordsTheBucketFlow(t *testing.T) { + for name, tc := range map[string]struct { + app *unstructured.Unstructured + want string + }{ + "system bucket": {withUseSystemBucket(newAltinityClickHouseApp("ch-test", "tenant-test"), true), "true"}, + "explicit false": {withUseSystemBucket(newAltinityClickHouseApp("ch-test", "tenant-test"), false), "false"}, + "unset": {newAltinityClickHouseApp("ch-test", "tenant-test"), "false"}, + } { + t.Run(name, func(t *testing.T) { + got := completeAltinityBackup(t, tc.app, completedAltinityK8sJob) + if v := got.Spec.DriverMetadata[altinityUseSystemBucketKey]; v != tc.want { + t.Errorf("driverMetadata[%s] = %q, want %q", altinityUseSystemBucketKey, v, tc.want) + } + }) + } +} + +// The flow recorded on the Backup is the application's setting when the +// backup Job was created, not the one read when the controller next sees the +// Job complete: the application may switch buckets in between. +func TestReconcileAltinity_RecordsTheBucketFlowTheJobStartedWith(t *testing.T) { + for _, tc := range []struct{ started, now bool }{{true, false}, {false, true}} { + app := withUseSystemBucket(newAltinityClickHouseApp("ch-test", "tenant-test"), tc.now) + got := completeAltinityBackup(t, app, func(bj *backupsv1alpha1.BackupJob) *batchv1.Job { + job := completedAltinityK8sJob(bj) + job.Annotations = map[string]string{altinityUseSystemBucketKey: fmt.Sprint(tc.started)} + return job + }) + if v := got.Spec.DriverMetadata[altinityUseSystemBucketKey]; v != fmt.Sprint(tc.started) { + t.Errorf("started on %v, now %v: recorded %q, want the flow the Job started with", tc.started, tc.now, v) + } + } +} + +func TestReconcileAltinity_BackupJobCarriesTheBucketFlow(t *testing.T) { + for _, flow := range []bool{true, false} { + app := withUseSystemBucket(newAltinityClickHouseApp("ch-test", "tenant-test"), flow) + bj := runningAltinityBackupJob() + strategy := newAltinityArchiveStrategy("clickhouse-strategy") + r, _, _ := newAltinityTestEnv(t, app, clientfake.NewClientBuilder().WithObjects(bj, strategy)) + ctx := context.Background() + if _, err := r.reconcileAltinity(ctx, bj, altinityResolved(strategy.Name)); err != nil { + t.Fatalf("reconcileAltinity: %v", err) + } + job := &batchv1.Job{} + if err := r.Get(ctx, client.ObjectKey{Namespace: bj.Namespace, Name: jobNameForBackupJob(bj)}, job); err != nil { + t.Fatalf("get backup Job: %v", err) + } + if v := job.Annotations[altinityUseSystemBucketKey]; v != fmt.Sprint(flow) { + t.Errorf("backup Job annotation = %q, want %v", v, flow) + } + } +} + +func TestReconcileAltinity_FailsOnMalformedUseSystemBucket(t *testing.T) { + app := newAltinityClickHouseApp("ch-test", "tenant-test") + if err := unstructured.SetNestedField(app.Object, "yes", "spec", "backup", "useSystemBucket"); err != nil { + t.Fatal(err) + } + bj := runningAltinityBackupJob() + strategy := newAltinityArchiveStrategy("clickhouse-strategy") + r, _, _ := newAltinityTestEnv(t, app, + clientfake.NewClientBuilder().WithObjects(bj, strategy, completedAltinityK8sJob(bj))) + ctx := context.Background() + if _, err := r.reconcileAltinity(ctx, bj, altinityResolved(strategy.Name)); err != nil { + t.Fatalf("reconcileAltinity: %v", err) + } + got := &backupsv1alpha1.BackupJob{} + if err := r.Get(ctx, client.ObjectKeyFromObject(bj), got); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + if got.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Errorf("phase = %q, want Failed when the bucket flow cannot be read", got.Status.Phase) + } + if err := r.Get(ctx, client.ObjectKeyFromObject(bj), &backupsv1alpha1.Backup{}); !apierrors.IsNotFound(err) { + t.Errorf("expected no Backup without a recorded bucket flow, got %v", err) + } +} diff --git a/internal/backupcontroller/altinitystrategy_controller.go b/internal/backupcontroller/altinitystrategy_controller.go index 4314c3dbf..e7e64eaea 100644 --- a/internal/backupcontroller/altinitystrategy_controller.go +++ b/internal/backupcontroller/altinitystrategy_controller.go @@ -15,6 +15,7 @@ import ( apierrors "k8s.io/apimachinery/pkg/api/errors" apimeta "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" ctrl "sigs.k8s.io/controller-runtime" @@ -51,6 +52,12 @@ const ( // may belong to a later Backup. altinityArchiveMetaKey = "altinity.strategy.backups.cozystack.io/archive" + // altinityUseSystemBucketKey records, on the backup Job and then on the + // Backup, the application's spec.backup.useSystemBucket as it read when + // the backup Job was created. It is not proof of where the archive went: + // the sidecar uploads to the bucket it was last restarted with. + altinityUseSystemBucketKey = "altinity.strategy.backups.cozystack.io/use-system-bucket" + // altinityArchiveTimeLayout is the UTC timestamp that ends an archive // name. It is fixed-width, so names sharing a prefix sort chronologically // as plain strings, which is what a restore of a Backup that records no @@ -375,12 +382,18 @@ func (r *BackupJobReconciler) reconcileAltinity(ctx context.Context, j *backupsv return ctrl.Result{RequeueAfter: wait}, nil } + useSystemBucket, _, err := unstructured.NestedBool(app, "spec", "backup", "useSystemBucket") + if err != nil { + return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to read spec.backup.useSystemBucket: %v", err)) + } + batchJob, err := r.ensureAltinityJob(ctx, j, j.Namespace, jobNameForBackupJob(j), altinityModeBackup, map[string]string{ backupsv1alpha1.OwningJobNameLabel: j.Name, backupsv1alpha1.OwningJobNamespaceLabel: j.Namespace, }, + map[string]string{altinityUseSystemBucketKey: fmt.Sprint(useSystemBucket)}, rendered, ) if err != nil { @@ -398,7 +411,15 @@ func (r *BackupJobReconciler) reconcileAltinity(ctx context.Context, j *backupsv archive = "" } } - artifact, err := r.createAltinityBackupArtifact(ctx, j, resolved, archive) + // The flow stamped on the Job when it was created is the closest the + // controller sees to the bucket the sidecar uploads to, since the + // application may switch before the Job is seen complete; a Job + // created before that stamp existed falls back to the application. + flow, ok := batchJob.Annotations[altinityUseSystemBucketKey] + if !ok { + flow = fmt.Sprint(useSystemBucket) + } + artifact, err := r.createAltinityBackupArtifact(ctx, j, resolved, archive, flow) if err != nil { return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to create Backup artifact: %v", err)) } @@ -446,7 +467,7 @@ func (r *BackupJobReconciler) ensureAltinityJob( ctx context.Context, owner client.Object, namespace, name, mode string, - ownerLabels map[string]string, + ownerLabels, annotations map[string]string, rendered *corev1.PodTemplateSpec, ) (*batchv1.Job, error) { existing := &batchv1.Job{} @@ -462,6 +483,7 @@ func (r *BackupJobReconciler) ensureAltinityJob( maps.Copy(labels, ownerLabels) desired := buildAltinityBatchJob(namespace, name, labels, rendered) + desired.Annotations = annotations if err := controllerutil.SetControllerReference(owner, desired, r.Scheme); err != nil { return nil, fmt.Errorf("set controller reference on backup Job: %w", err) } @@ -583,9 +605,9 @@ func (r *BackupJobReconciler) createAltinityBackupArtifact( ctx context.Context, j *backupsv1alpha1.BackupJob, resolved *ResolvedBackupConfig, - archive string, + archive, useSystemBucket string, ) (*backupsv1alpha1.Backup, error) { - driverMD := map[string]string{} + driverMD := map[string]string{altinityUseSystemBucketKey: useSystemBucket} if archive != "" { driverMD[altinityArchiveMetaKey] = archive } From 564bdd3a79b4314a6e6d55dbd2f0f3850c657229 Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Mon, 23 Nov 2026 12:14:55 +0300 Subject: [PATCH 2/7] fix(clickhouse): delete the archive when its Backup is deleted Deleting a Backup taken with the Altinity strategy released its finalizer at once and left the archive in the bucket. On the system bucket nothing else prunes it, so every ClickHouse backup stayed until someone called the sidecar by hand. Deleting such a Backup now runs a one-shot Job that asks the application's sidecar to delete the archive the Backup records, and holds the finalizer until the Job completes. The driver creates the Backup with the finalizer already set, so a Backup deleted before the reconciler first sees it still gets its archive deleted. An archive that is already gone counts as deleted. The sidecar refuses a delete while another operation runs, and cannot be reached while the ClickHouse Pod restarts, so the Job waits both out within its deadline; any other refusal fails the Job, which is reported as an ArtifactCleanupFailed Warning Event carrying the reason it failed. Each failure doubles the wait before the next cleanup Job, from 30 seconds up to 30 minutes, so a delete the sidecar refuses for good, such as one made with a wrong password, does not cost a Job, its Pod and a Warning Event every few seconds. The count of failures and the time the next Job may start are kept on the Backup, because the Backup controller does not watch Jobs; a start time further ahead than the longest wait, from a skewed clock or a hand edit, is logged and ignored. A Job the namespace's Job quota refuses is retried once a slot frees up rather than released, since the Backup would be gone by then and nothing would delete the archive. The Job is built by the controller, not rendered from the strategy template, because the shipped and the example templates run a restore for every mode other than backup. Only the image, how to pull it, and the node selector, tolerations, affinity and priority class come from the template, rendered against the application and the Backup as for the strategy's own Pods, so the cleanup Pod can be scheduled where they are. The strategy is read only when a Job has to be created, so a running delete outlives it. The Job also waits for the projected credentials to reach the sidecar, as the backup and restore Jobs do: a sidecar still serving the previous bucket answers "not found", and the delete would count as done. When the delete cannot run, the Backup is released with an ArtifactNotDeleted Warning Event naming the archive left behind: the namespace is terminating, the strategy, the application or its API Secret is gone, the application has left the system bucket, the platform's system bucket is no longer the one the Backup records (also when it changes while the delete runs), another Job holds the cleanup Job name, or the API server refuses the Job. An archive named without its BackupJob's UID is released the same way: such a name comes from a run that crossed the controller upgrade, and another run started in the same second may share it. The backups.cozystack.io/skip-artifact-cleanup annotation releases the Backup without starting a delete. An application on its own bucket keeps the archive's lifecycle, as with MongoDB. The restore scenario and the chart comments told tenants to delete an archive with DELETE /backup//remote, which clickhouse-backup 2.7 answers with 404; they now name POST /backup/delete/remote/. Co-authored-by: Yan Bondarenko <202671653+yankawai@users.noreply.github.com> Assisted-by: LLM Signed-off-by: Alexey Artamonov Signed-off-by: Yan Bondarenko <202671653+yankawai@users.noreply.github.com> --- .../clickhouse/92-scenario-user-restore.md | 8 +- .../altinitystrategy_archive_test.go | 1281 +++++++++++++++++ .../altinitystrategy_controller.go | 541 ++++++- .../altinitystrategy_controller_test.go | 3 + .../backupcontroller/backup_controller.go | 26 +- .../jobstrategy_controller.go | 4 +- .../templates/backup-api-auth-secret.yaml | 4 +- .../apps/clickhouse/templates/clickhouse.yaml | 2 +- 8 files changed, 1827 insertions(+), 42 deletions(-) diff --git a/examples/backups/clickhouse/92-scenario-user-restore.md b/examples/backups/clickhouse/92-scenario-user-restore.md index 7edb49a52..288d1f1b0 100644 --- a/examples/backups/clickhouse/92-scenario-user-restore.md +++ b/examples/backups/clickhouse/92-scenario-user-restore.md @@ -51,9 +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`. -- The actual archive in object storage is owned by `clickhouse-backup`'s - retention policy on the sidecar, not by the Cozystack `Backup` lifecycle. - Deleting the Cozystack `Backup` removes the CR but leaves the S3 archive - untouched; tenants who need to purge an archive should call - `DELETE /backup//remote` on the sidecar (or use the upstream tool's - retention configuration). +- 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 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 df230abae..0f94db8df 100644 --- a/internal/backupcontroller/altinitystrategy_archive_test.go +++ b/internal/backupcontroller/altinitystrategy_archive_test.go @@ -3,17 +3,31 @@ package backupcontroller import ( "context" + "errors" "fmt" + "os" + "os/exec" + "path/filepath" + "reflect" + "strings" "testing" "time" batchv1 "k8s.io/api/batch/v1" 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/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/tools/record" + ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" clientfake "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" strategyv1alpha1 "github.com/cozystack/cozystack/api/backups/strategy/v1alpha1" backupsv1alpha1 "github.com/cozystack/cozystack/api/backups/v1alpha1" @@ -137,6 +151,109 @@ func TestReconcileAltinity_BackupJobCarriesTheBucketFlow(t *testing.T) { } } +// altinityCredsSecret is the projected credentials Secret the sidecar of a +// system-bucket application reads its bucket from; an empty bucket leaves the +// key out. +func altinityCredsSecret(bucket string) *corev1.Secret { + s := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "cozy-backups-creds", Namespace: "tenant-test"}, Data: map[string][]byte{}} + if bucket != "" { + s.Data["bucketName"] = []byte(bucket) + } + return s +} + +var altinityTestCredentials = BackupCredentialsConfig{SourceNamespace: "cozy-system", SourceSecretName: "platform-creds", TargetSecretName: "cozy-backups-creds"} + +// A Backup records which bucket its archive went to, so that a delete asked +// of a sidecar that now serves another bucket is not taken for done when that +// bucket answers "not found". It is read when the backup Job is created, from +// the Secret the sidecar of a system-bucket application reads. +func TestReconcileAltinity_BackupJobCarriesTheBucket(t *testing.T) { + cases := []struct { + name string + system bool + secret *corev1.Secret + want string // empty: no bucket recorded + }{ + {name: "system bucket", system: true, secret: altinityCredsSecret("bucket-a"), want: "bucket-a"}, + {name: "own bucket", system: false, secret: altinityCredsSecret("bucket-a")}, + {name: "no projected Secret", system: true}, + {name: "Secret without a bucket", system: true, secret: altinityCredsSecret("")}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + app := withUseSystemBucket(newAltinityClickHouseApp("ch-test", "tenant-test"), tc.system) + bj := runningAltinityBackupJob() + strategy := newAltinityArchiveStrategy("clickhouse-strategy") + objs := []client.Object{bj, strategy} + if tc.secret != nil { + objs = append(objs, tc.secret) + } + r, _, _ := newAltinityTestEnv(t, app, clientfake.NewClientBuilder().WithObjects(objs...)) + r.CredentialsConfig = altinityTestCredentials + ctx := context.Background() + if _, err := r.reconcileAltinity(ctx, bj, altinityResolved(strategy.Name)); err != nil { + t.Fatalf("reconcileAltinity: %v", err) + } + job := &batchv1.Job{} + if err := r.Get(ctx, client.ObjectKey{Namespace: bj.Namespace, Name: jobNameForBackupJob(bj)}, job); err != nil { + t.Fatalf("get backup Job: %v", err) + } + if got, ok := job.Annotations[altinityBucketKey]; got != tc.want || ok != (tc.want != "") { + t.Errorf("backup Job bucket = %q (set %v), want %q", got, ok, tc.want) + } + }) + } +} + +// On a platform that projects no credentials there is no Secret to read the +// bucket from; reading one by an empty name, which the API server rejects, +// would fail every backup of a system-bucket application there. +func TestReconcileAltinity_RecordsNoBucketWithoutProjectedCredentials(t *testing.T) { + app := withUseSystemBucket(newAltinityClickHouseApp("ch-test", "tenant-test"), true) + bj := runningAltinityBackupJob() + strategy := newAltinityArchiveStrategy("clickhouse-strategy") + builder := clientfake.NewClientBuilder().WithObjects(bj, strategy).WithInterceptorFuncs(interceptor.Funcs{ + Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if key.Name == "" { + return apierrors.NewBadRequest("resource name may not be empty") + } + return c.Get(ctx, key, obj, opts...) + }, + }) + r, _, _ := newAltinityTestEnv(t, app, builder) + ctx := context.Background() + if _, err := r.reconcileAltinity(ctx, bj, altinityResolved(strategy.Name)); err != nil { + t.Fatalf("reconcileAltinity: %v", err) + } + job := &batchv1.Job{} + if err := r.Get(ctx, client.ObjectKey{Namespace: bj.Namespace, Name: jobNameForBackupJob(bj)}, job); err != nil { + t.Fatalf("get backup Job: %v", err) + } + if v, ok := job.Annotations[altinityBucketKey]; ok { + t.Errorf("backup Job records bucket %q without projected credentials", v) + } +} + +// The bucket recorded on the Backup is the one stamped on the backup Job when +// it was created; a Job without the stamp records none. +func TestReconcileAltinity_RecordsTheBucketTheJobStartedWith(t *testing.T) { + for _, bucket := range []string{"bucket-a", ""} { + app := withUseSystemBucket(newAltinityClickHouseApp("ch-test", "tenant-test"), true) + got := completeAltinityBackup(t, app, func(bj *backupsv1alpha1.BackupJob) *batchv1.Job { + job := completedAltinityK8sJob(bj) + job.Annotations = map[string]string{altinityUseSystemBucketKey: "true"} + if bucket != "" { + job.Annotations[altinityBucketKey] = bucket + } + return job + }) + if v, ok := got.Spec.DriverMetadata[altinityBucketKey]; v != bucket || ok != (bucket != "") { + t.Errorf("Job stamped %q: Backup records %q (set %v)", bucket, v, ok) + } + } +} + func TestReconcileAltinity_FailsOnMalformedUseSystemBucket(t *testing.T) { app := newAltinityClickHouseApp("ch-test", "tenant-test") if err := unstructured.SetNestedField(app.Object, "yes", "spec", "backup", "useSystemBucket"); err != nil { @@ -161,3 +278,1167 @@ func TestReconcileAltinity_FailsOnMalformedUseSystemBucket(t *testing.T) { t.Errorf("expected no Backup without a recorded bucket flow, got %v", err) } } + +func altinityCleanupBackup(name string) *backupsv1alpha1.Backup { + return &backupsv1alpha1.Backup{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "tenant-test"}, + Spec: backupsv1alpha1.BackupSpec{ + ApplicationRef: newAltinityClickHouseRef("ch-test"), + StrategyRef: corev1.TypedLocalObjectReference{ + APIGroup: new(strategyv1alpha1.GroupVersion.Group), + Kind: strategyv1alpha1.AltinityStrategyKind, + Name: "cozy-default-altinity", + }, + TakenAt: metav1.Now(), + DriverMetadata: map[string]string{ + altinityArchiveMetaKey: "clickhouse-ch-test-" + name, + altinityUseSystemBucketKey: "true", + }, + }, + } +} + +func altinityAPIAuthSecret() *corev1.Secret { + return &corev1.Secret{ObjectMeta: metav1.ObjectMeta{ + Name: "clickhouse-ch-test-backup-api-auth", Namespace: "tenant-test", + }} +} + +func altinityCleanupFixtures(backup *backupsv1alpha1.Backup) []client.Object { + return []client.Object{ + &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "tenant-test"}}, + backup, + newAltinityArchiveStrategy("cozy-default-altinity"), + altinityAPIAuthSecret(), + withUseSystemBucket(newAltinityClickHouseApp("ch-test", "tenant-test"), true), + } +} + +// newAltinityCleanupClient registers the ClickHouse application kind the +// cleanup path reads alongside what the Rabbitmq cleanup client carries. +func newAltinityCleanupClient(objs ...client.Object) (client.Client, *runtime.Scheme) { + return newAltinityCleanupClientWith(interceptor.Funcs{}, objs...) +} + +func newAltinityCleanupClientWith(funcs interceptor.Funcs, objs ...client.Object) (client.Client, *runtime.Scheme) { + s := runtime.NewScheme() + _ = scheme.AddToScheme(s) + _ = backupsv1alpha1.AddToScheme(s) + _ = strategyv1alpha1.AddToScheme(s) + gv := schema.GroupVersion{Group: backupsv1alpha1.DefaultApplicationAPIGroup, Version: "v1alpha1"} + s.AddKnownTypeWithName(gv.WithKind("ClickHouse"), &unstructured.Unstructured{}) + s.AddKnownTypeWithName(gv.WithKind("ClickHouseList"), &unstructured.UnstructuredList{}) + mapper := meta.NewDefaultRESTMapper([]schema.GroupVersion{gv}) + mapper.Add(gv.WithKind("ClickHouse"), meta.RESTScopeNamespace) + return clientfake.NewClientBuilder().WithScheme(s).WithRESTMapper(mapper). + WithStatusSubresource(&batchv1.Job{}). + WithInterceptorFuncs(funcs). + WithObjects(objs...).Build(), s +} + +func listJobs(t *testing.T, c client.Client) []batchv1.Job { + t.Helper() + jobs := &batchv1.JobList{} + if err := c.List(context.Background(), jobs, client.InNamespace("tenant-test")); err != nil { + t.Fatalf("list jobs: %v", err) + } + return jobs.Items +} + +func envValue(t *testing.T, c corev1.Container, name string) string { + t.Helper() + for _, e := range c.Env { + if e.Name == name { + return e.Value + } + } + t.Fatalf("env %s not set on %s", name, c.Name) + return "" +} + +// Deleting a system-bucket Backup deletes its archive through the sidecar and +// holds the finalizer until that delete finished. +func TestBackupReconcile_HoldsFinalizerWhileAltinityCleanupRuns(t *testing.T) { + backup := altinityCleanupBackup("ch-bk") + backup.Finalizers = []string{backupFinalizer} + c, s := newAltinityCleanupClient(altinityCleanupFixtures(backup)...) + r := &BackupReconciler{Client: c, Scheme: s, Recorder: record.NewFakeRecorder(10)} + ctx := context.Background() + + if err := c.Delete(ctx, backup); err != nil { + t.Fatalf("delete backup: %v", err) + } + key := client.ObjectKeyFromObject(backup) + res, err := r.Reconcile(ctx, ctrl.Request{NamespacedName: key}) + if err != nil { + t.Fatalf("Reconcile: %v", err) + } + if res.RequeueAfter == 0 { + t.Error("expected a requeue while the cleanup Job runs") + } + got := &backupsv1alpha1.Backup{} + if err := c.Get(ctx, key, got); err != nil { + t.Fatalf("Backup must still exist while cleanup runs: %v", err) + } + if !controllerutil.ContainsFinalizer(got, backupFinalizer) { + t.Error("expected the finalizer retained while the cleanup Job runs") + } + + jobs := listJobs(t, c) + if len(jobs) != 1 { + t.Fatalf("expected one cleanup Job, got %d", len(jobs)) + } + job := jobs[0] + if job.Name != "ch-bk-cleanup" { + t.Errorf("cleanup Job name = %q", job.Name) + } + if len(job.OwnerReferences) != 0 { + t.Errorf("cleanup Job must be ownerless so it outlives the Backup, got %+v", job.OwnerReferences) + } + if job.Spec.ActiveDeadlineSeconds == nil || job.Spec.TTLSecondsAfterFinished == nil { + t.Error("cleanup Job needs activeDeadlineSeconds and a TTL as backstops") + } + pod := job.Spec.Template.Spec + if len(pod.Containers) != 1 { + t.Fatalf("expected one container, got %d", len(pod.Containers)) + } + ctr := pod.Containers[0] + if ctr.Image != "altinity/clickhouse-backup:test" { + t.Errorf("image = %q, want the strategy container's image", ctr.Image) + } + if got := envValue(t, ctr, "ARCHIVE_NAME"); got != "clickhouse-ch-test-ch-bk" { + t.Errorf("ARCHIVE_NAME = %q", got) + } + if got := envValue(t, ctr, "API_HOST"); got != "chi-clickhouse-ch-test-clickhouse-0-0.tenant-test.svc" { + t.Errorf("API_HOST = %q", got) + } + for _, e := range ctr.Env { + if e.Name == "API_USERNAME" || e.Name == "API_PASSWORD" { + if e.ValueFrom == nil || e.ValueFrom.SecretKeyRef == nil || + e.ValueFrom.SecretKeyRef.Name != "clickhouse-ch-test-backup-api-auth" { + t.Errorf("%s must come from the backup-api-auth Secret, got %+v", e.Name, e.ValueFrom) + } + } + } + if strings.Contains(strings.Join(append(ctr.Command, ctr.Args...), " "), "restore") { + t.Error("cleanup Pod must never call a restore route") + } + + job.Status.Conditions = []batchv1.JobCondition{{Type: batchv1.JobComplete, Status: corev1.ConditionTrue}} + if err := c.Status().Update(ctx, &job); err != nil { + t.Fatalf("complete job: %v", err) + } + if _, err := r.Reconcile(ctx, ctrl.Request{NamespacedName: key}); err != nil { + t.Fatalf("Reconcile after completion: %v", err) + } + if err := c.Get(ctx, key, got); !apierrors.IsNotFound(err) { + t.Errorf("expected the Backup removed after the cleanup Job completed, got %v", err) + } + if left := listJobs(t, c); len(left) != 0 { + t.Errorf("expected the completed cleanup Job reaped, %d left", len(left)) + } +} + +// A Backup deleted before the Backup reconciler first sees it still has its +// archive deleted: the finalizer that holds it for cleanup comes with it from +// the driver, not from that reconciler's first pass. +func TestBackupReconcile_DeletesTheArchiveOfABackupDeletedAtOnce(t *testing.T) { + created := completeAltinityBackup(t, withUseSystemBucket(newAltinityClickHouseApp("ch-test", "tenant-test"), true), completedAltinityK8sJob) + if !controllerutil.ContainsFinalizer(created, backupFinalizer) { + t.Errorf("Backup created without %s, finalizers %v", backupFinalizer, created.Finalizers) + } + created.ResourceVersion = "" + c, s := newAltinityCleanupClient(append(altinityCleanupFixtures(created), newAltinityArchiveStrategy(created.Spec.StrategyRef.Name))...) + r := &BackupReconciler{Client: c, Scheme: s, Recorder: record.NewFakeRecorder(10)} + ctx := context.Background() + + if err := c.Delete(ctx, created); err != nil { + t.Fatalf("delete backup: %v", err) + } + key := client.ObjectKeyFromObject(created) + if err := c.Get(ctx, key, &backupsv1alpha1.Backup{}); err != nil { + t.Fatalf("Backup gone before its archive was deleted: %v", err) + } + if _, err := r.Reconcile(ctx, ctrl.Request{NamespacedName: key}); err != nil { + t.Fatalf("Reconcile: %v", err) + } + jobs := listJobs(t, c) + if len(jobs) != 1 { + t.Fatalf("expected one cleanup Job, got %d", len(jobs)) + } + if got, want := envValue(t, jobs[0].Spec.Template.Spec.Containers[0], "ARCHIVE_NAME"), created.Spec.DriverMetadata[altinityArchiveMetaKey]; got != want || got == "" { + t.Errorf("ARCHIVE_NAME = %q, want the recorded archive %q", got, want) + } +} + +// ownCleanupJob is the cleanup Job this Backup's own cleanup would create. +func ownCleanupJob(b *backupsv1alpha1.Backup) *batchv1.Job { + return buildAltinityCleanupJob(b.Namespace, b.Name+"-cleanup", corev1.Container{Image: "img"}, corev1.PodSpec{}, "host", "secret", + b.Spec.DriverMetadata[altinityArchiveMetaKey]) +} + +func TestCleanupAltinityBackup_FailedJobIsRetried(t *testing.T) { + backup := altinityCleanupBackup("ch-bk") + failed := ownCleanupJob(backup) + failed.Status.Conditions = []batchv1.JobCondition{{ + Type: batchv1.JobFailed, Status: corev1.ConditionTrue, + Reason: "DeadlineExceeded", Message: "Job was active longer than specified deadline", + }} + 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 { + t.Error("a failed delete must keep the Backup and requeue") + } + if len(rec.Events) == 0 { + t.Error("a failed delete must surface as a Warning Event on the Backup") + } else if ev := <-rec.Events; !strings.Contains(ev, "Warning") || !strings.Contains(ev, "ch-bk-cleanup") { + t.Errorf("event %q must be a Warning naming the failed Job", ev) + } else if !strings.Contains(ev, "DeadlineExceeded") || !strings.Contains(ev, "longer than specified deadline") { + // The same reconcile deletes the Job and its Pods, so the Event is + // the only place the failure is still readable. + t.Errorf("event %q must carry the reason and message of the Job's Failed condition", ev) + } else if strings.Contains(ev, "Pod log") { + t.Errorf("event %q must not send the reader to a Pod log the reconcile deletes", ev) + } + if left := listJobs(t, c); len(left) != 0 { + t.Errorf("expected the failed Job collected for a fresh attempt, %d left", len(left)) + } +} + +// A delete that keeps failing, such as one refused for a wrong sidecar +// password, would otherwise cost a Job, its Pod and a Warning Event every few +// seconds for as long as it fails. Each failure doubles the wait before the +// next Job, up to a cap, and the wait is kept on the Backup, since deleting the +// Job is what starts the next attempt. +func TestCleanupAltinityBackup_FailedJobBacksOff(t *testing.T) { + cases := []struct { + name string + failures string // recorded before this failure; empty for none + wantFailures string + wantDelay time.Duration + }{ + {name: "first failure", wantFailures: "1", wantDelay: altinityCleanupRetryBase}, + {name: "third failure", failures: "2", wantFailures: "3", wantDelay: 4 * altinityCleanupRetryBase}, + {name: "past the cap", failures: "40", wantFailures: "41", wantDelay: altinityCleanupRetryMax}, + {name: "far past the cap, where doubling would overflow", failures: "100", wantFailures: "101", wantDelay: altinityCleanupRetryMax}, + {name: "unreadable count starts over", failures: "many", wantFailures: "1", wantDelay: altinityCleanupRetryBase}, + {name: "negative count starts over", failures: "-3", wantFailures: "1", wantDelay: altinityCleanupRetryBase}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + backup := altinityCleanupBackup("ch-bk") + if tc.failures != "" { + backup.Annotations = map[string]string{altinityCleanupFailuresAnnotation: tc.failures} + } + failed := ownCleanupJob(backup) + 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)} + before := time.Now() + res, err := r.cleanupOnDelete(context.Background(), backup) + if err != nil { + t.Fatalf("cleanupOnDelete: %v", err) + } + if res.RequeueAfter != tc.wantDelay { + t.Errorf("RequeueAfter = %s, want %s", res.RequeueAfter, tc.wantDelay) + } + 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 != tc.wantFailures { + t.Errorf("failures = %q, want %q", f, tc.wantFailures) + } + at, err := time.Parse(time.RFC3339, got.Annotations[altinityCleanupRetryAfterAnnotation]) + if err != nil { + t.Fatalf("retry-after %q: %v", got.Annotations[altinityCleanupRetryAfterAnnotation], err) + } + if lo, hi := before.Add(tc.wantDelay).Add(-time.Second), time.Now().Add(tc.wantDelay).Add(time.Second); at.Before(lo) || at.After(hi) { + t.Errorf("retry-after = %s, want about %s from now", at, tc.wantDelay) + } + }) + } +} + +// 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. +func TestCleanupAltinityBackup_KeepsTheWaitWhenTheFailedJobCannotBeDeleted(t *testing.T) { + backup := altinityCleanupBackup("ch-bk") + failed := ownCleanupJob(backup) + failed.Status.Conditions = []batchv1.JobCondition{{Type: batchv1.JobFailed, Status: corev1.ConditionTrue, Reason: "BackoffLimitExceeded"}} + c, s := newAltinityCleanupClientWith(interceptor.Funcs{ + Delete: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.DeleteOption) error { + if _, isJob := obj.(*batchv1.Job); isJob { + return apierrors.NewServiceUnavailable("apiserver unavailable") + } + return c.Delete(ctx, obj, opts...) + }, + }, append(altinityCleanupFixtures(backup), failed)...) + r := &BackupReconciler{Client: c, Scheme: s, Recorder: record.NewFakeRecorder(10)} + if _, err := r.cleanupOnDelete(context.Background(), backup); err == nil { + t.Fatal("cleanupOnDelete succeeded although the failed Job could not be deleted") + } + got := &backupsv1alpha1.Backup{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(backup), got); err != nil { + t.Fatalf("get Backup: %v", err) + } + if got.Annotations[altinityCleanupRetryAfterAnnotation] == "" || got.Annotations[altinityCleanupFailuresAnnotation] != "1" { + t.Errorf("annotations = %v, want the failure and the wait recorded", got.Annotations) + } +} + +// The next cleanup Job waits for the time the last failure set; a reconcile +// before it, such as the one the annotation update itself triggers, starts +// nothing. +func TestCleanupAltinityBackup_WaitsForTheRetryTime(t *testing.T) { + cases := []struct { + name string + at string + wantJob bool + }{ + {name: "retry time ahead", at: time.Now().Add(10 * time.Minute).UTC().Format(time.RFC3339)}, + {name: "retry time passed", at: time.Now().Add(-time.Second).UTC().Format(time.RFC3339), wantJob: true}, + {name: "unreadable retry time", at: "soon", wantJob: true}, + // No failure sets a wait longer than the cap; a time further ahead + // comes from a skewed clock or a hand edit and would hold the Backup + // with nothing saying why. + {name: "retry time past the cap", at: time.Now().Add(altinityCleanupRetryMax + time.Hour).UTC().Format(time.RFC3339), wantJob: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + backup := altinityCleanupBackup("ch-bk") + backup.Annotations = map[string]string{ + altinityCleanupFailuresAnnotation: "3", + altinityCleanupRetryAfterAnnotation: tc.at, + } + c, s := newAltinityCleanupClient(altinityCleanupFixtures(backup)...) + 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) + } + if jobs := listJobs(t, c); (len(jobs) == 1) != tc.wantJob { + t.Fatalf("cleanup Jobs = %d, want a Job = %v", len(jobs), tc.wantJob) + } + if !tc.wantJob && res.RequeueAfter > 10*time.Minute { + t.Errorf("RequeueAfter = %s, want no later than the retry time", res.RequeueAfter) + } + }) + } +} + +// A cleanup Job left by an earlier Backup of the same name, released while +// its Job ran, deleted a different archive: its completion is not this one's. +func TestCleanupAltinityBackup_StaleJobForAnotherArchiveIsReplaced(t *testing.T) { + backup := altinityCleanupBackup("ch-bk") + stale := buildAltinityCleanupJob("tenant-test", "ch-bk-cleanup", corev1.Container{Image: "img"}, corev1.PodSpec{}, "host", "secret", "clickhouse-ch-test-earlier") + stale.Status.Conditions = []batchv1.JobCondition{{Type: batchv1.JobComplete, Status: corev1.ConditionTrue}} + c, s := newAltinityCleanupClient(append(altinityCleanupFixtures(backup), stale)...) + 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.Error("a Job for another archive must not release the Backup") + } + if left := listJobs(t, c); len(left) != 0 { + t.Errorf("expected the stale Job collected so a fresh one runs, %d left", len(left)) + } +} + +func TestCleanupAltinityBackup_RunningJobRequeues(t *testing.T) { + backup := altinityCleanupBackup("ch-bk") + c, s := newAltinityCleanupClient(append(altinityCleanupFixtures(backup), ownCleanupJob(backup))...) + 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.Error("expected a requeue while the Job runs") + } + if left := listJobs(t, c); len(left) != 1 { + t.Errorf("a running Job must be left alone, %d jobs", len(left)) + } +} + +// The strategy only supplies the image of a Job not yet created; one already +// running deletes the archive without it, so losing the strategy then must +// not release the Backup as if the archive were left behind. +func TestCleanupAltinityBackup_RunningJobOutlivesItsStrategy(t *testing.T) { + for name, mutate := range map[string]func([]client.Object) []client.Object{ + "strategy gone": func(objs []client.Object) []client.Object { + return dropObject(objs, &strategyv1alpha1.Altinity{}) + }, + "strategy has no container image": func(objs []client.Object) []client.Object { + for _, o := range objs { + if st, ok := o.(*strategyv1alpha1.Altinity); ok { + st.Spec.Template.Spec.Containers[0].Image = "" + } + } + return objs + }, + } { + t.Run(name, func(t *testing.T) { + backup := altinityCleanupBackup("ch-bk") + c, s := newAltinityCleanupClient(append(mutate(altinityCleanupFixtures(backup)), ownCleanupJob(backup))...) + 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 { + t.Error("expected the Backup held while its cleanup Job runs") + } + if len(rec.Events) != 0 { + t.Errorf("unexpected event %q for a delete still running", <-rec.Events) + } + }) + } +} + +// Every case here lets the Backup go without spawning a Job: the archive is +// either not the driver's to delete or cannot be deleted from here. +func TestCleanupAltinityBackup_ReleasesWithoutJob(t *testing.T) { + cases := map[string]struct { + mutate func(b *backupsv1alpha1.Backup, objs []client.Object) []client.Object + wantEvent bool + wantReason string + }{ + "no archive recorded": {mutate: func(b *backupsv1alpha1.Backup, objs []client.Object) []client.Object { + delete(b.Spec.DriverMetadata, altinityArchiveMetaKey) + return objs + }}, + "legacy bucket flow": {mutate: func(b *backupsv1alpha1.Backup, objs []client.Object) []client.Object { + b.Spec.DriverMetadata[altinityUseSystemBucketKey] = "false" + return objs + }}, + "flow not recorded": {mutate: func(b *backupsv1alpha1.Backup, objs []client.Object) []client.Object { + delete(b.Spec.DriverMetadata, altinityUseSystemBucketKey) + return objs + }}, + "skip annotation": {mutate: func(b *backupsv1alpha1.Backup, objs []client.Object) []client.Object { + b.Annotations = map[string]string{"backups.cozystack.io/skip-artifact-cleanup": "true"} + return objs + }}, + "archive name unsafe in a URL path": {wantEvent: true, mutate: func(b *backupsv1alpha1.Backup, objs []client.Object) []client.Object { + b.Spec.DriverMetadata[altinityArchiveMetaKey] = "../other/x" + return objs + }}, + "archive named before per-run names": {wantEvent: true, wantReason: "without its BackupJob's UID", mutate: func(b *backupsv1alpha1.Backup, objs []client.Object) []client.Object { + b.Spec.DriverMetadata[altinityArchiveMetaKey] = "clickhouse-ch-test-20260304T050607Z" + return objs + }}, + "strategy gone": {wantEvent: true, mutate: func(b *backupsv1alpha1.Backup, objs []client.Object) []client.Object { + return dropObject(objs, &strategyv1alpha1.Altinity{}) + }}, + "strategy has no container": {wantEvent: true, mutate: func(b *backupsv1alpha1.Backup, objs []client.Object) []client.Object { + for _, o := range objs { + if s, ok := o.(*strategyv1alpha1.Altinity); ok { + s.Spec.Template.Spec.Containers = nil + } + } + return objs + }}, + "strategy container has no image": {wantEvent: true, mutate: func(b *backupsv1alpha1.Backup, objs []client.Object) []client.Object { + for _, o := range objs { + if s, ok := o.(*strategyv1alpha1.Altinity); ok { + s.Spec.Template.Spec.Containers[0].Image = "" + } + } + return objs + }}, + "application gone": {wantEvent: true, wantReason: "application is gone", mutate: func(b *backupsv1alpha1.Backup, objs []client.Object) []client.Object { + return dropObject(objs, &unstructured.Unstructured{}) + }}, + "application moved off the system bucket": {wantEvent: true, wantReason: "no longer uses the system bucket", mutate: func(b *backupsv1alpha1.Backup, objs []client.Object) []client.Object { + for _, o := range objs { + if u, ok := o.(*unstructured.Unstructured); ok { + withUseSystemBucket(u, false) + } + } + return objs + }}, + "API Secret gone": {wantEvent: true, mutate: func(b *backupsv1alpha1.Backup, objs []client.Object) []client.Object { + return dropObject(objs, &corev1.Secret{}) + }}, + "namespace terminating": {wantEvent: true, mutate: func(b *backupsv1alpha1.Backup, objs []client.Object) []client.Object { + return dropObject(objs, &corev1.Namespace{}) + }}, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + backup := altinityCleanupBackup("ch-bk") + objs := tc.mutate(backup, altinityCleanupFixtures(backup)) + c, s := newAltinityCleanupClient(objs...) + 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.Requeue { + t.Errorf("expected the Backup released, got %+v", res) + } + if jobs := listJobs(t, c); len(jobs) != 0 { + t.Errorf("expected no cleanup Job, got %d", len(jobs)) + } + gotEvent := len(rec.Events) > 0 + if gotEvent != tc.wantEvent { + t.Errorf("warning event recorded = %v, want %v", gotEvent, tc.wantEvent) + } + if gotEvent { + if ev := <-rec.Events; !strings.Contains(ev, "ArtifactNotDeleted") || !strings.Contains(ev, backup.Spec.DriverMetadata[altinityArchiveMetaKey]) { + t.Errorf("event %q must name the archive left behind", ev) + } else if !strings.Contains(ev, tc.wantReason) { + t.Errorf("event %q must give the reason %q", ev, tc.wantReason) + } + } + }) + } +} + +// An archive named per run, the start time followed by the BackupJob's UID, +// is the one run's alone and is deleted. +func TestCleanupAltinityBackup_DeletesAnArchiveNamedPerRun(t *testing.T) { + backup := altinityCleanupBackup("ch-bk") + run := runningAltinityBackupJob() + run.UID = "0f3c9a1e-5b7d-4c2a-9e8f-1a2b3c4d5e6f" + archive := altinityArchiveName(run) + backup.Spec.DriverMetadata[altinityArchiveMetaKey] = archive + c, s := newAltinityCleanupClient(altinityCleanupFixtures(backup)...) + r := &BackupReconciler{Client: c, Scheme: s, Recorder: record.NewFakeRecorder(10)} + if _, err := r.cleanupOnDelete(context.Background(), backup); err != nil { + t.Fatalf("cleanupOnDelete: %v", err) + } + jobs := listJobs(t, c) + if len(jobs) != 1 { + t.Fatalf("expected one cleanup Job, got %d", len(jobs)) + } + if got := envValue(t, jobs[0].Spec.Template.Spec.Containers[0], "ARCHIVE_NAME"); got != archive { + t.Errorf("ARCHIVE_NAME = %q, want %q", got, archive) + } +} + +// With the ClickHouse kind no longer served there is no application to call. +func TestCleanupAltinityBackup_ApplicationKindNotServedReleases(t *testing.T) { + backup := altinityCleanupBackup("ch-bk") + c, s := newRabbitmqBackupReconcilerClient(altinityCleanupFixtures(backup)[:4]...) + 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 || len(listJobs(t, c)) != 0 || len(rec.Events) == 0 { + t.Errorf("expected release with a Warning Event and no Job, got %+v, %d events", res, len(rec.Events)) + } +} + +// The skip annotation also reaps a delete Job already in flight. +func TestCleanupAltinityBackup_SkipAnnotationReapsInflightJob(t *testing.T) { + backup := altinityCleanupBackup("ch-bk") + backup.Annotations = map[string]string{"backups.cozystack.io/skip-artifact-cleanup": "true"} + c, s := newAltinityCleanupClient(append(altinityCleanupFixtures(backup), ownCleanupJob(backup))...) + r := &BackupReconciler{Client: c, Scheme: s, Recorder: record.NewFakeRecorder(10)} + if _, err := r.cleanupOnDelete(context.Background(), backup); err != nil { + t.Fatalf("cleanupOnDelete: %v", err) + } + if left := listJobs(t, c); len(left) != 0 { + t.Errorf("expected the in-flight Job reaped, %d left", len(left)) + } +} + +// A Job of the same name this controller did not create (the ClickHouse +// chart's own cleanup hook is -cleanup) is never deleted or read as +// the outcome of the archive delete. +func TestCleanupAltinityBackup_LeavesForeignJobOfTheSameName(t *testing.T) { + for name, skip := range map[string]bool{"cleanup": false, "skip annotation": true} { + t.Run(name, func(t *testing.T) { + backup := altinityCleanupBackup("ch-bk") + if skip { + backup.Annotations = map[string]string{"backups.cozystack.io/skip-artifact-cleanup": "true"} + } + foreign := ownCleanupJob(backup) + foreign.Labels = map[string]string{"app.kubernetes.io/name": "clickhouse"} + foreign.Status.Conditions = []batchv1.JobCondition{{Type: batchv1.JobComplete, Status: corev1.ConditionTrue}} + c, s := newAltinityCleanupClient(append(altinityCleanupFixtures(backup), foreign)...) + 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 left := listJobs(t, c); len(left) != 1 { + t.Fatalf("the foreign Job must be left alone, %d jobs", len(left)) + } + if res.RequeueAfter != 0 || res.Requeue { + t.Errorf("expected the Backup released, got %+v", res) + } + if !skip && len(rec.Events) == 0 { + t.Error("a release because of a foreign Job must surface as a Warning Event") + } + }) + } +} + +func dropObject(objs []client.Object, like client.Object) []client.Object { + out := objs[:0:0] + for _, o := range objs { + if reflect.TypeOf(o) != reflect.TypeOf(like) { + out = append(out, o) + } + } + return out +} + +// runAltinityCleanupScript runs the cleanup Pod's script with a curl stub that +// answers with the given body and HTTP status, and returns the script's exit +// status and the URL and method the stub was called with. +func runAltinityCleanupScript(t *testing.T, body, code string) (int, string) { + t.Helper() + exit, calls := runAltinityCleanupScriptSeq(t, body, code) + return exit, calls[len(calls)-1] +} + +// runAltinityCleanupScriptSeq answers the n-th curl call with the n-th of the +// space-separated codes, repeating the last one; a code "xN" makes that call +// fail with curl exit status N and no answer, as a connection that could not +// be made does. sleep is a no-op and every +// date call advances the clock by 100 seconds, so a wait loop ends at once. +func runAltinityCleanupScriptSeq(t *testing.T, body, codes string) (int, []string) { + t.Helper() + if _, err := exec.LookPath("sh"); err != nil { + t.Skip("sh not available") + } + dir := t.TempDir() + stubs := map[string]string{ + "curl": "#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"$STUB_LOG\"\nn=$(wc -l < \"$STUB_LOG\")\nset -- $STUB_CODES\ncode=$1\ni=1\nfor c in \"$@\"; do [ \"$i\" -le \"$n\" ] && code=$c; i=$((i+1)); done\ncase \"$code\" in x*) exit \"${code#x}\" ;; esac\nprintf '%s\\n%s' \"$STUB_BODY\" \"$code\"\n", + "sleep": "#!/bin/sh\nexit 0\n", + "date": "#!/bin/sh\necho x >> \"$STUB_CLOCK\"\necho $((1000 + 100 * $(wc -l < \"$STUB_CLOCK\")))\n", + } + for name, src := range stubs { + if err := os.WriteFile(filepath.Join(dir, name), []byte(src), 0o755); err != nil { + t.Fatalf("write %s stub: %v", name, err) + } + } + logPath := filepath.Join(dir, "log") + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, "sh", "-c", altinityCleanupScript) + cmd.Env = []string{ + "PATH=" + dir + ":" + os.Getenv("PATH"), + "STUB_LOG=" + logPath, "STUB_BODY=" + body, "STUB_CODES=" + codes, + "STUB_CLOCK=" + filepath.Join(dir, "clock"), + "API_HOST=chi-x.ns.svc", "ARCHIVE_NAME=clickhouse-x-bk", + "API_USERNAME=u", "API_PASSWORD=p", + } + err := cmd.Run() + if ctx.Err() != nil { + t.Fatalf("script still running after %v: %v", 30*time.Second, ctx.Err()) + } + exit := 0 + if ee, ok := err.(*exec.ExitError); ok { + exit = ee.ExitCode() + } else if err != nil { + t.Fatalf("run script: %v", err) + } + called, rerr := os.ReadFile(logPath) + if rerr != nil { + t.Fatalf("curl stub was not called: %v", rerr) + } + return exit, strings.Split(strings.TrimSpace(string(called)), "\n") +} + +// The sidecar answers 423 to a delete while any other operation runs, such as +// a backup of the same application; failing the Job on it would spin a new +// Job and a Warning Event every few seconds for the whole backup. +func TestAltinityCleanupScript_WaitsForABusySidecar(t *testing.T) { + exit, calls := runAltinityCleanupScriptSeq(t, `{"status":"success"}`, "423 423 200") + if exit != 0 { + t.Errorf("exit = %d, a delete that went through after the sidecar was busy must succeed", exit) + } + if len(calls) != 3 { + t.Errorf("curl called %d times, want the delete retried until it was accepted", len(calls)) + } +} + +// A sidecar that cannot be reached, its Pod restarting or its node gone, is +// waited for like a busy one; failing at once would spin a new Job, two Pods +// and a Warning Event every few seconds for as long as it is down. +func TestAltinityCleanupScript_WaitsForAnUnreachableSidecar(t *testing.T) { + exit, calls := runAltinityCleanupScriptSeq(t, `{"status":"success"}`, "x7 x28 200") + if exit != 0 { + t.Errorf("exit = %d, a delete that went through once the sidecar was back must succeed", exit) + } + if len(calls) != 3 { + t.Errorf("curl called %d times, want the delete retried until the sidecar answered", len(calls)) + } +} + +func TestAltinityCleanupScript_GivesUpOnASidecarThatStaysUnreachable(t *testing.T) { + exit, calls := runAltinityCleanupScriptSeq(t, "", "x7") + if exit == 0 { + t.Error("exit 0 for a sidecar that never answered, want the Job failed before its deadline") + } + if len(calls) < 2 || len(calls) > 10 { + t.Errorf("curl called %d times, want a few attempts within the bounded wait", len(calls)) + } +} + +// The wait is bounded: a sidecar that stays busy fails the Job before its +// activeDeadlineSeconds, and the controller starts a fresh one. +func TestAltinityCleanupScript_GivesUpOnASidecarThatStaysBusy(t *testing.T) { + exit, calls := runAltinityCleanupScriptSeq(t, `{"status":"error","error":"another operation is currently running"}`, "423") + if exit == 0 { + t.Error("exit 0 although the delete never ran") + } + if len(calls) > 10 { + t.Errorf("curl called %d times, want the wait bounded by the time budget", len(calls)) + } +} + +func TestAltinityCleanupScript_CallsTheRemoteDeleteRoute(t *testing.T) { + exit, called := runAltinityCleanupScript(t, `{"status":"success"}`, "200") + if exit != 0 { + t.Errorf("exit = %d on 200", exit) + } + if !strings.Contains(called, "-X POST") || !strings.Contains(called, "http://chi-x.ns.svc:7171/backup/delete/remote/clickhouse-x-bk") { + t.Errorf("curl called with %q, want POST /backup/delete/remote/", called) + } + // Without a client-side limit a sidecar that never answers holds the Pod + // until the Job's deadline kills it mid-request. + if !strings.Contains(called, "--max-time ") { + t.Errorf("curl called with %q, want the request bounded by the remaining budget", called) + } +} + +func TestAltinityCleanupScript_ArchiveAlreadyGoneIsSuccess(t *testing.T) { + exit, _ := runAltinityCleanupScript(t, + `{"status":"error","operation":"delete","error":"'clickhouse-x-bk' is not found on remote storage"}`, "500") + if exit != 0 { + t.Errorf("exit = %d, an archive already gone must count as deleted", exit) + } +} + +func TestAltinityCleanupScript_FailsOnOtherErrors(t *testing.T) { + for _, tc := range []struct{ body, code string }{ + {`{"status":"error","error":"another operation is currently running"}`, "423"}, + {`{"status":"error","error":"can't connect to clickhouse"}`, "500"}, + {`not found`, "404"}, + {``, "401"}, + } { + if exit, _ := runAltinityCleanupScript(t, tc.body, tc.code); exit == 0 { + t.Errorf("exit 0 on %s %q, want failure so the delete is retried", tc.code, tc.body) + } + } +} + +// An application moved to its own bucket while the delete ran restarts its +// sidecar on that bucket, which answers "not found" for an archive left in +// the system bucket, and the Job completes. Releasing the Backup on that +// completion must say the archive may still be there. +func TestCleanupAltinityBackup_CompletionAfterLeavingTheSystemBucketWarns(t *testing.T) { + for name, tc := range map[string]struct { + onSystemBucket bool + appGone bool + wantEvent bool + }{ + "still on the system bucket": {onSystemBucket: true}, + "moved to its own bucket": {onSystemBucket: false, wantEvent: true}, + // The sidecar that answered was the application's own on the system + // bucket; removing the application afterwards does not undo that. + "removed after the delete": {appGone: true}, + } { + t.Run(name, func(t *testing.T) { + backup := altinityCleanupBackup("ch-bk") + done := ownCleanupJob(backup) + done.Status.Conditions = []batchv1.JobCondition{{Type: batchv1.JobComplete, Status: corev1.ConditionTrue}} + objs := append(altinityCleanupFixtures(backup), done) + for _, o := range objs { + if u, ok := o.(*unstructured.Unstructured); ok { + withUseSystemBucket(u, tc.onSystemBucket) + } + } + if tc.appGone { + objs = dropObject(objs, &unstructured.Unstructured{}) + } + c, s := newAltinityCleanupClient(objs...) + 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.Requeue { + t.Errorf("expected the Backup released on completion, got %+v", res) + } + if left := listJobs(t, c); len(left) != 0 { + t.Errorf("expected the completed Job reaped, %d left", len(left)) + } + if got := len(rec.Events) > 0; got != tc.wantEvent { + t.Fatalf("warning event recorded = %v, want %v", got, tc.wantEvent) + } + if tc.wantEvent { + if ev := <-rec.Events; !strings.Contains(ev, "ArtifactNotDeleted") || !strings.Contains(ev, "clickhouse-ch-test-ch-bk") || !strings.Contains(ev, "may remain") { + t.Errorf("event %q must say the named archive may remain", ev) + } + } + }) + } +} + +// A delete reaches the bucket the sidecar serves now. When the Backup records +// another bucket, that sidecar would answer "not found" and the delete would +// count as done while the archive stays where it was written, so the Backup is +// released with a Warning naming both buckets instead. A Backup that records +// no bucket, taken before this was recorded, is deleted as before. +func TestCleanupAltinityBackup_ChecksTheBucketItWasWrittenTo(t *testing.T) { + cases := []struct { + name string + recorded string + current *corev1.Secret + wantJob bool + wantEvent []string + }{ + {name: "same bucket", recorded: "bucket-a", current: altinityCredsSecret("bucket-a"), wantJob: true}, + {name: "bucket changed", recorded: "bucket-a", current: altinityCredsSecret("bucket-b"), wantEvent: []string{"ArtifactNotDeleted", "bucket-a", "bucket-b"}}, + {name: "no projected Secret", recorded: "bucket-a", wantEvent: []string{"ArtifactNotDeleted", "bucket-a"}}, + {name: "Secret without a bucket", recorded: "bucket-a", current: altinityCredsSecret(""), wantEvent: []string{"ArtifactNotDeleted", "bucket-a"}}, + {name: "bucket not recorded", current: altinityCredsSecret("bucket-b"), wantJob: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + backup := altinityCleanupBackup("ch-bk") + if tc.recorded != "" { + backup.Spec.DriverMetadata[altinityBucketKey] = tc.recorded + } + objs := altinityCleanupFixtures(backup) + if tc.current != nil { + objs = append(objs, tc.current) + } + c, s := newAltinityCleanupClient(objs...) + rec := record.NewFakeRecorder(10) + r := &BackupReconciler{Client: c, Scheme: s, Recorder: rec, CredentialsConfig: altinityTestCredentials} + if _, err := r.cleanupOnDelete(context.Background(), backup); err != nil { + t.Fatalf("cleanupOnDelete: %v", err) + } + if jobs := listJobs(t, c); (len(jobs) == 1) != tc.wantJob { + t.Fatalf("cleanup Jobs = %d, want a Job = %v", len(jobs), tc.wantJob) + } + if len(tc.wantEvent) == 0 { + if len(rec.Events) != 0 { + t.Errorf("unexpected event %q", <-rec.Events) + } + return + } + if len(rec.Events) == 0 { + t.Fatal("expected a Warning Event naming the archive left") + } + ev := <-rec.Events + for _, want := range tc.wantEvent { + if !strings.Contains(ev, want) { + t.Errorf("event %q does not mention %q", ev, want) + } + } + }) + } +} + +// The sidecar takes up projected credentials only some time after the Secret +// changes, so right after the platform's bucket moved back to the one a Backup +// records, the sidecar may still serve the other one, answer "not found" and +// have the delete counted as done. The cleanup Job waits that time out, as the +// backup and restore Jobs do. +func TestCleanupAltinityBackup_WaitsForProjectedCredentialsToReachTheSidecar(t *testing.T) { + cases := []struct { + name string + updated time.Time + wantJob bool + }{ + {name: "just updated", updated: time.Now()}, + {name: "updated long ago", updated: time.Now().Add(-altinityCredentialsPropagation - time.Second), wantJob: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + backup := altinityCleanupBackup("ch-bk") + backup.Spec.DriverMetadata[altinityBucketKey] = "bucket-a" + creds := altinityCredsSecret("bucket-a") + creds.Annotations = map[string]string{credentialsUpdatedAtAnnotation: tc.updated.UTC().Format(time.RFC3339)} + c, s := newAltinityCleanupClient(append(altinityCleanupFixtures(backup), creds)...) + r := &BackupReconciler{Client: c, Scheme: s, Recorder: record.NewFakeRecorder(10), CredentialsConfig: altinityTestCredentials} + 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) + } + if jobs := listJobs(t, c); (len(jobs) == 1) != tc.wantJob { + t.Fatalf("cleanup Jobs = %d, want a Job = %v", len(jobs), tc.wantJob) + } + }) + } +} + +// The platform's bucket can change while the delete runs; a sidecar +// restarted on the new one answers "not found" and the Job completes. +// Releasing the Backup on that completion must say the archive may remain. +func TestCleanupAltinityBackup_CompletionAfterTheBucketChangedWarns(t *testing.T) { + for name, tc := range map[string]struct { + current string + wantEvent bool + }{ + "same bucket": {current: "bucket-a"}, + "bucket changed": {current: "bucket-b", wantEvent: true}, + } { + t.Run(name, func(t *testing.T) { + backup := altinityCleanupBackup("ch-bk") + backup.Spec.DriverMetadata[altinityBucketKey] = "bucket-a" + done := ownCleanupJob(backup) + done.Status.Conditions = []batchv1.JobCondition{{Type: batchv1.JobComplete, Status: corev1.ConditionTrue}} + c, s := newAltinityCleanupClient(append(altinityCleanupFixtures(backup), done, altinityCredsSecret(tc.current))...) + rec := record.NewFakeRecorder(10) + r := &BackupReconciler{Client: c, Scheme: s, Recorder: rec, CredentialsConfig: altinityTestCredentials} + res, err := r.cleanupOnDelete(context.Background(), backup) + if err != nil { + t.Fatalf("cleanupOnDelete: %v", err) + } + if res.RequeueAfter != 0 || res.Requeue { + t.Errorf("expected the Backup released on completion, got %+v", res) + } + if got := len(rec.Events) > 0; got != tc.wantEvent { + t.Fatalf("warning event recorded = %v, want %v", got, tc.wantEvent) + } + if tc.wantEvent { + if ev := <-rec.Events; !strings.Contains(ev, "ArtifactNotDeleted") || !strings.Contains(ev, "may remain") || !strings.Contains(ev, "bucket-a") { + t.Errorf("event %q must say the archive may remain in bucket-a", ev) + } + } + }) + } +} + +// The cleanup Pod runs the strategy container's image, so it needs the pull +// settings the strategy's own Pod has; without them a private image never +// starts and the Backup stays terminating. +func TestCleanupAltinityBackup_CarriesTheStrategyPullSettings(t *testing.T) { + backup := altinityCleanupBackup("ch-bk") + objs := altinityCleanupFixtures(backup) + for _, o := range objs { + if s, ok := o.(*strategyv1alpha1.Altinity); ok { + s.Spec.Template.Spec.ImagePullSecrets = []corev1.LocalObjectReference{{Name: "registry-creds"}} + s.Spec.Template.Spec.Containers[0].ImagePullPolicy = corev1.PullAlways + } + } + c, s := newAltinityCleanupClient(objs...) + r := &BackupReconciler{Client: c, Scheme: s, Recorder: record.NewFakeRecorder(10)} + if _, err := r.cleanupOnDelete(context.Background(), backup); err != nil { + t.Fatalf("cleanupOnDelete: %v", err) + } + jobs := listJobs(t, c) + if len(jobs) != 1 { + t.Fatalf("expected one cleanup Job, got %d", len(jobs)) + } + pod := jobs[0].Spec.Template.Spec + if !reflect.DeepEqual(pod.ImagePullSecrets, []corev1.LocalObjectReference{{Name: "registry-creds"}}) { + t.Errorf("imagePullSecrets = %+v, want the strategy's", pod.ImagePullSecrets) + } + if got := pod.Containers[0].ImagePullPolicy; got != corev1.PullAlways { + t.Errorf("imagePullPolicy = %q, want the strategy container's", got) + } +} + +// The settings the cleanup Pod takes from the strategy are rendered as for the +// strategy's own Pods, so a value written as a template reaches it resolved. +func TestCleanupAltinityBackup_RendersTheStrategySettings(t *testing.T) { + backup := altinityCleanupBackup("ch-bk") + objs := altinityCleanupFixtures(backup) + for _, o := range objs { + if s, ok := o.(*strategyv1alpha1.Altinity); ok { + s.Spec.Template.Spec.NodeSelector = map[string]string{"backup.example.com/app": "{{ .Release.Name }}"} + s.Spec.Template.Spec.Containers[0].Image = "registry.example.com/client:{{ .Release.Namespace }}" + } + } + c, s := newAltinityCleanupClient(objs...) + r := &BackupReconciler{Client: c, Scheme: s, Recorder: record.NewFakeRecorder(10)} + if _, err := r.cleanupOnDelete(context.Background(), backup); err != nil { + t.Fatalf("cleanupOnDelete: %v", err) + } + jobs := listJobs(t, c) + if len(jobs) != 1 { + t.Fatalf("expected one cleanup Job, got %d", len(jobs)) + } + pod := jobs[0].Spec.Template.Spec + if got := pod.NodeSelector["backup.example.com/app"]; got != "ch-test" { + t.Errorf("nodeSelector value = %q, want the rendered %q", got, "ch-test") + } + if got := pod.Containers[0].Image; got != "registry.example.com/client:tenant-test" { + t.Errorf("image = %q, want the rendered one", got) + } +} + +// The cleanup Pod lands where the strategy's own Pods are allowed to run: a +// cluster that keeps backup Pods off tainted nodes, or on nodes that reach the +// sidecar, would otherwise leave it Pending until its deadline, again and +// again. The strategy's service account is not carried, since the cleanup Pod +// only calls the sidecar's HTTP API. +func TestCleanupAltinityBackup_CarriesTheStrategySchedulingSettings(t *testing.T) { + backup := altinityCleanupBackup("ch-bk") + objs := altinityCleanupFixtures(backup) + nodeSelector := map[string]string{"node-role.example.com/backup": "true"} + tolerations := []corev1.Toleration{{Key: "dedicated", Operator: corev1.TolerationOpEqual, Value: "backup", Effect: corev1.TaintEffectNoSchedule}} + affinity := &corev1.Affinity{NodeAffinity: &corev1.NodeAffinity{ + RequiredDuringSchedulingIgnoredDuringExecution: &corev1.NodeSelector{NodeSelectorTerms: []corev1.NodeSelectorTerm{{ + MatchExpressions: []corev1.NodeSelectorRequirement{{Key: "zone", Operator: corev1.NodeSelectorOpIn, Values: []string{"a"}}}, + }}}, + }} + for _, o := range objs { + if s, ok := o.(*strategyv1alpha1.Altinity); ok { + s.Spec.Template.Spec.NodeSelector = nodeSelector + s.Spec.Template.Spec.Tolerations = tolerations + s.Spec.Template.Spec.Affinity = affinity + s.Spec.Template.Spec.PriorityClassName = "backup-priority" + s.Spec.Template.Spec.ServiceAccountName = "backup-runner" + } + } + c, s := newAltinityCleanupClient(objs...) + r := &BackupReconciler{Client: c, Scheme: s, Recorder: record.NewFakeRecorder(10)} + if _, err := r.cleanupOnDelete(context.Background(), backup); err != nil { + t.Fatalf("cleanupOnDelete: %v", err) + } + jobs := listJobs(t, c) + if len(jobs) != 1 { + t.Fatalf("expected one cleanup Job, got %d", len(jobs)) + } + pod := jobs[0].Spec.Template.Spec + if !reflect.DeepEqual(pod.NodeSelector, nodeSelector) { + t.Errorf("nodeSelector = %+v, want the strategy's", pod.NodeSelector) + } + if !reflect.DeepEqual(pod.Tolerations, tolerations) { + t.Errorf("tolerations = %+v, want the strategy's", pod.Tolerations) + } + if !reflect.DeepEqual(pod.Affinity, affinity) { + t.Errorf("affinity = %+v, want the strategy's", pod.Affinity) + } + if pod.PriorityClassName != "backup-priority" { + t.Errorf("priorityClassName = %q, want the strategy's", pod.PriorityClassName) + } + if pod.ServiceAccountName != "" { + t.Errorf("serviceAccountName = %q, want none", pod.ServiceAccountName) + } +} + +func TestCleanupAltinityBackup_RetriesWhenJobQuotaBecomesAvailable(t *testing.T) { + ctx := context.Background() + backup := altinityCleanupBackup("ch-bk") + quotaFull := true + quotaErr := apierrors.NewForbidden(batchv1.Resource("jobs"), "ch-bk-cleanup", errors.New("exceeded quota: tenant, requested: count/jobs.batch=1, used: count/jobs.batch=2, limited: count/jobs.batch=2")) + c, scheme := newAltinityCleanupClientWith(interceptor.Funcs{ + Create: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.CreateOption) error { + if _, job := obj.(*batchv1.Job); job && quotaFull { + return quotaErr + } + return c.Create(ctx, obj, opts...) + }, + }, altinityCleanupFixtures(backup)...) + r := &BackupReconciler{Client: c, Scheme: scheme, Recorder: record.NewFakeRecorder(10)} + if _, err := r.cleanupOnDelete(ctx, backup); !errors.Is(err, quotaErr) { + t.Fatalf("full Job quota: got %v, want retryable quota error", err) + } + quotaFull = false + if _, err := r.cleanupOnDelete(ctx, backup); err != nil { + t.Fatal(err) + } + job := &batchv1.Job{} + if err := c.Get(ctx, client.ObjectKey{Namespace: backup.Namespace, Name: "ch-bk-cleanup"}, job); err != nil { + t.Fatalf("cleanup Job after the quota freed up: %v", err) + } +} + +// A cleanup Job the API server will never accept, such as one whose name +// -cleanup is too long for a Job, would otherwise be retried for good +// with the Backup stuck terminating. +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")), + } { + 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 refuse + } + return c.Create(ctx, obj, opts...) + }, + }, altinityCleanupFixtures(backup)...) + 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.Requeue { + t.Errorf("expected the Backup released, got %+v", res) + } + if len(rec.Events) == 0 { + t.Fatal("a refused cleanup Job must surface as a Warning Event") + } + if ev := <-rec.Events; !strings.Contains(ev, "ArtifactNotDeleted") || !strings.Contains(ev, "clickhouse-ch-test-ch-bk") { + t.Errorf("event %q must name the archive left behind", ev) + } + }) + } +} + +// Any other Create error is transient and goes back to the work queue with the +// Backup held. +func TestCleanupAltinityBackup_RetriesATransientCreateError(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 { + return apierrors.NewServiceUnavailable("etcd leader change") + }, + }, altinityCleanupFixtures(backup)...) + rec := record.NewFakeRecorder(10) + r := &BackupReconciler{Client: c, Scheme: s, Recorder: rec} + if _, err := r.cleanupOnDelete(context.Background(), backup); err == nil { + t.Error("expected the error returned so the Backup is retried") + } + if len(rec.Events) != 0 { + t.Errorf("a transient error must not release the Backup, got event %q", <-rec.Events) + } +} + +// A cleanup Job already being deleted has no outcome to read yet. +func TestCleanupAltinityBackup_WaitsForADeletingJob(t *testing.T) { + backup := altinityCleanupBackup("ch-bk") + deleting := ownCleanupJob(backup) + deleting.Finalizers = []string{"batch.kubernetes.io/job-tracking"} + deleting.Status.Conditions = []batchv1.JobCondition{{Type: batchv1.JobComplete, Status: corev1.ConditionTrue}} + c, s := newAltinityCleanupClient(append(altinityCleanupFixtures(backup), deleting)...) + if err := c.Delete(context.Background(), deleting); err != nil { + t.Fatalf("delete job: %v", err) + } + 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.Error("expected a requeue while the Job is being deleted, not a release on its stale completion") + } +} diff --git a/internal/backupcontroller/altinitystrategy_controller.go b/internal/backupcontroller/altinitystrategy_controller.go index e7e64eaea..8eade82c7 100644 --- a/internal/backupcontroller/altinitystrategy_controller.go +++ b/internal/backupcontroller/altinitystrategy_controller.go @@ -7,6 +7,7 @@ import ( "fmt" "maps" "regexp" + "strconv" "strings" "time" @@ -14,6 +15,7 @@ import ( corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" apimeta "k8s.io/apimachinery/pkg/api/meta" + "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime/schema" @@ -58,6 +60,27 @@ const ( // the sidecar uploads to the bucket it was last restarted with. altinityUseSystemBucketKey = "altinity.strategy.backups.cozystack.io/use-system-bucket" + // altinityBucketKey records, on the backup Job and then on the Backup, + // the system bucket the projected credentials named when the backup Job + // was created: the bucket the sidecar of a system-bucket application + // reads, so the one its archive went to unless the sidecar had not been + // restarted onto it yet. + altinityBucketKey = "altinity.strategy.backups.cozystack.io/bucket" + + altinityModeCleanup = "cleanup" + altinitySkipArtifactCleanupAnnotation = "backups.cozystack.io/skip-artifact-cleanup" + + // 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. + altinityCleanupFailuresAnnotation = "altinity.strategy.backups.cozystack.io/cleanup-failures" + altinityCleanupRetryAfterAnnotation = "altinity.strategy.backups.cozystack.io/cleanup-retry-after" + + // altinityCleanupRetryBase is the wait after the first failed cleanup + // Job; it doubles with each further failure up to altinityCleanupRetryMax. + altinityCleanupRetryBase = 30 * time.Second + altinityCleanupRetryMax = 30 * time.Minute + // altinityArchiveTimeLayout is the UTC timestamp that ends an archive // name. It is fixed-width, so names sharing a prefix sort chronologically // as plain strings, which is what a restore of a Backup that records no @@ -386,6 +409,16 @@ func (r *BackupJobReconciler) reconcileAltinity(ctx context.Context, j *backupsv if err != nil { return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to read spec.backup.useSystemBucket: %v", err)) } + jobAnnotations := map[string]string{altinityUseSystemBucketKey: fmt.Sprint(useSystemBucket)} + if useSystemBucket { + bucket, berr := altinitySystemBucket(ctx, r.Client, r.CredentialsConfig, j.Namespace) + if berr != nil { + return ctrl.Result{}, berr + } + if bucket != "" { + jobAnnotations[altinityBucketKey] = bucket + } + } batchJob, err := r.ensureAltinityJob(ctx, j, j.Namespace, jobNameForBackupJob(j), altinityModeBackup, @@ -393,7 +426,7 @@ func (r *BackupJobReconciler) reconcileAltinity(ctx context.Context, j *backupsv backupsv1alpha1.OwningJobNameLabel: j.Name, backupsv1alpha1.OwningJobNamespaceLabel: j.Namespace, }, - map[string]string{altinityUseSystemBucketKey: fmt.Sprint(useSystemBucket)}, + jobAnnotations, rendered, ) if err != nil { @@ -419,7 +452,7 @@ func (r *BackupJobReconciler) reconcileAltinity(ctx context.Context, j *backupsv if !ok { flow = fmt.Sprint(useSystemBucket) } - artifact, err := r.createAltinityBackupArtifact(ctx, j, resolved, archive, flow) + artifact, err := r.createAltinityBackupArtifact(ctx, j, resolved, archive, flow, batchJob.Annotations[altinityBucketKey]) if err != nil { return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to create Backup artifact: %v", err)) } @@ -588,14 +621,21 @@ func jobConditionState(j *batchv1.Job) batchv1.JobConditionType { // Used to surface the underlying clickhouse-backup error on the BackupJob // status without re-templating it. func jobFailureMessage(j *batchv1.Job) string { - for _, c := range j.Status.Conditions { - if c.Type == batchv1.JobFailed && c.Status == corev1.ConditionTrue { - return c.Message - } + if c := jobFailedCondition(j); c != nil { + return c.Message } return "" } +func jobFailedCondition(j *batchv1.Job) *batchv1.JobCondition { + for i := range j.Status.Conditions { + if c := &j.Status.Conditions[i]; c.Type == batchv1.JobFailed && c.Status == corev1.ConditionTrue { + return c + } + } + return nil +} + // createAltinityBackupArtifact materialises a Cozystack Backup carrying the // strategy reference, the archive the Job wrote (when known) and the // BackupClassStrategy parameters in effect at backup time. Parameters @@ -605,12 +645,15 @@ func (r *BackupJobReconciler) createAltinityBackupArtifact( ctx context.Context, j *backupsv1alpha1.BackupJob, resolved *ResolvedBackupConfig, - archive, useSystemBucket string, + archive, useSystemBucket, bucket string, ) (*backupsv1alpha1.Backup, error) { driverMD := map[string]string{altinityUseSystemBucketKey: useSystemBucket} if archive != "" { driverMD[altinityArchiveMetaKey] = archive } + if bucket != "" { + driverMD[altinityBucketKey] = bucket + } for k, v := range resolved.Parameters { driverMD[altinityParamPrefix+k] = v } @@ -619,6 +662,10 @@ func (r *BackupJobReconciler) createAltinityBackupArtifact( ObjectMeta: metav1.ObjectMeta{ Name: j.Name, Namespace: j.Namespace, + // The archive is deleted from the finalizer; without it at creation, + // a Backup deleted before the Backup reconciler first sees it goes + // at once and leaves its archive in the bucket. + Finalizers: []string{backupFinalizer}, }, Spec: backupsv1alpha1.BackupSpec{ ApplicationRef: j.Spec.ApplicationRef, @@ -633,14 +680,8 @@ func (r *BackupJobReconciler) createAltinityBackupArtifact( if j.Spec.PlanRef != nil { backup.Spec.PlanRef = j.Spec.PlanRef } - // Status fields set on the struct above are dropped server-side because - // Backup has the status subresource, but populating them here keeps the - // struct in step with what an out-of-band reconciler will fill in (the - // owning BackupReconciler watches Backup and is the natural place to - // promote phase=Ready). Mirrors the CNPG/Velero pattern - issuing a - // follow-up Status().Patch from this driver races with that reconciler - // adding the cleanup finalizer and surfaces as a "not found" 404 even - // though the Backup is on disk in Ready state. + // Status fields set on the struct above are dropped server-side, because + // Backup has the status subresource. if err := r.Create(ctx, backup); err != nil { if !apierrors.IsAlreadyExists(err) { return nil, err @@ -877,3 +918,473 @@ func (r *RestoreJobReconciler) reconcileAltinityRestore(ctx context.Context, res return ctrl.Result{RequeueAfter: altinityPollInterval}, nil } } + +// altinityArchiveNamePattern keeps the recorded archive name a single URL +// path segment; the name is interpolated into the sidecar's delete route. +var altinityArchiveNamePattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`) + +// altinityArchiveNamedBeforeUIDs matches a name ending in its start time, as a +// controller that did not append the BackupJob's UID gave it. Two runs of one +// application started in the same second got that name, and a run still in +// flight across the upgrade may yet record it, so no Backup can tell that the +// archive is its alone. +var altinityArchiveNamedBeforeUIDs = regexp.MustCompile(`-[0-9]{8}T[0-9]{6}Z$`) + +// altinityCleanupScript deletes one remote archive through the +// clickhouse-backup sidecar (POST /backup/delete/{where}/{name} in 2.7.x). +// The sidecar answers 423 while any other operation runs, a backup of the +// same application included, and cannot be reached at all while its Pod +// restarts, so the delete is retried until it is answered and accepted within +// a budget kept shorter than the Job's activeDeadlineSeconds. It +// answers 500 with "is not found on remote storage" for an archive that is +// already gone, which is the outcome cleanup wants; every other non-200 +// answer (a ClickHouse or S3 error) fails the Pod so the controller retries. +const altinityCleanupScript = `set -eu +deadline=$(( $(date +%s) + 540 )) +while :; do + left=$(( deadline - $(date +%s) )) + if [ "${left}" -le 0 ]; then + echo "delete ${ARCHIVE_NAME} not run: the sidecar stayed busy with another operation or unreachable" >&2 + exit 1 + fi + if resp=$(curl -sS --max-time "${left}" -u "${API_USERNAME}:${API_PASSWORD}" -w '\n%{http_code}' -X POST "http://${API_HOST}:7171/backup/delete/remote/${ARCHIVE_NAME}"); then + code=$(printf '%s' "${resp}" | tail -n 1) + [ "${code}" = "423" ] || break + fi + sleep 5 +done +body=$(printf '%s' "${resp}" | sed '$d') +if [ "${code}" = "200" ]; then + echo "deleted ${ARCHIVE_NAME}" + exit 0 +fi +case "${body}" in + *"is not found on remote storage"*) + echo "${ARCHIVE_NAME} is already absent" + exit 0 + ;; +esac +echo "delete ${ARCHIVE_NAME} failed: HTTP ${code}: ${body}" >&2 +exit 1 +` + +// cleanupAltinityBackup deletes the remote archive of a system-bucket Backup +// and holds the Backup until the delete finished. Nothing else prunes that +// bucket, so a Backup removed without this leaks its archive for good. An +// application on its own bucket keeps the archive's lifecycle, the same split +// as the MongoDB driver. The delete runs through the application's sidecar, +// so it needs the application; when the application or the namespace is +// gone, the Backup is released with a Warning Event naming the archive left. +// +// The cleanup Pod is built here, not rendered from the strategy template: the +// shipped and the example templates run restore_remote for every mode other +// than backup, so a template rendered in a delete mode would overwrite live +// data. Only the strategy container's image, how to pull it, and where the +// strategy's Pods may be scheduled are taken from the template, rendered as +// for the strategy's own Pods. +func (r *BackupReconciler) cleanupAltinityBackup(ctx context.Context, backup *backupsv1alpha1.Backup) (ctrl.Result, error) { + logger := getLogger(ctx) + jobKey := types.NamespacedName{Namespace: backup.Namespace, Name: backup.Name + "-cleanup"} + + if backup.Annotations[altinitySkipArtifactCleanupAnnotation] == "true" { + existing := &batchv1.Job{} + err := r.Get(ctx, jobKey, existing) + switch { + case err == nil: + if !isAltinityCleanupJob(existing) { + break + } + if derr := r.deleteAltinityCleanupJob(ctx, existing); derr != nil { + return ctrl.Result{}, derr + } + case !apierrors.IsNotFound(err): + return ctrl.Result{}, err + } + logger.Debug("skipping Altinity archive cleanup per annotation", "backup", backup.Name) + return ctrl.Result{}, nil + } + + archive := backup.Spec.DriverMetadata[altinityArchiveMetaKey] + if archive == "" || backup.Spec.DriverMetadata[altinityUseSystemBucketKey] != "true" { + return ctrl.Result{}, nil + } + if !altinityArchiveNamePattern.MatchString(archive) { + return r.releaseAltinityCleanup(ctx, backup, archive, "the recorded archive name is not a valid archive name"), nil + } + + job := &batchv1.Job{} + err := r.Get(ctx, jobKey, job) + switch { + case apierrors.IsNotFound(err): + terminating, nsErr := r.namespaceTerminating(ctx, backup.Namespace) + if nsErr != nil { + return ctrl.Result{}, nsErr + } + if terminating { + return r.releaseAltinityCleanup(ctx, backup, archive, "namespace is terminating"), nil + } + strategy := &strategyv1alpha1.Altinity{} + if err := r.Get(ctx, client.ObjectKey{Name: backup.Spec.StrategyRef.Name}, strategy); err != nil { + if apierrors.IsNotFound(err) { + return r.releaseAltinityCleanup(ctx, backup, archive, "strategy CR is gone"), nil + } + return ctrl.Result{}, err + } + containers := strategy.Spec.Template.Spec.Containers + if len(containers) == 0 || containers[0].Image == "" { + return r.releaseAltinityCleanup(ctx, backup, archive, "strategy template has no container image"), nil + } + if altinityArchiveNamedBeforeUIDs.MatchString(archive) { + return r.releaseAltinityCleanup(ctx, backup, archive, + "the archive is named without its BackupJob's UID, so another run started in the same second may have written or still be writing it"), nil + } + // The delete goes through the application's current sidecar. One that + // has since moved to its own bucket reports the archive as not found + // there, which the script would take for a completed delete. + app, onSystemBucket, found, aerr := r.altinityAppOnSystemBucket(ctx, backup) + if aerr != nil { + return ctrl.Result{}, aerr + } + if !found { + return r.releaseAltinityCleanup(ctx, backup, archive, "the ClickHouse application is gone"), nil + } + if !onSystemBucket { + return r.releaseAltinityCleanup(ctx, backup, archive, "the ClickHouse application no longer uses the system bucket"), nil + } + if recorded, current, changed, berr := r.altinityBucketChange(ctx, backup); berr != nil { + return ctrl.Result{}, berr + } else if changed { + return r.releaseAltinityCleanup(ctx, backup, archive, + fmt.Sprintf("the archive was written to bucket %s, but the system bucket is now %s", recorded, altinityBucketName(current))), nil + } + release := backup.Spec.ApplicationRef.Name + authSecret := "clickhouse-" + release + "-backup-api-auth" + if serr := r.Get(ctx, types.NamespacedName{Namespace: backup.Namespace, Name: authSecret}, &corev1.Secret{}); serr != nil { + if apierrors.IsNotFound(serr) { + return r.releaseAltinityCleanup(ctx, backup, archive, + fmt.Sprintf("Secret %s is gone, so the application's backup sidecar cannot be called", authSecret)), nil + } + return ctrl.Result{}, serr + } + if wait := altinityCleanupRetryWait(ctx, backup, time.Now()); wait > 0 { + return ctrl.Result{RequeueAfter: wait}, nil + } + // A sidecar that has not taken up the projected credentials yet still + // serves the bucket before them and answers "not found" there. + wait, werr := credentialsPropagationWait(ctx, r.Client, r.CredentialsConfig.TargetSecretName, backup.Namespace, jobKey.Name) + if werr != nil { + return ctrl.Result{}, werr + } + if wait > 0 { + logger.Debug("holding the Altinity archive delete until the projected credentials reach the sidecar", "backup", backup.Name, "wait", wait) + return ctrl.Result{RequeueAfter: wait}, nil + } + // Rendered as for the strategy's own Pods, so the settings taken from + // it reach the cleanup Pod resolved. + rendered, rerr := renderAltinityTemplate(strategy.Spec.Template, app.Object, release, backup.Namespace, + altinityModeCleanup, archive, backupParameters(backup), backup) + if rerr != nil { + return r.releaseAltinityCleanup(ctx, backup, archive, fmt.Sprintf("cannot render the strategy template: %v", rerr)), nil + } + desired := buildAltinityCleanupJob(jobKey.Namespace, jobKey.Name, rendered.Spec.Containers[0], + 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: ") { + return ctrl.Result{}, cerr + } + if apierrors.IsForbidden(cerr) || apierrors.IsInvalid(cerr) { + return r.releaseAltinityCleanup(ctx, backup, archive, fmt.Sprintf("cannot create cleanup Job: %v", cerr)), nil + } + return ctrl.Result{}, cerr + } + return ctrl.Result{RequeueAfter: altinityPollInterval}, nil + case err != nil: + return ctrl.Result{}, err + } + + if !isAltinityCleanupJob(job) { + return r.releaseAltinityCleanup(ctx, backup, archive, + fmt.Sprintf("Job %s, which this controller did not create, holds the cleanup Job name", job.Name)), nil + } + if !job.DeletionTimestamp.IsZero() { + return ctrl.Result{RequeueAfter: altinityPollInterval}, nil + } + if altinityCleanupJobArchive(job) != archive { + // Left by an earlier Backup of the same name that was released while + // its Job ran; its outcome is about another archive. + if derr := r.deleteAltinityCleanupJob(ctx, job); derr != nil { + return ctrl.Result{}, derr + } + return ctrl.Result{RequeueAfter: altinityPollInterval}, nil + } + switch jobConditionState(job) { + case batchv1.JobComplete: + _, onSystemBucket, found, aerr := r.altinityAppOnSystemBucket(ctx, backup) + if aerr != nil { + return ctrl.Result{}, aerr + } + recorded, current, bucketChanged, berr := r.altinityBucketChange(ctx, backup) + if berr != nil { + return ctrl.Result{}, berr + } + if derr := r.deleteAltinityCleanupJob(ctx, job); derr != nil { + return ctrl.Result{}, derr + } + if found && !onSystemBucket { + return r.releaseAltinityCleanup(ctx, backup, archive, + "the ClickHouse application moved to its own bucket while the delete ran, so the archive may remain"), nil + } + if bucketChanged { + return r.releaseAltinityCleanup(ctx, backup, archive, + fmt.Sprintf("the system bucket changed from %s to %s while the delete ran, so the archive may remain", recorded, altinityBucketName(current))), nil + } + logger.Debug("Altinity archive deleted", "backup", backup.Name, "archive", archive) + return ctrl.Result{}, nil + case batchv1.JobFailed: + 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) + // The Job and its Pod log go with the delete below, so the Event + // keeps the only account of why the attempt failed. + if c := jobFailedCondition(job); r.Recorder != nil && c != nil { + r.Recorder.Eventf(backup, corev1.EventTypeWarning, "ArtifactCleanupFailed", + "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 + // starting the next Job at once. + base := backup.DeepCopy() + if backup.Annotations == nil { + backup.Annotations = map[string]string{} + } + backup.Annotations[altinityCleanupFailuresAnnotation] = strconv.Itoa(failures) + backup.Annotations[altinityCleanupRetryAfterAnnotation] = time.Now().Add(delay).UTC().Format(time.RFC3339) + if perr := r.Patch(ctx, backup, client.MergeFrom(base)); perr != nil { + return ctrl.Result{}, perr + } + if derr := r.deleteAltinityCleanupJob(ctx, job); derr != nil { + return ctrl.Result{}, derr + } + return ctrl.Result{RequeueAfter: delay}, nil + default: + return ctrl.Result{RequeueAfter: altinityPollInterval}, nil + } +} + +// altinityAppOnSystemBucket reads the flag live rather than from the Backup: +// the delete goes through the sidecar the application runs now, and that +// sidecar answers for the bucket it was started on. The application is +// returned too, for rendering the strategy template against it. +func (r *BackupReconciler) altinityAppOnSystemBucket(ctx context.Context, backup *backupsv1alpha1.Backup) (app *unstructured.Unstructured, onSystemBucket, found bool, err error) { + group := backupsv1alpha1.DefaultApplicationAPIGroup + if ref := backup.Spec.ApplicationRef; ref.APIGroup != nil && *ref.APIGroup != "" { + group = *ref.APIGroup + } + mapping, err := r.RESTMapper().RESTMapping(schema.GroupKind{Group: group, Kind: backup.Spec.ApplicationRef.Kind}) + if err != nil { + if apimeta.IsNoMatchError(err) { + return nil, false, false, nil + } + return nil, false, false, err + } + app = &unstructured.Unstructured{} + app.SetGroupVersionKind(mapping.GroupVersionKind) + if err := r.Get(ctx, types.NamespacedName{Namespace: backup.Namespace, Name: backup.Spec.ApplicationRef.Name}, app); err != nil { + if apierrors.IsNotFound(err) { + return nil, false, false, nil + } + return nil, false, false, err + } + v, _, err := unstructured.NestedBool(app.Object, "spec", "backup", "useSystemBucket") + if err != nil { + return app, false, true, fmt.Errorf("read spec.backup.useSystemBucket: %w", err) + } + return app, v, true, nil +} + +// 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. +func altinitySystemBucket(ctx context.Context, c client.Client, cfg BackupCredentialsConfig, namespace string) (string, error) { + if !cfg.IsEnabled() { + return "", nil + } + secret := &corev1.Secret{} + if err := c.Get(ctx, types.NamespacedName{Namespace: namespace, Name: cfg.TargetSecretName}, secret); err != nil { + if apierrors.IsNotFound(err) { + return "", nil + } + return "", err + } + return string(secret.Data["bucketName"]), nil +} + +// altinityBucketChange compares the bucket a Backup records with the one the +// projected credentials name now. A Backup that records none, taken before +// buckets were recorded, reports no change. +func (r *BackupReconciler) altinityBucketChange(ctx context.Context, backup *backupsv1alpha1.Backup) (recorded, current string, changed bool, err error) { + recorded = backup.Spec.DriverMetadata[altinityBucketKey] + if recorded == "" { + return "", "", false, nil + } + current, err = altinitySystemBucket(ctx, r.Client, r.CredentialsConfig, backup.Namespace) + if err != nil { + return "", "", false, err + } + return recorded, current, current != recorded, nil +} + +func altinityBucketName(bucket string) string { + if bucket == "" { + return "unknown, as the projected credentials name none" + } + return bucket +} + +// altinityCleanupFailures reads how many cleanup Jobs of the Backup have +// failed. An unreadable count is logged and read as none, so the wait starts +// over rather than the cleanup stopping. +func altinityCleanupFailures(ctx context.Context, backup *backupsv1alpha1.Backup) int { + v, ok := backup.Annotations[altinityCleanupFailuresAnnotation] + if !ok { + return 0 + } + n, err := strconv.Atoi(v) + if err != nil || n < 0 { + getLogger(ctx).Info("ignoring an unreadable cleanup failure count", "backup", backup.Name, "value", v) + return 0 + } + return n +} + +// altinityCleanupRetryDelay is the wait after the given number of failed +// cleanup Jobs: altinityCleanupRetryBase, doubled with each further failure, +// at most altinityCleanupRetryMax. +func altinityCleanupRetryDelay(failures int) time.Duration { + d := altinityCleanupRetryBase + for i := 1; i < failures && d < altinityCleanupRetryMax; i++ { + d *= 2 + } + return min(d, altinityCleanupRetryMax) +} + +// altinityCleanupRetryWait is how long the next cleanup Job still has to wait +// after the last failure. An unreadable time is logged and waits for nothing, +// so the cleanup goes on. +func altinityCleanupRetryWait(ctx context.Context, backup *backupsv1alpha1.Backup, now time.Time) time.Duration { + v, ok := backup.Annotations[altinityCleanupRetryAfterAnnotation] + if !ok { + return 0 + } + at, err := time.Parse(time.RFC3339, v) + if err != nil { + getLogger(ctx).Info("ignoring an unreadable cleanup retry time", "backup", backup.Name, "value", v) + return 0 + } + if at.After(now.Add(altinityCleanupRetryMax)) { + getLogger(ctx).Info("ignoring a cleanup retry time further ahead than any failure sets", "backup", backup.Name, "value", v) + return 0 + } + return at.Sub(now) +} + +// isAltinityCleanupJob tells a cleanup Job this controller created from +// another Job of the same name, such as the ClickHouse chart's own +// -cleanup hook. +func isAltinityCleanupJob(job *batchv1.Job) bool { + return job.Labels[altinityLabelMode] == altinityModeCleanup +} + +func altinityCleanupJobArchive(job *batchv1.Job) string { + for _, c := range job.Spec.Template.Spec.Containers { + for _, e := range c.Env { + if e.Name == "ARCHIVE_NAME" { + return e.Value + } + } + } + return "" +} + +func (r *BackupReconciler) deleteAltinityCleanupJob(ctx context.Context, job *batchv1.Job) error { + policy := metav1.DeletePropagationBackground + return client.IgnoreNotFound(r.Delete(ctx, job, &client.DeleteOptions{PropagationPolicy: &policy})) +} + +// releaseAltinityCleanup gives up deleting the archive and lets the Backup be +// removed, with a Warning Event naming the archive left in the bucket. +func (r *BackupReconciler) releaseAltinityCleanup(ctx context.Context, backup *backupsv1alpha1.Backup, archive, reason string) ctrl.Result { + getLogger(ctx).Info("releasing Backup without deleting its archive", "backup", backup.Name, "archive", archive, "reason", reason) + if r.Recorder != nil { + r.Recorder.Eventf(backup, corev1.EventTypeWarning, "ArtifactNotDeleted", "left archive %s in the bucket: %s", archive, reason) + } + return ctrl.Result{} +} + +// buildAltinityCleanupJob is ownerless because cleanupAltinityBackup manages +// its lifecycle and it must outlive the Backup being deleted; +// activeDeadlineSeconds and the TTL are backstops if the controller stops +// mid-wait. It runs the strategy container's image with that image's pull +// settings, since only those are known to fetch it, and is placed as the +// strategy's own Pods are. The strategy's service account is left out: the +// cleanup Pod only calls the sidecar's HTTP API. +func buildAltinityCleanupJob(namespace, name string, strategyContainer corev1.Container, strategyPod corev1.PodSpec, apiHost, authSecret, archive string) *batchv1.Job { + labels := map[string]string{altinityLabelMode: altinityModeCleanup} + backoffLimit := int32(1) + activeDeadline := int64(600) + ttl := int32(300) + authEnv := func(envName, key string) corev1.EnvVar { + return corev1.EnvVar{Name: envName, ValueFrom: &corev1.EnvVarSource{SecretKeyRef: &corev1.SecretKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{Name: authSecret}, + Key: key, + }}} + } + return &batchv1.Job{ + ObjectMeta: metav1.ObjectMeta{Namespace: namespace, Name: name, Labels: labels}, + Spec: batchv1.JobSpec{ + BackoffLimit: &backoffLimit, + ActiveDeadlineSeconds: &activeDeadline, + TTLSecondsAfterFinished: &ttl, + Template: corev1.PodTemplateSpec{ + ObjectMeta: metav1.ObjectMeta{Labels: labels}, + Spec: corev1.PodSpec{ + RestartPolicy: corev1.RestartPolicyNever, + ImagePullSecrets: strategyPod.ImagePullSecrets, + NodeSelector: strategyPod.NodeSelector, + Tolerations: strategyPod.Tolerations, + Affinity: strategyPod.Affinity, + PriorityClassName: strategyPod.PriorityClassName, + Containers: []corev1.Container{{ + Name: "ch-backup-cleanup", + Image: strategyContainer.Image, + ImagePullPolicy: strategyContainer.ImagePullPolicy, + Command: []string{"/bin/sh", "-c", altinityCleanupScript}, + Env: []corev1.EnvVar{ + {Name: "API_HOST", Value: apiHost}, + {Name: "ARCHIVE_NAME", Value: archive}, + authEnv("API_USERNAME", "username"), + authEnv("API_PASSWORD", "password"), + }, + Resources: corev1.ResourceRequirements{ + Requests: corev1.ResourceList{ + corev1.ResourceCPU: resource.MustParse("10m"), + corev1.ResourceMemory: resource.MustParse("32Mi"), + }, + Limits: corev1.ResourceList{ + corev1.ResourceCPU: resource.MustParse("200m"), + corev1.ResourceMemory: resource.MustParse("128Mi"), + }, + }, + SecurityContext: &corev1.SecurityContext{ + AllowPrivilegeEscalation: new(false), + Capabilities: &corev1.Capabilities{Drop: []corev1.Capability{"ALL"}}, + SeccompProfile: &corev1.SeccompProfile{Type: corev1.SeccompProfileTypeRuntimeDefault}, + }, + }}, + }, + }, + }, + } +} diff --git a/internal/backupcontroller/altinitystrategy_controller_test.go b/internal/backupcontroller/altinitystrategy_controller_test.go index a9022ceb6..7975633c1 100644 --- a/internal/backupcontroller/altinitystrategy_controller_test.go +++ b/internal/backupcontroller/altinitystrategy_controller_test.go @@ -791,6 +791,9 @@ func TestAltinityArchiveName_DistinctForRunsStartedInTheSameSecond(t *testing.T) if !strings.HasPrefix(name, "ch-test-20260304050607-") { t.Errorf("archive %q does not start with the application and start time, so names stop sorting chronologically", name) } + if !altinityArchiveNamePattern.MatchString(name) { + t.Errorf("archive %q is not a name the cleanup path accepts", name) + } } } diff --git a/internal/backupcontroller/backup_controller.go b/internal/backupcontroller/backup_controller.go index b5fad8c54..23cf932e1 100644 --- a/internal/backupcontroller/backup_controller.go +++ b/internal/backupcontroller/backup_controller.go @@ -40,8 +40,9 @@ type BackupReconciler struct { Scheme *runtime.Scheme Recorder record.EventRecorder // CredentialsConfig locates the platform backup credentials: the Job-based - // cleanups project them into the Backup's namespace, and the MariaDB - // cleanup reads them to reach the platform bucket. + // cleanups project them into the Backup's namespace, the MariaDB cleanup + // reads them to reach the platform bucket, and the Altinity cleanup reads + // from them the system bucket and when it last changed. CredentialsConfig BackupCredentialsConfig // APIReader is the manager's uncached reader. The MariaDB cleanup lists // the RestoreJobs and operator Restores of a Backup, and the operator @@ -127,17 +128,10 @@ func (r *BackupReconciler) cleanupOnDelete(ctx context.Context, backup *backupsv // artifacts that survive Backup deletion. return ctrl.Result{}, nil case strategyv1alpha1.AltinityStrategyKind: - // Cozystack Backup deletion does NOT purge the upstream - // clickhouse-backup archive in object storage. Lifecycle of the - // archive belongs to the clickhouse-backup tool inside the chi-* - // Pod (its retention config) or to manual purge through that - // tool's HTTP API (DELETE /backup//remote). Surfacing this - // as an explicit branch (rather than falling through to the - // Velero default) makes the contract obvious: the Altinity - // driver does not own the S3 data, so it does not delete it on - // CR removal. See packages/apps/clickhouse/README.md "Backup - // orchestration" for tenant-facing guidance. - return ctrl.Result{}, nil + // The Altinity driver owns the archive of a system-bucket Backup, which + // nothing else prunes: delete it through the application's sidecar and + // wait for that before the Backup is removed (see cleanupAltinityBackup). + return r.cleanupAltinityBackup(ctx, backup) case strategyv1alpha1.MariaDBStrategyKind: // mariadb-operator's maxRetention prunes only from inside the next // backup run of the same prefix and a Plan never deletes a Backup, so @@ -153,7 +147,7 @@ func (r *BackupReconciler) cleanupOnDelete(ctx context.Context, backup *backupsv // Split by flow (see cleanupMongoDBBackup). A legacy backup writes to the // tenant's own bucket and its lifecycle stays the tenant's / psmdb // operator's — that branch is a no-op, the same "we do not own the - // archive" contract as Altinity / FDB. A useSystemBucket backup + // archive" contract as FDB. A useSystemBucket backup // lands in the shared cozy-backups bucket with no psmdb task retention to // prune it, so the driver OWNS it: this deletes the operator // PerconaServerMongoDBBackup CR and waits for its delete-backup finalizer @@ -165,8 +159,8 @@ func (r *BackupReconciler) cleanupOnDelete(ctx context.Context, backup *backupsv // continuously streaming backup_agent Deployment; its lifecycle // is governed by the next BackupJob's stopOtherFoundationDBBackups // call, by manual operator action, or by - // examples/backups/foundationdb/cleanup.sh. Same "we do not own - // the archive" contract as Altinity — the explicit + // examples/backups/foundationdb/cleanup.sh. The driver does not own + // the archive, so it does not delete it — the explicit // branch guards the seam against a future driver refactor that // might incidentally stamp velero.io/backup-name onto FDB // driverMetadata via a shared helper. diff --git a/internal/backupcontroller/jobstrategy_controller.go b/internal/backupcontroller/jobstrategy_controller.go index 594a2f2b1..e96eddda9 100644 --- a/internal/backupcontroller/jobstrategy_controller.go +++ b/internal/backupcontroller/jobstrategy_controller.go @@ -328,8 +328,8 @@ func buildJobStrategyBatchJob(namespace, name string, labels map[string]string, // reference and the BackupClassStrategy parameters in effect at backup time. // Parameters round-trip via DriverMetadata under jobStrategyParamPrefix so a // later RestoreJob can re-render the strategy template against the same values. -// Mirrors createAltinityBackupArtifact - see that function for why Status is -// populated on the struct but not promoted from this driver. +// Status set on the struct is dropped server-side, because Backup has the +// status subresource. func (r *BackupJobReconciler) createJobBackupArtifact( ctx context.Context, j *backupsv1alpha1.BackupJob, diff --git a/packages/apps/clickhouse/templates/backup-api-auth-secret.yaml b/packages/apps/clickhouse/templates/backup-api-auth-secret.yaml index 6db737aca..e1f81b808 100644 --- a/packages/apps/clickhouse/templates/backup-api-auth-secret.yaml +++ b/packages/apps/clickhouse/templates/backup-api-auth-secret.yaml @@ -5,8 +5,8 @@ passes the same credentials on its curl invocation. Without this, any Pod with network reach to `chi-...-clickhouse-...:7171` - could trigger restore_remote (overwrite tables from S3) or DELETE - /backup//remote (wipe archives) on the tenant's instance. The + could trigger restore_remote (overwrite tables from S3) or POST + /backup/delete/remote/ (wipe archives) on the tenant's instance. The Pod-IP-only scheme is no auth in a multi-tenant cluster. Persistence: use `lookup` to preserve the existing password across diff --git a/packages/apps/clickhouse/templates/clickhouse.yaml b/packages/apps/clickhouse/templates/clickhouse.yaml index bc439d40b..b9badef4b 100644 --- a/packages/apps/clickhouse/templates/clickhouse.yaml +++ b/packages/apps/clickhouse/templates/clickhouse.yaml @@ -271,7 +271,7 @@ spec: is reachable to any Pod with network access to the ClickHouseInstallation Pod IP and accepts restore_remote (overwrites tables from S3) and - DELETE /backup//remote (wipes archives) calls + POST /backup/delete/remote/ (wipes archives) calls with no credentials. Sidecar reads from the chart-emitted backup-api-auth Secret; strategy Pod reads the same Secret and curls with -u user:pass. From e199ef1d83f6012d596fe022c42a95ed3816f522 Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Mon, 23 Nov 2026 12:14:56 +0300 Subject: [PATCH 3/7] fix(clickhouse): take no backup Job's result that this BackupJob did not run A Job standing under a BackupJob's Job name was taken as its own. A BackupJob re-created under a used name, as a Plan does when the BackupJob of a schedule slot is deleted within the slot's starting deadline, met the completed Job of the earlier one before the garbage collector removed it, was marked Succeeded without uploading anything, and recorded a Backup for an archive nobody uploaded for it. A Job controlled by an earlier BackupJob of the same name is now waited out, with the Ready condition naming it; any other Job holding the name fails the BackupJob, since nothing will remove it. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- .../altinitystrategy_archive_test.go | 2 +- .../altinitystrategy_controller.go | 42 ++++++- .../altinitystrategy_controller_test.go | 108 +++++++++++++++++- 3 files changed, 144 insertions(+), 8 deletions(-) diff --git a/internal/backupcontroller/altinitystrategy_archive_test.go b/internal/backupcontroller/altinitystrategy_archive_test.go index 0f94db8df..7649aff2c 100644 --- a/internal/backupcontroller/altinitystrategy_archive_test.go +++ b/internal/backupcontroller/altinitystrategy_archive_test.go @@ -66,7 +66,7 @@ func runningAltinityBackupJob() *backupsv1alpha1.BackupJob { // BackupJob's archive name. func completedAltinityK8sJob(j *backupsv1alpha1.BackupJob) *batchv1.Job { return &batchv1.Job{ - ObjectMeta: metav1.ObjectMeta{Name: jobNameForBackupJob(j), Namespace: j.Namespace}, + ObjectMeta: metav1.ObjectMeta{Name: jobNameForBackupJob(j), Namespace: j.Namespace, OwnerReferences: altinityControllerRef(j)}, Spec: batchv1.JobSpec{Template: corev1.PodTemplateSpec{Spec: corev1.PodSpec{ Containers: []corev1.Container{{Name: "c", Args: []string{"--archive=" + altinityArchiveName(j)}}}, }}}, diff --git a/internal/backupcontroller/altinitystrategy_controller.go b/internal/backupcontroller/altinitystrategy_controller.go index 8eade82c7..d1b70d6bd 100644 --- a/internal/backupcontroller/altinitystrategy_controller.go +++ b/internal/backupcontroller/altinitystrategy_controller.go @@ -4,6 +4,7 @@ package backupcontroller import ( "context" "encoding/json" + "errors" "fmt" "maps" "regexp" @@ -22,6 +23,7 @@ import ( "k8s.io/apimachinery/pkg/types" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/apiutil" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" strategyv1alpha1 "github.com/cozystack/cozystack/api/backups/strategy/v1alpha1" @@ -429,6 +431,18 @@ func (r *BackupJobReconciler) reconcileAltinity(ctx context.Context, j *backupsv jobAnnotations, rendered, ) + if errors.Is(err, errAltinityPredecessorJob) { + apimeta.SetStatusCondition(&j.Status.Conditions, metav1.Condition{ + Type: "Ready", + Status: metav1.ConditionFalse, + Reason: "PredecessorJobPending", + Message: err.Error(), + }) + if uerr := r.Status().Update(ctx, j); uerr != nil { + return ctrl.Result{}, uerr + } + return ctrl.Result{RequeueAfter: altinityPollInterval}, nil + } if err != nil { return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to ensure batch/v1.Job: %v", err)) } @@ -506,7 +520,7 @@ func (r *BackupJobReconciler) ensureAltinityJob( existing := &batchv1.Job{} err := r.Get(ctx, types.NamespacedName{Namespace: namespace, Name: name}, existing) if err == nil { - return existing, nil + return existing, r.checkAltinityJobController(existing, owner) } if !apierrors.IsNotFound(err) { return nil, err @@ -525,13 +539,37 @@ func (r *BackupJobReconciler) ensureAltinityJob( if err := r.Get(ctx, types.NamespacedName{Namespace: namespace, Name: name}, existing); err != nil { return nil, err } - return existing, nil + return existing, r.checkAltinityJobController(existing, owner) } return nil, err } return desired, nil } +// errAltinityPredecessorJob marks a backup Job left under the Job name by an +// earlier BackupJob of the same name. Its owner is gone, so the garbage +// collector removes it, and the BackupJob waits for that instead of failing. +var errAltinityPredecessorJob = errors.New("waiting for the garbage collector to remove a Job of an earlier owner of the same name") + +// checkAltinityJobController refuses a Job under owner's Job name that owner +// does not control. A BackupJob re-created under a used name meets the Job of +// the earlier one, and that Job's completion says nothing about this run. +func (r *BackupJobReconciler) checkAltinityJobController(job *batchv1.Job, owner client.Object) error { + if metav1.IsControlledBy(job, owner) { + return nil + } + gvk, err := apiutil.GVKForObject(owner, r.Scheme) + if err != nil { + return err + } + if ref := metav1.GetControllerOf(job); ref != nil && ref.Kind == gvk.Kind && ref.Name == owner.GetName() { + if gv, perr := schema.ParseGroupVersion(ref.APIVersion); perr == nil && gv.Group == gvk.Group { + return fmt.Errorf("%w: Job %s", errAltinityPredecessorJob, job.Name) + } + } + return fmt.Errorf("Job %s, which this %s did not create, holds its Job name", job.Name, gvk.Kind) +} + // ensureAltinityRestoreJob mirrors ensureAltinityJob from the RestoreJob // reconciler. The Job lives in the RestoreJob's namespace - both // BackupRef and TargetApplicationRef on RestoreJob are diff --git a/internal/backupcontroller/altinitystrategy_controller_test.go b/internal/backupcontroller/altinitystrategy_controller_test.go index 7975633c1..a78a78e51 100644 --- a/internal/backupcontroller/altinitystrategy_controller_test.go +++ b/internal/backupcontroller/altinitystrategy_controller_test.go @@ -4,6 +4,7 @@ package backupcontroller import ( "context" "errors" + "fmt" "strings" "testing" "time" @@ -44,6 +45,12 @@ func newAltinityClickHouseApp(name, namespace string) *unstructured.Unstructured return u } +// altinityControllerRef is the controllerRef ensureAltinityJob gives the +// backup Job it creates for j. +func altinityControllerRef(j *backupsv1alpha1.BackupJob) []metav1.OwnerReference { + return []metav1.OwnerReference{*metav1.NewControllerRef(j, backupsv1alpha1.GroupVersion.WithKind("BackupJob"))} +} + // newAltinityTestEnv builds the scheme, dynamic client, REST mapper, and // reconciler harness used across Altinity strategy unit tests. func newAltinityTestEnv(t *testing.T, app *unstructured.Unstructured, builder *clientfake.ClientBuilder) (*BackupJobReconciler, *RestoreJobReconciler, *runtime.Scheme) { @@ -213,8 +220,9 @@ func TestReconcileAltinity_CompletesAndCreatesBackup(t *testing.T) { } completedK8sJob := &batchv1.Job{ ObjectMeta: metav1.ObjectMeta{ - Name: jobNameForBackupJob(backupJob), - Namespace: backupJob.Namespace, + Name: jobNameForBackupJob(backupJob), + Namespace: backupJob.Namespace, + OwnerReferences: altinityControllerRef(backupJob), Labels: map[string]string{ backupsv1alpha1.OwningJobNameLabel: backupJob.Name, backupsv1alpha1.OwningJobNamespaceLabel: backupJob.Namespace, @@ -294,8 +302,9 @@ func TestReconcileAltinity_FailsOnJobFailed(t *testing.T) { } failedK8sJob := &batchv1.Job{ ObjectMeta: metav1.ObjectMeta{ - Name: jobNameForBackupJob(backupJob), - Namespace: backupJob.Namespace, + Name: jobNameForBackupJob(backupJob), + Namespace: backupJob.Namespace, + OwnerReferences: altinityControllerRef(backupJob), Labels: map[string]string{ backupsv1alpha1.OwningJobNameLabel: backupJob.Name, backupsv1alpha1.OwningJobNamespaceLabel: backupJob.Namespace, @@ -963,7 +972,7 @@ func TestReconcileAltinity_RecordsNoArchiveTheJobWasNotGiven(t *testing.T) { Status: backupsv1alpha1.BackupJobStatus{StartedAt: &startedAt, Phase: backupsv1alpha1.BackupJobPhaseRunning}, } completedK8sJob := &batchv1.Job{ - ObjectMeta: metav1.ObjectMeta{Name: jobNameForBackupJob(backupJob), Namespace: backupJob.Namespace}, + ObjectMeta: metav1.ObjectMeta{Name: jobNameForBackupJob(backupJob), Namespace: backupJob.Namespace, OwnerReferences: altinityControllerRef(backupJob)}, Spec: batchv1.JobSpec{ Template: corev1.PodTemplateSpec{Spec: corev1.PodSpec{ RestartPolicy: corev1.RestartPolicyNever, @@ -1711,3 +1720,92 @@ func TestReconcileAltinity_CredentialsWaitKeepsTheArchiveName(t *testing.T) { t.Errorf("Backup takenAt %s is earlier than its archive's stamp", stamp) } } + +// TestReconcileAltinity_DoesNotReuseAJobItDoesNotControl covers a backup Job +// already standing under the BackupJob's Job name that this BackupJob did not +// create. Taking its completion for this run's would report a backup that +// never ran and record an archive nobody uploaded for it. +func TestReconcileAltinity_DoesNotReuseAJobItDoesNotControl(t *testing.T) { + predecessor := runningAltinityBackupJob() + predecessor.UID = "predecessor-uid" + cases := []struct { + name string + owners []metav1.OwnerReference + wantFailed bool + }{ + {name: "an earlier BackupJob of the same name controls it", owners: altinityControllerRef(predecessor)}, + {name: "nothing controls it", wantFailed: true}, + {name: "a BackupJob of another name controls it", wantFailed: true, owners: altinityControllerRef(&backupsv1alpha1.BackupJob{ + ObjectMeta: metav1.ObjectMeta{Name: "other-bj", Namespace: "tenant-test", UID: "other-uid"}, + })}, + {name: "a RestoreJob controls it", wantFailed: true, owners: []metav1.OwnerReference{ + *metav1.NewControllerRef(predecessor, backupsv1alpha1.GroupVersion.WithKind("RestoreJob")), + }}, + {name: "a BackupJob of another API group controls it", wantFailed: true, owners: []metav1.OwnerReference{ + *metav1.NewControllerRef(predecessor, schema.GroupVersion{Group: "example.com", Version: "v1alpha1"}.WithKind("BackupJob")), + }}, + } + for _, tc := range cases { + // raced: the cache does not show the Job yet, so the driver meets it + // only when its own create is refused. + for _, raced := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/raced=%t", tc.name, raced), func(t *testing.T) { + app := newAltinityClickHouseApp("ch-test", "tenant-test") + strategy := newAltinityArchiveStrategy("clickhouse-strategy") + bj := runningAltinityBackupJob() + bj.UID = "this-uid" + job := completedAltinityK8sJob(bj) + job.OwnerReferences = tc.owners + builder := clientfake.NewClientBuilder().WithObjects(bj, strategy, job) + if raced { + hidden := false + builder = builder.WithInterceptorFuncs(interceptor.Funcs{ + Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if _, isJob := obj.(*batchv1.Job); isJob && !hidden { + hidden = true + return apierrors.NewNotFound(batchv1.Resource("jobs"), key.Name) + } + return c.Get(ctx, key, obj, opts...) + }, + }) + } + r, _, _ := newAltinityTestEnv(t, app, builder) + ctx := context.Background() + + res, err := r.reconcileAltinity(ctx, bj, altinityResolved(strategy.Name)) + if err != nil { + t.Fatalf("reconcileAltinity: %v", err) + } + + got := &backupsv1alpha1.BackupJob{} + if err := r.Get(ctx, client.ObjectKeyFromObject(bj), got); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + if got.Status.BackupRef != nil { + t.Errorf("BackupJob points at Backup %q made from a Job it did not run", got.Status.BackupRef.Name) + } + if err := r.Get(ctx, client.ObjectKey{Namespace: bj.Namespace, Name: bj.Name}, &backupsv1alpha1.Backup{}); err == nil { + t.Error("a Backup was created from a Job this BackupJob did not run") + } + if tc.wantFailed { + if got.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("phase = %q, want Failed", got.Status.Phase) + } + if !strings.Contains(got.Status.Message, job.Name) { + t.Errorf("message %q does not name Job %s", got.Status.Message, job.Name) + } + return + } + if got.Status.Phase != backupsv1alpha1.BackupJobPhaseRunning { + t.Errorf("phase = %q, want Running while the earlier Job awaits garbage collection", got.Status.Phase) + } + if res.RequeueAfter <= 0 { + t.Errorf("no requeue while the earlier Job awaits garbage collection: %+v", res) + } + if c := meta.FindStatusCondition(got.Status.Conditions, "Ready"); c == nil || !strings.Contains(c.Message, job.Name) { + t.Errorf("Ready condition %+v does not say which Job it waits for", c) + } + }) + } + } +} From 084fed9e2fa5b8ac9d3f45caef525e2ecfd05876 Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Mon, 23 Nov 2026 12:14:56 +0300 Subject: [PATCH 4/7] fix(clickhouse): take no restore Job's result that this RestoreJob did not run The restore path took any Job standing under a RestoreJob's Job name as its own, so a RestoreJob re-created under a used name met the completed Job of the earlier one before the garbage collector removed it and was marked Succeeded although nothing was restored for it. The restore path now refuses such a Job the way the backup path does: the Job of an earlier RestoreJob of the same name is waited out, with the Ready condition naming it, and any other Job holding the name fails the RestoreJob. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- .../altinitystrategy_controller.go | 36 ++++--- .../altinitystrategy_controller_test.go | 97 +++++++++++++++++++ 2 files changed, 122 insertions(+), 11 deletions(-) diff --git a/internal/backupcontroller/altinitystrategy_controller.go b/internal/backupcontroller/altinitystrategy_controller.go index d1b70d6bd..7e5b68373 100644 --- a/internal/backupcontroller/altinitystrategy_controller.go +++ b/internal/backupcontroller/altinitystrategy_controller.go @@ -19,6 +19,7 @@ import ( "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" ctrl "sigs.k8s.io/controller-runtime" @@ -520,7 +521,7 @@ func (r *BackupJobReconciler) ensureAltinityJob( existing := &batchv1.Job{} err := r.Get(ctx, types.NamespacedName{Namespace: namespace, Name: name}, existing) if err == nil { - return existing, r.checkAltinityJobController(existing, owner) + return existing, checkAltinityJobController(r.Scheme, existing, owner) } if !apierrors.IsNotFound(err) { return nil, err @@ -539,26 +540,27 @@ func (r *BackupJobReconciler) ensureAltinityJob( if err := r.Get(ctx, types.NamespacedName{Namespace: namespace, Name: name}, existing); err != nil { return nil, err } - return existing, r.checkAltinityJobController(existing, owner) + return existing, checkAltinityJobController(r.Scheme, existing, owner) } return nil, err } return desired, nil } -// errAltinityPredecessorJob marks a backup Job left under the Job name by an -// earlier BackupJob of the same name. Its owner is gone, so the garbage -// collector removes it, and the BackupJob waits for that instead of failing. +// errAltinityPredecessorJob marks a Job left under the Job name by an earlier +// BackupJob or RestoreJob of the same name. Its owner is gone, so the garbage +// collector removes it, and the new owner waits for that instead of failing. var errAltinityPredecessorJob = errors.New("waiting for the garbage collector to remove a Job of an earlier owner of the same name") // checkAltinityJobController refuses a Job under owner's Job name that owner -// does not control. A BackupJob re-created under a used name meets the Job of -// the earlier one, and that Job's completion says nothing about this run. -func (r *BackupJobReconciler) checkAltinityJobController(job *batchv1.Job, owner client.Object) error { +// does not control. A BackupJob or RestoreJob re-created under a used name +// meets the Job of the earlier one, and that Job's completion says nothing +// about this run. +func checkAltinityJobController(scheme *runtime.Scheme, job *batchv1.Job, owner client.Object) error { if metav1.IsControlledBy(job, owner) { return nil } - gvk, err := apiutil.GVKForObject(owner, r.Scheme) + gvk, err := apiutil.GVKForObject(owner, scheme) if err != nil { return err } @@ -586,7 +588,7 @@ func (r *RestoreJobReconciler) ensureAltinityRestoreJob( existing := &batchv1.Job{} err := r.Get(ctx, types.NamespacedName{Namespace: namespace, Name: name}, existing) if err == nil { - return existing, nil + return existing, checkAltinityJobController(r.Scheme, existing, owner) } if !apierrors.IsNotFound(err) { return nil, err @@ -604,7 +606,7 @@ func (r *RestoreJobReconciler) ensureAltinityRestoreJob( if err := r.Get(ctx, types.NamespacedName{Namespace: namespace, Name: name}, existing); err != nil { return nil, err } - return existing, nil + return existing, checkAltinityJobController(r.Scheme, existing, owner) } return nil, err } @@ -920,6 +922,18 @@ func (r *RestoreJobReconciler) reconcileAltinityRestore(ctx context.Context, res }, rendered, ) + if errors.Is(err, errAltinityPredecessorJob) { + apimeta.SetStatusCondition(&restoreJob.Status.Conditions, metav1.Condition{ + Type: "Ready", + Status: metav1.ConditionFalse, + Reason: "PredecessorJobPending", + Message: err.Error(), + }) + if uerr := r.Status().Update(ctx, restoreJob); uerr != nil { + return ctrl.Result{}, uerr + } + return ctrl.Result{RequeueAfter: altinityPollInterval}, nil + } if err != nil { return r.markRestoreJobFailed(ctx, restoreJob, fmt.Sprintf("failed to ensure batch/v1.Job: %v", err)) } diff --git a/internal/backupcontroller/altinitystrategy_controller_test.go b/internal/backupcontroller/altinitystrategy_controller_test.go index a78a78e51..00dd83a52 100644 --- a/internal/backupcontroller/altinitystrategy_controller_test.go +++ b/internal/backupcontroller/altinitystrategy_controller_test.go @@ -1809,3 +1809,100 @@ func TestReconcileAltinity_DoesNotReuseAJobItDoesNotControl(t *testing.T) { } } } + +// TestReconcileAltinityRestore_DoesNotReuseAJobItDoesNotControl is the restore +// side of TestReconcileAltinity_DoesNotReuseAJobItDoesNotControl: taking +// another Job's completion would report a restore that never ran. +func TestReconcileAltinityRestore_DoesNotReuseAJobItDoesNotControl(t *testing.T) { + restoreRef := func(name, uid string, gv schema.GroupVersion, kind string) []metav1.OwnerReference { + owner := &backupsv1alpha1.RestoreJob{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "tenant-test", UID: types.UID(uid)}} + return []metav1.OwnerReference{*metav1.NewControllerRef(owner, gv.WithKind(kind))} + } + other := schema.GroupVersion{Group: "example.com", Version: "v1alpha1"} + cases := []struct { + name string + owners []metav1.OwnerReference + wantFailed bool + }{ + {name: "an earlier RestoreJob of the same name controls it", owners: restoreRef("rj", "predecessor-uid", backupsv1alpha1.GroupVersion, "RestoreJob")}, + {name: "nothing controls it", wantFailed: true}, + {name: "a RestoreJob of another name controls it", wantFailed: true, owners: restoreRef("other-rj", "other-uid", backupsv1alpha1.GroupVersion, "RestoreJob")}, + {name: "a BackupJob controls it", wantFailed: true, owners: restoreRef("rj", "predecessor-uid", backupsv1alpha1.GroupVersion, "BackupJob")}, + {name: "a RestoreJob of another API group controls it", wantFailed: true, owners: restoreRef("rj", "predecessor-uid", other, "RestoreJob")}, + } + for _, tc := range cases { + for _, raced := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/raced=%t", tc.name, raced), func(t *testing.T) { + targetApp := newAltinityClickHouseApp("ch-test", "tenant-test") + strategy := newAltinityArchiveStrategy("clickhouse-strategy") + now := metav1.Now() + backup := &backupsv1alpha1.Backup{ + ObjectMeta: metav1.ObjectMeta{Name: "ch-backup", Namespace: "tenant-test"}, + Spec: backupsv1alpha1.BackupSpec{ + ApplicationRef: newAltinityClickHouseRef("ch-test"), + StrategyRef: corev1.TypedLocalObjectReference{ + APIGroup: new(strategyv1alpha1.GroupVersion.Group), + Kind: strategyv1alpha1.AltinityStrategyKind, + Name: "clickhouse-strategy", + }, + TakenAt: now, + }, + } + restoreJob := &backupsv1alpha1.RestoreJob{ + ObjectMeta: metav1.ObjectMeta{Name: "rj", Namespace: "tenant-test", UID: "this-uid"}, + Spec: backupsv1alpha1.RestoreJobSpec{BackupRef: corev1.LocalObjectReference{Name: backup.Name}}, + Status: backupsv1alpha1.RestoreJobStatus{StartedAt: &now, Phase: backupsv1alpha1.RestoreJobPhaseRunning}, + } + job := &batchv1.Job{ + ObjectMeta: metav1.ObjectMeta{Name: jobNameForRestoreJob(restoreJob), Namespace: "tenant-test", OwnerReferences: tc.owners}, + Status: batchv1.JobStatus{Conditions: []batchv1.JobCondition{ + {Type: batchv1.JobComplete, Status: corev1.ConditionTrue}, + }}, + } + builder := clientfake.NewClientBuilder().WithObjects(strategy, backup, restoreJob, job) + if raced { + hidden := false + builder = builder.WithInterceptorFuncs(interceptor.Funcs{ + Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if _, isJob := obj.(*batchv1.Job); isJob && !hidden { + hidden = true + return apierrors.NewNotFound(batchv1.Resource("jobs"), key.Name) + } + return c.Get(ctx, key, obj, opts...) + }, + }) + } + _, rr, _ := newAltinityTestEnv(t, targetApp, builder) + ctx := context.Background() + + res, err := rr.reconcileAltinityRestore(ctx, restoreJob, backup) + if err != nil { + t.Fatalf("reconcileAltinityRestore: %v", err) + } + + got := &backupsv1alpha1.RestoreJob{} + if err := rr.Get(ctx, client.ObjectKeyFromObject(restoreJob), got); err != nil { + t.Fatalf("get RestoreJob: %v", err) + } + if tc.wantFailed { + if got.Status.Phase != backupsv1alpha1.RestoreJobPhaseFailed { + t.Fatalf("phase = %q, want Failed", got.Status.Phase) + } + if !strings.Contains(got.Status.Message, job.Name) { + t.Errorf("message %q does not name Job %s", got.Status.Message, job.Name) + } + return + } + if got.Status.Phase != backupsv1alpha1.RestoreJobPhaseRunning { + t.Errorf("phase = %q, want Running while the earlier Job awaits garbage collection", got.Status.Phase) + } + if res.RequeueAfter <= 0 { + t.Errorf("no requeue while the earlier Job awaits garbage collection: %+v", res) + } + if c := meta.FindStatusCondition(got.Status.Conditions, "Ready"); c == nil || !strings.Contains(c.Message, job.Name) { + t.Errorf("Ready condition %+v does not say which Job it waits for", c) + } + }) + } + } +} From 8cf04bdd0fe05e9fe5d4b3a16b76f2a153cf7fdb Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Mon, 23 Nov 2026 12:14:57 +0300 Subject: [PATCH 5/7] fix(clickhouse): make the example strategy use the archive its Backup records The example strategy minted its own archive name from the clock and restored the newest archive of the source application. The controller then found no archive name in the backup Job and recorded none, so a restore of an older Backup silently restored the latest archive and deleting a Backup left its archive in the bucket. The example now uploads under the name the controller chose and restores the archive the Backup records, as the shipped strategy does; the clock-made name and the newest archive remain the fallback for a run the controller gave no name. The backup scenario no longer says the archive is expired by the upstream tool's retention, which the chart does not configure. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- .../backups/clickhouse/01-create-strategy.sh | 24 ++- .../clickhouse/91-scenario-user-backup.md | 2 +- hack/clickhouse-example-strategy.bats | 137 ++++++++++++++++++ 3 files changed, 154 insertions(+), 9 deletions(-) create mode 100644 hack/clickhouse-example-strategy.bats diff --git a/examples/backups/clickhouse/01-create-strategy.sh b/examples/backups/clickhouse/01-create-strategy.sh index 9a4142e6e..5efdca7b1 100755 --- a/examples/backups/clickhouse/01-create-strategy.sh +++ b/examples/backups/clickhouse/01-create-strategy.sh @@ -78,6 +78,11 @@ spec: # \${API_USERNAME} / \${API_PASSWORD} come from the # backup-api-auth Secret mounted via env (see above). auth="-u \${API_USERNAME}:\${API_PASSWORD}" + # The archive the controller named for this run and records on + # its Backup, so that the restore and the delete of that Backup + # reach the archive the run wrote. Empty when the controller + # gave no name; the names below are the fallback for that case. + archive="{{ .ArchiveName | default "" }}" # Sidecar may still be coming up when the strategy Pod fires. # Block on /backup/status until it answers (max ~5 minutes). @@ -101,18 +106,21 @@ spec: # also lands on the correct archive. if [ "{{ .Mode }}" = "backup" ]; then prefix="clickhouse-{{ .Release.Name }}-" - target="\${prefix}\$(date -u +%Y%m%dT%H%M%SZ)" + target="\${archive:-\${prefix}\$(date -u +%Y%m%dT%H%M%SZ)}" echo "create_remote \${target}" curl -fsS \${auth} -X POST "\${api}/backup/create_remote?name=\${target}" >/dev/null else prefix="clickhouse-{{ .Backup.ApplicationRef.Name }}-" - # Pick the latest archive whose name starts with the - # source-release prefix. Falls through to "no remote - # backup found" if S3_PATH is misconfigured AND none of - # the listed names match. - target=\$(curl -fsS \${auth} --max-time 60 "\${api}/backup/list/remote" \\ - | jq -rs --arg prefix "\${prefix}" \\ - '[.[] | select((.name // "") | startswith(\$prefix))] | sort_by(.created // "") | last.name // ""') + # A Backup that records no archive gets the latest archive + # whose name starts with the source-release prefix. Falls + # through to "no remote backup found" if S3_PATH is + # misconfigured AND none of the listed names match. + target="\${archive}" + if [ -z "\${target}" ]; then + target=\$(curl -fsS \${auth} --max-time 60 "\${api}/backup/list/remote" \\ + | jq -rs --arg prefix "\${prefix}" \\ + '[.[] | select((.name // "") | startswith(\$prefix))] | sort_by(.created // "") | last.name // ""') + fi if [ -z "\${target}" ] || [ "\${target}" = "null" ]; then echo "no remote backup found" >&2 exit 1 diff --git a/examples/backups/clickhouse/91-scenario-user-backup.md b/examples/backups/clickhouse/91-scenario-user-backup.md index fce391429..c154498e0 100644 --- a/examples/backups/clickhouse/91-scenario-user-backup.md +++ b/examples/backups/clickhouse/91-scenario-user-backup.md @@ -42,5 +42,5 @@ This scenario assumes the admin steps (`01-...`, `02-...`) have already run. | Resource | Where | Purpose | |---|---|---| | `BackupJob/` | tenant namespace | Records the run; `status.phase=Succeeded`, `status.backupRef` points at the Backup | -| `Backup/` | tenant namespace | The restorable artifact reference (the actual data lives in S3 under the upstream tool's retention) | +| `Backup/` | tenant namespace | The restorable artifact reference; the data lives in S3 as the archive the Backup records. Nothing expires it: on `backup.useSystemBucket: true` deleting the `Backup` deletes the archive, and on the tenant's own bucket the archive stays until the tenant removes it, through the sidecar's `POST /backup/delete/remote/` or the bucket's lifecycle rules | | `batch/v1.Job/-backup` | tenant namespace | The completed strategy Pod | diff --git a/hack/clickhouse-example-strategy.bats b/hack/clickhouse-example-strategy.bats new file mode 100644 index 000000000..82bca362b --- /dev/null +++ b/hack/clickhouse-example-strategy.bats @@ -0,0 +1,137 @@ +#!/usr/bin/env bats +# Behavioural tests for the example ClickHouse (Altinity) strategy that +# examples/backups/clickhouse/01-create-strategy.sh applies. The script runs +# against a stubbed kubectl, which captures the Strategy it applies; the +# in-Pod script of that Strategy is then rendered the way the backup +# controller renders it and EXECUTED against a stubbed clickhouse-backup +# sidecar API. +# +# The contract pinned here is which archive the example touches: the one the +# controller named for the run (.ArchiveName), so that the Backup records the +# archive the run wrote, its restore reads that archive back and deleting it +# removes that archive. The name the script mints from the clock, and the +# newest archive of the source application, are only the fallbacks for a run +# the controller gave no name. + +load test_helper + +EXAMPLE=examples/backups/clickhouse/01-create-strategy.sh + +# Capture the Strategy the example applies into $1, with kubectl stubbed so +# no cluster is touched: `get` answers with a client image, so the example +# does not fall back to installing tools at run time, and `apply -f -` writes +# its manifest. +capture_strategy() { + out=$1 + stub=$(mktemp -d) + cat > "$stub/kubectl" < "$out" ;; +esac +STUB + chmod +x "$stub/kubectl" + PATH="$stub:$PATH" bash "$EXAMPLE" >/dev/null 2>&1 + [ -s "$out" ] || return 1 +} + +# Render the captured Strategy's in-Pod script into $2 as the controller +# would: $3 mode, $4 the application (release and source), $5 the archive +# name the controller chose or the Backup recorded (empty for none). +render_example() { + manifest=$1; out=$2; mode=$3; app=$4; archive=${5-} + yq eval '.spec.template.spec.containers[0].args[0]' "$manifest" \ + | sed -e "s#{{ .Mode }}#${mode}#g" \ + -e "s#{{ .Release.Name }}#${app}#g" \ + -e "s#{{ .Release.Namespace }}#tenant-x#g" \ + -e "s#{{ .Backup.ApplicationRef.Name }}#${app}#g" \ + -e "s#{{ .ArchiveName | default \"\" }}#${archive}#g" > "$out" + [ -s "$out" ] || return 1 + if grep -q '{{' "$out"; then + echo "rendered script still holds a controller placeholder" >&2 + return 1 + fi +} + +# A curl stub standing in for the sidecar, first on PATH next to a no-op +# sleep. Every request is logged to $2/requests; an accepted POST makes the +# action log report that operation as succeeded; list/remote lists two +# archives of app "ch", the newer one second. +make_sidecar() { + bin=$1; state=$2 + mkdir -p "$bin" "$state" + cat > "$bin/curl" <> "\$state/requests" +case "\$method \$url" in + "POST "*create_remote\?name=*) name=\${url#*name=}; echo "create_remote \$name" > "\$state/op" ;; + "POST "*/restore_remote/*) echo "restore_remote \${url##*/}" > "\$state/op" ;; + "GET "*/backup/actions) [ -s "\$state/op" ] && printf '{"command":"%s","status":"success","start":"2026-01-01 00:00:00"}\n' "\$(cat "\$state/op")" ;; + "GET "*/backup/list/remote) + printf '{"name":"clickhouse-ch-20260101T000000Z","created":"2026-01-01 00:00:00"}\n' + printf '{"name":"clickhouse-ch-20260102T000000Z","created":"2026-01-02 00:00:00"}\n' + ;; +esac +exit 0 +STUB + printf '#!/bin/sh\nexit 0\n' > "$bin/sleep" + chmod +x "$bin/curl" "$bin/sleep" +} + +setup() { + strict_setup + work=$(mktemp -d) + capture_strategy "$work/strategy.yaml" + make_sidecar "$work/bin" "$work/state" +} + +run_example() { + render_example "$work/strategy.yaml" "$work/script.sh" "$1" ch "${2-}" + API_USERNAME=u API_PASSWORD=p PATH="$work/bin:$PATH" bash "$work/script.sh" +} + +@test "backup uploads under the archive name the controller chose" { + run_example backup ch-20260304050607-0f3c9a1e5b7d + if ! grep -qx 'POST http://chi-clickhouse-ch-clickhouse-0-0.tenant-x.svc:7171/backup/create_remote?name=ch-20260304050607-0f3c9a1e5b7d' "$work/state/requests"; then + echo "backup did not upload under the controller's name:" >&2 + cat "$work/state/requests" >&2 + exit 1 + fi +} + +@test "backup without a controller name falls back to a name from the clock" { + run_example backup "" + if ! grep -qE '^POST .*/backup/create_remote\?name=clickhouse-ch-[0-9]{8}T[0-9]{6}Z$' "$work/state/requests"; then + echo "backup without a name did not mint one from the clock:" >&2 + cat "$work/state/requests" >&2 + exit 1 + fi +} + +@test "restore reads back the archive the Backup recorded, not the newest one" { + run_example restore clickhouse-ch-20260101T000000Z + if ! grep -qx 'POST http://chi-clickhouse-ch-clickhouse-0-0.tenant-x.svc:7171/backup/restore_remote/clickhouse-ch-20260101T000000Z' "$work/state/requests"; then + echo "restore did not read the recorded archive:" >&2 + cat "$work/state/requests" >&2 + exit 1 + fi +} + +@test "restore of a Backup that records no archive takes the newest one" { + run_example restore "" + if ! grep -qx 'POST http://chi-clickhouse-ch-clickhouse-0-0.tenant-x.svc:7171/backup/restore_remote/clickhouse-ch-20260102T000000Z' "$work/state/requests"; then + echo "restore without a recorded archive did not take the newest one:" >&2 + cat "$work/state/requests" >&2 + exit 1 + fi +} From a2f7ea18eef2b7f89c094a9f502e09b8a7b9ad38 Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Mon, 23 Nov 2026 12:14:57 +0300 Subject: [PATCH 6/7] fix(clickhouse): drop the predecessor wait once a run's own Job starts A BackupJob or RestoreJob that waited for the Job of an earlier owner of its name kept its Ready=False PredecessorJobPending condition after that Job was gone and its own Job had started, so for the whole run it still said it was waiting for the garbage collector. The condition is now dropped when the run's own Job is running, the way the credentials wait is. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- .../altinitystrategy_controller.go | 23 ++++++++++--- .../altinitystrategy_controller_test.go | 32 +++++++++++++++++++ 2 files changed, 51 insertions(+), 4 deletions(-) diff --git a/internal/backupcontroller/altinitystrategy_controller.go b/internal/backupcontroller/altinitystrategy_controller.go index 7e5b68373..accff2f70 100644 --- a/internal/backupcontroller/altinitystrategy_controller.go +++ b/internal/backupcontroller/altinitystrategy_controller.go @@ -180,6 +180,17 @@ func clearCredentialsWait(conditions *[]metav1.Condition) bool { return apimeta.RemoveStatusCondition(conditions, "Ready") } +// clearPredecessorWait drops the Ready condition a run set while it waited +// for the Job of an earlier owner of its name, once its own Job runs. It +// reports whether it did. +func clearPredecessorWait(conditions *[]metav1.Condition) bool { + ready := apimeta.FindStatusCondition(*conditions, "Ready") + if ready == nil || ready.Reason != altinityPredecessorJobReason { + return false + } + return apimeta.RemoveStatusCondition(conditions, "Ready") +} + const credentialsWaitReason = "WaitingForCredentials" // credentialsWaitCondition is the Ready condition of a job held back by @@ -436,7 +447,7 @@ func (r *BackupJobReconciler) reconcileAltinity(ctx context.Context, j *backupsv apimeta.SetStatusCondition(&j.Status.Conditions, metav1.Condition{ Type: "Ready", Status: metav1.ConditionFalse, - Reason: "PredecessorJobPending", + Reason: altinityPredecessorJobReason, Message: err.Error(), }) if uerr := r.Status().Update(ctx, j); uerr != nil { @@ -494,7 +505,7 @@ func (r *BackupJobReconciler) reconcileAltinity(ctx context.Context, j *backupsv return r.markBackupJobFailed(ctx, j, message) default: - if clearCredentialsWait(&j.Status.Conditions) { + if clearCredentialsWait(&j.Status.Conditions) || clearPredecessorWait(&j.Status.Conditions) { if err := r.Status().Update(ctx, j); err != nil { return ctrl.Result{}, err } @@ -547,6 +558,10 @@ func (r *BackupJobReconciler) ensureAltinityJob( return desired, nil } +// altinityPredecessorJobReason is the Ready reason of a run that waits for +// the Job of an earlier owner of its name to be removed. +const altinityPredecessorJobReason = "PredecessorJobPending" + // errAltinityPredecessorJob marks a Job left under the Job name by an earlier // BackupJob or RestoreJob of the same name. Its owner is gone, so the garbage // collector removes it, and the new owner waits for that instead of failing. @@ -926,7 +941,7 @@ func (r *RestoreJobReconciler) reconcileAltinityRestore(ctx context.Context, res apimeta.SetStatusCondition(&restoreJob.Status.Conditions, metav1.Condition{ Type: "Ready", Status: metav1.ConditionFalse, - Reason: "PredecessorJobPending", + Reason: altinityPredecessorJobReason, Message: err.Error(), }) if uerr := r.Status().Update(ctx, restoreJob); uerr != nil { @@ -962,7 +977,7 @@ func (r *RestoreJobReconciler) reconcileAltinityRestore(ctx context.Context, res return r.markRestoreJobFailed(ctx, restoreJob, message) default: - if clearCredentialsWait(&restoreJob.Status.Conditions) { + if clearCredentialsWait(&restoreJob.Status.Conditions) || clearPredecessorWait(&restoreJob.Status.Conditions) { if err := r.Status().Update(ctx, restoreJob); err != nil { return ctrl.Result{}, err } diff --git a/internal/backupcontroller/altinitystrategy_controller_test.go b/internal/backupcontroller/altinitystrategy_controller_test.go index 00dd83a52..d8547320e 100644 --- a/internal/backupcontroller/altinitystrategy_controller_test.go +++ b/internal/backupcontroller/altinitystrategy_controller_test.go @@ -1805,6 +1805,22 @@ func TestReconcileAltinity_DoesNotReuseAJobItDoesNotControl(t *testing.T) { if c := meta.FindStatusCondition(got.Status.Conditions, "Ready"); c == nil || !strings.Contains(c.Message, job.Name) { t.Errorf("Ready condition %+v does not say which Job it waits for", c) } + + // Once the garbage collector has removed the earlier Job, this + // run's own Job starts and the wait is over. + if err := r.Delete(ctx, job); err != nil { + t.Fatalf("remove the earlier Job: %v", err) + } + if _, err := r.reconcileAltinity(ctx, got, altinityResolved(strategy.Name)); err != nil { + t.Fatalf("reconcileAltinity after the earlier Job went: %v", err) + } + after := &backupsv1alpha1.BackupJob{} + if err := r.Get(ctx, client.ObjectKeyFromObject(bj), after); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + if c := meta.FindStatusCondition(after.Status.Conditions, "Ready"); c != nil && c.Reason == altinityPredecessorJobReason { + t.Errorf("Ready condition %+v still says the run waits for an earlier Job while its own runs", c) + } }) } } @@ -1902,6 +1918,22 @@ func TestReconcileAltinityRestore_DoesNotReuseAJobItDoesNotControl(t *testing.T) if c := meta.FindStatusCondition(got.Status.Conditions, "Ready"); c == nil || !strings.Contains(c.Message, job.Name) { t.Errorf("Ready condition %+v does not say which Job it waits for", c) } + + // Once the garbage collector has removed the earlier Job, this + // run's own Job starts and the wait is over. + if err := rr.Delete(ctx, job); err != nil { + t.Fatalf("remove the earlier Job: %v", err) + } + if _, err := rr.reconcileAltinityRestore(ctx, got, backup); err != nil { + t.Fatalf("reconcileAltinityRestore after the earlier Job went: %v", err) + } + after := &backupsv1alpha1.RestoreJob{} + if err := rr.Get(ctx, client.ObjectKeyFromObject(restoreJob), after); err != nil { + t.Fatalf("get RestoreJob: %v", err) + } + if c := meta.FindStatusCondition(after.Status.Conditions, "Ready"); c != nil && c.Reason == altinityPredecessorJobReason { + t.Errorf("Ready condition %+v still says the run waits for an earlier Job while its own runs", c) + } }) } } From 4fb8ea40e2785a21de2c155c62f9be91a6a970b0 Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Mon, 23 Nov 2026 12:14:58 +0300 Subject: [PATCH 7/7] test(clickhouse): delete the system-bucket Backup while its S3 host resolves Deleting a system-bucket Backup now deletes its archive through the clickhouse-backup sidecar, and the Backup is held until that delete is answered. The delete reaches S3 at s3.example.org only through the CoreDNS rewrite and the Ingress certificate the round-trip installs, and the script's EXIT trap removes both. The round-trip therefore deletes its Backup inside the script, before the trap runs, and waits for the cleanup; the preconditions and the step's finally mark a Backup they still find with skip-artifact-cleanup, since no S3 host is mapped by then. The wait covers a cleanup Job that runs out its 600s deadline, the 30s retry delay and a second Job, so the route is not removed while a retried delete still needs it. The test then checks the delete itself by listing the objects under the archive's prefix in the system bucket, through the S3 Ingress with the projected credentials and with folder entries left out: some before the delete, none once the Backup is gone. clickhouse-backup's list/remote is not used for this: it reports an archive for every prefix at the top of the bucket, and SeaweedFS was seen to keep the folders the delete emptied for minutes after all their objects were gone. Co-authored-by: Yan Bondarenko <202671653+yankawai@users.noreply.github.com> Assisted-by: LLM Signed-off-by: Andrey Kolkov Signed-off-by: Yan Bondarenko <202671653+yankawai@users.noreply.github.com> --- .../clickhouse/chainsaw-test.yaml | 22 +++++-- .../clickhouse/system-bucket-roundtrip.sh | 61 +++++++++++++++++++ .../clickhouse/system-bucket-tls.yaml | 3 +- 3 files changed, 80 insertions(+), 6 deletions(-) diff --git a/hack/e2e-chainsaw/clickhouse/chainsaw-test.yaml b/hack/e2e-chainsaw/clickhouse/chainsaw-test.yaml index e6253c06a..539c5e05f 100644 --- a/hack/e2e-chainsaw/clickhouse/chainsaw-test.yaml +++ b/hack/e2e-chainsaw/clickhouse/chainsaw-test.yaml @@ -465,9 +465,13 @@ spec: # Fixed names in a persistent namespace: a leftover Succeeded job # would satisfy the waits in the run step without a new attempt, and # a leftover Backup of the BackupJob's name, recording an earlier - # run's archive, fails the new BackupJob. + # run's archive, fails the new BackupJob. Its archive delete would go + # to an S3 host nothing maps yet, so it is skipped. kubectl -n "$NAMESPACE" delete restorejob sysbucket-restore --ignore-not-found --wait=true --timeout=30s kubectl -n "$NAMESPACE" delete backupjob sysbucket-backup --ignore-not-found --wait=true --timeout=30s + if kubectl -n "$NAMESPACE" get backup sysbucket-backup -o name >/dev/null 2>&1; then + kubectl -n "$NAMESPACE" annotate backup sysbucket-backup backups.cozystack.io/skip-artifact-cleanup=true --overwrite + fi kubectl -n "$NAMESPACE" delete backup sysbucket-backup --ignore-not-found --wait=true --timeout=60s kubectl -n "$NAMESPACE" delete secret cozy-backups-creds --ignore-not-found --wait=true --timeout=30s # Chainsaw reclaims only what its apply created, so objects a killed @@ -558,12 +562,15 @@ spec: # 480s BackupJob to Succeeded, including the driver's 2m hold # 480s RestoreJob to Succeeded; no hold by then, the stamp is # already older than the backup's own 2m wait + # 30s listing the archive's objects before the delete + # 1260s Backup delete, including a second cleanup Job after a timeout + # 30s listing them again after it # 90s the EXIT trap: Corefile replace plus a 60s Secret delete - # 1330s (22m10s) - # 25m leaves 2m50s for the SQL and kubectl calls between those waits, so + # 2650s (44m10s) + # 47m leaves 2m50s for the SQL and kubectl calls between those waits, so # an inner wait is what fires and names what stalled. - script: - timeout: 25m + timeout: 47m content: | set -eu cd ../../.. @@ -596,5 +603,10 @@ spec: kubectl -n "$NAMESPACE" delete restorejob sysbucket-restore --ignore-not-found --wait=true --timeout=30s kubectl -n "$NAMESPACE" delete backupjob sysbucket-backup --ignore-not-found --wait=true --timeout=30s # The driver names the Backup after the BackupJob; by name it is - # found even when status.backupRef was never written. + # found even when status.backupRef was never written. A Backup still + # here means the script failed, and its archive delete would now go + # to an S3 host the restore above unmapped, so it is skipped. + if kubectl -n "$NAMESPACE" get backup sysbucket-backup -o name >/dev/null 2>&1; then + kubectl -n "$NAMESPACE" annotate backup sysbucket-backup backups.cozystack.io/skip-artifact-cleanup=true --overwrite + fi kubectl -n "$NAMESPACE" delete backup sysbucket-backup --ignore-not-found --wait=true --timeout=60s diff --git a/hack/e2e-chainsaw/clickhouse/system-bucket-roundtrip.sh b/hack/e2e-chainsaw/clickhouse/system-bucket-roundtrip.sh index c1c216389..e068542d2 100755 --- a/hack/e2e-chainsaw/clickhouse/system-bucket-roundtrip.sh +++ b/hack/e2e-chainsaw/clickhouse/system-bucket-roundtrip.sh @@ -39,6 +39,9 @@ PROBE_TIMEOUT=240 # Each covers the driver's 2m hold after the credentials change plus the # strategy Job itself. JOB_TIMEOUT=480 +# Two 600s cleanup Jobs, the 30s retry delay and 30s to observe completion. +BACKUP_DELETE_TIMEOUT=1260 +ARCHIVE_KEY=altinity.strategy.backups.cozystack.io/archive workdir=$(mktemp -d) @@ -172,3 +175,61 @@ sidecar_after=$(sidecar_identity) [ "$sidecar_after" = "$sidecar_before" ] \ || { log_error "the ClickHouse Pod or its clickhouse-backup container restarted during the round-trip (uid restarts: '${sidecar_before}' then '${sidecar_after}')"; exit 1; } log_success "System-bucket round-trip verified: sentinel row ${sentinel} restored" + +# Prints the keys of the objects under prefix in the system bucket, one per +# line, folder entries left out. The objects are read rather than +# clickhouse-backup's list/remote, which reports an archive for every prefix +# left in the bucket, and SeaweedFS can keep the folders a delete empties. The +# credentials go over stdin to stay out of the probe's argv. +list_archive_objects() { + local prefix=$1 creds out + creds=$(kubectl -n "$NAMESPACE" get secret cozy-backups-creds -o json \ + | jq -r '.data | [.accessKey, .secretKey, .bucketName, .endpoint, .region] | map(. // "" | @base64d) | @tsv') + kubectl -n "$NAMESPACE" get secret "$CERT_SECRET" -o jsonpath='{.data.ca\.crt}' | base64 -d \ + | timeout 30 kubectl -n "$NAMESPACE" exec -i "$PROBE_POD" -- sh -c 'cat >/tmp/ca.crt' + # An empty region means us-east-1 to S3 clients, and SeaweedFS accepts a + # signature for any region. + # shellcheck disable=SC2016 # expanded by the probe's shell + if ! out=$(printf '%s\n' "$creds" | timeout 30 kubectl -n "$NAMESPACE" exec -i "$PROBE_POD" -- sh -c ' + IFS="$(printf "\t")" read -r ak sk bucket endpoint region + [ -n "$bucket" ] && [ -n "$endpoint" ] \ + || { echo "cozy-backups-creds names no bucketName or no endpoint" >&2; exit 1; } + curl -fsS --max-time 20 --cacert /tmp/ca.crt --user "${ak}:${sk}" \ + --aws-sigv4 "aws:amz:${region:-us-east-1}:s3" --get \ + --data-urlencode list-type=2 --data-urlencode "prefix=$1" \ + "https://${endpoint}/${bucket}"' sh "$prefix" 2>"$workdir/list.err"); then + log_error "could not list ${prefix} in the system bucket: $(cat "$workdir/list.err")" + return 1 + fi + printf '%s' "$out" | grep -o '[^<]*' | sed -e 's|||' -e 's|||' | grep -v '/$' || true +} + +# The archive lives in the system bucket only while the Backup does: deleting +# the Backup has to delete it, and the delete goes to S3 through the rewrite +# and certificate the EXIT trap removes, so it runs before the trap. +archive=$(kubectl -n "$NAMESPACE" get backup "$backup_ref" -o json | jq -r --arg k "$ARCHIVE_KEY" '.spec.driverMetadata[$k] // ""') +[ -n "$archive" ] || { log_error "Backup ${backup_ref} records no archive under ${ARCHIVE_KEY}"; exit 1; } +s3_path=$(kubectl -n "$NAMESPACE" get pod "chi-clickhouse-${CLICKHOUSE_NAME}-clickhouse-0-0-0" \ + -o jsonpath='{.spec.containers[?(@.name=="clickhouse-backup")].env[?(@.name=="S3_PATH")].value}') +[ -n "$s3_path" ] || { log_error "the clickhouse-backup container sets no S3_PATH"; exit 1; } +archive_prefix="${s3_path%/}/${archive}/" +list_archive_objects "$archive_prefix" >"$workdir/before.txt" +[ -s "$workdir/before.txt" ] \ + || { log_error "the system bucket holds no object under ${archive_prefix}, the archive of Backup ${backup_ref}"; exit 1; } + +log_step "Deleting Backup ${backup_ref} and its archive ${archive}" +if ! kubectl -n "$NAMESPACE" delete backup "$backup_ref" --wait=true --timeout="${BACKUP_DELETE_TIMEOUT}s"; then + log_error "Backup ${backup_ref} was not deleted within ${BACKUP_DELETE_TIMEOUT}s" + kubectl -n "$NAMESPACE" describe backup "$backup_ref" >&2 || true + kubectl -n "$NAMESPACE" logs "job/${backup_ref}-cleanup" --all-containers >&2 || true + exit 1 +fi +# The finalizer holds the Backup until the cleanup Job saw the delete +# answered, so the objects are gone by the time the Backup is. +list_archive_objects "$archive_prefix" >"$workdir/after.txt" +if [ -s "$workdir/after.txt" ]; then + log_error "Backup ${backup_ref} is gone but the system bucket still holds under ${archive_prefix}: $(tr '\n' ' ' <"$workdir/after.txt")" + kubectl -n "$NAMESPACE" get events --field-selector "involvedObject.name=${backup_ref}" >&2 || true + exit 1 +fi +log_success "Deleting Backup ${backup_ref} removed its archive ${archive} from the system bucket" diff --git a/hack/e2e-chainsaw/clickhouse/system-bucket-tls.yaml b/hack/e2e-chainsaw/clickhouse/system-bucket-tls.yaml index 06203a299..dcbf80969 100644 --- a/hack/e2e-chainsaw/clickhouse/system-bucket-tls.yaml +++ b/hack/e2e-chainsaw/clickhouse/system-bucket-tls.yaml @@ -35,7 +35,8 @@ spec: containers: - name: probe image: docker.io/alpine/k8s:1.36.2@sha256:44ef4942e171939b9c665a4a84beb80e2dcdb9a24330d4651cfdfd2e9deecc47 - command: [sleep, "3600"] + # Outlives the step timeouts from here through the run step (68m30s). + command: [sleep, "4800"] securityContext: allowPrivilegeEscalation: false capabilities: