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 <aleksei.artamonov@aenix.io>
This commit is contained in:
Alexey Artamonov authored and Aleksei Sviridkin committed 2026-11-23 12:15:04 +03:00
1 parent 319c2c81f7
commit b62f2f385f
2 files changed
+189 -4

No files matched your search

@@ -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)
}
}
@@ -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
}