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
package/queue/run.mjs
ADDED
|
@@ -0,0 +1,612 @@
|
|
|
1
|
+
// The `run` command, in four steps: planJob decides the limit and whether the job is refused, skipFor whether a check
|
|
2
|
+
// that already passed on this code is skipped, waitForSlot waits in line until a slot is taken (for a nested run,
|
|
3
|
+
// waitForPlace waits until a place under its parent job is), and runJob runs the job in its own process group under
|
|
4
|
+
// the limit. runCommand chains them and returns the exit code; it never ends the process itself. These come in
|
|
5
|
+
// through deps, so tests can drive each step: the clock, sleeping and timers, the health reading, the commit read when
|
|
6
|
+
// the job is queued and again when it starts, the current folder, starting the job, signals sent to it and signals
|
|
7
|
+
// received, messages, notifications and stored notices, and the environment in which a nested run finds the marker
|
|
8
|
+
// of its parent job. The rest is done directly: the slot, line, nested, place and journal files in the folders named
|
|
9
|
+
// by files, the git calls for the project name and the code fingerprint, the process table read by snapshot and
|
|
10
|
+
// killTree, and this process's own pid and node binary.
|
|
11
|
+
import { spawn as spawnProcess } from "node:child_process";
|
|
12
|
+
import { rmSync } from "node:fs";
|
|
13
|
+
import { fileURLToPath } from "node:url";
|
|
14
|
+
import { parseRunArgs, USAGE, USAGE_EXIT } from "./args.mjs";
|
|
15
|
+
import { minutesSince } from "./clock.mjs";
|
|
16
|
+
import { failStop } from "./failstop.mjs";
|
|
17
|
+
import { fingerprint } from "./fingerprint.mjs";
|
|
18
|
+
import { blockReason, blockText, decide, gateBlocks, shouldGiveUp } from "./gate.mjs";
|
|
19
|
+
import { gitState as readGitState } from "./git.mjs";
|
|
20
|
+
import { healthVerdict } from "./health.mjs";
|
|
21
|
+
import { NO_START_EXIT, readStartFailure, wrapperEnd } from "./job-wrapper.mjs";
|
|
22
|
+
import {
|
|
23
|
+
addWait, append, cmdString, jobEnd, parseLines, readLines, record, SKIPPABLE_KINDS, skipStamp,
|
|
24
|
+
} from "./journal.mjs";
|
|
25
|
+
import { alsoBuilds, cmdStem, kindOf } from "./kinds.mjs";
|
|
26
|
+
import { decideLimit, kindStats, stemStats } from "./limits.mjs";
|
|
27
|
+
import { addNotice as storeNotice, longRunAlert } from "./notices.mjs";
|
|
28
|
+
import {
|
|
29
|
+
JOB_MARKER, markerOf, NO_SKIP_MARKER, PARENT_MARKER, parentJob, placeKey, slotMarkerOf, stillRunning,
|
|
30
|
+
} from "./nested.mjs";
|
|
31
|
+
import { killTree, signalGroup } from "./proctree.mjs";
|
|
32
|
+
import { folderProject, jobProject } from "./project.mjs";
|
|
33
|
+
import { addNested, enqueue, releaseSlot, snapshot, takePlace, takeSlot, updateSlot } from "./slots.mjs";
|
|
34
|
+
import { afterMs, MAX_TIMER_MS, wakeableSleep } from "./timer.mjs";
|
|
35
|
+
import { MINUTE } from "./units.mjs";
|
|
36
|
+
|
|
37
|
+
/** The exit codes of dotime-queue itself; a job that ran passes its own code on. */
|
|
38
|
+
export const EXIT = { usage: USAGE_EXIT, refused: 3, gaveUp: 75, timedOut: 124, noStart: NO_START_EXIT, left: 130 };
|
|
39
|
+
const REPEAT_WAIT_LINE_MS = MINUTE;
|
|
40
|
+
const WRAPPER = fileURLToPath(new URL("./job-wrapper.mjs", import.meta.url));
|
|
41
|
+
// Signals that take a waiting job out of the line, and signals that are passed on to a running job.
|
|
42
|
+
const LEAVE_SIGNALS = ["SIGINT", "SIGTERM"];
|
|
43
|
+
const FORWARD_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
44
|
+
|
|
45
|
+
/** Decides the run limit of a job and whether it is refused, from the journal rows alone; reads and changes
|
|
46
|
+
* nothing. request: { label, command (the command line as text), kind (given with --kind, or undefined), maxRun,
|
|
47
|
+
* priority, afterFix, project, cwd, head, fingerprint, queuedAt, tz }.
|
|
48
|
+
* Returns { kind, stem, limit, refusal, afterFixUsed, details }: refusal is null or { reason }; afterFixUsed is true
|
|
49
|
+
* when --after-fix let through a run that would have been refused; details go into the journal line, with the
|
|
50
|
+
* fingerprint as fp. */
|
|
51
|
+
export function planJob(request, settings, journalRows) {
|
|
52
|
+
const { label, command, maxRun, priority, afterFix, project, cwd, head, queuedAt, tz } = request;
|
|
53
|
+
const limits = settings.limits;
|
|
54
|
+
const kind = kindOf(label, command, request.kind);
|
|
55
|
+
const stem = cmdStem(command);
|
|
56
|
+
const window = { project, now: queuedAt, windowDays: limits.windowDays };
|
|
57
|
+
const stats = kindStats(journalRows, { ...window, kind });
|
|
58
|
+
const stemRuns = stemStats(journalRows, { ...window, stem });
|
|
59
|
+
const limit = decideLimit({ maxRun, kind, stats, stem: stemRuns, priority }, limits);
|
|
60
|
+
const check = { label, cmd: command, project, cwd, head, fingerprint: request.fingerprint, at: queuedAt };
|
|
61
|
+
const verdict = failStop(journalRows, check, limits, tz);
|
|
62
|
+
const details = {
|
|
63
|
+
kind,
|
|
64
|
+
...(stem ? { stem } : {}),
|
|
65
|
+
limitMin: limit.limitMin,
|
|
66
|
+
limitBasis: limit.basis,
|
|
67
|
+
// Stored as fp, the name every copy of the queue that shares the journal reads.
|
|
68
|
+
fp: request.fingerprint,
|
|
69
|
+
...(afterFix ? { afterFix } : {}),
|
|
70
|
+
};
|
|
71
|
+
return {
|
|
72
|
+
kind,
|
|
73
|
+
stem,
|
|
74
|
+
limit,
|
|
75
|
+
refusal: verdict.refuse && !afterFix ? { reason: verdict.reason } : null,
|
|
76
|
+
afterFixUsed: verdict.refuse && !!afterFix,
|
|
77
|
+
details,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Could a job of this kind and these words ever be skipped? Only a kind in SKIPPABLE_KINDS, and on a guessed kind
|
|
82
|
+
* only when neither the label nor the command also names a build or a deploy. job: { kind, kindGiven, label,
|
|
83
|
+
* command }. A job that could not is run, and so is everything nested in it. */
|
|
84
|
+
export function canSkip(job) {
|
|
85
|
+
return SKIPPABLE_KINDS.includes(job.kind) && (job.kindGiven || !alsoBuilds(job.label, job.command));
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** The pass stamp on which a job is skipped, or null when it must run. Only a job of a kind in SKIPPABLE_KINDS is
|
|
89
|
+
* ever skipped, and only on a stamp from skipStamp: a run of the same project, label and command, in the same folder
|
|
90
|
+
* and with the same code fingerprint, that passed on this commit with a clean tree, while the tree is still clean
|
|
91
|
+
* now, with no failure of it on the commit since. A job whose label or command also names a build or a deploy is
|
|
92
|
+
* never skipped on a guessed kind, since its output may be needed; only --kind test or --kind lint allows it.
|
|
93
|
+
* job: { kind, kindGiven (true when --kind was given), label, command, cwd, fingerprint, folderProject (the
|
|
94
|
+
* project of the folder, as journal lines store it in project), commit ({ head, clean }, read when the job was
|
|
95
|
+
* queued), noSkip, at, tz }. rows: the journal rows. */
|
|
96
|
+
export function skipFor(job, rows) {
|
|
97
|
+
if (job.noSkip || !canSkip(job)) return null;
|
|
98
|
+
const folder = { project: job.folderProject, ...job.commit };
|
|
99
|
+
const check = { label: job.label, cmd: job.command, cwd: job.cwd, fp: job.fingerprint };
|
|
100
|
+
return skipStamp(rows, folder, check, { tz: job.tz, at: job.at });
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Waits in line until this job holds a slot. job: { pid, label, maxWait, slotMeta, settings, files, waitFrom,
|
|
104
|
+
* tally }; waitFrom and tally, when given, carry on an earlier wait, so the wait limit counts from its start and the
|
|
105
|
+
* time is booked with it. Priority plays no part in here: it is in the job's ticket, which orders the line, and in
|
|
106
|
+
* slotMeta.
|
|
107
|
+
* deps: { now, sleep, readHealth, say, leaving }; leaving() names a signal that asked the job to leave, or null.
|
|
108
|
+
* Returns { slot, tally, waitFrom }, { gaveUp: true, tally } or { left: signal, tally }; tally is the waiting time
|
|
109
|
+
* per gate in ms. */
|
|
110
|
+
export async function waitForSlot(job, deps) {
|
|
111
|
+
const { pid, label, maxWait, settings, files } = job;
|
|
112
|
+
const max = settings.slots;
|
|
113
|
+
const tally = { ...job.tally };
|
|
114
|
+
const waitFrom = job.waitFrom ?? deps.now();
|
|
115
|
+
let shownPosition = 0;
|
|
116
|
+
let shownAt = 0;
|
|
117
|
+
for (;;) {
|
|
118
|
+
const signal = deps.leaving?.() ?? null;
|
|
119
|
+
if (signal) return { left: signal, tally };
|
|
120
|
+
const snap = snapshot({ dirs: files, prune: true });
|
|
121
|
+
const turn = decide(snap, pid, max);
|
|
122
|
+
const ahead = turn.position - 1;
|
|
123
|
+
// One reading per poll, taken only when something needs it; the message reuses it.
|
|
124
|
+
let reading = null;
|
|
125
|
+
const health = () => (reading ??= healthVerdict(deps.readHealth(), settings.health));
|
|
126
|
+
// Only full slots make the health reading irrelevant to a waiter.
|
|
127
|
+
const slotFree = snap.holders.length < max;
|
|
128
|
+
const gateHealth = turn.go || slotFree ? health() : null;
|
|
129
|
+
if (turn.go && gateHealth.ok) {
|
|
130
|
+
const slot = takeSlot(pid, label, max, job.slotMeta, files);
|
|
131
|
+
if (slot) return { slot, tally, waitFrom };
|
|
132
|
+
}
|
|
133
|
+
const heldBy = blockReason({ holders: snap.holders, health: gateHealth, ahead }, max);
|
|
134
|
+
const now = deps.now();
|
|
135
|
+
const giveUp = shouldGiveUp({ startedAt: waitFrom, now, maxWaitMin: maxWait });
|
|
136
|
+
if (giveUp || turn.position !== shownPosition || now - shownAt > REPEAT_WAIT_LINE_MS) {
|
|
137
|
+
const all = gateBlocks({ holders: snap.holders, health: health(), ahead }, max);
|
|
138
|
+
const why = blockText(all) || "slot lost: another job took it a moment ago";
|
|
139
|
+
const waited = `${minutesSince(waitFrom, now)} min waited`;
|
|
140
|
+
if (giveUp) {
|
|
141
|
+
deps.say(`gave up: exit ${EXIT.gaveUp}, position ${turn.position}, ${waited}; ${why}; `
|
|
142
|
+
+ "hint: --max-wait 0 waits without limit");
|
|
143
|
+
return { gaveUp: true, tally };
|
|
144
|
+
}
|
|
145
|
+
const limitText = maxWait ? `wait limit ${maxWait} min` : "no wait limit";
|
|
146
|
+
deps.say(`in line: position ${turn.position}, ${waited}, ${limitText}; ${why}`);
|
|
147
|
+
shownPosition = turn.position;
|
|
148
|
+
shownAt = now;
|
|
149
|
+
}
|
|
150
|
+
const sleptFrom = deps.now();
|
|
151
|
+
await deps.sleep(settings.pollMs);
|
|
152
|
+
// A poll that ends with a signal pending is not booked: the job leaves at the top of the loop.
|
|
153
|
+
if (deps.leaving?.()) continue;
|
|
154
|
+
addWait(tally, heldBy, deps.now() - sleptFrom);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Waits until a nested run holds one of the settings.nestedPerJob places under its parent job. Only the parent's
|
|
159
|
+
* places count: no slot, no line and no health gate, so a nested run can never wait for its own outer job. Nested
|
|
160
|
+
* runs that wait under the same parent take the places in the order their notes were written. job: { pid, label,
|
|
161
|
+
* parent, maxWait, settings, files }, where parent is the job from outerJob(). deps: { now, sleep, say, leaving },
|
|
162
|
+
* as for waitForSlot. Returns { place, tally, waitFrom, atOnce }, where atOnce is true when the first look found a
|
|
163
|
+
* place, { gaveUp: true, tally }, { left: signal, tally }, or { parentGone: true, tally, waitFrom } once the parent
|
|
164
|
+
* has ended: the run is then no longer inside a job, and must not start without a slot. The parent is checked on
|
|
165
|
+
* every poll, and once more after a place was taken. */
|
|
166
|
+
export async function waitForPlace(job, deps) {
|
|
167
|
+
const { pid, label, parent, maxWait, settings, files } = job;
|
|
168
|
+
const max = settings.nestedPerJob;
|
|
169
|
+
const key = placeKey(parent);
|
|
170
|
+
const marker = markerOf(parent.file);
|
|
171
|
+
const under = (n) => n.outer === marker && n.outerPid === parent.pid && n.outerBorn === parent.born;
|
|
172
|
+
const tally = {};
|
|
173
|
+
const waitFrom = deps.now();
|
|
174
|
+
let shownPosition = 0;
|
|
175
|
+
let shownAt = 0;
|
|
176
|
+
for (;;) {
|
|
177
|
+
const signal = deps.leaving?.() ?? null;
|
|
178
|
+
if (signal) return { left: signal, tally };
|
|
179
|
+
const snap = snapshot({ dirs: files, prune: true });
|
|
180
|
+
if (!stillRunning(parent, snap)) return { parentGone: true, tally, waitFrom };
|
|
181
|
+
const taken = snap.places.filter((p) => p.parent === key).length;
|
|
182
|
+
const waiters = snap.nested.filter((n) => n.waiting && under(n)).sort((a, b) => a.at - b.at || a.pid - b.pid);
|
|
183
|
+
const index = waiters.findIndex((n) => n.pid === pid);
|
|
184
|
+
const position = index < 0 ? waiters.length + 1 : index + 1;
|
|
185
|
+
if (position <= max - taken) {
|
|
186
|
+
const place = takePlace(pid, label, key, max, files);
|
|
187
|
+
if (place && !stillRunning(parent, snapshot({ dirs: files }))) {
|
|
188
|
+
releaseSlot(place, pid);
|
|
189
|
+
return { parentGone: true, tally, waitFrom };
|
|
190
|
+
}
|
|
191
|
+
if (place) return { place, tally, waitFrom, atOnce: shownPosition === 0 && !Object.keys(tally).length };
|
|
192
|
+
}
|
|
193
|
+
const ahead = position - 1;
|
|
194
|
+
const why = taken >= max
|
|
195
|
+
? `no free nested place: ${taken} of ${max} taken under "${parent.label}", pid ${parent.pid}`
|
|
196
|
+
: ahead > 0 ? `not first in line under "${parent.label}": ${ahead} ahead`
|
|
197
|
+
: "place lost: another nested run took it a moment ago";
|
|
198
|
+
const now = deps.now();
|
|
199
|
+
const giveUp = shouldGiveUp({ startedAt: waitFrom, now, maxWaitMin: maxWait });
|
|
200
|
+
if (giveUp || position !== shownPosition || now - shownAt > REPEAT_WAIT_LINE_MS) {
|
|
201
|
+
const waited = `${minutesSince(waitFrom, now)} min waited`;
|
|
202
|
+
if (giveUp) {
|
|
203
|
+
deps.say(`gave up: exit ${EXIT.gaveUp}, nested position ${position}, ${waited}; ${why}; `
|
|
204
|
+
+ "hint: --max-wait 0 waits without limit, and nestedPerJob in config.json sets the places");
|
|
205
|
+
return { gaveUp: true, tally };
|
|
206
|
+
}
|
|
207
|
+
const limitText = maxWait ? `wait limit ${maxWait} min` : "no wait limit";
|
|
208
|
+
deps.say(`in line for a nested place: position ${position}, ${waited}, ${limitText}; ${why}`);
|
|
209
|
+
shownPosition = position;
|
|
210
|
+
shownAt = now;
|
|
211
|
+
}
|
|
212
|
+
const sleptFrom = deps.now();
|
|
213
|
+
await deps.sleep(settings.pollMs);
|
|
214
|
+
if (deps.leaving?.()) continue;
|
|
215
|
+
addWait(tally, [{ gate: "nested" }], deps.now() - sleptFrom);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Runs the job in a slot it holds and resolves with the exit code for `run`. job: { pid, label, project, cwd, cmd
|
|
220
|
+
* (the words), priority, kind, limit, waitFrom, settings, files, tz, journal, handOver, slotMarker }, where journal
|
|
221
|
+
* is the writer from journalWriter() and handOver(), when given, is called as soon as the job's own signal handlers
|
|
222
|
+
* are in place, so the caller can remove the ones it had until then without a moment in which a signal finds none.
|
|
223
|
+
* The job finds the marker of its slot in JOB_MARKER and in PARENT_MARKER. A nested run passes its note in place of
|
|
224
|
+
* a slot and the marker of the outermost job's slot as slotMarker, so its job finds that slot in JOB_MARKER and the
|
|
225
|
+
* note in PARENT_MARKER, and the note gets the job's process group and is removed at the end the same way. With
|
|
226
|
+
* job.noSkip (given for --no-skip, and for a job that could not be skipped itself) the job finds "1" in
|
|
227
|
+
* NO_SKIP_MARKER, so the runs nested in it are never skipped; without it the variable is left out.
|
|
228
|
+
* deps: { now, spawn, say, after, later, kill, notify, addNotice, gitState, signals }: after(minutes, fn) is the long
|
|
229
|
+
* timer, later(ms, fn) a short one, each returning a function that cancels it, kill(pid, signal) sends a signal,
|
|
230
|
+
* addNotice(key, entry, file) stores a notice, gitState(cwd) reads the commit, and signals is the process whose INT,
|
|
231
|
+
* TERM, HUP and exit events are watched. Every handler and timer it adds is removed at the end. A run limit whose last
|
|
232
|
+
* KILL is refused is reported, and journalled with stopFailed, as a stop that failed. */
|
|
233
|
+
export function runJob(job, slot, deps) {
|
|
234
|
+
const { pid, label, project, limit, settings, files, tz, journal } = job;
|
|
235
|
+
const killGraceMs = settings.limits.killGraceMs;
|
|
236
|
+
const { say, signals } = deps;
|
|
237
|
+
// The commit is read at this point because it is what a pass stamp will vouch for.
|
|
238
|
+
const commit = deps.gitState(job.cwd);
|
|
239
|
+
const startedAt = deps.now();
|
|
240
|
+
journal.note({ commit, startedAt });
|
|
241
|
+
if (startedAt - job.waitFrom > 5000) say(`started: ${minutesSince(job.waitFrom, startedAt)} min in line`);
|
|
242
|
+
// File descriptor 3 is a pipe on which the wrapper reports a command that could not be started. Whether the
|
|
243
|
+
// job inherits it depends on the system, so the run ends when the wrapper exits and not when the pipe closes.
|
|
244
|
+
const stdio = ["inherit", "inherit", "inherit", "pipe"];
|
|
245
|
+
const env = { ...process.env, [JOB_MARKER]: job.slotMarker ?? markerOf(slot), [PARENT_MARKER]: markerOf(slot) };
|
|
246
|
+
// Only this job's own --no-skip, or the one it was handed as a nested run, reaches the runs nested in it.
|
|
247
|
+
delete env[NO_SKIP_MARKER];
|
|
248
|
+
if (job.noSkip) env[NO_SKIP_MARKER] = "1";
|
|
249
|
+
const child = deps.spawn(process.execPath, [WRAPPER, String(pid), ...job.cmd], { stdio, detached: true, env });
|
|
250
|
+
updateSlot(slot, pid, { pgid: child.pid, startedAt });
|
|
251
|
+
const signalJob = (signal) => {
|
|
252
|
+
if (signalGroup(child.pid, signal, deps.kill).sent) return;
|
|
253
|
+
try { child.kill(signal); } catch { /* already gone */ }
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
// INT, TERM and HUP go on to the job; the first one received is kept for the journal.
|
|
257
|
+
let received = null;
|
|
258
|
+
let receivedAt = null;
|
|
259
|
+
const forwarders = FORWARD_SIGNALS.map((signal) => [signal, () => {
|
|
260
|
+
if (!received) {
|
|
261
|
+
received = signal;
|
|
262
|
+
receivedAt = deps.now();
|
|
263
|
+
}
|
|
264
|
+
signalJob(signal);
|
|
265
|
+
}]);
|
|
266
|
+
const onExit = () => { if (child.exitCode === null && child.signalCode === null) signalJob("SIGTERM"); };
|
|
267
|
+
for (const [signal, handler] of forwarders) signals.on(signal, handler);
|
|
268
|
+
signals.on("exit", onExit);
|
|
269
|
+
job.handOver?.();
|
|
270
|
+
|
|
271
|
+
let pastLimit = false;
|
|
272
|
+
let longRunAt = null;
|
|
273
|
+
let warnedAt = null;
|
|
274
|
+
let ended = false;
|
|
275
|
+
const timers = [];
|
|
276
|
+
const after = (minutes, fn) => { timers.push(deps.after(minutes, fn)); };
|
|
277
|
+
const later = (ms, fn) => { timers.push(deps.later(ms, fn)); };
|
|
278
|
+
let done;
|
|
279
|
+
const result = new Promise((resolve) => { done = resolve; });
|
|
280
|
+
const end = (exit) => {
|
|
281
|
+
if (ended) return;
|
|
282
|
+
ended = true;
|
|
283
|
+
releaseSlot(slot, pid);
|
|
284
|
+
for (const [signal, handler] of forwarders) signals.off(signal, handler);
|
|
285
|
+
// Safe to drop: the wrapper has exited, or the backstop ended a run whose last KILL was refused, and a TERM
|
|
286
|
+
// at exit would be refused the same way.
|
|
287
|
+
signals.off("exit", onExit);
|
|
288
|
+
for (const cancel of timers) cancel();
|
|
289
|
+
done(exit);
|
|
290
|
+
};
|
|
291
|
+
const stamps = () => ({
|
|
292
|
+
...(longRunAt ? { longRunAt: new Date(longRunAt).toISOString() } : {}),
|
|
293
|
+
...(warnedAt ? { warnedAt: new Date(warnedAt).toISOString() } : {}),
|
|
294
|
+
});
|
|
295
|
+
const killJob = (signal) => killTree(child.pid, signal, { kill: deps.kill });
|
|
296
|
+
// The last KILL decides: a process it cannot signal is still there, so the stop failed. A TERM refused earlier
|
|
297
|
+
// to a process that has ended since does not count.
|
|
298
|
+
const endTimedOut = () => {
|
|
299
|
+
if (ended) return;
|
|
300
|
+
const refused = killJob("SIGKILL").refused;
|
|
301
|
+
const why = refused.length ? `KILL refused for ${refused.join(", ")}` : null;
|
|
302
|
+
journal.finish("timed-out", EXIT.timedOut, { ...stamps(), ...(why ? { stopFailed: why } : {}) });
|
|
303
|
+
const how = why ? `stop failed after ${limit.killMin} min, ${why}` : `stopped after ${limit.killMin} min`;
|
|
304
|
+
say(`timed out: exit ${EXIT.timedOut}, ${how}; hint: the kind was taken as `
|
|
305
|
+
+ `${job.kind} (--kind <name> overrides it), and --max-run <min> sets the limit directly`);
|
|
306
|
+
end(EXIT.timedOut);
|
|
307
|
+
};
|
|
308
|
+
after(limit.killMin, () => {
|
|
309
|
+
pastLimit = true;
|
|
310
|
+
say(`run limit: stopping "${label}", KILL follows TERM after ${killGraceMs / 1000} s; ran ${limit.killMin} min `
|
|
311
|
+
+ `against a limit of ${limit.limitMin} min, set by ${limit.basis}`);
|
|
312
|
+
killJob("SIGTERM");
|
|
313
|
+
later(killGraceMs, () => killJob("SIGKILL"));
|
|
314
|
+
// Backstop for a wrapper that never exits.
|
|
315
|
+
later(Math.min(killGraceMs + 5000, MAX_TIMER_MS), endTimedOut);
|
|
316
|
+
});
|
|
317
|
+
if (job.priority) {
|
|
318
|
+
after(limit.limitMin, () => {
|
|
319
|
+
warnedAt = deps.now();
|
|
320
|
+
say(`priority warning: hard stop at ${limit.killMin} min, the ${limit.limitMin} min limit `
|
|
321
|
+
+ `(set by ${limit.basis}) was passed by "${label}"`);
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
if (limit.notifyLongRun) {
|
|
325
|
+
after(limit.longRunMin, () => {
|
|
326
|
+
longRunAt = deps.now();
|
|
327
|
+
try {
|
|
328
|
+
const alert = longRunAlert({
|
|
329
|
+
label, project, pid, minutes: minutesSince(startedAt, longRunAt), longRunBasis: limit.longRunBasis,
|
|
330
|
+
limitMin: limit.limitMin, killMin: limit.killMin, startedAt,
|
|
331
|
+
waiting: snapshot({ dirs: files }).queue, now: longRunAt, tz,
|
|
332
|
+
});
|
|
333
|
+
say(alert.message);
|
|
334
|
+
deps.notify(alert.title, alert.message);
|
|
335
|
+
deps.addNotice(alert.key, alert.entry, files.notices);
|
|
336
|
+
} catch { /* a notice that fails must not disturb the job */ }
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
wrapperEnd(child, child.stdio[3]).then(({ code, signal, report }) => {
|
|
340
|
+
if (pastLimit) return endTimedOut();
|
|
341
|
+
const startFailed = readStartFailure(report);
|
|
342
|
+
if (startFailed !== null) {
|
|
343
|
+
journal.finish("could-not-start", EXIT.noStart, stamps());
|
|
344
|
+
say(`start failed: exit ${EXIT.noStart}, ${startFailed}`);
|
|
345
|
+
return end(EXIT.noStart);
|
|
346
|
+
}
|
|
347
|
+
const exit = code ?? (signal ? 1 : 0);
|
|
348
|
+
const how = jobEnd({ code, signal, received });
|
|
349
|
+
const stoppedAt = new Date(receivedAt ?? deps.now()).toISOString();
|
|
350
|
+
const stopped = how.signal ? { signal: how.signal, stoppedAt } : {};
|
|
351
|
+
journal.finish(how.outcome, exit, { ...stamps(), ...stopped });
|
|
352
|
+
if (how.signal) {
|
|
353
|
+
say(`stopped: signal ${how.signal}, ${minutesSince(startedAt, deps.now())} min run, `
|
|
354
|
+
+ "journalled as stopped and not as failed");
|
|
355
|
+
}
|
|
356
|
+
end(exit);
|
|
357
|
+
});
|
|
358
|
+
// The wrapper is node itself, so this happens only when the system cannot start a process at all.
|
|
359
|
+
child.on("error", (e) => {
|
|
360
|
+
journal.finish("could-not-start", EXIT.noStart);
|
|
361
|
+
say(`start failed: exit ${EXIT.noStart}, ${e.message}`);
|
|
362
|
+
end(EXIT.noStart);
|
|
363
|
+
});
|
|
364
|
+
return result;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** The writer of a job's one journal line. note({ startedAt, commit, tally, details }) fills in any of those as the
|
|
368
|
+
* job goes; finish() writes the line once and ignores later calls. pid, when given, is the pid of the `run` process,
|
|
369
|
+
* kept with the line so a caller that started that process can find its own line. */
|
|
370
|
+
export function journalWriter({ label, folder, cwd, priority, queuedAt, command, details, file, now, pid }) {
|
|
371
|
+
const known = { startedAt: null, commit: { head: null, clean: null }, tally: {}, details };
|
|
372
|
+
let written = false;
|
|
373
|
+
return {
|
|
374
|
+
note(fields) {
|
|
375
|
+
for (const name of Object.keys(known)) if (fields[name] !== undefined) known[name] = fields[name];
|
|
376
|
+
},
|
|
377
|
+
finish(outcome, exit, more = {}) {
|
|
378
|
+
if (written) return;
|
|
379
|
+
written = true;
|
|
380
|
+
const { head, clean } = known.commit;
|
|
381
|
+
append(record({
|
|
382
|
+
label, project: folder, cwd, priority, queuedAt, startedAt: known.startedAt, endedAt: now(), outcome,
|
|
383
|
+
exit, tally: known.tally, cmd: command, head, clean, extra: { ...(pid ? { pid } : {}), ...known.details, ...more },
|
|
384
|
+
}), file);
|
|
385
|
+
},
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
const sleepFor = (ms) => new Promise((done) => setTimeout(done, ms));
|
|
390
|
+
|
|
391
|
+
/** The deps of the real command. readHealth, notify and after(minutes, fn) come from the entry point. */
|
|
392
|
+
export function realDeps({ readHealth, notify, after }) {
|
|
393
|
+
return {
|
|
394
|
+
now: Date.now,
|
|
395
|
+
sleep: sleepFor,
|
|
396
|
+
readHealth,
|
|
397
|
+
spawn: spawnProcess,
|
|
398
|
+
say: (text) => process.stderr.write(`dotime-queue: ${text}\n`),
|
|
399
|
+
usage: (text) => process.stderr.write(`${text}\n`),
|
|
400
|
+
after,
|
|
401
|
+
later: afterMs,
|
|
402
|
+
kill: (pid, signal) => process.kill(pid, signal),
|
|
403
|
+
notify,
|
|
404
|
+
addNotice: storeNotice,
|
|
405
|
+
gitState: readGitState,
|
|
406
|
+
signals: process,
|
|
407
|
+
cwd: () => process.cwd(),
|
|
408
|
+
env: process.env,
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** The folder the job runs in: ctx.cwd when given, else the current folder, read through deps.cwd(). Returns
|
|
413
|
+
* { cwd } or { error } when the current folder was removed. */
|
|
414
|
+
export function jobFolder(ctx, deps) {
|
|
415
|
+
if (ctx.cwd !== undefined) return { cwd: ctx.cwd };
|
|
416
|
+
try {
|
|
417
|
+
return { cwd: deps.cwd() };
|
|
418
|
+
} catch (e) {
|
|
419
|
+
if (e.code !== "ENOENT") throw e;
|
|
420
|
+
return { error: "the current folder was removed; start the job from a folder that exists" };
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/** Runs `dotime-queue run <args>` and resolves with its exit code. ctx: { settings, files, tz, cwd }; without cwd
|
|
425
|
+
* the current folder is read, and only after the arguments were found valid, so a usage error is reported the same
|
|
426
|
+
* way in a folder that was removed. A signal while the job waits takes it out of the line and resolves with 130
|
|
427
|
+
* instead of ending the process. A run whose deps.env holds a genuine marker of the job it runs in, in
|
|
428
|
+
* PARENT_MARKER or JOB_MARKER, is nested: once past the refusal check it runs with no slot, no place in line and no
|
|
429
|
+
* health gate, as soon as a place under that job is free. A test or lint check that already passed on the same clean
|
|
430
|
+
* commit is not run at all, nested or not, unless --no-skip is given: see skipFor. It takes no slot or place, is
|
|
431
|
+
* journalled as skipped with the stamp it relied on, and resolves with 0. */
|
|
432
|
+
export async function runCommand(args, ctx, deps) {
|
|
433
|
+
const { settings, files, tz } = ctx;
|
|
434
|
+
const { say, signals } = deps;
|
|
435
|
+
const parsed = parseRunArgs(args, settings);
|
|
436
|
+
if (parsed.error) {
|
|
437
|
+
if (parsed.error === USAGE) deps.usage(USAGE);
|
|
438
|
+
else say(parsed.error);
|
|
439
|
+
return EXIT.usage;
|
|
440
|
+
}
|
|
441
|
+
const folderRead = jobFolder(ctx, deps);
|
|
442
|
+
if (folderRead.error) {
|
|
443
|
+
say(folderRead.error);
|
|
444
|
+
return EXIT.usage;
|
|
445
|
+
}
|
|
446
|
+
const { cwd } = folderRead;
|
|
447
|
+
const { label, cmd, priority, maxWait, maxRun, afterFix } = parsed;
|
|
448
|
+
const queuedAt = deps.now();
|
|
449
|
+
const folder = folderProject(cwd);
|
|
450
|
+
const command = cmdString(cmd);
|
|
451
|
+
const project = jobProject({ label, project: folder, cwd });
|
|
452
|
+
const before = deps.gitState(cwd);
|
|
453
|
+
const print = fingerprint(cwd, cmd, settings.outputDirs);
|
|
454
|
+
const request = { label, command, kind: parsed.kind, maxRun, priority, afterFix, project, cwd, queuedAt, tz };
|
|
455
|
+
// The journal is read and parsed once for the whole plan.
|
|
456
|
+
const rows = parseLines(readLines(files.journal));
|
|
457
|
+
const plan = planJob({ ...request, head: before.head, fingerprint: print }, settings, rows);
|
|
458
|
+
const pid = process.pid;
|
|
459
|
+
const markers = deps.env?.[PARENT_MARKER] || deps.env?.[JOB_MARKER];
|
|
460
|
+
const outer = markers ? parentJob({ env: deps.env, pid, ...snapshot({ dirs: files }) }) : null;
|
|
461
|
+
const details = outer ? { ...plan.details, nested: true } : plan.details;
|
|
462
|
+
const journal = journalWriter({
|
|
463
|
+
label, folder, cwd, priority, queuedAt, command, details, file: files.journal, now: deps.now, pid,
|
|
464
|
+
});
|
|
465
|
+
if (plan.refusal) {
|
|
466
|
+
journal.note({ commit: before });
|
|
467
|
+
journal.finish("refused", EXIT.refused);
|
|
468
|
+
say(`refused: exit ${EXIT.refused}; ${plan.refusal.reason}`);
|
|
469
|
+
return EXIT.refused;
|
|
470
|
+
}
|
|
471
|
+
// --no-skip on the outer job reaches every run nested in it.
|
|
472
|
+
const noSkip = parsed.noSkip || (!!outer && deps.env?.[NO_SKIP_MARKER] === "1");
|
|
473
|
+
const check = { kind: plan.kind, kindGiven: parsed.kind !== undefined, label, command };
|
|
474
|
+
const where = { cwd, fingerprint: print, folderProject: folder, commit: before };
|
|
475
|
+
const stamp = skipFor({ ...check, ...where, noSkip, at: queuedAt, tz }, rows);
|
|
476
|
+
if (stamp) {
|
|
477
|
+
const ago = Math.max(0, Math.round((deps.now() - Date.parse(stamp.endedAt)) / MINUTE));
|
|
478
|
+
journal.note({ commit: before });
|
|
479
|
+
// The stamp is kept with the line, so history can tell how much run time the skip saved.
|
|
480
|
+
journal.finish("skipped", 0, { stamp: { head: stamp.head, endedAt: stamp.endedAt, runMin: stamp.runMin } });
|
|
481
|
+
say(`skipped: "${label}" already passed on commit ${String(stamp.head).slice(0, 8)} (${ago} min ago); `
|
|
482
|
+
+ "--no-skip runs it anyway");
|
|
483
|
+
return 0;
|
|
484
|
+
}
|
|
485
|
+
if (plan.afterFixUsed) {
|
|
486
|
+
say(`--after-fix accepted: note "${afterFix}", the check had failed twice on unchanged code`);
|
|
487
|
+
}
|
|
488
|
+
const { limit, kind } = plan;
|
|
489
|
+
// INT and TERM wake the wait, which then returns, so the one exit path in main() ends the process. The leave
|
|
490
|
+
// handlers stay until runJob has added its own: with no listener at all, a signal would end the process at once,
|
|
491
|
+
// with no journal line and the slot, place or note left behind. A signal that arrives while the job is being
|
|
492
|
+
// started reaches the handlers of the job and is passed on to it.
|
|
493
|
+
const watch = watchLeave(signals, deps.sleep);
|
|
494
|
+
const job = {
|
|
495
|
+
pid, label, project, cwd, cmd, priority, kind, limit, settings, files, tz, journal, maxWait, handOver: watch.drop,
|
|
496
|
+
// Nothing nested in a job that could not be skipped itself, such as a build, is ever skipped: the job may
|
|
497
|
+
// need what its steps make.
|
|
498
|
+
noSkip: noSkip || !canSkip(check),
|
|
499
|
+
};
|
|
500
|
+
const waitDeps = { ...deps, sleep: watch.sleep, leaving: watch.leaving };
|
|
501
|
+
try {
|
|
502
|
+
if (!outer) return await runInLine(job, waitDeps, deps);
|
|
503
|
+
const nested = await runNested({ ...job, outer }, waitDeps, deps);
|
|
504
|
+
if (!nested.parentGone) return nested.exit;
|
|
505
|
+
say(`parent gone: "${outer.label}", pid ${outer.pid}, ended while this run waited for a nested place; `
|
|
506
|
+
+ "joins the line as a normal run");
|
|
507
|
+
journal.note({ details: plan.details });
|
|
508
|
+
return await runInLine({ ...job, waitFrom: nested.waitFrom, tally: nested.tally }, waitDeps, deps);
|
|
509
|
+
} finally {
|
|
510
|
+
watch.drop();
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/** Watches INT and TERM while a run waits: the first one is kept, and each wakes the wait. Returns { leaving, sleep,
|
|
515
|
+
* drop }: leaving() names that signal or gives null, sleep is deps.sleep made wakeable, and drop() removes the
|
|
516
|
+
* handlers; calling it again does nothing. */
|
|
517
|
+
function watchLeave(signals, sleep) {
|
|
518
|
+
let leaving = null;
|
|
519
|
+
let dropped = false;
|
|
520
|
+
const sleeps = wakeableSleep(sleep);
|
|
521
|
+
const leavers = LEAVE_SIGNALS.map((signal) => [signal, () => {
|
|
522
|
+
leaving ??= signal;
|
|
523
|
+
sleeps.wake();
|
|
524
|
+
}]);
|
|
525
|
+
for (const [signal, handler] of leavers) signals.on(signal, handler);
|
|
526
|
+
const drop = () => {
|
|
527
|
+
if (dropped) return;
|
|
528
|
+
dropped = true;
|
|
529
|
+
for (const [signal, handler] of leavers) signals.off(signal, handler);
|
|
530
|
+
};
|
|
531
|
+
return { leaving: () => leaving, sleep: sleeps.sleep, drop };
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/** Journals a wait that ended without a slot or place, and gives its exit code: 130 for a signal, 75 for the wait
|
|
535
|
+
* limit. Gives null when the wait ended with a slot or place and no signal is pending. */
|
|
536
|
+
function endOfWait(waited, journal, leaving) {
|
|
537
|
+
journal.note({ tally: waited.tally });
|
|
538
|
+
if (waited.left || leaving) {
|
|
539
|
+
journal.finish("left", EXIT.left, { signal: waited.left ?? leaving });
|
|
540
|
+
return EXIT.left;
|
|
541
|
+
}
|
|
542
|
+
if (waited.gaveUp) {
|
|
543
|
+
journal.finish("gave-up", EXIT.gaveUp);
|
|
544
|
+
return EXIT.gaveUp;
|
|
545
|
+
}
|
|
546
|
+
return null;
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** Runs a job that waits in line for a slot. job is the one runJob takes, with maxWait, and with waitFrom and tally
|
|
550
|
+
* only when it carries on an earlier wait. waitDeps are deps with the wakeable sleep and leaving() of runCommand. */
|
|
551
|
+
async function runInLine(job, waitDeps, deps) {
|
|
552
|
+
const { pid, label, priority, kind, limit, project, cwd, settings, files, journal, maxWait } = job;
|
|
553
|
+
const { signals } = deps;
|
|
554
|
+
const ticket = enqueue(pid, label, priority, files);
|
|
555
|
+
let slot = null;
|
|
556
|
+
const leaveLine = () => {
|
|
557
|
+
rmSync(ticket, { force: true });
|
|
558
|
+
releaseSlot(slot, pid);
|
|
559
|
+
};
|
|
560
|
+
signals.on("exit", leaveLine);
|
|
561
|
+
const slotMeta = {
|
|
562
|
+
kind, limitMin: limit.limitMin, killMin: limit.killMin, longRunMin: limit.longRunMin, project, cwd,
|
|
563
|
+
...(priority ? { priority: true } : {}),
|
|
564
|
+
};
|
|
565
|
+
try {
|
|
566
|
+
const { waitFrom, tally } = job;
|
|
567
|
+
const waited = await waitForSlot({ pid, label, maxWait, slotMeta, settings, files, waitFrom, tally }, waitDeps);
|
|
568
|
+
slot = waited.slot ?? null;
|
|
569
|
+
const ended = endOfWait(waited, journal, waitDeps.leaving());
|
|
570
|
+
if (ended !== null) return ended;
|
|
571
|
+
rmSync(ticket, { force: true });
|
|
572
|
+
return await runJob({ ...job, waitFrom: waited.waitFrom }, slot, deps);
|
|
573
|
+
} finally {
|
|
574
|
+
leaveLine();
|
|
575
|
+
signals.off("exit", leaveLine);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/** Runs a nested job: in no slot, but in one of the places under its parent job, the one in outer, waiting for one
|
|
580
|
+
* when all are taken. It is noted in the nested folder from the start, so `status` can show it under its parent, and
|
|
581
|
+
* the note is the marker its own job is handed. job is the one runJob takes, without waitFrom, and with outer and
|
|
582
|
+
* maxWait; waitDeps are as for runInLine. While it waits, INT and TERM take it out as they take a job out of the
|
|
583
|
+
* line; from the handlers runJob adds onwards everything is the same as for a job in a slot. Resolves with { exit },
|
|
584
|
+
* or with { parentGone: true, tally, waitFrom } when the parent ended while the run waited; its note is removed
|
|
585
|
+
* then, and the caller sends it to the line. */
|
|
586
|
+
async function runNested(job, waitDeps, deps) {
|
|
587
|
+
const { pid, label, outer, files, journal, maxWait, settings } = job;
|
|
588
|
+
const { signals, say } = deps;
|
|
589
|
+
const intro = `nested: inside "${outer.label}", pid ${outer.pid}`;
|
|
590
|
+
const parent = { marker: markerOf(outer.file), pid: outer.pid, born: outer.born, slot: slotMarkerOf(outer) };
|
|
591
|
+
const note = addNested(pid, label, parent, files, { waiting: true });
|
|
592
|
+
let place = null;
|
|
593
|
+
const leave = () => {
|
|
594
|
+
rmSync(note, { force: true });
|
|
595
|
+
releaseSlot(place, pid);
|
|
596
|
+
};
|
|
597
|
+
signals.on("exit", leave);
|
|
598
|
+
try {
|
|
599
|
+
const waited = await waitForPlace({ pid, label, parent: outer, maxWait, settings, files }, waitDeps);
|
|
600
|
+
place = waited.place ?? null;
|
|
601
|
+
if (waited.parentGone && !waitDeps.leaving()) return waited;
|
|
602
|
+
const ended = endOfWait(waited, journal, waitDeps.leaving());
|
|
603
|
+
if (ended !== null) return { exit: ended };
|
|
604
|
+
say(waited.atOnce ? `${intro}; starts at once: no slot, no place in line, no health gate`
|
|
605
|
+
: `${intro}; starts now that a nested place is free: no slot, no place in line, no health gate`);
|
|
606
|
+
updateSlot(note, pid, { waiting: undefined });
|
|
607
|
+
return { exit: await runJob({ ...job, waitFrom: waited.waitFrom, slotMarker: parent.slot }, note, deps) };
|
|
608
|
+
} finally {
|
|
609
|
+
leave();
|
|
610
|
+
signals.off("exit", leave);
|
|
611
|
+
}
|
|
612
|
+
}
|