clavarium 0.2.520-next.1 → 0.2.521-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,104 @@
1
+ /* MULTIPASS UPDATED IN CLAVARIUM'S OWN WINDOW (23-11, its owner's ask, after a morning on a real server: snap
2
+ * updated Multipass by itself at 06:08, every machine was left suspended, nothing could be reached).
3
+ *
4
+ * At each turn of the updater (as root):
5
+ * - updates by itself (auto, asap): snap's own refresh of Multipass is held, for good;
6
+ * - never by itself (off, ask): the hold is taken off, so that Multipass still gets its fixes from snap;
7
+ * - machines left suspended by a turn that was cut are started again first;
8
+ * - in the update window, nothing being built or moved, a new Multipass out: the machines that run are put to
9
+ * sleep, written down, Multipass updated, those machines started again. Never more than one try a day.
10
+ * Only the machines that ran are started again: one asleep before stays asleep.
11
+ */
12
+ const SNAP_MS = 60_000;
13
+ const REFRESH_MS = 15 * 60_000;
14
+ const MACHINE_MS = 180_000;
15
+ const BACK_TRIES = 36;
16
+ const BACK_EVERY_MS = 5_000;
17
+ export const TRY_EVERY_MS = 20 * 3600_000;
18
+
19
+ const first = (r) => String(r?.stderr || r?.stdout || '').trim().split('\n').filter(Boolean).pop()?.slice(0, 200) || `exit ${r?.code}`;
20
+
21
+ /* The line of `snap list multipass` says "held" in its notes. */
22
+ export const isHeld = (text) => String(text).split('\n').some((l) => /^multipass\s/.test(l) && /\bheld\b/.test(l.trim().split(/\s+/).pop() ?? ''));
23
+ /* A newer revision on the channel it follows, from `snap info multipass` (`snap refresh --list` leaves out a held snap). */
24
+ export function hasRefresh(text) {
25
+ const t = String(text);
26
+ const tracking = /^tracking:\s+(\S+)/m.exec(t)?.[1];
27
+ const installed = Number(/^installed:.*\((\d+)\)/m.exec(t)?.[1]);
28
+ if (!tracking || !Number.isFinite(installed)) return false;
29
+ const line = t.split('\n').find((l) => l.trim().startsWith(`${tracking}:`));
30
+ const offered = Number(/\((\d+)\)/.exec(line ?? '')?.[1]);
31
+ return Number.isFinite(offered) && offered > installed;
32
+ }
33
+ /* The machines of this Clavarium that run, from `multipass list --format json`. */
34
+ export function runningMachines(text) {
35
+ let list;
36
+ try { list = JSON.parse(text).list; } catch { return null; }
37
+ if (!Array.isArray(list)) return null;
38
+ return list.filter((m) => m?.state === 'Running' && /^clv-[a-z0-9-]+$/.test(m?.name ?? '')).map((m) => m.name);
39
+ }
40
+
41
+ export async function multipassTurn({ run, mode, inWindow, busy, state, save, log = () => {}, now = () => Date.now(), sleep = (ms) => new Promise((r) => { setTimeout(r, ms); }), multipass = '/snap/bin/multipass' }) {
42
+ const sh = (argv, timeoutMs = SNAP_MS) => Promise.resolve(run(argv, { timeoutMs })).catch((e) => ({ code: 1, stderr: e.message }));
43
+ const list = await sh(['snap', 'list', 'multipass']);
44
+ if (list.code !== 0) return 'no multipass here';
45
+ const held = isHeld(list.stdout);
46
+ const own = mode === 'auto' || mode === 'asap';
47
+ if (!own) {
48
+ if (held) { const r = await sh(['snap', 'refresh', '--unhold', 'multipass']); log(r.code === 0 ? 'multipass: snap updates it again (updates are not automatic here)' : `multipass: the hold could not be taken off: ${first(r)}`); }
49
+ } else if (!held) {
50
+ const r = await sh(['snap', 'refresh', '--hold', 'multipass']);
51
+ if (r.code !== 0) { log(`multipass: snap's own updates could not be held: ${first(r)}`); return 'not held'; }
52
+ log('multipass: updated in the update window from now on, no longer by snap at any hour');
53
+ }
54
+
55
+ 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; };
56
+ /* Started again; what could not be stays written down, for the next turn. */
57
+ const back = async (names) => {
58
+ if (!(await answers())) { log('multipass: it does not answer: its machines are started at the next turn'); return names; }
59
+ const left = [];
60
+ for (const name of names) {
61
+ let r = await sh([multipass, 'start', name], MACHINE_MS);
62
+ if (r.code !== 0) { await sleep(BACK_EVERY_MS); r = await sh([multipass, 'start', name], MACHINE_MS); }
63
+ if (r.code !== 0) { left.push(name); log(`multipass: ${name} could not be started again: ${first(r)}`); }
64
+ }
65
+ return left;
66
+ };
67
+
68
+ const pending = state().multipassRefresh?.machines ?? [];
69
+ if (pending.length) {
70
+ const left = await back(pending);
71
+ save({ multipassRefresh: { ...state().multipassRefresh, machines: left } });
72
+ if (left.length) return `${left.length} machine(s) still to start again`;
73
+ log('multipass: the machines of the last update are running again');
74
+ }
75
+ if (!own || !inWindow) return 'nothing to do';
76
+ const tried = Date.parse(state().multipassRefresh?.triedAt ?? '');
77
+ if (Number.isFinite(tried) && now() - tried < TRY_EVERY_MS) return 'tried lately';
78
+ const out = await sh(['snap', 'info', 'multipass']);
79
+ if (out.code !== 0 || !hasRefresh(out.stdout)) return 'up to date';
80
+ const why = await busy();
81
+ if (why) return `waits: ${why}`;
82
+ const seen = await sh([multipass, 'list', '--format', 'json'], 30_000);
83
+ const running = seen.code === 0 ? runningMachines(seen.stdout) : null;
84
+ if (!running) { log(`multipass: its machines could not be read: not updated (${first(seen)})`); return 'not updated'; }
85
+
86
+ /* Written down BEFORE anything stops: a turn cut here still brings them back. */
87
+ save({ multipassRefresh: { triedAt: new Date(now()).toISOString(), machines: running } });
88
+ log(`multipass: a new version: ${running.length} machine(s) put to sleep for its update`);
89
+ for (const name of running) {
90
+ const r = await sh([multipass, 'suspend', name], MACHINE_MS);
91
+ if (r.code !== 0) {
92
+ log(`multipass: ${name} could not be put to sleep (${first(r)}): not updated, its machines started again`);
93
+ save({ multipassRefresh: { ...state().multipassRefresh, machines: await back(running) } });
94
+ return 'not updated';
95
+ }
96
+ }
97
+ /* --ignore-running: a client of Multipass still open (a terminal, a command) would make snap refuse (seen on a real machine); its machine is asleep. */
98
+ const done = await sh(['snap', 'refresh', 'multipass', '--ignore-running'], REFRESH_MS);
99
+ log(done.code === 0 ? 'multipass: updated' : `multipass: its update failed: ${first(done)}`);
100
+ const left = await back(running);
101
+ save({ multipassRefresh: { ...state().multipassRefresh, machines: left } });
102
+ log(left.length ? `multipass: ${left.length} machine(s) to start again at the next turn` : 'multipass: its machines are running again');
103
+ return done.code === 0 ? 'updated' : 'update failed';
104
+ }
@@ -56,6 +56,7 @@ import { fileURLToPath } from 'node:url';
56
56
  import { fetchToolArchives, REGISTRY } from './parley-archive.mjs';
