Public: anyone can read this; the crew can change it.
Checks and crew runs as cluster Jobs on any node: the lane moves to the vxrail (80 cores) instead of one pod's 5 GiB #1529
mason/forge:mason/1423-checks-and-crew-runs-as-cluster-jobs-on → main 11 commits fork 5 threads · 5 unresolved
CLAUDE.md +5
| @@ -186,6 +186,11 @@ src/ | ||
| 186 | 186 | actions/); actions/fleet.ts plans, applies, keeps the receipt |
| 187 | 187 | (core/fleet_ops.ts) and undoes |
| 188 | 188 | runs/ log (one file per run, appended live, tailed by listeners) |
| 189 | cluster/ work as a Job on the cluster (docs/CLUSTER.md): jobs (settings, | |
| 190 | the manifest, the kube client over the service account — the | |
| 191 | JobClient seam), tree (the token-gated door a Job fetches its | |
| 192 | checkout through), lane (what the Job runs: fetch, install, | |
| 193 | check, marked lines on stdout) | |
| 189 | 194 | crew/ agents as child processes: brief (the system + task prompts: |
| 190 | 195 | the golden path, written down), claude (the headless adapter: |
| 191 | 196 | argv, stream-json, outcome), sandbox (what the agent's shell |
docs/CLUSTER.md added +124
| @@ -0,0 +1,124 @@ | ||
| 1 | # Checks as cluster Jobs | |
| 2 | ||
| 3 | A check runs as a child of the forge by default: in a cell (`apps/contain.ts`), | |
| 4 | under the forge pod's own memory. With `checks.placement` set to `job` | |
| 5 | (Settings → Capacity, or `FORGE_CHECKS_PLACEMENT=job` as the boot default), the | |
| 6 | next check runs as a **Job on the cluster** instead, on whichever node the | |
| 7 | operator points it at. Checks at once then share nothing but the cluster, so | |
| 8 | `checks.concurrency` can go past 1 without the forge pod's 5 GiB in the | |
| 9 | equation (#1423). | |
| 10 | ||
| 11 | ## How one check runs | |
| 12 | ||
| 13 | 1. The forge prepares the checkout as it always has: `data/checks/<run>`, the | |
| 14 | tree, plus two shallow commits for a fast tier. | |
| 15 | 2. It creates a Job (`src/cluster/jobs.ts`, `jobManifest`) from the forge's own | |
| 16 | image. The command is `bun /app/src/cluster/lane.ts`. The check's | |
| 17 | environment is the same one a process gets, plus a token that opens only | |
| 18 | this checkout until the Job's deadline. | |
| 19 | 3. The lane (`src/cluster/lane.ts`) fetches the checkout as a tar from | |
| 20 | `GET /-/lane/<run>/tree` (`src/cluster/tree.ts`), then runs the install step | |
| 21 | and the check with `runStep`, the way the forge does. | |
| 22 | 4. The forge follows the pod's log into the run's log file as it arrives, and | |
| 23 | records the node on the run (`run.placement`, `run.node`). | |
| 24 | 5. The verdict is how the Job ended: the exit code, past its deadline, or | |
| 25 | **vanished** (deleted, evicted, node lost, the API unreachable for a | |
| 26 | minute). A vanished check is cancelled with `interrupted: its Job vanished; | |
| 27 | queued again` and queued once more. If its Job vanishes a second time, the | |
| 28 | check fails. The Job is deleted whatever happens. | |
| 29 | ||
| 30 | A cluster that refuses the Job (a quota, an admission webhook, a 5xx) is | |
| 31 | treated like a vanished Job: queued again once, then failed saying so. | |
| 32 | ||
| 33 | When a forge cannot start Jobs (no `FORGE_JOB_IMAGE`, not in a cluster, a | |
| 34 | setting that does not parse), the check runs as a process. Its log says why. | |
| 35 | ||
| 36 | **`job` placement is refused while `cells.egress` is `enforce`** (the | |
| 37 | default). A cell holds a check to the hosts `forge.json` declares; a Job | |
| 38 | cannot yet (see Egress below), and a setting must not loosen that boundary. | |
| 39 | Until the Job enforces declared hosts, the check runs as a process and its | |
| 40 | log says `job placement unavailable: cells.egress is enforce …`. | |
| 41 | ||
| 42 | The run page and `GET /api/v1/repos/:owner/:name/runs/:id` say where a run | |
| 43 | ran: `Ran as a Job on vxrail-1.` (`placement`, `node`). | |
| 44 | ||
| 45 | ## Settings (the forge's environment) | |
| 46 | ||
| 47 | | Variable | Meaning | | |
| 48 | | --- | --- | | |
| 49 | | `FORGE_JOB_IMAGE` | The image a Job runs. Set it to the forge's own image and tag. Required. | | |
| 50 | | `FORGE_JOB_NAMESPACE` | Where Jobs are created. Default: the service account's namespace. | | |
| 51 | | `FORGE_JOB_FORGE_URL` | The origin a Job uses to reach the forge, e.g. `http://forge.trevato-apps.svc`. Default: `FORGE_URL`. | | |
| 52 | | `FORGE_JOB_NODE_SELECTOR` | `key=value,…`, e.g. `plat.sh/site=vxrail`. | | |
| 53 | | `FORGE_JOB_TOLERATIONS` | `key=value:Effect,…` or `key:Effect`, e.g. `plat.sh/site=vxrail:NoSchedule`. | | |
| 54 | | `FORGE_JOB_PULL_SECRETS` | `name,…`: the secrets that pull a private image, e.g. `forgejo-registry`. | | |
| 55 | | `NODE_NAME` | Optional, via the downward API (`spec.nodeName`): the node a process-placed run records. | | |
| 56 | ||
| 57 | ## What the cluster grants (deployment side) | |
| 58 | ||
| 59 | None of this is in `charts/app`: the operator applies it. The forge's pod | |
| 60 | runs as a ServiceAccount of its own (`serviceAccountName: forge` in the | |
| 61 | deployment, where `forge` is the release name) with the `FORGE_JOB_*` | |
| 62 | variables above and, optionally, `NODE_NAME` from `spec.nodeName`. That | |
| 63 | ServiceAccount needs a Role in its own namespace. It needs nothing more: | |
| 64 | ||
| 65 | yaml | |
| 66 | apiVersion: v1 | |
| 67 | kind: ServiceAccount | |
| 68 | metadata: { name: forge } | |
| 69 | ||
| 70 | apiVersion: rbac.authorization.k8s.io/v1 | |
| 71 | kind: Role | |
| 72 | metadata: { name: forge-lane } | |
| 73 | rules: | |
| 74 | - apiGroups: ["batch"] | |
| 75 | resources: ["jobs"] | |
| 76 | verbs: ["create", "get", "list", "watch", "delete"] | |
| 77 | - apiGroups: [""] | |
| 78 | resources: ["pods"] | |
| 79 | verbs: ["get", "list"] | |
| 80 | - apiGroups: [""] | |
| 81 | resources: ["pods/log"] | |
| 82 | verbs: ["get"] | |
| 83 | ||
| 84 | apiVersion: rbac.authorization.k8s.io/v1 | |
| 85 | kind: RoleBinding | |
| 86 | metadata: { name: forge-lane } | |
| 87 | roleRef: { apiGroup: rbac.authorization.k8s.io, kind: Role, name: forge-lane } | |
| 88 | subjects: [{ kind: ServiceAccount, name: forge }] | |
| 89 | ||
| 90 | ||
| 91 | A Job's pod carries the label `forge.plat.sh/lane: check`. The pod runs as uid | |
| 92 | 1000 without privilege escalation, drops every capability, has a read-only root | |
| 93 | and no service account token, and writes only to an `emptyDir` sized to the | |
| 94 | check's disk limit. Its requests and limits are the cell's limits | |
| 95 | (`resolveLimits("step", check.limits)`). | |
| 96 | ||
| 97 | Egress is a NetworkPolicy, which speaks addresses, not host names. It lets the | |
| 98 | lane reach DNS, the forge, and the public internet on 80/443, and nothing | |
| 99 | private: | |
| 100 | ||
| 101 | yaml | |
| 102 | apiVersion: networking.k8s.io/v1 | |
| 103 | kind: NetworkPolicy | |
| 104 | metadata: { name: forge-lane } | |
| 105 | spec: | |
| 106 | podSelector: { matchLabels: { forge.plat.sh/lane: check } } | |
| 107 | policyTypes: [Ingress, Egress] | |
| 108 | ingress: [] | |
| 109 | egress: | |
| 110 | - ports: [{ protocol: UDP, port: 53 }, { protocol: TCP, port: 53 }] | |
| 111 | # The forge's own pods: the chart labels them `app: <release>`. | |
| 112 | - to: [{ podSelector: { matchLabels: { app: forge } } }] | |
| 113 | - to: | |
| 114 | - ipBlock: | |
| 115 | cidr: 0.0.0.0/0 | |
| 116 | except: [10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 169.254.0.0/16, 100.64.0.0/10] | |
| 117 | ports: [{ protocol: TCP, port: 80 }, { protocol: TCP, port: 443 }] | |
| 118 | ||
| 119 | ||
| 120 | This is looser than a cell. A cell refuses a host that `forge.json` did not | |
| 121 | declare. A Job refuses private addresses and every port except 80 and 443. | |
| 122 | Holding a Job to declared hosts needs an egress proxy in the pod, and that is | |
| 123 | still to come; until it does, `job` placement only applies while | |
| 124 | `cells.egress` is `report`. |
scripts/gate.ts +1
| @@ -85,6 +85,7 @@ export const GATE: readonly string[] = [ | ||
| 85 | 85 | "test/capacity.test.ts", |
| 86 | 86 | "test/guard-new-accounts.test.ts", |
| 87 | 87 | "test/checks.test.ts", |
| 88 | "test/checks-job.test.ts", | |
| 88 | 89 | "test/dependencies.test.ts", |
| 89 | 90 | "test/map-closing.test.ts", |
| 90 | 91 | "test/autonomy.test.ts", |
src/checks/service.ts +227 −36
| @@ -13,7 +13,7 @@ | ||
| 13 | 13 | |
| 14 | 14 | import { pullDir, runDir } from "../core/pulls.ts"; |
| 15 | 15 | import { existsSync, mkdirSync, rmSync } from "node:fs"; |
| 16 | import { tmpdir } from "node:os"; | |
| 16 | import { hostname, tmpdir } from "node:os"; | |
| 17 | 17 | import { join } from "node:path"; |
| 18 | 18 | import type { App } from "../app.ts"; |
| 19 | 19 | import { announceRun } from "../actions/runs.ts"; |
| @@ -33,6 +33,8 @@ import { | ||
| 33 | 33 | requeueCheck, |
| 34 | 34 | REQUEUED_SUMMARY, |
| 35 | 35 | sweepAbandonedChecks, |
| 36 | VANISHED_SUMMARY, | |
| 37 | vanishedBefore, | |
| 36 | 38 | type Run, |
| 37 | 39 | } from "../core/runs.ts"; |
| 38 | 40 | import { Gate } from "../git/env.ts"; |
| @@ -56,6 +58,7 @@ import { | ||
| 56 | 58 | capacityCount, |
| 57 | 59 | noteBooted, |
| 58 | 60 | capacityEnv, |
| 61 | checksPlacement, | |
| 59 | 62 | egressSetting, |
| 60 | 63 | } from "../core/capacity.ts"; |
| 61 | 64 | import { |
| @@ -66,6 +69,19 @@ import { | ||
| 66 | 69 | } from "../apps/contain.ts"; |
| 67 | 70 | import { summariseCheckFailure } from "./summary.ts"; |
| 68 | 71 | import type { CheckDetail } from "../core/runs.ts"; |
| 72 | import { | |
| 73 | inClusterAccess, | |
| 74 | JOB_WORK, | |
| 75 | jobManifest, | |
| 76 | jobName, | |
| 77 | jobSettings, | |
| 78 | kubeJobs, | |
| 79 | type JobClient, | |
| 80 | type JobSettings, | |
| 81 | } from "../cluster/jobs.ts"; | |
| 82 | import { LANE_MARK } from "../cluster/lane.ts"; | |
| 83 | import { checksRoot, treeToken } from "../cluster/tree.ts"; | |
| 84 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 69 | 85 | |
| 70 | 86 | const log = createLog("checks"); |
| 71 | 87 | |
| @@ -74,10 +90,26 @@ export interface ChecksOptions { | ||
| 74 | 90 | readonly concurrency?: number | undefined; |
| 75 | 91 | /** The forge's public URL, told to the check as `FORGE_URL`. */ |
| 76 | 92 | readonly forgeUrl: string; |
| 93 | /** | |
| 94 | * The cluster a check placed as a Job runs on (#1423). Absent: the | |
| 95 | * forge's own, over its service account, where `FORGE_JOB_*` says. | |
| 96 | */ | |
| 97 | readonly jobs?: { client: JobClient; settings: JobSettings } | undefined; | |
| 77 | 98 | /** How long a check may run before it is killed. @default BUDGETS.gate */ |
| 78 | 99 | readonly budgetMs?: number | undefined; |
| 79 | 100 | } |
| 80 | 101 | |
| 102 | /** How a check ended: passed, failed with the reason, or cut off by its Job vanishing. */ | |
| 103 | type Outcome = | |
| 104 | | { ok: true } | |
| 105 | | { | |
| 106 | ok: false; | |
| 107 | error: string; | |
| 108 | detail?: CheckDetail | undefined; | |
| 109 | /** Its Job vanished or the cluster refused it: never the commit's fault (#1423). */ | |
| 110 | vanished?: true; | |
| 111 | }; | |
| 112 | ||
| 81 | 113 | export interface ChecksHandle { |
| 82 | 114 | /** Ask for a check of one commit; the answer is the run, or nothing when the commit declares no check. */ |
| 83 | 115 | request( |
| @@ -165,9 +197,6 @@ export function requeueAbandonedChecks(app: App, staleMs: number): number { | ||
| 165 | 197 | return swept.requeued.length + swept.failed.length + swept.cancelled.length; |
| 166 | 198 | } |
| 167 | 199 | |
| 168 | /** Where a check's checkout lives while it runs. */ | |
| 169 | const checksRoot = (dataDir: string): string => join(dataDir, "checks"); | |
| 170 | ||
| 171 | 200 | const handles = new WeakMap<App, ChecksHandle>(); |
| 172 | 201 | |
| 173 | 202 | /** The checks service of this forge, if one was started. */ |
| @@ -408,6 +437,16 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle { | ||
| 408 | 437 | announceRun(app, moved.again, run.actorId ?? undefined); |
| 409 | 438 | return; |
| 410 | 439 | } |
| 440 | // A Job that vanished is the cluster's doing, not the commit's: the | |
| 441 | // check is queued again, once (#1423). | |
| 442 | if (!outcome.ok && outcome.vanished && !vanishedBefore(app.db, claimed)) { | |
| 443 | const moved = requeueCheck(app.db, run.id, undefined, VANISHED_SUMMARY); | |
| 444 | if (moved) { | |
| 445 | write(`${outcome.error}; queued again`); | |
| 446 | announceRun(app, moved.again, run.actorId ?? undefined); | |
| 447 | return; | |
| 448 | } | |
| 449 | } | |
| 411 | 450 | const seconds = Math.round((Date.now() - started) / 1000); |
| 412 | 451 | const done = finishRun(app.db, run.id, { |
| 413 | 452 | state: outcome.ok ? "ok" : "failed", |
| @@ -430,10 +469,7 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle { | ||
| 430 | 469 | repo: Repo, |
| 431 | 470 | write: (line: string) => void, |
| 432 | 471 | signal: AbortSignal, |
| 433 | ): Promise< | |
| 434 | | { ok: true } | |
| 435 | | { ok: false; error: string; detail?: CheckDetail | undefined } | |
| 436 | > { | |
| 472 | ): Promise<Outcome> { | |
| 437 | 473 | const bare = await runDir(app.db, app.reposRoot, repo, run.issueId); |
| 438 | 474 | // A pull's check is the fast tier, judged against where the pull left |
| 439 | 475 | // the base; anything else is the whole check (`apps/manifest.ts`). |
| @@ -469,12 +505,7 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle { | ||
| 469 | 505 | readonly signal: AbortSignal; |
| 470 | 506 | } |
| 471 | 507 | |
| 472 | async function runTier( | |
| 473 | x: Execution, | |
| 474 | ): Promise< | |
| 475 | | { ok: true } | |
| 476 | | { ok: false; error: string; detail?: CheckDetail | undefined } | |
| 477 | > { | |
| 508 | async function runTier(x: Execution): Promise<Outcome> { | |
| 478 | 509 | const { bare, repo, write, signal } = x; |
| 479 | 510 | // A pull's fast check is of the pull as it would land: its head merged |
| 480 | 511 | // into the base's tip. The gate comes from that tree, so a pull forked |
| @@ -565,6 +596,54 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle { | ||
| 565 | 596 | return { ok: false, error: given.error }; |
| 566 | 597 | } |
| 567 | 598 | } |
| 599 | const env = childEnv({ | |
| 600 | // The shard count an admin set (`core/capacity.ts`), never the pod's. | |
| 601 | ...capacityEnv(app.db), | |
| 602 | CI: "1", | |
| 603 | FORGE_URL: options.forgeUrl, | |
| 604 | FORGE_CHECK: run.id, | |
| 605 | FORGE_COMMIT: x.commitOid, | |
| 606 | ...(base === undefined | |
| 607 | ? {} | |
| 608 | : { | |
| 609 | FORGE_CHECK_BASE: base, | |
| 610 | FORGE_CHECK_LEARNED: readLearned( | |
| 611 | app.config.dataDir, | |
| 612 | x.pull!.id, | |
| 613 | ).join(","), | |
| 614 | }), | |
| 615 | // A cell inside a cell is not a cell. This check's own cell is the | |
| 616 | // boundary; a forge the tests boot inside it would wrap its apps in | |
| 617 | // nested cells, and those never answer in time. Its children run as | |
| 618 | // plain processes here — as they do on a runner without bwrap. | |
| 619 | FORGE_CELLS: "off", | |
| 620 | }); | |
| 621 | // Placed as a Job on the cluster when the forge says so and can (#1423); | |
| 622 | // a forge that cannot says why and runs the check here, as before. | |
| 623 | if (checksPlacement(app.db) === "job") { | |
| 624 | const cluster = lane(); | |
| 625 | if (cluster.ok) { | |
| 626 | try { | |
| 627 | return await runInJob(x, cluster.value, { | |
| 628 | dir, | |
| 629 | env, | |
| 630 | install: manifest.install, | |
| 631 | command, | |
| 632 | timeoutSeconds: manifest.timeout, | |
| 633 | limits: resolveLimits("step", manifest.limits), | |
| 634 | }); | |
| 635 | } finally { | |
| 636 | rmSync(dir, { recursive: true, force: true }); | |
| 637 | } | |
| 638 | } | |
| 639 | write(`job placement unavailable: ${cluster.error}; the check runs here`); | |
| 640 | log.info("check placed as a process", { run: x.id, why: cluster.error }); | |
| 641 | } | |
| 642 | if (x.runId !== undefined) | |
| 643 | noteRunProgress(app.db, x.runId, { | |
| 644 | placement: "process", | |
| 645 | node: process.env["NODE_NAME"] || hostname(), | |
| 646 | }); | |
| 568 | 647 | // The check is repository code: it runs in a cell of its own |
| 569 | 648 | // (`apps/contain.ts`), its checkout and a home its only places to write, |
| 570 | 649 | // the forge, the registry and what it declared its only way out. |
| @@ -591,28 +670,6 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle { | ||
| 591 | 670 | } |
| 592 | 671 | : undefined; |
| 593 | 672 | try { |
| 594 | const env = childEnv({ | |
| 595 | // The shard count an admin set (`core/capacity.ts`), never the pod's. | |
| 596 | ...capacityEnv(app.db), | |
| 597 | CI: "1", | |
| 598 | FORGE_URL: options.forgeUrl, | |
| 599 | FORGE_CHECK: run.id, | |
| 600 | FORGE_COMMIT: x.commitOid, | |
| 601 | ...(base === undefined | |
| 602 | ? {} | |
| 603 | : { | |
| 604 | FORGE_CHECK_BASE: base, | |
| 605 | FORGE_CHECK_LEARNED: readLearned( | |
| 606 | app.config.dataDir, | |
| 607 | x.pull!.id, | |
| 608 | ).join(","), | |
| 609 | }), | |
| 610 | // A cell inside a cell is not a cell. This check's own cell is the | |
| 611 | // boundary; a forge the tests boot inside it would wrap its apps in | |
| 612 | // nested cells, and those never answer in time. Its children run as | |
| 613 | // plain processes here — as they do on a runner without bwrap. | |
| 614 | FORGE_CELLS: "off", | |
| 615 | }); | |
| 616 | 673 | if (manifest.install !== null) { |
| 617 | 674 | const installed = await runStep("install", manifest.install, { |
| 618 | 675 | cwd: dir, |
| @@ -657,6 +714,140 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle { | ||
| 657 | 714 | } |
| 658 | 715 | } |
| 659 | 716 | |
| 717 | /** The cluster to place a check on, or why there is none. */ | |
| 718 | function lane(): Result<{ client: JobClient; settings: JobSettings }, string> { | |
| 719 | // A cell holds a check to the hosts forge.json declares; a Job's | |
| 720 | // NetworkPolicy speaks addresses and cannot yet. Pillar 0 is not | |
| 721 | // loosened by a setting: while egress is enforced, checks stay here. | |
| 722 | if (egressSetting(app.db) === "enforce") | |
| 723 | return err( | |
| 724 | "cells.egress is enforce, and a Job cannot yet hold a check to the hosts forge.json declares", | |
| 725 | ); | |
| 726 | if (options.jobs !== undefined) return ok(options.jobs); | |
| 727 | const settings = jobSettings(process.env, options.forgeUrl); | |
| 728 | if (!settings.ok) return settings; | |
| 729 | const access = inClusterAccess(settings.value.namespace); | |
| 730 | if (!access.ok) return err(access.error); | |
| 731 | return ok({ client: kubeJobs(access.value), settings: settings.value }); | |
| 732 | } | |
| 733 | ||
| 734 | /** | |
| 735 | * One check as a Job (#1423): the checkout prepared here is fetched by | |
| 736 | * the Job (`cluster/tree.ts`), the steps run there (`cluster/lane.ts`), | |
| 737 | * the pod's log is streamed into the run's log as it comes, and the | |
| 738 | * verdict is how the Job ended. Whatever happens, the Job is deleted. | |
| 739 | */ | |
| 740 | async function runInJob( | |
| 741 | x: Execution, | |
| 742 | cluster: { client: JobClient; settings: JobSettings }, | |
| 743 | step: { | |
| 744 | dir: string; | |
| 745 | env: Record<string, string>; | |
| 746 | install: string | null; | |
| 747 | command: string; | |
| 748 | timeoutSeconds: number; | |
| 749 | limits: ReturnType<typeof resolveLimits>; | |
| 750 | }, | |
| 751 | ): Promise<Outcome> { | |
| 752 | const { client, settings } = cluster; | |
| 753 | // The install step and the check each get the timeout, as they do here. | |
| 754 | const deadlineSeconds = step.timeoutSeconds * 2 + 120; | |
| 755 | const { HOME: _home, TMPDIR: _tmp, ...env } = step.env; | |
| 756 | const manifest = jobManifest( | |
| 757 | { | |
| 758 | lane: "check", | |
| 759 | id: x.id, | |
| 760 | command: ["bun", "/app/src/cluster/lane.ts"], | |
| 761 | limits: step.limits, | |
| 762 | deadlineSeconds, | |
| 763 | env: { | |
| 764 | ...env, | |
| 765 | TMPDIR: "/tmp", | |
| 766 | FORGE_LANE_TREE: `${settings.forgeUrl}/-/lane/${x.id}/tree`, | |
| 767 | FORGE_LANE_TOKEN: treeToken( | |
| 768 | app.config.dataDir, | |
| 769 | x.id, | |
| 770 | Date.now() + deadlineSeconds * 1000, | |
| 771 | ), | |
| 772 | FORGE_LANE_INSTALL: step.install ?? "", | |
| 773 | FORGE_LANE_COMMAND: step.command, | |
| 774 | FORGE_LANE_TIMEOUT_MS: String(step.timeoutSeconds * 1000), | |
| 775 | FORGE_LANE_WORK: JOB_WORK, | |
| 776 | }, | |
| 777 | }, | |
| 778 | settings, | |
| 779 | ); | |
| 780 | const name = jobName("check", x.id); | |
outdated
Medium: when the cluster refuses the Job (quota, admission, a 5xx), the check is failed against the commit. That is the cluster's fault, as with a vanished Job. Either fall back to process placement with the reason in the log, as |
||
| 781 | if (x.runId !== undefined) | |
| 782 | noteRunProgress(app.db, x.runId, { | |
| 783 | placement: "job", | |
| 784 | sandbox: { enforced: true, note: `a Job on the cluster (${name})` }, | |
| 785 | }); | |
| 786 | x.write(`placed as a Job: ${name}`); | |
| 787 | const created = await client.create(manifest); | |
| 788 | // A cluster that refuses the Job (quota, admission, a 5xx) is not the | |
| 789 | // commit's fault: retried once, like a Job that vanished. | |
| 790 | if (!created.ok) | |
| 791 | return { | |
| 792 | ok: false, | |
| 793 | error: `the cluster refused its Job: ${created.error}`, | |
| 794 | vanished: true, | |
| 795 | }; | |
| 796 | // The lane's own lines say where the check's output starts and why a | |
| 797 | // step failed; every other line is the commands' and goes to the log. | |
| 798 | const checkLines: string[] = []; | |
| 799 | let inCheck = false; | |
| 800 | let sawEcho = false; | |
| 801 | let laneError: string | undefined; | |
| 802 | const onLine = (line: string): void => { | |
| 803 | if (line.startsWith(`${LANE_MARK} `)) { | |
| 804 | const said = line.slice(LANE_MARK.length + 1); | |
| 805 | if (said === "check") inCheck = true; | |
| 806 | else if (said.startsWith("failed ")) laneError = said.slice(7); | |
| 807 | return; | |
| 808 | } | |
| 809 | if (inCheck && sawEcho) checkLines.push(line); | |
| 810 | if (inCheck) sawEcho = true; | |
| 811 | x.write(line); | |
| 812 | }; | |
| 813 | const following = new AbortController(); | |
| 814 | const stopFollowing = (): void => following.abort(); | |
| 815 | x.signal.addEventListener("abort", stopFollowing, { once: true }); | |
| 816 | try { | |
| 817 | const logs = client.logs(name, onLine, following.signal); | |
| 818 | const end = await client.wait(name, x.signal, (node) => { | |
| 819 | x.write(`running on ${node}`); | |
| 820 | if (x.runId !== undefined) noteRunProgress(app.db, x.runId, { node }); | |
| 821 | }); | |
| 822 | // What the pod said last is still on its way: a moment to arrive. | |
| 823 | await Promise.race([logs, Bun.sleep(5_000)]); | |
| 824 | if (x.signal.aborted) return { ok: false, error: "check cancelled" }; | |
| 825 | switch (end.kind) { | |
| 826 | case "vanished": | |
| 827 | return { ok: false, error: `its Job vanished: ${end.reason}`, vanished: true }; | |
| 828 | case "deadline": | |
| 829 | return { | |
| 830 | ok: false, | |
| 831 | error: `check took longer than ${deadlineSeconds}s`, | |
| 832 | }; | |
| 833 | case "exited": { | |
| 834 | if (end.code === 0) return { ok: true }; | |
| 835 | const error = | |
| 836 | end.reason === "OOMKilled" | |
| 837 | ? `check stopped: it went over its memory limit (${step.limits.memoryMiB} MiB)` | |
| 838 | : (laneError ?? `the Job exited with code ${end.code}`); | |
| 839 | if (!inCheck) return { ok: false, error }; | |
| 840 | const { summary, detail } = summariseCheckFailure(checkLines, error); | |
| 841 | return { ok: false, error: summary, detail }; | |
| 842 | } | |
| 843 | } | |
| 844 | } finally { | |
| 845 | following.abort(); | |
| 846 | x.signal.removeEventListener("abort", stopFollowing); | |
| 847 | await client.remove(name); | |
| 848 | } | |
| 849 | } | |
| 850 | ||
| 660 | 851 | // What starts a check: a branch moving, a pull opening, a fork's push |
| 661 | 852 | // moving a pull's head. The commit checked is always the one the pull |
| 662 | 853 | // proposes now. |
src/cluster/jobs.ts added +510
| @@ -0,0 +1,510 @@ | ||
| 1 | /** | |
| 2 | * Work as a Job on the cluster instead of a child of the forge's pod | |
| 3 | * (#1423). The forge's own lane — a check today — can run on any node the | |
| 4 | * operator points it at (the vxrail's 80 cores), so two checks at once no | |
| 5 | * longer share one pod's memory. | |
| 6 | * | |
| 7 | * Three things live here: | |
| 8 | * | |
| 9 | * - **Settings** (`jobSettings`): where a Job runs — the image, the | |
| 10 | * namespace, a node selector and tolerations — read from the operator's | |
| 11 | * environment and validated before anything is sent to the cluster. | |
| 12 | * - **The manifest** (`jobManifest`): plain data in, a `batch/v1` Job out. | |
| 13 | * The cell's limits (`apps/contain.ts`) become the pod's resources; the | |
| 14 | * pod runs as no one, writes only its own `emptyDir`, holds no service | |
| 15 | * account token, and carries the label the lane's NetworkPolicy selects | |
| 16 | * (`docs/CLUSTER.md`). | |
| 17 | * - **The client** (`kubeJobs`): the kube API over the pod's service | |
| 18 | * account, no dependency. It creates, watches, reads the log of and | |
| 19 | * deletes Jobs in the forge's own namespace — the Role grants nothing more. | |
| 20 | * | |
| 21 | * `JobClient` is the seam: the checks service is handed one, and a test | |
| 22 | * hands it a stand-in (`test/checks-job.test.ts`). | |
| 23 | */ | |
| 24 | ||
| 25 | import { existsSync, readFileSync } from "node:fs"; | |
| 26 | import type { Limits } from "../apps/contain.ts"; | |
| 27 | import { pump } from "../apps/process.ts"; | |
| 28 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 29 | ||
| 30 | /** How a Job ended, as far as the forge can tell. */ | |
| 31 | export type JobEnd = | |
| 32 | /** Its container exited: `code` 0 passed; `reason` is kube's word (`OOMKilled`, `Error`). */ | |
| 33 | | { | |
| 34 | readonly kind: "exited"; | |
| 35 | readonly code: number; | |
| 36 | readonly reason: string; | |
| 37 | } | |
| 38 | /** It ran past its deadline and the cluster stopped it. */ | |
| 39 | | { readonly kind: "deadline" } | |
| 40 | /** It is gone without an exit: deleted, evicted, its node lost — never the commit's fault. */ | |
| 41 | | { readonly kind: "vanished"; readonly reason: string }; | |
| 42 | ||
| 43 | export interface JobClient { | |
| 44 | /** Create the Job; an Err says why the cluster refused it. */ | |
| 45 | create(manifest: JobManifest): Promise<Result<void, string>>; | |
| 46 | /** | |
| 47 | * Wait for the Job to end. `onPlaced` is told the node once the pod is | |
| 48 | * scheduled. Never hangs on a Job that is gone: that is `vanished`. | |
| 49 | */ | |
| 50 | wait( | |
| 51 | name: string, | |
| 52 | signal: AbortSignal, | |
| 53 | onPlaced: (node: string) => void, | |
| 54 | ): Promise<JobEnd>; | |
| 55 | /** Follow the Job's pod log line by line until it ends or `signal` aborts. */ | |
| 56 | logs( | |
| 57 | name: string, | |
| 58 | onLine: (line: string) => void, | |
| 59 | signal: AbortSignal, | |
| 60 | ): Promise<void>; | |
| 61 | /** Delete the Job and its pod; a Job already gone is not an error. */ | |
| 62 | remove(name: string): Promise<void>; | |
| 63 | } | |
| 64 | ||
| 65 | // ---- settings ---- | |
| 66 | ||
| 67 | export interface Toleration { | |
| 68 | readonly key: string; | |
| 69 | readonly operator: "Equal" | "Exists"; | |
| 70 | readonly value?: string; | |
| 71 | readonly effect: "NoSchedule" | "PreferNoSchedule" | "NoExecute"; | |
| 72 | } | |
| 73 | ||
| 74 | export interface JobSettings { | |
| 75 | /** The image a Job runs: the forge's own, so the lane is the same code. */ | |
| 76 | readonly image: string; | |
| 77 | readonly namespace: string; | |
| 78 | /** The origin a Job reaches the forge on from inside the cluster. */ | |
| 79 | readonly forgeUrl: string; | |
| 80 | readonly nodeSelector: Readonly<Record<string, string>>; | |
| 81 | readonly tolerations: readonly Toleration[]; | |
| 82 | /** Secrets that pull a private image, by name. */ | |
| 83 | readonly pullSecrets: readonly string[]; | |
| 84 | } | |
| 85 | ||
| 86 | const SA_DIR = "/var/run/secrets/kubernetes.io/serviceaccount"; | |
| 87 | ||
| 88 | /** A label key (optionally prefixed) or value, as kube accepts them. */ | |
| 89 | const LABEL_KEY = /^([a-z0-9]([-a-z0-9.]{0,251}[a-z0-9])?\/)?[A-Za-z0-9]([-A-Za-z0-9_.]{0,61}[A-Za-z0-9])?$/; | |
| 90 | const LABEL_VALUE = /^([A-Za-z0-9]([-A-Za-z0-9_.]{0,61}[A-Za-z0-9])?)?$/; | |
| 91 | const NAMESPACE = /^[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?$/; | |
| 92 | const IMAGE = /^[A-Za-z0-9][A-Za-z0-9._\-/:@]{0,254}$/; | |
| 93 | const EFFECTS = ["NoSchedule", "PreferNoSchedule", "NoExecute"] as const; | |
| 94 | ||
| 95 | /** `k=v,k2=v2` → a node selector. */ | |
| 96 | export function parseNodeSelector( | |
| 97 | raw: string, | |
| 98 | ): Result<Record<string, string>, string> { | |
| 99 | const out: Record<string, string> = {}; | |
| 100 | for (const part of raw.split(",").map((s) => s.trim())) { | |
| 101 | if (part === "") continue; | |
| 102 | const at = part.indexOf("="); | |
| 103 | const key = at === -1 ? part : part.slice(0, at); | |
| 104 | const value = at === -1 ? "" : part.slice(at + 1); | |
| 105 | if (at === -1 || !LABEL_KEY.test(key) || !LABEL_VALUE.test(value)) | |
| 106 | return err(`not a node selector: ${JSON.stringify(part)}`); | |
| 107 | out[key] = value; | |
| 108 | } | |
| 109 | return ok(out); | |
| 110 | } | |
| 111 | ||
| 112 | /** `key=value:Effect` or `key:Effect` (Exists), comma-separated → tolerations. */ | |
| 113 | export function parseTolerations(raw: string): Result<Toleration[], string> { | |
| 114 | const out: Toleration[] = []; | |
| 115 | for (const part of raw.split(",").map((s) => s.trim())) { | |
| 116 | if (part === "") continue; | |
| 117 | const colon = part.lastIndexOf(":"); | |
| 118 | const effect = colon === -1 ? "" : part.slice(colon + 1); | |
| 119 | const head = colon === -1 ? part : part.slice(0, colon); | |
| 120 | const at = head.indexOf("="); | |
| 121 | const key = at === -1 ? head : head.slice(0, at); | |
| 122 | const value = at === -1 ? undefined : head.slice(at + 1); | |
| 123 | if ( | |
| 124 | !(EFFECTS as readonly string[]).includes(effect) || | |
| 125 | !LABEL_KEY.test(key) || | |
| 126 | (value !== undefined && !LABEL_VALUE.test(value)) | |
| 127 | ) | |
| 128 | return err(`not a toleration: ${JSON.stringify(part)}`); | |
| 129 | out.push({ | |
| 130 | key, | |
| 131 | operator: value === undefined ? "Exists" : "Equal", | |
| 132 | ...(value === undefined ? {} : { value }), | |
| 133 | effect: effect as Toleration["effect"], | |
| 134 | }); | |
| 135 | } | |
| 136 | return ok(out); | |
| 137 | } | |
| 138 | ||
| 139 | /** | |
| 140 | * Where a Job runs, from the operator's environment: `FORGE_JOB_IMAGE` | |
| 141 | * (required), `FORGE_JOB_NAMESPACE` (else the service account's own), | |
| 142 | * `FORGE_JOB_FORGE_URL` (else `forgeUrl`), `FORGE_JOB_NODE_SELECTOR` | |
| 143 | * (`plat.sh/site=vxrail`), `FORGE_JOB_TOLERATIONS` | |
| 144 | * (`plat.sh/site=vxrail:NoSchedule`) and `FORGE_JOB_PULL_SECRETS`. An Err says what is missing or wrong, | |
| 145 | * and the work runs as a process instead. | |
| 146 | */ | |
| 147 | export function jobSettings( | |
| 148 | env: Record<string, string | undefined>, | |
| 149 | forgeUrl: string, | |
| 150 | saDir: string = SA_DIR, | |
| 151 | ): Result<JobSettings, string> { | |
| 152 | const image = env["FORGE_JOB_IMAGE"]?.trim() ?? ""; | |
| 153 | if (image === "") return err("FORGE_JOB_IMAGE is not set"); | |
| 154 | if (!IMAGE.test(image)) return err("FORGE_JOB_IMAGE is not an image name"); | |
| 155 | const namespace = | |
| 156 | env["FORGE_JOB_NAMESPACE"]?.trim() || readSa(saDir, "namespace") || ""; | |
| 157 | if (!NAMESPACE.test(namespace)) | |
| 158 | return err("no namespace: set FORGE_JOB_NAMESPACE or run in a pod"); | |
| 159 | const url = env["FORGE_JOB_FORGE_URL"]?.trim() || forgeUrl; | |
| 160 | if (!/^https?:\/\/[^\s/]+\/?$/.test(url)) | |
| 161 | return err("FORGE_JOB_FORGE_URL is not an origin"); | |
| 162 | const selector = parseNodeSelector(env["FORGE_JOB_NODE_SELECTOR"] ?? ""); | |
| 163 | if (!selector.ok) return selector; | |
| 164 | const tolerations = parseTolerations(env["FORGE_JOB_TOLERATIONS"] ?? ""); | |
| 165 | if (!tolerations.ok) return tolerations; | |
| 166 | const pullSecrets = (env["FORGE_JOB_PULL_SECRETS"] ?? "") | |
| 167 | .split(",") | |
| 168 | .map((s) => s.trim()) | |
| 169 | .filter((s) => s !== ""); | |
| 170 | if (!pullSecrets.every((s) => NAMESPACE.test(s))) | |
| 171 | return err("FORGE_JOB_PULL_SECRETS is not a list of secret names"); | |
| 172 | return ok({ | |
| 173 | image, | |
| 174 | namespace, | |
| 175 | forgeUrl: url.replace(/\/$/, ""), | |
| 176 | nodeSelector: selector.value, | |
| 177 | tolerations: tolerations.value, | |
| 178 | pullSecrets, | |
| 179 | }); | |
| 180 | } | |
| 181 | ||
| 182 | function readSa(dir: string, file: string): string | undefined { | |
| 183 | const path = `${dir}/${file}`; | |
| 184 | return existsSync(path) ? readFileSync(path, "utf8").trim() : undefined; | |
| 185 | } | |
| 186 | ||
| 187 | // ---- the manifest ---- | |
| 188 | ||
| 189 | /** What a Job is for; also the label the lane's NetworkPolicy selects. */ | |
| 190 | export type Lane = "check"; | |
| 191 | ||
| 192 | export interface JobSpec { | |
| 193 | readonly lane: Lane; | |
| 194 | /** The run (or gate) it works for; the Job's name is made from it. */ | |
| 195 | readonly id: string; | |
| 196 | readonly command: readonly string[]; | |
| 197 | readonly env: Readonly<Record<string, string>>; | |
| 198 | readonly limits: Limits; | |
| 199 | /** The cluster stops the Job after this long. */ | |
| 200 | readonly deadlineSeconds: number; | |
| 201 | } | |
| 202 | ||
| 203 | export type JobManifest = Record<string, unknown> & { | |
| 204 | readonly metadata: { | |
| 205 | readonly name: string; | |
| 206 | readonly namespace: string; | |
| 207 | readonly labels: Readonly<Record<string, string>>; | |
| 208 | }; | |
| 209 | }; | |
| 210 | ||
| 211 | /** A Job's name: DNS-safe, at most 63 characters, unique per lane and id. */ | |
| 212 | export function jobName(lane: Lane, id: string): string { | |
| 213 | const safe = id.toLowerCase().replace(/[^a-z0-9-]/g, "-"); | |
| 214 | return `forge-${lane}-${safe}`.slice(0, 63).replace(/-+$/, ""); | |
| 215 | } | |
| 216 | ||
| 217 | /** The directory a Job works in: its own `emptyDir`, sized to the cell's disk. */ | |
| 218 | export const JOB_WORK = "/work"; | |
| 219 | ||
| 220 | export function jobManifest(spec: JobSpec, settings: JobSettings): JobManifest { | |
| 221 | const name = jobName(spec.lane, spec.id); | |
| 222 | const labels = { | |
| 223 | "app.kubernetes.io/managed-by": "forge", | |
| 224 | "forge.plat.sh/lane": spec.lane, | |
| 225 | }; | |
| 226 | const resources = { | |
| 227 | cpu: String(spec.limits.cpus), | |
| 228 | memory: `${spec.limits.memoryMiB}Mi`, | |
| 229 | "ephemeral-storage": `${spec.limits.diskMiB}Mi`, | |
| 230 | }; | |
| 231 | return { | |
| 232 | apiVersion: "batch/v1", | |
| 233 | kind: "Job", | |
| 234 | metadata: { name, namespace: settings.namespace, labels }, | |
| 235 | spec: { | |
| 236 | backoffLimit: 0, | |
| 237 | activeDeadlineSeconds: spec.deadlineSeconds, | |
| 238 | ttlSecondsAfterFinished: 600, | |
| 239 | template: { | |
| 240 | metadata: { labels }, | |
| 241 | spec: { | |
| 242 | restartPolicy: "Never", | |
| 243 | automountServiceAccountToken: false, | |
| 244 | enableServiceLinks: false, | |
| 245 | nodeSelector: { ...settings.nodeSelector }, | |
| 246 | tolerations: settings.tolerations.map((t) => ({ ...t })), | |
| 247 | imagePullSecrets: settings.pullSecrets.map((n) => ({ name: n })), | |
| 248 | securityContext: { | |
| 249 | runAsNonRoot: true, | |
| 250 | runAsUser: 1000, | |
| 251 | runAsGroup: 1000, | |
| 252 | fsGroup: 1000, | |
| 253 | seccompProfile: { type: "RuntimeDefault" }, | |
| 254 | }, | |
| 255 | containers: [ | |
| 256 | { | |
| 257 | name: "lane", | |
| 258 | image: settings.image, | |
| 259 | command: [...spec.command], | |
| 260 | workingDir: JOB_WORK, | |
| 261 | env: Object.entries(spec.env).map(([n, value]) => ({ | |
| 262 | name: n, | |
| 263 | value, | |
| 264 | })), | |
| 265 | resources: { requests: resources, limits: resources }, | |
| 266 | securityContext: { | |
| 267 | allowPrivilegeEscalation: false, | |
| 268 | readOnlyRootFilesystem: true, | |
| 269 | capabilities: { drop: ["ALL"] }, | |
| 270 | }, | |
| 271 | volumeMounts: [ | |
| 272 | { name: "work", mountPath: JOB_WORK }, | |
| 273 | { name: "tmp", mountPath: "/tmp" }, | |
| 274 | ], | |
| 275 | }, | |
| 276 | ], | |
| 277 | volumes: [ | |
| 278 | { name: "work", emptyDir: { sizeLimit: `${spec.limits.diskMiB}Mi` } }, | |
| 279 | { name: "tmp", emptyDir: { sizeLimit: "256Mi" } }, | |
| 280 | ], | |
| 281 | }, | |
| 282 | }, | |
| 283 | }, | |
| 284 | }; | |
| 285 | } | |
| 286 | ||
| 287 | // ---- the client ---- | |
| 288 | ||
| 289 | /** How often a Job is looked at while it runs. */ | |
| 290 | const POLL_MS = 2_000; | |
| 291 | /** How long the API may stay unreachable before a Job is taken as gone. */ | |
| 292 | const UNREACHABLE_MS = 60_000; | |
| 293 | /** A pod's own word for having been taken away rather than exiting. */ | |
| 294 | const GONE_REASONS = ["Evicted", "NodeLost", "Shutdown", "Terminated", "Preempting"]; | |
| 295 | ||
| 296 | interface PodView { | |
| 297 | readonly node: string; | |
| 298 | readonly phase: string; | |
| 299 | readonly reason: string; | |
| 300 | readonly terminated?: { code: number; reason: string } | undefined; | |
| 301 | } | |
| 302 | ||
| 303 | interface JobView { | |
| 304 | readonly complete: boolean; | |
| 305 | readonly failed: string | undefined; | |
| 306 | } | |
| 307 | ||
| 308 | /** What the forge needs to know of a pod, from the API's object. */ | |
| 309 | export function podView(pod: unknown): PodView { | |
| 310 | const p = pod as { | |
| 311 | spec?: { nodeName?: string }; | |
| 312 | status?: { | |
| 313 | phase?: string; | |
| 314 | reason?: string; | |
| 315 | containerStatuses?: { | |
| 316 | state?: { terminated?: { exitCode?: number; reason?: string } }; | |
| 317 | }[]; | |
| 318 | }; | |
| 319 | }; | |
| 320 | const t = p.status?.containerStatuses?.[0]?.state?.terminated; | |
| 321 | return { | |
| 322 | node: p.spec?.nodeName ?? "", | |
| 323 | phase: p.status?.phase ?? "", | |
| 324 | reason: p.status?.reason ?? "", | |
| 325 | terminated: | |
| 326 | t === undefined | |
| 327 | ? undefined | |
| 328 | : { code: t.exitCode ?? -1, reason: t.reason ?? "" }, | |
| 329 | }; | |
| 330 | } | |
| 331 | ||
| 332 | /** Whether a Job is done, and the reason kube gave when it failed. */ | |
| 333 | export function jobView(job: unknown): JobView { | |
| 334 | const conditions = | |
| 335 | (job as { status?: { conditions?: { type?: string; status?: string; reason?: string }[] } }) | |
| 336 | .status?.conditions ?? []; | |
| 337 | const on = (type: string) => | |
| 338 | conditions.find((c) => c.type === type && c.status === "True"); | |
| 339 | return { | |
| 340 | complete: on("Complete") !== undefined, | |
| 341 | failed: on("Failed")?.reason ?? undefined, | |
| 342 | }; | |
| 343 | } | |
| 344 | ||
| 345 | /** | |
| 346 | * How a Job ended, from one look at it and its pod — or undefined while it | |
| 347 | * is still going. Pure, so every way a Job can end is tested without a | |
| 348 | * cluster. | |
| 349 | */ | |
| 350 | export function judge( | |
| 351 | job: JobView | "gone", | |
| 352 | pod: PodView | undefined, | |
| 353 | ): JobEnd | undefined { | |
| 354 | if (job === "gone") return { kind: "vanished", reason: "the Job is gone" }; | |
| 355 | if (pod?.terminated !== undefined) | |
| 356 | return { | |
| 357 | kind: "exited", | |
| 358 | code: pod.terminated.code, | |
| 359 | reason: pod.terminated.reason, | |
| 360 | }; | |
| 361 | if (pod !== undefined && GONE_REASONS.includes(pod.reason)) | |
| 362 | return { | |
| 363 | kind: "vanished", | |
| 364 | reason: `its pod was ${pod.reason.toLowerCase()}${pod.node ? ` on ${pod.node}` : ""}`, | |
| 365 | }; | |
| 366 | if (job.complete) return { kind: "exited", code: 0, reason: "Completed" }; | |
| 367 | if (job.failed === "DeadlineExceeded") return { kind: "deadline" }; | |
| 368 | if (job.failed !== undefined) | |
| 369 | return { | |
| 370 | kind: "vanished", | |
| 371 | reason: `the Job failed (${job.failed}) with no exit from its pod`, | |
| 372 | }; | |
| 373 | if (pod?.phase === "Failed" || pod?.phase === "Unknown") | |
| 374 | return { kind: "vanished", reason: `its pod is ${pod.phase.toLowerCase()}` }; | |
| 375 | return undefined; | |
| 376 | } | |
| 377 | ||
| 378 | export interface KubeAccess { | |
| 379 | /** `https://host:port` of the API server. */ | |
| 380 | readonly server: string; | |
| 381 | readonly token: string; | |
| 382 | /** The cluster's CA, PEM. */ | |
| 383 | readonly ca: string; | |
| 384 | readonly namespace: string; | |
| 385 | } | |
| 386 | ||
| 387 | /** The API as the pod's service account sees it, or why it cannot. */ | |
| 388 | export function inClusterAccess( | |
| 389 | namespace: string, | |
| 390 | env: Record<string, string | undefined> = process.env, | |
| 391 | saDir: string = SA_DIR, | |
| 392 | ): Result<KubeAccess, string> { | |
| 393 | const host = env["KUBERNETES_SERVICE_HOST"]; | |
| 394 | const port = env["KUBERNETES_SERVICE_PORT"] ?? "443"; | |
| 395 | if (!host) return err("not running in a cluster"); | |
| 396 | const token = readSa(saDir, "token"); | |
| 397 | const ca = readSa(saDir, "ca.crt"); | |
| 398 | if (!token || !ca) return err("no service account is mounted"); | |
| 399 | const server = host.includes(":") ? `https://[${host}]:${port}` : `https://${host}:${port}`; | |
| 400 | return ok({ server, token, ca, namespace }); | |
| 401 | } | |
| 402 | ||
| 403 | /** The kube API client over a service account. */ | |
| 404 | export function kubeJobs(access: KubeAccess): JobClient { | |
| 405 | const ns = encodeURIComponent(access.namespace); | |
| 406 | const jobs = `${access.server}/apis/batch/v1/namespaces/${ns}/jobs`; | |
| 407 | const pods = `${access.server}/api/v1/namespaces/${ns}/pods`; | |
| 408 | const call = ( | |
| 409 | url: string, | |
| 410 | init: { method?: string; body?: string; signal?: AbortSignal } = {}, | |
| 411 | ): Promise<Response> => | |
| 412 | fetch(url, { | |
| 413 | method: init.method ?? "GET", | |
| 414 | headers: { | |
| 415 | authorization: `Bearer ${access.token}`, | |
| 416 | accept: "application/json", | |
| 417 | ...(init.body === undefined ? {} : { "content-type": "application/json" }), | |
| 418 | }, | |
| 419 | ...(init.body === undefined ? {} : { body: init.body }), | |
| 420 | ...(init.signal === undefined ? {} : { signal: init.signal }), | |
| 421 | tls: { ca: access.ca }, | |
| 422 | } as RequestInit); | |
| 423 | ||
| 424 | const podOf = async (name: string, signal?: AbortSignal): Promise<unknown> => { | |
| 425 | const selector = encodeURIComponent(`job-name=${name}`); | |
| 426 | const res = await call( | |
| 427 | `${pods}?labelSelector=${selector}`, | |
| 428 | signal === undefined ? {} : { signal }, | |
| 429 | ); | |
| 430 | if (!res.ok) throw new Error(`pods: ${res.status}`); | |
| 431 | const list = (await res.json()) as { items?: unknown[] }; | |
| 432 | return list.items?.[0]; | |
| 433 | }; | |
| 434 | ||
| 435 | return { | |
| 436 | async create(manifest) { | |
| 437 | try { | |
| 438 | const res = await call(jobs, { | |
| 439 | method: "POST", | |
| 440 | body: JSON.stringify(manifest), | |
| 441 | }); | |
| 442 | if (res.ok) return ok(); | |
| 443 | const body = (await res.json().catch(() => ({}))) as { message?: string }; | |
| 444 | return err(`the cluster refused the Job (${res.status}): ${body.message ?? ""}`.trim()); | |
| 445 | } catch (error) { | |
| 446 | return err(`the cluster could not be reached: ${String(error)}`); | |
| 447 | } | |
| 448 | }, | |
| 449 | ||
| 450 | async wait(name, signal, onPlaced) { | |
| 451 | let placed = ""; | |
| 452 | let lastSeen = Date.now(); | |
| 453 | while (!signal.aborted) { | |
| 454 | try { | |
| 455 | const res = await call(`${jobs}/${encodeURIComponent(name)}`, { signal }); | |
| 456 | if (res.status === 404) return judge("gone", undefined)!; | |
| 457 | if (!res.ok) throw new Error(`job: ${res.status}`); | |
| 458 | const job = jobView(await res.json()); | |
| 459 | const raw = await podOf(name, signal); | |
| 460 | const pod = raw === undefined ? undefined : podView(raw); | |
| 461 | if (pod?.node && pod.node !== placed) { | |
| 462 | placed = pod.node; | |
| 463 | onPlaced(placed); | |
| 464 | } | |
| 465 | lastSeen = Date.now(); | |
| 466 | const end = judge(job, pod); | |
| 467 | if (end !== undefined) return end; | |
| 468 | } catch { | |
| 469 | if (signal.aborted) break; | |
| 470 | if (Date.now() - lastSeen > UNREACHABLE_MS) | |
| 471 | return { kind: "vanished", reason: "the cluster stopped answering" }; | |
| 472 | } | |
| 473 | await Bun.sleep(POLL_MS); | |
| 474 | } | |
| 475 | return { kind: "vanished", reason: "stopped watching" }; | |
| 476 | }, | |
| 477 | ||
| 478 | async logs(name, onLine, signal) { | |
| 479 | // The log can be followed once the container has started; until then | |
| 480 | // the API answers 400. Asked again until it can, or the Job ends. | |
| 481 | while (!signal.aborted) { | |
| 482 | try { | |
| 483 | const raw = await podOf(name, signal); | |
| 484 | const pod = raw === undefined ? undefined : podView(raw); | |
| 485 | const podName = (raw as { metadata?: { name?: string } } | undefined) | |
| 486 | ?.metadata?.name; | |
| 487 | if (podName && pod && pod.phase !== "Pending") { | |
| 488 | const res = await call( | |
| 489 | `${pods}/${encodeURIComponent(podName)}/log?container=lane&follow=true`, | |
| 490 | { signal }, | |
| 491 | ); | |
| 492 | if (res.ok) { | |
| 493 | await pump(res.body, onLine, signal); | |
| 494 | return; | |
| 495 | } | |
| 496 | } | |
| 497 | } catch { | |
| 498 | if (signal.aborted) return; | |
| 499 | } | |
| 500 | await Bun.sleep(POLL_MS); | |
| 501 | } | |
| 502 | }, | |
| 503 | ||
| 504 | async remove(name) { | |
| 505 | await call(`${jobs}/${encodeURIComponent(name)}?propagationPolicy=Background`, { | |
| 506 | method: "DELETE", | |
| 507 | }).catch(() => undefined); | |
| 508 | }, | |
| 509 | }; | |
| 510 | } |
src/cluster/lane.ts added +116
| @@ -0,0 +1,116 @@ | ||
| 1 | /** | |
| 2 | * What a check's Job runs (#1423): `bun src/cluster/lane.ts` in the | |
| 3 | * forge's own image. It fetches the checkout the forge prepared | |
| 4 | * (`cluster/tree.ts`), runs the install step and the check exactly as the | |
| 5 | * forge would have run them as children (`runStep`), and says what | |
| 6 | * happened on its stdout — which is the pod's log, streamed back into the | |
| 7 | * run's log file line by line. The pod itself is the cell: its resources, | |
| 8 | * its NetworkPolicy, its own empty disk (`cluster/jobs.ts`). | |
| 9 | * | |
| 10 | * The verdict is the exit code. The lines it marks (`LANE_MARK`) only | |
| 11 | * shape the log: where the check's own output starts, and the one-line | |
| 12 | * reason a failure gives — the same words a process placement gives. | |
| 13 | */ | |
| 14 | ||
| 15 | import { mkdirSync } from "node:fs"; | |
| 16 | import { join } from "node:path"; | |
| 17 | import { runStep } from "../apps/process.ts"; | |
| 18 | ||
| 19 | /** Prefixes the lane's own lines in the log, apart from the commands'. */ | |
| 20 | export const LANE_MARK = "::forge-lane::"; | |
| 21 | ||
| 22 | /** Exit codes: the check passed, a step failed, the checkout never arrived. */ | |
| 23 | export const LANE_EXIT = { ok: 0, failed: 1, noTree: 2 } as const; | |
| 24 | ||
| 25 | /** Every lane setting is named so; none of them reaches the check. */ | |
| 26 | const OWN = /^FORGE_LANE_/; | |
| 27 | ||
| 28 | export async function runLane( | |
| 29 | env: Record<string, string | undefined>, | |
| 30 | log: (line: string) => void, | |
| 31 | signal: AbortSignal = new AbortController().signal, | |
| 32 | ): Promise<number> { | |
| 33 | const work = env["FORGE_LANE_WORK"] ?? "/work"; | |
| 34 | const dir = join(work, "tree"); | |
| 35 | const home = join(work, "home"); | |
| 36 | mkdirSync(dir, { recursive: true }); | |
| 37 | mkdirSync(home, { recursive: true }); | |
| 38 | const failed = (why: string, code: number = LANE_EXIT.failed): number => { | |
| 39 | log(`${LANE_MARK} failed ${why}`); | |
| 40 | return code; | |
| 41 | }; | |
| 42 | ||
| 43 | const fetched = await fetchTree( | |
| 44 | env["FORGE_LANE_TREE"] ?? "", | |
| 45 | env["FORGE_LANE_TOKEN"] ?? "", | |
| 46 | dir, | |
| 47 | signal, | |
| 48 | ); | |
| 49 | if (fetched !== undefined) return failed(fetched, LANE_EXIT.noTree); | |
| 50 | ||
| 51 | const stepEnv: Record<string, string> = {}; | |
| 52 | for (const [key, value] of Object.entries(env)) | |
| 53 | if (!OWN.test(key) && value !== undefined) stepEnv[key] = value; | |
| 54 | // The home is the Job's own, whatever the forge's was. | |
| 55 | stepEnv["HOME"] = home; | |
| 56 | const timeoutMs = Number(env["FORGE_LANE_TIMEOUT_MS"]) || 600_000; | |
| 57 | const install = env["FORGE_LANE_INSTALL"] ?? ""; | |
| 58 | if (install !== "") { | |
| 59 | const installed = await runStep("install", install, { | |
| 60 | cwd: dir, | |
| 61 | env: stepEnv, | |
| 62 | log, | |
| 63 | signal, | |
| 64 | timeoutMs, | |
| 65 | }); | |
| 66 | if (!installed.ok) return failed(installed.error); | |
| 67 | } | |
| 68 | log(`${LANE_MARK} check`); | |
| 69 | const ran = await runStep("check", env["FORGE_LANE_COMMAND"] ?? "", { | |
| 70 | cwd: dir, | |
| 71 | env: stepEnv, | |
| 72 | log, | |
| 73 | signal, | |
| 74 | timeoutMs, | |
| 75 | }); | |
| 76 | if (!ran.ok) return failed(ran.error); | |
| 77 | log(`${LANE_MARK} passed`); | |
| 78 | return LANE_EXIT.ok; | |
| 79 | } | |
| 80 | ||
| 81 | /** Fetch the checkout into `dir`; the answer is why it could not be, or nothing. */ | |
| 82 | async function fetchTree( | |
| 83 | url: string, | |
| 84 | token: string, | |
| 85 | dir: string, | |
| 86 | signal: AbortSignal, | |
| 87 | ): Promise<string | undefined> { | |
| 88 | if (!/^https?:\/\//.test(url)) return "no checkout to fetch"; | |
| 89 | let res: Response; | |
| 90 | try { | |
| 91 | res = await fetch(url, { | |
| 92 | headers: { authorization: `Bearer ${token}` }, | |
| 93 | signal, | |
| 94 | }); | |
| 95 | } catch (error) { | |
| 96 | return `the forge could not be reached for the checkout: ${String(error)}`; | |
| 97 | } | |
| 98 | if (!res.ok || res.body === null) | |
| 99 | return `the forge did not hand over the checkout (${res.status})`; | |
| 100 | const tar = Bun.spawn(["tar", "-x", "-C", dir], { | |
| 101 | stdin: res, | |
| 102 | stdout: "ignore", | |
| 103 | stderr: "pipe", | |
| 104 | }); | |
| 105 | const code = await tar.exited; | |
| 106 | if (code !== 0) | |
| 107 | return `the checkout could not be unpacked: ${(await new Response(tar.stderr).text()).trim()}`; | |
| 108 | return undefined; | |
| 109 | } | |
| 110 | ||
| 111 | if (import.meta.main) { | |
| 112 | const abort = new AbortController(); | |
| 113 | process.on("SIGTERM", () => abort.abort()); | |
| 114 | const code = await runLane(process.env, (line) => console.log(line), abort.signal); | |
| 115 | process.exit(code); | |
| 116 | } |
src/cluster/tree.ts added +77
| @@ -0,0 +1,77 @@ | ||
| 1 | /** | |
| 2 | * A check's checkout, handed to the Job that runs it (#1423). The forge's | |
| 3 | * data lives on one node's volume, which a Job on another node cannot | |
| 4 | * mount; so the forge prepares the checkout as it always has | |
| 5 | * (`checks/service.ts`) and the Job fetches it, once, as a tar over | |
| 6 | * `GET /-/lane/:id/tree`. | |
| 7 | * | |
| 8 | * The door is narrow: the bearer is an HMAC of the checkout's id and an | |
| 9 | * expiry under the forge's own key (`kernel/secret.ts`), minted for one | |
| 10 | * Job and good until its deadline; and there is something to fetch only | |
| 11 | * while that checkout exists, which is only while its check runs. | |
| 12 | */ | |
| 13 | ||
| 14 | import { createHmac, timingSafeEqual } from "node:crypto"; | |
| 15 | import { existsSync } from "node:fs"; | |
| 16 | import { join } from "node:path"; | |
| 17 | import type { Handler } from "../http/context.ts"; | |
| 18 | import { loadKey } from "../kernel/secret.ts"; | |
| 19 | ||
| 20 | /** Where a check's checkout lives while it runs. */ | |
| 21 | export const checksRoot = (dataDir: string): string => join(dataDir, "checks"); | |
| 22 | ||
| 23 | /** A checkout id: a run id, or `gate-<oid prefix>`. */ | |
| 24 | const ID = /^[a-z0-9][a-z0-9-]{0,63}$/; | |
| 25 | ||
| 26 | function mac(dataDir: string, id: string, expiry: number): string { | |
| 27 | // A key of its own, derived from the forge's, so this MAC can never be | |
| 28 | // mistaken for anything else the forge's key signs or seals. | |
| 29 | const key = createHmac("sha256", loadKey(dataDir)).update("lane-tree").digest(); | |
| 30 | return createHmac("sha256", key).update(`${id}.${expiry}`).digest("hex"); | |
| 31 | } | |
| 32 | ||
| 33 | /** The bearer that fetches checkout `id` until `expiresAt` (ms). */ | |
| 34 | export function treeToken(dataDir: string, id: string, expiresAt: number): string { | |
| 35 | const expiry = Math.ceil(expiresAt / 1000); | |
| 36 | return `${expiry}.${mac(dataDir, id, expiry)}`; | |
| 37 | } | |
| 38 | ||
| 39 | /** Whether `token` fetches checkout `id` now. */ | |
| 40 | export function treeTokenValid( | |
| 41 | dataDir: string, | |
| 42 | id: string, | |
| 43 | token: string, | |
| 44 | now: number = Date.now(), | |
| 45 | ): boolean { | |
| 46 | const match = /^(\d{1,12})\.([0-9a-f]{64})$/.exec(token); | |
| 47 | if (!match || !ID.test(id)) return false; | |
| 48 | const expiry = Number(match[1]); | |
| 49 | if (expiry * 1000 < now) return false; | |
| 50 | const want = Buffer.from(mac(dataDir, id, expiry), "hex"); | |
| 51 | const got = Buffer.from(match[2]!, "hex"); | |
| 52 | return want.length === got.length && timingSafeEqual(want, got); | |
| 53 | } | |
| 54 | ||
| 55 | /** `GET /-/lane/:id/tree`: the checkout as a tar, to the Job holding its token. */ | |
| 56 | export const laneTree: Handler = (ctx) => { | |
| 57 | const id = ctx.params["id"] ?? ""; | |
| 58 | const header = ctx.request.headers.get("authorization") ?? ""; | |
| 59 | const token = header.startsWith("Bearer ") ? header.slice(7) : ""; | |
| 60 | const dataDir = ctx.app.config.dataDir; | |
| 61 | // One answer for a wrong token, an unknown id and a finished check: none | |
| 62 | // of them says which. | |
| 63 | const dir = join(checksRoot(dataDir), id); | |
| 64 | if (!ID.test(id) || !treeTokenValid(dataDir, id, token) || !existsSync(dir)) | |
| 65 | return new Response("not found", { status: 404 }); | |
| 66 | const tar = Bun.spawn(["tar", "-c", "-C", dir, "."], { | |
| 67 | stdin: "ignore", | |
| 68 | stdout: "pipe", | |
| 69 | stderr: "ignore", | |
| 70 | }); | |
| 71 | return new Response(tar.stdout, { | |
| 72 | headers: { | |
| 73 | "content-type": "application/x-tar", | |
| 74 | "cache-control": "no-store", | |
| 75 | }, | |
| 76 | }); | |
| 77 | }; |
src/core/capacity.ts +13
| @@ -19,6 +19,7 @@ export type CapacityKey = | ||
| 19 | 19 | | "crew.concurrency" |
| 20 | 20 | | "checks.concurrency" |
| 21 | 21 | | "checks.shards" |
| 22 | | "checks.placement" | |
| 22 | 23 | | "children.max" |
| 23 | 24 | | "cells.egress" |
| 24 | 25 | | "guard_new_accounts"; |
| @@ -59,6 +60,13 @@ export const CAPACITY: Record<CapacityKey, Definition> = { | ||
| 59 | 60 | fallback: "", |
| 60 | 61 | help: "How many parallel shards a check's test run uses (handed to checks and crew shells as FORGE_CHECK_SHARDS). Empty: as many as the machine has cores.", |
| 61 | 62 | }, |
| 63 | "checks.placement": { | |
| 64 | label: "Where checks run", | |
| 65 | env: "FORGE_CHECKS_PLACEMENT", | |
| 66 | kind: { type: "choice", values: ["process", "job"] }, | |
| 67 | fallback: "process", | |
| 68 | help: "process runs a check as a child of the forge, in a cell; job runs it as a Job on the cluster, on the nodes FORGE_JOB_NODE_SELECTOR and FORGE_JOB_TOLERATIONS choose, so checks at once no longer share the forge's memory. Refused while cells.egress is enforce: a Job cannot yet hold a check to the hosts forge.json declares. A forge that cannot start Jobs runs the check as a process and says why in its log. Takes effect on the next check.", | |
| 69 | }, | |
| 62 | 70 | "children.max": { |
| 63 | 71 | label: "Forges this one may send", |
| 64 | 72 | env: "FORGE_CHILDREN_MAX", |
| @@ -201,6 +209,11 @@ export function egressSetting(db: Database): "enforce" | "report" { | ||
| 201 | 209 | return capacityValue(db, "cells.egress") === "report" ? "report" : "enforce"; |
| 202 | 210 | } |
| 203 | 211 | |
| 212 | /** Where the next check runs (#1423). */ | |
| 213 | export function checksPlacement(db: Database): "process" | "job" { | |
| 214 | return capacityValue(db, "checks.placement") === "job" ? "job" : "process"; | |
| 215 | } | |
| 216 | ||
| 204 | 217 | /** What a check's commands and a crew shell are told: the shard count, when one is set. */ |
| 205 | 218 | export function capacityEnv(db: Database): Record<string, string> { |
| 206 | 219 | const shards = capacityValue(db, "checks.shards"); |
src/core/runs.ts +34 −1
| @@ -78,6 +78,10 @@ export interface Run { | ||
| 78 | 78 | readonly sandboxNote: string; |
| 79 | 79 | /** A failed check's own detail, when its output was recognised; null otherwise. */ |
| 80 | 80 | readonly checkDetail: CheckDetail | null; |
| 81 | /** Where it ran: `process` (a child of the forge) or `job` (#1423); empty before it started. */ | |
| 82 | readonly placement: string; | |
|
||
| 83 | /** The node it ran on, once known. */ | |
| 84 | readonly node: string; | |
| 81 | 85 | readonly createdAt: string; |
| 82 | 86 | readonly startedAt: string | null; |
| 83 | 87 | /** When this deploy's environment started serving — set once, at the swap-in. */ |
| @@ -106,6 +110,8 @@ interface RunRow { | ||
| 106 | 110 | sandbox_enforced: number | null; |
| 107 | 111 | sandbox_note: string; |
| 108 | 112 | check_detail: string; |
| 113 | placement: string; | |
| 114 | node: string; | |
| 109 | 115 | created_at: string; |
| 110 | 116 | started_at: string | null; |
| 111 | 117 | serving_at: string | null; |
| @@ -134,6 +140,8 @@ const toRun = (r: RunRow): Run => ({ | ||
| 134 | 140 | r.sandbox_enforced === null ? null : r.sandbox_enforced !== 0, |
| 135 | 141 | sandboxNote: r.sandbox_note, |
| 136 | 142 | checkDetail: r.check_detail ? (JSON.parse(r.check_detail) as CheckDetail) : null, |
| 143 | placement: r.placement, | |
| 144 | node: r.node, | |
| 137 | 145 | createdAt: r.created_at, |
| 138 | 146 | startedAt: r.started_at, |
| 139 | 147 | servingAt: r.serving_at, |
| @@ -307,13 +315,17 @@ export function noteRunProgress( | ||
| 307 | 315 | subscriptionId?: string | undefined; |
| 308 | 316 | /** Whether the shell is held to the sandbox, and why not when it is not. */ |
| 309 | 317 | sandbox?: { enforced: boolean; note: string } | undefined; |
| 318 | /** Where it runs (#1423), and the node once it is placed. */ | |
| 319 | placement?: "process" | "job" | undefined; | |
| 320 | node?: string | undefined; | |
| 310 | 321 | }, |
| 311 | 322 | ): void { |
| 312 | 323 | db.query( |
| 313 | 324 | `UPDATE run SET session_id = COALESCE(?2, session_id), cost_usd = COALESCE(?3, cost_usd), |
| 314 | 325 | branch = COALESCE(?4, branch), subscription_id = COALESCE(?5, subscription_id), |
| 315 | 326 | sandbox_enforced = COALESCE(?6, sandbox_enforced), |
| 316 | sandbox_note = COALESCE(?7, sandbox_note) | |
| 327 | sandbox_note = COALESCE(?7, sandbox_note), | |
| 328 | placement = COALESCE(?8, placement), node = COALESCE(?9, node) | |
| 317 | 329 | WHERE id = ?1`, |
| 318 | 330 | ).run( |
| 319 | 331 | runId, |
| @@ -323,6 +335,8 @@ export function noteRunProgress( | ||
| 323 | 335 | progress.subscriptionId ?? null, |
| 324 | 336 | progress.sandbox === undefined ? null : progress.sandbox.enforced ? 1 : 0, |
| 325 | 337 | progress.sandbox?.note.slice(0, 300) ?? null, |
| 338 | progress.placement ?? null, | |
| 339 | progress.node?.slice(0, 253) ?? null, | |
| 326 | 340 | ); |
| 327 | 341 | } |
| 328 | 342 | |
| @@ -380,6 +394,25 @@ export function failAbandonedRuns( | ||
| 380 | 394 | /** What a check the forge's own restart cut off says as it is queued again. */ |
| 381 | 395 | export const REQUEUED_SUMMARY = "interrupted by a restart; queued again"; |
| 382 | 396 | |
| 397 | /** What a check says when the Job running it vanished (#1423): never the commit's fault. */ | |
| 398 | export const VANISHED_SUMMARY = "interrupted: its Job vanished; queued again"; | |
| 399 | ||
| 400 | /** | |
| 401 | * Whether this check — the same commit in the same environment — was | |
| 402 | * already queued again once because its Job vanished: a second vanish is | |
| 403 | * a failure, not another retry. | |
| 404 | */ | |
| 405 | export function vanishedBefore(db: Database, run: Run): boolean { | |
| 406 | return ( | |
| 407 | db | |
| 408 | .query( | |
| 409 | `SELECT 1 FROM run WHERE kind = 'check' AND repo_id = ?1 AND env = ?2 | |
| 410 | AND commit_oid = ?3 AND summary = ?4 AND id != ?5 LIMIT 1`, | |
| 411 | ) | |
| 412 | .get(run.repoId, run.env, run.commitOid, VANISHED_SUMMARY, run.id) !== null | |
| 413 | ); | |
| 414 | } | |
| 415 | ||
| 383 | 416 | /** |
| 384 | 417 | * How many times one check may be cut off by its forge going away and be |
| 385 | 418 | * queued again. Past it the check fails once, saying so: a check that kills |
src/core/schema.ts +6
| @@ -1595,6 +1595,12 @@ export const migrations: readonly string[] = [ | ||
| 1595 | 1595 | PRIMARY KEY (repo_id, parent_id, issue_id) |
| 1596 | 1596 | ); |
| 1597 | 1597 | `, |
| 1598 | // 76 — where a run ran (#1423): as a child of the forge (`process`) or a | |
| 1599 | // Job on the cluster (`job`), and the node. Empty for a run before this. | |
| 1600 | ` | |
| 1601 | ALTER TABLE run ADD COLUMN placement TEXT NOT NULL DEFAULT ''; | |
| 1602 | ALTER TABLE run ADD COLUMN node TEXT NOT NULL DEFAULT ''; | |
| 1603 | `, | |
| 1598 | 1604 | ]; |
| 1599 | 1605 | |
| 1600 | 1606 | /** |
src/http/server.ts +3
| @@ -86,6 +86,7 @@ import { | ||
| 86 | 86 | themeSubmit, |
| 87 | 87 | } from "../web/pages/site.ts"; |
| 88 | 88 | import { confirmPage, searchPage } from "../web/pages/search.ts"; |
| 89 | import { laneTree } from "../cluster/tree.ts"; | |
| 89 | 90 | import { followingSubmit } from "../web/pages/following.ts"; |
| 90 | 91 | import { reconnectSubmit } from "../web/pages/frozen.ts"; |
| 91 | 92 | import { activityAtom } from "../web/feeds.ts"; |
| @@ -583,6 +584,8 @@ export function buildRouter(): Router<Handler> { | ||
| 583 | 584 | // The JS-free half of every destructive action. Two literal segments, so it |
| 584 | 585 | // is registered before /:owner/:name can claim the shape. |
| 585 | 586 | router.add("GET", "/-/confirm", confirmPage); |
| 587 | // A check's checkout, fetched by the cluster Job that runs it (#1423). | |
| 588 | router.add("GET", "/-/lane/:id/tree", laneTree); | |
| 586 | 589 | router.add("GET", "/new", newRepoPage); |
| 587 | 590 | router.add("GET", "/audit", auditPage); |
| 588 | 591 | router.add("GET", "/audit.csv", auditCsv); |
src/web/studio/sandbox.ts +21 −5
| @@ -1,21 +1,37 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * The one honest line about where a run's code ran: an agent's shell held |
| 3 | 3 | * to the sandbox policy, a deploy's or check's processes held in a cell |
| 4 | * (`apps/contain.ts`) — or not, and why not. Runs that predate the record | |
| 5 | * say nothing. | |
| 4 | * (`apps/contain.ts`) — or not, and why not — and, once it was placed, | |
| 5 | * as what and on which node (#1423). Runs that predate the record say | |
| 6 | * nothing. | |
| 6 | 7 | */ |
| 7 | 8 | |
| 8 | 9 | import type { Run } from "../../core/runs.ts"; |
| 9 | 10 | import { html, type Html } from "../html.ts"; |
| 10 | 11 | |
| 12 | /** Where it ran, in a few words: `Ran as a Job on vxrail-1.`; empty before it was placed. */ | |
| 13 | export function placementText(run: Run): string { | |
| 14 | const on = run.node === "" ? "" : ` on ${run.node}`; | |
| 15 | if (run.placement === "job") return `Ran as a Job${on}.`; | |
| 16 | if (run.placement === "process") return `Ran as a child of the forge${on}.`; | |
| 17 | return ""; | |
| 18 | } | |
| 19 | ||
| 11 | 20 | export function sandboxLine(run: Run): Html | null { |
| 12 | if (run.sandboxEnforced === null) return null; | |
| 21 | const placed = placementText(run); | |
| 22 | const where = placed === "" ? "" : ` ${placed}`; | |
| 23 | if (run.sandboxEnforced === null) | |
| 24 | return placed === "" | |
| 25 | ? null | |
| 26 | : html`<p class="muted small" id="run-sandbox">${placed}</p>`; | |
| 13 | 27 | const agent = run.kind === "agent"; |
| 14 | 28 | if (run.sandboxEnforced) |
| 15 | 29 | return html`<p class="muted small" id="run-sandbox"> |
| 16 | 30 | ${agent |
| 17 | 31 | ? "Sandboxed: the shell was held to the policy." |
| 18 | : "Contained: the repository's code ran in a cell of its own, with limits."} | |
| 32 | : run.placement === "job" | |
| 33 | ? "Contained: the repository's code ran in a pod of its own, with limits." | |
| 34 | : "Contained: the repository's code ran in a cell of its own, with limits."}${where} | |
| 19 | 35 | </p>`; |
| 20 | 36 | return html`<p class="error-note" id="run-sandbox"> |
| 21 | 37 | ${agent |
| @@ -23,6 +39,6 @@ export function sandboxLine(run: Run): Html | null { | ||
| 23 | 39 | : "Uncontained: the repository's code ran unrestricted"}${run.sandboxNote === |
| 24 | 40 | "" |
| 25 | 41 | ? "" |
| 26 | : html` (${run.sandboxNote})`}. | |
| 42 | : html` (${run.sandboxNote})`}.${where} | |
| 27 | 43 | </p>`; |
| 28 | 44 | } |
test/checks-job.test.ts added +443
| @@ -0,0 +1,443 @@ | ||
| 1 | /** | |
| 2 | * A check placed as a Job on the cluster (#1423): the manifest the cluster | |
| 3 | * is handed, the door the Job fetches its checkout through, and a check run | |
| 4 | * to a verdict through a stand-in Job client that runs the real lane | |
| 5 | * in-process — so everything but the kube API itself is the real thing. | |
| 6 | */ | |
| 7 | ||
| 8 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 9 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { createApp, type App } from "../src/app.ts"; | |
| 13 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 14 | import { startChecks, type ChecksHandle } from "../src/checks/service.ts"; | |
| 15 | import { | |
| 16 | jobManifest, | |
| 17 | jobName, | |
| 18 | jobSettings, | |
| 19 | judge, | |
| 20 | parseNodeSelector, | |
| 21 | parseTolerations, | |
| 22 | type JobClient, | |
| 23 | type JobEnd, | |
| 24 | type JobManifest, | |
| 25 | type JobSettings, | |
| 26 | } from "../src/cluster/jobs.ts"; | |
| 27 | import { runLane } from "../src/cluster/lane.ts"; | |
| 28 | import { treeToken, treeTokenValid } from "../src/cluster/tree.ts"; | |
| 29 | import { setCapacity } from "../src/core/capacity.ts"; | |
| 30 | import { listRuns, VANISHED_SUMMARY, type Run } from "../src/core/runs.ts"; | |
| 31 | import { createUser, type User } from "../src/core/users.ts"; | |
| 32 | import type { Repo } from "../src/core/repos.ts"; | |
| 33 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 34 | import { readRunLog } from "../src/runs/log.ts"; | |
| 35 | ||
| 36 | const SETTINGS: JobSettings = { | |
| 37 | image: "registry.example/forge:1.2.3", | |
| 38 | namespace: "trevato-apps", | |
| 39 | forgeUrl: "http://forge.trevato-apps.svc", | |
| 40 | nodeSelector: { "plat.sh/site": "vxrail" }, | |
| 41 | tolerations: [ | |
| 42 | { | |
| 43 | key: "plat.sh/site", | |
| 44 | operator: "Equal", | |
| 45 | value: "vxrail", | |
| 46 | effect: "NoSchedule", | |
| 47 | }, | |
| 48 | ], | |
| 49 | pullSecrets: ["forgejo-registry"], | |
| 50 | }; | |
| 51 | ||
| 52 | type Pod = { | |
| 53 | spec: { | |
| 54 | nodeSelector: Record<string, string>; | |
| 55 | tolerations: unknown[]; | |
| 56 | automountServiceAccountToken: boolean; | |
| 57 | containers: { | |
| 58 | image: string; | |
| 59 | env: { name: string; value: string }[]; | |
| 60 | resources: { limits: Record<string, string> }; | |
| 61 | securityContext: Record<string, unknown>; | |
| 62 | }[]; | |
| 63 | }; | |
| 64 | }; | |
| 65 | const podOf = (m: JobManifest): Pod => | |
| 66 | (m["spec"] as { template: Pod }).template; | |
| 67 | ||
| 68 | describe("the Job a check becomes", () => { | |
| 69 | test("the cell's limits are the pod's resources; it lands where the operator said, as no one, holding no token", () => { | |
| 70 | const m = jobManifest( | |
| 71 | { | |
| 72 | lane: "check", | |
| 73 | id: "01M4Y983V1RM05X88S6NBS648C", | |
| 74 | command: ["bun", "/app/src/cluster/lane.ts"], | |
| 75 | env: { CI: "1" }, | |
| 76 | limits: { memoryMiB: 4096, cpus: 4, diskMiB: 8192 }, | |
| 77 | deadlineSeconds: 900, | |
| 78 | }, | |
| 79 | SETTINGS, | |
| 80 | ); | |
| 81 | expect(m.metadata.name).toBe("forge-check-01m4y983v1rm05x88s6nbs648c"); | |
| 82 | expect(m.metadata.namespace).toBe("trevato-apps"); | |
| 83 | expect(m.metadata.labels["forge.plat.sh/lane"]).toBe("check"); | |
| 84 | expect((m["spec"] as { backoffLimit: number }).backoffLimit).toBe(0); | |
| 85 | const pod = podOf(m); | |
| 86 | expect(pod.spec.nodeSelector).toEqual({ "plat.sh/site": "vxrail" }); | |
| 87 | expect(pod.spec.tolerations).toHaveLength(1); | |
| 88 | expect(pod.spec.automountServiceAccountToken).toBe(false); | |
| 89 | const [container] = pod.spec.containers; | |
| 90 | expect(container!.image).toBe(SETTINGS.image); | |
| 91 | expect(container!.resources.limits).toEqual({ | |
| 92 | cpu: "4", | |
| 93 | memory: "4096Mi", | |
| 94 | "ephemeral-storage": "8192Mi", | |
| 95 | }); | |
| 96 | expect(container!.securityContext["allowPrivilegeEscalation"]).toBe(false); | |
| 97 | expect(container!.securityContext["readOnlyRootFilesystem"]).toBe(true); | |
| 98 | }); | |
| 99 | ||
| 100 | test("a Job's name is DNS-safe and bounded whatever the id", () => { | |
| 101 | const name = jobName("check", `gate-${"A_b".repeat(40)}`); | |
| 102 | expect(name.length).toBeLessThanOrEqual(63); | |
| 103 | expect(name).toMatch(/^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/); | |
| 104 | }); | |
| 105 | ||
| 106 | test("node selectors and tolerations are parsed, and junk is refused before the cluster sees it", () => { | |
| 107 | expect(parseNodeSelector("plat.sh/site=vxrail")).toEqual({ | |
| 108 | ok: true, | |
| 109 | value: { "plat.sh/site": "vxrail" }, | |
| 110 | }); | |
| 111 | expect(parseTolerations("plat.sh/site=vxrail:NoSchedule")).toEqual({ | |
| 112 | ok: true, | |
| 113 | value: SETTINGS.tolerations as never, | |
| 114 | }); | |
| 115 | expect(parseTolerations("dedicated:NoExecute").ok).toBe(true); | |
| 116 | expect(parseNodeSelector("a=b c").ok).toBe(false); | |
| 117 | expect(parseNodeSelector("nokey").ok).toBe(false); | |
| 118 | expect(parseTolerations("plat.sh/site=vxrail").ok).toBe(false); | |
| 119 | expect(parseTolerations("x=y:Sometimes").ok).toBe(false); | |
| 120 | }); | |
| 121 | ||
| 122 | test("settings need an image and a namespace; without them the check runs as a process", () => { | |
| 123 | expect(jobSettings({}, "http://f", "/nonexistent").ok).toBe(false); | |
| 124 | expect( | |
| 125 | jobSettings({ FORGE_JOB_IMAGE: "img:1" }, "http://f", "/nonexistent").ok, | |
| 126 | ).toBe(false); | |
| 127 | expect( | |
| 128 | jobSettings( | |
| 129 | { FORGE_JOB_IMAGE: "img:1; rm -rf /", FORGE_JOB_NAMESPACE: "ns" }, | |
| 130 | "http://f", | |
| 131 | ).ok, | |
| 132 | ).toBe(false); | |
| 133 | const good = jobSettings( | |
| 134 | { | |
| 135 | FORGE_JOB_IMAGE: "img:1", | |
| 136 | FORGE_JOB_NAMESPACE: "ns", | |
| 137 | FORGE_JOB_NODE_SELECTOR: "plat.sh/site=vxrail", | |
| 138 | FORGE_JOB_TOLERATIONS: "plat.sh/site=vxrail:NoSchedule", | |
| 139 | }, | |
| 140 | "http://forge/", | |
| 141 | ); | |
| 142 | expect(good.ok && good.value.forgeUrl).toBe("http://forge"); | |
| 143 | }); | |
| 144 | ||
| 145 | test("every way a Job ends: exited, past its deadline, or vanished — never still waiting once it is gone", () => { | |
| 146 | const running = { complete: false, failed: undefined }; | |
| 147 | const pod = (over: object) => ({ | |
| 148 | node: "vxrail-1", | |
| 149 | phase: "Running", | |
| 150 | reason: "", | |
| 151 | ...over, | |
| 152 | }); | |
| 153 | expect(judge(running, pod({}))).toBeUndefined(); | |
| 154 | expect(judge(running, undefined)).toBeUndefined(); | |
| 155 | expect( | |
| 156 | judge(running, pod({ terminated: { code: 1, reason: "Error" } })), | |
| 157 | ).toEqual({ kind: "exited", code: 1, reason: "Error" }); | |
| 158 | expect(judge({ complete: true, failed: undefined }, undefined)).toEqual({ | |
| 159 | kind: "exited", | |
| 160 | code: 0, | |
| 161 | reason: "Completed", | |
| 162 | }); | |
| 163 | expect(judge({ complete: false, failed: "DeadlineExceeded" }, undefined)).toEqual({ | |
| 164 | kind: "deadline", | |
| 165 | }); | |
| 166 | expect(judge("gone", undefined)?.kind).toBe("vanished"); | |
| 167 | expect(judge(running, pod({ phase: "Failed", reason: "Evicted" }))?.kind).toBe( | |
| 168 | "vanished", | |
| 169 | ); | |
| 170 | expect( | |
| 171 | judge({ complete: false, failed: "BackoffLimitExceeded" }, undefined)?.kind, | |
| 172 | ).toBe("vanished"); | |
| 173 | expect(judge(running, pod({ phase: "Unknown" }))?.kind).toBe("vanished"); | |
| 174 | }); | |
| 175 | }); | |
| 176 | ||
| 177 | describe("the door a Job fetches its checkout through", () => { | |
| 178 | let dataDir: string; | |
| 179 | beforeAll(async () => { | |
| 180 | dataDir = await mkdtemp(join(tmpdir(), "forge-lane-token-")); | |
| 181 | }); | |
| 182 | afterAll(async () => { | |
| 183 | await rm(dataDir, { recursive: true, force: true }); | |
| 184 | }); | |
| 185 | ||
| 186 | test("a token opens one checkout until it expires, and nothing else", () => { | |
| 187 | const token = treeToken(dataDir, "run-a", Date.now() + 60_000); | |
| 188 | expect(treeTokenValid(dataDir, "run-a", token)).toBe(true); | |
| 189 | expect(treeTokenValid(dataDir, "run-b", token)).toBe(false); | |
| 190 | expect(treeTokenValid(dataDir, "run-a", token, Date.now() + 120_000)).toBe( | |
| 191 | false, | |
| 192 | ); | |
| 193 | const [expiry, mac] = token.split("."); | |
| 194 | expect( | |
| 195 | treeTokenValid(dataDir, "run-a", `${Number(expiry) + 3600}.${mac}`), | |
| 196 | ).toBe(false); | |
| 197 | expect(treeTokenValid(dataDir, "run-a", "")).toBe(false); | |
| 198 | expect(treeTokenValid(dataDir, "../etc", token)).toBe(false); | |
| 199 | }); | |
| 200 | }); | |
| 201 | ||
| 202 | /** | |
| 203 | * A cluster that runs each Job's lane right here: the manifest's own | |
| 204 | * command and environment, the checkout fetched over HTTP with the token | |
| 205 | * the forge minted, the log handed back line by line. | |
| 206 | */ | |
| 207 | function standInCluster(mode: { vanish: boolean; refuse?: boolean }) { | |
| 208 | const created: JobManifest[] = []; | |
| 209 | const running = new Map<string, { lines: string[]; end: Promise<JobEnd> }>(); | |
| 210 | const removed: string[] = []; | |
| 211 | const client: JobClient = { | |
| 212 | async create(manifest) { | |
| 213 | created.push(manifest); | |
| 214 | if (mode.refuse) return { ok: false, error: "exceeded quota: lane" }; | |
| 215 | const [container] = podOf(manifest).spec.containers; | |
| 216 | const env = Object.fromEntries( | |
| 217 | container!.env.map((e) => [e.name, e.value]), | |
| 218 | ); | |
| 219 | const lines: string[] = []; | |
| 220 | const end = mode.vanish | |
| 221 | ? Promise.resolve<JobEnd>({ | |
| 222 | kind: "vanished", | |
| 223 | reason: "its pod was evicted on vxrail-1", | |
| 224 | }) | |
| 225 | : (async (): Promise<JobEnd> => { | |
| 226 | const work = await mkdtemp(join(tmpdir(), "forge-lane-")); | |
| 227 | try { | |
| 228 | const code = await runLane( | |
| 229 | { ...env, FORGE_LANE_WORK: work }, | |
| 230 | (line) => lines.push(line), | |
| 231 | ); | |
| 232 | return { kind: "exited", code, reason: code === 0 ? "Completed" : "Error" }; | |
| 233 | } finally { | |
| 234 | await rm(work, { recursive: true, force: true }); | |
| 235 | } | |
| 236 | })(); | |
| 237 | running.set(manifest.metadata.name, { lines, end }); | |
| 238 | return { ok: true, value: undefined }; | |
| 239 | }, | |
| 240 | async wait(name, _signal, onPlaced) { | |
| 241 | const job = running.get(name); | |
| 242 | if (!job) return { kind: "vanished", reason: "the Job is gone" }; | |
| 243 | onPlaced("vxrail-1"); | |
| 244 | return job.end; | |
| 245 | }, | |
| 246 | async logs(name, onLine) { | |
| 247 | const job = running.get(name); | |
| 248 | if (!job) return; | |
| 249 | await job.end; | |
| 250 | for (const line of job.lines) onLine(line); | |
| 251 | }, | |
| 252 | async remove(name) { | |
| 253 | removed.push(name); | |
| 254 | running.delete(name); | |
| 255 | }, | |
| 256 | }; | |
| 257 | return { client, created, removed }; | |
| 258 | } | |
| 259 | ||
| 260 | describe("a check placed as a Job", () => { | |
| 261 | let dataDir: string; | |
| 262 | let app: App; | |
| 263 | let servers: Servers; | |
| 264 | let checks: ChecksHandle | undefined; | |
| 265 | let alice: User; | |
| 266 | let repo: Repo; | |
| 267 | let n = 0; | |
| 268 | ||
| 269 | async function settled(where: (run: Run) => boolean): Promise<Run> { | |
| 270 | const deadline = Date.now() + 30_000; | |
| 271 | while (Date.now() < deadline) { | |
| 272 | const run = listRuns(app.db, repo.id, { kind: "check", limit: 50 }).find( | |
| 273 | where, | |
| 274 | ); | |
| 275 | if (run && (run.state === "ok" || run.state === "failed")) return run; | |
| 276 | await Bun.sleep(50); | |
| 277 | } | |
| 278 | throw new Error("check did not settle"); | |
| 279 | } | |
| 280 | ||
| 281 | async function push(run: string, extra: Record<string, string> = {}) { | |
| 282 | n += 1; | |
| 283 | const pushed = await commitToBranch(app, alice, repo, { | |
| 284 | message: `Check ${n}`, | |
| 285 | files: [ | |
| 286 | { | |
| 287 | path: "forge.json", | |
| 288 | content: `{"check": {"run": ${JSON.stringify(run)}, "install": ""}}\n`, | |
| 289 | }, | |
| 290 | { path: "N.md", content: `${n}\n` }, | |
| 291 | ...Object.entries(extra).map(([path, content]) => ({ path, content })), | |
| 292 | ], | |
| 293 | }); | |
| 294 | if (!pushed.ok) throw new Error(JSON.stringify(pushed.error)); | |
| 295 | return pushed.value.commitOid; | |
| 296 | } | |
| 297 | ||
| 298 | async function useCluster(mode: { vanish: boolean; refuse?: boolean }) { | |
| 299 | // One checks service at a time, so a run is picked up by this test's cluster. | |
| 300 | await checks?.stop(); | |
| 301 | const cluster = standInCluster(mode); | |
| 302 | checks = startChecks(app, { | |
| 303 | forgeUrl: servers.url, | |
| 304 | concurrency: 2, | |
| 305 | jobs: { | |
| 306 | client: cluster.client, | |
| 307 | settings: { ...SETTINGS, forgeUrl: servers.url }, | |
| 308 | }, | |
| 309 | }); | |
| 310 | return cluster; | |
| 311 | } | |
| 312 | ||
| 313 | beforeAll(async () => { | |
| 314 | dataDir = await mkdtemp(join(tmpdir(), "forge-checks-job-")); | |
| 315 | app = createApp({ dataDir, port: 0 }); | |
| 316 | servers = await serve(app); | |
| 317 | const a = await createUser(app.db, { | |
| 318 | trusted: true, | |
| 319 | username: "alice", | |
| 320 | email: "[email protected]", | |
| 321 | password: "a-good-passphrase", | |
| 322 | adminIfFirst: true, | |
| 323 | }); | |
| 324 | if (!a.ok) throw new Error(a.error); | |
| 325 | alice = a.value; | |
| 326 | const made = await createRepo(app, alice, { name: "lib", visibility: "public" }); | |
| 327 | if (!made.ok) throw new Error(String(made.error)); | |
| 328 | repo = made.value; | |
| 329 | // `job` placement waits for declared-host egress in the pod; until then | |
| 330 | // it is refused while cells.egress is enforce (its own test, below). | |
| 331 | }); | |
| 332 | ||
| 333 | afterAll(async () => { | |
| 334 | await checks?.stop(); | |
| 335 | servers.stop(); | |
| 336 | app.close(); | |
| 337 | await rm(dataDir, { recursive: true, force: true }); | |
| 338 | }); | |
| 339 | ||
| 340 | test("the process placement is unchanged: no Job, the run says it ran here", async () => { | |
| 341 | setCapacity(app.db, "checks.placement", null, alice.id); | |
| 342 | const cluster = await useCluster({ vanish: false }); | |
| 343 | const commit = await push("test -f OK.md", { "OK.md": "ok\n" }); | |
| 344 | const run = await settled((r) => r.commitOid === commit); | |
| 345 | expect(run.state).toBe("ok"); | |
| 346 | expect(run.placement).toBe("process"); | |
| 347 | expect(run.node).not.toBe(""); | |
| 348 | expect(cluster.created).toHaveLength(0); | |
| 349 | const page = await (await fetch(`${servers.url}/alice/lib/runs/${run.id}`)).text(); | |
| 350 | expect(page).toContain(`Ran as a child of the forge on ${run.node}.`); | |
| 351 | }, 60_000); | |
| 352 | ||
| 353 | test("placed as a Job, a check fetches its checkout, runs to a verdict, and its log comes home", async () => { | |
| 354 | setCapacity(app.db, "checks.placement", "job", alice.id); | |
| 355 | setCapacity(app.db, "cells.egress", "report", alice.id); | |
| 356 | const cluster = await useCluster({ vanish: false }); | |
| 357 | const commit = await push("cat OK.md && echo from-the-lane", { "OK.md": "here\n" }); | |
| 358 | const run = await settled((r) => r.commitOid === commit); | |
| 359 | expect(run.state).toBe("ok"); | |
| 360 | expect(run.placement).toBe("job"); | |
| 361 | expect(run.node).toBe("vxrail-1"); | |
| 362 | expect(cluster.created).toHaveLength(1); | |
| 363 | expect(cluster.removed).toEqual([cluster.created[0]!.metadata.name]); | |
| 364 | const log = readRunLog(dataDir, run.id).lines.join("\n"); | |
| 365 | expect(log).toContain("placed as a Job"); | |
| 366 | expect(log).toContain("running on vxrail-1"); | |
| 367 | expect(log).toContain("from-the-lane"); | |
| 368 | expect(log).not.toContain("::forge-lane::"); | |
| 369 | // Where it ran is said on the run, to the page and to the API. | |
| 370 | const page = await fetch(`${servers.url}/alice/lib/runs/${run.id}`); | |
| 371 | expect(await page.text()).toContain("Ran as a Job on vxrail-1."); | |
| 372 | const api = (await ( | |
| 373 | await fetch(`${servers.url}/api/v1/repos/alice/lib/runs/${run.id}`) | |
| 374 | ).json()) as { placement: string; node: string }; | |
| 375 | expect(api).toMatchObject({ placement: "job", node: "vxrail-1" }); | |
| 376 | // The checkout is gone with the check: the token opens nothing now. | |
| 377 | const token = podOf(cluster.created[0]!) | |
| 378 | .spec.containers[0]!.env.find((e) => e.name === "FORGE_LANE_TOKEN")!.value; | |
| 379 | const late = await fetch(`${servers.url}/-/lane/${run.id}/tree`, { | |
| 380 | headers: { authorization: `Bearer ${token}` }, | |
| 381 | }); | |
| 382 | expect(late.status).toBe(404); | |
| 383 | }, 60_000); | |
| 384 | ||
| 385 | test("a failing check in a Job fails with the same words a process gives", async () => { | |
| 386 | setCapacity(app.db, "checks.placement", "job", alice.id); | |
| 387 | setCapacity(app.db, "cells.egress", "report", alice.id); | |
| 388 | const cluster = await useCluster({ vanish: false }); | |
| 389 | const commit = await push("echo nope >&2; exit 3"); | |
| 390 | const run = await settled((r) => r.commitOid === commit); | |
| 391 | expect(run.state).toBe("failed"); | |
| 392 | expect(run.summary).toBe("check failed: nope"); | |
| 393 | expect(cluster.created).toHaveLength(1); | |
| 394 | }, 60_000); | |
| 395 | ||
| 396 | test("a Job that vanishes interrupts the check, which is queued again once — then fails, never hangs", async () => { | |
| 397 | setCapacity(app.db, "checks.placement", "job", alice.id); | |
| 398 | setCapacity(app.db, "cells.egress", "report", alice.id); | |
| 399 | const cluster = await useCluster({ vanish: true }); | |
| 400 | const commit = await push("true"); | |
| 401 | const last = await settled((r) => r.commitOid === commit); | |
| 402 | const all = listRuns(app.db, repo.id, { kind: "check", limit: 50 }).filter( | |
| 403 | (r) => r.commitOid === commit, | |
| 404 | ); | |
| 405 | expect(all).toHaveLength(2); | |
| 406 | const first = all.find((r) => r.id !== last.id)!; | |
| 407 | expect(first.state).toBe("cancelled"); | |
| 408 | expect(first.summary).toBe(VANISHED_SUMMARY); | |
| 409 | expect(last.state).toBe("failed"); | |
| 410 | expect(last.attempt).toBe(1); | |
| 411 | expect(last.summary).toContain("its Job vanished"); | |
| 412 | expect(cluster.created).toHaveLength(2); | |
| 413 | }, 60_000); | |
| 414 | ||
| 415 | test("while egress is enforced, job placement is refused with the reason and the check runs here", async () => { | |
| 416 | setCapacity(app.db, "checks.placement", "job", alice.id); | |
| 417 | setCapacity(app.db, "cells.egress", null, alice.id); | |
| 418 | const cluster = await useCluster({ vanish: false }); | |
| 419 | const commit = await push("test -f OK.md", { "OK.md": "ok\n" }); | |
| 420 | const run = await settled((r) => r.commitOid === commit); | |
| 421 | expect(run.state).toBe("ok"); | |
| 422 | expect(run.placement).toBe("process"); | |
| 423 | expect(cluster.created).toHaveLength(0); | |
| 424 | const log = readRunLog(dataDir, run.id).lines.join("\n"); | |
| 425 | expect(log).toContain("job placement unavailable: cells.egress is enforce"); | |
| 426 | }, 60_000); | |
| 427 | ||
| 428 | test("a Job the cluster refuses is the cluster's fault: queued again once, then failed saying so", async () => { | |
| 429 | setCapacity(app.db, "checks.placement", "job", alice.id); | |
| 430 | setCapacity(app.db, "cells.egress", "report", alice.id); | |
| 431 | const cluster = await useCluster({ vanish: false, refuse: true }); | |
| 432 | const commit = await push("true"); | |
| 433 | const last = await settled((r) => r.commitOid === commit); | |
| 434 | const all = listRuns(app.db, repo.id, { kind: "check", limit: 50 }).filter( | |
| 435 | (r) => r.commitOid === commit, | |
| 436 | ); | |
| 437 | expect(all).toHaveLength(2); | |
| 438 | expect(all.find((r) => r.id !== last.id)!.summary).toBe(VANISHED_SUMMARY); | |
| 439 | expect(last.state).toBe("failed"); | |
| 440 | expect(last.summary).toContain("the cluster refused its Job: exceeded quota"); | |
| 441 | expect(cluster.created).toHaveLength(2); | |
| 442 | }, 60_000); | |
| 443 | }); |
This selects
app.kubernetes.io/name: forge, but the chart's pods are labelledapp: <release>(and lane.yaml uses that). Anyone who copies this policy blocks the lane from reaching the forge, so every tree fetch fails with exit 2. Use the label the deployment actually sets.