@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/ondemand.mjs
ADDED
|
@@ -0,0 +1,572 @@
|
|
|
1
|
+
// On-demand machines: cloud VMs that sleep until a job needs them, then wake,
|
|
2
|
+
// take it, and stop again once idle, because every second one runs is billed.
|
|
3
|
+
// Configured on the coordinator (config.json), by a row in a registry of who
|
|
4
|
+
// owns which VM, never by id (ids change):
|
|
5
|
+
// "machines": { "ondemand": [{ "name": "boat-1", "provider": "boat", "registry": "~/boat/VMS.md", "match": "dibs", "owner": "alex-3b" }] }
|
|
6
|
+
// The registry is a markdown table (VM | Owner | Shared with | Use | Notes).
|
|
7
|
+
// dibs takes the one row whose Use mentions match (and whose Owner is owner,
|
|
8
|
+
// when given), checks that VM exists, and keeps that row's Notes current.
|
|
9
|
+
// The coordinator lists each as a machine that is asleep. A job sent --on it,
|
|
10
|
+
// or --anywhere when its wait here would outlast waking the VM, wakes it:
|
|
11
|
+
// boat resume, a reverse forward so the VM's 127.0.0.1:<port> reaches this
|
|
12
|
+
// coordinator with no Tailscale, dibs and a pinned Node installed there when
|
|
13
|
+
// missing or out of date, a fresh invite token, then a worker. After idleStop
|
|
14
|
+
// (30s unless set, 3m at most) with nothing running or sent to it, it's
|
|
15
|
+
// stopped. boat's own auto-stop
|
|
16
|
+
// (one hour) stays as the backstop, and is pushed back only while a job runs.
|
|
17
|
+
//
|
|
18
|
+
// With "create": { "max": "large" } it also has a temporary sibling, <name>-temp,
|
|
19
|
+
// for jobs bigger than it (more --mem or --cpu): a VM made for them in the
|
|
20
|
+
// smallest size that fits (boat new --type), listed in the registry while it
|
|
21
|
+
// lives, and deleted, row and all, once its queue is empty or anything fails.
|
|
22
|
+
// One left behind by a crash is deleted when the coordinator starts.
|
|
23
|
+
//
|
|
24
|
+
// Only boat is supported. The boat CLI is `boat` on PATH, or DIBS_BOAT.
|
|
25
|
+
import fs from 'node:fs';
|
|
26
|
+
import os from 'node:os';
|
|
27
|
+
import path from 'node:path';
|
|
28
|
+
import { spawn, execFile } from 'node:child_process';
|
|
29
|
+
import { fileURLToPath } from 'node:url';
|
|
30
|
+
import { HOME } from './config.mjs';
|
|
31
|
+
import { event } from './events.mjs';
|
|
32
|
+
import { ms, now, log } from './util.mjs';
|
|
33
|
+
import { VERSION } from './version.mjs';
|
|
34
|
+
|
|
35
|
+
const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
36
|
+
// The VM's side. Everything on it may vanish: dibs keeps nothing there it can't put back.
|
|
37
|
+
const VM_HOME = '/home/user';
|
|
38
|
+
const APP = `${VM_HOME}/dibs-app`;
|
|
39
|
+
const NODE_DIR = `${VM_HOME}/.dibs-node`;
|
|
40
|
+
// Node for the VM, pinned with its checksum from nodejs.org/dist/v22.23.4/SHASUMS256.txt.
|
|
41
|
+
// 22.23.4 fixes the Brotli hole CVE-2026-111497 (see nodecheck.mjs). A VM on another
|
|
42
|
+
// version reinstalls at its next wake.
|
|
43
|
+
export const NODE = { version: 'v22.23.4', file: 'node-v22.23.4-linux-x64.tar.xz', sha256: '1805bcd35e6815559bd2eb97db438d3fdb0eb3a5e6a977b7c1badca76337e9ce' };
|
|
44
|
+
// A guess at waking until one has been measured; the measured one replaces it.
|
|
45
|
+
const RESUME_GUESS = 45e3;
|
|
46
|
+
// Sending a working copy up, a rough figure for the wake decision.
|
|
47
|
+
const UPLOAD_GUESS = 20e3;
|
|
48
|
+
// What one job ahead in a line is worth in wait, for --anywhere's wake decision:
|
|
49
|
+
// placement counts jobs ahead (60 points each), not minutes.
|
|
50
|
+
const JOB_AHEAD = 3 * 6e4;
|
|
51
|
+
// The worker has this long after the VM is up to check in, or the wake failed.
|
|
52
|
+
const FIRST_BEAT = 3 * 6e4;
|
|
53
|
+
// While a job runs, the VM's own auto-stop is kept at least this far off.
|
|
54
|
+
const EXTEND_TO = 3600, EXTEND_EVERY = 30 * 6e4;
|
|
55
|
+
const TICK = 5e3;
|
|
56
|
+
// While asleep, which VM it is and whether boat still has it is looked up this often, for the board and placement.
|
|
57
|
+
const RECHECK = 5 * 6e4;
|
|
58
|
+
const STATES_UP = new Set(['running', 'idle', 'up', 'ready', 'starting', 'resuming', 'pending']);
|
|
59
|
+
|
|
60
|
+
// The on-demand machines config.json names, checked. Throws with what's wrong.
|
|
61
|
+
export function ondemandOf(cfg) {
|
|
62
|
+
const list = cfg?.machines?.ondemand;
|
|
63
|
+
if (list == null) return [];
|
|
64
|
+
const like = '[{ "name": "boat-1", "provider": "boat", "registry": "~/boat/VMS.md", "match": "dibs" }]';
|
|
65
|
+
if (!Array.isArray(list)) throw new Error(`machines.ondemand in config.json is a list, like ${like}`);
|
|
66
|
+
return list.map((m, i) => {
|
|
67
|
+
const at = `machines.ondemand[${i}] in config.json`;
|
|
68
|
+
if (!m || typeof m !== 'object') throw new Error(`${at} is an object, like ${like}`);
|
|
69
|
+
if (!/^[\w.-]+$/.test(m.name || '')) throw new Error(`${at}: name is letters, digits, dots, dashes and underscores`);
|
|
70
|
+
if (m.provider !== 'boat') throw new Error(`${at}: provider is "boat", the only one dibs knows`);
|
|
71
|
+
if (m.id != null) throw new Error(`${at}: no id. VM ids change, so dibs finds the VM in its registry: "registry": "~/boat/VMS.md", "match": "dibs"`);
|
|
72
|
+
if (typeof m.registry !== 'string' || !m.registry) throw new Error(`${at}: registry is the file that says who owns which VM, like "~/boat/VMS.md"`);
|
|
73
|
+
if (typeof m.match !== 'string' || !m.match.trim()) throw new Error(`${at}: match is a word in the Use column of this VM's row, like "dibs"`);
|
|
74
|
+
if (m.create != null && !SIZES[m.create?.max]) throw new Error(`${at}: create is { "max": "small" }, "default" or "large": the biggest VM dibs may make for a job bigger than this one`);
|
|
75
|
+
return { name: m.name, provider: m.provider, registry: m.registry.replace(/^~(?=\/)/, os.homedir()), match: m.match.trim(), owner: m.owner || null,
|
|
76
|
+
idleStop: idleStopOf(m.idleStop, at), cores: m.cores ?? 4, memTotal: m.mem ? Number(m.mem) : 8 * 1024 ** 3, create: m.create ? { max: m.create.max } : null };
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// How long it may sit idle before it's stopped. Every idle second is billed:
|
|
81
|
+
// 30s by default (enough for a script's next job to follow its last), 3m at most.
|
|
82
|
+
const IDLE_DEFAULT = 30e3, IDLE_MAX = 3 * 6e4;
|
|
83
|
+
// boat's sizes, smallest first (boat new --help). xlarge needs a plan this account isn't on.
|
|
84
|
+
const SIZES = { small: { cores: 2, mem: 4 * 1024 ** 3 }, default: { cores: 4, mem: 8 * 1024 ** 3 }, large: { cores: 8, mem: 16 * 1024 ** 3 } };
|
|
85
|
+
// The smallest size up to max that takes every job given, or null.
|
|
86
|
+
export function sizeFor(need, max) {
|
|
87
|
+
const names = Object.keys(SIZES);
|
|
88
|
+
return names.slice(0, names.indexOf(max) + 1).find(n => need.every(j => (j.mem || 0) <= SIZES[n].mem && (j.cpu || 0) <= SIZES[n].cores)) ?? null;
|
|
89
|
+
}
|
|
90
|
+
// What a temporary VM's registry row says in Use, so dibs finds its own leftovers and nobody else's.
|
|
91
|
+
const tempUse = name => `dibs temporary VM (${name}) for a job too big for its dedicated one`;
|
|
92
|
+
function idleStopOf(v, at) {
|
|
93
|
+
const t = v == null ? IDLE_DEFAULT : ms(v);
|
|
94
|
+
if (t > IDLE_MAX) throw new Error(`${at}: idleStop is at most 3m, since every idle second is billed`);
|
|
95
|
+
return t;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// The registry's table: its rows by column name, whatever order the columns
|
|
99
|
+
// are in or columns get added ("Kind" was, 2026-10-18). [{ i, cells, get(name) }]
|
|
100
|
+
function rows(text) {
|
|
101
|
+
const lines = text.split('\n');
|
|
102
|
+
const cellsOf = line => line.trim().replace(/^\||\|$/g, '').split('|').map(c => c.trim());
|
|
103
|
+
const h = lines.findIndex(l => /^\s*\|/.test(l) && cellsOf(l).some(c => /^vm$/i.test(c)));
|
|
104
|
+
if (h < 0) return [];
|
|
105
|
+
const names = cellsOf(lines[h]).map(c => c.toLowerCase());
|
|
106
|
+
const out = [];
|
|
107
|
+
for (let i = h + 1; i < lines.length && /^\s*\|/.test(lines[i]); i++) {
|
|
108
|
+
const cells = cellsOf(lines[i]);
|
|
109
|
+
const get = name => cells[names.indexOf(name)] ?? '';
|
|
110
|
+
if (/^bx_\w+$/.test(get('vm'))) out.push({ i, cells, names, get });
|
|
111
|
+
}
|
|
112
|
+
return out;
|
|
113
|
+
}
|
|
114
|
+
// The VM this machine is: { id } or { problem }, in words. Never a guess: no
|
|
115
|
+
// row, or more than one, is a problem, and so is a VM boat doesn't have.
|
|
116
|
+
export async function findVm(c) {
|
|
117
|
+
let text;
|
|
118
|
+
try { text = fs.readFileSync(c.registry, 'utf8'); } catch (e) { return { problem: `can't read ${c.registry} (${e.code || e.message})` }; }
|
|
119
|
+
const want = c.match.toLowerCase();
|
|
120
|
+
// Not the temporary VMs dibs lists beside it: their Use says "dibs" too, and on 2026-10-20
|
|
121
|
+
// boat-1-temp's row made boat-1 unfindable, so jobs sent to boat-1 ran on the Mac.
|
|
122
|
+
const hits = rows(text).filter(r => r.get('use').toLowerCase().includes(want) && (!c.owner || r.get('owner') === c.owner) && r.get('kind').toLowerCase() !== 'temporary');
|
|
123
|
+
if (!hits.length) return { problem: `no row in ${c.registry} has "${c.match}" in its Use${c.owner ? ` with owner ${c.owner}` : ''}` };
|
|
124
|
+
if (hits.length > 1) return { problem: `${hits.length} rows in ${c.registry} have "${c.match}" in their Use (${hits.map(r => r.get('vm')).join(', ')}), so dibs won't guess` };
|
|
125
|
+
const id = hits[0].get('vm');
|
|
126
|
+
const r = await boat(['list', '--all', '--json'], { timeout: 60e3 });
|
|
127
|
+
if (r.code) return { problem: `boat list failed: ${r.err}` };
|
|
128
|
+
const vm = (json(r.out)?.sandboxes || []).find(x => x.id === id);
|
|
129
|
+
if (!vm) return { problem: `${c.registry} names ${id}, which boat doesn't have` };
|
|
130
|
+
return { id, state: vm.state };
|
|
131
|
+
}
|
|
132
|
+
// Its row's Notes, kept current: only that row's last cell, the rest of the
|
|
133
|
+
// file as it was. Written whole and renamed into place, so a reader never sees half.
|
|
134
|
+
export function noteVm(c, id, text) {
|
|
135
|
+
try {
|
|
136
|
+
const all = fs.readFileSync(c.registry, 'utf8');
|
|
137
|
+
const lines = all.split('\n');
|
|
138
|
+
const row = rows(all).find(r => r.get('vm') === id);
|
|
139
|
+
const at = row?.names.indexOf('notes');
|
|
140
|
+
if (!row || at < 0) return false;
|
|
141
|
+
const cells = [...row.cells];
|
|
142
|
+
while (cells.length <= at) cells.push('');
|
|
143
|
+
cells[at] = text.replace(/\|/g, '/').replace(/\s+/g, ' ');
|
|
144
|
+
lines[row.i] = `| ${cells.join(' | ')} |`;
|
|
145
|
+
const tmp = `${c.registry}.${process.pid}.tmp`;
|
|
146
|
+
fs.writeFileSync(tmp, lines.join('\n'));
|
|
147
|
+
fs.renameSync(tmp, c.registry);
|
|
148
|
+
return true;
|
|
149
|
+
} catch { return false; }
|
|
150
|
+
}
|
|
151
|
+
// A row added for a temporary VM, or taken out when it's deleted. Same atomic write.
|
|
152
|
+
function rewrite(registry, change) {
|
|
153
|
+
try {
|
|
154
|
+
const all = fs.readFileSync(registry, 'utf8');
|
|
155
|
+
const lines = change(all.split('\n'), rows(all));
|
|
156
|
+
if (!lines) return false;
|
|
157
|
+
const tmp = `${registry}.${process.pid}.tmp`;
|
|
158
|
+
fs.writeFileSync(tmp, lines.join('\n'));
|
|
159
|
+
fs.renameSync(tmp, registry);
|
|
160
|
+
return true;
|
|
161
|
+
} catch { return false; }
|
|
162
|
+
}
|
|
163
|
+
export function addRow(registry, cells) {
|
|
164
|
+
return rewrite(registry, (lines, rs) => {
|
|
165
|
+
if (!rs.length) return null;
|
|
166
|
+
const at = rs[rs.length - 1].i + 1;
|
|
167
|
+
const row = rs[0].names.map(n => String(cells[n] ?? '').replace(/\|/g, '/'));
|
|
168
|
+
lines.splice(at, 0, `| ${row.join(' | ')} |`);
|
|
169
|
+
return lines;
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
export const dropRow = (registry, id) => rewrite(registry, (lines, rs) => {
|
|
173
|
+
const r = rs.find(x => x.get('vm') === id);
|
|
174
|
+
if (!r) return null;
|
|
175
|
+
lines.splice(r.i, 1);
|
|
176
|
+
return lines;
|
|
177
|
+
});
|
|
178
|
+
// Temporary VMs this sibling made and a crash left listed: [id].
|
|
179
|
+
export const leftovers = (c, text) => rows(text).filter(r => r.get('kind').toLowerCase() === 'temporary' && r.get('use') === tempUse(c.name)).map(r => r.get('vm'));
|
|
180
|
+
const hhmm = (t = now()) => new Date(t).toTimeString().slice(0, 5);
|
|
181
|
+
|
|
182
|
+
// One boat call. The id always goes in, so it never acts on "the current" sandbox.
|
|
183
|
+
// An exec answers off a terminal in one JSON object ({ stdout, stderr, exitCode }):
|
|
184
|
+
// out and err are the command's own. Read raw, the wake's version check never
|
|
185
|
+
// matched, and every wake installed Node and dibs again (found 2026-10-19).
|
|
186
|
+
export function boat(args, { timeout = 60e3 } = {}) {
|
|
187
|
+
return new Promise(resolve => {
|
|
188
|
+
// --no-update first: after `--` it would go to the command run on the VM.
|
|
189
|
+
execFile(process.env.DIBS_BOAT || 'boat', ['--no-update', ...args], { timeout, maxBuffer: 16 * 1024 ** 2, encoding: 'utf8' }, (e, out, err) => {
|
|
190
|
+
const r = { code: e ? (typeof e.code === 'number' ? e.code : 1) : 0, out: out || '', err: (err || e?.message || '').trim() };
|
|
191
|
+
const j = args[0] === 'exec' && !args.includes('--detach') ? json(r.out) : null;
|
|
192
|
+
if (j && typeof j.stdout === 'string') Object.assign(r, { out: j.stdout, err: (j.stderr || r.err).trim(), code: j.exitCode ?? r.code });
|
|
193
|
+
resolve(r);
|
|
194
|
+
});
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
const json = s => { try { return JSON.parse(s); } catch { return null; } };
|
|
198
|
+
|
|
199
|
+
// boat's start quota (boat limits --json), read at most once a LIMITS_FOR. With
|
|
200
|
+
// no starts left every wake gets a 429, so dibs doesn't try: on 2026-10-19 the
|
|
201
|
+
// account's 200 daily starts ran out, and every job sent to boat-1 came back
|
|
202
|
+
// lost (76) instead of running on the Mac. Null when a start is possible, or
|
|
203
|
+
// when the quota can't be read (a wake that fails is handled anyway).
|
|
204
|
+
const LIMITS_FOR = 6e4;
|
|
205
|
+
let limits = { at: 0, why: null };
|
|
206
|
+
export async function startsBlocked() {
|
|
207
|
+
if (now() - limits.at < LIMITS_FOR) return limits.why;
|
|
208
|
+
const r = await boat(['limits', '--json'], { timeout: 20e3 });
|
|
209
|
+
const j = r.code ? null : json(r.out);
|
|
210
|
+
const day = j?.starts?.day, hour = j?.starts?.hour;
|
|
211
|
+
const until = Date.parse(j?.subscriptionCurrentPeriodEnd);
|
|
212
|
+
const why = !j ? null
|
|
213
|
+
: [j.blockedReason, j.startBlockedReason].includes('usage_depleted')
|
|
214
|
+
? `boat's compute for this billing period is used up${until ? ` (it comes back ${new Date(until).toISOString().slice(0, 10)})` : ''}`
|
|
215
|
+
: (j.canStart ?? j.starts?.canStart) === false ? "boat says no VM can start now"
|
|
216
|
+
: day?.remaining === 0 ? `boat's daily starts are used up (${day.used}/${day.limit})`
|
|
217
|
+
: hour?.remaining === 0 ? `boat's hourly starts are used up (${hour.used}/${hour.limit})` : null;
|
|
218
|
+
limits = { at: now(), why };
|
|
219
|
+
return why;
|
|
220
|
+
}
|
|
221
|
+
// How long a VM that couldn't wake is left alone: until boat's quota could have
|
|
222
|
+
// come back, or a few minutes for anything else.
|
|
223
|
+
const QUOTA_BACKOFF = 60 * 6e4, WAKE_BACKOFF = 5 * 6e4;
|
|
224
|
+
const QUOTA = /\b429\b|quota|rate.?limit|too many|used up|no VM can start/i;
|
|
225
|
+
export const cantWake = (vm, t = now()) => (vm?.cantWake && t < vm.cantWake.until ? vm.cantWake : null);
|
|
226
|
+
|
|
227
|
+
// The shell lines run on the VM. Paths are the VM's own.
|
|
228
|
+
const CHECK = `printf 'node=%s\\ndibs=%s\\n' "$(cat ${NODE_DIR}/.pinned 2>/dev/null)" "$(sed -n "s/.*VERSION = '\\\\(.*\\\\)'.*/\\\\1/p" ${APP}/src/version.mjs 2>/dev/null)"`;
|
|
229
|
+
const INSTALL_NODE = `set -e; t=$(mktemp -d); cd "$t"; curl -fsSLO https://nodejs.org/dist/${NODE.version}/${NODE.file}; `
|
|
230
|
+
+ `echo "${NODE.sha256} ${NODE.file}" | sha256sum -c -; rm -rf ${NODE_DIR}; mkdir -p ${NODE_DIR}; `
|
|
231
|
+
+ `tar -xJf ${NODE.file} -C ${NODE_DIR} --strip-components=1; echo ${NODE.version} > ${NODE_DIR}/.pinned; cd /; rm -rf "$t"`;
|
|
232
|
+
// A worker from before the VM was stopped comes back with boat's snapshot, on
|
|
233
|
+
// the old dibs and the old token. On 2026-10-20 one took a job while the VM
|
|
234
|
+
// woke, was turned away when its token was replaced, and killed the job (77);
|
|
235
|
+
// the new worker sat waiting for it to leave. So the one in worker.pid goes
|
|
236
|
+
// first, if it really is a dibs worker, and the new one starts once it's gone.
|
|
237
|
+
// It's stopped in a call of its own, finished before the new worker starts, so it can't
|
|
238
|
+
// check in after dibs starts waiting for the new one.
|
|
239
|
+
const OLD_WORKER = 5e3; // a worker ends its jobs and leaves in well under this
|
|
240
|
+
const KILL_OLD = `p=$(cat ${VM_HOME}/.dibs/worker.pid 2>/dev/null); `
|
|
241
|
+
+ `if [ -n "$p" ] && ps -ww -o args= -p "$p" 2>/dev/null | grep -q 'dibs.mjs worker'; then kill "$p"; i=0; `
|
|
242
|
+
+ `while kill -0 "$p" 2>/dev/null && [ $i -lt ${OLD_WORKER / 100} ]; do sleep 0.1; i=$((i+1)); done; kill -9 "$p" 2>/dev/null; fi; true`;
|
|
243
|
+
const WORKER = `mkdir -p ${VM_HOME}/.dibs; PATH=${NODE_DIR}/bin:$PATH; export PATH; cd ${VM_HOME}; `
|
|
244
|
+
+ `exec node ${APP}/bin/dibs.mjs worker --ephemeral >> ${VM_HOME}/.dibs/worker.log 2>&1`;
|
|
245
|
+
|
|
246
|
+
// The coordinator's side: one per configured machine. srv is makeServer's
|
|
247
|
+
// own (workers, jobs, trust); port is where this coordinator listens on loopback.
|
|
248
|
+
// clock: what idle time is measured against, so a test can move it on.
|
|
249
|
+
export function ondemand(list, srv, { port, tick = TICK, log: say = log, clock = now } = {}) {
|
|
250
|
+
const { workers, jobs, trust } = srv;
|
|
251
|
+
const vms = new Map();
|
|
252
|
+
const add = c => {
|
|
253
|
+
const vm = { ...c, id: null, problem: null, state: 'asleep', resumeMs: null, upSince: null, idleSince: null, extended: 0, forward: null, checked: 0 };
|
|
254
|
+
vms.set(c.name, vm);
|
|
255
|
+
workers.set(c.name, { name: c.name, ondemand: vm, os: 'linux', cores: c.cores, memTotal: c.memTotal, memFree: 100, load: 0, diskFree: null,
|
|
256
|
+
busy: {}, running: [], pending: [], assigned: 0, seen: 0, lost: false, only: trust.only(c.name), version: VERSION });
|
|
257
|
+
return vm;
|
|
258
|
+
};
|
|
259
|
+
for (const c of list) {
|
|
260
|
+
const vm = add(c);
|
|
261
|
+
if (!c.create) continue;
|
|
262
|
+
// Listed at the biggest size it may make; the VM it makes is the smallest that fits.
|
|
263
|
+
const max = SIZES[c.create.max];
|
|
264
|
+
vm.bigger = add({ ...c, name: `${c.name}-temp`, temp: true, of: c.name, cores: max.cores, memTotal: max.mem, over: { cores: c.cores, mem: c.memTotal } }).name;
|
|
265
|
+
}
|
|
266
|
+
const mark = (vm, state) => {
|
|
267
|
+
vm.state = state;
|
|
268
|
+
const w = workers.get(vm.name);
|
|
269
|
+
if (!w) return;
|
|
270
|
+
w.ondemand = vm;
|
|
271
|
+
// Up: its worker's check-in, held open waiting for work (src/serve.mjs), answers now with the jobs it may take.
|
|
272
|
+
if (state === 'running') for (const f of (w.wake || []).slice()) f();
|
|
273
|
+
};
|
|
274
|
+
// Which VM it is, looked up again each time it matters (a wake, a start, now and then while asleep).
|
|
275
|
+
// A temporary one is whatever dibs made, if anything.
|
|
276
|
+
const refresh = async vm => {
|
|
277
|
+
if (vm.temp) { vm.checked = now(); return { id: vm.id }; }
|
|
278
|
+
const f = await findVm(vm);
|
|
279
|
+
if (f.problem && f.problem !== vm.problem) say(`${vm.name}: ${f.problem}`);
|
|
280
|
+
Object.assign(vm, { id: f.id ?? null, problem: f.problem ?? null, checked: now() });
|
|
281
|
+
return f;
|
|
282
|
+
};
|
|
283
|
+
const busyOn = vm => {
|
|
284
|
+
const w = workers.get(vm.name);
|
|
285
|
+
return !!(w?.pending.length || w?.running?.length || [...jobs.values()].some(j => j.machine === vm.name && j.state !== 'done'));
|
|
286
|
+
};
|
|
287
|
+
|
|
288
|
+
// The reverse forward lives as long as the VM is up, started again if it drops.
|
|
289
|
+
const forward = vm => {
|
|
290
|
+
if (vm.forward || !['waking', 'running'].includes(vm.state)) return;
|
|
291
|
+
const p = spawn(process.env.DIBS_BOAT || 'boat', ['--no-update', 'forward', vm.id, '--reverse', '--local', String(port)], { stdio: 'ignore' });
|
|
292
|
+
vm.forward = p;
|
|
293
|
+
p.on('exit', () => { vm.forward = null; if (['waking', 'running'].includes(vm.state)) setTimeout(() => forward(vm), 2000).unref(); });
|
|
294
|
+
p.on('error', () => {});
|
|
295
|
+
};
|
|
296
|
+
const unforward = vm => { const p = vm.forward; vm.forward = null; try { p?.kill('SIGTERM'); } catch {} };
|
|
297
|
+
|
|
298
|
+
// Jobs waiting for a VM that can't take them go back to the machine that sent
|
|
299
|
+
// them, when it takes jobs. Lost (76) only when there's nowhere to go.
|
|
300
|
+
const sendBack = (vm, why) => {
|
|
301
|
+
for (const j of jobs.values()) {
|
|
302
|
+
if (j.machine !== vm.name || j.state === 'done' || j.state === 'running') continue;
|
|
303
|
+
if (workers.has(j.from) && !srv.fits(workers.get(j.from), j)) srv.move(j, j.from, `${vm.name} ${why}, so it runs on ${j.from}`);
|
|
304
|
+
else srv.finish(j, srv.LOST, `${vm.name} ${why}`);
|
|
305
|
+
}
|
|
306
|
+
const w = workers.get(vm.name);
|
|
307
|
+
if (w) Object.assign(w, { pending: [], assigned: 0 });
|
|
308
|
+
};
|
|
309
|
+
// Marked can't-wake until a retry time: placement skips it, a job sent --on it runs on its sender with the reason, and dibs machines says so.
|
|
310
|
+
const block = (vm, why) => {
|
|
311
|
+
vm.cantWake = { why, until: now() + (QUOTA.test(why) ? QUOTA_BACKOFF : WAKE_BACKOFF) };
|
|
312
|
+
say(`${vm.name}: can't wake (${why}); not trying again until ${new Date(vm.cantWake.until).toISOString()}`);
|
|
313
|
+
sendBack(vm, `can't wake (${why})`);
|
|
314
|
+
};
|
|
315
|
+
const fail = (vm, why) => {
|
|
316
|
+
say(`${vm.name}: ${why}`);
|
|
317
|
+
block(vm, why);
|
|
318
|
+
stop(vm, `waking failed: ${why}`);
|
|
319
|
+
};
|
|
320
|
+
|
|
321
|
+
// A temporary VM in the smallest size that takes every job waiting for it,
|
|
322
|
+
// listed in the registry before anything else happens to it.
|
|
323
|
+
const make = async vm => {
|
|
324
|
+
const w = workers.get(vm.name);
|
|
325
|
+
const waiting = (w?.pending || []).map(id => jobs.get(id)).filter(j => j && j.state !== 'done');
|
|
326
|
+
if (!waiting.length) return null;
|
|
327
|
+
// Cores only as --cpu asked: a resource's own guess never makes a bigger VM.
|
|
328
|
+
const type = sizeFor(waiting.map(j => ({ mem: j.mem, cpu: j.askedCpu ?? 0 })), vm.create.max);
|
|
329
|
+
if (!type) {
|
|
330
|
+
const max = SIZES[vm.create.max];
|
|
331
|
+
for (const id of w.pending.splice(0)) { const j = jobs.get(id); if (j && j.state !== 'done') srv.finish(j, srv.LOST, `${vm.name}: the job needs more than the biggest VM dibs may make (${vm.create.max}: ${max.cores} cores, ${max.mem / 1024 ** 3} GB)`); }
|
|
332
|
+
w.assigned = 0;
|
|
333
|
+
return null;
|
|
334
|
+
}
|
|
335
|
+
say(`${vm.name}: making a ${type} VM for a job too big for ${vm.of}`);
|
|
336
|
+
const t0 = now();
|
|
337
|
+
const r = await boat(['new', '--type', type, '--json'], { timeout: 10 * 6e4 });
|
|
338
|
+
const id = r.code ? null : r.out.match(/\bbx_[a-z0-9]+\b/)?.[0];
|
|
339
|
+
if (!id) return { problem: `boat new failed: ${r.err || r.out.trim() || 'no sandbox id in its answer'}` };
|
|
340
|
+
vm.id = id;
|
|
341
|
+
vm.resumeMs = now() - t0;
|
|
342
|
+
addRow(vm.registry, { vm: id, kind: 'temporary', owner: vm.owner || 'dibs', use: tempUse(vm.name),
|
|
343
|
+
notes: `Created ${hhmm()} by dibs (${type}); dibs deletes it, and this row, when its jobs end` });
|
|
344
|
+
Object.assign(w, { cores: SIZES[type].cores, memTotal: SIZES[type].mem });
|
|
345
|
+
vm.cantWake = null;
|
|
346
|
+
event({ kind: 'ondemand', act: 'create', name: vm.name, id, type, ms: vm.resumeMs });
|
|
347
|
+
return { id };
|
|
348
|
+
};
|
|
349
|
+
|
|
350
|
+
// Wake it: resume (or make a temporary one), forward, install what's missing, a new token, the worker.
|
|
351
|
+
const wake = async vm => {
|
|
352
|
+
if (vm.state !== 'asleep') return;
|
|
353
|
+
// No starts left on boat's account: don't try, and keep the jobs on the machines that sent them.
|
|
354
|
+
const none = await startsBlocked();
|
|
355
|
+
if (none) { block(vm, none); return; }
|
|
356
|
+
mark(vm, 'waking');
|
|
357
|
+
if (vm.temp) {
|
|
358
|
+
const m = await make(vm);
|
|
359
|
+
if (!m) { mark(vm, 'asleep'); return; }
|
|
360
|
+
vm.upSince = now();
|
|
361
|
+
if (m.problem) return fail(vm, m.problem);
|
|
362
|
+
return setup(vm);
|
|
363
|
+
}
|
|
364
|
+
// Its VM can't be found: say so, and run the jobs where they came from when that machine takes jobs.
|
|
365
|
+
const f = await refresh(vm);
|
|
366
|
+
if (f.problem) {
|
|
367
|
+
const w = workers.get(vm.name);
|
|
368
|
+
for (const id of w?.pending.splice(0) || []) {
|
|
369
|
+
const j = jobs.get(id);
|
|
370
|
+
if (!j || j.state === 'done') continue;
|
|
371
|
+
if (w) w.assigned = Math.max(0, w.assigned - 1);
|
|
372
|
+
if (workers.has(j.from) && !srv.fits(workers.get(j.from), j)) srv.move(j, j.from, `${vm.name} can't be used (${f.problem}), so it runs on ${j.from}`);
|
|
373
|
+
else srv.finish(j, srv.LOST, `${vm.name} can't be used: ${f.problem}`);
|
|
374
|
+
}
|
|
375
|
+
mark(vm, 'asleep');
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
const t0 = now();
|
|
379
|
+
say(`${vm.name}: waking ${vm.id} for a job`);
|
|
380
|
+
let r = await boat(['resume', vm.id, '--json'], { timeout: 5 * 6e4 });
|
|
381
|
+
if (r.code) return fail(vm, `boat resume failed: ${r.err}`);
|
|
382
|
+
vm.resumeMs = now() - t0;
|
|
383
|
+
vm.upSince = now();
|
|
384
|
+
vm.cantWake = null;
|
|
385
|
+
event({ kind: 'ondemand', act: 'resume', name: vm.name, id: vm.id, ms: vm.resumeMs });
|
|
386
|
+
noteVm(vm, vm.id, `Running dibs jobs (on-demand ${vm.name}) since ${hhmm()}. dibs stops it once its queue is empty`);
|
|
387
|
+
return setup(vm);
|
|
388
|
+
};
|
|
389
|
+
const setup = async vm => {
|
|
390
|
+
forward(vm);
|
|
391
|
+
let r = await boat(['exec', '--timeout', '120', vm.id, '--', 'sh', '-c', CHECK], { timeout: 3 * 6e4 });
|
|
392
|
+
if (r.code) return fail(vm, `couldn't look inside it: ${r.err}`);
|
|
393
|
+
const got = Object.fromEntries(r.out.split('\n').map(l => l.trim().split('=')).filter(x => x.length === 2));
|
|
394
|
+
const pinned = got.node, have = got.dibs;
|
|
395
|
+
if (pinned !== NODE.version) {
|
|
396
|
+
say(`${vm.name}: installing Node ${NODE.version}`);
|
|
397
|
+
r = await boat(['exec', '--timeout', '600', vm.id, '--', 'sh', '-c', INSTALL_NODE], { timeout: 11 * 6e4 });
|
|
398
|
+
if (r.code) return fail(vm, `installing Node failed: ${r.err}`);
|
|
399
|
+
}
|
|
400
|
+
if (have !== VERSION) {
|
|
401
|
+
say(`${vm.name}: installing dibs ${VERSION}${have ? ` (it had ${have})` : ''}`);
|
|
402
|
+
r = await boat(['push', vm.id, ROOT, '--to', APP], { timeout: 10 * 6e4 });
|
|
403
|
+
if (r.code) return fail(vm, `copying dibs there failed: ${r.err}`);
|
|
404
|
+
}
|
|
405
|
+
// Its own token every wake, never the coordinator's: a file, so the token is in no command line or history.
|
|
406
|
+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'dibs-od-'));
|
|
407
|
+
const file = path.join(tmp, 'remote.json');
|
|
408
|
+
try {
|
|
409
|
+
fs.writeFileSync(file, JSON.stringify({ url: `http://127.0.0.1:${port}`, token: trust.invite(vm.name), name: vm.name }), { mode: 0o600 });
|
|
410
|
+
r = await boat(['exec', '--timeout', '60', vm.id, '--', 'sh', '-c', `mkdir -p ${VM_HOME}/.dibs && chmod 700 ${VM_HOME}/.dibs`]);
|
|
411
|
+
if (!r.code) r = await boat(['scp', file, `${vm.id}:${VM_HOME}/.dibs/remote.json`], { timeout: 2 * 6e4 });
|
|
412
|
+
} finally { fs.rmSync(tmp, { recursive: true, force: true }); }
|
|
413
|
+
if (r.code) return fail(vm, `couldn't give it its token: ${r.err}`);
|
|
414
|
+
vm.adopted = false;
|
|
415
|
+
r = await boat(['exec', '--timeout', '30', vm.id, '--', 'sh', '-c', KILL_OLD], { timeout: 6e4 });
|
|
416
|
+
if (r.code) return fail(vm, `couldn't stop the worker it had before: ${r.err}`);
|
|
417
|
+
r = await boat(['exec', '--detach', vm.id, '--', 'sh', '-c', WORKER], { timeout: 2 * 6e4 });
|
|
418
|
+
if (r.code) return fail(vm, `couldn't start its worker: ${r.err}`);
|
|
419
|
+
vm.waitingSince = now();
|
|
420
|
+
};
|
|
421
|
+
|
|
422
|
+
const stop = async (vm, why) => {
|
|
423
|
+
if (vm.state === 'stopping' || vm.state === 'asleep' && !vm.upSince) return;
|
|
424
|
+
mark(vm, 'stopping');
|
|
425
|
+
unforward(vm);
|
|
426
|
+
let r;
|
|
427
|
+
if (vm.temp) r = vm.id ? await remove(vm, vm.id, why) : { code: 0 };
|
|
428
|
+
else {
|
|
429
|
+
say(`${vm.name}: stopping ${vm.id} (${why})`);
|
|
430
|
+
r = vm.id ? await boat(['stop', vm.id, '--json'], { timeout: 5 * 6e4 }) : { code: 1, err: 'no VM found for it' };
|
|
431
|
+
if (r.code) say(`${vm.name}: boat stop failed (${r.err}). Its own auto-stop still ends it within the hour.`);
|
|
432
|
+
else noteVm(vm, vm.id, `Stopped ${hhmm()} by dibs (${why})`);
|
|
433
|
+
}
|
|
434
|
+
event({ kind: 'ondemand', act: vm.temp ? 'delete' : 'stop', name: vm.name, id: vm.id, why, billed: vm.upSince ? Math.round((now() - vm.upSince) / 1000) : null, ok: !r.code });
|
|
435
|
+
const w = workers.get(vm.name);
|
|
436
|
+
if (w) Object.assign(w, { running: [], busy: {}, seen: 0, lost: false }, vm.temp ? { cores: vm.cores, memTotal: vm.memTotal } : {});
|
|
437
|
+
Object.assign(vm, { upSince: null, idleSince: null, waitingSince: null, extended: 0 }, vm.temp ? { id: null } : {});
|
|
438
|
+
mark(vm, 'asleep');
|
|
439
|
+
};
|
|
440
|
+
// A temporary VM deleted for good, and its row with it. One dibs can't delete
|
|
441
|
+
// keeps its row, which says so, so the checker and the person still see it.
|
|
442
|
+
const remove = async (vm, id, why) => {
|
|
443
|
+
say(`${vm.name}: deleting ${id} (${why})`);
|
|
444
|
+
const r = await boat(['delete', id, '--yes', '--json'], { timeout: 5 * 6e4 });
|
|
445
|
+
const gone = !r.code || /not.?found|no such|doesn.t exist/i.test(r.err);
|
|
446
|
+
if (gone) dropRow(vm.registry, id);
|
|
447
|
+
else {
|
|
448
|
+
say(`${vm.name}: boat delete ${id} failed (${r.err}). Delete it by hand: boat delete ${id} --yes`);
|
|
449
|
+
noteVm(vm, id, `dibs couldn't delete it ${hhmm()} (${r.err}). Delete it: boat delete ${id} --yes`);
|
|
450
|
+
}
|
|
451
|
+
return gone ? { code: 0 } : r;
|
|
452
|
+
};
|
|
453
|
+
|
|
454
|
+
// Up once the worker dibs just started checks in: the current version, unless it was
|
|
455
|
+
// taken back running jobs (takeBack), whatever version it is.
|
|
456
|
+
const up = (vm, w) => {
|
|
457
|
+
if (vm.state !== 'waking' || !vm.waitingSince || !w || w.seen < vm.waitingSince || !(vm.adopted || w.version === VERSION)) return false;
|
|
458
|
+
mark(vm, 'running');
|
|
459
|
+
vm.idleSince = null;
|
|
460
|
+
say(`${vm.name}: up and taking jobs (woke in ${Math.round((now() - vm.upSince + vm.resumeMs) / 1000)}s)`);
|
|
461
|
+
return true;
|
|
462
|
+
};
|
|
463
|
+
if (srv.hooks) srv.hooks.up = w => { const vm = vms.get(w.name); if (vm) up(vm, w); };
|
|
464
|
+
const pass = async () => {
|
|
465
|
+
for (const vm of vms.values()) {
|
|
466
|
+
const w = workers.get(vm.name);
|
|
467
|
+
if (vm.state === 'asleep' && w?.pending.length) { wake(vm); continue; }
|
|
468
|
+
// Asleep with no job for it: whether it could wake at all, so the board says so before
|
|
469
|
+
// anyone counts on it. On 2026-10-22 boat's compute ran out for the month, and boat-1
|
|
470
|
+
// read "asleep: a job sent there wakes it" while every job meant for it waited on the Mac.
|
|
471
|
+
if (vm.state === 'asleep' && !cantWake(vm) && now() - (vm.limitsAt || 0) > LIMITS_FOR) {
|
|
472
|
+
vm.limitsAt = now();
|
|
473
|
+
startsBlocked().then(why => { if (why && vm.state === 'asleep' && !cantWake(vm)) block(vm, why); }).catch(() => {});
|
|
474
|
+
}
|
|
475
|
+
if (vm.state === 'asleep' && now() - vm.checked > RECHECK) { vm.checked = now(); refresh(vm); continue; }
|
|
476
|
+
if (vm.state === 'waking' && vm.waitingSince) {
|
|
477
|
+
if (up(vm, w)) continue;
|
|
478
|
+
if (now() - vm.waitingSince > FIRST_BEAT) fail(vm, 'its worker never checked in');
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
481
|
+
if (vm.state !== 'running') continue;
|
|
482
|
+
if (w?.lost) { stop(vm, 'its worker stopped reporting'); continue; }
|
|
483
|
+
// A worker on an older dibs gets no new jobs (src/serve.mjs), so once its own are done
|
|
484
|
+
// the VM stops, and the jobs waiting for it wake it again with this version.
|
|
485
|
+
if (w && w.version !== VERSION && !w.running?.length && ![...jobs.values()].some(j => j.machine === vm.name && j.state === 'running')) {
|
|
486
|
+
stop(vm, `its worker runs dibs ${w.version}, not ${VERSION}`);
|
|
487
|
+
continue;
|
|
488
|
+
}
|
|
489
|
+
if (busyOn(vm)) {
|
|
490
|
+
vm.idleSince = null;
|
|
491
|
+
if (now() - vm.extended > EXTEND_EVERY) { vm.extended = now(); boat(['extend', vm.id, '--ttl', String(EXTEND_TO)]); }
|
|
492
|
+
continue;
|
|
493
|
+
}
|
|
494
|
+
vm.idleSince ??= clock();
|
|
495
|
+
if (clock() - vm.idleSince >= vm.idleStop) stop(vm, 'its queue is empty');
|
|
496
|
+
}
|
|
497
|
+
};
|
|
498
|
+
const timer = tick ? setInterval(() => { pass().catch(e => say(`on-demand machines: ${e.stack}`)); }, tick) : null;
|
|
499
|
+
timer?.unref();
|
|
500
|
+
|
|
501
|
+
// A VM found up with dibs's worker running jobs on it was left that way by a
|
|
502
|
+
// coordinator that restarted: take it back as waking, with its forward, and
|
|
503
|
+
// its worker checks in and hands its jobs over (src/serve.mjs adopt).
|
|
504
|
+
const takeBack = (vm, id, why) => {
|
|
505
|
+
Object.assign(vm, { id, upSince: now(), idleSince: null, waitingSince: now(), adopted: true });
|
|
506
|
+
mark(vm, 'waking');
|
|
507
|
+
forward(vm);
|
|
508
|
+
say(`${vm.name}: ${id} ${why}; picking its jobs up again`);
|
|
509
|
+
};
|
|
510
|
+
// On start, one of ours found up: busy with dibs's jobs, it's taken back; busy
|
|
511
|
+
// with other work (boat ps), it's left running and said so; idle, stopped.
|
|
512
|
+
const reconcile = async () => {
|
|
513
|
+
for (const vm of vms.values()) {
|
|
514
|
+
// Temporary ones a crash left behind: listed by dibs, so deleted by dibs, unless one still runs a job.
|
|
515
|
+
if (vm.temp) {
|
|
516
|
+
let text = '';
|
|
517
|
+
try { text = fs.readFileSync(vm.registry, 'utf8'); } catch {}
|
|
518
|
+
for (const id of leftovers(vm, text)) {
|
|
519
|
+
const b = vm.id ? { busy: false } : await vmBusy(id);
|
|
520
|
+
if (b.busy && b.ours) takeBack(vm, id, 'was left running a job');
|
|
521
|
+
else await remove(vm, id, 'left from before the coordinator started');
|
|
522
|
+
}
|
|
523
|
+
continue;
|
|
524
|
+
}
|
|
525
|
+
const f = await refresh(vm);
|
|
526
|
+
if (!f.id || !STATES_UP.has(f.state)) continue;
|
|
527
|
+
const b = await vmBusy(f.id);
|
|
528
|
+
if (b.busy && b.ours) takeBack(vm, f.id, 'was left running a job');
|
|
529
|
+
else if (b.busy) say(`${vm.name}: ${f.id} is running and busy with work outside dibs (${b.why}), so it's left running`);
|
|
530
|
+
else { vm.upSince = now(); await stop(vm, 'found running when the coordinator started, with nothing running on it'); }
|
|
531
|
+
}
|
|
532
|
+
};
|
|
533
|
+
|
|
534
|
+
return {
|
|
535
|
+
vms, wake, stop, reconcile, pass,
|
|
536
|
+
// A VM still running jobs stays up through a coordinator restart; the next one takes it back.
|
|
537
|
+
close: async () => {
|
|
538
|
+
if (timer) clearInterval(timer);
|
|
539
|
+
for (const vm of vms.values()) {
|
|
540
|
+
unforward(vm);
|
|
541
|
+
if (vm.upSince && busyOn(vm)) say(`${vm.name}: leaving ${vm.id} running: it has jobs, which the next coordinator picks up again`);
|
|
542
|
+
else if (vm.upSince) await stop(vm, 'the coordinator is stopping');
|
|
543
|
+
}
|
|
544
|
+
},
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// What runs on a VM, from boat ps: ours is dibs's own worker; busy is one of its
|
|
549
|
+
// jobs, or other work using CPU. Boat's own services and a desktop never count.
|
|
550
|
+
const BASELINE = /ascii-|ariana-fswatch|cua-driver|sunshine|ibus-|Xorg|lightdm|systemd|dbus|\/sbin\/init|socat|dockerd|containerd|sshd|pipewire|wireplumber|xfce|xfwm|xfdesktop|Xvfb|polkit|snapd|cron|rsyslog/;
|
|
551
|
+
// Summed CPU % of other processes above which it's busy, as ~/boat/checker.mjs counts it.
|
|
552
|
+
const BUSY_CPU = 5;
|
|
553
|
+
export async function vmBusy(id) {
|
|
554
|
+
const r = await boat(['ps', id, '--json'], { timeout: 60e3 });
|
|
555
|
+
const ps = json(r.out)?.processes;
|
|
556
|
+
// Can't tell: busy, so nothing is stopped under a job on a guess.
|
|
557
|
+
if (r.code || !Array.isArray(ps)) return { busy: true, ours: false, why: `boat ps failed: ${r.err || 'no answer'}` };
|
|
558
|
+
const cmds = ps.map(p => ({ c: String(p.command || ''), cpu: Number(p.cpuPercent) || 0 }));
|
|
559
|
+
const ours = cmds.some(p => /dibs\.mjs worker/.test(p.c));
|
|
560
|
+
const job = cmds.find(p => /dibs\.mjs run |src\/thin\.sh/.test(p.c));
|
|
561
|
+
if (job) return { busy: true, ours, why: job.c.slice(0, 60) };
|
|
562
|
+
const cpu = cmds.filter(p => !BASELINE.test(p.c) && !/dibs\.mjs worker/.test(p.c)).reduce((a, p) => a + p.cpu, 0);
|
|
563
|
+
return { busy: cpu >= BUSY_CPU, ours, why: `cpu ${cpu.toFixed(1)}%` };
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
// Whether a job sent --anywhere should wake a sleeping VM: only when its wait
|
|
567
|
+
// on the best awake machine would outlast waking the VM and sending it the copy.
|
|
568
|
+
export function worthWaking(vm, waitPoints) {
|
|
569
|
+
const wakeMs = (vm.resumeMs ?? RESUME_GUESS) + UPLOAD_GUESS;
|
|
570
|
+
return waitPoints / 60 * JOB_AHEAD >= wakeMs;
|
|
571
|
+
}
|
|
572
|
+
export const wakePoints = vm => 60 * ((vm.resumeMs ?? RESUME_GUESS) + UPLOAD_GUESS) / JOB_AHEAD;
|