Public: anyone can read this; the crew can change it.

A game box runs a claimed check in a cell with no reach to Docker, worlds or its token, and a join freezes it at once #17607

opened this

Merged 16h 54m ago, live in production

scout/forge:scout/17578-a-game-box-runs-a-claimed-check-in-a-cel → main 0 commits fork 1 thread · 1 unresolved

  • Merged. scout/17578-a-game-box-runs-a-claimed-check-in-a-cel was merged into main as 8b6ac90.

Review

Sign in to review this change.
14 files changed +857 −9
docs/features/game-box.md +5 −1
@@ -31,4 +31,8 @@ Code: `src/games/store.ts` (the `game_box` row and its token, the games store's)
3131 - **Console (owner only):** `/games/<box>` has a Console for the box's owner (forge admins are owners): a command is queued like an rcon (`kind: "shell"`, no service), and the agent runs it with `bash -lc` under `capped`, beside the sync: at most 30 s, no terminal and no input, at most 16 KB of output back at the next sync, streamed into the console over the box's own sync. A program that waits on a person (an editor, a pager, `top`, a bare shell or REPL, a `-f` follow) is refused before it is queued, saying what to run instead. Every command (`game.shell.asked`) and its output (`game.shell.done`) go to the audit, the owner's to read. In the terminal, `!` on a box's row opens the same console (`:` runs a command). `src/games/shell.ts`.
3232
3333 - **Spare while servers sleep (#17576):** `/games/<box>` has two `dl` rows (the `status-rows` of the security page), and the terminal's box screen (`b` on a service) the same two as its first line: "Spare while servers sleep: N core-hours a week, M GB (samples of 7 days). Forge checks, same week: C core-hours." (`src/games/spare.ts`, read by `spare_row.ts`, which keeps the pair a minute per box so a redraw or reload reads nothing). Spare memory = the box's memory − what is awake − a reserve that always fits the largest sleeping server (its highest memory seen awake in the window); spare core-hours = the idle cores (the box's vCPUs − awake servers' CPU, 100 % being a core) of each minute a server sleeps, scaled from the minutes sampled to a week. A box with everything awake has 0. Fewer than 24 hours of samples, or a size or sleeper's memory not known, says "unknown", never 0. The checks' figure is the `cpu_s` of the cost ledger's `check` entries that ended in the last 7 days (read from the end of the month files, stopping at the window's start, at most 4 MiB, not walking the chain; "not measured" when none carried it). A server counts as asleep in a minute that it held no memory.
34 - **Run checks while servers sleep (#17577):** the box's owner (forge admins own every box) sees a switch on `/games/<box>` (`POST /games/<box>/lend`, same-origin) and as `l` on the terminal's box screen, off by default, in the same words (`src/games/lend.ts`). Switching it on enrols a scoped `lent-box-<name>` runner for the box ([lent-runners.md](lent-runners.md)); switching it off revokes it at once. Its authors are the people who write the box's repository (its owner, teams and crew), read at each claim (a writer removed later is out at once), never a box owner who does not write it; a box with none names nobody, never anyone. The runner's token is not kept: the box's side of it is the next issue.
34 - **Run checks while servers sleep (#17577):** the box's owner (forge admins own every box) sees a switch on `/games/<box>` (`POST /games/<box>/lend`, same-origin) and as `l` on the terminal's box screen, off by default, in the same words (`src/games/lend.ts`). Switching it on enrols a scoped `lent-box-<name>` runner for the box ([lent-runners.md](lent-runners.md)); switching it off revokes it at once. Its authors are the people who write the box's repository (its owner, teams and crew), read at each claim (a writer removed later is out at once), never a box owner who does not write it; a box with none names nobody, never anyone. The runner's token is not kept: it is held in the forge's memory until the box's next sync carries it over, once (see below).
35 - **The box's side of it (#17578):** the sync answers `lend: { token }` once to a box that says `lend: "none"` while the switch is on (a forge restarted before the token was sent, or a reply lost, revokes that runner and enrols a new one: the box is never left without), and `lend: { off: true }` to one that still says `"have"` after the switch went off. The agent keeps the token in `/opt/forge-game/.runner.auth` (mode 600, beside `.auth`), and each tick claims one job (`wait: 0`) when it is safe: no container started in the last 90 s (`FORGE_GAME_LEND_QUIET`), no compose job running, `MemAvailable` at least 768 MiB (`FORGE_GAME_LEND_FLOOR_MIB`), and `bubblewrap` and `git` installed (new boxes install them; an older box runs nothing until they are there).
36 - **The cell:** the agent itself only claims, fetches the commit over the job's own git door as the unprivileged user `forge-job`, and answers. Each step is its own systemd unit (`forge-job-<id>`: `MemoryMax` the job's declared memory, no swap, `CPUQuota` its cpus, 512 tasks, `timeout` its seconds) as that user, in bubblewrap with `--unshare-all`, `/usr` read-only, the checkout at `/work`, a tmpfs `/tmp` and a cleared environment (`CI` and `FORGE_*` of the job only). It sees no `/run` (the Docker socket), no `/opt/forge-game` (`agent.env`, `.auth`, `.runner.auth`, compose), no data volume. The check step has no network at all. The install step shares the network, but an iptables rule on `forge-job`'s traffic rejects every private, loopback, link-local (the cloud's metadata door) and shared-range address, so the game network is not a route (the box's own addresses too, v4 and v6; a host with IPv6 and no `ip6tables` hands the install step back). A step's output is written inside that same tmpfs and no write takes it past 1 MiB (`FORGE_GAME_LEND_OUT_KIB`): the step is killed by SIGXFSZ, and the last 64 KiB is what is read. The disk cap is the checkout's own tmpfs (the job's `diskMiB`, at most 4 GiB, which is also charged to the job's memory cap). A job that names `egress` hosts, declares no memory, or whose step is missing a tool on the box (exit 126 or 127) is handed back (`abandon`): the forge runs it, and it is never red for the box's lack; after a missing tool the box claims nothing for 10 minutes. `/opt/forge-job-tools` is mounted read-only at `/opt/tools` (on `PATH`) when it exists: the toolchain a repository's check needs (bun, say) is put there by the box's owner.
37 - **A join:** `docker events` (a container starting) is read by the agent, and in that reader: claiming stops (`.wake`), every `forge-job-*` cgroup is frozen at once (`cgroup.freeze`), and nothing waits on the job. While a step runs, a guard looks twice a second: still frozen and `MemAvailable` under the floor, or frozen for 5 minutes (`FORGE_GAME_LEND_FROZEN_S`), and the job is killed (`cgroup.kill`, then the unit stopped) and answered `interrupted`; a quiet box (90 s, memory above the floor) thaws it. `interrupted` puts the job back in the queue with no result: it is never red, and its claim is not counted, so it is never a try of that check's `MAX_CLAIMS` (the check's log says "stopped the job … not a try, nor a result"). The guard also renews the lease every 10 s, frozen or not.
38 - **Not done, and not proved yet:** nothing here has run on a real box (it waits for the owner's go): tps and mspt of an awake server with and without a job, and the wake time on a join with one running, are still to be measured from `src/games/metrics.ts`'s samples. The cell was checked against stand-ins (`test/game-lend-box.test.ts`), not against a real kernel's bubblewrap.
docs/features/runners.md +4
@@ -197,3 +197,7 @@ The owner sees it too: while lent runners wait, the runners screen in the termin
197197 A runner reports its own machine, and the forge cannot check the report. So the figure the owner sets slots by trusts only the owner's own runners. A lent runner's report shows on its row and moves nothing.
198198
199199 **A runner's cells and the kernel.** Inside a runner's container a cell is held by the kernel (its own cgroup with `cpu.max`, `memory.max` and `pids.max`, OOM-killed whole past its memory) only where the container's cgroup is delegated to it: `FORGE_CELL_CGROUP` names it, read-write (on vxrail, `runners.sh` binds each delegated runner's own scope in at `/cgd/cg` as root, through `runner-cgroup.sh`). Docker mounts the container's cgroupfs read-only and root's, so without that a runner's cells are watched from `/proc` alone. The cgroup may arrive a moment after the runner starts: until it is writable, each cell asks again (`settled`, `src/apps/cgroup.ts`), so an early first job never leaves the runner uncontained.
200
201 ## A job given up because the machine needs itself
202
203 A runner may answer a held job `{ "interrupted": "<why>" }` (a game box does when a server wakes, [game-box.md](game-box.md)). The job goes back to queued with its claim not counted: it is no result, never red, and no nearer the check's `MAX_CLAIMS` than before. `abandon`, by contrast, ends the job and the forge runs the check itself.
src/checks/runner_jobs.ts +21 −1
@@ -664,6 +664,26 @@ export function settleJob(
664664 })();
665665 }
666666
667 /**
668 * A held job its runner gives up because the machine needs itself (a game box's server woke,
669 * #17578): back to queued, its token dead, and the claim not counted once, so a join is not a try;
670 * a job interrupted again keeps its claim, so a runner that interrupts forever brings the check to
671 * `MAX_CLAIMS` and the forge runs it itself. Never a result: the runner's reason is kept as
672 * `interrupted: …` for the check's log (a lapsed lease clears it). False, and nothing written, when
673 * the claim is no longer this token's.
674 */
675 export function interruptJob(db: Database, jobId: string, presented: string, why: string): boolean {
676 return (
677 db
678 .query(
679 `UPDATE check_job SET state = 'queued', runner_id = NULL, token_hash = NULL, lease_until = 0,
680 claims = CASE WHEN COALESCE(result, '') LIKE 'interrupted: %' THEN claims ELSE MAX(claims - 1, 0) END,
681 result = ?3 WHERE id = ?1 AND token_hash = ?2 AND state = 'claimed'`,
682 )
683 .run(jobId, sha256(presented), `interrupted: ${why.slice(0, 200)}`).changes > 0
684 );
685 }
686
667687 /**
668688 * Every claim whose lease ran out goes back to queued, its token dead. Returns their ids. The
669689 * check each serves is still running under the forge's own lease: nothing is counted as a try.
@@ -671,7 +691,7 @@ export function settleJob(
671691 export function lapseJobs(db: Database, now: number): string[] {
672692 return db
673693 .query<{ id: string }, [number]>(
674 `UPDATE check_job SET state = 'queued', runner_id = NULL, token_hash = NULL, lease_until = 0
694 `UPDATE check_job SET state = 'queued', runner_id = NULL, token_hash = NULL, lease_until = 0, result = NULL
675695 WHERE state = 'claimed' AND lease_until <= ?1 RETURNING id`,
676696 )
677697 .all(now)
src/checks/runner_step.ts +3 −1
@@ -229,7 +229,9 @@ export async function runRunnerStep(
229229 return { taken: false, why: "the job left the desk" };
230230 if (view.state === "queued" && holder !== "") {
231231 input.log(
232 `runner ${holder} went silent: the job is queued again, and that is not a try`,
232 view.result?.startsWith("interrupted: ") === true
233 ? `runner ${holder} stopped the job (${view.result.slice(13)}): queued again, and that is not a try, nor a result`
234 : `runner ${holder} went silent: the job is queued again, and that is not a try`,
233235 );
234236 // What a half-run printed is not the check's output.
235237 input.output.length = 0;
src/contract/openapi/routes/postApiV1RunnerJobsId.ts +2 −2
@@ -6,10 +6,10 @@ export const route: Route = {
66 summary:
77 "A runner reports on the job it holds. Takes that job's token",
88 detail:
9 "A runner reports on the job it holds. Takes that job's token as the bearer. lines (of one step) are appended to the check's log; done { steps, contained, note } ends it with a result, abandon hands it back; every report renews the lease and answers { lease } or { ended }",
9 "A runner reports on the job it holds. Takes that job's token as the bearer. lines (of one step) are appended to the check's log; done { steps, contained, note } ends it with a result, abandon hands it back (the forge runs the check itself); interrupted gives it up because the runner's machine needs itself (a game box's server woke): it is queued again, with no result and no try counted; every report renews the lease and answers { lease } or { ended }",
1010 auth: false,
1111 role: "anonymous",
12 body: { step: "string", lines: "array", done: "object", abandon: "string" },
12 body: { step: "string", lines: "array", done: "object", abandon: "string", interrupted: "string" },
1313 refusals: { not_found: "404: no such job, not this token's job, or its lease is over: stop the job", invalid_result: "422: done is not { steps: [{ name, ok, error?, ms }], contained, note }", adopting: "503: the forge is restarting and no one waits on the job yet: keep it, keep the lines, report again (the lease is pushed out)" },
1414 refuses: [404],
1515 errorStatus: { 503: "`adopting`: the forge is restarting; keep the job and report again" },
src/games/agent.sh +363 −1
@@ -916,6 +916,7 @@ sync() {
916916 --slurpfile metrics "$DIR/.sync.metrics" \
917917 --slurpfile snapshots "$DIR/.sync.snapshots" \
918918 --slurpfile chat "$DIR/.sync.chat" \
919 --arg lend "$(lend_has)" \
919920 'def sect: {"0":"r","1":"l","4":"n","22":"r","24":"r","39":"r","30":"0","31":"4","32":"2","33":"6","34":"1","35":"5","36":"3","37":"7","90":"8","91":"c","92":"a","93":"e","94":"9","95":"d","96":"b","97":"f"} as $t
920921 | ["30","31","32","33","34","35","36","37","90","91","92","93","94","95","96","97"] as $sixteen
921922 # 38;5;n is one of the sixteen colours by its number; a background (48) and the other
@@ -926,7 +927,7 @@ sync() {
926927 else [.[0]] + (.[1:] | codes) end;
927928 (if . == "" then ["0"] else split(";") end) | [codes[] | $t[.] // empty | "\u00a7" + .] | join("");
928929 def plain: gsub("\u001b\\[(?<p>[0-9;]*)m"; (.p // "" | sect)) | gsub("^(\u00a7r)+|(\u00a7r)+$"; "") | gsub("(\u00a7r)+"; "\u00a7r") | gsub("\u001b\\[[0-9;?]*[ -/]*[@-~]"; "") | gsub("\u001b[@-_]?"; "") | gsub("[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f]"; "");
929 {agent: 1, composeSha: $sha, services: $services[0], logs: $logs[0], results: $results[0], host: $host[0], diag: $diag[0], people: $people[0], metrics: $metrics[0], snapshots: $snapshots[0], chat: $chat[0].lines, chatId: $chat[0].id}
930 {agent: 1, composeSha: $sha, services: $services[0], logs: $logs[0], results: $results[0], host: $host[0], diag: $diag[0], people: $people[0], metrics: $metrics[0], snapshots: $snapshots[0], chat: $chat[0].lines, chatId: $chat[0].id, lend: $lend}
930931 | walk(if type == "string" then plain else . end)' >"$DIR/.sync.body" || return 1
931932 answer="$(curl -fsS -m 20 -H "@$AUTH" -H 'content-type: application/json' --data-binary "@$DIR/.sync.body" "${FORGE_URL%/}/api/v1/games/agent/sync")" || return 1
932933 # Delivered: the results and the log lines are the forge's now.
@@ -936,6 +937,366 @@ sync() {
936937 # A newer agent first: nothing of this answer is applied by a script the forge has replaced.
937938 self_update "$(jq -r '.agentSha // ""' <<<"$answer")"
938939 apply "$answer"
940 lend_apply "$answer"
941 }
942
943 # ---- "Run checks while servers sleep" (#17578): the box's side. With the owner's switch on, the
944 # forge has sent a runner token (`.runner.auth`, mode 600, in $DIR: no cell sees it). Each tick,
945 # when no server woke in the last LEND_QUIET seconds, nothing else runs and memory is above the
946 # floor, the agent claims one job and runs its steps here. The job's code never runs as root or in
947 # this shell: each step is its own systemd unit (`forge-job-<id>`: a memory, cpu and task cap, and a
948 # cgroup of its own to freeze) as the unprivileged user $LEND_USER, in a bubblewrap cell that sees
949 # /usr read-only and the job's checkout and nothing else: not /run (the Docker socket), not
950 # /opt/forge-game (agent.env, compose, .auth), not the data volume, and no network at all for the
951 # check step. The install step shares the network, but iptables rejects everything that user sends
952 # to a private or link-local address: the game network and the cloud's metadata door are not routes.
953 # The job's checkout is a tmpfs of its own size (the disk cap), gone when the job ends.
954 # A join (a container starting; `docker events`) is met in this order, in the event reader itself,
955 # so no job is waited on: claiming stops (`.wake`), the job's cgroup is frozen at once, and the job
956 # is stopped and handed back as interrupted when memory is needed (below the floor) or when it has
957 # been frozen too long. Interrupted is not red and not a try.
958 LEND_AUTH="$DIR/.runner.auth"
959 LEND_ROOT="${FORGE_GAME_LEND_ROOT:-/var/lib/forge-job}"
960 LEND_USER="${FORGE_GAME_LEND_USER:-forge-job}"
961 LEND_CGROUP="${FORGE_GAME_CGROUP:-/sys/fs/cgroup/system.slice}"
962 LEND_QUIET="${FORGE_GAME_LEND_QUIET:-90}"
963 LEND_FLOOR="${FORGE_GAME_LEND_FLOOR_MIB:-768}"
964 LEND_FROZEN_MAX="${FORGE_GAME_LEND_FROZEN_S:-300}"
965 LEND_LOOK="${FORGE_GAME_LEND_LOOK:-0.5}"
966 LEND_MEMINFO="${FORGE_GAME_MEMINFO:-/proc/meminfo}"
967 LEND_TOOLS="${FORGE_GAME_LEND_TOOLS:-/opt/forge-job-tools}"
968 # 1 (the default) on a real box: the user, the tmpfs and the iptables rules are made. 0 in a test.
969 LEND_HOST="${FORGE_GAME_LEND_HOST:-1}"
970 LEND_OUT_KIB="${FORGE_GAME_LEND_OUT_KIB:-1024}"
971 LEND_RUN=("${FORGE_GAME_LEND_RUN:-systemd-run}")
972 LEND_CELL="${FORGE_GAME_LEND_CELL:-bwrap}"
973 SYSTEMCTL="${FORGE_GAME_SYSTEMCTL:-systemctl}"
974 LEND_JOBAUTH="$DIR/.lend.job.auth"
975 EVICTED=0
976
977 lend_has() { [ -s "$LEND_AUTH" ] && echo have || echo none; }
978 lend_avail() { awk '/^MemAvailable:/ {print int($2/1024)}' "$LEND_MEMINFO" 2>/dev/null || echo 0; }
979 lend_quiet() {
980 local t
981 t="$(cat "$DIR/.wake" 2>/dev/null)"
982 [[ "$t" =~ ^[0-9]+$ ]] || t=0
983 [ $(($(date +%s) - t)) -ge "$LEND_QUIET" ]
984 }
985 lend_unit() { echo "$LEND_CGROUP/forge-job-$1.service"; }
986 lend_freeze() { [ -e "$(lend_unit "$1")/cgroup.freeze" ] && echo 1 >"$(lend_unit "$1")/cgroup.freeze"; return 0; }
987 lend_thaw() { [ -e "$(lend_unit "$1")/cgroup.freeze" ] && echo 0 >"$(lend_unit "$1")/cgroup.freeze"; return 0; }
988 # Every job's cgroup, at once: what a join does first.
989 lend_freeze_all() {
990 local f
991 for f in "$LEND_CGROUP"/forge-job-*.service/cgroup.freeze; do
992 [ -e "$f" ] && echo 1 >"$f"
993 done
994 return 0
995 }
996 # Stop a job: its processes killed where they are (a frozen cgroup is killed too), then its unit.
997 lend_kill() {
998 [ -e "$(lend_unit "$1")/cgroup.kill" ] && echo 1 >"$(lend_unit "$1")/cgroup.kill"
999 "$SYSTEMCTL" stop "forge-job-$1.service" >/dev/null 2>&1
1000 return 0
1001 }
1002
1003 # What a sync answered about the switch: the runner token, kept; or the word to drop it.
1004 lend_apply() {
1005 local answer="$1" token
1006 if jq -e '.lend.off == true' >/dev/null 2>&1 <<<"$answer"; then
1007 lend_stop_all
1008 rm -f "$LEND_AUTH"
1009 return
1010 fi
1011 token="$(jq -r '.lend.token // ""' <<<"$answer" 2>/dev/null)"
1012 [[ "$token" =~ ^forge_runner_[A-Za-z0-9_-]{16,128}$ ]] || return
1013 printf 'Authorization: Bearer %s\n' "$token" >"$LEND_AUTH.next" && mv "$LEND_AUTH.next" "$LEND_AUTH"
1014 }
1015
1016 # Switched off: the job in hand is stopped where it is; the forge has revoked its token.
1017 lend_stop_all() {
1018 local p
1019 p="$(cat "$DIR/.lend.pid" 2>/dev/null)"
1020 [ -n "$p" ] && kill "$p" 2>/dev/null
1021 "$SYSTEMCTL" stop 'forge-job-*.service' >/dev/null 2>&1
1022 rm -f "$DIR/.lend.pid" "$LEND_JOBAUTH"
1023 return 0
1024 }
1025
1026 # One `docker events` reader: each container that starts is a join (or a compose up). It stops
1027 # claiming and freezes the jobs at once, here, never waiting on one.
1028 lend_watch() {
1029 local p
1030 p="$(cat "$DIR/.lend.watch" 2>/dev/null)"
1031 [ -n "$p" ] && kill -0 "$p" 2>/dev/null && return
1032 (
1033 "$DOCKER" events --filter type=container --filter event=start --format '{{.ID}}' 2>/dev/null | while read -r _; do
1034 date +%s >"$DIR/.wake"
1035 lend_freeze_all
1036 done
1037 ) >/dev/null 2>&1 </dev/null &
1038 echo $! >"$DIR/.lend.watch"
1039 }
1040
1041 lend_running() {
1042 local p
1043 p="$(cat "$DIR/.lend.pid" 2>/dev/null)"
1044 [ -n "$p" ] && kill -0 "$p" 2>/dev/null
1045 }
1046
1047 # Each tick: one job at a time, and only in a quiet, roomy, idle box.
1048 lend_tick() {
1049 [ -s "$LEND_AUTH" ] || return 0
1050 # A box made before the cell was (no bubblewrap or git) runs nothing: a job never runs uncontained.
1051 command -v "$LEND_CELL" >/dev/null 2>&1 && command -v git >/dev/null 2>&1 || return 0
1052 lend_watch
1053 lend_running && return 0
1054 job_running && return 0
1055 lend_quiet || return 0
1056 [ "$(lend_avail)" -ge "$LEND_FLOOR" ] || return 0
1057 [ "$(date +%s)" -ge "$(cat "$DIR/.lend.cool" 2>/dev/null || echo 0)" ] || return 0
1058 lend_work &
1059 echo $! >"$DIR/.lend.pid"
1060 # A test waits for its one job; the service never does.
1061 if [ "$ONCE" = 1 ]; then wait $! 2>/dev/null; fi
1062 return 0
1063 }
1064
1065 # POST to a held job: its answer, its lines, or nothing (a heartbeat). Non-zero when the claim is gone.
1066 lend_post() {
1067 curl -sS -m 20 -o /dev/null --fail -H "@$LEND_JOBAUTH" -H 'content-type: application/json' --data "$2" "${FORGE_URL%/}/api/v1/runner/jobs/$1"
1068 }
1069
1070 lend_work() {
1071 local res="$DIR/.lend.claim" code cpus mem
1072 cpus="$(nproc 2>/dev/null || echo 1)"
1073 mem="$(awk '/^MemTotal:/ {print int($2/1024)}' "$LEND_MEMINFO" 2>/dev/null || echo 0)"
1074 code="$(curl -sS -m 20 -o "$res" -w '%{http_code}' -H "@$LEND_AUTH" -H 'content-type: application/json' \
1075 --data "$(jq -cn --argjson c "$cpus" --argjson m "${mem:-0}" '{wait: 0, cells: true, jobs: 1, machine: {cpus: $c, memoryMiB: $m, hostCpus: $c}}')" \
1076 "${FORGE_URL%/}/api/v1/runner/claim")" || return 0
1077 case "$code" in
1078 200) lend_job "$res" ;;
1079 # The forge does not know the token (switched off, or replaced): drop it; the next sync says which.
1080 401) rm -f "$LEND_AUTH" ;;
1081 esac
1082 return 0
1083 }
1084
1085 # The job's variables, as the runner's own filter lets them through: CI and FORGE_*, never FORGE_RUNNER*.
1086 lend_env() {
1087 jq -r '.job.env // {} | to_entries[] | select((.key == "CI" or (.key | test("^FORGE_[A-Z0-9_]+$"))) and (.key | startswith("FORGE_RUNNER") | not) and (.value | type == "string")) | "\(.key)=\(.value)"' "$1" 2>/dev/null
1088 }
1089
1090 # Ensure what keeps a job off the box: its user, and the rule that rejects its traffic to private
1091 # and link-local addresses (the game network, the cloud's metadata door). Non-zero when not so.
1092 lend_net_ready() {
1093 [ "$LEND_HOST" = 1 ] || return 0
1094 id "$LEND_USER" >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin "$LEND_USER" >/dev/null 2>&1 || return 1
1095 local tool dsts a mine4="" mine6=""
1096 # The box's own addresses too: Docker publishes the worlds' ports on them.
1097 for a in $(hostname -I 2>/dev/null); do
1098 case "$a" in *:*) mine6="$mine6,$a/128" ;; *.*) mine4="$mine4,$a/32" ;; esac
1099 done
1100 for tool in iptables ip6tables; do
1101 if ! command -v "$tool" >/dev/null 2>&1; then
1102 # No ip6tables is fine only on a host with no IPv6 to leave by.
1103 [ "$tool" = ip6tables ] && ! grep -qv '^00000000000000000000000000000001 ' /proc/net/if_inet6 2>/dev/null && continue
1104 return 1
1105 fi
1106 dsts="10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,169.254.0.0/16,127.0.0.0/8,100.64.0.0/10$mine4"
1107 [ "$tool" = ip6tables ] && dsts="::1/128,fc00::/7,fe80::/10$mine6"
1108 "$tool" -w -C OUTPUT -m owner --uid-owner "$LEND_USER" -d "$dsts" -j REJECT 2>/dev/null ||
1109 "$tool" -w -I OUTPUT -m owner --uid-owner "$LEND_USER" -d "$dsts" -j REJECT || return 1
1110 done
1111 }
1112
1113 # Run a command as the job's user (a test, which is not root, runs it as itself).
1114 as_job() {
1115 if [ "$LEND_HOST" = 1 ]; then
1116 setpriv --reuid="$LEND_USER" --regid="$LEND_USER" --clear-groups --no-new-privs "$@"
1117 else
1118 "$@"
1119 fi
1120 }
1121
1122 # One step in its own unit and cell. $1 job id, $2 command, $3 seconds, $4 MiB, $5 cpus, $6 net (1/0),
1123 # $7 the checkout, $8 the file its output goes to. The guard watches it while it runs.
1124 lend_step() {
1125 local id="$1" cmd="$2" secs="$3" mem="$4" cpus="$5" net="$6" work="$7" out="$8" pid rc kv
1126 local -a cell=(--unshare-all --die-with-parent --new-session
1127 --ro-bind /usr /usr --symlink usr/bin /bin --symlink usr/sbin /sbin --symlink usr/lib /lib --symlink usr/lib64 /lib64
1128 --ro-bind-try /etc/ssl /etc/ssl --ro-bind-try /etc/ca-certificates /etc/ca-certificates
1129 --proc /proc --dev /dev --tmpfs /tmp --bind "$work/src" /work --chdir /work --clearenv
1130 --setenv PATH /opt/tools/bin:/usr/local/bin:/usr/bin:/bin --setenv HOME /tmp)
1131 [ -d "$LEND_TOOLS" ] && cell+=(--ro-bind "$LEND_TOOLS" /opt/tools)
1132 if [ "$net" = 1 ]; then
1133 printf 'nameserver 1.1.1.1\nnameserver 9.9.9.9\n' >"$work/resolv.conf"
1134 cell+=(--share-net --ro-bind "$work/resolv.conf" /etc/resolv.conf)
1135 fi
1136 while IFS= read -r kv; do
1137 [ -n "$kv" ] && cell+=(--setenv "${kv%%=*}" "${kv#*=}")
1138 done <"$work/env"
1139 local -a props=(-p "MemoryMax=${mem}M" -p MemorySwapMax=0 -p "CPUQuota=$((cpus * 100))%" -p TasksMax=512)
1140 [ "$LEND_HOST" = 1 ] && props+=(-p "User=$LEND_USER")
1141 : >"$out"
1142 # What a step prints is bounded twice: the file is on the job's capped disk, and no write takes it
1143 # past LEND_OUT_KIB (the step is killed by SIGXFSZ then, and its tail is what is kept).
1144 (
1145 ulimit -f "$LEND_OUT_KIB"
1146 exec "${LEND_RUN[@]}" --quiet --collect --wait --pipe --unit "forge-job-$id" "${props[@]}" -- \
1147 timeout -k 5 "$secs" "$LEND_CELL" "${cell[@]}" -- bash -c "$cmd" >"$out" 2>&1 </dev/null

Non-blocking: ulimit -f binds systemd-run and its output redirect, not the unit's own processes, which systemd starts. The tmpfs cap is the real limit, so say so in the comment.

1148 ) &
1149 pid=$!
1150 lend_guard "$pid" "$id"
1151 wait "$pid"
1152 rc=$?
1153 return "$rc"
1154 }
1155
1156 # While a step runs: keep the claim alive, and meet a join in order: claiming has stopped (the
1157 # worker took none), the cgroup is frozen at once, and the job is stopped when memory is needed or
1158 # it has been frozen too long. A quiet box thaws it again.
1159 lend_guard() {
1160 local pid="$1" id="$2" beat=0 frozen=0 t
1161 while kill -0 "$pid" 2>/dev/null; do
1162 sleep "$LEND_LOOK"
1163 t="$(date +%s)"
1164 if ! lend_quiet; then
1165 lend_freeze "$id"
1166 [ "$frozen" = 0 ] && frozen="$t"
1167 if [ "$(lend_avail)" -lt "$LEND_FLOOR" ] || [ $((t - frozen)) -ge "$LEND_FROZEN_MAX" ]; then
1168 EVICTED=1
1169 lend_kill "$id"
1170 return 0
1171 fi
1172 elif [ "$frozen" != 0 ] && [ "$(lend_avail)" -ge "$LEND_FLOOR" ]; then
1173 lend_thaw "$id"
1174 frozen=0
1175 fi
1176 if [ $((t - beat)) -ge 10 ]; then
1177 lend_post "$id" '{}' || { EVICTED=2; lend_kill "$id"; return 0; }
1178 beat="$t"
1179 fi
1180 done
1181 }
1182
1183 # The job's claim file to its answer. Anything the box cannot or may not do is handed back, never red.
1184 lend_job() {
1185 local f="$1" id tok commit base depth secs mem cpus disk work out name cmd rc t0 ms err steps='[]' net
1186 id="$(jq -r '.job.id // ""' "$f")"
1187 tok="$(jq -r '.token // ""' "$f")"
1188 [[ "$id" =~ $SAFE ]] && [[ "$tok" =~ ^forge_job_[A-Za-z0-9_-]{16,128}$ ]] || return 0
1189 printf 'Authorization: Bearer %s\n' "$tok" >"$LEND_JOBAUTH"
1190 commit="$(jq -r '.job.commit // ""' "$f")"
1191 base="$(jq -r '.job.base // ""' "$f")"
1192 depth="$(jq -r '.job.depth // 1' "$f")"
1193 secs="$(jq -r '.job.timeoutS // 600' "$f")"
1194 mem="$(jq -r '.job.limits.memoryMiB // 0' "$f")"
1195 cpus="$(jq -r '.job.limits.cpus // 1' "$f")"
1196 disk="$(jq -r '.job.limits.diskMiB // 1024' "$f")"
1197 [[ "$commit" =~ ^[0-9a-f]{40}$ ]] || { lend_give "$id" abandon "the job names something that is not a commit id"; return 0; }
1198 [ -z "$base" ] || [[ "$base" =~ ^[0-9a-f]{40}$ ]] || { lend_give "$id" abandon "the job names a base that is not a commit id"; return 0; }
1199 [[ "$depth" =~ ^[0-9]{1,5}$ ]] && [[ "$secs" =~ ^[0-9]{1,5}$ ]] && [[ "$mem" =~ ^[0-9]{1,6}$ ]] && [[ "$cpus" =~ ^[0-9]{1,2}$ ]] && [[ "$disk" =~ ^[0-9]{1,6}$ ]] || { lend_give "$id" abandon "the job's limits are not numbers"; return 0; }
1200 [ "$mem" -ge 1 ] && [ "$cpus" -ge 1 ] || { lend_give "$id" abandon "the job declares no memory or cpus to hold it to"; return 0; }
1201 [ "$disk" -gt 4096 ] && disk=4096
1202 # What a cell without a network cannot serve: a check that names hosts it reaches.
1203 if [ "$(jq -r '(.job.egress // []) | length' "$f")" != 0 ]; then
1204 lend_give "$id" abandon "the job reaches hosts, and this box's cell has no network for a check"
1205 return 0
1206 fi
1207 if jq -e '[.job.steps[]? | .name] | index("install")' "$f" >/dev/null 2>&1 && ! lend_net_ready; then
1208 lend_give "$id" abandon "this box could not close its network to a job's install step"
1209 return 0
1210 fi
1211 work="${LEND_ROOT:?}/$id"
1212 mkdir -p "$work"
1213 lend_env "$f" >"$work.env"
1214 if [ "$LEND_HOST" = 1 ]; then
1215 mount -t tmpfs -o "size=${disk}m,mode=0700,uid=$(id -u "$LEND_USER" 2>/dev/null),gid=$(id -g "$LEND_USER" 2>/dev/null)" tmpfs "$work" || {
1216 lend_clean "$id" "$work"
1217 lend_give "$id" abandon "this box could not make the job's disk"
1218 return 0
1219 }
1220 fi
1221 # The checkout's directory is the job user's to write (the tmpfs is its own, mode 0700); the
1222 # step's output lives beside it, inside the same capped disk.
1223 as_job mkdir "$work/src" || { lend_clean "$id" "$work"; lend_give "$id" abandon "this box could not make the job's checkout"; return 0; }
1224 out="$work/out"
1225 mv "$work.env" "$work/env" 2>/dev/null || : >"$work/env"
1226 EVICTED=0
1227 if ! lend_checkout "$id" "$tok" "$commit" "$base" "$depth" "$work"; then
1228 lend_clean "$id" "$work"
1229 lend_give "$id" abandon "the box could not fetch the commit"
1230 return 0
1231 fi
1232 while IFS=$'\t' read -r name cmd; do
1233 net=0
1234 [ "$name" = install ] && net=1
1235 t0="$(date +%s%N)"
1236 lend_step "$id" "$cmd" "$secs" "$mem" "$cpus" "$net" "$work" "$out"
1237 rc=$?
1238 ms=$((($(date +%s%N) - t0) / 1000000))
1239 if [ "$EVICTED" = 1 ]; then
1240 lend_clean "$id" "$work"
1241 lend_give "$id" interrupted "a server woke on this box and needs its memory"
1242 return 0
1243 fi
1244 if [ "$EVICTED" = 2 ]; then
1245 lend_clean "$id" "$work"
1246 return 0
1247 fi
1248 # What the box lacks is not the check's fault: a missing command is handed back, and the box rests.
1249 if [ "$rc" = 126 ] || [ "$rc" = 127 ]; then
1250 echo $(($(date +%s) + 600)) >"$DIR/.lend.cool"
1251 lend_clean "$id" "$work"
1252 lend_give "$id" abandon "this box has no tool the step needs ($name exited with code $rc)"
1253 return 0
1254 fi
1255 lend_post "$id" "$(jq -cn --arg s "$name" --rawfile l <(tail -c 65536 "$out") '{step: $s, lines: ($l | split("\n") | .[-200:] | map(.[0:400]))}')" || true
1256 err=""
1257 case "$rc" in
1258 0) ;;
1259 124) err="$name took longer than ${secs}s" ;;
1260 *) if [ "$rc" -ge 128 ]; then err="$name was killed (signal $((rc - 128)))"; else err="$name exited with code $rc"; fi ;;
1261 esac
1262 steps="$(jq -c --arg n "$name" --arg e "$err" --argjson ms "$ms" '. + [{name: $n, ok: ($e == ""), ms: $ms} + (if $e == "" then {} else {error: $e} end)]' <<<"$steps")"
1263 [ -z "$err" ] || break
1264 done < <(jq -r '.job.steps[]? | select(.name == "install" or .name == "check") | [.name, (.command | gsub("[\\t\\n]"; " "))] | @tsv' "$f")
1265 lend_clean "$id" "$work"
1266 lend_give "$id" done "$steps"
1267 return 0
1268 }
1269
1270 # `git fetch` of the job's commit (and its base) over the job's own git door, as the job's user,
1271 # with the token in git's environment config (the environment of the call, never an argument, so
1272 # not in /proc/<pid>/cmdline or ps).
1273 lend_checkout() {
1274 local id="$1" tok="$2" commit="$3" base="$4" depth="$5" work="$6" url
1275 url="${FORGE_URL%/}/api/v1/runner/jobs/$id/git"
1276 GIT_CONFIG_VALUE_0="Authorization: Bearer $tok" as_job env GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader HOME="$work" GIT_TERMINAL_PROMPT=0 \
1277 bash -c 'cd "$1/src" && git init -q . && { [ -z "$5" ] || git fetch -q --no-tags --depth=1 "$2" "$5"; } && git fetch -q --no-tags --depth="$3" "$2" "$4" && git checkout -q --detach FETCH_HEAD' \
1278 _ "$work" "$url" "$depth" "$commit" "$base" >/dev/null 2>&1
1279 }
1280
1281 lend_clean() {
1282 local work="${2:?}"
1283 "$SYSTEMCTL" stop "forge-job-$1.service" >/dev/null 2>&1
1284 [ "$LEND_HOST" = 1 ] && umount "$work" 2>/dev/null
1285 rm -rf "${work:?}" "${work:?}.env"
1286 return 0
1287 }
1288
1289 # The job's end: `done` with its steps, `abandon` (the forge runs the check itself) or `interrupted`
1290 # (back in the queue, not red, not a try).
1291 lend_give() {
1292 local id="$1" kind="$2" what="$3" body
1293 if [ "$kind" = done ]; then
1294 body="$(jq -cn --argjson s "$what" '{done: {steps: $s, contained: true, note: ""}}')"
1295 else
1296 body="$(jq -cn --arg k "$kind" --arg w "$what" '{($k): $w}')"
1297 fi
1298 lend_post "$id" "$body" || true
1299 rm -f "$LEND_JOBAUTH"
9391300 }
9401301
9411302 # Once at each start: a volume attached but not mounted at the data directory is mounted, or the
@@ -949,6 +1310,7 @@ while :; do
9491310 shell_tick
9501311 sync || echo "forge-game-agent: sync failed; again in ${EVERY}s" >&2
9511312 job_tick
1313 lend_tick
9521314 [ "$ONCE" = 1 ] && exit 0
9531315 sleep "$EVERY"
9541316 done
src/games/boot.ts +1 −1
@@ -54,7 +54,7 @@ WantedBy=multi-user.target
5454 * `package_upgrade`: unattended-upgrades does that once the box is up.
5555 */
5656 export const INSTALL =
57 "for try in 1 2 3; do apt-get -o DPkg::Lock::Timeout=600 update && DEBIAN_FRONTEND=noninteractive apt-get -o DPkg::Lock::Timeout=600 install -y docker.io docker-compose-v2 jq curl ca-certificates ufw unattended-upgrades rsync && break; sleep 30; done";
57 "for try in 1 2 3; do apt-get -o DPkg::Lock::Timeout=600 update && DEBIAN_FRONTEND=noninteractive apt-get -o DPkg::Lock::Timeout=600 install -y docker.io docker-compose-v2 jq curl ca-certificates ufw unattended-upgrades rsync bubblewrap git iptables && break; sleep 30; done";
5858
5959 /** The cloud-config for a game box whose volume is mounted at `dataDir`. */
6060 export function gameBootConfig(g: GameBoot, dataDir: string): string {
src/games/lend.ts +38 −1
@@ -13,6 +13,18 @@ import { LEND_DAYS_MAX } from "../checks/lent_scope.ts";
1313 import { lendAuthors } from "./lend_fit.ts";
1414 import type { GameBox } from "./store.ts";
1515
16 /**
17 * The token of a runner just enrolled, until the box's next sync carries it over: in memory only,
18 * never written down, so a forge that restarts first forgets it and the box asks for a new one
19 * (`lendAnswer`). Keyed by database (`test/module-state.test.ts`).
20 */
21 const unsent = new WeakMap<Database, Map<string, string>>();
22 function hold(db: Database, boxId: string, token: string): void {
23 let m = unsent.get(db);
24 if (m === undefined) unsent.set(db, (m = new Map()));
25 m.set(boxId, token);
26 }
27
1628 /** The runner lent for a box, while it works; undefined when the switch is off. */
1729 export function lentRunnerOf(db: Database, boxId: string): string | undefined {
1830 return db.query<{ id: string }, [string]>("SELECT id FROM check_runner WHERE box_id = ?1 AND revoked_at = 0").get(boxId)?.id;
@@ -26,11 +38,36 @@ export function setLend(db: Database, box: GameBox, on: boolean, by: string, now
2638 const have = lentRunnerOf(db, box.id);
2739 if (!on) return have !== undefined && revokeRunner(db, have, now);
2840 if (have !== undefined) return false;
29 const { runner } = enrolRunner(db, `box-${box.name}`, by, { authors: lendAuthors(db, box), days: LEND_DAYS_MAX }, now);
41 const { runner, token } = enrolRunner(db, `box-${box.name}`, by, { authors: lendAuthors(db, box), days: LEND_DAYS_MAX }, now);
3042 db.query("UPDATE check_runner SET box_id = ?2 WHERE id = ?1").run(runner.id, box.id);
43 hold(db, box.id, token);
3144 return true;
3245 }
3346
47 /**
48 * What a sync answers about the switch (#17578). `said` is the box's word: "have" when it holds a
49 * runner token, anything else when it does not. Switched on and the box holds none: the token just
50 * enrolled, once; with nothing to send (a forge restarted since, a reply lost) the old runner is
51 * revoked and a new one enrolled, so the box is never left without. Switched off and the box
52 * still holds one: it is told to drop it. Nothing otherwise.
53 */
54 export function lendAnswer(db: Database, box: GameBox, said: unknown, now: number = Date.now()): { token: string } | { off: true } | undefined {
55 const have = lentRunnerOf(db, box.id);
56 if (have === undefined) return said === "have" ? { off: true } : undefined;
57 const token = unsent.get(db)?.get(box.id);
58 if (token !== undefined) {
59 unsent.get(db)!.delete(box.id);
60 return { token };
61 }
62 if (said === "have") return undefined;
63 const by = db.query<{ created_by: string }, [string]>("SELECT created_by FROM check_runner WHERE id = ?1").get(have)?.created_by ?? "";
64 revokeRunner(db, have, now);
65 setLend(db, box, true, by, now);
66 const fresh = unsent.get(db)!.get(box.id)!;
67 unsent.get(db)!.delete(box.id);
68 return { token: fresh };
69 }
70
3471 /** The switch's line, in the words both doors use. */
3572 export const lendWords = (on: boolean): string => `Run checks while servers sleep: ${on ? "on" : "off"}.`;
3673
src/games/store.ts +2
@@ -466,6 +466,8 @@ export interface SyncBody {
466466 readonly people?: unknown;
467467 readonly results?: readonly { id?: unknown; ok?: unknown; output?: unknown }[];
468468 readonly host?: Record<string, unknown>;
469 /** "have" when the box holds a runner token for the forge's checks (`lend.ts`). */
470 readonly lend?: unknown;
469471 /** The box's word about its boot, sent without jq when a tool is missing or by the boot's report. */
470472 readonly boot?: string;
471473 /** What the box sees of itself, about 8 KB (`diag.ts`): kept, replacing the last. */
src/http/api/runners.ts +7
@@ -25,6 +25,7 @@ import {
2525 holdsClaim,
2626 jobByToken,
2727 nextOffer,
28 interruptJob,
2829 noteHeldReport,
2930 noteRunnerJobs,
3031 noteRunnerMachine,
@@ -32,6 +33,7 @@ import {
3233 runOfJob,
3334 runnerByToken,
3435 settleJob,
36 wakeClaimers,
3537 type RunnerResult,
3638 } from "../../checks/runner_jobs.ts";
3739 import { readSeed } from "../../checks/runner_seeds.ts";
@@ -276,6 +278,11 @@ export function runnerRoutes(router: Router<Handler>): void {
276278 .slice(0, LINES_MAX)
277279 : [];
278280 if (lines.length > 0) mine.ear.lines(str(input.step), lines);
281 if (typeof input.interrupted === "string") {
282 if (!interruptJob(ctx.app.db, mine.job.id, token, input.interrupted)) return notFound();
283 wakeClaimers(ctx.app);
284 return json({ ended: true });
285 }
279286 if (typeof input.abandon === "string") {
280287 if (!settleJob(ctx.app.db, mine.job.id, token, { returned: input.abandon }))
281288 return notFound();
src/http/games_routes.ts +4
@@ -11,6 +11,7 @@ import { recordMetrics } from "../games/metrics.ts";
1111 import { recordPeople } from "../games/people.ts";
1212 import { gameChat, runChat } from "../games/chat.ts";
1313 import { packChecks } from "../games/pack_check.ts";
14 import { lendAnswer } from "../games/lend.ts";
1415 import { sleeping } from "../games/sleep.ts";
1516 import { boxByToken, envFiles, markAsleep, recordSync, signJarUrls, type SyncBody } from "../games/store.ts";
1617 import { BODY_CAPS } from "../kernel/body_caps.ts";
@@ -62,6 +63,9 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> {
6263 if (compose !== undefined && compose.sha !== (typeof body.composeSha === "string" ? body.composeSha : "")) reply["compose"] = signJarUrls(ctx.app, box, compose.text, ctx.url.origin);
6364 // The agent this forge runs: a box whose own differs fetches it (`gameAgentScript`) and restarts.
6465 reply["agentSha"] = AGENT_SHA;
66 // The runner token of "Run checks while servers sleep", once; or the word to drop it.
67 const lend = lendAnswer(ctx.app.db, box, body.lend);
68 if (lend !== undefined) reply["lend"] = lend;
6569 return json(reply);
6670 }
6771
test/game-lend-box.test.ts added +294
@@ -0,0 +1,294 @@
1 /**
2 * #17578, the box's side of "Run checks while servers sleep": `agent.sh` runs a claimed check in
3 * a cell that reaches neither Docker, the worlds nor the box's token, and a join meets it in
4 * order: claiming stops, its cgroup is frozen at once, and it is stopped and handed back as
5 * interrupted when its memory is needed. The agent is run for real against a fake forge, with
6 * stand-ins for what needs root (systemd-run, bwrap, systemctl, docker, git) that record what
7 * they were asked.
8 */
9 import { $ } from "bun";
10 import { afterEach, describe, expect, test } from "bun:test";
11 import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs";
12 import { rm } from "node:fs/promises";
13 import { tmpdir } from "node:os";
14 import { join } from "node:path";
15 import { AGENT_SHA } from "../src/games/boot.ts";
16
17 const AGENT = join(import.meta.dir, "../src/games/agent.sh");
18 const TOKEN = "fgb_abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG";
19 const RUNNER = "forge_runner_abcdefghijklmnopqrstuvwxyz0123456789";
20 const JOB = "forge_job_abcdefghijklmnopqrstuvwxyz0123456789";
21 const lacks = ["bash", "curl", "jq", "timeout"].filter((t) => Bun.which(t) === null);
22 const MEM = (kib: number): string => `MemTotal: 8000000 kB\nMemAvailable: ${String(kib)} kB\n`;
23
24 interface Seen {
25 readonly method: string;
26 readonly path: string;
27 readonly auth: string;
28 readonly body: Record<string, unknown>;
29 }
30
31 const cleanups: (() => Promise<void>)[] = [];
32 afterEach(async () => {
33 for (const c of cleanups.splice(0)) await c();
34 });
35
36 const script = (path: string, text: string): void => {
37 writeFileSync(path, `#!/bin/bash\n${text}\n`);
38 chmodSync(path, 0o755);
39 };
40
41 /** A box with the stand-ins, and a forge that sends one job. */
42 async function box(job: { steps: { name: string; command: string }[]; egress?: string[] }, opts: { wakeAt?: number; eventAfter?: number; host?: boolean; env?: Record<string, string> } = {}) {
43 const root = mkdtempSync(join(tmpdir(), "forge-lend-box-"));
44 const dir = join(root, "game");
45 const bin = join(root, "bin");
46 const cg = join(root, "cg");
47 const log = join(root, "log");
48 for (const d of [dir, bin, cg, log, join(root, "jobs")]) mkdirSync(d);
49 writeFileSync(join(root, "meminfo"), MEM(4_000_000));
50 // systemd-run: the unit's cgroup appears (with its freeze file), then the command runs as it.
51 script(
52 join(bin, "systemd-run"),
53 `unit=""; while [ $# -gt 0 ]; do case "$1" in --unit) unit="$2"; shift 2;; --) shift; break;; -p) shift 2;; *) shift;; esac; done
54 mkdir -p "$CG/$unit.service"; echo 0 >"$CG/$unit.service/cgroup.freeze"; echo $$ >"$CG/$unit.service/pid"
55 exec "$@"`,
56 );
57 // bwrap: what it was asked is one line of the log; then the command runs, uncontained, as a
58 // stand-in.
59 script(join(bin, "bwrap"), `echo "$*" >>"$LOG/bwrap"; while [ "$1" != "--" ]; do shift; done; shift; exec "$@"`);
60 // systemctl stop: the unit's freeze state at that moment is recorded, then its process ends.
61 script(
62 join(bin, "systemctl"),
63 `u="\${2:-}"; f="$CG/\${u}/cgroup.freeze"; echo "$1 $u freeze=$(cat "$f" 2>/dev/null)" >>"$LOG/systemctl"; [ -e "$CG/$u/pid" ] && kill "$(cat "$CG/$u/pid")" 2>/dev/null; exit 0`,
64 );
65 // git records what its environment carried (the token's header) and what its command line did.
66 script(join(bin, "git"), 'echo "$GIT_CONFIG_VALUE_0" >>"$LOG/git-env"; echo "$*" >>"$LOG/git-argv"; exit 0');
67 if (opts.host === true) {
68 // The root-only parts of a real box, as stand-ins that record what they were asked: the job's
69 // user, its tmpfs, setpriv (which runs the command as itself here), the firewall.
70 script(join(bin, "id"), 'case "$*" in *forge-job*) echo 4242 ;; *) exec /usr/bin/id "$@" ;; esac');
71 script(join(bin, "useradd"), 'echo "$*" >>"$LOG/useradd"');
72 script(join(bin, "mount"), 'echo "$*" >>"$LOG/mount"');
73 script(join(bin, "umount"), "exit 0");
74 script(join(bin, "hostname"), 'echo "203.0.113.7 2001:db8::7"');
75 script(join(bin, "iptables"), 'echo "iptables $*" >>"$LOG/fw"; case "$*" in *" -C "*) exit 1 ;; esac');
76 if (opts.env?.["NO_IP6TABLES"] !== "1") script(join(bin, "ip6tables"), 'echo "ip6tables $*" >>"$LOG/fw"; case "$*" in *" -C "*) exit 1 ;; esac');
77 script(join(bin, "setpriv"), 'echo "$*" >>"$LOG/setpriv"; while [ "${1#--}" != "$1" ]; do shift; done; exec "$@"');
78 }
79 // docker: a start event after a while, which is a server waking, and less memory with it.
80 script(
81 join(bin, "docker"),
82 `if [ "\${1:-}" = events ]; then
83 [ -n "\${EVENT_AFTER:-}" ] || exit 0
84 sleep "$EVENT_AFTER"; printf 'MemTotal: 8000000 kB\\nMemAvailable: 200000 kB\\n' >"$MEMINFO"; echo abc123; sleep 1
85 fi
86 exit 0`,
87 );
88 if (opts.wakeAt !== undefined) writeFileSync(join(dir, ".wake"), String(opts.wakeAt));
89 const seen: Seen[] = [];
90 let sent = false;
91 const forge = Bun.serve({
92 port: 0,
93 hostname: "127.0.0.1",
94 async fetch(req) {
95 const path = new URL(req.url).pathname;
96 const auth = req.headers.get("authorization") ?? "";
97 const text = req.method === "POST" ? await req.text() : "";
98 const body = text === "" ? {} : (JSON.parse(text) as Record<string, unknown>);
99 seen.push({ method: req.method, path, auth, body });
100 if (path === "/api/v1/games/agent/sync")
101 return Response.json({ composeSha: "", commands: [], agentSha: AGENT_SHA, ...(body["lend"] === "none" ? { lend: { token: RUNNER } } : {}) });
102 if (path === "/api/v1/runner/claim") {
103 if (auth !== `Bearer ${RUNNER}` || sent) return new Response(null, { status: 204 });
104 sent = true;
105 return Response.json({
106 token: JOB,
107 lease: 30000,
108 job: {
109 id: "job1",
110 run: "r1",
111 repo: "alice/mc-network",
112 commit: "a".repeat(40),
113 depth: 1,
114 steps: job.steps,
115 env: { CI: "1", FORGE_RUN: "r1", FORGE_RUNNER_TOKEN: "no", SECRET: "no" },
116 limits: { memoryMiB: 512, cpus: 1 },
117 timeoutS: 20,
118 egress: job.egress ?? [],
119 egressMode: "enforce",
120 cell: "required",
121 cache: { repo: "r", tree: "", base: "" },
122 },
123 });
124 }
125 if (path === "/api/v1/runner/jobs/job1") return auth === `Bearer ${JOB}` ? Response.json({ lease: 30000 }) : new Response(null, { status: 404 });
126 return new Response(null, { status: 404 });
127 },
128 });
129 cleanups.push(async () => {
130 forge.stop(true);
131 await rm(root, { recursive: true, force: true });
132 });
133 const run = async () => {
134 const ran = await $`bash ${AGENT}`
135 .env({
136 PATH: `${bin}:${process.env["PATH"] ?? ""}`,
137 HOME: root,
138 FORGE_URL: `http://127.0.0.1:${String(forge.port)}`,
139 FORGE_GAME_TOKEN: TOKEN,
140 FORGE_GAME_DIR: dir,
141 FORGE_GAME_DOCKER: join(bin, "docker"),
142 FORGE_GAME_ONCE: "1",
143 FORGE_GAME_DIAG_S: "0",
144 FORGE_GAME_VOLUME_CHECK: "0",
145 FORGE_GAME_LEND_HOST: opts.host === true ? "1" : "0",
146 FORGE_GAME_LEND_ROOT: join(root, "jobs"),
147 FORGE_GAME_CGROUP: cg,
148 FORGE_GAME_LEND_RUN: join(bin, "systemd-run"),
149 FORGE_GAME_LEND_CELL: join(bin, "bwrap"),
150 FORGE_GAME_SYSTEMCTL: join(bin, "systemctl"),
151 FORGE_GAME_MEMINFO: join(root, "meminfo"),
152 FORGE_GAME_LEND_QUIET: "3",
153 FORGE_GAME_LEND_LOOK: "0.2",
154 FORGE_GAME_LEND_TOOLS: join(root, "no-tools"),
155 ...(opts.env ?? {}),
156 CG: cg,
157 LOG: log,
158 MEMINFO: join(root, "meminfo"),
159 ...(opts.eventAfter === undefined ? {} : { EVENT_AFTER: String(opts.eventAfter) }),
160 })
161 .quiet()
162 .nothrow();
163 return { code: ran.exitCode, said: ran.stderr.toString() };
164 };
165 const read = (name: string): string => (existsSync(join(log, name)) ? readFileSync(join(log, name), "utf8") : "");
166 return { run, seen, dir, cg, read };
167 }
168
169 describe("a game box runs a claimed check in a cell", () => {
170 test.skipIf(lacks.length > 0)("the runner token comes with a sync, is kept private, and claims; the check runs in a cell and the job is answered", async () => {
171 const b = await box({ steps: [{ name: "install", command: "true" }, { name: "check", command: "echo hello" }] });
172 const { code, said } = await b.run();
173 expect(code).toBe(0);
174 expect(said).not.toContain("failed");
175 // The token lives in the agent's own directory, mode 600, and nowhere else.
176 expect(statSync(join(b.dir, ".runner.auth")).mode & 0o777).toBe(0o600);
177 expect(readFileSync(join(b.dir, ".runner.auth"), "utf8")).toBe(`Authorization: Bearer ${RUNNER}\n`);
178 expect(b.seen.find((s) => s.path === "/api/v1/games/agent/sync")?.body["lend"]).toBe("none");
179 expect(b.seen.find((s) => s.path === "/api/v1/runner/claim")?.auth).toBe(`Bearer ${RUNNER}`);
180 const [install, check] = b.read("bwrap").trim().split("\n");
181 // Nothing of the box in either cell: not the Docker socket (/run), the agent's directory or its
182 // token's.
183 for (const cell of [install!, check!]) {
184 expect(cell).toContain("--unshare-all");
185 expect(cell).toContain("--clearenv");
186 expect(cell).not.toContain("/run");
187 expect(cell).not.toContain(b.dir);
188 expect(cell).not.toContain("/opt/forge-game");
189 expect(cell).not.toContain(TOKEN);
190 expect(cell).not.toContain("FORGE_RUNNER_TOKEN");
191 expect(cell).not.toContain("SECRET");
192 expect(cell).toContain("--setenv CI 1");
193 }
194 // The install step alone has a network; the check has none.
195 expect(install).toContain("--share-net");
196 expect(check).not.toContain("--share-net");
197 const end = b.seen.filter((s) => s.path === "/api/v1/runner/jobs/job1").at(-1)!;
198 expect(end.auth).toBe(`Bearer ${JOB}`);
199 expect(end.body).toMatchObject({ done: { contained: true, steps: [{ name: "install", ok: true }, { name: "check", ok: true }] } });
200 });
201
202 test.skipIf(lacks.length > 0)("a failing check is red only by its own exit code", async () => {
203 const b = await box({ steps: [{ name: "check", command: "exit 3" }] });
204 await b.run();
205 const end = b.seen.filter((s) => s.path === "/api/v1/runner/jobs/job1").at(-1)!;
206 expect(end.body).toMatchObject({ done: { steps: [{ name: "check", ok: false, error: "check exited with code 3" }] } });
207 });
208
209 test.skipIf(lacks.length > 0)("what the box lacks is handed back, never red", async () => {
210 const b = await box({ steps: [{ name: "check", command: "no_such_tool_17578" }] });
211 await b.run();
212 const end = b.seen.filter((s) => s.path === "/api/v1/runner/jobs/job1").at(-1)!;
213 expect(Object.keys(end.body)).toEqual(["abandon"]);
214 });
215
216 test.skipIf(lacks.length > 0)("a check that names hosts is handed back: its cell has no network", async () => {
217 const b = await box({ steps: [{ name: "check", command: "true" }], egress: ["registry.npmjs.org"] });
218 await b.run();
219 expect(b.read("bwrap")).toBe("");
220 expect(Object.keys(b.seen.filter((s) => s.path === "/api/v1/runner/jobs/job1").at(-1)!.body)).toEqual(["abandon"]);
221 });
222
223 test.skipIf(lacks.length > 0)("a server that woke a moment ago stops the claim", async () => {
224 const b = await box({ steps: [{ name: "check", command: "true" }] }, { wakeAt: Math.floor(Date.now() / 1000) });
225 await b.run();
226 expect(b.seen.some((s) => s.path === "/api/v1/runner/claim")).toBe(false);
227 });
228 });
229
230 describe("a job is held to its disk, its user and its network", () => {
231 test.skipIf(lacks.length > 0)("a step that floods its output is cut at the cap and only a tail is sent", async () => {
232 const b = await box(
233 { steps: [{ name: "check", command: "yes flood | head -c 3000000; echo after" }] },
234 { env: { FORGE_GAME_LEND_OUT_KIB: "64" } },
235 );
236 await b.run();
237 const ends = b.seen.filter((s) => s.path === "/api/v1/runner/jobs/job1");
238 const lines = ends.find((s) => Array.isArray(s.body["lines"]))?.body["lines"] as string[] | undefined;
239 expect((lines?.length ?? 0) <= 200).toBe(true);
240 expect(JSON.stringify(ends.at(-1)!.body)).toContain("killed (signal 25)");
241 });
242
243 test.skipIf(lacks.length > 0)("on a real box the checkout is made as the job's user and the token is not on a command line", async () => {
244 const b = await box({ steps: [{ name: "check", command: "true" }] }, { host: true });
245 await b.run();
246 const setpriv = b.read("setpriv");
247 // The job's disk is a tmpfs of the job's own, and what is made in it is made as the job.
248 expect(b.read("mount")).toContain("uid=4242,gid=4242");
249 expect(setpriv).toMatch(/--reuid=forge-job .*mkdir .*\/src/);
250 expect(setpriv).toMatch(/--reuid=forge-job .*bash -c/);
251 // The token reached git by its environment, and appears in no argument of anything.
252 expect(b.read("git-env")).toContain(`Authorization: Bearer ${JOB}`);
253 for (const argv of [setpriv, b.read("git-argv"), b.read("bwrap")]) expect(argv).not.toContain(JOB);
254 });
255
256 test.skipIf(lacks.length > 0)("the job's network rule rejects the box's own addresses, v4 and v6", async () => {
257 const b = await box({ steps: [{ name: "install", command: "true" }, { name: "check", command: "true" }] }, { host: true });
258 await b.run();
259 const fw = b.read("fw");
260 expect(fw).toMatch(/iptables .*-d [^ ]*203\.0\.113\.7\/32[^ ]* -j REJECT/);
261 expect(fw).toMatch(/ip6tables .*-d [^ ]*2001:db8::7\/128[^ ]* -j REJECT/);
262 });
263
264 test.skipIf(lacks.length > 0)("an install step is handed back when ip6tables is missing and the host has IPv6", async () => {
265 const b = await box(
266 { steps: [{ name: "install", command: "true" }] },
267 { host: true, env: { NO_IP6TABLES: "1" } },
268 );
269 await b.run();
270 // Only decided when the machine has an IPv6 address besides loopback.
271 const v6 = existsSync("/proc/net/if_inet6") && readFileSync("/proc/net/if_inet6", "utf8").split("\n").some((l) => l !== "" && !l.startsWith("00000000000000000000000000000001 "));
272 const last = b.seen.filter((s) => s.path === "/api/v1/runner/jobs/job1").at(-1)!;
273 if (v6) expect(Object.keys(last.body)).toEqual(["abandon"]);
274 });
275 });
276
277 describe("a join meets the job in order", () => {
278 test.skipIf(lacks.length > 0)(
279 "freeze at once, then stop when memory is needed; the job goes back as interrupted, never done or abandoned",
280 async () => {
281 const b = await box({ steps: [{ name: "check", command: "sleep 30" }] }, { eventAfter: 1.5 });
282 const started = Date.now();
283 await b.run();
284 expect(Date.now() - started).toBeLessThan(15_000);
285 const ends = b.seen.filter((s) => s.path === "/api/v1/runner/jobs/job1" && Object.keys(s.body).some((k) => k !== "step" && k !== "lines"));
286 expect(ends.map((e) => Object.keys(e.body))).toEqual([["interrupted"]]);
287 // Frozen when it was stopped: the freeze came first.
288 expect(readFileSync(join(b.cg, "forge-job-job1.service", "cgroup.freeze"), "utf8").trim()).toBe("1");
289 expect(b.read("systemctl")).toContain("stop forge-job-job1.service freeze=1");
290 // The join also stopped any new claim for a while.
291 expect(existsSync(join(b.dir, ".wake"))).toBe(true);
292 },
293 );
294 });
test/game-lend.test.ts +21 −1
@@ -14,7 +14,7 @@ import { claimJob, getRunner, offerJob, type RunnerJob } from "../src/checks/run
1414 import type { Repo } from "../src/core/repos.ts";
1515 import { createToken } from "../src/core/tokens.ts";
1616 import { createUser, getUserByName, type User } from "../src/core/users.ts";
17 import { lentRunnerOf, setLend } from "../src/games/lend.ts";
17 import { lendAnswer, lentRunnerOf, setLend } from "../src/games/lend.ts";
1818 import { lendAuthors } from "../src/games/lend_fit.ts";
1919 import { recordMetrics } from "../src/games/metrics.ts";
2020 import { boxNamed, createGameBox, grant, type GameBox } from "../src/games/store.ts";
@@ -145,6 +145,26 @@ describe("a game box lends its spare to checks", () => {
145145 expect(claimJob(app.db, { id, cells: true }, NOW)).toBeUndefined();
146146 });
147147
148 test("the box is sent its runner's token once, a new one when it has none, and told to drop it when off", () => {
149 expect(lendAnswer(app.db, box, "none")).toBeUndefined();
150 setLend(app.db, box, true, alice.id);
151 const first = lendAnswer(app.db, box, "none") as { token: string };
152 expect(first.token).toStartWith("forge_runner_");
153 // Holding it, the box is told nothing more.
154 expect(lendAnswer(app.db, box, "have")).toBeUndefined();
155 // Saying it has none (the reply was lost, the forge restarted): the old runner goes, a new one
156 // comes.
157 const old = lentRunnerOf(app.db, box.id)!;
158 const second = lendAnswer(app.db, box, "none") as { token: string };
159 expect(second.token).not.toBe(first.token);
160 expect(getRunner(app.db, old)!.revokedAt).toBeGreaterThan(0);
161 expect(lentRunnerOf(app.db, box.id)).not.toBe(old);
162 expect(lendAnswer(app.db, box, "have")).toBeUndefined();
163 setLend(app.db, box, false, alice.id);
164 expect(lendAnswer(app.db, box, "have")).toEqual({ off: true });
165 expect(lendAnswer(app.db, box, "none")).toBeUndefined();
166 });
167
148168 test("a box with no writers names nobody, never anyone", () => {
149169 expect(lendAuthors(app.db, { repo: "nobody/nothing" })).toEqual(["-"]);
150170 });
test/runner-interrupted.test.ts added +92
@@ -0,0 +1,92 @@
1 /**
2 * #17578: a job a runner gives up because its machine needs itself (a game box's server woke) goes
3 * back to the queue as interrupted: never a result, never red, and never one of the check's tries
4 * (`MAX_CLAIMS`). Its token dies with it, and another runner takes it.
5 */
6 import { expect, test } from "bun:test";
7 import { deskOf, dropJob, enrolRunner, lapseJobs, offerJob, viewJob, wakeClaimers, type RunnerJob } from "../src/checks/runner_jobs.ts";
8 import { MAX_CLAIMS } from "../src/checks/runner_step.ts";
9 import { checksForge } from "./helpers/checks-forge.ts";
10 import { quietLogs } from "./helpers/globals.ts";
11
12 quietLogs();
13 const f = checksForge("forge-interrupt-");
14
15 const job: Omit<RunnerJob, "id"> = {
16 run: "run-interrupted",
17 repo: "alice/lib",
18 commit: "a".repeat(40),
19 depth: 1,
20 steps: [{ name: "check", command: "true" }],
21 env: { CI: "1" },
22 limits: {},
23 timeoutS: 60,
24 egress: [],
25 egressMode: "enforce",
26 cell: "preferred",
27 cache: { repo: "r", tree: "", base: "" },
28 };
29
30 /** The check waiting on a job, as the route sees it. */
31 const listen = (id: string): void => void deskOf(f.app).ears.set(id, { wake: () => {}, lines: () => {} });
32 const call = (token: string, path: string, body: unknown): Promise<Response> =>
33 fetch(`${f.servers.url}/api/v1/runner/${path}`, {
34 method: "POST",
35 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
36 body: JSON.stringify(body),
37 });
38 const claim = async (token: string): Promise<{ job: { id: string }; token: string } | undefined> => {
39 const r = await call(token, "claim", { wait: 0 });
40 return r.status === 200 ? ((await r.json()) as { job: { id: string }; token: string }) : undefined;
41 };
42
43 test("an interrupted job is queued again, not red, not a try, and its old token is dead", async () => {
44 const a = enrolRunner(f.app.db, "box-a", f.alice.id).token;
45 const b = enrolRunner(f.app.db, "box-b", f.alice.id).token;
46 const offered = offerJob(f.app.db, { runId: job.run, repoId: "r", dir: "/nowhere", job });
47 listen(offered.id);
48 wakeClaimers(f.app);
49 // The first join is not a try; one that interrupts again keeps its claims, so a runner that
50 // interrupts forever brings the check to MAX_CLAIMS and the forge runs it itself.
51 for (let i = 0; i < MAX_CLAIMS + 1; i++) {
52 const held = await claim(i % 2 === 0 ? a : b);
53 expect(held?.job.id).toBe(offered.id);
54 expect(viewJob(f.app.db, offered.id)?.claims).toBe(i === 0 ? 1 : i);
55 const ended = await call(held!.token, `jobs/${offered.id}`, { interrupted: "a server woke" });
56 expect(ended.status).toBe(200);
57 const view = viewJob(f.app.db, offered.id)!;
58 expect(view.state).toBe("queued");
59 expect(view.claims).toBe(i === 0 ? 0 : i);
60 expect(view.result).toBe("interrupted: a server woke");
61 // The claim it let go of is no longer its to answer.
62 expect((await call(held!.token, `jobs/${offered.id}`, { done: { steps: [{ name: "check", ok: true, ms: 1 }], contained: true, note: "" } })).status).toBe(404);
63 }
64 expect(viewJob(f.app.db, offered.id)?.state).toBe("queued");
65 expect(viewJob(f.app.db, offered.id)?.claims).toBe(MAX_CLAIMS);
66 });
67
68 test("a lapsed lease clears an interruption's words", async () => {
69 const d = enrolRunner(f.app.db, "box-d", f.alice.id).token;
70 f.app.db.query("SELECT id FROM check_job").all().forEach((r) => dropJob(f.app.db, (r as { id: string }).id));
71 const offered = offerJob(f.app.db, { runId: "run-lapse", repoId: "r", dir: "/nowhere", job: { ...job, run: "run-lapse" } });
72 listen(offered.id);
73 wakeClaimers(f.app);
74 const held = await claim(d);
75 await call(held!.token, `jobs/${offered.id}`, { interrupted: "a server woke" });
76 expect((await claim(d))?.job.id).toBe(offered.id);
77 f.app.db.query("UPDATE check_job SET lease_until = 1 WHERE id = ?1").run(offered.id);
78 expect(lapseJobs(f.app.db, Date.now())).toEqual([offered.id]);
79 expect(viewJob(f.app.db, offered.id)?.result).toBeNull();
80 });
81
82 test("a token that does not hold the claim interrupts nothing", async () => {
83 const c = enrolRunner(f.app.db, "box-c", f.alice.id).token;
84 f.app.db.query("SELECT id FROM check_job").all().forEach((r) => dropJob(f.app.db, (r as { id: string }).id));
85 const offered = offerJob(f.app.db, { runId: "run-other", repoId: "r", dir: "/nowhere", job: { ...job, run: "run-other" } });
86 listen(offered.id);
87 wakeClaimers(f.app);
88 const held = await claim(c);
89 expect(held?.job.id).toBe(offered.id);
90 expect((await call("forge_job_wrong", `jobs/${offered.id}`, { interrupted: "x" })).status).not.toBe(200);
91 expect(viewJob(f.app.db, offered.id)?.state).toBe("claimed");
92 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs