clavarium 0.2.94-next.1 → 0.2.96-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.
@@ -211,6 +211,18 @@ run() { if [ "$SAY" = "yes" ]; then printf '%s\n' "$*"; else exec "$@"; fi; }
211
211
  # with a letter; no trailing hyphen; 32 at most. The same rule as the server.
212
212
  is_name() { [[ "$1" =~ ^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$ ]]; }
213
213
  vm_of() { is_name "${1#clv-}" && [ "$1" != "${1#clv-}" ] || refuse "not one of our VMs: ${1:-<empty>}"; }
214
+ # The qemu process(es) of one of our machines -- a qemu-system whose disk is in
215
+ # that instance, the mapping "server room" also uses. Empty when none is left,
216
+ # which is what a suspend that freed the RAM leaves behind.
217
+ vm_qemu_pids() {
218
+ local want="$1" pid vm
219
+ for pid in $(pgrep qemu-system 2>/dev/null || true); do
220
+ vm="$(tr '\0' '\n' < "/proc/$pid/cmdline" 2>/dev/null | grep -oE '/instances/clv(shelf)?-[a-z0-9-]+/' | head -1 | cut -d/ -f3)" || vm=""
221
+ [ "$vm" = "$want" ] && printf '%s\n' "$pid"
222
+ done
223
+ }
224
+ # No qemu left for this machine after a short grace: its RAM has been freed.
225
+ vm_freed() { local v="$1" i; for i in $(seq 1 24); do [ -z "$(vm_qemu_pids "$v")" ] && return 0; sleep 0.5; done; return 1; }
214
226
  number() { [[ "$1" =~ ^[0-9]{1,6}$ ]] || refuse "not a number: ${1:-<empty>}"; }
215
227
  # A disk or partition named by its device: /dev/sdX, /dev/vdX, /dev/nvmeNnN(pN),
216
228
  # /dev/xvdX, /dev/mmcblkN(pN), with a digit or two at the end; a loop device only
@@ -770,9 +782,50 @@ case "$AREA $VERB" in
770
782
  "vm info")
771
783
  [ $# -eq 1 ] || usage; vm_of "$1"
772
784
  run "$MULTIPASS" info "$1" --format json ;;
773
- "vm start"|"vm stop"|"vm suspend")
785
+ "vm start"|"vm stop")
774
786
  [ $# -eq 1 ] || usage; vm_of "$1"
775
787
  run "$MULTIPASS" "$VERB" "$1" ;;
788
+ "vm suspend")
789
+ # Veille: suspend must save the machine's state AND free its RAM by ending
790
+ # its qemu process. Multipass saves the state reliably but at times leaves
791
+ # qemu alive (canonical/multipass #446, #2152, #5432), so the RAM stays
792
+ # taken though the machine shows "Suspended". The state being saved, we make
793
+ # the RAM come back, gentlest first: a second suspend from a clean running
794
+ # state usually ends qemu (and keeps the ~2s resume); failing that, a clean
795
+ # stop frees it for sure (it then wakes by a boot). Normally qemu is already
796
+ # gone after the first suspend and none of this runs.
797
+ [ $# -eq 1 ] || usage; vm_of "$1"
798
+ if [ "$SAY" = "yes" ]; then
799
+ printf '%s\n' "$MULTIPASS suspend $1" \
800
+ "if its qemu still holds the RAM: $MULTIPASS start $1 && $MULTIPASS suspend $1 (wake+resleep)" \
801
+ "if it still does: $MULTIPASS stop $1 (free it; it wakes by a boot)"
802
+ exit 0
803
+ fi
804
+ "$MULTIPASS" suspend "$1" || refuse "suspend of $1 failed"
805
+ vm_freed "$1" && exit 0
806
+ "$MULTIPASS" start "$1" >/dev/null 2>&1 && "$MULTIPASS" suspend "$1" >/dev/null 2>&1
807
+ vm_freed "$1" && exit 0
808
+ "$MULTIPASS" stop "$1" >/dev/null 2>&1 || true
809
+ vm_freed "$1" && exit 0
810
+ refuse "suspended $1 but its memory was not freed (its qemu stayed); the VM manager likely needs a restart" ;;
811
+ "vm reclaim")
812
+ # Free a machine that is ASLEEP but whose qemu still holds the RAM -- a
813
+ # suspend (maybe from before this existed) that did not end the process.
814
+ # Idempotent and safe for an asleep machine (nobody is using it): if its
815
+ # qemu is already gone, nothing happens. Touches only this machine, and
816
+ # never restarts the VM manager.
817
+ [ $# -eq 1 ] || usage; vm_of "$1"
818
+ if [ "$SAY" = "yes" ]; then
819
+ printf '%s\n' "if $1's qemu still holds the RAM: $MULTIPASS start $1 && $MULTIPASS suspend $1 (wake+resleep)" \
820
+ "if it still does: $MULTIPASS stop $1 (free it; it wakes by a boot)"
821
+ exit 0
822
+ fi
823
+ vm_freed "$1" && exit 0
824
+ "$MULTIPASS" start "$1" >/dev/null 2>&1 && "$MULTIPASS" suspend "$1" >/dev/null 2>&1
825
+ vm_freed "$1" && exit 0
826
+ "$MULTIPASS" stop "$1" >/dev/null 2>&1 || true
827
+ vm_freed "$1" && exit 0
828
+ refuse "could not free $1's memory (its qemu stayed); the VM manager likely needs a restart" ;;
776
829
  "vm kill")
