forgedock 1.59.2 → 1.60.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/engine/outcome-codes.mjs +3 -3
- package/bin/engine-cli.mjs +50 -10
- package/bin/labels.json +5 -0
- package/bin/lean/batch.mjs +21 -2
- package/bin/lean/batch.test.mjs +116 -1
- package/bin/lean/conformance.mjs +12 -5
- package/bin/lean/conformance.test.mjs +30 -2
- package/bin/lean/depcache.mjs +34 -15
- package/bin/lean/depcache.test.mjs +100 -1
- package/bin/lean/design-gate.mjs +15 -10
- package/bin/lean/design-gate.test.mjs +21 -0
- package/bin/lean/effects.mjs +18 -2
- package/bin/lean/execution.mjs +23 -5
- package/bin/lean/execution.test.mjs +81 -1
- package/bin/lean/gatewatch.test.mjs +5 -5
- package/bin/lean/issuewatch-triage.mjs +68 -0
- package/bin/lean/issuewatch-triage.test.mjs +98 -0
- package/bin/lean/issuewatch.mjs +34 -6
- package/bin/lean/issuewatch.test.mjs +11 -0
- package/bin/lean/lanelock.mjs +5 -4
- package/bin/lean/lean.mjs +123 -17
- package/bin/lean/lean.test.mjs +154 -6
- package/bin/lean/orchestrate-cancel.test.mjs +33 -0
- package/bin/lean/orchestrate-hostfallback.test.mjs +41 -0
- package/bin/lean/orchestrate-recovering.test.mjs +42 -0
- package/bin/lean/orchestrate.mjs +23 -10
- package/bin/lean/pagegate.mjs +50 -12
- package/bin/lean/pagegate.test.mjs +38 -1
- package/bin/lean/phaseledger.mjs +65 -2
- package/bin/lean/phaseledger.test.mjs +70 -2
- package/bin/lean/preflight.mjs +5 -2
- package/bin/lean/preflight.test.mjs +7 -0
- package/bin/lean/prompts.mjs +2 -1
- package/bin/lean/recovery.test.mjs +11 -6
- package/bin/lean/release-classify.mjs +143 -0
- package/bin/lean/release-classify.test.mjs +130 -0
- package/bin/lean/release-conductor.mjs +163 -0
- package/bin/lean/release-conductor.test.mjs +194 -0
- package/bin/lean/release-config.mjs +60 -8
- package/bin/lean/release-config.test.mjs +43 -1
- package/bin/lean/release-control.mjs +22 -5
- package/bin/lean/release-control.test.mjs +22 -0
- package/bin/lean/release-credentials.mjs +40 -0
- package/bin/lean/release-credentials.test.mjs +42 -0
- package/bin/lean/release-deploy.mjs +3 -3
- package/bin/lean/release-deploy.test.mjs +8 -0
- package/bin/lean/release-docs.test.mjs +93 -0
- package/bin/lean/release-fence.mjs +2 -0
- package/bin/lean/release-gate.mjs +88 -0
- package/bin/lean/release-gate.test.mjs +116 -0
- package/bin/lean/release-gates.mjs +5 -1
- package/bin/lean/release-ledger.mjs +47 -1
- package/bin/lean/release-ledger.test.mjs +33 -1
- package/bin/lean/release-mergeback.mjs +148 -0
- package/bin/lean/release-mergeback.test.mjs +129 -0
- package/bin/lean/release-p0.mjs +193 -0
- package/bin/lean/release-p0.test.mjs +127 -0
- package/bin/lean/release-plan.mjs +267 -0
- package/bin/lean/release-plan.test.mjs +202 -0
- package/bin/lean/release-preflight.mjs +16 -0
- package/bin/lean/release-regate.mjs +141 -0
- package/bin/lean/release-regate.test.mjs +149 -0
- package/bin/lean/release-review.mjs +5 -3
- package/bin/lean/release-rollback.mjs +277 -0
- package/bin/lean/release-rollback.test.mjs +245 -0
- package/bin/lean/release-snapshot.mjs +48 -9
- package/bin/lean/release-snapshot.test.mjs +43 -1
- package/bin/lean/release-start.mjs +164 -0
- package/bin/lean/release-start.test.mjs +171 -0
- package/bin/lean/release-status.mjs +6 -2
- package/bin/lean/release-train.mjs +159 -0
- package/bin/lean/release-train.test.mjs +139 -0
- package/bin/lean/release.mjs +127 -5
- package/bin/lean/release.test.mjs +80 -0
- package/bin/lean/sandbox-remote.mjs +2 -0
- package/bin/lean/schedd-load.test.mjs +82 -0
- package/bin/lean/schedd.mjs +67 -31
- package/bin/lean/schedd.test.mjs +80 -1
- package/bin/lean/validate-catalog.mjs +94 -0
- package/bin/lean/validate-catalog.test.mjs +42 -0
- package/bin/pool/agent.mjs +4 -1
- package/bin/pool/lane-tools.mjs +115 -0
- package/bin/pool/lane-tools.test.mjs +26 -0
- package/bin/pool/warm.mjs +1 -1
- package/docs/CONFIG.md +225 -1
- package/docs/ISSUE-WATCH.md +1 -0
- package/docs/design/visual-gate.md +10 -0
- package/docs/eval/adversarial-bench.md +1 -0
- package/package.json +1 -1
- package/pool/README.md +2 -0
- package/scripts/bench-adversarial.mjs +4 -0
- package/scripts/bench-lightlane.mjs +2 -1
- package/templates/github-actions/forge-conductor.scopes.json +7 -0
- package/templates/github-actions/forge-conductor.yml +57 -0
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* Gate-only fix lane (#5584, epic #5549 N5, rule R4): `forgedock release control regate <id> --ref <fix> --reason ...`
|
|
5
|
+
* re-evaluates the gates of an already-deployed release sha with the gate code of the fix ref, without a merge cycle.
|
|
6
|
+
* `classifyGateOnly` decides from the changed paths whether the fix is limited to gate artifacts; anything that ships in an
|
|
7
|
+
* image (app, migration, image path, a workflow hunk outside `gates.workflow_steps`) is the normal lane. `regatePlan` refuses
|
|
8
|
+
* closed (no recorded live record/rollback target, a run-set freeze with migration evidence, not gate-only); `regateDispatch`
|
|
9
|
+
* sends the one fenced dispatch (`forge_epoch`, never `override_freeze`, I26) and records the gate-script sha. Nothing here
|
|
10
|
+
* runs unless the verb is called.
|
|
11
|
+
*/
|
|
12
|
+
import { createHash } from "node:crypto";
|
|
13
|
+
import { buildDispatchArgs } from "./release-control.mjs";
|
|
14
|
+
import { fenced } from "./release-fence.mjs";
|
|
15
|
+
import { acquireLease } from "./release-ledger.mjs";
|
|
16
|
+
import { parseGatesConfig } from "./release-gates.mjs";
|
|
17
|
+
import { MIGRATION_PATHS } from "./release-config.mjs";
|
|
18
|
+
|
|
19
|
+
export const IMAGE_PATH = /(^|\/)(Dockerfile[^/]*|[^/]*\.dockerfile|docker-compose[^/]*\.ya?ml|\.dockerignore)$/i;
|
|
20
|
+
export const WORKFLOW_PATH = /^\.github\/workflows\/[^/]+\.ya?ml$/;
|
|
21
|
+
|
|
22
|
+
const reOf = (g) => new RegExp(`^${g.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*\//g, "\u0000").replace(/\*\*/g, "\u0001").replace(/\*/g, "[^/]*").replace(/\u0000/g, "(?:.*/)?").replace(/\u0001/g, ".*")}$`);
|
|
23
|
+
export const releaseRegateMatchesAny = (path, globs) => globs.some((g) => reOf(g).test(path));
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* @param {string[]} changedPaths files changed between the failed release sha and the candidate fix
|
|
27
|
+
* @param {object} policy release policy (`gates.paths`, `gates.workflow_steps`)
|
|
28
|
+
* @param {{workflowSteps?: Record<string, Array<string|null>>}} [o] per workflow file, the step name (null: outside any step) of each changed hunk
|
|
29
|
+
* @returns {{gateOnly: boolean, offenders: {path: string, kind: string}[]}}
|
|
30
|
+
*/
|
|
31
|
+
export function classifyGateOnly(changedPaths, policy, { workflowSteps = {} } = {}) {
|
|
32
|
+
const cfg = parseGatesConfig(policy), offenders = [];
|
|
33
|
+
for (const path of changedPaths) {
|
|
34
|
+
let kind = null;
|
|
35
|
+
if (releaseRegateMatchesAny(path, MIGRATION_PATHS)) kind = "migration";
|
|
36
|
+
else if (IMAGE_PATH.test(path)) kind = "image";
|
|
37
|
+
else if (WORKFLOW_PATH.test(path)) {
|
|
38
|
+
const steps = workflowSteps[path];
|
|
39
|
+
if (!Array.isArray(steps) || !steps.length || steps.some((s) => s == null || !cfg.workflowSteps.includes(s))) kind = "workflow-hunk";
|
|
40
|
+
} else if (!releaseRegateMatchesAny(path, cfg.paths)) kind = "app";
|
|
41
|
+
if (kind) offenders.push({ path, kind });
|
|
42
|
+
}
|
|
43
|
+
return { gateOnly: !!changedPaths.length && !offenders.length, offenders };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The step name each changed hunk of workflow `file` (between `base` and `ref`) lies in; null for a line outside any named step. */
|
|
47
|
+
export function hunkSteps(io, base, ref, file) {
|
|
48
|
+
const diff = String(io.git(["diff", "-U0", `${base}..${ref}`, "--", file]));
|
|
49
|
+
const lines = String(io.git(["show", `${ref}:${file}`])).split("\n");
|
|
50
|
+
const indent = (l) => l.length - l.trimStart().length;
|
|
51
|
+
const items = [];
|
|
52
|
+
lines.forEach((l, i) => {
|
|
53
|
+
if (!/^\s*-\s/.test(l)) return;
|
|
54
|
+
const ind = indent(l);
|
|
55
|
+
let end = i + 1;
|
|
56
|
+
while (end < lines.length && (!lines[end].trim() || lines[end].trim().startsWith("#") || indent(lines[end]) > ind || (indent(lines[end]) === ind && !/^\s*-\s/.test(lines[end])))) end++;
|
|
57
|
+
let name = null;
|
|
58
|
+
for (let j = i; j < end; j++) { const m = new RegExp(`^\\s{${j === i ? ind : ind + 2}}(?:-\\s+)?name:\\s*["']?(.+?)["']?\\s*$`).exec(lines[j]); if (m) { name = m[1]; break; } }
|
|
59
|
+
if (name) items.push({ start: i, end, name });
|
|
60
|
+
});
|
|
61
|
+
const out = [];
|
|
62
|
+
for (const m of diff.matchAll(/^@@ -\S+ \+(\d+)(?:,(\d+))? @@/gm)) {
|
|
63
|
+
const c = Number(m[1]), d = m[2] === undefined ? 1 : Number(m[2]);
|
|
64
|
+
const from = Math.max(c - 1, 0), to = d === 0 ? from : c - 2 + d; // 0-based inclusive; a pure deletion maps to the line it follows
|
|
65
|
+
for (let ln = from; ln <= to; ln++) out.push(items.filter((it) => it.start <= ln && ln < it.end).pop()?.name ?? null);
|
|
66
|
+
}
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const rev = (io, r) => String(io.git(["rev-parse", "--verify", `${r}^{commit}`])).trim();
|
|
71
|
+
|
|
72
|
+
/** sha1 over `path blob` of each changed gate path at `ref`: identifies the gate code that evaluates. */
|
|
73
|
+
export function gateScriptSha(io, ref, paths) {
|
|
74
|
+
const lines = [...paths].sort().map((p) => { let b = "deleted"; try { b = String(io.git(["rev-parse", `${ref}:${p}`])).trim(); } catch { /* deleted at ref */ } return `${p} ${b}`; });
|
|
75
|
+
return createHash("sha1").update(lines.join("\n")).digest("hex");
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Every refusal happens before anything is written or dispatched.
|
|
80
|
+
* `ctx`: {io, repo, policy, state}; `args`: {ref, gateFixRef?}.
|
|
81
|
+
* @returns {{refuse: string} | {plan: {sha, refName, ref, gateSha, gateFixRef, workflow, changed}}}
|
|
82
|
+
*/
|
|
83
|
+
export async function regatePlan({ io, repo, policy, state }, { ref, gateFixRef = null }) {
|
|
84
|
+
const d = state?.deploy;
|
|
85
|
+
if (!d?.target?.sha || !d.merge) return { refuse: "no recorded live record/rollback target for this release (I9); nothing to re-evaluate" };
|
|
86
|
+
if (!ref) return { refuse: "--ref <fix branch or sha> is required" };
|
|
87
|
+
const workflow = policy?.verify?.workflow;
|
|
88
|
+
if (!workflow) return { refuse: "policy verify.workflow is not set; nothing to dispatch" };
|
|
89
|
+
let refSha, changed;
|
|
90
|
+
try {
|
|
91
|
+
refSha = rev(io, ref);
|
|
92
|
+
changed = String(io.git(["diff", "--name-only", `${d.merge}..${refSha}`])).split("\n").filter(Boolean);
|
|
93
|
+
} catch (e) { return { refuse: `cannot diff ${String(d.merge).slice(0, 8)}..${ref}: ${String(e?.message ?? e).split("\n")[0]}` }; }
|
|
94
|
+
const name = policy?.deploy?.freeze_variable;
|
|
95
|
+
if (name) {
|
|
96
|
+
let v = ""; try { v = String(await io.gh(["variable", "get", name, "--repo", repo])).trim(); } catch { /* unset */ }
|
|
97
|
+
if (v && !d.freezeBefore) { // set during the deploy: the run froze it
|
|
98
|
+
let mig;
|
|
99
|
+
try { mig = String(io.git(["diff", "--name-only", `${d.target.sha}..${d.merge}`, "--", ...MIGRATION_PATHS])).split("\n").filter(Boolean); } catch { mig = ["(unreadable)"]; }
|
|
100
|
+
if (mig.length) return { refuse: `${name} was set by the run and migration evidence exists (${mig[0]}); a human decides with override_freeze (I26)` };
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
let workflowSteps = {};
|
|
104
|
+
try { for (const f of changed.filter((p) => WORKFLOW_PATH.test(p))) workflowSteps[f] = hunkSteps(io, d.merge, refSha, f); } catch { workflowSteps = {}; }
|
|
105
|
+
const c = classifyGateOnly(changed, policy, { workflowSteps });
|
|
106
|
+
if (!c.gateOnly) return { refuse: `not a gate-only fix; use the normal lane (${c.offenders.slice(0, 3).map((o) => `${o.path}: ${o.kind}`).join(", ") || "no changed paths"})` };
|
|
107
|
+
if ((state.regates ?? []).some((r) => r.ref === refSha)) return { refuse: `${refSha.slice(0, 8)} was already re-evaluated for this release` };
|
|
108
|
+
return { plan: { sha: d.merge, refName: ref, ref: refSha, gateSha: gateScriptSha(io, refSha, changed), gateFixRef, workflow, changed } };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The lease that fences the dispatch (own epoch, `forge_epoch` input); no `io.api`: unmanaged, no fence. */
|
|
112
|
+
async function takeFence(ctx, holder) {
|
|
113
|
+
if (!ctx.io.api) return { fence: null };
|
|
114
|
+
const lctx = { io: ctx.io, repo: ctx.repo, credential: "driver" };
|
|
115
|
+
const l = await acquireLease(lctx, { holder, release: ctx.state.id, issue: ctx.state.steps?.["release-pr"]?.result?.pr, ttlS: 300, now: ctx.io.now() });
|
|
116
|
+
if (!l.ok) return { refused: l.refused ?? "lease lost the race" };
|
|
117
|
+
const record = async (rec) => { const a = (ctx.state.intents ??= []); const i = a.findIndex((x) => x.key === rec.key); if (i < 0) a.push(rec); else a[i] = rec; ctx.save?.(); };
|
|
118
|
+
return { fence: { lctx, lease: l.lease, record, now: () => new Date(ctx.io.now()).toISOString() } };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* One fenced dispatch of the verification workflow at the fix ref for the same release sha. LIVE_CHECK (I28) is the
|
|
123
|
+
* workflow's and the caller's: the live record is not touched here.
|
|
124
|
+
* @returns {Promise<{ok: true, entry} | {refused: string}>}
|
|
125
|
+
*/
|
|
126
|
+
export async function regateDispatch(ctx, plan, { actor, host }) {
|
|
127
|
+
const { io, repo, state } = ctx;
|
|
128
|
+
const f = ctx.fence ? { fence: ctx.fence } : await takeFence(ctx, io.holder ?? `host-${process.pid}`);
|
|
129
|
+
if (f.refused) return { refused: f.refused };
|
|
130
|
+
const inputs = { sha: plan.sha, regate: "true", gate_sha: plan.gateSha, ...(plan.gateFixRef ? { gate_fix_ref: plan.gateFixRef } : {}) };
|
|
131
|
+
let epoch = null;
|
|
132
|
+
const r = await fenced(f.fence, { action: "dispatch", key: `${state.id}:regate:${f.fence?.lease?.epoch ?? 0}:${plan.ref}` }, (e) => {
|
|
133
|
+
epoch = e;
|
|
134
|
+
return io.gh(buildDispatchArgs({ workflow: plan.workflow, repo, ref: plan.refName, inputs: { ...inputs, ...(e != null ? { forge_epoch: e } : {}) } }));
|
|
135
|
+
});
|
|
136
|
+
if (r.refused) return { refused: `dispatch ${r.refused}` };
|
|
137
|
+
const entry = { at: new Date(io.now?.() ?? Date.now()).toISOString(), ref: plan.ref, sha: plan.sha, gate_sha: plan.gateSha, ...(plan.gateFixRef ? { gate_fix_ref: plan.gateFixRef } : {}), workflow: plan.workflow, actor, host: host ?? null, forge_epoch: epoch };
|
|
138
|
+
(state.regates ??= []).push(entry);
|
|
139
|
+
ctx.save?.();
|
|
140
|
+
return { ok: true, entry };
|
|
141
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
import { describe, it } from "node:test";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { classifyGateOnly, hunkSteps, gateScriptSha } from "./release-regate.mjs";
|
|
6
|
+
import { runControl, VERBS } from "./release-control.mjs";
|
|
7
|
+
import { gateRecord, parseGatesConfig } from "./release-gates.mjs";
|
|
8
|
+
|
|
9
|
+
const POLICY = { gates: { workflow_steps: ["Smoke"] }, verify: { workflow: "verify-release.yml" }, deploy: { freeze_variable: "DEPLOY_FREEZE" } };
|
|
10
|
+
const WF = ".github/workflows/deploy.yml";
|
|
11
|
+
const WF_TEXT = ["name: d", "jobs:", " j:", " steps:", " - name: Build", " run: make", " - name: Smoke", " run: ./s.sh", ""].join("\n");
|
|
12
|
+
|
|
13
|
+
describe("classifyGateOnly (#5584)", () => {
|
|
14
|
+
it("a gate-path-only diff is gate-only", () => {
|
|
15
|
+
const r = classifyGateOnly(["scripts/deploy/a.sh", "scripts/lib/b.sh", "scripts/prod-smoke-test.sh", "tests/gates/x.json"], POLICY);
|
|
16
|
+
assert.equal(r.gateOnly, true);
|
|
17
|
+
});
|
|
18
|
+
it("an app path, a migration path and an image path each flip it", () => {
|
|
19
|
+
for (const [p, kind] of [["src/app.ts", "app"], ["db/migrations/001.sql", "migration"], ["scripts/deploy/migrations/2.sql", "migration"], ["docker/Dockerfile.api", "image"], ["Dockerfile", "image"]]) {
|
|
20
|
+
const r = classifyGateOnly(["scripts/deploy/a.sh", p], POLICY);
|
|
21
|
+
assert.equal(r.gateOnly, false, p);
|
|
22
|
+
assert.deepEqual(r.offenders, [{ path: p, kind }]);
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
it("a workflow file qualifies only when every hunk lies in a listed step", () => {
|
|
26
|
+
assert.equal(classifyGateOnly([WF], POLICY, { workflowSteps: { [WF]: ["Smoke"] } }).gateOnly, true);
|
|
27
|
+
assert.equal(classifyGateOnly([WF], POLICY, { workflowSteps: { [WF]: ["Smoke", "Build"] } }).gateOnly, false);
|
|
28
|
+
assert.equal(classifyGateOnly([WF], POLICY, { workflowSteps: { [WF]: [null] } }).gateOnly, false);
|
|
29
|
+
assert.equal(classifyGateOnly([WF], POLICY).gateOnly, false);
|
|
30
|
+
});
|
|
31
|
+
it("custom gates.paths replace the default allowlist; no changes is not gate-only", () => {
|
|
32
|
+
assert.equal(classifyGateOnly(["ops/x.sh"], { gates: { paths: ["ops/**"] } }).gateOnly, true);
|
|
33
|
+
assert.equal(classifyGateOnly(["scripts/deploy/a.sh"], { gates: { paths: ["ops/**"] } }).gateOnly, false);
|
|
34
|
+
assert.equal(classifyGateOnly([], POLICY).gateOnly, false);
|
|
35
|
+
assert.ok(parseGatesConfig({}).paths.includes("scripts/deploy/**"));
|
|
36
|
+
});
|
|
37
|
+
it("hunkSteps maps changed lines to step names", () => {
|
|
38
|
+
const io = { git: (a) => (a[0] === "diff" ? "@@ -8 +8 @@\n-x\n+y\n@@ -6,0 +6,1 @@\n+z\n@@ -5 +5 @@\n+q\n" : WF_TEXT) };
|
|
39
|
+
assert.deepEqual(hunkSteps(io, "a", "b", WF), ["Smoke", "Build", "Build"]);
|
|
40
|
+
});
|
|
41
|
+
it("a gate record keeps a valid gate_sha", () => {
|
|
42
|
+
assert.equal(gateRecord({ gate: "g", outcome: "pass", gate_sha: "abcdef1" }).gate_sha, "abcdef1");
|
|
43
|
+
assert.equal(gateRecord({ gate: "g", outcome: "pass", gate_sha: "zz" }).gate_sha, undefined);
|
|
44
|
+
});
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
// A tiny in-memory GitHub for the control path, as in release-control.test.mjs.
|
|
48
|
+
function world({ changed = ["scripts/prod-smoke-test.sh"], deploy = { target: { sha: "t0" }, merge: "m1" }, freezeVar = "", migrations = "" } = {}) {
|
|
49
|
+
const w = { active: { epoch: 1, lease: { holder: "A", epoch: 1, release: "r20260101-000000-1", issue: 9 } }, controls: "", comments: [], gh: [], files: {}, sha: 0, saved: 0 };
|
|
50
|
+
w.state = { id: "r20260101-000000-1", deploy, steps: { "release-pr": { result: { pr: 9 } } } };
|
|
51
|
+
w.rel = { load: () => w.state, save: () => { w.saved++; } };
|
|
52
|
+
w.io = {
|
|
53
|
+
now: () => 1_700_000_000_000, holder: "h", print: () => {},
|
|
54
|
+
git: (a) => {
|
|
55
|
+
if (a[0] === "rev-parse") return a[a.length - 1].includes(":") ? "b10b" : "f1f1f1f1";
|
|
56
|
+
if (a[0] === "diff" && a.includes("--name-only")) return a.includes("--") ? migrations : changed.join("\n");
|
|
57
|
+
throw new Error(`git ${a.join(" ")}`);
|
|
58
|
+
},
|
|
59
|
+
gh: async (a) => { w.gh.push(a); if (a[0] === "variable") { if (!freezeVar) throw new Error("not set"); return freezeVar; } return ""; },
|
|
60
|
+
api: async (method, path, body) => {
|
|
61
|
+
if (method === "GET" && /git\/ref\/heads\/_active$/.test(path)) return { object: { sha: "h0" } };
|
|
62
|
+
if (method === "GET" && /contents\/active\.json/.test(path)) return { content: Buffer.from(JSON.stringify(w.active)).toString("base64") };
|
|
63
|
+
if (method === "GET" && /contents\/controls\.jsonl/.test(path)) return { content: Buffer.from(w.controls).toString("base64") };
|
|
64
|
+
if (method === "GET" && /git\/commits\//.test(path)) return { tree: { sha: "t0" } };
|
|
65
|
+
if (method === "POST" && /git\/trees/.test(path)) { for (const t of body.tree) w.files[t.path] = t.content; return { sha: "t1" }; }
|
|
66
|
+
if (method === "POST" && /git\/commits/.test(path)) return { sha: `c${++w.sha}` };
|
|
67
|
+
if (method === "PATCH" && /git\/refs/.test(path)) { w.active = JSON.parse(w.files["active.json"]); w.controls = w.files["controls.jsonl"] ?? w.controls; return {}; }
|
|
68
|
+
if (method === "POST" && /issues\/\d+\/comments/.test(path)) { w.comments.push(body.body); return { id: w.comments.length }; }
|
|
69
|
+
throw new Error(`unrouted ${method} ${path}`);
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
return w;
|
|
73
|
+
}
|
|
74
|
+
const RID = "r20260101-000000-1";
|
|
75
|
+
const run = (w, argv, extra = {}) => runControl("regate", [RID, "--reason", "fix smoke", ...argv], { io: w.io, repo: "o/r", actor: "op", host: "h1", now: 1_700_000_000_000, policy: POLICY, rel: w.rel, ...extra });
|
|
76
|
+
const auditLine = (w) => w.controls.trim().split("\n").map((l) => JSON.parse(l)).filter((l) => l.verb === "regate").pop();
|
|
77
|
+
const dispatches = (w) => w.gh.filter((a) => a[0] === "workflow");
|
|
78
|
+
|
|
79
|
+
describe("regate verb (#5584)", () => {
|
|
80
|
+
it("is a control verb", () => assert.ok(VERBS.includes("regate")));
|
|
81
|
+
it("replay of 11-12: one fenced dispatch at the fix ref for the same sha, no merge", async () => {
|
|
82
|
+
const w = world();
|
|
83
|
+
const r = await run(w, ["--ref", "fix/smoke"]);
|
|
84
|
+
assert.equal(r.ok, true, r.error);
|
|
85
|
+
const d = dispatches(w);
|
|
86
|
+
assert.equal(d.length, 1);
|
|
87
|
+
assert.deepEqual(d[0].slice(0, 7), ["workflow", "run", "verify-release.yml", "--repo", "o/r", "--ref", "fix/smoke"]);
|
|
88
|
+
const inputs = Object.fromEntries(d[0].filter((x) => x.includes("=")).map((x) => x.split("=")));
|
|
89
|
+
assert.equal(inputs.sha, "m1");
|
|
90
|
+
assert.equal(inputs.regate, "true");
|
|
91
|
+
assert.match(inputs.forge_epoch, /^\d+$/);
|
|
92
|
+
assert.equal(inputs.override_freeze, undefined);
|
|
93
|
+
assert.equal(w.gh.filter((a) => a[0] === "pr").length, 0, "no merge");
|
|
94
|
+
assert.equal(w.state.regates.length, 1);
|
|
95
|
+
assert.equal(w.state.regates[0].gate_sha, inputs.gate_sha);
|
|
96
|
+
});
|
|
97
|
+
it("the audit entry carries the gate-script sha and the actor", async () => {
|
|
98
|
+
const w = world();
|
|
99
|
+
const r = await run(w, ["--ref", "fix/smoke"]);
|
|
100
|
+
const line = auditLine(w);
|
|
101
|
+
assert.equal(line.verb, "regate");
|
|
102
|
+
assert.equal(line.actor, "op");
|
|
103
|
+
assert.match(line.after.gate_sha, /^[0-9a-f]{40}$/);
|
|
104
|
+
assert.equal(line.after.gate_sha, r.entry.after.gate_sha);
|
|
105
|
+
assert.equal(line.after.gate_sha, gateScriptSha(w.io, "f1f1f1f1", ["scripts/prod-smoke-test.sh"]));
|
|
106
|
+
});
|
|
107
|
+
it("gate_fix_ref rides the dispatch for a hotfix and is recorded", async () => {
|
|
108
|
+
const w = world();
|
|
109
|
+
const r = await run(w, ["--ref", "fix/smoke", "--gate-fix-ref", "hotfix/9"]);
|
|
110
|
+
assert.equal(r.ok, true, r.error);
|
|
111
|
+
assert.ok(dispatches(w)[0].includes("gate_fix_ref=hotfix/9"));
|
|
112
|
+
assert.equal(w.state.regates[0].gate_fix_ref, "hotfix/9");
|
|
113
|
+
assert.equal(auditLine(w).after.gate_fix_ref, "hotfix/9");
|
|
114
|
+
});
|
|
115
|
+
it("refuses with no recorded live record/rollback target", async () => {
|
|
116
|
+
const w = world({ deploy: null });
|
|
117
|
+
const r = await run(w, ["--ref", "fix/smoke"]);
|
|
118
|
+
assert.equal(r.ok, false);
|
|
119
|
+
assert.match(r.error, /no recorded live record/);
|
|
120
|
+
assert.equal(dispatches(w).length, 0);
|
|
121
|
+
assert.equal(w.controls, "");
|
|
122
|
+
});
|
|
123
|
+
it("refuses a run-set freeze with migration evidence, never sending override_freeze", async () => {
|
|
124
|
+
const w = world({ freezeVar: "1", migrations: "db/migrations/9.sql" });
|
|
125
|
+
const r = await run(w, ["--ref", "fix/smoke"]);
|
|
126
|
+
assert.equal(r.ok, false);
|
|
127
|
+
assert.match(r.error, /migration evidence/);
|
|
128
|
+
assert.equal(dispatches(w).length, 0);
|
|
129
|
+
const pre = world({ freezeVar: "1", migrations: "db/migrations/9.sql", deploy: { target: { sha: "t0" }, merge: "m1", freezeBefore: "1" } });
|
|
130
|
+
assert.equal((await run(pre, ["--ref", "fix/smoke"])).ok, true, "a freeze set before the deploy is not the run's");
|
|
131
|
+
});
|
|
132
|
+
it("refuses a non-gate-only fix and a repeated ref", async () => {
|
|
133
|
+
const w = world({ changed: ["scripts/prod-smoke-test.sh", "src/app.ts"] });
|
|
134
|
+
assert.match((await run(w, ["--ref", "f"])).error, /not a gate-only fix/);
|
|
135
|
+
const w2 = world();
|
|
136
|
+
assert.equal((await run(w2, ["--ref", "f"])).ok, true);
|
|
137
|
+
assert.match((await run(w2, ["--ref", "f"])).error, /already re-evaluated/);
|
|
138
|
+
assert.match((await run(world(), [])).error, /--ref/);
|
|
139
|
+
assert.match((await runControl("regate", [RID, "--ref", "f"], { io: w.io, repo: "o/r", rel: w.rel })).error, /--reason/);
|
|
140
|
+
});
|
|
141
|
+
it("a hold refuses the dispatch (fenced) after the audit line", async () => {
|
|
142
|
+
const w = world();
|
|
143
|
+
w.active.holds = { [RID]: { reason: "incident" } };
|
|
144
|
+
const r = await run(w, ["--ref", "fix/smoke"]);
|
|
145
|
+
assert.equal(r.ok, false);
|
|
146
|
+
assert.match(r.error, /held/);
|
|
147
|
+
assert.equal(dispatches(w).length, 0);
|
|
148
|
+
});
|
|
149
|
+
});
|
|
@@ -18,6 +18,7 @@ import { reviewStagingJson, reviewStagingIo, CI_EXCLUDED_CHECKS } from "../revie
|
|
|
18
18
|
import { pickFixes, recut, revertLast } from "./release-snapshot.mjs";
|
|
19
19
|
import { parseFixConfig, collectFindings, blockingOf, compileBrief, roundsAt, recordRound, secondPush, secondPushOf, holdForOwner, jobsToRerun, inputHash, deferredOf } from "./release-fixloop.mjs";
|
|
20
20
|
import { coStartCi } from "./release-preflight.mjs";
|
|
21
|
+
import { laneEnv } from "./release-credentials.mjs";
|
|
21
22
|
|
|
22
23
|
/** Delta passes after a head move: past it the job blocks for the manual path. Fix rounds are `ci.fix.max_rounds` (release-fixloop.mjs, default 1, #5567). */
|
|
23
24
|
export const MAX_DELTA_PASSES = 2;
|
|
@@ -298,8 +299,9 @@ export async function fixStep(ctx) {
|
|
|
298
299
|
const seamOf = (ctx) => ctx.io.review ?? (ctx.seam ??= realSeam(ctx));
|
|
299
300
|
|
|
300
301
|
/** Real effects of the review steps: the review-staging library, the engine runner, the filing scripts, gh and a lane process. */
|
|
301
|
-
export function realSeam({ repo, def, env = process.env, cwd = process.cwd(), makeRunner = null, gh: ghIn = null }) {
|
|
302
|
+
export function realSeam({ repo, def, env = process.env, laneStrip = [], cwd = process.cwd(), makeRunner = null, gh: ghIn = null }) {
|
|
302
303
|
const rs = { ...reviewStagingIo(), cwd, env };
|
|
304
|
+
const lane = laneEnv(env, laneStrip); // #5561: reviewer, fix and lane sandboxes never see the driver token
|
|
303
305
|
const sd = env.FORGE_SCRATCHPAD || join(cwd, ".forge-scratch");
|
|
304
306
|
let runner = null, shimEnv = null;
|
|
305
307
|
// Reviewer briefs say `forgedock ...`: pin that name to this release job's own build, whatever is installed globally.
|
|
@@ -308,7 +310,7 @@ export function realSeam({ repo, def, env = process.env, cwd = process.cwd(), ma
|
|
|
308
310
|
const dir = mkdtempSync(join(tmpdir(), "release-forgedock-"));
|
|
309
311
|
writeFileSync(join(dir, "forgedock"), `#!/bin/sh\nexec "${process.execPath}" "${join(ROOT, "bin", "forgedock.mjs")}" "$@"\n`, { mode: 0o755 });
|
|
310
312
|
process.once("exit", () => rmSync(dir, { recursive: true, force: true }));
|
|
311
|
-
return (shimEnv = { ...
|
|
313
|
+
return (shimEnv = { ...lane, PATH: `${dir}${delimiter}${lane.PATH ?? ""}` });
|
|
312
314
|
};
|
|
313
315
|
const gh = ghIn ?? ((args, input) => execFileSync("gh", args, { encoding: "utf8", input, maxBuffer: 64 << 20, env }));
|
|
314
316
|
return {
|
|
@@ -386,7 +388,7 @@ export function realSeam({ repo, def, env = process.env, cwd = process.cwd(), ma
|
|
|
386
388
|
runLane: ({ issue, lane }) => new Promise((resolve) => {
|
|
387
389
|
const dir = mkdtempSync(join(tmpdir(), "release-lane-"));
|
|
388
390
|
const rf = join(dir, "result.json");
|
|
389
|
-
const child = spawn(process.execPath, [join(ROOT, "bin", "forgedock.mjs"), "run-issue", String(issue), "--lane", lane, "--result-file", rf], { cwd, env, stdio: "ignore" });
|
|
391
|
+
const child = spawn(process.execPath, [join(ROOT, "bin", "forgedock.mjs"), "run-issue", String(issue), "--lane", lane, "--result-file", rf], { cwd, env: lane, stdio: "ignore" });
|
|
390
392
|
const timer = setTimeout(() => child.kill("SIGTERM"), LANE_MS);
|
|
391
393
|
const done = () => { clearTimeout(timer); let r = null; try { r = JSON.parse(readFileSync(rf, "utf8")); } catch { /* no result */ } rmSync(dir, { recursive: true, force: true }); resolve(r); };
|
|
392
394
|
child.on("error", done); child.on("exit", done);
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* Rollback ladder (#5563, epic #5549 Phase 3, I8/I10/I26, Q8): `forgedock release rollback <id> [--to flag|unit|full] --reason "..."`.
|
|
5
|
+
* The engine picks the lowest sufficient rung and records why: flag (kill the wave's rollout flags), unit (the service pipeline's
|
|
6
|
+
* rollback action with the recorded previous per-unit digests), full (the standalone rollback workflow), stop (hold, page, incident).
|
|
7
|
+
* Every dispatch is `fenced()` with `forge_epoch` and built by `buildDispatchArgs` (I26). After a unit or full rung the rollback
|
|
8
|
+
* result record must show matching per-service (and per-host) counts; a mismatch, an unreadable record or a failed health
|
|
9
|
+
* command escalates to stop. Rollback to code that predates a destructive migration is refused (I8). This module never talks to
|
|
10
|
+
* a database: the destructive-migration patterns live in release-config.mjs and are only matched against migration file text.
|
|
11
|
+
* Afterwards: a revert PR (default == live, I10), the wave's issues reopened, one incident issue, later waves held.
|
|
12
|
+
* Rationale: devdocs/decisions/5563-release-rollback.md.
|
|
13
|
+
*/
|
|
14
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
15
|
+
import { tmpdir } from "node:os";
|
|
16
|
+
import { join } from "node:path";
|
|
17
|
+
import { fenced } from "./release-fence.mjs";
|
|
18
|
+
import { buildDispatchArgs, runControl } from "./release-control.mjs";
|
|
19
|
+
import { acquireLease } from "./release-ledger.mjs";
|
|
20
|
+
import { releaseIssues } from "./release-verify.mjs";
|
|
21
|
+
import { DESTRUCTIVE_SQL, MIGRATION_PATHS } from "./release-config.mjs";
|
|
22
|
+
|
|
23
|
+
export const RUNGS = ["flag", "unit", "full", "stop"];
|
|
24
|
+
export const ROLLBACK_TRIGGERS = ["smoke", "health", "livecheck", "sli", "crashloop", "human"];
|
|
25
|
+
export const INCIDENT_MARKER = "FORGE:INCIDENT";
|
|
26
|
+
export const ROLLBACK_BOUNDS = { pollMs: 10_000, startPolls: 6, donePolls: 180 };
|
|
27
|
+
const FLAG_OK = ["smoke", "health", "sli", "crashloop", "human"]; // a wrong deploy (livecheck) is not fixed by a flag
|
|
28
|
+
const json = (s) => { try { return JSON.parse(String(s || "null")); } catch { return null; } };
|
|
29
|
+
const short = (s) => String(s ?? "").slice(0, 8);
|
|
30
|
+
const flagOf = (argv, f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : null; };
|
|
31
|
+
|
|
32
|
+
/** Trigger class of a recorded reason (release-verify / release-deploy wording). */
|
|
33
|
+
export function classifyTrigger(reason) {
|
|
34
|
+
const r = String(reason ?? "");
|
|
35
|
+
if (/SLI/i.test(r)) return "sli";
|
|
36
|
+
if (/crash/i.test(r)) return "crashloop";
|
|
37
|
+
if (/LIVE_CHECK|live sha|digest/i.test(r)) return "livecheck";
|
|
38
|
+
if (/health/i.test(r)) return "health";
|
|
39
|
+
if (/smoke|edge|verify/i.test(r)) return "smoke";
|
|
40
|
+
return "human";
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The lowest sufficient rung at or after `from` (`--to` or an escalation floor), honouring `rollback.ladder`.
|
|
45
|
+
* @returns {{rung: string, why: string}}
|
|
46
|
+
*/
|
|
47
|
+
export function chooseRung({ trigger, from = "flag", rb = {}, target = null }) {
|
|
48
|
+
const ladder = (rb.ladder?.length ? rb.ladder : RUNGS).filter((r) => RUNGS.includes(r));
|
|
49
|
+
const ok = {
|
|
50
|
+
flag: () => (!(rb.flags ?? []).some((f) => f?.kill_command) ? "no rollout flag has a kill_command" : FLAG_OK.includes(trigger) ? null : `a ${trigger} trigger is not fixed by a flag`),
|
|
51
|
+
unit: () => (!rb.unit_workflow ? "rollback.unit_workflow is not set" : Object.keys(target?.images ?? {}).length ? null : "no recorded previous per-unit digests"),
|
|
52
|
+
full: () => (rb.full_workflow ? null : "rollback.full_workflow is not set"),
|
|
53
|
+
stop: () => null,
|
|
54
|
+
};
|
|
55
|
+
const skipped = [];
|
|
56
|
+
for (const rung of RUNGS.slice(RUNGS.indexOf(from))) {
|
|
57
|
+
if (!ladder.includes(rung) && rung !== "stop") { skipped.push(`${rung}: not in rollback.ladder`); continue; }
|
|
58
|
+
const why = ok[rung]();
|
|
59
|
+
if (!why) return { rung, why: `${trigger}: lowest sufficient rung is ${rung}${skipped.length ? ` (skipped ${skipped.join("; ")})` : ""}` };
|
|
60
|
+
skipped.push(`${rung}: ${why}`);
|
|
61
|
+
}
|
|
62
|
+
return { rung: "stop", why: `${trigger}: no rung sufficient (${skipped.join("; ")})` };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* I8: destructive migrations between the rollback target and the live sha, read from migration file text only.
|
|
67
|
+
* @returns {{ok: true} | {refused: string}} unreadable git history refuses (fail closed)
|
|
68
|
+
*/
|
|
69
|
+
export function refuseAcross({ io, target, live, paths = MIGRATION_PATHS }) {
|
|
70
|
+
let files;
|
|
71
|
+
try { files = String(io.git(["diff", "--name-only", "--diff-filter=AM", `${target}..${live}`, "--", ...paths])).split("\n").filter(Boolean); }
|
|
72
|
+
catch (e) { return { refused: `cannot list migrations between ${short(target)} and ${short(live)}: ${String(e?.message ?? e).split("\n")[0]}` }; }
|
|
73
|
+
for (const f of files) {
|
|
74
|
+
let text;
|
|
75
|
+
try { text = String(io.git(["show", `${live}:${f}`])); } catch (e) { return { refused: `cannot read migration ${f}: ${String(e?.message ?? e).split("\n")[0]}` }; }
|
|
76
|
+
if (DESTRUCTIVE_SQL.test(text)) return { refused: `rollback to ${short(target)} crosses destructive migration ${f} (I8); roll forward instead` };
|
|
77
|
+
}
|
|
78
|
+
return { ok: true };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Per-service (and per-host) counts of the rollback result record against the recorded previous set (Q8). @returns {string|null} the mismatch */
|
|
82
|
+
export function checkCounts(record, target) {
|
|
83
|
+
const units = record?.units;
|
|
84
|
+
if (!units || typeof units !== "object" || !Object.keys(units).length) return "rollback result record is unreadable or empty";
|
|
85
|
+
const images = target?.images ?? {};
|
|
86
|
+
const missing = Object.keys(images).filter((u) => !units[u]);
|
|
87
|
+
if (missing.length) return `result record has no entry for ${missing.join(", ")}`;
|
|
88
|
+
for (const [u, x] of Object.entries(units)) {
|
|
89
|
+
if (images[u] && x?.digest && x.digest !== images[u]) return `${u}: rolled to ${x.digest}, recorded previous digest is ${images[u]}`;
|
|
90
|
+
for (const [h, c] of Object.entries(x?.hosts ?? { all: x })) {
|
|
91
|
+
if (!Number.isInteger(c?.expected) || !Number.isInteger(c?.rolled)) return `${u}@${h}: counts missing`;
|
|
92
|
+
if (c.rolled !== c.expected) return `${u}@${h}: ${c.rolled} of ${c.expected} rolled back`;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function poll(io, polls, ms, fn) {
|
|
99
|
+
for (let i = 0; i < polls; i++) { const v = await fn(); if (v) return v; if (i < polls - 1) await io.sleep(ms); }
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** A fenced dispatch of `workflow` and the run it makes (newer than every run seen before). Never redispatched once an intent exists (I7). */
|
|
104
|
+
async function dispatchRung(ctx, rung, workflow, inputs, b) {
|
|
105
|
+
const { io, repo } = ctx, st = ctx.state.rollbackRun, rec = (st.dispatch ??= {})[rung] ??= {};
|
|
106
|
+
const list = async () => json(await io.gh(["run", "list", "--repo", repo, "--workflow", workflow, "--json", "databaseId,status,conclusion", "--limit", "10"])) ?? [];
|
|
107
|
+
if (rec.baseId == null) { rec.baseId = Math.max(0, ...(await list()).map((r) => r.databaseId)); ctx.save(); }
|
|
108
|
+
const had = rec.dispatched || (ctx.state.intents ?? []).some((i) => i.action === "dispatch" && String(i.key).endsWith(`:rollback:${rung}`));
|
|
109
|
+
if (!had) {
|
|
110
|
+
const key = `${ctx.fence?.lease?.release ?? ctx.state.id}:${ctx.fence?.lease?.epoch ?? 0}:rollback:${rung}`;
|
|
111
|
+
const f = await fenced(ctx.fence, { action: "dispatch", key }, (epoch) => io.gh(buildDispatchArgs({ workflow, repo, ref: ctx.def, inputs: { ...inputs, ...(epoch != null ? { forge_epoch: epoch } : {}) } })));
|
|
112
|
+
if (f.refused) return { err: `dispatch ${f.refused}` };
|
|
113
|
+
rec.dispatched = true; ctx.save();
|
|
114
|
+
}
|
|
115
|
+
const newer = async () => (await list()).find((r) => r.databaseId > rec.baseId) ?? null;
|
|
116
|
+
const run = await poll(io, b.startPolls, b.pollMs, newer);
|
|
117
|
+
if (!run) return { err: `no ${workflow} run appeared after the ${rung} rollback dispatch (never redispatched; check the Actions tab)` };
|
|
118
|
+
const done = await poll(io, b.donePolls, b.pollMs, async () => { const r = await newer(); return r?.status === "completed" ? r : null; });
|
|
119
|
+
if (!done) return { err: `${workflow} run ${run.databaseId} did not finish` };
|
|
120
|
+
return done.conclusion === "success" ? { run: done } : { err: `${workflow} run ${done.databaseId} concluded ${done.conclusion}` };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function healthy(io, rb) {
|
|
124
|
+
if (!rb.health_command) return { ok: true, note: "health: unchecked (rollback.health_command unset)" };
|
|
125
|
+
const r = await io.rehearse(rb.health_command, { timeout: 120_000 });
|
|
126
|
+
return r?.ok ? { ok: true, note: "health: ok" } : { ok: false, why: `health command failed: ${String(r?.output ?? "").trim().slice(-200)}` };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Execute one rung. @returns {{ok: true, note} | {fail: string}} */
|
|
130
|
+
async function runRung(ctx, rung, rb, b, reason) {
|
|
131
|
+
const { io } = ctx, d = ctx.state.deploy, target = d.target;
|
|
132
|
+
if (rung === "flag") {
|
|
133
|
+
for (const f of rb.flags ?? []) {
|
|
134
|
+
if (!f?.kill_command) continue;
|
|
135
|
+
const r = await fenced(ctx.fence, { action: "flag-kill", key: `${ctx.fence?.lease?.release ?? ctx.state.id}:${ctx.fence?.lease?.epoch ?? 0}:rollback:flag:${f.flag}` }, () => io.rehearse(f.kill_command, { timeout: 120_000 }));
|
|
136
|
+
if (r.refused) return { fail: `flag ${f.flag}: ${r.refused}` };
|
|
137
|
+
if (!r.value?.ok) return { fail: `flag ${f.flag}: kill command failed` };
|
|
138
|
+
}
|
|
139
|
+
const h = await healthy(io, rb);
|
|
140
|
+
return h.ok ? { ok: true, note: h.note } : { fail: h.why };
|
|
141
|
+
}
|
|
142
|
+
const workflow = rung === "unit" ? rb.unit_workflow : rb.full_workflow;
|
|
143
|
+
const inputs = rung === "unit"
|
|
144
|
+
? { action: rb.unit_action ?? "rollback", sha: target.sha, digests: JSON.stringify(target.images ?? {}) }
|
|
145
|
+
: { sha: target.sha, reason: String(reason).slice(0, 200) };
|
|
146
|
+
const r = await dispatchRung(ctx, rung, workflow, inputs, b);
|
|
147
|
+
if (r.err) return { fail: r.err };
|
|
148
|
+
const rr = rb.result_command ? await io.rehearse(rb.result_command, { timeout: 120_000 }) : null;
|
|
149
|
+
const bad = checkCounts(rr?.ok ? json(rr.output) : null, target);
|
|
150
|
+
if (bad) return { fail: `counts check: ${bad}` };
|
|
151
|
+
const h = await healthy(io, rb);
|
|
152
|
+
return h.ok ? { ok: true, note: `counts match the recorded set; ${h.note}` } : { fail: h.why };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const ensureIssue = async (ctx, title, body, marker) => { // exactly one issue per marker, any state
|
|
156
|
+
const { io, repo } = ctx;
|
|
157
|
+
const found = json(await io.gh(["issue", "list", "--repo", repo, "--state", "all", "--search", `"${marker}" in:body`, "--json", "number,body", "--limit", "20"])) ?? [];
|
|
158
|
+
const hit = found.find((i) => String(i.body ?? "").includes(marker));
|
|
159
|
+
if (hit) return { number: hit.number, created: false };
|
|
160
|
+
const url = String(await io.gh(["issue", "create", "--repo", repo, "--title", title, "--body", `${body}\n\n<!-- ${marker} -->`])).trim();
|
|
161
|
+
return { number: Number(/\/issues\/(\d+)/.exec(url)?.[1]) || url, created: true };
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
/** Revert PR to the default branch (I10), built in a throwaway worktree so the caller's checkout is never touched. */
|
|
165
|
+
async function revertPr(ctx, reason) {
|
|
166
|
+
const { io, repo, def } = ctx, sha = ctx.state.deploy.merge, branch = `rollback/${ctx.state.id}`;
|
|
167
|
+
const open = json(await io.gh(["pr", "list", "--repo", repo, "--head", branch, "--state", "open", "--json", "number,url"])) ?? [];
|
|
168
|
+
if (open[0]) return { pr: open[0].number, reused: true };
|
|
169
|
+
const dir = mkdtempSync(join(ctx.tmp ?? tmpdir(), "forge-rollback-"));
|
|
170
|
+
const g = (...a) => io.git(["-C", dir, ...a]);
|
|
171
|
+
try {
|
|
172
|
+
io.git(["fetch", "origin", def]);
|
|
173
|
+
io.git(["worktree", "add", "--detach", dir, `origin/${def}`]);
|
|
174
|
+
const parents = String(g("rev-list", "--parents", "-n", "1", sha)).trim().split(/\s+/).length - 1;
|
|
175
|
+
g("checkout", "-b", branch);
|
|
176
|
+
g("revert", "--no-edit", ...(parents > 1 ? ["-m", "1"] : []), sha);
|
|
177
|
+
const f = await fenced(ctx.fence, { action: "revert-pr", key: `${ctx.state.id}:${ctx.fence?.lease?.epoch ?? 0}:rollback:revert` }, () => { g("push", "origin", branch); });
|
|
178
|
+
if (f.refused) return { err: f.refused };
|
|
179
|
+
} catch (e) { return { err: `revert PR not created: ${String(e?.message ?? e).split("\n")[0]}` }; }
|
|
180
|
+
finally { try { io.git(["worktree", "remove", "--force", dir]); } catch { rmSync(dir, { recursive: true, force: true }); } }
|
|
181
|
+
const url = String(await io.gh(["pr", "create", "--repo", repo, "--base", def, "--head", branch, "--title", `Revert release ${ctx.state.id} (rollback)`, "--body", `Rollback of ${short(sha)} so ${def} matches live (I10).\n\nCause: ${reason}`])).trim();
|
|
182
|
+
return { pr: Number(/\/pull\/(\d+)/.exec(url)?.[1]) || url, reused: false };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async function reopenIssues(ctx, reason) {
|
|
186
|
+
const { io, repo } = ctx, out = [];
|
|
187
|
+
for (const n of releaseIssues(ctx.state)) {
|
|
188
|
+
const info = json(await io.gh(["issue", "view", String(n), "--repo", repo, "--json", "state"]));
|
|
189
|
+
if (String(info?.state).toUpperCase() !== "CLOSED") continue;
|
|
190
|
+
const f = await fenced(ctx.fence, { action: "reopen", key: `${ctx.state.id}:${ctx.fence?.lease?.epoch ?? 0}:rollback:reopen:${n}` }, () => io.gh(["issue", "reopen", String(n), "--repo", repo, "--comment", `Reopened: release ${ctx.state.id} was rolled back (${reason}).`]));
|
|
191
|
+
if (!f.refused) out.push(n);
|
|
192
|
+
}
|
|
193
|
+
return out;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async function page(ctx, webhook, text) {
|
|
197
|
+
if (!webhook) return "no events.webhook_url";
|
|
198
|
+
try { const r = await (ctx.io.post ?? ((u, body) => fetch(u, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) })))(webhook, { text }); return r?.ok === false ? `webhook answered ${r.status}` : "paged"; }
|
|
199
|
+
catch (e) { return `page failed: ${String(e?.message ?? e).split("\n")[0]}`; }
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Run the ladder for `ctx.state` (a deployed release). `ctx`: {io, repo, def, state, save, fence?, policy, actor, host, config?}.
|
|
204
|
+
* `args`: {reason, to?, trigger?, later?: [release ids to hold]}. State in `state.rollbackRun`; reruns skip finished post-steps.
|
|
205
|
+
* @returns {Promise<{ok: boolean, rung: string, why: string, history: object[], refused?: string, post: object}>}
|
|
206
|
+
*/
|
|
207
|
+
export async function runRollback(ctx, { reason, to = "flag", trigger = null, later = [] }) {
|
|
208
|
+
const { io, state } = ctx, rb = ctx.policy?.rollback ?? {}, b = { ...ROLLBACK_BOUNDS, ...(ctx.config?.rollbackBounds ?? {}) };
|
|
209
|
+
const run = (state.rollbackRun ??= { history: [], post: {} });
|
|
210
|
+
const d = state.deploy;
|
|
211
|
+
if (!d?.target?.sha || !d.merge) return { ok: false, rung: "none", why: "no recorded rollback target (I9); nothing to roll back", history: run.history, refused: "no recorded rollback target", post: run.post };
|
|
212
|
+
const trig = trigger ?? classifyTrigger(reason);
|
|
213
|
+
if (rb.triggers?.length && trig !== "human" && !rb.triggers.includes(trig)) return { ok: false, rung: "none", why: `trigger ${trig} is not in rollback.triggers`, history: run.history, refused: `trigger ${trig} is not enabled`, post: run.post };
|
|
214
|
+
run.reason = reason; run.trigger = trig; ctx.save();
|
|
215
|
+
const across = refuseAcross({ io, target: d.target.sha, live: d.merge });
|
|
216
|
+
let from = to, refused = null, rung, why, note = "";
|
|
217
|
+
for (;;) {
|
|
218
|
+
({ rung, why } = chooseRung({ trigger: trig, from, rb, target: d.target }));
|
|
219
|
+
if (across.refused && (rung === "unit" || rung === "full")) { refused = across.refused; run.history.push({ rung, why: `refused: ${across.refused}` }); from = "stop"; continue; }
|
|
220
|
+
run.rung = rung; run.why = why; ctx.save();
|
|
221
|
+
if (rung === "stop") break;
|
|
222
|
+
const r = await runRung(ctx, rung, rb, b, reason);
|
|
223
|
+
run.history.push({ rung, why, result: r.ok ? r.note : r.fail });
|
|
224
|
+
if (r.ok) { note = r.note; break; }
|
|
225
|
+
from = rung === "flag" ? "unit" : "stop"; // a failed flag kill tries code; a failed unit/full or counts mismatch stops (Q8)
|
|
226
|
+
}
|
|
227
|
+
const ok = rung !== "stop";
|
|
228
|
+
const post = run.post;
|
|
229
|
+
if (rung === "unit" || rung === "full") { if (rb.open_revert_pr !== false) post.revert ??= await revertPr(ctx, reason); }
|
|
230
|
+
if (ok) post.reopened ??= await reopenIssues(ctx, reason);
|
|
231
|
+
const inc = await (post.incident ? Promise.resolve(post.incident) : ensureIssue(ctx, `incident: rollback of release ${state.id}`, `Release ${state.id} (${short(d.merge)}) was rolled back via rung ${rung}.\n\nTrigger: ${trig}\nReason: ${reason}\nWhy this rung: ${why}\n${refused ? `Refused: ${refused}\n` : ""}${note ? `Result: ${note}\n` : ""}Ladder: ${run.history.map((h) => `${h.rung} -> ${h.result ?? h.why}`).join("; ") || "none"}`, `${INCIDENT_MARKER} ${state.id}`));
|
|
232
|
+
post.incident = inc;
|
|
233
|
+
if (rung === "stop") post.paged ??= await page(ctx, ctx.policy?.events?.webhook_url, `Release ${state.id} rollback stopped at rung stop: ${reason}. Incident #${inc.number}.`);
|
|
234
|
+
post.held ??= [];
|
|
235
|
+
for (const id of io.api ? later.filter((x) => x !== state.id && !post.held.includes(x)) : []) { // later waves are held through the audited control path
|
|
236
|
+
const h = await runControl("hold", [id, "--reason", `release ${state.id} rolled back: ${reason}`], { io, repo: ctx.repo, policy: ctx.policy, actor: ctx.actor, host: ctx.host, now: io.now?.() });
|
|
237
|
+
if (h.ok) post.held.push(id);
|
|
238
|
+
}
|
|
239
|
+
run.done = true; ctx.save();
|
|
240
|
+
return { ok, rung, why, history: run.history, ...(refused ? { refused } : {}), post };
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** The lease that fences the rollback's effects (own epoch, `forge_epoch` on every dispatch); unmanaged (no `io.api`): no fence. */
|
|
244
|
+
export async function takeFence(ctx, holder, ttlS = 300) {
|
|
245
|
+
if (!ctx.io.api) return { fence: null };
|
|
246
|
+
const lctx = { io: ctx.io, repo: ctx.repo, credential: "driver" };
|
|
247
|
+
const l = await acquireLease(lctx, { holder, release: ctx.state.id, issue: ctx.state.steps?.["release-pr"]?.result?.pr, ttlS, now: ctx.io.now() });
|
|
248
|
+
if (!l.ok) return { refused: l.refused ?? "lease lost the race" };
|
|
249
|
+
const record = async (rec) => { const a = (ctx.state.intents ??= []); const i = a.findIndex((x) => x.key === rec.key); if (i < 0) a.push(rec); else a[i] = rec; ctx.save(); };
|
|
250
|
+
return { fence: { lctx, lease: l.lease, record, now: () => new Date(ctx.io.now()).toISOString() } };
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** `forgedock release rollback <id> --reason "..." [--to flag|unit|full] [--later id,id] [--repo R] [--json]`; @returns 0 rolled back, 1 refused, 3 stopped. */
|
|
254
|
+
export async function rollbackFromCli(argv, { io, rel, policy, def, actor, host }) {
|
|
255
|
+
const id = argv.find((a, i) => !a.startsWith("--") && !["--reason", "--to", "--later", "--repo"].includes(argv[i - 1]));
|
|
256
|
+
const reason = flagOf(argv, "--reason"), to = flagOf(argv, "--to") ?? "flag", json_ = argv.includes("--json");
|
|
257
|
+
const say = (o, line) => io.print(json_ ? JSON.stringify(o) : line);
|
|
258
|
+
const refuse = (error) => { say({ ok: false, error }, `release rollback: refused: ${error}`); return 1; };
|
|
259
|
+
if (!id) return refuse("release id required");
|
|
260
|
+
if (!reason || !reason.trim() || reason.startsWith("--")) return refuse("--reason is required");
|
|
261
|
+
if (!RUNGS.slice(0, 3).includes(to)) return refuse(`--to must be one of ${RUNGS.slice(0, 3).join("|")}`);
|
|
262
|
+
const state = rel.load();
|
|
263
|
+
if (!state) return refuse(`no release ${id}`);
|
|
264
|
+
const repo = flagOf(argv, "--repo") ?? state.repo;
|
|
265
|
+
const ctx = { io, repo, def, state, save: () => rel.save(state), policy, actor, host };
|
|
266
|
+
if (io.api) { // mutating: audited like every control verb (#5556)
|
|
267
|
+
const c = await runControl("rollback", [id, "--reason", reason, "--to", to], { io, repo, policy, actor, host, now: io.now?.() });
|
|
268
|
+
if (!c.ok) return refuse(c.error);
|
|
269
|
+
}
|
|
270
|
+
const f = await takeFence(ctx, io.holder ?? `host-${process.pid}`);
|
|
271
|
+
if (f.refused) return refuse(f.refused);
|
|
272
|
+
ctx.fence = f.fence;
|
|
273
|
+
const r = await runRollback(ctx, { reason, to, trigger: null, later: (flagOf(argv, "--later") ?? "").split(",").filter(Boolean) });
|
|
274
|
+
if (r.refused && r.rung === "none") return refuse(r.refused);
|
|
275
|
+
say(r, `release rollback ${id}: ${r.ok ? "rolled back" : "stopped"} at rung ${r.rung} (${r.why})${r.refused ? `; refused: ${r.refused}` : ""}`);
|
|
276
|
+
return r.ok ? 0 : 3;
|
|
277
|
+
}
|