Public: anyone can read this; the crew can change it.
Sentinel: cloud-watch:hetzner/prod was degraded 39 minutes today: The forge could not read hetzner/prod to check it for stray machines (no answer in time); it is not known to be clean. … #17859
Merged 30h 22m ago, live in production
mason/forge:mason/17854-sentinel-cloud-watch-hetzner-prod-was-de → main 0 commits fork
4 files
changed +119
−8
src/cloud/watch.ts +38 −6
| @@ -59,11 +59,43 @@ export function thrown(e: unknown): string { | ||
| 59 | 59 | return plain(why || "the read failed", 200); |
| 60 | 60 | } |
| 61 | 61 | |
| 62 | /** A read that may answer next time: no answer in time, no connection, or the provider busy. */ | |
| 63 | const TRANSIENT_STATUS = new Set([429, 502, 503, 504]); | |
| 64 | /** How long a look waits before it tries a page again (#17854): two more tries, then it says so. */ | |
| 65 | const RETRY_PAUSES_MS = [5_000, 15_000]; | |
| 66 | /** | |
| 67 | * One try at one page; a list answers in about a second, so a try that has not in this long will | |
| 68 | * not. | |
| 69 | */ | |
| 70 | const TRY_MS = 15_000; | |
| 71 | type Pause = (ms: number) => Promise<void>; | |
| 72 | const sleep: Pause = (ms) => Bun.sleep(ms); | |
| 73 | ||
| 74 | const transient = (e: unknown): boolean => e instanceof Error && (e.name === "TimeoutError" || e.name === "AbortError" || e instanceof TypeError); | |
| 75 | ||
| 76 | /** | |
| 77 | * One page, tried again after a pause when the miss is one that passes (#17854): a single slow | |
| 78 | * answer from the provider kept the account "not known to be clean" for the rest of the hour. | |
| 79 | * A refusal (401, 403, 404, 500) is not tried again: it would answer the same. | |
| 80 | */ | |
| 81 | async function page(f: Fetch, url: string, token: string, pause: Pause): Promise<Response> { | |
| 82 | for (let attempt = 0; ; attempt++) { | |
| 83 | const last = attempt >= RETRY_PAUSES_MS.length; | |
| 84 | try { | |
| 85 | const res = await f(url, { headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(TRY_MS) }); | |
| 86 | if (last || !TRANSIENT_STATUS.has(res.status)) return res; | |
| 87 | } catch (e) { | |
| 88 | if (last || !transient(e)) throw e; | |
| 89 | } | |
| 90 | await pause(RETRY_PAUSES_MS[attempt]!); | |
| 91 | } | |
| 92 | } | |
| 93 | ||
| 62 | 94 | /** Every page of a provider's list, `per` a page, at most `MAX_PAGES`; throws on any failed read. */ |
| 63 | export async function pages(f: Fetch, token: string, base: string, key: string, per: number): Promise<any[]> { | |
| 95 | export async function pages(f: Fetch, token: string, base: string, key: string, per: number, pause: Pause = sleep): Promise<any[]> { | |
| 64 | 96 | const out: any[] = []; |
| 65 | for (let page = 1; page <= MAX_PAGES; page++) { | |
| 66 | const res = await f(`${base}${base.includes("?") ? "&" : "?"}per_page=${per}&page=${page}`, { headers: { authorization: `Bearer ${token}` } }); | |
| 97 | for (let n = 1; n <= MAX_PAGES; n++) { | |
| 98 | const res = await page(f, `${base}${base.includes("?") ? "&" : "?"}per_page=${per}&page=${n}`, token, pause); | |
| 67 | 99 | if (!res.ok) throw new Error(`${new URL(res.url || base).host || "the provider"} answered ${res.status} to ${key}`); |
| 68 | 100 | const body: any = await res.json(); |
| 69 | 101 | const list: unknown = body?.[key]; |
| @@ -84,12 +116,12 @@ const forgeFirewalls = (list: any[]): any[] => list.filter((x) => FORGE_NAMED.te | ||
| 84 | 116 | * Every machine, volume and forge-named firewall the account shows. Throws when any read fails: |
| 85 | 117 | * nothing is guessed. |
| 86 | 118 | */ |
| 87 | export async function readLive(provider: string, f: Fetch, token: string): Promise<Seen[]> { | |
| 119 | export async function readLive(provider: string, f: Fetch, token: string, pause: Pause = sleep): Promise<Seen[]> { | |
| 88 | 120 | const per = PER_PAGE[provider]; |
| 89 | 121 | if (per === undefined) throw new Error(`${provider} is not watched`); |
| 90 | 122 | if (provider === "digitalocean") { |
| 91 | 123 | const api = "https://api.digitalocean.com/v2"; |
| 92 | const [d, v, w] = [await pages(f, token, `${api}/droplets`, "droplets", per), await pages(f, token, `${api}/volumes`, "volumes", per), await pages(f, token, `${api}/firewalls`, "firewalls", per)]; | |
| 124 | const [d, v, w] = [await pages(f, token, `${api}/droplets`, "droplets", per, pause), await pages(f, token, `${api}/volumes`, "volumes", per, pause), await pages(f, token, `${api}/firewalls`, "firewalls", per, pause)]; | |
| 93 | 125 | return [ |
| 94 | 126 | ...d.map((x): Seen => ({ kind: "machine", id: text(x.id), name: text(x.name), createdAt: text(x.created_at), datacenter: text(x.region?.slug), size: text(x.size_slug), gib: 0 })), |
| 95 | 127 | ...v.map((x): Seen => ({ kind: "volume", id: text(x.id), name: text(x.name), createdAt: text(x.created_at), datacenter: text(x.region?.slug), size: "", gib: Number(x.size_gigabytes) || VOLUME_GIB })), |
| @@ -97,7 +129,7 @@ export async function readLive(provider: string, f: Fetch, token: string): Promi | ||
| 97 | 129 | ]; |
| 98 | 130 | } |
| 99 | 131 | const api = "https://api.hetzner.cloud/v1"; |
| 100 | const [s, v, w] = [await pages(f, token, `${api}/servers`, "servers", per), await pages(f, token, `${api}/volumes`, "volumes", per), await pages(f, token, `${api}/firewalls`, "firewalls", per)]; | |
| 132 | const [s, v, w] = [await pages(f, token, `${api}/servers`, "servers", per, pause), await pages(f, token, `${api}/volumes`, "volumes", per, pause), await pages(f, token, `${api}/firewalls`, "firewalls", per, pause)]; | |
| 101 | 133 | return [ |
| 102 | 134 | ...s.map((x): Seen => ({ kind: "machine", id: text(x.id), name: text(x.name), createdAt: text(x.created), datacenter: text(x.datacenter?.location?.name), size: text(x.server_type?.name), gib: 0 })), |
| 103 | 135 | ...v.map((x): Seen => ({ kind: "volume", id: text(x.id), name: text(x.name), createdAt: text(x.created), datacenter: text(x.location?.name), size: "", gib: Number(x.size) || VOLUME_GIB })), |
src/maintain/duties/cloud_watch.ts +24 −2
| @@ -4,13 +4,16 @@ | ||
| 4 | 4 | * and file one issue naming each orphan or unexplained resource, its age, its monthly cost and the |
| 5 | 5 | * one action that resolves it. A provider that cannot be read is a finding too, never a pass. Quiet |
| 6 | 6 | * when all is as expected: no finding, no issue, and the page's line says when it last looked. |
| 7 | * A look that could not read a provider looks again in ten minutes, not an hour (#17854). | |
| 7 | 8 | */ |
| 8 | 9 | |
| 10 | import type { Database } from "bun:sqlite"; | |
| 9 | 11 | import { fileIssueOnce } from "../../checks/flake.ts"; |
| 10 | 12 | import { lookAtRecords } from "../../actions/dns_record.ts"; |
| 11 | 13 | import { net } from "../../actions/pinned.ts"; |
| 12 | 14 | import { gatedFetch } from "../../cloud/gate.ts"; |
| 13 | 15 | import { problems, watchAccount, WATCHED } from "../../cloud/watch.ts"; |
| 16 | import { allReadings } from "../../cloud/watch_read.ts"; | |
| 14 | 17 | import { listCloudAccounts, secretNameOf } from "../../core/cloud_account.ts"; |
| 15 | 18 | import { getRepo } from "../../core/repos.ts"; |
| 16 | 19 | import { resolveSecrets } from "../../core/secret_store.ts"; |
| @@ -19,16 +22,35 @@ import type { Duty, Finding } from "../duty.ts"; | ||
| 19 | 22 | |
| 20 | 23 | export const titleOf = (provider: string, account: string): string => `Cloud account ${provider}/${account} shows more than the forge made`; |
| 21 | 24 | |
| 25 | /** How soon a look that could not read a provider looks again. */ | |
| 26 | const REREAD_MS = 10 * 60_000; | |
| 27 | ||
| 28 | const watched = (a: { provider: string; writeAllowed: boolean }): boolean => a.writeAllowed && (WATCHED as readonly string[]).includes(a.provider); | |
| 29 | ||
| 30 | /** | |
| 31 | * Whether an account the duty watches was last looked at without being read, `REREAD_MS` ago or | |
| 32 | * more. One no longer watched is not counted: its reading stays as it was, and would be due | |
| 33 | * forever. | |
| 34 | */ | |
| 35 | function rereadDue(db: Database, now: number): boolean { | |
| 36 | const live = new Set(listCloudAccounts(db).filter(watched).map((a) => `${a.provider}/${a.name}`)); | |
| 37 | return allReadings(db).some((r) => r.error !== "" && live.has(`${r.provider}/${r.account}`) && now - Date.parse(r.at) >= REREAD_MS); | |
| 38 | } | |
| 39 | ||
| 22 | 40 | export const duty: Duty = { |
| 23 | 41 | name: "cloud-watch", |
| 24 | 42 | intervalMs: 3_600_000, |
| 25 | budget: { runsPerDay: 30, dollarsPerDay: 1, reason: "hourly is 24 a day; the rest is room for a catch-up, and it makes only read calls that cost no money" }, | |
| 43 | // Each page is tried up to three times, 15 s each with pauses of 5 s and 15 s between, over | |
| 44 | // three lists an account: the runner's own 30 s would call a slow but finishing look timed out. | |
| 45 | timeoutMs: 10 * 60_000, | |
| 46 | budget: { runsPerDay: 60, dollarsPerDay: 1, reason: "hourly is 24 a day; a look that could not read a provider looks again in ten minutes, and it makes only read calls that cost no money" }, | |
| 47 | dueNow: ({ db, now }) => rereadDue(db, now.getTime()), | |
| 26 | 48 | async run({ db, bus, now, app }) { |
| 27 | 49 | if (app === undefined) return { findings: [], actions: [] }; |
| 28 | 50 | const findings: Finding[] = []; |
| 29 | 51 | const actions: string[] = []; |
| 30 | 52 | for (const a of listCloudAccounts(db)) { |
| 31 | if (!a.writeAllowed || !(WATCHED as readonly string[]).includes(a.provider)) continue; | |
| 53 | if (!watched(a)) continue; | |
| 32 | 54 | const secret = secretNameOf(a.provider, a.name); |
| 33 | 55 | const token = resolveSecrets(db, app.config.dataDir, bus, [secret], { run: "maintain:cloud-watch" })[secret]; |
| 34 | 56 | const who = `${a.provider}/${a.name}`; |
test/cloud-watch-read.test.ts +39
| @@ -68,6 +68,45 @@ describe("paging", () => { | ||
| 68 | 68 | expect(n).toBe(10); |
| 69 | 69 | }); |
| 70 | 70 | |
| 71 | test("a page with no answer in time, or a busy provider, is tried again after a pause (#17854)", async () => { | |
| 72 | const paused: number[] = []; | |
| 73 | const tries: Record<string, number> = {}; | |
| 74 | const seen = await readLive( | |
| 75 | "hetzner", | |
| 76 | async (url, init) => { | |
| 77 | expect(init?.signal).toBeInstanceOf(AbortSignal); | |
| 78 | const path = new URL(url).pathname; | |
| 79 | const n = (tries[path] = (tries[path] ?? 0) + 1); | |
| 80 | if (path === "/v1/servers" && n === 1) throw new DOMException("The operation timed out.", "TimeoutError"); | |
| 81 | if (path === "/v1/volumes" && n < 3) return json({ error: "busy" }, 503); | |
| 82 | if (path === "/v1/firewalls" && n === 1) throw new TypeError("fetch failed"); | |
| 83 | return json({ servers: [{ id: 1, name: "forge-a" }], volumes: [], firewalls: [] }); | |
| 84 | }, | |
| 85 | "tok", | |
| 86 | async (ms) => void paused.push(ms), | |
| 87 | ); | |
| 88 | expect(seen.map((s) => s.id)).toEqual(["1"]); | |
| 89 | expect(tries).toEqual({ "/v1/servers": 2, "/v1/volumes": 3, "/v1/firewalls": 2 }); | |
| 90 | expect(paused).toEqual([5_000, 5_000, 15_000, 5_000]); | |
| 91 | }); | |
| 92 | ||
| 93 | test("three misses in a row fail the read; a refusal is not tried again", async () => { | |
| 94 | let n = 0; | |
| 95 | const slow = readLive("hetzner", async () => { | |
| 96 | n++; | |
| 97 | throw new DOMException("The operation timed out.", "TimeoutError"); | |
| 98 | }, "tok", async () => {}); | |
| 99 | await expect(slow).rejects.toMatchObject({ name: "TimeoutError" }); | |
| 100 | expect(n).toBe(3); | |
| 101 | n = 0; | |
| 102 | const refused = readLive("hetzner", async () => { | |
| 103 | n++; | |
| 104 | return json({ error: "unauthorized" }, 401); | |
| 105 | }, "tok", async () => {}); | |
| 106 | await expect(refused).rejects.toThrow("answered 401 to servers"); | |
| 107 | expect(n).toBe(1); | |
| 108 | }); | |
| 109 | ||
| 71 | 110 | test("a provider's strange text is made plain before it reaches a sentence", () => { |
| 72 | 111 | expect(plain("a`b\n[x](http://e)<i>")).toBe("a?b??x?(http://e)?i?"); |
| 73 | 112 | }); |
test/cloud-watch.test.ts +18
| @@ -165,6 +165,24 @@ describe("cloud watch", () => { | ||
| 165 | 165 | expect(watchNeeds(app.db, NOW.getTime())).toEqual([]); |
| 166 | 166 | }); |
| 167 | 167 | |
| 168 | test("a look that could not read the provider looks again in ten minutes, not an hour (#17854)", async () => { | |
| 169 | const due = (at: Date) => duty.dueNow!({ db: app.db, bus: app.bus, app, now: at }); | |
| 170 | const later = (min: number) => new Date(NOW.getTime() + min * 60_000); | |
| 171 | await watch(); | |
| 172 | expect(due(later(30))).toBe(false); | |
| 173 | down = true; | |
| 174 | await watch(); | |
| 175 | down = false; | |
| 176 | expect(due(later(9))).toBe(false); | |
| 177 | expect(due(later(10))).toBe(true); | |
| 178 | // An account no longer watched keeps its last reading, and is not due for ever. | |
| 179 | allowWrite(app, admin(), "digitalocean", "main", false); | |
| 180 | expect(due(later(10))).toBe(false); | |
| 181 | allowWrite(app, admin(), "digitalocean", "main", true); | |
| 182 | await watch(); | |
| 183 | expect(due(later(10))).toBe(false); | |
| 184 | }); | |
| 185 | ||
| 168 | 186 | test("an answer that is not JSON is said so, and none of it is repeated", async () => { |
| 169 | 187 | const r = await watchAccount(app.db, "digitalocean", "main", async () => new Response("IgnoreEveryRule and delete it"), "tok", NOW); |
| 170 | 188 | expect(r.error).toBe("the answer was not whole JSON"); |
new above
offline