forgedock 1.66.0 → 1.68.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 +2 -0
- package/bin/engine-cli.mjs +193 -27
- package/bin/engine.mjs +10 -0
- package/bin/forgedock.mjs +24 -1
- package/bin/help-text.mjs +4 -3
- package/bin/introspect-schedule.mjs +98 -0
- package/bin/introspect-schedule.test.mjs +67 -0
- package/bin/lean/admission.mjs +21 -0
- package/bin/lean/admission.test.mjs +30 -0
- package/bin/lean/advisory.test.mjs +64 -0
- package/bin/lean/amendment-schema.mjs +30 -0
- package/bin/lean/attempts.mjs +162 -0
- package/bin/lean/attempts.test.mjs +141 -0
- package/bin/lean/basered.mjs +81 -0
- package/bin/lean/basered.test.mjs +68 -1
- package/bin/lean/batch-health.mjs +20 -12
- package/bin/lean/batch-health.test.mjs +55 -11
- package/bin/lean/batch.mjs +45 -0
- package/bin/lean/batch.test.mjs +105 -5
- package/bin/lean/capwait.mjs +14 -3
- package/bin/lean/capwait.test.mjs +20 -0
- package/bin/lean/ci-gate.mjs +2 -90
- package/bin/lean/ci-gate.test.mjs +1 -127
- package/bin/lean/ci-precheck.mjs +25 -8
- package/bin/lean/ci-precheck.test.mjs +24 -0
- package/bin/lean/clear-breaker.mjs +14 -0
- package/bin/lean/clear-breaker.test.mjs +4 -3
- package/bin/lean/commentstate.mjs +46 -0
- package/bin/lean/commentstate.test.mjs +43 -0
- package/bin/lean/concurrency.mjs +89 -0
- package/bin/lean/concurrency.test.mjs +113 -0
- package/bin/lean/conformance.e2e.test.mjs +13 -8
- package/bin/lean/conformance.mjs +73 -181
- package/bin/lean/conformance.test.mjs +61 -345
- package/bin/lean/depcache.mjs +100 -10
- package/bin/lean/depcache.test.mjs +105 -0
- package/bin/lean/docsgate.mjs +0 -32
- package/bin/lean/docsgate.test.mjs +2 -23
- package/bin/lean/effects-cap.test.mjs +9 -1
- package/bin/lean/effects-killtree.test.mjs +35 -0
- package/bin/lean/effects.mjs +42 -24
- package/bin/lean/efficiency.mjs +162 -0
- package/bin/lean/efficiency.test.mjs +79 -0
- package/bin/lean/engine-readmit.test.mjs +35 -0
- package/bin/lean/envgap.mjs +93 -0
- package/bin/lean/envgap.test.mjs +53 -0
- package/bin/lean/execution.mjs +41 -17
- package/bin/lean/execution.test.mjs +58 -0
- package/bin/lean/failure-census.mjs +170 -0
- package/bin/lean/failure-census.test.mjs +59 -0
- package/bin/lean/failure-stop.mjs +46 -0
- package/bin/lean/failure-stop.test.mjs +45 -0
- package/bin/lean/fixtures/capacity-storm.json +609 -0
- package/bin/lean/guardgate.test.mjs +2 -3
- package/bin/lean/heavy.mjs +33 -4
- package/bin/lean/heavy.test.mjs +38 -6
- package/bin/lean/hotarea.mjs +0 -36
- package/bin/lean/hotarea.test.mjs +1 -22
- package/bin/lean/issuewatch-verify.mjs +19 -4
- package/bin/lean/issuewatch.mjs +21 -4
- package/bin/lean/issuewatch.test.mjs +48 -1
- package/bin/lean/lane-audit-gap.mjs +66 -0
- package/bin/lean/lane-audit-gap.test.mjs +59 -0
- package/bin/lean/lane-audit-llm.mjs +5 -0
- package/bin/lean/lane-audit-query.mjs +47 -0
- package/bin/lean/lane-audit-query.test.mjs +44 -0
- package/bin/lean/lane-audit-signatures.mjs +33 -0
- package/bin/lean/lane-audit.mjs +110 -0
- package/bin/lean/lane-audit.test.mjs +97 -0
- package/bin/lean/lane-recovery.test.mjs +33 -0
- package/bin/lean/lanecheck.mjs +5 -3
- package/bin/lean/lanecheck.test.mjs +6 -0
- package/bin/lean/lean.mjs +311 -154
- package/bin/lean/lean.test.mjs +530 -223
- package/bin/lean/limits.mjs +17 -0
- package/bin/lean/limits.test.mjs +15 -1
- package/bin/lean/live-execution.mjs +21 -2
- package/bin/lean/live-execution.test.mjs +39 -0
- package/bin/lean/liveness.mjs +37 -0
- package/bin/lean/liveness.test.mjs +33 -0
- package/bin/lean/orchestrate-attempts.test.mjs +82 -0
- package/bin/lean/orchestrate-envhold.test.mjs +47 -0
- package/bin/lean/orchestrate-heldroot.test.mjs +72 -0
- package/bin/lean/orchestrate-hostfallback.test.mjs +59 -1
- package/bin/lean/orchestrate-overload-recovery.test.mjs +37 -0
- package/bin/lean/orchestrate-pause.test.mjs +76 -1
- package/bin/lean/orchestrate-reconcile.test.mjs +164 -0
- package/bin/lean/orchestrate-relaunch-gates.test.mjs +57 -0
- package/bin/lean/orchestrate-stacking.test.mjs +10 -0
- package/bin/lean/orchestrate.mjs +344 -45
- package/bin/lean/phaseledger.mjs +6 -0
- package/bin/lean/phaseledger.test.mjs +13 -1
- package/bin/lean/postdeploy-check.test.mjs +1 -3
- package/bin/lean/precheck.mjs +20 -0
- package/bin/lean/preflight.mjs +100 -11
- package/bin/lean/preflight.test.mjs +44 -4
- package/bin/lean/prompts.mjs +13 -28
- package/bin/lean/reconcile.mjs +90 -0
- package/bin/lean/recurrence.mjs +6 -112
- package/bin/lean/recurrence.test.mjs +11 -92
- package/bin/lean/release-flakes.mjs +14 -2
- package/bin/lean/release-flakes.test.mjs +17 -1
- package/bin/lean/release-ledger.mjs +19 -1
- package/bin/lean/release-ledger.test.mjs +23 -0
- package/bin/lean/release-preflight.mjs +28 -0
- package/bin/lean/release-preflight.test.mjs +42 -1
- package/bin/lean/release-review.mjs +40 -5
- package/bin/lean/release-review.test.mjs +43 -2
- package/bin/lean/release.mjs +43 -14
- package/bin/lean/release.test.mjs +32 -0
- package/bin/lean/retry.mjs +1 -1
- package/bin/lean/retry.test.mjs +6 -1
- package/bin/lean/rotator.mjs +9 -0
- package/bin/lean/rotator.test.mjs +11 -1
- package/bin/lean/sandbox-remote.mjs +49 -11
- package/bin/lean/sched.mjs +19 -0
- package/bin/lean/sched.test.mjs +11 -1
- package/bin/lean/schedd-health.mjs +4 -4
- package/bin/lean/schedd-health.test.mjs +8 -4
- package/bin/lean/schedd.mjs +45 -8
- package/bin/lean/schedd.test.mjs +120 -7
- package/bin/lean/selfreview.mjs +1 -1
- package/bin/lean/slo.mjs +126 -0
- package/bin/lean/slo.test.mjs +112 -0
- package/bin/lean/statuscomment.mjs +40 -0
- package/bin/lean/statuscomment.test.mjs +48 -1
- package/bin/lean/validate-catalog.mjs +108 -0
- package/bin/lean/validate-catalog.test.mjs +46 -1
- package/bin/lean/verify.mjs +3 -2
- package/bin/pool/affinity.test.mjs +91 -0
- package/bin/pool/agent.mjs +144 -10
- package/bin/pool/cache-sweep.mjs +31 -10
- package/bin/pool/ci-autoscale.mjs +160 -0
- package/bin/pool/cli.mjs +53 -9
- package/bin/pool/docker.mjs +3 -0
- package/bin/pool/engine-placement.test.mjs +94 -0
- package/bin/pool/lane-target.mjs +41 -0
- package/bin/pool/lane-tools.mjs +26 -0
- package/bin/pool/lane-tools.test.mjs +9 -0
- package/bin/pool/mirror-seed.mjs +15 -11
- package/bin/pool/router.mjs +88 -32
- package/bin/pool/version.mjs +29 -2
- package/bin/review-staging.mjs +11 -3
- package/bin/runner.mjs +59 -11
- package/bin/stats/attempts.mjs +54 -0
- package/bin/stats/attempts.test.mjs +30 -0
- package/bin/stats/churn.mjs +49 -0
- package/bin/stats/churn.test.mjs +31 -0
- package/bin/stats/index.mjs +11 -3
- package/bin/stats/release.mjs +7 -0
- package/bin/stats/release.test.mjs +20 -0
- package/bin/stats/scorecard.mjs +187 -0
- package/bin/stats/scorecard.test.mjs +89 -0
- package/commands/orchestrate.md +21 -18
- package/docs/CONFIG.md +41 -0
- package/docs/OUTCOME-CODES.md +2 -0
- package/docs/STATS.md +17 -0
- package/package.json +1 -1
- package/pool/image/Dockerfile +14 -2
- package/pool/image/manifest.json +25 -0
- package/pool/image/mirror.sh +11 -2
- package/pool/install/install-agent.ps1 +11 -4
- package/scripts/check-devdocs-freshness.sh +1 -1
- package/scripts/ci-local/adapters/github-actions.mjs +8 -0
- package/scripts/ci-local/cli.mjs +1 -1
- package/scripts/ci-local/plan.mjs +3 -2
- package/scripts/ci-local.test.sh +11 -0
- package/scripts/failure-census.mjs +67 -0
- package/scripts/review-finalize.sh +5 -5
- package/scripts/review-finalize.test.sh +8 -1
- package/scripts/verify-phase-trail.sh +11 -0
- package/scripts/verify-phase-trail.test.sh +9 -0
package/bin/pool/agent.mjs
CHANGED
|
@@ -16,10 +16,24 @@ import { makeWarm } from "./warm.mjs";
|
|
|
16
16
|
import { resolveLaneImage, laneImageNow, laneToolsTag, isLaneToolsTagOf } from "./lane-tools.mjs";
|
|
17
17
|
import { hostDiskFree, hostMemFree, ensureNatPin, netState } from "./health.mjs";
|
|
18
18
|
import { laneDiskUsedGb, planDiskCap, fstrimDue, runFstrim } from "./disk.mjs";
|
|
19
|
+
import { step as laneStep, drainState, pressured } from "./lane-target.mjs";
|
|
19
20
|
import { makeMirrorSeed, dockerRunner } from "./mirror-seed.mjs";
|
|
20
21
|
import { planIdleEviction, CACHE_LABEL, agentLabel } from "./cache-sweep.mjs";
|
|
22
|
+
import { cpuQuotaEnv } from "./docker.mjs";
|
|
21
23
|
|
|
22
24
|
const LABEL = "computeshare=1";
|
|
25
|
+
/** #5695: ephemeral CI runner containers; a different label than LABEL so the orphan reaper never removes them. */
|
|
26
|
+
const RUNNER_LABEL = "computeshare.runner=1";
|
|
27
|
+
const RUNNER_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
28
|
+
const netSample = { at: 0, rx: 0 };
|
|
29
|
+
/** Host RX rate in MB/s since the previous call (null on the first call or when /proc/net/dev is unreadable). */
|
|
30
|
+
export function netRx(now = Date.now(), read = () => readFileSync("/proc/net/dev", "utf8")) {
|
|
31
|
+
try {
|
|
32
|
+
const rx = read().split("\n").slice(2).map((l) => l.trim().split(/[:\s]+/)).filter((c) => c[0] && c[0] !== "lo").reduce((a, c) => a + (Number(c[1]) || 0), 0);
|
|
33
|
+
const prev = { ...netSample }; netSample.at = now; netSample.rx = rx;
|
|
34
|
+
return prev.at && now > prev.at && rx >= prev.rx ? { rx_mbps: Math.round(((rx - prev.rx) / 1e6 / ((now - prev.at) / 1000)) * 100) / 100 } : null;
|
|
35
|
+
} catch { return null; }
|
|
36
|
+
}
|
|
23
37
|
const LOG_CHUNK = 256 * 1024;
|
|
24
38
|
const run = promisify(execFile);
|
|
25
39
|
|
|
@@ -172,7 +186,8 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
172
186
|
if (rows.length < (cfg.estimate_min_samples ?? 3)) return { cpus: slice.cpus, mem: slice.mem, samples: rows.length };
|
|
173
187
|
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
188
|
}
|
|
175
|
-
const
|
|
189
|
+
const runners = () => (store.data.runners ??= {}); // #5695: name -> {label, cpus, mem_gb, startedAt}; counted like a lane
|
|
190
|
+
const used = () => Object.values({ ...sb(), ...Object.fromEntries(Object.entries(runners()).map(([k, r]) => [`runner:${k}`, { cpus: r.cpus, mem_gb: r.mem_gb }])) }).filter((s) => s.state !== "exited").reduce((a, s) => ({ cpus: a.cpus + s.cpus, mem: a.mem + s.mem_gb }), { cpus: 0, mem: 0 });
|
|
176
191
|
// #5535: disk figures for the router inventory; optional, omitted when unreadable. Sandbox dirs are walked at most every 60s.
|
|
177
192
|
let diskCache = { at: 0, mb: {} };
|
|
178
193
|
let lastWorkSweep = -Infinity;
|
|
@@ -263,7 +278,55 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
263
278
|
const PRIORITIES = ["reserved", "normal", "borrow"];
|
|
264
279
|
const reservations = () => (Array.isArray(cfg.reservations) ? cfg.reservations.filter((r) => r && typeof r.name === "string" && r.cpus > 0 && r.mem_gb > 0) : []);
|
|
265
280
|
const prioOf = (r) => r.priority ?? "normal";
|
|
266
|
-
const
|
|
281
|
+
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 });
|
|
282
|
+
// #6047: heavy tokens (cfg.elastic_lanes, default off). A lane is admitted on its base reservation; each heavy step leases a token
|
|
283
|
+
// (weight = max(default, p90 history - base)) from this host's pool. Tokens live in store.data.heavy and expire with their lease,
|
|
284
|
+
// when the sandbox exits or when it is destroyed.
|
|
285
|
+
const elastic = () => cfg.elastic_lanes === true;
|
|
286
|
+
const heavyTtlMs = () => (cfg.heavy_ttl_s ?? 300) * 1000;
|
|
287
|
+
const heavyDefault = () => ({ cpus: cfg.heavy_weight?.cpus ?? 1, mem: cfg.heavy_weight?.mem_gb ?? 2 });
|
|
288
|
+
const heavyTokens = () => (store.data.heavy ??= {});
|
|
289
|
+
function heavyHeld() {
|
|
290
|
+
let dropped = false;
|
|
291
|
+
for (const [k, t] of Object.entries(heavyTokens())) { const r = sb()[t.sandbox]; if (t.expires <= now() || !r || r.state === "exited") { delete heavyTokens()[k]; dropped = true; } }
|
|
292
|
+
if (dropped) store.save();
|
|
293
|
+
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 });
|
|
294
|
+
}
|
|
295
|
+
const baseUse = () => activeRecs().reduce((a, r) => ({ cpus: a.cpus + r.cpus, mem: a.mem + r.mem_gb }), { cpus: 0, mem: 0 });
|
|
296
|
+
/** Elastic: base reservations plus held tokens; flat: each lane's projected peak (#5858). */
|
|
297
|
+
const projectedUse = () => { if (!elastic()) return peakUse(); const b = baseUse(), h = heavyHeld(); return { cpus: b.cpus + h.cpus, mem: b.mem + h.mem }; };
|
|
298
|
+
/** Lane ceiling derived from the token pool when elastic: a multiple of the default-weight heavy steps the host holds. */
|
|
299
|
+
function derivedCeiling() {
|
|
300
|
+
const e = effectiveCapacity(), w = heavyDefault();
|
|
301
|
+
return Math.max(1, Math.floor(Math.min((e.cpus - coTenant.cpus) / w.cpus, (e.mem - coTenant.mem_gb) / w.mem) * (cfg.elastic_lane_factor ?? 3)));
|
|
302
|
+
}
|
|
303
|
+
function heavyAcquire(r) {
|
|
304
|
+
const held = heavyHeld(), mine = Object.entries(heavyTokens()).find(([, t]) => t.sandbox === r.id);
|
|
305
|
+
const ttl = Math.round(heavyTtlMs() / 1000);
|
|
306
|
+
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 } }; }
|
|
307
|
+
const est = estimateFor(r.repo ?? null, { cpus: r.cpus, mem: r.mem_gb }), d = heavyDefault();
|
|
308
|
+
const w = { cpus: Math.max(d.cpus, est.cpus - r.cpus), mem: Math.max(d.mem, est.mem - r.mem_gb) };
|
|
309
|
+
const e = effectiveCapacity(), b = baseUse(), live_ = live(cfg), ram = Number.isFinite(live_?.mem_available_gb) ? live_.mem_available_gb : Infinity;
|
|
310
|
+
const fits = b.cpus + held.cpus + w.cpus <= e.cpus - coTenant.cpus + 1e-9 && b.mem + held.mem + w.mem <= e.mem - coTenant.mem_gb + 1e-9 && w.mem <= ram + 1e-9;
|
|
311
|
+
if (held.n > 0 && !fits) return { status: 200, body: { granted: false, retry_after_s: 15, held: held.n } }; // the first holder always runs: a step larger than the host must not starve
|
|
312
|
+
const token = randomBytes(12).toString("hex");
|
|
313
|
+
heavyTokens()[token] = { sandbox: r.id, cpus: w.cpus, mem: w.mem, at: now(), refs: 1, expires: now() + heavyTtlMs() };
|
|
314
|
+
store.save();
|
|
315
|
+
return { status: 200, body: { granted: true, token, ttl_s: ttl, weight: { cpus: w.cpus, mem_gb: w.mem } } };
|
|
316
|
+
}
|
|
317
|
+
function heavyTouch(r, action, token) {
|
|
318
|
+
heavyHeld();
|
|
319
|
+
const t = heavyTokens()[token];
|
|
320
|
+
if (!t || t.sandbox !== r.id) return { status: 200, body: { ok: action === "release", granted: false } };
|
|
321
|
+
if (action === "release") { if ((t.refs = (t.refs ?? 1) - 1) <= 0) delete heavyTokens()[token]; } else t.expires = now() + heavyTtlMs();
|
|
322
|
+
store.save();
|
|
323
|
+
return { status: 200, body: { ok: true, granted: action === "renew" } };
|
|
324
|
+
}
|
|
325
|
+
function heavyView() {
|
|
326
|
+
if (!elastic()) return {};
|
|
327
|
+
const h = heavyHeld(), e = effectiveCapacity(), b = baseUse();
|
|
328
|
+
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() };
|
|
329
|
+
}
|
|
267
330
|
const sumRecs = (rs) => rs.reduce((a, s) => ({ cpus: a.cpus + s.cpus, mem: a.mem + s.mem_gb }), { cpus: 0, mem: 0 });
|
|
268
331
|
const weighted = () => reservations().length > 0 || Boolean(cfg.idle_only);
|
|
269
332
|
const SHARES = () => ({ reserved: 4096, normal: 1024, borrow: 128, throttled: 2, ...(cfg.cpu_shares ?? {}) });
|
|
@@ -343,9 +406,12 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
343
406
|
}
|
|
344
407
|
/** #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. */
|
|
345
408
|
let policyPaused = Boolean(cfg.policy_paused);
|
|
409
|
+
const laneS = { target: null, greenSince: null, busySince: null };
|
|
410
|
+
const laneTargetOn = () => cfg.lane_autoscale !== false && Number.isInteger(cfg.max_lanes) && cfg.max_lanes >= 1;
|
|
411
|
+
const laneNow = () => laneS.target ?? Math.min(cfg.max_lanes, cfg.lane_start ?? 1);
|
|
346
412
|
function applyPolicy(body) {
|
|
347
413
|
const p = body && typeof body === "object" ? body : {}, int = (v, lo, hi) => (Number.isInteger(v) && v >= lo && v <= hi);
|
|
348
|
-
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")
|
|
414
|
+
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") || (p.elastic_lanes !== undefined && typeof p.elastic_lanes !== "boolean")
|
|
349
415
|
|| (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" } };
|
|
350
416
|
const set = {};
|
|
351
417
|
if (p.cpus !== undefined) set.allow_cpus = p.cpus;
|
|
@@ -353,6 +419,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
353
419
|
if (p.idle_only !== undefined) set.idle_only = p.idle_only;
|
|
354
420
|
if (p.floors?.host_disk_gb !== undefined) set.host_disk_floor_gb = p.floors.host_disk_gb;
|
|
355
421
|
if (p.paused !== undefined) set.policy_paused = p.paused;
|
|
422
|
+
if (p.elastic_lanes !== undefined) set.elastic_lanes = p.elastic_lanes;
|
|
356
423
|
if (cfg.config_path) {
|
|
357
424
|
try { const c = JSON.parse(readFileSync(cfg.config_path, "utf8")); writeFileSync(cfg.config_path, JSON.stringify({ ...c, ...set }, null, 2), { mode: 0o600 }); }
|
|
358
425
|
catch (e) { log.warn?.(`policy not persisted: ${e.message}`); }
|
|
@@ -374,7 +441,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
374
441
|
const active = Object.values(sb()).filter((s) => s.state !== "exited").length;
|
|
375
442
|
const e = effectiveCapacity();
|
|
376
443
|
const h = live(cfg);
|
|
377
|
-
return { host: cfg.name ?? hostname(), ...running, vm: e.vm, ...(pendingResize ? { pending_resize: { cpus: pendingResize.cpus, mem_gb: pendingResize.mem_gb } } : {}), upgrading: upgrade.state, ...(upgrade.log && upgrade.state === "failed" ? { upgrade_log: upgrade.log } : {}), ...(upgrade.error ? { upgrade_error: upgrade.error } : {}), ...(prepull.error ? { prepull_error: prepull.error } : {}), ...(cacheErr.size ? { cache_sweep_error: [...cacheErr.values()][0] } : {}), ...(cacheInfo.size ? { cache_volumes: Object.fromEntries([...cacheInfo].map(([v, i]) => [v, { size_gb: Math.round(i.size_bytes / 107374182.4) / 10, ...(i.depcache_bytes ? { depcache_gb: Object.fromEntries(Object.entries(i.depcache_bytes).map(([k, b]) => [k, Math.round(b / 107374182.4) / 10])) } : {}) }])) } : {}), cpus_total: e.cpus, mem_total_gb: e.mem, cpus_free: r2(e.cpus - u.cpus - coTenant.cpus), mem_free_gb: r2(e.mem - u.mem - coTenant.mem_gb), configured: { cpus: cfg.allow_cpus, mem_gb: cfg.allow_mem_gb }, clamped: e.clamped, ...(coTenant.cpus || coTenant.mem_gb ? { cotenant: { cpus: r2(coTenant.cpus), mem_gb: r2(coTenant.mem_gb) } } : {}), active, ...priorityView(), ...throttleView(h), ...diskView(), ...laneDiskView(), ...hostDiskView(active), ...hostMemView(), 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 }])) };
|
|
444
|
+
return { host: cfg.name ?? hostname(), ...running, vm: e.vm, ...(pendingResize ? { pending_resize: { cpus: pendingResize.cpus, mem_gb: pendingResize.mem_gb } } : {}), upgrading: upgrade.state, ...(upgrade.log && upgrade.state === "failed" ? { upgrade_log: upgrade.log } : {}), ...(upgrade.error ? { upgrade_error: upgrade.error } : {}), ...(prepull.error ? { prepull_error: prepull.error } : {}), ...(cacheErr.size ? { cache_sweep_error: [...cacheErr.values()][0] } : {}), ...(cacheInfo.size ? { cache_volumes: Object.fromEntries([...cacheInfo].map(([v, i]) => [v, { size_gb: Math.round(i.size_bytes / 107374182.4) / 10, ...(i.depcache_bytes ? { depcache_gb: Object.fromEntries(Object.entries(i.depcache_bytes).map(([k, b]) => [k, Math.round(b / 107374182.4) / 10])) } : {}) }])) } : {}), cpus_total: e.cpus, mem_total_gb: e.mem, cpus_free: r2(e.cpus - u.cpus - coTenant.cpus), mem_free_gb: r2(e.mem - u.mem - coTenant.mem_gb), configured: { cpus: cfg.allow_cpus, mem_gb: cfg.allow_mem_gb }, clamped: e.clamped, ...(coTenant.cpus || coTenant.mem_gb ? { cotenant: { cpus: r2(coTenant.cpus), mem_gb: r2(coTenant.mem_gb) } } : {}), active, ...priorityView(), ...throttleView(h), ...diskView(), ...laneDiskView(), ...hostDiskView(active), ...hostMemView(), ...heavyView(), runners: Object.entries(runners()).map(([name, r]) => ({ name, label: r.label })), net: (() => { const rx = netRx(now()); const n = readNet(); return rx ? { ...(n ?? {}), ...rx } : n; })(), paused: Boolean(cfg.paused || ownerPaused || policyPaused), owner_paused: ownerPaused, ...laneTargetView(), ...(Number.isFinite(h?.load_per_core) ? { load_per_core: h.load_per_core } : {}), ...(Number.isFinite(h?.mem_available_gb) ? { mem_available_gb: h.mem_available_gb } : {}), live: h, usage: Object.fromEntries(Object.values(sb()).filter((r) => r.usage?.samples).map((r) => [r.issue ?? r.id, { ...usageView(r), state: r.state }])) };
|
|
378
445
|
}
|
|
379
446
|
|
|
380
447
|
/** The image a spec's lanes run (the per-repo lane_tools tag when tools are listed), without building it. */
|
|
@@ -391,6 +458,36 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
391
458
|
return Promise.resolve().then(() => docker.run(args)).then(() => log.info?.(`env snapshot helper started for ${spec.repo.slug}`), (e) => log.warn?.(`env snapshot helper: ${String(e.stderr || e.message).slice(0, 200)}`));
|
|
392
459
|
}
|
|
393
460
|
|
|
461
|
+
/** #5695: start one --ephemeral runner from a JIT config (one job, then the container exits and --rm removes it). */
|
|
462
|
+
async function startRunner({ name, label, jitconfig, cpus = 1, mem_gb = 2 } = {}) {
|
|
463
|
+
if (typeof name !== "string" || !RUNNER_NAME.test(name) || typeof label !== "string" || !RUNNER_NAME.test(label) || typeof jitconfig !== "string" || !/^[A-Za-z0-9+/=_-]+$/.test(jitconfig)) throw Object.assign(new Error("name, label and jitconfig are required"), { status: 400 });
|
|
464
|
+
if (!(cpus > 0 && mem_gb > 0)) throw Object.assign(new Error("cpus and mem_gb must be positive"), { status: 400 });
|
|
465
|
+
if (runners()[name]) return { status: 200, body: { name, state: "running" } };
|
|
466
|
+
const c = capacity();
|
|
467
|
+
if (c.paused || c.cpus_free < cpus || c.mem_free_gb < mem_gb) return { status: 503, body: { error: "no capacity", capacity: c }, retryAfter: 60 };
|
|
468
|
+
const dir = join(stateDir, "runners");
|
|
469
|
+
mkdirSync(dir, { recursive: true });
|
|
470
|
+
const envFile = join(dir, `${name}.env`); // the JIT config is a credential: an 0600 env file, never argv
|
|
471
|
+
writeFileSync(envFile, `ACTIONS_RUNNER_INPUT_JITCONFIG=${jitconfig}\n`, { mode: 0o600 });
|
|
472
|
+
try {
|
|
473
|
+
await docker.run(["--rm", "--name", `cs-runner-${name}`.slice(0, 120), "--label", RUNNER_LABEL, "--label", `computeshare.runner.label=${label}`, "--cpus", String(cpus), "--memory", `${Math.round(mem_gb * 1024)}m`, "--env-file", envFile, cfg.runner_image ?? "ghcr.io/actions/actions-runner:latest", "/home/runner/run.sh"]);
|
|
474
|
+
} finally { rmSync(envFile, { force: true }); }
|
|
475
|
+
runners()[name] = { label, cpus, mem_gb, startedAt: now() }; store.save();
|
|
476
|
+
return { status: 201, body: { name, state: "running" } };
|
|
477
|
+
}
|
|
478
|
+
async function stopRunner(name) {
|
|
479
|
+
if (!runners()[name]) return false;
|
|
480
|
+
try { await docker.remove(`cs-runner-${name}`.slice(0, 120)); } catch { /* already gone */ }
|
|
481
|
+
delete runners()[name]; store.save();
|
|
482
|
+
return true;
|
|
483
|
+
}
|
|
484
|
+
/** Forget runners whose container exited (an ephemeral runner ends after its job). */
|
|
485
|
+
async function sweepRunners() {
|
|
486
|
+
if (!Object.keys(runners()).length) return;
|
|
487
|
+
const live = new Set(await docker.listLabelled(RUNNER_LABEL));
|
|
488
|
+
for (const n of Object.keys(runners())) if (!live.has(`cs-runner-${n}`.slice(0, 120)) && now() - runners()[n].startedAt > 60000) delete runners()[n];
|
|
489
|
+
store.save();
|
|
490
|
+
}
|
|
394
491
|
/** cgroup cpu weight per class (docker --cpu-shares); a borrowed lane yields to a reserved one under contention. */
|
|
395
492
|
const sharesArgs = (prio) => (weighted() ? ["--cpu-shares", String(SHARES()[prio])] : []);
|
|
396
493
|
|
|
@@ -403,7 +500,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
403
500
|
} });
|
|
404
501
|
const seedFail = (e) => { if (e.status) throw Object.assign(new Error(e.message), { status: e.status, body: { error: e.message, ...(e.extra ?? {}) } }); throw e; };
|
|
405
502
|
|
|
406
|
-
async function launch({ spec, cpus, mem_gb, limit = null }) {
|
|
503
|
+
async function launch({ spec, cpus, mem_gb, limit = null, max_lanes = null }) {
|
|
407
504
|
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 });
|
|
408
505
|
let existing = own(spec.id);
|
|
409
506
|
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
|
|
@@ -417,6 +514,8 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
417
514
|
const c = capacity();
|
|
418
515
|
const h = live(cfg);
|
|
419
516
|
const adm = admit({ prio, cpus, mem_gb, reservation, h });
|
|
517
|
+
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
|
|
518
|
+
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 };
|
|
420
519
|
if (c.paused || adm.refuse) {
|
|
421
520
|
const f = adm.refuse ?? {};
|
|
422
521
|
if (f.status === 400) return { status: 400, body: { error: f.error } };
|
|
@@ -425,11 +524,12 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
425
524
|
// Burst model: reservations are small, so also refuse when the VM is genuinely short of memory or overloaded right now.
|
|
426
525
|
// A reserved launch skips the load gate: it must never be refused because lanes are busy (they are throttled/drained below).
|
|
427
526
|
if (prio !== "reserved") { // #5858: ramp-aware: the admitted lanes' projected peaks plus this one must fit, however low the load is right now
|
|
428
|
-
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);
|
|
527
|
+
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);
|
|
429
528
|
const availMem = e.mem - coTenant.mem_gb, availCpus = e.cpus - coTenant.cpus;
|
|
430
529
|
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 };
|
|
431
530
|
}
|
|
432
|
-
if (
|
|
531
|
+
if (elastic() && prio !== "reserved" && !Number.isInteger(max_lanes) && activeRecs().length >= derivedCeiling()) return { status: 503, body: { error: `derived lane ceiling ${derivedCeiling()} reached`, code: "pool.host_lane_ceiling", capacity: c }, retryAfter: 60 };
|
|
532
|
+
if (!h.ok && prio !== "reserved") return { status: 503, body: { error: `host busy: ${h.reason}`, code: "pool.host_load", live: h }, retryAfter: 60 };
|
|
433
533
|
const gate = hostDiskView(c.active, spec.repo?.slug ?? null);
|
|
434
534
|
if (gate.host_disk_low) { // #5733: before any mkdir or docker run; the lane defers on the 503 (SANDBOX_CAPACITY)
|
|
435
535
|
const floor = floorGb();
|
|
@@ -461,7 +561,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
461
561
|
const envFile = join(dir, "env");
|
|
462
562
|
const credToken = randomBytes(24).toString("hex");
|
|
463
563
|
const withDocker = Boolean(spec.docker);
|
|
464
|
-
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),
|
|
564
|
+
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),
|
|
465
565
|
...(spec.env_snapshots?.enabled ? { FORGE_ENV_IMAGE: envImageOf(spec) } : {}) }; // the image is part of the snapshot key
|
|
466
566
|
writeFileSync(envFile, Object.entries(env).map(([k, v]) => envLine(k, v)).join("\n") + "\n", { mode: 0o600 });
|
|
467
567
|
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 } : {}) } : {}) };
|
|
@@ -506,6 +606,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
506
606
|
// Hard burst cap per container; the (smaller) reservation is only what placement counts.
|
|
507
607
|
// --memory-swap above --memory lets a rare spike page out instead of being OOM-killed (swap deal).
|
|
508
608
|
"--cpus", String(laneCpus), ...sharesArgs(prio), "--memory", mb(laneMem), "--memory-swap", mb(laneMem + swapFor(limit?.lane_swap_gb)), "--pids-limit", "4096",
|
|
609
|
+
"--init", // lane-compute audit 2026-11-26: PID 1 never reaped children (72–1408 zombies/lane in 17 min; the worst lane would reach the 4096 pid limit in ~50 min)
|
|
509
610
|
"--env-file", envFile, ...laneNet, ...work,
|
|
510
611
|
...(spec.claim_dir ? ["-v", `${join(dir, "claim")}:/claim`] : []), // #4912: warm sandboxes receive their lane here
|
|
511
612
|
...(withDocker ? [] : cacheMount), "-v", `${join(dir, "result")}:/result`, "-v", `${join(dir, "out")}:/csout`,
|
|
@@ -748,6 +849,25 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
748
849
|
if (!r.ok) log.warn?.(`fstrim: ${r.error}`);
|
|
749
850
|
}
|
|
750
851
|
|
|
852
|
+
// #6061: per-worker lane target, evaluated once per reap. Active only with an integer cfg.max_lanes (the ceiling) unless cfg.lane_autoscale is false.
|
|
853
|
+
// Draining refuses new launches only; running lanes are never stopped here (drainOne stays for idle_only borrowed lanes).
|
|
854
|
+
function laneDrain() {
|
|
855
|
+
const paused = Boolean(cfg.paused || ownerPaused || policyPaused);
|
|
856
|
+
return drainState({ paused, ownerPaused, policyPaused, busyForMs: laneS.busySince === null ? 0 : now() - laneS.busySince, drainAfterMs: (cfg.drain_busy_s ?? 300) * 1000 });
|
|
857
|
+
}
|
|
858
|
+
function laneTargetView() {
|
|
859
|
+
const d = laneDrain();
|
|
860
|
+
return { draining: d.draining, ...(d.reason ? { draining_reason: d.reason } : {}), accepting: !d.draining, ...(laneTargetOn() ? { lane_target: laneNow(), lane_ceiling: cfg.max_lanes } : {}) };
|
|
861
|
+
}
|
|
862
|
+
function laneTick() {
|
|
863
|
+
const h = live(cfg), t = now();
|
|
864
|
+
laneS.busySince = pressured(h) ? (laneS.busySince ?? t) : null;
|
|
865
|
+
if (!laneTargetOn()) { laneS.target = null; return; }
|
|
866
|
+
const r = laneStep({ target: laneNow(), ceiling: cfg.max_lanes, live: h, now: t, greenSince: laneS.greenSince, holdMs: (cfg.lane_hold_s ?? 60) * 1000 });
|
|
867
|
+
laneS.target = r.target; laneS.greenSince = r.greenSince;
|
|
868
|
+
if (r.change) log.info?.(`lane target ${r.change} to ${r.target}/${cfg.max_lanes}`);
|
|
869
|
+
}
|
|
870
|
+
|
|
751
871
|
async function reap() {
|
|
752
872
|
const t = now();
|
|
753
873
|
for (const r of Object.values(sb())) {
|
|
@@ -759,8 +879,10 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
759
879
|
await hostMemPressure(t); // #5967
|
|
760
880
|
const known = new Set(Object.values(sb()).flatMap((r) => [r.name, dindName(r.name)]));
|
|
761
881
|
for (const name of await docker.listLabelled(OWN)) if (!known.has(name)) { await docker.remove(name); log.info?.(`removed orphan container ${name}`); }
|
|
882
|
+
await sweepRunners().catch((e) => log.warn?.(`runner sweep: ${e.message}`));
|
|
762
883
|
await sampleUsage();
|
|
763
884
|
await reclaimIdle();
|
|
885
|
+
laneTick(); // #6061
|
|
764
886
|
await warm.maintain(maxLifeMs);
|
|
765
887
|
if (pendingResize && capacity().active === 0) {
|
|
766
888
|
const r = await resize(pendingResize);
|
|
@@ -844,7 +966,10 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
844
966
|
if (want.image !== running.image || want.version !== running.version) {
|
|
845
967
|
const nextImage = cfg.image && cfg.image !== "computeshare-lane:1" ? cfg.image : laneImageTag(want.version);
|
|
846
968
|
log.info?.(`rebuilding ${nextImage} (${running.version}/${running.image} -> ${want.version}/${want.image})`);
|
|
847
|
-
|
|
969
|
+
// 2026-11-26: a host pre-seeded with the image (docker load from another host) skips the build: on a slow or memory-tight
|
|
970
|
+
// host the build itself is the risk (an upgrade build coincided with a host crash)
|
|
971
|
+
if (await docker.hasImage?.(nextImage)) log.info?.(`${nextImage} already present; no build`);
|
|
972
|
+
else await buildWithRetry(() => docker.build(join(next, "pool", "image"), nextImage, laneBuildArgs(want.version)), { log }); // #5919
|
|
848
973
|
}
|
|
849
974
|
await pruneLaneImages([laneImageTag(want.version)]);
|
|
850
975
|
await prepullImages();
|
|
@@ -948,10 +1073,12 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
948
1073
|
|
|
949
1074
|
const routes = [
|
|
950
1075
|
[route("GET", "/health"), async () => ({ status: 200, body: { ok: true, ...capacity() } })],
|
|
951
|
-
[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
|
|
1076
|
+
[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"), uploader: url.searchParams.get("uploader") }).catch(seedFail) })], // #5949
|
|
952
1077
|
[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 ?? {}) } }; } }],
|
|
953
1078
|
[route("GET", "/capacity"), async () => ({ status: 200, body: capacity() })],
|
|
954
1079
|
[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; }],
|
|
1080
|
+
[route("POST", "/runners"), async (_p, body) => startRunner(body ?? {})], // #5695
|
|
1081
|
+
[route("DELETE", "/runners/:name"), async ({ name }) => ((await stopRunner(name)) ? { status: 200, body: { ok: true } } : { status: 404, body: { state: "gone" } })],
|
|
955
1082
|
[route("GET", "/warm"), async () => ({ status: 200, body: { warm: warm.list() } })],
|
|
956
1083
|
[route("POST", "/warm"), async (_p, body) => { const r = warm.configure({ ...(body ?? {}), n: body?.n }); await warm.replenish(); return { status: 200, body: { ...r, warm: warm.list() } }; }],
|
|
957
1084
|
[route("POST", "/warm/claim"), async (_p, body) => warm.claim(body ?? {})],
|
|
@@ -989,6 +1116,13 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
989
1116
|
if (cred) { const r = await sandboxCred(decodeURIComponent(cred[1]), cred[2], req); return send(res, r.status, r.body, r.retryAfter ? { "retry-after": String(r.retryAfter) } : {}); }
|
|
990
1117
|
const limited = req.method === "POST" && /^\/sandboxes\/([^/]+)\/creds\/claude\/limited$/.exec(url.pathname); // #5205
|
|
991
1118
|
if (limited) { const r = await sandboxCredLimited(decodeURIComponent(limited[1]), req, await readJson(req)); return send(res, r.status, r.body); }
|
|
1119
|
+
const heavy = req.method === "POST" && /^\/sandboxes\/([^/]+)\/heavy\/(acquire|release|renew)$/.exec(url.pathname); // #6047
|
|
1120
|
+
if (heavy) {
|
|
1121
|
+
const id = decodeURIComponent(heavy[1]);
|
|
1122
|
+
if (!sandboxAuthed(id, req)) return send(res, SANDBOX_UNAUTHORIZED.status, SANDBOX_UNAUTHORIZED.body);
|
|
1123
|
+
const body = await readJson(req, 4096), r0 = own(id), r = heavy[2] === "acquire" ? heavyAcquire(r0) : heavyTouch(r0, heavy[2], body?.token);
|
|
1124
|
+
return send(res, r.status, r.body);
|
|
1125
|
+
}
|
|
992
1126
|
const relay = (req.method === "POST" && /^\/sandboxes\/([^/]+)\/relay$/.exec(url.pathname)) || (req.method === "GET" && /^\/sandboxes\/([^/]+)\/relay\/([^/]+)$/.exec(url.pathname));
|
|
993
1127
|
if (relay) { const r = await sandboxRelay(decodeURIComponent(relay[1]), relay[2] ? decodeURIComponent(relay[2]) : null, req); return send(res, r.status, r.body ?? {}); }
|
|
994
1128
|
if (url.pathname !== "/health" && !bearerOk(req, cfg.token)) return send(res, 401, { error: "unauthorized", hop: "agent", reason: "agent auth: router token rejected by agent" });
|
package/bin/pool/cache-sweep.mjs
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// itself runs inside a short-lived container of the lane image with the cache volume on /cache. The agent ships this
|
|
5
5
|
// file's source in CS_CACHE_SWEEP_SRC and the options in CS_CACHE_SWEEP_OPTS; the JSON result goes to stdout.
|
|
6
6
|
import { execFileSync } from "node:child_process";
|
|
7
|
-
import { existsSync, readFileSync, rmSync } from "node:fs";
|
|
7
|
+
import { existsSync, readFileSync, rmSync, statSync } from "node:fs";
|
|
8
8
|
import { join } from "node:path";
|
|
9
9
|
|
|
10
10
|
export const CACHE_LABEL = "computeshare.cache=1";
|
|
@@ -15,6 +15,7 @@ export const PACKAGE_STORES = ["pnpm-store", ...["pnpm-store", "npm-cache", "uv-
|
|
|
15
15
|
/** #5881: owner label; the reaper and sweeps touch only containers and volumes carrying their own agent's label. */
|
|
16
16
|
export const agentLabel = (id) => `computeshare.agent=${id}`;
|
|
17
17
|
const DAY = 86400000;
|
|
18
|
+
const LOCK_LIVE_MS = 2 * 3600000; // a depcache key lock younger than this may belong to a running install or lane
|
|
18
19
|
|
|
19
20
|
/**
|
|
20
21
|
* Oldest-first deletion plan to bring `entries` ({path, bytes, mtimeMs, live}) under `capBytes`. Live entries (the work
|
|
@@ -55,22 +56,42 @@ const sizeOf = (p) => (Number(sh("du", ["-sk", p]).split(/\s/)[0]) || 0) * 1024;
|
|
|
55
56
|
const kids = (dir) => sh("find", [dir, "-mindepth", "1", "-maxdepth", "1", "-printf", "%p\t%T@\n"]).split("\n").filter(Boolean).map((l) => { const i = l.lastIndexOf("\t"); return { path: l.slice(0, i), mtimeMs: Number(l.slice(i + 1)) * 1000 }; });
|
|
56
57
|
|
|
57
58
|
const SNAP = /^[a-z]+-[0-9a-f]{16}$/;
|
|
59
|
+
const num = (p) => { try { const n = Number(readFileSync(p, "utf8").trim()); return Number.isFinite(n) && n > 0 ? n : null; } catch { return null; } };
|
|
60
|
+
const mtimeOf = (p) => { try { return statSync(p).mtimeMs; } catch { return null; } };
|
|
61
|
+
/** #5898: a snapshot is in use while its `<snap>.lock` is younger than LOCK_LIVE_MS (the container cannot check pids). */
|
|
62
|
+
const lockLive = (p, now) => { const m = mtimeOf(`${p}.lock`); return m !== null && now - m < LOCK_LIVE_MS; };
|
|
58
63
|
/** Last use of a depcache snapshot: its `last-used` file (epoch ms, written on every hit), else the directory mtime. */
|
|
59
|
-
const snapLastUsed = (k) => {
|
|
64
|
+
const snapLastUsed = (k) => {
|
|
65
|
+
let created = null;
|
|
66
|
+
try { created = Number(JSON.parse(readFileSync(join(k.path, "manifest.json"), "utf8")).created) || null; } catch { /* no manifest */ }
|
|
67
|
+
return num(join(k.path, "last-used")) ?? created ?? k.mtimeMs;
|
|
68
|
+
};
|
|
69
|
+
/** Every depcache snapshot as {path, lastUsedMs, live}; last use falls back to manifest `created`, then mtime. */
|
|
70
|
+
function depcacheSnaps(dc, now) {
|
|
71
|
+
const out = [];
|
|
72
|
+
for (const repo of kids(dc)) {
|
|
73
|
+
if (repo.path.endsWith("/stores")) continue;
|
|
74
|
+
for (const k of kids(repo.path)) {
|
|
75
|
+
if (!SNAP.test(k.path.slice(repo.path.length + 1))) continue;
|
|
76
|
+
out.push({ ...k, lastUsedMs: snapLastUsed(k), live: lockLive(k.path, now) });
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
60
81
|
|
|
61
82
|
/**
|
|
62
83
|
* #5901: depcache is `<dc>/<repoKey>/<eco>-<key>/`. Each snapshot (not the repo dir, whose mtime moves with every new
|
|
63
84
|
* snapshot) ages out by its last use and is trimmed least-recently-used past the per-repo cap. A snapshot with a lock file
|
|
64
85
|
* is in use and kept. Fills `depcacheBytes[repoKey]` with what remains.
|
|
65
86
|
*/
|
|
66
|
-
function sweepDepcache(dc, { cutoff, capBytes, rm, depcacheBytes }) {
|
|
87
|
+
function sweepDepcache(dc, { cutoff, now, capBytes, rm, depcacheBytes }) {
|
|
67
88
|
for (const repo of kids(dc)) {
|
|
68
89
|
const rk = repo.path.slice(dc.length + 1);
|
|
69
90
|
if (rk === "stores") continue;
|
|
70
|
-
if (SNAP.test(rk)) { if (repo
|
|
91
|
+
if (SNAP.test(rk)) { if (snapLastUsed(repo) < cutoff && !lockLive(repo.path, now)) rm(repo.path); continue; } // an entry of the flat layout (no repo level)
|
|
71
92
|
let snaps = kids(repo.path).filter((k) => SNAP.test(k.path.slice(repo.path.length + 1)));
|
|
72
|
-
const
|
|
73
|
-
snaps = snaps.map((k) => ({ ...k, lastUsedMs: snapLastUsed(k), live:
|
|
93
|
+
for (const k of kids(repo.path)) if (/\.(tmp-\d+|lock)$/.test(k.path) && k.mtimeMs < cutoff) rm(k.path); // dead publishers' tmp dirs, old locks
|
|
94
|
+
snaps = snaps.map((k) => ({ ...k, lastUsedMs: snapLastUsed(k), live: lockLive(k.path, now) }));
|
|
74
95
|
for (const k of snaps.filter((x) => x.lastUsedMs < cutoff && !x.live)) rm(k.path);
|
|
75
96
|
snaps = snaps.filter((x) => existsSync(x.path));
|
|
76
97
|
if (!snaps.length) { if (repo.mtimeMs < cutoff) rm(repo.path); continue; } // nothing left in it and untouched for the max age
|
|
@@ -94,7 +115,7 @@ export function sweepVolume({ root = "/cache", maxAgeDays = 14, maxGb = null, ma
|
|
|
94
115
|
const ageOut = (dir, skip = []) => { for (const k of kids(dir)) if (k.mtimeMs < cutoff && !skip.includes(k.path)) rm(k.path); };
|
|
95
116
|
const dc = join(root, "forge-depcache");
|
|
96
117
|
const depcacheBytes = {};
|
|
97
|
-
if (existsSync(dc)) { ageOut(join(dc, "stores")); sweepDepcache(dc, { cutoff, capBytes: Number.isFinite(maxDepcacheGb) ? maxDepcacheGb * 1024 ** 3 : null, rm, depcacheBytes }); } // store entries, then snapshots per repo
|
|
118
|
+
if (existsSync(dc)) { ageOut(join(dc, "stores")); sweepDepcache(dc, { cutoff, now, capBytes: Number.isFinite(maxDepcacheGb) ? maxDepcacheGb * 1024 ** 3 : null, rm, depcacheBytes }); } // store entries, then snapshots per repo
|
|
98
119
|
if (existsSync(join(root, "env"))) ageOut(join(root, "env"));
|
|
99
120
|
const ps = join(root, "pnpm-store");
|
|
100
121
|
if (existsSync(ps)) sh("pnpm", ["store", "prune", "--store-dir", ps]);
|
|
@@ -103,12 +124,12 @@ export function sweepVolume({ root = "/cache", maxAgeDays = 14, maxGb = null, ma
|
|
|
103
124
|
const entries = [];
|
|
104
125
|
const keepSet = new Set(keep);
|
|
105
126
|
for (const k of kids(join(root, "work"))) entries.push({ ...k, bytes: sizeOf(k.path), live: keepSet.has(k.path) });
|
|
106
|
-
for (const d of [...PACKAGE_STORES, "env", "forge-depcache
|
|
127
|
+
for (const d of [...PACKAGE_STORES, "env", "forge-depcache/stores"]) for (const k of kids(join(root, d))) entries.push({ ...k, bytes: sizeOf(k.path), live: false });
|
|
128
|
+
for (const k of depcacheSnaps(dc, now)) entries.push({ path: k.path, mtimeMs: k.lastUsedMs, bytes: sizeOf(k.path), live: k.live });
|
|
107
129
|
const plan = planCacheCap(entries, maxGb * 1024 ** 3);
|
|
108
130
|
for (const p of plan.delete) rm(p);
|
|
109
131
|
}
|
|
110
|
-
|
|
111
|
-
try { const n = Number(readFileSync(join(root, ".last-used"), "utf8").trim()); if (Number.isFinite(n) && n > 0) last = n * 1000; } catch { /* never recorded */ }
|
|
132
|
+
const lastSec = num(join(root, ".last-used")), last = lastSec === null ? null : lastSec * 1000;
|
|
112
133
|
return { size_bytes: sizeOf(root), last_used_ms: last, depcache_bytes: depcacheBytes, removed: removed.length, errors: errors.slice(0, 5) };
|
|
113
134
|
}
|
|
114
135
|
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
// #5695: demand- and capacity-driven CI runner autoscaler for the pool router. The decision logic (admitRunner, planScale,
|
|
2
|
+
// runnerPriority, decisionRecord) is pure; createAutoscaler wires it to the router's webhook, tick and agents.
|
|
3
|
+
// Imports stay inside bin/pool: the router ships agents only AGENT_BUNDLE_PATHS (pool-agent-bundle.test.mjs).
|
|
4
|
+
|
|
5
|
+
/** Priority classes, lowest number first: deploy > release-PR CI > lanes > ordinary PR CI. */
|
|
6
|
+
export const PRIORITY = { deploy: 0, release: 1, lane: 2, pr: 3 };
|
|
7
|
+
export const DEFAULT_FLOORS = { mem_available_gb: 3, load_per_cpu: 0.8, lane_cpus: 2, lane_mem_gb: 3, net_rx_mbps_max: null };
|
|
8
|
+
export const DEFAULT_SIZE = { cpus: 1, mem_gb: 2 };
|
|
9
|
+
|
|
10
|
+
const num = (v, d) => (Number.isFinite(Number(v)) && v !== null && v !== "" ? Number(v) : d);
|
|
11
|
+
|
|
12
|
+
/** Deploy labels and an explicit job.priority win; a release branch or job.release is release CI; the rest is PR CI. */
|
|
13
|
+
export function runnerPriority(job = {}) {
|
|
14
|
+
if (Number.isInteger(job.priority) && job.priority >= 0 && job.priority <= PRIORITY.pr) return job.priority;
|
|
15
|
+
if (/deploy/i.test(String(job.label ?? "")) || (job.labels ?? []).some((l) => /deploy/i.test(l))) return PRIORITY.deploy;
|
|
16
|
+
if (job.release === true || /^(release|hotfix)[/-]/i.test(String(job.head_branch ?? ""))) return PRIORITY.release;
|
|
17
|
+
return PRIORITY.pr;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** One telemetry record per decision, carrying every input it was made from. */
|
|
21
|
+
export function decisionRecord({ action, label, job = null, admit = null, reason, inputs = {}, dry_run = false, at = null }) {
|
|
22
|
+
return { at, action, label, job: job?.id ?? null, priority: job ? runnerPriority(job) : null, admit, reason, dry_run, inputs };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Does one more runner fit? free = {mem_available_gb, load_per_cpu, vcpus, cpus_free, mem_free_gb}; reserved = what earlier
|
|
27
|
+
* admissions of this round already took; net = {rx_mbps}. The lane floor keeps cpus_free/mem_free_gb for lanes at every
|
|
28
|
+
* priority, so CI never blocks a lane beyond it.
|
|
29
|
+
*/
|
|
30
|
+
export function admitRunner({ free, floors = {}, reserved = {}, job = {}, net = null, size = null }) {
|
|
31
|
+
const f = { ...DEFAULT_FLOORS, ...floors }, sz = size ?? job.size ?? DEFAULT_SIZE;
|
|
32
|
+
const rc = num(reserved.cpus, 0), rm = num(reserved.mem_gb, 0), vcpus = Math.max(1, num(free.vcpus, 1));
|
|
33
|
+
const after = {
|
|
34
|
+
mem_available_gb: num(free.mem_available_gb, Infinity) - rm - sz.mem_gb,
|
|
35
|
+
load_per_cpu: num(free.load_per_cpu, 0) + (rc + sz.cpus) / vcpus,
|
|
36
|
+
cpus_free: num(free.cpus_free, Infinity) - rc - sz.cpus,
|
|
37
|
+
mem_free_gb: num(free.mem_free_gb, Infinity) - rm - sz.mem_gb,
|
|
38
|
+
};
|
|
39
|
+
const inputs = { free, floors: f, reserved: { cpus: rc, mem_gb: rm }, size: sz, after, ...(net ? { net } : {}) };
|
|
40
|
+
const no = (reason) => ({ admit: false, reason, inputs });
|
|
41
|
+
if (after.mem_available_gb < f.mem_available_gb) return no(`MemAvailable ${after.mem_available_gb.toFixed(1)} GB after reservation < floor ${f.mem_available_gb}`);
|
|
42
|
+
if (after.load_per_cpu > f.load_per_cpu) return no(`load ${after.load_per_cpu.toFixed(2)}/cpu after reservation > ${f.load_per_cpu}`);
|
|
43
|
+
if (after.cpus_free < f.lane_cpus || after.mem_free_gb < f.lane_mem_gb) return no("lane floor: reservation would leave lanes less than the configured floor");
|
|
44
|
+
const rx = num(net?.rx_mbps, null);
|
|
45
|
+
if (f.net_rx_mbps_max && rx !== null && rx > f.net_rx_mbps_max && runnerPriority(job) > PRIORITY.deploy) return no(`network ${rx} MB/s > ${f.net_rx_mbps_max} (saturated)`);
|
|
46
|
+
return { admit: true, reason: "fits", inputs };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const inWindow = (window, t) => (window ?? []).find((w) => Number(w.from) <= t && t < Number(w.to)) ?? null;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Decide this round's runner starts and stops.
|
|
53
|
+
* demand: {label: [job]} queued jobs; running: {label: {total, busy}}; labels: {label: {min, max, size}};
|
|
54
|
+
* lanes: {waiting} (a waiting lane outranks ordinary PR CI); window: [{from,to}] maintenance windows in epoch ms.
|
|
55
|
+
* Returns decision records; `start`/`stop` ones are actionable. Candidates are admitted in priority order.
|
|
56
|
+
*/
|
|
57
|
+
export function planScale({ demand = {}, running = {}, labels = {}, lanes = {}, window = [], free, floors = {}, net = null, now = 0, dry_run = false }) {
|
|
58
|
+
const out = [], rec = (d) => out.push(decisionRecord({ at: now, dry_run, ...d }));
|
|
59
|
+
const win = inWindow(window, now), cand = [];
|
|
60
|
+
for (const [label, cfg] of Object.entries(labels)) {
|
|
61
|
+
const queued = demand[label] ?? [], r = running[label] ?? { total: 0, busy: 0 };
|
|
62
|
+
const min = num(cfg.min, 0), max = num(cfg.max, 0), size = cfg.size ?? DEFAULT_SIZE, idle = Math.max(0, r.total - r.busy);
|
|
63
|
+
const ctx = { queued: queued.length, total: r.total, busy: r.busy, idle, min, max, size };
|
|
64
|
+
const want = Math.min(Math.max(queued.length - idle, min - r.total, 0), Math.max(0, max - r.total));
|
|
65
|
+
const jobs = [...queued].sort((a, b) => runnerPriority({ label, ...a }) - runnerPriority({ label, ...b }));
|
|
66
|
+
for (let i = 0; i < want; i++) cand.push({ label, size, job: { label, ...(jobs[i] ?? { id: null }) }, ctx });
|
|
67
|
+
const keep = Math.max(min, queued.length), surplus = Math.max(0, idle - Math.max(0, keep - r.busy));
|
|
68
|
+
if (surplus > 0 && !win) rec({ action: "stop", label, admit: true, reason: `${surplus} idle runner(s) above max(min, queued)`, inputs: { ...ctx, surplus } });
|
|
69
|
+
else if (want === 0) rec({ action: "hold", label, admit: null, reason: "no runner needed", inputs: ctx });
|
|
70
|
+
}
|
|
71
|
+
cand.sort((a, b) => runnerPriority(a.job) - runnerPriority(b.job));
|
|
72
|
+
const reserved = { cpus: 0, mem_gb: 0 };
|
|
73
|
+
for (const c of cand) {
|
|
74
|
+
if (win) { rec({ action: "hold", label: c.label, job: c.job, admit: false, reason: `maintenance window${win.why ? `: ${win.why}` : ""}`, inputs: { ...c.ctx, window: win } }); continue; }
|
|
75
|
+
if ((lanes.waiting ?? 0) > 0 && runnerPriority(c.job) > PRIORITY.lane) { rec({ action: "hold", label: c.label, job: c.job, admit: false, reason: "a lane is waiting and outranks ordinary PR CI", inputs: { ...c.ctx, lanes } }); continue; }
|
|
76
|
+
const v = admitRunner({ free, floors, reserved, job: c.job, net, size: c.size });
|
|
77
|
+
if (v.admit) { reserved.cpus += c.size.cpus; reserved.mem_gb += c.size.mem_gb; }
|
|
78
|
+
rec({ action: v.admit ? "start" : "hold", label: c.label, job: c.job, admit: v.admit, reason: v.reason, inputs: { ...v.inputs, ...c.ctx } });
|
|
79
|
+
}
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Router-side controller. `ingest` takes a GitHub workflow_job payload (queued/in_progress/completed); `reconcile` (router
|
|
85
|
+
* tick) polls the jobs API as a fallback, plans, and asks an agent to start or stop ephemeral JIT runners. Off by default;
|
|
86
|
+
* dry_run logs every decision and starts nothing.
|
|
87
|
+
*/
|
|
88
|
+
export function createAutoscaler({ cfg = {}, now, log, capacities, agentCall, githubToken, fetchFn, agents }) {
|
|
89
|
+
const c = cfg.ci_autoscale ?? {};
|
|
90
|
+
const jobs = new Map(); // job id -> {id,label,status,runner,head_branch,at}
|
|
91
|
+
const decisions = [];
|
|
92
|
+
let lastPoll = -Infinity, seq = 0;
|
|
93
|
+
const labelOf = (wj) => (wj?.labels ?? []).find((l) => Object.hasOwn(c.labels ?? {}, l)) ?? null;
|
|
94
|
+
const track = (wj) => {
|
|
95
|
+
const label = labelOf(wj);
|
|
96
|
+
if (!label || !Number.isFinite(Number(wj.id))) return null;
|
|
97
|
+
if (wj.status === "completed") { jobs.delete(Number(wj.id)); return { label, status: "completed" }; }
|
|
98
|
+
const j = { id: Number(wj.id), label, labels: wj.labels, status: wj.status === "in_progress" ? "in_progress" : "queued", runner: wj.runner_name ?? null, head_branch: wj.head_branch ?? null, at: now() };
|
|
99
|
+
jobs.set(j.id, j);
|
|
100
|
+
return { label, status: j.status };
|
|
101
|
+
};
|
|
102
|
+
function ingest(body) {
|
|
103
|
+
if (!c.enabled) return { enabled: false, tracked: false };
|
|
104
|
+
const t = body?.workflow_job ? track(body.workflow_job) : null;
|
|
105
|
+
return { enabled: true, tracked: Boolean(t), ...(t ?? {}) };
|
|
106
|
+
}
|
|
107
|
+
const gh = async (path, body) => {
|
|
108
|
+
const r = await fetchFn(`https://api.github.com${path}`, { method: body ? "POST" : "GET", headers: { authorization: `Bearer ${await githubToken()}`, accept: "application/vnd.github+json", ...(body ? { "content-type": "application/json" } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}) });
|
|
109
|
+
if (!r.ok) throw new Error(`GitHub ${path} -> ${r.status}`);
|
|
110
|
+
return r.json();
|
|
111
|
+
};
|
|
112
|
+
async function poll() {
|
|
113
|
+
if (!c.repo || now() - lastPoll < (c.poll_s ?? 300) * 1000) return;
|
|
114
|
+
lastPoll = now();
|
|
115
|
+
const seen = new Set();
|
|
116
|
+
try {
|
|
117
|
+
const runs = (await gh(`/repos/${c.repo}/actions/runs?status=queued&per_page=20`)).workflow_runs ?? [];
|
|
118
|
+
for (const run of runs) for (const wj of (await gh(`/repos/${c.repo}/actions/runs/${run.id}/jobs?per_page=100`)).jobs ?? []) {
|
|
119
|
+
if (wj.status === "queued" && labelOf(wj)) { seen.add(Number(wj.id)); if (!jobs.has(Number(wj.id))) track({ ...wj, head_branch: wj.head_branch ?? run.head_branch }); }
|
|
120
|
+
}
|
|
121
|
+
for (const [id, j] of jobs) if (j.status === "queued" && !seen.has(id) && now() - j.at > (c.poll_s ?? 300) * 1000) jobs.delete(id); // the API no longer lists it
|
|
122
|
+
} catch (e) { log.warn?.(`ci-autoscale poll: ${e.message}`); }
|
|
123
|
+
}
|
|
124
|
+
const emit = (d) => { decisions.push(d); if (decisions.length > 200) decisions.shift(); log.info?.(`ci-autoscale ${JSON.stringify(d)}`); };
|
|
125
|
+
|
|
126
|
+
async function reconcile() {
|
|
127
|
+
if (!c.enabled) return [];
|
|
128
|
+
for (const [id, j] of jobs) if (now() - j.at > 6 * 3600000) jobs.delete(id); // a lost completed event
|
|
129
|
+
await poll();
|
|
130
|
+
const caps = (await capacities()).filter((x) => x.ok && !x.paused);
|
|
131
|
+
if (!caps.length) return [];
|
|
132
|
+
const host = caps.sort((a, b) => (b.live?.mem_available_gb ?? 0) - (a.live?.mem_available_gb ?? 0))[0];
|
|
133
|
+
const free = { mem_available_gb: host.live?.mem_available_gb, load_per_cpu: host.live?.load_per_core, vcpus: host.vm?.cpus ?? host.cpus_total, cpus_free: host.cpus_free, mem_free_gb: host.mem_free_gb };
|
|
134
|
+
const demand = {}, running = {};
|
|
135
|
+
for (const label of Object.keys(c.labels ?? {})) {
|
|
136
|
+
demand[label] = [...jobs.values()].filter((j) => j.label === label && j.status === "queued");
|
|
137
|
+
const mine = (host.runners ?? []).filter((r) => r.label === label), busyNames = new Set([...jobs.values()].filter((j) => j.status === "in_progress" && j.runner).map((j) => j.runner));
|
|
138
|
+
running[label] = { total: mine.length, busy: mine.filter((r) => busyNames.has(r.name)).length, names: mine.map((r) => r.name).filter((n) => !busyNames.has(n)) };
|
|
139
|
+
}
|
|
140
|
+
const win = (c.windows ?? []).map((w) => ({ from: Date.parse(w.from), to: Date.parse(w.to), why: w.why }));
|
|
141
|
+
const plan = planScale({ demand, running, labels: c.labels, lanes: { waiting: 0 }, window: win, free, floors: { ...c.floors, lane_cpus: c.lane_floor?.cpus ?? c.floors?.lane_cpus, lane_mem_gb: c.lane_floor?.mem_gb ?? c.floors?.lane_mem_gb }, net: host.net ?? null, now: now(), dry_run: Boolean(c.dry_run) });
|
|
142
|
+
for (const d of plan) {
|
|
143
|
+
emit(d);
|
|
144
|
+
if (c.dry_run) continue;
|
|
145
|
+
const a = agents()[host.name];
|
|
146
|
+
try {
|
|
147
|
+
if (d.action === "start") {
|
|
148
|
+
const name = `ci-${d.label}-${now().toString(36)}-${seq++}`.replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 64);
|
|
149
|
+
const jit = await gh(`/repos/${c.repo}/actions/runners/generate-jitconfig`, { name, runner_group_id: c.runner_group_id ?? 1, labels: ["self-hosted", d.label], work_folder: "_work" });
|
|
150
|
+
const r = await agentCall(a, "POST", "/runners", { name, label: d.label, jitconfig: jit.encoded_jit_config, cpus: d.inputs.size.cpus, mem_gb: d.inputs.size.mem_gb });
|
|
151
|
+
if (!r.ok) log.warn?.(`ci-autoscale start ${name} on ${host.name}: HTTP ${r.status}`);
|
|
152
|
+
} else if (d.action === "stop") {
|
|
153
|
+
for (const n of running[d.label].names.slice(0, d.inputs.surplus)) await agentCall(a, "DELETE", `/runners/${encodeURIComponent(n)}`);
|
|
154
|
+
}
|
|
155
|
+
} catch (e) { log.warn?.(`ci-autoscale ${d.action} ${d.label}: ${e.message}`); }
|
|
156
|
+
}
|
|
157
|
+
return plan;
|
|
158
|
+
}
|
|
159
|
+
return { ingest, reconcile, decisions, jobs };
|
|
160
|
+
}
|