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 #1429
mason/forge:mason/1423-checks-and-crew-runs-as-cluster-jobs-on → main 6 commits fork
15 files
changed +1573
−38
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 |
charts/app/templates/deployment.yaml +20
| @@ -37,6 +37,9 @@ spec: | ||
| 37 | 37 | # The crew drains for three minutes, then runs are cut and resume on |
| 38 | 38 | # the next pod; a little more than that here. |
| 39 | 39 | terminationGracePeriodSeconds: 300 |
| 40 | {{- if .Values.lane.enabled }} | |
| 41 | serviceAccountName: {{ .Release.Name }} | |
| 42 | {{- end }} | |
| 40 | 43 | {{- with .Values.imagePullSecrets }} |
| 41 | 44 | imagePullSecrets: |
| 42 | 45 | {{- toYaml . | nindent 8 }} |
| @@ -115,6 +118,23 @@ spec: | ||
| 115 | 118 | - name: FORGE_SSH_PORT |
| 116 | 119 | value: "0" |
| 117 | 120 | {{- end }} |
| 121 | {{- if .Values.lane.enabled }} | |
| 122 | # Where a check placed as a Job runs, and how it reaches back. | |
| 123 | - name: FORGE_JOB_IMAGE | |
| 124 | value: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}" | |
| 125 | - name: FORGE_JOB_FORGE_URL | |
| 126 | value: "http://{{ .Release.Name }}.{{ .Release.Namespace }}.svc:{{ .Values.service.port }}" | |
| 127 | - name: FORGE_JOB_NODE_SELECTOR | |
| 128 | value: {{ .Values.lane.nodeSelector | quote }} | |
| 129 | - name: FORGE_JOB_TOLERATIONS | |
| 130 | value: {{ .Values.lane.tolerations | quote }} | |
| 131 | - name: FORGE_JOB_PULL_SECRETS | |
| 132 | value: "{{ range $i, $s := .Values.imagePullSecrets }}{{ if $i }},{{ end }}{{ $s.name }}{{ end }}" | |
| 133 | {{- end }} | |
| 134 | - name: NODE_NAME | |
| 135 | valueFrom: | |
| 136 | fieldRef: | |
| 137 | fieldPath: spec.nodeName | |
| 118 | 138 | {{- with .Values.extraEnvFrom }} |
| 119 | 139 | envFrom: |
| 120 | 140 | {{- toYaml . | nindent 12 }} |
charts/app/templates/lane.yaml added +64
| @@ -0,0 +1,64 @@ | ||
| 1 | {{- if .Values.lane.enabled }} | |
| 2 | # The lane (#1423, docs/CLUSTER.md): checks placed as Jobs. The forge's | |
| 3 | # service account may create, watch and delete Jobs and read their pods' | |
| 4 | # logs in this namespace, and nothing more. | |
| 5 | apiVersion: v1 | |
| 6 | kind: ServiceAccount | |
| 7 | metadata: | |
| 8 | name: {{ .Release.Name }} | |
| 9 | ||
| 10 | apiVersion: rbac.authorization.k8s.io/v1 | |
| 11 | kind: Role | |
| 12 | metadata: | |
| 13 | name: {{ .Release.Name }}-lane | |
| 14 | rules: | |
| 15 | - apiGroups: ["batch"] | |
| 16 | resources: ["jobs"] | |
| 17 | verbs: ["create", "get", "list", "watch", "delete"] | |
| 18 | - apiGroups: [""] | |
| 19 | resources: ["pods"] | |
| 20 | verbs: ["get", "list"] | |
| 21 | - apiGroups: [""] | |
| 22 | resources: ["pods/log"] | |
| 23 | verbs: ["get"] | |
| 24 | ||
| 25 | apiVersion: rbac.authorization.k8s.io/v1 | |
| 26 | kind: RoleBinding | |
| 27 | metadata: | |
| 28 | name: {{ .Release.Name }}-lane | |
| 29 | roleRef: | |
| 30 | apiGroup: rbac.authorization.k8s.io | |
| 31 | kind: Role | |
| 32 | name: {{ .Release.Name }}-lane | |
| 33 | subjects: | |
| 34 | - kind: ServiceAccount | |
| 35 | name: {{ .Release.Name }} | |
| 36 | ||
| 37 | # A Job reaches DNS, the forge, and the public internet on 80 and 443; | |
| 38 | # nothing private. Looser than a cell: no per-host allow-list yet. | |
| 39 | apiVersion: networking.k8s.io/v1 | |
| 40 | kind: NetworkPolicy | |
| 41 | metadata: | |
| 42 | name: {{ .Release.Name }}-lane | |
| 43 | spec: | |
| 44 | podSelector: | |
| 45 | matchLabels: | |
| 46 | forge.plat.sh/lane: check | |
| 47 | policyTypes: [Ingress, Egress] | |
| 48 | ingress: [] | |
| 49 | egress: | |
| 50 | - ports: | |
| 51 | - { protocol: UDP, port: 53 } | |
| 52 | - { protocol: TCP, port: 53 } | |
| 53 | - to: | |
| 54 | - podSelector: | |
| 55 | matchLabels: | |
| 56 | app: {{ .Release.Name }} | |
| 57 | - to: | |
| 58 | - ipBlock: | |
| 59 | cidr: 0.0.0.0/0 | |
| 60 | 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] | |
| 61 | ports: | |
| 62 | - { protocol: TCP, port: 80 } | |
| 63 | - { protocol: TCP, port: 443 } | |
| 64 | {{- end }} |
charts/app/values.yaml +8
| @@ -61,6 +61,14 @@ resources: | ||
| 61 | 61 | cpu: "4" |
| 62 | 62 | memory: 4Gi |
| 63 | 63 | |
| 64 | # Checks as cluster Jobs (#1423, docs/CLUSTER.md). Enabling this grants the | |
| 65 | # forge its narrow Role and tells it where Jobs go; `checks.placement` on the | |
| 66 | # Capacity page (or FORGE_CHECKS_PLACEMENT) is what moves checks there. | |
| 67 | lane: | |
| 68 | enabled: false | |
| 69 | nodeSelector: "plat.sh/site=vxrail" | |
| 70 | tolerations: "plat.sh/site=vxrail:NoSchedule" | |
| 71 | ||
| 64 | 72 | # Appended by the platform: self-serve secrets, and whatever else it grants. |
| 65 | 73 | extraEnvFrom: [] |
| 66 | 74 | # Bumped by the platform when self-serve secrets change, to roll the pod. |
docs/CLUSTER.md added +103
| @@ -0,0 +1,103 @@ | ||
| 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 | When a forge cannot start Jobs (no `FORGE_JOB_IMAGE`, not in a cluster, a | |
| 31 | setting that does not parse), the check runs as a process. Its log says why. | |
| 32 | ||
| 33 | ## Settings (the forge's environment) | |
| 34 | ||
| 35 | | Variable | Meaning | | |
| 36 | | --- | --- | | |
| 37 | | `FORGE_JOB_IMAGE` | The image a Job runs. Set it to the forge's own image and tag. Required. | | |
| 38 | | `FORGE_JOB_NAMESPACE` | Where Jobs are created. Default: the service account's namespace. | | |
| 39 | | `FORGE_JOB_FORGE_URL` | The origin a Job uses to reach the forge, e.g. `http://forge.trevato-apps.svc`. Default: `FORGE_URL`. | | |
| 40 | | `FORGE_JOB_NODE_SELECTOR` | `key=value,…`, e.g. `plat.sh/site=vxrail`. | | |
| 41 | | `FORGE_JOB_TOLERATIONS` | `key=value:Effect,…` or `key:Effect`, e.g. `plat.sh/site=vxrail:NoSchedule`. | | |
| 42 | | `FORGE_JOB_PULL_SECRETS` | `name,…`: the secrets that pull a private image, e.g. `forgejo-registry`. | | |
| 43 | | `NODE_NAME` | Optional, via the downward API (`spec.nodeName`): the node a process-placed run records. | | |
| 44 | ||
| 45 | ## What the cluster grants (deployment side) | |
| 46 | ||
| 47 | The forge's ServiceAccount needs a Role in its own namespace. It needs nothing | |
| 48 | more: | |
| 49 | ||
| 50 | yaml | |
| 51 | apiVersion: rbac.authorization.k8s.io/v1 | |
| 52 | kind: Role | |
| 53 | metadata: { name: forge-lane } | |
| 54 | rules: | |
| 55 | - apiGroups: ["batch"] | |
| 56 | resources: ["jobs"] | |
| 57 | verbs: ["create", "get", "list", "watch", "delete"] | |
| 58 | - apiGroups: [""] | |
| 59 | resources: ["pods"] | |
| 60 | verbs: ["get", "list"] | |
| 61 | - apiGroups: [""] | |
| 62 | resources: ["pods/log"] | |
| 63 | verbs: ["get"] | |
| 64 | ||
| 65 | apiVersion: rbac.authorization.k8s.io/v1 | |
| 66 | kind: RoleBinding | |
| 67 | metadata: { name: forge-lane } | |
| 68 | roleRef: { apiGroup: rbac.authorization.k8s.io, kind: Role, name: forge-lane } | |
| 69 | subjects: [{ kind: ServiceAccount, name: forge }] | |
| 70 | ||
| 71 | ||
| 72 | A Job's pod carries the label `forge.plat.sh/lane: check`. The pod runs as uid | |
| 73 | 1000 without privilege escalation, drops every capability, has a read-only root | |
| 74 | and no service account token, and writes only to an `emptyDir` sized to the | |
| 75 | check's disk limit. Its requests and limits are the cell's limits | |
| 76 | (`resolveLimits("step", check.limits)`). | |
| 77 | ||
| 78 | Egress is a NetworkPolicy, which speaks addresses, not host names. It lets the | |
| 79 | lane reach DNS, the forge, and the public internet on 80/443, and nothing | |
| 80 | private: | |
| 81 | ||
| 82 | yaml | |
| 83 | apiVersion: networking.k8s.io/v1 | |
| 84 | kind: NetworkPolicy | |
| 85 | metadata: { name: forge-lane } | |
| 86 | spec: | |
| 87 | podSelector: { matchLabels: { forge.plat.sh/lane: check } } | |
| 88 | policyTypes: [Ingress, Egress] | |
| 89 | ingress: [] | |
| 90 | egress: | |
| 91 | - ports: [{ protocol: UDP, port: 53 }, { protocol: TCP, port: 53 }] | |
| 92 | - to: [{ podSelector: { matchLabels: { app.kubernetes.io/name: forge } } }] | |
| 93 | - to: | |
| 94 | - ipBlock: | |
| 95 | cidr: 0.0.0.0/0 | |
| 96 | 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] | |
| 97 | ports: [{ protocol: TCP, port: 80 }, { protocol: TCP, port: 443 }] | |
| 98 | ||
| 99 | ||
| 100 | This is looser than a cell. A cell refuses a host that `forge.json` did not | |
| 101 | declare. A Job refuses private addresses and every port except 80 and 443. | |
| 102 | Holding a Job to declared hosts needs an egress proxy in the pod, and that is | |
| 103 | still to come. |
scripts/gate.ts +1
| @@ -81,6 +81,7 @@ export const GATE: readonly string[] = [ | ||
| 81 | 81 | "test/capacity.test.ts", |
| 82 | 82 | "test/guard-new-accounts.test.ts", |
| 83 | 83 | "test/checks.test.ts", |
| 84 | "test/checks-job.test.ts", | |
| 84 | 85 | "test/dependencies.test.ts", |
| 85 | 86 | "test/map-closing.test.ts", |
| 86 | 87 | "test/autonomy.test.ts", |
src/checks/service.ts +212 −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"; |
| @@ -32,6 +32,8 @@ import { | ||
| 32 | 32 | requeueCheck, |
| 33 | 33 | REQUEUED_SUMMARY, |
| 34 | 34 | sweepAbandonedChecks, |
| 35 | VANISHED_SUMMARY, | |
| 36 | vanishedBefore, | |
| 35 | 37 | type Run, |
| 36 | 38 | } from "../core/runs.ts"; |
| 37 | 39 | import { Gate } from "../git/env.ts"; |
| @@ -54,6 +56,7 @@ import { | ||
| 54 | 56 | capacityCount, |
| 55 | 57 | noteBooted, |
| 56 | 58 | capacityEnv, |
| 59 | checksPlacement, | |
| 57 | 60 | egressSetting, |
| 58 | 61 | } from "../core/capacity.ts"; |
| 59 | 62 | import { |
| @@ -64,6 +67,19 @@ import { | ||
| 64 | 67 | } from "../apps/contain.ts"; |
| 65 | 68 | import { summariseCheckFailure } from "./summary.ts"; |
| 66 | 69 | import type { CheckDetail } from "../core/runs.ts"; |
| 70 | import { | |
| 71 | inClusterAccess, | |
| 72 | JOB_WORK, | |
| 73 | jobManifest, | |
| 74 | jobName, | |
| 75 | jobSettings, | |
| 76 | kubeJobs, | |
| 77 | type JobClient, | |
| 78 | type JobSettings, | |
| 79 | } from "../cluster/jobs.ts"; | |
| 80 | import { LANE_MARK } from "../cluster/lane.ts"; | |
| 81 | import { checksRoot, treeToken } from "../cluster/tree.ts"; | |
| 82 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 67 | 83 | |
| 68 | 84 | const log = createLog("checks"); |
| 69 | 85 | |
| @@ -72,8 +88,24 @@ export interface ChecksOptions { | ||
| 72 | 88 | readonly concurrency?: number | undefined; |
| 73 | 89 | /** The forge's public URL, told to the check as `FORGE_URL`. */ |
| 74 | 90 | readonly forgeUrl: string; |
| 91 | /** | |
| 92 | * The cluster a check placed as a Job runs on (#1423). Absent: the | |
| 93 | * forge's own, over its service account, where `FORGE_JOB_*` says. | |
| 94 | */ | |
| 95 | readonly jobs?: { client: JobClient; settings: JobSettings } | undefined; | |
| 75 | 96 | } |
| 76 | 97 | |
| 98 | /** How a check ended: passed, failed with the reason, or cut off by its Job vanishing. */ | |
| 99 | type Outcome = | |
| 100 | | { ok: true } | |
| 101 | | { | |
| 102 | ok: false; | |
| 103 | error: string; | |
| 104 | detail?: CheckDetail | undefined; | |
| 105 | /** Its Job vanished: never the commit's fault (#1423). */ | |
| 106 | vanished?: true; | |
| 107 | }; | |
| 108 | ||
| 77 | 109 | export interface ChecksHandle { |
| 78 | 110 | /** Ask for a check of one commit; the answer is the run, or nothing when the commit declares no check. */ |
| 79 | 111 | request( |
| @@ -161,9 +193,6 @@ export function requeueAbandonedChecks(app: App, staleMs: number): number { | ||
| 161 | 193 | return swept.requeued.length + swept.failed.length + swept.cancelled.length; |
| 162 | 194 | } |
| 163 | 195 | |
| 164 | /** Where a check's checkout lives while it runs. */ | |
| 165 | const checksRoot = (dataDir: string): string => join(dataDir, "checks"); | |
| 166 | ||
| 167 | 196 | const handles = new WeakMap<App, ChecksHandle>(); |
| 168 | 197 | |
| 169 | 198 | /** The checks service of this forge, if one was started. */ |
| @@ -366,6 +395,16 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle { | ||
| 366 | 395 | announceRun(app, moved.again, run.actorId ?? undefined); |
| 367 | 396 | return; |
| 368 | 397 | } |
| 398 | // A Job that vanished is the cluster's doing, not the commit's: the | |
| 399 | // check is queued again, once (#1423). | |
| 400 | if (!outcome.ok && outcome.vanished && !vanishedBefore(app.db, claimed)) { | |
| 401 | const moved = requeueCheck(app.db, run.id, undefined, VANISHED_SUMMARY); | |
| 402 | if (moved) { | |
| 403 | write(`${outcome.error}; queued again`); | |
| 404 | announceRun(app, moved.again, run.actorId ?? undefined); | |
| 405 | return; | |
| 406 | } | |
| 407 | } | |
| 369 | 408 | const seconds = Math.round((Date.now() - started) / 1000); |
| 370 | 409 | const done = finishRun(app.db, run.id, { |
| 371 | 410 | state: outcome.ok ? "ok" : "failed", |
| @@ -388,10 +427,7 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle { | ||
| 388 | 427 | repo: Repo, |
| 389 | 428 | write: (line: string) => void, |
| 390 | 429 | signal: AbortSignal, |
| 391 | ): Promise< | |
| 392 | | { ok: true } | |
| 393 | | { ok: false; error: string; detail?: CheckDetail | undefined } | |
| 394 | > { | |
| 430 | ): Promise<Outcome> { | |
| 395 | 431 | const bare = await runDir(app.db, app.reposRoot, repo, run.issueId); |
| 396 | 432 | // A pull's check is the fast tier, judged against where the pull left |
| 397 | 433 | // the base; anything else is the whole check (`apps/manifest.ts`). |
| @@ -427,12 +463,7 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle { | ||
| 427 | 463 | readonly signal: AbortSignal; |
| 428 | 464 | } |
| 429 | 465 | |
| 430 | async function runTier( | |
| 431 | x: Execution, | |
| 432 | ): Promise< | |
| 433 | | { ok: true } | |
| 434 | | { ok: false; error: string; detail?: CheckDetail | undefined } | |
| 435 | > { | |
| 466 | async function runTier(x: Execution): Promise<Outcome> { | |
| 436 | 467 | const { bare, repo, write, signal } = x; |
| 437 | 468 | // A pull's fast check is of the pull as it would land: its head merged |
| 438 | 469 | // into the base's tip. The gate comes from that tree, so a pull forked |
| @@ -523,6 +554,53 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle { | ||
| 523 | 554 | return { ok: false, error: given.error }; |
| 524 | 555 | } |
| 525 | 556 | } |
| 557 | const env = childEnv({ | |
| 558 | // The shard count an admin set (`core/capacity.ts`), never the pod's. | |
| 559 | ...capacityEnv(app.db), | |
| 560 | CI: "1", | |
| 561 | FORGE_URL: options.forgeUrl, | |
| 562 | FORGE_CHECK: run.id, | |
| 563 | FORGE_COMMIT: x.commitOid, | |
| 564 | ...(base === undefined | |
| 565 | ? {} | |
| 566 | : { | |
| 567 | FORGE_CHECK_BASE: base, | |
| 568 | FORGE_CHECK_LEARNED: readLearned( | |
| 569 | app.config.dataDir, | |
| 570 | x.pull!.id, | |
| 571 | ).join(","), | |
| 572 | }), | |
| 573 | // A cell inside a cell is not a cell. This check's own cell is the | |
| 574 | // boundary; a forge the tests boot inside it would wrap its apps in | |
| 575 | // nested cells, and those never answer in time. Its children run as | |
| 576 | // plain processes here — as they do on a runner without bwrap. | |
| 577 | FORGE_CELLS: "off", | |
| 578 | }); | |
| 579 | // Placed as a Job on the cluster when the forge says so and can (#1423); | |
| 580 | // a forge that cannot says why and runs the check here, as before. | |
| 581 | if (checksPlacement(app.db) === "job") { | |
| 582 | const cluster = lane(); | |
| 583 | if (cluster.ok) { | |
| 584 | try { | |
| 585 | return await runInJob(x, cluster.value, { | |
| 586 | dir, | |
| 587 | env, | |
| 588 | install: manifest.install, | |
| 589 | command, | |
| 590 | timeoutSeconds: manifest.timeout, | |
| 591 | limits: resolveLimits("step", manifest.limits), | |
| 592 | }); | |
| 593 | } finally { | |
| 594 | rmSync(dir, { recursive: true, force: true }); | |
| 595 | } | |
| 596 | } | |
| 597 | write(`job placement unavailable: ${cluster.error}; the check runs here`); | |
| 598 | } | |
| 599 | if (x.runId !== undefined) | |
| 600 | noteRunProgress(app.db, x.runId, { | |
| 601 | placement: "process", | |
| 602 | node: process.env["NODE_NAME"] || hostname(), | |
| 603 | }); | |
| 526 | 604 | // The check is repository code: it runs in a cell of its own |
| 527 | 605 | // (`apps/contain.ts`), its checkout and a home its only places to write, |
| 528 | 606 | // the forge, the registry and what it declared its only way out. |
| @@ -549,28 +627,6 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle { | ||
| 549 | 627 | } |
| 550 | 628 | : undefined; |
| 551 | 629 | try { |
| 552 | const env = childEnv({ | |
| 553 | // The shard count an admin set (`core/capacity.ts`), never the pod's. | |
| 554 | ...capacityEnv(app.db), | |
| 555 | CI: "1", | |
| 556 | FORGE_URL: options.forgeUrl, | |
| 557 | FORGE_CHECK: run.id, | |
| 558 | FORGE_COMMIT: x.commitOid, | |
| 559 | ...(base === undefined | |
| 560 | ? {} | |
| 561 | : { | |
| 562 | FORGE_CHECK_BASE: base, | |
| 563 | FORGE_CHECK_LEARNED: readLearned( | |
| 564 | app.config.dataDir, | |
| 565 | x.pull!.id, | |
| 566 | ).join(","), | |
| 567 | }), | |
| 568 | // A cell inside a cell is not a cell. This check's own cell is the | |
| 569 | // boundary; a forge the tests boot inside it would wrap its apps in | |
| 570 | // nested cells, and those never answer in time. Its children run as | |
| 571 | // plain processes here — as they do on a runner without bwrap. | |
| 572 | FORGE_CELLS: "off", | |
| 573 | }); | |
| 574 | 630 | if (manifest.install !== null) { |
| 575 | 631 | const installed = await runStep("install", manifest.install, { |
| 576 | 632 | cwd: dir, |
| @@ -615,6 +671,126 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle { | ||
| 615 | 671 | } |
| 616 | 672 | } |
| 617 | 673 | |
| 674 | /** The cluster to place a check on, or why there is none. */ | |
| 675 | function lane(): Result<{ client: JobClient; settings: JobSettings }, string> { | |
| 676 | if (options.jobs !== undefined) return ok(options.jobs); | |
| 677 | const settings = jobSettings(process.env, options.forgeUrl); | |
| 678 | if (!settings.ok) return settings; | |
| 679 | const access = inClusterAccess(settings.value.namespace); | |
| 680 | if (!access.ok) return err(access.error); | |
| 681 | return ok({ client: kubeJobs(access.value), settings: settings.value }); | |
| 682 | } | |
| 683 | ||
| 684 | /** | |
| 685 | * One check as a Job (#1423): the checkout prepared here is fetched by | |
| 686 | * the Job (`cluster/tree.ts`), the steps run there (`cluster/lane.ts`), | |
| 687 | * the pod's log is streamed into the run's log as it comes, and the | |
| 688 | * verdict is how the Job ended. Whatever happens, the Job is deleted. | |
| 689 | */ | |
| 690 | async function runInJob( | |
| 691 | x: Execution, | |
| 692 | cluster: { client: JobClient; settings: JobSettings }, | |
| 693 | step: { | |
| 694 | dir: string; | |
| 695 | env: Record<string, string>; | |
| 696 | install: string | null; | |
| 697 | command: string; | |
| 698 | timeoutSeconds: number; | |
| 699 | limits: ReturnType<typeof resolveLimits>; | |
| 700 | }, | |
| 701 | ): Promise<Outcome> { | |
| 702 | const { client, settings } = cluster; | |
| 703 | // The install step and the check each get the timeout, as they do here. | |
| 704 | const deadlineSeconds = step.timeoutSeconds * 2 + 120; | |
| 705 | const { HOME: _home, TMPDIR: _tmp, ...env } = step.env; | |
| 706 | const manifest = jobManifest( | |
| 707 | { | |
| 708 | lane: "check", | |
| 709 | id: x.id, | |
| 710 | command: ["bun", "/app/src/cluster/lane.ts"], | |
| 711 | limits: step.limits, | |
| 712 | deadlineSeconds, | |
| 713 | env: { | |
| 714 | ...env, | |
| 715 | TMPDIR: "/tmp", | |
| 716 | FORGE_LANE_TREE: `${settings.forgeUrl}/-/lane/${x.id}/tree`, | |
| 717 | FORGE_LANE_TOKEN: treeToken( | |
| 718 | app.config.dataDir, | |
| 719 | x.id, | |
| 720 | Date.now() + deadlineSeconds * 1000, | |
| 721 | ), | |
| 722 | FORGE_LANE_INSTALL: step.install ?? "", | |
| 723 | FORGE_LANE_COMMAND: step.command, | |
| 724 | FORGE_LANE_TIMEOUT_MS: String(step.timeoutSeconds * 1000), | |
| 725 | FORGE_LANE_WORK: JOB_WORK, | |
| 726 | }, | |
| 727 | }, | |
| 728 | settings, | |
| 729 | ); | |
| 730 | const name = jobName("check", x.id); | |
| 731 | if (x.runId !== undefined) | |
| 732 | noteRunProgress(app.db, x.runId, { | |
| 733 | placement: "job", | |
| 734 | sandbox: { enforced: true, note: `a Job on the cluster (${name})` }, | |
| 735 | }); | |
| 736 | x.write(`placed as a Job: ${name}`); | |
| 737 | const created = await client.create(manifest); | |
| 738 | if (!created.ok) return { ok: false, error: created.error }; | |
| 739 | // The lane's own lines say where the check's output starts and why a | |
| 740 | // step failed; every other line is the commands' and goes to the log. | |
| 741 | const checkLines: string[] = []; | |
| 742 | let inCheck = false; | |
| 743 | let sawEcho = false; | |
| 744 | let laneError: string | undefined; | |
| 745 | const onLine = (line: string): void => { | |
| 746 | if (line.startsWith(`${LANE_MARK} `)) { | |
| 747 | const said = line.slice(LANE_MARK.length + 1); | |
| 748 | if (said === "check") inCheck = true; | |
| 749 | else if (said.startsWith("failed ")) laneError = said.slice(7); | |
| 750 | return; | |
| 751 | } | |
| 752 | if (inCheck && sawEcho) checkLines.push(line); | |
| 753 | if (inCheck) sawEcho = true; | |
| 754 | x.write(line); | |
| 755 | }; | |
| 756 | const following = new AbortController(); | |
| 757 | const stopFollowing = (): void => following.abort(); | |
| 758 | x.signal.addEventListener("abort", stopFollowing, { once: true }); | |
| 759 | try { | |
| 760 | const logs = client.logs(name, onLine, following.signal); | |
| 761 | const end = await client.wait(name, x.signal, (node) => { | |
| 762 | x.write(`running on ${node}`); | |
| 763 | if (x.runId !== undefined) noteRunProgress(app.db, x.runId, { node }); | |
| 764 | }); | |
| 765 | // What the pod said last is still on its way: a moment to arrive. | |
| 766 | await Promise.race([logs, Bun.sleep(5_000)]); | |
| 767 | if (x.signal.aborted) return { ok: false, error: "check cancelled" }; | |
| 768 | switch (end.kind) { | |
| 769 | case "vanished": | |
| 770 | return { ok: false, error: `its Job vanished: ${end.reason}`, vanished: true }; | |
| 771 | case "deadline": | |
| 772 | return { | |
| 773 | ok: false, | |
| 774 | error: `check took longer than ${deadlineSeconds}s`, | |
| 775 | }; | |
| 776 | case "exited": { | |
| 777 | if (end.code === 0) return { ok: true }; | |
| 778 | const error = | |
| 779 | end.reason === "OOMKilled" | |
| 780 | ? `check stopped: it went over its memory limit (${step.limits.memoryMiB} MiB)` | |
| 781 | : (laneError ?? `the Job exited with code ${end.code}`); | |
| 782 | if (!inCheck) return { ok: false, error }; | |
| 783 | const { summary, detail } = summariseCheckFailure(checkLines, error); | |
| 784 | return { ok: false, error: summary, detail }; | |
| 785 | } | |
| 786 | } | |
| 787 | } finally { | |
| 788 | following.abort(); | |
| 789 | x.signal.removeEventListener("abort", stopFollowing); | |
| 790 | await client.remove(name); | |
| 791 | } | |
| 792 | } | |
| 793 | ||
| 618 | 794 | // What starts a check: a branch moving, a pull opening, a fork's push |
| 619 | 795 | // moving a pull's head. The commit checked is always the one the pull |
| 620 | 796 | // 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
| @@ -17,6 +17,7 @@ export type CapacityKey = | ||
| 17 | 17 | | "crew.concurrency" |
| 18 | 18 | | "checks.concurrency" |
| 19 | 19 | | "checks.shards" |
| 20 | | "checks.placement" | |
| 20 | 21 | | "cells.egress" |
| 21 | 22 | | "guard_new_accounts"; |
| 22 | 23 | |
| @@ -56,6 +57,13 @@ export const CAPACITY: Record<CapacityKey, Definition> = { | ||
| 56 | 57 | fallback: "", |
| 57 | 58 | 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.", |
| 58 | 59 | }, |
| 60 | "checks.placement": { | |
| 61 | label: "Where checks run", | |
| 62 | env: "FORGE_CHECKS_PLACEMENT", | |
| 63 | kind: { type: "choice", values: ["process", "job"] }, | |
| 64 | fallback: "process", | |
| 65 | 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. A forge that cannot start Jobs runs the check as a process and says why in its log. Takes effect on the next check.", | |
| 66 | }, | |
| 59 | 67 | "cells.egress": { |
| 60 | 68 | label: "Egress from cells", |
| 61 | 69 | env: "FORGE_CELLS_EGRESS", |
| @@ -158,6 +166,11 @@ export function egressSetting(db: Database): "enforce" | "report" { | ||
| 158 | 166 | return capacityValue(db, "cells.egress") === "report" ? "report" : "enforce"; |
| 159 | 167 | } |
| 160 | 168 | |
| 169 | /** Where the next check runs (#1423). */ | |
| 170 | export function checksPlacement(db: Database): "process" | "job" { | |
| 171 | return capacityValue(db, "checks.placement") === "job" ? "job" : "process"; | |
| 172 | } | |
| 173 | ||
| 161 | 174 | /** What a check's commands and a crew shell are told: the shard count, when one is set. */ |
| 162 | 175 | export function capacityEnv(db: Database): Record<string, string> { |
| 163 | 176 | const shards = capacityValue(db, "checks.shards"); |
src/core/runs.ts +36 −2
| @@ -77,6 +77,10 @@ export interface Run { | ||
| 77 | 77 | readonly sandboxNote: string; |
| 78 | 78 | /** A failed check's own detail, when its output was recognised; null otherwise. */ |
| 79 | 79 | readonly checkDetail: CheckDetail | null; |
| 80 | /** Where it ran: `process` (a child of the forge) or `job` (#1423); empty before it started. */ | |
| 81 | readonly placement: string; | |
| 82 | /** The node it ran on, once known. */ | |
| 83 | readonly node: string; | |
| 80 | 84 | readonly createdAt: string; |
| 81 | 85 | readonly startedAt: string | null; |
| 82 | 86 | /** When this deploy's environment started serving — set once, at the swap-in. */ |
| @@ -105,6 +109,8 @@ interface RunRow { | ||
| 105 | 109 | sandbox_enforced: number | null; |
| 106 | 110 | sandbox_note: string; |
| 107 | 111 | check_detail: string; |
| 112 | placement: string; | |
| 113 | node: string; | |
| 108 | 114 | created_at: string; |
| 109 | 115 | started_at: string | null; |
| 110 | 116 | serving_at: string | null; |
| @@ -133,6 +139,8 @@ const toRun = (r: RunRow): Run => ({ | ||
| 133 | 139 | r.sandbox_enforced === null ? null : r.sandbox_enforced !== 0, |
| 134 | 140 | sandboxNote: r.sandbox_note, |
| 135 | 141 | checkDetail: r.check_detail ? (JSON.parse(r.check_detail) as CheckDetail) : null, |
| 142 | placement: r.placement, | |
| 143 | node: r.node, | |
| 136 | 144 | createdAt: r.created_at, |
| 137 | 145 | startedAt: r.started_at, |
| 138 | 146 | servingAt: r.serving_at, |
| @@ -306,13 +314,17 @@ export function noteRunProgress( | ||
| 306 | 314 | subscriptionId?: string | undefined; |
| 307 | 315 | /** Whether the shell is held to the sandbox, and why not when it is not. */ |
| 308 | 316 | sandbox?: { enforced: boolean; note: string } | undefined; |
| 317 | /** Where it runs (#1423), and the node once it is placed. */ | |
| 318 | placement?: "process" | "job" | undefined; | |
| 319 | node?: string | undefined; | |
| 309 | 320 | }, |
| 310 | 321 | ): void { |
| 311 | 322 | db.query( |
| 312 | 323 | `UPDATE run SET session_id = COALESCE(?2, session_id), cost_usd = COALESCE(?3, cost_usd), |
| 313 | 324 | branch = COALESCE(?4, branch), subscription_id = COALESCE(?5, subscription_id), |
| 314 | 325 | sandbox_enforced = COALESCE(?6, sandbox_enforced), |
| 315 | sandbox_note = COALESCE(?7, sandbox_note) | |
| 326 | sandbox_note = COALESCE(?7, sandbox_note), | |
| 327 | placement = COALESCE(?8, placement), node = COALESCE(?9, node) | |
| 316 | 328 | WHERE id = ?1`, |
| 317 | 329 | ).run( |
| 318 | 330 | runId, |
| @@ -322,6 +334,8 @@ export function noteRunProgress( | ||
| 322 | 334 | progress.subscriptionId ?? null, |
| 323 | 335 | progress.sandbox === undefined ? null : progress.sandbox.enforced ? 1 : 0, |
| 324 | 336 | progress.sandbox?.note.slice(0, 300) ?? null, |
| 337 | progress.placement ?? null, | |
| 338 | progress.node?.slice(0, 253) ?? null, | |
| 325 | 339 | ); |
| 326 | 340 | } |
| 327 | 341 | |
| @@ -379,6 +393,25 @@ export function failAbandonedRuns( | ||
| 379 | 393 | /** What a check the forge's own restart cut off says as it is queued again. */ |
| 380 | 394 | export const REQUEUED_SUMMARY = "interrupted by a restart; queued again"; |
| 381 | 395 | |
| 396 | /** What a check says when the Job running it vanished (#1423): never the commit's fault. */ | |
| 397 | export const VANISHED_SUMMARY = "interrupted: its Job vanished; queued again"; | |
| 398 | ||
| 399 | /** | |
| 400 | * Whether this check — the same commit in the same environment — was | |
| 401 | * already queued again once because its Job vanished: a second vanish is | |
| 402 | * a failure, not another retry. | |
| 403 | */ | |
| 404 | export function vanishedBefore(db: Database, run: Run): boolean { | |
| 405 | return ( | |
| 406 | db | |
| 407 | .query( | |
| 408 | `SELECT 1 FROM run WHERE kind = 'check' AND repo_id = ?1 AND env = ?2 | |
| 409 | AND commit_oid = ?3 AND summary = ?4 AND id != ?5 LIMIT 1`, | |
| 410 | ) | |
| 411 | .get(run.repoId, run.env, run.commitOid, VANISHED_SUMMARY, run.id) !== null | |
| 412 | ); | |
| 413 | } | |
| 414 | ||
| 382 | 415 | /** |
| 383 | 416 | * How many times one check may be cut off by its forge going away and be |
| 384 | 417 | * queued again. Past it the check fails once, saying so: a check that kills |
| @@ -399,6 +432,7 @@ export function requeueCheck( | ||
| 399 | 432 | db: Database, |
| 400 | 433 | runId: string, |
| 401 | 434 | lapsedBefore?: string, |
| 435 | summary: string = REQUEUED_SUMMARY, | |
| 402 | 436 | ): { cancelled: Run; again: Run } | undefined { |
| 403 | 437 | return db.transaction(() => { |
| 404 | 438 | const changes = db |
| @@ -408,7 +442,7 @@ export function requeueCheck( | ||
| 408 | 442 | WHERE id = ?1 AND kind = 'check' AND state = 'running' |
| 409 | 443 | AND (?3 IS NULL OR heartbeat_at IS NULL OR heartbeat_at < ?3)`, |
| 410 | 444 | ) |
| 411 | .run(runId, REQUEUED_SUMMARY, lapsedBefore ?? null).changes; | |
| 445 | .run(runId, summary, lapsedBefore ?? null).changes; | |
| 412 | 446 | if (changes === 0) return undefined; |
| 413 | 447 | const cancelled = getRun(db, runId)!; |
| 414 | 448 | const again = createRun(db, { |
src/core/schema.ts +6
| @@ -1584,6 +1584,12 @@ export const migrations: readonly string[] = [ | ||
| 1584 | 1584 | ALTER TABLE look ADD COLUMN attached_by TEXT; |
| 1585 | 1585 | ALTER TABLE look ADD COLUMN note TEXT; |
| 1586 | 1586 | `, |
| 1587 | // 75 — where a run ran (#1423): as a child of the forge (`process`) or a | |
| 1588 | // Job on the cluster (`job`), and the node. Empty for a run before this. | |
| 1589 | ` | |
| 1590 | ALTER TABLE run ADD COLUMN placement TEXT NOT NULL DEFAULT ''; | |
| 1591 | ALTER TABLE run ADD COLUMN node TEXT NOT NULL DEFAULT ''; | |
| 1592 | `, | |
| 1587 | 1593 | ]; |
| 1588 | 1594 | |
| 1589 | 1595 | /** |
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); |
test/checks-job.test.ts added +399
| @@ -0,0 +1,399 @@ | ||
| 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 }) { | |
| 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 | const [container] = podOf(manifest).spec.containers; | |
| 215 | const env = Object.fromEntries( | |
| 216 | container!.env.map((e) => [e.name, e.value]), | |
| 217 | ); | |
| 218 | const lines: string[] = []; | |
| 219 | const end = mode.vanish | |
| 220 | ? Promise.resolve<JobEnd>({ | |
| 221 | kind: "vanished", | |
| 222 | reason: "its pod was evicted on vxrail-1", | |
| 223 | }) | |
| 224 | : (async (): Promise<JobEnd> => { | |
| 225 | const work = await mkdtemp(join(tmpdir(), "forge-lane-")); | |
| 226 | try { | |
| 227 | const code = await runLane( | |
| 228 | { ...env, FORGE_LANE_WORK: work }, | |
| 229 | (line) => lines.push(line), | |
| 230 | ); | |
| 231 | return { kind: "exited", code, reason: code === 0 ? "Completed" : "Error" }; | |
| 232 | } finally { | |
| 233 | await rm(work, { recursive: true, force: true }); | |
| 234 | } | |
| 235 | })(); | |
| 236 | running.set(manifest.metadata.name, { lines, end }); | |
| 237 | return { ok: true, value: undefined }; | |
| 238 | }, | |
| 239 | async wait(name, _signal, onPlaced) { | |
| 240 | const job = running.get(name); | |
| 241 | if (!job) return { kind: "vanished", reason: "the Job is gone" }; | |
| 242 | onPlaced("vxrail-1"); | |
| 243 | return job.end; | |
| 244 | }, | |
| 245 | async logs(name, onLine) { | |
| 246 | const job = running.get(name); | |
| 247 | if (!job) return; | |
| 248 | await job.end; | |
| 249 | for (const line of job.lines) onLine(line); | |
| 250 | }, | |
| 251 | async remove(name) { | |
| 252 | removed.push(name); | |
| 253 | running.delete(name); | |
| 254 | }, | |
| 255 | }; | |
| 256 | return { client, created, removed }; | |
| 257 | } | |
| 258 | ||
| 259 | describe("a check placed as a Job", () => { | |
| 260 | let dataDir: string; | |
| 261 | let app: App; | |
| 262 | let servers: Servers; | |
| 263 | let checks: ChecksHandle | undefined; | |
| 264 | let alice: User; | |
| 265 | let repo: Repo; | |
| 266 | let n = 0; | |
| 267 | ||
| 268 | async function settled(where: (run: Run) => boolean): Promise<Run> { | |
| 269 | const deadline = Date.now() + 30_000; | |
| 270 | while (Date.now() < deadline) { | |
| 271 | const run = listRuns(app.db, repo.id, { kind: "check", limit: 50 }).find( | |
| 272 | where, | |
| 273 | ); | |
| 274 | if (run && (run.state === "ok" || run.state === "failed")) return run; | |
| 275 | await Bun.sleep(50); | |
| 276 | } | |
| 277 | throw new Error("check did not settle"); | |
| 278 | } | |
| 279 | ||
| 280 | async function push(run: string, extra: Record<string, string> = {}) { | |
| 281 | n += 1; | |
| 282 | const pushed = await commitToBranch(app, alice, repo, { | |
| 283 | message: `Check ${n}`, | |
| 284 | files: [ | |
| 285 | { | |
| 286 | path: "forge.json", | |
| 287 | content: `{"check": {"run": ${JSON.stringify(run)}, "install": ""}}\n`, | |
| 288 | }, | |
| 289 | { path: "N.md", content: `${n}\n` }, | |
| 290 | ...Object.entries(extra).map(([path, content]) => ({ path, content })), | |
| 291 | ], | |
| 292 | }); | |
| 293 | if (!pushed.ok) throw new Error(JSON.stringify(pushed.error)); | |
| 294 | return pushed.value.commitOid; | |
| 295 | } | |
| 296 | ||
| 297 | async function useCluster(mode: { vanish: boolean }) { | |
| 298 | // One checks service at a time, so a run is picked up by this test's cluster. | |
| 299 | await checks?.stop(); | |
| 300 | const cluster = standInCluster(mode); | |
| 301 | checks = startChecks(app, { | |
| 302 | forgeUrl: servers.url, | |
| 303 | concurrency: 2, | |
| 304 | jobs: { | |
| 305 | client: cluster.client, | |
| 306 | settings: { ...SETTINGS, forgeUrl: servers.url }, | |
| 307 | }, | |
| 308 | }); | |
| 309 | return cluster; | |
| 310 | } | |
| 311 | ||
| 312 | beforeAll(async () => { | |
| 313 | dataDir = await mkdtemp(join(tmpdir(), "forge-checks-job-")); | |
| 314 | app = createApp({ dataDir, port: 0 }); | |
| 315 | servers = await serve(app); | |
| 316 | const a = await createUser(app.db, { | |
| 317 | trusted: true, | |
| 318 | username: "alice", | |
| 319 | email: "[email protected]", | |
| 320 | password: "a-good-passphrase", | |
| 321 | adminIfFirst: true, | |
| 322 | }); | |
| 323 | if (!a.ok) throw new Error(a.error); | |
| 324 | alice = a.value; | |
| 325 | const made = await createRepo(app, alice, { name: "lib", visibility: "public" }); | |
| 326 | if (!made.ok) throw new Error(String(made.error)); | |
| 327 | repo = made.value; | |
| 328 | }); | |
| 329 | ||
| 330 | afterAll(async () => { | |
| 331 | await checks?.stop(); | |
| 332 | servers.stop(); | |
| 333 | app.close(); | |
| 334 | await rm(dataDir, { recursive: true, force: true }); | |
| 335 | }); | |
| 336 | ||
| 337 | test("the process placement is unchanged: no Job, the run says it ran here", async () => { | |
| 338 | setCapacity(app.db, "checks.placement", null, alice.id); | |
| 339 | const cluster = await useCluster({ vanish: false }); | |
| 340 | const commit = await push("test -f OK.md", { "OK.md": "ok\n" }); | |
| 341 | const run = await settled((r) => r.commitOid === commit); | |
| 342 | expect(run.state).toBe("ok"); | |
| 343 | expect(run.placement).toBe("process"); | |
| 344 | expect(run.node).not.toBe(""); | |
| 345 | expect(cluster.created).toHaveLength(0); | |
| 346 | }, 60_000); | |
| 347 | ||
| 348 | test("placed as a Job, a check fetches its checkout, runs to a verdict, and its log comes home", async () => { | |
| 349 | setCapacity(app.db, "checks.placement", "job", alice.id); | |
| 350 | const cluster = await useCluster({ vanish: false }); | |
| 351 | const commit = await push("cat OK.md && echo from-the-lane", { "OK.md": "here\n" }); | |
| 352 | const run = await settled((r) => r.commitOid === commit); | |
| 353 | expect(run.state).toBe("ok"); | |
| 354 | expect(run.placement).toBe("job"); | |
| 355 | expect(run.node).toBe("vxrail-1"); | |
| 356 | expect(cluster.created).toHaveLength(1); | |
| 357 | expect(cluster.removed).toEqual([cluster.created[0]!.metadata.name]); | |
| 358 | const log = readRunLog(dataDir, run.id).lines.join("\n"); | |
| 359 | expect(log).toContain("placed as a Job"); | |
| 360 | expect(log).toContain("running on vxrail-1"); | |
| 361 | expect(log).toContain("from-the-lane"); | |
| 362 | expect(log).not.toContain("::forge-lane::"); | |
| 363 | // The checkout is gone with the check: the token opens nothing now. | |
| 364 | const token = podOf(cluster.created[0]!) | |
| 365 | .spec.containers[0]!.env.find((e) => e.name === "FORGE_LANE_TOKEN")!.value; | |
| 366 | const late = await fetch(`${servers.url}/-/lane/${run.id}/tree`, { | |
| 367 | headers: { authorization: `Bearer ${token}` }, | |
| 368 | }); | |
| 369 | expect(late.status).toBe(404); | |
| 370 | }, 60_000); | |
| 371 | ||
| 372 | test("a failing check in a Job fails with the same words a process gives", async () => { | |
| 373 | setCapacity(app.db, "checks.placement", "job", alice.id); | |
| 374 | const cluster = await useCluster({ vanish: false }); | |
| 375 | const commit = await push("echo nope >&2; exit 3"); | |
| 376 | const run = await settled((r) => r.commitOid === commit); | |
| 377 | expect(run.state).toBe("failed"); | |
| 378 | expect(run.summary).toBe("check failed: nope"); | |
| 379 | expect(cluster.created).toHaveLength(1); | |
| 380 | }, 60_000); | |
| 381 | ||
| 382 | test("a Job that vanishes interrupts the check, which is queued again once — then fails, never hangs", async () => { | |
| 383 | setCapacity(app.db, "checks.placement", "job", alice.id); | |
| 384 | const cluster = await useCluster({ vanish: true }); | |
| 385 | const commit = await push("true"); | |
| 386 | const last = await settled((r) => r.commitOid === commit); | |
| 387 | const all = listRuns(app.db, repo.id, { kind: "check", limit: 50 }).filter( | |
| 388 | (r) => r.commitOid === commit, | |
| 389 | ); | |
| 390 | expect(all).toHaveLength(2); | |
| 391 | const first = all.find((r) => r.id !== last.id)!; | |
| 392 | expect(first.state).toBe("cancelled"); | |
| 393 | expect(first.summary).toBe(VANISHED_SUMMARY); | |
| 394 | expect(last.state).toBe("failed"); | |
| 395 | expect(last.attempt).toBe(1); | |
| 396 | expect(last.summary).toContain("its Job vanished"); | |
| 397 | expect(cluster.created).toHaveLength(2); | |
| 398 | }, 60_000); | |
| 399 | }); |
new above
offline