clavarium 0.2.0 → 0.2.1-next.2
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 +41 -1
- package/deploy/install.sh +2 -1
- package/deploy/updater.mjs +220 -34
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/server/api.mjs +1 -1
- package/server/bridge.mjs +26 -3
- package/server/devices.mjs +9 -1
- package/server/door.mjs +3 -1
- package/server/main.mjs +45 -11
- package/server/updates.mjs +2 -2
- package/server/vmwatch.mjs +63 -0
- package/web/app.js +14 -4
- package/web/style.css +3 -0
package/deploy/clavarium-host
CHANGED
|
@@ -89,7 +89,7 @@ UPDATER="$CODE/current/app/deploy/updater.mjs"
|
|
|
89
89
|
UPDATE_STATE="/var/lib/clavarium/update"
|
|
90
90
|
|
|
91
91
|
refuse() { echo "REFUSED: $*" >&2; exit 78; }
|
|
92
|
-
usage() { echo "usage: clavarium-host [--say-only [--data DIR] [--mnt DIR]] <vm|shelf|folder|work|view|tools|net|git|server|update> <verb> [arguments]" >&2; exit 64; }
|
|
92
|
+
usage() { echo "usage: clavarium-host [--say-only [--data DIR] [--mnt DIR]] <vm|shelf|folder|work|view|tools|mounts|net|git|server|update> <verb> [arguments]" >&2; exit 64; }
|
|
93
93
|
|
|
94
94
|
SAY="no"; DATA=""; MNT=""
|
|
95
95
|
while [ $# -gt 0 ]; do
|
|
@@ -210,6 +210,22 @@ folder_of() {
|
|
|
210
210
|
held "$MNT/resources/$1"
|
|
211
211
|
}
|
|
212
212
|
|
|
213
|
+
# A VIEW WHOSE PROGRAM IS GONE (bindfs killed or crashed) stays mounted, but
|
|
214
|
+
# everything done there fails with "Transport endpoint is not connected": the
|
|
215
|
+
# view cannot be made again, and before 0.2.1 the server died at its start on
|
|
216
|
+
# it -- only a reboot cleared it (the update of 19-10). Such a mount is taken
|
|
217
|
+
# off (lazily: whatever still holds it gets an error, never a hang); one that
|
|
218
|
+
# answers is left alone. Only a FUSE mount exactly at that path, under $MNT.
|
|
219
|
+
unstale() {
|
|
220
|
+
[ "$SAY" = "yes" ] && return 0
|
|
221
|
+
local at="$1"
|
|
222
|
+
case "$at" in "$MNT"/views/*|"$MNT"/toolbox/view) : ;; *) refuse "not a view: $at" ;; esac
|
|
223
|
+
awk -v p="$at" '$2 == p && $3 ~ /^fuse/ { found = 1 } END { exit !found }' /proc/self/mounts || return 0
|
|
224
|
+
timeout 10 stat -- "$at" >/dev/null 2>&1 && return 0
|
|
225
|
+
umount -l -- "$at" || refuse "the broken view at $at could not be taken off"
|
|
226
|
+
echo "a broken view was taken off: $at" >&2
|
|
227
|
+
}
|
|
228
|
+
|
|
213
229
|
# How a finished read unit is said to the server: from what systemd recorded,
|
|
214
230
|
# never from what the code inside printed. See "git read".
|
|
215
231
|
unit_code() {
|
|
@@ -255,6 +271,16 @@ case "$AREA $VERB" in
|
|
|
255
271
|
[ $# -ge 3 ] || usage
|
|
256
272
|
vm="$1"; shift 2
|
|
257
273
|
run "$MULTIPASS" exec "$vm" -- "$@" ;;
|
|
274
|
+
"vm ping")
|
|
275
|
+
# Does the VM manager answer at all? Asked now and then by the server
|
|
276
|
+
# (vmwatch.mjs); bounded, so that a VM manager that hangs is an answer.
|
|
277
|
+
[ $# -eq 0 ] || usage
|
|
278
|
+
run timeout 25 "$MULTIPASS" list --format csv ;;
|
|
279
|
+
"vm revive")
|
|
280
|
+
# The VM manager has not answered for minutes: its daemon restarted.
|
|
281
|
+
# Asked by the server at most once in hours (vmwatch.mjs), never by a page.
|
|
282
|
+
[ $# -eq 0 ] || usage
|
|
283
|
+
run timeout 170 snap restart multipass.multipassd ;;
|
|
258
284
|
"vm info")
|
|
259
285
|
[ $# -eq 1 ] || usage; vm_of "$1"
|
|
260
286
|
run "$MULTIPASS" info "$1" --format json ;;
|
|
@@ -531,6 +557,7 @@ case "$AREA $VERB" in
|
|
|
531
557
|
[ $# -eq 1 ] || usage; is_name "$1" || refuse "not a folder name: $1"
|
|
532
558
|
folder_of "$1"; kept views
|
|
533
559
|
if [ "$SAY" != "yes" ]; then
|
|
560
|
+
unstale "$MNT/views/$1"
|
|
534
561
|
mkdir -p "$MNT/views/$1"
|
|
535
562
|
held "$MNT/views/$1"
|
|
536
563
|
mountpoint -q "$MNT/views/$1" && exit 0
|
|
@@ -548,6 +575,7 @@ case "$AREA $VERB" in
|
|
|
548
575
|
files="$MNT/toolbox/files"; view="$MNT/toolbox/view"
|
|
549
576
|
if [ "$SAY" = "yes" ]; then printf '%s\n' "install -d -o OWNER -g GROUP -m 0755 $files" "bindfs -r -o allow_other $files $view"; exit 0; fi
|
|
550
577
|
kept toolbox
|
|
578
|
+
unstale "$view"
|
|
551
579
|
[ ! -L "$files" ] && [ ! -L "$view" ] || refuse "the tools folder is not what it should be"
|
|
552
580
|
if [ ! -e "$files" ]; then owner="$(stat -c %u:%g "$DATA")"; install -d -o "${owner%:*}" -g "${owner#*:}" -m 0755 "$files"; fi
|
|
553
581
|
held "$files"
|
|
@@ -559,11 +587,23 @@ case "$AREA $VERB" in
|
|
|
559
587
|
[ $# -eq 1 ] || usage; is_name "$1" || refuse "not a folder name: $1"
|
|
560
588
|
kept views
|
|
561
589
|
if [ "$SAY" != "yes" ]; then
|
|
590
|
+
unstale "$MNT/views/$1"
|
|
562
591
|
[ -e "$MNT/views/$1" ] || exit 0
|
|
563
592
|
held "$MNT/views/$1"
|
|
564
593
|
mountpoint -q "$MNT/views/$1" || exit 0
|
|
565
594
|
fi
|
|
566
595
|
run umount "$MNT/views/$1" ;;
|
|
596
|
+
"mounts repair")
|
|
597
|
+
# Every broken view taken off (see unstale): asked by the server as it
|
|
598
|
+
# starts, and by the updater (root) after each stop of the server, so
|
|
599
|
+
# that a view left broken never needs a reboot. Says what it did.
|
|
600
|
+
[ $# -eq 0 ] || usage
|
|
601
|
+
if [ "$SAY" = "yes" ]; then echo "umount -l <each FUSE view under $MNT that does not answer>"; exit 0; fi
|
|
602
|
+
kept views; kept toolbox
|
|
603
|
+
awk '$3 ~ /^fuse/ { print $2 }' /proc/self/mounts | while IFS= read -r at; do
|
|
604
|
+
case "$at" in "$MNT"/views/*|"$MNT"/toolbox/view) unstale "$at" ;; esac
|
|
605
|
+
done
|
|
606
|
+
exit 0 ;;
|
|
567
607
|
"net taps")
|
|
568
608
|
[ $# -eq 0 ] || usage
|
|
569
609
|
run pgrep -a qemu-system ;;
|
package/deploy/install.sh
CHANGED
|
@@ -551,7 +551,8 @@ fi
|
|
|
551
551
|
# with Let's Encrypt's as soon as it can (sudo clavarium doctor --certificate).
|
|
552
552
|
BIND=""; [ -z "$RELAY" ] || BIND=" bind 127.0.0.1"
|
|
553
553
|
# The probe's token: kept on a rerun (see deploy/doctor.mjs, probeBlock).
|
|
554
|
-
|
|
554
|
+
# No Caddyfile yet (going online from local mode): no token, not a failure (pipefail).
|
|
555
|
+
PROBE="$( { sed -n 's/.*respond "\([0-9a-f]\{32\}\)" 200.*/\1/p' /etc/caddy/Caddyfile 2>/dev/null || true; } | head -1)"
|
|
555
556
|
[ -n "$PROBE" ] || PROBE="$(openssl rand -hex 16)"
|
|
556
557
|
cat > /etc/caddy/Caddyfile <<CADDY
|
|
557
558
|
# The only thing on this machine that takes what comes from the outside.
|
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,24 @@ 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
|
+
/* Restarts by systemd, the server not answering: it is looping (a port held, a view broken). */
|
|
73
|
+
const WATCH_LOOP = 3;
|
|
74
|
+
const WATCH_EVERY_MS = 3600_000;
|
|
75
|
+
/* An update this recent is the first suspect when the server will not stay up. */
|
|
76
|
+
const WATCH_RECENT_MS = 24 * 3600_000;
|
|
68
77
|
const HISTORY_MAX = 30;
|
|
69
78
|
const ASK_EVERY_MS = 6 * 3600_000;
|
|
70
79
|
const PROVENANCE = 'https://slsa.dev/provenance/v1';
|
|
80
|
+
/* What the log of a failure keeps, at most (history entry `log`, shown behind "See the log"). */
|
|
81
|
+
const LOG_MAX = 12_000;
|
|
82
|
+
/* Set beside the server's unit by the updater (root): a crash loop never locks the service out, so a
|
|
83
|
+
restart asked later (an update, the watchdog) still starts it. */
|
|
84
|
+
export const DROP_IN = '/etc/systemd/system/clavarium.service.d/restart.conf';
|
|
85
|
+
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
86
|
|
|
72
87
|
export class Refused extends Error {}
|
|
73
88
|
|
|
@@ -142,16 +157,27 @@ const toHex = (integrity) => Buffer.from(String(integrity).replace(/^sha512-/, '
|
|
|
142
157
|
export class Updater {
|
|
143
158
|
#o; #run; #fetch;
|
|
144
159
|
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
|
-
|
|
160
|
+
verifySignatures, restart, health, backup, restoreData, installPrivileged, ensureNode, serviceState, answers, restarts, mainPid, pidCwd, diagnose, dropIn = DROP_IN,
|
|
161
|
+
clock = () => Date.now(), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), minFreeMb = 1024, healthMs = 60_000, watchMs = 120_000, settleMs = 10_000 } = {}) {
|
|
162
|
+
this.#o = { code, conf, stateDir, data, hostTarget, gitReadTarget, registry: registry.replace(/\/$/, ''), now, log, minFreeMb, healthMs, watchMs, settleMs, clock, sleep, dropIn };
|
|
147
163
|
this.#run = run; this.#fetch = fetcher;
|
|
148
164
|
this.verifySignatures = verifySignatures ?? ((dir) => this.#npm(['audit', 'signatures'], { cwd: dir, timeoutMs: 300_000 }));
|
|
149
|
-
this.restart = restart ?? (() => this.#
|
|
165
|
+
this.restart = restart ?? (() => this.#restart());
|
|
166
|
+
/* What was seen when the server did not come up: its journal, its unit, who holds its port. */
|
|
167
|
+
this.diagnose = diagnose ?? (() => this.#diagnose());
|
|
150
168
|
this.health = health ?? ((release) => this.#health(release));
|
|
151
169
|
this.backup = backup ?? ((app) => this.#backup(app));
|
|
152
170
|
this.restoreData = restoreData ?? ((app, archive) => this.#restoreData(app, archive));
|
|
153
171
|
this.installPrivileged = installPrivileged ?? ((app) => this.#installPrivileged(app));
|
|
154
172
|
this.ensureNode = ensureNode ?? ((app) => this.#ensureNode(app));
|
|
173
|
+
/* What systemd says of the server: 'active', 'activating', 'failed', 'inactive'... */
|
|
174
|
+
this.serviceState = serviceState ?? (async () => (await this.#run(['systemctl', 'show', '-p', 'ActiveState', '--value', 'clavarium.service'], { timeoutMs: 10_000 })).stdout.trim() || 'unknown');
|
|
175
|
+
/* Does the server answer, on its port, here? */
|
|
176
|
+
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));
|
|
177
|
+
/* How many times systemd started it again by itself since it was last started. */
|
|
178
|
+
this.restarts = restarts ?? (async () => Number((await this.#run(['systemctl', 'show', '-p', 'NRestarts', '--value', 'clavarium.service'], { timeoutMs: 10_000 })).stdout.trim()) || 0);
|
|
179
|
+
this.mainPid = mainPid ?? (async () => (await this.#run(['systemctl', 'show', '-p', 'MainPID', '--value', 'clavarium.service'], { timeoutMs: 10_000 })).stdout.trim());
|
|
180
|
+
this.pidCwd = pidCwd ?? ((pid) => { try { return realpathSync(`/proc/${pid}/cwd`); } catch { return ''; } });
|
|
155
181
|
}
|
|
156
182
|
|
|
157
183
|
get releasesDir() { return join(this.#o.code, 'releases'); }
|
|
@@ -340,12 +366,26 @@ export class Updater {
|
|
|
340
366
|
renameSync(`${link}.new`, link);
|
|
341
367
|
}
|
|
342
368
|
|
|
343
|
-
/* A conversation in the middle of a build, a move or a restart: '' or why not now.
|
|
344
|
-
|
|
369
|
+
/* A conversation in the middle of a build, a move or a restart: '' or why not now.
|
|
370
|
+
Only while the server runs (a phase in the file of a server that is down is not going on), and
|
|
371
|
+
only a phase younger than BUSY_STALE_MS (older: cut short; the server settles it when it starts). */
|
|
372
|
+
async busy() {
|
|
373
|
+
const file = join(this.#o.data, 'conversations.json');
|
|
345
374
|
let all = [];
|
|
346
|
-
try { all = JSON.parse(readFileSync(
|
|
347
|
-
const busy = (Array.isArray(all) ? all : []).filter((c) => BUSY.includes(c.phase))
|
|
348
|
-
|
|
375
|
+
try { all = JSON.parse(readFileSync(file, 'utf8')); } catch { return ''; }
|
|
376
|
+
const busy = (Array.isArray(all) ? all : []).filter((c) => c && BUSY.includes(c.phase));
|
|
377
|
+
if (!busy.length) return '';
|
|
378
|
+
const names = (list) => list.slice(0, 3).map((c) => c.name).join(', ');
|
|
379
|
+
const state = await this.serviceState().catch(() => 'unknown');
|
|
380
|
+
if (state !== 'active') { this.#o.log(`busy phases not waited for: the server is ${state} (${names(busy)})`); return ''; }
|
|
381
|
+
let written = this.#o.now().getTime();
|
|
382
|
+
try { written = statSync(file).mtimeMs; } catch { /* now */ }
|
|
383
|
+
const now = this.#o.now().getTime();
|
|
384
|
+
const since = (c) => { const t = Date.parse(c.restartingSince ?? c.buildingSince ?? c.movingSince ?? ''); return Number.isFinite(t) ? t : written; };
|
|
385
|
+
const stale = busy.filter((c) => now - since(c) > BUSY_STALE_MS);
|
|
386
|
+
if (stale.length) this.#o.log(`busy phases older than 30 minutes not waited for: ${names(stale)}`);
|
|
387
|
+
const live = busy.filter((c) => !stale.includes(c));
|
|
388
|
+
return live.length ? `a machine is being built or restarted (${names(live)}): the update waits` : '';
|
|
349
389
|
}
|
|
350
390
|
#dataFormat() { try { return JSON.parse(readFileSync(join(this.#o.data, 'data-format.json'), 'utf8')).format; } catch { return undefined; } }
|
|
351
391
|
|
|
@@ -356,7 +396,9 @@ export class Updater {
|
|
|
356
396
|
try { const fd = openSync(file, 'wx'); writeFileSync(fd, String(process.pid)); closeSync(fd); return () => rmSync(file, { force: true }); } catch (error) {
|
|
357
397
|
if (error.code !== 'EEXIST') throw error;
|
|
358
398
|
const pid = Number(readFileSync(file, 'utf8')) || 0;
|
|
359
|
-
|
|
399
|
+
/* A lock left by a process that is gone (killed, the machine stopped) is taken over. */
|
|
400
|
+
let alive = false; try { if (pid) { process.kill(pid, 0); alive = true; } } catch (e) { alive = e.code === 'EPERM'; }
|
|
401
|
+
if (!alive) this.#o.log(`a stale lock (process ${pid || '?'} is gone): taken over`);
|
|
360
402
|
if (alive) throw new Refused('an update or an installation is running already');
|
|
361
403
|
rmSync(file, { force: true });
|
|
362
404
|
}
|
|
@@ -371,7 +413,7 @@ export class Updater {
|
|
|
371
413
|
/* Asked for the version that runs (a request that waited while it came by itself): done already. */
|
|
372
414
|
if (from && compareVersions(version, from.version) === 0) return;
|
|
373
415
|
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);
|
|
416
|
+
const why = await this.busy(); if (why) throw new Refused(why);
|
|
375
417
|
const unlock = this.#lock();
|
|
376
418
|
try {
|
|
377
419
|
let release;
|
|
@@ -382,7 +424,7 @@ export class Updater {
|
|
|
382
424
|
this.#step('update', version, 'Backing up');
|
|
383
425
|
archive = await this.backup(from?.app ?? release.app);
|
|
384
426
|
} 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();
|
|
427
|
+
const late = await this.busy();
|
|
386
428
|
if (late) { this.#history({ action: 'update', from: from?.version ?? null, to: version, result: 'failed', why: late }); throw new Refused(late); }
|
|
387
429
|
const failed = await this.#switchAndCheck(release, 'update', version);
|
|
388
430
|
if (!failed) {
|
|
@@ -390,18 +432,19 @@ export class Updater {
|
|
|
390
432
|
this.prune();
|
|
391
433
|
return this.about();
|
|
392
434
|
}
|
|
393
|
-
/* IT DID NOT COME UP: back to what ran, its data too if it moved. */
|
|
435
|
+
/* IT DID NOT COME UP: what was seen kept, then back to what ran, its data too if it moved. */
|
|
394
436
|
let why2 = failed;
|
|
437
|
+
let log = await this.#seen(`${version} did not come up: ${failed}`);
|
|
395
438
|
if (from) {
|
|
396
439
|
this.#step('update', version, 'Going back');
|
|
397
440
|
this.switchTo(from.id);
|
|
398
441
|
await this.installPrivileged(from.app).catch(() => {});
|
|
399
442
|
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
443
|
const back = await this.#restartAndCheck(from);
|
|
401
|
-
if (back) why2 += `; ${from.version} did not come back either (${back}): journalctl -u clavarium`;
|
|
444
|
+
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
445
|
rmSync(release.dir, { recursive: true, force: true });
|
|
403
446
|
}
|
|
404
|
-
this.#history({ action: 'update', from: from?.version ?? null, to: version, result: from ? 'rolled-back' : 'failed', why: why2 });
|
|
447
|
+
this.#history({ action: 'update', from: from?.version ?? null, to: version, result: from ? 'rolled-back' : 'failed', why: why2, log: log.slice(-LOG_MAX) });
|
|
405
448
|
this.prune();
|
|
406
449
|
return this.about();
|
|
407
450
|
} finally { unlock(); }
|
|
@@ -416,19 +459,20 @@ export class Updater {
|
|
|
416
459
|
if (to.current) throw new Refused(`${id} is the release that runs`);
|
|
417
460
|
const format = this.#dataFormat();
|
|
418
461
|
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);
|
|
462
|
+
const why = await this.busy(); if (why) throw new Refused(why);
|
|
420
463
|
const unlock = this.#lock();
|
|
421
464
|
try {
|
|
422
465
|
const failed = await this.#switchAndCheck(to, 'back', to.version);
|
|
423
466
|
if (!failed) { this.#history({ action: 'back', from: from?.version ?? null, to: to.version, result: 'done' }); return this.about(); }
|
|
424
467
|
let why2 = failed;
|
|
468
|
+
let log = await this.#seen(`${to.version} did not come up: ${failed}`);
|
|
425
469
|
if (from) {
|
|
426
470
|
this.switchTo(from.id);
|
|
427
471
|
await this.installPrivileged(from.app).catch(() => {});
|
|
428
472
|
const back = await this.#restartAndCheck(from);
|
|
429
|
-
if (back) why2 += `; ${from.version} did not come back either (${back})`;
|
|
473
|
+
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
474
|
}
|
|
431
|
-
this.#history({ action: 'back', from: from?.version ?? null, to: to.version, result: 'failed', why: why2 });
|
|
475
|
+
this.#history({ action: 'back', from: from?.version ?? null, to: to.version, result: 'failed', why: why2, log: log.slice(-LOG_MAX) });
|
|
432
476
|
return this.about();
|
|
433
477
|
} finally { unlock(); }
|
|
434
478
|
}
|
|
@@ -455,7 +499,7 @@ export class Updater {
|
|
|
455
499
|
const all = this.releases();
|
|
456
500
|
const current = all.find((r) => r.current);
|
|
457
501
|
/* 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');
|
|
502
|
+
const last = (this.#state().history ?? []).find((h) => h.result === 'done' && h.action !== 'restart');
|
|
459
503
|
const previous = all.find((r) => !r.current && last && r.version === last.from) ?? all.find((r) => !r.current);
|
|
460
504
|
const keep = new Set([current?.id, previous?.id].filter(Boolean));
|
|
461
505
|
for (const r of all) if (!keep.has(r.id)) rmSync(r.dir, { recursive: true, force: true });
|
|
@@ -482,13 +526,71 @@ export class Updater {
|
|
|
482
526
|
if (conf.MODE === 'ask') return `${available} is out: waiting for the owner`;
|
|
483
527
|
/* A version that failed here is not tried again by itself: the owner can, from Settings. */
|
|
484
528
|
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
|
-
|
|
529
|
+
const why = await this.busy(); if (why) return why;
|
|
486
530
|
await this.apply(available);
|
|
487
531
|
/* What the history says, not what was hoped: a version that did not start was undone. */
|
|
488
|
-
const last = (this.#state().history ?? [])
|
|
532
|
+
const last = (this.#state().history ?? [])[0];
|
|
489
533
|
return last?.to === available && last.result !== 'done' ? `${available} did not work: back to ${last.from ?? 'nothing'} (${last.why ?? last.result})` : `updated to ${available}`;
|
|
490
534
|
}
|
|
491
535
|
|
|
536
|
+
/* THE WATCHDOG, at each timer turn: the server down (its service failed, stopped, or starting
|
|
537
|
+
again and again; or no answer WATCH_MISSES turns in a row) is acted on, once, and said in the
|
|
538
|
+
history:
|
|
539
|
+
- first, one restart of the release that runs: what blocked the old server (a process left
|
|
540
|
+
on its port, a view left broken) is cleared by the restart itself (#restart), and the new
|
|
541
|
+
version is seldom the cause (19-10: going back cured nothing);
|
|
542
|
+
- only if it does not come back, after an update of less than WATCH_RECENT_MS with the
|
|
543
|
+
release before it kept (and able to read the data): back to it, by itself, not tried
|
|
544
|
+
again by itself.
|
|
545
|
+
Never more than one action in WATCH_EVERY_MS, so that it never loops. { acted, said } */
|
|
546
|
+
async watchdog() {
|
|
547
|
+
const state = await this.serviceState().catch(() => 'unknown');
|
|
548
|
+
const up = state === 'active' && await this.answers().catch(() => false);
|
|
549
|
+
const w = this.#state().watch ?? {};
|
|
550
|
+
if (up) { if (w.misses) this.#save({ watch: { ...w, misses: 0 } }); return { acted: false, said: 'up' }; }
|
|
551
|
+
const misses = (w.misses ?? 0) + 1;
|
|
552
|
+
this.#save({ watch: { ...w, misses, seen: state } });
|
|
553
|
+
/* Started again and again by systemd (seen "activating", or "active" for the second before it
|
|
554
|
+
dies again: many restarts by itself) is down at once, like failed or stopped. */
|
|
555
|
+
const looping = state === 'activating' || await this.restarts().catch(() => 0) >= WATCH_LOOP;
|
|
556
|
+
const down = state === 'failed' || state === 'inactive' || looping || misses >= WATCH_MISSES;
|
|
557
|
+
this.#o.log(`watchdog: the server is ${state === 'active' ? 'active but does not answer' : state} (turn ${misses})`);
|
|
558
|
+
if (!down) return { acted: false, said: `the server does not answer (turn ${misses} of ${WATCH_MISSES})` };
|
|
559
|
+
const now = this.#o.now();
|
|
560
|
+
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' };
|
|
561
|
+
let unlock;
|
|
562
|
+
try { unlock = this.#lock(); } catch (error) { if (error instanceof Refused) return { acted: false, said: 'the server is down, but an update runs' }; throw error; }
|
|
563
|
+
try {
|
|
564
|
+
this.#save({ watch: { misses: 0, actedAt: now.toISOString(), seen: state } });
|
|
565
|
+
const log = await this.#seen(`the server was down (${state})`);
|
|
566
|
+
const current = this.current();
|
|
567
|
+
const v = current?.version ?? null;
|
|
568
|
+
const was = looping ? 'starting again and again' : state === 'active' ? 'no answer' : state;
|
|
569
|
+
this.#o.log(`watchdog: the server is ${state}: restarted once`);
|
|
570
|
+
const failed = current ? await this.#restartAndCheck(current) : await this.restart().then((r) => (r?.code ? lastLine(r) : '')).catch((e) => e.message);
|
|
571
|
+
/* The last update or return (a restart by the watchdog is not one). */
|
|
572
|
+
const last = (this.#state().history ?? []).find((h) => h.action !== 'restart');
|
|
573
|
+
const recent = failed && current && last && last.action === 'update' && last.result === 'done' && last.to === current.version && now - new Date(last.at) < WATCH_RECENT_MS;
|
|
574
|
+
const previous = recent ? this.releases().find((r) => !r.current && r.version === last.from) : undefined;
|
|
575
|
+
const format = this.#dataFormat();
|
|
576
|
+
if (previous && (format === undefined || previous.dataFormat >= format)) {
|
|
577
|
+
let why = `${current.version} did not stay up (its service ${state === 'active' ? 'did not answer' : `was ${state}`}) nor came back after a restart (${failed}): back to ${previous.version}`;
|
|
578
|
+
this.#o.log(`watchdog: ${why}`);
|
|
579
|
+
this.#step('update', current.version, 'Going back');
|
|
580
|
+
let back;
|
|
581
|
+
try { this.switchTo(previous.id); await this.installPrivileged(previous.app).catch(() => {}); back = await this.#restartAndCheck(previous); } catch (error) { back = error.message; }
|
|
582
|
+
if (back) why += `; ${previous.version} did not come back either (${back}): journalctl -u clavarium`;
|
|
583
|
+
else rmSync(current.dir, { recursive: true, force: true });
|
|
584
|
+
this.#history({ action: 'update', from: previous.version, to: current.version, result: 'rolled-back', by: 'watchdog', why, log: log.slice(-LOG_MAX) });
|
|
585
|
+
this.prune();
|
|
586
|
+
return { acted: true, said: why };
|
|
587
|
+
}
|
|
588
|
+
const why = `the server was down (${was}): restarted by itself${failed ? `; it did not come back (${failed}): journalctl -u clavarium` : ''}`;
|
|
589
|
+
this.#history({ action: 'restart', from: v, to: v, result: failed ? 'failed' : 'done', by: 'watchdog', why, log: log.slice(-LOG_MAX) });
|
|
590
|
+
return { acted: true, said: why };
|
|
591
|
+
} finally { unlock(); }
|
|
592
|
+
}
|
|
593
|
+
|
|
492
594
|
/* What the host program asked (a request file), or the timer's turn. */
|
|
493
595
|
async runOnce() {
|
|
494
596
|
const file = join(this.#o.stateDir, 'request');
|
|
@@ -502,6 +604,9 @@ export class Updater {
|
|
|
502
604
|
await this.check().catch(() => {});
|
|
503
605
|
return r;
|
|
504
606
|
}
|
|
607
|
+
/* The timer's turn: first, is the server up? (it may have died after an update that looked well) */
|
|
608
|
+
const watched = await this.watchdog();
|
|
609
|
+
if (watched.acted) return watched.said;
|
|
505
610
|
return await this.tick();
|
|
506
611
|
} catch (error) {
|
|
507
612
|
if (error instanceof Refused && request) this.#save({ refused: { at: this.#o.now().toISOString(), why: error.message } });
|
|
@@ -509,28 +614,107 @@ export class Updater {
|
|
|
509
614
|
}
|
|
510
615
|
}
|
|
511
616
|
|
|
617
|
+
/* What was seen, as text: never fails (a log that could not be read says so). */
|
|
618
|
+
async #seen(title) {
|
|
619
|
+
const text = await Promise.resolve().then(() => this.diagnose()).catch((e) => `the log could not be read: ${e.message}`);
|
|
620
|
+
return `== ${this.#o.now().toISOString()} ${title}\n${String(text ?? '').trim()}`;
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
/* THE DROP-IN beside the server's unit: written when it differs, then systemd told. true when written. */
|
|
624
|
+
async ensureDropIn() {
|
|
625
|
+
const file = this.#o.dropIn;
|
|
626
|
+
try { if (readFileSync(file, 'utf8') === DROP_IN_TEXT) return false; } catch { /* not there */ }
|
|
627
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o755 });
|
|
628
|
+
writeFileSync(`${file}.new`, DROP_IN_TEXT, { mode: 0o644 });
|
|
629
|
+
renameSync(`${file}.new`, file);
|
|
630
|
+
if (process.getuid?.() === 0) await this.#run(['systemctl', 'daemon-reload'], { timeoutMs: 60_000 });
|
|
631
|
+
return true;
|
|
632
|
+
}
|
|
633
|
+
|
|
512
634
|
/* ------------------------- the real machine's ways ------------------------- */
|
|
513
|
-
|
|
635
|
+
/* The processes still there after a stop: in the unit's cgroup, or holding its port. [{ pid, state, port }] */
|
|
636
|
+
async #leftovers() {
|
|
637
|
+
const port = readConf(this.#o.conf).PORT;
|
|
638
|
+
const pids = new Map();
|
|
639
|
+
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 */ }
|
|
640
|
+
const ss = await this.#run(['ss', '-Hltnp', `sport = :${port}`], { timeoutMs: 10_000 });
|
|
641
|
+
for (const m of String(ss.stdout).matchAll(/pid=(\d+)/g)) pids.set(m[1], true);
|
|
642
|
+
return [...pids].map(([pid, holds]) => {
|
|
643
|
+
let state = '?';
|
|
644
|
+
try { state = /^State:\s+(\S)/m.exec(readFileSync(`/proc/${pid}/status`, 'utf8'))?.[1] ?? '?'; } catch { state = 'gone'; }
|
|
645
|
+
return { pid: Number(pid), state, port: holds };
|
|
646
|
+
}).filter((p) => p.state !== 'gone');
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/* A RESTART that does not trust the stop: its failures forgotten (reset-failed), stopped, and
|
|
650
|
+
what is left of the old server looked at -- killed, or, when it cannot be (state D: waiting on
|
|
651
|
+
the kernel), said precisely: then nothing would answer on the port before a reboot. */
|
|
652
|
+
async #restart() {
|
|
653
|
+
await this.#run(['systemctl', 'reset-failed', 'clavarium.service'], { timeoutMs: 30_000 });
|
|
654
|
+
await this.#run(['systemctl', 'stop', 'clavarium.service'], { timeoutMs: 120_000 });
|
|
655
|
+
let left = await this.#leftovers();
|
|
656
|
+
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 */ } }
|
|
657
|
+
if (left.length) { await this.#o.sleep(2000); left = await this.#leftovers(); }
|
|
658
|
+
const stuck = left.filter((x) => x.state === 'D' && x.port);
|
|
659
|
+
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` };
|
|
660
|
+
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(', ')}`);
|
|
661
|
+
/* The views the old server left broken (their program killed with it): taken off, or the
|
|
662
|
+
new server could not make them again before a reboot. Never a reason not to start. */
|
|
663
|
+
const repaired = await this.#run([this.#o.hostTarget, 'mounts', 'repair'], { timeoutMs: 60_000 });
|
|
664
|
+
if (repaired.code || String(repaired.stderr).trim()) this.#o.log(`mounts: ${String(repaired.stderr).trim() || `exit ${repaired.code}`}`);
|
|
665
|
+
await this.#run(['systemctl', 'reset-failed', 'clavarium.service'], { timeoutMs: 30_000 });
|
|
666
|
+
return this.#run(['systemctl', 'start', 'clavarium.service'], { timeoutMs: 120_000 });
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
async #diagnose() {
|
|
514
670
|
const port = readConf(this.#o.conf).PORT;
|
|
515
|
-
const
|
|
671
|
+
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()}`; };
|
|
672
|
+
const left = await this.#leftovers().catch(() => []);
|
|
673
|
+
return [
|
|
674
|
+
await part('systemctl status clavarium', ['systemctl', 'status', 'clavarium.service', '--no-pager', '-n', '0']),
|
|
675
|
+
await part(`who listens on ${port}`, ['ss', '-Hltnp', `sport = :${port}`]),
|
|
676
|
+
`-- 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'}`,
|
|
677
|
+
await part('journalctl -u clavarium -n 80', ['journalctl', '-u', 'clavarium.service', '-n', '80', '--no-pager', '-o', 'short-iso']),
|
|
678
|
+
].join('\n');
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
/* Comes up (answers, from this release) within healthMs, then STAYS up: watched until watchMs after
|
|
682
|
+
the restart; one restart by systemd is forgiven if it answers at the end, not two. */
|
|
683
|
+
async #health(release) {
|
|
684
|
+
const { clock, sleep } = this.#o;
|
|
685
|
+
const start = clock();
|
|
516
686
|
const target = realpathSync(release.dir);
|
|
687
|
+
const mine = async () => { const pid = await this.mainPid(); return { pid, ok: !!pid && pid !== '0' && this.pidCwd(pid).startsWith(target) }; };
|
|
517
688
|
let said = 'it did not answer';
|
|
689
|
+
let pid = '';
|
|
518
690
|
for (;;) {
|
|
519
|
-
const
|
|
520
|
-
const answered =
|
|
691
|
+
const state = await this.serviceState().catch(() => 'unknown');
|
|
692
|
+
const answered = state === 'active' && await this.answers().catch(() => false);
|
|
521
693
|
if (answered) {
|
|
522
|
-
const
|
|
523
|
-
|
|
524
|
-
if (cwd.startsWith(target)) break;
|
|
694
|
+
const m = await mine();
|
|
695
|
+
if (m.ok) { pid = m.pid; break; }
|
|
525
696
|
said = 'the server that answers is not this release';
|
|
526
|
-
} else if (active
|
|
527
|
-
if (
|
|
528
|
-
await
|
|
697
|
+
} else if (state !== 'active' && state !== 'activating') said = 'its service stopped';
|
|
698
|
+
if (clock() - start > this.#o.healthMs) return said;
|
|
699
|
+
await sleep(1000);
|
|
529
700
|
}
|
|
530
701
|
/* And it stays up. */
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
702
|
+
const until = Math.max(start + this.#o.watchMs, clock() + this.#o.settleMs);
|
|
703
|
+
let restarts = 0;
|
|
704
|
+
while (clock() < until) {
|
|
705
|
+
await sleep(Math.min(5000, Math.max(1, until - clock())));
|
|
706
|
+
const now = await this.mainPid().catch(() => '');
|
|
707
|
+
if (now && now !== '0' && now !== pid) { restarts += 1; pid = now; }
|
|
708
|
+
if (restarts > 1) return 'the server stopped more than once in its first minutes';
|
|
709
|
+
}
|
|
710
|
+
/* At the end: it answers, from this release (a moment given if it is in its one restart). */
|
|
711
|
+
const last = clock() + this.#o.settleMs;
|
|
712
|
+
for (;;) {
|
|
713
|
+
const state = await this.serviceState().catch(() => 'unknown');
|
|
714
|
+
if (state === 'active' && await this.answers().catch(() => false) && (await mine()).ok) return '';
|
|
715
|
+
if (clock() > last) return restarts ? 'the server stopped soon after it started, and did not answer again' : 'the server stopped soon after it started';
|
|
716
|
+
await sleep(1000);
|
|
717
|
+
}
|
|
534
718
|
}
|
|
535
719
|
|
|
536
720
|
async #backup(app) {
|
|
@@ -554,6 +738,7 @@ export class Updater {
|
|
|
554
738
|
const r = await this.#run(['install', '-o', 'root', '-g', 'root', '-m', '0755', from, to], { timeoutMs: 30_000 });
|
|
555
739
|
if (r.code !== 0) throw new Error(`${to}: ${lastLine(r)}`);
|
|
556
740
|
}
|
|
741
|
+
await this.ensureDropIn().catch((error) => this.#o.log(`the drop-in of the server's unit could not be written: ${error.message}`));
|
|
557
742
|
/* What a release sets up beside itself (the certificate timer): an update does not run install.sh again.
|
|
558
743
|
Best effort: the update does not depend on it; `sudo clavarium doctor` says when it is missing. */
|
|
559
744
|
const node = join(dirname(app), 'node', 'bin', 'node');
|
|
@@ -599,6 +784,7 @@ async function main(argv) {
|
|
|
599
784
|
/* What this release sets up beside itself (the certificate timer), at its first turn: the
|
|
600
785
|
update that brought it ran the PREVIOUS release's code. Idempotent; never stops the turn. */
|
|
601
786
|
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}`); }
|
|
787
|
+
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
788
|
const r = await u.runOnce(); console.log(typeof r === 'string' ? r : 'done'); return; }
|
|
603
789
|
case 'set': if (rest.length !== 2) throw new Refused('set <mode|channel|window|port> <value>'); return print(u.set(rest[0], rest[1]));
|
|
604
790
|
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.2",
|
|
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.2",
|
|
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/bridge.mjs
CHANGED
|
@@ -29,6 +29,8 @@ export const PATH = '/terminal';
|
|
|
29
29
|
export const DEVICE_PATH = '/c/terminal';
|
|
30
30
|
export const CLOSE_ENDED = 1000;
|
|
31
31
|
export const CLOSE_TAKEN = 4001;
|
|
32
|
+
/* A device whose right on this terminal was taken back (or its session ended): put out at once. */
|
|
33
|
+
export const CLOSE_REVOKED = 4003;
|
|
32
34
|
/* A channel that dropped is reopened after a moment, a few times a minute at most. */
|
|
33
35
|
export const REOPEN_AFTER_MS = 1000;
|
|
34
36
|
export const REDRAW_AFTER_MS = 250;
|
|
@@ -82,15 +84,33 @@ export const sameOrigin = makeOriginCheck();
|
|
|
82
84
|
export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () => {}, originOk = sameOrigin, gate = () => 'local', deviceName = () => undefined, onRejoin = () => {}, onTyped = () => {} }) {
|
|
83
85
|
const sockets = new WebSocketServer({ noServer: true });
|
|
84
86
|
const seats = new Seats();
|
|
87
|
+
/* THE DEVICES AT A TERMINAL, each with what lets it stay: asked again when the owner changes
|
|
88
|
+
what devices were given (recheck), and before anything it types is typed. A right taken
|
|
89
|
+
back used to end only at the next connection -- an open terminal went on (found 19-10). */
|
|
90
|
+
const deviceSeats = new Map(); /* viewer -> () => still allowed */
|
|
91
|
+
const revoked = new WeakSet();
|
|
92
|
+
const allowed = (viewer) => {
|
|
93
|
+
if (revoked.has(viewer)) return false;
|
|
94
|
+
const still = deviceSeats.get(viewer);
|
|
95
|
+
if (!still || still()) return true;
|
|
96
|
+
revoked.add(viewer); deviceSeats.delete(viewer);
|
|
97
|
+
viewer.close(CLOSE_REVOKED, 'not given any more');
|
|
98
|
+
/* A device that does not answer the close is not waited for. */
|
|
99
|
+
setTimeout(() => viewer.terminate(), 2000).unref?.();
|
|
100
|
+
return false;
|
|
101
|
+
};
|
|
85
102
|
|
|
86
103
|
server.on('upgrade', (request, socket, head) => {
|
|
87
104
|
const url = new URL(request.url ?? '/', 'http://local');
|
|
88
105
|
let name;
|
|
106
|
+
let still;
|
|
89
107
|
if (url.pathname === DEVICE_PATH) {
|
|
90
108
|
/* A device: no operator identity is looked at, and none is needed. */
|
|
91
109
|
/* `d`: which of its pairings this device speaks for. */
|
|
92
|
-
|
|
110
|
+
const ask = () => deviceName(request.headers, url.searchParams.get('d') ?? '', url.searchParams.get('c') ?? undefined) ?? '';
|
|
111
|
+
name = ask();
|
|
93
112
|
if (!isConversationName(name) || !originOk(request.headers)) { socket.destroy(); return; }
|
|
113
|
+
still = () => ask() === name;
|
|
94
114
|
} else if (url.pathname === PATH) {
|
|
95
115
|
name = url.searchParams.get('c') ?? '';
|
|
96
116
|
if (!isConversationName(name) || !originOk(request.headers) || gate(request.headers) === undefined) { socket.destroy(); return; }
|
|
@@ -98,6 +118,7 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
|
|
|
98
118
|
const cols = Number(url.searchParams.get('cols'));
|
|
99
119
|
const rows = Number(url.searchParams.get('rows'));
|
|
100
120
|
sockets.handleUpgrade(request, socket, head, (viewer) => {
|
|
121
|
+
if (still) { deviceSeats.set(viewer, still); viewer.on('close', () => deviceSeats.delete(viewer)); }
|
|
101
122
|
seat(viewer, name, within(cols, COLS) ? cols : 80, within(rows, ROWS) ? rows : 24);
|
|
102
123
|
});
|
|
103
124
|
});
|
|
@@ -236,7 +257,7 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
|
|
|
236
257
|
if (viewer.readyState === 1) viewer.send(JSON.stringify({ type: 'ready' }));
|
|
237
258
|
const mine = kept;
|
|
238
259
|
viewer.on('message', (data, binary) => {
|
|
239
|
-
if (mine.sink !== viewer) return;
|
|
260
|
+
if (mine.sink !== viewer || !allowed(viewer)) return;
|
|
240
261
|
/* `onTyped`: told THAT something came from a screen (the owner is there), which is not reading what the tool prints. */
|
|
241
262
|
if (binary) {
|
|
242
263
|
const typed = data.toString();
|
|
@@ -296,5 +317,7 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
|
|
|
296
317
|
since anything came out of it -- THAT something came, never what: a
|
|
297
318
|
tool still drawing its first screen is not reading its keyboard yet. */
|
|
298
319
|
const settled = (name) => { const kept = live.get(name); return kept ? { openFor: Date.now() - kept.openedAt, quietFor: Date.now() - kept.outputAt } : null; };
|
|
299
|
-
|
|
320
|
+
/* What devices were given changed: each device at a terminal is asked again. */
|
|
321
|
+
const recheck = () => { for (const viewer of [...deviceSeats.keys()]) allowed(viewer); };
|
|
322
|
+
return { seats, drop, warm, type, settled, recheck, open: (name) => live.has(name), droppedAt: (name) => dropped.get(name) };
|
|
300
323
|
}
|
package/server/devices.mjs
CHANGED
|
@@ -60,6 +60,7 @@ export class Devices {
|
|
|
60
60
|
conversation was shared in two parts (see below). */
|
|
61
61
|
constructor(store, now = () => Date.now(), grants = new Grants(), { chatWas = () => false } = {}) {
|
|
62
62
|
this.#store = store; this.#now = now; this.#grants = grants;
|
|
63
|
+
this.changed = () => {};
|
|
63
64
|
/* Sessions outlive a restart of this server (a new version put in place): what is kept is
|
|
64
65
|
only their sha256 and their end, on the device's record, never the session itself. */
|
|
65
66
|
for (const d of store.all()) for (const k of Array.isArray(d.sessions) ? d.sessions : []) {
|
|
@@ -133,6 +134,7 @@ export class Devices {
|
|
|
133
134
|
const clean = readRights(asset, rights);
|
|
134
135
|
if (typeOf(asset) === 'secret') throw new Refusal(400, 'A secret is handed to a conversation, never shared with a device.');
|
|
135
136
|
this.#grants.give(pairingSubject(id), asset, clean);
|
|
137
|
+
this.changed();
|
|
136
138
|
}
|
|
137
139
|
/* A name the owner will recognise. */
|
|
138
140
|
rename(id, label) {
|
|
@@ -148,6 +150,7 @@ export class Devices {
|
|
|
148
150
|
if (!this.#store.get(id)) throw new Refusal(404, 'No such device.');
|
|
149
151
|
this.#grants.take(pairingSubject(id), String(asset));
|
|
150
152
|
if (this.grantsOf(id).length === 0) this.revoke(id);
|
|
153
|
+
this.changed();
|
|
151
154
|
}
|
|
152
155
|
|
|
153
156
|
revoke(id) {
|
|
@@ -156,6 +159,7 @@ export class Devices {
|
|
|
156
159
|
this.#grants.forgetSubject(pairingSubject(id));
|
|
157
160
|
this.#challenges.delete(id);
|
|
158
161
|
for (const [key, s] of this.#sessions) if (s.device === id) this.#sessions.delete(key);
|
|
162
|
+
this.changed();
|
|
159
163
|
}
|
|
160
164
|
|
|
161
165
|
/* Something is gone (a conversation archived, a folder removed): nobody
|
|
@@ -164,6 +168,7 @@ export class Devices {
|
|
|
164
168
|
forgetAsset(asset) {
|
|
165
169
|
this.#grants.forgetAsset(asset);
|
|
166
170
|
for (const d of this.#store.all()) if (this.grantsOf(d.name).length === 0) this.revoke(d.name);
|
|
171
|
+
this.changed();
|
|
167
172
|
}
|
|
168
173
|
|
|
169
174
|
/* ---- device side ---- */
|
|
@@ -231,7 +236,10 @@ export class Devices {
|
|
|
231
236
|
const id = this.pairingOf(session, pairing);
|
|
232
237
|
if (id === undefined) return undefined;
|
|
233
238
|
const mine = this.conversationsOf(id);
|
|
234
|
-
|
|
239
|
+
/* None named: its first. One named and not given: none -- never another one in its place
|
|
240
|
+
(a terminal asked for one conversation once opened on another). */
|
|
241
|
+
if (wanted === undefined || wanted === '') return mine[0];
|
|
242
|
+
return mine.includes(wanted) ? wanted : undefined;
|
|
235
243
|
}
|
|
236
244
|
}
|
|
237
245
|
|
package/server/door.mjs
CHANGED
|
@@ -60,7 +60,7 @@ async function readJson(request) {
|
|
|
60
60
|
}
|
|
61
61
|
|
|
62
62
|
/* The conversation the pairing asking speaks for, or undefined: the one it
|
|
63
|
-
names if it was given it,
|
|
63
|
+
names, only if it was given it; naming none, the first it was given. */
|
|
64
64
|
export function deviceConversation(devices, headers, pairing, wanted) {
|
|
65
65
|
if (!isPairingId(pairing)) return undefined;
|
|
66
66
|
return devices.conversationOf(readCookie(headers.cookie, cookieNameOf(pairing)), pairing, wanted);
|
|
@@ -70,6 +70,8 @@ export function deviceConversation(devices, headers, pairing, wanted) {
|
|
|
70
70
|
A pairing given its chat alone gets no terminal channel at all -- no
|
|
71
71
|
keys, no shortcuts, no dictation typed into it. */
|
|
72
72
|
export function deviceTerminal(devices, headers, pairing, wanted) {
|
|
73
|
+
/* A terminal is always asked for by the name of its conversation: nothing is guessed. */
|
|
74
|
+
if (typeof wanted !== 'string' || wanted === '') return undefined;
|
|
73
75
|
const name = deviceConversation(devices, headers, pairing, wanted);
|
|
74
76
|
return name !== undefined && devices.rightsOn(pairing, name).includes('x') ? name : undefined;
|
|
75
77
|
}
|
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,27 @@ 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
|
+
/* A view left broken (its program gone: killed, crashed) is taken off first, or none can
|
|
230
|
+
be made there again before a reboot: see clavarium-host, "mounts repair". */
|
|
231
|
+
const repaired = await asHost(['mounts', 'repair'], { timeoutMs: 60_000 });
|
|
232
|
+
if (repaired.code || repaired.stderr.trim()) console.error(`mounts: ${repaired.stderr.trim() || `exit ${repaired.code}`}`);
|
|
233
|
+
/* Before anything can start a VM: see resources.mjs. */
|
|
234
|
+
await folders.ensureViews().catch((error) => console.error(`views: ${error.message}`));
|
|
235
|
+
/* Not in place is said, not fatal: no machine is then given /tools. */
|
|
236
|
+
await toolbox.prepare().catch((error) => console.error(error.message));
|
|
237
|
+
await Promise.resolve(all.ensureWork?.()).catch((error) => console.error(`work folders: ${error.message}`));
|
|
238
|
+
})();
|
|
239
|
+
const bounded = (promise, ms, what) => {
|
|
240
|
+
let timer;
|
|
241
|
+
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?.(); });
|
|
242
|
+
return Promise.race([promise, late]).finally(() => clearTimeout(timer));
|
|
243
|
+
};
|
|
244
|
+
await bounded(hostSteps, startWaitMs, 'the host program');
|
|
223
245
|
const shortcuts = new Shortcuts(new Store(`${dataDir}/shortcuts.json`));
|
|
224
246
|
/* The engine of dictation: chosen in Settings, else the environment's (voice.mjs). */
|
|
225
247
|
const voice = new Dictation({ file: new JsonFile(`${dataDir}/dictation.json`, {}), env, secret: (name) => secrets.reveal(name) });
|
|
@@ -242,7 +264,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
242
264
|
const network = new Network({ host: asHost, offline: () => all.offline() });
|
|
243
265
|
/* The rules follow what runs: applied now, and again each time a
|
|
244
266
|
conversation is opened, since a VM that just started has a new tap. */
|
|
245
|
-
await network.apply();
|
|
267
|
+
const hostReady = (async () => { await hostSteps; await network.apply().catch((error) => console.error(`network rules: ${error.message}`)); })();
|
|
268
|
+
await bounded(hostReady, startWaitMs, 'the network rules');
|
|
246
269
|
/* OPENING MUST BE QUICK. Each command sent into a VM costs a noticeable
|
|
247
270
|
part of a second, and delivering secrets takes several: done at every
|
|
248
271
|
opening, it made each page load wait for seconds (felt by the owner).
|
|
@@ -258,6 +281,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
258
281
|
/* Why Parley is not in a machine, said once in the log, not at each opening. */
|
|
259
282
|
const parleySaid = new Map();
|
|
260
283
|
all.prepare = async (name, woke) => {
|
|
284
|
+
await hostReady;
|
|
261
285
|
const wanted = secrets.signature(name);
|
|
262
286
|
const rules = network.apply();
|
|
263
287
|
if (woke || delivered.get(name) !== wanted) {
|
|
@@ -343,7 +367,10 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
343
367
|
/* What the VM manager says each machine has is what is recorded (a record
|
|
344
368
|
may say otherwise: set by hand, or by an earlier version). Not waited for. */
|
|
345
369
|
void all.reconcileAll?.().catch(() => {});
|
|
346
|
-
|
|
370
|
+
/* The VM manager, watched: said to the pages when it does not answer, restarted once when stuck (vmwatch.mjs). */
|
|
371
|
+
const vmWatch = new VmWatch({ run: asHost, store: new Store(`${dataDir}/vm-manager.json`), alert: (payload) => { void alerts.tell(payload)?.catch?.(() => {}); } });
|
|
372
|
+
const stopVmWatch = vmWatch.start(vmWatchEveryMs);
|
|
373
|
+
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
374
|
/* Who gets what, and a whole setup in one file: see setup.mjs. */
|
|
348
375
|
/* Settings, Updates: what the updater (deploy/updater.mjs, as root) wrote, and how to ask it. */
|
|
349
376
|
const updates = new Updates({ host: asHost, version: platform.version, store: new Store(`${dataDir}/updates.json`), alerts, ...(updateState ? { stateFile: updateState } : {}), ...(updateConf ? { confFile: updateConf } : {}) });
|
|
@@ -357,7 +384,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
357
384
|
all.room = (ask) => capacity.check(ask);
|
|
358
385
|
const stopWatch = capacity.start();
|
|
359
386
|
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(); });
|
|
387
|
+
server.on('close', () => { closing = true; stopVmWatch(); stopShelf(); stopHealth(); stopUpdates(); stopWatch(); clearInterval(mailTimer); clearInterval(answerTimer); clearInterval(wakeTimer); clearInterval(gitTimer); talk.stop(); });
|
|
361
388
|
let closing = false;
|
|
362
389
|
bridge = attachBridge(server, {
|
|
363
390
|
onRejoin: (name) => all.rejoin(name),
|
|
@@ -383,6 +410,10 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
383
410
|
deviceName: (headers, pairing, wanted) => deviceTerminal(devices, headers, pairing, wanted),
|
|
384
411
|
});
|
|
385
412
|
all.drop = (name) => bridge.drop(name);
|
|
413
|
+
/* What a device was given changes: a terminal it holds and lost goes at once. */
|
|
414
|
+
devices.changed = () => bridge.recheck();
|
|
415
|
+
/* And a session that ends by itself (its hours are up): seen within a minute. */
|
|
416
|
+
const rechecking = setInterval(() => bridge.recheck(), 60_000); rechecking.unref?.();
|
|
386
417
|
/* A TERMINAL THAT DOES NOT COME, though its machine runs (asked by the
|
|
387
418
|
page once it has waited): repaired (conversations.mjs), then opened
|
|
388
419
|
again before the page comes back for it. */
|
|
@@ -413,6 +444,9 @@ function hostSetting(key) {
|
|
|
413
444
|
}
|
|
414
445
|
|
|
415
446
|
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
|
447
|
+
/* A promise rejected that nobody waited for is said, not fatal: one unlucky
|
|
448
|
+
call must not take every conversation's server down with it. */
|
|
449
|
+
process.on('unhandledRejection', (reason) => { console.error(`unhandled: ${reason?.stack ?? reason}`); });
|
|
416
450
|
const argv = process.argv.slice(2);
|
|
417
451
|
const port = Number(option(argv, 'port', '7717'));
|
|
418
452
|
const host = option(argv, 'host', '');
|
|
@@ -428,7 +462,7 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
|
|
428
462
|
const mntDir = hostSetting('MNT') || dataDir;
|
|
429
463
|
/* --name: the name of this Clavarium until one is chosen in Settings (instance.mjs). */
|
|
430
464
|
const name = option(argv, 'name', '') || undefined;
|
|
431
|
-
const server = await startHome({ port, host: host.split(' ').filter(Boolean), dataDir, mntDir, operators, publicOrigin, vaultKey, appName: name });
|
|
465
|
+
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
466
|
console.log(`http://127.0.0.1:${server.address().port}/`);
|
|
433
467
|
} else {
|
|
434
468
|
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
|
@@ -25,8 +25,9 @@
|
|
|
25
25
|
let deviceShared = [];
|
|
26
26
|
/* The parts of its conversation this device was given: its terminal, its
|
|
27
27
|
chat ('write', 'read' or null). Only those are shown -- and the server
|
|
28
|
-
refuses the others whatever this page does.
|
|
29
|
-
|
|
28
|
+
refuses the others whatever this page does. Nothing until the server said (/me): a
|
|
29
|
+
terminal button shown before that was a terminal the device had not been given. */
|
|
30
|
+
let deviceParts = { terminal: false, chat: null };
|
|
30
31
|
/* What Parley mounted for the chat screen, and for which conversation. */
|
|
31
32
|
let thread = null;
|
|
32
33
|
let threadOf = '';
|
|
@@ -3351,9 +3352,11 @@
|
|
|
3351
3352
|
for (const h of u.history) {
|
|
3352
3353
|
const li = document.createElement('li'); li.dataset.result = h.result;
|
|
3353
3354
|
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}`;
|
|
3355
|
+
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
3356
|
li.append(t, what);
|
|
3356
3357
|
if (h.why) { const why = document.createElement('small'); why.textContent = h.why; li.append(why); }
|
|
3358
|
+
/* What the updater saw when it went wrong: the journal, the unit, who held the port. */
|
|
3359
|
+
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
3360
|
list.append(li);
|
|
3358
3361
|
}
|
|
3359
3362
|
$('updates-history-box').hidden = u.history.length === 0;
|
|
@@ -3525,8 +3528,15 @@
|
|
|
3525
3528
|
if (DEVICE) return;
|
|
3526
3529
|
const r = await fetch(`${API}/server/brief`).then((x) => (x.ok ? x.json() : null)).catch(() => null);
|
|
3527
3530
|
const g = $('server-gauge');
|
|
3528
|
-
|
|
3531
|
+
/* The VM manager does not answer: said here, whatever the room. */
|
|
3532
|
+
const away = r?.machines === false;
|
|
3533
|
+
if (!r?.high && !away) { g.hidden = true; return; }
|
|
3529
3534
|
g.replaceChildren();
|
|
3535
|
+
if (away) {
|
|
3536
|
+
const t = document.createElement('span'); t.className = 'gauge-title'; t.textContent = 'The machines cannot be reached just now';
|
|
3537
|
+
g.append(t); g.setAttribute('aria-label', 'The machines cannot be reached just now: the server keeps trying.'); g.hidden = false;
|
|
3538
|
+
if (!r.high) return;
|
|
3539
|
+
}
|
|
3530
3540
|
const row = (label, f) => {
|
|
3531
3541
|
const line = document.createElement('span'); line.className = 'gauge-line'; line.dataset.level = f.level;
|
|
3532
3542
|
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); }
|