@dibssoftware/dibs 0.0.0-stage → 0.0.179
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 +594 -0
- package/LICENSE +670 -0
- package/README.md +85 -2
- package/bin/dibs-guard.mjs +7 -0
- package/bin/dibs.mjs +548 -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/reference.md +157 -0
- package/docs/relay.md +196 -0
- package/docs/releasing.md +27 -0
- package/docs/scheduling.md +163 -0
- package/docs/simulators.md +17 -0
- package/package.json +45 -4
- package/skills/dibs/SKILL.md +183 -0
- package/src/acquire.mjs +700 -0
- package/src/admin.mjs +145 -0
- package/src/agents.mjs +145 -0
- package/src/alerts.mjs +499 -0
- package/src/answers.mjs +65 -0
- package/src/board.mjs +202 -0
- package/src/broker.mjs +369 -0
- package/src/commands.mjs +810 -0
- package/src/config.mjs +324 -0
- package/src/connect.mjs +106 -0
- package/src/cool.mjs +160 -0
- package/src/diskwarn.mjs +154 -0
- package/src/events.mjs +96 -0
- package/src/files.mjs +1123 -0
- package/src/guard.mjs +613 -0
- package/src/history.mjs +247 -0
- package/src/hogs.mjs +227 -0
- package/src/later.mjs +487 -0
- package/src/measure.mjs +262 -0
- package/src/news.mjs +101 -0
- package/src/nodecheck.mjs +17 -0
- package/src/notes.mjs +171 -0
- package/src/notices.mjs +160 -0
- package/src/ondemand.mjs +572 -0
- package/src/overlap.mjs +151 -0
- package/src/override.mjs +360 -0
- package/src/owner.mjs +30 -0
- package/src/plain.mjs +470 -0
- package/src/platform.mjs +357 -0
- package/src/preempt.mjs +438 -0
- package/src/primer.mjs +89 -0
- package/src/proc.mjs +99 -0
- package/src/progress.mjs +187 -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 +1020 -0
- package/src/scratch.mjs +61 -0
- package/src/serve.mjs +742 -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 +702 -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 +1119 -0
- package/src/worker.mjs +318 -0
package/src/serve.mjs
ADDED
|
@@ -0,0 +1,742 @@
|
|
|
1
|
+
// dibs serve: the coordinator. Workers check in and pick up jobs; clients place
|
|
2
|
+
// jobs and read their output. It never connects out, so it only needs to be
|
|
3
|
+
// reachable: on this machine, and on its Tailscale address when there is one.
|
|
4
|
+
import http from 'node:http';
|
|
5
|
+
import dgram from 'node:dgram';
|
|
6
|
+
import crypto from 'node:crypto';
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import os from 'node:os';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { execFileSync } from 'node:child_process';
|
|
11
|
+
import { HOME, machine } from './config.mjs';
|
|
12
|
+
import { hogsOnce } from './hogs.mjs';
|
|
13
|
+
import { watcherDown } from './diskwarn.mjs';
|
|
14
|
+
import { FIND, TS_CLI, REMOTE, DEFAULT_PORT, LOST, MAYBE_RAN, MAX_BUNDLE, remoteConf, saveRemote, newToken, shortHost, copyKey } from './remote.mjs';
|
|
15
|
+
import { die, now, log, dur, clock } from './util.mjs';
|
|
16
|
+
import { VERSION } from './version.mjs';
|
|
17
|
+
import { makeTrust, allowed, NAME, MACHINES, newCode, codeKey, codeProof, CODE_LIFE } from './trust.mjs';
|
|
18
|
+
import { logChange } from './owner.mjs';
|
|
19
|
+
import { loadConfig } from './config.mjs';
|
|
20
|
+
import { ondemand, ondemandOf, worthWaking, wakePoints, cantWake } from './ondemand.mjs';
|
|
21
|
+
import { unpatched } from './nodecheck.mjs';
|
|
22
|
+
|
|
23
|
+
const OUT_HOLD = 15e3; // a client's read waits this long for output
|
|
24
|
+
// Tests shorten these with DIBS_SERVE_TIMING.
|
|
25
|
+
const {
|
|
26
|
+
beatHold: BEAT_HOLD, // a worker's check-in waits this long for work before answering
|
|
27
|
+
workerLost: WORKER_LOST, // no check-in for this long: the machine is gone
|
|
28
|
+
clientLost: CLIENT_LOST, // nobody reading a job for this long: the sender is gone, stop it
|
|
29
|
+
} = { beatHold: 10e3, workerLost: 35e3, clientLost: 90e3, ...JSON.parse(process.env.DIBS_SERVE_TIMING || '{}') };
|
|
30
|
+
const KEEP_DONE = 15 * 6e4; // finished jobs stay this long for late readers and --bring
|
|
31
|
+
// A little over the senders' own limit, so a bundle a sender accepted is never refused here.
|
|
32
|
+
const MAX_UPLOAD = MAX_BUNDLE + 10 * 1024 ** 2;
|
|
33
|
+
const MAX_JSON = 64 * 1024 ** 2; // a job's file list and output batches travel as JSON
|
|
34
|
+
const MAX_OUT = 16 * 1024 ** 2; // output kept per job; older output is dropped
|
|
35
|
+
// Machine pairing codes (dibs pair --machine). Open at once: a new one past this drops the oldest.
|
|
36
|
+
const MAX_CODES = 5;
|
|
37
|
+
// Wrong codes in FAIL_WINDOW before every try is refused until it passes, the right code too.
|
|
38
|
+
// 40 bits at 10 tries per 10 minutes: one chance in two million a year. Open codes stay good,
|
|
39
|
+
// or anyone who can reach the port could keep the person from pairing for good.
|
|
40
|
+
const MAX_FAILS = 10, FAIL_WINDOW = 10 * 6e4;
|
|
41
|
+
const FAIL_DELAY = 800;
|
|
42
|
+
// Lookups (a joiner's broadcast, its hello) answered per second: enough for a few machines
|
|
43
|
+
// joining at once, too few for anyone to use the coordinator to flood someone else.
|
|
44
|
+
const LOOKUPS_PER_SEC = 20;
|
|
45
|
+
|
|
46
|
+
const fail = (status, msg) => Object.assign(new Error(msg), { status });
|
|
47
|
+
// What a worker's check-in may set. The rest of a worker's record (its queue,
|
|
48
|
+
// who is waiting on it, when it was seen) is the coordinator's own.
|
|
49
|
+
// Numbers are checked: placement does arithmetic on them for every sender.
|
|
50
|
+
const REPORT = ['os', 'version', 'busy', 'running', 'copies', 'board'];
|
|
51
|
+
const REPORT_NUM = ['cores', 'memTotal', 'memFree', 'load', 'diskFree'];
|
|
52
|
+
|
|
53
|
+
// A machine with a free copy of the job's project skips reinstalling
|
|
54
|
+
// dependencies and rebuilding caches. That's worth most of one job ahead in
|
|
55
|
+
// line (60), so a warm machine wins unless a cold one would start a whole job
|
|
56
|
+
// sooner, or is much less loaded. A copy a job is using, or that a job on its
|
|
57
|
+
// way there will take (need.claimed), doesn't count: that job would get a fresh folder.
|
|
58
|
+
const WARM = 40;
|
|
59
|
+
function warm(w, need) {
|
|
60
|
+
if (!need.root || !w.copies) return false;
|
|
61
|
+
const c = w.copies[copyKey(need.from, need.root)];
|
|
62
|
+
return !!c && c.free > (need.claimed?.[w.name] || 0);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Lower is better. Mostly: how long would the job wait there?
|
|
66
|
+
export function score(w, need, t = now()) {
|
|
67
|
+
let s = 0;
|
|
68
|
+
for (const r of need.res) {
|
|
69
|
+
const b = w.busy?.[r];
|
|
70
|
+
if (b) s += 60 * (b.waiting + Math.max(0, b.used - b.slots + 1));
|
|
71
|
+
}
|
|
72
|
+
s += 30 * Math.min(2, w.load / Math.max(1, w.cores));
|
|
73
|
+
if (w.memFree < 20) s += 50;
|
|
74
|
+
s += 20 * (w.assigned || 0);
|
|
75
|
+
if (w.name === need.from) s -= 15 + WARM; // nothing to ship, and the warmest copy of all
|
|
76
|
+
else if (warm(w, need)) s -= WARM;
|
|
77
|
+
return s;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// An on-demand machine asleep or waking (src/ondemand.mjs) isn't reporting, and needn't be: a job wakes it.
|
|
81
|
+
const reporting = w => !w.ondemand || w.ondemand.state === 'running';
|
|
82
|
+
function fits(w, need, t = now()) {
|
|
83
|
+
if (reporting(w) && (w.lost || t - w.seen > WORKER_LOST)) return `${w.name} isn't reporting in`;
|
|
84
|
+
if (w.ondemand?.state === 'stopping') return `${w.name} is stopping`;
|
|
85
|
+
if (w.ondemand?.problem) return `${w.name} can't be used: ${w.ondemand.problem}`;
|
|
86
|
+
const no = cantWake(w.ondemand, t);
|
|
87
|
+
if (no) return `${w.name} can't wake: ${no.why}, retry ${clock(no.until)}`;
|
|
88
|
+
if (need.os && w.os !== need.os) return `${w.name} runs ${w.os}, and ${need.res.join(', ')} needs ${need.os}`;
|
|
89
|
+
if (need.mem && w.memTotal && need.mem > w.memTotal) return `${w.name} has less memory than the job needs`;
|
|
90
|
+
return allowed(w, need);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const BACKUP_EVERY = Number(process.env.DIBS_BACKUP_MS) || 30e3; // the watcher checks every few seconds; half a minute late is still early
|
|
94
|
+
|
|
95
|
+
// Where a job should go, or why it can't go anywhere.
|
|
96
|
+
export function place(workers, need, t = now()) {
|
|
97
|
+
if (need.on) {
|
|
98
|
+
const w = workers.get(need.on);
|
|
99
|
+
if (!w) {
|
|
100
|
+
if (need.on === need.from) return { machine: need.from, why: 'you asked for this machine' };
|
|
101
|
+
return { error: `no machine named ${need.on}. Machines: ${[...workers.keys()].join(', ') || 'none'}` };
|
|
102
|
+
}
|
|
103
|
+
const bad = fits(w, need, t);
|
|
104
|
+
// A VM that can't be found (src/ondemand.mjs findVm) is said plainly, and the job runs where it came from.
|
|
105
|
+
if (bad && w.ondemand?.problem && need.from) return { machine: need.from, why: `${bad}, so it runs here` };
|
|
106
|
+
// One already marked can't-wake (boat's starts used up) sends the job back the way a refused wake
|
|
107
|
+
// does. Refused here instead, a send that came just after the coordinator's own check of boat's
|
|
108
|
+
// limits exited 2, while one just before it ran on its sender (2026-11-03).
|
|
109
|
+
const no = cantWake(w.ondemand, t);
|
|
110
|
+
if (bad && no && bad.startsWith(`${w.name} can't wake`) && need.from)
|
|
111
|
+
return { machine: need.from, why: `${w.name} can't wake (${no.why}), so it runs on ${need.from}` };
|
|
112
|
+
// Too big for it: a VM made for the job (src/ondemand.mjs create), when that's on.
|
|
113
|
+
const big = w.ondemand?.bigger && workers.get(w.ondemand.bigger);
|
|
114
|
+
const short = bad || ((need.askedCpu || 0) > w.cores && `${w.name} has fewer cores than the job asked for`);
|
|
115
|
+
if (big && short && !fits(big, need, t) && (need.askedCpu || 0) <= big.cores) return { machine: big.name, why: `${short}, so dibs makes a VM big enough for it, and deletes it after` };
|
|
116
|
+
return bad ? { error: bad } : { machine: w.name, why: 'you asked for it' };
|
|
117
|
+
}
|
|
118
|
+
// A temporary VM is only made for jobs bigger than the VM it stands beside.
|
|
119
|
+
const tooBigFor = o => (need.mem || 0) > o.mem || (need.askedCpu || 0) > o.cores;
|
|
120
|
+
let ok = [...workers.values()].filter(w => !fits(w, need, t) && (!w.ondemand?.over || w.ondemand.state === 'running' || tooBigFor(w.ondemand.over)));
|
|
121
|
+
// A sleeping VM only when the job's wait on every awake machine would outlast waking it.
|
|
122
|
+
const awake = ok.filter(w => reporting(w));
|
|
123
|
+
const best = Math.min(...awake.map(w => score(w, need, t)));
|
|
124
|
+
// With nothing awake to compare against, the job's wait isn't known: it runs where it was sent from.
|
|
125
|
+
ok = ok.filter(w => reporting(w) || (awake.length > 0 && worthWaking(w.ondemand, best)));
|
|
126
|
+
if (!ok.length) {
|
|
127
|
+
if (!need.os || need.os === need.fromOs) return { machine: need.from, why: 'no other machine is taking jobs' };
|
|
128
|
+
const reasons = [...workers.values()].map(w => fits(w, need, t));
|
|
129
|
+
return { error: `no machine can take it${reasons.length ? `: ${reasons.join('; ')}` : ' (no workers)'}` };
|
|
130
|
+
}
|
|
131
|
+
const cost = w => (reporting(w) ? score(w, need, t) : wakePoints(w.ondemand));
|
|
132
|
+
ok.sort((a, b) => cost(a) - cost(b));
|
|
133
|
+
const w = ok[0];
|
|
134
|
+
if (!reporting(w)) return { machine: w.name, why: `it's asleep, and waking it (about ${Math.round(((w.ondemand.resumeMs ?? 45e3)) / 1000)}s) beats the wait anywhere awake` };
|
|
135
|
+
const busy = need.res.map(r => w.busy?.[r]).filter(Boolean);
|
|
136
|
+
const waiting = busy.reduce((a, b) => a + b.waiting, 0);
|
|
137
|
+
return { machine: w.name, why: `${warm(w, need) ? 'it already has a copy of this project' : 'the least busy'} (load ${w.load.toFixed(1)} on ${w.cores} cores${waiting ? `, ${waiting} waiting` : ', nobody waiting'})` };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// The Tailscale address of this machine. Ask Tailscale itself when its CLI is
|
|
141
|
+
// around; otherwise a 100.64.0.0/10 address on a tunnel interface. That range
|
|
142
|
+
// alone isn't enough: carrier-grade NAT and some hotspots use it too.
|
|
143
|
+
function tailscaleIp() {
|
|
144
|
+
for (const cli of TS_CLI) {
|
|
145
|
+
try {
|
|
146
|
+
const ip = execFileSync(cli, ['ip', '-4'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5000 }).trim().split('\n')[0];
|
|
147
|
+
if (/^100\.\d+\.\d+\.\d+$/.test(ip)) return ip;
|
|
148
|
+
} catch {}
|
|
149
|
+
}
|
|
150
|
+
for (const [name, list] of Object.entries(os.networkInterfaces())) {
|
|
151
|
+
if (!/^(utun\d+|tailscale\d*)$/i.test(name)) continue;
|
|
152
|
+
for (const a of list || []) {
|
|
153
|
+
if (a.family !== 'IPv4' && a.family !== 4) continue;
|
|
154
|
+
const [x, y] = a.address.split('.').map(Number);
|
|
155
|
+
if (x === 100 && y >= 64 && y <= 127) return a.address;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return null;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// A row as a limited machine sees it: resource and who, not what it runs or
|
|
162
|
+
// why. A file lease's path says what's being worked on, so it goes too.
|
|
163
|
+
const hidePath = r => (typeof r === 'string' && r.startsWith('files:') ? 'files:' : r);
|
|
164
|
+
// A machine's lines, with every file lease folded into one files: line.
|
|
165
|
+
export function bareBusy(busy) {
|
|
166
|
+
const out = {};
|
|
167
|
+
for (const [k, b] of Object.entries(busy || {})) {
|
|
168
|
+
const o = out[hidePath(k)] ||= { used: 0, slots: 0, waiting: 0 };
|
|
169
|
+
o.used += b?.used || 0; o.slots += b?.slots || 0; o.waiting += b?.waiting || 0;
|
|
170
|
+
}
|
|
171
|
+
return out;
|
|
172
|
+
}
|
|
173
|
+
export const bare = x => ({ ...x, cmd: x.cmd == null ? x.cmd : Array.isArray(x.cmd) ? [] : '', purpose: '',
|
|
174
|
+
...(Array.isArray(x.res) ? { res: x.res.map(hidePath) } : {}), ...(Array.isArray(x.holds) ? { holds: x.holds.map(hidePath) } : {}) });
|
|
175
|
+
|
|
176
|
+
// What a client sees of an on-demand machine: its state and how long it takes to wake.
|
|
177
|
+
// mem: the VM's size as configured, which a sender packs jobs into (src/remote.mjs loadShipTarget).
|
|
178
|
+
const vmOf = w => w.ondemand && { state: w.ondemand.state, provider: w.ondemand.provider, resumeMs: w.ondemand.resumeMs, idleStop: w.ondemand.idleStop, cantWake: cantWake(w.ondemand) || undefined, problem: w.ondemand.problem, mem: w.ondemand.memTotal,
|
|
179
|
+
temp: w.ondemand.temp ? { of: w.ondemand.of, max: w.ondemand.create.max } : undefined };
|
|
180
|
+
|
|
181
|
+
// port: the coordinator's, which pairing lookups are answered on (UDP). addrs: the
|
|
182
|
+
// addresses other machines can reach it at, as URLs.
|
|
183
|
+
export function makeServer({ token, log = () => {}, self = null, joinUrl = () => null, registry = MACHINES, port = null, addrs = () => [] }) {
|
|
184
|
+
const workers = new Map();
|
|
185
|
+
const jobs = new Map();
|
|
186
|
+
// up(w): src/ondemand.mjs marks a waking VM up the moment its new worker checks in, so that check-in gets the jobs.
|
|
187
|
+
const hooks = {};
|
|
188
|
+
// Ids carry this coordinator's start time, so a job from before a restart
|
|
189
|
+
// can never be mistaken for a new one with the same number.
|
|
190
|
+
let seq = 0;
|
|
191
|
+
const started = now();
|
|
192
|
+
const boot = started.toString(36);
|
|
193
|
+
const jobDir = id => path.join(HOME, 'jobs', String(id));
|
|
194
|
+
const trust = makeTrust({ token, file: registry });
|
|
195
|
+
// Codes live in memory only: one outlives neither its ten minutes nor a restart.
|
|
196
|
+
const codes = []; // { id, key, exp, name, made }
|
|
197
|
+
const open = () => { const t = now(); for (let i = codes.length; i--;) if (codes[i].exp <= t) codes.splice(i, 1); return codes; };
|
|
198
|
+
const fails = [];
|
|
199
|
+
let lookups = { sec: 0, n: 0 };
|
|
200
|
+
const lookupOk = () => {
|
|
201
|
+
const sec = Math.floor(now() / 1000);
|
|
202
|
+
if (lookups.sec !== sec) lookups = { sec, n: 0 };
|
|
203
|
+
return ++lookups.n <= LOOKUPS_PER_SEC;
|
|
204
|
+
};
|
|
205
|
+
// A machine on the same network finds this coordinator by broadcast. The socket is
|
|
206
|
+
// open only while a code is, and its answer says no more than where to ask next.
|
|
207
|
+
let finder = null;
|
|
208
|
+
const findable = () => {
|
|
209
|
+
if (finder || !port) return;
|
|
210
|
+
const sock = dgram.createSocket({ type: 'udp4', reuseAddr: true });
|
|
211
|
+
finder = sock;
|
|
212
|
+
sock.on('message', (msg, from) => {
|
|
213
|
+
if (String(msg) !== FIND || !open().length || !lookupOk()) return;
|
|
214
|
+
sock.send(JSON.stringify({ t: 'dibs-coordinator-v1', name: self, port, urls: addrs() }), from.port, from.address);
|
|
215
|
+
});
|
|
216
|
+
sock.on('error', e => { log(`can't answer pairing lookups on UDP ${port}: ${e.message}. Joining machines need --at <address>`); try { sock.close(); } catch {} if (finder === sock) finder = null; });
|
|
217
|
+
sock.bind(Number(process.env.DIBS_PAIR_PORT) || port);
|
|
218
|
+
};
|
|
219
|
+
const unfindable = () => { if (finder && !open().length) { try { finder.close(); } catch {} finder = null; } };
|
|
220
|
+
const machineList = () => Object.entries(trust.reg.machines).map(([name, m]) => ({ name, invited: m.invited, joined: m.joined, paired: m.paired || null, online: workers.has(name) && !fits(workers.get(name), {}) }));
|
|
221
|
+
// Before any token: a joiner has none yet. Each answer is a step of dibs join <code>.
|
|
222
|
+
const pairing = {
|
|
223
|
+
'POST /pair/hello': async req => {
|
|
224
|
+
const { n } = await jsonBody(req);
|
|
225
|
+
if (typeof n !== 'string' || !/^[\w-]{43}$/.test(n)) throw fail(400, 'a hello carries a 32-byte nonce');
|
|
226
|
+
if (!lookupOk()) throw fail(429, 'too many lookups this second; try again');
|
|
227
|
+
if (!open().length) throw fail(404, 'no machine pairing code is open here. On the coordinator: dibs pair --machine');
|
|
228
|
+
const nc = crypto.randomBytes(32).toString('base64url');
|
|
229
|
+
return { name: self, nc, proofs: open().map(c => codeProof(c.key, n, nc)) };
|
|
230
|
+
},
|
|
231
|
+
'POST /pair/join': async req => {
|
|
232
|
+
const { code, name: asked } = await jsonBody(req);
|
|
233
|
+
const t = now();
|
|
234
|
+
while (fails.length && t - fails[0] > FAIL_WINDOW) fails.shift();
|
|
235
|
+
if (fails.length >= MAX_FAILS) throw fail(429, `too many wrong codes in the last ${FAIL_WINDOW / 6e4} minutes, so every try is refused for now. The code still works once that passes`);
|
|
236
|
+
const k = codeKey(code);
|
|
237
|
+
const c = open().find(x => crypto.timingSafeEqual(x.key, k));
|
|
238
|
+
if (!c) {
|
|
239
|
+
fails.push(t);
|
|
240
|
+
await new Promise(r => setTimeout(r, FAIL_DELAY));
|
|
241
|
+
throw fail(401, 'that code is wrong, used or expired. On the coordinator: dibs pair --machine for a new one');
|
|
242
|
+
}
|
|
243
|
+
const name = c.name || asked;
|
|
244
|
+
if (!NAME.test(name || '')) throw fail(400, 'a machine name is letters, digits, dots, dashes and underscores (--name)');
|
|
245
|
+
if (name === self) throw fail(409, `${name} is the coordinator's own name. Join with --name <another>`);
|
|
246
|
+
// A code made for a name may replace that machine (as dibs invite does); an open one may not take a name in use.
|
|
247
|
+
if (trust.has(name) && !c.name) throw fail(409, `a machine called ${name} is already in the group. Join with --name <another>, or on the coordinator make the code for it: dibs pair --machine --name ${name}`);
|
|
248
|
+
codes.splice(codes.indexOf(c), 1);
|
|
249
|
+
unfindable();
|
|
250
|
+
const replaced = trust.has(name);
|
|
251
|
+
if (replaced) {
|
|
252
|
+
drop(name, `${name} joined again with a pairing code, so the job was stopped`);
|
|
253
|
+
trust.revoke(name, `${name} joined again with a pairing code, so this token no longer works`);
|
|
254
|
+
}
|
|
255
|
+
const token = trust.invite(name, { paired: now() });
|
|
256
|
+
log(`${name} joined with a pairing code${replaced ? ' (its old token no longer works)' : ''}`);
|
|
257
|
+
return { name, token, url: joinUrl(), version: VERSION };
|
|
258
|
+
},
|
|
259
|
+
};
|
|
260
|
+
// Every answer closes its connection. A kept-alive one is dropped here after
|
|
261
|
+
// 5s idle, and a client that was busy longer (packing a big working copy)
|
|
262
|
+
// can send its next call on it before it notices: fetch failed, ECONNRESET.
|
|
263
|
+
const send = (resp, code, body) => {
|
|
264
|
+
if (resp.writableEnded) return;
|
|
265
|
+
if (Buffer.isBuffer(body)) {
|
|
266
|
+
resp.writeHead(code, { 'content-type': 'application/octet-stream', 'content-length': body.length, connection: 'close' });
|
|
267
|
+
resp.end(body);
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
const txt = JSON.stringify(body);
|
|
271
|
+
resp.writeHead(code, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(txt), connection: 'close' });
|
|
272
|
+
resp.end(txt);
|
|
273
|
+
};
|
|
274
|
+
const body = (req, limit) => new Promise((resolve, reject) => {
|
|
275
|
+
const parts = []; let n = 0;
|
|
276
|
+
req.on('data', d => { n += d.length; if (n > limit) { reject(fail(413, 'too large')); req.destroy(); } else parts.push(d); });
|
|
277
|
+
req.on('end', () => resolve(Buffer.concat(parts)));
|
|
278
|
+
req.on('error', reject);
|
|
279
|
+
});
|
|
280
|
+
const jsonBody = async req => {
|
|
281
|
+
const b = await body(req, MAX_JSON);
|
|
282
|
+
try { return b.length ? JSON.parse(b) : {}; } catch { throw fail(400, 'bad JSON'); }
|
|
283
|
+
};
|
|
284
|
+
|
|
285
|
+
// Wake whoever is waiting on a job or a worker.
|
|
286
|
+
const wake = x => { const ws = x.wake || []; x.wake = []; for (const f of ws) f(); };
|
|
287
|
+
// The response's close event, unlike the request's, means the caller hung up.
|
|
288
|
+
const waitFor = (x, ms, resp) => new Promise(resolve => {
|
|
289
|
+
const done = () => { clearTimeout(timer); resp.off('close', done); x.wake = (x.wake || []).filter(f => f !== done); resolve(); };
|
|
290
|
+
const timer = setTimeout(done, ms);
|
|
291
|
+
(x.wake ||= []).push(done);
|
|
292
|
+
resp.on('close', done);
|
|
293
|
+
});
|
|
294
|
+
|
|
295
|
+
const adopt = (w, x, running) => {
|
|
296
|
+
if (!x || typeof x.id !== 'string' || !/^[\w-]+$/.test(x.id) || !running.has(x.id) || jobs.has(x.id) || typeof x.from !== 'string') return;
|
|
297
|
+
const pick = k => (x[k] === undefined ? undefined : x[k]);
|
|
298
|
+
const j = { id: x.id, from: x.from, who: pick('who'), agent: pick('agent'), label: pick('label'), purpose: x.purpose || '',
|
|
299
|
+
res: Array.isArray(x.res) ? x.res.map(String) : [], cmd: Array.isArray(x.cmd) ? x.cmd.map(String) : [], bring: Array.isArray(x.bring) ? x.bring : [],
|
|
300
|
+
machine: w.name, state: 'running', adopted: true, created: Number(x.created) || now(), started: now(), seen: now(),
|
|
301
|
+
out: [], outBytes: 0, base: 0, next: 0, dropped: 0, code: null, artifacts: false };
|
|
302
|
+
jobs.set(j.id, j);
|
|
303
|
+
log(`job ${j.id} ${j.res.join(',')} from ${j.agent || j.who}@${j.from} on ${w.name}: picked up again after a restart`);
|
|
304
|
+
};
|
|
305
|
+
|
|
306
|
+
const finish = (j, code, why) => {
|
|
307
|
+
if (j.state === 'done') return;
|
|
308
|
+
Object.assign(j, { state: 'done', code, why: why || j.why || null, doneAt: now() });
|
|
309
|
+
const w = workers.get(j.machine);
|
|
310
|
+
if (w) w.assigned = Math.max(0, (w.assigned || 0) - 1);
|
|
311
|
+
log(`job ${j.id} ${j.res.join(',')} on ${j.machine}: exit ${code}${why ? ` (${why})` : ''}`);
|
|
312
|
+
wake(j);
|
|
313
|
+
};
|
|
314
|
+
const append = (j, s, buf) => {
|
|
315
|
+
if (!buf.length) return;
|
|
316
|
+
j.out.push([s, buf]); j.outBytes += buf.length; j.next++;
|
|
317
|
+
while (j.outBytes > MAX_OUT && j.out.length > 1) { const [, d] = j.out.shift(); j.outBytes -= d.length; j.base++; j.dropped += d.length; }
|
|
318
|
+
wake(j);
|
|
319
|
+
};
|
|
320
|
+
const assign = j => {
|
|
321
|
+
if (j.state === 'done') return;
|
|
322
|
+
let w = workers.get(j.machine);
|
|
323
|
+
if (!w || fits(w, j)) {
|
|
324
|
+
// Its machine went away before it started: any other machine that fits will do, unless --on named one.
|
|
325
|
+
const need = { ...j, claimed: claimed(j, j) };
|
|
326
|
+
const others = j.on ? [] : [...workers.values()].filter(x => !fits(x, j)).sort((a, b) => score(a, need) - score(b, need));
|
|
327
|
+
if (!others.length) return finish(j, LOST, `${j.machine} stopped reporting before the job started${j.on ? '' : ', and no other machine can take it'}`);
|
|
328
|
+
w = others[0];
|
|
329
|
+
j.machine = w.name;
|
|
330
|
+
}
|
|
331
|
+
j.state = 'queued';
|
|
332
|
+
w.pending.push(j.id);
|
|
333
|
+
w.assigned = (w.assigned || 0) + 1;
|
|
334
|
+
wake(w);
|
|
335
|
+
};
|
|
336
|
+
const cancelJob = (j, why) => {
|
|
337
|
+
j.cancel = true;
|
|
338
|
+
if (j.state === 'uploading' || j.state === 'queued') {
|
|
339
|
+
const w = workers.get(j.machine);
|
|
340
|
+
if (w) w.pending = w.pending.filter(x => x !== j.id);
|
|
341
|
+
finish(j, 130, why);
|
|
342
|
+
} else { const w = workers.get(j.machine); if (w) wake(w); }
|
|
343
|
+
};
|
|
344
|
+
// A removed machine: what it runs is lost to its senders, what it sent is stopped.
|
|
345
|
+
const drop = (name, why) => {
|
|
346
|
+
const w = workers.get(name);
|
|
347
|
+
workers.delete(name);
|
|
348
|
+
if (w) { w.pending = []; wake(w); }
|
|
349
|
+
let lost = 0, cancelled = 0;
|
|
350
|
+
for (const j of jobs.values()) {
|
|
351
|
+
if (j.state === 'done') continue;
|
|
352
|
+
if (j.machine === name && j.from !== name) { j.cancel = true; finish(j, j.state === 'running' ? MAYBE_RAN : LOST, why); lost++; }
|
|
353
|
+
else if (j.from === name) {
|
|
354
|
+
// Stopped there, and done here at once: a read already in flight gets 76 or 77, not the job's own exit.
|
|
355
|
+
const code = j.state === 'running' ? MAYBE_RAN : LOST;
|
|
356
|
+
cancelJob(j, `${name} sent it and was removed from the group`);
|
|
357
|
+
finish(j, code, `${name} sent it and was removed from the group`);
|
|
358
|
+
cancelled++;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
return { lost, cancelled };
|
|
362
|
+
};
|
|
363
|
+
// Jobs for the same project on their way to a machine will take its free
|
|
364
|
+
// copies before the machine's next report can say so.
|
|
365
|
+
const claimed = (need, skip) => {
|
|
366
|
+
const out = {};
|
|
367
|
+
for (const j of jobs.values()) {
|
|
368
|
+
if (j === skip || j.state === 'done' || j.from !== need.from || j.root !== need.root) continue;
|
|
369
|
+
const w = workers.get(j.machine);
|
|
370
|
+
if (w && !(w.running || []).includes(j.id)) out[j.machine] = (out[j.machine] || 0) + 1;
|
|
371
|
+
}
|
|
372
|
+
return out;
|
|
373
|
+
};
|
|
374
|
+
const pub = j => ({ id: j.id, res: j.res, cmd: j.cmd, who: j.who, agent: j.agent, from: j.from, machine: j.machine, state: j.state,
|
|
375
|
+
code: j.code, purpose: j.purpose, created: j.created, doneAt: j.doneAt || null, mem: j.mem });
|
|
376
|
+
// A machine limited with dibs limit sees other machines' work without what
|
|
377
|
+
// it runs or why: resource, who and times only. Admin and unlimited tokens see all.
|
|
378
|
+
const limited = who => !who.admin && !!trust.only(who.name);
|
|
379
|
+
const cannotSend = (name, res) => {
|
|
380
|
+
const s = trust.sends(name);
|
|
381
|
+
if (!s || res.every(r => s.includes(r))) return null;
|
|
382
|
+
return `${name} ${s.length ? `may only send ${s.join(', ')} jobs` : 'may not send jobs'} to other machines (dibs limit on the coordinator)`;
|
|
383
|
+
};
|
|
384
|
+
const jobsFor = (who, js) => js.map(pub).map(j => (limited(who) && j.from !== who.name && j.machine !== who.name ? bare(j) : j));
|
|
385
|
+
const boardFor = (who, w) => (!w.board || !limited(who) || w.name === who.name ? w.board || null
|
|
386
|
+
: { ...w.board, held: (w.board.held || []).map(bare), waiting: (w.board.waiting || []).map(bare) });
|
|
387
|
+
|
|
388
|
+
const routes = {
|
|
389
|
+
'GET /hello': () => ({ version: VERSION, machines: [...workers.values()].filter(w => !fits(w, {}, now())).map(w => w.name) }),
|
|
390
|
+
|
|
391
|
+
'GET /machines': (req, j, q, resp, who) => ({ now: now(), version: VERSION, started,
|
|
392
|
+
machines: [...workers.values()].map(w => ({ ...w, pending: undefined, wake: undefined, board: undefined, lost: !!fits(w, {}), ondemand: vmOf(w),
|
|
393
|
+
// A file lease's path says what's being worked on, and a copy's name which projects: not for a limited machine.
|
|
394
|
+
...(limited(who) && w.name !== who.name && { busy: bareBusy(w.busy), copies: undefined }) })),
|
|
395
|
+
jobs: jobsFor(who, [...jobs.values()]),
|
|
396
|
+
invited: Object.entries(trust.reg.machines).filter(([n]) => !workers.has(n)).map(([name, m]) => ({ name, invited: m.invited, joined: m.joined, paired: m.paired || null })),
|
|
397
|
+
removed: Object.entries(trust.reg.removed).map(([name, r]) => ({ name, at: r.at, why: r.why })),
|
|
398
|
+
limits: trust.reg.limits, sends: trust.reg.sends }),
|
|
399
|
+
|
|
400
|
+
// Every machine's board, as of its last check-in, for plain `dibs`.
|
|
401
|
+
'GET /board': (req, j, q, resp, who) => ({ now: now(), version: VERSION,
|
|
402
|
+
machines: [...workers.values()].map(w => ({ name: w.name, os: w.os, cores: w.cores, load: w.load, memFree: w.memFree, diskFree: w.diskFree,
|
|
403
|
+
version: w.version, lost: !!fits(w, {}), age: now() - (w.boardAt || w.seen), board: boardFor(who, w), ondemand: vmOf(w) })),
|
|
404
|
+
jobs: jobsFor(who, [...jobs.values()].filter(j => j.state !== 'done')) }),
|
|
405
|
+
|
|
406
|
+
'POST /place': async (req, j, q, resp, who) => {
|
|
407
|
+
const need = await jsonBody(req);
|
|
408
|
+
if (!who.admin) need.from = who.name;
|
|
409
|
+
if (!Array.isArray(need.res) || !need.res.length) throw fail(400, 'name a resource');
|
|
410
|
+
const no = !who.admin && cannotSend(who.name, need.res);
|
|
411
|
+
if (no && need.on && need.on !== need.from) throw fail(409, no);
|
|
412
|
+
if (no) return { machine: need.from, why: no };
|
|
413
|
+
const p = place(workers, { ...need, fromOs: workers.get(need.from)?.os ?? need.fromOs, claimed: claimed(need) });
|
|
414
|
+
// Invited but never joined reads as "no machine named mini" to placement, while dibs machines lists it.
|
|
415
|
+
if (p.error && need.on && !workers.get(need.on) && trust.has(need.on))
|
|
416
|
+
throw fail(409, `${need.on} was invited but hasn't joined yet: run the join line dibs invite printed on ${need.on}, then dibs service install worker there`);
|
|
417
|
+
if (p.error) throw fail(409, p.error);
|
|
418
|
+
return p;
|
|
419
|
+
},
|
|
420
|
+
|
|
421
|
+
'POST /jobs': async (req, j0, q, resp, who) => {
|
|
422
|
+
const m = await jsonBody(req);
|
|
423
|
+
if (!Array.isArray(m.cmd) || !m.cmd.length || !Array.isArray(m.res) || !m.res.length || !m.machine)
|
|
424
|
+
throw fail(400, 'a job needs res, cmd and machine');
|
|
425
|
+
if (!who.admin && m.from !== who.name) throw fail(403, `this machine's token is for ${who.name}; it can't send jobs as ${m.from}`);
|
|
426
|
+
if (!trust.current(who)) throw fail(401, `${who.name} was removed from the group`); // kicked while the body arrived
|
|
427
|
+
const cant = !who.admin && cannotSend(who.name, m.res);
|
|
428
|
+
if (cant) throw fail(403, cant);
|
|
429
|
+
const no = allowed(workers.get(m.machine) || { name: m.machine, only: trust.only(m.machine) }, m);
|
|
430
|
+
if (no) throw fail(409, no);
|
|
431
|
+
const j = { ...m, id: `${boot}-${++seq}`, state: 'uploading', created: now(), seen: now(), out: [], outBytes: 0, base: 0, next: 0, dropped: 0, code: null, artifacts: false };
|
|
432
|
+
jobs.set(j.id, j);
|
|
433
|
+
log(`job ${j.id} ${j.res.join(',')} from ${j.agent || j.who}@${j.from} for ${j.machine}: ${j.cmd.join(' ').slice(0, 80)}`);
|
|
434
|
+
return { id: j.id, machine: j.machine };
|
|
435
|
+
},
|
|
436
|
+
|
|
437
|
+
'PUT /jobs/:id/bundle': async (req, j) => {
|
|
438
|
+
if (j.state !== 'uploading' || j.receiving) throw fail(409, 'already sent');
|
|
439
|
+
// A slow upload is the sender at work, not a sender gone.
|
|
440
|
+
j.receiving = true;
|
|
441
|
+
req.on('data', () => { j.seen = now(); });
|
|
442
|
+
let buf;
|
|
443
|
+
try { buf = await body(req, MAX_UPLOAD); } finally { j.receiving = false; }
|
|
444
|
+
if (j.state !== 'uploading') throw fail(409, 'the job was stopped while it uploaded');
|
|
445
|
+
fs.mkdirSync(jobDir(j.id), { recursive: true });
|
|
446
|
+
fs.writeFileSync(path.join(jobDir(j.id), 'bundle.tgz'), buf);
|
|
447
|
+
j.seen = now();
|
|
448
|
+
assign(j);
|
|
449
|
+
return { ok: true, machine: j.machine };
|
|
450
|
+
},
|
|
451
|
+
|
|
452
|
+
'GET /jobs/:id/out': async (req, j, q, resp) => {
|
|
453
|
+
j.seen = now();
|
|
454
|
+
// Picked up after a restart, its output starts over at 0: number it on
|
|
455
|
+
// from where its sender had read to, so nothing is skipped or repeated.
|
|
456
|
+
if (j.adopted && !j.synced) {
|
|
457
|
+
j.synced = true;
|
|
458
|
+
const shift = Math.max(0, (Number(q.get('after')) || 0) - j.base);
|
|
459
|
+
j.base += shift; j.next += shift;
|
|
460
|
+
}
|
|
461
|
+
const after = Math.max(Number(q.get('after')) || 0, j.base);
|
|
462
|
+
// A read held open is a sender still there, however quiet the job: it counts as reading.
|
|
463
|
+
j.readers = (j.readers || 0) + 1;
|
|
464
|
+
try { if (j.next <= after && j.state !== 'done') await waitFor(j, OUT_HOLD, resp); } finally { j.readers--; }
|
|
465
|
+
j.seen = now();
|
|
466
|
+
const from = Math.max(Number(q.get('after')) || 0, j.base);
|
|
467
|
+
const gap = Number(q.get('after')) < j.base ? j.dropped : 0;
|
|
468
|
+
return { chunks: j.out.slice(from - j.base).map(([s, d]) => [s, d.toString('base64')]), next: j.next, gap,
|
|
469
|
+
state: j.state, machine: j.machine, code: j.code, why: j.why, artifacts: j.artifacts };
|
|
470
|
+
},
|
|
471
|
+
|
|
472
|
+
'POST /jobs/:id/cancel': (req, j) => {
|
|
473
|
+
cancelJob(j, 'stopped before it started');
|
|
474
|
+
return { ok: true };
|
|
475
|
+
},
|
|
476
|
+
|
|
477
|
+
// Workers.
|
|
478
|
+
'POST /worker/beat': async (req, j, q, resp, who) => {
|
|
479
|
+
const info = await jsonBody(req);
|
|
480
|
+
if (!info.name) throw fail(400, 'a worker needs a name');
|
|
481
|
+
if (!who.admin && info.name !== who.name) throw fail(403, `this machine's token is for ${who.name}, so it can't take jobs as ${info.name}. Drop --name, or join again with --name ${who.name}`);
|
|
482
|
+
if (!trust.current(who)) throw fail(401, `${who.name} was removed from the group`); // kicked while the body arrived
|
|
483
|
+
if (!who.admin) trust.joined(who.name);
|
|
484
|
+
const w = workers.get(info.name) || { name: info.name, pending: [], assigned: 0 };
|
|
485
|
+
const fresh = !workers.has(info.name) || w.lost || now() - w.seen > WORKER_LOST;
|
|
486
|
+
if (typeof info.name !== 'string') throw fail(400, 'a worker needs a name');
|
|
487
|
+
for (const k of REPORT) if (k in info) w[k] = info[k];
|
|
488
|
+
for (const k of REPORT_NUM) w[k] = Number.isFinite(info[k]) ? info[k] : k === 'diskFree' ? null : w[k] ?? 0;
|
|
489
|
+
if (!Array.isArray(w.running)) w.running = [];
|
|
490
|
+
if (!w.busy || typeof w.busy !== 'object') w.busy = {};
|
|
491
|
+
Object.assign(w, { seen: now(), boardAt: now(), lost: false, only: trust.only(info.name) });
|
|
492
|
+
workers.set(w.name, w);
|
|
493
|
+
if (fresh) log(`machine ${w.name} (${w.os}, ${w.cores} cores) is taking jobs`);
|
|
494
|
+
const running = new Set(w.running);
|
|
495
|
+
// Jobs it runs that this coordinator never heard of were sent before it
|
|
496
|
+
// restarted: pick them up again, so their output and exit code still reach
|
|
497
|
+
// the sender, which waits for that (src/remote.mjs follow).
|
|
498
|
+
for (const x of Array.isArray(info.jobs) ? info.jobs : []) adopt(w, x, running);
|
|
499
|
+
// Jobs the worker no longer runs but we think it does ended with it (it restarted).
|
|
500
|
+
for (const j of jobs.values())
|
|
501
|
+
if (j.machine === w.name && j.state === 'running' && !running.has(j.id) && now() - j.started > 5000) finish(j, MAYBE_RAN, `${w.name} restarted while running it`);
|
|
502
|
+
const answer = () => {
|
|
503
|
+
const cancel = [...running].filter(id => { const j = jobs.get(id); return !j || j.cancel || j.state === 'done'; });
|
|
504
|
+
// An on-demand VM's worker gets jobs only once the VM is up and the worker is this
|
|
505
|
+
// version: one boat's snapshot brought back on the old dibs is about to be replaced
|
|
506
|
+
// (src/ondemand.mjs WORKER), and a job it took would die with it.
|
|
507
|
+
const ready = !w.ondemand || (w.ondemand.state === 'running' && w.version === VERSION);
|
|
508
|
+
const give = ready ? w.pending.splice(0).map(id => jobs.get(id)).filter(j => j && j.state === 'queued') : [];
|
|
509
|
+
for (const j of give) Object.assign(j, { state: 'running', started: now() });
|
|
510
|
+
return { cancel, jobs: give.map(j => ({ ...pub(j), cwdRel: j.cwdRel, files: j.files, bring: j.bring, root: j.root, label: j.label,
|
|
511
|
+
prio: j.prio, by: j.by, est: j.est, mem: j.mem, askedMem: j.askedMem, cpu: j.cpu, disk: j.disk, ports: j.ports, wait: j.wait, maxWait: j.maxWait, stayOn: j.stayOn, rule: j.rule, repo: j.repo })) };
|
|
512
|
+
};
|
|
513
|
+
hooks.up?.(w);
|
|
514
|
+
let a = answer();
|
|
515
|
+
if (!a.jobs.length && !a.cancel.length) { await waitFor(w, BEAT_HOLD, resp); w.seen = now(); a = answer(); }
|
|
516
|
+
return a;
|
|
517
|
+
},
|
|
518
|
+
|
|
519
|
+
'GET /jobs/:id/bundle': (req, j) => fs.readFileSync(path.join(jobDir(j.id), 'bundle.tgz')),
|
|
520
|
+
|
|
521
|
+
'POST /jobs/:id/out': async (req, j) => {
|
|
522
|
+
const { chunks } = await jsonBody(req);
|
|
523
|
+
for (const [s, d] of chunks || []) append(j, s === 2 ? 2 : 1, Buffer.from(d, 'base64'));
|
|
524
|
+
return { cancel: !!j.cancel };
|
|
525
|
+
},
|
|
526
|
+
|
|
527
|
+
'PUT /jobs/:id/artifacts': async (req, j) => {
|
|
528
|
+
const buf = await body(req, MAX_UPLOAD);
|
|
529
|
+
fs.mkdirSync(jobDir(j.id), { recursive: true });
|
|
530
|
+
fs.writeFileSync(path.join(jobDir(j.id), 'artifacts.tgz'), buf);
|
|
531
|
+
j.artifacts = true;
|
|
532
|
+
return { ok: true };
|
|
533
|
+
},
|
|
534
|
+
|
|
535
|
+
'GET /jobs/:id/artifacts': (req, j) => {
|
|
536
|
+
if (!j.artifacts) throw fail(404, 'the job brought nothing back');
|
|
537
|
+
return fs.readFileSync(path.join(jobDir(j.id), 'artifacts.tgz'));
|
|
538
|
+
},
|
|
539
|
+
|
|
540
|
+
'POST /jobs/:id/done': async (req, j) => {
|
|
541
|
+
const { code, why } = await jsonBody(req);
|
|
542
|
+
finish(j, Number.isInteger(code) ? code : 1, why);
|
|
543
|
+
return { ok: true };
|
|
544
|
+
},
|
|
545
|
+
|
|
546
|
+
// The coordinator's own machine only (checked in handle).
|
|
547
|
+
'POST /admin/invite': async req => {
|
|
548
|
+
const { name } = await jsonBody(req);
|
|
549
|
+
if (!NAME.test(name || '')) throw fail(400, 'a machine name is letters, digits, dots, dashes and underscores');
|
|
550
|
+
if (name === self) throw fail(409, `${name} is the coordinator's own machine; it uses the token in its remote.json`);
|
|
551
|
+
const replaced = trust.has(name);
|
|
552
|
+
const stopped = replaced ? drop(name, `${name} was given a new token, so the job was stopped`) : { lost: 0, cancelled: 0 };
|
|
553
|
+
if (replaced) trust.revoke(name, `${name} was given a new token with dibs invite, so this one no longer works. Run the join line it printed on ${name}`);
|
|
554
|
+
const token = trust.invite(name);
|
|
555
|
+
log(`invited ${name}${replaced ? ' (its old token no longer works)' : ''}`);
|
|
556
|
+
return { name, token, url: joinUrl(), replaced, ...stopped };
|
|
557
|
+
},
|
|
558
|
+
'POST /admin/pair': async req => {
|
|
559
|
+
const { name } = await jsonBody(req);
|
|
560
|
+
if (name != null && !NAME.test(name)) throw fail(400, 'a machine name is letters, digits, dots, dashes and underscores');
|
|
561
|
+
if (name === self) throw fail(409, `${name} is the coordinator's own machine`);
|
|
562
|
+
const code = newCode();
|
|
563
|
+
if (open().length >= MAX_CODES) codes.shift();
|
|
564
|
+
const c = { id: crypto.randomBytes(4).toString('hex'), key: codeKey(code), exp: now() + CODE_LIFE, name: name || null, made: now() };
|
|
565
|
+
codes.push(c);
|
|
566
|
+
findable();
|
|
567
|
+
log(`pairing code ${c.id} open for ${CODE_LIFE / 6e4} minutes${c.name ? `, for ${c.name}` : ''}`);
|
|
568
|
+
return { code, id: c.id, exp: c.exp, name: c.name, urls: addrs(), port };
|
|
569
|
+
},
|
|
570
|
+
'GET /admin/pairs': () => ({ now: now(), codes: open().map(c => ({ id: c.id, name: c.name, exp: c.exp, made: c.made })), machines: machineList() }),
|
|
571
|
+
'POST /admin/unpair': async req => {
|
|
572
|
+
const { id } = await jsonBody(req);
|
|
573
|
+
const gone = open().filter(c => id === 'all' || c.id === id);
|
|
574
|
+
for (const c of gone) codes.splice(codes.indexOf(c), 1);
|
|
575
|
+
unfindable();
|
|
576
|
+
return { removed: gone.length };
|
|
577
|
+
},
|
|
578
|
+
'POST /admin/kick': async req => {
|
|
579
|
+
const { name } = await jsonBody(req);
|
|
580
|
+
if (!trust.has(name)) throw fail(404, `no invited machine named ${name}. Invited: ${Object.keys(trust.reg.machines).join(', ') || 'none'}`);
|
|
581
|
+
trust.revoke(name, `${name} was removed from the group with dibs kick. To bring it back: dibs pair --machine on the coordinator, then dibs join <code> on ${name}`);
|
|
582
|
+
const r = drop(name, `${name} was removed from the group (dibs kick), so the job was stopped`);
|
|
583
|
+
log(`removed ${name}: ${r.lost} running there reported lost, ${r.cancelled} it sent stopped`);
|
|
584
|
+
return { name, ...r };
|
|
585
|
+
},
|
|
586
|
+
'POST /admin/limit': async req => {
|
|
587
|
+
const { name, only, sends } = await jsonBody(req);
|
|
588
|
+
if (!NAME.test(name || '')) throw fail(400, 'name a machine');
|
|
589
|
+
const names = x => Array.isArray(x) && x.every(r => typeof r === 'string' && r);
|
|
590
|
+
if (only != null && (!names(only) || !only.length)) throw fail(400, '--only takes resource names, e.g. --only test,heavy');
|
|
591
|
+
if (sends != null && !names(sends)) throw fail(400, '--sends takes resource names, e.g. --sends test,heavy, or none');
|
|
592
|
+
trust.limit(name, only, sends);
|
|
593
|
+
const w = workers.get(name);
|
|
594
|
+
if (w) w.only = trust.only(name);
|
|
595
|
+
log(`${name}: takes ${trust.only(name)?.join(', ') || 'any'} jobs, sends ${trust.sends(name) ? trust.sends(name).join(', ') || 'none' : 'any'}`);
|
|
596
|
+
return { name, only: trust.only(name), sends: trust.sends(name) };
|
|
597
|
+
},
|
|
598
|
+
};
|
|
599
|
+
// Which side of a job each route belongs to.
|
|
600
|
+
const OWNER = { 'GET /jobs/:id/out': 'from', 'POST /jobs/:id/cancel': 'from', 'GET /jobs/:id/artifacts': 'from', 'PUT /jobs/:id/bundle': 'from',
|
|
601
|
+
'GET /jobs/:id/bundle': 'machine', 'POST /jobs/:id/out': 'machine', 'PUT /jobs/:id/artifacts': 'machine', 'POST /jobs/:id/done': 'machine' };
|
|
602
|
+
|
|
603
|
+
const handle = async (req, resp) => {
|
|
604
|
+
try {
|
|
605
|
+
const pre = pairing[`${req.method} ${new URL(req.url, 'http://x').pathname}`];
|
|
606
|
+
if (pre) return send(resp, 200, await pre(req));
|
|
607
|
+
const who = trust.who(req);
|
|
608
|
+
if (who.error) return send(resp, 401, { error: who.error });
|
|
609
|
+
const u = new URL(req.url, 'http://x');
|
|
610
|
+
const m = u.pathname.match(/^\/jobs\/([\w-]+)\/(\w+)$/);
|
|
611
|
+
const key = `${req.method} ${m ? `/jobs/:id/${m[2]}` : u.pathname}`;
|
|
612
|
+
const h = routes[key];
|
|
613
|
+
if (!h) return send(resp, 404, { error: `no such route ${key}` });
|
|
614
|
+
let j;
|
|
615
|
+
if (m) { j = jobs.get(m[1]); if (!j) return send(resp, 404, { error: `no job ${m[1]}` }); }
|
|
616
|
+
if (!who.admin && m && j[OWNER[key]] !== who.name) return send(resp, 403, { error: `job ${j.id} isn't ${who.name}'s` });
|
|
617
|
+
if (!who.admin && u.pathname.startsWith('/admin/')) return send(resp, 403, { error: "only the coordinator's own machine can do that. Run it there" });
|
|
618
|
+
const out = await h(req, j, u.searchParams, resp, who);
|
|
619
|
+
send(resp, 200, out);
|
|
620
|
+
} catch (e) {
|
|
621
|
+
send(resp, e.status || 500, { error: e.status ? e.message : `coordinator error: ${e.message}` });
|
|
622
|
+
if (!e.status) log(`error on ${req.method} ${req.url}: ${e.stack}`);
|
|
623
|
+
}
|
|
624
|
+
};
|
|
625
|
+
const server = () => {
|
|
626
|
+
const s = http.createServer(handle);
|
|
627
|
+
s.requestTimeout = 0; // uploads of big working copies take a while
|
|
628
|
+
s.headersTimeout = 30e3;
|
|
629
|
+
return s;
|
|
630
|
+
};
|
|
631
|
+
|
|
632
|
+
// Machines that stop reporting take their jobs with them; senders that stop
|
|
633
|
+
// reading get their jobs stopped; old jobs are cleaned up.
|
|
634
|
+
const sweep = setInterval(() => {
|
|
635
|
+
const t = now();
|
|
636
|
+
for (const w of workers.values()) {
|
|
637
|
+
if (!reporting(w) || w.lost || t - w.seen <= WORKER_LOST) continue;
|
|
638
|
+
w.lost = true;
|
|
639
|
+
log(`machine ${w.name} stopped reporting`);
|
|
640
|
+
for (const id of w.pending.splice(0)) { const j = jobs.get(id); if (j) { w.assigned--; assign(j); } }
|
|
641
|
+
for (const j of jobs.values()) if (j.machine === w.name && j.state === 'running') finish(j, MAYBE_RAN, `${w.name} stopped reporting while running the job`);
|
|
642
|
+
}
|
|
643
|
+
for (const j of jobs.values()) {
|
|
644
|
+
if (j.state !== 'done' && !j.cancel && !j.receiving && !j.readers && t - j.seen > CLIENT_LOST) {
|
|
645
|
+
j.cancel = true;
|
|
646
|
+
log(`job ${j.id}: nobody is reading its output, stopping it`);
|
|
647
|
+
if (j.state !== 'running') finish(j, 130, 'the sender went away');
|
|
648
|
+
else {
|
|
649
|
+
// A sender that was only slow or asleep reads again later: it's told why
|
|
650
|
+
// its job ended early and brought nothing back.
|
|
651
|
+
j.why = `the coordinator stopped the job: nothing read its output for ${dur(CLIENT_LOST)}`;
|
|
652
|
+
const w = workers.get(j.machine);
|
|
653
|
+
if (w) wake(w);
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
if (j.state === 'done' && t - j.doneAt > KEEP_DONE) {
|
|
657
|
+
jobs.delete(j.id);
|
|
658
|
+
fs.rmSync(jobDir(j.id), { recursive: true, force: true });
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
unfindable();
|
|
662
|
+
}, Math.min(5000, WORKER_LOST / 4));
|
|
663
|
+
sweep.unref();
|
|
664
|
+
// A job not yet started, sent to another machine instead (an on-demand VM that can't be found).
|
|
665
|
+
const move = (j, name, why) => {
|
|
666
|
+
const w = workers.get(name);
|
|
667
|
+
j.machine = name;
|
|
668
|
+
append(j, 2, Buffer.from(`dibs: ${why}\n`));
|
|
669
|
+
w.pending.push(j.id);
|
|
670
|
+
w.assigned = (w.assigned || 0) + 1;
|
|
671
|
+
wake(w);
|
|
672
|
+
};
|
|
673
|
+
return { server, workers, jobs, trust, finish, move, fits, LOST, hooks, stop: () => { clearInterval(sweep); if (finder) { try { finder.close(); } catch {} finder = null; } } };
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
// dibs serve [--listen 7420] [--bind addr]
|
|
677
|
+
export async function serve(o) {
|
|
678
|
+
{ const hole = unpatched(); if (hole) console.error(`warning: ${hole}. Then dibs service install serve on a fixed Node replaces this one.`); }
|
|
679
|
+
let rc = remoteConf();
|
|
680
|
+
const port = Number(o.listen) || (rc && Number(new URL(rc.url).port)) || DEFAULT_PORT;
|
|
681
|
+
const local = rc && /^http:\/\/(127\.0\.0\.1|localhost)(:|$)/.test(rc.url);
|
|
682
|
+
// Joined to another coordinator: serving here would drop that join without a word.
|
|
683
|
+
if (rc && !local && !o.force) die(`this machine is joined to the coordinator at ${rc.url}. To leave that group and be a coordinator here: dibs serve --force`);
|
|
684
|
+
if (rc && !local) logChange('serve --force', { left: rc.url });
|
|
685
|
+
// The coordinator's machine reaches it over loopback, with a token of its own
|
|
686
|
+
// (never the old group's). Saved only once it listens, so a serve that fails changes nothing.
|
|
687
|
+
const fresh = !local && { url: `http://127.0.0.1:${port}`, token: newToken(), name: rc?.name || shortHost() };
|
|
688
|
+
if (fresh) rc = fresh;
|
|
689
|
+
const listening = new Map();
|
|
690
|
+
const joinUrl = () => { const ip = [...listening.keys()].find(h => h !== '127.0.0.1'); return ip ? `http://${ip}:${port}` : null; };
|
|
691
|
+
let made;
|
|
692
|
+
const addrs = () => [...listening.keys()].filter(h => h !== '127.0.0.1').map(h => `http://${h}:${port}`);
|
|
693
|
+
try { made = makeServer({ token: rc.token, log, self: rc.name, joinUrl, port, addrs }); } catch (e) { die(e.message); }
|
|
694
|
+
const { server } = made;
|
|
695
|
+
const listen = host => new Promise(resolve => {
|
|
696
|
+
if (listening.has(host)) return resolve(true);
|
|
697
|
+
const s = server();
|
|
698
|
+
s.once('error', e => { log(`can't listen on ${host}:${port}: ${e.message}`); resolve(false); });
|
|
699
|
+
s.listen(port, host, () => { listening.set(host, s); resolve(true); });
|
|
700
|
+
});
|
|
701
|
+
const up = host => log(`listening on http://${host}:${port}`);
|
|
702
|
+
const first = o.bind || '127.0.0.1';
|
|
703
|
+
if (!await listen(first)) die(o.bind ? `can't listen on ${o.bind}:${port}` : `port ${port} is taken. Is a coordinator already running? (dibs machines)`);
|
|
704
|
+
// "listening" comes after remote.json is saved: whatever waits for the line
|
|
705
|
+
// and then reads the file (a test on 2026-10-16) found it missing.
|
|
706
|
+
if (fresh) saveRemote(fresh);
|
|
707
|
+
up(first);
|
|
708
|
+
fs.rmSync(path.join(HOME, 'jobs'), { recursive: true, force: true }); // jobs from a previous run are gone
|
|
709
|
+
const announce = ip => {
|
|
710
|
+
log(`other machines can reach http://${ip}:${port}. Give each its own token: dibs invite <name> on this machine`);
|
|
711
|
+
};
|
|
712
|
+
if (!o.bind) {
|
|
713
|
+
const ts = tailscaleIp();
|
|
714
|
+
if (ts && await listen(ts)) { up(ts); announce(ts); }
|
|
715
|
+
else log('no Tailscale address yet, so only this machine can reach the coordinator. It starts listening on Tailscale as soon as it comes up.');
|
|
716
|
+
setInterval(async () => {
|
|
717
|
+
const ip = tailscaleIp();
|
|
718
|
+
if (ip && !listening.has(ip) && await listen(ip)) { up(ip); announce(ip); }
|
|
719
|
+
}, 30e3);
|
|
720
|
+
} else if (o.bind !== '127.0.0.1') announce(o.bind);
|
|
721
|
+
log(`this machine's token is in ${REMOTE} and only works here; other machines' tokens are in ${MACHINES} (hashed)`);
|
|
722
|
+
let od = null;
|
|
723
|
+
try {
|
|
724
|
+
const list = ondemandOf(loadConfig());
|
|
725
|
+
if (list.length) {
|
|
726
|
+
od = ondemand(list, made, { port, log });
|
|
727
|
+
log(`on-demand machines: ${list.map(m => `${m.name} (the ${m.provider} VM whose row in ${m.registry} has "${m.match}" in its Use${m.owner ? `, owned by ${m.owner}` : ''})`).join(', ')}`);
|
|
728
|
+
await od.reconcile();
|
|
729
|
+
}
|
|
730
|
+
} catch (e) { log(`on-demand machines are off: ${e.message}`); }
|
|
731
|
+
// The disk warnings and cleaning come from the throttle watcher (src/cool.mjs); while it
|
|
732
|
+
// isn't running, the coordinator sends them, so one dead service can't silence them.
|
|
733
|
+
let covering = false;
|
|
734
|
+
const backup = setInterval(() => {
|
|
735
|
+
const down = watcherDown();
|
|
736
|
+
if (down !== covering) { covering = down; log(down ? "the throttle watcher isn't running, so the coordinator sends the low-disk notes and clears caches meanwhile" : 'the throttle watcher is back; it sends the low-disk notes again'); }
|
|
737
|
+
if (down) hogsOnce(loadConfig(), machine());
|
|
738
|
+
}, BACKUP_EVERY);
|
|
739
|
+
backup.unref();
|
|
740
|
+
const stop = async () => { if (od) await od.close(); for (const s of listening.values()) s.close(); process.exit(0); };
|
|
741
|
+
process.on('SIGINT', stop); process.on('SIGTERM', stop);
|
|
742
|
+
}
|