clavarium 0.2.248-beta.1 → 0.2.249-beta.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.
@@ -956,10 +956,21 @@ case "$AREA $VERB" in
956
956
  "vm revive")
957
957
  # The VM manager has not answered for minutes: its daemon restarted
958
958
  # (every machine is suspended and resumed). Asked by the server as its
959
- # owner chose (vmwatch.mjs: at night, always, or never by itself), at
960
- # most once in hours; or by its owner, confirmed in Settings, Machines.
961
- [ $# -eq 0 ] || usage
962
- run timeout 170 snap restart multipass.multipassd ;;
959
+ # owner chose (vmwatch.mjs: at night, always, or never by itself); or by
960
+ # its owner, confirmed in Settings, Machines.
961
+ # hard (25-11: a restart left it mute for hours): stopped, its daemon process
962
+ # ended if it stayed (by its exact name), then started.
963
+ [ $# -le 1 ] || usage
964
+ if [ $# -eq 1 ]; then
965
+ [ "$1" = "hard" ] || refuse "vm revive [hard]"
966
+ if [ "$SAY" = "yes" ]; then echo "snap stop multipass.multipassd; pkill -KILL -x multipassd; snap start multipass.multipassd"; exit 0; fi
967
+ timeout 120 snap stop multipass.multipassd || true
968
+ pkill -KILL -x multipassd 2>/dev/null || true
969
+ sleep 2
970
+ run timeout 120 snap start multipass.multipassd
971
+ else
972
+ run timeout 170 snap restart multipass.multipassd
973
+ fi ;;
963
974
  "vm states")
964
975
  # EVERY MACHINE'S STATE AT ONCE: one question to the VM manager instead of one per
965
976
  # machine. It answers one question at a time, and a machine frozen inside makes each
@@ -1219,13 +1230,15 @@ case "$AREA $VERB" in
1219
1230
  # WHAT THE SERVER'S PROGRAMS SAID, for Settings (This server, Logs): one
1220
1231
  # source, over a span; read-only, bounded. The page masks what looks
1221
1232
  # like a secret before showing it.
1222
- # server logs <clavarium|machines|updates|web|signin|tunnel|system> <10m|1|6|24|168|boot>
1233
+ # server logs <clavarium|machines|updates|web|signin|tunnel|system> <10m|1|6|24|168|boot|prev> [<from> <until> [<lines>]]
1234
+ # prev: the boot BEFORE this one (what led to a restart, 25-11). <from> <until>: a window, HH:MM or
1235
+ # YYYY-MM-DD HH:MM (or - for none), within that boot for boot and prev. <lines>: the newest 50 to 20000.
1223
1236
  # 17-11: a journal flooded by sudo (a line a second, the server's own calls of this program)
1224
1237
  # took more than the page waits. The server's unit is read by indexed fields, its own output
1225
1238
  # only (stdout), not sudo's syslog lines; sudo and PAM session lines are left out of any
1226
1239
  # source; the read is given LOGS_SECONDS, then what it said by then is shown, with a NOTE
1227
1240
  # on stderr -- never a bare failure.
1228
- [ $# -eq 2 ] || usage
1241
+ [ $# -ge 2 ] && [ $# -le 5 ] || usage
1229
1242
  # A unit by its fields: what it wrote, and what systemd said of it.
1230
1243
  unit() { printf '%s\n' "_SYSTEMD_UNIT=$1" + "UNIT=$1" "_PID=1" +; }
1231
1244
  case "$1" in
@@ -1242,13 +1255,22 @@ case "$AREA $VERB" in
1242
1255
  system) matches=(-k) ;;
1243
1256
  *) refuse "not a source of logs: $1" ;;
1244
1257
  esac
1245
- case "$2" in 10m) since=(--since "-10min") ;; 1|6|24|168) since=(--since "-$2h") ;; boot) since=(-b) ;; *) refuse "not a span: $2 (10m, 1, 6, 24, 168 hours, or boot)" ;; esac
1246
- # The newest 20000 lines at most: more is too much to read on a page, and to send.
1247
- if [ "$SAY" = "yes" ]; then echo "journalctl ${matches[*]} ${since[*]} -o short-iso --no-pager -q -n 20000 (sudo and PAM session lines left out; ${LOGS_SECONDS}s at most)"; exit 0; fi
1258
+ case "$2" in 10m) since=(--since "-10min") ;; 1|6|24|168) since=(--since "-$2h") ;; boot) since=(-b) ;; prev) since=(-b -1) ;; *) refuse "not a span: $2 (10m, 1, 6, 24, 168 hours, boot or prev)" ;; esac
1259
+ window='^([0-9]{4}-[0-9]{2}-[0-9]{2} )?[0-9]{2}:[0-9]{2}$'
1260
+ from="${3:--}"; until="${4:--}"; lines="${5:-20000}"
1261
+ [ "$from" = "-" ] || [[ "$from" =~ $window ]] || refuse "not a time: $from (HH:MM or YYYY-MM-DD HH:MM)"
1262
+ [ "$until" = "-" ] || [[ "$until" =~ $window ]] || refuse "not a time: $until (HH:MM or YYYY-MM-DD HH:MM)"
1263
+ [[ "$lines" =~ ^[0-9]{2,5}$ ]] && [ "$lines" -ge 50 ] && [ "$lines" -le 20000 ] || refuse "not a number of lines: $lines (50 to 20000)"
1264
+ # A window replaces an hour span; within a boot it narrows it.
1265
+ if [ "$from" != "-" ] || [ "$until" != "-" ]; then case "$2" in boot|prev) : ;; *) since=() ;; esac; fi
1266
+ [ "$from" = "-" ] || since+=(--since "$from")
1267
+ [ "$until" = "-" ] || since+=(--until "$until")
1268
+ # The newest $lines lines at most (20000 by default): more is too much to read on a page, and to send.
1269
+ if [ "$SAY" = "yes" ]; then echo "journalctl ${matches[*]} ${since[*]} -o short-iso --no-pager -q -n $lines (sudo and PAM session lines left out; ${LOGS_SECONDS}s at most)"; exit 0; fi
1248
1270
  out="$(mktemp)"; err="$(mktemp)"
