import { readFileSync, readdirSync } from 'node:fs' /** Process facts from /proc (Linux only): the watchdog's only source. */ function readOrEmpty(path) { try { return readFileSync(path, 'utf8') } catch { return '' } } function listOrEmpty(path) { try { return readdirSync(path) } catch { return [] } } const numbersOf = (text) => text.split(/\s+/).filter(Boolean).map(Number) /** Direct children of `pid`, over all its threads; [] once it is gone. */ export function childrenOf(pid) { return listOrEmpty(`/proc/${pid}/task`).flatMap((tid) => numbersOf(readOrEmpty(`/proc/${pid}/task/${tid}/children`)), ) } /** `root` and every process below it, breadth first. */ export function treeOf(root) { const tree = [root] for (let i = 0; i < tree.length; i += 1) { for (const child of childrenOf(tree[i])) { if (!tree.includes(child)) tree.push(child) } } return tree } /** VmRSS in bytes; 0 for a process that is gone or a zombie. */ export function rssBytesOf(pid) { const status = readOrEmpty(`/proc/${pid}/status`) const match = /^VmRSS:\s+(\d+) kB$/m.exec(status) return match ? Number(match[1]) * 1024 : 0 } /** * A process that renders web content: Chromium's renderers, Firefox's * "Web Content" and "Isolated Web Content" (comm is cut at 15 bytes), * WebKit's web process. Read at every sample: names change after exec. */ export function isContentProcess(pid) { const comm = readOrEmpty(`/proc/${pid}/comm`).trim() if (comm.startsWith('WPEWebProcess') || comm.startsWith('WebKitWebProc')) { return true } if (comm.startsWith('Web Content') || comm.startsWith('Isolated Web')) { return true } // Chromium rewrites its argv as one space-separated title. const cmdline = readOrEmpty(`/proc/${pid}/cmdline`) return /(^|[\0 ])--type=renderer([\0 ]|$)/.test(cmdline) } /** Summed, content-process and largest single VmRSS of the tree. */ export function treeRss(root) { const pids = treeOf(root) const sizes = pids.map(rssBytesOf) const content = pids.filter((pid, i) => sizes[i] > 0 && isContentProcess(pid)) const sum = (list) => list.reduce((total, size) => total + size, 0) return { pids, totalBytes: sum(sizes), contentBytes: sum(content.map((pid) => sizes[pids.indexOf(pid)])), maxProcessBytes: Math.max(0, ...sizes), } } /** * SIGKILL to each pid, the first one (the tree's root) first so it cannot * respawn a child. Callers pass only a tree they launched. */ export function killAll(pids) { for (const pid of pids) { try { process.kill(pid, 'SIGKILL') } catch { // Already gone. } } }