@dibssoftware/dibs 0.0.0-stage → 0.0.178
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/CHANGELOG.md +577 -0
- package/LICENSE +670 -0
- package/README.md +234 -2
- package/bin/dibs-guard.mjs +7 -0
- package/bin/dibs.mjs +526 -0
- package/docs/benchmarks.md +193 -0
- package/docs/files.md +30 -0
- package/docs/guard.md +91 -0
- package/docs/later.md +43 -0
- package/docs/machines.md +147 -0
- package/docs/questions.md +78 -0
- package/docs/relay.md +196 -0
- package/docs/releasing.md +25 -0
- package/docs/scheduling.md +163 -0
- package/docs/simulators.md +17 -0
- package/package.json +44 -4
- package/skills/dibs/SKILL.md +162 -0
- package/src/acquire.mjs +697 -0
- package/src/admin.mjs +145 -0
- package/src/agents.mjs +145 -0
- package/src/alerts.mjs +437 -0
- package/src/answers.mjs +65 -0
- package/src/board.mjs +202 -0
- package/src/broker.mjs +369 -0
- package/src/commands.mjs +801 -0
- package/src/config.mjs +320 -0
- package/src/connect.mjs +106 -0
- package/src/cool.mjs +160 -0
- package/src/diskwarn.mjs +161 -0
- package/src/events.mjs +94 -0
- package/src/files.mjs +1100 -0
- package/src/guard.mjs +583 -0
- package/src/history.mjs +247 -0
- package/src/hogs.mjs +214 -0
- package/src/later.mjs +487 -0
- package/src/measure.mjs +262 -0
- package/src/nodecheck.mjs +17 -0
- package/src/notices.mjs +121 -0
- package/src/ondemand.mjs +572 -0
- package/src/overlap.mjs +151 -0
- package/src/override.mjs +351 -0
- package/src/owner.mjs +30 -0
- package/src/plain.mjs +467 -0
- package/src/platform.mjs +357 -0
- package/src/preempt.mjs +438 -0
- package/src/primer.mjs +61 -0
- package/src/proc.mjs +98 -0
- package/src/progress.mjs +158 -0
- package/src/qr.mjs +204 -0
- package/src/questions.mjs +389 -0
- package/src/quota.mjs +81 -0
- package/src/reads.mjs +54 -0
- package/src/relay.mjs +779 -0
- package/src/remote.mjs +584 -0
- package/src/reset.mjs +127 -0
- package/src/schedule.mjs +995 -0
- package/src/scratch.mjs +61 -0
- package/src/serve.mjs +736 -0
- package/src/service.mjs +221 -0
- package/src/shard.mjs +59 -0
- package/src/simctl.mjs +42 -0
- package/src/simpool.mjs +258 -0
- package/src/state.mjs +201 -0
- package/src/stats.mjs +328 -0
- package/src/style.mjs +44 -0
- package/src/talk.mjs +523 -0
- package/src/thin.sh +130 -0
- package/src/trust.mjs +152 -0
- package/src/util.mjs +184 -0
- package/src/version.mjs +2 -0
- package/src/web.mjs +1117 -0
- package/src/worker.mjs +318 -0
package/src/board.mjs
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
// The board: who holds what and who waits, on this machine and, when it's
|
|
2
|
+
// joined to a coordinator, on every other machine too.
|
|
3
|
+
import { resCfg } from './config.mjs';
|
|
4
|
+
import { tag, isMine } from './proc.mjs';
|
|
5
|
+
import { idleFor } from './acquire.mjs';
|
|
6
|
+
import { forecast, byRank, remaining, used, overBy, verdict, memUsed, cpuUsed, shownFree, swapGrowing, diskSqueeze, BREAKER_LINE } from './schedule.mjs';
|
|
7
|
+
import { grewLine, cappedLine } from './measure.mjs';
|
|
8
|
+
import { pauseLabel } from './preempt.mjs';
|
|
9
|
+
import { alongsideLabel } from './overlap.mjs';
|
|
10
|
+
import { ownerLabel } from './override.mjs';
|
|
11
|
+
import { quotasNow, quotaBlock } from './quota.mjs';
|
|
12
|
+
import { agentsNow } from './agents.mjs';
|
|
13
|
+
import { remoteConf, call } from './remote.mjs';
|
|
14
|
+
import { bytes, dur, gb, clock, now, holder, when } from './util.mjs';
|
|
15
|
+
import { short, isFiles, sameAgent } from './files.mjs';
|
|
16
|
+
import { named, about, minutes, usingText, nextText, stuckFor, heldByLoad } from './plain.mjs';
|
|
17
|
+
|
|
18
|
+
// Why a waiter isn't running, short enough for its board row: the rule and
|
|
19
|
+
// what it's stuck on (a file lease's path, a bucket's name). Disk says the
|
|
20
|
+
// numbers, since a disk wait is the one an agent can do something about.
|
|
21
|
+
// `dibs --json` carries it as is ("slot: xcode-build", "behind web-app").
|
|
22
|
+
export const waitReason = v => (v.ok ? null : v.rule === 'ahead' && v.ahead ? `behind ${tag(v.ahead)}`
|
|
23
|
+
: v.rule === 'load' && v.since != null ? heldByLoad(v)
|
|
24
|
+
: v.rule === 'disk' ? v.why.replace('you need', 'needs')
|
|
25
|
+
: `${v.rule}${v.on ? `: ${short(v.on).replace(/^(files|quota):/, '')}` : ''}`);
|
|
26
|
+
const blockedBy = v => { const r = waitReason(v); return r && !/^(behind|held by) /.test(r) ? `blocked by ${r}` : r; };
|
|
27
|
+
|
|
28
|
+
// What holds a waiter back, as its own dibs decides (acquire.mjs decide: the
|
|
29
|
+
// line and the machine, then a shared rate limit), or, when nothing does, that
|
|
30
|
+
// nobody has decided for it lately. On 2026-10-20 two test runs showed no
|
|
31
|
+
// reason at all and didn't start, with free slots and memory.
|
|
32
|
+
const UNPOLLED = 3 * 6e4; // a waiter's dibs decides every few seconds, and notes it once a minute (acquire.mjs POLLED_EVERY)
|
|
33
|
+
function waitingOn(s, q, cfg, hist, t) {
|
|
34
|
+
const v = verdict(s, q, cfg, hist, t);
|
|
35
|
+
if (!v.ok) return blockedBy(v);
|
|
36
|
+
const quota = quotaBlock(s, q, cfg, hist, t);
|
|
37
|
+
if (quota) return blockedBy(quota);
|
|
38
|
+
return q.polledAt && t - q.polledAt > UNPOLLED ? `ready, but its dibs hasn't looked in ${dur(t - q.polledAt)}` : null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const ASK_FOR = 1500; // plain `dibs` never waits longer than this for other machines
|
|
42
|
+
const STALE = 20e3; // a board older than this says how old it is
|
|
43
|
+
|
|
44
|
+
// What the board shows, in a form other machines can read: no pids, no
|
|
45
|
+
// environment, and times as durations so two clocks needn't agree. With `me`,
|
|
46
|
+
// rows that are the caller's are marked, and carry the ids the owner's
|
|
47
|
+
// commands take (dibs boost, pause, stop), which mean nothing elsewhere.
|
|
48
|
+
export function boardOf(s, cfg, hist, t = now(), me = null) {
|
|
49
|
+
const fc = forecast(s, cfg, hist, t);
|
|
50
|
+
// A sibling subagent's row is its session's, not the caller's own.
|
|
51
|
+
const you = x => ({ ...(me && isMine(x, me) ? sameAgent(x, me) ? { you: true } : { yourSession: true } : {}), ...(me ? { id: x.id } : {}) });
|
|
52
|
+
return {
|
|
53
|
+
// The same numbers the scheduler decides by (schedule.mjs memUsed), so the board and the wait lines agree.
|
|
54
|
+
memUsed: memUsed(s), memBudget: bytes(cfg.budget), cpuUsed: cpuUsed(s), cores: cfg.cores,
|
|
55
|
+
held: [...s.leases].sort((a, b) => a.start - b.start).map(l => ({
|
|
56
|
+
res: l.res.map(r => short(r)), who: l.who, label: l.label, agentId: l.agentId, for: t - l.start, left: remaining(l, hist, t), idle: idleFor(l, t),
|
|
57
|
+
stuck: s.queue.some(q => q.pid) && stuckFor(l, t) > 0,
|
|
58
|
+
prio: l.prio, paused: pauseLabel(l) || null, alongside: alongsideLabel(l) || (l.breaker ? BREAKER_LINE : null), owner: ownerLabel(l) || null, purpose: l.purpose, cmd: l.cmd ? l.cmd.slice(0, 40) : null,
|
|
59
|
+
mem: l.mem, use: l.use?.mem ?? null, over: overBy(l) > 0, grew: grewLine(l) || null, ...you(l) })),
|
|
60
|
+
waiting: [...s.queue].sort(byRank(hist, t)).map(q => ({
|
|
61
|
+
res: q.res.map(r => short(r)), who: q.who, label: q.label, agentId: q.agentId, waited: t - q.enq, in: fc.has(q.id) ? fc.get(q.id) - t : null,
|
|
62
|
+
prio: q.prio, owner: ownerLabel(q) || null, due: q.by ? q.by - t : null, yielded: q.yieldRank != null, kept: !q.pid, holds: q.holding?.res.map(r => short(r)) || null,
|
|
63
|
+
blocked: q.pid ? waitingOn(s, q, cfg, hist, t) : null, capped: cappedLine(q) || null,
|
|
64
|
+
purpose: q.purpose, ...you(q) })),
|
|
65
|
+
free: Object.keys(cfg.resources).map(r => {
|
|
66
|
+
// A per-project resource is free for other projects up to its cap across them (src/schedule.mjs roomFor).
|
|
67
|
+
const c = resCfg(cfg, r), slots = c.exclusiveBy === 'repo' ? c.across ?? c.slots : c.slots;
|
|
68
|
+
const left = slots - used(s, r);
|
|
69
|
+
return left > 0 ? `${r}${slots > 1 ? `(${left})` : ''}` : null;
|
|
70
|
+
}).filter(Boolean),
|
|
71
|
+
quotas: quotasNow(s, cfg, t),
|
|
72
|
+
agents: agentsNow(cfg),
|
|
73
|
+
caps: s.caps || {},
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// The limits dibs starts work by and how much room each has left, in one
|
|
78
|
+
// line, so agents stop checking memory, disk and swap by hand.
|
|
79
|
+
const GB = b => gb(b).replace(/G$/, ' GB');
|
|
80
|
+
export function limitsLine(s, cfg, m) {
|
|
81
|
+
const budget = bytes(cfg.budget), out = memUsed(s), free = shownFree(m);
|
|
82
|
+
const mem = `memory ${GB(out)} of ${GB(budget)} taken (${out >= budget ? 'none' : GB(budget - out)} left)${free != null ? `, ${GB(free)} free or reclaimable on the machine` : ''}${m.vmPressure >= 1 ? ', pressure high' : ''}`;
|
|
83
|
+
const floor = bytes(cfg.minDisk), sq = diskSqueeze(cfg, floor, m);
|
|
84
|
+
const disk = m.diskFree == null ? 'disk unknown' : `disk ${GB(m.diskFree)} free (floor ${GB(sq?.rule === 'swaproom' ? sq.need : floor)}${sq?.rule === 'drain' ? `, falling ${GB(sq.fell)} in 5 min` : ''})`;
|
|
85
|
+
const over = cfg.maxSwap != null && m.swapUsed > bytes(cfg.maxSwap);
|
|
86
|
+
const swap = m.swapUsed == null ? '' : `swap ${GB(m.swapUsed)}${swapGrowing(m) ? `, growing (${GB(m.swapGrowth)} in 5 min)` : ', steady'}${over ? `, over maxSwap ${GB(bytes(cfg.maxSwap))}` : ''}`;
|
|
87
|
+
return [mem, disk, swap].filter(Boolean).join('; ');
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export const handedOut = b => `handed out: memory ${gb(b.memUsed)}/${gb(b.memBudget)}, CPU ${b.cpuUsed}/${b.cores} cores in use`;
|
|
91
|
+
|
|
92
|
+
// HELD, WAITING and free. `age` is how old the board is, so durations read as of now.
|
|
93
|
+
export function boardLines(b, t = now(), age = 0, yours = x => x.you) {
|
|
94
|
+
const out = [];
|
|
95
|
+
const you = x => `${x.id != null ? ` #${x.id}` : ''}${yours(x) ? ' <- you' : x.yourSession ? ' <- your session' : ''}`;
|
|
96
|
+
if (b.held.length) {
|
|
97
|
+
out.push('', 'HELD');
|
|
98
|
+
for (const l of b.held)
|
|
99
|
+
out.push(` ${l.res.join(',').padEnd(14)} ${holder(l, tag).padEnd(28)} ${dur(l.for + age).padStart(7)}`
|
|
100
|
+
+ `${l.left != null ? ` ~${dur(l.left - age)} left` : ''}${l.prio && l.prio !== 'normal' ? ` [${l.prio}]` : ''}${l.owner ? ` [${l.owner}]` : ''}${l.idle ? ` [idle ${dur(l.idle + age)}${l.stuck ? ', may be stuck' : ''}]` : ''}${l.paused ? ` [${l.paused}]` : ''}${l.alongside ? ` [${l.alongside}]` : ''}`
|
|
101
|
+
+ `${l.over ? ` [over: using ${gb(l.use)} of ${gb(l.mem)}]` : l.grew ? ` [${l.grew}]` : ''}`
|
|
102
|
+
+ `${l.purpose ? ` "${l.purpose}"` : ''}${l.cmd ? ` ${l.cmd}` : ' (hold)'}${you(l)}`);
|
|
103
|
+
}
|
|
104
|
+
if (b.waiting.length) {
|
|
105
|
+
out.push('', "QUEUE (in the order they'll go)");
|
|
106
|
+
b.waiting.forEach((q, i) => {
|
|
107
|
+
const flags = [q.prio && q.prio !== 'normal' ? q.prio : '', q.owner || '', q.holds ? `holds ${q.holds.join(',')}, goes first` : '', q.blocked || '', q.capped || '', q.due != null ? `due ${clock(t - age + q.due)}` : '',
|
|
108
|
+
q.yielded ? 'let ahead' : '', q.kept ? 'place kept' : ''].filter(Boolean).join(', ');
|
|
109
|
+
out.push(` ${String(i + 1).padStart(2)} ${q.res.join(',').padEnd(11)} ${holder(q, tag).padEnd(28)} waited ${dur(q.waited + age).padStart(6)}`
|
|
110
|
+
+ `${q.in != null ? ` starts ~${clock(t - age + q.in)}` : ''}${flags ? ` [${flags}]` : ''}${q.purpose ? ` "${q.purpose}"` : ''}${you(q)}`);
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
// An id typed from here can be someone else's: acting on it takes the owner by name (src/override.mjs).
|
|
114
|
+
if ([...b.held, ...b.waiting].some(x => x.id != null && !yours(x)))
|
|
115
|
+
out.push('', "Acting on a job that isn't yours (dibs boost, pause, resume, stop <id>): add --owner <the name before its #>.");
|
|
116
|
+
out.push('', `free: ${b.free.join(' ') || 'nothing'}`);
|
|
117
|
+
const caps = Object.entries(b.caps || {});
|
|
118
|
+
if (caps.length) out.push(`capped: ${caps.map(([who, c]) => `${who} at ${c.prio}${c.by ? ` (by ${c.by})` : ''}`).join(', ')}`);
|
|
119
|
+
if (b.quotas?.length)
|
|
120
|
+
out.push(`quotas: ${b.quotas.map(q => (q.error ? `${q.name} (${q.error})` : `${q.name} ${q.left}/${q.limit} per ${dur(q.per)}`)).join(' ')}`);
|
|
121
|
+
if (b.agents?.running.length) {
|
|
122
|
+
const n = new Map();
|
|
123
|
+
for (const a of b.agents.running) n.set(a.who, (n.get(a.who) || 0) + 1);
|
|
124
|
+
out.push(`subagents: ${b.agents.running.length} of ${b.agents.slots} running (${[...n].map(([who, k]) => `${who} x${k}`).join(', ')})`);
|
|
125
|
+
}
|
|
126
|
+
return out;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// Every machine's board from the coordinator, or { error } within ASK_FOR.
|
|
130
|
+
export async function elsewhere(rc = remoteConf()) {
|
|
131
|
+
if (!rc) return null;
|
|
132
|
+
try { return await call(rc, 'GET', '/board', undefined, { timeout: ASK_FOR }); }
|
|
133
|
+
catch (e) {
|
|
134
|
+
const why = e.name === 'TimeoutError' || e.name === 'AbortError' ? `no answer in ${ASK_FOR / 1000}s` : e.status ? e.message : e.cause?.code || e.message;
|
|
135
|
+
return { error: why };
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Another machine's busy lines in sentences, from its board rows. Built here
|
|
140
|
+
// rather than sent, so a limited machine's view hides the same purposes and
|
|
141
|
+
// paths its board rows do (src/serve.mjs bare).
|
|
142
|
+
function remoteSentences(b, cfg, age) {
|
|
143
|
+
const live = b.waiting.filter(q => !q.kept);
|
|
144
|
+
const res = [...new Set([...b.held.flatMap(l => l.res), ...live.flatMap(q => q.res)])];
|
|
145
|
+
return res.map(r => {
|
|
146
|
+
// A hold's row has no command (null). A limited view blanks a run's command to '', so it still reads as a run.
|
|
147
|
+
const held = b.held.filter(l => l.res.includes(r)).map(l => {
|
|
148
|
+
const hold = l.cmd == null, left = l.left == null ? null : Math.max(l.left - age, 0);
|
|
149
|
+
return { who: l.who, hold, endsIn: left, endsText: left == null ? 'time left unknown' : hold ? `up to ${minutes(left)} left` : `${about(left)} left` };
|
|
150
|
+
});
|
|
151
|
+
const next = live.filter(q => q.res.includes(r)).map(q => q.who);
|
|
152
|
+
return `${named(cfg, r).label}: ${held.length ? usingText(held, named(cfg, r)) : 'free'}${next.length ? `. ${nextText(next)}` : ''}.`;
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// The other machines in sentences, for plain `dibs`.
|
|
157
|
+
export function elsewherePlain(r, rc, cfg) {
|
|
158
|
+
if (r.error) return [`Other machines: can't reach the coordinator at ${rc.url} (${r.error}).`];
|
|
159
|
+
const out = [];
|
|
160
|
+
for (const m of r.machines.filter(x => x.name !== rc.name).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
161
|
+
if (m.ondemand?.problem) out.push(`${m.name} is an on-demand VM dibs can't use: ${m.ondemand.problem}.`);
|
|
162
|
+
else if (m.ondemand?.temp && m.ondemand.state === 'asleep') out.push(`${m.name} is made when a job is too big for ${m.ondemand.temp.of}, and deleted after.`);
|
|
163
|
+
// Same words as `dibs machines`: on 2026-10-22 boat's compute ran out and the board still said a job would wake it.
|
|
164
|
+
else if (m.ondemand?.cantWake && m.ondemand.state === 'asleep') out.push(`${m.name} is an on-demand VM that can't wake: ${m.ondemand.cantWake.why}. Jobs stay here; dibs checks again ${when(m.ondemand.cantWake.until)}.`);
|
|
165
|
+
else if (m.ondemand && m.ondemand.state !== 'running') out.push(`${m.name} is an on-demand VM, ${m.ondemand.state}${m.ondemand.state === 'asleep' ? ': a job sent there wakes it' : ''}.`);
|
|
166
|
+
else if (m.lost) out.push(`${m.name} hasn't reported in ${minutes(m.age)}.`);
|
|
167
|
+
else if (!m.board) out.push(`${m.name} runs an older dibs (${m.version}) that doesn't share what it's running.`);
|
|
168
|
+
else {
|
|
169
|
+
const busy = remoteSentences(m.board, cfg, m.age);
|
|
170
|
+
out.push(busy.length ? `On ${m.name}:` : `${m.name} has nothing running.`, ...busy.map(x => ` ${x}`));
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
const moving = (r.jobs || []).filter(j => j.state !== 'done').length;
|
|
174
|
+
if (moving) out.push(`${moving} job${moving > 1 ? 's' : ''} moving between machines. More: dibs --detail`);
|
|
175
|
+
return out;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// The other machines' sections, then the jobs moving between machines.
|
|
179
|
+
export function elsewhereLines(r, rc, me, t = now()) {
|
|
180
|
+
if (r.error) return [`other machines: can't reach the coordinator at ${rc.url} (${r.error})`];
|
|
181
|
+
const out = [];
|
|
182
|
+
// A job sent from here shows on the other machine as you@thismachine.
|
|
183
|
+
const sentByMe = x => x.who === `${me.agent || me.who}@${rc.name}`;
|
|
184
|
+
for (const m of r.machines.filter(x => x.name !== rc.name).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
185
|
+
out.push('');
|
|
186
|
+
if (m.ondemand && m.ondemand.state !== 'running') { out.push(`${m.name} ${m.ondemand.temp ? 'temporary' : 'on-demand'} VM, ${m.ondemand.temp && m.ondemand.state === 'asleep' ? 'none made' : m.ondemand.state}`); continue; }
|
|
187
|
+
if (m.lost) { out.push(`${m.name} not reporting, last heard ${dur(m.age)} ago`); continue; }
|
|
188
|
+
if (!m.board) { out.push(`${m.name} runs dibs ${m.version}, which doesn't send its board`); continue; }
|
|
189
|
+
out.push(`${m.name} ${handedOut(m.board)} machine: ${m.memFree}% memory free${m.diskFree != null ? `, disk ${gb(m.diskFree)} free` : ''}, load ${m.load.toFixed(1)}`
|
|
190
|
+
+ `${m.age > STALE ? ` (as of ${dur(m.age)} ago)` : ''}`);
|
|
191
|
+
out.push(...boardLines(m.board, t, m.age, sentByMe));
|
|
192
|
+
}
|
|
193
|
+
const jobs = (r.jobs || []).filter(j => j.state !== 'done');
|
|
194
|
+
if (jobs.length) {
|
|
195
|
+
out.push('', 'SENT BETWEEN MACHINES');
|
|
196
|
+
for (const j of jobs)
|
|
197
|
+
out.push(` ${j.res.join(',').padEnd(14)} ${(j.agent || j.who).padEnd(20)} ${`${j.from} -> ${j.machine}`.padEnd(24)} ${j.state.padEnd(9)} ${dur(r.now - j.created).padStart(6)}`
|
|
198
|
+
+ `${j.purpose ? ` "${j.purpose}"` : ''} ${j.cmd.join(' ').slice(0, 40)}`);
|
|
199
|
+
}
|
|
200
|
+
if (out.length) out.push('');
|
|
201
|
+
return out;
|
|
202
|
+
}
|
package/src/broker.mjs
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
// The broker: one Node process that waits for every thin waiter on this
|
|
2
|
+
// machine (src/thin.sh), instead of one Node per waiter. Each tick it takes
|
|
3
|
+
// the state lock once and runs, for each waiter in rank order, the same step
|
|
4
|
+
// acquire()'s loop runs for itself, then writes to the waiters' FIFOs: lines
|
|
5
|
+
// to print, "go", or "exit N". It keeps nothing that isn't in state.json, so
|
|
6
|
+
// killing it loses no place: the next waiter to notice starts another. It
|
|
7
|
+
// starts when someone has to wait, and exits after a quiet minute or when a
|
|
8
|
+
// release changes its code on disk. Nothing is installed; no daemon.
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import net from 'node:net';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
13
|
+
import { fileURLToPath } from 'node:url';
|
|
14
|
+
import { HOME, paths, loadConfig } from './config.mjs';
|
|
15
|
+
import { pstart, makeAlive } from './proc.mjs';
|
|
16
|
+
import { processes } from './platform.mjs';
|
|
17
|
+
import { withState, history, kick, quiet, KEEP_PLACE } from './state.mjs';
|
|
18
|
+
import { decide, step, waiter, full, markIdle, saidText, abandon, POLL } from './acquire.mjs';
|
|
19
|
+
import { byRank } from './schedule.mjs';
|
|
20
|
+
import { noticeScan } from './notices.mjs';
|
|
21
|
+
import { event } from './events.mjs';
|
|
22
|
+
import { now, noSpace, sleepSync, signalExit, notifyLine, LEAN } from './util.mjs';
|
|
23
|
+
|
|
24
|
+
const SRC = path.dirname(fileURLToPath(import.meta.url));
|
|
25
|
+
const BIN = path.join(SRC, '..', 'bin', 'dibs.mjs');
|
|
26
|
+
export const PIDFILE = path.join(HOME, 'broker.pid');
|
|
27
|
+
const STARTING = path.join(HOME, 'broker.lock');
|
|
28
|
+
const WAKE = path.join(HOME, 'w');
|
|
29
|
+
// With no thin waiter for this long, the broker exits: nothing runs while
|
|
30
|
+
// nobody waits. DIBS_BROKER_IDLE lets a test see it go.
|
|
31
|
+
const IDLE_EXIT = Number(process.env.DIBS_BROKER_IDLE) || 6e4;
|
|
32
|
+
// How often the broker stamps state.broker.beat. Not every tick: an unchanged
|
|
33
|
+
// state file isn't rewritten, and older waiters poll less while it's unchanged.
|
|
34
|
+
const BEAT = 10e3;
|
|
35
|
+
// A beat older than this is a broker that's alive but stuck: the next waiter replaces it.
|
|
36
|
+
const HUNG = 30e3;
|
|
37
|
+
// How long a waiter gives the broker it started to open the control FIFO. A
|
|
38
|
+
// Node start under memory pressure has taken seconds. A broker that dies
|
|
39
|
+
// before then is noticed within CRASH_CHECK. One still starting after it is
|
|
40
|
+
// slow, not broken: the waiter waits in Node and the broker takes over once up.
|
|
41
|
+
// DIBS_BROKER_START_WAIT (ms) lets a test see a slow start.
|
|
42
|
+
const START_WAIT = Number(process.env.DIBS_BROKER_START_WAIT) || 10e3;
|
|
43
|
+
const CRASH_CHECK = 500;
|
|
44
|
+
// A broker that couldn't be started marks it here. For BROKEN_FOR after, thin
|
|
45
|
+
// waiters don't try again: they wait in Node at once (src/thin.sh checks it too).
|
|
46
|
+
export const BROKEN = path.join(HOME, 'broker.broken');
|
|
47
|
+
const BROKEN_FOR = 6e4;
|
|
48
|
+
// Between kicks, a tick whose state file hasn't changed since the last one
|
|
49
|
+
// is skipped until this much time has passed: deciding for 50 waiters costs
|
|
50
|
+
// a few hundred ms of CPU, and with nothing new only the machine's readings
|
|
51
|
+
// (memory, swap, disk) or a wait limit can change the answer.
|
|
52
|
+
const QUIET_POLL = 5e3;
|
|
53
|
+
// FIFOs of shells that are gone are cleared this often.
|
|
54
|
+
const PRUNE_EVERY = 6e4;
|
|
55
|
+
const { O_WRONLY, O_RDWR, O_NONBLOCK } = fs.constants;
|
|
56
|
+
|
|
57
|
+
// A line to a thin waiter's FIFO: _enqueue's answer, which the shell reads
|
|
58
|
+
// before any broker writes. The shell holds the FIFO open, so this never blocks.
|
|
59
|
+
function reply(fifo, line) {
|
|
60
|
+
const fd = fs.openSync(fifo, O_WRONLY | O_NONBLOCK);
|
|
61
|
+
try { fs.writeSync(fd, `${line}\n`); } finally { fs.closeSync(fd); }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// _enqueue: getting a thin waiter in line, as dibs run or hold does, with
|
|
65
|
+
// its shell's pid in the entry. Each way out answers the shell: go (its turn
|
|
66
|
+
// now), wait (the broker has it), fat (wait in-process: a case thin waits
|
|
67
|
+
// don't cover), or exit 0 (nothing to wait for). Any other exit code is the
|
|
68
|
+
// shell's to pass on.
|
|
69
|
+
export function thinCall(shell, fifo) {
|
|
70
|
+
if (shell === process.pid) return inlineCall(shell, fifo);
|
|
71
|
+
let replied = false;
|
|
72
|
+
const answer = line => { reply(fifo, line); replied = true; };
|
|
73
|
+
process.on('exit', code => { if (!replied && code === 0) answer('exit 0'); });
|
|
74
|
+
const call = {
|
|
75
|
+
shell, fifo, handed: false,
|
|
76
|
+
fat: () => { call.handed = true; answer('fat'); process.exit(0); },
|
|
77
|
+
go: lease => { call.handed = true; answer(`go ${lease.id}`); process.exit(0); },
|
|
78
|
+
wait: w => {
|
|
79
|
+
call.handed = true;
|
|
80
|
+
answer(`wait ${w.me.id}`);
|
|
81
|
+
const wake = { ...w.info, path: fifo, pid: shell, talk: w.talk.save(), blocked: w.blocked, saidAhead: w.saidAhead, warnedHolding: w.warnedHolding };
|
|
82
|
+
const ok = withState(s => {
|
|
83
|
+
const q = s.queue.find(x => x.id === w.me.id && x.pid === shell);
|
|
84
|
+
if (q) q.wake = wake;
|
|
85
|
+
return !!q;
|
|
86
|
+
});
|
|
87
|
+
const up = ok && ensureBroker();
|
|
88
|
+
if (!up) {
|
|
89
|
+
event({ kind: 'thin', why: ok ? 'no broker could be started: waiting in Node' : 'place gone before the hand-over: waiting in Node', id: w.me.id, shell, res: w.me.res, who: w.me.who });
|
|
90
|
+
withState(s => { const q = s.queue.find(x => x.id === w.me.id && x.pid === shell); if (q) keepFor(q, shell); });
|
|
91
|
+
reply(fifo, 'fat');
|
|
92
|
+
}
|
|
93
|
+
process.exit(0);
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
return call;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const THIN_SH = path.join(SRC, 'thin.sh');
|
|
100
|
+
// The shell exec'd this Node (src/thin.sh), so it is the shell, pid and all.
|
|
101
|
+
// Its turn now: it runs right here. Paths thin waits don't cover go on here too.
|
|
102
|
+
// To wait, it keeps its place for this pid and execs back into the shell, which
|
|
103
|
+
// gets in line again the usual way (a second Node, which picks the place up) and
|
|
104
|
+
// waits on its FIFO. Without process.execve (Node before 23.11) it waits here.
|
|
105
|
+
function inlineCall(shell, fifo) {
|
|
106
|
+
return {
|
|
107
|
+
shell, fifo, inline: true, handed: false,
|
|
108
|
+
go: () => {},
|
|
109
|
+
wait: w => {
|
|
110
|
+
if (!process.execve) return 'stay';
|
|
111
|
+
withState(s => { const q = s.queue.find(x => x.id === w.me.id && x.pid === shell); if (q) keepFor(q, shell); });
|
|
112
|
+
process.execve('/bin/sh', ['/bin/sh', THIN_SH, BIN, ...process.argv.slice(2)], { ...process.env, DIBS_THIN_RESUME: '1' });
|
|
113
|
+
},
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// Make sure a broker is up and has heard there's news. One that's alive but
|
|
118
|
+
// hasn't stamped its beat in HUNG is killed first (its start time checked).
|
|
119
|
+
// When several waiters find none at once, one starts it and the rest wait for it.
|
|
120
|
+
export function ensureBroker() {
|
|
121
|
+
let b = null;
|
|
122
|
+
try { b = JSON.parse(fs.readFileSync(paths.state, 'utf8')).broker; } catch {}
|
|
123
|
+
const hung = b && now() - b.beat > HUNG && pstart(b.pid) === b.pstart;
|
|
124
|
+
// Even when no broker can be started: alive, a stuck one holds its waiters'
|
|
125
|
+
// FIFOs open, so their shells never see it gone and never move to Node.
|
|
126
|
+
if (hung) try { process.kill(b.pid, 'SIGKILL'); } catch {}
|
|
127
|
+
try { if (now() - fs.statSync(BROKEN).mtimeMs < BROKEN_FOR) return false; } catch {}
|
|
128
|
+
if (!hung && kick()) return true;
|
|
129
|
+
let mine = false;
|
|
130
|
+
try { fs.mkdirSync(STARTING); mine = true; } catch {
|
|
131
|
+
// A starter killed before it finished leaves its folder behind.
|
|
132
|
+
try { if (now() - fs.statSync(STARTING).mtimeMs > START_WAIT) { fs.rmdirSync(STARTING); fs.mkdirSync(STARTING); mine = true; } } catch {}
|
|
133
|
+
}
|
|
134
|
+
try {
|
|
135
|
+
let child = null;
|
|
136
|
+
if (mine) {
|
|
137
|
+
const log = fs.openSync(path.join(HOME, 'broker.log'), 'a');
|
|
138
|
+
// The broker waits for everyone: nothing of the job whose waiter happened to start it.
|
|
139
|
+
const env = { ...process.env };
|
|
140
|
+
for (const k of ['DIBS_LEASE', 'DIBS_REMOTE_JOB', 'DIBS_LATER_JOB']) delete env[k];
|
|
141
|
+
child = spawn(process.execPath, [...LEAN, BIN, '_broker'], { cwd: HOME, env, detached: true, stdio: ['ignore', 'ignore', log] });
|
|
142
|
+
child.unref();
|
|
143
|
+
fs.closeSync(log);
|
|
144
|
+
}
|
|
145
|
+
// This loop never yields, so a child that died is a zombie, not an exit event.
|
|
146
|
+
const died = () => !/^[^Z]/.test(spawnSync('ps', ['-o', 'stat=', '-p', String(child.pid)], { encoding: 'utf8' }).stdout.trim());
|
|
147
|
+
for (let t0 = now(), checked = t0; now() - t0 < START_WAIT; sleepSync(20)) {
|
|
148
|
+
if (kick()) { try { fs.rmSync(BROKEN, { force: true }); } catch {} return true; }
|
|
149
|
+
if (child && now() - checked > CRASH_CHECK) {
|
|
150
|
+
checked = now();
|
|
151
|
+
if (died()) break;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
if (!mine) return false;
|
|
155
|
+
// Marked broken, it would keep every waiter in Node, and the throttle watcher from
|
|
156
|
+
// replacing a stuck broker, for BROKEN_FOR: on a loaded machine that was a minute lost.
|
|
157
|
+
if (!died()) { event({ kind: 'thin', why: 'the broker is slow to start: waiting in Node meanwhile', pid: child.pid }); return false; }
|
|
158
|
+
event({ kind: 'thin', why: "the broker didn't start", log: path.join(HOME, 'broker.log') });
|
|
159
|
+
try { fs.writeFileSync(BROKEN, `${new Date().toISOString()} the broker didn't start: see ${path.join(HOME, 'broker.log')}\n`); } catch {}
|
|
160
|
+
return false;
|
|
161
|
+
} finally { if (mine) try { fs.rmdirSync(STARTING); } catch {} }
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// The throttle watcher's pass (src/cool.mjs), every 10 s: a broker that's
|
|
165
|
+
// alive but hasn't stamped its beat in HUNG is stuck. Replacing it here means
|
|
166
|
+
// its waiters don't sit until someone new gets in line. Returns what it did, for the log.
|
|
167
|
+
export function watchBroker() {
|
|
168
|
+
let s;
|
|
169
|
+
try { s = JSON.parse(fs.readFileSync(paths.state, 'utf8')); } catch { return null; }
|
|
170
|
+
const b = s.broker;
|
|
171
|
+
if (!b || now() - b.beat <= HUNG || pstart(b.pid) !== b.pstart) return null;
|
|
172
|
+
const n = thinWaiters(s).length;
|
|
173
|
+
event({ kind: 'thin', why: 'stuck broker replaced', pid: b.pid, waiting: n });
|
|
174
|
+
return `broker ${b.pid} stuck (no beat for ${Math.round((now() - b.beat) / 1000)}s, ${n} waiting): ${ensureBroker() ? 'replaced' : "replaced, but no new one is up yet"}`;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// A thin waiter's place, kept while its shell becomes Node to wait there. keptFor
|
|
178
|
+
// names that shell: the place goes when it dies, so a waiter killed in between
|
|
179
|
+
// leaves no place behind for two minutes (src/state.mjs reap).
|
|
180
|
+
function keepFor(q, shell) {
|
|
181
|
+
Object.assign(q, { pid: null, keepUntil: now() + KEEP_PLACE, keptFor: shell });
|
|
182
|
+
delete q.wake;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// _leave: a thin waiter's shell was interrupted (why is the signal), or gave
|
|
186
|
+
// up on the broker (why is keep: the place stays for its in-process retry).
|
|
187
|
+
// id 0: interrupted before it knew its id; its place is the one under its pid.
|
|
188
|
+
export function leaveLine(id, shell, why) {
|
|
189
|
+
withState(s => {
|
|
190
|
+
// Its place by id when it knows it, else by its pid. A place kept with nobody on it (for its own
|
|
191
|
+
// retry in Node, or taken for gone) is its too: interrupted, it gives that up as well.
|
|
192
|
+
const q = s.queue.find(x => (id ? x.id === id && (x.pid === shell || (why !== 'keep' && !x.pid)) : x.pid === shell)
|
|
193
|
+
|| (why !== 'keep' && x.keptFor === shell));
|
|
194
|
+
if (!q) return;
|
|
195
|
+
if (why === 'keep') return keepFor(q, shell);
|
|
196
|
+
s.queue = s.queue.filter(x => x !== q);
|
|
197
|
+
if (q.wake?.notify) notified(q, signalExit(why));
|
|
198
|
+
if (q.wake) event({ kind: 'left', id: q.id, res: q.res, who: q.who, prio: q.prio || 'normal', type: q.kind, ms: now() - q.enq, why });
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// --notify's line for a thin wait that ended before its command started (src/commands.mjs notifyOnExit).
|
|
203
|
+
function notified(q, code) {
|
|
204
|
+
notifyLine(q.wake.notify, { at: new Date().toISOString(), code, started: false, res: q.res, cmd: q.cmd, cwd: q.wake.cwd,
|
|
205
|
+
secs: Math.round((now() - q.wake.started) / 1000), pid: q.pid });
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// A waiter's messages, down its FIFO. The FIFO is opened on first sight
|
|
209
|
+
// ("hi") and held until go or exit: while the broker holds it the shell never
|
|
210
|
+
// reads end of file, and when the broker dies it closes, which is how the
|
|
211
|
+
// shell knows to start another.
|
|
212
|
+
function sink(q) {
|
|
213
|
+
let fd = null;
|
|
214
|
+
const send = text => {
|
|
215
|
+
if (fd == null) {
|
|
216
|
+
try { fd = fs.openSync(q.wake.path, O_WRONLY | O_NONBLOCK); } catch { return; } // no reader: the shell is gone, and is reaped by its pid
|
|
217
|
+
text = `hi\n${text}`;
|
|
218
|
+
}
|
|
219
|
+
const buf = Buffer.from(text);
|
|
220
|
+
// A stopped shell (Ctrl-Z) doesn't read: what doesn't fit is dropped rather than waited for.
|
|
221
|
+
for (let off = 0; off < buf.length;) try { off += fs.writeSync(fd, buf, off); } catch { return; }
|
|
222
|
+
};
|
|
223
|
+
const lines = text => text.replace(/\n$/, '').split('\n').map(l => `out ${l}\n`).join('');
|
|
224
|
+
const out = {
|
|
225
|
+
done: false,
|
|
226
|
+
open: () => send(''),
|
|
227
|
+
say: msg => send(lines(`dibs: ${msg}`)),
|
|
228
|
+
said: (...ls) => send(lines(saidText(...ls))),
|
|
229
|
+
raw: text => send(lines(text)),
|
|
230
|
+
die: (msg, code) => { send(lines(`dibs: ${msg}`)); return out.exit(code); },
|
|
231
|
+
exit: code => { if (q.wake.notify) notified(q, code); send(`exit ${code}\n`); out.close(); return { exit: code }; },
|
|
232
|
+
go: () => { send('go\n'); out.close(); },
|
|
233
|
+
fat: () => { send('fat\n'); out.close(); },
|
|
234
|
+
close: () => { if (fd != null) try { fs.closeSync(fd); } catch {} fd = null; out.done = true; },
|
|
235
|
+
};
|
|
236
|
+
return out;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// A liveness hint for a quiet tick, with no process table read: a waiter
|
|
240
|
+
// gone since the last one is reaped (pid and start time checked) by a full tick.
|
|
241
|
+
const running = pid => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
|
|
242
|
+
const thinWaiters = s => s.queue.filter(q => q.wake && q.pid && q.wake.pid === q.pid);
|
|
243
|
+
|
|
244
|
+
// _broker. Exits at once if another live broker has the job.
|
|
245
|
+
export function broker() {
|
|
246
|
+
fs.mkdirSync(WAKE, { recursive: true });
|
|
247
|
+
const me = { pid: process.pid, pstart: pstart(process.pid) };
|
|
248
|
+
const mine = withState(s => {
|
|
249
|
+
const b = s.broker;
|
|
250
|
+
if (b && b.pid !== me.pid && now() - b.beat < HUNG && makeAlive([b.pid])(b.pid, b.pstart)) return false;
|
|
251
|
+
s.broker = { ...me, beat: now() };
|
|
252
|
+
return true;
|
|
253
|
+
});
|
|
254
|
+
if (!mine) return;
|
|
255
|
+
quiet(); // its own state changes don't kick it
|
|
256
|
+
// Written before the control FIFO opens, so whoever sees a kick land sees this pid too.
|
|
257
|
+
fs.writeFileSync(PIDFILE, String(me.pid));
|
|
258
|
+
try { fs.unlinkSync(paths.ctl); } catch {}
|
|
259
|
+
if (spawnSync('mkfifo', ['-m', '600', paths.ctl], { stdio: 'ignore' }).status !== 0) throw new Error(`couldn't make the control FIFO ${paths.ctl}`);
|
|
260
|
+
const ctl = new net.Socket({ fd: fs.openSync(paths.ctl, O_RDWR | O_NONBLOCK), readable: true, writable: false });
|
|
261
|
+
const code = fs.readFileSync(path.join(SRC, 'version.mjs'), 'utf8');
|
|
262
|
+
const waits = new Map(); // queue id -> its wait (src/acquire.mjs waiter), with its FIFO as out
|
|
263
|
+
let cfg = loadConfig(), hist = history(), histAt = 0, beat = 0, idleSince = now(), pending = false, forced = false, pruned = 0, seen = '', full = 0;
|
|
264
|
+
|
|
265
|
+
const exit = () => {
|
|
266
|
+
for (const w of waits.values()) w.out.close();
|
|
267
|
+
try { if (fs.readFileSync(PIDFILE, 'utf8') === String(me.pid)) fs.unlinkSync(PIDFILE); } catch {}
|
|
268
|
+
process.exit(0);
|
|
269
|
+
};
|
|
270
|
+
// Under the lock, so a waiter handed over meanwhile either keeps this broker
|
|
271
|
+
// or, after it, finds nobody reading the control FIFO and starts another.
|
|
272
|
+
const leave = always => {
|
|
273
|
+
const gone = withState(s => {
|
|
274
|
+
if (!always && thinWaiters(s).length) return false;
|
|
275
|
+
if (s.broker?.pid === me.pid) delete s.broker;
|
|
276
|
+
ctl.destroy();
|
|
277
|
+
return true;
|
|
278
|
+
});
|
|
279
|
+
if (gone) exit();
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
const tick = () => {
|
|
283
|
+
const kicked = forced;
|
|
284
|
+
pending = forced = false;
|
|
285
|
+
const t = now();
|
|
286
|
+
// A release changed the code: the waiters' shells start the new one.
|
|
287
|
+
try { if (fs.readFileSync(path.join(SRC, 'version.mjs'), 'utf8') !== code) return leave(true); } catch {}
|
|
288
|
+
if (t - pruned > PRUNE_EVERY) { pruned = t; prune(); }
|
|
289
|
+
// With nobody to wait for, the lock is taken only to keep the beat fresh.
|
|
290
|
+
let quietNow = false, text = '';
|
|
291
|
+
try { text = fs.readFileSync(paths.state, 'utf8'); quietNow = !waits.size && !thinWaiters(JSON.parse(text)).length; } catch {}
|
|
292
|
+
if (!quietNow && !kicked && text === seen && t - full < QUIET_POLL && [...waits.values()].every(w => running(w.me.pid))) return;
|
|
293
|
+
if (quietNow) {
|
|
294
|
+
if (t - idleSince > IDLE_EXIT) return leave(false);
|
|
295
|
+
if (t - beat > BEAT) withState(s => { if (s.broker?.pid === me.pid || !s.broker) s.broker = { ...me, beat: (beat = t) }; });
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
processes(); // read the process table before taking the lock, not while holding it
|
|
299
|
+
noticeScan();
|
|
300
|
+
try { cfg = loadConfig(); } catch {}
|
|
301
|
+
try { const m = fs.statSync(paths.history).mtimeMs; if (m !== histAt) { histAt = m; hist = history(); } } catch {}
|
|
302
|
+
let rs;
|
|
303
|
+
try {
|
|
304
|
+
rs = withState(s => {
|
|
305
|
+
if (s.broker && s.broker.pid !== me.pid) return null; // taken for hung and replaced: step aside
|
|
306
|
+
if (t - beat > BEAT || !s.broker) s.broker = { ...me, beat: (beat = t) };
|
|
307
|
+
markIdle(s);
|
|
308
|
+
const thin = thinWaiters(s).sort(byRank(hist));
|
|
309
|
+
for (const [id, w] of waits) if (!thin.some(q => q.id === id)) { w.out.close(); waits.delete(id); }
|
|
310
|
+
return thin.map(q => {
|
|
311
|
+
let w = waits.get(q.id);
|
|
312
|
+
if (!w) {
|
|
313
|
+
w = waiter(q.wake, cfg, hist, sink(q));
|
|
314
|
+
w.me = { ...q };
|
|
315
|
+
waits.set(q.id, w);
|
|
316
|
+
w.out.open();
|
|
317
|
+
}
|
|
318
|
+
Object.assign(w, { cfg, hist });
|
|
319
|
+
return [w, decide(s, w)];
|
|
320
|
+
});
|
|
321
|
+
});
|
|
322
|
+
} catch (e) {
|
|
323
|
+
if (!noSpace(e)) throw e;
|
|
324
|
+
for (const w of waits.values()) full(w);
|
|
325
|
+
return done();
|
|
326
|
+
}
|
|
327
|
+
if (!rs) return exit();
|
|
328
|
+
const follows = rs.map(([w]) => w.info.follow).filter(f => f?.pid);
|
|
329
|
+
const up = follows.length ? makeAlive(follows.map(f => f.pid)) : null;
|
|
330
|
+
for (const [w, r] of rs) {
|
|
331
|
+
if (w.full) { w.full = false; w.out.say("there's disk space again; back in line."); }
|
|
332
|
+
// A job sent from another machine ends when the worker that started it does (bin/dibs.mjs followParent).
|
|
333
|
+
// Checked by the worker's own pid and start time, not by the shell's parent, which a Linux run took for gone.
|
|
334
|
+
const f = w.info.follow;
|
|
335
|
+
if (f?.pid && !r.lease && !up(f.pid, f.pstart)) {
|
|
336
|
+
abandon(w, 'worker gone', signalExit('SIGTERM'), 'the worker that started this job is gone, so it stopped waiting. Your command did NOT run.');
|
|
337
|
+
continue;
|
|
338
|
+
}
|
|
339
|
+
try {
|
|
340
|
+
const x = step(r, w);
|
|
341
|
+
if (x?.lease) w.out.go();
|
|
342
|
+
// Held by load and able to ship (acquire.mjs): its shell waits in Node, keeping its place, and asks the coordinator there.
|
|
343
|
+
else if (x?.ship) { withState(s => { const q = s.queue.find(y => y.id === w.me.id && y.pid === w.me.pid); if (q) keepFor(q, w.me.pid); }); w.out.fat(); }
|
|
344
|
+
} catch (e) {
|
|
345
|
+
event({ kind: 'thin', why: 'the broker crashed deciding for a waiter', id: w.me.id, shell: w.me.pid, res: w.me.res, who: w.me.who, error: String(e?.stack || e).slice(0, 2000) });
|
|
346
|
+
w.out.die(`dibs itself crashed (a bug in dibs, not in your command; exit 70). Report it: dibs ask "..."\n${e?.stack || e}`, 70);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
done();
|
|
350
|
+
idleSince = full = now();
|
|
351
|
+
try { seen = fs.readFileSync(paths.state, 'utf8'); } catch {}
|
|
352
|
+
};
|
|
353
|
+
const done = () => { for (const [id, w] of waits) if (w.out.done) waits.delete(id); };
|
|
354
|
+
const soon = kick => { forced ||= kick; if (!pending) { pending = true; setImmediate(tick); } };
|
|
355
|
+
ctl.on('data', () => soon(true));
|
|
356
|
+
ctl.on('error', () => {});
|
|
357
|
+
setInterval(() => soon(false), POLL);
|
|
358
|
+
tick();
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// FIFOs of shells that are gone. Only in ~/.dibs/w, the folder dibs made for them.
|
|
362
|
+
function prune() {
|
|
363
|
+
let names = [];
|
|
364
|
+
try { names = fs.readdirSync(WAKE); } catch { return; }
|
|
365
|
+
for (const n of names) {
|
|
366
|
+
if (!/^\d+$/.test(n)) continue;
|
|
367
|
+
try { process.kill(Number(n), 0); } catch (e) { if (e.code === 'ESRCH') try { fs.unlinkSync(path.join(WAKE, n)); } catch {} }
|
|
368
|
+
}
|
|
369
|
+
}
|