Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

ubicloud: sync ubi-runner.sh with gstack 5532345a; UBI_REAP guard, UBI_OWNER, left= infra gate, #8050 TTL fixes

garrytane2c5001f063b
diff --git a/.gitignore b/.gitignore
index 93d1222161..0dca68dbbc 100644
--- a/.gitignore
+++ b/.gitignore
@@ -17,6 +17,7 @@ bin/
!.gstack/redact-allowlist
!.gstack/pregate.json
!.gstack/ship-policy.json
+!.gstack/ubicloud.json
supabase/.temp/
.claude/skills/
# admin/dist/ is the React SPA bundle. CLAUDE.md says it's committed for
diff --git a/.gstack/pregate.json b/.gstack/pregate.json
index a1a153591a..6dfe766f8e 100644
--- a/.gstack/pregate.json
+++ b/.gstack/pregate.json
@@ -20,8 +20,12 @@
],
"scripts/ubicloud/ubi-runner.sh": [
"test/scripts/ubi-runner.test.ts",
+ "test/scripts/ubi-runner-run.test.ts",
"test/scripts/ci-ubicloud-vm-names.test.ts"
],
+ ".gstack/ubicloud.json": [
+ "test/scripts/ubi-runner-run.test.ts"
+ ],
"scripts/ubicloud/reap-expired.ts": [
"test/scripts/ubicloud-reap-expired.test.ts"
],
diff --git a/.gstack/ubicloud.json b/.gstack/ubicloud.json
new file mode 100644
index 0000000000..6f0261f7ce
--- /dev/null
+++ b/.gstack/ubicloud.json
@@ -0,0 +1,12 @@
+{
+ "setup": "scripts/ubicloud/setup-ci-vm.sh",
+ "command": "SLOT=1 bash scripts/ubicloud/ci-item.sh heavy",
+ "size": "standard-30",
+ "env": [
+ "SLOTS=1",
+ "GBRAIN_HEAVY_LOG_DIR=/home/ubi/heavy-logs"
+ ],
+ "pull": [
+ "heavy-logs:.context/ubicloud-verify"
+ ]
+}
diff --git a/docs/TESTING.md b/docs/TESTING.md
index fd7e261a67..16de064b6e 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -458,8 +458,8 @@ too; build the admin app on the host when updating its committed bundle.
from one heaviest-first work queue; every VM is destroyed on exit. VM setup, scheduling, weights, quota
and flags are in [scripts/ubicloud/README.md](../scripts/ubicloud/README.md).
-VMs are named `ubirun-<owner>-<epoch>-<suffix>-t<H>`; set `UBI_OWNER` to your thread
-code. `scripts/ubicloud/ubi-runner.sh usage` shows vCPUs by owner.
+VMs are named `ubirun-<owner>-<epoch>-<suffix>-t<H>`; `UBI_OWNER` (your thread
+code) is required. `scripts/ubicloud/ubi-runner.sh usage` shows vCPUs by owner.
A sleeping machine kills the run with no signal, so teardown never runs: on Capy, run
`ci:ubicloud` as a watched background operation. After any interrupted run, check
`ubi-runner.sh list --mine` and reap leftovers with `down NAME` (or `gc HOURS`, own VMs only).
diff --git a/docs/eval/hnsw-scale-bench.md b/docs/eval/hnsw-scale-bench.md
index 0602bc9b0a..269d91896e 100644
--- a/docs/eval/hnsw-scale-bench.md
+++ b/docs/eval/hnsw-scale-bench.md
@@ -604,7 +604,7 @@ What the table shows:
```bash
# VM (Ubicloud standard-16, 320 GB): bootstrap Docker, Bun 1.4.4 and a tuned pgvector/pg16 on 127.0.0.1:5434
-UBI_OWNER=<thread> scripts/ubicloud/ubi-runner.sh up -s standard-16 -S 320
+UBI_OWNER=<thread> scripts/ubicloud/ubi-runner.sh up -s standard-16 -S 320 --ttl-hours 48
scripts/ubicloud/ubi-runner.sh sync <vm> . && scripts/ubicloud/ubi-runner.sh ssh <vm> 'cd work/gbrain && bash scripts/bench/hnsw-scale-vm-setup.sh'
export DATABASE_URL=postgresql://postgres:[email protected]:5434/postgres
B=scripts/bench/hnsw-iterative-scan.ts
diff --git a/scripts/bench/production-soak/ubicloud.sh b/scripts/bench/production-soak/ubicloud.sh
index 3221798a4a..909eacc553 100755
--- a/scripts/bench/production-soak/ubicloud.sh
+++ b/scripts/bench/production-soak/ubicloud.sh
@@ -3,13 +3,14 @@
# on ephemeral Ubicloud VMs, one VM per latency, in parallel (GBRA-174).
#
# UBI_OWNER=<thread> scripts/bench/production-soak/ubicloud.sh start [--pages 600000] [--hours 3]
-# [--rtts 65,2] [--size standard-16] [--storage 640] [--ttl-hours 15] [--out .context/production-soak]
+# [--rtts 65,2] [--size standard-16] [--storage 640] [--ttl-hours HOURS+12] [--out .context/production-soak]
# scripts/bench/production-soak/ubicloud.sh status [--out DIR] # last lines of each cell's run log
# scripts/bench/production-soak/ubicloud.sh collect [--out DIR] # copy each finished cell back, destroy its VM
#
-# start creates one VM per latency, named with a TTL (--ttl-hours: a -t15 name
-# by default, above the 3-hour soak plus setup and collect) so the operator
-# reaper or gstack's reap destroys it if nobody collects it, syncs this checkout
+# start creates one VM per latency, named with a TTL (--ttl-hours: the soak's
+# --hours, rounded up, plus 12 by default, so a -t15 name for the 3-hour soak;
+# start refuses a TTL under --hours + 4, which the reapers would end mid-soak)
+# so the operator reaper or gstack's reap destroys it if nobody collects it, syncs this checkout
# (uncommitted edits included), bootstraps it (vm-setup.sh) and launches
# run.sh detached on the VM, so the soak does not depend on this machine
# staying awake. collect copies <out>/rtt<N>/out back for every cell whose run
@@ -19,7 +20,7 @@ set -euo pipefail
cd "$(dirname "$0")/../../.."
UBI=scripts/ubicloud/ubi-runner.sh
CMD=${1:-}; shift || true
-PAGES=600000 HOURS=3 RTTS=65,2 SIZE=standard-16 STORAGE=640 TTL=15 OUT=.context/production-soak EXTRA=()
+PAGES=600000 HOURS=3 RTTS=65,2 SIZE=standard-16 STORAGE=640 TTL="" OUT=.context/production-soak EXTRA=()
while [ $# -gt 0 ]; do
case $1 in
--pages) PAGES=$2; shift 2 ;;
@@ -35,6 +36,11 @@ done
case $CMD in
start)
[ -n "${UBI_OWNER:-}" ] || { echo "set UBI_OWNER to your thread code" >&2; exit 2; }
+ whole=$(awk -v h="$HOURS" 'BEGIN { if (h !~ /^[0-9]+(\.[0-9]+)?$/) exit 1; c = int(h); if (c < h) c++; print c }') \
+ || { echo "--hours must be a number of hours (got $HOURS)" >&2; exit 2; }
+ TTL=${TTL:-$(( whole + 12 ))}
+ [[ "$TTL" =~ ^[1-9][0-9]{0,2}$ ]] || { echo "--ttl-hours must be a whole number from 1 to 999 (got $TTL)" >&2; exit 2; }
+ [ "$TTL" -ge $(( whole + 4 )) ] || { echo "--ttl-hours $TTL is under --hours $HOURS + 4: the reapers would destroy the VMs mid-soak; give at least $(( whole + 4 ))" >&2; exit 2; }
mkdir -p "$OUT"
for rtt in ${RTTS//,/ }; do
cell="$OUT/rtt$rtt"; mkdir -p "$cell"
diff --git a/scripts/ci-ubicloud.ts b/scripts/ci-ubicloud.ts
index 9d6e2dba04..ada0e0f924 100755
--- a/scripts/ci-ubicloud.ts
+++ b/scripts/ci-ubicloud.ts
@@ -32,7 +32,8 @@
* expiry, so a VM a sleeping machine never tore down
* dies within hours (scripts/ubicloud/reap-expired.ts)
*
- * Needs UBICLOUD_API_KEY (or UBICLOUD_API_TOKEN) plus bash, curl, python3,
+ * Needs UBI_OWNER (your thread code; every VM name carries it, and the run
+ * refuses without it) and UBICLOUD_API_KEY (or UBICLOUD_API_TOKEN) plus bash, curl, python3,
* ssh, ssh-keygen and tar locally. The checkout (tracked + untracked-unignored
* files + .git) is packed once and streamed to every VM, so uncommitted edits
* are tested.
@@ -53,12 +54,18 @@
* merged into .context/ci-ubicloud/weights.json, which weights the next run.
*
* VMs are named ubirun-<owner>-<epoch>-ciNN<hex>-t<ttl hours> (owner:
- * UBI_OWNER or the runner's per-machine id), gstack's runner grammar, so
+ * UBI_OWNER), gstack's runner grammar, so
* gstack's reap reads the same TTL. Each name is appended to <run>/vms.txt before its
* create request is sent. On exit, including SIGINT, SIGTERM, SIGHUP (a
* dropped terminal, a cancelled background operation) and SIGQUIT, in-flight
* `up` calls are allowed to finish (they destroy their own VM), then every
- * recorded name is destroyed and polled until it is confirmed gone.
+ * recorded name is destroyed and polled until it is confirmed gone. Then the
+ * project's VM list is read once more and the run prints gstack's leftover line,
+ * UBICLOUD: left=<n|unknown> owner=<owner> vms=<requested> others=<n>
+ * (left: this run's VMs still listed; others: this owner's other VMs, for
+ * information), also appended to UBI_LEFT_FILE when set
+ * (scripts/pregate-remote-gate.sh reads it). A left other than 0 fails a run
+ * that would otherwise pass; --keep reports its VMs as left=<n> kept=1.
*/
import { spawnSync, type ChildProcess } from "node:child_process";
@@ -226,6 +233,11 @@ async function main() {
console.error("ci-ubicloud: UBICLOUD_API_KEY (or UBICLOUD_API_TOKEN) is not set");
process.exit(2);
}
+ if (!process.env.UBI_OWNER) {
+ console.error("ci-ubicloud: UBI_OWNER is not set; set it to your thread code in lowercase (e.g. UBI_OWNER=gbra106) so every VM carries its owner (UBI_OWNER_REQUIRED)");
+ process.exit(2);
+ }
+ const owner = sh("bash", [RUNNER, "owner"]).trim();
const sha = sh("git", ["rev-parse", "HEAD"]).trim();
const runId = `${new Date().toISOString().replace(/[:.]/g, "-")}-${sha.slice(0, 8)}`;
const runDir = join(ROOT, ".context/ci-ubicloud", runId);
@@ -238,7 +250,10 @@ async function main() {
const classification = spawnSync("bun", ["run", "scripts/select-e2e.ts", "--classify-only"], { cwd: ROOT, encoding: "utf8" }).stdout?.trim();
if (classification === "DOC_ONLY") {
log("--diff: doc-only diff — running the doc checks locally, then gitleaks (ci:local doc-only fast-path)");
- if (spawnSync("bash", ["scripts/ci-doc-checks.sh"], { cwd: ROOT, stdio: "inherit" }).status !== 0) process.exit(1);
+ if (spawnSync("bash", ["scripts/ci-doc-checks.sh"], { cwd: ROOT, stdio: "inherit" }).status !== 0) {
+ await leftover(owner, [], false);
+ process.exit(1);
+ }
opts.lanes = new Set(["gitleaks"]);
opts.vms = 1;
} else {
@@ -314,7 +329,6 @@ async function main() {
?? "1.4.4";
// ── Teardown on every exit path ──────────────────────────────────────────
- const owner = sh("bash", [RUNNER, "owner"]).trim();
const ledger = join(runDir, "vms.txt");
const createdAt = Math.floor(Date.now() / 1000);
const vms: Vm[] = Array.from({ length: opts.vms }, (_, i) => ({
@@ -338,8 +352,10 @@ async function main() {
await Promise.all(ups.map((child) => new Promise((done) => (child.exitCode !== null || child.signalCode !== null ? done(null) : child.once("exit", done)))));
rmSync(tarball, { force: true });
const live = vms.filter((vm) => vm.requested && vm.state !== "destroyed");
+ const requested = vms.filter((vm) => vm.requested).map((vm) => vm.name);
if (opts.keep) {
log(`--keep: leaving ${live.map((vm) => vm.name).join(" ")} running; destroy with: scripts/ubicloud/ubi-runner.sh down NAME (the operator reaper destroys them ${opts.ttlHours}h after creation; pass --ttl-hours up to 999 for longer)`);
+ await leftover(owner, requested, true);
return;
}
log(`destroying ${live.length} VM(s): ${live.map((vm) => vm.name).join(" ")}`);
@@ -354,7 +370,9 @@ async function main() {
}));
const left = live.filter((vm) => vm.state !== "destroyed").length;
log(left ? `teardown left ${left} VM(s) unconfirmed (names in ${ledger})` : `teardown confirmed ${live.length} VM(s) gone`);
+ leftClean = await leftover(owner, requested, false);
};
+ let leftClean = true;
let interrupted = false;
// After SIGHUP the terminal may be gone: a failed log write must not abort teardown.
for (const stream of [process.stdout, process.stderr]) stream.on("error", () => {});
@@ -483,7 +501,7 @@ async function main() {
if (up.code !== 0) {
vm.state = "failed";
const setupText = readFileSync(setupLog, "utf8").trim();
- const quota = setupText.indexOf("ubi-runner: quota refused");
+ const quota = setupText.search(/ubi-runner: quota (preflight )?refused/);
if (quota >= 0) log(`VM ${index + 1} refused by the Ubicloud vCPU quota; the run continues on the VMs that started:\n${setupText.slice(quota)}`);
else log(`VM ${index + 1} failed to provision (see ${setupLog}): ${setupText.split("\n").slice(-2).join(" | ")}`);
return;
@@ -539,6 +557,10 @@ async function main() {
clearInterval(progress);
await teardown();
}
+ if (!leftClean) {
+ console.error(`ci-ubicloud: VM cleanup not confirmed (see the UBICLOUD: line above); check with: UBI_OWNER=${owner} scripts/ubicloud/ubi-runner.sh list --mine`);
+ exitCode = 1;
+ }
// ── Report ───────────────────────────────────────────────────────────────
const all = [...results.values()];
@@ -643,6 +665,23 @@ async function main() {
process.exit(exitCode);
}
+/**
+ * Print gstack's leftover line after teardown (and append it to UBI_LEFT_FILE):
+ * left counts `names` still in the project's VM list ("unknown" when the list
+ * cannot be read), others this owner's other ubirun VMs. Returns whether left
+ * is 0; a --keep run reports its live VMs as left=<n> kept=1.
+ */
+async function leftover(owner: string, names: string[], kept: boolean): Promise<boolean> {
+ const list = await runner(["cli", "vm", "list", "-N", "-f", "location,name"], { timeoutMs: 120_000 });
+ const listed = list.code === 0 ? new Set(list.stdout.split("\n").map((line) => line.trim().split(/\s+/)[1]).filter(Boolean)) : null;
+ const left = listed ? names.filter((name) => listed.has(name)).length : "unknown";
+ const others = listed ? [...listed].filter((name) => name!.startsWith(`ubirun-${owner}-`) && !names.includes(name!)).length : "unknown";
+ const line = `UBICLOUD: left=${left} owner=${owner} vms=${names.length} ${kept ? "kept=1" : `others=${others}`}`;
+ console.log(line);
+ if (process.env.UBI_LEFT_FILE) appendFileSync(process.env.UBI_LEFT_FILE, line + "\n");
+ return left === 0;
+}
+
/**
* test.yml's unit shards as this gate checks them: the partition and mined weights of unitShardPlan, failing a
* shard over UNIT_SHARD_BUDGET_MS exactly as test/scripts/unit-shard-budget.test.ts does. `measured` (this run's
diff --git a/scripts/pregate-remote-gate.sh b/scripts/pregate-remote-gate.sh
index 991bb55331..2ed87704a7 100755
--- a/scripts/pregate-remote-gate.sh
+++ b/scripts/pregate-remote-gate.sh
@@ -37,6 +37,13 @@
# from the gate's summary. No line is printed when the gate printed no
# summary. The exit code is the gate's.
#
+# VM cleanup is checked before any receipt: the gate runs with UBI_LEFT_FILE
+# set, and ci:ubicloud appends its `UBICLOUD: left=<n> ...` line there after
+# teardown (gstack's runner format). A missing line, or a left= other than 0
+# (VMs it could not confirm gone, or `unknown`), is an infrastructure failure:
+# PREGATE_REMOTE_INFRA, exit 4, no receipt, whatever the tests did, so a leak
+# is never read as a test result.
+#
# Needs UBI_OWNER (your thread code, lowercase) so the VMs are tagged and torn
# down as yours, plus what ci:ubicloud needs (UBICLOUD_API_KEY or
# UBICLOUD_API_TOKEN). Provider API keys are removed from the gate's
@@ -52,6 +59,7 @@ set -uo pipefail
fail() { echo "pregate-remote-gate: $1" >&2; exit "${2:-1}"; }
[ -n "${UBI_OWNER:-}" ] || fail "UBI_OWNER is not set; set it to your thread code in lowercase (e.g. UBI_OWNER=gbra106) so the gate's VMs are yours to tear down" 2
+export UBI_OWNER
TOP=$(git rev-parse --show-toplevel 2>/dev/null) || fail "not inside a git checkout" 2
cd "$TOP" || exit 2
@@ -73,7 +81,7 @@ if [ -n "${PREGATE_TREE:-}" ] && [ "$before" != "$PREGATE_TREE" ]; then
fi
log=$(mktemp "${TMPDIR:-/tmp}/pregate-remote-gate-log-XXXXXX") || fail "cannot create a log file"
-trap 'rm -f "$log"' EXIT
+trap 'rm -f "$log" "$log.left"' EXIT
strip_keys() { env -u OPENAI_API_KEY -u ANTHROPIC_API_KEY -u VOYAGE_API_KEY -u GEMINI_API_KEY -u JEV_TYPESAFE_API_KEY -u DATABASE_URL "$@"; }
@@ -109,9 +117,14 @@ if [ -n "$reused" ]; then
[ "${reused#* }" = 0 ] || rc=1
else
gate_cmd=${GBRAIN_PREGATE_GATE_CMD:-bun run ci:ubicloud:diff}
+ : >"$log.left"
# shellcheck disable=SC2086
- strip_keys bash -c "$gate_cmd \"\$@\"" pregate-remote-gate "$@" 2>&1 | tee "$log"
+ UBI_LEFT_FILE="$log.left" strip_keys bash -c "$gate_cmd \"\$@\"" pregate-remote-gate "$@" 2>&1 | tee "$log"
rc=${PIPESTATUS[0]}
+ left=$(sed -n 's/^UBICLOUD: left=\([^ ]*\).*/\1/p' "$log.left" | tail -1)
+ if [ "$left" != 0 ]; then
+ fail "PREGATE_REMOTE_INFRA: VM cleanup not confirmed (UBICLOUD: left=${left:-missing}, gate exit $rc); an infrastructure failure, not a test result, so no receipt. Check and destroy leftovers: UBI_OWNER=$UBI_OWNER scripts/ubicloud/ubi-runner.sh list --mine" 4
+ fi
totals=$(awk '
/^=== ci-ubicloud summary ===$/ { seen = 1; next }
seen && /^ +[a-z0-9-]+ +[0-9]+ passed, [0-9]+ failed/ { passed += $2; failed += $4; rows++ }
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index f1fb35cead..fdf49d5e71 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -352,6 +352,7 @@ test/scripts/test-env-opt-ins-guard.test.ts check-test-env-opt-ins 5 readFileSyn
test/scripts/test-shard.slow.test.ts test-shard.sh — LPT balance contract 5 readFileSync
test/scripts/test-shard.slow.test.ts test-shard.sh — exclusion contract 7 readFileSync
test/scripts/tier2-openclaw-mcp.test.ts Tier 2 OpenClaw MCP wiring (#8002) 7 readFileSync
+test/scripts/ubi-runner-run.test.ts run leftover line 2 readFileSync
test/scripts/ubicloud-typecheck-state.test.ts (file-level) 3 readFileSync
test/search/graph-signals-wire-integration.test.ts v0.40.4 — source-grep regression guard 1 source-surface-helper
test/serve-behavior-notice-6543.test.ts (file-level) 3 readFileSync
diff --git a/scripts/ubicloud/README.md b/scripts/ubicloud/README.md
index f4c5eab2a9..e2fd003e65 100644
--- a/scripts/ubicloud/README.md
+++ b/scripts/ubicloud/README.md
@@ -24,23 +24,34 @@ the integrator runs the full gate.
## Ownership and teardown
-Every VM the runner names is `ubirun-<owner>-<epoch>-<suffix>-t<H>`, gstack's
-runner grammar: its TTL ends H hours (1 to 999) after the creation epoch.
-The owner is `UBI_OWNER` (lowercased, letters and digits only, at most 12
-characters, starting with a letter) or a random per-machine id kept in the
-runner's state directory. Set `UBI_OWNER` to your thread code
-(`UBI_OWNER=gbra41 bun run ci:ubicloud`) so everyone can see whose VMs hold
-the quota. Ubicloud names allow 63 characters of `[a-z0-9-]`, so a full name
-stays under 50.
+`scripts/ubicloud/ubi-runner.sh` is gstack's runner, vendored (synced at gstack
+5532345a); its header lists gbrain's additions, which a sync keeps. Every VM
+the runner names is `ubirun-<owner>-<epoch>-<suffix>-t<H>`, gstack's runner
+grammar: its TTL ends H hours (1 to 999) after the creation epoch. The owner
+is `UBI_OWNER` (lowercased, letters and digits only, at most 12 characters,
+starting with a letter), and it is required: `up`, `run`, `verify`,
+`ci:ubicloud` and `scripts/pregate-remote-gate.sh` refuse without it, so no VM
+is created untagged (read-only commands fall back to a per-machine id). Set it
+to your thread code (`UBI_OWNER=gbra41 bun run ci:ubicloud`). Ubicloud names
+allow 63 characters of `[a-z0-9-]`, so a full name stays under 50.
Ubicloud has no VM tags, so the TTL lives in the name, and gstack's
`ubi-runner.sh reap` reads the TTL of every name gbrain generates the same way. `ci:ubicloud` gives every gate VM a
two-hour TTL (`--ttl-hours N` changes it, up to 999). `ubi-runner.sh up` and
-`run` take the same `--ttl-hours H`; without it their VMs get `-t999` (about
-41 days) for long dev, benchmark and eval VMs. gstack's `up` also destroys
-the caller's own (`UBI_OWNER`) `ubirun-*` VMs that carry no `-t<H>` (TTL-less or
-older `-x<expiry>` names) once they are four hours old, so give a long-lived VM a
-TTL before running gstack's runner under the same owner. `scripts/ubicloud/reap-expired.ts` is the operator
+`run` take the same `--ttl-hours H`; without it their VMs get `UBI_TTL_HOURS`
+(gstack's default, 3 hours), so give a long dev, benchmark or eval VM
+`--ttl-hours` above its longest run. With `-n NAME`, `--ttl-hours H` appends
+`-t<H>`, and a `ubirun-` name without a TTL is refused (nothing could ever reap it).
+`ubi-runner.sh reap` destroys every VM whose TTL ended over ten minutes ago,
+any owner's, plus the caller's own TTL-less `ubirun-<owner>-*` VMs once they are
+`UBI_LEGACY_HOURS` (4) old. gstack's `up` runs that reap first; gbrain's copy
+does only with `UBI_REAP=1`, and logs one `reap skipped` line otherwise, until
+gbrain's TTL-less VMs older than four hours are gone. `run`, `verify` and
+`ci:ubicloud` end with gstack's leftover line, `UBICLOUD: left=<n> owner=<owner> ...`
+(also appended to `UBI_LEFT_FILE`), counting their own VMs still in the
+project's list after teardown; anything but `left=0` fails a run that would
+otherwise pass, and `scripts/pregate-remote-gate.sh` treats it, or a missing
+line, as `PREGATE_REMOTE_INFRA` (exit 4, no receipt). `scripts/ubicloud/reap-expired.ts` is the operator
side of the leak guard: run from the operator's Capy automation, where the
Ubicloud token already lives (never from GitHub Actions), it lists the project's
VMs, selects only names with a TTL (or the older
diff --git a/scripts/ubicloud/ci-item.sh b/scripts/ubicloud/ci-item.sh
index 7f852fcfd4..5f768d9134 100755
--- a/scripts/ubicloud/ci-item.sh
+++ b/scripts/ubicloud/ci-item.sh
@@ -13,6 +13,8 @@
# e2e scripts/run-e2e.sh FILE against this slot's own postgres + pgbouncer
# (backend-matrix files also run through the slot's pgbouncer)
# verify check-bun-test-timeout.sh + bun run verify (no FILE)
+# heavy bun run test:heavy against this slot's gbrain_test, as
+# heavy-tests.yml runs it (no FILE; .gstack/ubicloud.json's verify)
# gitleaks the ci:local host scans (no FILE)
#
# Every item is bracketed by marker lines the orchestrator parses:
@@ -62,6 +64,11 @@ run_item() {
bash scripts/run-e2e.sh "$1"
;;
verify) bash scripts/check-bun-test-timeout.sh && bun run verify ;;
+ heavy)
+ env -u GBRAIN_TEST_TIMEOUT_MULTIPLIER -u GBRAIN_TEST_EXPORT_SCALE_PAGES \
+ DATABASE_URL="$pg/gbrain_test" GBRAIN_TEST_ALLOW_DATABASE_URL=1 \
+ bun run test:heavy
+ ;;
gitleaks)
bash scripts/test-gitleaks-config.sh &&
bash scripts/scan-worktree-secrets.sh &&
diff --git a/scripts/ubicloud/reap-expired.ts b/scripts/ubicloud/reap-expired.ts
index 790248ad56..27551f0e2a 100644
--- a/scripts/ubicloud/reap-expired.ts
+++ b/scripts/ubicloud/reap-expired.ts
@@ -15,14 +15,14 @@
* --now EPOCH evaluate at this time (default now; for tests and replays)
*
* Only names that carry a TTL are ever selected, in gstack's runner grammar
- * (the one gstack's `ubi-runner.sh reap` reads, expiring H hours after the
- * creation epoch):
+ * (exactly what gstack's `ubi-runner.sh reap` reads, expiring H hours after
+ * the creation epoch; an untagged ubirun-<epoch>-...-t<H> or -t0 counts too):
*
* ubirun-<owner>-<created epoch>-<suffix>-t<H>
*
* which `ci:ubicloud` writes for its gate VMs (`--ttl-hours`, default 2) and
* `ubi-runner.sh up|run` writes for every name it generates (`--ttl-hours H`,
- * default 999), whichever tool and owner made the VM; or in the older form
+ * else UBI_TTL_HOURS, default 3), whichever tool and owner made the VM; or in the older form
* gbrain wrote before it, reaped until none are left:
*
* ubirun-<owner>-<created epoch>-x<expiry epoch>-<suffix>
@@ -52,7 +52,10 @@ import { join } from "node:path";
const RUNNER = join(import.meta.dir, "ubi-runner.sh");
const MAX_NAME = 63;
const OWNER = "[a-z][a-z0-9]{0,11}";
-const TTL = new RegExp(`^ubirun-(${OWNER})-(\\d{10})-([a-z0-9][a-z0-9-]*)-t(\\d{1,3})$`);
+// gstack's vm_rows exactly: an owner-tagged or untagged ubirun- prefix, any
+// middle, and -t<1 to 3 digits> at the end (-t0 expires at creation).
+const TTL = new RegExp(`^ubirun-(${OWNER})-(\\d{10})(?:-[a-z0-9-]*)?-t(\\d{1,3})$`);
+const UNTAGGED_TTL = /^ubirun-(\d{10})(?:-[a-z0-9-]*)?-t(\d{1,3})$/;
const EXPIRING = new RegExp(`^ubirun-(${OWNER})-(\\d{10})-x(\\d{10})-([a-z0-9]{1,24})$`);
const NO_EXPIRY = new RegExp(`^ubirun-(${OWNER})-(\\d{10})-([a-z0-9]{1,24})$`);
const LEGACY = /^ubirun-(\d{10})-[a-z0-9]{1,24}$/;
@@ -65,7 +68,9 @@ export type ParsedName =
export function parseVmName(name: string): ParsedName {
let m = TTL.exec(name);
- if (m) return { kind: "expiring", owner: m[1]!, createdAt: Number(m[2]), expiresAt: Number(m[2]) + Number(m[4]) * 3600 };
+ if (m) return { kind: "expiring", owner: m[1]!, createdAt: Number(m[2]), expiresAt: Number(m[2]) + Number(m[3]) * 3600 };
+ m = UNTAGGED_TTL.exec(name);
+ if (m) return { kind: "expiring", owner: "(untagged)", createdAt: Number(m[1]), expiresAt: Number(m[1]) + Number(m[2]) * 3600 };
m = EXPIRING.exec(name);
if (m) return { kind: "expiring", owner: m[1]!, createdAt: Number(m[2]), expiresAt: Number(m[3]) };
m = NO_EXPIRY.exec(name);
@@ -97,7 +102,7 @@ export function planReap(rows: VmRow[], o: { now: number; graceSeconds: number }
if (parsed.kind === "foreign") return { ...row, parsed, action: "skip", reason: "not named by ubi-runner" };
if (parsed.kind === "legacy") return { ...row, parsed, action: "skip", reason: "legacy name" };
if (parsed.kind === "no-expiry") return { ...row, parsed, action: "skip", reason: "no expiry" };
- if (parsed.expiresAt <= parsed.createdAt) return { ...row, parsed, action: "skip", reason: "expiry before creation" };
+ if (EXPIRING.test(row.name) && parsed.expiresAt <= parsed.createdAt) return { ...row, parsed, action: "skip", reason: "expiry before creation" };
return { ...row, parsed, action: o.now >= parsed.expiresAt + o.graceSeconds ? "destroy" : "keep" };
});
}
diff --git a/scripts/ubicloud/ubi-runner.sh b/scripts/ubicloud/ubi-runner.sh
index 111b1399b3..b4dcef55c0 100755
--- a/scripts/ubicloud/ubi-runner.sh
+++ b/scripts/ubicloud/ubi-runner.sh
@@ -3,10 +3,30 @@
#
# UBICLOUD_API_KEY=... scripts/ubicloud/ubi-runner.sh run --setup S.sh -- 'make test'
#
-# Vendored from the gstack Ubicloud runner. gbrain additions: UBICLOUD_API_TOKEN
-# is accepted as an alias for UBICLOUD_API_KEY, SSH connections are multiplexed
-# per VM (scripts/ci-ubicloud.ts issues hundreds of short commands per VM), and
-# `pack` / `unpack` upload one prebuilt checkout tarball to many VMs.
+# Vendored from gstack's scripts/ubicloud/ubi-runner.sh (synced at gstack
+# 5532345a, v1.91.341.0). UBICLOUD_API_TOKEN is accepted as an alias for
+# UBICLOUD_API_KEY. SSH connections are multiplexed per VM, and `pack` /
+# `unpack` upload one prebuilt checkout tarball to many VMs.
+#
+# gbrain additions (keep them when syncing; each is marked "gbrain:" below):
+# - UBI_REAP defaults to 0: `up` reaps nothing unless UBI_REAP=1, and says so.
+# - --ttl-hours H on up and run (overrides UBI_TTL_HOURS); with -n NAME it
+# appends -t<H>, and a ubirun- NAME without a -t<H> TTL is refused.
+# - vm_rows also reads the older ubirun-<owner>-<epoch>-x<expiry>-<suffix> names.
+# - list --mine and gc cover every VM this machine created, under any owner tag.
+# - pack ships a slim .git (HEAD's branch and origin/master only), and a
+# split index's shared half.
+# - --env is checked like --pass (NAME=VALUE, never UBICLOUD_*).
+# - watched keeps one log per call (ci:ubicloud runs several on one VM at
+# once) and only after a kill.
+# - Bash 5.2 lost-signal-trap guard (set -E, FAILED, finish).
+#
+# Scratch record: every VM this machine creates is appended to a VM-id file
+# (UBI_VM_RECORD; default ~/.capy/work/ubi-runner/vms.tsv when ~/.capy/work
+# exists, else $STATE_ROOT/vms.tsv) as `name location owner created_at pid`,
+# and removed once `down` confirms it gone. A resumed Capy thread reads that
+# file to find VMs an earlier turn left behind (docs/TESTING_INTERNALS.md,
+# "Resuming after a wake").
#
# Creates a VM (standard-16 by default), streams the checkout to it (tracked +
# untracked-unignored files + .git, so uncommitted edits are included), runs an
@@ -15,20 +35,12 @@
# Needs only bash, curl, python3, ssh, ssh-keygen, and tar locally, so it works
# from dev boxes, containers, and cloud sandboxes.
#
-# Ownership: VMs are named ubirun-<owner>-<epoch>-<suffix>-t<H>. <owner> is UBI_OWNER
+# Ownership: VMs are named ubirun-<owner>-<epoch>-<suffix>-t<hours>. <owner> is UBI_OWNER
# (lowercased, letters and digits only, at most 12 characters, starting with a
-# letter) or a random per-machine id kept in $STATE_ROOT/owner-id. Ubicloud names
-# allow 63 characters of [a-z0-9-], so a full name stays under 50.
-#
-# Expiry: every name `up` and `run` generate ends in a TTL,
-# ubirun-<owner>-<epoch>-<suffix>-t<H>, expiring H hours after creation: H is
-# --ttl-hours (1 to 999), or 999 without it (about 41 days, for long dev,
-# benchmark and eval VMs). That is gstack's runner grammar, so the operator
-# reaper (scripts/ubicloud/reap-expired.ts) and gstack's reap both destroy a VM
-# once its TTL has ended, whoever owns it; ci:ubicloud names its gate VMs the
-# same way (2 hours by default). Every parser here still reads the older
-# ubirun-<owner>-<epoch>-x<expiry epoch>-<suffix> and TTL-less names, and a
-# generated name stays under 50 characters.
+# letter). `up`, `run` and `verify` refuse without it (UBI_OWNER_REQUIRED), so
+# every VM names whoever can be asked about it; read-only commands fall back to a
+# per-machine id kept in $STATE_ROOT/owner-id. Ubicloud names allow 63 characters
+# of [a-z0-9-], so a full name stays under 45.
#
# Teardown: `up` records each VM's state (location, create status) before it
# sends the create request, and `down` destroys and polls until the VM is
@@ -37,15 +49,45 @@
# that `down`; further signals are ignored until it finishes. A create refused
# for vCPU quota prints the project's usage per owner.
#
-# Stale-VM sweeps are off by default. With UBI_GC_HOURS set to a positive
+# The owner-age sweep is off by default (the TTL reap below always runs). With UBI_GC_HOURS set to a positive
# number, every `up` first destroys this owner's VMs older than that; `gc HOURS`
# runs the same sweep on demand. Neither ever touches another owner's VMs.
#
-# "This owner's VMs" (`list --mine`, `gc`, the `up` sweep) are the VMs tagged
-# with the caller's owner tag plus every VM this machine created under any tag:
-# `up` keeps a VM's state here until `down` confirms it gone, so a run started
-# with UBI_OWNER=x whose teardown never ran is still found by a later call that
-# did not export the same UBI_OWNER.
+# TTL and reaper: a name this script generates ends in -t<hours> (UBI_TTL_HOURS,
+# 1-999, default 3), the creator's own declaration of how long the VM may live.
+# `reap` destroys every VM in the project whose TTL expired more than ten
+# minutes ago, whichever owner made it, and this owner's own ubirun-<owner>-*
+# names with no TTL once they are UBI_LEGACY_HOURS old (default 4; another
+# owner's or an untagged TTL-less VM is never reaped); every `up` runs it first when UBI_REAP=1
+# (gbrain: off by default until gbrain's TTL-less VMs older than 4 h are gone;
+# the operator reaper, scripts/ubicloud/reap-expired.ts, still destroys expired
+# TTL VMs), so a runner killed by a sleeping machine leaves nothing behind for
+# longer than its TTL. --ttl-hours H (gbrain) sets one VM's TTL.
+# Names outside the ubirun- prefix are never reaped.
+#
+# Leftover line: `run` and `verify` end with
+# UBICLOUD: left=<0|1|unknown> owner=<owner> vm=<name> others=<n>
+# after teardown: left counts this invocation's own VM, checked against the
+# project's VM list, and others counts this owner's other VMs (information only).
+# A left other than 0 turns a passing command into exit 1; `run --keep` reports
+# its live VM as left=1 kept=1 and keeps its exit status. With UBI_LEFT_FILE set,
+# the line is also appended to that file, out of reach of the command's output.
+#
+# Quota preflight: when the project's vCPU ceiling is known (UBI_QUOTA_VCPUS, or
+# the maximum a refusal printed, cached in $STATE_ROOT/quota-max), `up` adds the
+# size's vCPUs to the project's running VMs and refuses before any create when
+# that exceeds it; UBI_QUOTA_WAIT=<seconds> waits for room instead.
+#
+# Watchdog: `run`, `verify` and `ssh NAME COMMAND` stream the remote output
+# through a watchdog that logs a heartbeat every UBI_HEARTBEAT seconds (300)
+# and kills a command silent for UBI_IDLE_TIMEOUT seconds (1800) or older than
+# UBI_RUN_TIMEOUT seconds (0, unlimited), exiting 124 with the last 40 lines,
+# so a hung verify fails fast instead of holding the VM until its TTL.
+#
+# `verify` is the one entry point for a repository's full remote verify: it
+# reads .gstack/ubicloud.json (setup, command, size, location, env, pass, pull)
+# and runs it through `run`, so lanes share one committed definition instead of
+# per-lane wrappers.
set -Eeuo pipefail
# Keep heredoc bodies on temp files, not the pipe window (test/heredoc-pipe-deadlock.test.ts).
BASH_COMPAT=50
@@ -59,22 +101,37 @@ API_TIMEOUT="${UBI_API_TIMEOUT:-120}"
CREATE_GRACE="${UBI_CREATE_GRACE:-180}"
DOWN_TIMEOUT="${UBI_DOWN_TIMEOUT:-900}"
POLL="${UBI_POLL_SECONDS:-5}"
+ALLOWED_STORAGE="${UBI_ALLOWED_STORAGE:-320 640}"
+TTL_HOURS="${UBI_TTL_HOURS:-3}"
+LEGACY_HOURS="${UBI_LEGACY_HOURS:-4}"
+# gbrain: no reap before up unless UBI_REAP=1 (GBRA-108).
+REAP="${UBI_REAP:-0}"
+REAP_GRACE=600
+IDLE_TIMEOUT="${UBI_IDLE_TIMEOUT:-1800}"
+RUN_TIMEOUT="${UBI_RUN_TIMEOUT:-0}"
+HEARTBEAT="${UBI_HEARTBEAT:-300}"
+QUOTA_VCPUS="${UBI_QUOTA_VCPUS:-}"
+QUOTA_WAIT="${UBI_QUOTA_WAIT:-0}"
PREFIX="ubirun"
+if [ -n "${UBI_VM_RECORD:-}" ]; then VM_RECORD="$UBI_VM_RECORD"
+elif [ -d "$HOME/.capy/work" ]; then VM_RECORD="$HOME/.capy/work/ubi-runner/vms.tsv"
+else VM_RECORD="$STATE_ROOT/vms.tsv"; fi
die() { echo "ubi-runner: $*" >&2; exit 1; }
log() { echo "ubi-runner: $*" >&2; }
-# Bash 5.2 can lose a signal trap: when the signal lands just before the shell
-# parses a $(...), the trap runs inside that parse, fails to parse itself
-# ("trap: line 2: unexpected EOF while looking for matching `)'") and the shell
-# exits 2 without running it (fixed in bash 5.3). The EXIT trap still runs.
-# The only other exit 2 here is a failed command, which sets FAILED through
-# the ERR trap, so finish reports an exit 2 without FAILED as the signal's 130.
+# gbrain: Bash 5.2 can lose a signal trap: when the signal lands just before
+# the shell parses a $(...), the trap runs inside that parse, fails to parse
+# itself ("trap: line 2: unexpected EOF while looking for matching `)'") and the
+# shell exits 2 without running it (fixed in bash 5.3). The EXIT trap still
+# runs. The only other exit 2 here is a failed command, which sets FAILED
+# through the ERR trap, so an exit 2 without FAILED is reported as the
+# signal's 130.
FAILED=""
trap 'FAILED=1' ERR
-# finish STATUS NAME: EXIT handler of `up` and `run`. Destroys NAME unless it
-# is empty, then exits with STATUS.
+# finish STATUS NAME: EXIT handler of `up`. Destroys NAME unless it is empty,
+# then exits with STATUS.
finish() {
local rc=$1
[ "$rc" != 2 ] || [ -n "$FAILED" ] || rc=130
@@ -87,6 +144,10 @@ for bin in curl python3 ssh ssh-keygen tar; do
done
UBICLOUD_API_KEY="${UBICLOUD_API_KEY:-${UBICLOUD_API_TOKEN:-}}"
[[ "$GC_HOURS" =~ ^[0-9]+$ ]] || die "UBI_GC_HOURS must be a whole number of hours (unset or 0 disables the sweep)"
+for v in IDLE_TIMEOUT RUN_TIMEOUT HEARTBEAT QUOTA_WAIT; do
+ [[ "${!v}" =~ ^[0-9]+$ ]] || die "UBI_$v must be a whole number of seconds (0 disables it)"
+done
+[ -z "$QUOTA_VCPUS" ] || [[ "$QUOTA_VCPUS" =~ ^[0-9]+$ ]] || die "UBI_QUOTA_VCPUS must be a whole number of vCPUs"
owner_id() {
local raw=${UBI_OWNER:-} file="$STATE_ROOT/owner-id" tmp
@@ -107,6 +168,21 @@ owner_id() {
}
OWNER=$(owner_id)
+# require_owner: up, run and verify create VMs, and a VM must name its owner
+# and carry a TTL. Only creates check UBI_TTL_HOURS, so an old value never
+# blocks down, reap or list.
+require_owner() {
+ [ -n "${UBI_OWNER:-}" ] || die "UBI_OWNER is not set: every VM must carry its owner; export UBI_OWNER=<your thread or session code> (for example gsta164) and rerun (UBI_OWNER_REQUIRED)"
+ [[ "$TTL_HOURS" =~ ^[1-9][0-9]{0,2}$ ]] || die "UBI_TTL_HOURS must be a whole number of hours from 1 to 999 with no leading zero (every VM carries a TTL; set it above your longest run)"
+}
+
+# leftover FIELDS...: print the UBICLOUD: leftover line, and append it to
+# UBI_LEFT_FILE when set, so a caller can read it apart from the command's output.
+leftover() {
+ echo "UBICLOUD: $*" >&2
+ [ -z "${UBI_LEFT_FILE:-}" ] || echo "UBICLOUD: $*" >>"$UBI_LEFT_FILE"
+}
+
# api OUT ARGS...: send one Ubicloud CLI command, write the body to OUT, and
# print the HTTP status (000 when no response arrived).
api() {
@@ -163,33 +239,170 @@ remote() {
ssh $(ssh_opts) "ubi@$IP" "umask 022; $*"
}
-# vm_rows: "location name owner" for every VM in the project; owner is
-# "-" for untagged ubirun-<epoch>-* names and "." for VMs this runner did not name.
+mtime() { stat -c %Y "$1" 2>/dev/null || stat -f %m "$1"; }
+
+# sq STRING: STRING as one single-quoted shell word.
+sq() { printf "'%s'" "$(printf %s "$1" | sed "s/'/'\\\\''/g")"; }
+
+# remote_cancel NAME SIDFILE: end the session a watched command started on the
+# VM (its leader pid is in SIDFILE there), bounded to 20 seconds. Killing the
+# local ssh client alone leaves a silent remote command running until it next
+# writes to the closed channel.
+remote_cancel() {
+ local name=$1 sidf=$2 cpid i=0
+ remote "$name" "sid=\$(cat $sidf 2>/dev/null); rm -f $sidf; [ -z \"\$sid\" ] || { pkill -TERM -s \"\$sid\"; sleep 2; pkill -KILL -s \"\$sid\"; }; true" >/dev/null 2>&1 </dev/null &
+ cpid=$!
+ while kill -0 "$cpid" 2>/dev/null && [ "$i" -lt 20 ]; do sleep 1; i=$(( i + 1 )); done
+ kill "$cpid" 2>/dev/null || true
+ wait "$cpid" 2>/dev/null || true
+}
+
+# watched NAME PHASE COMMAND: run COMMAND on the VM, streaming its output and
+# keeping a copy of both streams in PHASE-<runner pid>.log in the VM's state
+# dir (gbrain: one file per call, since ci:ubicloud runs several commands on
+# one VM at once; kept only after a kill), with a heartbeat every HEARTBEAT
+# seconds and a watchdog that kills it after IDLE_TIMEOUT seconds of silence or
+# RUN_TIMEOUT seconds in total: exit 124, reason and the last 40 lines on
+# stderr. The ssh runs in its own session (python3's setsid) so the watchdog
+# kills it and anything it started, not just the shell that launched it; on
+# the VM the command runs in its own session too (setsid where the image has
+# it), whose leader pid is written to ~/.ubirun-PHASE-<runner pid>.sid so
+# remote_cancel can end it when the client is killed.
+watched() {
+ local name=$1 phase=$2 cmd=$3 out pid rc=0 start now last_beat idle elapsed why="" old_traps inner sidf
+ sidf="~/.ubirun-$phase-$$.sid"
+ load "$name"
+ out="$(state_dir "$name")/$phase-$$.log"
+ : >"$out"
+ inner=$(sq "printf %s \$\$ >$sidf; $cmd")
+ # The sid file outlives the command on purpose: a background child it left
+ # behind keeps the ssh channel open after the wrapper exits, and remote_cancel
+ # still needs the session id to end it. remote_cancel removes the file.
+ cmd="if command -v setsid >/dev/null 2>&1; then setsid -w bash -c $inner; else bash -c $inner; fi"
+ # The caller's stdin is handed to the background ssh explicitly (a background
+ # job in a non-interactive shell would otherwise read /dev/null), so piped
+ # input reaches the remote command as it did before the watchdog.
+ exec 3<&0
+ # shellcheck disable=SC2046
+ ( exec python3 -c 'import os, sys; os.setsid(); os.execvp(sys.argv[1], sys.argv[1:])' \
+ ssh $(ssh_opts) "ubi@$IP" "umask 022; $cmd" ) <&3 > >(tee -a "$out") 2> >(tee -a "$out" >&2) &
+ pid=$!
+ exec 3<&-
+ # A signal to this process takes the ssh session down with it, so Ctrl-C on
+ # `ssh NAME COMMAND` leaves no orphaned client behind.
+ old_traps=$(trap -p INT TERM)
+ trap 'kill -TERM -- "-$pid" 2>/dev/null; exit 130' INT TERM
+ start=$(date +%s)
+ last_beat=$start
+ while :; do
+ sleep 1
+ kill -0 "$pid" 2>/dev/null || break
+ now=$(date +%s)
+ elapsed=$(( now - start ))
+ idle=$(( now - $(mtime "$out") ))
+ if [ "$IDLE_TIMEOUT" -gt 0 ] && [ "$idle" -ge "$IDLE_TIMEOUT" ]; then
+ why="printed nothing for ${idle}s (UBI_IDLE_TIMEOUT=$IDLE_TIMEOUT)"
+ elif [ "$RUN_TIMEOUT" -gt 0 ] && [ "$elapsed" -ge "$RUN_TIMEOUT" ]; then
+ why="ran ${elapsed}s (UBI_RUN_TIMEOUT=$RUN_TIMEOUT)"
+ fi
+ if [ -n "$why" ]; then
+ # The command may have finished while the clock was read; a finished
+ # command is never reported as a timeout.
+ kill -0 "$pid" 2>/dev/null || break
+ log "watchdog: $phase $why; killing it. Last output:"
+ tail -n 40 "$out" >&2
+ kill -TERM -- "-$pid" 2>/dev/null || kill "$pid" 2>/dev/null || true
+ wait "$pid" 2>/dev/null || rc=$?
+ trap - INT TERM; eval "$old_traps"
+ # A command killed by the watchdog never exits 0; a 0 here means it
+ # finished in the instant before the kill, and that result stands.
+ if [ "$rc" -eq 0 ]; then
+ log "watchdog: $phase finished before it could be killed; its exit 0 stands"
+ rm -f "$out"
+ return 0
+ fi
+ remote_cancel "$name" "$sidf"
+ log "watchdog: kept the output in $out"
+ return 124
+ fi
+ if [ "$HEARTBEAT" -gt 0 ] && [ $(( now - last_beat )) -ge "$HEARTBEAT" ]; then
+ log "heartbeat: $phase ${elapsed}s elapsed, last output ${idle}s ago"
+ last_beat=$now
+ fi
+ done
+ wait "$pid" || rc=$?
+ trap - INT TERM; eval "$old_traps"
+ rm -f "$out"
+ return "$rc"
+}
+
+# vm_rows: "location name owner expires created" for every VM in the project;
+# owner is "-" for untagged ubirun-<epoch>-* names and "." for VMs this runner
+# did not name; expires is the epoch the name's -t<hours> TTL ends at (gbrain:
+# or the older -x<expiry epoch>- form's expiry, when later than its creation),
+# or "-"; created is the name's epoch, or "-".
vm_rows() {
+ local loc name owner created expires
cli vm list -N -f location,name | while read -r loc name; do
- if [[ "$name" =~ ^${PREFIX}-([a-z][a-z0-9]{0,11})-[0-9]{10}- ]]; then
- echo "$loc $name ${BASH_REMATCH[1]}"
- elif [[ "$name" =~ ^${PREFIX}-[0-9]{10}- ]]; then
- echo "$loc $name -"
- else
- echo "$loc $name ."
+ owner=. created="" expires=-
+ if [[ "$name" =~ ^${PREFIX}-([a-z][a-z0-9]{0,11})-([0-9]{10})- ]]; then
+ owner=${BASH_REMATCH[1]} created=${BASH_REMATCH[2]}
+ if [[ "$name" =~ ^${PREFIX}-[a-z][a-z0-9]{0,11}-[0-9]{10}-x([0-9]{10})-[a-z0-9]+$ ]] && [ "${BASH_REMATCH[1]}" -gt "$created" ]; then
+ expires=$(( 10#${BASH_REMATCH[1]} ))
+ fi
+ elif [[ "$name" =~ ^${PREFIX}-([0-9]{10})- ]]; then
+ owner=- created=${BASH_REMATCH[1]}
fi
+ if [ -n "$created" ] && [[ "$name" =~ -t([0-9]{1,3})$ ]]; then
+ expires=$(( 10#$created + 10#${BASH_REMATCH[1]} * 3600 ))
+ fi
+ echo "$loc $name $owner $expires ${created:--}"
done
}
-# mine_rows: vm_rows for the VMs tagged with this owner or created from this machine (their `up` state is still here).
+# mine_rows: vm_rows for the VMs tagged with this owner or created from this
+# machine (their `up` state is still here). gbrain: list --mine and gc use it,
+# so a run started under another UBI_OWNER is still found.
mine_rows() {
- local loc name owner
- vm_rows | while read -r loc name owner; do
- if [ "$owner" = "$OWNER" ] || [ -f "$(state_dir "$name")/env" ]; then echo "$loc $name $owner"; fi
+ local loc name owner rest
+ vm_rows | while read -r loc name owner rest; do
+ if [ "$owner" = "$OWNER" ] || [ -f "$(state_dir "$name")/env" ]; then echo "$loc $name $owner $rest"; fi
done
}
+# reap: destroy every VM whose name carries a TTL that ended more than
+# REAP_GRACE seconds ago, whichever owner created it (the TTL is that owner's
+# own declaration), and the caller's own TTL-less ubirun-<UBI_OWNER>-* names at
+# least LEGACY_HOURS old. Another owner's TTL-less VM, an untagged one, and names
+# outside the prefix are never touched: only a TTL lets reap judge another lane's VM.
+cmd_reap() {
+ local now rows loc name owner expires created n=0 failed=0
+ [[ "$LEGACY_HOURS" =~ ^[1-9][0-9]{0,3}$ ]] || die "UBI_LEGACY_HOURS must be a whole number of hours from 1 to 9999 with no leading zero (how old a TTL-less ubirun-* VM must be before reap destroys it)"
+ now=$(date +%s)
+ rows=$(vm_rows) || { log "reap: could not list the project's VMs; nothing destroyed"; return 1; }
+ while read -r loc name owner expires created; do
+ [ -n "$name" ] || continue
+ if [ "$expires" != - ]; then
+ [ "$now" -ge $(( expires + REAP_GRACE )) ] || continue
+ log "reaping expired $loc/$name (owner $owner; its TTL ended $(( (now - expires) / 60 )) min ago)"
+ else
+ [ -n "${UBI_OWNER:-}" ] && [ "$owner" = "$OWNER" ] && [ "$created" != - ] || continue
+ [ $(( now - 10#$created )) -ge $(( LEGACY_HOURS * 3600 )) ] || continue
+ log "reaping TTL-less $loc/$name (owner $owner; $(( (now - 10#$created) / 3600 ))h old, legacy sweep at ${LEGACY_HOURS}h)"
+ fi
+ n=$(( n + 1 ))
+ cmd_down "$name" -l "$loc" || { failed=$(( failed + 1 )); log "failed to reap $loc/$name"; }
+ done <<<"$rows"
+ [ "$n" -gt 0 ] || log "reap: no expired VMs"
+ [ "$failed" -eq 0 ] || { log "reap: $failed of $n expired VMs could not be destroyed"; return 1; }
+}
+
cmd_gc() {
local hours=${1:-$GC_HOURS} now loc name owner
- if ! [[ "$hours" =~ ^[0-9]+$ ]] || [ "$hours" -eq 0 ]; then die "gc: give HOURS > 0 (or set UBI_GC_HOURS)"; fi
+ [[ "$hours" =~ ^[0-9]+$ ]] || die "gc: HOURS must be a whole number (or set UBI_GC_HOURS)"
+ if [ "$hours" -eq 0 ]; then log "gc: no sweep (give HOURS > 0 or set UBI_GC_HOURS); nothing listed, nothing destroyed"; return 0; fi
now=$(date +%s)
- mine_rows | while read -r loc name owner; do
+ mine_rows | while read -r loc name owner _; do
[[ "$name" =~ -([0-9]{10})- ]] || continue
if [ $(( (now - BASH_REMATCH[1]) / 3600 )) -ge "$hours" ]; then
log "destroying stale $loc/$name (owner $owner, older than ${hours}h)"
@@ -215,18 +428,18 @@ cmd_list() {
cmd_usage() {
local tmp loc name owner i=0
tmp=$(mktemp -d)
- while read -r loc name owner; do
+ while read -r loc name owner _; do
i=$(( i + 1 ))
cli vm "$loc/$name" show 2>/dev/null | sed -n "s/^size: /$owner /p" >"$tmp/$i" &
[ $(( i % 8 )) -ne 0 ] || wait
done < <(vm_rows)
wait
cat "$tmp"/* 2>/dev/null | awk -v me="$OWNER" '
- { n = $2; sub(/^.*-/, "", n); o = $1 == "-" ? "(untagged)" : $1 == "." ? "(other)" : $1
+ { n = $2; sub(/^.*-/, "", n); o = ($1 == "-") ? "(untagged)" : ($1 == ".") ? "(other)" : $1
vms[o]++; cpu[o] += n; total += n; count++ }
END {
printf "%-14s %4s %6s\n", "OWNER", "VMS", "VCPUS"
- for (o in cpu) printf "%-14s %4d %6d%s\n", o, vms[o], cpu[o], o == me ? " (you)" : "" | "sort -k3,3nr"
+ for (o in cpu) printf("%-14s %4d %6d%s\n", o, vms[o], cpu[o], (o == me) ? " (you)" : "") | "sort -k3,3nr"
close("sort -k3,3nr")
printf "%-14s %4d %6d\n", "total", count, total
}'
@@ -238,41 +451,132 @@ write_state() {
"$1" "$2" "$3" "$4" "$5" "$6" "$$" >"$(state_dir "$1")/env"
}
-# new_name TTL_HOURS: a fresh name for this owner whose TTL ends TTL_HOURS after now.
+# record_vm NAME LOCATION: append to the scratch VM-id file (record-before-create).
+record_vm() {
+ mkdir -p "$(dirname "$VM_RECORD")" 2>/dev/null || return 0
+ printf '%s\t%s\t%s\t%s\t%s\n' "$1" "$2" "$OWNER" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$$" >>"$VM_RECORD"
+}
+
+# forget_vm NAME: drop the VM from the scratch file once it is confirmed gone.
+forget_vm() {
+ [ -f "$VM_RECORD" ] || return 0
+ local tmp="$VM_RECORD.$$"
+ awk -F'\t' -v n="$1" '$1!=n' "$VM_RECORD" >"$tmp" && mv "$tmp" "$VM_RECORD"
+}
+
+# records: print the scratch file (VMs this machine created and has not confirmed gone).
+cmd_records() {
+ echo "record: $VM_RECORD"
+ [ -s "$VM_RECORD" ] || { echo "(no VMs recorded)"; return 0; }
+ printf '%-40s %-14s %-12s %-20s %s\n' NAME LOCATION OWNER CREATED_AT PID
+ awk -F'\t' '{ printf "%-40s %-14s %-12s %-20s %s\n", $1, $2, $3, $4, $5 }' "$VM_RECORD"
+}
+
+# new_name [TTL]: a fresh name for this owner ending in -t<TTL> (default UBI_TTL_HOURS).
new_name() {
- local suffix
- suffix=$(head -c4 /dev/urandom | od -An -tx1 | tr -d ' \n')
- echo "$PREFIX-$OWNER-$(date +%s)-$suffix-t$1"
+ echo "$PREFIX-$OWNER-$(date +%s)-$(head -c4 /dev/urandom | od -An -tx1 | tr -d ' \n')-t${1:-$TTL_HOURS}"
}
+# gbrain: check_ttl H validates --ttl-hours.
check_ttl() {
- [[ "$1" =~ ^[1-9][0-9]{0,2}$ ]] \
- || die "--ttl-hours must be a whole number of hours from 1 to 999 (omit it for the longest TTL, 999 hours)"
+ [[ "$1" =~ ^[1-9][0-9]{0,2}$ ]] || die "--ttl-hours must be a whole number of hours from 1 to 999"
+}
+
+# gbrain: vm_name NAME TTL: the name up and run create. No NAME: a generated
+# one, with TTL hours (else UBI_TTL_HOURS). -n NAME with --ttl-hours gets
+# -t<TTL> appended. A ubirun- NAME must end in a -t<hours> TTL, or no reaper
+# could ever judge it (#8050); names outside the prefix are the caller's to manage.
+vm_name() {
+ local name=$1 ttl=$2
+ if [ -z "$name" ]; then new_name "$ttl"; return; fi
+ if [ -n "$ttl" ]; then
+ [[ ! "$name" =~ -t[0-9]+$ ]] || die "-n $name already ends in a TTL; drop --ttl-hours or the -t<hours> suffix"
+ name="$name-t$ttl"
+ fi
+ if [[ "$name" = "$PREFIX"-* ]] && [[ ! "$name" =~ -t[1-9][0-9]{0,2}$ ]]; then
+ die "-n $name has no -t<hours> TTL, so no reaper could destroy it if this run dies; add --ttl-hours H (1-999) or name it outside the $PREFIX- prefix"
+ fi
+ echo "$name"
+}
+
+# vcpus SIZE: the vCPU count a Ubicloud size name carries (standard-16 -> 16).
+vcpus() { [[ "$1" =~ -([0-9]+)$ ]] && echo "${BASH_REMATCH[1]}"; }
+
+# quota_preflight LOCATION NAME SIZE: refuse (or wait UBI_QUOTA_WAIT seconds)
+# before the create request when the project's running VMs plus this size
+# exceed the known vCPU ceiling. The ceiling comes from UBI_QUOTA_VCPUS or the
+# maximum the last refusal printed; without either the API's own refusal rules.
+QUOTA_CACHE_MAX_AGE=86400
+quota_preflight() {
+ local location=$1 name=$2 size=$3 need max used remaining step source="UBI_QUOTA_VCPUS" cache="$STATE_ROOT/quota-max"
+ need=$(vcpus "$size") || return 0
+ max=$QUOTA_VCPUS
+ if [ -z "$max" ] && [ -f "$cache" ]; then
+ # A refusal's maximum is remembered for a day: after that (a raised quota,
+ # another project's key) the API's own answer decides again.
+ if [ $(( $(date +%s) - $(mtime "$cache") )) -lt "$QUOTA_CACHE_MAX_AGE" ]; then
+ max=$(cat "$cache" 2>/dev/null || true); source="the last refusal, cached in $cache"
+ else
+ rm -f "$cache"
+ fi
+ fi
+ [[ "$max" =~ ^[0-9]+$ ]] || return 0
+ # The budget counts seconds spent waiting for room, not the usage calls
+ # between them: a slow first usage read must not shave the printed budget.
+ remaining=$QUOTA_WAIT
+ while :; do
+ used=$(cmd_usage 2>/dev/null | awk '$1=="total" {print $3}')
+ [[ "$used" =~ ^[0-9]+$ ]] || return 0
+ [ $(( used + need )) -gt "$max" ] || return 0
+ if [ "$remaining" -le 0 ]; then
+ log "quota preflight refused $location/$name ($size): it needs $need vCPUs and the project's VMs already use $used of $max (ceiling from $source; other usage such as managed runners counts on top)"
+ cmd_usage >&2 || true
+ die "create refused before any request: vCPU quota exhausted (quota full); wait for running VMs to finish (UBI_QUOTA_WAIT=<seconds> waits here), run $0 reap, use a smaller size, or set UBI_QUOTA_VCPUS to the project's real ceiling"
+ fi
+ log "quota: $used of $max vCPUs in use and $need needed; waiting up to ${remaining}s more for room"
+ step=$(( remaining < 30 ? remaining : 30 ))
+ sleep "$step"
+ remaining=$(( remaining - step ))
+ done
}
valid_name() { [[ "$1" =~ ^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$ ]]; }
+# check_storage GIB: Ubicloud accepts only these disk sizes; refuse before any API call.
+check_storage() {
+ case " $ALLOWED_STORAGE " in
+ *" $1 "*) [ -n "$1" ] && return 0 ;;
+ esac
+ die "invalid storage '$1' GiB (allowed: $ALLOWED_STORAGE; set UBI_ALLOWED_STORAGE when Ubicloud adds sizes)"
+}
+
UP_NAME=""
UP_READY=""
cmd_up() {
+ require_owner
local size=$DEFAULT_SIZE location=$DEFAULT_LOCATION name="" storage="" image=ubuntu-noble ttl=""
while [ $# -gt 0 ]; do
case $1 in
-s|--size) size=$2; shift 2 ;;
-l|--location) location=$2; shift 2 ;;
-n|--name) name=$2; shift 2 ;;
- -S|--storage) storage=$2; shift 2 ;;
+ -S|--storage) check_storage "$2"; storage=$2; shift 2 ;;
-b|--image) image=$2; shift 2 ;;
--ttl-hours) check_ttl "$2"; ttl=$2; shift 2 ;;
*) die "up: unknown option $1" ;;
esac
done
- [ -z "$name" ] || [ -z "$ttl" ] || die "up: --ttl-hours writes the expiry into the generated name, so it cannot be combined with -n"
- [ -n "$name" ] || name=$(new_name "${ttl:-999}")
+ name=$(vm_name "$name" "$ttl")
valid_name "$name" || die "invalid VM name '$name' (Ubicloud allows 1-63 of a-z, 0-9 and '-', starting and ending with a letter or digit)"
+ if [ "$REAP" != 0 ]; then
+ cmd_reap || log "reap failed; continuing"
+ elif [ -z "${UBI_REAP:-}" ]; then
+ log "reap skipped: gbrain defaults UBI_REAP=0 until its TTL-less VMs older than ${LEGACY_HOURS}h are gone (UBI_REAP=1 reaps; reap-expired.ts still destroys expired TTL VMs)"
+ fi
if [ "$GC_HOURS" -gt 0 ]; then
cmd_gc "$GC_HOURS" || log "stale-VM cleanup failed; continuing"
fi
+ quota_preflight "$location" "$name" "$size"
local dir create_at
dir=$(state_dir "$name")
@@ -285,6 +589,7 @@ cmd_up() {
args+=("$(cat "$dir/key.pub")")
create_at=$(date +%s)
write_state "$name" "$location" "$size" "" unknown "$create_at"
+ record_vm "$name" "$location"
UP_NAME=$name
log "creating $location/$name ($size)"
# Hold signals until the create answer is recorded, so teardown knows
@@ -302,6 +607,7 @@ cmd_up() {
die "create failed"
fi
read -r need used max <<<"$refusal"
+ echo "$max" >"$STATE_ROOT/quota-max"
log "quota refused $location/$name ($size): it needs $need vCPUs and the project already uses $used of $max"
log "VMs in the project by owner (the rest of the used count is other usage, such as managed GitHub runners):"
cmd_usage >&2 || true
@@ -372,7 +678,13 @@ cmd_down() {
if [ "$code" = 200 ]; then
seen=1
if [ $(( now - asked )) -ge 60 ]; then
- api "$out" vm "$loc/$name" destroy -f >/dev/null
+ code=$(api "$out" vm "$loc/$name" destroy -f)
+ if [ "$code" != 200 ]; then
+ cat "$out" >&2
+ rm -f "$out"
+ log "FAILED to destroy $loc/$name (HTTP $code); retry: $0 down $name"
+ return 1
+ fi
asked=$now
log "destroy requested: $loc/$name"
fi
@@ -381,6 +693,7 @@ cmd_down() {
&& { [ "$CREATE_PID" = "$$" ] || ! kill -0 "$CREATE_PID" 2>/dev/null; }; }; then
rm -f "$out"
rm -rf "$dir"
+ forget_vm "$name"
if [ "$seen" = 1 ]; then log "destroyed ${loc:-?}/$name"; else log "gone: ${loc:-?}/$name (never existed or already destroyed)"; fi
return 0
fi
@@ -395,45 +708,73 @@ cmd_down() {
done
}
-# slim_git SRC DIR: build DIR/.git holding only the objects HEAD and
-# origin/master reach, with SRC's branch, index and config, so a checkout that
-# fetched many branches does not upload all of them to every VM. Fails (and
-# the caller ships SRC's own .git) on anything unexpected.
-slim_git() {
- local src=$1 dir=$2 git_dir common branch specs
- git_dir=$(git -C "$src" rev-parse --absolute-git-dir) || return 1
- common=$(cd "$src" && cd "$(git rev-parse --git-common-dir)" && pwd) || return 1
- branch=$(git -C "$src" symbolic-ref -q HEAD) || branch=""
- specs=("+HEAD:${branch:-refs/heads/ubi-pack-head}")
- if git -C "$src" rev-parse -q --verify refs/remotes/origin/master >/dev/null; then
- specs+=("+refs/remotes/origin/master:refs/remotes/origin/master")
- fi
- git init -q "$dir" &&
- # --update-head-ok: the fresh repo's unborn HEAD names init's default branch
- # (master), which is also the branch a checkout on master fetches into.
- git -C "$dir" fetch -q --update-head-ok --update-shallow --no-tags --no-write-fetch-head "$src" "${specs[@]}" &&
- cp "$common/config" "$dir/.git/config" &&
- { [ ! -f "$git_dir/index" ] || cp "$git_dir/index" "$dir/.git/index"; } &&
- if [ -n "$branch" ]; then git -C "$dir" symbolic-ref HEAD "$branch"; else git -C "$dir" update-ref --no-deref HEAD "$(git -C "$src" rev-parse HEAD)"; fi
-}
-
# pack SRC: write a gzipped checkout tarball to stdout (tracked + untracked
-# files that are not ignored, plus a slim .git; a non-git directory is taken whole).
+# files that are not ignored, plus a .git snapshot; a non-git directory is
+# taken whole). The live .git is never tarred: another process running git in
+# the checkout (a review subagent's diff, a trial merge's worktree add) writes
+# index.lock, packed-refs and objects while tar reads, and GNU tar exits 1
+# on a file that changed under it (GSTA-121's PREGATE_REMOTE_INFRA). Instead
+# the refs are fetched into a fresh repository through git's own transport,
+# which reads a consistent view, the remote.* config is replayed so
+# origin/<base> still resolves, and the index is copied (git writes it
+# atomically through a rename). A linked worktree's .git is a one-line
+# pointer into the main repository, useless on the VM; the same snapshot
+# replaces it, on the worktree's own branch and index. Not carried: submodule
+# repositories (.git/modules) and a partial clone's promisor (the fetch pulls
+# every missing blob first); gstack has neither.
cmd_pack() {
- local src tmp
+ local src tmp gitdir branch head entry shared specs
src=$(cd "${1:-.}" && pwd)
if git -C "$src" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
+ head=$(git -C "$src" rev-parse --verify -q HEAD) || die "pack: $src has no commits; the VM needs a HEAD to fingerprint"
+ branch=$(git -C "$src" symbolic-ref -q --short HEAD || true)
tmp=$(mktemp -d)
+ # The path is baked in: a set -e failure unwinds the function before the trap runs, and a local $tmp is unset there.
+ trap "rm -rf $(printf %q "$tmp")" EXIT
+ # No template hooks from a global init.templateDir, and no auto-gc under the tar.
+ git -c gc.auto=0 init -q --bare --template= "$tmp/.git"
+ # gbrain: a slim snapshot, only HEAD (on its branch) and origin/master, so a
+ # checkout that fetched many branches does not upload all of them to every VM.
+ [ -n "$branch" ] || branch="detached-${head:0:12}"
+ specs=("+HEAD:refs/heads/$branch")
+ if git -C "$src" rev-parse -q --verify refs/remotes/origin/master >/dev/null; then
+ specs+=("+refs/remotes/origin/master:refs/remotes/origin/master")
+ fi
+ git -C "$tmp/.git" -c gc.auto=0 fetch -q --no-tags --update-shallow "$src" "${specs[@]}" \
+ || die "pack: could not snapshot the refs of $src"
+ git -C "$tmp/.git" symbolic-ref HEAD "refs/heads/$branch"
+ git -C "$tmp/.git" config core.bare false
+ gitdir=$(cd "$src" && cd "$(git rev-parse --git-common-dir)" && pwd)
+ while IFS= read -r -d '' entry; do
+ # A key with no value (`[remote "x"] mirror`) is boolean true.
+ case $entry in *$'\n'*) ;; *) entry="$entry"$'\n'true ;; esac
+ git -C "$tmp/.git" config --add "${entry%%$'\n'*}" "${entry#*$'\n'}"
+ done < <(git -C "$gitdir" config --local --null --get-regexp '^(remote|branch)\.' 2>/dev/null || true)
+ # The checkout's index rides along so the VM's status matches (gbrain: a
+ # split index with its shared half, sharedindex.<sha>, which git looks up
+ # beside it). The index's blobs that HEAD's tree lacks (staged,
+ # intent-to-add, the stages of an unmerged entry) are behind no ref, so
+ # they travel as a pack of their own; without them the VM's write-tree
+ # cannot read a staged file.
+ cp "$(cd "$src" && cd "$(dirname "$(git rev-parse --git-path index)")" && pwd)/index" "$tmp/.git/index"
+ shared=$(cd "$src" && git rev-parse --shared-index-path)
+ [ -z "$shared" ] || cp "$(cd "$src" && cd "$(dirname "$shared")" && pwd)/$(basename "$shared")" "$tmp/.git/"
+ # Read the copy, not the live index, so the pack matches it; a gitlink's
+ # sha (mode 160000) is a submodule commit this object store lacks.
+ GIT_INDEX_FILE="$tmp/.git/index" git -C "$src" ls-files -s | awk '$1 != "160000" {print $2}' | sort -u \
+ | comm -23 - <(git -C "$src" ls-tree -r HEAD | awk '{print $3}' | sort -u) \
+ | git -C "$src" pack-objects -q --stdout \
+ | git -C "$tmp/.git" unpack-objects -q \
+ || die "pack: could not snapshot the staged blobs of $src"
(
cd "$src"
- if slim_git "$src" "$tmp/repo" >&2; then git_from=(-C "$tmp/repo" .git); else git_from=(.git); fi
git ls-files -z -co --exclude-standard \
| while IFS= read -r -d '' f; do
- if { [ -e "$f" ] || [ -L "$f" ]; } && [ "$f" != .git ]; then printf '%s\0' "$f"; fi
+ if [ -e "$f" ] || [ -L "$f" ]; then printf '%s\0' "$f"; fi
done \
- | tar --null -T - "${git_from[@]}" -czf -
+ | tar --null -T - -c -C "$tmp" .git -zf -
)
- rm -rf "$tmp"
+ rm -rf "$tmp"; trap - EXIT
else
tar -C "$src" -czf - .
fi
@@ -455,24 +796,86 @@ cmd_sync() {
}
# pull NAME REMOTE_GLOB LOCAL_DIR: copy matching remote entries into LOCAL_DIR.
-# Relative remote paths start at /home/ubi.
+# Relative remote paths start at /home/ubi. A glob that matches nothing (for
+# example an optional flake ledger) is reported and skipped, not a failure.
cmd_pull() {
- local name=$1 from=$2 to=$3
+ local name=$1 from=$2 to=$3 dir
+ dir=$(printf %q "$(dirname "$from")")
+ if ! remote "$name" "cd $dir 2>/dev/null && ls -d -- $(basename "$from") >/dev/null 2>&1"; then
+ log "pull: nothing matches $from"
+ return 0
+ fi
mkdir -p "$to"
- remote "$name" "cd $(printf %q "$(dirname "$from")") && tar -czf - $(basename "$from")" | tar -xzf - -C "$to"
+ remote "$name" "cd $dir && tar -czf - $(basename "$from")" | tar -xzf - -C "$to"
+}
+
+# pass_name OPTION NAME: a variable this runner may forward to a VM. Its own
+# credentials (UBICLOUD_*) never leave this machine, whoever asks (gbrain:
+# --env NAME=VALUE is checked the same way).
+pass_name() {
+ [[ "$2" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || die "$1 $2: not a variable name"
+ case $2 in UBICLOUD_*) die "$1 $2: the runner never forwards its own Ubicloud credentials to a VM" ;; esac
+}
+
+# inside_dir DIR ROOT: DIR resolves, symlinks followed, to ROOT or below it.
+# Its nearest existing ancestor is checked first, so a refused destination
+# creates nothing (not even outside the root); only then is DIR created and
+# checked again.
+inside_dir() {
+ local a b near=$1
+ b=$(cd "$2" 2>/dev/null && pwd -P) || return 1
+ while [ ! -d "$near" ]; do
+ [ "$near" != "$(dirname "$near")" ] || return 1
+ near=$(dirname "$near")
+ done
+ a=$(cd "$near" 2>/dev/null && pwd -P) || return 1
+ [ "$a" = "$b" ] || [[ "$a" = "$b"/* ]] || return 1
+ mkdir -p "$1" 2>/dev/null || return 1
+ a=$(cd "$1" 2>/dev/null && pwd -P) || return 1
+ [ "$a" = "$b" ] || [[ "$a" = "$b"/* ]]
+}
+
+# PULL_ROOT: set by verify; every pull destination must resolve inside it at
+# pull time (an earlier pull may have placed a symlink where a later one lands).
+PULL_ROOT=""
+
+# run_teardown RC: run's EXIT handler. Destroys RUN_VM, ignoring further
+# signals, then checks the project's VM list for it and prints the leftover
+# line; a VM still listed, or a list that cannot be read, fails the run.
+run_teardown() {
+ local rc=$1 rows left others
+ # gbrain: an exit 2 without FAILED is a lost signal trap (see finish).
+ [ "$rc" != 2 ] || [ -n "$FAILED" ] || rc=130
+ trap "" INT TERM HUP QUIT
+ cmd_down "$RUN_VM" || log "WARNING: failed to destroy $RUN_VM; run: $0 down $RUN_VM"
+ if rows=$(vm_rows 2>/dev/null); then
+ left=$(awk -v n="$RUN_VM" '$2==n' <<<"$rows" | grep -c . || true)
+ others=$(awk -v n="$RUN_VM" -v o="$OWNER" '$3==o && $2!=n' <<<"$rows" | grep -c . || true)
+ else
+ left=unknown others=unknown
+ fi
+ leftover "left=$left owner=$OWNER vm=$RUN_VM others=$others"
+ if [ "$left" != 0 ]; then
+ log "VM cleanup not confirmed for $RUN_VM (left=$left); destroy it with: $0 down $RUN_VM"
+ [ "$rc" -ne 0 ] || rc=1
+ fi
+ exit "$rc"
}
cmd_run() {
- local up_args=() src=. dest="" setup="" keep=0 pulls=() envs=() ttl=""
+ require_owner
+ local up_args=() src=. dest="" setup="" keep=0 pulls=() envs=() name="" ttl=""
while [ $# -gt 0 ]; do
case $1 in
- -s|--size|-l|--location|-n|--name|-S|--storage|-b|--image) up_args+=("$1" "$2"); shift 2 ;;
+ -S|--storage) check_storage "$2"; up_args+=("$1" "$2"); shift 2 ;;
+ -s|--size|-l|--location|-b|--image) up_args+=("$1" "$2"); shift 2 ;;
+ -n|--name) name=$2; shift 2 ;;
--ttl-hours) check_ttl "$2"; ttl=$2; shift 2 ;;
--src) src=$2; shift 2 ;;
--dest) dest=$2; shift 2 ;;
--setup) setup=$2; shift 2 ;;
- --env) envs+=("$2"); shift 2 ;;
- --pass) [ -n "${!2+x}" ] || die "--pass $2: not set locally"; envs+=("$2=${!2}"); shift 2 ;;
+ --env) [[ "$2" == *=* ]] || die "--env $2: give NAME=VALUE"; pass_name --env "${2%%=*}"; envs+=("$2"); shift 2 ;;
+ --pass) pass_name --pass "$2"; [ -n "${!2+x}" ] || die "--pass $2: not set locally"; envs+=("$2=${!2}"); shift 2 ;;
--pull) pulls+=("$2"); shift 2 ;;
--keep) keep=1; shift ;;
--) shift; break ;;
@@ -484,20 +887,24 @@ cmd_run() {
src=$(cd "$src" && pwd)
[ -n "$dest" ] || dest="work/$(basename "$src")"
- local i name=""
- for (( i = 0; i < ${#up_args[@]}; i += 2 )); do
- case ${up_args[i]} in -n|--name) name=${up_args[i+1]} ;; esac
- done
- [ -z "$name" ] || [ -z "$ttl" ] || die "run: --ttl-hours writes the expiry into the generated name, so it cannot be combined with -n"
- [ -n "$name" ] || { name=$(new_name "${ttl:-999}"); up_args+=(-n "$name"); }
+ name=$(vm_name "$name" "$ttl")
+ up_args+=(-n "$name")
RUN_VM=$name
# Armed before the create request: an interrupted `up` still destroys its VM.
# A second signal must not cut teardown short, so the EXIT handler ignores them.
- trap 'rc=$?; trap "" INT TERM HUP QUIT; finish "$rc" "$RUN_VM"' EXIT
+ trap 'run_teardown "$?"' EXIT
trap 'exit 130' INT TERM HUP QUIT
cmd_up "${up_args[@]}" >/dev/null
+ if [[ "$name" =~ -t([0-9]+)$ ]]; then
+ log "$name carries a ${BASH_REMATCH[1]}h TTL (any later run of this script reaps it); if this process dies first: $0 down $name"
+ elif [[ "$name" =~ ^$PREFIX-$OWNER-[0-9]{10}- ]]; then
+ log "$name has no TTL (reap destroys it once it is ${LEGACY_HOURS}h old); if this process dies before its teardown line, destroy it with: $0 down $name"
+ else
+ log "$name has no TTL and no reapable name, so nothing reaps it; if this process dies before its teardown line, destroy it with: $0 down $name"
+ fi
if [ "$keep" = 1 ]; then
- RUN_VM=""
+ trap - EXIT
+ leftover "left=1 owner=$OWNER vm=$name kept=1"
log "--keep: leaving $name running; destroy with: $0 down $name"
fi
@@ -506,27 +913,118 @@ cmd_run() {
| remote "$name" 'umask 077 && cat > ~/.ubirun-env'
cmd_sync "$name" "$src" "$dest"
- local qdest
+ local qdest rc=0
qdest=$(printf %q "$dest")
if [ -n "$setup" ]; then
remote "$name" 'cat > ~/.ubirun-setup.sh' <"$setup"
log "running setup $(basename "$setup")"
- remote "$name" "cd $qdest && . ~/.ubirun-env && bash -l ~/.ubirun-setup.sh" || die "setup failed"
+ watched "$name" setup "cd $qdest && . ~/.ubirun-env && bash -l ~/.ubirun-setup.sh" || { rc=$?; log "setup failed (exit $rc)"; exit "$rc"; }
fi
- local start rc=0
+ local start
start=$(date +%s)
log "running on $name: $*"
- remote "$name" "cd $qdest && . ~/.ubirun-env && bash -lc $(printf %q "$*")" || rc=$?
+ watched "$name" command "cd $qdest && . ~/.ubirun-env && bash -lc $(printf %q "$*")" || rc=$?
log "command exited $rc after $(( $(date +%s) - start ))s"
local p
for p in ${pulls[@]+"${pulls[@]}"}; do
+ if [ -n "$PULL_ROOT" ] && ! inside_dir "${p#*:}" "$PULL_ROOT"; then
+ log "pull refused: ${p#*:} resolves outside $PULL_ROOT"
+ [ "$rc" -ne 0 ] || rc=1
+ continue
+ fi
cmd_pull "$name" "${p%%:*}" "${p#*:}" || log "pull failed: $p"
done
return "$rc"
}
+# verify [run opts] [--trust-config] [-- COMMAND]: run the repository's
+# committed remote verify. .gstack/ubicloud.json under --src (default .)
+# supplies setup, command, size, location, storage, image, env, pass and pull;
+# flags given here and a trailing -- COMMAND override it. Without the file it
+# refuses, so every lane runs the one committed definition instead of its own
+# wrapper.
+#
+# The file is repository content and gets no reach beyond the checkout on its
+# own: its setup script and pull destinations must resolve inside --src, and a
+# local variable it lists under pass is forwarded only when this command line
+# also names it (--pass NAME) or grants every listed name (--trust-config).
+cmd_verify() {
+ local src=. i j g n cfg cfg_setup cfg_cmd parsed err rc=0 trust=0 cfg_args=() cfg_pass=() user_pre=() user_cmd=() granted=() missing=()
+ for (( i = 1; i <= $#; i++ )); do
+ [ "${!i}" = -- ] && break
+ if [ "${!i}" = --src ]; then j=$(( i + 1 )); src=${!j}; fi
+ done
+ cfg="$src/.gstack/ubicloud.json"
+ [ -f "$cfg" ] || die "verify: no $cfg; commit one ({\"setup\": \"scripts/ubicloud/bootstrap.sh\", \"command\": \"bash scripts/ubicloud/verify.sh\"}) so every lane runs the same verify instead of its own wrapper"
+ err=$(mktemp)
+ parsed=$(python3 -c '
+import json, os, shlex, sys
+cfg, src = sys.argv[1], sys.argv[2]
+try:
+ c = json.load(open(cfg))
+except ValueError:
+ sys.exit(3)
+if not isinstance(c, dict):
+ sys.exit(3)
+base, root = os.path.abspath(src), os.path.realpath(src)
+def inside(rel, what):
+ if not isinstance(rel, str) or not rel or os.path.isabs(rel) or rel.startswith("~") or ".." in rel.replace("\\", "/").split("/"):
+ print("%s %r must be a relative path inside the checkout" % (what, rel), file=sys.stderr); sys.exit(2)
+ full = os.path.realpath(os.path.join(root, rel))
+ if full != root and not full.startswith(root + os.sep):
+ print("%s %r resolves outside the checkout (%s)" % (what, rel, full), file=sys.stderr); sys.exit(2)
+ return os.path.join(base, rel)
+q = lambda s: shlex.quote(str(s))
+args = []
+for key, flag in (("size", "-s"), ("location", "-l"), ("storage", "-S"), ("image", "-b")):
+ if key in c: args += [flag, q(c[key])]
+for item in c.get("env", []): args += ["--env", q(item)]
+for item in c.get("pull", []):
+ remote, sep, local = str(item).partition(":")
+ if not sep or not remote:
+ print("pull entry %r must be REMOTE_GLOB:LOCAL_DIR" % (item,), file=sys.stderr); sys.exit(2)
+ args += ["--pull", q(remote + ":" + inside(local, "pull destination"))]
+setup = c.get("setup", "")
+print("cfg_args=(" + " ".join(args) + ")")
+print("cfg_pass=(" + " ".join(q(x) for x in c.get("pass", [])) + ")")
+print("cfg_setup=" + q(inside(setup, "setup") if setup else ""))
+print("cfg_cmd=" + q(c.get("command", "")))
+' "$cfg" "$src" 2>"$err") || rc=$?
+ case $rc in
+ 0) ;;
+ 2) local why; why=$(cat "$err"); rm -f "$err"; die "verify: $cfg: $why" ;;
+ *) rm -f "$err"; die "verify: $cfg is not valid JSON" ;;
+ esac
+ rm -f "$err"
+ eval "$parsed"
+ while [ $# -gt 0 ]; do
+ case $1 in
+ --) shift; user_cmd=("$@"); break ;;
+ --trust-config) trust=1; shift ;;
+ --keep) user_pre+=("$1"); shift ;;
+ --pass|-S|--storage|-s|--size|-l|--location|-n|--name|-b|--image|--ttl-hours|--src|--dest|--setup|--env|--pull)
+ [ $# -ge 2 ] || die "verify: $1 needs a value"
+ [ "$1" != --pass ] || granted+=("$2")
+ user_pre+=("$1" "$2"); shift 2 ;;
+ *) die "verify: unknown option $1" ;;
+ esac
+ done
+ for n in ${cfg_pass[@]+"${cfg_pass[@]}"}; do
+ pass_name --pass "$n"
+ if [ "$trust" = 1 ]; then cfg_args+=(--pass "$n"); continue; fi
+ for g in ${granted[@]+"${granted[@]}"}; do [ "$g" = "$n" ] && continue 2; done
+ missing+=("$n")
+ done
+ [ ${#missing[@]} -eq 0 ] || die "verify: $cfg asks to forward local ${missing[*]}; grant each on this command line with --pass NAME, or every name it lists with --trust-config"
+ [ ${#user_cmd[@]} -gt 0 ] || [ -n "$cfg_cmd" ] || die "verify: $cfg names no command and none was given after --"
+ [ ${#user_cmd[@]} -gt 0 ] || user_cmd=("$cfg_cmd")
+ log "verify: $cfg"
+ PULL_ROOT=$(cd "$src" && pwd)
+ cmd_run ${cfg_args[@]+"${cfg_args[@]}"} ${cfg_setup:+--setup "$cfg_setup"} --src "$src" ${user_pre[@]+"${user_pre[@]}"} -- "${user_cmd[@]}"
+}
+
usage() {
cat <<EOF
usage: ubi-runner.sh <command> [args]
@@ -534,45 +1032,62 @@ usage: ubi-runner.sh <command> [args]
run [up opts] [--ttl-hours H] [--src DIR] [--dest PATH] [--setup FILE] [--env K=V]...
[--pass NAME]... [--pull REMOTE_GLOB:LOCAL_DIR]... [--keep] -- COMMAND
up + sync + setup + command + pull + destroy; exits with COMMAND's status
- up [-s SIZE] [-l LOCATION] [-n NAME | --ttl-hours H] [-S STORAGE_GIB] [-b IMAGE]
- create a VM and wait for SSH; prints its name. --ttl-hours H
- gives it a TTL of H hours (1-999; default 999), after which
- the operator reaper and gstack's reap destroy it
+ verify [run opts] [--trust-config] [-- COMMAND]
+ run the repository's committed verify (.gstack/ubicloud.json under --src);
+ its setup script and every pull destination stay inside --src (checked
+ again at pull time), and its pass names are forwarded only when granted
+ here (--pass NAME, or all: --trust-config)
+ up [-s SIZE] [-l LOCATION] [-n NAME] [--ttl-hours H] [-S STORAGE_GIB] [-b IMAGE]
+ create a VM and wait for SSH; prints its name
+ (STORAGE_GIB: one of $ALLOWED_STORAGE). --ttl-hours H (1-999)
+ sets its TTL (default UBI_TTL_HOURS) and is appended to -n NAME;
+ a $PREFIX- NAME must carry a -t<hours> TTL
ssh NAME [COMMAND] shell or login-shell command on the VM (user ubi, passwordless sudo)
sync NAME [SRC] [DEST] stream a checkout (tracked + untracked-unignored + .git)
- pack [SRC] write that checkout tarball to stdout (with a slim .git: HEAD + origin/master)
+ pack [SRC] write that checkout tarball to stdout (slim .git: HEAD + origin/master)
unpack NAME DEST extract a tarball from stdin into DEST on the VM
pull NAME REMOTE_GLOB LOCAL_DIR
copy matching remote entries into LOCAL_DIR
down NAME [-l LOC] destroy the VM; returns once it is confirmed gone or never existed
- list [--mine] list all VMs in the project, or only this owner's
+ list [--mine] list all VMs in the project, or this owner's and this machine's
usage VMs and vCPUs per owner across the project
owner print this caller's owner tag ($OWNER)
+ records VMs this machine created and has not confirmed gone ($VM_RECORD)
gc HOURS destroy this owner's VMs older than HOURS (never other owners')
+ reap destroy every VM whose -t<hours> TTL has ended (any owner) and this
+ owner's TTL-less ubirun-* VMs older than UBI_LEGACY_HOURS
cli ARGS... raw Ubicloud CLI passthrough (e.g. cli vm list)
-VMs are named $PREFIX-<owner>-<epoch>-<suffix>-t<ttl hours>; set UBI_OWNER (e.g. your thread code) to tag them, otherwise a
-per-machine id is used.
+VMs are named $PREFIX-<owner>-<epoch>-<suffix>-t<ttl hours>; up, run and verify need
+UBI_OWNER (e.g. your thread code); run and verify end with a UBICLOUD: left=<n> line.
defaults: size=$DEFAULT_SIZE location=$DEFAULT_LOCATION (env UBI_SIZE, UBI_LOCATION)
-env: UBI_GC_HOURS (unset/0: no sweep on up), UBI_CREATE_GRACE (${CREATE_GRACE}s),
- UBI_DOWN_TIMEOUT (${DOWN_TIMEOUT}s), UBI_API_TIMEOUT (${API_TIMEOUT}s)
+env: UBI_TTL_HOURS (${TTL_HOURS}h in the name, 1-999), UBI_REAP (default 0 in gbrain; 1: up reaps first),
+ UBI_LEGACY_HOURS (${LEGACY_HOURS}h: reap's bound for this owner's TTL-less ubirun-* names),
+ UBI_IDLE_TIMEOUT (${IDLE_TIMEOUT}s of silence kills the remote command, exit 124; 0 disables),
+ UBI_RUN_TIMEOUT (${RUN_TIMEOUT}s wall clock; 0 unlimited), UBI_HEARTBEAT (${HEARTBEAT}s between heartbeat lines),
+ UBI_QUOTA_VCPUS (project vCPU ceiling for the preflight; else the last refusal's maximum),
+ UBI_QUOTA_WAIT (${QUOTA_WAIT}s to wait for quota room instead of refusing),
+ UBI_GC_HOURS (unset/0: no sweep on up), UBI_CREATE_GRACE (${CREATE_GRACE}s),
+ UBI_DOWN_TIMEOUT (${DOWN_TIMEOUT}s), UBI_API_TIMEOUT (${API_TIMEOUT}s), UBI_VM_RECORD (scratch VM-id file),
+ UBI_ALLOWED_STORAGE (the -S sizes Ubicloud accepts; default "320 640")
EOF
}
cmd=${1:-help}
[ $# -eq 0 ] || shift
case $cmd in
- owner|pack|help|-h|--help) ;;
+ owner|pack|records|help|-h|--help) ;;
*) [ -n "${UBICLOUD_API_KEY:-}" ] || die "UBICLOUD_API_KEY is not set (create a token under your Ubicloud project's Tokens page)" ;;
esac
case $cmd in
run) cmd_run "$@" ;;
+ verify) cmd_verify "$@" ;;
up) trap 'rc=$?; trap "" INT TERM HUP QUIT; [ -z "$UP_READY" ] || UP_NAME=""; finish "$rc" "$UP_NAME"' EXIT
trap 'exit 130' INT TERM HUP QUIT
cmd_up "$@" ;;
ssh) name=$1; shift; load "$name"
# shellcheck disable=SC2046
- if [ $# -eq 0 ]; then exec ssh -t $(ssh_opts) "ubi@$IP"; else remote "$name" "bash -lc $(printf %q "$*")"; fi ;;
+ if [ $# -eq 0 ]; then exec ssh -t $(ssh_opts) "ubi@$IP"; else watched "$name" ssh "bash -lc $(printf %q "$*")"; fi ;;
sync) cmd_sync "$@" ;;
pack) cmd_pack "$@" ;;
unpack) cmd_unpack "$@" ;;
@@ -581,7 +1096,9 @@ case $cmd in
list) cmd_list "$@" ;;
usage) cmd_usage ;;
owner) echo "$OWNER" ;;
+ records) cmd_records ;;
gc) cmd_gc "$@" ;;
+ reap) cmd_reap ;;
cli) cli "$@" ;;
help|-h|--help) usage ;;
*) usage >&2; exit 2 ;;
diff --git a/test/helpers/mock-ubicloud-api.ts b/test/helpers/mock-ubicloud-api.ts
index 12fe4b6919..45a0421156 100644
--- a/test/helpers/mock-ubicloud-api.ts
+++ b/test/helpers/mock-ubicloud-api.ts
@@ -2,13 +2,16 @@
// endpoint, enough for scripts/ubicloud/ubi-runner.sh: `vm list`, `vm L/N
// create` (slow on purpose, and completed even when the client hangs up, like
// the real API), `vm L/N show` (404 once gone) and `vm L/N destroy -f`.
-// VMs never reach `running`, so every `up` stays mid-provision until killed.
+// VMs never reach `running`, so every `up` stays mid-provision until killed,
+// unless `running` is set: then a created VM shows as running at 192.0.2.1
+// (pair it with a fake `ssh` on PATH). `faults` makes `destroy` or `list`
+// answer HTTP 500 / 503 from the next request on.
export interface MockVm {
location: string;
name: string;
size: string;
- state: "creating" | "destroying";
+ state: "creating" | "running" | "destroying";
}
export interface MockUbicloudOptions {
@@ -18,6 +21,8 @@ export interface MockUbicloudOptions {
destroyDelayMs?: number;
/** Refuse every create with Ubicloud's vCPU quota error (400). */
rejectCreates?: boolean;
+ /** Created VMs show as running at 192.0.2.1. */
+ running?: boolean;
seed?: Array<{ location?: string; name: string; size?: string }>;
}
@@ -26,12 +31,15 @@ export interface MockUbicloud {
vms: Map<string, MockVm>;
/** "create-start N", "created N", "create-rejected N", "destroy N", "removed N", in order. */
events: string[];
+ /** Flip to make every later `destroy` (500) or `list` (503) fail. */
+ faults: { destroy: boolean; list: boolean };
stop(): void;
}
export function startMockUbicloud(opts: MockUbicloudOptions = {}): MockUbicloud {
const vms = new Map<string, MockVm>();
const events: string[] = [];
+ const faults = { destroy: false, list: false };
for (const vm of opts.seed ?? []) {
vms.set(vm.name, { location: vm.location ?? "eu-central-h1", name: vm.name, size: vm.size ?? "standard-16", state: "creating" });
}
@@ -43,6 +51,7 @@ export function startMockUbicloud(opts: MockUbicloudOptions = {}): MockUbicloud
const { argv } = (await req.json()) as { argv: string[] };
if (argv[0] !== "vm") return text(`! unsupported: ${argv.join(" ")}`, 400);
if (argv[1] === "list") {
+ if (faults.list) return text("! Unexpected response status: 503", 503);
return text([...vms.values()].map((vm) => `${vm.location} ${vm.name}\n`).join(""));
}
const [location, name] = (argv[1] ?? "").split("/") as [string, string];
@@ -55,16 +64,17 @@ export function startMockUbicloud(opts: MockUbicloudOptions = {}): MockUbicloud
return text("! Unexpected response status: 400\nDetails: Validation failed for following fields: size\n size: Insufficient quota for requested size. Requested vCPU count: 16, currently used vCPU count: 252, maximum allowed vCPU count: 256, remaining vCPU count: 4", 400);
}
const size = argv[argv.indexOf("-s") + 1] ?? "standard-16";
- vms.set(name, { location, name, size, state: "creating" });
+ vms.set(name, { location, name, size, state: opts.running ? "running" : "creating" });
events.push(`created ${name}`);
return text(`VM created with id: vm-${name}`);
}
const vm = vms.get(name);
if (verb === "show") {
if (!vm) return text("! Unexpected response status: 404", 404);
- return text(`id: vm-${name}\nname: ${name}\nstate: ${vm.state}\nlocation: ${vm.location}\nsize: ${vm.size}\n`);
+ return text(`id: vm-${name}\nname: ${name}\nstate: ${vm.state}\nlocation: ${vm.location}\nsize: ${vm.size}\n${vm.state === "running" ? "ip4: 192.0.2.1\n" : ""}`);
}
if (verb === "destroy") {
+ if (faults.destroy) return text("! Unexpected response status: 500", 500);
if (vm && vm.state !== "destroying") {
vm.state = "destroying";
events.push(`destroy ${name}`);
@@ -78,7 +88,7 @@ export function startMockUbicloud(opts: MockUbicloudOptions = {}): MockUbicloud
return text(`! unsupported: ${argv.join(" ")}`, 400);
},
});
- return { url: `http://127.0.0.1:${server.port}`, vms, events, stop: () => server.stop(true) };
+ return { url: `http://127.0.0.1:${server.port}`, vms, events, faults, stop: () => server.stop(true) };
}
export async function waitForEvent(mock: MockUbicloud, pattern: RegExp, timeoutMs = 20_000): Promise<string> {
diff --git a/test/scripts/ci-ubicloud-teardown.slow.test.ts b/test/scripts/ci-ubicloud-teardown.slow.test.ts
index 3009b1f5d1..7b8eb51209 100644
--- a/test/scripts/ci-ubicloud-teardown.slow.test.ts
+++ b/test/scripts/ci-ubicloud-teardown.slow.test.ts
@@ -5,6 +5,10 @@
// returns only after each VM that came to exist is destroyed and gone. Every
// gate VM name carries its expiry, two hours after creation by default
// (scripts/ubicloud/reap-expired.ts reaps a VM teardown never reached).
+// After teardown the run prints gstack's UBICLOUD: left= line (also into
+// UBI_LEFT_FILE, which scripts/pregate-remote-gate.sh reads): left=0 once every
+// VM is confirmed gone, left=<n> when a destroy fails. Without UBI_OWNER the
+// run refuses before it provisions anything.
//
// The orchestrator packs its whole checkout (.git and untracked files
// included) before it provisions anything, so it runs from a fixture repo
@@ -32,7 +36,7 @@ afterEach(() => {
});
describe("ci:ubicloud teardown", () => {
- for (const signal of ["SIGTERM", "SIGHUP"] as const) it(`${signal} mid-provision destroys every VM it asked for, including creates still in flight`, async () => {
+ for (const [signal, destroyFails] of [["SIGTERM", false], ["SIGHUP", false], ["SIGTERM", true]] as const) it(`${signal} mid-provision destroys every VM it asked for, including creates still in flight${destroyFails ? "; a destroy that fails reads UBICLOUD: left=3" : ""}`, async () => {
dir = mkdtempSync(join(tmpdir(), "ci-ubicloud-teardown-"));
const repo = join(dir, "repo");
mkdirSync(repo);
@@ -50,6 +54,8 @@ describe("ci:ubicloud teardown", () => {
UBI_RUNNER_STATE: join(dir, "state"),
UBI_OWNER: "probe",
UBI_POLL_SECONDS: "0.2",
+ UBI_DOWN_TIMEOUT: "2",
+ UBI_LEFT_FILE: join(dir, "left"),
},
stdout: "pipe",
stderr: "pipe",
@@ -65,6 +71,7 @@ describe("ci:ubicloud teardown", () => {
for (const vm of [/^create-start \S+-ci02/, /^create-start \S+-ci03/]) await Promise.race([waitForEvent(api, vm, 10_000), exitedEarly]);
exitedEarly.catch(() => {});
expect(api.events.some((e) => /^created \S+-ci0[23]/.test(e))).toBe(false);
+ api.faults.destroy = destroyFails;
child.kill(signal);
expect(await child.exited).toBe(130);
const out = await stdout;
@@ -76,12 +83,38 @@ describe("ci:ubicloud teardown", () => {
for (const name of requested) {
expect(name).toMatch(/^ubirun-probe-\d{10}-ci0[123][0-9a-f]{4}-t2$/);
expect(api.events).toContain(`created ${name}`);
- expect(api.events).toContain(`removed ${name}`);
+ if (!destroyFails) expect(api.events).toContain(`removed ${name}`);
+ }
+ const left = destroyFails ? 3 : 0;
+ expect(out).toContain(`UBICLOUD: left=${left} owner=probe vms=3 others=0\n`);
+ expect(readFileSync(join(dir, "left"), "utf8")).toBe(`UBICLOUD: left=${left} owner=probe vms=3 others=0\n`);
+ if (destroyFails) {
+ expect(api.vms.size).toBe(3);
+ expect(out).toContain("teardown left 3 VM(s) unconfirmed");
+ return;
}
expect(api.vms.size).toBe(0);
expect(out).toContain("teardown confirmed 3 VM(s) gone");
expect(await stderr).not.toContain("WARNING");
}, 180_000);
+
+ it("refuses without UBI_OWNER before it provisions anything", async () => {
+ dir = mkdtempSync(join(tmpdir(), "ci-ubicloud-owner-"));
+ const api = (mock = startMockUbicloud());
+ // Async: the mock API is served from this process, so a blocking spawn would starve it.
+ const child = (proc = Bun.spawn(["bun", "run", "scripts/ci-ubicloud.ts", "--vms", "1", "--lanes", "gitleaks"], {
+ cwd: ROOT,
+ env: { PATH: process.env.PATH ?? "/usr/bin:/bin", HOME: dir, UBICLOUD_API_KEY: "test-token", UBICLOUD_API_URL: api.url, UBI_RUNNER_STATE: join(dir, "state") },
+ stdout: "ignore",
+ stderr: "pipe",
+ }));
+ const stderr = new Response(child.stderr).text();
+ // Unrefused, the run would reach a create within seconds.
+ const settled = await Promise.race([child.exited, waitForEvent(api, /^create-start /, 30_000).then(() => "created")]);
+ expect(settled).toBe(2);
+ expect(await stderr).toContain("ci-ubicloud: UBI_OWNER is not set");
+ expect(api.events).toEqual([]);
+ }, 60_000);
});
// A SIGTERM while batches run (a cancelled gate) kills those batches. They
diff --git a/test/scripts/ci-ubicloud-vm-names.test.ts b/test/scripts/ci-ubicloud-vm-names.test.ts
index f762f2cbcc..7e42721629 100644
--- a/test/scripts/ci-ubicloud-vm-names.test.ts
+++ b/test/scripts/ci-ubicloud-vm-names.test.ts
@@ -3,13 +3,14 @@
// TTL-less names, for scripts/ubicloud/ubi-runner.sh and scripts/ci-ubicloud.ts.
//
// Protects: `up`/`run --ttl-hours H` name their VM with a -t<H> TTL, and
-// without --ttl-hours with -t999, so no generated name is TTL-less (gstack's
-// reap destroys those at four hours); the flag is validated (1 to 999) and
-// cannot be combined with -n; every parser (list --mine, usage, gc, down)
-// reads all three formats alike: gc ages a VM by its creation epoch, never its
-// expiry.
+// without it with UBI_TTL_HOURS (gstack's default, 3), so no generated name is
+// TTL-less; the flag is validated (1 to 999), with -n NAME it appends -t<H>,
+// and a ubirun- NAME without a TTL is refused before any create (#8050);
+// every parser (list --mine, usage, gc, down) reads all three formats alike:
+// gc ages a VM by its creation epoch, never its expiry.
// Fails when: a new-format name is not owner-tagged for list --mine or usage,
-// gc sweeps by the expiry or another owner's VM, or the flag is ignored.
+// gc sweeps by the expiry or another owner's VM, the flag is ignored, or a
+// hand-named ubirun- VM reaches the API without a TTL.
// Network: none (in-process mock Ubicloud API).
import { afterEach, describe, expect, it } from "bun:test";
@@ -75,30 +76,50 @@ describe("--ttl-hours", () => {
});
}
- it("without --ttl-hours the name carries the longest TTL, -t999", async () => {
- const api = serve();
- const proc = spawnRunner(["up"], { UBI_OWNER: "gbra135" });
- const name = (await waitForEvent(api, /^create-start /)).split(" ")[1]!;
- proc.kill("SIGTERM");
- await proc.exited;
- expect(name).toMatch(/^ubirun-gbra135-\d{10}-[0-9a-f]{8}-t999$/);
- expect(name.length).toBeLessThanOrEqual(63);
+ it("without --ttl-hours the name carries UBI_TTL_HOURS: gstack's 3 by default, 999 at most", async () => {
+ for (const [extra, ttl] of [[{}, "t3"], [{ UBI_TTL_HOURS: "999" }, "t999"]] as const) {
+ const api = serve({ rejectCreates: true });
+ const r = await run(["up"], { UBI_OWNER: "gbra135", ...extra });
+ expect(r.code).toBe(1);
+ const name = api.events[0]!.split(" ")[1]!;
+ expect(name).toMatch(new RegExp(`^ubirun-gbra135-\\d{10}-[0-9a-f]{8}-${ttl}$`));
+ expect(name.length).toBeLessThanOrEqual(63);
+ mock!.stop();
+ }
});
- it("refuses a bad value and the combination with -n before any create", async () => {
+ it("refuses a bad value before any create", async () => {
const api = serve();
for (const bad of ["0", "1.5", "abc", "1000", "024"]) {
- const r = await run(["up", "--ttl-hours", bad], { UBI_OWNER: "t1" });
+ for (const args of [["up", "--ttl-hours", bad], ["run", "--ttl-hours", bad, "--", "true"]]) {
+ const r = await run(args, { UBI_OWNER: "t1" });
+ expect(r.code).toBe(1);
+ expect(r.stderr).toContain("--ttl-hours must be a whole number of hours from 1 to 999");
+ }
+ }
+ expect(api.events).toEqual([]);
+ });
+
+ // #8050 item 1: a hand-named ubirun- VM used to bypass the TTL.
+ it("-n NAME with --ttl-hours appends -t<H>; a ubirun- NAME without a TTL is refused before any create; other names pass", async () => {
+ const api = serve({ rejectCreates: true });
+ for (const args of [["up", "-n", "ubirun-t1-1790000000-aaaaaaaa", "--ttl-hours", "2"], ["run", "--ttl-hours", "2", "-n", "ubirun-t1-1790000000-bbbbbbbb", "--", "true"]]) {
+ expect((await run(args, { UBI_OWNER: "t1" })).code).toBe(1);
+ }
+ expect(api.events.filter((e) => e.startsWith("create-start "))).toEqual(["create-start ubirun-t1-1790000000-aaaaaaaa-t2", "create-start ubirun-t1-1790000000-bbbbbbbb-t2"]);
+ api.events.length = 0;
+ for (const args of [["up", "-n", "ubirun-t1-1790000000-cccccccc"], ["run", "-n", "ubirun-t1-1790000000-dddddddd", "--", "true"], ["up", "-n", "ubirun-t1-1790000000-eeeeeeee-t0"]]) {
+ const r = await run(args, { UBI_OWNER: "t1" });
expect(r.code).toBe(1);
- expect(r.stderr).toContain("--ttl-hours must be a whole number of hours from 1 to 999");
+ expect(r.stderr).toContain("has no -t<hours> TTL, so no reaper could destroy it if this run dies; add --ttl-hours H");
}
- const both = await run(["up", "-n", "ubirun-t1-1790000000-aaaaaaaa", "--ttl-hours", "2"], { UBI_OWNER: "t1" });
- expect(both.code).toBe(1);
- expect(both.stderr).toContain("cannot be combined with -n");
- const runBoth = await run(["run", "--ttl-hours", "2", "-n", "ubirun-t1-1790000000-aaaaaaaa", "--", "true"], { UBI_OWNER: "t1" });
- expect(runBoth.code).toBe(1);
- expect(runBoth.stderr).toContain("cannot be combined with -n");
+ const twice = await run(["up", "-n", "ubirun-t1-1790000000-ffffffff-t5", "--ttl-hours", "2"], { UBI_OWNER: "t1" });
+ expect(twice.code).toBe(1);
+ expect(twice.stderr).toContain("already ends in a TTL");
expect(api.events).toEqual([]);
+ expect((await run(["up", "-n", "ubirun-t1-1790000000-abababab-t5"], { UBI_OWNER: "t1" })).code).toBe(1);
+ expect((await run(["up", "-n", "bench-db-1"], { UBI_OWNER: "t1" })).code).toBe(1);
+ expect(api.events.filter((e) => e.startsWith("create-start "))).toEqual(["create-start ubirun-t1-1790000000-abababab-t5", "create-start bench-db-1"]);
});
});
diff --git a/test/scripts/pregate-remote-gate.test.ts b/test/scripts/pregate-remote-gate.test.ts
index 74e9d66200..2690253051 100644
--- a/test/scripts/pregate-remote-gate.test.ts
+++ b/test/scripts/pregate-remote-gate.test.ts
@@ -18,6 +18,9 @@
* Seams: GBRAIN_PREGATE_GATE_CMD replaces `bun run ci:ubicloud:diff`,
* GBRAIN_PREGATE_REUSE_CMD replaces `bun scripts/ci-reuse.ts --gate`,
* GBRAIN_PREGATE_REPO names the repository.
+ * VM cleanup: the gate's UBICLOUD: left= line (UBI_LEFT_FILE) must say 0, or
+ * the run is PREGATE_REMOTE_INFRA (exit 4, no receipt), never a test result;
+ * a missing line counts as not confirmed.
*/
import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
import { spawnSync } from 'node:child_process';
@@ -26,6 +29,7 @@ import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
const SCRIPT = resolve(import.meta.dir, '..', '..', 'scripts/pregate-remote-gate.sh');
+const LEFT0 = `echo 'UBICLOUD: left=0 owner=gbra0test vms=1 others=0' >> "$UBI_LEFT_FILE"`;
const SUMMARY = [
'=== ci-ubicloud summary ===',
' gitleaks 1 passed, 0 failed, 8s compute',
@@ -49,10 +53,11 @@ beforeEach(() => {
});
afterEach(() => rmSync(repo, { recursive: true, force: true }));
-function run(gate: string, env: Record<string, string | undefined> = {}) {
+/** Runs the script with `gate` as the gate command; unless `raw`, the gate first reports a clean VM teardown (left=0). */
+function run(gate: string, env: Record<string, string | undefined> = {}, raw = false) {
const r = spawnSync('bash', [SCRIPT], {
cwd: repo, encoding: 'utf8',
- env: { ...process.env, GIT_CONFIG_NOSYSTEM: '1', UBI_OWNER: 'gbra0test', PREGATE_TREE: undefined, GBRAIN_PREGATE_REPO: undefined, GBRAIN_PREGATE_REUSE: undefined, GBRAIN_PREGATE_REUSE_CMD: undefined, GBRAIN_PREGATE_GATE_CMD: gate, ...env },
+ env: { ...process.env, GIT_CONFIG_NOSYSTEM: '1', UBI_OWNER: 'gbra0test', UBI_LEFT_FILE: undefined, PREGATE_TREE: undefined, GBRAIN_PREGATE_REPO: undefined, GBRAIN_PREGATE_REUSE: undefined, GBRAIN_PREGATE_REUSE_CMD: undefined, GBRAIN_PREGATE_GATE_CMD: raw ? gate : `${LEFT0}; ${gate}`, ...env },
});
return { code: r.status, out: r.stdout, err: r.stderr };
}
@@ -83,7 +88,7 @@ describe('pregate-remote-gate.sh', () => {
it('a green gate exits 0 with failed=0 and receives the extra arguments', () => {
const gate = join(repo, '.git', 'gate.sh');
- writeFileSync(gate, `echo "args: $*"; printf '%s\\n' '=== ci-ubicloud summary ===' ' unit 4 passed, 0 failed, 1s compute'\n`);
+ writeFileSync(gate, `echo "args: $*"; ${LEFT0}; printf '%s\\n' '=== ci-ubicloud summary ===' ' unit 4 passed, 0 failed, 1s compute'\n`);
const r = spawnSync('bash', [SCRIPT, '--vms', '8'], {
cwd: repo, encoding: 'utf8',
env: { ...process.env, GIT_CONFIG_NOSYSTEM: '1', UBI_OWNER: 'gbra0test', GBRAIN_PREGATE_GATE_CMD: `bash ${gate}` } as Record<string, string>,
@@ -96,7 +101,7 @@ describe('pregate-remote-gate.sh', () => {
it('runs the development gate, bun run ci:ubicloud:diff, by default and passes the extra arguments on', () => {
const bin = join(repo, '.git', 'fake-bin');
mkdirSync(bin);
- writeFileSync(join(bin, 'bun'), `#!/usr/bin/env bash\necho "fake-bun: $*"\nprintf '%s\\n' '=== ci-ubicloud summary ===' ' gitleaks 1 passed, 0 failed, 2s compute'\n`);
+ writeFileSync(join(bin, 'bun'), `#!/usr/bin/env bash\necho "fake-bun: $*"\n${LEFT0}\nprintf '%s\\n' '=== ci-ubicloud summary ===' ' gitleaks 1 passed, 0 failed, 2s compute'\n`);
chmodSync(join(bin, 'bun'), 0o755);
const r = spawnSync('bash', [SCRIPT, '--lanes', 'unit'], {
cwd: repo, encoding: 'utf8',
@@ -121,6 +126,23 @@ describe('pregate-remote-gate.sh', () => {
expect(r.code).toBe(1);
});
+ it('a gate whose VM cleanup is not confirmed (left=1, left=unknown or no left line) is PREGATE_REMOTE_INFRA, exit 4, never a test result', () => {
+ const green = `printf '%s\\n' '=== ci-ubicloud summary ===' ' unit 4 passed, 0 failed, 1s compute'`;
+ for (const [report, shown] of [[`echo 'UBICLOUD: left=1 owner=gbra0test vms=2 others=0' >> "$UBI_LEFT_FILE"; `, 'left=1'], [`echo 'UBICLOUD: left=unknown owner=gbra0test vms=2 others=unknown' >> "$UBI_LEFT_FILE"; `, 'left=unknown'], ['', 'left=missing']] as const) {
+ for (const gate of [`${report}${green}`, `${report}${green}; exit 1`]) {
+ const r = run(gate, {}, true);
+ expect(r.code).toBe(4);
+ expect(r.err).toContain(`pregate-remote-gate: PREGATE_REMOTE_INFRA: VM cleanup not confirmed (UBICLOUD: ${shown}, gate exit `);
+ expect(r.err).toContain('an infrastructure failure, not a test result, so no receipt. Check and destroy leftovers: UBI_OWNER=gbra0test scripts/ubicloud/ubi-runner.sh list --mine');
+ expect(r.out).not.toContain('PREGATE_REMOTE:');
+ }
+ }
+ // A clean teardown keeps the gate's own result: a test failure exits 1 with its receipt.
+ const failing = run(`printf '%s\\n' '=== ci-ubicloud summary ===' ' unit 4 passed, 1 failed, 1s compute'; exit 1`);
+ expect(failing.code).toBe(1);
+ expect(failing.out.trim().split('\n').at(-1)).toBe(`PREGATE_REMOTE: tree=${contentTree()} tests=5 failed=1`);
+ });
+
it('refuses before the gate without UBI_OWNER or when PREGATE_TREE is another tree', () => {
const marker = join(repo, '.git', 'ran');
const noOwner = run(`touch ${marker}`, { UBI_OWNER: '' });
diff --git a/test/scripts/production-soak-ubicloud.test.ts b/test/scripts/production-soak-ubicloud.test.ts
new file mode 100644
index 0000000000..510edfd4a1
--- /dev/null
+++ b/test/scripts/production-soak-ubicloud.test.ts
@@ -0,0 +1,62 @@
+// production-soak-ubicloud.test.ts — scripts/bench/production-soak/ubicloud.sh
+// start's VM TTL (#8050 item 3).
+//
+// Protects: the soak VMs' TTL covers the soak: by default --hours (rounded up)
+// plus 12, and a --ttl-hours under --hours + 4 is refused before any VM is
+// created, since the operator reaper and gstack's reap destroy a VM about ten
+// minutes past its TTL.
+// Fails when: the TTL stops following --hours (the old fixed 15 lost a 20 h
+// soak at about 15 h) or a too-short TTL reaches the API.
+// Network: none (in-process mock Ubicloud API that refuses every create).
+
+import { afterEach, describe, expect, it } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { startMockUbicloud, type MockUbicloud } from "../helpers/mock-ubicloud-api.ts";
+
+const SCRIPT = resolve(import.meta.dir, "..", "..", "scripts/bench/production-soak/ubicloud.sh");
+let dir = "";
+let mock: MockUbicloud | null = null;
+afterEach(() => {
+ mock?.stop();
+ mock = null;
+ rmSync(dir, { recursive: true, force: true });
+});
+
+// Async: the mock API is served from this process, so a blocking spawn would starve it.
+async function start(args: string[]) {
+ dir ||= mkdtempSync(join(tmpdir(), "soak-ubicloud-"));
+ const proc = Bun.spawn(["bash", SCRIPT, "start", "--rtts", "65", "--out", join(dir, "out"), ...args], {
+ env: { PATH: process.env.PATH ?? "/usr/bin:/bin", HOME: dir, UBI_OWNER: "t1", UBICLOUD_API_KEY: "test-token", UBICLOUD_API_URL: mock!.url, UBI_RUNNER_STATE: join(dir, "state") },
+ stdout: "ignore",
+ stderr: "pipe",
+ });
+ const [stderr, code] = await Promise.all([new Response(proc.stderr).text(), proc.exited]);
+ return { code, stderr, names: mock!.events.filter((e) => e.startsWith("create-start ")).map((e) => e.split(" ")[1]!) };
+}
+
+describe("production soak TTL", () => {
+ it("defaults the VM TTL to --hours rounded up plus 12", async () => {
+ for (const [hours, ttl] of [["20", "t32"], ["3", "t15"], ["2.5", "t15"]] as const) {
+ mock = startMockUbicloud({ rejectCreates: true });
+ const r = await start(["--hours", hours]);
+ expect(r.code).not.toBe(0);
+ expect(r.names).toHaveLength(1);
+ expect(r.names[0]).toMatch(new RegExp(`^ubirun-t1-\\d{10}-[0-9a-f]{8}-${ttl}$`));
+ mock.stop();
+ }
+ }, 60_000);
+
+ it("refuses a TTL under --hours + 4, or a bad --hours, before any VM is created", async () => {
+ mock = startMockUbicloud({ rejectCreates: true });
+ const short = await start(["--hours", "20", "--ttl-hours", "15"]);
+ expect(short.code).toBe(2);
+ expect(short.stderr).toContain("--ttl-hours 15 is under --hours 20 + 4: the reapers would destroy the VMs mid-soak; give at least 24");
+ expect((await start(["--hours", "abc"])).stderr).toContain("--hours must be a number of hours");
+ expect((await start(["--hours", "3", "--ttl-hours", "1000"])).stderr).toContain("--ttl-hours must be a whole number from 1 to 999");
+ expect(mock.events).toEqual([]);
+ const ok = await start(["--hours", "20", "--ttl-hours", "24"]);
+ expect(ok.names[0]).toMatch(/-t24$/);
+ }, 60_000);
+});
diff --git a/test/scripts/ubi-runner-run.test.ts b/test/scripts/ubi-runner-run.test.ts
new file mode 100644
index 0000000000..76268d24cd
--- /dev/null
+++ b/test/scripts/ubi-runner-run.test.ts
@@ -0,0 +1,491 @@
+// ubi-runner-run.test.ts — scripts/ubicloud/ubi-runner.sh's run, verify,
+// reap, leftover line, watchdog and quota preflight against the in-process mock
+// Ubicloud API (VMs show as running) and a fake ssh on PATH. No network, no VM.
+// Ported from gstack's test/ubicloud-runner.test.ts (synced at gstack 5532345a)
+// onto gbrain's mock API.
+//
+// Protects: up, run and verify refuse without UBI_OWNER before any API call;
+// gbrain's up reaps nothing unless UBI_REAP=1 and says so in one line; reap
+// destroys expired TTL VMs of any owner and only the caller's own TTL-less
+// ubirun-<owner>-* VMs past UBI_LEGACY_HOURS; run ends with the UBICLOUD:
+// left= line (also in UBI_LEFT_FILE), and a VM it cannot confirm gone fails a
+// passing command; a silent or overlong remote command is killed with exit
+// 124, its last output and its remote session ended; --pass/--env and a
+// committed .gstack/ubicloud.json never forward UBICLOUD_*, and the config's
+// setup and pull destinations stay inside --src; a known vCPU ceiling refuses
+// before any create request.
+// Fails when: any of those reaches the API or the VM when it should not, a
+// leaked VM reads as left=0, or a timeout passes silently.
+
+import { afterEach, beforeEach, describe, expect, it } from "bun:test";
+import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { startMockUbicloud, type MockUbicloud, type MockUbicloudOptions } from "../helpers/mock-ubicloud-api.ts";
+
+const ROOT = resolve(import.meta.dir, "..", "..");
+const RUNNER = join(ROOT, "scripts/ubicloud/ubi-runner.sh");
+const NOW = Math.floor(Date.now() / 1000);
+
+let dir = "";
+let mock: MockUbicloud | null = null;
+
+// The fake ssh logs every remote command (its last argument) to ssh.log and
+// plays the part the command asks for. command-mode / setup-mode files under
+// the fixture root script the command and setup phases.
+const FAKE_SSH = [
+ "#!/usr/bin/env bash",
+ "root=${UBI_FAKE_ROOT:?}",
+ "cmd=${*: -1}",
+ "printf '%s\\n' \"$cmd\" >> \"$root/ssh.log\"",
+ "case \"$cmd\" in",
+ " -O|exit|true) exit 0 ;;",
+ " *pkill*) echo \"$cmd\" >> \"$root/cancel.log\" ;;",
+ " *captured*) cat > \"$root/captured\" ;;",
+ " *\"cat > ~/.ubirun-env\"*) cat > \"$root/ubirun-env\" ;;",
+ " *\"cat > ~/.ubirun-setup.sh\"*) cat > \"$root/ubirun-setup.sh\" ;;",
+ " *\"tar -xzf -\"*) cat > /dev/null ;;",
+ " *\"tar -czf -\"*) base=${cmd##* }; tar -czf - -C \"$root/remote-fs\" \"$base\" ;;",
+ " *\"bash -l ~/.ubirun-setup.sh\"*) echo \"setup start\"; if [ -f \"$root/setup-mode\" ]; then bash -c \"$(cat \"$root/setup-mode\")\"; fi; echo \"setup done\" ;;",
+ " *\"bash -lc \"*) if [ -f \"$root/command-mode\" ]; then bash -c \"$(cat \"$root/command-mode\")\"; else echo \"ran: $cmd\"; fi ;;",
+ " *) : ;;",
+ "esac",
+].join("\n");
+
+beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), "ubi-runner-run-"));
+ mkdirSync(join(dir, "bin"));
+ writeFileSync(join(dir, "bin/ssh"), FAKE_SSH);
+ chmodSync(join(dir, "bin/ssh"), 0o755);
+ mkdirSync(join(dir, "src"));
+ writeFileSync(join(dir, "src/file.txt"), "x\n");
+});
+afterEach(() => {
+ mock?.stop();
+ mock = null;
+ rmSync(dir, { recursive: true, force: true });
+});
+
+function serve(opts: MockUbicloudOptions = {}): MockUbicloud {
+ mock?.stop();
+ mock = startMockUbicloud({ running: true, destroyDelayMs: 50, ...opts });
+ return mock;
+}
+
+function env(extra: Record<string, string> = {}): Record<string, string> {
+ return {
+ PATH: `${join(dir, "bin")}:${process.env.PATH ?? "/usr/bin:/bin"}`,
+ HOME: dir,
+ UBI_FAKE_ROOT: dir,
+ UBICLOUD_API_KEY: "test-token",
+ UBICLOUD_API_URL: mock?.url ?? "http://127.0.0.1:9",
+ UBI_RUNNER_STATE: join(dir, "state"),
+ UBI_POLL_SECONDS: "0.2",
+ UBI_OWNER: "t1",
+ UBI_HEARTBEAT: "0",
+ ...extra,
+ };
+}
+
+async function run(args: string[], extra: Record<string, string> = {}, stdin?: string) {
+ const proc = Bun.spawn(["bash", RUNNER, ...args], { env: env(extra), stdin: stdin === undefined ? "ignore" : new Blob([stdin]), stdout: "pipe", stderr: "pipe" });
+ const [stdout, stderr, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ return { stdout, stderr, code };
+}
+
+const read = (p: string) => (existsSync(join(dir, p)) ? readFileSync(join(dir, p), "utf8") : "");
+const creates = () => (mock?.events ?? []).filter((e) => e.startsWith("create-start "));
+const destroyed = () => (mock?.events ?? []).filter((e) => e.startsWith("destroy ")).map((e) => e.slice("destroy ".length)).sort();
+const RUN_VM = /ubirun-t1-\d{10}-[0-9a-f]{8}-t3/.source;
+
+// A VM this machine already created (state dir with its env), for ssh NAME COMMAND.
+function knownVm(name = "vm-a") {
+ mkdirSync(join(dir, "state", name), { recursive: true });
+ writeFileSync(join(dir, "state", name, "env"), `NAME=${name}\nLOCATION=eu-central-h1\nSIZE=standard-16\nIP=192.0.2.1\nCREATED=yes\nCREATE_AT=0\nCREATE_PID=1\n`);
+ writeFileSync(join(dir, "state", name, "key"), "");
+}
+
+function repo(cfg: unknown): string {
+ const src = join(dir, "repo");
+ mkdirSync(join(src, ".gstack"), { recursive: true });
+ mkdirSync(join(src, "scripts"), { recursive: true });
+ writeFileSync(join(src, "scripts/boot.sh"), "echo boot\n");
+ writeFileSync(join(src, ".gstack/ubicloud.json"), JSON.stringify(cfg));
+ return src;
+}
+
+describe("owner and reap", () => {
+ it("up, run and verify refuse without UBI_OWNER before any API call; list, usage, reap and down still work without it", async () => {
+ const api = serve({ seed: [{ name: "vm-a" }] });
+ const src = repo({ command: "make verify" });
+ for (const args of [["up"], ["run", "--", "true"], ["verify", "--src", src]]) {
+ const r = await run(args, { UBI_OWNER: "" });
+ expect(r.code).toBe(1);
+ expect(r.stderr).toContain("UBI_OWNER is not set: every VM must carry its owner; export UBI_OWNER=<your thread or session code>");
+ expect(r.stderr).toContain("(UBI_OWNER_REQUIRED)");
+ }
+ expect(api.events).toEqual([]);
+ for (const args of [["list"], ["usage"], ["reap"]]) expect((await run(args, { UBI_OWNER: "" })).code).toBe(0);
+ expect((await run(["down", "vm-a"], { UBI_OWNER: "" })).code).toBe(0);
+ }, 60_000);
+
+ // GBRA-108: gbrain still holds TTL-less VMs older than gstack's 4 h legacy
+ // bound, so gbrain's up reaps nothing until UBI_REAP=1, and says so.
+ it("gbrain's up reaps nothing by default and says so in one line; UBI_REAP=1 reaps expired TTL VMs of any owner first", async () => {
+ const seed = [{ name: "ubirun-other-1000000000-bbbb-t1" }, { name: "ubirun-t1-1000000000-aaaa" }, { name: `ubirun-peer-${NOW}-cccc-t3` }];
+ serve({ rejectCreates: true, seed });
+ const def = await run(["up"]);
+ expect(def.code).toBe(1);
+ expect(def.stderr.match(/reap skipped: gbrain defaults UBI_REAP=0 until its TTL-less VMs older than 4h are gone \(UBI_REAP=1 reaps; reap-expired\.ts still destroys expired TTL VMs\)/g)).toHaveLength(1);
+ expect(def.stderr).not.toContain("reaping");
+ expect(destroyed()).toEqual([]);
+ const off = await run(["up"], { UBI_REAP: "0" });
+ expect(off.stderr).not.toContain("reap skipped");
+ expect(destroyed()).toEqual([]);
+ expect(creates()).toHaveLength(2);
+ const on = await run(["up"], { UBI_REAP: "1" });
+ expect(on.code).toBe(1);
+ expect(on.stderr).toMatch(/reaping expired eu-central-h1\/ubirun-other-1000000000-bbbb-t1 \(owner other; its TTL ended \d+ min ago\)/);
+ expect(on.stderr).toMatch(/reaping TTL-less eu-central-h1\/ubirun-t1-1000000000-aaaa \(owner t1; \d+h old, legacy sweep at 4h\)/);
+ expect(on.stderr).not.toContain("reap skipped");
+ expect(destroyed()).toEqual(["ubirun-other-1000000000-bbbb-t1", "ubirun-t1-1000000000-aaaa"]);
+ }, 60_000);
+
+ it("reap destroys expired TTLs (and older -x expiries) and this owner's old TTL-less names, never unexpired, recent, another owner's TTL-less, untagged or foreign ones", async () => {
+ const seed = [
+ "ubirun-other-1000000000-bbbb-t1",
+ "ubirun-t1-9999999999-dddd-t1",
+ "ubirun-t1-1000000000-aaaa",
+ "ubirun-1000000000-cccc",
+ `ubirun-t1-${NOW - 3 * 3600}-eeee`,
+ "ubirun-gbra240-1000000000-gggg",
+ "team-db-1000000000-ffff",
+ `ubirun-other-${NOW - 5 * 3600}-x${NOW - 3 * 3600}-hhhh`,
+ ].map((name) => ({ name }));
+ const api = serve({ seed });
+ const reap = await run(["reap"]);
+ expect(reap.code).toBe(0);
+ expect(destroyed()).toEqual(["ubirun-other-1000000000-bbbb-t1", "ubirun-t1-1000000000-aaaa", seed[7]!.name].sort());
+ expect((await run(["reap"])).stderr).toContain("reap: no expired VMs");
+ const lowered = await run(["reap"], { UBI_LEGACY_HOURS: "2" });
+ expect(lowered.code).toBe(0);
+ expect(lowered.stderr).toMatch(/reaping TTL-less eu-central-h1\/ubirun-t1-\d{10}-eeee \(owner t1; 3h old, legacy sweep at 2h\)/);
+ const ownerless = await run(["reap"], { UBI_OWNER: "", UBI_LEGACY_HOURS: "1" });
+ expect(ownerless.code).toBe(0);
+ expect(ownerless.stderr).not.toContain("reaping TTL-less");
+ expect([...api.vms.keys()].sort()).toEqual(["team-db-1000000000-ffff", "ubirun-1000000000-cccc", "ubirun-gbra240-1000000000-gggg", "ubirun-t1-9999999999-dddd-t1"]);
+ }, 60_000);
+
+ it("reap reports a failed list and a failed destroy; bad UBI_TTL_HOURS refuses creates and bad UBI_LEGACY_HOURS refuses reap, never read-only commands", async () => {
+ const api = serve({ seed: [{ name: "ubirun-other-1000000000-bbbb-t1" }] });
+ api.faults.destroy = true;
+ const destroyFails = await run(["reap"]);
+ expect(destroyFails.code).toBe(1);
+ expect(destroyFails.stderr).toContain("failed to reap eu-central-h1/ubirun-other-1000000000-bbbb-t1");
+ expect(destroyFails.stderr).toContain("reap: 1 of 1 expired VMs could not be destroyed");
+ api.faults.list = true;
+ const listFails = await run(["reap"]);
+ expect(listFails.code).toBe(1);
+ expect(listFails.stderr).toContain("reap: could not list the project's VMs; nothing destroyed");
+ for (const ttl of ["0", "08", "1000", "abc"]) {
+ const r = await run(["up"], { UBI_TTL_HOURS: ttl });
+ expect(r.code).toBe(1);
+ expect(r.stderr).toContain("UBI_TTL_HOURS must be a whole number of hours from 1 to 999");
+ }
+ expect((await run(["owner"], { UBI_TTL_HOURS: "0", UBI_LEGACY_HOURS: "0" })).code).toBe(0);
+ for (const legacy of ["0", "04", "x"]) {
+ const r = await run(["reap"], { UBI_LEGACY_HOURS: legacy });
+ expect(r.code).toBe(1);
+ expect(r.stderr).toContain("UBI_LEGACY_HOURS must be a whole number of hours from 1 to 9999");
+ }
+ expect(creates()).toEqual([]);
+ }, 60_000);
+});
+
+describe("run leftover line", () => {
+ it("ends with UBICLOUD: left=0 for its own VM, also in UBI_LEFT_FILE; a same-owner sibling is information only; --keep reports left=1 kept=1", async () => {
+ const api = serve({ seed: [{ name: "ubirun-t1-9999999999-sib1-t3" }] });
+ const leftFile = join(dir, "left");
+ const r = await run(["run", "--src", join(dir, "src"), "--", "true"], { UBI_LEFT_FILE: leftFile });
+ expect(r.code).toBe(0);
+ expect(r.stderr).toMatch(new RegExp(`UBICLOUD: left=0 owner=t1 vm=${RUN_VM} others=1\\n`));
+ expect(read("left")).toMatch(new RegExp(`^UBICLOUD: left=0 owner=t1 vm=${RUN_VM} others=1\\n$`));
+ // scripts/pregate-remote-gate.sh parses the file with this expression.
+ const parser = readFileSync(join(ROOT, "scripts/pregate-remote-gate.sh"), "utf8").match(/left=\$\(sed -n '([^']+)'/)![1]!;
+ expect(Bun.spawnSync(["sed", "-n", parser, leftFile], { timeout: 30_000 }).stdout.toString()).toBe("0\n");
+ expect([...api.vms.keys()]).toEqual(["ubirun-t1-9999999999-sib1-t3"]);
+ const kept = await run(["run", "--src", join(dir, "src"), "--keep", "--", "true"]);
+ expect(kept.code).toBe(0);
+ expect(kept.stderr).toMatch(new RegExp(`UBICLOUD: left=1 owner=t1 vm=${RUN_VM} kept=1\\n`));
+ expect(kept.stderr).not.toContain("left=0");
+ expect(api.vms.size).toBe(2);
+ }, 60_000);
+
+ it("a passing command whose teardown fails exits 1 with left=1 and the down command; a failing one keeps its status; an unreadable list is left=unknown", async () => {
+ const api = serve();
+ api.faults.destroy = true;
+ const leaked = await run(["run", "--src", join(dir, "src"), "--", "true"], { UBI_DOWN_TIMEOUT: "3" });
+ expect(leaked.code).toBe(1);
+ expect(leaked.stderr).toMatch(new RegExp(`UBICLOUD: left=1 owner=t1 vm=(${RUN_VM}) others=0\\n[^]*VM cleanup not confirmed for \\1 \\(left=1\\); destroy it with: \\S+ down \\1`));
+ writeFileSync(join(dir, "command-mode"), "exit 7");
+ const failedLeak = await run(["run", "--src", join(dir, "src"), "--", "false"], { UBI_DOWN_TIMEOUT: "3" });
+ expect(failedLeak.code).toBe(7);
+ expect(failedLeak.stderr).toMatch(new RegExp(`UBICLOUD: left=1 owner=t1 vm=${RUN_VM} others=1\\n`));
+ api.faults.destroy = false;
+ rmSync(join(dir, "command-mode"));
+ api.faults.list = true;
+ const blind = await run(["run", "--src", join(dir, "src"), "--", "true"]);
+ expect(blind.code).toBe(1);
+ expect(blind.stderr).toMatch(new RegExp(`UBICLOUD: left=unknown owner=t1 vm=${RUN_VM} others=unknown\\n`));
+ }, 90_000);
+});
+
+describe("watchdog", () => {
+ it("kills a silent ssh command with exit 124, its last output and its remote session; the heartbeat reports progress", async () => {
+ knownVm();
+ writeFileSync(join(dir, "command-mode"), 'echo "line one"; echo "warn one" >&2; sleep 20');
+ const hung = await run(["ssh", "vm-a", "make test"], { UBI_IDLE_TIMEOUT: "2" });
+ expect(hung.code).toBe(124);
+ expect(hung.stdout).toBe("line one\n");
+ expect(hung.stderr).toContain("warn one");
+ expect(hung.stderr).toMatch(/watchdog: ssh printed nothing for \d+s \(UBI_IDLE_TIMEOUT=2\); killing it\. Last output:/);
+ expect(hung.stderr.lastIndexOf("line one")).toBeGreaterThan(hung.stderr.indexOf("Last output:"));
+ expect(read("cancel.log")).toMatch(/sid=\$\(cat ~\/\.ubirun-ssh-\d+\.sid .*pkill -TERM -s/);
+ expect(read("ssh.log")).toMatch(/setsid -w bash -c 'printf %s \$\$ >~\/\.ubirun-ssh-\d+\.sid; bash -lc make\\ test'/);
+ const kept = readdirSync(join(dir, "state/vm-a")).filter((f) => f.endsWith(".log"));
+ expect(kept).toHaveLength(1);
+ expect(kept[0]).toMatch(/^ssh-\d+\.log$/);
+ expect(read(`state/vm-a/${kept[0]}`)).toContain("line one");
+
+ writeFileSync(join(dir, "command-mode"), 'for i in 1 2 3 4 5 6; do echo "tick $i"; sleep 0.5; done');
+ const beating = await run(["ssh", "vm-a", "true"], { UBI_IDLE_TIMEOUT: "0", UBI_HEARTBEAT: "1" });
+ expect(beating.code).toBe(0);
+ expect(beating.stdout).toContain("tick 6");
+ expect(beating.stderr).toMatch(/heartbeat: ssh \d+s elapsed, last output \d+s ago/);
+ expect(readdirSync(join(dir, "state/vm-a")).filter((f) => f.endsWith(".log"))).toEqual(kept);
+ }, 60_000);
+
+ it("times each command on its own clock: a silent command dies while another on the same VM keeps printing", async () => {
+ knownVm();
+ writeFileSync(join(dir, "command-mode"), 'if [ -f "$UBI_FAKE_ROOT/chatty" ]; then rm -f "$UBI_FAKE_ROOT/chatty"; for i in $(seq 1 16); do echo "chat $i"; sleep 0.5; done; else sleep 12; fi');
+ writeFileSync(join(dir, "chatty"), "");
+ let chattyDone = false;
+ const chatty = run(["ssh", "vm-a", "chatty"], { UBI_IDLE_TIMEOUT: "3" }).then((r) => ((chattyDone = true), r));
+ while (existsSync(join(dir, "chatty"))) await Bun.sleep(50);
+ const silent = await run(["ssh", "vm-a", "silent"], { UBI_IDLE_TIMEOUT: "3" });
+ expect(silent.code).toBe(124);
+ expect(chattyDone).toBe(false);
+ const c = await chatty;
+ expect(c.code).toBe(0);
+ expect(c.stdout).toContain("chat 16");
+ }, 60_000);
+
+ it("ssh NAME COMMAND hands the caller's stdin to the remote command", async () => {
+ knownVm();
+ const r = await run(["ssh", "vm-a", "cat > captured"], {}, "payload line\n");
+ expect(r.code).toBe(0);
+ expect(read("captured")).toBe("payload line\n");
+ }, 30_000);
+});
+
+describe("run", () => {
+ it("a hung setup is killed by the watchdog with exit 124, never reaches the command, and the VM is destroyed", async () => {
+ const api = serve();
+ writeFileSync(join(dir, "setup-mode"), "sleep 20");
+ writeFileSync(join(dir, "setup.sh"), "echo hi\n");
+ const r = await run(["run", "--src", join(dir, "src"), "--setup", join(dir, "setup.sh"), "--", "make test"], { UBI_IDLE_TIMEOUT: "2" });
+ expect(r.code).toBe(124);
+ expect(r.stderr).toMatch(/watchdog: setup printed nothing for \d+s \(UBI_IDLE_TIMEOUT=2\)/);
+ expect(r.stderr).toContain("setup failed (exit 124)");
+ expect(read("ssh.log")).not.toContain("bash -lc");
+ expect(read("cancel.log")).toMatch(/cat ~\/\.ubirun-setup-\d+\.sid/);
+ expect(r.stderr).toMatch(new RegExp(`destroyed eu-central-h1/${RUN_VM}`));
+ expect(api.vms.size).toBe(0);
+ }, 60_000);
+
+ it("UBI_RUN_TIMEOUT kills a command that keeps printing, with exit 124 and its reason", async () => {
+ const api = serve();
+ writeFileSync(join(dir, "command-mode"), 'for i in $(seq 1 20); do echo "tick $i"; sleep 0.5; done');
+ const r = await run(["run", "--src", join(dir, "src"), "--", "make test"], { UBI_RUN_TIMEOUT: "2" });
+ expect(r.code).toBe(124);
+ expect(r.stderr).toMatch(/watchdog: command ran \d+s \(UBI_RUN_TIMEOUT=2\); killing it/);
+ expect(r.stderr).toContain("command exited 124 after");
+ expect(api.vms.size).toBe(0);
+ }, 60_000);
+
+ it("--pass and --env forward named variables only; UBICLOUD_* and non-names are refused before any API call", async () => {
+ serve();
+ const ok = await run(["run", "--src", join(dir, "src"), "--pass", "UBI_TEST_TOKEN", "--env", "CI=1", "--", "make test"], { UBI_TEST_TOKEN: "sekret value" });
+ expect(ok.code).toBe(0);
+ expect(ok.stderr).toContain("command exited 0 after");
+ const envFile = read("ubirun-env");
+ expect(envFile).toContain("export UBI_TEST_TOKEN=sekret\\ value");
+ expect(envFile).toContain("export CI=1");
+ expect(envFile).not.toContain("UBICLOUD");
+ expect(ok.stdout + ok.stderr).not.toContain("sekret");
+ const before = creates().length;
+ for (const [flag, value, why] of [
+ ["--pass", "UBICLOUD_API_KEY", /never forwards its own Ubicloud credentials/],
+ ["--pass", "UBICLOUD_API_TOKEN", /never forwards its own Ubicloud credentials/],
+ ["--env", "UBICLOUD_API_KEY=x", /never forwards its own Ubicloud credentials/],
+ ["--pass", "X;Y", /not a variable name/],
+ ["--env", "A B=1", /not a variable name/],
+ ["--env", "NOVALUE", /give NAME=VALUE/],
+ ] as const) {
+ const r = await run(["run", "--src", join(dir, "src"), flag, value, "--", "true"]);
+ expect(r.code).toBe(1);
+ expect(r.stderr).toMatch(why);
+ }
+ expect(creates().length).toBe(before);
+ }, 90_000);
+
+ it("up and run accept only the storage sizes Ubicloud offers, before any API call; UBI_ALLOWED_STORAGE widens the list", async () => {
+ serve();
+ for (const args of [["up", "-S", "100"], ["run", "--storage", "1000", "--", "true"], ["up", "-S", ""]]) {
+ const r = await run(args);
+ expect(r.code).toBe(1);
+ expect(r.stderr).toContain("(allowed: 320 640; set UBI_ALLOWED_STORAGE when Ubicloud adds sizes)");
+ }
+ for (const [size, extra] of [["320", {}], ["1280", { UBI_ALLOWED_STORAGE: "320 640 1280" }]] as const) {
+ expect((await run(["run", "-S", size, "--bogus"], extra)).stderr).toContain("run: unknown option --bogus");
+ }
+ expect(creates()).toEqual([]);
+ }, 60_000);
+
+ it("up records the VM in the scratch file before its create request and down forgets it", async () => {
+ serve();
+ const up = await run(["up"]);
+ expect(up.code).toBe(0);
+ const name = up.stdout.trim();
+ expect(read("state/vms.tsv")).toMatch(new RegExp(`^${name}\\teu-central-h1\\tt1\\t\\S+\\t\\d+\\n$`));
+ expect((await run(["records"])).stdout).toContain(name);
+ expect((await run(["down", name])).code).toBe(0);
+ expect(read("state/vms.tsv")).toBe("");
+ }, 60_000);
+});
+
+describe("verify", () => {
+ it("runs only a committed .gstack/ubicloud.json, with its setup resolved against --src, refusing before any API call", async () => {
+ serve();
+ const src = join(dir, "repo");
+ mkdirSync(join(src, ".gstack"), { recursive: true });
+ const missing = await run(["verify", "--src", src]);
+ expect(missing.code).toBe(1);
+ expect(missing.stderr).toContain(`verify: no ${src}/.gstack/ubicloud.json; commit one`);
+ writeFileSync(join(src, ".gstack/ubicloud.json"), JSON.stringify({ setup: "scripts/boot.sh" }));
+ expect((await run(["verify", "--src", src])).stderr).toContain("names no command and none was given after --");
+ writeFileSync(join(src, ".gstack/ubicloud.json"), JSON.stringify({ setup: "scripts/boot.sh", command: "make verify" }));
+ expect((await run(["verify", "--src", src])).stderr).toContain(`setup script not found: ${src}/scripts/boot.sh`);
+ writeFileSync(join(src, ".gstack/ubicloud.json"), "{");
+ expect((await run(["verify", "--src", src])).stderr).toContain("is not valid JSON");
+ expect(creates()).toEqual([]);
+ }, 60_000);
+
+ it("forwards a configured pass name only when the command line grants it, and never UBICLOUD_*", async () => {
+ serve();
+ const src = repo({ setup: "scripts/boot.sh", command: "make verify", pass: ["UBI_TEST_TOKEN"] });
+ const refused = await run(["verify", "--src", src], { UBI_TEST_TOKEN: "x" });
+ expect(refused.code).toBe(1);
+ expect(refused.stderr).toContain("asks to forward local UBI_TEST_TOKEN; grant each on this command line with --pass NAME, or every name it lists with --trust-config");
+ expect(creates()).toEqual([]);
+ const granted = await run(["verify", "--src", src, "--pass", "UBI_TEST_TOKEN"], { UBI_TEST_TOKEN: "granted value" });
+ expect(granted.code).toBe(0);
+ expect(read("ubirun-env")).toContain("export UBI_TEST_TOKEN=granted\\ value");
+ expect(read("ubirun-setup.sh")).toBe("echo boot\n");
+ expect(read("ssh.log")).toContain("bash -lc make\\ verify");
+ const trusted = await run(["verify", "--src", src, "--trust-config"], { UBI_TEST_TOKEN: "trusted value" });
+ expect(trusted.code).toBe(0);
+ expect(read("ubirun-env")).toContain("export UBI_TEST_TOKEN=trusted\\ value");
+ writeFileSync(join(src, ".gstack/ubicloud.json"), JSON.stringify({ command: "make verify", pass: ["UBICLOUD_API_KEY"] }));
+ const n = creates().length;
+ const key = await run(["verify", "--src", src, "--trust-config"]);
+ expect(key.code).toBe(1);
+ expect(key.stderr).toContain("never forwards its own Ubicloud credentials");
+ expect(creates().length).toBe(n);
+ }, 90_000);
+
+ it("keeps the setup script and pull destinations inside --src: absolute, ~ and .. paths are refused before any API call", async () => {
+ serve();
+ const src = repo({});
+ writeFileSync(join(dir, "outside.sh"), "echo outside\n");
+ const cases: Array<[unknown, RegExp]> = [
+ [{ setup: join(dir, "outside.sh"), command: "x" }, /setup '[^']*outside\.sh' must be a relative path inside the checkout/],
+ [{ setup: "../outside.sh", command: "x" }, /must be a relative path inside the checkout/],
+ [{ setup: "scripts/../../outside.sh", command: "x" }, /must be a relative path inside the checkout/],
+ [{ setup: "~/outside.sh", command: "x" }, /must be a relative path inside the checkout/],
+ [{ command: "x", pull: ["logs:/etc/cron.d"] }, /pull destination '\/etc\/cron\.d' must be a relative path inside the checkout/],
+ [{ command: "x", pull: ["logs:../stolen"] }, /pull destination '\.\.\/stolen' must be a relative path inside the checkout/],
+ [{ command: "x", pull: ["no-colon"] }, /pull entry 'no-colon' must be REMOTE_GLOB:LOCAL_DIR/],
+ ];
+ for (const [cfg, want] of cases) {
+ writeFileSync(join(src, ".gstack/ubicloud.json"), JSON.stringify(cfg));
+ const r = await run(["verify", "--src", src]);
+ expect(r.code).toBe(1);
+ expect(r.stderr).toMatch(want);
+ }
+ expect(creates()).toEqual([]);
+ }, 90_000);
+
+ it("rechecks every pull destination at pull time: a symlink an earlier pull planted cannot redirect a later pull outside --src", async () => {
+ const api = serve();
+ const src = repo({ command: "make verify", pull: ["escape:.", "artifacts:escape/new/sub"] });
+ const victim = join(dir, "victim");
+ mkdirSync(victim);
+ mkdirSync(join(dir, "remote-fs/artifacts"), { recursive: true });
+ writeFileSync(join(dir, "remote-fs/artifacts/authorized_keys"), "ssh-ed25519 AAAA attacker\n");
+ symlinkSync(victim, join(dir, "remote-fs/escape"));
+ const r = await run(["verify", "--src", src]);
+ expect(r.code).toBe(1);
+ expect(r.stderr).toMatch(/pull refused: .*\/repo\/escape\/new\/sub resolves outside .*\/repo/);
+ expect(lstatSync(join(src, "escape")).isSymbolicLink()).toBe(true);
+ expect(readdirSync(victim)).toEqual([]);
+ expect(api.vms.size).toBe(0);
+ }, 60_000);
+
+ it("the committed .gstack/ubicloud.json is accepted: its setup is inside the checkout and it forwards nothing", async () => {
+ const cfg = JSON.parse(readFileSync(join(ROOT, ".gstack/ubicloud.json"), "utf8")) as { setup: string; command: string; pass?: string[]; env?: string[] };
+ expect(existsSync(join(ROOT, cfg.setup))).toBe(true);
+ expect(cfg.pass ?? []).toEqual([]);
+ expect((cfg.env ?? []).filter((e) => e.startsWith("UBICLOUD_"))).toEqual([]);
+ serve({ rejectCreates: true });
+ const r = await run(["verify", "--src", ROOT]);
+ expect(r.stderr).toContain(`verify: ${ROOT}/.gstack/ubicloud.json`);
+ expect(r.stderr).toContain("quota refused");
+ expect(creates()).toHaveLength(1);
+ }, 60_000);
+});
+
+describe("quota preflight", () => {
+ it("a refusal caches the maximum; the cache drives the preflight for a day, then is dropped; UBI_QUOTA_WAIT waits before refusing", async () => {
+ serve({ rejectCreates: true });
+ const refused = await run(["up"]);
+ expect(refused.code).toBe(1);
+ expect(refused.stderr).toContain("create failed: vCPU quota exhausted");
+ expect(read("state/quota-max").trim()).toBe("256");
+
+ serve({ seed: [{ name: "ubirun-peer-9999999999-cccc" }] });
+ writeFileSync(join(dir, "state/quota-max"), "31\n");
+ const cached = await run(["up"]);
+ expect(cached.code).toBe(1);
+ expect(cached.stderr).toMatch(new RegExp(`quota preflight refused eu-central-h1/${RUN_VM} \\(standard-16\\): it needs 16 vCPUs and the project's VMs already use 16 of 31 \\(ceiling from the last refusal, cached in .*quota-max;`));
+ expect(cached.stderr).toContain("create refused before any request: vCPU quota exhausted");
+ const t0 = Date.now();
+ const waited = await run(["up"], { UBI_QUOTA_WAIT: "3" });
+ expect(waited.code).toBe(1);
+ expect(waited.stderr).toMatch(/quota: 16 of 31 vCPUs in use and 16 needed; waiting up to 3s more for room/);
+ expect(Date.now() - t0).toBeGreaterThanOrEqual(3000); // gstack-timing-ok: UBI_QUOTA_WAIT is a wall-clock wait; a lower bound cannot flake
+ const fromEnv = await run(["up"], { UBI_QUOTA_VCPUS: "24" });
+ expect(fromEnv.stderr).toMatch(/already use 16 of 24 \(ceiling from UBI_QUOTA_VCPUS;/);
+ expect(creates()).toEqual([]);
+
+ const old = new Date(Date.now() - 2 * 86_400_000);
+ utimesSync(join(dir, "state/quota-max"), old, old);
+ const stale = await run(["up"]);
+ expect(stale.code).toBe(0);
+ expect(stale.stderr).not.toContain("quota preflight refused");
+ expect(existsSync(join(dir, "state/quota-max"))).toBe(false);
+ const name = stale.stdout.trim();
+ expect(name).toMatch(new RegExp(`^${RUN_VM}$`));
+ expect((await run(["down", name])).code).toBe(0);
+ }, 90_000);
+});
diff --git a/test/scripts/ubi-runner.test.ts b/test/scripts/ubi-runner.test.ts
index 0cc42fa3ff..d51ad2310e 100644
--- a/test/scripts/ubi-runner.test.ts
+++ b/test/scripts/ubi-runner.test.ts
@@ -75,7 +75,7 @@ describe("teardown waits for in-flight creates", () => {
const proc = spawnRunner(["up"], { UBI_OWNER: "t1" });
const started = await waitForEvent(api, /^create-start /);
const name = started.split(" ")[1]!;
- expect(name).toMatch(/^ubirun-t1-\d{10}-[0-9a-f]{8}-t999$/);
+ expect(name).toMatch(/^ubirun-t1-\d{10}-[0-9a-f]{8}-t3$/);
proc.kill(signal);
expect(await proc.exited).toBe(130);
expect(api.events).toEqual([`create-start ${name}`, `created ${name}`, `destroy ${name}`, `removed ${name}`]);
@@ -186,9 +186,12 @@ describe("stale sweep and ownership", () => {
expect([...api.vms.keys()].sort()).toEqual(seed.slice(1).map((s) => s.name).sort());
});
- it("gc HOURS destroys only the caller's VMs older than HOURS and requires HOURS", async () => {
+ it("gc HOURS destroys only the caller's VMs older than HOURS; without HOURS it destroys nothing", async () => {
const api = serve({ seed });
- expect((await run(["gc"], { UBI_OWNER: "t1" })).code).toBe(1);
+ const none = await run(["gc"], { UBI_OWNER: "t1" });
+ expect(none.code).toBe(0);
+ expect(none.stderr).toContain("gc: no sweep");
+ expect(api.events).toEqual([]);
const gc = await run(["gc", "1"], { UBI_OWNER: "t1" });
expect(gc.code).toBe(0);
expect(api.events).toEqual([`destroy ubirun-t1-${OLD}-aaaaaaaa`, `removed ubirun-t1-${OLD}-aaaaaaaa`]);
diff --git a/test/scripts/ubicloud-reap-expired.test.ts b/test/scripts/ubicloud-reap-expired.test.ts
index b88a9068ae..4ea49f69cd 100644
--- a/test/scripts/ubicloud-reap-expired.test.ts
+++ b/test/scripts/ubicloud-reap-expired.test.ts
@@ -47,9 +47,22 @@ describe("parseVmName", () => {
expect(parseVmName(`ubirun-gbra135-${NOW}-ci01a1b2-t2`)).toEqual({ kind: "expiring", owner: "gbra135", createdAt: NOW, expiresAt: NOW + 2 * H });
expect(parseVmName(`ubirun-trut4-${NOW}-e54c3f57-t4`)).toEqual({ kind: "expiring", owner: "trut4", createdAt: NOW, expiresAt: NOW + 4 * H });
expect(parseVmName(`ubirun-gsta30-${NOW}-a-b-c-t999`)).toEqual({ kind: "expiring", owner: "gsta30", createdAt: NOW, expiresAt: NOW + 999 * H });
- expect(parseVmName(`ubirun-gbra1-${NOW}-t5`)).toEqual({ kind: "no-expiry", owner: "gbra1", createdAt: NOW });
expect(parseVmName(`ubirun-gbra1-${NOW}-aaaa-t1000`)).toEqual({ kind: "foreign" });
- expect(parseVmName(`ubirun-${NOW}-aaaa-t3`)).toEqual({ kind: "foreign" });
+ });
+
+ // #8050 item 4: every name gstack's vm_rows reads as a TTL, this reaper reads the same way.
+ it("matches gstack's reap on hand-built TTL names: -t0, -t000, -t02, no suffix and untagged; a backwards -x expiry still skips", () => {
+ const names = [`ubirun-gbra1-${NOW - 2 * H}-aaaa-t0`, `ubirun-gbra1-${NOW - 2 * H}-bbbb-t000`, `ubirun-gbra1-${NOW - 3 * H}-cccc-t02`, `ubirun-gbra1-${NOW - 6 * H}-t5`, `ubirun-${NOW - 3 * H}-dddd-t2`];
+ expect(names.map(parseVmName)).toEqual([
+ { kind: "expiring", owner: "gbra1", createdAt: NOW - 2 * H, expiresAt: NOW - 2 * H },
+ { kind: "expiring", owner: "gbra1", createdAt: NOW - 2 * H, expiresAt: NOW - 2 * H },
+ { kind: "expiring", owner: "gbra1", createdAt: NOW - 3 * H, expiresAt: NOW - H },
+ { kind: "expiring", owner: "gbra1", createdAt: NOW - 6 * H, expiresAt: NOW - H },
+ { kind: "expiring", owner: "(untagged)", createdAt: NOW - 3 * H, expiresAt: NOW - H },
+ ]);
+ const plan = planReap([...names, backwards].map((name) => ({ location: LOC, name })), { now: NOW, graceSeconds: 15 * 60 });
+ expect(plan.map((row) => row.action)).toEqual(["destroy", "destroy", "destroy", "destroy", "destroy", "skip"]);
+ expect(plan.at(-1)!.reason).toBe("expiry before creation");
});
it("the gate's name helper writes -t<H> names of at most 63 characters that read back with their expiry", () => {
@@ -112,14 +125,14 @@ describe("planReap over both grammars", () => {
const ttlZero = `ubirun-gbra1-${NOW - H}-aaaaaaaa-t0`;
const rows = [ttlExpired, ttlGate, ttlLive, ttlLong, ttlZero, expired, live, noExpiry].map((name) => ({ location: LOC, name }));
- it("destroys expired -t<H> names of every owner and expired -x<expiry> names, and keeps live and TTL-less ones", () => {
+ it("destroys expired -t<H> names of every owner (a -t0 one too, as gstack does) and expired -x<expiry> names, and keeps live and TTL-less ones", () => {
const action = Object.fromEntries(planReap(rows, { now: NOW, graceSeconds: 15 * 60 }).map((row) => [row.name, row.action]));
expect(action).toEqual({
[ttlExpired]: "destroy",
[ttlGate]: "destroy",
[ttlLive]: "keep",
[ttlLong]: "keep",
- [ttlZero]: "skip",
+ [ttlZero]: "destroy",
[expired]: "destroy",
[live]: "keep",
[noExpiry]: "skip",
@@ -136,8 +149,8 @@ describe("planReap over both grammars", () => {
stderr: "pipe",
});
expect(await proc.exited).toBe(0);
- expect(mock.events.filter((e) => e.startsWith("destroy ")).sort()).toEqual([ttlExpired, ttlGate, expired].map((n) => `destroy ${n}`).sort());
- expect([...mock.vms.keys()].sort()).toEqual([ttlLive, ttlLong, ttlZero, live, noExpiry].sort());
+ expect(mock.events.filter((e) => e.startsWith("destroy ")).sort()).toEqual([ttlExpired, ttlGate, ttlZero, expired].map((n) => `destroy ${n}`).sort());
+ expect([...mock.vms.keys()].sort()).toEqual([ttlLive, ttlLong, live, noExpiry].sort());
} finally {
mock.stop();
rmSync(dir, { recursive: true, force: true });