777
830
  # A stop that does not wait for the system inside: asked only after a
778
831
  # clean stop hung or failed (a restart the owner asked for).
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.94-next.1",
3
+ "version": "0.2.96-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.94-next.1",
9
+ "version": "0.2.96-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.94-next.1",
3
+ "version": "0.2.96-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.",
@@ -49,6 +49,13 @@ export const RESERVE_DISK_MAX_MB = 1024 * 1024;
49
49
  export const RESERVE_MEMORY_MAX_MB = 256 * 1024;
50
50
  export const ROOM_MS = 10_000;
51
51
  export const USAGE_MS = 5 * 60_000;
52
+ /* A sleeping machine whose qemu still holds at least this much host memory is a
53
+ suspend that did not free it (see the host program's `vm suspend`); the watch
54
+ reclaims it. */
55
+ export const RECLAIM_MIN_MB = 128;
56
+ /* The same machine is not reclaimed again within this, so a stubborn one (rare,
57
+ needs a VM-manager restart) is reported once, not looped on. */
58
+ export const RECLAIM_EVERY_MS = 30 * 60_000;
52
59
  /* The page shows its small gauge when disk or memory is fuller than this, or
53
60
  when what is free is under this many times the reserve. */
54
61
  export const HIGH_PERCENT = 85;