1249
1271
  trap 'rm -f -- "$out" "$err"' EXIT
1250
1272
  code=0
1251
- timeout -k 5 "$LOGS_SECONDS" "$JOURNALCTL" "${matches[@]}" "${since[@]}" -o short-iso --no-pager -q -n 20000 >"$out" 2>"$err" || code=$?
1273
+ timeout -k 5 "$LOGS_SECONDS" "$JOURNALCTL" "${matches[@]}" "${since[@]}" -o short-iso --no-pager -q -n "$lines" >"$out" 2>"$err" || code=$?
1252
1274
  grep -avE ' (sudo|pkexec)\[[0-9]+\]: | pam_unix\((sudo|sudo-i|pkexec):session\)' "$out" | cut -c1-2000 || true
1253
1275
  case "$code" in
1254
1276
  0) : ;;
@@ -55,14 +55,37 @@ export async function multipassTurn({ run, mode, inWindow, busy, state, save, lo
55
55
  }
56
56
 
57
57
  const answers = async () => { for (let i = 0; i < BACK_TRIES; i += 1) { if ((await sh([multipass, 'list', '--format', 'json'], 30_000)).code === 0) return true; await sleep(BACK_EVERY_MS); } return false; };
58
+ /* MUTE AFTER ITS UPDATE (25-11, on a real server: four machines started, then its daemon died and stayed mute for
59
+ three hours). Not waited for: its daemon restarted, then stopped and started for sure; each step said. Its
60
+ previous version is never put back by itself (its owner's choice: it may not read what the new one wrote).
61
+ Still mute: the server's watch tries again every 10 minutes and says so. True once it answers. */
62
+ const rescue = async () => {
63
+ if (await answers()) return true;
64
+ const steps = [
65
+ ['its daemon is restarted', ['snap', 'restart', 'multipass.multipassd']],
66
+ ['its daemon is stopped and started for sure', null],
67
+ ];
68
+ for (const [what, argv] of steps) {
69
+ log(`multipass: it does not answer: ${what}`);
70
+ if (argv) await sh(argv, REFRESH_MS);
71
+ else { await sh(['snap', 'stop', 'multipass.multipassd'], SNAP_MS); await sh(['pkill', '-KILL', '-x', 'multipassd'], 30_000); await sleep(2_000); await sh(['snap', 'start', 'multipass.multipassd'], SNAP_MS); }
72
+ if (await answers()) { log(`multipass: it answers again (${what})`); return true; }
73
+ }
74
+ return false;
75
+ };
58
76
  /* Started again; what could not be stays written down, for the next turn. */
59
77
  const back = async (names) => {
60
- if (!(await answers())) { log('multipass: it does not answer: its machines are started at the next turn'); return names; }
78
+ if (!(await rescue())) { log('multipass: it still does not answer: its machines are started at the next turn; the server\'s watch keeps trying'); return names; }
61
79
  const left = [];
62
80
  for (const name of names) {
63
81
  let r = await sh([multipass, 'start', name], MACHINE_MS);
64
82
  if (r.code !== 0) { await sleep(BACK_EVERY_MS); r = await sh([multipass, 'start', name], MACHINE_MS); }
65
- if (r.code !== 0) { left.push(name); log(`multipass: ${name} could not be started again: ${first(r)}`); }
83
+ if (r.code !== 0) {
84
+ /* It died while they were started (25-11): rescued, then this one tried once more. */
85
+ const mute = (await sh([multipass, 'list', '--format', 'json'], 30_000)).code !== 0;
86
+ if (mute && await rescue()) r = await sh([multipass, 'start', name], MACHINE_MS);
87
+ if (r.code !== 0) { left.push(name); log(`multipass: ${name} could not be started again: ${first(r)}`); }
88
+ }
66
89
  }
67
90
  return left;
68
91
  };
@@ -409,8 +409,9 @@ export class Updater {
409
409
  #o; #run; #fetch;
410
410
  constructor({ code = PATHS.code, conf = PATHS.conf, stateDir = PATHS.stateDir, data = PATHS.data, hostTarget = PATHS.host, gitReadTarget = PATHS.gitRead, tunnelTarget = PATHS.tunnel, registry = REGISTRY, run = runCommand, fetcher = fetch, now = () => new Date(), log = (line) => console.log(line),
411
411
  verifySignatures, restart, health, backup, restoreData, installPrivileged, ensureNode, serviceState, answers, restarts, mainPid, pidCwd, diagnose, dropIn = DROP_IN,
412
+ bootId = () => { try { return readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim(); } catch { return ''; } },
412
413
  clock = () => Date.now(), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), minFreeMb = 1024, healthMs = 60_000, watchMs = 120_000, settleMs = 10_000, noticeMs = NOTICE_MS, releaseSettleMs = RELEASE_SETTLE_MS } = {}) {
413
- this.#o = { code, conf, stateDir, data, hostTarget, gitReadTarget, tunnelTarget, registry: registry.replace(/\/$/, ''), now, log, minFreeMb, healthMs, watchMs, settleMs, noticeMs, releaseSettleMs, clock, sleep, dropIn };
414
+ this.#o = { code, conf, stateDir, data, hostTarget, gitReadTarget, tunnelTarget, registry: registry.replace(/\/$/, ''), now, log, bootId, minFreeMb, healthMs, watchMs, settleMs, noticeMs, releaseSettleMs, clock, sleep, dropIn };
414
415
  this.#run = run; this.#fetch = fetcher;
415
416
  this.verifySignatures = verifySignatures ?? ((dir) => this.#npm(['audit', 'signatures'], { cwd: dir, timeoutMs: 300_000 }));
416
417
  this.restart = restart ?? (() => this.#restart());
@@ -668,15 +669,35 @@ export class Updater {
668
669
  }
669
670
  #dataFormat() { try { return JSON.parse(readFileSync(join(this.#o.data, 'data-format.json'), 'utf8')).format; } catch { return undefined; } }
670
671
 
672
+ /* Whether the lock is held by a process alive now -- of THIS start of the machine (25-11, on a test machine: frozen
673
+ in the middle of an update, started again; its lock and its "under way" stayed, and a number taken by another
674
+ process after the start would have looked alive for ever). */
675
+ #lockHeld() {
676
+ let text = '';
677
+ try { text = readFileSync(join(this.#o.stateDir, 'lock'), 'utf8').trim(); } catch { return false; }
678
+ const [pidText, boot] = text.split(/\s+/);
679
+ const pid = Number(pidText) || 0;
680
+ if (boot && boot !== this.#o.bootId()) return false;
681
+ let alive = false; try { if (pid) { process.kill(pid, 0); alive = true; } } catch (e) { alive = e.code === 'EPERM'; }
682
+ return alive;
683
+ }
684
+ /* An update or a return cut by the machine stopping: no longer said "under way"; written down as cut. */
685
+ clearCut() {
686
+ const running = this.#state().running;
687
+ if (!running || this.#lockHeld()) return false;
688
+ this.#o.log(`${running.action} ${running.version}: cut at "${running.step}" (the machine stopped): no longer under way`);
689
+ this.#history({ action: running.action === 'back' ? 'back' : 'update', to: running.version ?? null, result: 'failed', why: `cut at "${running.step}": the machine stopped in the middle; nothing was switched` });
690
+ return true;
691
+ }
671
692
  #lock() {
672
693
  mkdirSync(this.#o.stateDir, { recursive: true, mode: 0o755 });
673
694
  const file = join(this.#o.stateDir, 'lock');
674
695
  for (let i = 0; i < 2; i += 1) {
675
- try { const fd = openSync(file, 'wx'); writeFileSync(fd, String(process.pid)); closeSync(fd); return () => rmSync(file, { force: true }); } catch (error) {
696
+ try { const fd = openSync(file, 'wx'); writeFileSync(fd, `${process.pid} ${this.#o.bootId()}`); closeSync(fd); return () => rmSync(file, { force: true }); } catch (error) {
676
697
  if (error.code !== 'EEXIST') throw error;
677
- const pid = Number(readFileSync(file, 'utf8')) || 0;
698
+ const pid = Number(readFileSync(file, 'utf8').trim().split(/\s+/)[0]) || 0;
678
699
  /* A lock left by a process that is gone (killed, the machine stopped) is taken over. */
679
- let alive = false; try { if (pid) { process.kill(pid, 0); alive = true; } } catch (e) { alive = e.code === 'EPERM'; }
700
+ const alive = this.#lockHeld();
680
701
  if (!alive) this.#o.log(`a stale lock (process ${pid || '?'} is gone): taken over`);
681
702
  if (alive) throw new Refused('an update or an installation is running already');
682
703
  rmSync(file, { force: true });
@@ -890,6 +911,7 @@ export class Updater {
890
911
 
891
912
  /* What the host program asked (a request file), or the timer's turn. */
892
913
  async runOnce() {
914
+ this.clearCut();
893
915
  const file = join(this.#o.stateDir, 'request');
894
916
  let request = '';
895
917
  try { request = readFileSync(file, 'utf8').trim(); rmSync(file, { force: true }); } catch { /* none */ }
@@ -1086,7 +1108,7 @@ async function main(argv) {
1086
1108
  const u = new Updater({ log: (line) => console.error(line) });
1087
1109
  const print = (x) => console.log(JSON.stringify(x, null, 2));
1088
1110
  switch (verb) {
1089
- case 'check': await u.check().catch(() => {}); return print(u.about());
1111
+ case 'check': u.clearCut(); await u.check().catch(() => {}); return print(u.about());
1090
1112
  case 'status': return print(u.about());
1091
1113
  case 'run': {
1092
1114
  /* What this release sets up beside itself (the certificate timer), at its first turn: the
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.248-beta.1",
3
+ "version": "0.2.249-beta.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.248-beta.1",
9
+ "version": "0.2.249-beta.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.248-beta.1",
3
+ "version": "0.2.249-beta.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "A conversation is a VM with a terminal in it. Everything else is a folder.",
package/server/api.mjs CHANGED
@@ -486,7 +486,7 @@ export async function handleApi(request, response, conversations, headers, resou
486
486
  }
487
487
  /* What this server asked of the host, by 5-minute window, and its own event loop (vm.mjs HostTally). */
488
488
  if (pathname === '/api/server/load' && serverLogs) return send(200, serverLogs.load()), true;
489
- if (pathname === '/api/server/logs' && serverLogs) { const r = await serverLogs.start(query.get('source') ?? 'clavarium', query.get('span') ?? '10m'); return send(r.pending ? 202 : 200, r), true; }
489
+ if (pathname === '/api/server/logs' && serverLogs) { const r = await serverLogs.start(query.get('source') ?? 'clavarium', query.get('span') ?? '10m', undefined, { from: query.get('from') || undefined, until: query.get('until') || undefined, lines: query.get('lines') || undefined }); return send(r.pending ? 202 : 200, r), true; }
490
490
  if (pathname === '/api/machines/disks' && machinesMove) return send(200, await machinesMove.disks()), true;
491
491
  if (pathname === '/api/machines/places' && machinesMove) return send(200, await machinesMove.places()), true;
492
492
  if (pathname === '/api/machines/moving' && machinesMove) return send(200, await machinesMove.moving()), true;
@@ -599,8 +599,8 @@ export const PROFILE_TOOL = {
599
599
  export const LOGS_TOOL = {
600
600
  name: 'clavarium_logs',
601
601
  title: 'Logs of this Clavarium',
602
- description: 'Read-only: what one of the server\'s programs said over a span, as Settings reads it (secrets masked). source: clavarium (default), machines, updates, web, signin, tunnel, system. span: 10m (default), 1, 6, 24, 168 (hours) or boot. A big journal takes a while: {pending: true} means ask again in a moment.',
603
- inputSchema: { type: 'object', properties: { source: { type: 'string' }, span: { type: 'string' } }, additionalProperties: false },
602
+ description: 'Read-only: what one of the server\'s programs said, as Settings reads it (secrets masked). source: clavarium (default), machines, updates, web, signin, tunnel, system. span: 10m (default), 1, 6, 24, 168 (hours), boot (since this start) or prev (the start before it: what led to a restart). from/until: a window, HH:MM or YYYY-MM-DD HH:MM (within boot or prev for those). lines: the newest 50 to 20000 (2000 by default here). A big journal takes a while: {pending: true} means ask again in a moment.',
603
+ inputSchema: { type: 'object', properties: { source: { type: 'string' }, span: { type: 'string' }, from: { type: 'string' }, until: { type: 'string' }, lines: { type: 'integer', minimum: 50, maximum: 20000 } }, additionalProperties: false },
604
604
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
605
605
  };
606
606
  export const CONVERSATIONS_TOOL = {
@@ -1233,7 +1233,7 @@ export async function handleExternal(request, response, { keys, status, chats =
1233
1233
  if (!diagnostics) throw new Refusal(404, 'Not available on this server.');
1234
1234
  if (name === LOAD_TOOL.name) return result(diagnostics.load());
1235
1235
  if (name === PROFILE_TOOL.name) return result(await diagnostics.profile(args.seconds ?? 10));
1236
- const r = await diagnostics.logs(typeof args.source === 'string' ? args.source : 'clavarium', typeof args.span === 'string' ? args.span : '10m');
1236
+ const r = await diagnostics.logs(typeof args.source === 'string' ? args.source : 'clavarium', typeof args.span === 'string' ? args.span : '10m', { from: typeof args.from === 'string' ? args.from : undefined, until: typeof args.until === 'string' ? args.until : undefined, lines: Number.isInteger(args.lines) ? args.lines : 2000 });
1237
1237
  return result(r.pending ? r : { ...r, text: masked(r.text ?? '') });
1238
1238
  }
1239
1239
  if (name === JOB_LOG_TOOL.name) {
package/server/main.mjs CHANGED
@@ -943,7 +943,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
943
943
  /* What Clavarium does (jobs.mjs), as Settings shows it: the list without logs, one job with its log. */
944
944
  jobs: { list: () => withUpdates(all.jobs, all.list(), updates?.about().history ?? []), log: (id) => all.jobs.log(id) },
945
945
  /* Diagnostics (scope "diagnostics"): what Settings > Diagnostics > Load and Logs show. */
946
- diagnostics: { load: () => serverLogs.load(), profile: (seconds) => serverLogs.profile(seconds), logs: (source, span) => serverLogs.start(source, span) },
946
+ diagnostics: { load: () => serverLogs.load(), profile: (seconds) => serverLogs.profile(seconds), logs: (source, span, how) => serverLogs.start(source, span, undefined, how) },
947
947
  /* A key's conversations (their chat, through talk.mjs): read as the page reads it; a message posted as the page
948
948
  posts one (its secrets lifted the same way), signed with the key's name. */
949
949
  chats: {
@@ -14,7 +14,10 @@
14
14
  import { Refusal } from './conversations.mjs';
15
15
 
16
16
  export const SOURCES = ['clavarium', 'machines', 'updates', 'web', 'signin', 'tunnel', 'system'];
17
- export const SPANS = ['10m', '1', '6', '24', '168', 'boot'];
17
+ export const SPANS = ['10m', '1', '6', '24', '168', 'boot', 'prev'];
18
+ /* A window (25-11: what led to a restart, read after it): HH:MM or YYYY-MM-DD HH:MM; and how many of the newest lines. */
19
+ export const WHEN = /^(\d{4}-\d{2}-\d{2}[ T])?\d{2}:\d{2}$/;
20
+ export const LINES_MIN = 50; export const LINES_MAX = 20000;
18
21
  /* What a page reads at once: masking and sending more held this server for seconds (found 31-10:
19
22
  the front then said "being updated" to every other page meanwhile). The newest are kept. */
20
23
  const TEXT_MAX = 4 * 1024 * 1024;
@@ -47,14 +50,14 @@ export class ServerLogs {
47
50
 
48
51
  /* The same read asked again while it runs is the same read; once done, kept a moment for
49
52
  the page that comes back for it. Resolves { pending: true } past `wait`. */
50
- async start(source, span, wait = WAIT_MS) {
51
- const key = `${source}:${span}`;
53
+ async start(source, span, wait = WAIT_MS, how = {}) {
54
+ const key = `${source}:${span}:${how.from ?? ''}:${how.until ?? ''}:${how.lines ?? ''}`;
52
55
  const now = this.#now();
53
56
  for (const [k, r] of this.#reads) if (r.done && now - r.done > KEPT_MS) this.#reads.delete(k);
54
57
  let r = this.#reads.get(key);
55
58
  if (!r) {
56
59
  r = { done: 0 };
57
- r.promise = this.read(source, span).then((v) => { r.value = v; }, (e) => { r.error = e; }).finally(() => { r.done = this.#now(); });
60
+ r.promise = this.read(source, span, how).then((v) => { r.value = v; }, (e) => { r.error = e; }).finally(() => { r.done = this.#now(); });
58
61
  this.#reads.set(key, r);
59
62
  }
60
63
  await Promise.race([r.promise, new Promise((ok) => { setTimeout(ok, wait).unref?.(); })]);
@@ -64,10 +67,14 @@ export class ServerLogs {
64
67
  return r.value;
65
68
  }
66
69
 
67
- async read(source, span) {
70
+ async read(source, span, { from, until, lines } = {}) {
68
71
  if (!SOURCES.includes(source)) throw new Refusal(400, `Not a source of logs: say one of ${SOURCES.join(', ')}.`);
69
- if (!SPANS.includes(String(span))) throw new Refusal(400, 'Not a span: 10 minutes (10m), 1, 6, 24 or 168 hours, or since the server started (boot).');
70
- const r = await this.#host(['server', 'logs', source, String(span)], { timeoutMs: 120_000, maxBytes: TEXT_MAX * 2 });
72
+ if (!SPANS.includes(String(span))) throw new Refusal(400, 'Not a span: 10 minutes (10m), 1, 6, 24 or 168 hours, since the server started (boot), or the start before it (prev).');
73
+ for (const t of [from, until]) if (t !== undefined && t !== null && t !== '' && !WHEN.test(String(t))) throw new Refusal(400, 'A time is HH:MM or YYYY-MM-DD HH:MM.');
74
+ if (lines !== undefined && lines !== null && lines !== '' && !(Number.isInteger(Number(lines)) && Number(lines) >= LINES_MIN && Number(lines) <= LINES_MAX)) throw new Refusal(400, `Lines: ${LINES_MIN} to ${LINES_MAX}.`);
75
+ const when = (t) => (t ? String(t).replace('T', ' ') : '-');
76
+ const extra = from || until || lines ? [when(from), when(until), ...(lines ? [String(Number(lines))] : [])] : [];
77
+ const r = await this.#host(['server', 'logs', source, String(span), ...extra], { timeoutMs: 120_000, maxBytes: TEXT_MAX * 2 });
71
78
  if (r.code !== 0) {
72
79
  const why = r.timedOut ? 'no answer in 120 s' : r.tooLong ? 'more than 8 MB' : lastWord(r.stderr) || `exit ${r.code}`;
73
80
  throw new Refusal(502, `The logs could not be read: ${why}`);
@@ -80,7 +87,7 @@ export class ServerLogs {
80
87
  const cut = text.length > TEXT_MAX;
81
88
  if (cut) text = text.slice(text.length - TEXT_MAX).replace(/^[^\n]*\n/, '');
82
89
  text = mask(text);
83
- return { source, span: String(span), text, lines: text ? text.split('\n').filter(Boolean).length : 0, cut, ...(note ? { note } : {}) };
90
+ return { source, span: String(span), ...(from ? { from: String(from) } : {}), ...(until ? { until: String(until) } : {}), text, lines: text ? text.split('\n').filter(Boolean).length : 0, cut, ...(note ? { note } : {}) };
84
91
  }
85
92
  async restart() {
86
93
  const r = await this.#host(['server', 'restart']);
@@ -21,6 +21,11 @@ export const EVERY_MS = 60_000;
21
21
  has said nothing at all for this long: mute (30 s each) on three looks in a row. */
22
22
  export const STUCK_MS = 2 * 60_000;
23
23
  export const REVIVE_EVERY_MS = 6 * 3600_000;
24
+ /* 25-11, on a real server: restarted once after an update of Multipass, it stayed mute for three hours -- one try was
25
+ not enough. While it stays mute: tried again every 10 minutes, a stronger restart from the second try, up to
26
+ SOON_TRIES; then every REVIVE_EVERY_MS. Each try said to its owner. */
27
+ export const SOON_EVERY_MS = 10 * 60_000;
28
+ export const SOON_TRIES = 6;
24
29
  /* After a cut, how long a machine is given to answer before it is restarted: 2 min. */
25
30
  export const ANSWER_TRIES = 5;
26
31
  export const ANSWER_EVERY_MS = 30_000;
@@ -100,10 +105,16 @@ export class VmWatch {
100
105
  return 'asked';
101
106
  }
102
107
  const before = this.#store.get('revive');
103
- if (before?.at && this.#now() - Date.parse(before.at) < this.#reviveEveryMs) return 'down; restarted already';
104
- this.#log(`vm manager: ${why}: its daemon is restarted, once`);
105
- const result = await this.#revive(why, 'server');
106
- this.#alert({ title: 'The machines could not be reached', body: `${why}: it was restarted (${result}).`, url: '/?open=settings&at=machines' });
108
+ /* Tries within the last REVIVE_EVERY_MS, mute all along or mute again: soon at first, then rarely -- never a loop. */
109
+ const tries = before?.at && this.#now() - Date.parse(before.at) < this.#reviveEveryMs ? (before.tries ?? 1) : 0;
110
+ const every = tries < SOON_TRIES ? SOON_EVERY_MS : this.#reviveEveryMs;
111
+ if (tries > 0 && before?.at && this.#now() - Date.parse(before.at) < every) return 'down; restarted already';
112
+ /* Mute again soon after a restart, or still mute: the stronger restart. */
113
+ const hard = tries >= 1;
114
+ this.#log(`vm manager: ${why}: its daemon is restarted${hard ? ', by force' : ''} (try ${tries + 1})`);
115
+ const result = await this.#revive(why, 'server', { hard, tries: tries + 1 });
116
+ const back = (await this.#run(['vm', 'ping'], { timeoutMs: PING_MS }).catch(() => ({ code: 1 }))).code === 0;
117
+ this.#alert({ title: back ? 'The machines answer again' : 'The machines still cannot be reached', body: `${why}: restarted${hard ? ' by force' : ''}, try ${tries + 1} (${result})${back ? '.' : `; tried again in ${Math.round((tries + 1 < SOON_TRIES ? SOON_EVERY_MS : this.#reviveEveryMs) / 60_000)} minutes. A restart of the whole server is the last resort.`}`, url: '/?open=settings&at=machines' });
107
118
  return result === 'done' ? 'revived' : 'revive failed';
108
119
  }
109
120
 
@@ -148,12 +159,12 @@ export class VmWatch {
148
159
  return this.about();
149
160
  }
150
161
 
151
- #revive(why, by) {
162
+ #revive(why, by, { hard = false, tries = 1 } = {}) {
152
163
  this.#reviving = (async () => {
153
- this.#store.put({ name: 'revive', at: new Date(this.#now()).toISOString(), why, result: null, by });
154
- const done = await this.#run(['vm', 'revive'], { timeoutMs: 180_000 }).catch((e) => ({ code: 1, stderr: e.message }));
164
+ this.#store.put({ name: 'revive', at: new Date(this.#now()).toISOString(), why, result: null, by, tries });
165
+ const done = await this.#run(hard ? ['vm', 'revive', 'hard'] : ['vm', 'revive'], { timeoutMs: 240_000 }).catch((e) => ({ code: 1, stderr: e.message }));
155
166
  const result = done.code === 0 ? 'done' : `failed: ${said(done)}`;
156
- this.#store.put({ name: 'revive', at: new Date(this.#now()).toISOString(), why, result, by });
167
+ this.#store.put({ name: 'revive', at: new Date(this.#now()).toISOString(), why, result, by, tries });
157
168
  this.#log(`vm manager: restart ${result}`);
158
169
  if (done.code === 0) { this.#store.remove?.('asked'); this.#downSince = null; }
159
170
  return result;
package/web/index.html CHANGED
@@ -1417,6 +1417,7 @@
1417
1417
  <option value="24">the last 24 hours</option>
1418
1418
  <option value="168">the last 7 days</option>
1419
1419
  <option value="boot">since the server started</option>
1420
+ <option value="prev">before the server last started</option>
1420
1421
  </select></label>
1421
1422
  <button type="button" id="logs-show">Show</button>
1422
1423
  </div>