forgedock 1.71.0 → 1.72.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/config-schema.mjs +1 -1
- package/bin/engine/outcome-codes.mjs +5 -4
- package/bin/init-detect.mjs +35 -2
- package/bin/lean/admit.mjs +152 -0
- package/bin/lean/admit.test.mjs +120 -0
- package/bin/lean/attempts.mjs +1 -1
- package/bin/lean/batch.mjs +8 -0
- package/bin/lean/batch.test.mjs +17 -0
- package/bin/lean/concurrency.mjs +7 -2
- package/bin/lean/concurrency.test.mjs +16 -3
- package/bin/lean/conformance.mjs +2 -0
- package/bin/lean/conformance.test.mjs +9 -0
- package/bin/lean/effects.mjs +22 -0
- package/bin/lean/failure-census.mjs +1 -1
- package/bin/lean/heavy.mjs +20 -6
- package/bin/lean/heavy.test.mjs +24 -3
- package/bin/lean/lean.mjs +97 -5
- package/bin/lean/lean.test.mjs +38 -0
- package/bin/lean/orchestrate-envhold.test.mjs +14 -0
- package/bin/lean/orchestrate-heldroot.test.mjs +32 -0
- package/bin/lean/orchestrate.mjs +33 -11
- package/bin/lean/queuecause.mjs +42 -0
- package/bin/lean/release-cigreen.mjs +18 -4
- package/bin/lean/release-cigreen.test.mjs +23 -0
- package/bin/lean/release-review.mjs +24 -10
- package/bin/lean/release-review.test.mjs +65 -0
- package/bin/lean/release.mjs +1 -1
- package/bin/lean/release.test.mjs +19 -0
- package/bin/lean/schedd.mjs +24 -1
- package/bin/lean/schedd.test.mjs +38 -0
- package/bin/pool/agent.mjs +61 -18
- package/bin/pool/docker-dns.mjs +39 -0
- package/bin/pool/docker.mjs +7 -3
- package/bin/pool/engine-placement.test.mjs +2 -2
- package/bin/pool/image-manifest.test.mjs +13 -0
- package/bin/pool/lane-image.mjs +56 -15
- package/bin/pool/lane-tools.mjs +26 -12
- package/bin/pool/lane-tools.test.mjs +63 -1
- package/bin/pool/project-layer.mjs +2 -2
- package/bin/pool/router.mjs +2 -1
- package/bin/review-staging.mjs +14 -11
- package/bin/review-staging.test.mjs +20 -1
- package/bin/stats/escapes.mjs +124 -0
- package/bin/stats/index.mjs +5 -1
- package/bin/stats/quality-ledger.mjs +49 -0
- package/bin/stats/quality-ledger.test.mjs +84 -0
- package/bin/stats/weekly.mjs +230 -0
- package/docs/OUTCOME-CODES.md +2 -1
- package/package.json +1 -1
- package/pool/README.md +2 -0
- package/pool/image/Dockerfile +4 -1
- package/pool/image/lane-tools-sets.json +6 -0
- package/scripts/lane-variants.mjs +51 -0
package/bin/pool/agent.mjs
CHANGED
|
@@ -10,8 +10,9 @@ import { appendFileSync, closeSync, constants as fsConstants, existsSync, fstatS
|
|
|
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";
|
|
13
|
-
import { repoRoot, versionOf, laneImageTag, laneBuildArgs } from "./version.mjs";
|
|
14
|
-
import { provideLaneImage } from "./lane-image.mjs";
|
|
13
|
+
import { repoRoot, versionOf, laneImageTag, laneBuildArgs, cmpVersion } from "./version.mjs";
|
|
14
|
+
import { provideLaneImage, pullVariantImage, withIpv4Fallback, fetchLaneDigest } from "./lane-image.mjs";
|
|
15
|
+
import { ensureDaemonDns } from "./docker-dns.mjs";
|
|
15
16
|
import { jsonStore } from "./store.mjs";
|
|
16
17
|
import { makeWarm } from "./warm.mjs";
|
|
17
18
|
import { resolveLaneImage, laneImageNow, laneToolsTag, isLaneToolsTagOf } from "./lane-tools.mjs";
|
|
@@ -149,7 +150,7 @@ export function readLaneFile(path) {
|
|
|
149
150
|
if (fd === null) return "";
|
|
150
151
|
try { return readFileSync(fd, "utf8"); } catch { return ""; } finally { try { closeSync(fd); } catch { /* closed */ } }
|
|
151
152
|
}
|
|
152
|
-
export function createAgent(cfg, { docker, now = () => Date.now(), log = console, live = liveHeadroom, hostDisk = null, hostMem = null, net = netState, vm = vmSize, trim = runFstrim, mirrorRunner = null } = {}) {
|
|
153
|
+
export function createAgent(cfg, { docker, now = () => Date.now(), log = console, live = liveHeadroom, hostDisk = null, hostMem = null, net = netState, vm = vmSize, trim = runFstrim, mirrorRunner = null, fetchDigest = fetchLaneDigest } = {}) {
|
|
153
154
|
const stateDir = cfg.state_dir;
|
|
154
155
|
const store = jsonStore(join(stateDir, "state.json"), { sandboxes: {} });
|
|
155
156
|
const sb = () => store.data.sandboxes;
|
|
@@ -172,6 +173,10 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
172
173
|
const running = versionOf(cfg.code_root ?? repoRoot);
|
|
173
174
|
// The lane image tracks the installed ForgeDock version; only an explicit non-legacy cfg.image overrides it.
|
|
174
175
|
const image = cfg.image && cfg.image !== "computeshare-lane:1" ? cfg.image : laneImageTag(running.version);
|
|
176
|
+
// #6187: lane_tools variants of the published default tag are pulled from ghcr first; every build runs under the IPv4 fallback
|
|
177
|
+
const variantDocker = (base) => (base === laneImageTag(running.version) && docker.pull && docker.tag
|
|
178
|
+
? Object.assign(Object.create(docker), { withFallback: (op) => withIpv4Fallback(op, { log }), pullVariant: (tag) => pullVariantImage({ docker, tag, version: running.version, log }) })
|
|
179
|
+
: Object.assign(Object.create(docker), { withFallback: (op) => withIpv4Fallback(op, { log }) }));
|
|
175
180
|
const upgrade = { state: "idle", error: null };
|
|
176
181
|
const prepull = { error: null };
|
|
177
182
|
const dindImage = cfg.dind_image ?? "docker:27.5.1-dind";
|
|
@@ -179,10 +184,14 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
179
184
|
const agentId = String(cfg.agent_id ?? cfg.name ?? hostname()).toLowerCase().replace(/[^a-z0-9_.-]/g, "-").slice(0, 60);
|
|
180
185
|
const AGENT = agentLabel(agentId);
|
|
181
186
|
const OWN = [LABEL, AGENT];
|
|
187
|
+
// #6195/#6234: a dockerd DNS failure triggers a daemon.json dns repair. Admission is held across the idle check and the restart; the restart runs only with no sandbox and no container at all (co-tenants included) on the daemon. Lane containers use per-container --dns (netArgs).
|
|
188
|
+
let dnsHold = 0;
|
|
189
|
+
const noOtherContainers = async () => { if (typeof docker.listRunning !== "function") return false; try { return (await docker.listRunning()).length === 0; } catch { return false; } };
|
|
190
|
+
const pinOpts = { ensureDns: () => ensureDaemonDns({ hold: () => { dnsHold++; return () => { dnsHold--; }; }, idle: async () => activeRecs().length === 0 && await noOtherContainers() && activeRecs().length === 0, restart: () => run("systemctl", ["restart", "docker"], { timeout: 120000 }), log }) };
|
|
182
191
|
/** Images a sandbox may need are pulled ahead of time, never inside a launch request (which has a short timeout). */
|
|
183
192
|
async function prepullImages() {
|
|
184
193
|
if (await docker.hasImage?.(dindImage)) { prepull.error = null; return; }
|
|
185
|
-
try { await docker.pull(dindImage); prepull.error = null; return; }
|
|
194
|
+
try { await withIpv4Fallback(() => docker.pull(dindImage), { ...pinOpts, log }); prepull.error = null; return; }
|
|
186
195
|
catch (e) { log.warn?.(`pull ${dindImage} failed (${String(e.stderr || e.message).slice(0, 160)}); fetching it from the router`); }
|
|
187
196
|
// Fallback: the router host pulls the image and streams it (some hosts' daemons cannot reach the registry).
|
|
188
197
|
const file = join(stateDir, "image.tar");
|
|
@@ -319,10 +328,10 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
319
328
|
const reservations = () => (Array.isArray(cfg.reservations) ? cfg.reservations.filter((r) => r && typeof r.name === "string" && r.cpus > 0 && r.mem_gb > 0) : []);
|
|
320
329
|
const prioOf = (r) => r.priority ?? "normal";
|
|
321
330
|
const peakUse = () => 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 });
|
|
322
|
-
// #6047: heavy tokens (cfg.elastic_lanes, default
|
|
331
|
+
// #6047: heavy tokens (cfg.elastic_lanes, default on since #6204). A lane is admitted on its base reservation; each heavy step leases a token
|
|
323
332
|
// (weight = max(default, p90 history - base)) from this host's pool. Tokens live in store.data.heavy and expire with their lease,
|
|
324
333
|
// when the sandbox exits or when it is destroyed.
|
|
325
|
-
const elastic = () => cfg.elastic_lanes
|
|
334
|
+
const elastic = () => cfg.elastic_lanes !== false; // #6204: on by default; `elastic_lanes: false` restores worst-case accounting
|
|
326
335
|
const heavyTtlMs = () => (cfg.heavy_ttl_s ?? 300) * 1000;
|
|
327
336
|
const heavyDefault = () => ({ cpus: cfg.heavy_weight?.cpus ?? 1, mem: cfg.heavy_weight?.mem_gb ?? 2 });
|
|
328
337
|
const heavyTokens = () => (store.data.heavy ??= {});
|
|
@@ -332,7 +341,36 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
332
341
|
if (dropped) store.save();
|
|
333
342
|
return Object.values(heavyTokens()).reduce((a, t) => ({ cpus: a.cpus + t.cpus, mem: a.mem + t.mem, n: a.n + 1 }), { cpus: 0, mem: 0, n: 0 });
|
|
334
343
|
}
|
|
335
|
-
|
|
344
|
+
/** #6204: elastic admission charges a lane its measured footprint (cfg.elastic_base floor, raised to the mean live usage of the running lanes), never above what it asked for. */
|
|
345
|
+
function elasticBase() {
|
|
346
|
+
const fl = { cpus: cfg.elastic_base?.cpus ?? 0.4, mem: cfg.elastic_base?.mem_gb ?? 0.3 };
|
|
347
|
+
const us = activeRecs().map((r) => r.usage).filter((u) => u?.samples >= 3);
|
|
348
|
+
if (!us.length) return fl;
|
|
349
|
+
const mean = (k) => us.reduce((a, u) => a + u[k] / u.samples, 0) / us.length;
|
|
350
|
+
return { cpus: Math.max(fl.cpus, mean("cpu_sum")), mem: Math.max(fl.mem, mean("mem_sum")) };
|
|
351
|
+
}
|
|
352
|
+
// #6235: only a lane whose image carries the remote heavy backend (`remote`) is charged the elastic base: its heavy steps lease tokens.
|
|
353
|
+
// Any other lane (a pre-1.72 image, an unlabelled image, a record from before this field) gates nothing, so it is charged what it asked for.
|
|
354
|
+
const charge = (cpus, mem, base = elastic() ? elasticBase() : null, remote = false) => (base && remote ? { cpus: Math.min(cpus, base.cpus), mem: Math.min(mem, base.mem) } : { cpus, mem });
|
|
355
|
+
const HEAVY_REMOTE_MIN = "1.72.0"; // first engine version whose bin/lean/heavy.mjs speaks the pool agent's /heavy route (#6047, default #6204)
|
|
356
|
+
/** #6235: does this lane image carry the remote heavy backend? Read its version label (derived tools/project images inherit it); unknown fails closed. */
|
|
357
|
+
const heavyCapCache = new Map(); // image -> {at, v}: launches are frequent, the label is not
|
|
358
|
+
async function laneHasRemoteHeavy(img) {
|
|
359
|
+
const hit = heavyCapCache.get(img);
|
|
360
|
+
if (hit && now() - hit.at < 60000) return hit.v;
|
|
361
|
+
const v = await laneHasRemoteHeavyNow(img);
|
|
362
|
+
heavyCapCache.set(img, { at: now(), v });
|
|
363
|
+
return v;
|
|
364
|
+
}
|
|
365
|
+
async function laneHasRemoteHeavyNow(img) {
|
|
366
|
+
try {
|
|
367
|
+
const v = String((await docker.imageLabel?.(img, "org.opencontainers.image.version")) ?? "").trim();
|
|
368
|
+
const c = cmpVersion(v, HEAVY_REMOTE_MIN);
|
|
369
|
+
if (c === null) { log.warn?.(`lane image ${img} has no engine version label; charging its lanes worst-case`); return false; }
|
|
370
|
+
return c >= 0;
|
|
371
|
+
} catch { return false; }
|
|
372
|
+
}
|
|
373
|
+
const baseUse = () => { const b = elastic() ? elasticBase() : null; return activeRecs().reduce((a, r) => { const c = charge(r.cpus, r.mem_gb, b, r.heavyRemote === true); return { cpus: a.cpus + c.cpus, mem: a.mem + c.mem }; }, { cpus: 0, mem: 0 }); };
|
|
336
374
|
/** Elastic: base reservations plus held tokens; flat: each lane's projected peak (#5858). */
|
|
337
375
|
const projectedUse = () => { if (!elastic()) return peakUse(); const b = baseUse(), h = heavyHeld(); return { cpus: b.cpus + h.cpus, mem: b.mem + h.mem }; };
|
|
338
376
|
/** Lane ceiling derived from the token pool when elastic: a multiple of the default-weight heavy steps the host holds. */
|
|
@@ -344,6 +382,8 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
344
382
|
const held = heavyHeld(), mine = Object.entries(heavyTokens()).find(([, t]) => t.sandbox === r.id);
|
|
345
383
|
const ttl = Math.round(heavyTtlMs() / 1000);
|
|
346
384
|
if (mine) { mine[1].refs = (mine[1].refs ?? 1) + 1; mine[1].expires = now() + heavyTtlMs(); store.save(); return { status: 200, body: { granted: true, token: mine[0], ttl_s: ttl } }; }
|
|
385
|
+
const hm = hostMemView(); // #5967/#6235: below the floor no NEW lease is granted (a lane already holding one keeps it above), so heavy work stops before the host OOMs
|
|
386
|
+
if (hm.host_mem_low) return { status: 200, body: { granted: false, retry_after_s: cfg.host_mem_retry_after_s ?? 30, reason: "host_mem", host_mem_free_gb: hm.host_mem_free_gb, floor_gb: hm.host_mem_floor_gb, held: held.n } };
|
|
347
387
|
const est = estimateFor(r.repo ?? null, { cpus: r.cpus, mem: r.mem_gb }), d = heavyDefault();
|
|
348
388
|
const w = { cpus: Math.max(d.cpus, est.cpus - r.cpus), mem: Math.max(d.mem, est.mem - r.mem_gb) };
|
|
349
389
|
const e = effectiveCapacity(), b = baseUse(), live_ = live(cfg), ram = Number.isFinite(live_?.mem_available_gb) ? live_.mem_available_gb : Infinity;
|
|
@@ -365,9 +405,9 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
365
405
|
function heavyView() {
|
|
366
406
|
if (!elastic()) return {};
|
|
367
407
|
const h = heavyHeld(), e = effectiveCapacity(), b = baseUse();
|
|
368
|
-
return { elastic_lanes: true, heavy_tokens: h.n, heavy_held: { cpus: r2(h.cpus), mem_gb: r2(h.mem) }, cpus_free_elastic: r2(e.cpus - b.cpus - h.cpus - coTenant.cpus), mem_free_gb_elastic: r2(e.mem - b.mem - h.mem - coTenant.mem_gb), lanes_ceiling_derived: derivedCeiling() };
|
|
408
|
+
return { elastic_lanes: true, elastic_base: { cpus: r2(elasticBase().cpus), mem_gb: r2(elasticBase().mem) }, heavy_tokens: h.n, heavy_held: { cpus: r2(h.cpus), mem_gb: r2(h.mem) }, cpus_free_elastic: r2(e.cpus - b.cpus - h.cpus - coTenant.cpus), mem_free_gb_elastic: r2(e.mem - b.mem - h.mem - coTenant.mem_gb), lanes_ceiling_derived: derivedCeiling() };
|
|
369
409
|
}
|
|
370
|
-
const sumRecs = (rs) => rs.reduce((a, s) => ({ cpus: a.cpus +
|
|
410
|
+
const sumRecs = (rs) => { const b = elastic() ? elasticBase() : null; return rs.reduce((a, s) => { const c = charge(s.cpus, s.mem_gb, b, s.heavyRemote === true); return { cpus: a.cpus + c.cpus, mem: a.mem + c.mem }; }, { cpus: 0, mem: 0 }); }; // #6204: elastic lanes are charged their measured base
|
|
371
411
|
const weighted = () => reservations().length > 0 || Boolean(cfg.idle_only);
|
|
372
412
|
const SHARES = () => ({ reserved: 4096, normal: 1024, borrow: 128, throttled: 2, ...(cfg.cpu_shares ?? {}) });
|
|
373
413
|
/** Admission headroom per class: free = physical, unreserved_free = space outside every reservation, borrowable = what `borrow` may take. */
|
|
@@ -481,7 +521,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
481
521
|
const active = Object.values(sb()).filter((s) => s.state !== "exited").length;
|
|
482
522
|
const e = effectiveCapacity();
|
|
483
523
|
const h = live(cfg);
|
|
484
|
-
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 }])) };
|
|
524
|
+
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 || dnsHold > 0), 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 }])) };
|
|
485
525
|
}
|
|
486
526
|
|
|
487
527
|
/** The image a spec's lanes run (the per-repo lane_tools tag when tools are listed), without building it. */
|
|
@@ -554,7 +594,8 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
554
594
|
const reservation = prio === "reserved" ? (spec.reservation ?? (reservations().length === 1 ? reservations()[0].name : null)) : null;
|
|
555
595
|
const c = capacity();
|
|
556
596
|
const h = live(cfg);
|
|
557
|
-
const
|
|
597
|
+
const heavyRemote = elastic() ? await laneHasRemoteHeavy(spec.image ?? image) : false; // #6235
|
|
598
|
+
const adm = admit({ prio, cpus: charge(cpus, mem_gb, undefined, heavyRemote).cpus, mem_gb: charge(cpus, mem_gb, undefined, heavyRemote).mem, reservation, h }); // #6204
|
|
558
599
|
if (c.draining && !c.paused) return { status: 503, body: { error: `draining: ${c.draining_reason}`, code: "pool.draining", capacity: c }, retryAfter: 60 }; // #6061: finish running lanes, accept none
|
|
559
600
|
if (laneTargetOn() && !c.paused && c.active >= laneNow()) return { status: 503, body: { error: `lane target ${laneNow()} reached (${c.active} running)`, code: "pool.lane_target", lane_target: laneNow(), capacity: c }, retryAfter: 60 };
|
|
560
601
|
if (c.paused || adm.refuse) {
|
|
@@ -565,7 +606,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
565
606
|
// Burst model: reservations are small, so also refuse when the VM is genuinely short of memory or overloaded right now.
|
|
566
607
|
// A reserved launch skips the load gate: it must never be refused because lanes are busy (they are throttled/drained below).
|
|
567
608
|
if (prio !== "reserved") { // #5858: ramp-aware: the admitted lanes' projected peaks plus this one must fit, however low the load is right now
|
|
568
|
-
const e = effectiveCapacity(), pu = projectedUse(), est = elastic() ? { cpus, mem: mem_gb } : estimateFor(slugOf(spec), { cpus, mem: mem_gb }), nm = Math.max(mem_gb, est.mem), nc = Math.max(cpus, est.cpus);
|
|
609
|
+
const e = effectiveCapacity(), pu = projectedUse(), est = elastic() ? { cpus, mem: mem_gb } : estimateFor(slugOf(spec), { cpus, mem: mem_gb }), ch = charge(cpus, mem_gb, undefined, heavyRemote), nm = elastic() ? ch.mem : Math.max(mem_gb, est.mem), nc = elastic() ? ch.cpus : Math.max(cpus, est.cpus);
|
|
569
610
|
const availMem = e.mem - coTenant.mem_gb, availCpus = e.cpus - coTenant.cpus;
|
|
570
611
|
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 };
|
|
571
612
|
}
|
|
@@ -585,7 +626,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
585
626
|
}
|
|
586
627
|
if (spec.lane_tools?.length) { // #5650 follow-up: never build inside the launch request (router timeout); 503 + retry while it builds
|
|
587
628
|
let st;
|
|
588
|
-
try { st = await laneImageNow({ tools: spec.lane_tools, baseImage: spec.image ?? image, docker }); } catch (e) { return { status: 422, body: { error: e.message, code: e.code ?? "lane_tools.invalid" } }; }
|
|
629
|
+
try { st = await laneImageNow({ tools: spec.lane_tools, baseImage: spec.image ?? image, docker: variantDocker(spec.image ?? image) }); } catch (e) { return { status: 422, body: { error: e.message, code: e.code ?? "lane_tools.invalid" } }; }
|
|
589
630
|
if (st.building) return { status: 503, body: { error: `lane image ${st.tag} building`, code: "lane_tools.building" }, retryAfter: LANE_BUILD_RETRY_AFTER_S };
|
|
590
631
|
if (st.failed) return { status: 422, body: { error: st.failed, code: "lane_tools.build_failed" } };
|
|
591
632
|
}
|
|
@@ -610,10 +651,10 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
610
651
|
const envFile = join(dir, "env");
|
|
611
652
|
const credToken = randomBytes(24).toString("hex");
|
|
612
653
|
const withDocker = Boolean(spec.docker);
|
|
613
|
-
const env = { ...(spec.env ?? {}), ...(withDocker ? { DOCKER_HOST: "tcp://127.0.0.1:2375" } : {}), ...(elastic() ? { CS_HEAVY_BASE: `http://host.docker.internal:${cfg.listen.port}/sandboxes/${encodeURIComponent(spec.id)}/heavy` } : {}), 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, ...cpuQuotaEnv(limit?.lane_cpus ?? cpus), 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),
|
|
654
|
+
const env = { ...(spec.env ?? {}), ...(withDocker ? { DOCKER_HOST: "tcp://127.0.0.1:2375" } : {}), ...(elastic() && heavyRemote ? { CS_HEAVY_BASE: `http://host.docker.internal:${cfg.listen.port}/sandboxes/${encodeURIComponent(spec.id)}/heavy` } : {}), 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, ...cpuQuotaEnv(limit?.lane_cpus ?? cpus), 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),
|
|
614
655
|
...(spec.env_snapshots?.enabled ? { FORGE_ENV_IMAGE: envImageOf(spec) } : {}) }; // the image is part of the snapshot key
|
|
615
656
|
writeFileSync(envFile, Object.entries(env).map(([k, v]) => envLine(k, v)).join("\n") + "\n", { mode: 0o600 });
|
|
616
|
-
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 } : {}) } : {}) };
|
|
657
|
+
const rec = { heavyRemote, 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 } : {}) } : {}) };
|
|
617
658
|
sb()[spec.id] = rec;
|
|
618
659
|
store.save();
|
|
619
660
|
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
|
|
@@ -627,7 +668,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
627
668
|
const cacheMount = ["-v", `${rec.cacheVolume}:/cache`];
|
|
628
669
|
try {
|
|
629
670
|
// #5650: a repo's lane_tools select a derived image (built once per tool list); none keeps spec.image ?? image.
|
|
630
|
-
const toolsImage = spec.lane_tools?.length ? await resolveLaneImage({ tools: spec.lane_tools, baseImage: spec.image ?? image, docker }) : (spec.image ?? image);
|
|
671
|
+
const toolsImage = spec.lane_tools?.length ? await resolveLaneImage({ tools: spec.lane_tools, baseImage: spec.image ?? image, docker: variantDocker(spec.image ?? image) }) : (spec.image ?? image);
|
|
631
672
|
const laneImage = projectImage ?? toolsImage; // #6038: the project layer sits on the tools image, or is skipped (base) while building
|
|
632
673
|
if (withDocker) {
|
|
633
674
|
// Private Docker daemon per sandbox (never the host socket). The lane joins its network namespace, so ports the
|
|
@@ -1062,7 +1103,8 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
1062
1103
|
const nextImage = cfg.image && cfg.image !== "computeshare-lane:1" ? cfg.image : laneImageTag(want.version);
|
|
1063
1104
|
log.info?.(`rebuilding ${nextImage} (${running.version}/${running.image} -> ${want.version}/${want.image})`);
|
|
1064
1105
|
// #6166: present (pre-seeded) -> pull the published image -> local build only as the fallback
|
|
1065
|
-
const
|
|
1106
|
+
const pub = nextImage === laneImageTag(want.version) ? await fetchDigest(want.version) : null; // #6185: pull by the publisher-recorded digest
|
|
1107
|
+
const how = await provideLaneImage({ docker, image: nextImage, version: want.version, recipe: want.image, digest: pub?.digest, publishable: nextImage === laneImageTag(want.version), log, pinOpts,
|
|
1066
1108
|
build: () => buildWithRetry(() => docker.build(join(next, "pool", "image"), nextImage, laneBuildArgs(want.version, want.image)), { log }) }); // #5919
|
|
1067
1109
|
log.info?.(`${nextImage}: ${how}`);
|
|
1068
1110
|
}
|
|
@@ -1233,7 +1275,8 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
1233
1275
|
|
|
1234
1276
|
/** Build the lane image for the running ForgeDock version when this host does not have it yet. */
|
|
1235
1277
|
async function ensureImage() {
|
|
1236
|
-
|
|
1278
|
+
const pub = image === laneImageTag(running.version) && !(await docker.hasImage?.(image)) ? await fetchDigest(running.version) : null; // #6185
|
|
1279
|
+
await provideLaneImage({ docker, image, version: running.version, recipe: running.image, digest: pub?.digest, publishable: image === laneImageTag(running.version), log, pinOpts,
|
|
1237
1280
|
build: () => docker.build(join(cfg.code_root ?? repoRoot, "pool", "image"), image, laneBuildArgs(running.version, running.image)) });
|
|
1238
1281
|
await pruneLaneImages();
|
|
1239
1282
|
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
// #6195/#6234: on WSL2 mirrored networking dockerd's resolver (the WSL proxy, 10.255.255.254) can fail while the host resolver works.
|
|
4
|
+
// Lane containers get a per-container `--dns` (agent netArgs), which never touches the shared daemon. Only the daemon's own pulls need the
|
|
5
|
+
// daemon-wide fallback, and a dockerd restart kills every container on it, so it runs only when provably nothing else is on the daemon.
|
|
6
|
+
import { readFileSync, writeFileSync } from "node:fs";
|
|
7
|
+
|
|
8
|
+
/** dockerd's own resolver failing: "lookup ghcr.io on 10.255.255.254:53: no such host" / "server misbehaving". */
|
|
9
|
+
export const DNS_FAIL_RE = /lookup \S+ on [0-9a-f.:]+:53: (no such host|server misbehaving)/i;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Repair dockerd's resolver for the agent's own pulls. Order matters and is atomic against admission:
|
|
13
|
+
* 1. `hold()` pauses admission on the agent (returns a release function; called in a finally),
|
|
14
|
+
* 2. `idle()` (sync or async) must say that no sandbox is active AND no container at all (co-tenants included) runs on the daemon,
|
|
15
|
+
* 3. only then daemon.json `dns` is written (other keys kept; a `dns` already set is left alone) and docker restarted.
|
|
16
|
+
* Not idle, an unreadable file or a failed restart: daemon.json is left (or put back) as it was, so no resolver is pinned without a restart.
|
|
17
|
+
* Returns {changed, restarted, reason?}. Never throws.
|
|
18
|
+
*/
|
|
19
|
+
export async function ensureDaemonDns({ file = "/etc/docker/daemon.json", dns = ["1.1.1.1", "8.8.8.8"], restart = async () => {}, idle = () => false, hold = () => () => {}, log = null } = {}) {
|
|
20
|
+
let release = () => {};
|
|
21
|
+
try { release = hold() ?? release; } catch (e) { log?.warn?.(`docker DNS repair: cannot pause admission: ${e.message}`); return { changed: false, restarted: false, reason: "hold" }; }
|
|
22
|
+
try {
|
|
23
|
+
let raw = "", cfg = {};
|
|
24
|
+
try { raw = readFileSync(file, "utf8"); cfg = JSON.parse(raw || "{}"); } catch (e) { if (e?.code !== "ENOENT") { log?.warn?.(`daemon.json unreadable: ${e.message}`); return { changed: false, restarted: false, reason: "unreadable" }; } raw = ""; }
|
|
25
|
+
if (!cfg || typeof cfg !== "object" || Array.isArray(cfg)) return { changed: false, restarted: false, reason: "unreadable" };
|
|
26
|
+
if (Array.isArray(cfg.dns) && cfg.dns.length) return { changed: false, restarted: false, reason: "dns-set" };
|
|
27
|
+
let quiet = false;
|
|
28
|
+
try { quiet = (await idle()) === true; } catch { quiet = false; }
|
|
29
|
+
if (!quiet) { log?.warn?.("docker not restarted: sandboxes or other containers are running; lane containers use per-container --dns, daemon.json is untouched"); return { changed: false, restarted: false, reason: "busy" }; }
|
|
30
|
+
try { writeFileSync(file, `${JSON.stringify({ ...cfg, dns }, null, 2)}\n`); } catch (e) { log?.warn?.(`cannot write ${file}: ${e.message}`); return { changed: false, restarted: false, reason: "unwritable" }; }
|
|
31
|
+
try { await restart(); } catch (e) {
|
|
32
|
+
log?.warn?.(`docker restart failed: ${e.message}; daemon.json restored`);
|
|
33
|
+
try { writeFileSync(file, raw || "{}\n"); } catch { /* best effort */ }
|
|
34
|
+
return { changed: false, restarted: false, reason: "restart-failed" };
|
|
35
|
+
}
|
|
36
|
+
log?.info?.(`docker daemon DNS set to ${dns.join(", ")} in ${file}; docker restarted while idle`);
|
|
37
|
+
return { changed: true, restarted: true };
|
|
38
|
+
} finally { try { release(); } catch { /* ignore */ } }
|
|
39
|
+
}
|
package/bin/pool/docker.mjs
CHANGED
|
@@ -11,10 +11,11 @@ export const cpuQuotaEnv = (cpus) => (Number.isFinite(cpus) && cpus > 0 ? { CS_C
|
|
|
11
11
|
export const SWEEP_TIMEOUT_MS = 10 * 60000;
|
|
12
12
|
const SWEEP_SRC = new URL("./cache-sweep.mjs", import.meta.url);
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
/** #6189: `keepTail` keeps the END of stderr (a build error's useful part), not the head. */
|
|
15
|
+
function docker(args, { timeoutMs = 120000, keepTail = false } = {}) {
|
|
15
16
|
return new Promise((resolve, reject) => {
|
|
16
17
|
execFile("docker", args, { timeout: timeoutMs, maxBuffer: 16 << 20 }, (err, stdout, stderr) => {
|
|
17
|
-
if (err) {
|
|
18
|
+
if (err) { const t = String(stderr ?? ""); err.stderr = keepTail ? t.slice(-4000) : t.slice(0, 2000); reject(err); } else resolve(String(stdout).trim());
|
|
18
19
|
});
|
|
19
20
|
});
|
|
20
21
|
}
|
|
@@ -47,6 +48,8 @@ export const dockerCli = {
|
|
|
47
48
|
const out = await docker(["ps", "-a", ...[].concat(label).flatMap((l) => ["--filter", `label=${l}`]), "--format", "{{.Names}}"], { timeoutMs: 20000 });
|
|
48
49
|
return out ? out.split("\n").filter(Boolean) : [];
|
|
49
50
|
},
|
|
51
|
+
/** #6234: names of every running container on the daemon (any owner); the DNS repair restarts dockerd only when this is empty. */
|
|
52
|
+
async listRunning() { const out = await docker(["ps", "--format", "{{.Names}}"], { timeoutMs: 20000 }); return out ? out.split("\n").filter(Boolean) : []; },
|
|
50
53
|
async removeVolume(name) { try { await docker(["volume", "rm", "-f", name], { timeoutMs: 120000 }); } catch (e) { if (!/no such volume/i.test(e.stderr ?? "")) throw e; } },
|
|
51
54
|
/** #5881: `label` (one or a list) restricts the list to volumes carrying it, e.g. this agent's. */
|
|
52
55
|
async listVolumes(prefix, label = []) {
|
|
@@ -84,6 +87,7 @@ export const dockerCli = {
|
|
|
84
87
|
/** #6166: retags a local image (the pulled ghcr.io image becomes forgedock-lane:<version>). */
|
|
85
88
|
async tag(src, dst) { return docker(["tag", src, dst], { timeoutMs: 30000 }); },
|
|
86
89
|
/** #6166: one label of a local image ("" when unset or the image is missing). */
|
|
90
|
+
async imageRepoDigests(ref) { try { const j = JSON.parse(await docker(["image", "inspect", "--format", "{{json .RepoDigests}}", ref], { timeoutMs: 20000 })); return Array.isArray(j) ? j : []; } catch { return []; } },
|
|
87
91
|
async imageLabel(ref, label) { try { return await docker(["image", "inspect", "--format", `{{index .Config.Labels "${label}"}}`, ref], { timeoutMs: 20000 }); } catch { return ""; } },
|
|
88
92
|
async load(file) { return docker(["load", "-q", "-i", file], { timeoutMs: 30 * 60000 }); },
|
|
89
93
|
async hasImage(ref) { try { await docker(["image", "inspect", ref], { timeoutMs: 20000 }); return true; } catch { return false; } },
|
|
@@ -101,7 +105,7 @@ export const dockerCli = {
|
|
|
101
105
|
}
|
|
102
106
|
return res;
|
|
103
107
|
},
|
|
104
|
-
async build(dir, tag, buildArgs = {}) { return docker(["build", "
|
|
108
|
+
async build(dir, tag, buildArgs = {}) { return docker(["build", "--progress=plain", "-t", tag, ...Object.entries(buildArgs).flatMap(([k, v]) => ["--build-arg", `${k}=${v}`]), dir], { timeoutMs: 45 * 60000, keepTail: true }); },
|
|
105
109
|
/** #5696: removes one lane worktree (/cache/work/<id>) from a cache volume. */
|
|
106
110
|
async removeWorkDir(volume, image, workDir) { await docker(["run", "--rm", "--network", "none", "-v", `${volume}:/cache`, "--entrypoint", "sh", image, "-c", 'rm -rf -- "$1"', "sh", workDir], { timeoutMs: SWEEP_TIMEOUT_MS }); },
|
|
107
111
|
/** #5696: removes every /cache/work/* dir of a cache volume except the kept ones (full paths). */
|
|
@@ -11,7 +11,7 @@ import { tmpDir } from "../tests/_tmp.mjs";
|
|
|
11
11
|
const quiet = { info() {}, warn() {}, error() {} };
|
|
12
12
|
const json = (o, status = 200) => new Response(JSON.stringify(o), { status, headers: { "content-type": "application/json" } });
|
|
13
13
|
const spec = (id, extra = {}) => ({ id, issue: 1, batch: "b", repo: { slug: "o/x", url: "https://github.com/o/x.git" }, command: ["x"], ...extra });
|
|
14
|
-
const TARGET = "
|
|
14
|
+
const TARGET = JSON.parse((await import("node:fs")).readFileSync("package.json", "utf8")).version; // the router's own target: this repo's package.json version (asserted below)
|
|
15
15
|
|
|
16
16
|
// `old` has more free cpus, so capacity order alone would pick it.
|
|
17
17
|
function fixture({ oldFree = true, newFree = true } = {}) {
|
|
@@ -87,7 +87,7 @@ test("cmpVersion is numeric, agents without a version never lag", () => {
|
|
|
87
87
|
test("upgradeAgentsAfterUpdate names agents left behind and keeps its string result", async () => {
|
|
88
88
|
const warned = [], dir = tmpDir("cs-eng-cfg-"), cfgPath = `${dir}/router.json`;
|
|
89
89
|
(await import("node:fs")).writeFileSync(cfgPath, "{}");
|
|
90
|
-
const r = await upgradeAgentsAfterUpdate({ configPath: cfgPath, runPoolCli: async () => {}, warn: (m) => warned.push(m),
|
|
90
|
+
const r = await upgradeAgentsAfterUpdate({ configPath: cfgPath, runPoolCli: async () => {}, ensureRouterFresh: async () => ({ ok: true }), warn: (m) => warned.push(m),
|
|
91
91
|
leftBehind: async () => ({ target: "1.67.0", rows: [{ name: "old", version: "1.66.0" }] }) });
|
|
92
92
|
assert.equal(r, "upgraded");
|
|
93
93
|
assert.match(warned[0], /left behind.*old 1\.66\.0/);
|
|
@@ -18,3 +18,16 @@ describe("#6037 image manifest", () => {
|
|
|
18
18
|
assert.ok(!manifestProvides(loadImageManifest(join(d, "nope.json")), "yq"));
|
|
19
19
|
});
|
|
20
20
|
});
|
|
21
|
+
|
|
22
|
+
describe("#6187 variant remote refs", () => {
|
|
23
|
+
it("remoteVariantImage maps the local tag to ghcr and pullVariantImage retags it", async () => {
|
|
24
|
+
const { remoteVariantImage, pullVariantImage, LANE_REGISTRY_IMAGE } = await import("./lane-image.mjs");
|
|
25
|
+
const { laneToolsTag } = await import("./lane-tools.mjs");
|
|
26
|
+
const tag = laneToolsTag("forgedock-lane:1.2.3", ["xvfb"]);
|
|
27
|
+
assert.equal(remoteVariantImage("1.2.3", tag), `${LANE_REGISTRY_IMAGE}:1.2.3${tag.slice(tag.lastIndexOf("-t"))}`);
|
|
28
|
+
assert.match(remoteVariantImage("1.2.3", tag), /:1\.2\.3-t[0-9a-f]{12}$/);
|
|
29
|
+
const seen = [], docker = { pull: async (r) => seen.push(["pull", r]), tag: async (a, b) => seen.push(["tag", a, b]) };
|
|
30
|
+
await pullVariantImage({ docker, tag, version: "1.2.3" });
|
|
31
|
+
assert.deepEqual(seen, [["pull", remoteVariantImage("1.2.3", tag)], ["tag", remoteVariantImage("1.2.3", tag), tag]]);
|
|
32
|
+
});
|
|
33
|
+
});
|
package/bin/pool/lane-image.mjs
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// #6166: a pool host gets the lane image by PULLING the one publish.yml built (ghcr.io), and builds locally only when the pull fails.
|
|
4
4
|
import { readFileSync, writeFileSync } from "node:fs";
|
|
5
5
|
import { resolve4 } from "node:dns/promises";
|
|
6
|
+
import { DNS_FAIL_RE } from "./docker-dns.mjs";
|
|
6
7
|
|
|
7
8
|
export const LANE_REGISTRY_IMAGE = "ghcr.io/rapiercraftstudios/forgedock-lane";
|
|
8
9
|
/** Label the Dockerfile stamps with the recipe hash (versionOf().image); checked after a pull. */
|
|
@@ -20,6 +21,9 @@ export const remoteLaneImage = (version) => `${LANE_REGISTRY_IMAGE}:${version}`;
|
|
|
20
21
|
/** Tag carrying the image recipe hash, pushed beside the version tag (identifies the recipe independent of a version bump). */
|
|
21
22
|
export const remoteRecipeImage = (recipe) => `${LANE_REGISTRY_IMAGE}:r-${recipe}`;
|
|
22
23
|
|
|
24
|
+
/** Remote ref of a lane_tools variant: the local tag `<base>-t<12 hex>` published as `forgedock-lane:<version>-t<12 hex>` (#6187). */
|
|
25
|
+
export const remoteVariantImage = (version, tag) => `${LANE_REGISTRY_IMAGE}:${version}${String(tag).slice(String(tag).lastIndexOf("-t"))}`;
|
|
26
|
+
|
|
23
27
|
let pinDepth = 0; // concurrent pins share one /etc/hosts edit; the last one out removes it
|
|
24
28
|
/**
|
|
25
29
|
* Run `fn` with temporary /etc/hosts IPv4 pins for the registry hosts (lines tagged `# forgedock-ipv4-pin`), removed afterwards,
|
|
@@ -41,44 +45,81 @@ export async function withIpv4Pins(fn, { hosts = REGISTRY_HOSTS, file = "/etc/ho
|
|
|
41
45
|
}
|
|
42
46
|
}
|
|
43
47
|
|
|
44
|
-
/** Run `op`; on an IPv6 dial error retry it once under temporary IPv4 pins. A host that cannot pin reports the original error. */
|
|
48
|
+
/** Run `op`; on a docker DNS failure repair the daemon DNS and retry once (#6195); on an IPv6 dial error retry it once under temporary IPv4 pins. A host that cannot pin reports the original error. */
|
|
45
49
|
export async function withIpv4Fallback(op, pinOpts = {}) {
|
|
46
50
|
try { return await op(); } catch (e) {
|
|
51
|
+
if (DNS_FAIL_RE.test(errText(e)) && pinOpts.ensureDns) {
|
|
52
|
+
// #6195: dockerd's resolver is broken; set daemon DNS and retry once when docker was restarted.
|
|
53
|
+
pinOpts.log?.warn?.(`docker DNS error; repairing daemon DNS: ${errText(e).slice(-300)}`);
|
|
54
|
+
let fixed = null;
|
|
55
|
+
try { fixed = await pinOpts.ensureDns(); } catch { /* report the original error */ }
|
|
56
|
+
if (!fixed?.restarted) throw e;
|
|
57
|
+
return withIpv4Fallback(op, { ...pinOpts, ensureDns: null });
|
|
58
|
+
}
|
|
47
59
|
if (!IPV6_DIAL_RE.test(errText(e))) throw e;
|
|
48
60
|
pinOpts.log?.warn?.(`IPv6 dial error; retrying with IPv4 pins: ${errText(e).slice(-300)}`);
|
|
49
61
|
try { return await withIpv4Pins(op, pinOpts); } catch (e2) { if (e2 === e || IPV6_DIAL_RE.test(errText(e2))) throw e2; throw e; }
|
|
50
62
|
}
|
|
51
63
|
}
|
|
52
64
|
|
|
65
|
+
/** Release holding the lane-image.json asset ({version, recipe, digest}) that publish.yml/lane-image.yml write after the push (#6185). */
|
|
66
|
+
export const laneDigestUrl = (version) => `https://github.com/rapiercraftstudios/forgedock/releases/download/lane-image-v${version}/lane-image.json`;
|
|
67
|
+
const DIGEST_RE = /^sha256:[0-9a-f]{64}$/;
|
|
68
|
+
|
|
69
|
+
/** Read the publisher-recorded digest of the lane image for `version`: {digest, recipe} or null on any failure (no asset, network, bad JSON). */
|
|
70
|
+
export async function fetchLaneDigest(version, { fetch: doFetch = globalThis.fetch, timeoutMs = 15000 } = {}) {
|
|
71
|
+
try {
|
|
72
|
+
const res = await doFetch(laneDigestUrl(version), { signal: AbortSignal.timeout(timeoutMs) });
|
|
73
|
+
if (!res.ok) return null;
|
|
74
|
+
const j = await res.json();
|
|
75
|
+
if (!DIGEST_RE.test(j?.digest ?? "") || (j.version != null && j.version !== version)) return null;
|
|
76
|
+
return { digest: j.digest, recipe: typeof j.recipe === "string" ? j.recipe : "" };
|
|
77
|
+
} catch { return null; }
|
|
78
|
+
}
|
|
79
|
+
|
|
53
80
|
/**
|
|
54
|
-
* Pull the published lane image
|
|
55
|
-
* a
|
|
81
|
+
* Pull the published lane image BY DIGEST (the one publish recorded), confirm the pulled image's RepoDigests contain it, retag it as
|
|
82
|
+
* `image`, and check its recipe label equals `recipe` as a secondary consistency check. A mismatching image is removed again (it must
|
|
83
|
+
* never serve lanes) and rejects. Resolves true on success.
|
|
56
84
|
*/
|
|
57
|
-
export async function pullLaneImage({ docker, image, version, recipe, log = null, pinOpts = {} }) {
|
|
58
|
-
|
|
85
|
+
export async function pullLaneImage({ docker, image, version, recipe, digest, log = null, pinOpts = {} }) {
|
|
86
|
+
if (!DIGEST_RE.test(digest ?? "")) throw new Error(`no trusted digest for ${remoteLaneImage(version)}`);
|
|
87
|
+
const remote = `${LANE_REGISTRY_IMAGE}@${digest}`;
|
|
88
|
+
const drop = async () => { try { await docker.removeImage?.(remote); } catch { /* best effort */ } };
|
|
59
89
|
await withIpv4Fallback(() => docker.pull(remote), { ...pinOpts, log });
|
|
90
|
+
const digests = (await docker.imageRepoDigests?.(remote)) ?? [];
|
|
91
|
+
if (!digests.some((d) => d === remote || d.endsWith(`@${digest}`))) { await drop(); throw new Error(`pulled ${remote} reports digests [${digests.join(", ")}], want ${digest}`); }
|
|
60
92
|
const got = await docker.imageLabel(remote, RECIPE_LABEL);
|
|
61
|
-
if (got !== recipe) {
|
|
62
|
-
try { await docker.removeImage?.(remote); } catch { /* best effort */ }
|
|
63
|
-
throw new Error(`pulled ${remote} has recipe ${got || "(none)"}, want ${recipe}`);
|
|
64
|
-
}
|
|
93
|
+
if (got !== recipe) { await drop(); throw new Error(`pulled ${remote} has recipe ${got || "(none)"}, want ${recipe}`); }
|
|
65
94
|
await docker.tag(remote, image);
|
|
95
|
+
// #6184: the ghcr tag is invisible to pruneLaneImages and would pin the image's layers forever; untagging it frees nothing yet keeps `image`.
|
|
96
|
+
try { await docker.removeImage?.(remote); } catch (e) { log?.warn?.(`could not drop ${remote} tag: ${errText(e).slice(-200)}`); }
|
|
66
97
|
return true;
|
|
67
98
|
}
|
|
68
99
|
|
|
69
100
|
/**
|
|
70
|
-
* Make `image` exist locally: already present, else pulled (only the default `forgedock-lane:<version>` tag has a published
|
|
101
|
+
* Make `image` exist locally: already present, else pulled by recorded digest (only the default `forgedock-lane:<version>` tag has a published
|
|
71
102
|
* counterpart), else built by `build()`. Resolves "present" | "pulled" | "built". `build` is wrapped in the IPv4 fallback too.
|
|
72
103
|
*/
|
|
73
|
-
export async function provideLaneImage({ docker, image, version, recipe, publishable = true, build, log = null, pinOpts = {} }) {
|
|
104
|
+
export async function provideLaneImage({ docker, image, version, recipe, digest = null, publishable = true, build, log = null, pinOpts = {} }) {
|
|
74
105
|
if (await docker.hasImage?.(image)) return "present";
|
|
75
|
-
|
|
106
|
+
// #6185: no known digest -> no pull (the recipe label is self-declared by the image); build locally.
|
|
107
|
+
if (publishable && recipe && digest && docker.pull && docker.tag && docker.imageLabel) {
|
|
76
108
|
try {
|
|
77
|
-
await pullLaneImage({ docker, image, version, recipe, log, pinOpts });
|
|
78
|
-
log?.info?.(`${image} pulled from ${
|
|
109
|
+
await pullLaneImage({ docker, image, version, recipe, digest, log, pinOpts });
|
|
110
|
+
log?.info?.(`${image} pulled from ${LANE_REGISTRY_IMAGE}@${digest}; no build`);
|
|
79
111
|
return "pulled";
|
|
80
|
-
} catch (e) { log?.warn?.(`pull of ${
|
|
112
|
+
} catch (e) { log?.warn?.(`pull of ${LANE_REGISTRY_IMAGE}@${digest} failed, building locally: ${errText(e).slice(-300)}`); }
|
|
81
113
|
}
|
|
82
114
|
await withIpv4Fallback(build, { ...pinOpts, log });
|
|
83
115
|
return "built";
|
|
84
116
|
}
|
|
117
|
+
|
|
118
|
+
/** Pull the published variant for local `tag` and retag it as `tag` (#6187). Rejects when the registry has none; the caller builds. */
|
|
119
|
+
export async function pullVariantImage({ docker, tag, version, log = null, pinOpts = {} }) {
|
|
120
|
+
const remote = remoteVariantImage(version, tag);
|
|
121
|
+
await withIpv4Fallback(() => docker.pull(remote), { ...pinOpts, log });
|
|
122
|
+
await docker.tag(remote, tag);
|
|
123
|
+
log?.info?.(`${tag} pulled from ${remote}; no build`);
|
|
124
|
+
return true;
|
|
125
|
+
}
|
package/bin/pool/lane-tools.mjs
CHANGED
|
@@ -160,52 +160,66 @@ export function laneToolsDockerfile(baseImage, tools) {
|
|
|
160
160
|
/** One in-flight build per tag (shared by every launch and the warm pool), and the last failure per tag. */
|
|
161
161
|
const BUILDS = new Map();
|
|
162
162
|
const FAILED = new Map();
|
|
163
|
-
/**
|
|
163
|
+
/** Longest a failed build is reported instead of retried; the window grows 1, 2, 5, 10 min with consecutive failures of a tag. */
|
|
164
164
|
export const LANE_BUILD_RETRY_MS = 10 * 60000;
|
|
165
|
+
const BACKOFF_MS = [60000, 120000, 300000, LANE_BUILD_RETRY_MS];
|
|
166
|
+
/** Reporting window after the `count`-th consecutive failure of a tag. */
|
|
167
|
+
export const laneBuildBackoffMs = (count) => BACKOFF_MS[Math.min(Math.max(count, 1), BACKOFF_MS.length) - 1];
|
|
165
168
|
|
|
166
169
|
/**
|
|
167
170
|
* The image a launch runs: `baseImage` when no tools; else the per-repo tag, reused when present, built from the base
|
|
168
|
-
* otherwise.
|
|
171
|
+
* otherwise. A published variant is pulled first when `docker.pullVariant(tag)` (optional) resolves true; `docker.withFallback(op)`
|
|
172
|
+
* (optional) wraps the build in the IPv4 fallback (#6187). `docker.hasImage` and `docker.build(dir, tag, args)` are injected. Throws typed lane_tools.unknown_recipe
|
|
169
173
|
* (nothing built) or lane_tools.build_failed (build error or timeout, never a hang).
|
|
170
174
|
*/
|
|
171
|
-
export async function resolveLaneImage({ tools = [], baseImage, docker, buildTimeoutMs = 45 * 60000 }) {
|
|
175
|
+
export async function resolveLaneImage({ tools = [], baseImage, docker, buildTimeoutMs = 45 * 60000, sleep }) {
|
|
172
176
|
if (!tools.length) return baseImage;
|
|
173
177
|
checkRecipes(tools);
|
|
174
178
|
const tag = laneToolsTag(baseImage, tools);
|
|
175
179
|
if (await docker.hasImage?.(tag)) return tag;
|
|
176
|
-
if (!BUILDS.has(tag)) BUILDS.set(tag, buildLaneImage({ tag, baseImage, tools, docker, buildTimeoutMs }).finally(() => BUILDS.delete(tag)));
|
|
180
|
+
if (!BUILDS.has(tag)) BUILDS.set(tag, buildLaneImage({ tag, baseImage, tools, docker, buildTimeoutMs, ...(sleep ? { sleep, retryDelayMs: 0 } : {}) }).finally(() => BUILDS.delete(tag)));
|
|
177
181
|
return BUILDS.get(tag); // concurrent callers share one build of a tag
|
|
178
182
|
}
|
|
179
183
|
|
|
180
184
|
/**
|
|
181
185
|
* Non-blocking form for a launch (the router waits ~120 s, a build can take many minutes): {image} when the tag exists,
|
|
182
186
|
* {building: true} after starting (or joining) a background build, {failed: message} for a build that failed in the last
|
|
183
|
-
*
|
|
187
|
+
* window `laneBuildBackoffMs` of its consecutive failures. Throws typed lane_tools.unknown_recipe.
|
|
184
188
|
*/
|
|
185
|
-
export async function laneImageNow({ tools = [], baseImage, docker, buildTimeoutMs = 45 * 60000, now = Date.now }) {
|
|
189
|
+
export async function laneImageNow({ tools = [], baseImage, docker, buildTimeoutMs = 45 * 60000, now = Date.now, sleep }) {
|
|
186
190
|
if (!tools.length) return { image: baseImage };
|
|
187
191
|
checkRecipes(tools);
|
|
188
192
|
const tag = laneToolsTag(baseImage, tools);
|
|
189
193
|
if (await docker.hasImage?.(tag)) return { image: tag };
|
|
190
194
|
const f = FAILED.get(tag);
|
|
191
|
-
if (f && now() - f.at <
|
|
195
|
+
if (f && now() - f.at < laneBuildBackoffMs(f.count)) return { failed: f.message };
|
|
192
196
|
if (!BUILDS.has(tag)) {
|
|
193
|
-
|
|
194
|
-
|
|
197
|
+
const p = buildLaneImage({ tag, baseImage, tools, docker, buildTimeoutMs, ...(sleep ? { sleep, retryDelayMs: 0 } : {}) })
|
|
198
|
+
.then(() => { FAILED.delete(tag); }, (e) => { FAILED.set(tag, { at: now(), message: e.message, count: (f?.count ?? 0) + 1 }); }) // a failure is never permanent: it expires on a growing backoff
|
|
199
|
+
.finally(() => BUILDS.delete(tag));
|
|
195
200
|
BUILDS.set(tag, p);
|
|
196
201
|
}
|
|
197
202
|
return { building: true, tag };
|
|
198
203
|
}
|
|
199
204
|
|
|
200
|
-
|
|
205
|
+
/** #6189: the last ~20 lines of a build error (the failing step's own output), bounded to `max` chars. */
|
|
206
|
+
export function buildErrorTail(e, max = 1500) {
|
|
207
|
+
const t = String(e?.stderr || e?.message || e || "").trim().split("\n").slice(-20).join("\n");
|
|
208
|
+
return t.length <= max ? t : `…${t.slice(t.length - max + 1)}`;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async function buildLaneImage({ tag, baseImage, tools, docker, buildTimeoutMs, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), retryDelayMs = 15000 }) {
|
|
212
|
+
try { if (await docker.pullVariant?.(tag)) return tag; } catch { /* no published variant (or no route): build it */ }
|
|
201
213
|
const dir = mkdtempSync(join(tmpdir(), "lane-tools-"));
|
|
202
214
|
let timer;
|
|
203
215
|
try {
|
|
204
216
|
writeFileSync(join(dir, "Dockerfile"), laneToolsDockerfile(baseImage, tools));
|
|
205
217
|
const timeout = new Promise((_, rej) => { timer = setTimeout(() => rej(new Error(`build timed out after ${buildTimeoutMs}ms`)), buildTimeoutMs); });
|
|
206
|
-
|
|
218
|
+
const build = () => docker.build(dir, tag, {});
|
|
219
|
+
const attempt = () => Promise.race([docker.withFallback ? docker.withFallback(build) : build(), timeout]);
|
|
220
|
+
try { await attempt(); } catch { await sleep(retryDelayMs); await attempt(); } // #6189: one retry, a failed build is often transient
|
|
207
221
|
} catch (e) {
|
|
208
|
-
throw typed("lane_tools.build_failed", `lane_tools image ${tag} build failed: ${
|
|
222
|
+
throw typed("lane_tools.build_failed", `lane_tools image ${tag} build failed: ${buildErrorTail(e)}`);
|
|
209
223
|
} finally { clearTimeout(timer); rmSync(dir, { recursive: true, force: true }); }
|
|
210
224
|
return tag;
|
|
211
225
|
}
|
|
@@ -2,7 +2,7 @@
|
|
|
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 { RECIPES, hasRecipe, recipeFor, installCommands, installLaneTools, laneToolsDockerfile } from "./lane-tools.mjs";
|
|
5
|
+
import { RECIPES, hasRecipe, recipeFor, installCommands, installLaneTools, laneToolsDockerfile, laneToolsTag, laneBuildBackoffMs, resolveLaneImage, laneImageNow } 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", () => {
|
|
@@ -64,3 +64,65 @@ describe("#6037 image manifest tools skip the fallback installers", () => {
|
|
|
64
64
|
assert.ok((src.match(/@deprecated/g) ?? []).length >= 4);
|
|
65
65
|
});
|
|
66
66
|
});
|
|
67
|
+
|
|
68
|
+
describe("#6187 pulled variants, backoff and error tail", () => {
|
|
69
|
+
const dock = (over = {}) => { const images = new Set(); return { builds: [], pulls: [], async hasImage(r) { return images.has(r); }, async build(d, t) { this.builds.push(t); if (over.failBuild) throw Object.assign(new Error("x"), { stderr: `${"head ".repeat(600)}REAL-CAUSE` }); images.add(t); }, ...over }; };
|
|
70
|
+
const settle = async () => { for (let i = 0; i < 20; i++) await new Promise((r) => setImmediate(r)); };
|
|
71
|
+
it("a pulled variant skips the build, and its tag is laneToolsTag", async () => {
|
|
72
|
+
const pulled = [], docker = dock({ pullVariant: async (t) => { pulled.push(t); return true; } });
|
|
73
|
+
const img = await resolveLaneImage({ tools: ["xvfb"], baseImage: "pv:1", docker });
|
|
74
|
+
assert.equal(img, laneToolsTag("pv:1", ["xvfb"]));
|
|
75
|
+
assert.deepEqual(pulled, [img]);
|
|
76
|
+
assert.equal(docker.builds.length, 0);
|
|
77
|
+
});
|
|
78
|
+
it("a failed pull falls back to the build, wrapped by withFallback", async () => {
|
|
79
|
+
let wrapped = 0;
|
|
80
|
+
const docker = dock({ pullVariant: async () => { throw new Error("404"); }, withFallback: (op) => { wrapped++; return op(); } });
|
|
81
|
+
await resolveLaneImage({ tools: ["xvfb"], baseImage: "pv:2", docker, sleep: async () => {} });
|
|
82
|
+
assert.equal(docker.builds.length, 1);
|
|
83
|
+
assert.equal(wrapped, 1);
|
|
84
|
+
});
|
|
85
|
+
it("a failed build message keeps the tail, and the retry window grows 1, 2, 5, 10 min", async () => {
|
|
86
|
+
assert.deepEqual([1, 2, 3, 4, 9].map(laneBuildBackoffMs), [60000, 120000, 300000, 600000, 600000]);
|
|
87
|
+
let t = 0;
|
|
88
|
+
const now = () => t, docker = dock({ failBuild: true }), a = { tools: ["shellcheck"], baseImage: "pv:3", docker, now, sleep: async () => {} };
|
|
89
|
+
await laneImageNow(a); await settle();
|
|
90
|
+
assert.match((await laneImageNow(a)).failed, /REAL-CAUSE$/);
|
|
91
|
+
t += 60001; await laneImageNow(a); await settle(); // 2nd failure
|
|
92
|
+
t += 60001;
|
|
93
|
+
assert.ok((await laneImageNow(a)).failed, "still inside the 2 min window");
|
|
94
|
+
assert.equal(docker.builds.length, 4); // 2 failures x (build + retry)
|
|
95
|
+
t += 60001;
|
|
96
|
+
assert.ok((await laneImageNow(a)).building);
|
|
97
|
+
});
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
describe("lane image build errors and retry (#6189)", async () => {
|
|
101
|
+
const { laneImageNow, resolveLaneImage } = await import("./lane-tools.mjs");
|
|
102
|
+
const tools = ["shellcheck"];
|
|
103
|
+
const longErr = () => Object.assign(new Error("failed"), { stderr: `Dockerfile:5\n${Array.from({ length: 30 }, (_, i) => `line ${i}`).join("\n")}\nE: apt failed` });
|
|
104
|
+
const settle = () => new Promise((r) => setTimeout(r, 20));
|
|
105
|
+
const mk = (build) => ({ hasImage: async () => false, build });
|
|
106
|
+
|
|
107
|
+
it("failure message carries the tail of a long stderr", async () => {
|
|
108
|
+
const docker = mk(async () => { throw longErr(); });
|
|
109
|
+
await laneImageNow({ tools, baseImage: "base:tail", docker, sleep: async () => {} });
|
|
110
|
+
await settle();
|
|
111
|
+
const r = await laneImageNow({ tools, baseImage: "base:tail", docker, sleep: async () => {} });
|
|
112
|
+
assert.match(r.failed, /E: apt failed/);
|
|
113
|
+
assert.doesNotMatch(r.failed, /Dockerfile:5/);
|
|
114
|
+
});
|
|
115
|
+
it("retries a failed build once and yields the image", async () => {
|
|
116
|
+
let calls = 0;
|
|
117
|
+
const docker = mk(async () => { if (++calls === 1) throw longErr(); });
|
|
118
|
+
const img = await resolveLaneImage({ tools, baseImage: "base:retry", docker, sleep: async () => {} });
|
|
119
|
+
assert.equal(calls, 2);
|
|
120
|
+
assert.match(img, /base|lane/);
|
|
121
|
+
});
|
|
122
|
+
it("a persistent failure gives build_failed after 2 calls", async () => {
|
|
123
|
+
let calls = 0;
|
|
124
|
+
const docker = mk(async () => { calls++; throw longErr(); });
|
|
125
|
+
await assert.rejects(resolveLaneImage({ tools, baseImage: "base:fail", docker, sleep: async () => {} }), (e) => e.code === "lane_tools.build_failed" && /E: apt failed/.test(e.message));
|
|
126
|
+
assert.equal(calls, 2);
|
|
127
|
+
});
|
|
128
|
+
});
|