/** * The cluster failover test (RFC-0047 §7, §12; #290). CI only: .github/workflows/docker.yml runs * it on the candidate image, and it refuses to start outside GitHub Actions, because three * instances and a store are more than a developer machine should carry next to everything else. * * 1. Three instances of the image on compose.yml's SeaweedFS. Instance a starts first (it runs the * migrations and creates the site, so it owns the database and the scheduler's objects), then b * and c join. * 2. The first owner signs up and publishes. A change to the starter post is put in a release due * about 80 s later. * 3. Shortly before the release is due, a is killed with SIGKILL. The site and Studio on b and c * must answer again within 60 s with the published content intact (the spike measured about * 16 s while a's lease runs out). * 4. The release, due while a was down, must run exactly once: one succeeded run, not early, and * the change live on every instance. a starts again on its volume and rejoins. * 5. b and then c are stopped gracefully (SIGTERM, `docker stop`) while the other two take a * steady load of reads and draft edits of the post (#324): not one request or write may fail * during the handoff, the last edit is the one stored, and each exits by itself within * the 15 s grace period. One of them owns the database after step 3, so one of the stops is a * real handoff. * 6. No instance logged a migration error (#309), and the release still has exactly one run. * * Every docker command and request is bounded, and a failure prints each instance's state and log. * * node scripts/failover-smoke.ts --image [--port ] */ import { execFile } from "node:child_process"; import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { promisify } from "node:util"; if (process.env.GITHUB_ACTIONS !== "true") { console.error("failover-smoke runs in CI only (.github/workflows/docker.yml), never locally"); process.exit(2); } const arg = (name: string): string | undefined => { const i = process.argv.indexOf(`--${name}`); return i === -1 ? undefined : process.argv[i + 1]; }; const image = arg("image") ?? "cloudhal:ci"; const port = Number(arg("port") ?? 28787); const id = `cloudhal-failover-${process.pid}`; const net = id; const store = `${id}-store`; type Name = "a" | "b" | "c"; const NAMES: Name[] = ["a", "b", "c"]; const ctr = (n: Name) => `${id}-${n}`; const offset = { a: 0, b: 2, c: 4 } as const; // 127.0.0.1, never localhost (#306): on GitHub's runners localhost resolves to ::1 first. const studio = (n: Name) => `http://127.0.0.1:${port + offset[n]}`; const site = (n: Name) => `http://127.0.0.1:${port + offset[n] + 1}`; /** One public origin for the installation: every instance gets the same config (RFC-0047 §2). */ const ORIGIN = studio("a"); const NEW_TITLE = "Released during the outage"; const HOME_H1 = /]*>Failover Site<\/h1>/; const STORE_IMAGE = /image: (chrislusf\/seaweedfs:\S+)/.exec( readFileSync( path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../deploy/docker/compose.yml"), "utf8", ), )?.[1]; if (!STORE_IMAGE) throw new Error("compose.yml names no SeaweedFS image"); const run = promisify(execFile); /** A docker command, bounded (#306). */ async function docker(args: string[], timeout = 120_000): Promise { const { stdout } = await run("docker", args, { encoding: "utf8", timeout, maxBuffer: 64 << 20 }); return stdout.trim(); } const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); const t0 = Date.now(); const elapsed = () => `${((Date.now() - t0) / 1000).toFixed(1)}s`; const step = (text: string) => console.log(`✓ [${elapsed()}] ${text}`); function expect(ok: boolean, what: string, detail?: unknown): void { if (!ok) throw new Error(`${what}${detail === undefined ? "" : `: ${JSON.stringify(detail)}`}`); } /** Secrets go to `docker run` in 0600 files, so a failed command never prints them. */ const envDir = mkdtempSync(path.join(os.tmpdir(), "cloudhal-failover-")); function envFile(name: string, env: Record): string { const file = path.join(envDir, `${name}.env`); writeFileSync( file, Object.entries(env) .map(([k, v]) => `${k}=${v}\n`) .join(""), { mode: 0o600 }, ); return file; } async function secrets(): Promise> { const text = await docker(["run", "--rm", image, "secrets"]); return Object.fromEntries( text .split("\n") .filter((l) => l.includes("=") && !l.startsWith("#")) .map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)]), ); } async function startStore(env: Record): Promise { await docker(["network", "create", net]); const config = JSON.stringify({ identities: [ { name: "cloudhal", credentials: [{ accessKey: env.AWS_ACCESS_KEY_ID, secretKey: env.AWS_SECRET_ACCESS_KEY }], actions: ["Admin", "Read", "Write", "List", "Tagging"], }, ], }); await docker([ ...["run", "-d", "--name", store, "--network", net, "--network-alias", "seaweedfs"], ...["--env-file", envFile("store", { S3_CONFIG: config }), "--entrypoint", "/bin/sh"], STORE_IMAGE as string, "-c", 'printf "%s" "$S3_CONFIG" > /tmp/s3.json && exec weed server -dir=/data -s3 -s3.config=/tmp/s3.json -master.volumeSizeLimitMB=256', ]); } /** An instance as compose.yml runs it, its Durable Objects on its own volume. */ async function startInstance(n: Name, env: Record): Promise { const file = envFile(n, { ...env, CLOUDHAL_S3_ENDPOINT: "http://seaweedfs:8333", CLOUDHAL_S3_BUCKET: "cloudhal", CLOUDHAL_CLUSTER_ADVERTISE: `${ctr(n)}:7000`, CLOUDHAL_SITE_NAME: "Failover Site", CLOUDHAL_BASE_URL: ORIGIN, }); await docker([ ...["run", "-d", "--name", ctr(n), "--network", net, "--read-only", "--tmpfs", "/tmp"], ...["--cap-drop", "ALL", "--security-opt", "no-new-privileges:true"], ...["--stop-timeout", "15", "-v", `${ctr(n)}:/data`, "--env-file", file], ...["-p", `127.0.0.1:${port + offset[n]}:8787`, "-p", `127.0.0.1:${port + offset[n] + 1}:8788`], image, ]); } async function waitHealthy(n: Name, seconds = 180): Promise { const deadline = Date.now() + seconds * 1000; while (Date.now() < deadline) { const [status, running] = ( await docker(["inspect", "--format", "{{.State.Health.Status}} {{.State.Running}}", ctr(n)]) ).split(" "); if (status === "healthy") return; if (running !== "true") throw new Error(`${ctr(n)} stopped while starting`); await sleep(2000); } throw new Error(`${ctr(n)} did not become healthy within ${seconds} s`); } interface Res { status: number; text: string; body: unknown; headers: Headers; } /** A request, bounded at 10 s; a network error answers status 0 with the error as text. */ async function req(url: string, init: RequestInit = {}): Promise { try { const res = await fetch(url, { ...init, signal: AbortSignal.timeout(10_000) }); const text = await res.text(); let body: unknown = text; try { body = JSON.parse(text); } catch { // not JSON } return { status: res.status, text, body, headers: res.headers }; } catch (e) { const err = e as { name?: string; cause?: { code?: string } }; const text = err.cause?.code ?? err.name ?? String(e); return { status: 0, text, body: text, headers: new Headers() }; } } async function until( what: string, seconds: number, check: () => Promise, ): Promise { const deadline = Date.now() + seconds * 1000; while (Date.now() < deadline) { const v = await check().catch(() => undefined); if (v !== undefined) return v; await sleep(1000); } throw new Error(`${what} within ${seconds} s`); } const env = await secrets(); const siteId = env.CLOUDHAL_SITE_ID as string; const admin = { authorization: `Bearer ${env.CLOUDHAL_DEPLOY_TOKEN}` }; let cookie = ""; let releaseId = ""; /** The starter post, which the handoffs edit as a draft (#324). */ let postId = ""; const api = (n: Name, p: string, init: RequestInit = {}) => req(`${studio(n)}${p}`, { ...init, headers: { origin: ORIGIN, cookie, ...(init.headers as Record) }, }); const post = (n: Name, p: string, body: unknown, headers: Record = {}) => api(n, p, { method: "POST", headers: { "content-type": "application/json", ...headers }, body: JSON.stringify(body), }); /** * A failed answer, with what tells its cause apart: the status, `retry-after` and the * `x-cloudhal-*` headers (RFC-0043's status pages), and the start of the body. */ function failed(what: string, r: Res): string { const headers = [...r.headers] .filter(([k]) => k === "retry-after" || k.startsWith("x-cloudhal")) .map(([k, v]) => `${k}: ${v}`); const text = r.text.replace(/\s+/g, " ").slice(0, 160); return `${what} ${r.status}${headers.length ? ` [${headers.join(", ")}]` : ""} ${text}`; } /** What every instance must answer while it serves: the site, Studio's API and a database read. */ async function serves(n: Name, postTitle?: string): Promise { const home = await req(`${site(n)}/`); if (home.status !== 200 || !HOME_H1.test(home.text)) return failed("site /", home); const post = await req(`${site(n)}/posts/hello-world`); if (post.status !== 200) return failed("site /posts/hello-world", post); if (postTitle && !post.text.includes(postTitle)) return `the post is not "${postTitle}"`; const sites = await req(`${studio(n)}/api/admin/sites`, { headers: admin }); const listed = (sites.body as { sites?: { id: string }[] }).sites ?? []; if (sites.status !== 200 || !listed.some((s) => s.id === siteId)) return failed("studio /api/admin/sites", sites); return undefined; } async function firstSiteAndPublish(): Promise { await until("the entrypoint did not create the site", 120, async () => { const r = await req(`${studio("a")}/api/admin/sites`, { headers: admin }); const sites = (r.body as { sites?: { id: string }[] }).sites ?? []; return sites.some((s) => s.id === siteId) ? true : undefined; }); const before = await req(`${site("a")}/`); expect(before.status === 503, "the site answers 503 before the first publish", before.status); const signUp = await post( "a", "/api/auth/sign-up/email", { name: "Failover Owner", email: "owner@example.com", password: "failover-test-password" }, { "x-cloudhal-setup-token": env.CLOUDHAL_SETUP_TOKEN as string }, ); expect(signUp.status === 200, "sign-up of the first owner", signUp.body); cookie = signUp.headers .getSetCookie() .map((c) => c.split(";")[0] as string) .find((c) => c.includes("better-auth.session_token=")) ?? ""; expect(cookie !== "", "sign-up set a session cookie"); const published = await post("a", `/api/sites/${siteId}/snapshots`, { publish: true }); expect(published.status === 201, "publish", published.body); } /** The starter post retitled in a draft, in a release due at `at`; returns the release id. */ async function scheduleRelease(at: number): Promise { const list = await api("a", `/api/sites/${siteId}/entries?collection=posts`); const entry = (list.body as { id: string; slug: string }[]).find?.( (e) => e.slug === "hello-world", ); expect(list.status === 200 && entry !== undefined, "the starter post", list.status); const saved = await api("a", `/api/sites/${siteId}/entries/${entry?.id}`, { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ ...entry, title: NEW_TITLE }), }); expect(saved.status === 200, "the draft change", saved.body); postId = entry?.id as string; const when = { at: new Date(at).toISOString() }; const draft = await post("a", `/api/sites/${siteId}/releases`, { title: "Failover", nodeIds: [entry?.id], when, }); const rel = (draft.body as { release?: { id: string; rev: number } }).release; expect(draft.status === 201 && rel !== undefined, "the draft release", draft.body); const done = await post("a", `/api/sites/${siteId}/releases/${rel?.id}/schedule`, { when, rev: rel?.rev, }); const state = (done.body as { release?: { state?: string } }).release?.state; expect(done.status === 200 && state === "scheduled", "the release is scheduled", done.body); return rel?.id as string; } async function runsOf(n: Name): Promise<{ state: string; startedAt?: string; trigger?: string }[]> { const r = await api(n, `/api/sites/${siteId}/runs?releaseId=${releaseId}`); expect(r.status === 200, "the release's runs", r.body); return (r.body as { runs: { state: string; startedAt?: string; trigger?: string }[] }).runs; } /** A draft edit of the starter post through `n` (the live post keeps its released title). */ async function saveDraft(n: Name, summary: string): Promise { const path = `/api/sites/${siteId}/entries/${postId}`; const got = await api(n, path); if (got.status !== 200) return failed("GET entry", got); const saved = await api(n, path, { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ ...(got.body as Record), summary }), }); return saved.status === 200 ? undefined : failed("PUT entry", saved); } /** * Steady load on `targets` while `victim` stops gracefully: reads on every target and draft edits * through the first (#324), and not one may fail; the last edit is the one stored. */ async function handoff(victim: Name, targets: Name[]): Promise { const failures: string[] = []; let requests = 0; let writes = 0; let lastWritten = ""; let stopping = true; const writer = async (n: Name) => { while (stopping) { const summary = `handoff of ${victim}, write ${writes + 1}`; const why = await saveDraft(n, summary); writes++; if (why && failures.length < 50) failures.push(`${elapsed()} ${n} write: ${why}`); else if (!why) lastWritten = summary; await sleep(250); } }; const loop = async (n: Name) => { while (stopping) { const why = await serves(n, NEW_TITLE); requests++; if (why && failures.length < 50) failures.push(`${elapsed()} ${n}: ${why}`); await sleep(100); } }; const loops = [...targets.map(loop), writer(targets[0] as Name)]; await sleep(3000); const started = Date.now(); await docker(["stop", "--timeout", "15", ctr(victim)], 60_000); const took = (Date.now() - started) / 1000; // the handoff runs on after the victim exits: its leases move to the survivors await sleep(25_000); stopping = false; await Promise.all(loops); const exit = await docker(["inspect", "--format", "{{.State.ExitCode}}", ctr(victim)]); expect(failures.length === 0, `requests failed while ${victim} stopped`, failures); const stored = await api(targets[0] as Name, `/api/sites/${siteId}/entries/${postId}`); const summary = (stored.body as { summary?: string }).summary; expect(summary === lastWritten, "the last draft edit is the one stored", { summary, lastWritten, }); expect(exit !== "137" && took < 15, `${victim} exits by itself within 15 s`, { exit, took }); step( `${victim} stopped on SIGTERM in ${took.toFixed(1)} s; ${requests} rounds and ${writes} writes, none failed`, ); } async function diagnostics(): Promise { const out = (what: string, text: string) => console.error(`--- ${what}\n${text}`); const safe = async (f: () => Promise) => f().catch((e: Error) => `error: ${e.message}`); out("containers", await safe(() => docker(["ps", "-a", "--filter", `name=${id}`], 30_000))); for (const n of NAMES) { for (const u of [`${studio(n)}/api/health`, `${site(n)}/`]) out(`${n} ${u}`, String((await req(u)).status)); if (releaseId) { const r = await api(n, `/api/sites/${siteId}/releases/${releaseId}`); out(`${n} release`, r.text.slice(0, 2000)); out(`${n} runs`, (await api(n, `/api/sites/${siteId}/runs?releaseId=${releaseId}`)).text); } const status = await req(`${studio(n)}/api/admin/schedules/status`, { headers: admin }); out(`${n} scheduler`, status.text.slice(0, 2000)); } for (const name of [...NAMES.map(ctr), store]) out( `${name} logs`, await safe(() => dockerOutput(["logs", "--tail", "300", "--timestamps", name])), ); } /** `docker logs` writes the container's stderr to its own stderr. */ async function dockerOutput(args: string[]): Promise { const { stdout, stderr } = await run("docker", args, { encoding: "utf8", timeout: 30_000 }); return `${stdout}${stderr}`; } async function main(): Promise { await startStore(env); await startInstance("a", env); await waitHealthy("a"); await firstSiteAndPublish(); await Promise.all([startInstance("b", env), startInstance("c", env)]); await Promise.all([waitHealthy("b"), waitHealthy("c")]); for (const n of NAMES) expect((await serves(n, "Hello, world")) === undefined, `${n} serves`); step("three instances on SeaweedFS serve the published site"); const due = Date.now() + 80_000; releaseId = await scheduleRelease(due); expect( (await serves("b", NEW_TITLE)) === `the post is not "${NEW_TITLE}"`, "the change waits for its release", ); step(`a release of a changed post is due at ${new Date(due).toISOString()}`); await sleep(Math.max(0, due - 10_000 - Date.now())); await docker(["kill", "--signal", "KILL", ctr("a")], 30_000); const killed = Date.now(); step("a (the first instance) is killed with SIGKILL, 10 s before the release is due"); await until("b and c did not serve the published site and Studio", 60, async () => { const why = [await serves("b"), await serves("c")].filter(Boolean); return why.length === 0 ? true : undefined; }); step( `b and c serve the site and Studio again ${((Date.now() - killed) / 1000).toFixed(1)} s after the kill`, ); await until("the release did not run", 180, async () => { const r = await api("b", `/api/sites/${siteId}/releases/${releaseId}`); return (r.body as { state?: string }).state === "published" ? true : undefined; }); const runs = await runsOf("b"); expect(runs.length === 1 && runs[0]?.state === "succeeded", "exactly one succeeded run", runs); expect(Date.parse(runs[0]?.startedAt ?? "") >= due, "the release did not run early", runs); for (const n of ["b", "c"] as const) expect((await serves(n, NEW_TITLE)) === undefined, `${n} serves the released change`); step(`the release due during the outage ran exactly once (${runs[0]?.trigger}) and is live`); await docker(["start", ctr("a")]); await waitHealthy("a"); await until("a did not serve the released change after rejoining", 60, async () => (await serves("a", NEW_TITLE)) === undefined ? true : undefined, ); step("a starts again on its volume, rejoins and serves the released change"); await handoff("b", ["a", "c"]); await docker(["start", ctr("b")]); await waitHealthy("b"); await handoff("c", ["a", "b"]); const logs = await Promise.all(NAMES.map((n) => dockerOutput(["logs", ctr(n)]))); const errs = logs.flatMap((l) => l.split("\n")).filter((l) => l.includes('migration "')); expect(errs.length === 0, "an instance logged a migration error", errs); expect((await runsOf("a")).length === 1, "the release still has exactly one run"); step("no instance logged a migration error; the release still has exactly one run"); console.log("\nCluster failover test passed."); } try { await main(); } catch (e) { console.error(`\n✗ [${elapsed()}] ${e instanceof Error ? e.message : String(e)}`); await diagnostics().catch((d: Error) => console.error(`diagnostics failed: ${d.message}`)); process.exitCode = 1; } finally { for (const name of [...NAMES.map(ctr), store]) await docker(["rm", "-f", "-v", name], 60_000).catch(() => undefined); for (const n of NAMES) await docker(["volume", "rm", ctr(n)], 30_000).catch(() => undefined); await docker(["network", "rm", net], 30_000).catch(() => undefined); rmSync(envDir, { recursive: true, force: true }); }