clavarium 0.2.520-next.1 → 0.2.522-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.522-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.522-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.522-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.",
@@ -21,6 +21,9 @@ 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
+ /* After a cut, how long a machine is given to answer before it is restarted: 2 min. */
25
+ export const ANSWER_TRIES = 5;
26
+ export const ANSWER_EVERY_MS = 30_000;
24
27
  export const MANAGER_MODES = Object.freeze(['night', 'always', 'ask']);
25
28
  export const NIGHT_FROM = 0;
26
29
  export const NIGHT_UNTIL = 7;
@@ -29,11 +32,19 @@ const PING_MS = 40_000;
29
32
 
30
33
  const said = (r) => String(r?.stderr || r?.stdout || '').trim().split('\n').filter(Boolean).pop()?.slice(0, 200) || `exit ${r?.code}`;
31
34
 
35
+ /* Name -> state, from `multipass list --format csv`. */
36
+ export function statesOf(csv) {
37
+ const out = new Map();
38
+ 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); }
39
+ return out;
40
+ }
41
+
32
42
  export class VmWatch {
33
- #run; #store; #now; #hour; #log; #alert; #stuckMs; #reviveEveryMs; #downSince = null; #reviving = null;
43
+ #run; #store; #now; #hour; #log; #alert; #stuckMs; #reviveEveryMs; #downSince = null; #reviving = null; #running = new Set(); #wait;
34
44
  ok = true;
35
45
  /* `hour()`: this server's local hour, 0-23 (injected for tests). */
36
- constructor({ run, store, now = () => Date.now(), hour = () => new Date().getHours(), log = (line) => console.error(line), alert = () => {}, stuckMs = STUCK_MS, reviveEveryMs = REVIVE_EVERY_MS }) {
46
+ constructor({ run, store, now = () => Date.now(), hour = () => new Date().getHours(), log = (line) => console.error(line), alert = () => {}, stuckMs = STUCK_MS, reviveEveryMs = REVIVE_EVERY_MS, wait = (ms) => new Promise((r) => { setTimeout(r, ms).unref?.(); }) }) {
47
+ this.#wait = wait;
37
48
  this.#run = run; this.#store = store; this.#now = now; this.#hour = hour; this.#log = log; this.#alert = alert; this.#stuckMs = stuckMs; this.#reviveEveryMs = reviveEveryMs;
38
49
  }
39
50
 
@@ -61,9 +72,13 @@ export class VmWatch {
61
72
  async look() {
62
73
  const r = await this.#run(['vm', 'ping'], { timeoutMs: PING_MS }).catch((e) => ({ code: 1, stderr: e.message }));
63
74
  if (r.code === 0) {
64
- if (!this.ok) this.#log('vm manager: it answers again');
75
+ const was = !this.ok;
76
+ if (was) this.#log('vm manager: it answers again');
65
77
  this.ok = true; this.#downSince = null;
66
78
  this.#store.remove?.('asked');
79
+ const states = statesOf(r.stdout);
80
+ if (was) await this.#bringBack(states);
81
+ else this.#running = new Set([...states].filter(([, s]) => s === 'Running').map(([n]) => n));
67
82
  return 'ok';
68
83
  }
69
84
  if (this.ok) this.#log(`vm manager: it does not answer (${said(r)})`);
@@ -90,6 +105,38 @@ export class VmWatch {
90
105
  return result === 'done' ? 'revived' : 'revive failed';
91
106
  }
92
107
 
108
+ /* BACK AFTER A CUT (23-11, on real machines: Multipass updated by snap left every machine suspended, and a machine
109
+ suspended reads as a conversation asleep; and Multipass can say « Running » of a machine whose process is gone,
110
+ which nothing can reach). Only those that ran at the last look before it: the suspended started again, then each
111
+ asked if it answers, for a while; one that never does is stopped for sure and started. */
112
+ async #bringBack(states) {
113
+ const ran = [...this.#running].filter((n) => states.has(n));
114
+ this.#running = new Set(ran);
115
+ if (!ran.length) return;
116
+ const failed = [];
117
+ const start = async (name) => {
118
+ const done = await this.#run(['vm', 'start', name], { timeoutMs: 300_000 }).catch((e) => ({ code: 1, stderr: e.message }));
119
+ if (done.code !== 0) { failed.push(name); this.#log(`vm manager: ${name} could not be started again (${said(done)})`); }
120
+ return done.code === 0;
121
+ };
122
+ const asleep = ran.filter((n) => states.get(n) === 'Suspended');
123
+ if (asleep.length) this.#log(`vm manager: ${asleep.length} machine(s) left suspended by the cut: started again`);
124
+ for (const name of asleep) await start(name);
125
+ let silent = ran.filter((n) => !failed.includes(n));
126
+ for (let i = 0; i < ANSWER_TRIES && silent.length; i += 1) {
127
+ if (i) await this.#wait(ANSWER_EVERY_MS);
128
+ const said_ = await Promise.all(silent.map(async (n) => (await this.#run(['vm', 'exec', n, '--', 'true'], { timeoutMs: 20_000 }).catch(() => ({ code: 1 }))).code === 0));
129
+ silent = silent.filter((_, k) => !said_[k]);
130
+ }
131
+ for (const name of silent) {
132
+ this.#log(`vm manager: ${name} does not answer after the cut: stopped for sure and started`);
133
+ await this.#run(['vm', 'halt', name, 'force', 'kill'], { timeoutMs: 180_000 }).catch(() => {});
134
+ await start(name);
135
+ }
136
+ for (const n of failed) this.#running.delete(n);
137
+ if (failed.length) this.#alert({ title: 'Machines still down', body: `After the machine manager was cut, ${failed.length} could not be started again: open them.`, url: '/?open=settings&at=machines' });
138
+ }
139
+
93
140
  /* RESTARTED BY ITS OWNER (Settings, Machines; confirmed there): now, whatever the hour or the last one.
94
141
  One at a time. Resolves with what the server records: { at, why, result, by }. */
95
142
  async revive() {