deployontime 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +661 -0
- package/README.md +259 -2
- package/SECURITY.md +61 -0
- package/mcp/jobs.mjs +137 -0
- package/mcp/runner.mjs +64 -0
- package/mcp/server.mjs +209 -0
- package/mcp/tools.mjs +380 -0
- package/package.json +47 -4
- package/queue/README.md +880 -0
- package/queue/args.mjs +136 -0
- package/queue/cli.mjs +207 -0
- package/queue/clock.mjs +49 -0
- package/queue/commands.mjs +35 -0
- package/queue/failstop.mjs +45 -0
- package/queue/files.mjs +71 -0
- package/queue/fingerprint.mjs +63 -0
- package/queue/gate.mjs +37 -0
- package/queue/git.mjs +61 -0
- package/queue/health.mjs +154 -0
- package/queue/idle.mjs +63 -0
- package/queue/job-wrapper.mjs +116 -0
- package/queue/journal.mjs +216 -0
- package/queue/kinds.mjs +95 -0
- package/queue/limits.mjs +79 -0
- package/queue/linux.mjs +72 -0
- package/queue/nested.mjs +83 -0
- package/queue/notices.mjs +114 -0
- package/queue/notify.mjs +47 -0
- package/queue/probes.mjs +162 -0
- package/queue/proctree.mjs +124 -0
- package/queue/project.mjs +26 -0
- package/queue/ps.mjs +54 -0
- package/queue/reaper.mjs +278 -0
- package/queue/run.mjs +612 -0
- package/queue/schedule-check.mjs +177 -0
- package/queue/settings.mjs +145 -0
- package/queue/setup.mjs +270 -0
- package/queue/slots.mjs +144 -0
- package/queue/stats.mjs +8 -0
- package/queue/stray.mjs +38 -0
- package/queue/timer.mjs +47 -0
- package/queue/units.mjs +8 -0
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// Process trees and signals: which processes make up a job, and how a job or a process group is told to stop.
|
|
2
|
+
// Every walk over a process table and every group signal of the queue goes through here.
|
|
3
|
+
import { probeProcessTree } from "./probes.mjs";
|
|
4
|
+
import { psRows } from "./ps.mjs";
|
|
5
|
+
|
|
6
|
+
// The longest chain of parents followed, so a damaged table can never keep a walk going.
|
|
7
|
+
const MAX_DEPTH = 64;
|
|
8
|
+
|
|
9
|
+
/** True while a process with this pid exists. EPERM: it exists but belongs to another user. */
|
|
10
|
+
export function alive(pid) {
|
|
11
|
+
try {
|
|
12
|
+
process.kill(pid, 0);
|
|
13
|
+
return true;
|
|
14
|
+
} catch (e) { return e.code === "EPERM"; }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** An index over process rows ({ pid, ppid }): byPid and children (parent pid to child pids). Build it once to walk
|
|
18
|
+
* a large table many times; every walk below also takes the rows themselves. */
|
|
19
|
+
export function treeIndex(rows) {
|
|
20
|
+
const byPid = new Map();
|
|
21
|
+
const children = new Map();
|
|
22
|
+
for (const row of rows) {
|
|
23
|
+
byPid.set(row.pid, row);
|
|
24
|
+
(children.get(row.ppid) ?? children.set(row.ppid, []).get(row.ppid)).push(row.pid);
|
|
25
|
+
}
|
|
26
|
+
return { byPid, children };
|
|
27
|
+
}
|
|
28
|
+
const indexOf = (table) => (table instanceof Array ? treeIndex(table) : table);
|
|
29
|
+
|
|
30
|
+
/** The root pids and every process below them by parent pid, as a Set. */
|
|
31
|
+
export function descendants(table, rootPids) {
|
|
32
|
+
const { children } = indexOf(table);
|
|
33
|
+
const found = new Set(rootPids);
|
|
34
|
+
const todo = [...found];
|
|
35
|
+
while (todo.length) {
|
|
36
|
+
for (const child of children.get(todo.pop()) ?? []) {
|
|
37
|
+
if (found.has(child)) continue;
|
|
38
|
+
found.add(child);
|
|
39
|
+
todo.push(child);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return found;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The row of pid and the rows of its parents, nearest first. Stops at a pid missing from the table, at a pid seen
|
|
46
|
+
* before, and after MAX_DEPTH rows. */
|
|
47
|
+
export function ancestors(table, pid) {
|
|
48
|
+
const { byPid } = indexOf(table);
|
|
49
|
+
const chain = [];
|
|
50
|
+
const seen = new Set();
|
|
51
|
+
for (let row = byPid.get(pid); row && !seen.has(row.pid) && chain.length < MAX_DEPTH; row = byPid.get(row.ppid)) {
|
|
52
|
+
seen.add(row.pid);
|
|
53
|
+
chain.push(row);
|
|
54
|
+
}
|
|
55
|
+
return chain;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// The pids of a job: its group members, then everything below them by parent pid, which also catches children
|
|
59
|
+
// that started a group of their own.
|
|
60
|
+
function jobPids(leader, rows) {
|
|
61
|
+
const members = rows.filter((row) => row.pgid === leader).map((row) => row.pid);
|
|
62
|
+
return descendants(rows, [leader, ...members]);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The pids of a job, from the given `ps` text or a fresh listing. */
|
|
66
|
+
export function treePids(leader, ps = null) {
|
|
67
|
+
return [...jobPids(leader, psRows(ps ?? probeProcessTree()))];
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Returns null for a holder whose leader process is not listed, else the CPU seconds of all its processes. */
|
|
71
|
+
export function jobCpu(holder, rows) {
|
|
72
|
+
const leader = holder.pgid ?? holder.pid;
|
|
73
|
+
if (!rows.some((row) => row.pid === leader)) return null;
|
|
74
|
+
const pids = jobPids(leader, rows);
|
|
75
|
+
return Math.round(rows.reduce((sum, row) => sum + (pids.has(row.pid) ? row.cpu : 0), 0) * 100) / 100;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const sendSignal = (pid, signal) => process.kill(pid, signal);
|
|
79
|
+
|
|
80
|
+
/** Sends a signal to a whole process group. Returns { sent: true }, or { sent: false, code } with the error code:
|
|
81
|
+
* ESRCH when the group is gone, EPERM when it belongs to another user. */
|
|
82
|
+
export function signalGroup(pgid, signal, kill = sendSignal) {
|
|
83
|
+
try {
|
|
84
|
+
kill(-pgid, signal);
|
|
85
|
+
return { sent: true };
|
|
86
|
+
} catch (e) { return { sent: false, code: e.code ?? String(e.message) }; }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Signals a job: the group as a whole first, then each process of the job. A group or process that is gone
|
|
90
|
+
* already is passed over. Returns { pids, refused }: the pids it signalled, and one text for each signal that was
|
|
91
|
+
* refused, such as "pid 4101 (EPERM)". opts: ps, the `ps` text to walk instead of a fresh listing; kill. */
|
|
92
|
+
export function killTree(leader, signal, { ps = null, kill = sendSignal } = {}) {
|
|
93
|
+
const pids = treePids(leader, ps);
|
|
94
|
+
const refused = [];
|
|
95
|
+
const group = signalGroup(leader, signal, kill);
|
|
96
|
+
if (!group.sent && group.code !== "ESRCH") refused.push(`group ${leader} (${group.code})`);
|
|
97
|
+
for (const pid of pids) {
|
|
98
|
+
try {
|
|
99
|
+
kill(pid, signal);
|
|
100
|
+
} catch (e) {
|
|
101
|
+
if (e.code !== "ESRCH") refused.push(`pid ${pid} (${e.code ?? e.message})`);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return { pids, refused };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Sends TERM to a process group, waits graceMs, then sends KILL to the listed processes that are still there.
|
|
108
|
+
* Returns { stopped: true }, or { stopped: false, why } when a signal was refused. A group that is already gone
|
|
109
|
+
* counts as stopped. */
|
|
110
|
+
export async function stopGroup(pgid, procs, { graceMs, isAlive = alive, kill = sendSignal }) {
|
|
111
|
+
const term = signalGroup(pgid, "SIGTERM", kill);
|
|
112
|
+
if (!term.sent && term.code !== "ESRCH") return { stopped: false, why: `TERM refused (${term.code})` };
|
|
113
|
+
await new Promise((done) => setTimeout(done, graceMs));
|
|
114
|
+
const refused = [];
|
|
115
|
+
for (const proc of procs) {
|
|
116
|
+
if (!isAlive(proc.pid)) continue;
|
|
117
|
+
try {
|
|
118
|
+
kill(proc.pid, "SIGKILL");
|
|
119
|
+
} catch (e) {
|
|
120
|
+
if (e.code !== "ESRCH") refused.push(`${proc.pid} (${e.code ?? e.message})`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return refused.length ? { stopped: false, why: `KILL refused for pid ${refused.join(", ")}` } : { stopped: true };
|
|
124
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// Works out which project a job counts under: the part of its label in front of the colon, else the name of the
|
|
2
|
+
// repository folder it runs in, else the name of the folder itself.
|
|
3
|
+
import { basename } from "node:path";
|
|
4
|
+
import { repoName } from "./git.mjs";
|
|
5
|
+
|
|
6
|
+
// The project prefix of a label: up to 40 characters in front of the first colon.
|
|
7
|
+
const PREFIX_RE = /^([^:]{1,40}):\s*/;
|
|
8
|
+
|
|
9
|
+
/** The label prefix: "shop-api" for "shop-api: unit tests", null without one. */
|
|
10
|
+
export function labelProject(label) {
|
|
11
|
+
return String(label ?? "").match(PREFIX_RE)?.[1].trim() || null;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** The label without its project prefix, so a project name never decides what a job is. */
|
|
15
|
+
export function labelTask(label) {
|
|
16
|
+
return String(label ?? "").replace(PREFIX_RE, "");
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** The repository folder name for a working directory. A linked worktree reports its main repository. */
|
|
20
|
+
export function folderProject(cwd) {
|
|
21
|
+
return repoName(cwd) || basename(cwd) || "unknown";
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function jobProject({ label, project, cwd } = {}) {
|
|
25
|
+
return labelProject(label) || project || (cwd ? basename(cwd) : null) || "unknown";
|
|
26
|
+
}
|
package/queue/ps.mjs
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// Parsers for `ps` output. Each takes the text a probe in probes.mjs returned and never runs anything itself, so it
|
|
2
|
+
// can be tested on sample output. A line that does not fit the layout, such as a header, is skipped.
|
|
3
|
+
|
|
4
|
+
/** A `ps` time value, "[[days-]hours:]minutes:seconds" with optional fractions of a second, in seconds. Both the
|
|
5
|
+
* elapsed time (etime) and the CPU time (time) use this layout. */
|
|
6
|
+
export function psSeconds(value) {
|
|
7
|
+
const text = String(value).trim();
|
|
8
|
+
const dash = text.indexOf("-");
|
|
9
|
+
const days = dash < 0 ? 0 : Number(text.slice(0, dash));
|
|
10
|
+
return text.slice(dash + 1).split(":").map(Number).reduce((total, part) => total * 60 + part, 0) + days * 86_400;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Seconds each listed process has run, from `ps -o pid=,etime=`. A pid ps does not list is left out. */
|
|
14
|
+
export function parseElapsed(text) {
|
|
15
|
+
const ages = new Map();
|
|
16
|
+
for (const line of String(text ?? "").split("\n")) {
|
|
17
|
+
const found = line.trim().match(/^(\d+)\s+((?:\d+-)?(?:\d+:)?\d+:\d+)$/);
|
|
18
|
+
if (found) ages.set(Number(found[1]), psSeconds(found[2]));
|
|
19
|
+
}
|
|
20
|
+
return ages;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Parses `ps -o pid=,ppid=,pgid=[,time=]` text into [{ pid, ppid, pgid, cpu }]; cpu is 0 without a time column. */
|
|
24
|
+
export function psRows(text) {
|
|
25
|
+
const rows = [];
|
|
26
|
+
for (const line of String(text ?? "").split("\n")) {
|
|
27
|
+
const [pid, ppid, pgid, time] = line.trim().split(/\s+/);
|
|
28
|
+
if (![pid, ppid, pgid].every((x) => /^\d+$/.test(x ?? ""))) continue;
|
|
29
|
+
rows.push({ pid: Number(pid), ppid: Number(ppid), pgid: Number(pgid), cpu: time ? psSeconds(time) : 0 });
|
|
30
|
+
}
|
|
31
|
+
return rows;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const TABLE_LINE = /^(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\S+)\s+([\d.]+)\s+(\d+)\s+(.*)$/;
|
|
35
|
+
/** Parses `ps -Ao pid=,ppid=,pgid=,etime=,time=,pcpu=,rss=,command=` text into rows; age in ms, cpu in seconds,
|
|
36
|
+
* rss in KB. */
|
|
37
|
+
export function parseProcessTable(text) {
|
|
38
|
+
const rows = [];
|
|
39
|
+
for (const line of String(text ?? "").split("\n")) {
|
|
40
|
+
const m = line.trim().match(TABLE_LINE);
|
|
41
|
+
if (!m) continue;
|
|
42
|
+
rows.push({
|
|
43
|
+
pid: +m[1], ppid: +m[2], pgid: +m[3], age: psSeconds(m[4]) * 1000, cpu: psSeconds(m[5]), pcpu: +m[6],
|
|
44
|
+
rss: +m[7], cmd: m[8],
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
return rows;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The process group id from `ps -o pgid= -p <pid>`, or null when the text holds no positive whole number. */
|
|
51
|
+
export function parseGroupId(text) {
|
|
52
|
+
const value = String(text ?? "").trim();
|
|
53
|
+
return /^\d+$/.test(value) && Number(value) > 0 ? Number(value) : null;
|
|
54
|
+
}
|
package/queue/reaper.mjs
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The reaper, meant to be started by a scheduler every few minutes. It stops dev servers that have gone idle and
|
|
3
|
+
// sends notices about test runs outside the queue, jobs idle in a slot, an overloaded machine and a filling disk.
|
|
4
|
+
// Only idle dev servers are ever stopped. `--dry` prints what a run would do and changes nothing.
|
|
5
|
+
import { existsSync } from "node:fs";
|
|
6
|
+
import { basename } from "node:path";
|
|
7
|
+
import { isMainModule, loadSettings, paths, timeZone } from "./settings.mjs";
|
|
8
|
+
import { snapshot } from "./slots.mjs";
|
|
9
|
+
import { idleText, sampleKeepMs, serverIdleVerdict, serverTest } from "./idle.mjs";
|
|
10
|
+
import { LAUNCHER_RE, TEST_RUN_RE } from "./commands.mjs";
|
|
11
|
+
import { parseProcessTable } from "./ps.mjs";
|
|
12
|
+
import { ancestors, descendants, stopGroup } from "./proctree.mjs";
|
|
13
|
+
import { addNotice, slotIdleCheck } from "./notices.mjs";
|
|
14
|
+
import { flagError, SCRIPT_FLAGS, USAGE_EXIT } from "./args.mjs";
|
|
15
|
+
import { strayRuns } from "./stray.mjs";
|
|
16
|
+
import { readHealth } from "./health.mjs";
|
|
17
|
+
import { notify as sendNotice } from "./notify.mjs";
|
|
18
|
+
import { readJson, writeJsonAtomic } from "./files.mjs";
|
|
19
|
+
import { HOUR, MINUTE } from "./units.mjs";
|
|
20
|
+
import { probeGroupOf, probeLoad, probeProcessCpu, probeProcessTable, probeSwapPct } from "./probes.mjs";
|
|
21
|
+
|
|
22
|
+
// Minimum time between two notices of the same sort; for a failed stop, of the same process group.
|
|
23
|
+
const REPEAT = { stray: HOUR, overload: HOUR, lowDisk: 6 * HOUR, stopFailed: HOUR };
|
|
24
|
+
const OVERLOAD_RUNS = 2;
|
|
25
|
+
|
|
26
|
+
/** Returns a Map from process group id to its rows. */
|
|
27
|
+
export function groupRows(rows) {
|
|
28
|
+
const groups = new Map();
|
|
29
|
+
for (const row of rows) (groups.get(row.pgid) ?? groups.set(row.pgid, []).get(row.pgid)).push(row);
|
|
30
|
+
return groups;
|
|
31
|
+
}
|
|
32
|
+
/** A command line cut down to its program name and first argument, with folders removed. */
|
|
33
|
+
export function shortCommand(command) {
|
|
34
|
+
const [program = "", arg] = String(command ?? "").trim().split(/\s+/);
|
|
35
|
+
return [basename(program), arg?.startsWith("/") ? basename(arg) : arg].filter(Boolean).join(" ");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** True when every process in the group is the server, a process it started, or a process on the line above it that
|
|
39
|
+
* is a launcher or itself names a dev server (isServerCmd). */
|
|
40
|
+
export function serverOnly(procs, server, isServerCmd = () => false) {
|
|
41
|
+
const line = descendants(procs, [server.pid]);
|
|
42
|
+
for (const p of ancestors(procs, server.ppid)) {
|
|
43
|
+
if (line.has(p.pid)) break;
|
|
44
|
+
if (!LAUNCHER_RE.test(p.cmd) && !isServerCmd(p.cmd)) return false;
|
|
45
|
+
line.add(p.pid);
|
|
46
|
+
}
|
|
47
|
+
return procs.every((p) => line.has(p.pid));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Each check below takes the readings of this run (ctx) and the state the previous run left, and returns
|
|
51
|
+
// { state, lines } with the state keys it owns, plus what reap() needs to sum up the run.
|
|
52
|
+
|
|
53
|
+
/** Idle dev servers: a server group that stayed idle for the window is stopped. A stop that fails sends a notice,
|
|
54
|
+
* at most one per group per REPEAT.stopFailed. State: samples, the CPU samples per process group, and
|
|
55
|
+
* stopFailedTold, the time of the last failed-stop notice per process group. */
|
|
56
|
+
export async function checkIdleServers(ctx, state) {
|
|
57
|
+
const { groups, holders, now, dry, settings, myPgid, isDevServer, keep, stopIdle, notify } = ctx;
|
|
58
|
+
const samples = { ...state.samples };
|
|
59
|
+
const stopFailedTold = {};
|
|
60
|
+
for (const [pgid, at] of Object.entries(state.stopFailedTold ?? {})) {
|
|
61
|
+
if (groups.has(Number(pgid))) stopFailedTold[pgid] = at;
|
|
62
|
+
}
|
|
63
|
+
const lines = [];
|
|
64
|
+
const stopped = [];
|
|
65
|
+
const failed = [];
|
|
66
|
+
const slotPids = new Set(holders.flatMap((h) => [h.pid, h.pgid]).filter(Boolean));
|
|
67
|
+
const keepMs = sampleKeepMs(settings.idle.serverIdleMin);
|
|
68
|
+
let watched = 0;
|
|
69
|
+
for (const [pgid, procs] of groups) {
|
|
70
|
+
// the innermost match, so a launcher of any shape that names the server (sh -ec "vite & make watch",
|
|
71
|
+
// concurrently "vite" "make watch") is a process above the server, never the server itself
|
|
72
|
+
const matches = procs.filter((p) => isDevServer(p.cmd));
|
|
73
|
+
const above = new Set(matches.map((p) => p.ppid));
|
|
74
|
+
const server = matches.find((p) => !above.has(p.pid));
|
|
75
|
+
if (pgid <= 1 || pgid === myPgid || !server) {
|
|
76
|
+
delete samples[pgid];
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
watched++;
|
|
80
|
+
const inSlot = (p) => slotPids.has(p.pid) || slotPids.has(p.pgid);
|
|
81
|
+
const protectedProc = (p) => TEST_RUN_RE.test(p.cmd) || inSlot(p) || !!keep?.test(p.cmd);
|
|
82
|
+
const exempt = procs.some(protectedProc);
|
|
83
|
+
const cpu = procs.reduce((sum, p) => sum + p.cpu, 0);
|
|
84
|
+
const ageMs = Math.max(...procs.map((p) => p.age));
|
|
85
|
+
samples[pgid] = [...(samples[pgid] ?? []), { t: now, cpu }].filter((sample) => now - sample.t <= keepMs);
|
|
86
|
+
const verdict = serverIdleVerdict({ ageMs, samples: samples[pgid], now, exempt }, settings.idle);
|
|
87
|
+
const name = shortCommand(server.cmd);
|
|
88
|
+
if (dry) {
|
|
89
|
+
const age = Math.round(ageMs / MINUTE);
|
|
90
|
+
const facts = `${age} min old, ${cpu.toFixed(0)} s of CPU so far, state ${verdict.state}`;
|
|
91
|
+
lines.push(`server group ${pgid}: ${name}, ${facts}`);
|
|
92
|
+
}
|
|
93
|
+
if (!verdict.idle) continue;
|
|
94
|
+
if (!serverOnly(procs, server, isDevServer)) { // stopping the group would stop that program too
|
|
95
|
+
const shared = "shares its group with another program: left running";
|
|
96
|
+
lines.push(`idle dev server ${name} (process group ${pgid}) ${shared}`);
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
const memoryMB = Math.round(procs.reduce((sum, p) => sum + (p.rss || 0), 0) / 1024);
|
|
100
|
+
const what = `${name} (process group ${pgid}, ${idleText(verdict)}, ${memoryMB} MB of memory)`;
|
|
101
|
+
if (!dry) {
|
|
102
|
+
const result = await stopIdle(pgid, procs);
|
|
103
|
+
if (result?.stopped === false) {
|
|
104
|
+
failed.push(what);
|
|
105
|
+
const text = `stop failed: idle dev server ${what}, ${result.why}`;
|
|
106
|
+
lines.push(text);
|
|
107
|
+
if (now - (stopFailedTold[pgid] ?? 0) > REPEAT.stopFailed) {
|
|
108
|
+
notify("dotime: dev server stop failed", text);
|
|
109
|
+
stopFailedTold[pgid] = now;
|
|
110
|
+
}
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
delete samples[pgid];
|
|
114
|
+
}
|
|
115
|
+
stopped.push(what);
|
|
116
|
+
}
|
|
117
|
+
for (const pgid of Object.keys(samples)) if (!groups.has(Number(pgid))) delete samples[pgid];
|
|
118
|
+
if (stopped.length) {
|
|
119
|
+
lines.push(`${dry ? "dry run, would stop after idling" : "stopped after idling"}: ${stopped.join("; ")}`);
|
|
120
|
+
if (!dry) notify("dotime: dev servers stopped", stopped.join("; "));
|
|
121
|
+
}
|
|
122
|
+
return { state: { samples, stopFailedTold }, lines, stopped, failed, watched };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Large test runs that bypassed the queue: reported, never stopped, with at most one notice per REPEAT.stray.
|
|
126
|
+
* State: strayTold, the root pids already told about, and lastStray. */
|
|
127
|
+
export function checkStrayRuns(ctx, state) {
|
|
128
|
+
const { rows, holders, now, dry, notify } = ctx;
|
|
129
|
+
const livePids = new Set(rows.map((row) => row.pid));
|
|
130
|
+
const strayTold = (state.strayTold ?? []).filter((pid) => livePids.has(pid));
|
|
131
|
+
let lastStray = state.lastStray;
|
|
132
|
+
const lines = [];
|
|
133
|
+
for (const run of strayRuns(rows, { holders })) {
|
|
134
|
+
const size = `${run.procs} test processes, ${(run.rssMB / 1024).toFixed(1)} GB of memory`;
|
|
135
|
+
const text = `unqueued test run: ${shortCommand(run.cmd)}, pid ${run.rootPid}, ${size}, left running; `
|
|
136
|
+
+ 'hint: start large runs with dotime-queue run --label "<project>: <task>" -- <command>';
|
|
137
|
+
lines.push(text);
|
|
138
|
+
if (dry || strayTold.includes(run.rootPid) || now - (lastStray ?? 0) <= REPEAT.stray) continue;
|
|
139
|
+
notify("dotime: unqueued test run", text);
|
|
140
|
+
lastStray = now;
|
|
141
|
+
strayTold.push(run.rootPid);
|
|
142
|
+
}
|
|
143
|
+
return { state: { strayTold, ...(lastStray === undefined ? {} : { lastStray }) }, lines };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Jobs that hold a slot without doing work: one notice each. State: slotIdle, the CPU samples per slot. */
|
|
147
|
+
export function checkIdleSlots(ctx, state) {
|
|
148
|
+
const { holders, queue, now, dry, notify, record, cpuPs, settings, tz } = ctx;
|
|
149
|
+
try {
|
|
150
|
+
const checked = slotIdleCheck({
|
|
151
|
+
holders, waiting: queue, state: state.slotIdle ?? {}, now, dry, notify, record, ps: cpuPs,
|
|
152
|
+
idle: settings.idle, tz,
|
|
153
|
+
});
|
|
154
|
+
return { state: { slotIdle: checked.state }, lines: checked.lines };
|
|
155
|
+
} catch (e) {
|
|
156
|
+
return { state: {}, lines: [`idle-slot check skipped: ${String(e?.message ?? e).slice(0, 200)}`] };
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** An overloaded machine, reported when it shows on OVERLOAD_RUNS runs in a row, at most once per REPEAT.overload.
|
|
161
|
+
* State: streak and lastOverload. */
|
|
162
|
+
export function checkOverload(ctx, state) {
|
|
163
|
+
const { rows, now, dry, notify, health, load, cores, swapPct } = ctx;
|
|
164
|
+
const reaperSettings = ctx.settings.reaper;
|
|
165
|
+
const diskShort = health.diskGB != null && health.diskGB < reaperSettings.overloadDiskGB;
|
|
166
|
+
const memoryShort = health.freePct != null && health.freePct < reaperSettings.overloadMemPct;
|
|
167
|
+
const busy = load > cores * reaperSettings.overloadPerCore || swapPct > reaperSettings.overloadSwapPct;
|
|
168
|
+
const overloaded = busy || diskShort || memoryShort;
|
|
169
|
+
const streak = overloaded ? state.streak + 1 : 0;
|
|
170
|
+
let lastOverload = state.lastOverload;
|
|
171
|
+
const lines = [];
|
|
172
|
+
if (streak >= OVERLOAD_RUNS && now - lastOverload > REPEAT.overload) {
|
|
173
|
+
const cpuByProgram = new Map();
|
|
174
|
+
for (const row of rows) {
|
|
175
|
+
const program = shortCommand(row.cmd).split(" ")[0];
|
|
176
|
+
cpuByProgram.set(program, (cpuByProgram.get(program) ?? 0) + row.pcpu);
|
|
177
|
+
}
|
|
178
|
+
const busiest = [...cpuByProgram].sort((a, b) => b[1] - a[1]).slice(0, 3);
|
|
179
|
+
const top = busiest.map(([program, pcpu]) => `${program} ${Math.round(pcpu)}%`).join(", ");
|
|
180
|
+
const memory = health.freePct == null ? "no memory reading" : `${health.freePct}% of memory free`;
|
|
181
|
+
const disk = health.diskGB == null ? "no disk reading" : `${health.diskGB.toFixed(1)} GB of disk free`;
|
|
182
|
+
const text = `overloaded: busiest programs ${top || "not known"}; ${cores} cores at load ${load.toFixed(1)}, `
|
|
183
|
+
+ `${disk}, ${memory}, ${Math.round(swapPct)}% of swap in use`;
|
|
184
|
+
lines.push(text);
|
|
185
|
+
if (!dry) {
|
|
186
|
+
notify("dotime: machine overloaded", text);
|
|
187
|
+
lastOverload = now;
|
|
188
|
+
}
|
|
189
|
+
} else if (overloaded) {
|
|
190
|
+
lines.push(`overload seen: run ${streak} in a row, no notice this time`);
|
|
191
|
+
}
|
|
192
|
+
return { state: { streak, lastOverload }, lines, overloaded };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Free disk below reaper.lowDiskGB, reported early and at most once per REPEAT.lowDisk. State: lastLowDisk. */
|
|
196
|
+
export function checkLowDisk(ctx, state) {
|
|
197
|
+
const { now, dry, notify, health } = ctx;
|
|
198
|
+
const lowDiskGB = ctx.settings.reaper.lowDiskGB;
|
|
199
|
+
if (health.diskGB == null || health.diskGB >= lowDiskGB || now - (state.lastLowDisk ?? 0) <= REPEAT.lowDisk) {
|
|
200
|
+
return { state: {}, lines: [] };
|
|
201
|
+
}
|
|
202
|
+
const text = `disk low: ${health.diskGB.toFixed(1)} GB free, notice level ${lowDiskGB} GB`;
|
|
203
|
+
if (dry) return { state: {}, lines: [text] };
|
|
204
|
+
notify("dotime: disk space low", text);
|
|
205
|
+
return { state: { lastLowDisk: now }, lines: [text] };
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** One reaper run over the given readings. Nothing is read from the machine or the state folder in here, so tests
|
|
209
|
+
* can pass any process table. settings and tz come from the caller; record(key, entry) stores an idle-slot notice.
|
|
210
|
+
* state is what the previous run returned. Runs the checks in order and merges their state and lines.
|
|
211
|
+
* Returns { state, lines, stopped }. */
|
|
212
|
+
export async function reap({
|
|
213
|
+
rows, holders = [], queue = [], state = {}, now = Date.now(), dry = false, settings, tz,
|
|
214
|
+
health = { freePct: null, diskGB: null }, load = 0, cores = 1, swapPct = 0, myPgid = null,
|
|
215
|
+
notify = () => {}, record = () => {}, stop = null, cpuPs = () => "",
|
|
216
|
+
}) {
|
|
217
|
+
let keep;
|
|
218
|
+
try { keep = new RegExp(settings.reaper.keepPattern); } catch { keep = null; }
|
|
219
|
+
const ctx = {
|
|
220
|
+
rows, groups: groupRows(rows), holders, queue, now, dry, settings, tz, health, load, cores, swapPct, myPgid,
|
|
221
|
+
notify, record, cpuPs, keep,
|
|
222
|
+
// Both patterns are compiled once per run.
|
|
223
|
+
isDevServer: serverTest(settings.reaper.serverPattern),
|
|
224
|
+
stopIdle: stop ?? ((pgid, procs) => stopGroup(pgid, procs, { graceMs: settings.limits.killGraceMs })),
|
|
225
|
+
};
|
|
226
|
+
let next = { samples: {}, streak: 0, lastOverload: 0, ...state };
|
|
227
|
+
const lines = [];
|
|
228
|
+
const merge = (result) => {
|
|
229
|
+
next = { ...next, ...result.state };
|
|
230
|
+
lines.push(...result.lines);
|
|
231
|
+
return result;
|
|
232
|
+
};
|
|
233
|
+
const servers = merge(await checkIdleServers(ctx, next));
|
|
234
|
+
merge(checkStrayRuns(ctx, next));
|
|
235
|
+
merge(checkIdleSlots(ctx, next));
|
|
236
|
+
const overload = merge(checkOverload(ctx, next));
|
|
237
|
+
merge(checkLowDisk(ctx, next));
|
|
238
|
+
if (!servers.stopped.length && !servers.failed.length && !overload.overloaded) {
|
|
239
|
+
lines.push(`quiet: dev-server groups under watch ${servers.watched}, ${Math.round(swapPct)}% of swap in use, `
|
|
240
|
+
+ `load ${load.toFixed(1)}`);
|
|
241
|
+
}
|
|
242
|
+
return { state: next, lines, stopped: servers.stopped };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async function main() {
|
|
246
|
+
const badFlag = flagError(["reaper", ...process.argv.slice(2)], SCRIPT_FLAGS);
|
|
247
|
+
if (badFlag) {
|
|
248
|
+
process.stderr.write(`reaper: ${badFlag}; usage: reaper.mjs [--dry]\n`);
|
|
249
|
+
process.exitCode = USAGE_EXIT;
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
const dry = process.argv.includes("--dry");
|
|
253
|
+
const now = Date.now();
|
|
254
|
+
const settings = loadSettings();
|
|
255
|
+
const files = paths();
|
|
256
|
+
const stateFile = files.reaperState;
|
|
257
|
+
const state = readJson(stateFile, {});
|
|
258
|
+
const { holders, queue } = snapshot({ dirs: files, prune: !dry });
|
|
259
|
+
const { load, cores } = probeLoad();
|
|
260
|
+
const run = await reap({
|
|
261
|
+
rows: parseProcessTable(probeProcessTable()), holders, queue, state, now, dry, settings, tz: timeZone(),
|
|
262
|
+
health: readHealth(), load, cores, swapPct: probeSwapPct(), myPgid: probeGroupOf(process.pid),
|
|
263
|
+
notify: (title, message) => sendNotice(title, message, { env: process.env, logFile: files.notifyLog }),
|
|
264
|
+
record: (key, entry) => addNotice(key, entry, files.notices),
|
|
265
|
+
cpuPs: probeProcessCpu,
|
|
266
|
+
});
|
|
267
|
+
for (const line of run.lines) console.log(`${new Date(now).toISOString()} reaper: ${line}`);
|
|
268
|
+
if (dry) {
|
|
269
|
+
if (!existsSync(stateFile)) {
|
|
270
|
+
console.log("reaper: dry run without saved samples, idle servers show only after real runs have covered "
|
|
271
|
+
+ "one idle window");
|
|
272
|
+
}
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
writeJsonAtomic(stateFile, run.state);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
if (isMainModule(import.meta.url)) await main();
|