forgedock 1.68.0 → 1.69.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/engine-cli.mjs +4 -9
- package/bin/lean/advisory.test.mjs +14 -5
- package/bin/lean/batch.mjs +11 -1
- package/bin/lean/capsample.mjs +25 -0
- package/bin/lean/conformance.mjs +6 -1
- package/bin/lean/conformance.test.mjs +6 -0
- package/bin/lean/depcache.mjs +2 -0
- package/bin/lean/effects.mjs +15 -1
- package/bin/lean/envgap.mjs +18 -0
- package/bin/lean/envgap.test.mjs +12 -1
- package/bin/lean/execution.mjs +3 -0
- package/bin/lean/execution.test.mjs +21 -0
- package/bin/lean/failure-stop.mjs +12 -1
- package/bin/lean/failure-stop.test.mjs +14 -1
- package/bin/lean/hostconfig.mjs +54 -0
- package/bin/lean/hostconfig.test.mjs +67 -0
- package/bin/lean/lane-audit-llm.mjs +51 -4
- package/bin/lean/lane-audit-llm.test.mjs +57 -0
- package/bin/lean/lane-audit.mjs +1 -1
- package/bin/lean/lean.mjs +63 -26
- package/bin/lean/lean.test.mjs +99 -19
- package/bin/lean/live-execution.mjs +3 -0
- package/bin/lean/live-execution.test.mjs +23 -0
- package/bin/lean/orchestrate-dispatch-placement.test.mjs +81 -0
- package/bin/lean/orchestrate-envhold.test.mjs +15 -1
- package/bin/lean/orchestrate.mjs +27 -9
- package/bin/lean/preflight.mjs +10 -3
- package/bin/lean/preflight.test.mjs +21 -1
- package/bin/lean/prompts.mjs +1 -0
- package/bin/lean/release-deploy.mjs +35 -5
- package/bin/lean/release-deploy.test.mjs +50 -3
- package/bin/lean/release-flakes.mjs +34 -0
- package/bin/lean/release-flakes.test.mjs +28 -0
- package/bin/lean/release.mjs +2 -1
- package/bin/lean/sandbox-remote.mjs +35 -4
- package/bin/lean/schedd.mjs +2 -2
- package/bin/pool/agent.mjs +105 -15
- package/bin/pool/cli.mjs +22 -4
- package/bin/pool/docker.mjs +2 -0
- package/bin/pool/image-manifest.mjs +24 -0
- package/bin/pool/image-manifest.test.mjs +20 -0
- package/bin/pool/lane-tools.mjs +23 -4
- package/bin/pool/lane-tools.test.mjs +27 -7
- package/bin/pool/project-layer.mjs +142 -0
- package/bin/pool/project-layer.test.mjs +73 -0
- package/bin/pool/router.mjs +20 -6
- package/bin/pool/version.mjs +45 -2
- package/bin/stats/tool-parks.mjs +29 -0
- package/bin/stats/tool-parks.test.mjs +21 -0
- package/package.json +1 -1
- package/pool/image/Dockerfile +1 -1
- package/scripts/ci-local.test.sh +3 -2
package/bin/pool/agent.mjs
CHANGED
|
@@ -6,7 +6,7 @@ const LANE_BUILD_RETRY_AFTER_S = 300;
|
|
|
6
6
|
import { randomBytes } from "node:crypto";
|
|
7
7
|
import { execFile, spawn } from "node:child_process";
|
|
8
8
|
import { promisify } from "node:util";
|
|
9
|
-
import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, rmSync, statSync, statfsSync, lstatSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { appendFileSync, closeSync, constants as fsConstants, existsSync, fstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, rmSync, statSync, statfsSync, lstatSync, writeFileSync } from "node:fs";
|
|
10
10
|
import { basename, dirname, join } from "node:path";
|
|
11
11
|
import { cpus, hostname } from "node:os";
|
|
12
12
|
import { bearerOk, call, readJson, route, sameSecret, send } from "./http.mjs";
|
|
@@ -14,6 +14,7 @@ import { repoRoot, versionOf, laneImageTag, laneBuildArgs } from "./version.mjs"
|
|
|
14
14
|
import { jsonStore } from "./store.mjs";
|
|
15
15
|
import { makeWarm } from "./warm.mjs";
|
|
16
16
|
import { resolveLaneImage, laneImageNow, laneToolsTag, isLaneToolsTagOf } from "./lane-tools.mjs";
|
|
17
|
+
import { projectLayerTag, projectLayerImageNow, isProjectLayerTagOf } from "./project-layer.mjs";
|
|
17
18
|
import { hostDiskFree, hostMemFree, ensureNatPin, netState } from "./health.mjs";
|
|
18
19
|
import { laneDiskUsedGb, planDiskCap, fstrimDue, runFstrim } from "./disk.mjs";
|
|
19
20
|
import { step as laneStep, drainState, pressured } from "./lane-target.mjs";
|
|
@@ -35,6 +36,8 @@ export function netRx(now = Date.now(), read = () => readFileSync("/proc/net/dev
|
|
|
35
36
|
} catch { return null; }
|
|
36
37
|
}
|
|
37
38
|
const LOG_CHUNK = 256 * 1024;
|
|
39
|
+
const RUNS_IN_SANDBOX = "/root/.forge/runs/."; // #6117: where the lane engine writes its run log (docker cp source)
|
|
40
|
+
const RUNLOG_MAX = 20 * 1024 * 1024, TAIL_LINES = 200, GRAVE_LOG_MAX = 1024 * 1024;
|
|
38
41
|
const run = promisify(execFile);
|
|
39
42
|
|
|
40
43
|
/** What this machine/VM actually has (on WSL: the VM caps from .wslconfig). */
|
|
@@ -69,6 +72,15 @@ export function liveHeadroom(cfg = {}) {
|
|
|
69
72
|
} catch { return { ok: true }; }
|
|
70
73
|
}
|
|
71
74
|
export const dindName = (name) => `${name}-dind`;
|
|
75
|
+
/** #6062: rolls usageView rows up for one worker: admitted (reserved) vs used (summed lane avg and peak) and the utilization ratios. Read-only; null ratios when nothing is reserved. */
|
|
76
|
+
export function usageSummary(rows) {
|
|
77
|
+
const f = (x) => Math.round(x * 100) / 100, list = (rows ?? []).filter((r) => r && r.reserved);
|
|
78
|
+
const sum = (g) => f(list.reduce((a, r) => a + (Number.isFinite(g(r)) ? g(r) : 0), 0));
|
|
79
|
+
const admitted = { cpus: sum((r) => r.reserved.cpus), mem_gb: sum((r) => r.reserved.mem_gb) };
|
|
80
|
+
const used = { cpu_avg: sum((r) => r.cpu_avg), cpu_peak: sum((r) => r.cpu_peak), mem_avg_gb: sum((r) => r.mem_avg_gb), mem_peak_gb: sum((r) => r.mem_peak_gb) };
|
|
81
|
+
const ratio = (u, d) => (d > 0 ? f(u / d) : null);
|
|
82
|
+
return { lanes: list.length, admitted, used, utilization: { cpu: ratio(used.cpu_avg, admitted.cpus), mem: ratio(used.mem_avg_gb, admitted.mem_gb) } };
|
|
83
|
+
}
|
|
72
84
|
export const workVolume = (name) => `cs-work-${name.replace(/^cs-/, "")}`;
|
|
73
85
|
/** #5696: the lane worktree is a plain dir on the cache volume (one mount), so depcache hardlinks never hit EXDEV. */
|
|
74
86
|
export const workDirOf = (name) => `/cache/work/${name.replace(/^cs-/, "")}`;
|
|
@@ -118,16 +130,43 @@ export async function buildWithRetry(build, { sleep = (ms) => new Promise((r) =>
|
|
|
118
130
|
}
|
|
119
131
|
}
|
|
120
132
|
|
|
133
|
+
const BURY_TIMEOUT_MS = 30000; // evidence copy before a destroy (run logs out of the container) never holds the destroy longer
|
|
134
|
+
/** An fd for a regular file a lane may have written, opened without following a symlink and without blocking on a FIFO; null otherwise. Caller closes it. */
|
|
135
|
+
export function openLaneFile(path) {
|
|
136
|
+
let fd = null;
|
|
137
|
+
try {
|
|
138
|
+
if (!lstatSync(path).isFile()) return null;
|
|
139
|
+
fd = openSync(path, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0) | (fsConstants.O_NONBLOCK ?? 0));
|
|
140
|
+
if (fstatSync(fd).isFile()) return fd;
|
|
141
|
+
} catch { /* gone, a link, or not a file */ }
|
|
142
|
+
if (fd !== null) { try { closeSync(fd); } catch { /* closed */ } }
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
/** A regular file the lane may have written, read without following symlinks (a lane can plant a link to a host file); "" otherwise. */
|
|
146
|
+
export function readLaneFile(path) {
|
|
147
|
+
const fd = openLaneFile(path);
|
|
148
|
+
if (fd === null) return "";
|
|
149
|
+
try { return readFileSync(fd, "utf8"); } catch { return ""; } finally { try { closeSync(fd); } catch { /* closed */ } }
|
|
150
|
+
}
|
|
121
151
|
export function createAgent(cfg, { docker, now = () => Date.now(), log = console, live = liveHeadroom, hostDisk = null, hostMem = null, net = netState, vm = vmSize, trim = runFstrim, mirrorRunner = null } = {}) {
|
|
122
152
|
const stateDir = cfg.state_dir;
|
|
123
153
|
const store = jsonStore(join(stateDir, "state.json"), { sandboxes: {} });
|
|
124
154
|
const sb = () => store.data.sandboxes;
|
|
155
|
+
const usageView = (r) => {
|
|
156
|
+
const u = r.usage; const f = (x) => Math.round(x * 100) / 100;
|
|
157
|
+
return u?.samples ? { reserved: { cpus: r.cpus, mem_gb: r.mem_gb }, cpu_avg: f(u.cpu_sum / u.samples), cpu_peak: f(u.cpu_peak), mem_avg_gb: f(u.mem_sum / u.samples), mem_peak_gb: f(u.mem_peak), samples: u.samples } : null;
|
|
158
|
+
};
|
|
159
|
+
let pendingResize = null;
|
|
160
|
+
const view = (r) => ({ id: r.id, state: r.state, issue: r.issue, cpus: r.cpus, mem_gb: r.mem_gb, started_at: new Date(r.startedAt).toISOString(), ...(r.error ? { error: r.error } : {}), ...(r.diskPaused ? { status_detail: "paused (disk)" } : {}), ...(r.memPaused ? { status_detail: "paused (host memory)" } : {}), ...(r.diskPressure ? { code: "sandbox.disk_pressure", status_detail: "stopped (disk pressure): worktree kept for resume" } : {}) });
|
|
161
|
+
let warm; // assigned below once launch/destroy exist
|
|
125
162
|
const activeRecs = () => Object.values(sb()).filter((s) => s.state !== "exited");
|
|
126
163
|
// Sandbox ids come from requests: read own keys only, so "__proto__" or "constructor" never resolves to an inherited member (#4566).
|
|
127
164
|
const own = (id) => (typeof id === "string" && Object.hasOwn(sb(), id) ? sb()[id] : warm.byAlias(id)); // #4912: a claimed warm sandbox also answers to its lane id
|
|
128
165
|
const leaseTtlMs = (cfg.lease_ttl_s ?? 600) * 1000;
|
|
129
166
|
const maxLifeMs = (cfg.max_lifetime_s ?? 6 * 3600) * 1000;
|
|
130
167
|
const keepExitedMs = (cfg.keep_exited_s ?? 2 * 3600) * 1000;
|
|
168
|
+
const keepLogMs = (cfg.keep_log_s ?? 600) * 1000; // #6117: a destroyed sandbox's last log, run log and result stay readable this long, so a late fetch still works
|
|
169
|
+
const graveyard = new Map(); // sandbox id -> {until, log: {from, size, text}, tail, runLog, result}
|
|
131
170
|
const keepPressureMs = (cfg.keep_disk_pressure_s ?? 24 * 3600) * 1000; // #5891: a disk-pressure stop keeps its worktree long enough for the requeue
|
|
132
171
|
const running = versionOf(cfg.code_root ?? repoRoot);
|
|
133
172
|
// The lane image tracks the installed ForgeDock version; only an explicit non-legacy cfg.image overrides it.
|
|
@@ -441,11 +480,12 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
441
480
|
const active = Object.values(sb()).filter((s) => s.state !== "exited").length;
|
|
442
481
|
const e = effectiveCapacity();
|
|
443
482
|
const h = live(cfg);
|
|
444
|
-
return { host: cfg.name ?? hostname(), ...running, vm: e.vm, ...(pendingResize ? { pending_resize: { cpus: pendingResize.cpus, mem_gb: pendingResize.mem_gb } } : {}), upgrading: upgrade.state, ...(upgrade.log && upgrade.state === "failed" ? { upgrade_log: upgrade.log } : {}), ...(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, ...(i.depcache_bytes ? { depcache_gb: Object.fromEntries(Object.entries(i.depcache_bytes).map(([k, b]) => [k, Math.round(b / 107374182.4) / 10])) } : {}) }])) } : {}), cpus_total: e.cpus, mem_total_gb: e.mem, cpus_free: r2(e.cpus - u.cpus - coTenant.cpus), mem_free_gb: r2(e.mem - u.mem - coTenant.mem_gb), configured: { cpus: cfg.allow_cpus, mem_gb: cfg.allow_mem_gb }, clamped: e.clamped, ...(coTenant.cpus || coTenant.mem_gb ? { cotenant: { cpus: r2(coTenant.cpus), mem_gb: r2(coTenant.mem_gb) } } : {}), active, ...priorityView(), ...throttleView(h), ...diskView(), ...laneDiskView(), ...hostDiskView(active), ...hostMemView(), ...heavyView(), runners: Object.entries(runners()).map(([name, r]) => ({ name, label: r.label })), net: (() => { const rx = netRx(now()); const n = readNet(); return rx ? { ...(n ?? {}), ...rx } : n; })(), paused: Boolean(cfg.paused || ownerPaused || policyPaused), owner_paused: ownerPaused, ...laneTargetView(), ...(Number.isFinite(h?.load_per_core) ? { load_per_core: h.load_per_core } : {}), ...(Number.isFinite(h?.mem_available_gb) ? { mem_available_gb: h.mem_available_gb } : {}), live: h, usage: Object.fromEntries(Object.values(sb()).filter((r) => r.usage?.samples).map((r) => [r.issue ?? r.id, { ...usageView(r), state: r.state }])) };
|
|
483
|
+
return { host: cfg.name ?? hostname(), usage_summary: usageSummary(Object.values(sb()).filter((r) => r.state !== "exited").map(usageView)), ...running, vm: e.vm, ...(pendingResize ? { pending_resize: { cpus: pendingResize.cpus, mem_gb: pendingResize.mem_gb } } : {}), upgrading: upgrade.state, ...(upgrade.log && upgrade.state === "failed" ? { upgrade_log: upgrade.log } : {}), ...(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, ...(i.depcache_bytes ? { depcache_gb: Object.fromEntries(Object.entries(i.depcache_bytes).map(([k, b]) => [k, Math.round(b / 107374182.4) / 10])) } : {}) }])) } : {}), cpus_total: e.cpus, mem_total_gb: e.mem, cpus_free: r2(e.cpus - u.cpus - coTenant.cpus), mem_free_gb: r2(e.mem - u.mem - coTenant.mem_gb), configured: { cpus: cfg.allow_cpus, mem_gb: cfg.allow_mem_gb }, clamped: e.clamped, ...(coTenant.cpus || coTenant.mem_gb ? { cotenant: { cpus: r2(coTenant.cpus), mem_gb: r2(coTenant.mem_gb) } } : {}), active, ...priorityView(), ...throttleView(h), ...diskView(), ...laneDiskView(), ...hostDiskView(active), ...hostMemView(), ...heavyView(), runners: Object.entries(runners()).map(([name, r]) => ({ name, label: r.label })), net: (() => { const rx = netRx(now()); const n = readNet(); return rx ? { ...(n ?? {}), ...rx } : n; })(), paused: Boolean(cfg.paused || ownerPaused || policyPaused), owner_paused: ownerPaused, ...laneTargetView(), ...(Number.isFinite(h?.load_per_core) ? { load_per_core: h.load_per_core } : {}), ...(Number.isFinite(h?.mem_available_gb) ? { mem_available_gb: h.mem_available_gb } : {}), live: h, usage: Object.fromEntries(Object.values(sb()).filter((r) => r.usage?.samples).map((r) => [r.issue ?? r.id, { ...usageView(r), state: r.state }])) };
|
|
445
484
|
}
|
|
446
485
|
|
|
447
486
|
/** The image a spec's lanes run (the per-repo lane_tools tag when tools are listed), without building it. */
|
|
448
|
-
const
|
|
487
|
+
const laneBaseOf = (spec) => (spec.lane_tools?.length ? laneToolsTag(spec.image ?? image, spec.lane_tools) : (spec.image ?? image));
|
|
488
|
+
const envImageOf = (spec) => (spec.project_deps?.hash ? projectLayerTag(laneBaseOf(spec), spec.project_deps.hash) : laneBaseOf(spec));
|
|
449
489
|
const envEnsured = new Map(); // cache volume -> last ensure start
|
|
450
490
|
/**
|
|
451
491
|
* env.snapshots: start the snapshot helper for the repo, at most once per ENV_ENSURE_GAP_MS and one at a time per cache
|
|
@@ -548,6 +588,14 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
548
588
|
if (st.building) return { status: 503, body: { error: `lane image ${st.tag} building`, code: "lane_tools.building" }, retryAfter: LANE_BUILD_RETRY_AFTER_S };
|
|
549
589
|
if (st.failed) return { status: 422, body: { error: st.failed, code: "lane_tools.build_failed" } };
|
|
550
590
|
}
|
|
591
|
+
// #6038: the project-deps layer builds in the background; a launch never waits for it and runs the lane image meanwhile.
|
|
592
|
+
let projectImage = null;
|
|
593
|
+
if (spec.project_deps?.hash) {
|
|
594
|
+
try {
|
|
595
|
+
const st = await projectLayerImageNow({ deps: spec.project_deps, baseImage: laneBaseOf(spec), docker });
|
|
596
|
+
if (st.image && st.image !== laneBaseOf(spec)) projectImage = st.image;
|
|
597
|
+
} catch (e) { log.warn?.(`project layer: ${String(e.message).slice(0, 200)}`); }
|
|
598
|
+
}
|
|
551
599
|
// Last refusal point passed: only now stop borrowed lanes (#5897), a launch refused above must not have drained any.
|
|
552
600
|
if (prio === "reserved") {
|
|
553
601
|
for (const r of tiers().act.filter((s) => prioOf(s) === "borrow")) await throttle(r, SHARES().throttled); // throttle every borrower first,
|
|
@@ -578,7 +626,8 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
578
626
|
const cacheMount = ["-v", `${rec.cacheVolume}:/cache`];
|
|
579
627
|
try {
|
|
580
628
|
// #5650: a repo's lane_tools select a derived image (built once per tool list); none keeps spec.image ?? image.
|
|
581
|
-
const
|
|
629
|
+
const toolsImage = spec.lane_tools?.length ? await resolveLaneImage({ tools: spec.lane_tools, baseImage: spec.image ?? image, docker }) : (spec.image ?? image);
|
|
630
|
+
const laneImage = projectImage ?? toolsImage; // #6038: the project layer sits on the tools image, or is skipped (base) while building
|
|
582
631
|
if (withDocker) {
|
|
583
632
|
// Private Docker daemon per sandbox (never the host socket). The lane joins its network namespace, so ports the
|
|
584
633
|
// project's compose stack publishes are on the lane's localhost, and the API listens on loopback only. Both share
|
|
@@ -626,9 +675,8 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
626
675
|
return { status: 201, body: view(rec) };
|
|
627
676
|
}
|
|
628
677
|
|
|
629
|
-
const view = (r) => ({ id: r.id, state: r.state, issue: r.issue, cpus: r.cpus, mem_gb: r.mem_gb, started_at: new Date(r.startedAt).toISOString(), ...(r.error ? { error: r.error } : {}), ...(r.diskPaused ? { status_detail: "paused (disk)" } : {}), ...(r.memPaused ? { status_detail: "paused (host memory)" } : {}), ...(r.diskPressure ? { code: "sandbox.disk_pressure", status_detail: "stopped (disk pressure): worktree kept for resume" } : {}) });
|
|
630
678
|
|
|
631
|
-
|
|
679
|
+
warm = makeWarm({ store, sb, own, now, launch, destroy: (id, why) => destroy(id, why), view, log });
|
|
632
680
|
|
|
633
681
|
async function refresh(r) {
|
|
634
682
|
if (r.state === "exited") return r;
|
|
@@ -657,9 +705,54 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
657
705
|
try { return JSON.parse(readFileSync(join(r.dir, "result", basename(r.result_file)), "utf8")); } catch { return null; }
|
|
658
706
|
}
|
|
659
707
|
|
|
708
|
+
/** #6117: the lane's own run log (jsonl text, newest RUNLOG_MAX bytes), copied out of the container (running or exited); "" when unavailable. */
|
|
709
|
+
async function readRunLog(r) {
|
|
710
|
+
if (typeof docker.copyOut !== "function") return "";
|
|
711
|
+
let tmp = null;
|
|
712
|
+
try {
|
|
713
|
+
tmp = mkdtempSync(join(stateDir, "runlog-"));
|
|
714
|
+
await docker.copyOut(r.name, RUNS_IN_SANDBOX, tmp);
|
|
715
|
+
const want = new RegExp(`(^|__)${String(r.issue ?? "").replace(/[^\w.-]/g, "")}\\.jsonl$`);
|
|
716
|
+
const files = readdirSync(tmp).filter((f) => want.test(f) && (() => { try { return lstatSync(join(tmp, f)).isFile(); } catch { return false; } })());
|
|
717
|
+
if (!files.length) return "";
|
|
718
|
+
const text = readLaneFile(join(tmp, files.sort((a, b) => lstatSync(join(tmp, b)).size - lstatSync(join(tmp, a)).size)[0]));
|
|
719
|
+
if (text.length <= RUNLOG_MAX) return text;
|
|
720
|
+
const cut = text.slice(-RUNLOG_MAX); return cut.slice(cut.indexOf("\n") + 1); // whole lines only
|
|
721
|
+
} catch { return ""; } finally { if (tmp) rmSync(tmp, { recursive: true, force: true }); }
|
|
722
|
+
}
|
|
723
|
+
/** The last TAIL_LINES lines of the sandbox's lane log (its engine stderr/stdout). */
|
|
724
|
+
function logTail(r) {
|
|
725
|
+
const t = readLaneFile(join(r.dir, "out", "lane.log")); return t ? t.split("\n").slice(-(TAIL_LINES + 1)).join("\n") : "";
|
|
726
|
+
}
|
|
727
|
+
const grave = (id) => { const g = typeof id === "string" ? graveyard.get(id) : null; if (g && g.until <= now()) { graveyard.delete(id); return null; } return g ?? null; };
|
|
728
|
+
/** #6117: `{run_log, tail}` of a live sandbox, or of a destroyed one inside its grace period; null when unknown. */
|
|
729
|
+
async function evidence(id) {
|
|
730
|
+
const r = own(id);
|
|
731
|
+
if (r) return { run_log: await readRunLog(r), tail: logTail(r) };
|
|
732
|
+
const g = grave(id);
|
|
733
|
+
return g ? { run_log: g.runLog, tail: g.tail } : null;
|
|
734
|
+
}
|
|
735
|
+
/** Keeps what a late fetch needs once the container and its dir are gone. */
|
|
736
|
+
const GRAVE_MAX = 64; // destroyed sandboxes whose evidence is kept at once; the oldest goes first
|
|
737
|
+
async function bury(r) {
|
|
738
|
+
while (graveyard.size >= GRAVE_MAX) graveyard.delete(graveyard.keys().next().value);
|
|
739
|
+
try {
|
|
740
|
+
let text = "", size = 0;
|
|
741
|
+
const fd = openLaneFile(join(r.dir, "out", "lane.log")); // no symlink, no FIFO: a lane can plant either (#6145 delta review)
|
|
742
|
+
if (fd !== null) { try { size = fstatSync(fd).size; const len = Math.min(size, GRAVE_LOG_MAX); const buf = Buffer.alloc(len); readSync(fd, buf, 0, len, size - len); text = buf.toString("utf8"); } catch { /* no log */ } finally { closeSync(fd); } }
|
|
743
|
+
graveyard.set(r.id, { until: now() + keepLogMs, log: { from: size - Buffer.byteLength(text), size, text }, tail: logTail(r), runLog: await readRunLog(r), result: readResult(r) });
|
|
744
|
+
} catch { /* best effort: the destroy goes on */ }
|
|
745
|
+
}
|
|
746
|
+
function graveLog(g, cursor) {
|
|
747
|
+
const c = Math.max(Number(cursor) || 0, g.log.from);
|
|
748
|
+
if (c >= g.log.size) return { text: "", cursor: g.log.size };
|
|
749
|
+
return { text: Buffer.from(g.log.text).subarray(c - g.log.from).toString("utf8"), cursor: g.log.size };
|
|
750
|
+
}
|
|
751
|
+
|
|
660
752
|
async function destroy(id, why, { keepWork = false } = {}) {
|
|
661
753
|
const r = own(id);
|
|
662
754
|
if (!r) return false;
|
|
755
|
+
if (keepLogMs > 0) await Promise.race([bury(r), new Promise((res) => { const t = setTimeout(res, BURY_TIMEOUT_MS); t.unref?.(); })]); // #6117: before the container and its dir go; bounded so a hung copy never blocks the destroy
|
|
663
756
|
if (r.slug && r.diskPeakMb) { const h = (hist()[r.slug] ??= []); h.push(r.diskPeakMb); if (h.length > 50) h.shift(); }
|
|
664
757
|
const history = r.usage?.samples ? JSON.stringify({ at: new Date(now()).toISOString(), id: r.id, issue: r.issue, repo: r.repo ?? null, docker: Boolean(r.docker), minutes: Math.round((((r.finishedAt ?? now()) - r.startedAt) / 60000) * 10) / 10, ...usageView(r) }) : null;
|
|
665
758
|
await docker.remove(r.name);
|
|
@@ -694,7 +787,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
694
787
|
const keepN = Math.max(1, Number(cfg.keep_lane_images ?? 2) || 2);
|
|
695
788
|
const keep = [...bases.slice(0, keepN), laneImageTag(running.version), image, ...alsoKeep];
|
|
696
789
|
for (const t of tags) {
|
|
697
|
-
if (keep.some((b) => isLaneToolsTagOf(t, b)) || inUse.has(t)) continue;
|
|
790
|
+
if (keep.some((b) => isLaneToolsTagOf(t, b) || isProjectLayerTagOf(t, b)) || inUse.has(t)) continue;
|
|
698
791
|
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)}`); }
|
|
699
792
|
}
|
|
700
793
|
} catch (e) { log.warn?.(`lane image prune: ${String(e.stderr || e.message).slice(0, 200)}`); }
|
|
@@ -870,6 +963,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
870
963
|
|
|
871
964
|
async function reap() {
|
|
872
965
|
const t = now();
|
|
966
|
+
for (const id of [...graveyard.keys()]) grave(id); // #6117: expired grace entries go
|
|
873
967
|
for (const r of Object.values(sb())) {
|
|
874
968
|
try { await refresh(r); } catch { /* docker hiccup: judge by lease only */ }
|
|
875
969
|
const why = t - r.lease > leaseTtlMs && !r.diskPaused && !r.memPaused ? "lease expired" : t - r.startedAt > maxLifeMs ? "max lifetime" : r.state === "exited" && r.finishedAt && t - r.finishedAt > (r.diskPressure ? keepPressureMs : keepExitedMs) ? "exited retention" : null;
|
|
@@ -1014,11 +1108,6 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
1014
1108
|
}
|
|
1015
1109
|
store.save();
|
|
1016
1110
|
}
|
|
1017
|
-
const usageView = (r) => {
|
|
1018
|
-
const u = r.usage; const f = (x) => Math.round(x * 100) / 100;
|
|
1019
|
-
return u?.samples ? { reserved: { cpus: r.cpus, mem_gb: r.mem_gb }, cpu_avg: f(u.cpu_sum / u.samples), cpu_peak: f(u.cpu_peak), mem_avg_gb: f(u.mem_sum / u.samples), mem_peak_gb: f(u.mem_peak), samples: u.samples } : null;
|
|
1020
|
-
};
|
|
1021
|
-
let pendingResize = null;
|
|
1022
1111
|
async function resize(body) {
|
|
1023
1112
|
const int = (v, lo, hi) => (Number.isInteger(v) && v >= lo && v <= hi ? v : null);
|
|
1024
1113
|
const cpus = int(body.cpus, 1, 256), mem = int(body.mem_gb, 1, 1024), vmCpus = int(body.vm_cpus ?? body.cpus, 1, 256), vmMem = int(body.vm_mem_gb ?? (body.mem_gb + 2), 2, 1024);
|
|
@@ -1083,8 +1172,9 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
1083
1172
|
[route("POST", "/warm"), async (_p, body) => { const r = warm.configure({ ...(body ?? {}), n: body?.n }); await warm.replenish(); return { status: 200, body: { ...r, warm: warm.list() } }; }],
|
|
1084
1173
|
[route("POST", "/warm/claim"), async (_p, body) => warm.claim(body ?? {})],
|
|
1085
1174
|
[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) }; }],
|
|
1086
|
-
[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 } }; }],
|
|
1087
|
-
[route("GET", "/sandboxes/:id/
|
|
1175
|
+
[route("GET", "/sandboxes/:id/logs"), async ({ id }, _b, url) => { const r = own(id), g = !r && grave(id); return r ? { status: 200, body: readLog(r, url.searchParams.get("cursor")) } : g ? { status: 200, body: graveLog(g, url.searchParams.get("cursor")) } : { status: 404, body: { text: "", cursor: 0 } }; }],
|
|
1176
|
+
[route("GET", "/sandboxes/:id/runlog"), async ({ id }) => { const e = await evidence(id); return e ? { status: 200, body: e } : { status: 404, body: { error: "no run log" } }; }], // #6117
|
|
1177
|
+
[route("GET", "/sandboxes/:id/result"), async ({ id }) => { const r = own(id); const x = r ? readResult(r) : grave(id)?.result; if (!x && r?.drained) return { status: 200, body: { drained: true, reason: r.drained } }; if (!x && r?.diskPressure) return { status: 200, body: { disk_pressure: true, code: "sandbox.disk_pressure", reason: "host drive below the hard floor" } }; /* #5891 */ 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
|
|
1088
1178
|
[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: {} }; }],
|
|
1089
1179
|
[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 } }; }],
|
|
1090
1180
|
// #5274: SIGTERM the lane (PID 1) so its teardown checkpoints and reports deferred run.interrupted; the sandbox is kept, never destroyed.
|
|
@@ -1148,7 +1238,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
1148
1238
|
await pruneLaneImages();
|
|
1149
1239
|
}
|
|
1150
1240
|
|
|
1151
|
-
return { handle, launch, warm, reap, destroy, capacity, refresh, store, prepullImages, ensureImage };
|
|
1241
|
+
return { handle, launch, warm, reap, destroy, capacity, refresh, store, prepullImages, ensureImage, evidence, graveLog: (id, cursor) => { const g = grave(id); return g ? graveLog(g, cursor) : null; } };
|
|
1152
1242
|
}
|
|
1153
1243
|
|
|
1154
1244
|
/**
|
package/bin/pool/cli.mjs
CHANGED
|
@@ -60,16 +60,32 @@ export async function keptRows(root, { now = Date.now() } = {}) {
|
|
|
60
60
|
} catch { return []; }
|
|
61
61
|
}
|
|
62
62
|
export const keptLines = (rows) => rows.length ? [`kept sandboxes (${rows.length}):`, ...rows.map((k) => ` #${k.issue} batch ${k.batch} age ${Math.round((k.ageMs ?? 0) / 60000)}m phase ${k.phase ?? "?"}`)] : [];
|
|
63
|
+
/** #6062: queue_wait p50/p95 (ms) per worker from batch report rows whose phases.queue_wait names the worker. */
|
|
64
|
+
export function queueWaitByWorker(rows) {
|
|
65
|
+
const by = {};
|
|
66
|
+
for (const r of rows ?? []) { const q = r?.phases?.queue_wait; if (q?.worker && Number.isFinite(q.ms)) (by[q.worker] ??= []).push(q.ms); }
|
|
67
|
+
const pct = (xs, p) => xs[Math.min(xs.length - 1, Math.ceil(p * xs.length) - 1)];
|
|
68
|
+
return Object.fromEntries(Object.entries(by).map(([w, xs]) => { xs.sort((a, b) => a - b); return [w, { n: xs.length, p50_ms: pct(xs, 0.5), p95_ms: pct(xs, 0.95) }]; }));
|
|
69
|
+
}
|
|
70
|
+
export async function queueRows(root) {
|
|
71
|
+
try {
|
|
72
|
+
const B = await import("../lean/batch.mjs"), out = [];
|
|
73
|
+
for (const id of B.listBatches(root)) out.push(...(B.openBatch(root, id).readReport()?.rows ?? []));
|
|
74
|
+
return out;
|
|
75
|
+
} catch { return []; }
|
|
76
|
+
}
|
|
63
77
|
const num = (x) => (Number.isFinite(x) ? String(Math.round(x * 10) / 10) : "-");
|
|
78
|
+
const usedCell = (u) => (u?.used && u.admitted ? `${num(u.used.cpu_avg)}/${num(u.used.mem_avg_gb)} vs ${num(u.admitted.cpus)}/${num(u.admitted.mem_gb)}` : "-");
|
|
79
|
+
const queueCell = (q) => (q && Number.isFinite(q.p50_ms) ? `${num(q.p50_ms / 1000)}/${num(q.p95_ms / 1000)}` : "-");
|
|
64
80
|
/** #5885: one row per host: used/borrowable/total cpus and memory, lane counts, pause state and why lanes are throttled or drained. */
|
|
65
81
|
export function statusTable(agents) {
|
|
66
82
|
const withAccount = agents.some((a) => a.account); // #5886: the column appears only when an agent has an account
|
|
67
83
|
const withEngine = agents.some((a) => a.engine_version); // the ENGINE column appears only when an agent reports its lane engine
|
|
68
|
-
const head = ["HOST", ...(withAccount ? ["ACCOUNT"] : []), "CPUS used/borrow/total", "MEM GB used/borrow/total", "ACTIVE", "THROTTLED", "PAUSED", ...(withEngine ? ["ENGINE"] : []), "REASON"];
|
|
84
|
+
const head = ["HOST", ...(withAccount ? ["ACCOUNT"] : []), "CPUS used/borrow/total", "MEM GB used/borrow/total", "ACTIVE", "THROTTLED", "PAUSED", ...(withEngine ? ["ENGINE"] : []), "REASON", "USED cpu/mem vs admitted", "QUEUE p50/p95 s"];
|
|
69
85
|
const rows = agents.map((a) => {
|
|
70
86
|
const name = a.name ?? a.host ?? "?";
|
|
71
87
|
const acct = withAccount ? [a.account ?? "-"] : [];
|
|
72
|
-
if (a.ok === false) return [name, ...acct, "-", "-", "-", "-", ...(withEngine ? ["-"] : []), "-", `unreachable${a.error ? `: ${a.error}` : ""}
|
|
88
|
+
if (a.ok === false) return [name, ...acct, "-", "-", "-", "-", ...(withEngine ? ["-"] : []), "-", `unreachable${a.error ? `: ${a.error}` : ""}`, "-", "-"];
|
|
73
89
|
const used = (tot, free) => (Number.isFinite(tot) && Number.isFinite(free) ? tot - Math.max(0, free) : null);
|
|
74
90
|
const borrow = (b, free) => num(b ?? free);
|
|
75
91
|
const paused = a.owner_paused ? "owner" : a.paused ? (a.pending_resize ? "resize" : "yes") : "no";
|
|
@@ -78,7 +94,7 @@ export function statusTable(agents) {
|
|
|
78
94
|
a.idle_gate ? `owner busy: ${a.idle_gate}` : null, a.last_drain ? `last drain ${a.last_drain.sandbox} at ${a.last_drain.at}: ${a.last_drain.reason}` : null].filter(Boolean).join("; ");
|
|
79
95
|
return [name, ...acct, `${num(used(a.cpus_total, a.cpus_free))}/${borrow(a.cpus_borrowable, a.cpus_free)}/${num(a.cpus_total)}`,
|
|
80
96
|
`${num(used(a.mem_total_gb, a.mem_free_gb))}/${borrow(a.mem_borrowable_gb, a.mem_free_gb)}/${num(a.mem_total_gb)}`,
|
|
81
|
-
String(a.active ?? "-"), String(a.throttled ?? 0), paused, ...(withEngine ? [a.engine_version ? `${a.engine_version}${a.engine_skew ? " SKEW" : ""}` : "-"] : []), why || "-"];
|
|
97
|
+
String(a.active ?? "-"), String(a.throttled ?? 0), paused, ...(withEngine ? [a.engine_version ? `${a.engine_version}${a.engine_skew ? " SKEW" : ""}` : "-"] : []), why || "-", usedCell(a.usage_summary), queueCell(a.queue_wait)];
|
|
82
98
|
});
|
|
83
99
|
const w = head.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));
|
|
84
100
|
return [head, ...rows].map((r) => r.map((c, i) => (i === r.length - 1 ? c : c.padEnd(w[i]))).join(" ")).join("\n");
|
|
@@ -140,7 +156,9 @@ export async function runPoolCli(argv, deps = {}) {
|
|
|
140
156
|
case "status": {
|
|
141
157
|
const cfg = routerConfig();
|
|
142
158
|
const r = await call(`http://${cfg.listen.host}:${cfg.listen.port}`, "GET", `/agents${flag("account") ? `?account=${encodeURIComponent(flag("account"))}` : ""}`, { token: cfg.forgedock_token });
|
|
143
|
-
const
|
|
159
|
+
const root = (await import("../lean/batch.mjs")).batchRoot(), kept = await keptRows(root);
|
|
160
|
+
const qw = queueWaitByWorker(await queueRows(root)); // #6062
|
|
161
|
+
if (Array.isArray(r.data?.agents)) r.data = { ...r.data, agents: r.data.agents.map((a) => (qw[a?.name] ? { ...a, queue_wait: qw[a.name] } : a)) };
|
|
144
162
|
if (rest.includes("--json")) console.log(JSON.stringify(r.data && typeof r.data === "object" && !Array.isArray(r.data) && kept.length ? { ...r.data, kept_sandboxes: kept } : r.data, null, 2));
|
|
145
163
|
else if (!r.ok) throw new Error(`router refused: HTTP ${r.status} ${JSON.stringify(r.data)}`);
|
|
146
164
|
else console.log(statusTable(r.data?.agents ?? []));
|
package/bin/pool/docker.mjs
CHANGED
|
@@ -32,6 +32,8 @@ export const dockerCli = {
|
|
|
32
32
|
throw e;
|
|
33
33
|
}
|
|
34
34
|
},
|
|
35
|
+
/** #6117: copies `src` (a path inside container `name`, running or exited) into the host dir `dest`. */
|
|
36
|
+
async copyOut(name, src, dest) { await docker(["cp", `${name}:${src}`, dest], { timeoutMs: 60000 }); },
|
|
35
37
|
async remove(name) { try { await docker(["rm", "-f", "-v", name], { timeoutMs: 60000 }); } catch (e) { if (!/No such container/i.test(e.stderr ?? "")) throw e; } },
|
|
36
38
|
/** Signal the container's main process (the lane). False when the container is gone or already stopped. */
|
|
37
39
|
async kill(name, signal = "TERM") {
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
import { readFileSync } from "node:fs";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The lane image manifest (#6035, #6037): pool/image/manifest.json lists the tools the pool image ships. Plan-time preflight
|
|
8
|
+
* and the sandbox install path resolve a tool against it instead of probing or installing it. Pure apart from the file read.
|
|
9
|
+
*/
|
|
10
|
+
export const MANIFEST_PATH = fileURLToPath(new URL("../../pool/image/manifest.json", import.meta.url));
|
|
11
|
+
|
|
12
|
+
/** {tools: [{name, binary, ...}]}; a missing or malformed file yields an empty manifest, never throws. */
|
|
13
|
+
export function loadImageManifest(path = MANIFEST_PATH) {
|
|
14
|
+
try {
|
|
15
|
+
const raw = JSON.parse(readFileSync(path, "utf8"));
|
|
16
|
+
return { tools: (Array.isArray(raw?.tools) ? raw.tools : []).filter((t) => t && typeof t.name === "string") };
|
|
17
|
+
} catch { return { tools: [] }; }
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** True when `tool` is the name or binary of a manifest entry. */
|
|
21
|
+
export function manifestProvides(manifest, tool) {
|
|
22
|
+
const t = String(tool ?? "");
|
|
23
|
+
return !!t && (manifest?.tools ?? []).some((e) => e.name === t || e.binary === t);
|
|
24
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
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 { join } from "node:path";
|
|
6
|
+
import { tmpDir } from "../tests/_tmp.mjs";
|
|
7
|
+
import { loadImageManifest, manifestProvides } from "./image-manifest.mjs";
|
|
8
|
+
|
|
9
|
+
describe("#6037 image manifest", () => {
|
|
10
|
+
it("resolves names and binaries of the real manifest", () => {
|
|
11
|
+
const m = loadImageManifest();
|
|
12
|
+
for (const t of ["shellcheck", "yq", "psql", "python3.12", "xvfb-run"]) assert.ok(manifestProvides(m, t), t);
|
|
13
|
+
for (const t of ["vite", "promtool", "", undefined]) assert.ok(!manifestProvides(m, t), String(t));
|
|
14
|
+
});
|
|
15
|
+
it("a missing or malformed file gives an empty manifest", () => {
|
|
16
|
+
const d = tmpDir("imgm");
|
|
17
|
+
assert.deepEqual(loadImageManifest(join(d, "nope.json")), { tools: [] });
|
|
18
|
+
assert.ok(!manifestProvides(loadImageManifest(join(d, "nope.json")), "yq"));
|
|
19
|
+
});
|
|
20
|
+
});
|
package/bin/pool/lane-tools.mjs
CHANGED
|
@@ -4,6 +4,9 @@ import { createHash } from "node:crypto";
|
|
|
4
4
|
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
5
5
|
import { tmpdir } from "node:os";
|
|
6
6
|
import { join } from "node:path";
|
|
7
|
+
import { loadImageManifest, manifestProvides } from "./image-manifest.mjs";
|
|
8
|
+
|
|
9
|
+
const IMAGE = loadImageManifest();
|
|
7
10
|
|
|
8
11
|
/**
|
|
9
12
|
* Per-repo lane images (#5650): forge.yaml `execution.lane_tools` lists the tools a repo's lanes need (`name` or
|
|
@@ -12,6 +15,7 @@ import { join } from "node:path";
|
|
|
12
15
|
* Dockerfile instructions (Debian/Ubuntu base, building as root) that install it.
|
|
13
16
|
*/
|
|
14
17
|
const apt = (...pkgs) => `RUN apt-get update && apt-get install -y --no-install-recommends ${pkgs.join(" ")} && rm -rf /var/lib/apt/lists/*`;
|
|
18
|
+
/** @deprecated Fallback only (#6017, #6037): pool/image/manifest.json is the source of truth for tools the image ships. */
|
|
15
19
|
export const RECIPES = {
|
|
16
20
|
"postgresql-client": { versioned: true, steps: (v) => [apt(v ? `postgresql-client-${v}` : "postgresql-client")] },
|
|
17
21
|
python: { versioned: true, steps: (v) => [apt(v ? `python${v} python${v}-venv` : "python3 python3-venv")] },
|
|
@@ -56,14 +60,20 @@ export function recipeFor(tool) {
|
|
|
56
60
|
}
|
|
57
61
|
|
|
58
62
|
/** True when `name` has a lane_tools recipe, directly or as a binary one provides (#5652, #5764). */
|
|
63
|
+
/** @deprecated Fallback only; see pool/image/manifest.json (#6017). */
|
|
59
64
|
export function hasRecipe(name) { return recipeFor(name) !== null; }
|
|
60
65
|
|
|
61
66
|
/**
|
|
62
67
|
* In-sandbox install commands (#5652) for one tool: the recipe's Dockerfile `RUN` steps as shell commands, `sudo` prefixed
|
|
63
|
-
* when the sandbox user is not root. Empty for a tool with no recipe
|
|
68
|
+
* when the sandbox user is not root. Empty for a tool with no recipe or one the image manifest provides (#6037).
|
|
69
|
+
* @deprecated Fallback only; pool/image/manifest.json replaces it (#6017).
|
|
70
|
+
* Pure; the image build keeps using `steps`.
|
|
64
71
|
*/
|
|
65
72
|
export function installCommands(entry, { root = true } = {}) {
|
|
66
73
|
const { name, version } = parseLaneTool(entry);
|
|
74
|
+
// the image covers the tool only when no version is pinned, or the manifest entry carries that same version (#6147)
|
|
75
|
+
const baked = (IMAGE?.tools ?? []).find((e) => e.name === name || e.binary === name);
|
|
76
|
+
if (manifestProvides(IMAGE, name) && (!version || String(baked?.version ?? "") === String(version))) return [];
|
|
67
77
|
const recipe = recipeFor(name);
|
|
68
78
|
if (!recipe) return [];
|
|
69
79
|
const sh = (s) => s.replace(/^RUN\s+/, "");
|
|
@@ -75,21 +85,29 @@ export function installCommands(entry, { root = true } = {}) {
|
|
|
75
85
|
* Generic install for a tool no recipe covers (2026-11-26 unclog): a missing Python module is pip-installed, a missing
|
|
76
86
|
* Node package npm-installed into the worktree, a missing command apt-installed. Replaces adding one recipe per tool
|
|
77
87
|
* (77 of 215 needs-human parks on open issues were "Remote sandbox lacks X"). `miss`: {kind, tool} from the validate
|
|
78
|
-
* preflight. Returns [] for an unsafe name or a kind nothing can install (environment, forgedock-path).
|
|
88
|
+
* preflight. Returns [] for an image-manifest tool, an unsafe name or a kind nothing can install (environment, forgedock-path).
|
|
89
|
+
* @deprecated Fallback only; pool/image/manifest.json replaces it (#6017, #6037).
|
|
79
90
|
*/
|
|
80
91
|
const PYPI = { yaml: "PyYAML", PIL: "Pillow", cv2: "opencv-python-headless", bs4: "beautifulsoup4", sklearn: "scikit-learn", dateutil: "python-dateutil", jwt: "PyJWT", dotenv: "python-dotenv", google: "protobuf", attr: "attrs", magic: "python-magic", Crypto: "pycryptodome", OpenSSL: "pyOpenSSL", serial: "pyserial", usb: "pyusb", zmq: "pyzmq", git: "GitPython", jose: "python-jose", multipart: "python-multipart" };
|
|
81
92
|
const SAFE = /^@?[A-Za-z0-9][A-Za-z0-9._/+-]*$/;
|
|
82
93
|
/** Debian/Ubuntu package stems where the import name differs (python3-<stem>). */
|
|
83
94
|
const APT_PY = { PIL: "pil", cv2: "opencv", bs4: "bs4", sklearn: "sklearn", dateutil: "dateutil", jwt: "jwt", dotenv: "dotenv", serial: "serial", git: "git", magic: "magic" };
|
|
95
|
+
/** Python modules a failed run's output reports missing (`No module named 'yaml'`, top-level name only). */
|
|
96
|
+
export function missingPythonModules(output) {
|
|
97
|
+
return [...new Set([...String(output ?? "").matchAll(/No module named ['"]?([A-Za-z0-9_]+)/gi)].map((m) => m[1]))];
|
|
98
|
+
}
|
|
84
99
|
export function genericInstallCommands(miss, { root = true } = {}) {
|
|
85
100
|
const tool = String(miss?.tool ?? "").trim();
|
|
86
|
-
if (!tool || !SAFE.test(tool) || tool.includes("..")) return [];
|
|
101
|
+
if (!tool || !SAFE.test(tool) || tool.includes("..") || (miss.kind === "command" && manifestProvides(IMAGE, tool))) return [];
|
|
87
102
|
const su = (c) => (root ? c : `sudo sh -c ${JSON.stringify(c)}`);
|
|
88
103
|
if (miss.kind === "python-module") {
|
|
89
104
|
const mod = tool.split(".")[0], pkg = PYPI[mod] ?? mod;
|
|
90
105
|
// 2026-11-26: lane images may ship python3 without pip; the distro package (python3-<module>) is the fallback
|
|
91
106
|
const deb = `python3-${(APT_PY[mod] ?? mod).toLowerCase().replace(/_/g, "-")}`;
|
|
92
|
-
|
|
107
|
+
// #6138: install into the interpreter the validate runs, system-wide (no --user: `python3 -I` ignores user site-packages), then the distro package
|
|
108
|
+
const pip = `python3 -m pip install --quiet --break-system-packages ${pkg} || python3 -m pip install --quiet ${pkg}`;
|
|
109
|
+
const apt = `apt-get update -qq && apt-get install -y --no-install-recommends ${deb} && rm -rf /var/lib/apt/lists/*`;
|
|
110
|
+
return [root ? `${pip} || (${apt})` : `${su(pip)} || (${su(apt)})`];
|
|
93
111
|
}
|
|
94
112
|
if (miss.kind === "node-module") return [`npm install --no-save --no-audit --no-fund ${tool}`];
|
|
95
113
|
if (miss.kind === "command" && !tool.includes("/")) return [su(`apt-get update -qq && apt-get install -y --no-install-recommends ${tool} && rm -rf /var/lib/apt/lists/*`)];
|
|
@@ -97,6 +115,7 @@ export function genericInstallCommands(miss, { root = true } = {}) {
|
|
|
97
115
|
}
|
|
98
116
|
|
|
99
117
|
/**
|
|
118
|
+
* @deprecated Fallback only; see pool/image/manifest.json (#6017).
|
|
100
119
|
* Installs `tools` in the running sandbox through the injected `run({command, timeoutMs})` -> {rc, stdout, stderr}.
|
|
101
120
|
* Never throws: {ok:true} or {ok:false, tool, stderrTail}.
|
|
102
121
|
*/
|
|
@@ -2,18 +2,22 @@
|
|
|
2
2
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
3
|
import { describe, it } from "node:test";
|
|
4
4
|
import assert from "node:assert/strict";
|
|
5
|
-
import { hasRecipe, recipeFor, installCommands, installLaneTools, laneToolsDockerfile } from "./lane-tools.mjs";
|
|
5
|
+
import { RECIPES, hasRecipe, recipeFor, installCommands, installLaneTools, laneToolsDockerfile } from "./lane-tools.mjs";
|
|
6
6
|
|
|
7
7
|
describe("#5652 in-sandbox lane tool install", () => {
|
|
8
8
|
it("installCommands strips RUN, prefixes sudo when not root, and is empty without a recipe", () => {
|
|
9
9
|
assert.ok(hasRecipe("promtool") && !hasRecipe("nope"));
|
|
10
|
-
assert.match(installCommands("
|
|
11
|
-
assert.match(installCommands("
|
|
10
|
+
assert.match(installCommands("yaml")[0], /^apt-get update/);
|
|
11
|
+
assert.match(installCommands("yaml", { root: false })[0], /^sudo sh -c /);
|
|
12
12
|
assert.deepEqual(installCommands("nope"), []);
|
|
13
13
|
});
|
|
14
|
+
it("a manifest-provided tool is skipped unpinned, but a pinned version still installs (#6147)", () => {
|
|
15
|
+
assert.deepEqual(installCommands("postgresql-client"), []);
|
|
16
|
+
assert.match(installCommands("postgresql-client@16").join("\n"), /postgresql-client-16/);
|
|
17
|
+
});
|
|
14
18
|
it("installLaneTools runs every step, and returns the stderr tail of the first failure", async () => {
|
|
15
19
|
const seen = [];
|
|
16
|
-
assert.deepEqual(await installLaneTools(["
|
|
20
|
+
assert.deepEqual(await installLaneTools(["yaml"], { run: async (a) => { seen.push(a.command); return { rc: 0 }; } }), { ok: true });
|
|
17
21
|
assert.equal(seen.length, 1);
|
|
18
22
|
const bad = await installLaneTools(["promtool@2.54.1"], { run: async () => ({ rc: 3, stderr: "a\nb\n404" }) });
|
|
19
23
|
assert.equal(bad.ok, false);
|
|
@@ -25,14 +29,14 @@ describe("#5652 in-sandbox lane tool install", () => {
|
|
|
25
29
|
});
|
|
26
30
|
it("#5763 shellcheck is an unversioned apt recipe in the derived image", () => {
|
|
27
31
|
assert.ok(hasRecipe("shellcheck"));
|
|
28
|
-
assert.match(
|
|
32
|
+
assert.match(RECIPES.shellcheck.steps()[0], /^RUN apt-get update && apt-get install -y --no-install-recommends shellcheck /);
|
|
29
33
|
assert.match(laneToolsDockerfile("base:1", ["shellcheck"]), /\nRUN apt-get update && apt-get install -y --no-install-recommends shellcheck /);
|
|
30
34
|
});
|
|
31
35
|
it("#5764 a binary a recipe provides resolves to it; python3 installs the unversioned python recipe", () => {
|
|
32
36
|
for (const [b, r] of [["python3", "python"], ["python3.12", "python"], ["pip3", "python"], ["psql", "postgresql-client"], ["xvfb-run", "xvfb"], ["python", "python"]]) assert.equal(recipeFor(b), r, b);
|
|
33
37
|
assert.ok(hasRecipe("python3") && !hasRecipe("zzcheck") && recipeFor("zzcheck") === null);
|
|
34
|
-
assert.match(
|
|
35
|
-
assert.match(
|
|
38
|
+
assert.match(RECIPES.python.steps()[0], /install -y --no-install-recommends python3 python3-venv /);
|
|
39
|
+
assert.match(RECIPES.python.steps("3.12")[0], /python3\.12 python3\.12-venv/);
|
|
36
40
|
});
|
|
37
41
|
});
|
|
38
42
|
|
|
@@ -44,3 +48,19 @@ describe("#5749 yaml recipe", () => {
|
|
|
44
48
|
assert.ok(!hasRecipe("vite") && !hasRecipe("forgedock"), "#5749: manifest/owned deps get no recipe");
|
|
45
49
|
});
|
|
46
50
|
});
|
|
51
|
+
|
|
52
|
+
describe("#6037 image manifest tools skip the fallback installers", () => {
|
|
53
|
+
it("returns [] for manifest tools and keeps commands for others", async () => {
|
|
54
|
+
const { genericInstallCommands } = await import("./lane-tools.mjs");
|
|
55
|
+
for (const t of ["shellcheck", "xvfb", "yq"]) assert.deepEqual(installCommands(t), [], t);
|
|
56
|
+
for (const t of ["shellcheck", "yq"]) assert.deepEqual(genericInstallCommands({ kind: "command", tool: t }), [], t);
|
|
57
|
+
assert.ok(installCommands("promtool").length);
|
|
58
|
+
assert.match(genericInstallCommands({ kind: "command", tool: "ripgrep" })[0], /apt-get install/);
|
|
59
|
+
});
|
|
60
|
+
it("marks the fallbacks deprecated", async () => {
|
|
61
|
+
const { readFileSync } = await import("node:fs");
|
|
62
|
+
const src = readFileSync(new URL("./lane-tools.mjs", import.meta.url), "utf8");
|
|
63
|
+
assert.match(src, /@deprecated[^\n]*\n(export const RECIPES|export function hasRecipe)/);
|
|
64
|
+
assert.ok((src.match(/@deprecated/g) ?? []).length >= 4);
|
|
65
|
+
});
|
|
66
|
+
});
|