Public: anyone can read this; the crew can change it.

/metrics: forge_process_restarts_total and forge_child_processes{comm} #16864

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/3727-metrics-forge-process-restarts-total-and → main 0 commits fork

  • Merged. scout/3727-metrics-forge-process-restarts-total-and was merged into main as 03718a4.

Review

Sign in to review this change.
5 files changed +93 −2
docs/METRICS.md +3
@@ -30,6 +30,9 @@ not an admin, 200 for an admin's `ro` token. It is never cached
3030 | `forge_loop_stalls_total` | counter | `route` | Those stalls, counted the same way. |
3131 | `forge_loop_stall_hour_milliseconds` | gauge | `route` | Stall milliseconds in the last hour: the top 10 routes, most first, plus `/api/v1/telemetry/flow` always (0 when it stalled nothing). |
3232 | `forge_loop_stall_hour_count` | gauge | `route` | Stalls in the last hour, for the routes the gauge above lists. |
33 | `forge_process_restarts_total` | counter | none | Starts after the first, releases and crashes alike, from `boots.json` (#3727). |
34 | `forge_process_unclean_restarts_total` | counter | none | Earlier starts that never exited cleanly. |
35 | `forge_child_processes` | gauge | `comm` | Processes on the machine by command name (`socat`, `bwrap`…), the forge itself excluded. Names are set by whoever runs the process, so only the 10 most numerous are kept and the rest are summed under `comm="other"`; read at most every 5 seconds. |
3336 | `forge_app_up` | gauge | `app`, `env` | 1 when the app environment is serving, 0 when it is asleep, stopped, deploying or failed. |
3437 | `forge_cell_cpu_seconds` (samples `forge_cell_cpu_seconds_total`) | counter | `app`, `env` | CPU seconds (user plus system) used by the processes of a running app cell. |
3538 | `forge_cell_memory_bytes` | gauge | `app`, `env` | Resident memory of the processes of a running app cell. |
src/http/api.ts +2 −2
@@ -393,7 +393,7 @@ import { INVALID_TOKEN_HINT, INVALID_TOKEN_WORDS, manifestFor, registeredPageMan
393393 import { ok } from "../kernel/result.ts";
394394 import { egressRowsFor, egressTotalsFor } from "../spawn/process_counters.ts";
395395 import { egressMetrics } from "../apps/egress_metrics.ts";
396 import { forgeMetrics } from "../metrics/forge.ts";
396 import { forgeMetrics, processSources } from "../metrics/forge.ts";
397397 import { appSources } from "../metrics/app_sources.ts";
398398 import { ADMIN_WORDS } from "../actions/admin_words.ts";
399399 import { ORDER_WORDS, VISIBILITY_WORDS } from "../core/arg_words.ts";
@@ -2839,7 +2839,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
28392839 router.add("GET", "/metrics", (ctx) => {
28402840 const denied = accountAdmin(ctx, "ro");
28412841 if (denied) return denied;
2842 return new Response(egressMetrics(egressRowsFor(ctx.app), egressTotalsFor(ctx.app)) + forgeMetrics(ctx.app.db, appSources(ctx.app), Date.now(), liveOf(ctx.app).loopWatch), {
2842 return new Response(egressMetrics(egressRowsFor(ctx.app), egressTotalsFor(ctx.app)) + forgeMetrics(ctx.app.db, appSources(ctx.app), Date.now(), liveOf(ctx.app).loopWatch, processSources(ctx.app.config.dataDir)), {
28432843 headers: {
28442844 "content-type": "text/plain; version=0.0.4; charset=utf-8",
28452845 "cache-control": "no-store",
src/metrics/forge.ts +49
@@ -19,6 +19,8 @@ import { EDGES_MS, readTotals } from "../core/route_timing.ts";
1919 import { closesFromBody } from "../core/pulls.ts";
2020 import { telemetryReadsFamily } from "../system/telemetry_reads.ts";
2121 import { createLoopWatch, type LoopWatch } from "../perf/loop.ts";
22 import { bootCounts, type BootCounts } from "../kernel/boots.ts";
23 import { census, processRows } from "../kernel/census.ts";
2224 import { stallFamilies } from "./stalls.ts";
2325 import { openMetrics, type Family, type HistogramSample, type Sample } from "./openmetrics.ts";
2426
@@ -329,6 +331,50 @@ export function appFamilies({ apps, cells }: AppSources): Family[] {
329331 ];
330332 }
331333
334 /** What the process families read: the boot ledger's counts and the process table by name. */
335 export interface ProcessSources {
336 readonly boots: BootCounts;
337 readonly census: ReadonlyMap<string, number>;
338 }
339
340 /** Read live from `boots.json` and `/proc`; nothing is started or shelled out. */
341 export function processSources(dataDir: string, now: number = Date.now()): ProcessSources {
342 // The /proc walk is synchronous: at most one per CENSUS_TTL_MS, however often it is scraped.
343 if (!censusCache || now - censusCache.at >= CENSUS_TTL_MS || now < censusCache.at) censusCache = { at: now, counts: census(processRows()) };
344 return { boots: bootCounts(dataDir), census: censusCache.counts };
345 }
346
347 const CENSUS_TTL_MS = 5_000;
348 let censusCache: { at: number; counts: ReadonlyMap<string, number> } | undefined;
349
350 /**
351 * Command names are set by whoever runs the process: keep this many series, fold the rest into
352 * `other`.
353 */
354 export const CHILD_COMM_LIMIT = 10;
355
356 /** The top names by count (ties by name), the remainder summed under `other`. */
357 export function boundedChildren(counts: ReadonlyMap<string, number>, limit: number = CHILD_COMM_LIMIT): [string, number][] {
358 const sorted = [...counts].sort(([a, x], [b, y]) => y - x || (a < b ? -1 : 1));
359 const kept = new Map(sorted.slice(0, limit));
360 let rest = 0;
361 for (const [, n] of sorted.slice(limit)) rest += n;
362 if (rest > 0) kept.set("other", (kept.get("other") ?? 0) + rest);
363 return [...kept].sort(([a], [b]) => (a < b ? -1 : 1));
364 }
365
366 /**
367 * Restarts (releases and crashes), the unclean ones among them, and the children by command name.
368 */
369 export function processFamilies({ boots, census: counts }: ProcessSources): Family[] {
370 const children = boundedChildren(counts);
371 return [
372 { type: "counter", name: "forge_process_restarts_total", help: "Starts of the forge after the first, releases and crashes alike.", samples: [{ value: boots.restarts }] },
373 { type: "counter", name: "forge_process_unclean_restarts_total", help: "Earlier starts that never exited cleanly: crashes and kills.", samples: [{ value: boots.unclean }] },
374 { type: "gauge", name: "forge_child_processes", help: "Processes on the machine by command name, the forge itself excluded.", samples: children.map(([comm, n]) => ({ labels: { comm }, value: n })) },
375 ];
376 }
377
332378 /** The forge's families as Prometheus text (no `# EOF`: the body is `text/plain; version=0.0.4`). */
333379 export function forgeMetrics(
334380 db: Database,
@@ -336,6 +382,8 @@ export function forgeMetrics(
336382 now: number = Date.now(),
337383 /** The forge's own loop watch (`liveOf(app).loopWatch`); none read means none stalled. */
338384 loop: LoopWatch = createLoopWatch(),
385 /** Boot counts and the process census; none read means the series are left out. */
386 proc?: ProcessSources,
339387 ): string {
340388 return openMetrics([
341389 durationFamily(db),
@@ -350,5 +398,6 @@ export function forgeMetrics(
350398 mainRedFamily(db, now),
351399 telemetryReadsFamily(),
352400 ...stallFamilies(loop.tally(performance.now())),
401 ...(proc ? processFamilies(proc) : []),
353402 ]).replace(/# EOF\n$/, "");
354403 }
test/metrics-forge.test.ts +32
@@ -64,3 +64,35 @@ test("totals are kept per database and stop growing new patterns at the cap", ()
6464 ta.record("/p0", 1);
6565 expect(readTotals(a).get("/p0")!.counts[0]).toBe(2);
6666 });
67
68 test("process families: counts and one escaped series per command name (#3727)", async () => {
69 const { processFamilies } = await import("../src/metrics/forge.ts");
70 const { openMetrics } = await import("../src/metrics/openmetrics.ts");
71 const text = openMetrics(
72 processFamilies({ boots: { boots: 4, restarts: 3, unclean: 1 }, census: new Map([["socat", 2], ['a"b', 1]]) }),
73 );
74 expect(text).toContain("forge_process_restarts_total 3\n");
75 expect(text).toContain("forge_process_unclean_restarts_total 1\n");
76 expect(text).toContain('forge_child_processes{comm="socat"} 2\n');
77 expect(text).toContain('forge_child_processes{comm="a\\"b"} 1\n');
78 });
79
80 test("child processes: more than the limit distinct names fold into one other series (#3727)", async () => {
81 const { boundedChildren, CHILD_COMM_LIMIT } = await import("../src/metrics/forge.ts");
82 const counts = new Map<string, number>([["socat", 50], ["bwrap", 40]]);
83 for (let i = 0; i < 200; i++) counts.set(`evil${i}`, 1);
84 const rows = boundedChildren(counts);
85 expect(rows.length).toBe(CHILD_COMM_LIMIT + 1);
86 expect(rows.find(([c]) => c === "socat")![1]).toBe(50);
87 expect(rows.find(([c]) => c === "bwrap")![1]).toBe(40);
88 expect(rows.find(([c]) => c === "other")![1]).toBe(200 - (CHILD_COMM_LIMIT - 2));
89 expect(boundedChildren(new Map([["a", 1]]))).toEqual([["a", 1]]);
90 });
91
92 test("the census is read once per few seconds (#3727)", async () => {
93 const { processSources } = await import("../src/metrics/forge.ts");
94 const dir = process.env.TMPDIR ?? "/tmp";
95 const a = processSources(dir, 1_000_000).census;
96 expect(processSources(dir, 1_001_000).census).toBe(a);
97 expect(processSources(dir, 1_006_000).census).not.toBe(a);
98 });
test/metrics-route.test.ts +7
@@ -77,3 +77,10 @@ test("every family the route serves is listed in docs/METRICS.md", async () => {
7777 // A counter's TYPE line names the family without `_total`; the doc names the sample.
7878 for (const f of families) expect(doc.includes(`\`${f}\``) || doc.includes(`\`${f}_total\``)).toBe(true);
7979 });
80
81 test("restarts and child processes by name are served (#3727)", async () => {
82 const text = await read();
83 expect(text).toMatch(/^forge_process_restarts_total \d+$/m);
84 expect(text).toMatch(/^forge_process_unclean_restarts_total \d+$/m);
85 expect(text).toMatch(/^forge_child_processes\{comm="[^"]+"\} \d+$/m);
86 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs