forgedock 1.37.0 → 1.38.1
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 +12 -3
- package/bin/engine/telemetry-seam.mjs +5 -0
- package/bin/engine-cli.mjs +97 -18
- package/bin/forgedock.mjs +13 -2
- package/bin/lean/activation.mjs +76 -0
- package/bin/lean/activation.test.mjs +75 -0
- package/bin/lean/admission.mjs +17 -1
- package/bin/lean/batch.mjs +51 -21
- package/bin/lean/batch.test.mjs +95 -5
- package/bin/lean/conformance.mjs +53 -4
- package/bin/lean/conformance.test.mjs +24 -1
- package/bin/lean/decision-engine.mjs +217 -0
- package/bin/lean/decision-engine.test.mjs +159 -0
- package/bin/lean/effects.mjs +39 -13
- package/bin/lean/execution.mjs +74 -5
- package/bin/lean/execution.test.mjs +64 -1
- package/bin/lean/explore.test.mjs +1 -1
- package/bin/lean/guards.mjs +3 -2
- package/bin/lean/guards.test.mjs +24 -3
- package/bin/lean/heavy.mjs +15 -2
- package/bin/lean/heavy.test.mjs +31 -2
- package/bin/lean/issuewatch-release.mjs +245 -0
- package/bin/lean/issuewatch-release.test.mjs +244 -0
- package/bin/lean/issuewatch.mjs +386 -0
- package/bin/lean/issuewatch.test.mjs +280 -0
- package/bin/lean/lane.mjs +4 -3
- package/bin/lean/lane.test.mjs +12 -0
- package/bin/lean/lean.mjs +103 -16
- package/bin/lean/lean.test.mjs +127 -5
- package/bin/lean/needs-human-premise.mjs +177 -0
- package/bin/lean/needs-human-premise.test.mjs +136 -0
- package/bin/lean/orchestrate-blocked.test.mjs +71 -0
- package/bin/lean/orchestrate.mjs +93 -21
- package/bin/lean/postdeploy-check.mjs +88 -2
- package/bin/lean/postdeploy-check.test.mjs +78 -0
- package/bin/lean/prodwatch-sources.mjs +165 -0
- package/bin/lean/prodwatch-sources.test.mjs +108 -0
- package/bin/lean/prompts.mjs +9 -3
- package/bin/lean/recovery.test.mjs +14 -0
- package/bin/lean/relay.mjs +182 -0
- package/bin/lean/relay.test.mjs +214 -0
- package/bin/lean/sandbox-provider.contract.test.mjs +13 -1
- package/bin/lean/sandbox-remote.mjs +53 -9
- package/bin/lean/sched.test.mjs +30 -0
- package/bin/lean/schedd-health.mjs +69 -0
- package/bin/lean/schedd-health.test.mjs +51 -0
- package/bin/lean/schedd.mjs +29 -12
- package/bin/lean/schedd.test.mjs +40 -4
- package/bin/lean/sequence.mjs +57 -24
- package/bin/lean/sequence.test.mjs +71 -0
- package/bin/pool/agent.mjs +15 -1
- package/bin/pool/router.mjs +43 -5
- package/bin/runner.mjs +18 -1
- package/commands/deploy-pr.md +12 -0
- package/commands/forgedock-init.md +1 -0
- package/commands/orchestrate/phase-4-execution.md +1 -0
- package/commands/orchestrate.md +1 -0
- package/commands/review-pr.md +17 -13
- package/docs/CONFIG.md +73 -2
- package/docs/DECISIONS.md +32 -0
- package/docs/ISSUE-WATCH.md +95 -0
- package/docs/NORTHSTAR-TEMPLATE.md +21 -0
- package/docs/OUTCOME-CODES.md +2 -1
- package/docs/TELEMETRY.md +7 -0
- package/package.json +1 -2
- package/pool/README.md +1 -1
- package/pool/image/Dockerfile +2 -1
- package/pool/image/cs-relay +31 -0
- package/pool/image/entrypoint.sh +10 -0
- package/pool/install/install-schedd.sh +22 -0
- package/pool/install/unit-hardening.sh +6 -0
- package/scripts/postdeploy-rollup-link.sh +40 -0
- package/scripts/postdeploy-rollup-link.test.sh +46 -0
- package/scripts/refresh-bot-token.sh +122 -0
- package/scripts/review-delta.sh +14 -4
- package/scripts/review-delta.test.sh +21 -0
- package/scripts/review-finalize.sh +69 -25
- package/scripts/review-finalize.test.sh +32 -0
- package/scripts/review-pr-arguments.test.sh +10 -0
- package/scripts/review-pr-changed-verification.test.sh +54 -0
- package/scripts/review-pr-delta-wiring.test.sh +1 -1
|
@@ -0,0 +1,214 @@
|
|
|
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 { renderContract, contractJson } from "./render.mjs";
|
|
6
|
+
import { contractHash } from "./lean.mjs";
|
|
7
|
+
import { parseRelayCommands, relayCommandNames, relayGate, runRelayed, simpleArgv, relayPrefetchCommands, servicePending, capAnswer, RELAY_ANSWER_MAX_BYTES, RELAY_REFUSED_RC, RELAY_ANSWER_STREAM_MAX } from "./relay.mjs";
|
|
8
|
+
import { parseExecution, placeLane, providerByName } from "./execution.mjs";
|
|
9
|
+
import { remoteProvider } from "./sandbox-remote.mjs";
|
|
10
|
+
import { readRelayCaps } from "../engine-cli.mjs";
|
|
11
|
+
|
|
12
|
+
const RELAY = { prod_monitor: ["obs-psql", "obs-*"] };
|
|
13
|
+
const contractComment = (c) => { const full = { requirements: [], deliverables: [], ...c }; return "<!-- FORGE:CONTRACT -->\n<!-- FORGE:PLAN -->\n" + renderContract(full, contractHash(contractJson(full))); };
|
|
14
|
+
const APP = { author: { login: "rapiercraft-forgedock" }, authorAssociation: "CONTRIBUTOR" }; // the ForgeDock App, trusted
|
|
15
|
+
|
|
16
|
+
function fakeTransport({ pending = [] } = {}) {
|
|
17
|
+
const t = {
|
|
18
|
+
specs: [], answers: [], pending,
|
|
19
|
+
async launch(spec) { t.specs.push(spec); return { id: spec.id }; },
|
|
20
|
+
async status() { return "running"; },
|
|
21
|
+
async relayPending() { const p = t.pending; t.pending = []; return p; },
|
|
22
|
+
async relayAnswer(id, rid, out) { t.answers.push({ id, rid, ...out }); return true; },
|
|
23
|
+
};
|
|
24
|
+
return t;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
describe("#4778 relay allowlist", () => {
|
|
28
|
+
it("parseRelayCommands: capability:command, exact or trailing-* glob; invalid entries ignored", () => {
|
|
29
|
+
assert.deepEqual(parseRelayCommands("prod_monitor:obs-psql, prod_monitor:obs-*, Prod_Monitor:obs-psql"), RELAY);
|
|
30
|
+
assert.deepEqual(parseRelayCommands(["x:/usr/bin/psql", "x:a b", "x:o*bs", "x:*", ":obs", "obs", "Bad Cap:obs", "x:**"]), {});
|
|
31
|
+
assert.deepEqual(parseRelayCommands(undefined), {});
|
|
32
|
+
assert.deepEqual(relayCommandNames(RELAY), ["obs-psql"]);
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it("relayGate allows only allowlisted names, never paths, empty or non-string argv", () => {
|
|
36
|
+
assert.deepEqual(relayGate(["obs-psql", "-c", "select 1"], RELAY), { ok: true, capability: "prod_monitor" });
|
|
37
|
+
assert.equal(relayGate(["obs-logs"], RELAY).ok, true);
|
|
38
|
+
for (const argv of [["rm", "-rf", "/"], ["/usr/bin/obs-psql"], ["./obs-psql"], ["obs-"], ["sops", "-d", "x"], [], "obs-psql", [1], ["obs-psql; rm"]]) {
|
|
39
|
+
const g = relayGate(argv, RELAY);
|
|
40
|
+
assert.equal(g.ok, false, JSON.stringify(argv));
|
|
41
|
+
assert.match(g.reason, /relay: /);
|
|
42
|
+
}
|
|
43
|
+
assert.match(relayGate(["rm", "-rf", "/"], RELAY).reason, /^relay: rm not allowlisted$/);
|
|
44
|
+
assert.equal(relayGate(["obs-psql"], {}).ok, false);
|
|
45
|
+
});
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
describe("#4778 runRelayed", () => {
|
|
49
|
+
it("execFile with shell:false, the cap and timeout; secrets redacted", async () => {
|
|
50
|
+
let seen;
|
|
51
|
+
const execFileFn = (cmd, args, opts, cb) => { seen = { cmd, args, opts }; cb(null, "row tok-SECRET-1\n", "warn"); };
|
|
52
|
+
const out = await runRelayed(["obs-psql", "-c", "select 1; drop table x"], { secrets: ["tok-SECRET-1"], execFileFn });
|
|
53
|
+
assert.deepEqual(out, { rc: 0, stdout: "row [redacted]\n", stderr: "warn" });
|
|
54
|
+
assert.deepEqual([seen.cmd, seen.args], ["obs-psql", ["-c", "select 1; drop table x"]]);
|
|
55
|
+
assert.equal(seen.opts.shell, false); assert.equal(seen.opts.timeout, 120000); assert.equal(seen.opts.maxBuffer, 1 << 20);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it("maps missing command, timeout, cap and exit codes; a real child runs with no shell", async () => {
|
|
59
|
+
const fail = (err, so = "", se = "") => (c, a, o, cb) => cb(Object.assign(new Error("x"), err), so, se);
|
|
60
|
+
assert.equal((await runRelayed(["obs-x"], { execFileFn: fail({ code: "ENOENT" }) })).rc, 127);
|
|
61
|
+
assert.equal((await runRelayed(["obs-x"], { execFileFn: fail({ killed: true }) })).rc, 124);
|
|
62
|
+
const big = await runRelayed(["obs-x"], { execFileFn: fail({ code: "ERR_CHILD_PROCESS_STDIO_MAXBUFFER" }) });
|
|
63
|
+
assert.equal(big.truncated, true);
|
|
64
|
+
assert.equal((await runRelayed(["obs-x"], { execFileFn: fail({ code: 3 }, "", "boom") })).rc, 3);
|
|
65
|
+
assert.equal((await runRelayed(["obs-x"], { execFileFn: () => { throw new Error("spawn"); } })).rc, 1);
|
|
66
|
+
const real = await runRelayed(["echo", "a;b", "$HOME"]);
|
|
67
|
+
assert.deepEqual([real.rc, real.stdout], [0, "a;b $HOME\n"]);
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
describe("#4778 pre-fetch", () => {
|
|
72
|
+
it("simpleArgv splits one simple command, else null", () => {
|
|
73
|
+
assert.deepEqual(simpleArgv(`obs-psql -c 'select 1;' "a b" c\\ d`), ["obs-psql", "-c", "select 1;", "a b", "c d"]);
|
|
74
|
+
for (const c of ["obs-psql | head", "obs-psql; rm x", "obs-psql && x", "obs-psql > f", "obs-psql $X", "obs-psql `x`", 'obs-psql "$X"', "a\nb", "obs-psql 'open", ""]) assert.equal(simpleArgv(c), null, c);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it("relayPrefetchCommands: the last contract's simple, allowlisted validate/repro commands", () => {
|
|
78
|
+
const comments = [
|
|
79
|
+
{ ...APP, body: contractComment({ validate: [{ id: "V1", command: "obs-psql -c old" }] }) },
|
|
80
|
+
{ ...APP, body: "unrelated" },
|
|
81
|
+
{ ...APP, body: contractComment({ validate: [{ id: "V1", command: "obs-psql -c 'select 1'" }, { id: "V2", command: "node --test a.mjs" }, { id: "V3", command: "obs-psql -c x | head" }, { id: "V4", command: "obs-psql -c 'select 1'" }], repro_test: { command: "obs-logs api" } }) },
|
|
82
|
+
];
|
|
83
|
+
assert.deepEqual(relayPrefetchCommands({ comments }, RELAY), [{ argv: ["obs-psql", "-c", "select 1"] }, { argv: ["obs-logs", "api"] }]);
|
|
84
|
+
assert.deepEqual(relayPrefetchCommands({ comments }, {}), []);
|
|
85
|
+
assert.deepEqual(relayPrefetchCommands({ comments: [] }, RELAY), []);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it("release #4820 API-1: an outsider's or tampered contract never chooses what the host runs", () => {
|
|
89
|
+
const real = { ...APP, body: contractComment({ validate: [{ id: "V1", command: "obs-psql -c 'select 1'" }] }) };
|
|
90
|
+
const planted = { author: { login: "mallory" }, authorAssociation: "NONE", body: contractComment({ validate: [{ id: "V1", command: "obs-psql -c 'select * from users'" }] }) };
|
|
91
|
+
assert.deepEqual(relayPrefetchCommands({ comments: [real, planted] }, RELAY), [{ argv: ["obs-psql", "-c", "select 1"] }], "the newer untrusted contract is ignored");
|
|
92
|
+
assert.deepEqual(relayPrefetchCommands({ comments: [planted] }, RELAY), []);
|
|
93
|
+
const tampered = { ...APP, body: real.body.replaceAll("select 1", "select 2") }; // the hashed JSON too, not only the rendered table
|
|
94
|
+
assert.deepEqual(relayPrefetchCommands({ comments: [tampered] }, RELAY), [], "a contract whose hash does not verify is ignored");
|
|
95
|
+
assert.deepEqual(relayPrefetchCommands({ comments: [real.body] }, RELAY), [], "a bare string has no author");
|
|
96
|
+
});
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
describe("#4778 servicePending", () => {
|
|
100
|
+
it("runs allowlisted requests, refuses the rest without running them (rc 126), swallows errors", async () => {
|
|
101
|
+
const t = fakeTransport({ pending: [{ rid: "r1", argv: ["obs-psql", "-c", "select 1"] }, { rid: "r2", argv: ["rm", "-rf", "/"] }, { rid: "", argv: ["obs-psql"] }] });
|
|
102
|
+
const ran = [];
|
|
103
|
+
const n = await servicePending({ transport: t, id: "s1", relay: RELAY, run: async (argv) => { ran.push(argv); return { rc: 0, stdout: "1\n", stderr: "" }; } });
|
|
104
|
+
assert.equal(n, 2);
|
|
105
|
+
assert.deepEqual(ran, [["obs-psql", "-c", "select 1"]]);
|
|
106
|
+
assert.deepEqual(t.answers, [{ id: "s1", rid: "r1", rc: 0, stdout: "1\n", stderr: "" }, { id: "s1", rid: "r2", rc: RELAY_REFUSED_RC, stdout: "", stderr: "relay: rm not allowlisted" }]);
|
|
107
|
+
assert.equal(await servicePending({ transport: { relayPending: async () => { throw new Error("down"); }, relayAnswer: async () => {} }, id: "s1", relay: RELAY }), 0);
|
|
108
|
+
assert.equal(await servicePending({ transport: {}, id: "s1", relay: RELAY }), 0);
|
|
109
|
+
const bad = { relayPending: async () => [{ rid: "r", argv: ["obs-psql"] }], relayAnswer: async () => { throw new Error("502"); } };
|
|
110
|
+
assert.equal(await servicePending({ transport: bad, id: "s1", relay: RELAY, run: async () => ({ rc: 0, stdout: "", stderr: "" }) }), 0);
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it("release #4820 INFRA-1: streams are capped, and a 4xx-rejected answer becomes a small rc 1 answer, never a re-run", async () => {
|
|
114
|
+
const answers = [], ran = [];
|
|
115
|
+
let first = true;
|
|
116
|
+
const t = { relayPending: async () => [{ rid: "r1", argv: ["obs-psql", "-c", "big"] }],
|
|
117
|
+
relayAnswer: async (id, rid, out) => { if (first) { first = false; throw Object.assign(new Error("HTTP 413"), { status: 413 }); } answers.push(out); } };
|
|
118
|
+
const n = await servicePending({ transport: t, id: "s1", relay: RELAY, run: async (argv) => { ran.push(argv); return { rc: 0, stdout: "x".repeat(RELAY_ANSWER_STREAM_MAX * 3), stderr: "" }; } });
|
|
119
|
+
assert.equal(n, 1);
|
|
120
|
+
assert.equal(ran.length, 1);
|
|
121
|
+
assert.equal(answers.length, 1);
|
|
122
|
+
assert.equal(answers[0].rc, 1);
|
|
123
|
+
assert.match(answers[0].stderr, /rejected by the router \(HTTP 413\)/);
|
|
124
|
+
const posts = [];
|
|
125
|
+
const t3 = { relayPending: async () => [{ rid: "r3", argv: ["obs-psql"] }], relayAnswer: async (id, rid, out) => { posts.push(out); throw Object.assign(new Error("x"), { status: 502 }); } };
|
|
126
|
+
assert.equal(await servicePending({ transport: t3, id: "s1", relay: RELAY, run: async () => ({ rc: 0, stdout: "", stderr: "" }) }), 0);
|
|
127
|
+
assert.equal(posts.length, 1);
|
|
128
|
+
const capped = []; const t2 = { relayPending: async () => [{ rid: "r2", argv: ["obs-psql"] }], relayAnswer: async (id, rid, out) => { capped.push(out); } };
|
|
129
|
+
await servicePending({ transport: t2, id: "s1", relay: RELAY, run: async () => ({ rc: 0, stdout: "y".repeat(RELAY_ANSWER_STREAM_MAX + 10), stderr: "" }) });
|
|
130
|
+
assert.ok(capped[0].stdout.length < RELAY_ANSWER_STREAM_MAX + 100);
|
|
131
|
+
assert.match(capped[0].stdout, /output truncated/);
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
describe("#4778 provider and config", () => {
|
|
136
|
+
it("parseExecution reads relay_commands; without it the output is unchanged", () => {
|
|
137
|
+
assert.deepEqual(parseExecution({ mode: "remote", relay_commands: ["prod_monitor:obs-psql", "bad cap:x"] }).relay, { prod_monitor: ["obs-psql"] });
|
|
138
|
+
assert.equal("relay" in parseExecution({ mode: "remote" }), false);
|
|
139
|
+
assert.equal("relay" in parseExecution({ mode: "remote", relay_commands: "x:/bin/sh" }), false);
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
it("remote provider exposes relays, so placeLane places a relayed need remote; others stay local", () => {
|
|
143
|
+
const exec = parseExecution({ mode: "remote", max_remote: "2", provider: "remote", endpoint: "http://r", relay_commands: "prod_monitor:obs-psql" });
|
|
144
|
+
const p = providerByName("remote", { batch: { id: "b" }, repo: "o/r", exec, env: {}, transport: fakeTransport() });
|
|
145
|
+
assert.deepEqual(p.relays, ["prod_monitor"]);
|
|
146
|
+
assert.equal(placeLane({ exec, needs: ["prod_monitor"], relays: p.relays }).where, "remote");
|
|
147
|
+
assert.deepEqual(placeLane({ exec, needs: ["sops"], relays: p.relays }), placeLane({ exec, needs: ["sops"] }));
|
|
148
|
+
assert.match(placeLane({ exec, needs: ["sops"], relays: p.relays }).reason, /host capability: sops/);
|
|
149
|
+
const noRelay = { ...fakeTransport() }; delete noRelay.relayPending;
|
|
150
|
+
assert.deepEqual(providerByName("remote", { batch: { id: "b" }, repo: "o/r", exec, env: {}, transport: noRelay }).relays, []);
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
it("start ships relay env and the pre-fetch, never a host secret; status services the relay without changing its result", async () => {
|
|
154
|
+
const t = fakeTransport();
|
|
155
|
+
const ran = [];
|
|
156
|
+
const relayRun = async (argv, { secrets }) => { ran.push(argv); return { rc: 0, stdout: `out ${secrets.includes("host-secret-xyz") ? "known" : "?"} host-secret-xyz`, stderr: "" }; };
|
|
157
|
+
const p = remoteProvider({ batch: { id: "b" }, repo: "o/r", transport: t, env: { FD_TOKEN: "host-secret-xyz" }, gitIdentity: () => null, relayRun,
|
|
158
|
+
settings: { secrets: ["FD_TOKEN"], relay: RELAY, prefetch: (n) => (n === 7 ? [{ argv: ["obs-psql", "-c", "select 1"] }, { argv: ["obs-big"] }] : []) } });
|
|
159
|
+
const h = await p.start({ issue: 7, args: [] });
|
|
160
|
+
const env = t.specs[0].env;
|
|
161
|
+
assert.equal(env.CS_RELAY_COMMANDS, "obs-psql"); assert.equal(env.CS_RELAY_CAPS, "prod_monitor");
|
|
162
|
+
const pre = JSON.parse(Buffer.from(env.CS_RELAY_PREFETCH_B64, "base64").toString());
|
|
163
|
+
assert.deepEqual(pre.map((x) => x.argv), [["obs-psql", "-c", "select 1"], ["obs-big"]]);
|
|
164
|
+
const leak = Object.entries(env).filter(([k, v]) => k.startsWith("CS_RELAY") && String(v).includes("host-secret-xyz"));
|
|
165
|
+
assert.deepEqual(leak, []);
|
|
166
|
+
assert.ok(!Buffer.from(env.CS_RELAY_PREFETCH_B64, "base64").toString().includes("host-secret-xyz"));
|
|
167
|
+
// an entry past the 96 KB cap is dropped
|
|
168
|
+
const tb = fakeTransport();
|
|
169
|
+
await remoteProvider({ batch: { id: "b" }, repo: "o/r", transport: tb, env: {}, gitIdentity: () => null, relayRun: async () => ({ rc: 0, stdout: "x".repeat(200 * 1024), stderr: "" }),
|
|
170
|
+
settings: { relay: RELAY, prefetch: () => [{ argv: ["obs-big"] }] } }).start({ issue: 1, args: [] });
|
|
171
|
+
assert.equal("CS_RELAY_PREFETCH_B64" in tb.specs[0].env, false);
|
|
172
|
+
t.pending = [{ rid: "r1", argv: ["obs-psql"] }, { rid: "r2", argv: ["cat", "/etc/shadow"] }];
|
|
173
|
+
assert.equal(await p.status(h), "running");
|
|
174
|
+
await new Promise((r) => setTimeout(r, 10));
|
|
175
|
+
assert.deepEqual(t.answers.map((a) => [a.rid, a.rc]), [["r1", 0], ["r2", RELAY_REFUSED_RC]]);
|
|
176
|
+
assert.ok(!ran.some((a) => a[0] === "cat"));
|
|
177
|
+
const throwing = fakeTransport(); throwing.relayPending = async () => { throw new Error("router down"); };
|
|
178
|
+
const q = remoteProvider({ batch: { id: "b" }, repo: "o/r", transport: throwing, env: {}, gitIdentity: () => null, settings: { relay: RELAY } });
|
|
179
|
+
assert.equal(await q.status(await q.start({ issue: 2, args: [] })), "running");
|
|
180
|
+
const plain = fakeTransport();
|
|
181
|
+
await remoteProvider({ batch: { id: "b" }, repo: "o/r", transport: plain, env: {}, gitIdentity: () => null }).start({ issue: 3, args: [] });
|
|
182
|
+
assert.deepEqual(Object.keys(plain.specs[0].env).filter((k) => k.startsWith("CS_RELAY")), []);
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
it("readRelayCaps parses CS_RELAY_CAPS", () => {
|
|
186
|
+
assert.deepEqual(readRelayCaps({ CS_RELAY_CAPS: "prod_monitor, Bad Cap ,prod_monitor,obs" }), { relayCaps: ["prod_monitor", "obs"] });
|
|
187
|
+
assert.deepEqual(readRelayCaps({}), {});
|
|
188
|
+
});
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
describe("#4831 oversized relay answers", () => {
|
|
192
|
+
const jsonBytes = (o) => Buffer.byteLength(JSON.stringify(o));
|
|
193
|
+
it("capAnswer leaves a small answer unchanged", () => {
|
|
194
|
+
const a = { rc: 0, stdout: "1\n", stderr: "" };
|
|
195
|
+
assert.equal(capAnswer(a), a);
|
|
196
|
+
});
|
|
197
|
+
it("capAnswer bounds two stream-capped, escape-heavy streams that together exceed the limit", () => {
|
|
198
|
+
const out = capAnswer({ rc: 0, stdout: "\n".repeat(RELAY_ANSWER_STREAM_MAX), stderr: '"'.repeat(RELAY_ANSWER_STREAM_MAX) });
|
|
199
|
+
assert.ok(jsonBytes(out) <= RELAY_ANSWER_MAX_BYTES);
|
|
200
|
+
assert.equal(out.rc, 1);
|
|
201
|
+
});
|
|
202
|
+
it("servicePending caps a ~1 MB quote/newline-heavy answer under the router limit, once, without corrupting multibyte text", async () => {
|
|
203
|
+
const big = 'é"\n'.repeat(250000);
|
|
204
|
+
const t = fakeTransport({ pending: [{ rid: "r1", argv: ["obs-psql"] }] });
|
|
205
|
+
let ran = 0;
|
|
206
|
+
const n = await servicePending({ transport: t, id: "s1", relay: RELAY, run: async () => { ran++; return { rc: 0, stdout: big, stderr: "" }; } });
|
|
207
|
+
assert.equal(n, 1);
|
|
208
|
+
assert.equal(ran, 1);
|
|
209
|
+
const { id, rid, ...out } = t.answers[0];
|
|
210
|
+
assert.ok(jsonBytes(out) <= RELAY_ANSWER_MAX_BYTES && jsonBytes(out) < 1 << 20);
|
|
211
|
+
assert.match(out.stdout + out.stderr, /truncated/);
|
|
212
|
+
assert.ok(out.stdout.length > 0 && !out.stdout.includes("\uFFFD"));
|
|
213
|
+
});
|
|
214
|
+
});
|
|
@@ -319,12 +319,24 @@ describe("pool provider (#4546)", () => {
|
|
|
319
319
|
});
|
|
320
320
|
|
|
321
321
|
describe("remote capacity (GET /status, #4540)", () => {
|
|
322
|
-
const mk = (res) => httpTransport({ endpoint: "https://pool.example/v1", fetchFn: async (url) => { if (res instanceof Error) throw res; assert.equal(url, "https://pool.example/v1/status"); return { status: res.status, ok: res.status < 400, text: async () => res.body ?? "", headers: { get: () => null } }; } });
|
|
322
|
+
const mk = (res) => httpTransport({ endpoint: "https://pool.example/v1", fetchFn: async (url) => { if (res instanceof Error) throw res; if (url.endsWith("/agents")) return { status: 404, ok: false, text: async () => "", headers: { get: () => null } }; assert.equal(url, "https://pool.example/v1/status"); return { status: res.status, ok: res.status < 400, text: async () => res.body ?? "", headers: { get: () => null } }; } });
|
|
323
323
|
it("free integer is reported; 404, malformed, negative and transport errors are unknown (null)", async () => {
|
|
324
324
|
assert.deepEqual(await mk({ status: 200, body: '{"free":3}' }).capacity(), { free: 3 });
|
|
325
325
|
assert.deepEqual(await mk({ status: 200, body: '{"free":0}' }).capacity(), { free: 0 });
|
|
326
326
|
for (const r of [{ status: 404 }, { status: 200, body: "nope" }, { status: 200, body: '{"free":"2"}' }, { status: 200, body: '{"free":-1}' }, new Error("down")]) assert.equal(await mk(r).capacity(), null);
|
|
327
327
|
});
|
|
328
|
+
it("#4788: no online on /status: derived from /agents (ok && !paused); an unreadable /agents stays unknown", async () => {
|
|
329
|
+
const mkA = (status, agents) => httpTransport({ endpoint: "https://pool.example/v1", fetchFn: async (url) => {
|
|
330
|
+
const body = url.endsWith("/agents") ? agents : "";
|
|
331
|
+
const st = url.endsWith("/agents") ? 200 : status;
|
|
332
|
+
return { status: st, ok: st < 400, text: async () => (typeof body === "string" ? body : JSON.stringify(body)), headers: { get: () => null } };
|
|
333
|
+
} });
|
|
334
|
+
const down = { agents: [{ name: "legion", ok: false, error: "timeout" }] };
|
|
335
|
+
assert.deepEqual(await mkA(404, down).capacity(), { online: 0, total: 1 });
|
|
336
|
+
assert.deepEqual(await mkA(404, { agents: [{ ok: true }, { ok: true, paused: true }, { ok: false }] }).capacity(), { online: 1, total: 3 });
|
|
337
|
+
assert.deepEqual(await mkA(200, down).capacity(), { online: 0, total: 1 });
|
|
338
|
+
assert.equal(await mkA(404, "nope").capacity(), null);
|
|
339
|
+
});
|
|
328
340
|
it("remoteProvider.capacity delegates, and is null without a transport capability or on a throw", async () => {
|
|
329
341
|
const batch = openBatch(join(tmpDir("cap-"), "batches"), "bt");
|
|
330
342
|
const p = (transport) => remoteProvider({ batch, repo: "o/r", transport, env: {}, credentials: () => null });
|
|
@@ -21,8 +21,10 @@ import { dirname } from "node:path";
|
|
|
21
21
|
import { safeSegment } from "./ledger.mjs";
|
|
22
22
|
import { scopedEnv } from "./execution.mjs";
|
|
23
23
|
import { resolveCredential } from "./credentials.mjs";
|
|
24
|
+
import { relayCommandNames, runRelayed, servicePending } from "./relay.mjs";
|
|
24
25
|
|
|
25
26
|
const REDACTED = "[redacted]";
|
|
27
|
+
const PREFETCH_MAX_B64 = 96 * 1024; // one env string stays under Linux MAX_ARG_STRLEN (128 KB)
|
|
26
28
|
/** Replace every value of `secrets` (4+ chars, longest first) in `text`. */
|
|
27
29
|
export function redact(text, secrets = []) {
|
|
28
30
|
let s = String(text ?? "");
|
|
@@ -44,7 +46,9 @@ export function isActionsEndpoint(endpoint) {
|
|
|
44
46
|
* GET /sandboxes/:id/usage -> {minutes, agent?} (agent: the pool agent that ran it, #4549), DELETE /sandboxes/:id (404 = gone). `Authorization: Bearer <token>`.
|
|
45
47
|
* 429/503 on launch is a retryable capacity error (`Retry-After` seconds). Error text never carries the token.
|
|
46
48
|
* Optional `POST /sandboxes/:id/stop` (#4612) asks the pool to SIGTERM the lane so its teardown checkpoints and it reports `deferred run.interrupted`; 2xx = sent, 404/405 = unsupported or gone (never a DELETE fallback).
|
|
47
|
-
* Optional `GET /
|
|
49
|
+
* Optional relay (#4778): `GET /sandboxes/:id/relay -> {requests: [{rid, argv}]}` lists a sandbox's pending read-only capability
|
|
50
|
+
* requests (404/405 or malformed = none, an older router) and `POST /sandboxes/:id/relay/:rid` `{rc, stdout, stderr}` answers one.
|
|
51
|
+
* Optional `GET /status -> {free: N, online?, total?}` is the pool's free slots (#4540); without `online` the agents of `GET /agents` give it (#4788). Anything else (404, error, malformed) is unknown (null).
|
|
48
52
|
*/
|
|
49
53
|
export function httpTransport({ endpoint, token = null, fetchFn = globalThis.fetch }) {
|
|
50
54
|
const root = String(endpoint ?? "").replace(/\/+$/, "");
|
|
@@ -77,16 +81,25 @@ export function httpTransport({ endpoint, token = null, fetchFn = globalThis.fet
|
|
|
77
81
|
async usage(id) { const r = await call("GET", `${p(id)}/usage`); return r.ok && Number.isFinite(Number(r.data?.minutes)) ? { minutes: Number(r.data.minutes), ...(typeof r.data.agent === "string" && r.data.agent ? { agent: r.data.agent } : {}) } : null; }, // agent: #4549, optional
|
|
78
82
|
async stop(id) { const r = await call("POST", `${p(id)}/stop`); if (r.ok) return true; if (r.status === 404 || r.status === 405) return false; throw fail("stop", r); },
|
|
79
83
|
async destroy(id) { const r = await call("DELETE", p(id)); if (r.ok || r.status === 404) return true; throw fail("destroy", r); },
|
|
84
|
+
async relayPending(id) { const r = await call("GET", `${p(id)}/relay`); return r.ok && Array.isArray(r.data?.requests) ? r.data.requests : []; },
|
|
85
|
+
async relayAnswer(id, rid, out) { const r = await call("POST", `${p(id)}/relay/${encodeURIComponent(rid)}`, out); if (!r.ok) throw fail("relay answer", r); return true; },
|
|
80
86
|
async capacity() {
|
|
81
87
|
// `free` (#4540) and agent liveness `online`/`total` (#4547) are each optional; none valid is unknown.
|
|
88
|
+
const ok = (v) => Number.isInteger(v) && v >= 0;
|
|
89
|
+
let out = {};
|
|
82
90
|
try {
|
|
83
91
|
const r = await call("GET", "/status");
|
|
84
|
-
if (
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
92
|
+
if (r.ok) { const { free, online, total } = r.data ?? {}; out = { ...(ok(free) ? { free } : {}), ...(ok(online) ? { online } : {}), ...(ok(total) ? { total } : {}) }; }
|
|
93
|
+
} catch { out = {}; }
|
|
94
|
+
if (out.online === undefined) {
|
|
95
|
+
// #4788: a router without /status liveness: online = agents answering and not paused, as bin/pool/router.mjs status() does.
|
|
96
|
+
try {
|
|
97
|
+
const r = await call("GET", "/agents");
|
|
98
|
+
const list = r.ok && Array.isArray(r.data?.agents) ? r.data.agents : null;
|
|
99
|
+
if (list) out = { ...out, online: list.filter((a) => a?.ok === true && !a.paused).length, total: list.length };
|
|
100
|
+
} catch { /* liveness stays unknown */ }
|
|
101
|
+
}
|
|
102
|
+
return Object.keys(out).length ? out : null;
|
|
90
103
|
},
|
|
91
104
|
};
|
|
92
105
|
}
|
|
@@ -111,7 +124,8 @@ export function gitIdentityEnv(identity, laneEnv = {}) {
|
|
|
111
124
|
return out;
|
|
112
125
|
}
|
|
113
126
|
|
|
114
|
-
export function remoteProvider({ batch, repo, settings = {}, name = "remote", transport, env = process.env, credentials = (name) => resolveCredential(name, { env }), now = () => Date.now(), gitIdentity = hostGitIdentity
|
|
127
|
+
export function remoteProvider({ batch, repo, settings = {}, name = "remote", transport, env = process.env, credentials = (name) => resolveCredential(name, { env }), now = () => Date.now(), gitIdentity = hostGitIdentity,
|
|
128
|
+
relayRun = runRelayed }) {
|
|
115
129
|
if (!transport) throw new Error("remote provider needs a transport");
|
|
116
130
|
const idFor = (issue) => `fdrsbx-${safeSegment(batch.id)}-${issue}`;
|
|
117
131
|
const known = new Set(); // secret values seen this process, for redaction
|
|
@@ -124,6 +138,32 @@ export function remoteProvider({ batch, repo, settings = {}, name = "remote", tr
|
|
|
124
138
|
if (m === null && Number.isFinite(h.startedAt)) m = Math.round(((now() - h.startedAt) / 60000) * 10) / 10;
|
|
125
139
|
if (m !== null) h.minutes = Math.max(h.minutes ?? 0, m);
|
|
126
140
|
};
|
|
141
|
+
// #4778: capabilities the host relays (execution.relay_commands), only over a transport that carries relay requests.
|
|
142
|
+
const relay = settings.relay && typeof settings.relay === "object" ? settings.relay : {};
|
|
143
|
+
const relays = typeof transport.relayPending === "function" ? Object.keys(relay).filter((c) => relay[c]?.length).sort() : [];
|
|
144
|
+
const inflight = new Set();
|
|
145
|
+
const serviceRelay = async (h) => {
|
|
146
|
+
if (!relays.length || inflight.has(h.id)) return 0;
|
|
147
|
+
inflight.add(h.id);
|
|
148
|
+
try { return await servicePending({ transport, id: h.id, relay, run: relayRun, secrets: [...known] }); } catch { return 0; } finally { inflight.delete(h.id); }
|
|
149
|
+
};
|
|
150
|
+
// #4778: the frozen contract's read-only queries, run on the host at dispatch and shipped with the lane (96 KB cap).
|
|
151
|
+
const prefetchEnv = async (issue) => {
|
|
152
|
+
if (!relays.length || typeof settings.prefetch !== "function") return {};
|
|
153
|
+
let cmds = [];
|
|
154
|
+
try { cmds = settings.prefetch(issue) ?? []; } catch { cmds = []; }
|
|
155
|
+
const list = [];
|
|
156
|
+
let b64 = "";
|
|
157
|
+
for (const { argv } of Array.isArray(cmds) ? cmds : []) {
|
|
158
|
+
const raw = await relayRun(argv, { secrets: [...known] });
|
|
159
|
+
const out = { rc: Number.isInteger(raw?.rc) ? raw.rc : 1, stdout: redact(raw?.stdout, [...known]), stderr: redact(raw?.stderr, [...known]) };
|
|
160
|
+
const next = Buffer.from(JSON.stringify([...list, { argv, ...out }])).toString("base64");
|
|
161
|
+
if (next.length > PREFETCH_MAX_B64) continue;
|
|
162
|
+
list.push({ argv, ...out });
|
|
163
|
+
b64 = next;
|
|
164
|
+
}
|
|
165
|
+
return b64 ? { CS_RELAY_PREFETCH_B64: b64 } : {};
|
|
166
|
+
};
|
|
127
167
|
const pullLogs = async (h) => {
|
|
128
168
|
if (!transport.logs) return;
|
|
129
169
|
try {
|
|
@@ -135,6 +175,8 @@ export function remoteProvider({ batch, repo, settings = {}, name = "remote", tr
|
|
|
135
175
|
return {
|
|
136
176
|
name,
|
|
137
177
|
idFor,
|
|
178
|
+
relays,
|
|
179
|
+
serviceRelay,
|
|
138
180
|
async start({ issue, args = [], env: laneEnv = env, secrets = settings.secrets ?? [] }) {
|
|
139
181
|
const id = idFor(issue);
|
|
140
182
|
// Each allowlisted secret from the env, else the keychain (#4254); nothing else from the host.
|
|
@@ -142,12 +184,13 @@ export function remoteProvider({ batch, repo, settings = {}, name = "remote", tr
|
|
|
142
184
|
for (const k of secrets) { const v = laneEnv?.[k] !== undefined && laneEnv[k] !== "" ? String(laneEnv[k]) : credentials(k); if (v) { resolved[k] = v; remember(v); } }
|
|
143
185
|
const li = args.indexOf("--lane");
|
|
144
186
|
const resultFile = `/result/${issue}.json`;
|
|
187
|
+
const relayEnv = relays.length ? { CS_RELAY_COMMANDS: relayCommandNames(relay).join(","), CS_RELAY_CAPS: relays.join(","), ...(await prefetchEnv(issue)) } : {};
|
|
145
188
|
const spec = {
|
|
146
189
|
id, issue, batch: batch.id, image: settings.image ?? null,
|
|
147
190
|
repo: { slug: repo, url: repo ? `https://github.com/${repo}.git` : null, ref: li >= 0 ? args[li + 1] ?? null : null },
|
|
148
191
|
cache: settings.cacheStore ? { store: settings.cacheStore, key: safeSegment(String(repo ?? "repo")) } : null,
|
|
149
192
|
// The host's git identity: without it the lane image falls back to a placeholder author that fails DCO.
|
|
150
|
-
env: { ...gitIdentityEnv(gitIdentity(), laneEnv ?? {}), ...scopedEnv({ env: resolved, secrets, batchId: batch.id, repo }), ...(settings.forgeYaml ? { CS_FORGE_YAML_B64: Buffer.from(settings.forgeYaml).toString("base64") } : {}) }, // #4546: the dispatcher's forge.yaml (gitignored in the repo)
|
|
193
|
+
env: { ...gitIdentityEnv(gitIdentity(), laneEnv ?? {}), ...scopedEnv({ env: resolved, secrets, batchId: batch.id, repo }), ...(settings.forgeYaml ? { CS_FORGE_YAML_B64: Buffer.from(settings.forgeYaml).toString("base64") } : {}), ...relayEnv }, // #4546: the dispatcher's forge.yaml (gitignored in the repo)
|
|
151
194
|
command: ["forgedock", "run-issue", String(issue), ...args, "--result-file", resultFile], result_file: resultFile,
|
|
152
195
|
};
|
|
153
196
|
const startedAt = now();
|
|
@@ -159,6 +202,7 @@ export function remoteProvider({ batch, repo, settings = {}, name = "remote", tr
|
|
|
159
202
|
// #4672: a transport error is not an exit; it propagates and providerLanes retries it for execution.unreachable_window_min.
|
|
160
203
|
s = await transport.status(h.id);
|
|
161
204
|
await pullLogs(h);
|
|
205
|
+
if (s === "running") serviceRelay(h).catch(() => {}); // #4778: in the background; never changes the status
|
|
162
206
|
return s === "running" ? "running" : s === "gone" ? "gone" : "exited";
|
|
163
207
|
},
|
|
164
208
|
async fetchResult(h) {
|
package/bin/lean/sched.test.mjs
CHANGED
|
@@ -78,6 +78,15 @@ describe("host lane registry (#4191)", () => {
|
|
|
78
78
|
assert.equal(a2.list().slots.length, 3);
|
|
79
79
|
});
|
|
80
80
|
|
|
81
|
+
it("sched show reports the schedd tick age (#4780)", async () => {
|
|
82
|
+
const { handle } = world();
|
|
83
|
+
const lines = [];
|
|
84
|
+
const l = console.log; console.log = (m) => lines.push(String(m));
|
|
85
|
+
try { await schedFromCli(["show"], { sched: handle(401) }); } finally { console.log = l; }
|
|
86
|
+
assert.ok(lines.some((m) => /^schedd: (not running|pid \d+, last tick \d+ s ago)/.test(m)), lines.join("\n"));
|
|
87
|
+
assert.ok(lines.some((m) => m.startsWith("host cap:")), "existing lines kept");
|
|
88
|
+
});
|
|
89
|
+
|
|
81
90
|
it("forgedock sched cap changes the cap live; --clear falls back to the caller's config", async () => {
|
|
82
91
|
const { handle } = world();
|
|
83
92
|
const a = handle(301), b = handle(302);
|
|
@@ -482,3 +491,24 @@ describe("#4481: one lane per repo and issue across batches", () => {
|
|
|
482
491
|
assert.equal(maxActive.get(5), 1);
|
|
483
492
|
});
|
|
484
493
|
});
|
|
494
|
+
|
|
495
|
+
describe("live local lane cap (#4777)", () => {
|
|
496
|
+
it("sched.cap as a function is evaluated at every admission: a lowered cap queues the next lane until it is raised", async () => {
|
|
497
|
+
const { handle } = world();
|
|
498
|
+
const registry = handle(7101);
|
|
499
|
+
const cap = { n: 1 };
|
|
500
|
+
let running = 0, peak = 0;
|
|
501
|
+
const gate = { open: false };
|
|
502
|
+
const runOne = async () => { running++; peak = Math.max(peak, running); await until(() => gate.open, "gate"); running--; return { terminalReason: "merged", cost_usd: 0 }; };
|
|
503
|
+
const p = orchestrate({ issues: [1, 2], parallel: 5, readBody: async () => "", runOne, pollMs: 2, batchId: "lc", sched: { registry, batch: "lc", repo: "o/r", cap: () => cap.n } });
|
|
504
|
+
await until(() => running === 1, "first lane");
|
|
505
|
+
await new Promise((r) => setTimeout(r, 30));
|
|
506
|
+
assert.equal(running, 1, "cap 1 keeps the second lane queued");
|
|
507
|
+
cap.n = 2;
|
|
508
|
+
await until(() => running === 2, "second lane after the cap rises");
|
|
509
|
+
gate.open = true;
|
|
510
|
+
const rows = await p;
|
|
511
|
+
assert.deepEqual(rows.map((r) => r.outcome), ["merged", "merged"]);
|
|
512
|
+
assert.equal(peak, 2);
|
|
513
|
+
});
|
|
514
|
+
});
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* schedd liveness (#4780). The daemon's event loop writes `heartbeat.json` ({pid, ts}) every `HEARTBEAT_MS`; a starved or
|
|
5
|
+
* wedged loop stops writing, so the file goes stale while the pid stays alive (which `Restart=always` cannot see).
|
|
6
|
+
* `sched show` / `schedd status` report "last tick N s ago" from it, and `watchdog` (run by a systemd timer, outside the
|
|
7
|
+
* daemon) signals a live daemon whose heartbeat is older than `stallMs`; the unit's `Restart=always` then restarts it and
|
|
8
|
+
* the new daemon resumes every hosted batch.
|
|
9
|
+
*/
|
|
10
|
+
import { readFileSync, rmSync } from "node:fs";
|
|
11
|
+
import { setPriority } from "node:os";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import { writeAtomic } from "./batch.mjs";
|
|
14
|
+
import { schedDir, pidAlive } from "./sched.mjs";
|
|
15
|
+
|
|
16
|
+
export const HEARTBEAT_MS = 5 * 1000;
|
|
17
|
+
export const STALL_MS = 60 * 1000;
|
|
18
|
+
export const KILL_GRACE_MS = 10 * 1000;
|
|
19
|
+
|
|
20
|
+
export const heartbeatPath = (dir = schedDir()) => join(dir, "heartbeat.json");
|
|
21
|
+
|
|
22
|
+
/** Record a tick now. */
|
|
23
|
+
export function writeHeartbeat({ dir = schedDir(), pid = process.pid, now = () => Date.now() } = {}) {
|
|
24
|
+
writeAtomic(heartbeatPath(dir), JSON.stringify({ pid, ts: now() }));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The last heartbeat `{pid, ts}`, or null when absent or unreadable. */
|
|
28
|
+
export function readHeartbeat(dir = schedDir()) {
|
|
29
|
+
try {
|
|
30
|
+
const h = JSON.parse(readFileSync(heartbeatPath(dir), "utf8"));
|
|
31
|
+
return Number.isInteger(h?.pid) && Number.isFinite(h?.ts) ? h : null;
|
|
32
|
+
} catch { return null; }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export const clearHeartbeat = (dir = schedDir()) => rmSync(heartbeatPath(dir), { force: true });
|
|
36
|
+
|
|
37
|
+
/** `{status:"ok"|"stalled"|"down", pid, ageMs}`: down = no heartbeat or its pid is gone. */
|
|
38
|
+
export function stallCheck({ dir = schedDir(), stallMs = STALL_MS, now = () => Date.now(), alive = pidAlive } = {}) {
|
|
39
|
+
const h = readHeartbeat(dir);
|
|
40
|
+
if (!h || !alive(h.pid)) return { status: "down", pid: h?.pid ?? null, ageMs: h ? now() - h.ts : null };
|
|
41
|
+
const ageMs = Math.max(0, now() - h.ts);
|
|
42
|
+
return { status: ageMs > stallMs ? "stalled" : "ok", pid: h.pid, ageMs };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The `last tick N s ago` text for a stall-check result. */
|
|
46
|
+
export function tickText(c) {
|
|
47
|
+
if (c.status === "down") return "schedd: not running";
|
|
48
|
+
const s = `schedd: pid ${c.pid}, last tick ${Math.round(c.ageMs / 1000)} s ago`;
|
|
49
|
+
return c.status === "stalled" ? `${s} (STALLED)` : s;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Signal a stalled live daemon: SIGTERM, then SIGKILL after `graceMs` if it is still alive. @returns the check, plus `killed` */
|
|
53
|
+
export async function watchdog({ dir = schedDir(), stallMs = STALL_MS, now = () => Date.now(), alive = pidAlive, kill = (p, s) => process.kill(p, s),
|
|
54
|
+
sleep = (ms) => new Promise((r) => setTimeout(r, ms)), graceMs = KILL_GRACE_MS, log = (m) => console.log(m) } = {}) {
|
|
55
|
+
const c = stallCheck({ dir, stallMs, now, alive });
|
|
56
|
+
if (c.status !== "stalled") return { ...c, killed: null };
|
|
57
|
+
log(`schedd watchdog: pid ${c.pid} silent for ${Math.round(c.ageMs / 1000)} s (limit ${Math.round(stallMs / 1000)} s), sending SIGTERM`);
|
|
58
|
+
try { kill(c.pid, "SIGTERM"); } catch { return { ...c, killed: null }; }
|
|
59
|
+
await sleep(graceMs);
|
|
60
|
+
if (!alive(c.pid)) return { ...c, killed: "SIGTERM" };
|
|
61
|
+
log(`schedd watchdog: pid ${c.pid} ignored SIGTERM, sending SIGKILL`);
|
|
62
|
+
try { kill(c.pid, "SIGKILL"); } catch { /* gone */ }
|
|
63
|
+
return { ...c, killed: "SIGKILL" };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Raise the daemon's own scheduling priority; a user without CAP_SYS_NICE cannot, and that is fine (never throws). */
|
|
67
|
+
export function bestEffortRenice(set = setPriority, level = -5) {
|
|
68
|
+
try { set(0, level); return true; } catch { return false; }
|
|
69
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
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 { tmpDir } from "../tests/_tmp.mjs";
|
|
6
|
+
import { writeHeartbeat, readHeartbeat, clearHeartbeat, stallCheck, tickText, watchdog, bestEffortRenice } from "./schedd-health.mjs";
|
|
7
|
+
|
|
8
|
+
describe("schedd heartbeat and watchdog (#4780)", () => {
|
|
9
|
+
it("heartbeat round-trips and clears", () => {
|
|
10
|
+
const dir = tmpDir("hb-");
|
|
11
|
+
assert.equal(readHeartbeat(dir), null);
|
|
12
|
+
writeHeartbeat({ dir, pid: 42, now: () => 1000 });
|
|
13
|
+
assert.deepEqual(readHeartbeat(dir), { pid: 42, ts: 1000 });
|
|
14
|
+
clearHeartbeat(dir);
|
|
15
|
+
assert.equal(readHeartbeat(dir), null);
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
it("stallCheck: ok when fresh, stalled when old with a live pid, down when pid gone or no file", () => {
|
|
19
|
+
const dir = tmpDir("hb-");
|
|
20
|
+
assert.equal(stallCheck({ dir }).status, "down");
|
|
21
|
+
writeHeartbeat({ dir, pid: 42, now: () => 1000 });
|
|
22
|
+
const at = (t, alive = true) => stallCheck({ dir, stallMs: 60_000, now: () => t, alive: () => alive });
|
|
23
|
+
assert.equal(at(1000 + 30_000).status, "ok");
|
|
24
|
+
assert.equal(at(1000 + 61_000).status, "stalled");
|
|
25
|
+
assert.equal(at(1000 + 61_000, false).status, "down");
|
|
26
|
+
assert.match(tickText(at(1000 + 30_000)), /pid 42, last tick 30 s ago/);
|
|
27
|
+
assert.match(tickText(at(1000 + 90_000)), /last tick 90 s ago \(STALLED\)/);
|
|
28
|
+
assert.equal(tickText(at(1000, false)), "schedd: not running");
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it("watchdog signals only a stalled live daemon: TERM, then KILL when it survives", async () => {
|
|
32
|
+
const dir = tmpDir("hb-");
|
|
33
|
+
writeHeartbeat({ dir, pid: 42, now: () => 0 });
|
|
34
|
+
const sent = [];
|
|
35
|
+
const run = (t, alive) => watchdog({ dir, stallMs: 60_000, now: () => t, alive, kill: (p, s) => sent.push([p, s]), sleep: async () => {}, graceMs: 0, log: () => {} });
|
|
36
|
+
assert.equal((await run(30_000, () => true)).killed, null);
|
|
37
|
+
assert.equal((await run(90_000, () => false)).killed, null);
|
|
38
|
+
assert.deepEqual(sent, [], "a fresh or dead daemon is never signalled");
|
|
39
|
+
let calls = 0;
|
|
40
|
+
assert.equal((await run(90_000, () => ++calls === 1)).killed, "SIGTERM");
|
|
41
|
+
assert.deepEqual(sent, [[42, "SIGTERM"]]);
|
|
42
|
+
sent.length = 0;
|
|
43
|
+
assert.equal((await run(90_000, () => true)).killed, "SIGKILL");
|
|
44
|
+
assert.deepEqual(sent, [[42, "SIGTERM"], [42, "SIGKILL"]]);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it("bestEffortRenice never throws", () => {
|
|
48
|
+
assert.equal(bestEffortRenice(() => { throw new Error("EACCES"); }), false);
|
|
49
|
+
assert.equal(bestEffortRenice(() => {}), true);
|
|
50
|
+
});
|
|
51
|
+
});
|