Skip to content

Commit 970191d

Browse files
fix(clickhouse): restore the archive a Backup was taken as (#5208)
## What this PR does A ClickHouse `RestoreJob` restored the newest archive under the app prefix, whichever `Backup` it named. Strategy pod generated the archive name with `date -u` and nothing was recorded on the `Backup`, so restore could only list the remote archives and take the last one. Restoring an older `Backup` brought back the latest data. Now the controller names the archive before it creates the backup Job (`clickhouse-<app>-<startedAt>` from persisted `status.startedAt`, so retried pods write the same one), passes it to the pod as `.ArchiveName` and records it in the `Backup` `driverMetadata`. Restore takes exactly that archive and fails with its name when storage has no such archive. The name is recorded only when the Job's pod got it, so a Job left from the previous controller during an upgrade, or a custom strategy with its own names, leaves no name instead of a wrong one. A retried pod reuses the name, so it waits for an attempt the sidecar still runs (no 423) and asks for `resume`. A `Backup` outlives its `BackupJob` and a Plan names `BackupJob`s after the schedule slot, so a `BackupJob` created again under a used name met the earlier run's `Backup` when its Job completed, took it as its result and left the archive it just wrote recorded nowhere. Now it fails if that `Backup` records another archive, and the message names both. A retry of the same run still gets its own `Backup` back. Old `Backup`s have no recorded name and stay restorable: the pod logs a `WARNING` and takes the newest archive stamped no later than `takenAt`, and fails when nothing qualifies. While the chart rolls out, previous controller pod can still render the new template and pass no `takenAt`, so a restore of a `Backup` without recorded name fails before it touches any table, and works when created again after the rollout. Fixes #5199 Tests are go unit tests for naming, recording, a reused `BackupJob` name and restore render, and `hack/altinity-backup-strategy.bats`, which runs the shipped script against a stubbed clickhouse-backup API (the restore tests go red on the old template). Checked on a live ClickHouse with two backups of 1500 and 2000 rows: restore of the older one by recorded name ends with 1500 rows, fallback for an unnamed older backup picks the same archive with the warning, a missing archive fails without touching the table, a retry over an existing local backup completes under the same name. The controller binary itself was not run on the cluster, only its rendered output in the pod. ### Downstream repositories - [x] No downstream repository is affected by this change - [ ] [cozystack/website](https://github.com/cozystack/website) - follow-up: - [ ] [cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack) - follow-up: - [ ] [cozystack/ansible-cozystack](https://github.com/cozystack/ansible-cozystack) - follow-up: - [ ] [cozystack/ccp](https://github.com/cozystack/ccp) - follow-up: - [ ] [cozystack/talm](https://github.com/cozystack/talm) - follow-up: - [ ] [cozystack/cozyhr](https://github.com/cozystack/cozyhr) - follow-up: - [ ] [cozystack/cozy-proxy](https://github.com/cozystack/cozy-proxy) - follow-up: - [ ] [cozystack/cozystack-telemetry-server](https://github.com/cozystack/cozystack-telemetry-server) - follow-up: - [ ] [cozystack/external-apps-example](https://github.com/cozystack/external-apps-example) - follow-up: - [ ] [cozystack/examples](https://github.com/cozystack/examples) - follow-up: - [ ] [cozystack/community](https://github.com/cozystack/community) - follow-up: ### Release note ```release-note fix(clickhouse): a RestoreJob now restores the archive its Backup was taken as, not the newest one. New Backups record the archive name, Backups taken before this release are restored best effort from the newest archive stamped no later than their takenAt, with a warning in the restore pod log. A ClickHouse BackupJob created again under a name whose Backup still exists now fails instead of reporting that Backup as its result. ``` <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Backups now use a consistent archive name tied to the backup job, and completed backups retain that name for future restores. * Restores can select the recorded archive and backup timestamp. If no archive was recorded, the system selects the newest eligible archive for the application. * **Bug Fixes** * A restore now fails when its recorded archive is missing instead of silently selecting a different one. * Backup requests avoid starting a duplicate action when the matching action is already in progress. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
2 parents 18779dd + d7ae34d commit 970191d

4 files changed

Lines changed: 653 additions & 22 deletions

File tree

‎hack/altinity-backup-strategy.bats‎

Lines changed: 218 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,218 @@
1+
#!/usr/bin/env bats
2+
# Behavioural tests for the shipped Altinity (ClickHouse) backup/restore
3+
# strategy script, extracted from the rendered cozy-default-altinity Strategy
4+
# CR and EXECUTED against a stubbed clickhouse-backup HTTP API, with the real
5+
# jq doing the archive selection. Which archive a restore reads back is
6+
# decided by that selection over list/remote, so it is exercised against
7+
# several archives rather than string-matched.
8+
#
9+
# The script runs with `bash`, not `sh`, for the reason given in
10+
# hack/redis-backup-strategy.bats: it opens `set -euo pipefail`, which the
11+
# production image's busybox ash supports and the CI runner's dash rejects.
12+
13+
load test_helper
14+
15+
CHART=packages/system/backupstrategy-controller
16+
17+
# Render the shipped strategy's in-Pod script into $1 and substitute the
18+
# controller-render placeholders the way the driver fills them: $2 mode, $3
19+
# app (release and source application), $4 the archive name recorded on the
20+
# Backup (empty for a Backup that records none), $5 the Backup name, $6 its
21+
# takenAt in the archive-name layout. An empty render fails early, as does a
22+
# placeholder left unsubstituted.
23+
render_script() {
24+
out=$1; mode=$2; app=$3; archive=$4; backup=$5; takenat=$6
25+
helm template t "$CHART" -n cozy-backup-controller \
26+
--set backupStorage.bucketNameOverride=test-bucket 2>/dev/null \
27+
| yq eval 'select(.kind == "Altinity") | .spec.template.spec.containers[0].args[0]' - \
28+
| sed -e "s#{{ .Mode }}#${mode}#g" \
29+
-e "s#{{ .Release.Name }}#${app}#g" \
30+
-e "s#{{ .Release.Namespace }}#tenant-x#g" \
31+
-e "s#{{ .Backup.ApplicationRef.Name }}#${app}#g" \
32+
-e "s#{{ .Backup.Name }}#${backup}#g" \
33+
-e "s#{{ .ArchiveName | default \"\" }}#${archive}#g" \
34+
-e "s#{{ .Backup.TakenAt | default \"\" }}#${takenat}#g" > "$out"
35+
[ -s "$out" ] || return 1
36+
if grep -q '{{' "$out"; then
37+
echo "rendered script still holds a controller placeholder" >&2
38+
return 1
39+
fi
40+
}
41+
42+
# Stub the clickhouse-backup API behind curl, first on PATH. list/remote
43+
# serves $state/remote; actions serves $state/actions plus one success row per
44+
# operation the script has issued, and after its first read swaps in
45+
# $state/actions.next when a test seeds one (an operation that finishes while
46+
# the script waits). Every request is logged to $state/curl.log. sleep is
47+
# stubbed to fail after a few calls, so a script that never sees its
48+
# operation finish fails the test instead of hanging it.
49+
make_stubs() {
50+
bin=$1; state=$2
51+
mkdir -p "$bin"
52+
: > "$state/remote"
53+
: > "$state/actions"
54+
cat > "$bin/curl" <<STUB
55+
#!/usr/bin/env bash
56+
set -eu
57+
method=GET; url=""
58+
for a in "\$@"; do
59+
case "\$a" in POST) method=POST ;; http://*) url="\$a" ;; esac
60+
done
61+
echo "\$method \$url" >> "$state/curl.log"
62+
case "\$method \$url" in
63+
"GET "*/backup/status) echo '{}' ;;
64+
"GET "*/backup/list/remote) cat "$state/remote" ;;
65+
"GET "*/backup/actions)
66+
cat "$state/actions"
67+
if [ -f "$state/actions.done" ]; then cat "$state/actions.done"; fi
68+
if [ -f "$state/actions.next" ]; then mv "$state/actions.next" "$state/actions"; fi
69+
;;
70+
"POST "*/backup/create_remote*)
71+
name=\${url#*name=}; name=\${name%%&*}
72+
printf '{"command":"create_remote --resume %s","status":"success","start":"2099-01-01 00:00:00"}\n' "\$name" >> "$state/actions.done"
73+
;;
74+
"POST "*/backup/restore_remote/*)
75+
printf '{"command":"restore_remote %s","status":"success","start":"2099-01-01 00:00:00"}\n' "\${url##*/}" >> "$state/actions.done"
76+
;;
77+
*) echo "unexpected request: \$method \$url" >&2; exit 22 ;;
78+
esac
79+
STUB
80+
cat > "$bin/sleep" <<STUB
81+
#!/usr/bin/env bash
82+
n=\$(cat "$state/sleeps" 2>/dev/null || echo 0)
83+
echo \$((n + 1)) > "$state/sleeps"
84+
if [ "\$n" -ge 3 ]; then echo "sleep budget spent: the operation never finished" >&2; exit 1; fi
85+
STUB
86+
chmod 0755 "$bin/curl" "$bin/sleep"
87+
export API_USERNAME=u API_PASSWORD=p
88+
}
89+
90+
# One list/remote row per argument, "name" or "name|desc"; created mirrors
91+
# the name's timestamp, which is the order the pre-fix selection sorted by.
92+
remote_rows() {
93+
for row in "$@"; do
94+
name=${row%%|*}; desc="tar, regular"
95+
if [ "$row" != "$name" ]; then desc=${row#*|}; fi
96+
ts=${name##*-}
97+
printf '{"name":"%s","created":"%s","location":"remote","required":"","desc":"%s"}\n' "$name" "$ts" "$desc"
98+
done
99+
}
100+
101+
@test "an empty render fails the fixture instead of passing as a no-op" {
102+
tmp=$(mktemp -d)
103+
CHART=$tmp/no-such-chart
104+
if render_script "$tmp/s.sh" restore myapp "" bkp 20260304T050622Z 2>/dev/null; then
105+
echo "FAIL: render_script reported success with no chart"
106+
false
107+
fi
108+
rm -rf "$tmp"
109+
}
110+
111+
@test "restore reads back the archive the Backup recorded, not the newest one" {
112+
tmp=$(mktemp -d)
113+
make_stubs "$tmp/bin" "$tmp"
114+
render_script "$tmp/s.sh" restore myapp clickhouse-myapp-20260304T050607Z bkp-a 20260304T050622Z
115+
remote_rows clickhouse-myapp-20260304T040000Z clickhouse-myapp-20260304T050607Z \
116+
clickhouse-myapp-20260304T060000Z clickhouse-myapp-20260304T070000Z > "$tmp/remote"
117+
PATH="$tmp/bin:$PATH" bash "$tmp/s.sh"
118+
grep -qxF 'POST http://chi-clickhouse-myapp-clickhouse-0-0.tenant-x.svc:7171/backup/restore_remote/clickhouse-myapp-20260304T050607Z' "$tmp/curl.log"
119+
[ "$(grep -c '/backup/restore_remote/' "$tmp/curl.log")" -eq 1 ]
120+
rm -rf "$tmp"
121+
}
122+
123+
@test "restore fails naming the recorded archive when remote storage lacks it" {
124+
tmp=$(mktemp -d)
125+
make_stubs "$tmp/bin" "$tmp"
126+
render_script "$tmp/s.sh" restore myapp clickhouse-myapp-20260304T050607Z bkp-a 20260304T050622Z
127+
remote_rows clickhouse-myapp-20260304T040000Z clickhouse-myapp-20260304T060000Z > "$tmp/remote"
128+
out=""
129+
if out=$(PATH="$tmp/bin:$PATH" bash "$tmp/s.sh" 2>&1); then
130+
echo "FAIL: restore succeeded without the recorded archive: $out"
131+
false
132+
fi
133+
printf '%s\n' "$out" | grep -qF 'archive clickhouse-myapp-20260304T050607Z recorded on Backup bkp-a is not in remote storage'
134+
if grep -qF '/backup/restore_remote/' "$tmp/curl.log"; then
135+
echo "FAIL: restored another archive: $(cat "$tmp/curl.log")"
136+
false
137+
fi
138+
rm -rf "$tmp"
139+
}
140+
141+
@test "restore of a Backup without a recorded archive takes the newest one stamped by its takenAt, and warns" {
142+
tmp=$(mktemp -d)
143+
make_stubs "$tmp/bin" "$tmp"
144+
render_script "$tmp/s.sh" restore myapp "" bkp-a 20260304T050800Z
145+
# Each decoy sorts after the expected archive and is ruled out by one
146+
# filter: broken, not a bare timestamp after the prefix, or stamped after
147+
# takenAt.
148+
remote_rows clickhouse-myapp-20260304T040000Z clickhouse-myapp-20260304T050607Z \
149+
"clickhouse-myapp-20260304T050700Z|broken (can't stat metadata.json)" \
150+
clickhouse-myapp-20260304T050710Z-copy \
151+
clickhouse-myapp-20260304T060000Z > "$tmp/remote"
152+
out=$(PATH="$tmp/bin:$PATH" bash "$tmp/s.sh" 2>&1)
153+
grep -qxF 'POST http://chi-clickhouse-myapp-clickhouse-0-0.tenant-x.svc:7171/backup/restore_remote/clickhouse-myapp-20260304T050607Z' "$tmp/curl.log"
154+
[ "$(grep -c '/backup/restore_remote/' "$tmp/curl.log")" -eq 1 ]
155+
printf '%s\n' "$out" | grep -qF 'WARNING: Backup bkp-a records no archive name'
156+
rm -rf "$tmp"
157+
}
158+
159+
@test "restore of a Backup without a recorded archive fails when no archive is stamped by its takenAt" {
160+
tmp=$(mktemp -d)
161+
make_stubs "$tmp/bin" "$tmp"
162+
render_script "$tmp/s.sh" restore myapp "" bkp-a 20260304T050800Z
163+
remote_rows clickhouse-myapp-20260304T060000Z clickhouse-myapp-20260304T070000Z > "$tmp/remote"
164+
out=""
165+
if out=$(PATH="$tmp/bin:$PATH" bash "$tmp/s.sh" 2>&1); then
166+
echo "FAIL: restore succeeded with every archive newer than takenAt: $out"
167+
false
168+
fi
169+
printf '%s\n' "$out" | grep -qF 'no archive of myapp stamped no later than 20260304T050800Z'
170+
if grep -qF '/backup/restore_remote/' "$tmp/curl.log"; then
171+
echo "FAIL: restored an archive newer than takenAt: $(cat "$tmp/curl.log")"
172+
false
173+
fi
174+
rm -rf "$tmp"
175+
}
176+
177+
@test "backup writes the archive under the name the controller chose" {
178+
tmp=$(mktemp -d)
179+
make_stubs "$tmp/bin" "$tmp"
180+
render_script "$tmp/s.sh" backup myapp clickhouse-myapp-20260304T050607Z "" ""
181+
PATH="$tmp/bin:$PATH" bash "$tmp/s.sh"
182+
grep -qxF 'POST http://chi-clickhouse-myapp-clickhouse-0-0.tenant-x.svc:7171/backup/create_remote?name=clickhouse-myapp-20260304T050607Z&resume=true' "$tmp/curl.log"
183+
rm -rf "$tmp"
184+
}
185+
186+
@test "a retried backup waits on the attempt the sidecar is still running" {
187+
tmp=$(mktemp -d)
188+
make_stubs "$tmp/bin" "$tmp"
189+
render_script "$tmp/s.sh" backup myapp clickhouse-myapp-20260304T050607Z "" ""
190+
printf '{"command":"create_remote --resume clickhouse-myapp-20260304T050607Z","status":"in progress","start":"2026-03-04 05:06:08"}\n' > "$tmp/actions"
191+
printf '{"command":"create_remote --resume clickhouse-myapp-20260304T050607Z","status":"success","start":"2026-03-04 05:06:08"}\n' > "$tmp/actions.next"
192+
PATH="$tmp/bin:$PATH" bash "$tmp/s.sh"
193+
# The sidecar answers a second operation with 423 while one runs.
194+
if grep -qF 'POST ' "$tmp/curl.log"; then
195+
echo "FAIL: started another operation over the running one: $(cat "$tmp/curl.log")"
196+
false
197+
fi
198+
rm -rf "$tmp"
199+
}
200+
201+
@test "a retried backup after a failed attempt resumes the same archive" {
202+
tmp=$(mktemp -d)
203+
make_stubs "$tmp/bin" "$tmp"
204+
render_script "$tmp/s.sh" backup myapp clickhouse-myapp-20260304T050607Z "" ""
205+
printf '{"command":"create_remote clickhouse-myapp-20260304T050607Z","status":"error","start":"2026-03-04 05:06:08","error":"S3 PutObject 403"}\n' > "$tmp/actions"
206+
PATH="$tmp/bin:$PATH" bash "$tmp/s.sh"
207+
grep -qxF 'POST http://chi-clickhouse-myapp-clickhouse-0-0.tenant-x.svc:7171/backup/create_remote?name=clickhouse-myapp-20260304T050607Z&resume=true' "$tmp/curl.log"
208+
rm -rf "$tmp"
209+
}
210+
211+
@test "backup falls back to a timestamped name when the controller supplies none" {
212+
tmp=$(mktemp -d)
213+
make_stubs "$tmp/bin" "$tmp"
214+
render_script "$tmp/s.sh" backup myapp "" "" ""
215+
PATH="$tmp/bin:$PATH" bash "$tmp/s.sh"
216+
grep -qE '^POST http://[^ ]*/backup/create_remote\?name=clickhouse-myapp-[0-9]{8}T[0-9]{6}Z&resume=true$' "$tmp/curl.log"
217+
rm -rf "$tmp"
218+
}

‎internal/backupcontroller/altinitystrategy_controller.go‎

Lines changed: 67 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22
package backupcontroller
33

44
import (
5+
"bytes"
56
"context"
7+
"encoding/json"
68
"fmt"
79
"maps"
810
"strings"
@@ -43,6 +45,18 @@ const (
4345
// were in effect at backup time.
4446
altinityParamPrefix = "altinity.strategy.backups.cozystack.io/parameter/"
4547

48+
// altinityArchiveMetaKey records, on the Backup, the clickhouse-backup
49+
// archive its Job wrote, as named by altinityArchiveName. A restore reads
50+
// back exactly that archive: the newest one under the release's prefix
51+
// may belong to a later Backup.
52+
altinityArchiveMetaKey = "altinity.strategy.backups.cozystack.io/archive"
53+
54+
// altinityArchiveTimeLayout is the UTC timestamp that ends an archive
55+
// name. It is fixed-width, so names sharing a prefix sort chronologically
56+
// as plain strings, which is what a restore of a Backup that records no
57+
// archive relies on.
58+
altinityArchiveTimeLayout = "20060102T150405Z"
59+
4660
// Polling cadence for the Altinity Job lifecycle. Mirrors the CNPG /
4761
// Velero strategy cadence so behaviour is uniform across drivers.
4862
altinityPollInterval = 5 * time.Second
@@ -102,14 +116,37 @@ func backupParameters(b *backupsv1alpha1.Backup) map[string]string {
102116
return out
103117
}
104118

119+
// altinityArchiveName mints the archive name for one BackupJob from its
120+
// persisted StartedAt, so every reconcile and every Pod retry of the Job
121+
// writes the same archive. It keeps the clickhouse-<release>-<timestamp>
122+
// shape, because a Backup that records no archive is restored by the
123+
// timestamp in that shape.
124+
func altinityArchiveName(j *backupsv1alpha1.BackupJob) string {
125+
return fmt.Sprintf("clickhouse-%s-%s", j.Spec.ApplicationRef.Name, j.Status.StartedAt.UTC().Format(altinityArchiveTimeLayout))
126+
}
127+
128+
// altinityJobCarriesArchive reports whether the Job's Pod was rendered with
129+
// the archive name. A Job created by a controller that predates archive
130+
// names, or rendered from a strategy that names its own archives, wrote an
131+
// archive under another name, and recording this one would point the Backup
132+
// at an archive that does not exist.
133+
func altinityJobCarriesArchive(job *batchv1.Job, archive string) bool {
134+
spec, err := json.Marshal(job.Spec.Template.Spec)
135+
if err != nil {
136+
return false
137+
}
138+
return bytes.Contains(spec, []byte(archive))
139+
}
140+
105141
// renderAltinityTemplate runs the strategy's PodTemplateSpec through the
106142
// repository's text/template engine with the same context shape as the CNPG
107143
// driver: every string field is templated against the application object,
108-
// the release shorthand, the run mode, and the resolved parameters.
144+
// the release shorthand, the run mode, the archive name, and the resolved
145+
// parameters.
109146
func renderAltinityTemplate(
110147
tmpl corev1.PodTemplateSpec,
111148
app map[string]any,
112-
releaseName, releaseNamespace, mode string,
149+
releaseName, releaseNamespace, mode, archiveName string,
113150
parameters map[string]string,
114151
backup *backupsv1alpha1.Backup,
115152
) (*corev1.PodTemplateSpec, error) {
@@ -119,8 +156,9 @@ func renderAltinityTemplate(
119156
"Name": releaseName,
120157
"Namespace": releaseNamespace,
121158
},
122-
"Mode": mode,
123-
"Parameters": parameters,
159+
"Mode": mode,
160+
"ArchiveName": archiveName,
161+
"Parameters": parameters,
124162
}
125163
if backup != nil {
126164
// Expose ApplicationRef so restore strategies can reference the
@@ -143,6 +181,9 @@ func renderAltinityTemplate(
143181
"Kind": backup.Spec.ApplicationRef.Kind,
144182
"Name": backup.Spec.ApplicationRef.Name,
145183
},
184+
// In the archive-name layout, so a strategy can compare it with
185+
// the timestamp an archive name ends in.
186+
"TakenAt": backup.Spec.TakenAt.UTC().Format(altinityArchiveTimeLayout),
146187
}
147188
}
148189
return template.Template(&tmpl, ctxMap)
@@ -209,12 +250,14 @@ func (r *BackupJobReconciler) reconcileAltinity(ctx context.Context, j *backupsv
209250
return ctrl.Result{}, err
210251
}
211252

253+
archive := altinityArchiveName(j)
212254
rendered, err := renderAltinityTemplate(
213255
strategy.Spec.Template,
214256
app,
215257
j.Spec.ApplicationRef.Name,
216258
j.Namespace,
217259
altinityModeBackup,
260+
archive,
218261
resolved.Parameters,
219262
nil,
220263
)
@@ -239,7 +282,10 @@ func (r *BackupJobReconciler) reconcileAltinity(ctx context.Context, j *backupsv
239282
if j.Status.BackupRef != nil {
240283
return ctrl.Result{}, nil
241284
}
242-
artifact, err := r.createAltinityBackupArtifact(ctx, j, resolved)
285+
if !altinityJobCarriesArchive(batchJob, archive) {
286+
archive = ""
287+
}
288+
artifact, err := r.createAltinityBackupArtifact(ctx, j, resolved, archive)
243289
if err != nil {
244290
return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to create Backup artifact: %v", err))
245291
}
@@ -411,16 +457,20 @@ func jobFailureMessage(j *batchv1.Job) string {
411457
}
412458

413459
// createAltinityBackupArtifact materialises a Cozystack Backup carrying the
414-
// strategy reference and the BackupClassStrategy parameters in effect at
415-
// backup time. Parameters round-trip via DriverMetadata under
416-
// altinityParamPrefix so a later RestoreJob can re-render the strategy
417-
// template against the same values.
460+
// strategy reference, the archive the Job wrote (when known) and the
461+
// BackupClassStrategy parameters in effect at backup time. Parameters
462+
// round-trip via DriverMetadata under altinityParamPrefix so a later
463+
// RestoreJob can re-render the strategy template against the same values.
418464
func (r *BackupJobReconciler) createAltinityBackupArtifact(
419465
ctx context.Context,
420466
j *backupsv1alpha1.BackupJob,
421467
resolved *ResolvedBackupConfig,
468+
archive string,
422469
) (*backupsv1alpha1.Backup, error) {
423470
driverMD := map[string]string{}
471+
if archive != "" {
472+
driverMD[altinityArchiveMetaKey] = archive
473+
}
424474
for k, v := range resolved.Parameters {
425475
driverMD[altinityParamPrefix+k] = v
426476
}
@@ -459,6 +509,13 @@ func (r *BackupJobReconciler) createAltinityBackupArtifact(
459509
if getErr := r.Get(ctx, types.NamespacedName{Namespace: backup.Namespace, Name: backup.Name}, existing); getErr != nil {
460510
return nil, getErr
461511
}
512+
// A Backup outlives its BackupJob, so a BackupJob re-created under a
513+
// used name meets the earlier run's Backup here. Only one recording
514+
// this run's archive was created by an earlier reconcile of this run.
515+
if got := existing.Spec.DriverMetadata[altinityArchiveMetaKey]; got != archive {
516+
return nil, fmt.Errorf("Backup %s/%s already exists and records archive %q, not %q that this run wrote",
517+
backup.Namespace, backup.Name, got, archive)
518+
}
462519
return existing, nil
463520
}
464521
return backup, nil
@@ -616,6 +673,7 @@ func (r *RestoreJobReconciler) reconcileAltinityRestore(ctx context.Context, res
616673
targetAppName,
617674
targetNamespace,
618675
altinityModeRestore,
676+
backup.Spec.DriverMetadata[altinityArchiveMetaKey],
619677
backupParameters(backup),
620678
backup,
621679
)

0 commit comments

Comments
 (0)