57
57
  import { ensureTunnel, tunnelUnit, relayOfUnit, TUNNEL_UNIT, TUNNEL_PROGRAM } from './tunnel.mjs';
58
58
  import { ensureGenericClientId } from './oidc.mjs';
59
+ import { multipassTurn } from './multipass-refresh.mjs';
59
60
  /* The updater's run keeps the tunnel up to date: the same functions, from here too. */
60
61
  export { ensureTunnel, tunnelUnit, relayOfUnit, TUNNEL_UNIT, TUNNEL_PROGRAM };
61
62
 
@@ -1122,6 +1123,13 @@ async function main(argv) {
1122
1123
  if (m.edge) console.error('updater: the front serves the maintenance page while the server is down');
1123
1124
  if (m.why) console.error(`updater: the maintenance page: ${m.why}`);
1124
1125
  } catch (error) { console.error(`updater: the maintenance page could not be set: ${error.message}`); }
1126
+ try {
1127
+ const conf = readConf(PATHS.conf);
1128
+ const file = join(PATHS.stateDir, 'multipass-refresh.json');
1129
+ const state = () => { try { return JSON.parse(readFileSync(file, 'utf8')); } catch { return {}; } };
1130
+ const save = (change) => { writeFileSync(`${file}.new`, `${JSON.stringify({ ...state(), ...change })}\n`); renameSync(`${file}.new`, file); };
1131
+ await multipassTurn({ run: runCommand, mode: conf.MODE, inWindow: inWindow(conf.WINDOW, new Date()), busy: () => u.busy(), state, save, log: (line) => console.error(`updater: ${line}`) });
1132
+ } catch (error) { console.error(`updater: Multipass could not be looked at: ${error.message}`); }
1125
1133
  const r = await u.runOnce(); console.log(typeof r === 'string' ? r : 'done'); return; }
