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
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
14 files
changed +857
−9
- docs/features/game-box.md
- docs/features/runners.md
- src/checks/runner_jobs.ts
- src/checks/runner_step.ts
- src/contract/openapi/routes/postApiV1RunnerJobsId.ts
- src/games/agent.sh
- src/games/boot.ts
- src/games/lend.ts
- src/games/store.ts
- src/http/api/runners.ts
- src/http/games_routes.ts
- test/game-lend-box.test.ts
- test/game-lend.test.ts
- test/runner-interrupted.test.ts
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) | ||
| 31 | 31 | - **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`. |
| 32 | 32 | |
| 33 | 33 | - **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)); 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)); 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 | ||
| 197 | 197 | 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. |
| 198 | 198 | |
| 199 | 199 | **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)). 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( | ||
| 664 | 664 | })(); |
| 665 | 665 | } |
| 666 | 666 | |
| 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 | ||
| 667 | 687 | /** |
| 668 | 688 | * Every claim whose lease ran out goes back to queued, its token dead. Returns their ids. The |
| 669 | 689 | * 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( | ||
| 671 | 691 | export function lapseJobs(db: Database, now: number): string[] { |
| 672 | 692 | return db |
| 673 | 693 | .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 | |
| 675 | 695 | WHERE state = 'claimed' AND lease_until <= ?1 RETURNING id`, |
| 676 | 696 | ) |
| 677 | 697 | .all(now) |
src/checks/runner_step.ts +3 −1
| @@ -229,7 +229,9 @@ export async function runRunnerStep( | ||
| 229 | 229 | return { taken: false, why: "the job left the desk" }; |
| 230 | 230 | if (view.state === "queued" && holder !== "") { |
| 231 | 231 | 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`, | |
| 233 | 235 | ); |
| 234 | 236 | // What a half-run printed is not the check's output. |
| 235 | 237 | input.output.length = 0; |
src/contract/openapi/routes/postApiV1RunnerJobsId.ts +2 −2
| @@ -6,10 +6,10 @@ export const route: Route = { | ||
| 6 | 6 | summary: |
| 7 | 7 | "A runner reports on the job it holds. Takes that job's token", |
| 8 | 8 | 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 }", | |
| 10 | 10 | auth: false, |
| 11 | 11 | role: "anonymous", |
| 12 | body: { step: "string", lines: "array", done: "object", abandon: "string" }, | |
| 12 | body: { step: "string", lines: "array", done: "object", abandon: "string", interrupted: "string" }, | |
| 13 | 13 | 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)" }, |
| 14 | 14 | refuses: [404], |
| 15 | 15 | errorStatus: { 503: "`adopting`: the forge is restarting; keep the job and report again" }, |
src/games/agent.sh +363 −1
| @@ -916,6 +916,7 @@ sync() { | ||
| 916 | 916 | --slurpfile metrics "/.sync.metrics" \ |
| 917 | 917 | --slurpfile snapshots "/.sync.snapshots" \ |
| 918 | 918 | --slurpfile chat "/.sync.chat" \ |
| 919 | --arg lend "$(lend_has)" \ | |
| 919 | 920 | '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 |
| 920 | 921 | | ["30","31","32","33","34","35","36","37","90","91","92","93","94","95","96","97"] as |
| 921 | 922 | # 38;5;n is one of the sixteen colours by its number; a background (48) and the other |
| @@ -926,7 +927,7 @@ sync() { | ||
| 926 | 927 | else [.[0]] + (.[1:] | codes) end; |
| 927 | 928 | (if . == "" then ["0"] else split(";") end) | [codes[] | [.] // empty | "\u00a7" + .] | join(""); |
| 928 | 929 | 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: , services: [0], logs: [0], results: [0], host: [0], diag: [0], people: [0], metrics: [0], snapshots: [0], chat: [0].lines, chatId: [0].id} | |
| 930 | {agent: 1, composeSha: , services: [0], logs: [0], results: [0], host: [0], diag: [0], people: [0], metrics: [0], snapshots: [0], chat: [0].lines, chatId: [0].id, lend: } | |
| 930 | 931 | | walk(if type == "string" then plain else . end)' >"$DIR/.sync.body" || return 1 |
| 931 | 932 | answer="$(curl -fsS -m 20 -H "@" -H 'content-type: application/json' --data-binary "@/.sync.body" "/api/v1/games/agent/sync")" || return 1 |
| 932 | 933 | # Delivered: the results and the log lines are the forge's now. |
| @@ -936,6 +937,366 @@ sync() { | ||
| 936 | 937 | # A newer agent first: nothing of this answer is applied by a script the forge has replaced. |
| 937 | 938 | self_update "$(jq -r '.agentSha // ""' <<<"")" |
| 938 | 939 | apply "" |
| 940 | lend_apply "" | |
| 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="/.runner.auth" | |
| 959 | LEND_ROOT="" | |
| 960 | LEND_USER="" | |
| 961 | LEND_CGROUP="" | |
| 962 | LEND_QUIET="" | |
| 963 | LEND_FLOOR="" | |
| 964 | LEND_FROZEN_MAX="" | |
| 965 | LEND_LOOK="" | |
| 966 | LEND_MEMINFO="" | |
| 967 | LEND_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="" | |
| 970 | LEND_OUT_KIB="" | |
| 971 | LEND_RUN=("") | |
| 972 | LEND_CELL="" | |
| 973 | SYSTEMCTL="" | |
| 974 | LEND_JOBAUTH="/.lend.job.auth" | |
| 975 | EVICTED=0 | |
| 976 | ||
| 977 | lend_has() { [ -s "" ] && echo have || echo none; } | |
| 978 | lend_avail() { awk '/^MemAvailable:/ {print int($2/1024)}' "" 2>/dev/null || echo 0; } | |
| 979 | lend_quiet() { | |
| 980 | local t | |
| 981 | t="$(cat "/.wake" 2>/dev/null)" | |
| 982 | [[ "" =~ ^[0-9]+$ ]] || t=0 | |
| 983 | [ -ge "" ] | |
| 984 | } | |
| 985 | lend_unit() { echo "/forge-job-$1.service"; } | |
| 986 | lend_freeze() { [ -e "$(lend_unit "")/cgroup.freeze" ] && echo 1 >"$(lend_unit "")/cgroup.freeze"; return 0; } | |
| 987 | lend_thaw() { [ -e "$(lend_unit "")/cgroup.freeze" ] && echo 0 >"$(lend_unit "")/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 ""/forge-job-*.service/cgroup.freeze; do | |
| 992 | [ -e "" ] && echo 1 >"" | |
| 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 "")/cgroup.kill" ] && echo 1 >"$(lend_unit "")/cgroup.kill" | |
| 999 | "" 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 <<<""; then | |
| 1007 | lend_stop_all | |
| 1008 | rm -f "" | |
| 1009 | return | |
| 1010 | fi | |
| 1011 | token="$(jq -r '.lend.token // ""' <<<"" 2>/dev/null)" | |
| 1012 | [[ "" =~ ^forge_runner_[A-Za-z0-9_-]{16,128}$ ]] || return | |
| 1013 | printf 'Authorization: Bearer %s\n' "" >".next" && mv ".next" "" | |
| 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 "/.lend.pid" 2>/dev/null)" | |
| 1020 | [ -n "" ] && kill "" 2>/dev/null | |
| 1021 | "" stop 'forge-job-*.service' >/dev/null 2>&1 | |
| 1022 | rm -f "/.lend.pid" "" | |
| 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 "/.lend.watch" 2>/dev/null)" | |
| 1031 | [ -n "" ] && kill -0 "" 2>/dev/null && return | |
| 1032 | ( | |
| 1033 | "" events --filter type=container --filter event=start --format '{{.ID}}' 2>/dev/null | while read -r _; do | |
| 1034 | date +%s >"/.wake" | |
| 1035 | lend_freeze_all | |
| 1036 | done | |
| 1037 | ) >/dev/null 2>&1 </dev/null & | |
| 1038 | echo $! >"/.lend.watch" | |
| 1039 | } | |
| 1040 | ||
| 1041 | lend_running() { | |
| 1042 | local p | |
| 1043 | p="$(cat "/.lend.pid" 2>/dev/null)" | |
| 1044 | [ -n "" ] && kill -0 "" 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 "" ] || return 0 | |
| 1050 | # A box made before the cell was (no bubblewrap or git) runs nothing: a job never runs uncontained. | |
| 1051 | command -v "" >/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 "" ] || return 0 | |
| 1057 | [ "$(date +%s)" -ge "$(cat "/.lend.cool" 2>/dev/null || echo 0)" ] || return 0 | |
| 1058 | lend_work & | |
| 1059 | echo $! >"/.lend.pid" | |
| 1060 | # A test waits for its one job; the service never does. | |
| 1061 | if [ "" = 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 "@" -H 'content-type: application/json' --data "$2" "/api/v1/runner/jobs/$1" | |
| 1068 | } | |
| 1069 | ||
| 1070 | lend_work() { | |
| 1071 | local res="/.lend.claim" code cpus mem | |
| 1072 | cpus="$(nproc 2>/dev/null || echo 1)" | |
| 1073 | mem="$(awk '/^MemTotal:/ {print int($2/1024)}' "" 2>/dev/null || echo 0)" | |
| 1074 | code="$(curl -sS -m 20 -o "" -w '%{http_code}' -H "@" -H 'content-type: application/json' \ | |
| 1075 | --data "$(jq -cn --argjson c "" --argjson m "" '{wait: 0, cells: true, jobs: 1, machine: {cpus: , memoryMiB: , hostCpus: }}')" \ | |
| 1076 | "/api/v1/runner/claim")" || return 0 | |
| 1077 | case "" in | |
| 1078 | 200) lend_job "" ;; | |
| 1079 | # The forge does not know the token (switched off, or replaced): drop it; the next sync says which. | |
| 1080 | 401) rm -f "" ;; | |
| 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 | [ "" = 1 ] || return 0 | |
| 1094 | id "" >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin "" >/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 ; do | |
| 1098 | case "" in *:*) mine6=",/128" ;; *.*) mine4=",/32" ;; esac | |
| 1099 | done | |
| 1100 | for tool in iptables ip6tables; do | |
| 1101 | if ! command -v "" >/dev/null 2>&1; then | |
| 1102 | # No ip6tables is fine only on a host with no IPv6 to leave by. | |
| 1103 | [ "" = 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" | |
| 1107 | [ "" = ip6tables ] && dsts="::1/128,fc00::/7,fe80::/10" | |
| 1108 | "" -w -C OUTPUT -m owner --uid-owner "" -d "" -j REJECT 2>/dev/null || | |
| 1109 | "" -w -I OUTPUT -m owner --uid-owner "" -d "" -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 [ "" = 1 ]; then | |
| 1116 | setpriv --reuid="" --regid="" --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 "/src" /work --chdir /work --clearenv | |
| 1130 | --setenv PATH /opt/tools/bin:/usr/local/bin:/usr/bin:/bin --setenv HOME /tmp) | |
| 1131 | [ -d "" ] && cell+=(--ro-bind "" /opt/tools) | |
| 1132 | if [ "" = 1 ]; then | |
| 1133 | printf 'nameserver 1.1.1.1\nnameserver 9.9.9.9\n' >"/resolv.conf" | |
| 1134 | cell+=(--share-net --ro-bind "/resolv.conf" /etc/resolv.conf) | |
| 1135 | fi | |
| 1136 | while IFS= read -r kv; do | |
| 1137 | [ -n "" ] && cell+=(--setenv "" "") | |
| 1138 | done <"/env" | |
| 1139 | local -a props=(-p "MemoryMax=M" -p MemorySwapMax=0 -p "CPUQuota=$((cpus * 100))%" -p TasksMax=512) | |
| 1140 | [ "" = 1 ] && props+=(-p "User=") | |
| 1141 | : >"" | |
| 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 "" | |
| 1146 | exec "" --quiet --collect --wait --pipe --unit "forge-job-" "" -- \ | |
| 1147 | timeout -k 5 "" "" "" -- bash -c "" >"" 2>&1 </dev/null | |
| 1148 | ) & | |
| 1149 | pid=$! | |
| 1150 | lend_guard "" "" | |
| 1151 | wait "" | |
| 1152 | rc= | |
| 1153 | return "" | |
| 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 "" 2>/dev/null; do | |
| 1162 | sleep "" | |
| 1163 | t="$(date +%s)" | |
| 1164 | if ! lend_quiet; then | |
| 1165 | lend_freeze "" | |
| 1166 | [ "" = 0 ] && frozen="" | |
| 1167 | if [ "$(lend_avail)" -lt "" ] || [ -ge "" ]; then | |
| 1168 | EVICTED=1 | |
| 1169 | lend_kill "" | |
| 1170 | return 0 | |
| 1171 | fi | |
| 1172 | elif [ "" != 0 ] && [ "$(lend_avail)" -ge "" ]; then | |
| 1173 | lend_thaw "" | |
| 1174 | frozen=0 | |
| 1175 | fi | |
| 1176 | if [ -ge 10 ]; then | |
| 1177 | lend_post "" '{}' || { EVICTED=2; lend_kill ""; return 0; } | |
| 1178 | beat="" | |
| 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 // ""' "")" | |
| 1187 | tok="$(jq -r '.token // ""' "")" | |
| 1188 | [[ "" =~ ]] && [[ "" =~ ^forge_job_[A-Za-z0-9_-]{16,128}$ ]] || return 0 | |
| 1189 | printf 'Authorization: Bearer %s\n' "" >"" | |
| 1190 | commit="$(jq -r '.job.commit // ""' "")" | |
| 1191 | base="$(jq -r '.job.base // ""' "")" | |
| 1192 | depth="$(jq -r '.job.depth // 1' "")" | |
| 1193 | secs="$(jq -r '.job.timeoutS // 600' "")" | |
| 1194 | mem="$(jq -r '.job.limits.memoryMiB // 0' "")" | |
| 1195 | cpus="$(jq -r '.job.limits.cpus // 1' "")" | |
| 1196 | disk="$(jq -r '.job.limits.diskMiB // 1024' "")" | |
| 1197 | [[ "" =~ ^[0-9a-f]{40}$ ]] || { lend_give "" abandon "the job names something that is not a commit id"; return 0; } | |
| 1198 | [ -z "" ] || [[ "" =~ ^[0-9a-f]{40}$ ]] || { lend_give "" abandon "the job names a base that is not a commit id"; return 0; } | |
| 1199 | [[ "" =~ ^[0-9]{1,5}$ ]] && [[ "" =~ ^[0-9]{1,5}$ ]] && [[ "" =~ ^[0-9]{1,6}$ ]] && [[ "" =~ ^[0-9]{1,2}$ ]] && [[ "" =~ ^[0-9]{1,6}$ ]] || { lend_give "" abandon "the job's limits are not numbers"; return 0; } | |
| 1200 | [ "" -ge 1 ] && [ "" -ge 1 ] || { lend_give "" abandon "the job declares no memory or cpus to hold it to"; return 0; } | |
| 1201 | [ "" -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' "")" != 0 ]; then | |
| 1204 | lend_give "" 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")' "" >/dev/null 2>&1 && ! lend_net_ready; then | |
| 1208 | lend_give "" abandon "this box could not close its network to a job's install step" | |
| 1209 | return 0 | |
| 1210 | fi | |
| 1211 | work="/" | |
| 1212 | mkdir -p "" | |
| 1213 | lend_env "" >".env" | |
| 1214 | if [ "" = 1 ]; then | |
| 1215 | mount -t tmpfs -o "size=m,mode=0700,uid=$(id -u "" 2>/dev/null),gid=$(id -g "" 2>/dev/null)" tmpfs "" || { | |
| 1216 | lend_clean "" "" | |
| 1217 | lend_give "" 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 "/src" || { lend_clean "" ""; lend_give "" abandon "this box could not make the job's checkout"; return 0; } | |
| 1224 | out="/out" | |
| 1225 | mv ".env" "/env" 2>/dev/null || : >"/env" | |
| 1226 | EVICTED=0 | |
| 1227 | if ! lend_checkout "" "" "" "" "" ""; then | |
| 1228 | lend_clean "" "" | |
| 1229 | lend_give "" 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 | [ "" = install ] && net=1 | |
| 1235 | t0="$(date +%s%N)" | |
| 1236 | lend_step "" "" "" "" "" "" "" "" | |
| 1237 | rc= | |
| 1238 | ms= | |
| 1239 | if [ "" = 1 ]; then | |
| 1240 | lend_clean "" "" | |
| 1241 | lend_give "" interrupted "a server woke on this box and needs its memory" | |
| 1242 | return 0 | |
| 1243 | fi | |
| 1244 | if [ "" = 2 ]; then | |
| 1245 | lend_clean "" "" | |
| 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 [ "" = 126 ] || [ "" = 127 ]; then | |
| 1250 | echo >"/.lend.cool" | |
| 1251 | lend_clean "" "" | |
| 1252 | lend_give "" abandon "this box has no tool the step needs ( exited with code )" | |
| 1253 | return 0 | |
| 1254 | fi | |
| 1255 | lend_post "" "$(jq -cn --arg s "" --rawfile l <(tail -c 65536 "") '{step: , lines: ( | split("\n") | .[-200:] | map(.[0:400]))}')" || true | |
| 1256 | err="" | |
| 1257 | case "" in | |
| 1258 | 0) ;; | |
| 1259 | 124) err=" took longer than s" ;; | |
| 1260 | *) if [ "" -ge 128 ]; then err=" was killed (signal $((rc - 128)))"; else err=" exited with code "; fi ;; | |
| 1261 | esac | |
| 1262 | steps="$(jq -c --arg n "" --arg e "" --argjson ms "" '. + [{name: , ok: ( == ""), ms: } + (if == "" then {} else {error: } end)]' <<<"")" | |
| 1263 | [ -z "" ] || break | |
| 1264 | done < <(jq -r '.job.steps[]? | select(.name == "install" or .name == "check") | [.name, (.command | gsub("[\\t\\n]"; " "))] | @tsv' "") | |
| 1265 | lend_clean "" "" | |
| 1266 | lend_give "" done "" | |
| 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="/api/v1/runner/jobs//git" | |
| 1276 | GIT_CONFIG_VALUE_0="Authorization: Bearer " as_job env GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader HOME="" 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 | _ "" "" "" "" "" >/dev/null 2>&1 | |
| 1279 | } | |
| 1280 | ||
| 1281 | lend_clean() { | |
| 1282 | local work="" | |
| 1283 | "" stop "forge-job-$1.service" >/dev/null 2>&1 | |
| 1284 | [ "" = 1 ] && umount "" 2>/dev/null | |
| 1285 | rm -rf "" ".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 [ "" = done ]; then | |
| 1294 | body="$(jq -cn --argjson s "" '{done: {steps: , contained: true, note: ""}}')" | |
| 1295 | else | |
| 1296 | body="$(jq -cn --arg k "" --arg w "" '{(): }')" | |
| 1297 | fi | |
| 1298 | lend_post "" "" || true | |
| 1299 | rm -f "" | |
| 939 | 1300 | } |
| 940 | 1301 | |
| 941 | 1302 | # Once at each start: a volume attached but not mounted at the data directory is mounted, or the |
| @@ -949,6 +1310,7 @@ while :; do | ||
| 949 | 1310 | shell_tick |
| 950 | 1311 | sync || echo "forge-game-agent: sync failed; again in s" >&2 |
| 951 | 1312 | job_tick |
| 1313 | lend_tick | |
| 952 | 1314 | [ "" = 1 ] && exit 0 |
| 953 | 1315 | sleep "" |
| 954 | 1316 | done |
src/games/boot.ts +1 −1
| @@ -54,7 +54,7 @@ WantedBy=multi-user.target | ||
| 54 | 54 | * `package_upgrade`: unattended-upgrades does that once the box is up. |
| 55 | 55 | */ |
| 56 | 56 | 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"; | |
| 58 | 58 | |
| 59 | 59 | /** The cloud-config for a game box whose volume is mounted at `dataDir`. */ |
| 60 | 60 | 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"; | ||
| 13 | 13 | import { lendAuthors } from "./lend_fit.ts"; |
| 14 | 14 | import type { GameBox } from "./store.ts"; |
| 15 | 15 | |
| 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 | ||
| 16 | 28 | /** The runner lent for a box, while it works; undefined when the switch is off. */ |
| 17 | 29 | export function lentRunnerOf(db: Database, boxId: string): string | undefined { |
| 18 | 30 | 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 | ||
| 26 | 38 | const have = lentRunnerOf(db, box.id); |
| 27 | 39 | if (!on) return have !== undefined && revokeRunner(db, have, now); |
| 28 | 40 | 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); | |
| 30 | 42 | db.query("UPDATE check_runner SET box_id = ?2 WHERE id = ?1").run(runner.id, box.id); |
| 43 | hold(db, box.id, token); | |
| 31 | 44 | return true; |
| 32 | 45 | } |
| 33 | 46 | |
| 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 | ||
| 34 | 71 | /** The switch's line, in the words both doors use. */ |
| 35 | 72 | export const lendWords = (on: boolean): string => `Run checks while servers sleep: ${on ? "on" : "off"}.`; |
| 36 | 73 |
src/games/store.ts +2
| @@ -466,6 +466,8 @@ export interface SyncBody { | ||
| 466 | 466 | readonly people?: unknown; |
| 467 | 467 | readonly results?: readonly { id?: unknown; ok?: unknown; output?: unknown }[]; |
| 468 | 468 | 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; | |
| 469 | 471 | /** The box's word about its boot, sent without jq when a tool is missing or by the boot's report. */ |
| 470 | 472 | readonly boot?: string; |
| 471 | 473 | /** 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 { | ||
| 25 | 25 | holdsClaim, |
| 26 | 26 | jobByToken, |
| 27 | 27 | nextOffer, |
| 28 | interruptJob, | |
| 28 | 29 | noteHeldReport, |
| 29 | 30 | noteRunnerJobs, |
| 30 | 31 | noteRunnerMachine, |
| @@ -32,6 +33,7 @@ import { | ||
| 32 | 33 | runOfJob, |
| 33 | 34 | runnerByToken, |
| 34 | 35 | settleJob, |
| 36 | wakeClaimers, | |
| 35 | 37 | type RunnerResult, |
| 36 | 38 | } from "../../checks/runner_jobs.ts"; |
| 37 | 39 | import { readSeed } from "../../checks/runner_seeds.ts"; |
| @@ -276,6 +278,11 @@ export function runnerRoutes(router: Router<Handler>): void { | ||
| 276 | 278 | .slice(0, LINES_MAX) |
| 277 | 279 | : []; |
| 278 | 280 | 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 | } | |
| 279 | 286 | if (typeof input.abandon === "string") { |
| 280 | 287 | if (!settleJob(ctx.app.db, mine.job.id, token, { returned: input.abandon })) |
| 281 | 288 | return notFound(); |
src/http/games_routes.ts +4
| @@ -11,6 +11,7 @@ import { recordMetrics } from "../games/metrics.ts"; | ||
| 11 | 11 | import { recordPeople } from "../games/people.ts"; |
| 12 | 12 | import { gameChat, runChat } from "../games/chat.ts"; |
| 13 | 13 | import { packChecks } from "../games/pack_check.ts"; |
| 14 | import { lendAnswer } from "../games/lend.ts"; | |
| 14 | 15 | import { sleeping } from "../games/sleep.ts"; |
| 15 | 16 | import { boxByToken, envFiles, markAsleep, recordSync, signJarUrls, type SyncBody } from "../games/store.ts"; |
| 16 | 17 | import { BODY_CAPS } from "../kernel/body_caps.ts"; |
| @@ -62,6 +63,9 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> { | ||
| 62 | 63 | if (compose !== undefined && compose.sha !== (typeof body.composeSha === "string" ? body.composeSha : "")) reply["compose"] = signJarUrls(ctx.app, box, compose.text, ctx.url.origin); |
| 63 | 64 | // The agent this forge runs: a box whose own differs fetches it (`gameAgentScript`) and restarts. |
| 64 | 65 | 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; | |
| 65 | 69 | return json(reply); |
| 66 | 70 | } |
| 67 | 71 |
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 | ||
| 14 | 14 | import type { Repo } from "../src/core/repos.ts"; |
| 15 | 15 | import { createToken } from "../src/core/tokens.ts"; |
| 16 | 16 | 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"; | |
| 18 | 18 | import { lendAuthors } from "../src/games/lend_fit.ts"; |
| 19 | 19 | import { recordMetrics } from "../src/games/metrics.ts"; |
| 20 | 20 | import { boxNamed, createGameBox, grant, type GameBox } from "../src/games/store.ts"; |
| @@ -145,6 +145,26 @@ describe("a game box lends its spare to checks", () => { | ||
| 145 | 145 | expect(claimJob(app.db, { id, cells: true }, NOW)).toBeUndefined(); |
| 146 | 146 | }); |
| 147 | 147 | |
| 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 | ||
| 148 | 168 | test("a box with no writers names nobody, never anyone", () => { |
| 149 | 169 | expect(lendAuthors(app.db, { repo: "nobody/nothing" })).toEqual(["-"]); |
| 150 | 170 | }); |
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 | }); |
new above
offline
Non-blocking:
ulimit -fbindssystemd-runand 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.