@@ -92,7 +99,7 @@ const percent = (part, all) => (all > 0 ? Math.round((part / all) * 100) : 0);
92
99
  export class Capacity {
93
100
  /* What the machines take on their disk, as last measured (MB), or undefined. */
94
101
  machinesUsedMb() { const u = this.#usage; if (!u) return undefined; return Object.values(u.machines ?? {}).reduce((a, b) => a + b, 0) + (u.shelf ?? 0) + (u.images ?? 0); }
95
- #run; #store; #conversations; #shelf; #now; #roomMs; #sleep; #alert; #say; #short = { disk: false, memory: false }; #room = null; #roomAt = -Infinity; #usage = null; #usageAt = -Infinity; #going = null; #measuring = null;
102
+ #run; #store; #conversations; #shelf; #now; #roomMs; #sleep; #alert; #say; #reclaim; #reclaimEveryMs; #sweeping = false; #short = { disk: false, memory: false }; #room = null; #roomAt = -Infinity; #usage = null; #usageAt = -Infinity; #going = null; #measuring = null;
96
103
 
97
104
  /* `run(argv)`: the host program. `store`: where the reserve is kept.
98
105
  `conversations`: what each machine was given. `shelf`: how large a
@@ -100,8 +107,8 @@ export class Capacity {
100
107
  /* `roomMs`: how long what is free is taken as known (ROOM_MS). */
101
108
  /* `sleep(name)`, `alert(payload)`, `say(name, text)`: what watch() does
102
109
  when what is free falls under the reserve. */
103
- constructor({ run, store, conversations, shelf = null, now = () => Date.now(), roomMs = ROOM_MS, sleep = null, alert = null, say = null }) {
104
- this.#roomMs = roomMs; this.#sleep = sleep; this.#alert = alert; this.#say = say;
110
+ constructor({ run, store, conversations, shelf = null, now = () => Date.now(), roomMs = ROOM_MS, sleep = null, alert = null, say = null, reclaim = null, reclaimEveryMs = RECLAIM_EVERY_MS }) {
111
+ this.#roomMs = roomMs; this.#sleep = sleep; this.#alert = alert; this.#say = say; this.#reclaim = reclaim; this.#reclaimEveryMs = reclaimEveryMs;
105
112
  this.#run = run; this.#store = store; this.#conversations = conversations; this.#shelf = shelf; this.#now = now;
106
113
  }
107
114
 
@@ -288,9 +295,50 @@ export class Capacity {
288
295
  return done;
289
296
  }
290
297
 
298
+ /* WATCHED too, and on its own: machines that are ASLEEP (not awake) yet whose
299
+ qemu still holds the host RAM -- a suspend that did not end the process,
300
+ including ones left stuck before this ran. Each is freed through the host
301
+ program (`vm reclaim`: wake+resleep, then a clean stop if needed), the owner
302
+ told, and not tried again within reclaimEveryMs, so a stubborn one (rare,
303
+ the VM manager would need a restart) is reported once, not looped on. Only
304
+ asleep machines are touched; the others are never disturbed, and the VM
305
+ manager is never restarted. Resolves with what was reclaimed. */
306
+ async reclaimSleepers() {
307
+ if (!this.#reclaim || this.#sweeping) return [];
308
+ this.#sweeping = true;
309
+ try {
310
+ const f = this.#figures(await this.room({ fresh: true }).catch(() => null));
311
+ if (!f) return [];
312
+ const awake = new Set(this.#conversations.awake?.() ?? []);
313
+ const holding = f.machines.filter((m) => m.name && !m.shelf && !awake.has(m.name) && m.rssMb >= RECLAIM_MIN_MB);
314
+ if (!holding.length) return [];
315
+ const now = this.#now();
316
+ const at = this.#store.get('reclaim')?.at ?? {};
317
+ const done = [];
318
+ for (const m of holding) {
319
+ if (at[m.name] && now - at[m.name] < this.#reclaimEveryMs) continue;
320
+ at[m.name] = now;
321
+ this.#store.put({ name: 'reclaim', at });
322
+ const held = m.rssMb;
323
+ await Promise.resolve(this.#reclaim(m.name)).catch(() => {});
324
+ const after = this.#figures(await this.room({ fresh: true }).catch(() => null));
325
+ const freed = !after?.machines.some((x) => x.name === m.name && !awake.has(x.name) && x.rssMb >= RECLAIM_MIN_MB);
326
+ this.#alert?.(freed
327
+ ? { title: "Reclaimed a sleeping machine's memory", body: `${m.name} was asleep but still held ${gb(held)} (its sleep had not freed it); its memory was reclaimed.`, url: '/?open=settings&at=resources' }
328
+ : { title: 'A sleeping machine still holds memory', body: `${m.name} was asleep but still held ${gb(held)} and could not be freed; the VM manager may need a restart.`, url: '/?open=settings&at=resources' });
329
+ this.#say?.(m.name, freed
330
+ ? `This machine was asleep but still held ${gb(held)} of memory (its sleep had not freed it). Its memory was reclaimed; it still wakes when you open it.`
331
+ : `This machine was asleep but still held ${gb(held)} of memory, and it could not be freed automatically — the VM manager may need a restart.`);
332
+ done.push({ name: m.name, heldMb: held, freed });
333
+ }
334
+ return done;
335
+ } finally { this.#sweeping = false; }
336
+ }
337
+
291
338
  /* Watches every `everyMs`; returns what stops it. */
292
339
  start(everyMs = WATCH_MS) {
293
- const timer = setInterval(() => { void this.watch().catch(() => {}); }, everyMs);
340
+ const tick = () => { void this.watch().catch(() => {}).finally(() => { void this.reclaimSleepers().catch(() => {}); }); };
341
+ const timer = setInterval(tick, everyMs);
294
342
  timer.unref?.();
295
343
  return () => clearInterval(timer);
296
344
  }
package/server/main.mjs CHANGED
@@ -524,6 +524,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
524
524
  const capacity = new Capacity({ run: asHost, store: new Store(`${dataDir}/server.json`), conversations: all, shelf, ...(serverRoomMs === undefined ? {} : { roomMs: serverRoomMs }),
525
525
  /* Under the reserve: the machine that takes the most put to sleep, the owner told, and its chat. */
526
526
  sleep: (name) => { events.add({ kind: 'machine', text: `Machine of ${name} put to sleep: this server was short of room`, conversation: name }); return all.sleep(name); }, alert: (payload) => { events.add({ kind: 'server', text: `${payload.title}: ${payload.body ?? ''}`.trim() }); void alerts.tell(payload); },
527
+ /* A machine asleep but still holding its RAM (a suspend that did not free it): its memory reclaimed, only that machine touched. */
528
+ reclaim: (name) => { events.add({ kind: 'machine', text: `Machine of ${name}: memory reclaimed (it was asleep but still held RAM)`, conversation: name }); return vms.reclaim(name); },
527
529
  say: (name, text) => { try { talk.event(name, { kind: 'machine-problem', text, tone: 'warn', topic: 'Machine' }); } catch { /* its chat may be off */ } } });
528
530
  all.room = (ask) => capacity.check(ask);
529
531
  const stopWatch = capacity.start();
package/server/vm.mjs CHANGED
@@ -52,7 +52,7 @@ export function runner(prefix) {
52
52
  }
53
53
 
54
54
  /* The verbs that change a machine: its state is asked again after them. */
55
- const CHANGES = new Set(['launch', 'clone', 'start', 'stop', 'suspend', 'kill', 'delete', 'purge', 'set', 'rename', 'restore', 'snapshot', 'revive']);
55
+ const CHANGES = new Set(['launch', 'clone', 'start', 'stop', 'suspend', 'kill', 'delete', 'purge', 'set', 'rename', 'restore', 'snapshot', 'revive', 'reclaim']);
56
56
  export const STATES_FRESH_MS = 3000;
57
57
  /* The VM manager did not say what a machine is in: not an answer about the machine. */
58
58
  export class VmUnknown extends Error {
@@ -181,5 +181,8 @@ export class Vms {
181
181
  return { memoryMb: mb === undefined ? undefined : Math.round(mb), diskGb: disk === undefined ? undefined : Math.round(disk / 1024), cpus };
182
182
  }
183
183
  suspend(conversation) { return this.run(['vm', 'suspend', vmName(conversation)], { timeoutMs: 300_000 }); }
184
+ /* Free the RAM of a machine that is asleep but whose qemu still holds it (a
185
+ suspend that did not end the process): wake+resleep, then a clean stop. */
186
+ reclaim(conversation) { return this.run(['vm', 'reclaim', vmName(conversation)], { timeoutMs: 300_000 }); }
184
187
  remove(conversation) { return this.run(['vm', 'delete', vmName(conversation)], { timeoutMs: 300_000 }); }
185
188
  }