forgedock 1.63.0 → 1.65.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 +3 -0
- package/bin/engine/outcome-codes.mjs +5 -0
- package/bin/engine-cli.mjs +88 -12
- package/bin/env/cli.mjs +18 -1
- package/bin/lean/basered.mjs +56 -11
- package/bin/lean/basered.test.mjs +58 -5
- package/bin/lean/batch-health.mjs +46 -4
- package/bin/lean/batch-health.test.mjs +55 -1
- package/bin/lean/batch.mjs +8 -1
- package/bin/lean/batch.test.mjs +71 -6
- package/bin/lean/ceiling.mjs +47 -3
- package/bin/lean/ceiling.test.mjs +32 -1
- package/bin/lean/clear-breaker.mjs +15 -0
- package/bin/lean/clear-breaker.test.mjs +100 -0
- package/bin/lean/conformance.e2e.test.mjs +32 -6
- package/bin/lean/conformance.mjs +57 -13
- package/bin/lean/conformance.test.mjs +93 -1
- package/bin/lean/execution.mjs +18 -8
- package/bin/lean/execution.test.mjs +44 -3
- package/bin/lean/issuewatch-reconcile.mjs +2 -0
- package/bin/lean/issuewatch-reconcile.test.mjs +25 -0
- package/bin/lean/issuewatch.mjs +3 -0
- package/bin/lean/lanecheck.test.mjs +13 -1
- package/bin/lean/lean.mjs +157 -28
- package/bin/lean/lean.test.mjs +289 -21
- package/bin/lean/live-execution.mjs +25 -0
- package/bin/lean/live-execution.test.mjs +35 -1
- package/bin/lean/merged-park.mjs +76 -0
- package/bin/lean/merged-park.test.mjs +64 -0
- package/bin/lean/mergetrain.mjs +357 -0
- package/bin/lean/mergetrain.test.mjs +348 -0
- package/bin/lean/mirror-bundle.mjs +84 -0
- package/bin/lean/orchestrate-envhold.test.mjs +62 -0
- package/bin/lean/orchestrate-stacking.test.mjs +23 -1
- package/bin/lean/orchestrate-train.test.mjs +130 -0
- package/bin/lean/orchestrate-transient-git.test.mjs +53 -0
- package/bin/lean/orchestrate.mjs +170 -13
- package/bin/lean/prompts.mjs +4 -3
- package/bin/lean/release-review.mjs +8 -1
- package/bin/lean/release-review.test.mjs +42 -2
- package/bin/lean/release-status.test.mjs +53 -1
- package/bin/lean/release.mjs +6 -3
- package/bin/lean/render.mjs +6 -1
- package/bin/lean/sandbox-provider.contract.test.mjs +6 -0
- package/bin/lean/sandbox-remote.mjs +43 -3
- package/bin/lean/sched.mjs +19 -2
- package/bin/lean/sched.test.mjs +33 -1
- package/bin/lean/schedd-health.mjs +2 -1
- package/bin/lean/schedd-health.test.mjs +7 -0
- package/bin/lean/schedd.mjs +58 -7
- package/bin/lean/schedd.test.mjs +78 -1
- package/bin/lean/stacking.mjs +45 -0
- package/bin/lean/stacking.test.mjs +25 -1
- package/bin/lean/statuscomment.mjs +14 -8
- package/bin/lean/statuscomment.test.mjs +18 -1
- package/bin/lean/validate-catalog.mjs +1 -1
- package/bin/lean/validate-catalog.test.mjs +3 -0
- package/bin/lean/worktree.mjs +8 -3
- package/bin/lean/worktree.test.mjs +18 -0
- package/bin/pool/agent.mjs +309 -33
- package/bin/pool/cache-sweep.mjs +4 -2
- package/bin/pool/cli.mjs +125 -6
- package/bin/pool/disk.mjs +43 -0
- package/bin/pool/docker.mjs +11 -0
- package/bin/pool/health.mjs +95 -0
- package/bin/pool/mirror-seed.mjs +103 -0
- package/bin/pool/router.mjs +301 -27
- package/bin/runner.mjs +3 -1
- package/bin/stats/chains.mjs +101 -0
- package/bin/stats/chains.test.mjs +53 -0
- package/bin/stats/efficiency.mjs +7 -6
- package/bin/stats/efficiency.test.mjs +48 -7
- package/bin/stats/index.mjs +11 -3
- package/bin/stats/stats.test.mjs +9 -0
- package/docs/CONFIG.md +8 -1
- package/docs/OUTCOME-CODES.md +4 -0
- package/package.json +1 -1
- package/pool/README.md +10 -0
- package/pool/image/Dockerfile +2 -1
- package/pool/image/entrypoint.sh +25 -6
- package/pool/image/mirror.sh +71 -0
- package/pool/install/install-agent-linux.sh +57 -5
- package/pool/install/install-agent-macos.sh +148 -0
- package/pool/install/install-agent.ps1 +11 -0
- package/pool/install/install-agent.sh +59 -7
- package/pool/install/uninstall-agent-linux.sh +75 -0
- package/pool/install/uninstall-agent-macos.sh +60 -0
- package/pool/install/uninstall-agent.ps1 +1 -0
- package/scripts/transition-label.sh +11 -0
package/bin/pool/agent.mjs
CHANGED
|
@@ -7,14 +7,16 @@ import { randomBytes } from "node:crypto";
|
|
|
7
7
|
import { execFile, spawn } from "node:child_process";
|
|
8
8
|
import { promisify } from "node:util";
|
|
9
9
|
import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, rmSync, statSync, statfsSync, lstatSync, writeFileSync } from "node:fs";
|
|
10
|
-
import { basename, join } from "node:path";
|
|
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";
|
|
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
16
|
import { resolveLaneImage, laneImageNow, laneToolsTag, isLaneToolsTagOf } from "./lane-tools.mjs";
|
|
17
|
-
import { hostDiskFree } from "./health.mjs";
|
|
17
|
+
import { hostDiskFree, ensureNatPin, netState } from "./health.mjs";
|
|
18
|
+
import { laneDiskUsedGb, planDiskCap, fstrimDue, runFstrim } from "./disk.mjs";
|
|
19
|
+
import { makeMirrorSeed, dockerRunner } from "./mirror-seed.mjs";
|
|
18
20
|
import { planIdleEviction, CACHE_LABEL, agentLabel } from "./cache-sweep.mjs";
|
|
19
21
|
|
|
20
22
|
const LABEL = "computeshare=1";
|
|
@@ -85,15 +87,34 @@ const envLine = (k, v) => `${k}=${String(v).replace(/\r?\n/g, " ")}`;
|
|
|
85
87
|
* Host agent: runs each sandbox as one docker container inside a fixed reservation (allow_cpus / allow_mem_gb).
|
|
86
88
|
* A sandbox lives only while its lease is renewed; the reaper removes expired, over-age and orphaned containers.
|
|
87
89
|
*/
|
|
88
|
-
|
|
90
|
+
/** #5919: a build/upgrade failure as text, keeping its END (the failing step's own output), not the Dockerfile echo at its head. */
|
|
91
|
+
export function upgradeErrorText(e, max = 2000) {
|
|
92
|
+
const t = String(e?.stderr || e?.stdout || e?.message || e || "").trim();
|
|
93
|
+
return t.length <= max ? t : `…${t.slice(t.length - max + 1)}`;
|
|
94
|
+
}
|
|
95
|
+
/** #5919: a build failure that a retry can fix (network, registry or DNS), as opposed to a bad Dockerfile or version pin. */
|
|
96
|
+
export const NETWORK_BUILD_RE = /ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|ENOTFOUND|socket hang up|network timeout|timed out|Could not resolve host|Connection reset|TLS handshake|i\/o timeout|unexpected EOF|curl: \((?:6|7|18|28|35|52|56)\)|npm (?:ERR!|error) (?:code|network) (?:ETIMEDOUT|ECONNRESET|EAI_AGAIN|ENOTFOUND)|503 Service Unavailable|502 Bad Gateway/i;
|
|
97
|
+
/** #5919: run `build`; one retry after `delayMs` when the first failure looks like a network error. */
|
|
98
|
+
export async function buildWithRetry(build, { sleep = (ms) => new Promise((r) => setTimeout(r, ms)), delayMs = 30000, log = null } = {}) {
|
|
99
|
+
try { return await build(); } catch (e) {
|
|
100
|
+
if (!NETWORK_BUILD_RE.test(upgradeErrorText(e, 20000))) throw e;
|
|
101
|
+
log?.warn?.(`lane image build failed on a network error; retrying once: ${upgradeErrorText(e, 300)}`);
|
|
102
|
+
await sleep(delayMs);
|
|
103
|
+
return build();
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function createAgent(cfg, { docker, now = () => Date.now(), log = console, live = liveHeadroom, hostDisk = null, net = netState, vm = vmSize, trim = runFstrim, mirrorRunner = null } = {}) {
|
|
89
108
|
const stateDir = cfg.state_dir;
|
|
90
109
|
const store = jsonStore(join(stateDir, "state.json"), { sandboxes: {} });
|
|
91
110
|
const sb = () => store.data.sandboxes;
|
|
111
|
+
const activeRecs = () => Object.values(sb()).filter((s) => s.state !== "exited");
|
|
92
112
|
// Sandbox ids come from requests: read own keys only, so "__proto__" or "constructor" never resolves to an inherited member (#4566).
|
|
93
113
|
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
|
|
94
114
|
const leaseTtlMs = (cfg.lease_ttl_s ?? 600) * 1000;
|
|
95
115
|
const maxLifeMs = (cfg.max_lifetime_s ?? 6 * 3600) * 1000;
|
|
96
116
|
const keepExitedMs = (cfg.keep_exited_s ?? 2 * 3600) * 1000;
|
|
117
|
+
const keepPressureMs = (cfg.keep_disk_pressure_s ?? 24 * 3600) * 1000; // #5891: a disk-pressure stop keeps its worktree long enough for the requeue
|
|
97
118
|
const running = versionOf(cfg.code_root ?? repoRoot);
|
|
98
119
|
// The lane image tracks the installed ForgeDock version; only an explicit non-legacy cfg.image overrides it.
|
|
99
120
|
const image = cfg.image && cfg.image !== "computeshare-lane:1" ? cfg.image : laneImageTag(running.version);
|
|
@@ -123,6 +144,34 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
123
144
|
log.warn?.(`prepull ${dindImage}: ${prepull.error}`);
|
|
124
145
|
} finally { rmSync(file, { force: true }); }
|
|
125
146
|
}
|
|
147
|
+
// #5858: advertised capacity is the configured allowance clamped to the measured VM minus a host reserve, less what
|
|
148
|
+
// non-sandbox containers use; admission projects each repo's measured per-sandbox peak, not only the configured slice.
|
|
149
|
+
const r1 = (x) => Math.round(x * 10) / 10, r2 = (x) => Math.round(x * 100) / 100;
|
|
150
|
+
let clampWarned = false;
|
|
151
|
+
let coTenant = { cpus: 0, mem_gb: 0 };
|
|
152
|
+
function effectiveCapacity() {
|
|
153
|
+
let v = {}; try { v = vm() ?? {}; } catch { /* unknown VM: no clamp */ }
|
|
154
|
+
const reserve = cfg.host_reserve_mem_gb ?? Math.max(1, (v.mem_gb ?? 0) * 0.1);
|
|
155
|
+
const cpusEff = v.cpus > 0 ? Math.min(cfg.allow_cpus, v.cpus) : cfg.allow_cpus;
|
|
156
|
+
const memEff = v.mem_gb > 0 ? Math.min(cfg.allow_mem_gb, Math.max(1, r1(v.mem_gb - reserve))) : cfg.allow_mem_gb;
|
|
157
|
+
const clamped = cpusEff < cfg.allow_cpus || memEff < cfg.allow_mem_gb;
|
|
158
|
+
if (clamped && !clampWarned) { clampWarned = true; log.warn?.(`configured capacity ${cfg.allow_cpus} cpus / ${cfg.allow_mem_gb} GB exceeds the VM (${v.cpus} cpus / ${v.mem_gb} GB minus ${r1(reserve)} GB reserve); advertising ${cpusEff} cpus / ${memEff} GB`); }
|
|
159
|
+
return { cpus: cpusEff, mem: memEff, clamped, vm: v };
|
|
160
|
+
}
|
|
161
|
+
const slugOf = (spec) => (spec?.repo?.slug ? String(spec.repo.slug).toLowerCase() : null);
|
|
162
|
+
let histRows = null;
|
|
163
|
+
function usageRows() {
|
|
164
|
+
if (histRows) return histRows;
|
|
165
|
+
try { histRows = readFileSync(join(stateDir, "usage-history.jsonl"), "utf8").split("\n").filter(Boolean).slice(-500).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean); } catch { histRows = []; }
|
|
166
|
+
return histRows;
|
|
167
|
+
}
|
|
168
|
+
const pct = (xs, p) => { const a = [...xs].sort((x, y) => x - y); return a[Math.min(a.length - 1, Math.ceil(p * a.length) - 1)]; };
|
|
169
|
+
/** Per-sandbox projection for a repo: p90 mem_peak_gb / p75 cpu_avg over the last N finished sandboxes, never below the slice. */
|
|
170
|
+
function estimateFor(repo, slice) {
|
|
171
|
+
const rows = repo ? usageRows().filter((x) => x.repo === repo && Number.isFinite(x.mem_peak_gb) && Number.isFinite(x.cpu_avg)).slice(-(cfg.estimate_window ?? 20)) : [];
|
|
172
|
+
if (rows.length < (cfg.estimate_min_samples ?? 3)) return { cpus: slice.cpus, mem: slice.mem, samples: rows.length };
|
|
173
|
+
return { cpus: Math.max(slice.cpus, pct(rows.map((x) => x.cpu_avg), 0.75)), mem: Math.max(slice.mem, pct(rows.map((x) => x.mem_peak_gb), 0.9)), samples: rows.length };
|
|
174
|
+
}
|
|
126
175
|
const used = () => Object.values(sb()).filter((s) => s.state !== "exited").reduce((a, s) => ({ cpus: a.cpus + s.cpus, mem: a.mem + s.mem_gb }), { cpus: 0, mem: 0 });
|
|
127
176
|
// #5535: disk figures for the router inventory; optional, omitted when unreadable. Sandbox dirs are walked at most every 60s.
|
|
128
177
|
let diskCache = { at: 0, mb: {} };
|
|
@@ -138,7 +187,13 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
138
187
|
try { const f = statfsSync(stateDir); out.disk_free_gb = Math.round((Number(f.bavail) * Number(f.bsize)) / 107374182.4) / 10; } catch { /* unknown */ }
|
|
139
188
|
if (Date.now() - diskCache.at > 60000) {
|
|
140
189
|
const mb = {};
|
|
141
|
-
for (const r of Object.values(sb())) if (r.state !== "exited")
|
|
190
|
+
for (const r of Object.values(sb())) if (r.state !== "exited") {
|
|
191
|
+
mb[r.id] = dirMb(join(stateDir, "sandboxes", safeName(r.id)));
|
|
192
|
+
// #5891: peak size (feeds the repo's p90 reservation) and growth rate (picks the sandbox to pause)
|
|
193
|
+
r.diskPeakMb = Math.max(r.diskPeakMb ?? 0, mb[r.id]);
|
|
194
|
+
if (r.diskPrev && now() > r.diskPrev.at) r.growthMbH = Math.round(((mb[r.id] - r.diskPrev.mb) / ((now() - r.diskPrev.at) / 3600000)));
|
|
195
|
+
r.diskPrev = { at: now(), mb: mb[r.id] };
|
|
196
|
+
}
|
|
142
197
|
diskCache = { at: Date.now(), mb };
|
|
143
198
|
}
|
|
144
199
|
out.sandbox_disk_mb = diskCache.mb;
|
|
@@ -150,12 +205,43 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
150
205
|
if (now() - hostDiskCache.at > 60000) hostDiskCache = { at: now(), v: hostDiskFree({ path: cfg.host_disk_path ?? null }) };
|
|
151
206
|
return hostDiskCache.v;
|
|
152
207
|
});
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
208
|
+
// #5891: disk is a reserved resource. A lane reserves the p90 of its repo's measured peak sandbox_disk_mb (fallback sandbox_disk_growth_gb);
|
|
209
|
+
// admission needs host free minus every reservation to stay above the floor. Host free already contains the current use.
|
|
210
|
+
const floorGb = () => cfg.host_disk_floor_gb ?? cfg.min_host_disk_free_gb ?? 25;
|
|
211
|
+
const hist = () => (store.data.disk_hist ??= {});
|
|
212
|
+
const reservationGb = (slug) => {
|
|
213
|
+
const xs = [...(hist()[slug] ?? [])].sort((a, b) => a - b);
|
|
214
|
+
return xs.length >= (cfg.disk_min_samples ?? 3) ? Math.max(0.1, xs[Math.min(xs.length - 1, Math.ceil(xs.length * 0.9) - 1)] / 1024) : (cfg.sandbox_disk_growth_gb ?? 3.5);
|
|
215
|
+
};
|
|
216
|
+
const diskPaused = () => activeRecs().some((r) => r.diskPaused);
|
|
217
|
+
const hostDiskLow = (free, active, slug = null) => free < floorGb() || diskPaused() || free - (activeRecs().reduce((a, r) => a + reservationGb(r.slug), 0) + reservationGb(slug)) < floorGb();
|
|
218
|
+
const hostSamples = []; // [{t, gb}] over the last 3h: the drive's growth rate and time-to-full
|
|
219
|
+
function noteHostDisk(gb) {
|
|
220
|
+
const t = now();
|
|
221
|
+
if (hostSamples.length && hostSamples[hostSamples.length - 1].t === t) hostSamples.pop();
|
|
222
|
+
hostSamples.push({ t, gb });
|
|
223
|
+
while (hostSamples.length > 2 && t - hostSamples[0].t > 3 * 3600000) hostSamples.shift();
|
|
224
|
+
}
|
|
225
|
+
/** GB/h the host drive shrinks (negative = freeing), or null until two samples at least a minute apart exist. */
|
|
226
|
+
function hostGrowthPerH() {
|
|
227
|
+
const a = hostSamples[0], b = hostSamples[hostSamples.length - 1];
|
|
228
|
+
return a && b && b.t - a.t >= 60000 ? Math.round(((a.gb - b.gb) / ((b.t - a.t) / 3600000)) * 10) / 10 : null;
|
|
229
|
+
}
|
|
230
|
+
let netCache = { at: -Infinity, v: null };
|
|
231
|
+
const readNet = () => { if (now() - netCache.at > 60000) netCache = { at: now(), v: net() }; return netCache.v; };
|
|
232
|
+
// #5884: lane disk cap (cfg.lane_disk_cap_gb, unset = off, nothing added to /capacity): sandbox dirs plus cache volumes.
|
|
233
|
+
function laneDiskView() {
|
|
234
|
+
if (!(Number(cfg.lane_disk_cap_gb) > 0)) return {};
|
|
235
|
+
const used = laneDiskUsedGb({ sandboxMb: diskView().sandbox_disk_mb, cacheVolumes: Object.fromEntries(cacheInfo) });
|
|
236
|
+
const state = planDiskCap({ usedGb: used, capGb: cfg.lane_disk_cap_gb, pruneAtPct: cfg.disk_prune_at_pct });
|
|
237
|
+
return { lane_disk_used_gb: used, lane_disk_cap_gb: Number(cfg.lane_disk_cap_gb), disk_capped: state === "full" };
|
|
238
|
+
}
|
|
239
|
+
function hostDiskView(active, slug = null) {
|
|
156
240
|
let hd = null; try { hd = readHostDisk(); } catch { hd = null; }
|
|
157
241
|
if (!hd || !Number.isFinite(hd.gb)) return {};
|
|
158
|
-
|
|
242
|
+
noteHostDisk(hd.gb);
|
|
243
|
+
const g = hostGrowthPerH();
|
|
244
|
+
return { host_disk_free_gb: hd.gb, host_disk_low: hostDiskLow(hd.gb, active, slug), ...(g === null ? {} : { host_disk_growth_gb_per_h: g, ...(g > 0 ? { host_disk_full_in_h: Math.round((hd.gb / g) * 10) / 10 } : {}) }), ...(diskPaused() ? { disk_paused: activeRecs().filter((r) => r.diskPaused).length } : {}) };
|
|
159
245
|
}
|
|
160
246
|
// #5856: priority classes. `reserved` sandboxes are admitted up to a named reservation (cfg.reservations) and may reclaim
|
|
161
247
|
// capacity from `borrow` ones (throttle first, then SIGTERM so the lane checkpoints and reports run.interrupted);
|
|
@@ -163,7 +249,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
163
249
|
const PRIORITIES = ["reserved", "normal", "borrow"];
|
|
164
250
|
const reservations = () => (Array.isArray(cfg.reservations) ? cfg.reservations.filter((r) => r && typeof r.name === "string" && r.cpus > 0 && r.mem_gb > 0) : []);
|
|
165
251
|
const prioOf = (r) => r.priority ?? "normal";
|
|
166
|
-
const
|
|
252
|
+
const projectedUse = () => activeRecs().reduce((a, r) => { const e = estimateFor(r.repo ?? null, { cpus: r.cpus, mem: r.mem_gb }); return { cpus: a.cpus + Math.max(r.cpus, e.cpus), mem: a.mem + Math.max(r.mem_gb, e.mem) }; }, { cpus: 0, mem: 0 });
|
|
167
253
|
const sumRecs = (rs) => rs.reduce((a, s) => ({ cpus: a.cpus + s.cpus, mem: a.mem + s.mem_gb }), { cpus: 0, mem: 0 });
|
|
168
254
|
const weighted = () => reservations().length > 0 || Boolean(cfg.idle_only);
|
|
169
255
|
const SHARES = () => ({ reserved: 4096, normal: 1024, borrow: 128, throttled: 2, ...(cfg.cpu_shares ?? {}) });
|
|
@@ -172,8 +258,9 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
172
258
|
const act = activeRecs(), rs = reservations();
|
|
173
259
|
const tot = rs.reduce((a, r) => ({ cpus: a.cpus + r.cpus, mem: a.mem + r.mem_gb }), { cpus: 0, mem: 0 });
|
|
174
260
|
const u = sumRecs(act), nonRes = sumRecs(act.filter((s) => prioOf(s) !== "reserved"));
|
|
175
|
-
const
|
|
176
|
-
|
|
261
|
+
const e = effectiveCapacity();
|
|
262
|
+
const free = { cpus: e.cpus - u.cpus - coTenant.cpus, mem: e.mem - u.mem - coTenant.mem_gb };
|
|
263
|
+
return { act, rs, tot, free, unreserved: { cpus: Math.max(0, Math.min(free.cpus, e.cpus - tot.cpus - nonRes.cpus)), mem: Math.max(0, Math.min(free.mem, e.mem - tot.mem - nonRes.mem)) } };
|
|
177
264
|
}
|
|
178
265
|
/** Owner load per core with this agent's own sandboxes subtracted (the box's primary workload), or null when unknown. */
|
|
179
266
|
function ownerLoad(h) {
|
|
@@ -192,6 +279,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
192
279
|
}
|
|
193
280
|
// 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).
|
|
194
281
|
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; };
|
|
282
|
+
let lastDrain = null; // #5885: the most recent drain, for capacity().last_drain
|
|
195
283
|
/** SIGTERM (the lane checkpoints and reports run.interrupted), wait out the grace, then SIGKILL; the router/dispatcher reschedules the lane. */
|
|
196
284
|
async function drainOne(r, why) {
|
|
197
285
|
for (const n of r.docker ? [r.name, dindName(r.name)] : [r.name]) { try { await docker.kill(n, "TERM"); } catch { /* gone */ } }
|
|
@@ -199,6 +287,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
199
287
|
try { await docker.kill(r.name, "KILL"); } catch { /* already exited */ }
|
|
200
288
|
if (r.docker) { try { await docker.remove(dindName(r.name)); } catch { /* destroy retries */ } }
|
|
201
289
|
r.state = "exited"; r.finishedAt = now(); r.drained = why;
|
|
290
|
+
lastDrain = { reason: why, at: new Date(now()).toISOString(), sandbox: r.id }; // #5885: shown by `pool status`
|
|
202
291
|
log.info?.(`drained borrowed sandbox ${r.id} (${why})`);
|
|
203
292
|
}
|
|
204
293
|
/** Admission by class: `{ victims }` (borrow sandboxes to reclaim, reserved only) or `{ refuse }` (a 503/400 body). */
|
|
@@ -223,6 +312,42 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
223
312
|
}
|
|
224
313
|
return needC > 0 || needM > 0 ? { refuse: { status: 503 } } : { victims };
|
|
225
314
|
}
|
|
315
|
+
/** #5885: why borrowed lanes are throttled or drained (weighted agents only, like priorityView). */
|
|
316
|
+
function throttleView(h) {
|
|
317
|
+
if (!weighted()) return {};
|
|
318
|
+
return { idle_gate: notIdle(h), throttled: activeRecs().filter((r) => r.throttled).length, last_drain: lastDrain };
|
|
319
|
+
}
|
|
320
|
+
/** #5885: the owner's own pause, distinct from the resize drain's cfg.paused; a file beside the agent config keeps it across restarts. */
|
|
321
|
+
const ownerPauseFile = join(cfg.config_path ? dirname(cfg.config_path) : stateDir, "owner-paused");
|
|
322
|
+
let ownerPaused = existsSync(ownerPauseFile);
|
|
323
|
+
function setOwnerPause(on) {
|
|
324
|
+
if (on) writeFileSync(ownerPauseFile, `${new Date(now()).toISOString()}\n`, { mode: 0o600 });
|
|
325
|
+
else rmSync(ownerPauseFile, { force: true });
|
|
326
|
+
ownerPaused = on;
|
|
327
|
+
log.info?.(`owner ${on ? "paused" : "resumed"} this agent`);
|
|
328
|
+
return { status: 200, body: { ok: true, owner_paused: on, active: capacity().active } };
|
|
329
|
+
}
|
|
330
|
+
/** #5886: a router-pushed policy (allowlisted keys, persisted beside the agent config). Its `paused` is separate from the owner's pause: the router can set or clear only its own, never the owner's. */
|
|
331
|
+
let policyPaused = Boolean(cfg.policy_paused);
|
|
332
|
+
function applyPolicy(body) {
|
|
333
|
+
const p = body && typeof body === "object" ? body : {}, int = (v, lo, hi) => (Number.isInteger(v) && v >= lo && v <= hi);
|
|
334
|
+
if ((p.cpus !== undefined && !int(p.cpus, 1, 256)) || (p.mem_gb !== undefined && !int(p.mem_gb, 1, 1024)) || (p.idle_only !== undefined && typeof p.idle_only !== "boolean") || (p.paused !== undefined && typeof p.paused !== "boolean")
|
|
335
|
+
|| (p.floors !== undefined && !(p.floors && typeof p.floors === "object" && Object.keys(p.floors).every((k) => k === "host_disk_gb" && Number.isFinite(p.floors[k]) && p.floors[k] >= 0)))) return { status: 400, body: { error: "invalid policy" } };
|
|
336
|
+
const set = {};
|
|
337
|
+
if (p.cpus !== undefined) set.allow_cpus = p.cpus;
|
|
338
|
+
if (p.mem_gb !== undefined) set.allow_mem_gb = p.mem_gb;
|
|
339
|
+
if (p.idle_only !== undefined) set.idle_only = p.idle_only;
|
|
340
|
+
if (p.floors?.host_disk_gb !== undefined) set.host_disk_floor_gb = p.floors.host_disk_gb;
|
|
341
|
+
if (p.paused !== undefined) set.policy_paused = p.paused;
|
|
342
|
+
if (cfg.config_path) {
|
|
343
|
+
try { const c = JSON.parse(readFileSync(cfg.config_path, "utf8")); writeFileSync(cfg.config_path, JSON.stringify({ ...c, ...set }, null, 2), { mode: 0o600 }); }
|
|
344
|
+
catch (e) { log.warn?.(`policy not persisted: ${e.message}`); }
|
|
345
|
+
}
|
|
346
|
+
Object.assign(cfg, set);
|
|
347
|
+
if (p.paused !== undefined) policyPaused = p.paused;
|
|
348
|
+
log.info?.(`policy applied: ${Object.keys(set).join(", ") || "none"}`);
|
|
349
|
+
return { status: 200, body: { ok: true, applied: Object.keys(p), paused: Boolean(cfg.paused || ownerPaused || policyPaused), owner_paused: ownerPaused } };
|
|
350
|
+
}
|
|
226
351
|
/** #5856: reserved vs borrowable headroom for the router (only when reservations or idle_only are configured). */
|
|
227
352
|
function priorityView() {
|
|
228
353
|
if (!weighted()) return {};
|
|
@@ -233,7 +358,9 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
233
358
|
function capacity() {
|
|
234
359
|
const u = used();
|
|
235
360
|
const active = Object.values(sb()).filter((s) => s.state !== "exited").length;
|
|
236
|
-
|
|
361
|
+
const e = effectiveCapacity();
|
|
362
|
+
const h = live(cfg);
|
|
363
|
+
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 }])) } : {}), 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), net: readNet(), paused: Boolean(cfg.paused || ownerPaused || policyPaused), owner_paused: ownerPaused, live: h, usage: Object.fromEntries(Object.values(sb()).filter((r) => r.usage?.samples).map((r) => [r.issue ?? r.id, { ...usageView(r), state: r.state }])) };
|
|
237
364
|
}
|
|
238
365
|
|
|
239
366
|
/** The image a spec's lanes run (the per-repo lane_tools tag when tools are listed), without building it. */
|
|
@@ -253,10 +380,20 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
253
380
|
/** cgroup cpu weight per class (docker --cpu-shares); a borrowed lane yields to a reserved one under contention. */
|
|
254
381
|
const sharesArgs = (prio) => (weighted() ? ["--cpu-shares", String(SHARES()[prio])] : []);
|
|
255
382
|
|
|
383
|
+
/** The per-repo cache volume (`/cache`: worktrees, bare mirror, stores). An explicit agent_id gives this agent its own volume. */
|
|
384
|
+
const cacheVolumeOf = (key) => `cs-cache-${cfg.agent_id ? `${agentId}-` : ""}${String(key ?? "default").toLowerCase().replace(/[^a-z0-9_.-]/g, "-")}`;
|
|
385
|
+
/** #5949: dispatcher-seeded mirrors (GET /mirrors, POST /mirrors/seed); git runs in a helper container on the cache volume. */
|
|
386
|
+
const mirrors = makeMirrorSeed({ seedDir: join(stateDir, "seed"), runnerFor: ({ slug, cache_key }) => {
|
|
387
|
+
const volume = cacheVolumeOf(cache_key ?? slug), run = (mirrorRunner ?? dockerRunner)({ volume, image, seedDir: join(stateDir, "seed") });
|
|
388
|
+
return async (script, env) => { try { await docker.createVolume?.(volume, [CACHE_LABEL, AGENT]); } catch { /* an unlabelled volume still works */ } cacheUsed.set(volume, now()); return run(script, env); };
|
|
389
|
+
} });
|
|
390
|
+
const seedFail = (e) => { if (e.status) throw Object.assign(new Error(e.message), { status: e.status, body: { error: e.message, ...(e.extra ?? {}) } }); throw e; };
|
|
391
|
+
|
|
256
392
|
async function launch({ spec, cpus, mem_gb, limit = null }) {
|
|
257
393
|
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 });
|
|
258
394
|
let existing = own(spec.id);
|
|
259
395
|
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
|
|
396
|
+
if (existing?.diskPressure && existing.state === "exited") { await destroy(existing.id, "disk pressure: resume", { keepWork: true }); existing = null; } // #5891: the worktree stays, the lane adopts it
|
|
260
397
|
if (existing) { existing.lease = now(); store.save(); return { status: 200, body: view(existing) }; }
|
|
261
398
|
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
|
|
262
399
|
const prio = spec.priority ?? "normal";
|
|
@@ -272,14 +409,19 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
272
409
|
}
|
|
273
410
|
// Burst model: reservations are small, so also refuse when the VM is genuinely short of memory or overloaded right now.
|
|
274
411
|
// A reserved launch skips the load gate: it must never be refused because lanes are busy (they are throttled/drained below).
|
|
412
|
+
if (prio !== "reserved") { // #5858: ramp-aware: the admitted lanes' projected peaks plus this one must fit, however low the load is right now
|
|
413
|
+
const e = effectiveCapacity(), pu = projectedUse(), est = estimateFor(slugOf(spec), { cpus, mem: mem_gb }), nm = Math.max(mem_gb, est.mem), nc = Math.max(cpus, est.cpus);
|
|
414
|
+
const availMem = e.mem - coTenant.mem_gb, availCpus = e.cpus - coTenant.cpus;
|
|
415
|
+
if (pu.mem + nm > availMem + 1e-9 || pu.cpus + nc > availCpus + 1e-9) return { status: 503, body: { error: `projected peak ${r1(pu.mem + nm)} GB / ${r1(pu.cpus + nc)} cpus exceeds capacity ${r1(availMem)} GB / ${r1(availCpus)} cpus`, code: "pool.projected_peak", capacity: c }, retryAfter: 60 };
|
|
416
|
+
}
|
|
275
417
|
if (!h.ok && prio !== "reserved") return { status: 503, body: { error: `host busy: ${h.reason}`, live: h }, retryAfter: 60 };
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
418
|
+
const gate = hostDiskView(c.active, spec.repo?.slug ?? null);
|
|
419
|
+
if (gate.host_disk_low) { // #5733: before any mkdir or docker run; the lane defers on the 503 (SANDBOX_CAPACITY)
|
|
420
|
+
const floor = floorGb();
|
|
421
|
+
return { status: 503, body: { error: `host disk low: ${gate.host_disk_free_gb} GB free, floor ${floor} GB with ${c.active} running`, code: "pool.disk_low", host_disk_free_gb: gate.host_disk_free_gb, floor_gb: floor }, retryAfter: cfg.disk_low_retry_after_s ?? 300 };
|
|
279
422
|
}
|
|
280
|
-
if (c.
|
|
281
|
-
|
|
282
|
-
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 };
|
|
423
|
+
if (c.disk_capped) { // #5884: lane disk is at the hard cap; pressure prune runs in reap(), the lane defers like pool.disk_low
|
|
424
|
+
return { status: 503, body: { error: `lane disk full: ${c.lane_disk_used_gb} GB of ${c.lane_disk_cap_gb} GB cap`, code: "pool.disk_cap", lane_disk_used_gb: c.lane_disk_used_gb, cap_gb: c.lane_disk_cap_gb }, retryAfter: cfg.disk_low_retry_after_s ?? 300 };
|
|
283
425
|
}
|
|
284
426
|
if (spec.lane_tools?.length) { // #5650 follow-up: never build inside the launch request (router timeout); 503 + retry while it builds
|
|
285
427
|
let st;
|
|
@@ -287,6 +429,11 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
287
429
|
if (st.building) return { status: 503, body: { error: `lane image ${st.tag} building`, code: "lane_tools.building" }, retryAfter: LANE_BUILD_RETRY_AFTER_S };
|
|
288
430
|
if (st.failed) return { status: 422, body: { error: st.failed, code: "lane_tools.build_failed" } };
|
|
289
431
|
}
|
|
432
|
+
// Last refusal point passed: only now stop borrowed lanes (#5897), a launch refused above must not have drained any.
|
|
433
|
+
if (prio === "reserved") {
|
|
434
|
+
for (const r of tiers().act.filter((s) => prioOf(s) === "borrow")) await throttle(r, SHARES().throttled); // throttle every borrower first,
|
|
435
|
+
for (const v of adm.victims) await drainOne(v, `reserved ${reservation} arrived`); // then stop only as many as the reservation needs
|
|
436
|
+
}
|
|
290
437
|
const name = safeName(spec.id);
|
|
291
438
|
const dir = join(stateDir, "sandboxes", name);
|
|
292
439
|
mkdirSync(join(dir, "result"), { recursive: true });
|
|
@@ -298,11 +445,10 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
298
445
|
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),
|
|
299
446
|
...(spec.env_snapshots?.enabled ? { FORGE_ENV_IMAGE: envImageOf(spec) } : {}) }; // the image is part of the snapshot key
|
|
300
447
|
writeFileSync(envFile, Object.entries(env).map(([k, v]) => envLine(k, v)).join("\n") + "\n", { mode: 0o600 });
|
|
301
|
-
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 } : {}) } : {}) };
|
|
448
|
+
const rec = { id: spec.id, name, dir, issue: spec.issue ?? null, slug: spec.repo?.slug ?? null, repo: slugOf(spec), 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 } : {}) } : {}) };
|
|
302
449
|
sb()[spec.id] = rec;
|
|
303
450
|
store.save();
|
|
304
|
-
|
|
305
|
-
rec.cacheVolume = `cs-cache-${cfg.agent_id ? `${agentId}-` : ""}${cacheKey}`; // an explicit agent_id gives this agent its own volume: a shared one would let its work sweep delete a co-resident agent's worktrees
|
|
451
|
+
rec.cacheVolume = cacheVolumeOf(spec.cache?.key ?? spec.repo?.slug); // an explicit agent_id gives this agent its own volume: a shared one would let its work sweep delete a co-resident agent's worktrees
|
|
306
452
|
rec.workDir = workDirOf(name);
|
|
307
453
|
cacheUsed.set(rec.cacheVolume, now());
|
|
308
454
|
try { await docker.createVolume?.(rec.cacheVolume, [CACHE_LABEL, AGENT]); } catch (e) { log.warn?.(`label ${rec.cacheVolume}: ${String(e.stderr || e.message).slice(0, 200)}`); } // an unlabelled volume still works
|
|
@@ -360,7 +506,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
360
506
|
return { status: 201, body: view(rec) };
|
|
361
507
|
}
|
|
362
508
|
|
|
363
|
-
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 } : {}) });
|
|
509
|
+
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.diskPressure ? { code: "sandbox.disk_pressure", status_detail: "stopped (disk pressure): worktree kept for resume" } : {}) });
|
|
364
510
|
|
|
365
511
|
const warm = makeWarm({ store, sb, own, now, launch, destroy: (id, why) => destroy(id, why), view, log });
|
|
366
512
|
|
|
@@ -369,7 +515,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
369
515
|
const s = await docker.inspect(r.name);
|
|
370
516
|
if (!s) { r.state = "exited"; r.finishedAt ??= now(); }
|
|
371
517
|
else if (!s.running && r.state !== "starting") { r.state = "exited"; r.exitCode = s.exitCode; r.finishedAt = Date.parse(s.finishedAt) || now(); }
|
|
372
|
-
else if (s.running) r.state = "running";
|
|
518
|
+
else if (s.running) r.state = r.diskPaused ? "paused" : "running";
|
|
373
519
|
return r;
|
|
374
520
|
}
|
|
375
521
|
|
|
@@ -391,20 +537,22 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
391
537
|
try { return JSON.parse(readFileSync(join(r.dir, "result", basename(r.result_file)), "utf8")); } catch { return null; }
|
|
392
538
|
}
|
|
393
539
|
|
|
394
|
-
async function destroy(id, why) {
|
|
540
|
+
async function destroy(id, why, { keepWork = false } = {}) {
|
|
395
541
|
const r = own(id);
|
|
396
542
|
if (!r) return false;
|
|
397
|
-
|
|
543
|
+
if (r.slug && r.diskPeakMb) { const h = (hist()[r.slug] ??= []); h.push(r.diskPeakMb); if (h.length > 50) h.shift(); }
|
|
544
|
+
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;
|
|
398
545
|
await docker.remove(r.name);
|
|
399
546
|
if (r.docker) await docker.remove(dindName(r.name));
|
|
400
|
-
if (r.workDir) {
|
|
547
|
+
if (r.workDir && keepWork) { /* #5891: a disk-pressure stop keeps the worktree and cache volume for the resumed lane */ }
|
|
548
|
+
else if (r.workDir) { try { await docker.removeWorkDir(r.cacheVolume, image, r.workDir); } catch (e) { sweepFail(r.cacheVolume, "work dir", e); } }
|
|
401
549
|
else if (r.docker) await docker.removeVolume(workVolume(r.name)); // sandbox launched before #5696
|
|
402
550
|
try { await docker.wipe(r.dir, image); } catch (e) { log.warn?.(`wipe ${r.name}: ${String(e.stderr || e.message).slice(0, 200)}`); }
|
|
403
551
|
rmSync(r.dir, { recursive: true, force: true });
|
|
404
552
|
delete sb()[r.id];
|
|
405
553
|
store.save();
|
|
406
554
|
// Written once, after the sandbox is really gone (a teardown that throws and is retried must not log it twice).
|
|
407
|
-
if (history) { try { appendFileSync(join(stateDir, "usage-history.jsonl"), history + "\n"); } catch { /* best effort */ } }
|
|
555
|
+
if (history) { try { appendFileSync(join(stateDir, "usage-history.jsonl"), history + "\n"); } catch { /* best effort */ } if (histRows) histRows.push(JSON.parse(history)); }
|
|
408
556
|
log.info?.(`destroyed ${id} (${why})`);
|
|
409
557
|
return true;
|
|
410
558
|
}
|
|
@@ -488,13 +636,89 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
488
636
|
if (!act.some((r) => prioOf(r) === "reserved")) for (const r of borrowed.filter((x) => x.throttled)) await throttle(r, SHARES().borrow);
|
|
489
637
|
}
|
|
490
638
|
|
|
639
|
+
|
|
640
|
+
// #5891: runtime disk control, once per reap. Below the floor: prune rebuildables, then pause the fastest grower (lease kept),
|
|
641
|
+
// then below floor/2 stop it with sandbox.disk_pressure (worktree + volume kept). Above floor + margin: unpause.
|
|
642
|
+
const freshHostDisk = () => { if (!hostDisk) hostDiskCache.at = -Infinity; try { const hd = readHostDisk(); return hd && Number.isFinite(hd.gb) ? hd.gb : null; } catch { return null; } };
|
|
643
|
+
const cntNames = (r) => (r.docker ? [r.name, dindName(r.name)] : [r.name]);
|
|
644
|
+
/** Removes the exited container(s) of sandboxes dead for ttlMs (their data stays for a resume), and orphan fdrsbx-* volumes. Never cs-cache-*. */
|
|
645
|
+
async function reapDead(t, ttlMs) {
|
|
646
|
+
for (const r of Object.values(sb())) {
|
|
647
|
+
if (r.state !== "exited" || r.containerReaped || !r.finishedAt || t - r.finishedAt < ttlMs) continue;
|
|
648
|
+
try { for (const n of cntNames(r)) await docker.remove(n); r.containerReaped = true; log.info?.(`removed dead sandbox container ${r.name}`); } catch (e) { log.warn?.(`reap ${r.name}: ${String(e.stderr || e.message).slice(0, 200)}`); }
|
|
649
|
+
}
|
|
650
|
+
const names = Object.values(sb()).flatMap((r) => [r.id, r.name]); // a volume named after a known sandbox stays for its resume
|
|
651
|
+
try {
|
|
652
|
+
for (const v of (await docker.listVolumes?.("fdrsbx-")) ?? []) {
|
|
653
|
+
if (!v.startsWith("fdrsbx-") || v.startsWith("cs-cache-") || names.some((n) => v === n || v.startsWith(`${n}-`) || v.startsWith(`${n}_`))) continue;
|
|
654
|
+
try { await docker.removeVolume(v); log.info?.(`removed dead sandbox volume ${v}`); } catch (e) { log.warn?.(`rm volume ${v}: ${String(e.stderr || e.message).slice(0, 200)}`); }
|
|
655
|
+
}
|
|
656
|
+
} catch (e) { log.warn?.(`dead volume sweep: ${String(e.stderr || e.message).slice(0, 200)}`); }
|
|
657
|
+
}
|
|
658
|
+
async function reclaimDisk(t) {
|
|
659
|
+
try { await docker.builderPrune?.(0); } catch (e) { log.warn?.(`builder prune: ${String(e.stderr || e.message).slice(0, 200)}`); }
|
|
660
|
+
try { await docker.pruneImages?.(); } catch (e) { log.warn?.(`image prune: ${String(e.stderr || e.message).slice(0, 200)}`); }
|
|
661
|
+
const heavy = activeRecs().sort((a, b) => (diskCache.mb[b.id] ?? 0) - (diskCache.mb[a.id] ?? 0)).slice(0, cfg.disk_reclaim_sandboxes ?? 3);
|
|
662
|
+
for (const r of heavy) { try { await docker.pruneCaches?.(r.name); } catch { /* best effort: package-manager caches only */ } }
|
|
663
|
+
await reapDead(t, 0);
|
|
664
|
+
}
|
|
665
|
+
async function hostDiskPressure(t) {
|
|
666
|
+
let free = freshHostDisk();
|
|
667
|
+
if (free === null) { await reapDead(t, (cfg.dead_ttl_s ?? 600) * 1000); return; }
|
|
668
|
+
noteHostDisk(free);
|
|
669
|
+
const floor = floorGb(), hard = floor / 2;
|
|
670
|
+
if (free >= floor) {
|
|
671
|
+
await reapDead(t, (cfg.dead_ttl_s ?? 600) * 1000);
|
|
672
|
+
if (free >= floor + (cfg.disk_resume_margin_gb ?? 2)) for (const r of activeRecs().filter((x) => x.diskPaused)) {
|
|
673
|
+
try { for (const n of cntNames(r)) await docker.unpause?.(n); r.diskPaused = false; r.state = "running"; log.info?.(`resumed ${r.id}: host disk ${free} GB`); } catch (e) { log.warn?.(`unpause ${r.id}: ${String(e.stderr || e.message).slice(0, 200)}`); }
|
|
674
|
+
}
|
|
675
|
+
for (const r of activeRecs().filter((x) => x.diskPaused)) r.lease = t;
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
await reclaimDisk(t);
|
|
679
|
+
free = freshHostDisk() ?? free;
|
|
680
|
+
if (free >= floor) return; // pruning was enough: nothing paused or stopped
|
|
681
|
+
let victim = activeRecs().find((r) => r.diskPaused);
|
|
682
|
+
if (!victim) {
|
|
683
|
+
victim = activeRecs().filter((r) => r.state === "running").sort((a, b) => (b.growthMbH ?? 0) - (a.growthMbH ?? 0) || (diskCache.mb[b.id] ?? 0) - (diskCache.mb[a.id] ?? 0))[0];
|
|
684
|
+
if (victim) { try { for (const n of cntNames(victim)) await docker.pause?.(n); victim.diskPaused = true; victim.state = "paused"; log.warn?.(`paused ${victim.id} (disk): host free ${free} GB < floor ${floor} GB`); } catch (e) { log.warn?.(`pause ${victim.id}: ${String(e.stderr || e.message).slice(0, 200)}`); victim = null; } }
|
|
685
|
+
}
|
|
686
|
+
for (const r of activeRecs().filter((x) => x.diskPaused)) r.lease = t; // the paused lane stays leased: it is not lost
|
|
687
|
+
if (victim && free < hard) { // the guest is about to fill: stop it to save every other sandbox; worktree and volume stay
|
|
688
|
+
for (const n of cntNames(victim)) { try { await docker.unpause?.(n); } catch { /* not paused */ } }
|
|
689
|
+
for (const n of cntNames(victim)) { try { await docker.kill(n, "KILL"); } catch { /* gone */ } }
|
|
690
|
+
victim.diskPaused = false; victim.state = "exited"; victim.finishedAt = t; victim.diskPressure = true;
|
|
691
|
+
log.error?.(`stopped ${victim.id} (sandbox.disk_pressure): host free ${free} GB < ${hard} GB`);
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
/** #5884: at the prune threshold of lane_disk_cap_gb prune this agent's own leftovers and sweep caches; fstrim on an interval and after a prune. Log lines only. */
|
|
695
|
+
let lastFstrim = -Infinity;
|
|
696
|
+
async function diskPressure(t) {
|
|
697
|
+
const v = laneDiskView();
|
|
698
|
+
const state = "lane_disk_cap_gb" in v ? planDiskCap({ usedGb: v.lane_disk_used_gb, capGb: v.lane_disk_cap_gb, pruneAtPct: cfg.disk_prune_at_pct }) : "ok";
|
|
699
|
+
if (state !== "ok") {
|
|
700
|
+
log.warn?.(`lane disk ${v.lane_disk_used_gb}/${v.lane_disk_cap_gb} GB (${state}): pruning`);
|
|
701
|
+
for (const [what, fn] of [["container prune", docker.containerPrune], ["image prune", docker.imagePrune]]) {
|
|
702
|
+
try { await fn?.call(docker, OWN); } catch (e) { log.warn?.(`${what}: ${String(e.stderr || e.message).slice(0, 200)}`); }
|
|
703
|
+
}
|
|
704
|
+
try { await docker.builderPrune?.(cfg.build_cache_keep_gb ?? 20); } catch (e) { log.warn?.(`builder prune: ${String(e.stderr || e.message).slice(0, 200)}`); }
|
|
705
|
+
lastCacheSweep = t;
|
|
706
|
+
await cacheSweep(t);
|
|
707
|
+
}
|
|
708
|
+
if (cfg.fstrim === false || !fstrimDue({ now: t, last: lastFstrim, intervalS: cfg.fstrim_interval_s, force: state !== "ok" })) return;
|
|
709
|
+
lastFstrim = t;
|
|
710
|
+
const r = await trim({ root: cfg.docker_root });
|
|
711
|
+
if (!r.ok) log.warn?.(`fstrim: ${r.error}`);
|
|
712
|
+
}
|
|
713
|
+
|
|
491
714
|
async function reap() {
|
|
492
715
|
const t = now();
|
|
493
716
|
for (const r of Object.values(sb())) {
|
|
494
717
|
try { await refresh(r); } catch { /* docker hiccup: judge by lease only */ }
|
|
495
|
-
const why = t - r.lease > leaseTtlMs ? "lease expired" : t - r.startedAt > maxLifeMs ? "max lifetime" : r.state === "exited" && r.finishedAt && t - r.finishedAt > keepExitedMs ? "exited retention" : null;
|
|
718
|
+
const why = t - r.lease > leaseTtlMs && !r.diskPaused ? "lease expired" : t - r.startedAt > maxLifeMs ? "max lifetime" : r.state === "exited" && r.finishedAt && t - r.finishedAt > (r.diskPressure ? keepPressureMs : keepExitedMs) ? "exited retention" : null;
|
|
496
719
|
if (why) await destroy(r.id, why);
|
|
497
720
|
}
|
|
721
|
+
await hostDiskPressure(t); // #5891
|
|
498
722
|
const known = new Set(Object.values(sb()).flatMap((r) => [r.name, dindName(r.name)]));
|
|
499
723
|
for (const name of await docker.listLabelled(OWN)) if (!known.has(name)) { await docker.remove(name); log.info?.(`removed orphan container ${name}`); }
|
|
500
724
|
await sampleUsage();
|
|
@@ -514,6 +738,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
514
738
|
}
|
|
515
739
|
}
|
|
516
740
|
await sweepBuildCache(t);
|
|
741
|
+
try { await diskPressure(t); } catch (e) { log.warn?.(`disk pressure: ${String(e.message).slice(0, 200)}`); }
|
|
517
742
|
if (t - lastCacheSweep >= (cfg.cache_sweep_interval_s ?? 3600) * 1000) {
|
|
518
743
|
lastCacheSweep = t;
|
|
519
744
|
await cacheSweep(t);
|
|
@@ -581,7 +806,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
581
806
|
if (want.image !== running.image || want.version !== running.version) {
|
|
582
807
|
const nextImage = cfg.image && cfg.image !== "computeshare-lane:1" ? cfg.image : laneImageTag(want.version);
|
|
583
808
|
log.info?.(`rebuilding ${nextImage} (${running.version}/${running.image} -> ${want.version}/${want.image})`);
|
|
584
|
-
await docker.build(join(next, "pool", "image"), nextImage, laneBuildArgs(want.version));
|
|
809
|
+
await buildWithRetry(() => docker.build(join(next, "pool", "image"), nextImage, laneBuildArgs(want.version)), { log }); // #5919
|
|
585
810
|
}
|
|
586
811
|
await pruneLaneImages([laneImageTag(want.version)]);
|
|
587
812
|
await prepullImages();
|
|
@@ -592,7 +817,8 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
592
817
|
upgrade.state = "restarting";
|
|
593
818
|
setTimeout(() => process.exit(0), 500);
|
|
594
819
|
} catch (e) {
|
|
595
|
-
upgrade.state = "failed"; upgrade.error =
|
|
820
|
+
upgrade.state = "failed"; upgrade.error = upgradeErrorText(e); // #5919: the tail, where the failing command's output is
|
|
821
|
+
try { writeFileSync(join(stateDir, "upgrade.log"), `${new Date(now()).toISOString()}\n${upgradeErrorText(e, 200000)}\n`); upgrade.log = join(stateDir, "upgrade.log"); } catch { /* best effort */ }
|
|
596
822
|
log.error?.(`self-update failed: ${upgrade.error}`);
|
|
597
823
|
}
|
|
598
824
|
}
|
|
@@ -606,6 +832,14 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
606
832
|
let st;
|
|
607
833
|
try { st = await docker.stats?.(OWN); } catch { return; }
|
|
608
834
|
if (!st) return;
|
|
835
|
+
try { // #5858: containers that are not this agent's sandboxes (all containers minus the labelled ones and known sandboxes)
|
|
836
|
+
const all = await docker.stats?.([]);
|
|
837
|
+
if (all) {
|
|
838
|
+
const mine = new Set([...Object.keys(st), ...Object.values(sb()).flatMap((r) => [r.name, dindName(r.name)])]);
|
|
839
|
+
const others = Object.entries(all).filter(([n]) => !mine.has(n)).map(([, x]) => x);
|
|
840
|
+
coTenant = { cpus: others.reduce((a, x) => a + (x.cpu || 0), 0), mem_gb: others.reduce((a, x) => a + (x.mem_gb || 0), 0) };
|
|
841
|
+
}
|
|
842
|
+
} catch { /* keep the last reading */ }
|
|
609
843
|
for (const r of Object.values(sb())) {
|
|
610
844
|
if (r.state === "exited") continue;
|
|
611
845
|
const parts = [st[r.name], r.docker ? st[dindName(r.name)] : null].filter(Boolean);
|
|
@@ -676,6 +910,8 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
676
910
|
|
|
677
911
|
const routes = [
|
|
678
912
|
[route("GET", "/health"), async () => ({ status: 200, body: { ok: true, ...capacity() } })],
|
|
913
|
+
[route("GET", "/mirrors"), async (_p, _b, url) => ({ status: 200, body: await mirrors.tips({ slug: url.searchParams.get("slug"), cache_key: url.searchParams.get("cache_key"), upload: url.searchParams.get("upload") }).catch(seedFail) })], // #5949
|
|
914
|
+
[route("POST", "/mirrors/seed"), async (_p, body) => { try { return { status: 200, body: body?.finish ? await mirrors.finish(body) : mirrors.chunk(body) }; } catch (e) { return { status: e.status ?? 500, body: { error: e.message, ...(e.extra ?? {}) } }; } }],
|
|
679
915
|
[route("GET", "/capacity"), async () => ({ status: 200, body: capacity() })],
|
|
680
916
|
[route("POST", "/sandboxes"), async (_p, body) => { const r = await launch(body ?? {}); if (Number.isInteger(body?.spec?.warm)) warm.replenish().catch((e) => log.warn?.(`warm replenish: ${e.message}`)); return r; }],
|
|
681
917
|
[route("GET", "/warm"), async () => ({ status: 200, body: { warm: warm.list() } })],
|
|
@@ -683,7 +919,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
683
919
|
[route("POST", "/warm/claim"), async (_p, body) => warm.claim(body ?? {})],
|
|
684
920
|
[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) }; }],
|
|
685
921
|
[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 } }; }],
|
|
686
|
-
[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
|
|
922
|
+
[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 } }; 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
|
|
687
923
|
[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: {} }; }],
|
|
688
924
|
[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 } }; }],
|
|
689
925
|
// #5274: SIGTERM the lane (PID 1) so its teardown checkpoints and reports deferred run.interrupted; the sandbox is kept, never destroyed.
|
|
@@ -701,6 +937,9 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
701
937
|
return { status: 200, body: { rows: rows.slice(-500) } };
|
|
702
938
|
}],
|
|
703
939
|
[route("POST", "/admin/resize"), async (_p, body) => resize(body ?? {})],
|
|
940
|
+
[route("POST", "/admin/policy"), async (_p, body) => applyPolicy(body)], // #5886
|
|
941
|
+
[route("POST", "/pause"), async () => setOwnerPause(true)], // #5885: box-local `forgedock pool pause`; running lanes finish
|
|
942
|
+
[route("POST", "/resume"), async () => setOwnerPause(false)],
|
|
704
943
|
[route("POST", "/admin/update"), async () => { selfUpdate(); return { status: 202, body: { ok: true, from: running } }; }],
|
|
705
944
|
[route("DELETE", "/sandboxes/:id"), async ({ id }) => ((await destroy(id, "requested")) ? { status: 200, body: { ok: true } } : { status: 404, body: { state: "gone" } })],
|
|
706
945
|
];
|
|
@@ -744,10 +983,11 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
744
983
|
* WSL with mirrored networking often has no IPv6 default route, yet dockerd still dials registries over IPv6 and fails
|
|
745
984
|
* ("network is unreachable"). Turn IPv6 off inside the distro (persistently) and restart docker while it is idle.
|
|
746
985
|
*/
|
|
747
|
-
export async function wslNetworkFixup({ run: runCmd = run, log = console, idle = () => true } = {}) {
|
|
986
|
+
export async function wslNetworkFixup({ run: runCmd = run, log = console, idle = () => true, pin = ensureNatPin } = {}) {
|
|
748
987
|
let release = "";
|
|
749
988
|
try { release = readFileSync("/proc/sys/kernel/osrelease", "utf8"); } catch { return "not linux"; }
|
|
750
989
|
if (!/microsoft/i.test(release)) return "not wsl";
|
|
990
|
+
try { const p = pin(); if (p?.applied) log.info?.(`WSL mirrored: pinned docker NAT source ports to ${p.range} (${p.applied} rules)`); } catch (e) { log.warn?.(`NAT port pin failed: ${e.message}`); }
|
|
751
991
|
try {
|
|
752
992
|
const { stdout } = await runCmd("ip", ["-6", "route", "show", "default"]);
|
|
753
993
|
if (String(stdout).trim()) return "ipv6 route present";
|
|
@@ -761,6 +1001,40 @@ export async function wslNetworkFixup({ run: runCmd = run, log = console, idle =
|
|
|
761
1001
|
return "applied";
|
|
762
1002
|
}
|
|
763
1003
|
|
|
1004
|
+
/**
|
|
1005
|
+
* #5882: outbound-only transport. Long-polls the router (`GET /agent/poll`, which doubles as the heartbeat), runs each queued
|
|
1006
|
+
* request against this agent's own bearer-checked HTTP API and posts the answer to `/agent/reply/:rid`. The router never dials in.
|
|
1007
|
+
* `dispatch` defaults to a loopback call on cfg.listen; tests inject their own.
|
|
1008
|
+
*/
|
|
1009
|
+
export function startPoll(cfg, { log = console, fetchFn = globalThis.fetch, waitS = 25, dispatch = null, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}) {
|
|
1010
|
+
let stopped = false, backoff = 1000;
|
|
1011
|
+
const host = !cfg.listen?.host || cfg.listen.host === "0.0.0.0" ? "127.0.0.1" : cfg.listen.host;
|
|
1012
|
+
const local = dispatch ?? ((m, path, body) => call(`http://${host}:${cfg.listen.port}`, m, path, { body, token: cfg.token, timeoutMs: 180000 }));
|
|
1013
|
+
const reply = (rid, r) => call(cfg.router_url, "POST", `/agent/reply/${encodeURIComponent(rid)}`, { body: { status: r.status, data: r.data, retry_after: r.retryAfter ?? null }, token: cfg.token, timeoutMs: 30000, fetchFn });
|
|
1014
|
+
async function serve({ rid, method, path, body }) {
|
|
1015
|
+
let r;
|
|
1016
|
+
if (typeof path !== "string" || !/^\/(?!\/)/.test(path) || !["GET", "POST", "DELETE"].includes(method)) r = { status: 400, data: { error: "bad request" } };
|
|
1017
|
+
else r = await local(method, path, body).catch((e) => ({ status: 502, data: { error: `agent local dispatch failed: ${e.message}` } }));
|
|
1018
|
+
await reply(rid, r).catch((e) => log.warn?.(`poll reply ${rid}: ${e.message}`));
|
|
1019
|
+
}
|
|
1020
|
+
const done = (async () => {
|
|
1021
|
+
while (!stopped) {
|
|
1022
|
+
try {
|
|
1023
|
+
const r = await call(cfg.router_url, "GET", `/agent/poll?wait=${waitS}`, { token: cfg.token, timeoutMs: (waitS + 15) * 1000, fetchFn });
|
|
1024
|
+
if (r.status !== 204 && (!r.ok || !r.data?.rid)) throw new Error(`poll HTTP ${r.status}`);
|
|
1025
|
+
backoff = 1000;
|
|
1026
|
+
if (r.status !== 204) serve(r.data).catch((e) => log.warn?.(`poll serve: ${e.message}`));
|
|
1027
|
+
} catch (e) {
|
|
1028
|
+
if (stopped) break;
|
|
1029
|
+
log.warn?.(`router poll failed: ${e.message}; retry in ${backoff}ms`);
|
|
1030
|
+
await sleep(backoff);
|
|
1031
|
+
backoff = Math.min(backoff * 2, 30000);
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
})();
|
|
1035
|
+
return { stop: () => { stopped = true; }, done };
|
|
1036
|
+
}
|
|
1037
|
+
|
|
764
1038
|
export function startAgent(cfg, deps) {
|
|
765
1039
|
const agent = createAgent(cfg, deps);
|
|
766
1040
|
const server = createServer(agent.handle);
|
|
@@ -771,5 +1045,7 @@ export function startAgent(cfg, deps) {
|
|
|
771
1045
|
wslNetworkFixup({ idle: () => agent.capacity().active === 0 })
|
|
772
1046
|
.catch((e) => console.error("wsl network fixup failed", e))
|
|
773
1047
|
.finally(() => agent.prepullImages());
|
|
774
|
-
|
|
1048
|
+
// #5882: outbound mode keeps the local listener for the lanes' credential calls (bind it to the docker bridge, not a public interface).
|
|
1049
|
+
const poll = cfg.outbound ? startPoll(cfg, { log: deps?.log }) : null;
|
|
1050
|
+
return { agent, server, close: () => { clearInterval(timer); poll?.stop(); server.close(); } };
|
|
775
1051
|
}
|