forgedock 1.61.2 → 1.62.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/config-schema.mjs +10 -1
- package/bin/engine/outcome-codes.mjs +4 -0
- package/bin/engine-cli.mjs +159 -17
- package/bin/env/env.mjs +6 -4
- package/bin/forge-home-check.mjs +91 -0
- package/bin/forgedock.mjs +50 -7
- package/bin/gc.mjs +2 -0
- package/bin/hooks/pre-tool-use.mjs +4 -0
- package/bin/journey.mjs +55 -5
- package/bin/lean/admission.mjs +16 -5
- package/bin/lean/batch-health.mjs +55 -16
- package/bin/lean/batch-health.test.mjs +67 -1
- package/bin/lean/batch.mjs +8 -0
- package/bin/lean/batch.test.mjs +5 -0
- package/bin/lean/ceiling.mjs +20 -0
- package/bin/lean/ceiling.test.mjs +33 -2
- package/bin/lean/ci-gate.mjs +240 -0
- package/bin/lean/ci-gate.test.mjs +227 -0
- package/bin/lean/ci-precheck.mjs +178 -0
- package/bin/lean/ci-precheck.test.mjs +149 -0
- package/bin/lean/conformance.mjs +85 -9
- package/bin/lean/conformance.test.mjs +155 -3
- package/bin/lean/context.test.mjs +7 -6
- package/bin/lean/dag.mjs +128 -0
- package/bin/lean/dag.test.mjs +131 -0
- package/bin/lean/decisions.mjs +5 -4
- package/bin/lean/decisions.test.mjs +11 -0
- package/bin/lean/delguard.mjs +84 -0
- package/bin/lean/delguard.test.mjs +104 -0
- package/bin/lean/depcache.mjs +125 -17
- package/bin/lean/depcache.test.mjs +111 -0
- package/bin/lean/design-gate.mjs +5 -5
- package/bin/lean/design-gate.test.mjs +14 -0
- package/bin/lean/effects.mjs +72 -4
- package/bin/lean/execution.mjs +41 -7
- package/bin/lean/execution.test.mjs +99 -3
- package/bin/lean/forgedock-lane-workflow.test.mjs +35 -0
- package/bin/lean/guardgate.mjs +30 -7
- package/bin/lean/guardgate.test.mjs +44 -1
- package/bin/lean/guards.test.mjs +1 -1
- package/bin/lean/heavy.test.mjs +87 -0
- package/bin/lean/hotarea.mjs +73 -0
- package/bin/lean/hotarea.test.mjs +73 -0
- package/bin/lean/issuewatch-reconcile.mjs +20 -1
- package/bin/lean/issuewatch-reconcile.test.mjs +30 -0
- package/bin/lean/lanecheck.mjs +27 -3
- package/bin/lean/lanecheck.test.mjs +47 -5
- package/bin/lean/laneconfine.mjs +83 -0
- package/bin/lean/laneconfine.test.mjs +113 -0
- package/bin/lean/lean.mjs +376 -79
- package/bin/lean/lean.test.mjs +710 -22
- package/bin/lean/live-reconcile.mjs +169 -0
- package/bin/lean/live-reconcile.test.mjs +176 -0
- package/bin/lean/orchestrate-envhold.test.mjs +245 -0
- package/bin/lean/orchestrate-hostfallback.test.mjs +39 -0
- package/bin/lean/orchestrate.mjs +207 -17
- package/bin/lean/outcomeevidence.mjs +104 -0
- package/bin/lean/outcomeevidence.test.mjs +78 -0
- package/bin/lean/page-capture.mjs +68 -0
- package/bin/lean/page-capture.test.mjs +44 -0
- package/bin/lean/pagegate.mjs +46 -7
- package/bin/lean/pagegate.test.mjs +66 -1
- package/bin/lean/postdeploy-check.mjs +18 -4
- package/bin/lean/postdeploy-check.test.mjs +32 -1
- package/bin/lean/prefilter.mjs +36 -4
- package/bin/lean/prefilter.test.mjs +31 -1
- package/bin/lean/preflight.mjs +22 -0
- package/bin/lean/preflight.test.mjs +19 -1
- package/bin/lean/probe.mjs +18 -0
- package/bin/lean/probe.test.mjs +40 -0
- package/bin/lean/prompts.mjs +40 -3
- package/bin/lean/recovery.test.mjs +20 -0
- package/bin/lean/recurrence.mjs +133 -0
- package/bin/lean/recurrence.test.mjs +99 -0
- package/bin/lean/release-config.mjs +2 -1
- package/bin/lean/release-config.test.mjs +18 -0
- package/bin/lean/release-control.mjs +4 -2
- package/bin/lean/release-control.test.mjs +15 -0
- package/bin/lean/release-merge-hold.mjs +65 -0
- package/bin/lean/release-merge-hold.test.mjs +69 -0
- package/bin/lean/release-review.mjs +26 -9
- package/bin/lean/release-review.test.mjs +53 -0
- package/bin/lean/release-status.mjs +3 -1
- package/bin/lean/release-status.test.mjs +11 -0
- package/bin/lean/release.test.mjs +26 -1
- package/bin/lean/render.mjs +8 -7
- package/bin/lean/routing.mjs +49 -0
- package/bin/lean/routing.test.mjs +54 -1
- package/bin/lean/run-issue-placement.test.mjs +30 -1
- package/bin/lean/sandbox-actions.mjs +121 -0
- package/bin/lean/sandbox-actions.test.mjs +94 -0
- package/bin/lean/sandbox-provider.contract.test.mjs +22 -1
- package/bin/lean/sandbox-remote.mjs +3 -1
- package/bin/lean/schedd-health.mjs +14 -2
- package/bin/lean/schedd-health.test.mjs +13 -0
- package/bin/lean/schedd.mjs +43 -17
- package/bin/lean/schedd.test.mjs +61 -1
- package/bin/lean/toolchain.mjs +16 -6
- package/bin/lean/toolplace.mjs +12 -0
- package/bin/lean/weakguard.mjs +105 -0
- package/bin/lean/weakguard.test.mjs +59 -0
- package/bin/lean/winspawn.mjs +61 -0
- package/bin/lean/winspawn.test.mjs +45 -0
- package/bin/lean/worktree.mjs +3 -1
- package/bin/lean/worktree.test.mjs +11 -0
- package/bin/pool/agent.mjs +210 -14
- package/bin/pool/cache-sweep.mjs +74 -0
- package/bin/pool/cli.mjs +11 -3
- package/bin/pool/docker.mjs +33 -2
- package/bin/pool/health.mjs +38 -0
- package/bin/pool/lane-tools.mjs +23 -4
- package/bin/pool/lane-tools.test.mjs +12 -1
- package/bin/pool/router.mjs +21 -3
- package/bin/runner.mjs +37 -0
- package/bin/splash-scene.mjs +356 -0
- package/bin/win-hide-children.mjs +114 -0
- package/commands/orchestrate.md +18 -27
- package/commands/review-pr-agents/infra.md +1 -0
- package/commands/review-pr-staging.md +2 -2
- package/docs/CONFIG.md +60 -3
- package/docs/OUTCOME-CODES.md +3 -0
- package/package.json +1 -1
- package/plugins/forgedock-splash/.claude-plugin/plugin.json +1 -1
- package/plugins/forgedock-splash/README.md +1 -1
- package/plugins/forgedock-splash/hooks/scene.ts +142 -8
- package/pool/README.md +6 -0
- package/pool/image/entrypoint.sh +1 -0
- package/scripts/check-spec-size.sh +3 -1
- package/scripts/gen-splash-scene.mjs +24 -0
- package/scripts/review-staging-pre.sh +8 -3
- package/scripts/review-staging-pre.test.sh +2 -0
package/bin/pool/agent.mjs
CHANGED
|
@@ -13,7 +13,9 @@ import { bearerOk, call, readJson, route, sameSecret, send } from "./http.mjs";
|
|
|
13
13
|
import { repoRoot, versionOf, laneImageTag, laneBuildArgs } from "./version.mjs";
|
|
14
14
|
import { jsonStore } from "./store.mjs";
|
|
15
15
|
import { makeWarm } from "./warm.mjs";
|
|
16
|
-
import { resolveLaneImage, laneImageNow, laneToolsTag } from "./lane-tools.mjs";
|
|
16
|
+
import { resolveLaneImage, laneImageNow, laneToolsTag, isLaneToolsTagOf } from "./lane-tools.mjs";
|
|
17
|
+
import { hostDiskFree } from "./health.mjs";
|
|
18
|
+
import { planIdleEviction, CACHE_LABEL } from "./cache-sweep.mjs";
|
|
17
19
|
|
|
18
20
|
const LABEL = "computeshare=1";
|
|
19
21
|
const LOG_CHUNK = 256 * 1024;
|
|
@@ -83,7 +85,7 @@ const envLine = (k, v) => `${k}=${String(v).replace(/\r?\n/g, " ")}`;
|
|
|
83
85
|
* Host agent: runs each sandbox as one docker container inside a fixed reservation (allow_cpus / allow_mem_gb).
|
|
84
86
|
* A sandbox lives only while its lease is renewed; the reaper removes expired, over-age and orphaned containers.
|
|
85
87
|
*/
|
|
86
|
-
export function createAgent(cfg, { docker, now = () => Date.now(), log = console, live = liveHeadroom } = {}) {
|
|
88
|
+
export function createAgent(cfg, { docker, now = () => Date.now(), log = console, live = liveHeadroom, hostDisk = null } = {}) {
|
|
87
89
|
const stateDir = cfg.state_dir;
|
|
88
90
|
const store = jsonStore(join(stateDir, "state.json"), { sandboxes: {} });
|
|
89
91
|
const sb = () => store.data.sandboxes;
|
|
@@ -121,6 +123,11 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
121
123
|
// #5535: disk figures for the router inventory; optional, omitted when unreadable. Sandbox dirs are walked at most every 60s.
|
|
122
124
|
let diskCache = { at: 0, mb: {} };
|
|
123
125
|
let lastWorkSweep = -Infinity;
|
|
126
|
+
let lastCachePrune = -Infinity;
|
|
127
|
+
// #5757: cache volume hygiene state: per-volume sweep error/size/last use (last use also from launches in this process).
|
|
128
|
+
let lastCacheSweep = -Infinity;
|
|
129
|
+
const cacheErr = new Map(), cacheInfo = new Map(), cacheUsed = new Map();
|
|
130
|
+
const sweepFail = (v, what, e) => { const m = `${what} ${v}: ${String(e.stderr || e.message).slice(0, 200)}`; cacheErr.set(`${what}:${v}`, m); log.warn?.(m); };
|
|
124
131
|
const dirMb = (d) => { let n = 0, seen = 0; const walk = (x) => { if (seen++ > 200000) return; let st; try { st = lstatSync(x); } catch { return; } n += st.size; if (st.isDirectory()) { try { for (const e of readdirSync(x)) walk(join(x, e)); } catch { /* unreadable */ } } }; walk(d); return Math.round(n / 1048576); };
|
|
125
132
|
function diskView() {
|
|
126
133
|
const out = {};
|
|
@@ -133,9 +140,96 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
133
140
|
out.sandbox_disk_mb = diskCache.mb;
|
|
134
141
|
return out;
|
|
135
142
|
}
|
|
143
|
+
// #5733: free space on the Windows drive behind a WSL distro's vhdx (null off WSL or unreadable: no field, no gate).
|
|
144
|
+
let hostDiskCache = { at: -Infinity, v: null };
|
|
145
|
+
const readHostDisk = hostDisk ?? (() => {
|
|
146
|
+
if (now() - hostDiskCache.at > 60000) hostDiskCache = { at: now(), v: hostDiskFree({ path: cfg.host_disk_path ?? null }) };
|
|
147
|
+
return hostDiskCache.v;
|
|
148
|
+
});
|
|
149
|
+
/** Under the floor now, or once the running sandboxes plus the new one grow the vhdx by sandbox_disk_growth_gb each. */
|
|
150
|
+
const hostDiskLow = (free, active) => { const floor = cfg.min_host_disk_free_gb ?? 25; return free < floor || free - (cfg.sandbox_disk_growth_gb ?? 3.5) * (active + 1) < floor; };
|
|
151
|
+
function hostDiskView(active) {
|
|
152
|
+
let hd = null; try { hd = readHostDisk(); } catch { hd = null; }
|
|
153
|
+
if (!hd || !Number.isFinite(hd.gb)) return {};
|
|
154
|
+
return { host_disk_free_gb: hd.gb, host_disk_low: hostDiskLow(hd.gb, active) };
|
|
155
|
+
}
|
|
156
|
+
// #5856: priority classes. `reserved` sandboxes are admitted up to a named reservation (cfg.reservations) and may reclaim
|
|
157
|
+
// capacity from `borrow` ones (throttle first, then SIGTERM so the lane checkpoints and reports run.interrupted);
|
|
158
|
+
// `normal` stays out of reserved space; `borrow` may use reserved-but-idle space. Without reservations/idle_only: flat, as before.
|
|
159
|
+
const PRIORITIES = ["reserved", "normal", "borrow"];
|
|
160
|
+
const reservations = () => (Array.isArray(cfg.reservations) ? cfg.reservations.filter((r) => r && typeof r.name === "string" && r.cpus > 0 && r.mem_gb > 0) : []);
|
|
161
|
+
const prioOf = (r) => r.priority ?? "normal";
|
|
162
|
+
const activeRecs = () => Object.values(sb()).filter((s) => s.state !== "exited");
|
|
163
|
+
const sumRecs = (rs) => rs.reduce((a, s) => ({ cpus: a.cpus + s.cpus, mem: a.mem + s.mem_gb }), { cpus: 0, mem: 0 });
|
|
164
|
+
const weighted = () => reservations().length > 0 || Boolean(cfg.idle_only);
|
|
165
|
+
const SHARES = () => ({ reserved: 4096, normal: 1024, borrow: 128, throttled: 2, ...(cfg.cpu_shares ?? {}) });
|
|
166
|
+
/** Admission headroom per class: free = physical, unreserved_free = space outside every reservation, borrowable = what `borrow` may take. */
|
|
167
|
+
function tiers() {
|
|
168
|
+
const act = activeRecs(), rs = reservations();
|
|
169
|
+
const tot = rs.reduce((a, r) => ({ cpus: a.cpus + r.cpus, mem: a.mem + r.mem_gb }), { cpus: 0, mem: 0 });
|
|
170
|
+
const u = sumRecs(act), nonRes = sumRecs(act.filter((s) => prioOf(s) !== "reserved"));
|
|
171
|
+
const free = { cpus: cfg.allow_cpus - u.cpus, mem: cfg.allow_mem_gb - u.mem };
|
|
172
|
+
return { act, rs, tot, free, unreserved: { cpus: Math.max(0, Math.min(free.cpus, cfg.allow_cpus - tot.cpus - nonRes.cpus)), mem: Math.max(0, Math.min(free.mem, cfg.allow_mem_gb - tot.mem - nonRes.mem)) } };
|
|
173
|
+
}
|
|
174
|
+
/** Owner load per core with this agent's own sandboxes subtracted (the box's primary workload), or null when unknown. */
|
|
175
|
+
function ownerLoad(h) {
|
|
176
|
+
if (!Number.isFinite(h?.load_per_core)) return null;
|
|
177
|
+
const cores = cfg.cores ?? (cpus().length || 1);
|
|
178
|
+
const own = activeRecs().reduce((a, r) => a + (r.cpu_now ?? 0), 0);
|
|
179
|
+
return Math.max(0, h.load_per_core - own / cores);
|
|
180
|
+
}
|
|
181
|
+
/** idle_only: the reason the host is not idle enough to run borrowed lanes, or null. */
|
|
182
|
+
function notIdle(h) {
|
|
183
|
+
if (!cfg.idle_only) return null;
|
|
184
|
+
const load = ownerLoad(h), maxLoad = cfg.idle_max_owner_load_per_core ?? 0.5, minMem = cfg.idle_min_free_mem_gb ?? 4;
|
|
185
|
+
if (load !== null && load > maxLoad) return `owner load ${load.toFixed(2)}/core (> ${maxLoad})`;
|
|
186
|
+
if (Number.isFinite(h?.mem_available_gb) && h.mem_available_gb < minMem) return `only ${h.mem_available_gb} GB available (< ${minMem})`;
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
// Throttle = low cpu weight + a halved soft memory limit (`--memory-reservation`: under host memory pressure the kernel reclaims from containers over it first; the docker CLI has no memory.high).
|
|
190
|
+
const throttle = async (r, shares) => { const memMb = Math.round(r.mem_gb * (shares === SHARES().throttled ? 512 : 1024)); for (const n of r.docker ? [r.name, dindName(r.name)] : [r.name]) { try { await docker.update?.(n, { cpuShares: shares, memoryReservationMb: memMb }); } catch (e) { log.warn?.(`throttle ${n}: ${String(e.stderr || e.message).slice(0, 160)}`); } } r.throttled = shares === SHARES().throttled; };
|
|
191
|
+
/** SIGTERM (the lane checkpoints and reports run.interrupted), wait out the grace, then SIGKILL; the router/dispatcher reschedules the lane. */
|
|
192
|
+
async function drainOne(r, why) {
|
|
193
|
+
for (const n of r.docker ? [r.name, dindName(r.name)] : [r.name]) { try { await docker.kill(n, "TERM"); } catch { /* gone */ } }
|
|
194
|
+
for (let i = 0, max = Math.ceil((cfg.drain_grace_s ?? 20) * 2); i < max; i++) { const st = await docker.inspect(r.name).catch(() => null); if (!st?.running) break; await new Promise((res) => setTimeout(res, 500)); }
|
|
195
|
+
try { await docker.kill(r.name, "KILL"); } catch { /* already exited */ }
|
|
196
|
+
if (r.docker) { try { await docker.remove(dindName(r.name)); } catch { /* destroy retries */ } }
|
|
197
|
+
r.state = "exited"; r.finishedAt = now(); r.drained = why;
|
|
198
|
+
log.info?.(`drained borrowed sandbox ${r.id} (${why})`);
|
|
199
|
+
}
|
|
200
|
+
/** Admission by class: `{ victims }` (borrow sandboxes to reclaim, reserved only) or `{ refuse }` (a 503/400 body). */
|
|
201
|
+
function admit({ prio, cpus: c, mem_gb: m, reservation, h }) {
|
|
202
|
+
const t = tiers();
|
|
203
|
+
if (!t.rs.length && !(cfg.idle_only && prio === "borrow")) return c > t.free.cpus || m > t.free.mem ? { refuse: { status: 503 } } : { victims: [] };
|
|
204
|
+
if (prio === "borrow") {
|
|
205
|
+
const why = notIdle(h);
|
|
206
|
+
if (why) return { refuse: { status: 503, error: `host not idle: ${why}`, code: "pool.not_idle" } };
|
|
207
|
+
return c > t.free.cpus || m > t.free.mem ? { refuse: { status: 503 } } : { victims: [] };
|
|
208
|
+
}
|
|
209
|
+
if (prio === "normal") return c > t.unreserved.cpus || m > t.unreserved.mem ? { refuse: { status: 503 } } : { victims: [] };
|
|
210
|
+
const rv = t.rs.find((r) => r.name === reservation);
|
|
211
|
+
if (!rv) return { refuse: { status: 400, error: `unknown reservation ${reservation ?? "(none)"}` } };
|
|
212
|
+
const inRes = sumRecs(t.act.filter((s) => prioOf(s) === "reserved" && s.reservation === rv.name));
|
|
213
|
+
if (inRes.cpus + c > rv.cpus || inRes.mem + m > rv.mem_gb) return { refuse: { status: 503, error: `reservation ${rv.name} exceeded`, code: "pool.reservation_full" } };
|
|
214
|
+
let needC = c - t.free.cpus, needM = m - t.free.mem;
|
|
215
|
+
const victims = [];
|
|
216
|
+
for (const v of t.act.filter((s) => prioOf(s) === "borrow").sort((a, b) => b.startedAt - a.startedAt)) {
|
|
217
|
+
if (needC <= 0 && needM <= 0) break;
|
|
218
|
+
victims.push(v); needC -= v.cpus; needM -= v.mem_gb;
|
|
219
|
+
}
|
|
220
|
+
return needC > 0 || needM > 0 ? { refuse: { status: 503 } } : { victims };
|
|
221
|
+
}
|
|
222
|
+
/** #5856: reserved vs borrowable headroom for the router (only when reservations or idle_only are configured). */
|
|
223
|
+
function priorityView() {
|
|
224
|
+
if (!weighted()) return {};
|
|
225
|
+
const t = tiers();
|
|
226
|
+
return { cpus_free_unreserved: t.unreserved.cpus, mem_free_unreserved_gb: t.unreserved.mem, cpus_borrowable: Math.max(0, t.free.cpus), mem_borrowable_gb: Math.max(0, t.free.mem), ...(cfg.idle_only ? { idle_only: true } : {}),
|
|
227
|
+
reservations: t.rs.map((r) => { const u = sumRecs(t.act.filter((s) => prioOf(s) === "reserved" && s.reservation === r.name)); return { name: r.name, cpus: r.cpus, mem_gb: r.mem_gb, cpus_used: u.cpus, mem_used_gb: u.mem, cpus_free: r.cpus - u.cpus, mem_free_gb: r.mem_gb - u.mem }; }) };
|
|
228
|
+
}
|
|
136
229
|
function capacity() {
|
|
137
230
|
const u = used();
|
|
138
|
-
|
|
231
|
+
const active = Object.values(sb()).filter((s) => s.state !== "exited").length;
|
|
232
|
+
return { host: cfg.name ?? hostname(), ...running, vm: vmSize(), ...(pendingResize ? { pending_resize: { cpus: pendingResize.cpus, mem_gb: pendingResize.mem_gb } } : {}), upgrading: upgrade.state, ...(upgrade.error ? { upgrade_error: upgrade.error } : {}), ...(prepull.error ? { prepull_error: prepull.error } : {}), ...(cacheErr.size ? { cache_sweep_error: [...cacheErr.values()][0] } : {}), ...(cacheInfo.size ? { cache_volumes: Object.fromEntries([...cacheInfo].map(([v, i]) => [v, { size_gb: Math.round(i.size_bytes / 107374182.4) / 10 }])) } : {}), cpus_total: cfg.allow_cpus, mem_total_gb: cfg.allow_mem_gb, cpus_free: cfg.allow_cpus - u.cpus, mem_free_gb: cfg.allow_mem_gb - u.mem, active, ...priorityView(), ...diskView(), ...hostDiskView(active), paused: Boolean(cfg.paused), live: live(cfg), usage: Object.fromEntries(Object.values(sb()).filter((r) => r.usage?.samples).map((r) => [r.issue ?? r.id, { ...usageView(r), state: r.state }])) };
|
|
139
233
|
}
|
|
140
234
|
|
|
141
235
|
/** The image a spec's lanes run (the per-repo lane_tools tag when tools are listed), without building it. */
|
|
@@ -152,16 +246,37 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
152
246
|
return Promise.resolve().then(() => docker.run(args)).then(() => log.info?.(`env snapshot helper started for ${spec.repo.slug}`), (e) => log.warn?.(`env snapshot helper: ${String(e.stderr || e.message).slice(0, 200)}`));
|
|
153
247
|
}
|
|
154
248
|
|
|
249
|
+
/** cgroup cpu weight per class (docker --cpu-shares); a borrowed lane yields to a reserved one under contention. */
|
|
250
|
+
const sharesArgs = (prio) => (weighted() ? ["--cpu-shares", String(SHARES()[prio])] : []);
|
|
251
|
+
|
|
155
252
|
async function launch({ spec, cpus, mem_gb, limit = null }) {
|
|
156
253
|
if (typeof spec?.id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(spec.id) || !Array.isArray(spec.command) || !spec.command.length) throw Object.assign(new Error("spec.id ([A-Za-z0-9._-], max 128) and spec.command are required"), { status: 400 });
|
|
157
|
-
|
|
254
|
+
let existing = own(spec.id);
|
|
255
|
+
if (existing?.drained && existing.state === "exited") { await destroy(existing.id, "drained: relaunch"); existing = null; } // #5856: the router/dispatcher rescheduled a drained lane under the same id
|
|
158
256
|
if (existing) { existing.lease = now(); store.save(); return { status: 200, body: view(existing) }; }
|
|
159
257
|
if (Number.isInteger(spec.warm)) warm.configure({ spec, cpus, mem_gb, limit, n: spec.warm }); // #4912: the lane's execution.warm_sandboxes sizes the repo's pool
|
|
258
|
+
const prio = spec.priority ?? "normal";
|
|
259
|
+
if (!PRIORITIES.includes(prio)) throw Object.assign(new Error(`spec.priority must be one of ${PRIORITIES.join(", ")}`), { status: 400 });
|
|
260
|
+
const reservation = prio === "reserved" ? (spec.reservation ?? (reservations().length === 1 ? reservations()[0].name : null)) : null;
|
|
160
261
|
const c = capacity();
|
|
161
|
-
if (c.paused || c.cpus_free < cpus || c.mem_free_gb < mem_gb) return { status: 503, body: { error: "no capacity", capacity: c }, retryAfter: 60 };
|
|
162
|
-
// Burst model: reservations are small, so also refuse when the VM is genuinely short of memory or overloaded right now.
|
|
163
262
|
const h = live(cfg);
|
|
164
|
-
|
|
263
|
+
const adm = admit({ prio, cpus, mem_gb, reservation, h });
|
|
264
|
+
if (c.paused || adm.refuse) {
|
|
265
|
+
const f = adm.refuse ?? {};
|
|
266
|
+
if (f.status === 400) return { status: 400, body: { error: f.error } };
|
|
267
|
+
return { status: 503, body: { error: f.error ?? "no capacity", ...(f.code ? { code: f.code } : {}), capacity: c }, retryAfter: 60 };
|
|
268
|
+
}
|
|
269
|
+
// Burst model: reservations are small, so also refuse when the VM is genuinely short of memory or overloaded right now.
|
|
270
|
+
// A reserved launch skips the load gate: it must never be refused because lanes are busy (they are throttled/drained below).
|
|
271
|
+
if (!h.ok && prio !== "reserved") return { status: 503, body: { error: `host busy: ${h.reason}`, live: h }, retryAfter: 60 };
|
|
272
|
+
if (prio === "reserved") {
|
|
273
|
+
for (const r of tiers().act.filter((s) => prioOf(s) === "borrow")) await throttle(r, SHARES().throttled); // throttle every borrower first,
|
|
274
|
+
for (const v of adm.victims) await drainOne(v, `reserved ${reservation} arrived`); // then stop only as many as the reservation needs
|
|
275
|
+
}
|
|
276
|
+
if (c.host_disk_low) { // #5733: before any mkdir or docker run; the lane defers on the 503 (SANDBOX_CAPACITY)
|
|
277
|
+
const floor = cfg.min_host_disk_free_gb ?? 25;
|
|
278
|
+
return { status: 503, body: { error: `host disk low: ${c.host_disk_free_gb} GB free, floor ${floor} GB with ${c.active} running`, code: "pool.disk_low", host_disk_free_gb: c.host_disk_free_gb, floor_gb: floor }, retryAfter: cfg.disk_low_retry_after_s ?? 300 };
|
|
279
|
+
}
|
|
165
280
|
if (spec.lane_tools?.length) { // #5650 follow-up: never build inside the launch request (router timeout); 503 + retry while it builds
|
|
166
281
|
let st;
|
|
167
282
|
try { st = await laneImageNow({ tools: spec.lane_tools, baseImage: spec.image ?? image, docker }); } catch (e) { return { status: 422, body: { error: e.message, code: e.code ?? "lane_tools.invalid" } }; }
|
|
@@ -179,12 +294,14 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
179
294
|
const env = { ...(spec.env ?? {}), ...(withDocker ? { DOCKER_HOST: "tcp://127.0.0.1:2375" } : {}), CS_CRED_BASE: `http://host.docker.internal:${cfg.listen.port}/sandboxes/${encodeURIComponent(spec.id)}/creds`, CS_RELAY_BASE: `http://host.docker.internal:${cfg.listen.port}/sandboxes/${encodeURIComponent(spec.id)}/relay`, CS_CRED_TOKEN: credToken, CS_SANDBOX_ID: spec.id, CS_REPO_SLUG: spec.repo?.slug ?? "", CS_REPO_URL: spec.repo?.url ?? "", CS_REPO_REF: spec.repo?.ref ?? "", CS_RESULT_FILE: spec.result_file ?? "", CS_WORK_DIR: workDirOf(name),
|
|
180
295
|
...(spec.env_snapshots?.enabled ? { FORGE_ENV_IMAGE: envImageOf(spec) } : {}) }; // the image is part of the snapshot key
|
|
181
296
|
writeFileSync(envFile, Object.entries(env).map(([k, v]) => envLine(k, v)).join("\n") + "\n", { mode: 0o600 });
|
|
182
|
-
const rec = { id: spec.id, name, dir, issue: spec.issue ?? null, batch: spec.batch ?? null, cpus, mem_gb, result_file: spec.result_file ?? null, state: "starting", startedAt: now(), finishedAt: null, lease: now(), credToken, docker: withDocker };
|
|
297
|
+
const rec = { id: spec.id, name, dir, issue: spec.issue ?? null, batch: spec.batch ?? null, cpus, mem_gb, result_file: spec.result_file ?? null, state: "starting", startedAt: now(), finishedAt: null, lease: now(), credToken, docker: withDocker, ...(weighted() || spec.priority ? { priority: prio, ...(reservation ? { reservation } : {}) } : {}) };
|
|
183
298
|
sb()[spec.id] = rec;
|
|
184
299
|
store.save();
|
|
185
300
|
const cacheKey = String(spec.cache?.key ?? spec.repo?.slug ?? "default").toLowerCase().replace(/[^a-z0-9_.-]/g, "-");
|
|
186
301
|
rec.cacheVolume = `cs-cache-${cacheKey}`;
|
|
187
302
|
rec.workDir = workDirOf(name);
|
|
303
|
+
cacheUsed.set(rec.cacheVolume, now());
|
|
304
|
+
try { await docker.createVolume?.(rec.cacheVolume, [CACHE_LABEL]); } catch (e) { log.warn?.(`label ${rec.cacheVolume}: ${String(e.stderr || e.message).slice(0, 200)}`); } // an unlabelled volume still works
|
|
188
305
|
// Public resolvers: host resolvers like Tailscale MagicDNS are not reachable from the container network.
|
|
189
306
|
const netArgs = ["--add-host", "host.docker.internal:host-gateway", ...(cfg.dns ?? ["1.1.1.1", "8.8.8.8"]).flatMap((d) => ["--dns", String(d)])];
|
|
190
307
|
let laneCpus = cpus, laneMem = mem_gb, laneNet = netArgs, work = [];
|
|
@@ -203,7 +320,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
203
320
|
work = cacheMount; // the daemon sees the checkout at the same /cache/work path as the lane
|
|
204
321
|
await docker.run([
|
|
205
322
|
"--name", dindName(name), "--label", LABEL, "--label", `computeshare.id=${spec.id}`, "--label", "computeshare.role=dind",
|
|
206
|
-
"--privileged", "--cpus", String(dCpus), "--memory", mb(dMem), "--memory-swap", mb(dMem + swapFor(limit?.dind_swap_gb)),
|
|
323
|
+
"--privileged", "--cpus", String(dCpus), ...sharesArgs(prio), "--memory", mb(dMem), "--memory-swap", mb(dMem + swapFor(limit?.dind_swap_gb)),
|
|
207
324
|
...netArgs, ...work,
|
|
208
325
|
// Bypass dockerd-entrypoint: it adds tcp://0.0.0.0:2375 (reachable from other sandboxes on the bridge).
|
|
209
326
|
// #5738: the lane's /work is a symlink to its work dir (entrypoint.sh), so give the daemon the same symlink:
|
|
@@ -218,7 +335,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
218
335
|
"--name", name, "--label", LABEL, "--label", `computeshare.id=${spec.id}`,
|
|
219
336
|
// Hard burst cap per container; the (smaller) reservation is only what placement counts.
|
|
220
337
|
// --memory-swap above --memory lets a rare spike page out instead of being OOM-killed (swap deal).
|
|
221
|
-
"--cpus", String(laneCpus), "--memory", mb(laneMem), "--memory-swap", mb(laneMem + swapFor(limit?.lane_swap_gb)), "--pids-limit", "4096",
|
|
338
|
+
"--cpus", String(laneCpus), ...sharesArgs(prio), "--memory", mb(laneMem), "--memory-swap", mb(laneMem + swapFor(limit?.lane_swap_gb)), "--pids-limit", "4096",
|
|
222
339
|
"--env-file", envFile, ...laneNet, ...work,
|
|
223
340
|
...(spec.claim_dir ? ["-v", `${join(dir, "claim")}:/claim`] : []), // #4912: warm sandboxes receive their lane here
|
|
224
341
|
...(withDocker ? [] : cacheMount), "-v", `${join(dir, "result")}:/result`, "-v", `${join(dir, "out")}:/csout`,
|
|
@@ -275,7 +392,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
275
392
|
const history = r.usage?.samples ? JSON.stringify({ at: new Date(now()).toISOString(), id: r.id, issue: r.issue, docker: Boolean(r.docker), minutes: Math.round((((r.finishedAt ?? now()) - r.startedAt) / 60000) * 10) / 10, ...usageView(r) }) : null;
|
|
276
393
|
await docker.remove(r.name);
|
|
277
394
|
if (r.docker) await docker.remove(dindName(r.name));
|
|
278
|
-
if (r.workDir) { try { await docker.removeWorkDir(r.cacheVolume, image, r.workDir); } catch (e) {
|
|
395
|
+
if (r.workDir) { try { await docker.removeWorkDir(r.cacheVolume, image, r.workDir); } catch (e) { sweepFail(r.cacheVolume, "work dir", e); } }
|
|
279
396
|
else if (r.docker) await docker.removeVolume(workVolume(r.name)); // sandbox launched before #5696
|
|
280
397
|
try { await docker.wipe(r.dir, image); } catch (e) { log.warn?.(`wipe ${r.name}: ${String(e.stderr || e.message).slice(0, 200)}`); }
|
|
281
398
|
rmSync(r.dir, { recursive: true, force: true });
|
|
@@ -287,6 +404,76 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
287
404
|
return true;
|
|
288
405
|
}
|
|
289
406
|
|
|
407
|
+
/** Version order of `forgedock-lane:<version>` bases, newest first (numeric segments, then plain text). */
|
|
408
|
+
const newerFirst = (a, b) => b.localeCompare(a, "en", { numeric: true });
|
|
409
|
+
/**
|
|
410
|
+
* Removes superseded `forgedock-lane:` images: keeps the newest cfg.keep_lane_images (default 2) versions with their
|
|
411
|
+
* tools variants, the running one and `alsoKeep`, and any tag a container (running or exited) still uses. Never throws.
|
|
412
|
+
*/
|
|
413
|
+
async function pruneLaneImages(alsoKeep = []) {
|
|
414
|
+
if (!docker.listImages || !docker.removeImage) return;
|
|
415
|
+
try {
|
|
416
|
+
const prefix = laneImageTag("");
|
|
417
|
+
const tags = await docker.listImages(prefix);
|
|
418
|
+
const inUse = new Set(await (docker.listContainerImages?.() ?? []));
|
|
419
|
+
const baseOf = (t) => t.replace(/-t[0-9a-f]{12}$/, "");
|
|
420
|
+
const bases = [...new Set(tags.map(baseOf))].sort(newerFirst);
|
|
421
|
+
const keepN = Math.max(1, Number(cfg.keep_lane_images ?? 2) || 2);
|
|
422
|
+
const keep = [...bases.slice(0, keepN), laneImageTag(running.version), image, ...alsoKeep];
|
|
423
|
+
for (const t of tags) {
|
|
424
|
+
if (keep.some((b) => isLaneToolsTagOf(t, b)) || inUse.has(t)) continue;
|
|
425
|
+
try { await docker.removeImage(t); log.info?.(`removed superseded lane image ${t}`); } catch (e) { log.warn?.(`rmi ${t}: ${String(e.stderr || e.message).slice(0, 200)}`); }
|
|
426
|
+
}
|
|
427
|
+
} catch (e) { log.warn?.(`lane image prune: ${String(e.stderr || e.message).slice(0, 200)}`); }
|
|
428
|
+
}
|
|
429
|
+
/** Interval-gated build cache trim and sweep of dangling anonymous volumes (64-hex names); errors are logged only. */
|
|
430
|
+
async function sweepBuildCache(t) {
|
|
431
|
+
if (t - lastCachePrune < (cfg.build_cache_interval_s ?? 6 * 3600) * 1000) return;
|
|
432
|
+
lastCachePrune = t;
|
|
433
|
+
try { await docker.builderPrune?.(cfg.build_cache_keep_gb ?? 20); } catch (e) { log.warn?.(`builder prune: ${String(e.stderr || e.message).slice(0, 200)}`); }
|
|
434
|
+
try {
|
|
435
|
+
for (const v of (await docker.listDanglingVolumes?.()) ?? []) {
|
|
436
|
+
if (!/^[0-9a-f]{64}$/.test(v)) continue;
|
|
437
|
+
try { await docker.removeVolume(v); log.info?.(`removed anonymous volume ${v.slice(0, 12)}`); } catch (e) { log.warn?.(`rm volume ${v.slice(0, 12)}: ${String(e.stderr || e.message).slice(0, 200)}`); }
|
|
438
|
+
}
|
|
439
|
+
} catch (e) { log.warn?.(`anonymous volume sweep: ${String(e.stderr || e.message).slice(0, 200)}`); }
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/** #5757: age-out / size cap inside each cache volume, then idle eviction. Never-evict volumes are left alone; failures go to /capacity. */
|
|
443
|
+
async function cacheSweep(t) {
|
|
444
|
+
const never = cfg.cache_never_evict ?? [];
|
|
445
|
+
const keep = Object.values(sb()).map((r) => r.workDir).filter(Boolean);
|
|
446
|
+
const volumes = [];
|
|
447
|
+
for (const v of await docker.listVolumes("cs-cache-")) {
|
|
448
|
+
if (never.includes(v)) continue;
|
|
449
|
+
try {
|
|
450
|
+
const r = await docker.sweepCache(v, image, { maxAgeDays: cfg.cache_max_age_days ?? 14, maxGb: cfg.cache_max_gb ?? null, keep, now: t });
|
|
451
|
+
cacheInfo.set(v, r); cacheErr.delete(`cache sweep:${v}`);
|
|
452
|
+
if (r.errors?.length) cacheErr.set(`cache sweep:${v}`, `cache sweep ${v}: ${r.errors[0]}`);
|
|
453
|
+
volumes.push({ name: v, lastUsedMs: Math.max(r.last_used_ms ?? -Infinity, cacheUsed.get(v) ?? -Infinity) });
|
|
454
|
+
} catch (e) { sweepFail(v, "cache sweep", e); }
|
|
455
|
+
}
|
|
456
|
+
const referenced = new Set(Object.values(sb()).map((r) => r.cacheVolume).filter(Boolean));
|
|
457
|
+
for (const v of planIdleEviction({ volumes: volumes.map((x) => ({ ...x, lastUsedMs: Number.isFinite(x.lastUsedMs) ? x.lastUsedMs : null })), referenced, neverEvict: never, now: t, idleMs: (cfg.cache_idle_days ?? 30) * 86400000 })) {
|
|
458
|
+
try { await docker.removeVolume(v); cacheInfo.delete(v); cacheUsed.delete(v); log.info?.(`evicted idle cache volume ${v}`); } catch (e) { sweepFail(v, "cache evict", e); }
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/** Each reap: lift the throttle once no reserved sandbox runs; under idle_only, throttle borrowed lanes when the owner's load rises, then drain the newest. */
|
|
463
|
+
async function reclaimIdle() {
|
|
464
|
+
if (!weighted()) return;
|
|
465
|
+
const act = activeRecs(), borrowed = act.filter((r) => prioOf(r) === "borrow");
|
|
466
|
+
const busy = notIdle(live(cfg));
|
|
467
|
+
if (busy) {
|
|
468
|
+
const fresh = borrowed.filter((r) => !r.throttled);
|
|
469
|
+
if (fresh.length) { for (const r of fresh) await throttle(r, SHARES().throttled); return; } // throttle first,
|
|
470
|
+
const v = borrowed.sort((a, b) => b.startedAt - a.startedAt)[0];
|
|
471
|
+
if (v) await drainOne(v, `owner busy: ${busy}`); // one per pass, only if throttling was not enough
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
if (!act.some((r) => prioOf(r) === "reserved")) for (const r of borrowed.filter((x) => x.throttled)) await throttle(r, SHARES().borrow);
|
|
475
|
+
}
|
|
476
|
+
|
|
290
477
|
async function reap() {
|
|
291
478
|
const t = now();
|
|
292
479
|
for (const r of Object.values(sb())) {
|
|
@@ -297,6 +484,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
297
484
|
const known = new Set(Object.values(sb()).flatMap((r) => [r.name, dindName(r.name)]));
|
|
298
485
|
for (const name of await docker.listLabelled(LABEL)) if (!known.has(name)) { await docker.remove(name); log.info?.(`removed orphan container ${name}`); }
|
|
299
486
|
await sampleUsage();
|
|
487
|
+
await reclaimIdle();
|
|
300
488
|
await warm.maintain(maxLifeMs);
|
|
301
489
|
if (pendingResize && capacity().active === 0) {
|
|
302
490
|
const r = await resize(pendingResize);
|
|
@@ -308,9 +496,14 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
308
496
|
lastWorkSweep = t;
|
|
309
497
|
const keep = Object.values(sb()).map((r) => r.workDir).filter(Boolean);
|
|
310
498
|
for (const v of await docker.listVolumes("cs-cache-")) {
|
|
311
|
-
try { await docker.pruneWorkDirs(v, image, keep);
|
|
499
|
+
try { await docker.pruneWorkDirs(v, image, keep); cacheErr.delete(`work sweep:${v}`); } catch (e) { sweepFail(v, "work sweep", e); }
|
|
312
500
|
}
|
|
313
501
|
}
|
|
502
|
+
await sweepBuildCache(t);
|
|
503
|
+
if (t - lastCacheSweep >= (cfg.cache_sweep_interval_s ?? 3600) * 1000) {
|
|
504
|
+
lastCacheSweep = t;
|
|
505
|
+
await cacheSweep(t);
|
|
506
|
+
}
|
|
314
507
|
store.save();
|
|
315
508
|
}
|
|
316
509
|
|
|
@@ -376,6 +569,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
376
569
|
log.info?.(`rebuilding ${nextImage} (${running.version}/${running.image} -> ${want.version}/${want.image})`);
|
|
377
570
|
await docker.build(join(next, "pool", "image"), nextImage, laneBuildArgs(want.version));
|
|
378
571
|
}
|
|
572
|
+
await pruneLaneImages([laneImageTag(want.version)]);
|
|
379
573
|
await prepullImages();
|
|
380
574
|
rmSync(`${root}.old`, { recursive: true, force: true });
|
|
381
575
|
await run("mv", [root, `${root}.old`]);
|
|
@@ -403,6 +597,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
403
597
|
const parts = [st[r.name], r.docker ? st[dindName(r.name)] : null].filter(Boolean);
|
|
404
598
|
if (!parts.length) continue;
|
|
405
599
|
const cpu = parts.reduce((a, x) => a + x.cpu, 0), mem = parts.reduce((a, x) => a + x.mem_gb, 0);
|
|
600
|
+
r.cpu_now = cpu;
|
|
406
601
|
const u = (r.usage ??= { samples: 0, cpu_sum: 0, cpu_peak: 0, mem_sum: 0, mem_peak: 0 });
|
|
407
602
|
u.samples++; u.cpu_sum += cpu; u.mem_sum += mem; u.cpu_peak = Math.max(u.cpu_peak, cpu); u.mem_peak = Math.max(u.mem_peak, mem);
|
|
408
603
|
}
|
|
@@ -474,7 +669,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
474
669
|
[route("POST", "/warm/claim"), async (_p, body) => warm.claim(body ?? {})],
|
|
475
670
|
[route("GET", "/sandboxes/:id"), async ({ id }) => { const r = own(id); if (!r) return { status: 404, body: { state: "gone" } }; await refresh(r); store.save(); return { status: 200, body: view(r) }; }],
|
|
476
671
|
[route("GET", "/sandboxes/:id/logs"), async ({ id }, _b, url) => { const r = own(id); return r ? { status: 200, body: readLog(r, url.searchParams.get("cursor")) } : { status: 404, body: { text: "", cursor: 0 } }; }],
|
|
477
|
-
[route("GET", "/sandboxes/:id/result"), async ({ id }) => { const r = own(id); const x = r && readResult(r); return x ? { status: 200, body: x } : { status: 404, body: { error: "no result" } }; }],
|
|
672
|
+
[route("GET", "/sandboxes/:id/result"), async ({ id }) => { const r = own(id); const x = r && readResult(r); if (!x && r?.drained) return { status: 200, body: { drained: true, reason: r.drained } }; return x ? { status: 200, body: x } : { status: 404, body: { error: "no result" } }; }], // #5856: a drained lane without its own result is reported so the dispatcher reschedules it
|
|
478
673
|
[route("GET", "/sandboxes/:id/usage"), async ({ id }) => { const r = own(id); return r ? { status: 200, body: { minutes: Math.round((((r.finishedAt ?? now()) - r.startedAt) / 60000) * 10) / 10 } } : { status: 404, body: {} }; }],
|
|
479
674
|
[route("POST", "/sandboxes/:id/lease"), async ({ id }) => { const r = own(id); if (!r) return { status: 404, body: { state: "gone" } }; r.lease = now(); store.save(); return { status: 200, body: { ok: true } }; }],
|
|
480
675
|
// #5274: SIGTERM the lane (PID 1) so its teardown checkpoints and reports deferred run.interrupted; the sandbox is kept, never destroyed.
|
|
@@ -522,9 +717,10 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
522
717
|
|
|
523
718
|
/** Build the lane image for the running ForgeDock version when this host does not have it yet. */
|
|
524
719
|
async function ensureImage() {
|
|
525
|
-
if (await docker.hasImage?.(image)) return;
|
|
720
|
+
if (await docker.hasImage?.(image)) { await pruneLaneImages(); return; }
|
|
526
721
|
log.info?.(`building ${image}`);
|
|
527
722
|
await docker.build(join(cfg.code_root ?? repoRoot, "pool", "image"), image, laneBuildArgs(running.version));
|
|
723
|
+
await pruneLaneImages();
|
|
528
724
|
}
|
|
529
725
|
|
|
530
726
|
return { handle, launch, warm, reap, destroy, capacity, refresh, store, prepullImages, ensureImage };
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
// #5757: cache volume hygiene for pool agents. The planners are pure (imported by the agent and unit tests); the sweep
|
|
4
|
+
// itself runs inside a short-lived container of the lane image with the cache volume on /cache. The agent ships this
|
|
5
|
+
// file's source in CS_CACHE_SWEEP_SRC and the options in CS_CACHE_SWEEP_OPTS; the JSON result goes to stdout.
|
|
6
|
+
import { execFileSync } from "node:child_process";
|
|
7
|
+
import { existsSync, readFileSync, rmSync } from "node:fs";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
|
|
10
|
+
export const CACHE_LABEL = "computeshare.cache=1";
|
|
11
|
+
const DAY = 86400000;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Oldest-first deletion plan to bring `entries` ({path, bytes, mtimeMs, live}) under `capBytes`. Live entries (the work
|
|
15
|
+
* dirs of running sandboxes) count towards the total and are never chosen. Returns {delete, total, after}.
|
|
16
|
+
*/
|
|
17
|
+
export function planCacheCap(entries, capBytes) {
|
|
18
|
+
const total = entries.reduce((a, e) => a + (e.bytes || 0), 0);
|
|
19
|
+
if (!Number.isFinite(capBytes) || capBytes < 0 || total <= capBytes) return { delete: [], total, after: total };
|
|
20
|
+
let after = total;
|
|
21
|
+
const out = [];
|
|
22
|
+
for (const e of entries.filter((x) => !x.live).sort((a, b) => a.mtimeMs - b.mtimeMs)) {
|
|
23
|
+
if (after <= capBytes) break;
|
|
24
|
+
out.push(e.path);
|
|
25
|
+
after -= e.bytes || 0;
|
|
26
|
+
}
|
|
27
|
+
return { delete: out, total, after };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Cache volumes to remove: last use known (`lastUsedMs` a number), older than `idleMs`, no sandbox record references
|
|
32
|
+
* it and it is not in the never-evict list. `volumes` is [{name, lastUsedMs}].
|
|
33
|
+
*/
|
|
34
|
+
export function planIdleEviction({ volumes, referenced = new Set(), neverEvict = [], now, idleMs }) {
|
|
35
|
+
const never = new Set(neverEvict);
|
|
36
|
+
return volumes.filter((v) => Number.isFinite(v.lastUsedMs) && now - v.lastUsedMs > idleMs && !referenced.has(v.name) && !never.has(v.name)).map((v) => v.name);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const sh = (cmd, args) => { try { return execFileSync(cmd, args, { encoding: "utf8", maxBuffer: 64 << 20, stdio: ["ignore", "pipe", "ignore"] }); } catch { return ""; } };
|
|
40
|
+
const sizeOf = (p) => (Number(sh("du", ["-sk", p]).split(/\s/)[0]) || 0) * 1024;
|
|
41
|
+
const kids = (dir) => sh("find", [dir, "-mindepth", "1", "-maxdepth", "1", "-printf", "%p\t%T@\n"]).split("\n").filter(Boolean).map((l) => { const i = l.lastIndexOf("\t"); return { path: l.slice(0, i), mtimeMs: Number(l.slice(i + 1)) * 1000 }; });
|
|
42
|
+
|
|
43
|
+
/** Runs inside the container. Returns {size_bytes, last_used_ms, removed, errors}. */
|
|
44
|
+
export function sweepVolume({ root = "/cache", maxAgeDays = 14, maxGb = null, keep = [], now = Date.now() } = {}) {
|
|
45
|
+
const errors = [], removed = [];
|
|
46
|
+
const rm = (p) => { try { rmSync(p, { recursive: true, force: true }); removed.push(p); } catch (e) { errors.push(`${p}: ${e.message}`); } };
|
|
47
|
+
const cutoff = now - maxAgeDays * DAY;
|
|
48
|
+
for (const d of ["uv", "npm", "pip", "poetry"]) { // package caches: old files out, then the empty dirs
|
|
49
|
+
const dir = join(root, d);
|
|
50
|
+
if (!existsSync(dir)) continue;
|
|
51
|
+
sh("find", [dir, "-type", "f", "-mtime", `+${maxAgeDays}`, "-delete"]);
|
|
52
|
+
sh("find", [dir, "-mindepth", "1", "-type", "d", "-empty", "-delete"]);
|
|
53
|
+
}
|
|
54
|
+
const ageOut = (dir, skip = []) => { for (const k of kids(dir)) if (k.mtimeMs < cutoff && !skip.includes(k.path)) rm(k.path); };
|
|
55
|
+
const dc = join(root, "forge-depcache");
|
|
56
|
+
if (existsSync(dc)) { ageOut(join(dc, "stores")); ageOut(dc, [join(dc, "stores")]); } // snapshots, then store entries
|
|
57
|
+
if (existsSync(join(root, "env"))) ageOut(join(root, "env"));
|
|
58
|
+
const ps = join(root, "pnpm-store");
|
|
59
|
+
if (existsSync(ps)) sh("pnpm", ["store", "prune", "--store-dir", ps]);
|
|
60
|
+
for (const m of kids(join(root, "git")).filter((k) => k.path.endsWith(".git"))) sh("git", ["-C", m.path, "gc", "--auto", "--quiet"]);
|
|
61
|
+
if (Number.isFinite(maxGb)) {
|
|
62
|
+
const entries = [];
|
|
63
|
+
const keepSet = new Set(keep);
|
|
64
|
+
for (const k of kids(join(root, "work"))) entries.push({ ...k, bytes: sizeOf(k.path), live: keepSet.has(k.path) });
|
|
65
|
+
for (const d of ["uv", "npm", "pip", "poetry", "env", "forge-depcache", "forge-depcache/stores"]) for (const k of kids(join(root, d))) if (!k.path.endsWith("/stores")) entries.push({ ...k, bytes: sizeOf(k.path), live: false });
|
|
66
|
+
const plan = planCacheCap(entries, maxGb * 1024 ** 3);
|
|
67
|
+
for (const p of plan.delete) rm(p);
|
|
68
|
+
}
|
|
69
|
+
let last = null;
|
|
70
|
+
try { const n = Number(readFileSync(join(root, ".last-used"), "utf8").trim()); if (Number.isFinite(n) && n > 0) last = n * 1000; } catch { /* never recorded */ }
|
|
71
|
+
return { size_bytes: sizeOf(root), last_used_ms: last, removed: removed.length, errors: errors.slice(0, 5) };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (process.env.CS_CACHE_SWEEP_OPTS) process.stdout.write(JSON.stringify(sweepVolume(JSON.parse(process.env.CS_CACHE_SWEEP_OPTS))) + "\n");
|
package/bin/pool/cli.mjs
CHANGED
|
@@ -15,7 +15,7 @@ import { call as httpCall } from "./http.mjs";
|
|
|
15
15
|
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
|
|
16
16
|
const loadJson = (p) => JSON.parse(readFileSync(p, "utf8"));
|
|
17
17
|
|
|
18
|
-
const USAGE = "usage: forgedock pool router [install] | enroll [--cpus N --mem GB] | status | upgrade [agent] | remove <agent> [--config path]";
|
|
18
|
+
const USAGE = "usage: forgedock pool router [install] | enroll [--cpus N --mem GB --agent-url URL] | status | upgrade [agent] | remove <agent> [--config path]";
|
|
19
19
|
const HELP_FLAGS = ["--help", "-h"];
|
|
20
20
|
// Flags each verb accepts: `value` flags consume the next token, `bool` flags stand alone. Anything else dash-prefixed is rejected (#5008).
|
|
21
21
|
const VERB_FLAGS = {
|
|
@@ -24,8 +24,8 @@ const VERB_FLAGS = {
|
|
|
24
24
|
status: { value: ["--config"], bool: [] },
|
|
25
25
|
upgrade: { value: ["--config"], bool: [] },
|
|
26
26
|
remove: { value: ["--config"], bool: [] },
|
|
27
|
-
enroll: { value: ["--config", "--cpus", "--mem"], bool: [] },
|
|
28
|
-
"install-command": { value: ["--config", "--cpus", "--mem"], bool: [] },
|
|
27
|
+
enroll: { value: ["--config", "--cpus", "--mem", "--agent-url"], bool: [] },
|
|
28
|
+
"install-command": { value: ["--config", "--cpus", "--mem", "--agent-url"], bool: [] },
|
|
29
29
|
resize: { value: ["--config", "--cpus", "--mem", "--vm-cpus", "--vm-mem", "--vm-swap"], bool: ["--drain"] },
|
|
30
30
|
};
|
|
31
31
|
|
|
@@ -96,6 +96,14 @@ export async function runPoolCli(argv, deps = {}) {
|
|
|
96
96
|
const r = await call(`http://${cfg.listen.host}:${cfg.listen.port}`, "POST", "/codes", { token: cfg.forgedock_token });
|
|
97
97
|
if (!r.ok) throw new Error(`router refused: HTTP ${r.status}`);
|
|
98
98
|
const size = `${flag("cpus") ? `&cpus=${Number(flag("cpus"))}` : ""}${flag("mem") ? `&mem=${Number(flag("mem"))}` : ""}`;
|
|
99
|
+
const agentUrl = flag("agent-url"); // #5856: a host reachable only through an SSH tunnel (no Tailscale) enrolls with its tunnel URL
|
|
100
|
+
if (agentUrl) {
|
|
101
|
+
let u; try { u = new URL(agentUrl); } catch { u = null; }
|
|
102
|
+
if (!u || !["http:", "https:"].includes(u.protocol)) throw new Error("--agent-url must be an http(s) URL, e.g. http://127.0.0.1:7711");
|
|
103
|
+
console.log(`AGENT_URL='${u.origin}' pool/install/install-agent-linux.sh --router '${cfg.public_url}' --token '${r.data.code}'${flag("cpus") ? ` --cpus ${Number(flag("cpus"))}` : ""}${flag("mem") ? ` --mem ${Number(flag("mem"))}` : ""}`);
|
|
104
|
+
console.error(`(one-time code, expires ${r.data.expires_at}; the router reaches the agent at ${u.origin})`);
|
|
105
|
+
break;
|
|
106
|
+
}
|
|
99
107
|
console.log(`powershell -NoProfile -ExecutionPolicy Bypass -Command "irm '${cfg.public_url}/bootstrap/install.ps1?token=${r.data.code}${size}' | iex"`);
|
|
100
108
|
console.error(`(one-time code, expires ${r.data.expires_at})`);
|
|
101
109
|
break;
|
package/bin/pool/docker.mjs
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
2
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
3
|
import { execFile } from "node:child_process";
|
|
4
|
+
import { readFileSync } from "node:fs";
|
|
5
|
+
|
|
6
|
+
/** #5757: work-dir and cache sweeps walk big trees (node_modules): 10 min, not the 120 s of a small rm. */
|
|
7
|
+
export const SWEEP_TIMEOUT_MS = 10 * 60000;
|
|
8
|
+
const SWEEP_SRC = new URL("./cache-sweep.mjs", import.meta.url);
|
|
4
9
|
|
|
5
10
|
function docker(args, { timeoutMs = 120000 } = {}) {
|
|
6
11
|
return new Promise((resolve, reject) => {
|
|
@@ -29,6 +34,8 @@ export const dockerCli = {
|
|
|
29
34
|
try { await docker(["kill", `--signal=${signal}`, name], { timeoutMs: 20000 }); return true; }
|
|
30
35
|
catch (e) { if (/No such container|is not running/i.test(e.stderr ?? "")) return false; throw e; }
|
|
31
36
|
},
|
|
37
|
+
/** #5856: re-weights a running container (throttle/unthrottle a borrowed lane); a gone container is not an error. */
|
|
38
|
+
async update(name, { cpuShares, memoryReservationMb }) { try { await docker(["update", "--cpu-shares", String(cpuShares), ...(memoryReservationMb ? ["--memory-reservation", `${memoryReservationMb}m`] : []), name], { timeoutMs: 20000 }); } catch (e) { if (!/No such container/i.test(e.stderr ?? "")) throw e; } },
|
|
32
39
|
async listLabelled(label) {
|
|
33
40
|
const out = await docker(["ps", "-a", "--filter", `label=${label}`, "--format", "{{.Names}}"], { timeoutMs: 20000 });
|
|
34
41
|
return out ? out.split("\n").filter(Boolean) : [];
|
|
@@ -38,6 +45,23 @@ export const dockerCli = {
|
|
|
38
45
|
const out = await docker(["volume", "ls", "-q", "--filter", `name=${prefix}`], { timeoutMs: 20000 });
|
|
39
46
|
return out ? out.split("\n").filter((v) => v.startsWith(prefix)) : [];
|
|
40
47
|
},
|
|
48
|
+
/** Local image refs (`repo:tag`) starting with prefix; untagged images are skipped. */
|
|
49
|
+
async listImages(prefix) {
|
|
50
|
+
const out = await docker(["images", "--format", "{{.Repository}}:{{.Tag}}"], { timeoutMs: 30000 });
|
|
51
|
+
return [...new Set(out ? out.split("\n").filter((t) => t.startsWith(prefix) && !t.endsWith(":<none>")) : [])];
|
|
52
|
+
},
|
|
53
|
+
async removeImage(tag) { try { await docker(["rmi", tag], { timeoutMs: 120000 }); } catch (e) { if (!/no such image/i.test(e.stderr ?? "")) throw e; } },
|
|
54
|
+
/** Image refs of every container, running or exited (a ref in use must never be removed). */
|
|
55
|
+
async listContainerImages() {
|
|
56
|
+
const out = await docker(["ps", "-a", "--format", "{{.Image}}"], { timeoutMs: 30000 });
|
|
57
|
+
return out ? [...new Set(out.split("\n").filter(Boolean))] : [];
|
|
58
|
+
},
|
|
59
|
+
async builderPrune(keepGb) { return docker(["builder", "prune", "-f", "--keep-storage", `${keepGb}gb`], { timeoutMs: 10 * 60000 }); },
|
|
60
|
+
/** Volumes no container references (anonymous ones are named by 64 hex chars). */
|
|
61
|
+
async listDanglingVolumes() {
|
|
62
|
+
const out = await docker(["volume", "ls", "-q", "--filter", "dangling=true"], { timeoutMs: 30000 });
|
|
63
|
+
return out ? out.split("\n").filter(Boolean) : [];
|
|
64
|
+
},
|
|
41
65
|
async pull(image) { return docker(["pull", "-q", image], { timeoutMs: 30 * 60000 }); },
|
|
42
66
|
async load(file) { return docker(["load", "-q", "-i", file], { timeoutMs: 30 * 60000 }); },
|
|
43
67
|
async hasImage(ref) { try { await docker(["image", "inspect", ref], { timeoutMs: 20000 }); return true; } catch { return false; } },
|
|
@@ -57,11 +81,18 @@ export const dockerCli = {
|
|
|
57
81
|
},
|
|
58
82
|
async build(dir, tag, buildArgs = {}) { return docker(["build", "-q", "-t", tag, ...Object.entries(buildArgs).flatMap(([k, v]) => ["--build-arg", `${k}=${v}`]), dir], { timeoutMs: 45 * 60000 }); },
|
|
59
83
|
/** #5696: removes one lane worktree (/cache/work/<id>) from a cache volume. */
|
|
60
|
-
async removeWorkDir(volume, image, workDir) { await docker(["run", "--rm", "--network", "none", "-v", `${volume}:/cache`, "--entrypoint", "sh", image, "-c", 'rm -rf -- "$1"', "sh", workDir], { timeoutMs:
|
|
84
|
+
async removeWorkDir(volume, image, workDir) { await docker(["run", "--rm", "--network", "none", "-v", `${volume}:/cache`, "--entrypoint", "sh", image, "-c", 'rm -rf -- "$1"', "sh", workDir], { timeoutMs: SWEEP_TIMEOUT_MS }); },
|
|
61
85
|
/** #5696: removes every /cache/work/* dir of a cache volume except the kept ones (full paths). */
|
|
62
86
|
async pruneWorkDirs(volume, image, keep) {
|
|
63
87
|
const script = 'for d in /cache/work/* /cache/work/.[!.]*; do [ -e "$d" ] || continue; for k in "$@"; do [ "$d" = "$k" ] && continue 2; done; rm -rf -- "$d"; done';
|
|
64
|
-
await docker(["run", "--rm", "--network", "none", "-v", `${volume}:/cache`, "--entrypoint", "sh", image, "-c", script, "sh", ...keep], { timeoutMs:
|
|
88
|
+
await docker(["run", "--rm", "--network", "none", "-v", `${volume}:/cache`, "--entrypoint", "sh", image, "-c", script, "sh", ...keep], { timeoutMs: SWEEP_TIMEOUT_MS });
|
|
89
|
+
},
|
|
90
|
+
/** #5757: creates a volume carrying labels (idempotent: an existing volume keeps its labels). */
|
|
91
|
+
async createVolume(name, labels = []) { await docker(["volume", "create", ...labels.flatMap((l) => ["--label", l]), name], { timeoutMs: 20000 }); },
|
|
92
|
+
/** #5757: runs the in-volume cache sweep (bin/pool/cache-sweep.mjs) in a lane-image container; resolves its JSON result, rejects on failure or timeout. */
|
|
93
|
+
async sweepCache(volume, image, opts) {
|
|
94
|
+
const out = await docker(["run", "--rm", "--network", "none", "-v", `${volume}:/cache`, "-e", `CS_CACHE_SWEEP_OPTS=${JSON.stringify(opts)}`, "-e", `CS_CACHE_SWEEP_SRC=${readFileSync(SWEEP_SRC, "utf8")}`, "--entrypoint", "sh", image, "-c", 'printf %s "$CS_CACHE_SWEEP_SRC" > /tmp/cache-sweep.mjs && exec node /tmp/cache-sweep.mjs'], { timeoutMs: SWEEP_TIMEOUT_MS });
|
|
95
|
+
return JSON.parse(out.split("\n").filter(Boolean).pop());
|
|
65
96
|
},
|
|
66
97
|
/** Removes files the root-owned lane container wrote into a bind mount, using the lane image itself. */
|
|
67
98
|
async wipe(dir, image) { await docker(["run", "--rm", "--network", "none", "-v", `${dir}:/d`, "--entrypoint", "sh", image, "-c", "rm -rf /d/* /d/.[!.]* 2>/dev/null; true"], { timeoutMs: 120000 }); },
|
package/bin/pool/health.mjs
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
2
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
3
|
import { spawnSync } from "node:child_process";
|
|
4
|
+
import { readFileSync, readdirSync, statfsSync } from "node:fs";
|
|
5
|
+
import { join } from "node:path";
|
|
4
6
|
|
|
5
7
|
const sh = (cmd, args) => { const r = spawnSync(cmd, args, { encoding: "utf8", timeout: 5000 }); return r.status === 0 ? r.stdout : null; };
|
|
6
8
|
|
|
@@ -28,3 +30,39 @@ export function restartCheck({ unit, run = sh } = {}) {
|
|
|
28
30
|
const why = lastExitReason(lines);
|
|
29
31
|
return { status: "warn", detail: `${unit} restarted ${recent}x in the last hour (NRestarts=${total})${why ? `; last exit: ${why}` : ""}. Check for OOM kills (earlyoom/systemd-oomd) under memory pressure` };
|
|
30
32
|
}
|
|
33
|
+
|
|
34
|
+
const LXSS_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Lxss";
|
|
35
|
+
const readRelease = () => readFileSync("/proc/sys/kernel/osrelease", "utf8");
|
|
36
|
+
/** reg.exe through the WSL interop socket: systemd services lack WSL_INTEROP (same handling as the agent's resize). */
|
|
37
|
+
function winRun(cmd, args, env = process.env) {
|
|
38
|
+
const sock = env.WSL_INTEROP ? null : (() => { try { return readdirSync("/run/WSL").filter((f) => f.endsWith("_interop")).map((f) => join("/run/WSL", f)).sort().pop() ?? null; } catch { return null; } })();
|
|
39
|
+
const r = spawnSync(cmd, args, { encoding: "utf8", timeout: 5000, windowsHide: true, env: { ...env, ...(sock ? { WSL_INTEROP: sock } : {}) } });
|
|
40
|
+
return r.status === 0 ? r.stdout : null;
|
|
41
|
+
}
|
|
42
|
+
/** The /mnt/<letter> drive holding the distro's vhdx: its Lxss BasePath matched by DistributionName, or null. */
|
|
43
|
+
function distroDrive(regOut, distro) {
|
|
44
|
+
if (!regOut || !distro) return null;
|
|
45
|
+
for (const block of String(regOut).split(/\r?\n(?=HKEY_)/)) {
|
|
46
|
+
const name = /^\s*DistributionName\s+REG_\w+\s+(.+?)\s*$/m.exec(block)?.[1];
|
|
47
|
+
if (name !== distro) continue;
|
|
48
|
+
const letter = /^\s*BasePath\s+REG_\w+\s+\S*?([A-Za-z]):[\\/]/m.exec(block)?.[1];
|
|
49
|
+
return letter ? `/mnt/${letter.toLowerCase()}` : null;
|
|
50
|
+
}
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* #5733: free space of the Windows drive that backs this WSL distro's vhdx (lanes grow it; the in-VM statfs only sees
|
|
55
|
+
* the vhdx's virtual size). `{ gb, path }`, or null off WSL or when unreadable (absent means unknown: no gate).
|
|
56
|
+
* Drive: explicit `path` (agent cfg host_disk_path), else the distro's Lxss BasePath, else /mnt/c. All I/O is injectable.
|
|
57
|
+
*/
|
|
58
|
+
export function hostDiskFree({ path = null, osrelease = readRelease, statfs = statfsSync, run = winRun, env = process.env } = {}) {
|
|
59
|
+
try {
|
|
60
|
+
if (!/microsoft/i.test(String(osrelease() ?? ""))) return null;
|
|
61
|
+
let drive = path;
|
|
62
|
+
if (!drive) { try { drive = distroDrive(run("/mnt/c/Windows/System32/reg.exe", ["query", LXSS_KEY, "/s"], env), env.WSL_DISTRO_NAME); } catch { drive = null; } }
|
|
63
|
+
drive ??= "/mnt/c";
|
|
64
|
+
const f = statfs(drive);
|
|
65
|
+
const gb = Math.round((Number(f.bavail) * Number(f.bsize)) / 107374182.4) / 10;
|
|
66
|
+
return Number.isFinite(gb) ? { gb, path: drive } : null;
|
|
67
|
+
} catch { return null; }
|
|
68
|
+
}
|