Public: anyone can read this; the crew can change it.
The release agent refuses a dark roll unless the owner said yes to that roll #1169
torque/forge:torque/1072-the-release-agent-refuses-a-dark-roll-un → main 8 commits fork
6 files
changed +1175
−0
README.md +4
| @@ -400,6 +400,10 @@ The terminal has no backups view, so it has no readout. | ||
| 400 | 400 | grew up in switched off: what a host owes it, the moves in order, and what is |
| 401 | 401 | given up. |
| 402 | 402 | |
| 403 | `docs/ops/RELEASE.md` is the release checklist: a release rolls only when a | |
| 404 | second forge pod fits beside the first, and a roll that would go dark waits | |
| 405 | for the owner's yes to that roll (`scripts/roll-preflight.ts`). | |
| 406 | ||
| 403 | 407 | ### Passports |
| 404 | 408 | |
| 405 | 409 | A crew run's environment carries `FORGE_PASSPORT`, a 15-minute credential |
docs/ops/RELEASE.md added +107
| @@ -0,0 +1,107 @@ | ||
| 1 | # Release checklist: the roll | |
| 2 | ||
| 3 | A release never goes dark without the owner's yes to that roll (#876, part | |
| 4 | of #873). The owner, 2026-10-06, after a three-minute dark roll: "that | |
| 5 | should never happen … i should have the option to have it never go down." | |
| 6 | ||
| 7 | The chart rolls with `maxSurge: 1, maxUnavailable: 0` | |
| 8 | (`charts/app/templates/deployment.yaml`): the new pod comes up beside the old | |
| 9 | one and the old one drains only once the new one is ready. The volume is | |
| 10 | local-path, bound to one node, so the new pod must fit on **that node**. When | |
| 11 | it does not, the only way through is to take the old pod down first — dark | |
| 12 | for the drain plus the new pod's start: 3 min 33 s on v0.7.52. | |
| 13 | ||
| 14 | ## Before every roll | |
| 15 | ||
| 16 | The forge runs in namespace `$NS` as the Helm release `$REL` (the Deployment and its `app` label carry that name). | |
| 17 | ||
| 18 | sh | |
| 19 | POD= | |
| 20 | NODE= | |
| 21 | kubectl get node "" -o json > node.json | |
| 22 | kubectl get pods -A -o json --field-selector spec.nodeName="" > pods.json | |
| 23 | # The forge's steady memory: the MEMORY column, read over a quiet minute | |
| 24 | # (no crew run starting), not a peak and not a cold start. | |
| 25 | kubectl -n "" top pod "" --no-headers | |
| 26 | ||
| 27 | bun scripts/roll-preflight.ts --version 0.7.53 \ | |
| 28 | --node node.json --pods pods.json --pod "/" --steady 3712Mi \ | |
| 29 | --overlay path/to/the/gitops/helmrelease.yaml | |
| 30 | ||
| 31 | ||
| 32 | `--overlay` names every file of the gitops overlay that shapes this | |
| 33 | deployment; it may be given more than once. | |
| 34 | ||
| 35 | The rule (`scripts/roll.ts`), in whole millicores and bytes as the scheduler | |
| 36 | counts them: | |
| 37 | ||
| 38 | | quantity | is | | |
| 39 | | --------- | ---------------------------------------------------------------- | | |
| 40 | | free | node `status.allocatable` − the requests of every pod on it that has not Succeeded or Failed | | |
| 41 | | need | cpu: the forge pod's request; memory: max(its request, its steady memory) | | |
| 42 | | fits | free ≥ need, for cpu and for memory | | |
| 43 | | short by | need − free, never below zero: the headroom that makes the roll zero-downtime | | |
| 44 | | dark for | drain (180 s, the crew's) + start (33 s) = 213 s, as v0.7.52 measured; at most the grace period (300 s) + the startup probe's ceiling (3 s × 60) + one readiness period (5 s) = 485 s | | |
| 45 | ||
| 46 | Steady memory is in `need` because the request is a floor: a pod requesting | |
| 47 | 2 Gi that steadies at 3.5–4 Gi schedules on 2 Gi free and then both pods | |
| 48 | hold more memory than the node has. Measured drain and start replace the | |
| 49 | typical figures with `--drain-seconds` and `--start-seconds`. | |
| 50 | ||
| 51 | ## What the exit code means | |
| 52 | ||
| 53 | | exit | the agent | | |
| 54 | | ---- | --------------------------------------------------------------------------------------------- | | |
| 55 | | 0 | rolls | | |
| 56 | | 3 | does **not** roll. Posts the report — the seconds it would be dark, what it is short by, the roll id — to the owner, and waits | | |
| 57 | | 4 | does **not** roll. The overlay carries `maxSurge: 0` or `type: Recreate`; it comes out first | | |
| 58 | | 2 | does not roll; the input was not what `kubectl` prints | | |
| 59 | ||
| 60 | ## The owner's yes | |
| 61 | ||
| 62 | A yes is to **one roll**: the owner's reply quotes the roll id from the | |
| 63 | report, and the agent re-runs the gate with `--yes <roll id>`. | |
| 64 | ||
| 65 | The roll id is random — 96 bits drawn when the gate first reports this roll | |
| 66 | as dark — and the gate keeps it in `$FORGE_APP_DATA/roll-ask.json` (mode | |
| 67 | 0600; `--asked <file>` names another place, and with neither a dark roll | |
| 68 | exits 2). It is bound to the roll's key: the release and the node's numbers | |
| 69 | it was judged on. So: | |
| 70 | ||
| 71 | - nobody can compute the id from `kubectl get node`, or know it before the | |
| 72 | report exists; the public key itself is refused as a yes (`test/roll.test.ts`); | |
| 73 | - re-running the gate for the same roll prints the same id, so the owner's | |
| 74 | yes does not go stale while the agent waits; | |
| 75 | - if the release or the node's numbers move, the gate draws a new id, the | |
| 76 | old one answers nothing, and the agent asks again; | |
| 77 | - a yes that lets the roll go is used up: the ask file is removed, and the | |
| 78 | same id never lets a second roll go. | |
| 79 | ||
| 80 | "yes", "always", an id the gate did not ask, or a yes from anyone but the | |
| 81 | owner is no yes. The id proves the yes answers this report; who wrote it is | |
| 82 | still the reply's author, so the agent takes the id only from the owner's own | |
| 83 | reply on the thread where it posted the report (on the forge: a comment whose | |
| 84 | author is the owner and is not `untrusted`). When in doubt, the agent does | |
| 85 | not roll and asks again. | |
| 86 | ||
| 87 | With exit 0 under `--yes`, the dark roll is a one-off patch on the live | |
| 88 | deployment, undone as soon as the new pod is ready: | |
| 89 | ||
| 90 | sh | |
| 91 | kubectl -n "" patch deploy "" --type merge \ | |
| 92 | -p '{"spec":{"strategy":{"rollingUpdate":{"maxSurge":0,"maxUnavailable":1}}}}' | |
| 93 | # … the release rolls; wait for it … | |
| 94 | kubectl -n "" rollout status deploy/"" --timeout=10m | |
| 95 | kubectl -n "" patch deploy "" --type merge \ | |
| 96 | -p '{"spec":{"strategy":{"rollingUpdate":{"maxSurge":1,"maxUnavailable":0}}}}' | |
| 97 | kubectl -n "" get deploy "" -o jsonpath='{.spec.strategy.rollingUpdate}' | |
| 98 | # → {"maxSurge":1,"maxUnavailable":0} | |
| 99 | ||
| 100 | ||
| 101 | ## Never a standing value | |
| 102 | ||
| 103 | `maxSurge: 0` (or `type: Recreate`) is never committed — not to this chart | |
| 104 | and not to the gitops overlay. A standing no-surge turns every later roll, | |
| 105 | settings-only rolls included, into a dark one that nobody said yes to. | |
| 106 | `test/roll.test.ts` holds the chart to `maxSurge: 1, maxUnavailable: 0`; the | |
| 107 | gate's `--overlay` holds the overlay to it at every roll. |
scripts/gate.ts +1
| @@ -49,6 +49,7 @@ export const GATE: readonly string[] = [ | ||
| 49 | 49 | "test/restore-card.test.ts", |
| 50 | 50 | "test/recovery-doc.test.ts", |
| 51 | 51 | "test/returns.test.ts", |
| 52 | "test/roll.test.ts", | |
| 52 | 53 | "test/review-route.test.ts", |
| 53 | 54 | "test/review-lines.test.ts", |
| 54 | 55 | "test/review-gate.test.ts", |
scripts/roll-preflight.ts added +218
| @@ -0,0 +1,218 @@ | ||
| 1 | /** | |
| 2 | * The release checklist's roll gate (`docs/ops/RELEASE.md`, #876). Reads | |
| 3 | * what `kubectl` printed, decides with `scripts/roll.ts`, prints the report | |
| 4 | * the agent posts to the owner, and exits: | |
| 5 | * | |
| 6 | * 0 roll: a second forge pod fits, or the owner said yes to this roll id | |
| 7 | * 3 do not roll: it would go dark and the owner has not said yes to it; | |
| 8 | * the report carries a fresh roll id, kept in the ask file | |
| 9 | * 4 do not roll: an overlay carries maxSurge 0 / Recreate as a standing value | |
| 10 | * 2 the input is not what kubectl prints | |
| 11 | * | |
| 12 | * bun scripts/roll-preflight.ts --version 0.7.53 \ | |
| 13 | * --node node.json --pods pods.json --pod forge/forge-7d9c-abcde \ | |
| 14 | * --steady 3712Mi [--overlay helmrelease.yaml]… [--yes <roll id>] \ | |
| 15 | * [--asked <file>] [--json] | |
| 16 | * | |
| 17 | * The roll id is random, drawn when a dark report is first made for this | |
| 18 | * roll and kept in the ask file (`$FORGE_APP_DATA/roll-ask.json` unless | |
| 19 | * `--asked` names another), never in the repository; a yes that matches | |
| 20 | * it is used up. It runs nothing and reaches no cluster: the files are the | |
| 21 | * agent's. | |
| 22 | */ | |
| 23 | ||
| 24 | import { randomBytes } from "node:crypto"; | |
| 25 | import { readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; | |
| 26 | import { join } from "node:path"; | |
| 27 | import { | |
| 28 | type Ask, | |
| 29 | askFor, | |
| 30 | DARK_TIMING, | |
| 31 | decide, | |
| 32 | parseAsk, | |
| 33 | parseQuantity, | |
| 34 | preflight, | |
| 35 | report, | |
| 36 | standingNoSurge, | |
| 37 | } from "./roll.ts"; | |
| 38 | ||
| 39 | export interface Args { | |
| 40 | version: string; | |
| 41 | node: string; | |
| 42 | pods: string; | |
| 43 | pod: string; | |
| 44 | steady: string; | |
| 45 | overlays: string[]; | |
| 46 | yes?: string; | |
| 47 | asked?: string; | |
| 48 | json: boolean; | |
| 49 | drainSeconds?: number; | |
| 50 | startSeconds?: number; | |
| 51 | } | |
| 52 | ||
| 53 | const VALUED = new Set([ | |
| 54 | "--version", | |
| 55 | "--node", | |
| 56 | "--pods", | |
| 57 | "--pod", | |
| 58 | "--steady", | |
| 59 | "--overlay", | |
| 60 | "--yes", | |
| 61 | "--asked", | |
| 62 | "--drain-seconds", | |
| 63 | "--start-seconds", | |
| 64 | ]); | |
| 65 | ||
| 66 | function seconds(flag: string, text: string): number { | |
| 67 | if (!/^[0-9]{1,5}$/.test(text)) throw new Error(`${flag} wants whole seconds, not ${JSON.stringify(text)}`); | |
| 68 | return Number(text); | |
| 69 | } | |
| 70 | ||
| 71 | export function parseArgs(argv: readonly string[]): Args { | |
| 72 | const one: Record<string, string> = {}; | |
| 73 | const overlays: string[] = []; | |
| 74 | let json = false; | |
| 75 | for (let i = 0; i < argv.length; i++) { | |
| 76 | const flag = argv[i] ?? ""; | |
| 77 | if (flag === "--json") { | |
| 78 | json = true; | |
| 79 | continue; | |
| 80 | } | |
| 81 | if (!VALUED.has(flag)) throw new Error(`unknown argument ${JSON.stringify(flag)}`); | |
| 82 | const value = argv[++i]; | |
| 83 | if (value === undefined) throw new Error(`${flag} wants a value`); | |
| 84 | if (flag === "--overlay") overlays.push(value); | |
| 85 | else if (one[flag] !== undefined) throw new Error(`${flag} given twice`); | |
| 86 | else one[flag] = value; | |
| 87 | } | |
| 88 | for (const f of ["--version", "--node", "--pods", "--pod", "--steady"]) | |
| 89 | if (one[f] === undefined) throw new Error(`${f} is required`); | |
| 90 | const args: Args = { | |
| 91 | version: one["--version"]!, | |
| 92 | node: one["--node"]!, | |
| 93 | pods: one["--pods"]!, | |
| 94 | pod: one["--pod"]!, | |
| 95 | steady: one["--steady"]!, | |
| 96 | overlays, | |
| 97 | json, | |
| 98 | }; | |
| 99 | if (one["--yes"] !== undefined) args.yes = one["--yes"]; | |
| 100 | if (one["--asked"] !== undefined) args.asked = one["--asked"]; | |
| 101 | if (one["--drain-seconds"] !== undefined) | |
| 102 | args.drainSeconds = seconds("--drain-seconds", one["--drain-seconds"]); | |
| 103 | if (one["--start-seconds"] !== undefined) | |
| 104 | args.startSeconds = seconds("--start-seconds", one["--start-seconds"]); | |
| 105 | return args; | |
| 106 | } | |
| 107 | ||
| 108 | function readJson(path: string): unknown { | |
| 109 | return JSON.parse(readFileSync(path, "utf8")); | |
| 110 | } | |
| 111 | ||
| 112 | /** The ask file's ask; null when there is none. Throws on one that is not an ask. */ | |
| 113 | function readAsk(path: string): Ask | null { | |
| 114 | let text: string; | |
| 115 | try { | |
| 116 | text = readFileSync(path, "utf8"); | |
| 117 | } catch { | |
| 118 | return null; | |
| 119 | } | |
| 120 | const ask = parseAsk(JSON.parse(text)); | |
| 121 | if (ask === null) throw new Error(`${path} is not a roll ask: remove it and ask again`); | |
| 122 | return ask; | |
| 123 | } | |
| 124 | ||
| 125 | function writeAsk(path: string, ask: Ask): void { | |
| 126 | const tmp = `${path}.${process.pid}.tmp`; | |
| 127 | writeFileSync(tmp, JSON.stringify(ask), { mode: 0o600 }); | |
| 128 | renameSync(tmp, path); | |
| 129 | } | |
| 130 | ||
| 131 | export interface World { | |
| 132 | readonly env: Readonly<Record<string, string | undefined>>; | |
| 133 | readonly draw: () => string; | |
| 134 | readonly now: () => Date; | |
| 135 | } | |
| 136 | ||
| 137 | const WORLD: World = { | |
| 138 | env: process.env, | |
| 139 | draw: () => randomBytes(12).toString("hex"), | |
| 140 | now: () => new Date(), | |
| 141 | }; | |
| 142 | ||
| 143 | /** The whole gate as a function of the arguments: exit code and output. */ | |
| 144 | export function run( | |
| 145 | argv: readonly string[], | |
| 146 | world: World = WORLD, | |
| 147 | ): { code: number; out: string } { | |
| 148 | let args: Args; | |
| 149 | try { | |
| 150 | args = parseArgs(argv); | |
| 151 | } catch (e) { | |
| 152 | return { code: 2, out: `roll-preflight: ${(e as Error).message}` }; | |
| 153 | } | |
| 154 | const standing: string[] = []; | |
| 155 | for (const path of args.overlays) { | |
| 156 | let text: string; | |
| 157 | try { | |
| 158 | text = readFileSync(path, "utf8"); | |
| 159 | } catch { | |
| 160 | return { code: 2, out: `roll-preflight: cannot read overlay ${path}` }; | |
| 161 | } | |
| 162 | for (const line of standingNoSurge(text)) standing.push(` ${path}: ${line}`); | |
| 163 | } | |
| 164 | if (standing.length > 0) | |
| 165 | return { | |
| 166 | code: 4, | |
| 167 | out: [ | |
| 168 | "not rolling: no-surge is a standing value in the overlay; remove it first", | |
| 169 | ...standing, | |
| 170 | ].join("\n"), | |
| 171 | }; | |
| 172 | try { | |
| 173 | const steady = parseQuantity(args.steady); | |
| 174 | if (steady === null) throw new Error(`--steady ${JSON.stringify(args.steady)} is not a quantity`); | |
| 175 | const p = preflight({ | |
| 176 | version: args.version, | |
| 177 | node: readJson(args.node), | |
| 178 | pods: readJson(args.pods), | |
| 179 | forgePod: args.pod, | |
| 180 | steadyMemory: steady, | |
| 181 | timing: { | |
| 182 | ...DARK_TIMING, | |
| 183 | ...(args.drainSeconds !== undefined ? { drainSeconds: args.drainSeconds } : {}), | |
| 184 | ...(args.startSeconds !== undefined ? { startSeconds: args.startSeconds } : {}), | |
| 185 | }, | |
| 186 | }); | |
| 187 | let ask: Ask | null = null; | |
| 188 | let d = decide(p, args.yes, null); | |
| 189 | if (!p.fits) { | |
| 190 | const data = world.env["FORGE_APP_DATA"]; | |
| 191 | const path = args.asked ?? (data ? join(data, "roll-ask.json") : undefined); | |
| 192 | if (path === undefined) | |
| 193 | throw new Error("the roll would go dark and there is nowhere to keep its id: set FORGE_APP_DATA or --asked"); | |
| 194 | const standing = readAsk(path); | |
| 195 | d = decide(p, args.yes, standing); | |
| 196 | if (d.go) { | |
| 197 | // a yes is for one roll: used now, it answers nothing again | |
| 198 | rmSync(path, { force: true }); | |
| 199 | ask = standing; | |
| 200 | } else { | |
| 201 | ask = askFor(p, standing, world.draw, world.now()); | |
| 202 | if (ask !== standing) writeAsk(path, ask); | |
| 203 | } | |
| 204 | } | |
| 205 | const out = args.json | |
| 206 | ? JSON.stringify({ ...p, rollId: d.go ? null : (ask?.id ?? null), decision: d }, null, 2) | |
| 207 | : report(p, d, ask); | |
| 208 | return { code: d.go ? 0 : 3, out }; | |
| 209 | } catch (e) { | |
| 210 | return { code: 2, out: `roll-preflight: ${(e as Error).message}` }; | |
| 211 | } | |
| 212 | } | |
| 213 | ||
| 214 | if (import.meta.main) { | |
| 215 | const { code, out } = run(process.argv.slice(2)); | |
| 216 | console.log(out); | |
| 217 | process.exit(code); | |
| 218 | } |
scripts/roll.ts added +460
| @@ -0,0 +1,460 @@ | ||
| 1 | /** | |
| 2 | * Whether a release can roll without going dark (#876, part of #873). | |
| 3 | * | |
| 4 | * The chart rolls with `maxSurge: 1, maxUnavailable: 0`: the new forge pod | |
| 5 | * comes up beside the old one and the old one drains only once the new one | |
| 6 | * is ready. Local-path storage binds the volume to one node, so the new pod | |
| 7 | * must schedule on *that* node. When it cannot, the roll either sticks | |
| 8 | * (the pod stays Pending and nothing changes) or — if someone sets | |
| 9 | * `maxSurge: 0` — goes dark: the old pod drains first and nobody is served | |
| 10 | * until the new one is ready. That cost 3 min 33 s on v0.7.52. | |
| 11 | * | |
| 12 | * Plain data in, plain data out. `scripts/roll-preflight.ts` reads what | |
| 13 | * `kubectl` printed and prints what this decides; nothing here talks to a | |
| 14 | * cluster. | |
| 15 | * | |
| 16 | * The rule, in the scheduler's own terms (NodeResourcesFit): | |
| 17 | * | |
| 18 | * free = node.status.allocatable − Σ requests of the pods on the node | |
| 19 | * need.cpu = the forge pod's cpu request | |
| 20 | * need.mem = max(the forge pod's memory request, its steady memory) | |
| 21 | * fits ⇔ free.cpu ≥ need.cpu ∧ free.mem ≥ need.mem | |
| 22 | * | |
| 23 | * Steady memory is in `need` because the request (2 Gi) is a floor, not | |
| 24 | * what the pod holds: a pod that steadies at 3.5–4 Gi schedules on 2 Gi | |
| 25 | * free and then the node runs out of memory under both pods. | |
| 26 | */ | |
| 27 | ||
| 28 | import { createHash, timingSafeEqual } from "node:crypto"; | |
| 29 | ||
| 30 | /** | |
| 31 | * Whole millicores and whole bytes, as the scheduler counts them (a | |
| 32 | * quantity is rounded up to its unit, `Quantity.MilliValue`), so `4100m − | |
| 33 | * 3100m` is exactly `1000m` and never a hair under it. | |
| 34 | */ | |
| 35 | export interface Resources { | |
| 36 | readonly milliCpu: number; | |
| 37 | readonly memory: number; | |
| 38 | } | |
| 39 | ||
| 40 | const BINARY: Record<string, number> = { | |
| 41 | Ki: 2 ** 10, | |
| 42 | Mi: 2 ** 20, | |
| 43 | Gi: 2 ** 30, | |
| 44 | Ti: 2 ** 40, | |
| 45 | Pi: 2 ** 50, | |
| 46 | Ei: 2 ** 60, | |
| 47 | }; | |
| 48 | const DECIMAL: Record<string, number> = { | |
| 49 | n: 1e-9, | |
| 50 | u: 1e-6, | |
| 51 | m: 1e-3, | |
| 52 | "": 1, | |
| 53 | k: 1e3, | |
| 54 | M: 1e6, | |
| 55 | G: 1e9, | |
| 56 | T: 1e12, | |
| 57 | P: 1e15, | |
| 58 | E: 1e18, | |
| 59 | }; | |
| 60 | ||
| 61 | /** | |
| 62 | * A Kubernetes resource quantity (`resource.Quantity`): `8130464Ki`, `2Gi`, | |
| 63 | * `500m`, `1.5`, `12e6`. Answers the plain number (bytes, or cores), or | |
| 64 | * null for anything that is not one — never a guess. | |
| 65 | */ | |
| 66 | export function parseQuantity(text: unknown): number | null { | |
| 67 | if (typeof text !== "string") return null; | |
| 68 | const m = /^([0-9]+(?:\.[0-9]+)?|\.[0-9]+)(?:([eE][+-]?[0-9]{1,2})|(Ki|Mi|Gi|Ti|Pi|Ei|n|u|m|k|M|G|T|P|E))?$/.exec( | |
| 69 | text.trim(), | |
| 70 | ); | |
| 71 | if (!m) return null; | |
| 72 | const base = Number(m[1]); | |
| 73 | if (m[2]) return base * 10 ** Number(m[2].slice(1)); | |
| 74 | const suffix = m[3] ?? ""; | |
| 75 | const scale = BINARY[suffix] ?? DECIMAL[suffix]; | |
| 76 | return scale === undefined ? null : base * scale; | |
| 77 | } | |
| 78 | ||
| 79 | const ZERO: Resources = { milliCpu: 0, memory: 0 }; | |
| 80 | ||
| 81 | function add(a: Resources, b: Resources): Resources { | |
| 82 | return { milliCpu: a.milliCpu + b.milliCpu, memory: a.memory + b.memory }; | |
| 83 | } | |
| 84 | ||
| 85 | function max(a: Resources, b: Resources): Resources { | |
| 86 | return { milliCpu: Math.max(a.milliCpu, b.milliCpu), memory: Math.max(a.memory, b.memory) }; | |
| 87 | } | |
| 88 | ||
| 89 | function obj(v: unknown): Record<string, unknown> { | |
| 90 | return v && typeof v === "object" && !Array.isArray(v) | |
| 91 | ? (v as Record<string, unknown>) | |
| 92 | : {}; | |
| 93 | } | |
| 94 | ||
| 95 | function list(v: unknown): unknown[] { | |
| 96 | return Array.isArray(v) ? v : []; | |
| 97 | } | |
| 98 | ||
| 99 | /** `{cpu, memory}` from a requests/allocatable map; absent reads as zero. */ | |
| 100 | function resources(map: unknown, where: string): Resources { | |
| 101 | const m = obj(map); | |
| 102 | const read = (key: "cpu" | "memory"): number => { | |
| 103 | if (m[key] === undefined) return 0; | |
| 104 | const n = parseQuantity(m[key]); | |
| 105 | if (n === null || n < 0) | |
| 106 | throw new Error(`${where}: ${key} ${JSON.stringify(m[key])} is not a quantity`); | |
| 107 | return n; | |
| 108 | }; | |
| 109 | return { | |
| 110 | milliCpu: Math.ceil(read("cpu") * 1000 - 1e-6), | |
| 111 | memory: Math.ceil(read("memory") - 1e-6), | |
| 112 | }; | |
| 113 | } | |
| 114 | ||
| 115 | /** | |
| 116 | * What the scheduler reserves for a pod (Kubernetes ≥ 1.29, "Resource | |
| 117 | * sharing within containers"): the containers and sidecars (init | |
| 118 | * containers with `restartPolicy: Always`) summed; each plain init | |
| 119 | * container, with the sidecars started before it, taken as a floor; plus | |
| 120 | * the runtime class's overhead. | |
| 121 | */ | |
| 122 | export function podRequest(pod: unknown): Resources { | |
| 123 | const spec = obj(obj(pod)["spec"]); | |
| 124 | const name = String(obj(obj(pod)["metadata"])["name"] ?? "?"); | |
| 125 | const req = (c: unknown) => | |
| 126 | resources(obj(obj(c)["resources"])["requests"], `pod ${name}`); | |
| 127 | let sidecars = ZERO; | |
| 128 | let initFloor = ZERO; | |
| 129 | for (const c of list(spec["initContainers"])) { | |
| 130 | if (obj(c)["restartPolicy"] === "Always") sidecars = add(sidecars, req(c)); | |
| 131 | else initFloor = max(initFloor, add(req(c), sidecars)); | |
| 132 | } | |
| 133 | let sum = sidecars; | |
| 134 | for (const c of list(spec["containers"])) sum = add(sum, req(c)); | |
| 135 | return add(max(sum, initFloor), resources(spec["overhead"], `pod ${name}`)); | |
| 136 | } | |
| 137 | ||
| 138 | /** A pod the scheduler still counts against its node. */ | |
| 139 | function holdsNode(pod: unknown, node: string): boolean { | |
| 140 | const phase = obj(obj(pod)["status"])["phase"]; | |
| 141 | return ( | |
| 142 | obj(obj(pod)["spec"])["nodeName"] === node && | |
| 143 | phase !== "Succeeded" && | |
| 144 | phase !== "Failed" | |
| 145 | ); | |
| 146 | } | |
| 147 | ||
| 148 | /** | |
| 149 | * How long a roll without a surge pod is dark, in seconds. The old pod | |
| 150 | * stops serving when it starts to drain; the new one cannot start until | |
| 151 | * the old one is gone and then must pass its probes. | |
| 152 | */ | |
| 153 | export interface DarkTiming { | |
| 154 | /** Old pod's drain, typical: the crew drains three minutes (`crew/dispatch.ts`). */ | |
| 155 | readonly drainSeconds: number; | |
| 156 | /** New pod from scheduled to ready, typical. */ | |
| 157 | readonly startSeconds: number; | |
| 158 | /** Ceiling on the drain: the chart's `terminationGracePeriodSeconds`. */ | |
| 159 | readonly graceSeconds: number; | |
| 160 | /** Ceiling on start: the chart's startupProbe period × failureThreshold, plus one readiness period. */ | |
| 161 | readonly startCeilingSeconds: number; | |
| 162 | } | |
| 163 | ||
| 164 | /** | |
| 165 | * The defaults, from the chart (`charts/app/templates/deployment.yaml`, | |
| 166 | * cross-checked by `test/roll.test.ts`) and from v0.7.52's dark roll as | |
| 167 | * measured: 213 s dark = 180 s drain + 33 s start. | |
| 168 | */ | |
| 169 | export const DARK_TIMING: DarkTiming = { | |
| 170 | drainSeconds: 180, | |
| 171 | startSeconds: 33, | |
| 172 | graceSeconds: 300, | |
| 173 | startCeilingSeconds: 3 * 60 + 5, | |
| 174 | }; | |
| 175 | ||
| 176 | export interface PreflightInput { | |
| 177 | /** The release about to roll, `0.7.53` or `v0.7.53`. */ | |
| 178 | readonly version: string; | |
| 179 | /** `kubectl get node <node> -o json`. */ | |
| 180 | readonly node: unknown; | |
| 181 | /** `kubectl get pods -A -o json` (other nodes' pods are ignored). */ | |
| 182 | readonly pods: unknown; | |
| 183 | /** The running forge pod, `namespace/name`. */ | |
| 184 | readonly forgePod: string; | |
| 185 | /** Its steady memory in bytes (`kubectl top pod`, over a quiet minute). */ | |
| 186 | readonly steadyMemory: number; | |
| 187 | readonly timing?: DarkTiming; | |
| 188 | } | |
| 189 | ||
| 190 | export interface Preflight { | |
| 191 | readonly version: string; | |
| 192 | readonly node: string; | |
| 193 | readonly allocatable: Resources; | |
| 194 | readonly requested: Resources; | |
| 195 | readonly podsOnNode: number; | |
| 196 | readonly free: Resources; | |
| 197 | readonly forgeRequest: Resources; | |
| 198 | readonly steadyMemory: number; | |
| 199 | readonly need: Resources; | |
| 200 | /** Would the scheduler place the surge pod at all (requests only)? */ | |
| 201 | readonly schedulable: boolean; | |
| 202 | /** Would it place it *and* would both pods' steady memory fit? */ | |
| 203 | readonly fits: boolean; | |
| 204 | /** What more must be free on this node for the roll to be zero-downtime. */ | |
| 205 | readonly shortfall: Resources; | |
| 206 | /** If rolled dark anyway: typical and worst seconds without service. */ | |
| 207 | readonly darkSeconds: { readonly typical: number; readonly worst: number }; | |
| 208 | /** | |
| 209 | * This roll under these numbers. Public — anyone who reads the node can | |
| 210 | * compute it — so it is never the yes; it binds the yes (an `Ask`) to | |
| 211 | * one roll. | |
| 212 | */ | |
| 213 | readonly rollKey: string; | |
| 214 | readonly timing: DarkTiming; | |
| 215 | } | |
| 216 | ||
| 217 | const VERSION = /^v?([0-9]{1,4}\.[0-9]{1,4}\.[0-9]{1,6}(?:-[0-9A-Za-z.-]{1,40})?)$/; | |
| 218 | const POD = /^([a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?)\/([a-z0-9]([-a-z0-9.]{0,251}[a-z0-9])?)$/; | |
| 219 | ||
| 220 | /** | |
| 221 | * A roll's key: the version and the node's numbers it was judged on. A yes | |
| 222 | * bound to it is a yes for this release under this pressure, never the next | |
| 223 | * release and never a standing yes. It is a hash of public numbers, so it | |
| 224 | * only names the roll; the yes itself is the `Ask`'s random id. | |
| 225 | */ | |
| 226 | export function rollKey(p: { | |
| 227 | version: string; | |
| 228 | node: string; | |
| 229 | free: Resources; | |
| 230 | need: Resources; | |
| 231 | }): string { | |
| 232 | const mib = (n: number) => Math.round(n / 2 ** 20); | |
| 233 | const text = JSON.stringify([ | |
| 234 | p.version, | |
| 235 | p.node, | |
| 236 | mib(p.free.memory), | |
| 237 | p.free.milliCpu, | |
| 238 | mib(p.need.memory), | |
| 239 | p.need.milliCpu, | |
| 240 | ]); | |
| 241 | return createHash("sha256").update(text).digest("hex").slice(0, 12); | |
| 242 | } | |
| 243 | ||
| 244 | /** Decide. Throws on input that is not what `kubectl` prints. */ | |
| 245 | export function preflight(input: PreflightInput): Preflight { | |
| 246 | const v = VERSION.exec(input.version.trim()); | |
| 247 | if (!v?.[1]) throw new Error(`version ${JSON.stringify(input.version)} is not x.y.z`); | |
| 248 | const version = v[1]; | |
| 249 | const pod = POD.exec(input.forgePod.trim()); | |
| 250 | if (!pod) throw new Error(`forge pod ${JSON.stringify(input.forgePod)} is not namespace/name`); | |
| 251 | const [ns, podName] = [pod[1], pod[3]]; | |
| 252 | if (!Number.isFinite(input.steadyMemory) || input.steadyMemory <= 0) | |
| 253 | throw new Error("steady memory must be a positive quantity"); | |
| 254 | const timing = input.timing ?? DARK_TIMING; | |
| 255 | ||
| 256 | const nodeName = obj(obj(input.node)["metadata"])["name"]; | |
| 257 | if (typeof nodeName !== "string" || nodeName === "") | |
| 258 | throw new Error("node: no metadata.name — is it `kubectl get node -o json`?"); | |
| 259 | const allocatable = resources( | |
| 260 | obj(obj(input.node)["status"])["allocatable"], | |
| 261 | `node ${nodeName}`, | |
| 262 | ); | |
| 263 | if (allocatable.memory <= 0 || allocatable.milliCpu <= 0) | |
| 264 | throw new Error(`node ${nodeName}: no status.allocatable cpu and memory`); | |
| 265 | ||
| 266 | const items = list(obj(input.pods)["items"]); | |
| 267 | const forge = items.find((p) => { | |
| 268 | const m = obj(obj(p)["metadata"]); | |
| 269 | return m["namespace"] === ns && m["name"] === podName; | |
| 270 | }); | |
| 271 | if (!forge) throw new Error(`pods: no ${ns}/${podName} in the list`); | |
| 272 | if (obj(obj(forge)["spec"])["nodeName"] !== nodeName) | |
| 273 | throw new Error(`${ns}/${podName} is not on node ${nodeName}: the volume's node is the one to judge`); | |
| 274 | ||
| 275 | const onNode = items.filter((p) => holdsNode(p, nodeName)); | |
| 276 | const requested = onNode.reduce<Resources>((s, p) => add(s, podRequest(p)), ZERO); | |
| 277 | const free = { | |
| 278 | milliCpu: allocatable.milliCpu - requested.milliCpu, | |
| 279 | memory: allocatable.memory - requested.memory, | |
| 280 | }; | |
| 281 | const forgeRequest = podRequest(forge); | |
| 282 | const need = { | |
| 283 | milliCpu: forgeRequest.milliCpu, | |
| 284 | memory: Math.max(forgeRequest.memory, input.steadyMemory), | |
| 285 | }; | |
| 286 | const schedulable = | |
| 287 | free.milliCpu >= forgeRequest.milliCpu && free.memory >= forgeRequest.memory; | |
| 288 | const fits = free.milliCpu >= need.milliCpu && free.memory >= need.memory; | |
| 289 | const shortfall = { | |
| 290 | milliCpu: Math.max(0, need.milliCpu - free.milliCpu), | |
| 291 | memory: Math.max(0, need.memory - free.memory), | |
| 292 | }; | |
| 293 | return { | |
| 294 | version, | |
| 295 | node: nodeName, | |
| 296 | allocatable, | |
| 297 | requested, | |
| 298 | podsOnNode: onNode.length, | |
| 299 | free, | |
| 300 | forgeRequest, | |
| 301 | steadyMemory: input.steadyMemory, | |
| 302 | need, | |
| 303 | schedulable, | |
| 304 | fits, | |
| 305 | shortfall, | |
| 306 | darkSeconds: { | |
| 307 | typical: timing.drainSeconds + timing.startSeconds, | |
| 308 | worst: timing.graceSeconds + timing.startCeilingSeconds, | |
| 309 | }, | |
| 310 | rollKey: rollKey({ version, node: nodeName, free, need }), | |
| 311 | timing, | |
| 312 | }; | |
| 313 | } | |
| 314 | ||
| 315 | /** | |
| 316 | * The question put to the owner about one dark roll: a random id, drawn | |
| 317 | * when the report is made and kept where only the agent reads it | |
| 318 | * (`FORGE_APP_DATA`), bound to the roll's key. The owner's yes quotes the | |
| 319 | * id; nobody can compute it from the node's numbers or before the report. | |
| 320 | */ | |
| 321 | export interface Ask { | |
| 322 | readonly key: string; | |
| 323 | readonly id: string; | |
| 324 | readonly askedAt: string; | |
| 325 | } | |
| 326 | ||
| 327 | /** 96 random bits, as 24 hex digits. */ | |
| 328 | export const ASK_ID = /^[0-9a-f]{24}$/; | |
| 329 | ||
| 330 | /** A stored ask as read back from disk, or null when it is not one. */ | |
| 331 | export function parseAsk(v: unknown): Ask | null { | |
| 332 | const o = obj(v); | |
| 333 | const { key, id, askedAt } = o; | |
| 334 | if (typeof key !== "string" || !/^[0-9a-f]{12}$/.test(key)) return null; | |
| 335 | if (typeof id !== "string" || !ASK_ID.test(id)) return null; | |
| 336 | if (typeof askedAt !== "string" || Number.isNaN(Date.parse(askedAt))) return null; | |
| 337 | return { key, id, askedAt }; | |
| 338 | } | |
| 339 | ||
| 340 | /** | |
| 341 | * The ask for this roll: the standing one when it is for this roll (so | |
| 342 | * re-running the gate does not move the id under the owner), else a new | |
| 343 | * one with an id from `draw` — which replaces the old and voids its yes. | |
| 344 | */ | |
| 345 | export function askFor( | |
| 346 | p: Preflight, | |
| 347 | standing: Ask | null, | |
| 348 | draw: () => string, | |
| 349 | now: Date, | |
| 350 | ): Ask { | |
| 351 | if (standing !== null && standing.key === p.rollKey) return standing; | |
| 352 | const id = draw(); | |
| 353 | if (!ASK_ID.test(id)) throw new Error("the drawn roll id is not 24 hex digits"); | |
| 354 | return { key: p.rollKey, id, askedAt: now.toISOString() }; | |
| 355 | } | |
| 356 | ||
| 357 | function sameId(a: string, b: string): boolean { | |
| 358 | const x = Buffer.from(a); | |
| 359 | const y = Buffer.from(b); | |
| 360 | return x.length === y.length && timingSafeEqual(x, y); | |
| 361 | } | |
| 362 | ||
| 363 | /** What the agent may do: roll, or wait for the owner. */ | |
| 364 | export type Decision = | |
| 365 | | { readonly go: true; readonly dark: false } | |
| 366 | | { readonly go: true; readonly dark: true } | |
| 367 | | { readonly go: false; readonly why: string }; | |
| 368 | ||
| 369 | /** | |
| 370 | * A roll that fits goes. One that does not goes only with the owner's yes | |
| 371 | * to exactly the id of the ask posted for it — no ask, an ask for another | |
| 372 | * roll (another release, or this one under other numbers), or any other | |
| 373 | * text, the public key included, is no yes. | |
| 374 | */ | |
| 375 | export function decide( | |
| 376 | p: Preflight, | |
| 377 | ownerYes: string | undefined, | |
| 378 | ask: Ask | null, | |
| 379 | ): Decision { | |
| 380 | if (p.fits) return { go: true, dark: false }; | |
| 381 | const yes = ownerYes?.trim(); | |
| 382 | if (yes !== undefined && ask !== null && ask.key === p.rollKey && sameId(yes, ask.id)) | |
| 383 | return { go: true, dark: true }; | |
| 384 | return { | |
| 385 | go: false, | |
| 386 | why: | |
| 387 | yes === undefined | |
| 388 | ? "a second forge pod does not fit: waiting for the owner's yes to this roll" | |
| 389 | : ask === null || ask.key !== p.rollKey | |
| 390 | ? `no roll id was asked for this roll: the yes ${JSON.stringify(yes).slice(0, 40)} answers nothing` | |
| 391 | : `the yes ${JSON.stringify(yes).slice(0, 40)} is not the id asked for this roll`, | |
| 392 | }; | |
| 393 | } | |
| 394 | ||
| 395 | const gib = (n: number) => `${(n / 2 ** 30).toFixed(2)} GiB`; | |
| 396 | const cores = (milli: number) => `${(milli / 1000).toFixed(2)} cpu`; | |
| 397 | ||
| 398 | /** | |
| 399 | * The report the agent posts to the owner, as plain lines. `ask` is the | |
| 400 | * question it carries when the roll would go dark. | |
| 401 | */ | |
| 402 | export function report(p: Preflight, d: Decision, ask: Ask | null = null): string { | |
| 403 | const row = (label: string, r: Resources, extra = "") => | |
| 404 | ` ${label.padEnd(20)}${gib(r.memory).padStart(11)} ${cores(r.milliCpu).padStart(10)}${extra}`; | |
| 405 | const head = p.fits | |
| 406 | ? `roll v${p.version} on ${p.node}: zero-downtime — a second forge pod fits` | |
| 407 | : `roll v${p.version} on ${p.node}: DARK — a second forge pod does not fit` + | |
| 408 | (p.schedulable ? " beside the first once both hold their steady memory" : ""); | |
| 409 | const lines = [ | |
| 410 | head, | |
| 411 | row("node allocatable", p.allocatable), | |
| 412 | row("requested now", p.requested, ` (${p.podsOnNode} pods)`), | |
| 413 | row("free", p.free), | |
| 414 | row( | |
| 415 | "surge pod needs", | |
| 416 | p.need, | |
| 417 | ` (request ${gib(p.forgeRequest.memory)}, steady ${gib(p.steadyMemory)})`, | |
| 418 | ), | |
| 419 | ]; | |
| 420 | if (!p.fits) { | |
| 421 | const t = p.timing; | |
| 422 | lines.push( | |
| 423 | row("short by", p.shortfall), | |
| 424 | ` dark for about ${p.darkSeconds.typical} s (drain ${t.drainSeconds} s + start ${t.startSeconds} s), at most ${p.darkSeconds.worst} s`, | |
| 425 | ` zero-downtime needs ${gib(p.shortfall.memory)} and ${cores(p.shortfall.milliCpu)} more free on ${p.node}` + | |
| 426 | " (a larger node, or fewer requests on this one)", | |
| 427 | ); | |
| 428 | if (ask !== null && !d.go) lines.push(` roll id ${ask.id}`); | |
| 429 | } | |
| 430 | if (d.go && d.dark) | |
| 431 | lines.push(`rolling dark: the owner said yes to roll ${ask?.id ?? "?"}`); | |
| 432 | else if (d.go) lines.push("rolling"); | |
| 433 | else { | |
| 434 | lines.push(`not rolling: ${d.why}`); | |
| 435 | if (!p.fits) | |
| 436 | lines.push( | |
| 437 | "a yes counts only from the owner's own reply to this report, quoting the roll id", | |
| 438 | ); | |
| 439 | } | |
| 440 | return lines.join("\n"); | |
| 441 | } | |
| 442 | ||
| 443 | /** | |
| 444 | * Lines of a manifest or values file that make no-surge a standing value: | |
| 445 | * `maxSurge: 0` (or `0%`) or `type: Recreate`. A dark roll the owner said | |
| 446 | * yes to is a one-off patch, undone after the roll; it never lives in the | |
| 447 | * chart or the gitops overlay. | |
| 448 | */ | |
| 449 | export function standingNoSurge(text: string): string[] { | |
| 450 | const found: string[] = []; | |
| 451 | for (const line of text.split("\n")) { | |
| 452 | const code = line.replace(/#.*$/, ""); | |
| 453 | if ( | |
| 454 | /\bmaxSurge["']?\s*[:=]\s*["']?0+%?["']?(?![0-9.%])/.test(code) || | |
| 455 | /\btype["']?\s*:\s*["']?Recreate\b/.test(code) | |
| 456 | ) | |
| 457 | found.push(line.trim()); | |
| 458 | } | |
| 459 | return found; | |
| 460 | } |
test/roll.test.ts added +385
| @@ -0,0 +1,385 @@ | ||
| 1 | /** | |
| 2 | * The roll gate (#876): a release that would go dark does not roll unless | |
| 3 | * the owner said yes to that roll, and no-surge is never a standing value. | |
| 4 | * Every number below is worked by hand in the comment beside it. | |
| 5 | */ | |
| 6 | ||
| 7 | import { describe, expect, test } from "bun:test"; | |
| 8 | import { createHash } from "node:crypto"; | |
| 9 | import { existsSync, mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { run } from "../scripts/roll-preflight.ts"; | |
| 13 | import { | |
| 14 | askFor, | |
| 15 | DARK_TIMING, | |
| 16 | decide, | |
| 17 | parseQuantity, | |
| 18 | podRequest, | |
| 19 | preflight, | |
| 20 | report, | |
| 21 | standingNoSurge, | |
| 22 | } from "../scripts/roll.ts"; | |
| 23 | ||
| 24 | const Mi = 2 ** 20; | |
| 25 | ||
| 26 | const container = (cpu: string, memory: string) => ({ | |
| 27 | name: "c", | |
| 28 | resources: { requests: { cpu, memory } }, | |
| 29 | }); | |
| 30 | ||
| 31 | function pod( | |
| 32 | ns: string, | |
| 33 | name: string, | |
| 34 | spec: Record<string, unknown>, | |
| 35 | phase = "Running", | |
| 36 | nodeName = "droplet", | |
| 37 | ) { | |
| 38 | return { | |
| 39 | metadata: { namespace: ns, name }, | |
| 40 | spec: { nodeName, ...spec }, | |
| 41 | status: { phase }, | |
| 42 | }; | |
| 43 | } | |
| 44 | ||
| 45 | // Requests on node "droplet" (Running and Pending pods only): | |
| 46 | // forge 1 cpu 2048 Mi | |
| 47 | // two-box 1.5 cpu 3072 Mi (1000m/2Gi + 500m/1Gi) | |
| 48 | // init-heavy 0.5 cpu 512 Mi (max(init 500m/512Mi, main 100m/256Mi)) | |
| 49 | // overhead 0.1 cpu 128 Mi (no container requests, runtime overhead) | |
| 50 | // ───────────────────────────────── | |
| 51 | // requested 3.1 cpu 5760 Mi | |
| 52 | // Not counted: a Succeeded job (4 Gi) and a pod on another node (4 Gi). | |
| 53 | const PODS = { | |
| 54 | items: [ | |
| 55 | pod("forge", "forge-abc", { containers: [container("1", "2Gi")] }), | |
| 56 | pod("db", "two-box", { | |
| 57 | containers: [container("1000m", "2Gi"), container("500m", "1Gi")], | |
| 58 | }), | |
| 59 | pod("ops", "init-heavy", { | |
| 60 | initContainers: [container("500m", "512Mi")], | |
| 61 | containers: [container("100m", "256Mi")], | |
| 62 | }), | |
| 63 | pod("ops", "overhead", { | |
| 64 | containers: [{ name: "c" }], | |
| 65 | overhead: { cpu: "100m", memory: "128Mi" }, | |
| 66 | }), | |
| 67 | pod("ops", "done-job", { containers: [container("1", "4Gi")] }, "Succeeded"), | |
| 68 | pod("ops", "elsewhere", { containers: [container("1", "4Gi")] }, "Running", "other"), | |
| 69 | ], | |
| 70 | }; | |
| 71 | ||
| 72 | const node = (cpu: string, memory: string) => ({ | |
| 73 | metadata: { name: "droplet" }, | |
| 74 | status: { allocatable: { cpu, memory } }, | |
| 75 | }); | |
| 76 | ||
| 77 | const STEADY = 3712 * Mi; // 3.625 GiB, what the forge holds once warm | |
| 78 | const ID = "0123456789abcdef01234567"; | |
| 79 | const OTHER = "fedcba9876543210fedcba98"; | |
| 80 | const NOW = new Date("2026-10-14T12:00:00Z"); | |
| 81 | ||
| 82 | function judge(cpu: string, memory: string, version = "0.7.53") { | |
| 83 | return preflight({ | |
| 84 | version, | |
| 85 | node: node(cpu, memory), | |
| 86 | pods: PODS, | |
| 87 | forgePod: "forge/forge-abc", | |
| 88 | steadyMemory: STEADY, | |
| 89 | }); | |
| 90 | } | |
| 91 | ||
| 92 | describe("quantities", () => { | |
| 93 | test("parse as kubectl prints them", () => { | |
| 94 | expect(parseQuantity("8130464Ki")).toBe(8130464 * 1024); | |
| 95 | expect(parseQuantity("2Gi")).toBe(2 * 2 ** 30); | |
| 96 | expect(parseQuantity("1G")).toBe(1e9); | |
| 97 | expect(parseQuantity("500m")).toBe(0.5); | |
| 98 | expect(parseQuantity("1.5")).toBe(1.5); | |
| 99 | expect(parseQuantity("12e6")).toBe(12e6); | |
| 100 | expect(parseQuantity("250000n")).toBeCloseTo(0.00025, 12); | |
| 101 | }); | |
| 102 | test("refuse what is not a quantity", () => { | |
| 103 | for (const bad of ["", "Gi", "2 Gi", "-1", "1Zi", "1e", "0x10", "1Gi;rm"]) | |
| 104 | expect(parseQuantity(bad)).toBeNull(); | |
| 105 | expect(parseQuantity(5)).toBeNull(); | |
| 106 | }); | |
| 107 | }); | |
| 108 | ||
| 109 | describe("a pod's request, as the scheduler reckons it", () => { | |
| 110 | test("init floor, sidecars summed, overhead added", () => { | |
| 111 | // sidecar 100m/64Mi runs throughout; plain init 2 cpu/1Gi runs after it, | |
| 112 | // so its floor is 2.1 cpu / 1088 Mi; containers + sidecar = 0.6 / 576 Mi. | |
| 113 | // max → 2.1 cpu / 1088 Mi, + overhead 50m/32Mi → 2.15 cpu / 1120 Mi. | |
| 114 | const r = podRequest( | |
| 115 | pod("x", "y", { | |
| 116 | initContainers: [ | |
| 117 | { ...container("100m", "64Mi"), restartPolicy: "Always" }, | |
| 118 | container("2", "1Gi"), | |
| 119 | ], | |
| 120 | containers: [container("500m", "512Mi")], | |
| 121 | overhead: { cpu: "50m", memory: "32Mi" }, | |
| 122 | }), | |
| 123 | ); | |
| 124 | expect(r.milliCpu).toBe(2150); | |
| 125 | expect(r.memory).toBe(1120 * Mi); | |
| 126 | }); | |
| 127 | }); | |
| 128 | ||
| 129 | describe("preflight", () => { | |
| 130 | test("the 8 GB droplet: dark, with the shortfall and the seconds", () => { | |
| 131 | // allocatable 3.9 cpu / 7680 Mi − requested 3.1 / 5760 → free 0.8 / 1920 Mi | |
| 132 | // need: cpu 1, memory max(2048, 3712) = 3712 Mi | |
| 133 | // short: 0.2 cpu, 3712 − 1920 = 1792 Mi = 1.75 GiB | |
| 134 | const p = judge("3900m", "7680Mi"); | |
| 135 | expect(p.podsOnNode).toBe(4); | |
| 136 | expect(p.requested.milliCpu).toBe(3100); | |
| 137 | expect(p.requested.memory).toBe(5760 * Mi); | |
| 138 | expect(p.free.milliCpu).toBe(800); | |
| 139 | expect(p.free.memory).toBe(1920 * Mi); | |
| 140 | expect(p.need).toEqual({ milliCpu: 1000, memory: 3712 * Mi }); | |
| 141 | expect(p.schedulable).toBe(false); | |
| 142 | expect(p.fits).toBe(false); | |
| 143 | expect(p.shortfall.milliCpu).toBe(200); | |
| 144 | expect(p.shortfall.memory).toBe(1792 * Mi); | |
| 145 | // 180 s drain + 33 s start (v0.7.52's 3 min 33 s); worst 300 s grace + 3 s × 60 + 5 s | |
| 146 | expect(p.darkSeconds).toEqual({ typical: 213, worst: 485 }); | |
| 147 | const ask = askFor(p, null, () => ID, NOW); | |
| 148 | const text = report(p, decide(p, undefined, ask), ask); | |
| 149 | expect(text).toContain("DARK"); | |
| 150 | expect(text).toContain("1.75 GiB"); | |
| 151 | expect(text).toContain("about 213 s"); | |
| 152 | expect(text).toContain(`roll id ${ID}`); | |
| 153 | expect(text).not.toContain(p.rollKey); | |
| 154 | expect(text).toContain("not rolling"); | |
| 155 | }); | |
| 156 | ||
| 157 | test("schedulable on requests is not enough: steady memory decides", () => { | |
| 158 | // allocatable 4.1 cpu / 8704 Mi → free 1.0 / 2944 Mi: the request | |
| 159 | // (1 / 2048) fits, the steady 3712 Mi does not: short 768 Mi = 0.75 GiB | |
| 160 | const p = judge("4100m", "8704Mi"); | |
| 161 | expect(p.schedulable).toBe(true); | |
| 162 | expect(p.fits).toBe(false); | |
| 163 | expect(p.shortfall).toEqual({ milliCpu: 0, memory: 768 * Mi }); | |
| 164 | expect(decide(p, undefined, null).go).toBe(false); | |
| 165 | }); | |
| 166 | ||
| 167 | test("room for two pods rolls without asking", () => { | |
| 168 | // 16 Gi / 8 cpu → free 10624 Mi / 4.9 cpu ≥ 3712 Mi / 1 cpu | |
| 169 | const p = judge("8", "16Gi"); | |
| 170 | expect(p.fits).toBe(true); | |
| 171 | expect(p.shortfall).toEqual({ milliCpu: 0, memory: 0 }); | |
| 172 | expect(decide(p, undefined, null)).toEqual({ go: true, dark: false }); | |
| 173 | expect(report(p, decide(p, undefined, null))).toContain("zero-downtime"); | |
| 174 | }); | |
| 175 | ||
| 176 | test("the owner's yes covers that roll and no other", () => { | |
| 177 | const p = judge("3900m", "7680Mi"); | |
| 178 | const ask = askFor(p, null, () => ID, NOW); | |
| 179 | expect(decide(p, ID, ask)).toEqual({ go: true, dark: true }); | |
| 180 | expect(decide(p, ` ${ID}\n`, ask).go).toBe(true); | |
| 181 | // the next release under the same pressure is a new roll | |
| 182 | const next = judge("3900m", "7680Mi", "0.7.54"); | |
| 183 | expect(next.rollKey).not.toBe(p.rollKey); | |
| 184 | expect(decide(next, ID, ask).go).toBe(false); | |
| 185 | // so is this release once the node's numbers move | |
| 186 | const moved = judge("3900m", "7000Mi"); | |
| 187 | expect(decide(moved, ID, ask).go).toBe(false); | |
| 188 | // a blanket word is no yes | |
| 189 | for (const word of ["yes", "", "*", "true"]) expect(decide(p, word, ask).go).toBe(false); | |
| 190 | // nor is the right id with no ask behind it | |
| 191 | expect(decide(p, ID, null).go).toBe(false); | |
| 192 | // judging the same numbers again names the same roll | |
| 193 | expect(judge("3900m", "7680Mi", "v0.7.53").rollKey).toBe(p.rollKey); | |
| 194 | }); | |
| 195 | ||
| 196 | test("an id computed from the public numbers is no yes", () => { | |
| 197 | const p = judge("3900m", "7680Mi"); | |
| 198 | const ask = askFor(p, null, () => ID, NOW); | |
| 199 | // everything the key is made of can be read off `kubectl get node` | |
| 200 | const forged = createHash("sha256") | |
| 201 | .update(JSON.stringify(["0.7.53", "droplet", 1920, 800, 3712, 1000])) | |
| 202 | .digest("hex"); | |
| 203 | expect(forged.slice(0, 12)).toBe(p.rollKey); | |
| 204 | for (const guess of [p.rollKey, forged, forged.slice(0, 24)]) | |
| 205 | expect(decide(p, guess, ask).go).toBe(false); | |
| 206 | }); | |
| 207 | ||
| 208 | test("the ask keeps its id while the roll is the same, and draws anew when it moves", () => { | |
| 209 | const p = judge("3900m", "7680Mi"); | |
| 210 | const ask = askFor(p, null, () => ID, NOW); | |
| 211 | expect(ask).toEqual({ key: p.rollKey, id: ID, askedAt: NOW.toISOString() }); | |
| 212 | expect(askFor(p, ask, () => OTHER, NOW)).toBe(ask); | |
| 213 | const moved = judge("3900m", "7000Mi"); | |
| 214 | expect(askFor(moved, ask, () => OTHER, NOW).id).toBe(OTHER); | |
| 215 | expect(() => askFor(moved, null, () => "not-random", NOW)).toThrow(/24 hex/); | |
| 216 | }); | |
| 217 | ||
| 218 | test("input that is not kubectl's is refused, not guessed", () => { | |
| 219 | expect(() => judge("3900m", "7680Mi", "latest")).toThrow(/version/); | |
| 220 | expect(() => | |
| 221 | preflight({ version: "0.7.53", node: node("4", "8Gi"), pods: PODS, forgePod: "forge/nope", steadyMemory: STEADY }), | |
| 222 | ).toThrow(/no forge\/nope/); | |
| 223 | expect(() => | |
| 224 | preflight({ version: "0.7.53", node: node("4", "8Gi"), pods: PODS, forgePod: "ops/elsewhere", steadyMemory: STEADY }), | |
| 225 | ).toThrow(/not on node/); | |
| 226 | expect(() => | |
| 227 | preflight({ version: "0.7.53", node: {}, pods: PODS, forgePod: "forge/forge-abc", steadyMemory: STEADY }), | |
| 228 | ).toThrow(/metadata.name/); | |
| 229 | expect(() => | |
| 230 | preflight({ version: "0.7.53", node: node("4", "lots"), pods: PODS, forgePod: "forge/forge-abc", steadyMemory: STEADY }), | |
| 231 | ).toThrow(/not a quantity/); | |
| 232 | }); | |
| 233 | }); | |
| 234 | ||
| 235 | describe("no-surge is never a standing value", () => { | |
| 236 | test("found where it is written", () => { | |
| 237 | expect(standingNoSurge(" maxSurge: 0")).toHaveLength(1); | |
| 238 | expect(standingNoSurge(`maxSurge: "0%"`)).toHaveLength(1); | |
| 239 | expect(standingNoSurge("rollingUpdate: {maxSurge: 0, maxUnavailable: 1}")).toHaveLength(1); | |
| 240 | expect(standingNoSurge(`{"maxSurge":0}`)).toHaveLength(1); | |
| 241 | expect(standingNoSurge(" type: Recreate")).toHaveLength(1); | |
| 242 | expect(standingNoSurge("maxSurge: 1\nmaxSurge: 10\nmaxSurge: 25%\n# maxSurge: 0")).toEqual([]); | |
| 243 | }); | |
| 244 | ||
| 245 | const deployment = readFileSync( | |
| 246 | join(import.meta.dir, "../charts/app/templates/deployment.yaml"), | |
| 247 | "utf8", | |
| 248 | ); | |
| 249 | ||
| 250 | test("the chart surges one and never takes the only pod down", () => { | |
| 251 | expect(standingNoSurge(deployment)).toEqual([]); | |
| 252 | expect( | |
| 253 | standingNoSurge(readFileSync(join(import.meta.dir, "../charts/app/values.yaml"), "utf8")), | |
| 254 | ).toEqual([]); | |
| 255 | expect(deployment).toMatch(/maxSurge: 1\n\s*maxUnavailable: 0\n/); | |
| 256 | }); | |
| 257 | ||
| 258 | test("the dark-seconds ceilings are the chart's own", () => { | |
| 259 | const n = (re: RegExp) => Number(re.exec(deployment)?.[1]); | |
| 260 | expect(n(/terminationGracePeriodSeconds: (\d+)/)).toBe(DARK_TIMING.graceSeconds); | |
| 261 | const startup = /startupProbe:[\s\S]*?periodSeconds: (\d+)\s*\n\s*failureThreshold: (\d+)/.exec(deployment); | |
| 262 | const readiness = n(/readinessProbe:[\s\S]*?periodSeconds: (\d+)/); | |
| 263 | expect(Number(startup?.[1]) * Number(startup?.[2]) + readiness).toBe( | |
| 264 | DARK_TIMING.startCeilingSeconds, | |
| 265 | ); | |
| 266 | }); | |
| 267 | }); | |
| 268 | ||
| 269 | describe("the gate the release agent runs", () => { | |
| 270 | const dir = mkdtempSync(join(tmpdir(), "roll-")); | |
| 271 | const file = (name: string, body: unknown) => { | |
| 272 | const path = join(dir, name); | |
| 273 | writeFileSync(path, typeof body === "string" ? body : JSON.stringify(body)); | |
| 274 | return path; | |
| 275 | }; | |
| 276 | const tight = file("node.json", node("3900m", "7680Mi")); | |
| 277 | const roomy = file("roomy.json", node("8", "16Gi")); | |
| 278 | const pods = file("pods.json", PODS); | |
| 279 | const args = (n: string) => [ | |
| 280 | "--version", "0.7.53", "--node", n, "--pods", pods, | |
| 281 | "--pod", "forge/forge-abc", "--steady", "3712Mi", | |
| 282 | ]; | |
| 283 | let ids: string[] = []; | |
| 284 | const world = (data: string | undefined) => ({ | |
| 285 | env: { FORGE_APP_DATA: data }, | |
| 286 | draw: () => { | |
| 287 | const id = ids.shift(); | |
| 288 | if (id === undefined) throw new Error("drew more ids than the test expected"); | |
| 289 | return id; | |
| 290 | }, | |
| 291 | now: () => NOW, | |
| 292 | }); | |
| 293 | const fresh = () => mkdtempSync(join(dir, "data-")); | |
| 294 | ||
| 295 | test("exits 3 and waits when the roll would go dark, with a random roll id kept aside", () => { | |
| 296 | const data = fresh(); | |
| 297 | ids = [ID]; | |
| 298 | const r = run(args(tight), world(data)); | |
| 299 | expect(r.code).toBe(3); | |
| 300 | expect(r.out).toContain("waiting for the owner's yes"); | |
| 301 | expect(r.out).toContain("a yes counts only from the owner's own reply"); | |
| 302 | expect(r.out).toContain(`roll id ${ID}`); | |
| 303 | const kept = join(data, "roll-ask.json"); | |
| 304 | expect(JSON.parse(readFileSync(kept, "utf8")).id).toBe(ID); | |
| 305 | expect(statSync(kept).mode & 0o777).toBe(0o600); | |
| 306 | // asking again for the same roll does not move the id under the owner | |
| 307 | const again = run(args(tight), world(data)); | |
| 308 | expect(again.out).toContain(`roll id ${ID}`); | |
| 309 | }); | |
| 310 | ||
| 311 | test("exits 0 once with the owner's yes to the id it asked", () => { | |
| 312 | const data = fresh(); | |
| 313 | ids = [ID]; | |
| 314 | run(args(tight), world(data)); | |
| 315 | const r = run([...args(tight), "--yes", ID], world(data)); | |
| 316 | expect(r.code).toBe(0); | |
| 317 | expect(r.out).toContain(`the owner said yes to roll ${ID}`); | |
| 318 | expect(existsSync(join(data, "roll-ask.json"))).toBe(false); | |
| 319 | // a yes is for one roll: the same id again answers nothing, and a new id is asked | |
| 320 | ids = [OTHER]; | |
| 321 | const twice = run([...args(tight), "--yes", ID], world(data)); | |
| 322 | expect(twice.code).toBe(3); | |
| 323 | expect(twice.out).toContain(`roll id ${OTHER}`); | |
| 324 | }); | |
| 325 | ||
| 326 | test("refuses an id recomputed from the public numbers, and one never asked", () => { | |
| 327 | const data = fresh(); | |
| 328 | const key = judge("3900m", "7680Mi").rollKey; | |
| 329 | ids = [ID]; | |
| 330 | expect(run([...args(tight), "--yes", key], world(data)).code).toBe(3); | |
| 331 | expect(run([...args(tight), "--yes", "0123456789ab"], world(data)).code).toBe(3); | |
| 332 | expect(run([...args(tight), "--yes", OTHER], world(data)).code).toBe(3); | |
| 333 | // the right id is still the right id: the wrong ones did not move it | |
| 334 | expect(run([...args(tight), "--yes", ID], world(data)).code).toBe(0); | |
| 335 | // with no ask on file, even a well-formed id is refused | |
| 336 | ids = [OTHER]; | |
| 337 | expect(run([...args(tight), "--yes", ID], world(fresh())).code).toBe(3); | |
| 338 | }); | |
| 339 | ||
| 340 | test("--asked names the ask file; with neither it and no FORGE_APP_DATA a dark roll is refused", () => { | |
| 341 | const asked = join(fresh(), "ask.json"); | |
| 342 | ids = [ID]; | |
| 343 | expect(run([...args(tight), "--asked", asked], world(undefined)).code).toBe(3); | |
| 344 | expect(JSON.parse(readFileSync(asked, "utf8")).id).toBe(ID); | |
| 345 | const none = run(args(tight), world(undefined)); | |
| 346 | expect(none.code).toBe(2); | |
| 347 | expect(none.out).toContain("nowhere to keep its id"); | |
| 348 | // a roll with room needs no ask | |
| 349 | expect(run(args(roomy), world(undefined)).code).toBe(0); | |
| 350 | // an ask file that is not an ask is not read as one | |
| 351 | const bad = join(fresh(), "roll-ask.json"); | |
| 352 | writeFileSync(bad, JSON.stringify({ key: "x", id: ID, askedAt: "now" })); | |
| 353 | expect(run([...args(tight), "--asked", bad, "--yes", ID], world(undefined)).code).toBe(2); | |
| 354 | }); | |
| 355 | ||
| 356 | test("exits 0 when there is room", () => { | |
| 357 | expect(run(args(roomy), world(undefined)).code).toBe(0); | |
| 358 | }); | |
| 359 | ||
| 360 | test("measured timings replace the defaults", () => { | |
| 361 | ids = [ID]; | |
| 362 | const r = run( | |
| 363 | [...args(tight), "--json", "--drain-seconds", "20", "--start-seconds", "40"], | |
| 364 | world(fresh()), | |
| 365 | ); | |
| 366 | expect(r.code).toBe(3); | |
| 367 | expect(JSON.parse(r.out).darkSeconds.typical).toBe(60); | |
| 368 | expect(JSON.parse(r.out).rollId).toBe(ID); | |
| 369 | }); | |
| 370 | ||
| 371 | test("exits 4 when an overlay carries no-surge, even with room", () => { | |
| 372 | const overlay = file("hr.yaml", "spec:\n strategy:\n rollingUpdate:\n maxSurge: 0\n"); | |
| 373 | const r = run([...args(roomy), "--overlay", overlay]); | |
| 374 | expect(r.code).toBe(4); | |
| 375 | expect(r.out).toContain("maxSurge: 0"); | |
| 376 | }); | |
| 377 | ||
| 378 | test("exits 2 on input it does not understand", () => { | |
| 379 | expect(run([...args(tight), "--force"]).code).toBe(2); | |
| 380 | expect(run(args(tight).slice(2)).code).toBe(2); | |
| 381 | expect(run([...args(tight).slice(0, -1), "lots"]).code).toBe(2); | |
| 382 | expect(run([...args(tight), "--drain-seconds", "-5"]).code).toBe(2); | |
| 383 | expect(run([...args(tight), "--overlay", join(dir, "missing.yaml")]).code).toBe(2); | |
| 384 | }); | |
| 385 | }); |
new above
offline