Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import {
} from "@lzc/contracts";
import {
assertRetirementProtectedResources,
bucketCleanupErrors,
retirementBuckets,
retirementInventory,
retirementInventorySchema,
retirementPlanProjection,
Expand Down Expand Up @@ -148,6 +150,7 @@ const resultSchema = z.strictObject({
"retirement_runner_stopped_before_apply",
])
.or(retirementPlanFailureCodeSchema)
.or(z.enum(bucketCleanupErrors))
.nullable()
.optional(),
});
Expand Down Expand Up @@ -379,6 +382,24 @@ export class RetirementExecution {
!this.runner.supportsArtifact?.(saved.runner_package_id)
)
throw fail("retirement_artifact_changed");
if (!saved.projection) throw fail("retirement_plan_unavailable");
const savedInput = this.template(session, saved);
const checked = verifyRetirementPlan(
saved.projection,
savedInput.before,
savedInput.baseline,
savedInput.phase,
);
const buckets = retirementBuckets(
checked.deletes,
savedInput.protectedProjectIds,
);
if (
buckets.length &&
(savedInput.bucketCleanupPolicy !== 1 ||
request.confirmBucketContentsDeletion !== true)
)
throw fail("retirement_bucket_cleanup_confirmation_required");
return this.start(
session,
await this.context(session, id, request.generation, saved.scope_id),
Expand All @@ -405,6 +426,7 @@ export class RetirementExecution {
ticket = randomBytes(32).toString("base64url");
const input = templateSchema.parse({
id,
bucketCleanupPolicy: 1,
operation: saved ? "apply" : "plan",
retirementId: context.retirementId,
generation: context.generation,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,21 @@ const phaseLabels: Record<string, string> = {
complete: "Stillgelegt",
};
const errors: Record<string, string> = {
retirement_bucket_cleanup_confirmation_required:
"Erstelle einen neuen Rückbauplan und bestätige die Löschung der Bucket-Inhalte.",
retirement_bucket_cleanup_locked:
"Bucket-Inhalte sind durch Aufbewahrungsfristen oder Legal Hold geschützt. Die Bereinigung umgeht diese Sperren nicht.",
retirement_bucket_cleanup_unavailable:
"Die Bucket-Bereinigung konnte nicht abgeschlossen werden. Prüfe die Ausgabe und den Bereinigungszugang.",
retirement_bucket_cleanup_access_failed:
"Der unabhängige Zugang benötigt Zugriff auf Object Storage und die Inhalte der zu löschenden Buckets.",
retirement_bucket_cleanup_incomplete:
"Die Buckets sind noch nicht vollständig leer. Prüfe laufende Schreibzugriffe und die Ausgabe; erstelle danach einen neuen Plan.",
retirement_bucket_cleanup_credentials_failed:
"Der kurzlebige Bereinigungszugang konnte nicht sicher erstellt oder entfernt werden. Prüfe die Object-Storage-Zugänge des betroffenen Projekts.",
retirement_bucket_cleanup_scope_invalid:
"Der Bucket-Umfang stimmt nicht mit dem geprüften Rückbauplan überein. Erstelle einen neuen Plan.",

retirement_runner_unavailable:
"Die Ausführungsumgebung konnte nicht gestartet werden. Es liegt kein OpenTofu-Ergebnis vor. Aktualisiere den Status und erstelle einen neuen Plan.",
retirement_private_runner_required:
Expand Down Expand Up @@ -134,6 +149,7 @@ export function RetirementExecutionPanel({
const [handoff, setHandoff] = useState(false),
[independent, setIndependent] = useState(false),
[confirmDelete, setConfirmDelete] = useState(false),
[confirmBucketContents, setConfirmBucketContents] = useState(false),
[retention, setRetention] = useState(false);
const [preview, setPreview] = useState<z.infer<typeof previewSchema> | null>(
null,
Expand All @@ -144,6 +160,12 @@ export function RetirementExecutionPanel({
[confirmRecovery, setConfirmRecovery] = useState(false);
const approvalPanel = useRef<HTMLElement | null>(null);
const previewId = preview?.id;
const hasBucketDeletes =
preview?.deletes.some((r) => r.type === "stackit_objectstorage_bucket") ??
false;
useEffect(() => {
if (preview?.id && preview.artifactSha256) setConfirmBucketContents(false);
}, [preview?.id, preview?.artifactSha256]);
useEffect(() => {
if (previewId) approvalPanel.current?.focus({ preventScroll: true });
}, [previewId]);
Expand Down Expand Up @@ -807,6 +829,18 @@ export function RetirementExecutionPanel({
"Ich bestätige die unwiderrufliche Löschung genau dieses geprüften Umfangs.",
)}
</label>
{hasBucketDeletes && (
<label>
<input
type="checkbox"
checked={confirmBucketContents}
onChange={(e) => setConfirmBucketContents(e.target.checked)}
/>
{t(
"Ich bestätige die endgültige Löschung aller Inhalte und Versionen der oben aufgeführten Buckets.",
)}
</label>
)}
{!review?.jobs.some((j) => j.id === preview.id && j.canApply) && (
<p role="status">
{t(
Expand All @@ -823,6 +857,7 @@ export function RetirementExecutionPanel({
busy ||
!retention ||
!confirmDelete ||
(hasBucketDeletes && !confirmBucketContents) ||
!review?.jobs.some((j) => j.id === preview.id && j.canApply)
}
onClick={() =>
Expand All @@ -831,6 +866,9 @@ export function RetirementExecutionPanel({
artifactSha256: preview.artifactSha256,
confirmDestroyResources: true,
confirmDataRetentionReviewed: true,
...(hasBucketDeletes
? { confirmBucketContentsDeletion: true }
: {}),
})
}
>
Expand Down
16 changes: 16 additions & 0 deletions landing-zone-configurator/app/apps/web/src/locales/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4092,4 +4092,20 @@ export const englishMessages: Record<string, string> = {
"This workspace still contains existing Landing Zones. Complete their retirement first.",
"Im Arbeitsbereich läuft noch eine Ausführung oder eine Wiederherstellung ist offen. Schließe diese zuerst ab.":
"An execution or recovery is still pending in this workspace. Complete it before deleting the workspace.",
"Ich bestätige die endgültige Löschung aller Inhalte und Versionen der oben aufgeführten Buckets.":
"I confirm the permanent deletion of all contents and versions in the buckets listed above.",
"Erstelle einen neuen Rückbauplan und bestätige die Löschung der Bucket-Inhalte.":
"Create a new retirement plan and confirm deletion of bucket contents.",
"Bucket-Inhalte sind durch Aufbewahrungsfristen oder Legal Hold geschützt. Die Bereinigung umgeht diese Sperren nicht.":
"Bucket contents are protected by retention periods or legal hold. Cleanup does not bypass these protections.",
"Die Bucket-Bereinigung konnte nicht abgeschlossen werden. Prüfe die Ausgabe und den Bereinigungszugang.":
"Bucket cleanup could not complete. Check the output and cleanup access.",
"Der unabhängige Zugang benötigt Zugriff auf Object Storage und die Inhalte der zu löschenden Buckets.":
"The independent account needs Object Storage access and access to the contents of the buckets being deleted.",
"Die Buckets sind noch nicht vollständig leer. Prüfe laufende Schreibzugriffe und die Ausgabe; erstelle danach einen neuen Plan.":
"The buckets are not completely empty. Check ongoing writes and the output, then create a new plan.",
"Der kurzlebige Bereinigungszugang konnte nicht sicher erstellt oder entfernt werden. Prüfe die Object-Storage-Zugänge des betroffenen Projekts.":
"The temporary cleanup access could not be safely created or removed. Check Object Storage credentials in the affected project.",
"Der Bucket-Umfang stimmt nicht mit dem geprüften Rückbauplan überein. Erstelle einen neuen Plan.":
"The bucket scope does not match the reviewed retirement plan. Create a new plan.",
};
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,14 @@ export async function retirementOutput(
.sort((a, b) => b.length - a.length);
let text = "",
truncated = false;
for (const name of ["init", "validate", "plan", "plan-details", "apply"]) {
for (const name of [
"init",
"validate",
"plan",
"plan-details",
"bucket-cleanup",
"apply",
]) {
for (const stream of ["out", "err"]) {
const file = await open(
join(directory, `${name}.${stream}`),
Expand Down Expand Up @@ -58,7 +65,7 @@ export async function retirementOutput(
: name === "apply"
? "apply retirement.plan"
: name;
const chunk = `$ tofu ${command}${stream === "err" ? " (stderr)" : ""}\n${content}\n`;
const chunk = `$ ${name === "bucket-cleanup" ? "bucket cleanup" : `tofu ${command}`}${stream === "err" ? " (stderr)" : ""}\n${content}\n`;
truncated ||= bytesRead < size || Buffer.byteLength(chunk) > remaining;
text += new TextDecoder().decode(
Buffer.from(chunk).subarray(0, remaining),
Expand Down
62 changes: 61 additions & 1 deletion landing-zone-configurator/app/apps/worker/src/retirement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { spawn } from "node:child_process";
import { createHash } from "node:crypto";
import { constants } from "node:fs";
import {
appendFile,
cp,
lstat,
mkdtemp,
Expand All @@ -19,10 +20,13 @@ import {
} from "@lzc/contracts";
import {
assertRetirementProtectedResources,
bucketCleanupErrors,
emptyRetirementBuckets,
parseServiceAccountKey,
readApplicationExecutionManifest,
readRetirementSource,
retirementAdapterCommit,
retirementBuckets,
retirementCompletedDeletes,
retirementFolderConflict,
retirementInventory,
Expand Down Expand Up @@ -58,6 +62,7 @@ export type RetirementWorkerOptions = {
report?: Report;
recoveryRetryMilliseconds?: number;
fetch?: typeof fetch;
bucketCleanup?: typeof emptyRetirementBuckets;
};
async function bounded(path: string) {
const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
Expand Down Expand Up @@ -448,7 +453,62 @@ export async function runRetirementWorker(
await report("result", { status: "succeeded" });
return "succeeded";
}
await report("stage", { stage: "applying" });
let applyingStage = false;
const beginApplying = async () => {
await report("stage", { stage: "applying" });
applyingStage = true;
};
const buckets = retirementBuckets(
checked.deletes,
input.protectedProjectIds,
);
if (buckets.length) {
if (input.bucketCleanupPolicy !== 1)
throw Error("retirement_bucket_cleanup_confirmation_required");
const progressFile = join(work, "bucket-cleanup.out");
await writeFile(progressFile, "", { mode: 0o600, flag: "wx" });
const progress = async (line: string) => {
await appendFile(progressFile, line, { mode: 0o600 });
await publishOutput();
};
try {
await (options.bucketCleanup ?? emptyRetirementBuckets)({
buckets,
key: input.key,
jobId: input.id,
deadline,
...(options.fetch ? { request: options.fetch } : {}),
progress,
beforeDelete: beginApplying,
});
} catch (error) {
const code = bucketCleanupErrors.includes(
(error as Error).message as (typeof bucketCleanupErrors)[number],
)
? (error as Error).message
: "retirement_bucket_cleanup_unavailable";
await progress(
`Bucket cleanup stopped: ${code}. OpenTofu Apply has not started.\n`,
);
const unchanged = await readRetirementBackendState(
input.backend.address,
options.ticket,
deadline,
options.fetch,
);
if (retirementStateSha256(unchanged) !== input.beforeStateSha256)
throw Error("retirement_state_changed");
await report("result", {
status: "failed",
stateSha256: input.beforeStateSha256,
removed: [],
completedDeletes: [],
errorCode: code,
});
return "failed";
}
}
if (!applyingStage) await beginApplying();
const applied = await command(
"apply",
[
Expand Down
Loading
Loading