1126
1134
  case 'set': if (rest.length !== 2) throw new Refused('set <mode|channel|window|port> <value>'); return print(u.set(rest[0], rest[1]));
1127
1135
  case 'prepare': { const r = await u.prepare({ version: value('--version'), fromDir: value('--from-dir') }); console.log(r.id); return; }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.520-next.1",
3
+ "version": "0.2.521-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.520-next.1",
9
+ "version": "0.2.521-next.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.520-next.1",
3
+ "version": "0.2.521-next.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.",
@@ -29,8 +29,15 @@ const PING_MS = 40_000;
29
29
 
30
30
  const said = (r) => String(r?.stderr || r?.stdout || '').trim().split('\n').filter(Boolean).pop()?.slice(0, 200) || `exit ${r?.code}`;
31
31
 
32
+ /* Name -> state, from `multipass list --format csv`. */
33
+ export function statesOf(csv) {
34
+ const out = new Map();
35
+ for (const line of String(csv ?? '').split('\n').slice(1)) { const [name, state] = line.split(','); if (/^clv-[a-z0-9-]+$/.test(name ?? '') && state) out.set(name, state); }
36
+ return out;
37
+ }
38
+
32
39
  export class VmWatch {
33
- #run; #store; #now; #hour; #log; #alert; #stuckMs; #reviveEveryMs; #downSince = null; #reviving = null;
40
+ #run; #store; #now; #hour; #log; #alert; #stuckMs; #reviveEveryMs; #downSince = null; #reviving = null; #running = new Set();
34
41
  ok = true;
35
42
  /* `hour()`: this server's local hour, 0-23 (injected for tests). */
36
43
  constructor({ run, store, now = () => Date.now(), hour = () => new Date().getHours(), log = (line) => console.error(line), alert = () => {}, stuckMs = STUCK_MS, reviveEveryMs = REVIVE_EVERY_MS }) {
@@ -61,9 +68,13 @@ export class VmWatch {
61
68
  async look() {
62
69
  const r = await this.#run(['vm', 'ping'], { timeoutMs: PING_MS }).catch((e) => ({ code: 1, stderr: e.message }));
63
70
  if (r.code === 0) {
64
- if (!this.ok) this.#log('vm manager: it answers again');
71
+ const was = !this.ok;
72
+ if (was) this.#log('vm manager: it answers again');
65
73
  this.ok = true; this.#downSince = null;
66
74
  this.#store.remove?.('asked');
75
+ const states = statesOf(r.stdout);
76
+ if (was) await this.#bringBack(states);
77
+ else this.#running = new Set([...states].filter(([, s]) => s === 'Running').map(([n]) => n));
67
78
  return 'ok';
68
79
  }
69
80
  if (this.ok) this.#log(`vm manager: it does not answer (${said(r)})`);
@@ -90,6 +101,21 @@ export class VmWatch {
90
101
  return result === 'done' ? 'revived' : 'revive failed';
91
102
  }
92
103
 
104
+ /* BACK AFTER A CUT (23-11, on a real server: Multipass updated by snap left every machine suspended, and a machine
105
+ suspended reads as a conversation asleep: nobody woke them). Only those that ran at the last look before it. */
106
+ async #bringBack(states) {
107
+ const left = [...this.#running].filter((n) => states.get(n) === 'Suspended');
108
+ this.#running = new Set([...states].filter(([, s]) => s === 'Running').map(([n]) => n));
109
+ if (!left.length) return;
110
+ this.#log(`vm manager: ${left.length} machine(s) left suspended by the cut: started again`);
111
+ const failed = [];
112
+ for (const name of left) {
113
+ const done = await this.#run(['vm', 'start', name], { timeoutMs: 300_000 }).catch((e) => ({ code: 1, stderr: e.message }));
114
+ if (done.code === 0) this.#running.add(name); else { failed.push(name); this.#log(`vm manager: ${name} could not be started again (${said(done)})`); }
115
+ }
116
+ if (failed.length) this.#alert({ title: 'Machines still asleep', body: `After the machine manager was cut, ${failed.length} could not be started again: open them.`, url: '/?open=settings&at=machines' });
117
+ }
118
+
93
119
  /* RESTARTED BY ITS OWNER (Settings, Machines; confirmed there): now, whatever the hour or the last one.
94
120
  One at a time. Resolves with what the server records: { at, why, result, by }. */
95
121
  async revive() {