clavarium 0.2.0 → 0.2.1-next.1
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/deploy/clavarium-host +10 -0
- package/deploy/updater.mjs +204 -34
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/server/api.mjs +1 -1
- package/server/main.mjs +37 -11
- package/server/updates.mjs +2 -2
- package/server/vmwatch.mjs +63 -0
- package/web/app.js +11 -2
- package/web/style.css +3 -0
package/deploy/clavarium-host
CHANGED
|
@@ -255,6 +255,16 @@ case "$AREA $VERB" in
|
|
|
255
255
|
[ $# -ge 3 ] || usage
|
|
256
256
|
vm="$1"; shift 2
|
|
257
257
|
run "$MULTIPASS" exec "$vm" -- "$@" ;;
|
|
258
|
+
"vm ping")
|
|
259
|
+
# Does the VM manager answer at all? Asked now and then by the server
|
|
260
|
+
# (vmwatch.mjs); bounded, so that a VM manager that hangs is an answer.
|
|
261
|
+
[ $# -eq 0 ] || usage
|
|
262
|
+
run timeout 25 "$MULTIPASS" list --format csv ;;
|
|
263
|
+
"vm revive")
|
|
264
|
+
# The VM manager has not answered for minutes: its daemon restarted.
|
|
265
|
+
# Asked by the server at most once in hours (vmwatch.mjs), never by a page.
|
|
266
|
+
[ $# -eq 0 ] || usage
|
|
267
|
+
run timeout 170 snap restart multipass.multipassd ;;
|
|
258
268
|
"vm info")
|
|
259
269
|
[ $# -eq 1 ] || usage; vm_of "$1"
|
|
260
270
|
run "$MULTIPASS" info "$1" --format json ;;
|
package/deploy/updater.mjs
CHANGED
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
* --------------------------------------------------------------------------- */
|
|
49
49
|
import { spawn } from 'node:child_process';
|
|
50
50
|
import { createHash } from 'node:crypto';
|
|
51
|
-
import { readFileSync, writeFileSync, renameSync, mkdirSync, rmSync, readdirSync, existsSync, symlinkSync, realpathSync, cpSync, openSync, closeSync, statfsSync, chmodSync } from 'node:fs';
|
|
51
|
+
import { readFileSync, writeFileSync, renameSync, mkdirSync, rmSync, readdirSync, existsSync, symlinkSync, realpathSync, cpSync, openSync, closeSync, statfsSync, statSync, chmodSync } from 'node:fs';
|
|
52
52
|
import { dirname, join, basename } from 'node:path';
|
|
53
53
|
import { fileURLToPath } from 'node:url';
|
|
54
54
|
import { fetchParleyArchive, REGISTRY } from './parley-archive.mjs';
|
|
@@ -65,9 +65,22 @@ export const WINDOW = /^([01]\d|2[0-3]):[0-5]\d-([01]\d|2[0-3]):[0-5]\d$/;
|
|
|
65
65
|
export const DEFAULTS = { MODE: 'auto', CHANNEL: 'latest', WINDOW: '02:00-05:00', PORT: '7717' };
|
|
66
66
|
/* A conversation in one of these phases is in the middle of something the restart would cut. */
|
|
67
67
|
const BUSY = ['building', 'moving', 'restarting'];
|
|
68
|
+
/* A busy phase older than this was cut short (the server died under it): it does not hold an update back. */
|
|
69
|
+
const BUSY_STALE_MS = 30 * 60_000;
|
|
70
|
+
/* THE WATCHDOG (each timer turn): down this many turns in a row, or its service failed: one action, at most one an hour. */
|
|
71
|
+
const WATCH_MISSES = 3;
|
|
72
|
+
const WATCH_EVERY_MS = 3600_000;
|
|
73
|
+
/* An update this recent is the first suspect when the server will not stay up. */
|
|
74
|
+
const WATCH_RECENT_MS = 24 * 3600_000;
|
|
68
75
|
const HISTORY_MAX = 30;
|
|
69
76
|
const ASK_EVERY_MS = 6 * 3600_000;
|
|
70
77
|
const PROVENANCE = 'https://slsa.dev/provenance/v1';
|
|
78
|
+
/* What the log of a failure keeps, at most (history entry `log`, shown behind "See the log"). */
|
|
79
|
+
const LOG_MAX = 12_000;
|
|
80
|
+
/* Set beside the server's unit by the updater (root): a crash loop never locks the service out, so a
|
|
81
|
+
restart asked later (an update, the watchdog) still starts it. */
|
|
82
|
+
export const DROP_IN = '/etc/systemd/system/clavarium.service.d/restart.conf';
|
|
83
|
+
export const DROP_IN_TEXT = '# Written by the Clavarium updater: a crash loop never locks the service out.\n[Unit]\nStartLimitIntervalSec=0\n\n[Service]\nRestartSec=3\n';
|
|
71
84
|
|
|
72
85
|
export class Refused extends Error {}
|
|
73
86
|
|
|
@@ -142,16 +155,25 @@ const toHex = (integrity) => Buffer.from(String(integrity).replace(/^sha512-/, '
|
|
|
142
155
|
export class Updater {
|
|
143
156
|
#o; #run; #fetch;
|
|
144
157
|
constructor({ code = PATHS.code, conf = PATHS.conf, stateDir = PATHS.stateDir, data = PATHS.data, hostTarget = PATHS.host, gitReadTarget = PATHS.gitRead, registry = REGISTRY, run = runCommand, fetcher = fetch, now = () => new Date(), log = (line) => console.log(line),
|
|
145
|
-
verifySignatures, restart, health, backup, restoreData, installPrivileged, ensureNode,
|
|
146
|
-
|
|
158
|
+
verifySignatures, restart, health, backup, restoreData, installPrivileged, ensureNode, serviceState, answers, mainPid, pidCwd, diagnose, dropIn = DROP_IN,
|
|
159
|
+
clock = () => Date.now(), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), minFreeMb = 1024, healthMs = 60_000, watchMs = 120_000, settleMs = 10_000 } = {}) {
|
|
160
|
+
this.#o = { code, conf, stateDir, data, hostTarget, gitReadTarget, registry: registry.replace(/\/$/, ''), now, log, minFreeMb, healthMs, watchMs, settleMs, clock, sleep, dropIn };
|
|
147
161
|
this.#run = run; this.#fetch = fetcher;
|
|
148
162
|
this.verifySignatures = verifySignatures ?? ((dir) => this.#npm(['audit', 'signatures'], { cwd: dir, timeoutMs: 300_000 }));
|
|
149
|
-
this.restart = restart ?? (() => this.#
|
|
163
|
+
this.restart = restart ?? (() => this.#restart());
|
|
164
|
+
/* What was seen when the server did not come up: its journal, its unit, who holds its port. */
|
|
165
|
+
this.diagnose = diagnose ?? (() => this.#diagnose());
|
|
150
166
|
this.health = health ?? ((release) => this.#health(release));
|
|
151
167
|
this.backup = backup ?? ((app) => this.#backup(app));
|
|
152
168
|
this.restoreData = restoreData ?? ((app, archive) => this.#restoreData(app, archive));
|
|
153
169
|
this.installPrivileged = installPrivileged ?? ((app) => this.#installPrivileged(app));
|
|
154
170
|
this.ensureNode = ensureNode ?? ((app) => this.#ensureNode(app));
|
|
171
|
+
/* What systemd says of the server: 'active', 'activating', 'failed', 'inactive'... */
|
|
172
|
+
this.serviceState = serviceState ?? (async () => (await this.#run(['systemctl', 'show', '-p', 'ActiveState', '--value', 'clavarium.service'], { timeoutMs: 10_000 })).stdout.trim() || 'unknown');
|
|
173
|
+
/* Does the server answer, on its port, here? */
|
|
174
|
+
this.answers = answers ?? (() => this.#fetch(`http://127.0.0.1:${readConf(this.#o.conf).PORT}/`, { signal: AbortSignal.timeout(5000), redirect: 'manual' }).then((r) => r.status < 500).catch(() => false));
|
|
175
|
+
this.mainPid = mainPid ?? (async () => (await this.#run(['systemctl', 'show', '-p', 'MainPID', '--value', 'clavarium.service'], { timeoutMs: 10_000 })).stdout.trim());
|
|
176
|
+
this.pidCwd = pidCwd ?? ((pid) => { try { return realpathSync(`/proc/${pid}/cwd`); } catch { return ''; } });
|
|
155
177
|
}
|
|
156
178
|
|
|
157
179
|
get releasesDir() { return join(this.#o.code, 'releases'); }
|
|
@@ -340,12 +362,26 @@ export class Updater {
|
|
|
340
362
|
renameSync(`${link}.new`, link);
|
|
341
363
|
}
|
|
342
364
|
|
|
343
|
-
/* A conversation in the middle of a build, a move or a restart: '' or why not now.
|
|
344
|
-
|
|
365
|
+
/* A conversation in the middle of a build, a move or a restart: '' or why not now.
|
|
366
|
+
Only while the server runs (a phase in the file of a server that is down is not going on), and
|
|
367
|
+
only a phase younger than BUSY_STALE_MS (older: cut short; the server settles it when it starts). */
|
|
368
|
+
async busy() {
|
|
369
|
+
const file = join(this.#o.data, 'conversations.json');
|
|
345
370
|
let all = [];
|
|
346
|
-
try { all = JSON.parse(readFileSync(
|
|
347
|
-
const busy = (Array.isArray(all) ? all : []).filter((c) => BUSY.includes(c.phase))
|
|
348
|
-
|
|
371
|
+
try { all = JSON.parse(readFileSync(file, 'utf8')); } catch { return ''; }
|
|
372
|
+
const busy = (Array.isArray(all) ? all : []).filter((c) => c && BUSY.includes(c.phase));
|
|
373
|
+
if (!busy.length) return '';
|
|
374
|
+
const names = (list) => list.slice(0, 3).map((c) => c.name).join(', ');
|
|
375
|
+
const state = await this.serviceState().catch(() => 'unknown');
|
|
376
|
+
if (state !== 'active') { this.#o.log(`busy phases not waited for: the server is ${state} (${names(busy)})`); return ''; }
|
|
377
|
+
let written = this.#o.now().getTime();
|
|
378
|
+
try { written = statSync(file).mtimeMs; } catch { /* now */ }
|
|
379
|
+
const now = this.#o.now().getTime();
|
|
380
|
+
const since = (c) => { const t = Date.parse(c.restartingSince ?? c.buildingSince ?? c.movingSince ?? ''); return Number.isFinite(t) ? t : written; };
|
|
381
|
+
const stale = busy.filter((c) => now - since(c) > BUSY_STALE_MS);
|
|
382
|
+
if (stale.length) this.#o.log(`busy phases older than 30 minutes not waited for: ${names(stale)}`);
|
|
383
|
+
const live = busy.filter((c) => !stale.includes(c));
|
|
384
|
+
return live.length ? `a machine is being built or restarted (${names(live)}): the update waits` : '';
|
|
349
385
|
}
|
|
350
386
|
#dataFormat() { try { return JSON.parse(readFileSync(join(this.#o.data, 'data-format.json'), 'utf8')).format; } catch { return undefined; } }
|
|
351
387
|
|
|
@@ -356,7 +392,9 @@ export class Updater {
|
|
|
356
392
|
try { const fd = openSync(file, 'wx'); writeFileSync(fd, String(process.pid)); closeSync(fd); return () => rmSync(file, { force: true }); } catch (error) {
|
|
357
393
|
if (error.code !== 'EEXIST') throw error;
|
|
358
394
|
const pid = Number(readFileSync(file, 'utf8')) || 0;
|
|
359
|
-
|
|
395
|
+
/* A lock left by a process that is gone (killed, the machine stopped) is taken over. */
|
|
396
|
+
let alive = false; try { if (pid) { process.kill(pid, 0); alive = true; } } catch (e) { alive = e.code === 'EPERM'; }
|
|
397
|
+
if (!alive) this.#o.log(`a stale lock (process ${pid || '?'} is gone): taken over`);
|
|
360
398
|
if (alive) throw new Refused('an update or an installation is running already');
|
|
361
399
|
rmSync(file, { force: true });
|
|
362
400
|
}
|
|
@@ -371,7 +409,7 @@ export class Updater {
|
|
|
371
409
|
/* Asked for the version that runs (a request that waited while it came by itself): done already. */
|
|
372
410
|
if (from && compareVersions(version, from.version) === 0) return;
|
|
373
411
|
if (from && compareVersions(version, from.version) < 0) throw new Refused(`${version} is not newer than ${from.version}`);
|
|
374
|
-
const why = this.busy(); if (why) throw new Refused(why);
|
|
412
|
+
const why = await this.busy(); if (why) throw new Refused(why);
|
|
375
413
|
const unlock = this.#lock();
|
|
376
414
|
try {
|
|
377
415
|
let release;
|
|
@@ -382,7 +420,7 @@ export class Updater {
|
|
|
382
420
|
this.#step('update', version, 'Backing up');
|
|
383
421
|
archive = await this.backup(from?.app ?? release.app);
|
|
384
422
|
} catch (error) { rmSync(release.dir, { recursive: true, force: true }); this.#history({ action: 'update', from: from?.version ?? null, to: version, result: 'failed', why: `the backup failed: ${error.message}` }); throw error; }
|
|
385
|
-
const late = this.busy();
|
|
423
|
+
const late = await this.busy();
|
|
386
424
|
if (late) { this.#history({ action: 'update', from: from?.version ?? null, to: version, result: 'failed', why: late }); throw new Refused(late); }
|
|
387
425
|
const failed = await this.#switchAndCheck(release, 'update', version);
|
|
388
426
|
if (!failed) {
|
|
@@ -390,18 +428,19 @@ export class Updater {
|
|
|
390
428
|
this.prune();
|
|
391
429
|
return this.about();
|
|
392
430
|
}
|
|
393
|
-
/* IT DID NOT COME UP: back to what ran, its data too if it moved. */
|
|
431
|
+
/* IT DID NOT COME UP: what was seen kept, then back to what ran, its data too if it moved. */
|
|
394
432
|
let why2 = failed;
|
|
433
|
+
let log = await this.#seen(`${version} did not come up: ${failed}`);
|
|
395
434
|
if (from) {
|
|
396
435
|
this.#step('update', version, 'Going back');
|
|
397
436
|
this.switchTo(from.id);
|
|
398
437
|
await this.installPrivileged(from.app).catch(() => {});
|
|
399
438
|
if (archive && this.#dataFormat() !== before) { const r = await this.restoreData(from.app, archive).catch((e) => ({ code: 1, stderr: e.message })); if (r?.code) why2 += `; the data backup could not be put back (${lastLine(r)}): ${archive}`; }
|
|
400
439
|
const back = await this.#restartAndCheck(from);
|
|
401
|
-
if (back) why2 += `; ${from.version} did not come back either (${back}): journalctl -u clavarium`;
|
|
440
|
+
if (back) { why2 += `; ${from.version} did not come back either (${back}): journalctl -u clavarium`; log = `${log}\n\n${await this.#seen(`${from.version} did not come back: ${back}`)}`; }
|
|
402
441
|
rmSync(release.dir, { recursive: true, force: true });
|
|
403
442
|
}
|
|
404
|
-
this.#history({ action: 'update', from: from?.version ?? null, to: version, result: from ? 'rolled-back' : 'failed', why: why2 });
|
|
443
|
+
this.#history({ action: 'update', from: from?.version ?? null, to: version, result: from ? 'rolled-back' : 'failed', why: why2, log: log.slice(-LOG_MAX) });
|
|
405
444
|
this.prune();
|
|
406
445
|
return this.about();
|
|
407
446
|
} finally { unlock(); }
|
|
@@ -416,19 +455,20 @@ export class Updater {
|
|
|
416
455
|
if (to.current) throw new Refused(`${id} is the release that runs`);
|
|
417
456
|
const format = this.#dataFormat();
|
|
418
457
|
if (format !== undefined && to.dataFormat < format) throw new Refused(`${to.version} cannot read the data of this version (format ${format}; it reads ${to.dataFormat})`);
|
|
419
|
-
const why = this.busy(); if (why) throw new Refused(why);
|
|
458
|
+
const why = await this.busy(); if (why) throw new Refused(why);
|
|
420
459
|
const unlock = this.#lock();
|
|
421
460
|
try {
|
|
422
461
|
const failed = await this.#switchAndCheck(to, 'back', to.version);
|
|
423
462
|
if (!failed) { this.#history({ action: 'back', from: from?.version ?? null, to: to.version, result: 'done' }); return this.about(); }
|
|
424
463
|
let why2 = failed;
|
|
464
|
+
let log = await this.#seen(`${to.version} did not come up: ${failed}`);
|
|
425
465
|
if (from) {
|
|
426
466
|
this.switchTo(from.id);
|
|
427
467
|
await this.installPrivileged(from.app).catch(() => {});
|
|
428
468
|
const back = await this.#restartAndCheck(from);
|
|
429
|
-
if (back) why2 += `; ${from.version} did not come back either (${back})`;
|
|
469
|
+
if (back) { why2 += `; ${from.version} did not come back either (${back})`; log = `${log}\n\n${await this.#seen(`${from.version} did not come back: ${back}`)}`; }
|
|
430
470
|
}
|
|
431
|
-
this.#history({ action: 'back', from: from?.version ?? null, to: to.version, result: 'failed', why: why2 });
|
|
471
|
+
this.#history({ action: 'back', from: from?.version ?? null, to: to.version, result: 'failed', why: why2, log: log.slice(-LOG_MAX) });
|
|
432
472
|
return this.about();
|
|
433
473
|
} finally { unlock(); }
|
|
434
474
|
}
|
|
@@ -455,7 +495,7 @@ export class Updater {
|
|
|
455
495
|
const all = this.releases();
|
|
456
496
|
const current = all.find((r) => r.current);
|
|
457
497
|
/* The one gone from at the last update or return that worked; else the newest other one. */
|
|
458
|
-
const last = (this.#state().history ?? []).find((h) => h.result === 'done');
|
|
498
|
+
const last = (this.#state().history ?? []).find((h) => h.result === 'done' && h.action !== 'restart');
|
|
459
499
|
const previous = all.find((r) => !r.current && last && r.version === last.from) ?? all.find((r) => !r.current);
|
|
460
500
|
const keep = new Set([current?.id, previous?.id].filter(Boolean));
|
|
461
501
|
for (const r of all) if (!keep.has(r.id)) rmSync(r.dir, { recursive: true, force: true });
|
|
@@ -482,13 +522,63 @@ export class Updater {
|
|
|
482
522
|
if (conf.MODE === 'ask') return `${available} is out: waiting for the owner`;
|
|
483
523
|
/* A version that failed here is not tried again by itself: the owner can, from Settings. */
|
|
484
524
|
if ((state.history ?? []).some((h) => h.to === available && h.action === 'update' && h.result !== 'done')) return `${available} failed here before: not tried again by itself`;
|
|
485
|
-
|
|
525
|
+
const why = await this.busy(); if (why) return why;
|
|
486
526
|
await this.apply(available);
|
|
487
527
|
/* What the history says, not what was hoped: a version that did not start was undone. */
|
|
488
|
-
const last = (this.#state().history ?? [])
|
|
528
|
+
const last = (this.#state().history ?? [])[0];
|
|
489
529
|
return last?.to === available && last.result !== 'done' ? `${available} did not work: back to ${last.from ?? 'nothing'} (${last.why ?? last.result})` : `updated to ${available}`;
|
|
490
530
|
}
|
|
491
531
|
|
|
532
|
+
/* THE WATCHDOG, at each timer turn: the server down (its service failed or stopped, or no answer
|
|
533
|
+
WATCH_MISSES turns in a row) is acted on, once, and said in the history:
|
|
534
|
+
- after an update of less than WATCH_RECENT_MS, with the release before it kept (and able to
|
|
535
|
+
read the data): back to it, by itself ("did not stay up"), not tried again by itself;
|
|
536
|
+
- otherwise: one restart.
|
|
537
|
+
Never more than one action in WATCH_EVERY_MS, so that it never loops. { acted, said } */
|
|
538
|
+
async watchdog() {
|
|
539
|
+
const state = await this.serviceState().catch(() => 'unknown');
|
|
540
|
+
const up = state === 'active' && await this.answers().catch(() => false);
|
|
541
|
+
const w = this.#state().watch ?? {};
|
|
542
|
+
if (up) { if (w.misses) this.#save({ watch: { ...w, misses: 0 } }); return { acted: false, said: 'up' }; }
|
|
543
|
+
const misses = (w.misses ?? 0) + 1;
|
|
544
|
+
this.#save({ watch: { ...w, misses, seen: state } });
|
|
545
|
+
const down = state === 'failed' || state === 'inactive' || misses >= WATCH_MISSES;
|
|
546
|
+
this.#o.log(`watchdog: the server is ${state === 'active' ? 'active but does not answer' : state} (turn ${misses})`);
|
|
547
|
+
if (!down) return { acted: false, said: `the server does not answer (turn ${misses} of ${WATCH_MISSES})` };
|
|
548
|
+
const now = this.#o.now();
|
|
549
|
+
if (w.actedAt && now - new Date(w.actedAt) < WATCH_EVERY_MS) return { acted: false, said: 'the server is down; something was done less than an hour ago: nothing more by itself' };
|
|
550
|
+
let unlock;
|
|
551
|
+
try { unlock = this.#lock(); } catch (error) { if (error instanceof Refused) return { acted: false, said: 'the server is down, but an update runs' }; throw error; }
|
|
552
|
+
try {
|
|
553
|
+
this.#save({ watch: { misses: 0, actedAt: now.toISOString(), seen: state } });
|
|
554
|
+
const log = await this.#seen(`the server was down (${state})`);
|
|
555
|
+
const current = this.current();
|
|
556
|
+
/* The last update or return (a restart by the watchdog is not one). */
|
|
557
|
+
const last = (this.#state().history ?? []).find((h) => h.action !== 'restart');
|
|
558
|
+
const recent = current && last && last.action === 'update' && last.result === 'done' && last.to === current.version && now - new Date(last.at) < WATCH_RECENT_MS;
|
|
559
|
+
const previous = recent ? this.releases().find((r) => !r.current && r.version === last.from) : undefined;
|
|
560
|
+
const format = this.#dataFormat();
|
|
561
|
+
if (previous && (format === undefined || previous.dataFormat >= format)) {
|
|
562
|
+
let why = `${current.version} did not stay up (its service ${state === 'active' ? 'did not answer' : `was ${state}`}): back to ${previous.version}`;
|
|
563
|
+
this.#o.log(`watchdog: ${why}`);
|
|
564
|
+
this.#step('update', current.version, 'Going back');
|
|
565
|
+
let back;
|
|
566
|
+
try { this.switchTo(previous.id); await this.installPrivileged(previous.app).catch(() => {}); back = await this.#restartAndCheck(previous); } catch (error) { back = error.message; }
|
|
567
|
+
if (back) why += `; ${previous.version} did not come back either (${back}): journalctl -u clavarium`;
|
|
568
|
+
else rmSync(current.dir, { recursive: true, force: true });
|
|
569
|
+
this.#history({ action: 'update', from: previous.version, to: current.version, result: 'rolled-back', by: 'watchdog', why, log: log.slice(-LOG_MAX) });
|
|
570
|
+
this.prune();
|
|
571
|
+
return { acted: true, said: why };
|
|
572
|
+
}
|
|
573
|
+
const v = current?.version ?? null;
|
|
574
|
+
this.#o.log(`watchdog: the server is ${state}: restarted once`);
|
|
575
|
+
const failed = current ? await this.#restartAndCheck(current) : await this.restart().then((r) => (r?.code ? lastLine(r) : '')).catch((e) => e.message);
|
|
576
|
+
const why = `the server was down (${state === 'active' ? 'no answer' : state}): restarted by itself${failed ? `; it did not come back (${failed}): journalctl -u clavarium` : ''}`;
|
|
577
|
+
this.#history({ action: 'restart', from: v, to: v, result: failed ? 'failed' : 'done', by: 'watchdog', why, log: log.slice(-LOG_MAX) });
|
|
578
|
+
return { acted: true, said: why };
|
|
579
|
+
} finally { unlock(); }
|
|
580
|
+
}
|
|
581
|
+
|
|
492
582
|
/* What the host program asked (a request file), or the timer's turn. */
|
|
493
583
|
async runOnce() {
|
|
494
584
|
const file = join(this.#o.stateDir, 'request');
|
|
@@ -502,6 +592,9 @@ export class Updater {
|
|
|
502
592
|
await this.check().catch(() => {});
|
|
503
593
|
return r;
|
|
504
594
|
}
|
|
595
|
+
/* The timer's turn: first, is the server up? (it may have died after an update that looked well) */
|
|
596
|
+
const watched = await this.watchdog();
|
|
597
|
+
if (watched.acted) return watched.said;
|
|
505
598
|
return await this.tick();
|
|
506
599
|
} catch (error) {
|
|
507
600
|
if (error instanceof Refused && request) this.#save({ refused: { at: this.#o.now().toISOString(), why: error.message } });
|
|
@@ -509,28 +602,103 @@ export class Updater {
|
|
|
509
602
|
}
|
|
510
603
|
}
|
|
511
604
|
|
|
605
|
+
/* What was seen, as text: never fails (a log that could not be read says so). */
|
|
606
|
+
async #seen(title) {
|
|
607
|
+
const text = await Promise.resolve().then(() => this.diagnose()).catch((e) => `the log could not be read: ${e.message}`);
|
|
608
|
+
return `== ${this.#o.now().toISOString()} ${title}\n${String(text ?? '').trim()}`;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/* THE DROP-IN beside the server's unit: written when it differs, then systemd told. true when written. */
|
|
612
|
+
async ensureDropIn() {
|
|
613
|
+
const file = this.#o.dropIn;
|
|
614
|
+
try { if (readFileSync(file, 'utf8') === DROP_IN_TEXT) return false; } catch { /* not there */ }
|
|
615
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o755 });
|
|
616
|
+
writeFileSync(`${file}.new`, DROP_IN_TEXT, { mode: 0o644 });
|
|
617
|
+
renameSync(`${file}.new`, file);
|
|
618
|
+
if (process.getuid?.() === 0) await this.#run(['systemctl', 'daemon-reload'], { timeoutMs: 60_000 });
|
|
619
|
+
return true;
|
|
620
|
+
}
|
|
621
|
+
|
|
512
622
|
/* ------------------------- the real machine's ways ------------------------- */
|
|
513
|
-
|
|
623
|
+
/* The processes still there after a stop: in the unit's cgroup, or holding its port. [{ pid, state, port }] */
|
|
624
|
+
async #leftovers() {
|
|
625
|
+
const port = readConf(this.#o.conf).PORT;
|
|
626
|
+
const pids = new Map();
|
|
627
|
+
try { for (const p of readFileSync('/sys/fs/cgroup/system.slice/clavarium.service/cgroup.procs', 'utf8').split('\n')) if (/^\d+$/.test(p.trim())) pids.set(p.trim(), false); } catch { /* none */ }
|
|
628
|
+
const ss = await this.#run(['ss', '-Hltnp', `sport = :${port}`], { timeoutMs: 10_000 });
|
|
629
|
+
for (const m of String(ss.stdout).matchAll(/pid=(\d+)/g)) pids.set(m[1], true);
|
|
630
|
+
return [...pids].map(([pid, holds]) => {
|
|
631
|
+
let state = '?';
|
|
632
|
+
try { state = /^State:\s+(\S)/m.exec(readFileSync(`/proc/${pid}/status`, 'utf8'))?.[1] ?? '?'; } catch { state = 'gone'; }
|
|
633
|
+
return { pid: Number(pid), state, port: holds };
|
|
634
|
+
}).filter((p) => p.state !== 'gone');
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/* A RESTART that does not trust the stop: its failures forgotten (reset-failed), stopped, and
|
|
638
|
+
what is left of the old server looked at -- killed, or, when it cannot be (state D: waiting on
|
|
639
|
+
the kernel), said precisely: then nothing would answer on the port before a reboot. */
|
|
640
|
+
async #restart() {
|
|
641
|
+
await this.#run(['systemctl', 'reset-failed', 'clavarium.service'], { timeoutMs: 30_000 });
|
|
642
|
+
await this.#run(['systemctl', 'stop', 'clavarium.service'], { timeoutMs: 120_000 });
|
|
643
|
+
let left = await this.#leftovers();
|
|
644
|
+
for (const p of left.filter((x) => x.state !== 'D')) { try { process.kill(p.pid, 'SIGKILL'); this.#o.log(`a process of the old server was still there: ${p.pid} (state ${p.state}): killed`); } catch { /* gone */ } }
|
|
645
|
+
if (left.length) { await this.#o.sleep(2000); left = await this.#leftovers(); }
|
|
646
|
+
const stuck = left.filter((x) => x.state === 'D' && x.port);
|
|
647
|
+
if (stuck.length) return { code: 1, stderr: `a stuck process holds the port: ${stuck.map((p) => `pid ${p.pid}, state D`).join('; ')} (it waits on the kernel and cannot be killed): the server needs a reboot` };
|
|
648
|
+
if (left.some((x) => x.state === 'D')) this.#o.log(`processes of the old server stuck in state D (not on the port): ${left.map((p) => p.pid).join(', ')}`);
|
|
649
|
+
await this.#run(['systemctl', 'reset-failed', 'clavarium.service'], { timeoutMs: 30_000 });
|
|
650
|
+
return this.#run(['systemctl', 'start', 'clavarium.service'], { timeoutMs: 120_000 });
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
async #diagnose() {
|
|
514
654
|
const port = readConf(this.#o.conf).PORT;
|
|
515
|
-
const
|
|
655
|
+
const part = async (title, argv) => { const r = await this.#run(argv, { timeoutMs: 20_000 }); return `-- ${title}\n${String(r.stdout || r.stderr || `exit ${r.code}`).trim()}`; };
|
|
656
|
+
const left = await this.#leftovers().catch(() => []);
|
|
657
|
+
return [
|
|
658
|
+
await part('systemctl status clavarium', ['systemctl', 'status', 'clavarium.service', '--no-pager', '-n', '0']),
|
|
659
|
+
await part(`who listens on ${port}`, ['ss', '-Hltnp', `sport = :${port}`]),
|
|
660
|
+
`-- processes of the server's unit or on its port\n${left.map((p) => `pid ${p.pid} state ${p.state}${p.port ? ' (holds the port)' : ''}`).join('\n') || 'none'}`,
|
|
661
|
+
await part('journalctl -u clavarium -n 80', ['journalctl', '-u', 'clavarium.service', '-n', '80', '--no-pager', '-o', 'short-iso']),
|
|
662
|
+
].join('\n');
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
/* Comes up (answers, from this release) within healthMs, then STAYS up: watched until watchMs after
|
|
666
|
+
the restart; one restart by systemd is forgiven if it answers at the end, not two. */
|
|
667
|
+
async #health(release) {
|
|
668
|
+
const { clock, sleep } = this.#o;
|
|
669
|
+
const start = clock();
|
|
516
670
|
const target = realpathSync(release.dir);
|
|
671
|
+
const mine = async () => { const pid = await this.mainPid(); return { pid, ok: !!pid && pid !== '0' && this.pidCwd(pid).startsWith(target) }; };
|
|
517
672
|
let said = 'it did not answer';
|
|
673
|
+
let pid = '';
|
|
518
674
|
for (;;) {
|
|
519
|
-
const
|
|
520
|
-
const answered =
|
|
675
|
+
const state = await this.serviceState().catch(() => 'unknown');
|
|
676
|
+
const answered = state === 'active' && await this.answers().catch(() => false);
|
|
521
677
|
if (answered) {
|
|
522
|
-
const
|
|
523
|
-
|
|
524
|
-
if (cwd.startsWith(target)) break;
|
|
678
|
+
const m = await mine();
|
|
679
|
+
if (m.ok) { pid = m.pid; break; }
|
|
525
680
|
said = 'the server that answers is not this release';
|
|
526
|
-
} else if (active
|
|
527
|
-
if (
|
|
528
|
-
await
|
|
681
|
+
} else if (state !== 'active' && state !== 'activating') said = 'its service stopped';
|
|
682
|
+
if (clock() - start > this.#o.healthMs) return said;
|
|
683
|
+
await sleep(1000);
|
|
529
684
|
}
|
|
530
685
|
/* And it stays up. */
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
686
|
+
const until = Math.max(start + this.#o.watchMs, clock() + this.#o.settleMs);
|
|
687
|
+
let restarts = 0;
|
|
688
|
+
while (clock() < until) {
|
|
689
|
+
await sleep(Math.min(5000, Math.max(1, until - clock())));
|
|
690
|
+
const now = await this.mainPid().catch(() => '');
|
|
691
|
+
if (now && now !== '0' && now !== pid) { restarts += 1; pid = now; }
|
|
692
|
+
if (restarts > 1) return 'the server stopped more than once in its first minutes';
|
|
693
|
+
}
|
|
694
|
+
/* At the end: it answers, from this release (a moment given if it is in its one restart). */
|
|
695
|
+
const last = clock() + this.#o.settleMs;
|
|
696
|
+
for (;;) {
|
|
697
|
+
const state = await this.serviceState().catch(() => 'unknown');
|
|
698
|
+
if (state === 'active' && await this.answers().catch(() => false) && (await mine()).ok) return '';
|
|
699
|
+
if (clock() > last) return restarts ? 'the server stopped soon after it started, and did not answer again' : 'the server stopped soon after it started';
|
|
700
|
+
await sleep(1000);
|
|
701
|
+
}
|
|
534
702
|
}
|
|
535
703
|
|
|
536
704
|
async #backup(app) {
|
|
@@ -554,6 +722,7 @@ export class Updater {
|
|
|
554
722
|
const r = await this.#run(['install', '-o', 'root', '-g', 'root', '-m', '0755', from, to], { timeoutMs: 30_000 });
|
|
555
723
|
if (r.code !== 0) throw new Error(`${to}: ${lastLine(r)}`);
|
|
556
724
|
}
|
|
725
|
+
await this.ensureDropIn().catch((error) => this.#o.log(`the drop-in of the server's unit could not be written: ${error.message}`));
|
|
557
726
|
/* What a release sets up beside itself (the certificate timer): an update does not run install.sh again.
|
|
558
727
|
Best effort: the update does not depend on it; `sudo clavarium doctor` says when it is missing. */
|
|
559
728
|
const node = join(dirname(app), 'node', 'bin', 'node');
|
|
@@ -599,6 +768,7 @@ async function main(argv) {
|
|
|
599
768
|
/* What this release sets up beside itself (the certificate timer), at its first turn: the
|
|
600
769
|
update that brought it ran the PREVIOUS release's code. Idempotent; never stops the turn. */
|
|
601
770
|
try { const [{ installWatch }, { realSys }] = await Promise.all([import('./doctor.mjs'), import('./online.mjs')]); if (await installWatch(realSys())) console.error('updater: the certificate timer set up'); } catch (error) { console.error(`updater: the certificate timer could not be set up: ${error.message}`); }
|
|
771
|
+
try { if (await u.ensureDropIn()) console.error('updater: the drop-in of the server\'s unit written'); } catch (error) { console.error(`updater: the drop-in could not be written: ${error.message}`); }
|
|
602
772
|
const r = await u.runOnce(); console.log(typeof r === 'string' ? r : 'done'); return; }
|
|
603
773
|
case 'set': if (rest.length !== 2) throw new Refused('set <mode|channel|window|port> <value>'); return print(u.set(rest[0], rest[1]));
|
|
604
774
|
case 'prepare': { const r = await u.prepare({ version: value('--version'), fromDir: value('--from-dir') }); console.log(r.id); return; }
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.1-next.1",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "clavarium",
|
|
9
|
-
"version": "0.2.
|
|
9
|
+
"version": "0.2.1-next.1",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@xterm/addon-fit": "^0.11.0",
|
package/package.json
CHANGED
package/server/api.mjs
CHANGED
|
@@ -215,7 +215,7 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
215
215
|
if (pathname === '/api/updates' && updates) return send(200, updates.about()), true;
|
|
216
216
|
/* This server's disk and memory (capacity.mjs): everything for Settings; only whether it is high for the list. */
|
|
217
217
|
if (pathname === '/api/server' && capacity) return send(200, await capacity.about()), true;
|
|
218
|
-
if (pathname === '/api/server/brief' && capacity) return send(200, await capacity.brief()), true;
|
|
218
|
+
if (pathname === '/api/server/brief' && capacity) return send(200, { ...(await capacity.brief()), machines: platform?.machines ?? true }), true;
|
|
219
219
|
if (pathname === '/api/alerts' && alerts) return send(200, alerts.about()), true;
|
|
220
220
|
if (pathname === '/api/flows' && setup) return send(200, setup.graph()), true;
|
|
221
221
|
if (pathname === '/api/setup/import' && setup) return send(200, setup.job()), true;
|
package/server/main.mjs
CHANGED
|
@@ -56,6 +56,7 @@ import { Capacity } from './capacity.mjs';
|
|
|
56
56
|
import { packageFile, PARLEY } from './parley.mjs';
|
|
57
57
|
import { Updates } from './updates.mjs';
|
|
58
58
|
import { migrateData } from './dataformat.mjs';
|
|
59
|
+
import { VmWatch } from './vmwatch.mjs';
|
|
59
60
|
|
|
60
61
|
const ROOT = fileURLToPath(new URL('..', import.meta.url));
|
|
61
62
|
export const FILES = {
|
|
@@ -162,7 +163,12 @@ function serve(port, conversations, resources, { gate = () => 'local', originOk,
|
|
|
162
163
|
}
|
|
163
164
|
await sendFile(response, file);
|
|
164
165
|
});
|
|
165
|
-
|
|
166
|
+
/* Its port taken (an old server that did not die on its stop): said plainly, and the start fails. */
|
|
167
|
+
const listening = new Promise((ready, fail) => {
|
|
168
|
+
server.once('error', (error) => { if (error.code === 'EADDRINUSE') console.error(`start: port ${port} is in use by another process (an old server that did not stop?): see ss -ltnp 'sport = :${port}'`); fail(error); });
|
|
169
|
+
server.listen(port, '127.0.0.1', () => ready(server));
|
|
170
|
+
});
|
|
171
|
+
return { server, listening };
|
|
166
172
|
}
|
|
167
173
|
|
|
168
174
|
/* Development: one tool on this machine, no VM. */
|
|
@@ -184,7 +190,7 @@ const PARLEY_WAIT_MS = 20_000;
|
|
|
184
190
|
/* The product: conversations are VMs. `host` is how the host program is
|
|
185
191
|
reached on this installation, as an argument vector: it is the ONLY thing
|
|
186
192
|
this server runs with more rights than its own. */
|
|
187
|
-
export async function startHome({ port, host, dataDir, mntDir = dataDir, gitReserveBytes, env = process.env, conversations, resources, operators = [], publicOrigin, vaultKey, tools = loadTools(), stopDelayMs, mailReader, gitLocalRemotes = false, gitSsh, answerFetcher, answerEveryMs, wakeEveryMs, alertSend, talkEveryMs, gitEveryMs, shelfEveryMs, shelfFirstMs, healthEveryMs, healthSettleMs, setupPollMs, rereadAfterMs, serverRoomMs, updateState, updateConf, appName }) {
|
|
193
|
+
export async function startHome({ port, host, dataDir, mntDir = dataDir, gitReserveBytes, env = process.env, conversations, resources, operators = [], publicOrigin, vaultKey, tools = loadTools(), stopDelayMs, mailReader, gitLocalRemotes = false, gitSsh, answerFetcher, answerEveryMs, wakeEveryMs, alertSend, talkEveryMs, gitEveryMs, shelfEveryMs, shelfFirstMs, healthEveryMs, healthSettleMs, setupPollMs, rereadAfterMs, serverRoomMs, updateState, updateConf, appName, startWaitMs = 20_000, vmWatchEveryMs }) {
|
|
188
194
|
/* The data, in the format this code reads, before anything reads it (dataformat.mjs). */
|
|
189
195
|
const migrated = migrateData(dataDir);
|
|
190
196
|
if (migrated.ran.length) console.log(`data: format ${migrated.from} -> ${migrated.to}`);
|
|
@@ -215,11 +221,23 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
215
221
|
as one that is itself a virtual machine on a small disk. */
|
|
216
222
|
const stopShelf = shelf.start(env.CLAVARIUM_SHELF === 'off' ? 0 : shelfEveryMs, shelfFirstMs);
|
|
217
223
|
if (all.shelf) all.shelf = shelf;
|
|
218
|
-
/*
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
224
|
+
/* What the host must have before a machine starts (its views, /tools, the work disks, the
|
|
225
|
+
network rules, further down). Waited for at start, but never long: this server listens
|
|
226
|
+
and serves its pages even when the host program or the VM manager does not answer;
|
|
227
|
+
a machine that starts waits for it (all.prepare). */
|
|
228
|
+
const hostSteps = (async () => {
|
|
229
|
+
/* Before anything can start a VM: see resources.mjs. */
|
|
230
|
+
await folders.ensureViews().catch((error) => console.error(`views: ${error.message}`));
|
|
231
|
+
/* Not in place is said, not fatal: no machine is then given /tools. */
|
|
232
|
+
await toolbox.prepare().catch((error) => console.error(error.message));
|
|
233
|
+
await Promise.resolve(all.ensureWork?.()).catch((error) => console.error(`work folders: ${error.message}`));
|
|
234
|
+
})();
|
|
235
|
+
const bounded = (promise, ms, what) => {
|
|
236
|
+
let timer;
|
|
237
|
+
const late = new Promise((r) => { timer = setTimeout(() => { console.error(`start: ${what} still going after ${ms / 1000} s: the server starts without waiting for it`); r(); }, ms); timer.unref?.(); });
|
|
238
|
+
return Promise.race([promise, late]).finally(() => clearTimeout(timer));
|
|
239
|
+
};
|
|
240
|
+
await bounded(hostSteps, startWaitMs, 'the host program');
|
|
223
241
|
const shortcuts = new Shortcuts(new Store(`${dataDir}/shortcuts.json`));
|
|
224
242
|
/* The engine of dictation: chosen in Settings, else the environment's (voice.mjs). */
|
|
225
243
|
const voice = new Dictation({ file: new JsonFile(`${dataDir}/dictation.json`, {}), env, secret: (name) => secrets.reveal(name) });
|
|
@@ -242,7 +260,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
242
260
|
const network = new Network({ host: asHost, offline: () => all.offline() });
|
|
243
261
|
/* The rules follow what runs: applied now, and again each time a
|
|
244
262
|
conversation is opened, since a VM that just started has a new tap. */
|
|
245
|
-
await network.apply();
|
|
263
|
+
const hostReady = (async () => { await hostSteps; await network.apply().catch((error) => console.error(`network rules: ${error.message}`)); })();
|
|
264
|
+
await bounded(hostReady, startWaitMs, 'the network rules');
|
|
246
265
|
/* OPENING MUST BE QUICK. Each command sent into a VM costs a noticeable
|
|
247
266
|
part of a second, and delivering secrets takes several: done at every
|
|
248
267
|
opening, it made each page load wait for seconds (felt by the owner).
|
|
@@ -258,6 +277,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
258
277
|
/* Why Parley is not in a machine, said once in the log, not at each opening. */
|
|
259
278
|
const parleySaid = new Map();
|
|
260
279
|
all.prepare = async (name, woke) => {
|
|
280
|
+
await hostReady;
|
|
261
281
|
const wanted = secrets.signature(name);
|
|
262
282
|
const rules = network.apply();
|
|
263
283
|
if (woke || delivered.get(name) !== wanted) {
|
|
@@ -343,7 +363,10 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
343
363
|
/* What the VM manager says each machine has is what is recorded (a record
|
|
344
364
|
may say otherwise: set by hand, or by an earlier version). Not waited for. */
|
|
345
365
|
void all.reconcileAll?.().catch(() => {});
|
|
346
|
-
|
|
366
|
+
/* The VM manager, watched: said to the pages when it does not answer, restarted once when stuck (vmwatch.mjs). */
|
|
367
|
+
const vmWatch = new VmWatch({ run: asHost, store: new Store(`${dataDir}/vm-manager.json`), alert: (payload) => { void alerts.tell(payload)?.catch?.(() => {}); } });
|
|
368
|
+
const stopVmWatch = vmWatch.start(vmWatchEveryMs);
|
|
369
|
+
const platform = { get machines() { return vmWatch.ok; }, answerer: answerer.about(), operators: [...operators], address: publicOrigin ?? null, version: JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version, get dictation() { return voice.current() ? (voice.model ?? 'set') : null; } };
|
|
347
370
|
/* Who gets what, and a whole setup in one file: see setup.mjs. */
|
|
348
371
|
/* Settings, Updates: what the updater (deploy/updater.mjs, as root) wrote, and how to ask it. */
|
|
349
372
|
const updates = new Updates({ host: asHost, version: platform.version, store: new Store(`${dataDir}/updates.json`), alerts, ...(updateState ? { stateFile: updateState } : {}), ...(updateConf ? { confFile: updateConf } : {}) });
|
|
@@ -357,7 +380,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
357
380
|
all.room = (ask) => capacity.check(ask);
|
|
358
381
|
const stopWatch = capacity.start();
|
|
359
382
|
const { server, listening } = serve(port, all, folders, { gate, originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, capacity, updates, instance, repair: (name) => repairTerminal(name) });
|
|
360
|
-
server.on('close', () => { closing = true; stopShelf(); stopHealth(); stopUpdates(); stopWatch(); clearInterval(mailTimer); clearInterval(answerTimer); clearInterval(wakeTimer); clearInterval(gitTimer); talk.stop(); });
|
|
383
|
+
server.on('close', () => { closing = true; stopVmWatch(); stopShelf(); stopHealth(); stopUpdates(); stopWatch(); clearInterval(mailTimer); clearInterval(answerTimer); clearInterval(wakeTimer); clearInterval(gitTimer); talk.stop(); });
|
|
361
384
|
let closing = false;
|
|
362
385
|
bridge = attachBridge(server, {
|
|
363
386
|
onRejoin: (name) => all.rejoin(name),
|
|
@@ -413,6 +436,9 @@ function hostSetting(key) {
|
|
|
413
436
|
}
|
|
414
437
|
|
|
415
438
|
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
|
439
|
+
/* A promise rejected that nobody waited for is said, not fatal: one unlucky
|
|
440
|
+
call must not take every conversation's server down with it. */
|
|
441
|
+
process.on('unhandledRejection', (reason) => { console.error(`unhandled: ${reason?.stack ?? reason}`); });
|
|
416
442
|
const argv = process.argv.slice(2);
|
|
417
443
|
const port = Number(option(argv, 'port', '7717'));
|
|
418
444
|
const host = option(argv, 'host', '');
|
|
@@ -428,7 +454,7 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
|
|
428
454
|
const mntDir = hostSetting('MNT') || dataDir;
|
|
429
455
|
/* --name: the name of this Clavarium until one is chosen in Settings (instance.mjs). */
|
|
430
456
|
const name = option(argv, 'name', '') || undefined;
|
|
431
|
-
const server = await startHome({ port, host: host.split(' ').filter(Boolean), dataDir, mntDir, operators, publicOrigin, vaultKey, appName: name });
|
|
457
|
+
const server = await startHome({ port, host: host.split(' ').filter(Boolean), dataDir, mntDir, operators, publicOrigin, vaultKey, appName: name }).catch((error) => { console.error(`start: FAILED: ${error.message}`); process.exit(1); });
|
|
432
458
|
console.log(`http://127.0.0.1:${server.address().port}/`);
|
|
433
459
|
} else {
|
|
434
460
|
const command = option(argv, 'command', 'bash').split(' ').filter(Boolean);
|
package/server/updates.mjs
CHANGED
|
@@ -62,7 +62,7 @@ export class Updates {
|
|
|
62
62
|
refused: s.refused ?? null,
|
|
63
63
|
/* What can be gone back to: the kept releases that do not run. */
|
|
64
64
|
back: releases.filter((r) => !r.current && (VERSION.test(r.id) || LOCAL.test(r.id))).map((r) => ({ id: r.id, version: r.version })),
|
|
65
|
-
history: (Array.isArray(s.history) ? s.history : []).slice(0, HISTORY_SHOWN).map(({ at, action, from, to, result, why }) => ({ at, action, from, to, result, why: why ?? null })),
|
|
65
|
+
history: (Array.isArray(s.history) ? s.history : []).slice(0, HISTORY_SHOWN).map(({ at, action, from, to, result, why, log }) => ({ at, action, from, to, result, why: why ?? null, log: typeof log === 'string' ? log : null })),
|
|
66
66
|
};
|
|
67
67
|
}
|
|
68
68
|
|
|
@@ -110,7 +110,7 @@ export class Updates {
|
|
|
110
110
|
const key = `${last.at}|${last.to}`;
|
|
111
111
|
if (this.#store.get('told')?.key === key) return;
|
|
112
112
|
this.#store.put({ name: 'told', key });
|
|
113
|
-
const title = last.result === 'rolled-back' ? `The update to ${last.to} did not work: back on ${last.from}` : `${last.action === 'back' ? 'Going back to' : 'The update to'} ${last.to} failed`;
|
|
113
|
+
const title = last.action === 'restart' ? 'The server was down: restarting it did not work' : last.result === 'rolled-back' ? `The update to ${last.to} did not work: back on ${last.from}` : `${last.action === 'back' ? 'Going back to' : 'The update to'} ${last.to} failed`;
|
|
114
114
|
void this.#alerts?.tell({ title, body: String(last.why ?? '').slice(0, 180), url: '/?open=settings&at=updates' })?.catch?.(() => {});
|
|
115
115
|
};
|
|
116
116
|
look();
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/* THE VM MANAGER, WATCHED. Every machine goes through it; when it stops
|
|
2
|
+
* answering, nothing about a machine can be done, while this server itself
|
|
3
|
+
* must go on serving its pages. So it is asked now and then (host program:
|
|
4
|
+
* `vm ping`, bounded), and:
|
|
5
|
+
* - while it does not answer, `ok` is false: the pages say "the machines
|
|
6
|
+
* cannot be reached just now";
|
|
7
|
+
* - when it has not answered for STUCK_MS, its daemon is restarted ONCE
|
|
8
|
+
* (host program: `vm revive`), recorded, and the owner told; not again
|
|
9
|
+
* within REVIVE_EVERY_MS, so that it never loops.
|
|
10
|
+
*/
|
|
11
|
+
export const EVERY_MS = 60_000;
|
|
12
|
+
export const STUCK_MS = 5 * 60_000;
|
|
13
|
+
export const REVIVE_EVERY_MS = 6 * 3600_000;
|
|
14
|
+
|
|
15
|
+
const said = (r) => String(r?.stderr || r?.stdout || '').trim().split('\n').filter(Boolean).pop()?.slice(0, 200) || `exit ${r?.code}`;
|
|
16
|
+
|
|
17
|
+
export class VmWatch {
|
|
18
|
+
#run; #store; #now; #log; #alert; #stuckMs; #reviveEveryMs; #downSince = null;
|
|
19
|
+
ok = true;
|
|
20
|
+
constructor({ run, store, now = () => Date.now(), log = (line) => console.error(line), alert = () => {}, stuckMs = STUCK_MS, reviveEveryMs = REVIVE_EVERY_MS }) {
|
|
21
|
+
this.#run = run; this.#store = store; this.#now = now; this.#log = log; this.#alert = alert; this.#stuckMs = stuckMs; this.#reviveEveryMs = reviveEveryMs;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/* What the last restart of the VM manager was, if any: { at, why, result }. */
|
|
25
|
+
last() { const r = this.#store.get('revive'); return r ? { at: r.at, why: r.why, result: r.result ?? null } : null; }
|
|
26
|
+
|
|
27
|
+
/* One look: 'ok', 'down', 'down; restarted already', 'revived' or 'revive failed'. */
|
|
28
|
+
async look() {
|
|
29
|
+
const r = await this.#run(['vm', 'ping'], { timeoutMs: 30_000 }).catch((e) => ({ code: 1, stderr: e.message }));
|
|
30
|
+
if (r.code === 0) {
|
|
31
|
+
if (!this.ok) this.#log('vm manager: it answers again');
|
|
32
|
+
this.ok = true; this.#downSince = null;
|
|
33
|
+
return 'ok';
|
|
34
|
+
}
|
|
35
|
+
if (this.ok) this.#log(`vm manager: it does not answer (${said(r)})`);
|
|
36
|
+
this.ok = false;
|
|
37
|
+
this.#downSince ??= this.#now();
|
|
38
|
+
if (this.#now() - this.#downSince < this.#stuckMs) return 'down';
|
|
39
|
+
const before = this.#store.get('revive');
|
|
40
|
+
if (before?.at && this.#now() - Date.parse(before.at) < this.#reviveEveryMs) return 'down; restarted already';
|
|
41
|
+
const minutes = Math.round((this.#now() - this.#downSince) / 60_000);
|
|
42
|
+
const why = `the VM manager did not answer for ${minutes} minutes (${said(r)})`;
|
|
43
|
+
this.#store.put({ name: 'revive', at: new Date(this.#now()).toISOString(), why, result: null });
|
|
44
|
+
this.#log(`vm manager: ${why}: its daemon is restarted, once`);
|
|
45
|
+
const done = await this.#run(['vm', 'revive'], { timeoutMs: 180_000 }).catch((e) => ({ code: 1, stderr: e.message }));
|
|
46
|
+
const result = done.code === 0 ? 'done' : `failed: ${said(done)}`;
|
|
47
|
+
this.#store.put({ name: 'revive', at: new Date(this.#now()).toISOString(), why, result });
|
|
48
|
+
this.#log(`vm manager: restart ${result}`);
|
|
49
|
+
this.#alert({ title: 'The machines could not be reached', body: `${why}: it was restarted (${result}).`, url: '/?open=settings' });
|
|
50
|
+
this.#downSince = null;
|
|
51
|
+
return done.code === 0 ? 'revived' : 'revive failed';
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/* Looked at every `everyMs` (0: never), one look at a time. */
|
|
55
|
+
start(everyMs = EVERY_MS, firstMs = 5_000) {
|
|
56
|
+
if (!everyMs) return () => {};
|
|
57
|
+
let busy = false;
|
|
58
|
+
const turn = () => { if (busy) return; busy = true; void this.look().catch(() => {}).finally(() => { busy = false; }); };
|
|
59
|
+
const first = setTimeout(turn, firstMs); first.unref?.();
|
|
60
|
+
const timer = setInterval(turn, everyMs); timer.unref?.();
|
|
61
|
+
return () => { clearTimeout(first); clearInterval(timer); };
|
|
62
|
+
}
|
|
63
|
+
}
|
package/web/app.js
CHANGED
|
@@ -3351,9 +3351,11 @@
|
|
|
3351
3351
|
for (const h of u.history) {
|
|
3352
3352
|
const li = document.createElement('li'); li.dataset.result = h.result;
|
|
3353
3353
|
const t = document.createElement('time'); t.dateTime = h.at; t.textContent = when(h.at);
|
|
3354
|
-
const what = document.createElement('span'); what.textContent = `${h.from ?? '?'} → ${h.to} · ${h.action === 'back' && h.result === 'done' ? 'Went back' : RESULT_WORDS[h.result] ?? h.result}`;
|
|
3354
|
+
const what = document.createElement('span'); what.textContent = `${h.from ?? '?'} → ${h.to} · ${h.action === 'back' && h.result === 'done' ? 'Went back' : h.action === 'restart' ? (h.result === 'done' ? 'Restarted by itself' : 'Restart by itself failed') : RESULT_WORDS[h.result] ?? h.result}`;
|
|
3355
3355
|
li.append(t, what);
|
|
3356
3356
|
if (h.why) { const why = document.createElement('small'); why.textContent = h.why; li.append(why); }
|
|
3357
|
+
/* What the updater saw when it went wrong: the journal, the unit, who held the port. */
|
|
3358
|
+
if (h.log) { const d = document.createElement('details'); d.className = 'update-log'; const sum = document.createElement('summary'); sum.textContent = 'See the log'; const pre = document.createElement('pre'); pre.textContent = h.log; d.append(sum, pre); li.append(d); }
|
|
3357
3359
|
list.append(li);
|
|
3358
3360
|
}
|
|
3359
3361
|
$('updates-history-box').hidden = u.history.length === 0;
|
|
@@ -3525,8 +3527,15 @@
|
|
|
3525
3527
|
if (DEVICE) return;
|
|
3526
3528
|
const r = await fetch(`${API}/server/brief`).then((x) => (x.ok ? x.json() : null)).catch(() => null);
|
|
3527
3529
|
const g = $('server-gauge');
|
|
3528
|
-
|
|
3530
|
+
/* The VM manager does not answer: said here, whatever the room. */
|
|
3531
|
+
const away = r?.machines === false;
|
|
3532
|
+
if (!r?.high && !away) { g.hidden = true; return; }
|
|
3529
3533
|
g.replaceChildren();
|
|
3534
|
+
if (away) {
|
|
3535
|
+
const t = document.createElement('span'); t.className = 'gauge-title'; t.textContent = 'The machines cannot be reached just now';
|
|
3536
|
+
g.append(t); g.setAttribute('aria-label', 'The machines cannot be reached just now: the server keeps trying.'); g.hidden = false;
|
|
3537
|
+
if (!r.high) return;
|
|
3538
|
+
}
|
|
3530
3539
|
const row = (label, f) => {
|
|
3531
3540
|
const line = document.createElement('span'); line.className = 'gauge-line'; line.dataset.level = f.level;
|
|
3532
3541
|
const word = document.createElement('span'); word.className = 'gauge-word'; word.textContent = label;
|
package/web/style.css
CHANGED
|
@@ -993,6 +993,9 @@ button.inline:hover { color: var(--brass); }
|
|
|
993
993
|
#updates-back .hint { margin: 0; }
|
|
994
994
|
.updates-history { list-style: none; margin: 6px 0 0; padding: 0; display: grid; gap: 6px; font-size: .8125rem; }
|
|
995
995
|
.updates-history li { display: grid; grid-template-columns: auto 1fr; gap: 0 10px; }
|
|
996
|
+
.updates-history .update-log { grid-column: 1 / -1; }
|
|
997
|
+
.updates-history .update-log summary { cursor: pointer; color: var(--ink2); }
|
|
998
|
+
.updates-history .update-log pre { max-height: 50vh; overflow: auto; white-space: pre-wrap; word-break: break-word; font-size: .75rem; margin: 4px 0 0; }
|
|
996
999
|
.updates-history time { color: var(--ink2); font-variant-numeric: tabular-nums; white-space: nowrap; }
|
|
997
1000
|
.updates-history small { grid-column: 2; color: var(--ink2); overflow-wrap: anywhere; }
|
|
998
1001
|
.updates-history [data-result="rolled-back"], .updates-history [data-result="failed"] { color: var(--danger); }
|