/** * Observability of the self-host image, end to end (#293). CI only: .github/workflows/docker.yml * runs it on the candidate image, and it refuses to start outside GitHub Actions. * * 1. Starts SeaweedFS, the otel profile's collector (deploy/docker/otel-collector.yaml, the image * compose.yml pins), and one instance with OTEL_EXPORTER_OTLP_ENDPOINT and * CLOUDHAL_METRICS_TOKEN. * 2. Requests to Studio and the site produce spans that reach the collector with * `service.name` (the Worker), `service.instance.id` (the instance) and `service.version`. * 3. `GET /api/metrics` answers its token holder in Prometheus text (requests of both Workers, * the scheduler, store errors), and anyone else 401. * * node scripts/otel-smoke.ts --image [--port ] */ import { execFile } from "node:child_process"; import { randomBytes } from "node:crypto"; 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("otel-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") ?? 58797); const id = `cloudhal-otel-${process.pid}`; const names = { store: `${id}-store`, collector: `${id}-collector`, cloudhal: `${id}-cloudhal` }; // 127.0.0.1, never localhost (#306) const studio = `http://127.0.0.1:${port}`; const site = `http://127.0.0.1:${port + 1}`; const docker_ = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../deploy/docker"); const compose = readFileSync(path.join(docker_, "compose.yml"), "utf8"); const pinned = (repo: string) => { const at = compose.indexOf(`image: ${repo}:`); if (at === -1) throw new Error(`compose.yml names no ${repo} image`); return compose.slice(at + 7, compose.indexOf("\n", at)).trim(); }; const STORE_IMAGE = pinned("chrislusf/seaweedfs"); const COLLECTOR_IMAGE = pinned("otel/opentelemetry-collector-contrib"); const metricsToken = randomBytes(24).toString("hex"); const run = promisify(execFile); async function docker(args: string[], timeout = 120_000): Promise { const { stdout } = await run("docker", args, { encoding: "utf8", timeout, maxBuffer: 64 << 20 }); return stdout.trim(); } async function dockerLogs(name: string, tail = "2000"): Promise { const { stdout, stderr } = await run("docker", ["logs", "--tail", tail, name], { encoding: "utf8", timeout: 30_000, maxBuffer: 64 << 20, }); return `${stdout}${stderr}`; } /** How many resource spans the debug exporter printed per `service.name`. */ function servicesSeen(text: string): Map { const out = new Map(); const marker = "service.name: Str("; for (let at = text.indexOf(marker); at !== -1; at = text.indexOf(marker, at + 1)) { const end = text.indexOf(")", at + marker.length); if (end === -1 || end - at > 100) continue; const name = text.slice(at + marker.length, end); out.set(name, (out.get(name) ?? 0) + 1); } out.delete("otelcol-contrib"); return out; } const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); const step = (text: string) => console.log(`āœ“ ${text}`); function expect(ok: boolean, what: string, detail?: unknown): void { if (!ok) throw new Error(`${what}${detail === undefined ? "" : `: ${JSON.stringify(detail)}`}`); } const work = mkdtempSync(path.join(os.tmpdir(), "cloudhal-otel-")); function envFile(name: string, env: Record): string { const file = path.join(work, `${name}.env`); writeFileSync( file, Object.entries(env) .map(([k, v]) => `${k}=${v}\n`) .join(""), { mode: 0o600 }, ); return file; } async function req(url: string, init: RequestInit = {}): Promise<{ status: number; text: string }> { try { const res = await fetch(url, { ...init, signal: AbortSignal.timeout(20_000) }); return { status: res.status, text: await res.text() }; } catch (e) { return { status: 0, text: (e as { cause?: { code?: string } }).cause?.code ?? String(e) }; } } async function until(what: string, seconds: number, check: () => Promise) { const deadline = Date.now() + seconds * 1000; while (Date.now() < deadline) { const v = await check().catch(() => undefined); if (v !== undefined) return v; await sleep(2000); } throw new Error(`${what} within ${seconds} s`); } async function start(env: Record): Promise { await docker(["network", "create", id]); const s3 = 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", names.store, "--network", id, "--network-alias", "seaweedfs"], ...["--env-file", envFile("store", { S3_CONFIG: s3 }), "--entrypoint", "/bin/sh"], STORE_IMAGE, "-c", 'printf "%s" "$S3_CONFIG" > /tmp/s3.json && exec weed server -dir=/data -s3 -s3.config=/tmp/s3.json -master.volumeSizeLimitMB=256', ]); await docker([ ...[ "run", "-d", "--name", names.collector, "--network", id, "--network-alias", "otel-collector", ], ...["-v", `${path.join(docker_, "otel-collector.yaml")}:/etc/otelcol-contrib/config.yaml:ro`], COLLECTOR_IMAGE, ]); await docker([ ...["run", "-d", "--name", names.cloudhal, "--network", id, "--read-only", "--tmpfs", "/tmp"], ...["--cap-drop", "ALL", "--security-opt", "no-new-privileges:true"], "--env-file", envFile("cloudhal", { ...env, CLOUDHAL_S3_ENDPOINT: "http://seaweedfs:8333", CLOUDHAL_S3_BUCKET: "cloudhal", CLOUDHAL_CLUSTER_ADVERTISE: `${names.cloudhal}:7000`, CLOUDHAL_SITE_NAME: "Otel Site", CLOUDHAL_BASE_URL: studio, OTEL_EXPORTER_OTLP_ENDPOINT: "http://otel-collector:4318", CLOUDHAL_METRICS_TOKEN: metricsToken, }), ...["-p", `127.0.0.1:${port}:8787`, "-p", `127.0.0.1:${port + 1}:8788`], image, ]); } async function main(env: Record): Promise { await start(env); const admin = { authorization: `Bearer ${env.CLOUDHAL_DEPLOY_TOKEN}` }; await until("the instance did not create its site", 180, async () => { const r = await req(`${studio}/api/admin/sites`, { headers: admin }); return r.status === 200 && r.text.includes(env.CLOUDHAL_SITE_ID as string) ? true : undefined; }); for (let i = 0; i < 5; i++) { await req(`${studio}/api/health`); await req(`${site}/`); } step("an instance exporting to the otel profile's collector is up and answered requests"); // The whole log, never a tail: workerd's own Workers (d1, cron) export many spans, and the // debug exporter prints each over dozens of lines (#343's first run read only a tail). const instance = `service.instance.id: Str(${names.cloudhal}:7000)`; let seen = new Map(); const wanted = (prefix: string) => [...seen.keys()].some((n) => n.split("-")[0] === prefix); const logs = await until( "no span of the admin and site Workers with the instance reached the collector", 120, async () => { await req(`${studio}/api/health`); await req(`${site}/`); const text = await dockerLogs(names.collector, "all"); seen = servicesSeen(text); return text.includes(instance) && wanted("admin") && wanted("site") ? text : undefined; }, ).catch((e: Error) => { throw new Error(`${e.message}; services seen: ${JSON.stringify(Object.fromEntries(seen))}`); }); expect(/service\.version: Str\(\S+\)/.test(logs), "the version on the spans"); expect(logs.includes("service.namespace: Str(cloudhal)"), "the namespace on the spans"); step( `spans reached the collector with the instance and the version, by service: ${JSON.stringify(Object.fromEntries(seen))}`, ); const anonymous = await req(`${studio}/api/metrics`); expect(anonymous.status === 401, "/api/metrics without the token", anonymous.status); const wrong = await req(`${studio}/api/metrics`, { headers: { authorization: "Bearer nope" } }); expect(wrong.status === 401, "/api/metrics with a wrong token", wrong.status); const metrics = await until("/api/metrics did not show the scheduler", 90, async () => { const r = await req(`${studio}/api/metrics`, { headers: { authorization: `Bearer ${metricsToken}` }, }); return r.status === 200 && r.text.includes("cloudhal_scheduler_healthy") ? r.text : undefined; }); for (const line of [ /^cloudhal_http_requests_total\{worker="admin",area="api",class="2xx"\} [1-9]/m, /^cloudhal_http_requests_total\{worker="site",class="5xx"\} [1-9]/m, /^cloudhal_http_request_duration_seconds_count\{worker="site"\} [1-9]/m, /^cloudhal_store_errors_total\{store="d1"\} \d+$/m, /^cloudhal_scheduler_healthy [01]$/m, /^# TYPE cloudhal_publish_duration_seconds histogram$/m, ]) expect(line.test(metrics), `/api/metrics has ${line.source}`, metrics.slice(0, 3000)); step("/api/metrics answers its token holder in Prometheus text, and nobody else"); console.log("\nObservability smoke test passed."); } const env = Object.fromEntries( (await docker(["run", "--rm", image, "secrets"])) .split("\n") .filter((l) => l.includes("=") && !l.startsWith("#")) .map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)]), ) as Record; try { await main(env); } catch (e) { console.error(`\nāœ— ${e instanceof Error ? e.message : String(e)}`); for (const name of Object.values(names)) { const text = await dockerLogs(name, "150").catch((d: Error) => `error: ${d.message}`); console.error(`--- ${name} logs\n${text.slice(-12_000)}`); } process.exitCode = 1; } finally { for (const name of Object.values(names)) await docker(["rm", "-f", "-v", name], 60_000).catch(() => undefined); await docker(["network", "rm", id], 30_000).catch(() => undefined); rmSync(work, { recursive: true, force: true }); }