clavarium 0.2.6 → 0.2.7-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.
@@ -495,6 +495,8 @@ case "$AREA $VERB" in
495
495
  # place <machines|data|folders> <device> <size MB> <free MB>
496
496
  # memory <total MB> <available MB>
497
497
  # machine <one of our VMs> <resident MB>
498
+ # cpu <total ticks> <idle ticks> <cores> (for the curves: a difference of two looks)
499
+ # machinecpu <one of our VMs> <ticks it used>
498
500
  [ $# -eq 0 ] || usage
499
501
  if [ "$SAY" = "yes" ]; then printf '%s\n' "df $SHELF_STORE $DATA $MNT" "/proc/meminfo" "resident memory of the processes of our machines"; exit 0; fi
500
502
  store="$SHELF_STORE"; [ -d "$store" ] || store="/var"
@@ -511,7 +513,10 @@ case "$AREA $VERB" in
511
513
  [ -n "$vm" ] || continue
512
514
  rss="$(awk '/^VmRSS:/{print int($2/1024)}' "/proc/$pid/status" 2>/dev/null)" || rss=""
513
515
  [ -n "$rss" ] && printf 'machine %s %s\n' "$vm" "$rss"
516
+ ticks="$(awk '{print $14 + $15}' "/proc/$pid/stat" 2>/dev/null)" || ticks=""
517
+ [ -n "$ticks" ] && printf 'machinecpu %s %s\n' "$vm" "$ticks"
514
518
  done
519
+ awk '/^cpu /{t=0; for (i=2; i<=NF; i++) t+=$i; idle=$5+$6} /^cpu[0-9]/{n++} END{printf "cpu %d %d %d\n", t, idle, n}' /proc/stat
515
520
  exit 0 ;;
516
521
  "server usage")
517
522
  # WHAT TAKES THE ROOM, for Settings: this server's own data, the
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.6",
3
+ "version": "0.2.7-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.6",
9
+ "version": "0.2.7-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.6",
3
+ "version": "0.2.7-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.",
package/server/api.mjs CHANGED
@@ -70,6 +70,7 @@
70
70
  * GET /api/machines/places GET /api/machines/moving POST /api/machines/move {to}: all the machines to another disk
71
71
  * POST /api/machines/forget-old: the copy a move left behind, removed
72
72
  * GET /api/machines/disks: every disk, whole POST /api/machines/mount {path} POST /api/machines/prepare {path, typed}: erased
73
+ * GET /api/history?of=server|<name>&span=1h|24h|7d the curves of memory, CPU and disk (and the reserve, for the server)
73
74
  * GET /api/server/logs?source=&span= what the server's programs said POST /api/server/restart
74
75
  * GET /api/operators who may sign in POST /api/operators {email} -> {email, password}: shown once
75
76
  * POST /api/operators/<email>/password -> {email, password} POST /api/operators/<email>/disable|enable|remove
@@ -124,7 +125,7 @@ function readBody(request, max = BODY_MAX) {
124
125
  }
125
126
 
126
127
  /* Returns true when the request was an API request (answered here). */
127
- export async function handleApi(request, response, conversations, headers, resources, originOk = sameOrigin, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs) {
128
+ export async function handleApi(request, response, conversations, headers, resources, originOk = sameOrigin, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history) {
128
129
  const { pathname } = new URL(request.url ?? '/', 'http://local');
129
130
  if (!pathname.startsWith('/api/')) return false;
130
131
  const send = (status, body) => {
@@ -227,6 +228,21 @@ export async function handleApi(request, response, conversations, headers, resou
227
228
  /* Who may sign in (operators.mjs): none in local mode. */
228
229
  const reactOf = /^\/api\/conversations\/([^/]+)\/health-react$/.exec(pathname);
229
230
  if (reactOf && reacting) return send(200, reacting.settings(decodeURIComponent(reactOf[1]))), true;
231
+ if (pathname === '/api/history' && history) {
232
+ const of = query.get('of') ?? 'server';
233
+ if (of !== 'server' && !conversations.list().some((c) => c.name === of)) throw new Refusal(404, 'No such conversation.');
234
+ const curves = history.series(of, query.get('span') ?? '1h');
235
+ /* The reserve as a level of the curve: where what is used meets what must stay free. */
236
+ if (of === 'server' && capacity) {
237
+ const a = await capacity.about().catch(() => null);
238
+ const disk = a?.disk ?? a?.disks?.find?.((d) => d.holds?.includes('machines'));
239
+ curves.reserve = {
240
+ memory: a?.memory?.totalMb ? Math.max(0, 100 - (a.reserve.memoryMb / a.memory.totalMb) * 100) : null,
241
+ disk: disk?.sizeMb ? Math.max(0, 100 - (a.reserve.diskMb / disk.sizeMb) * 100) : null,
242
+ };
243
+ }
244
+ return send(200, curves), true;
245
+ }
230
246
  if (pathname === '/api/server/logs' && serverLogs) return send(200, await serverLogs.read(query.get('source') ?? 'clavarium', query.get('span') ?? '1')), true;
231
247
  if (pathname === '/api/machines/disks' && machinesMove) return send(200, await machinesMove.disks()), true;
232
248
  if (pathname === '/api/machines/places' && machinesMove) return send(200, await machinesMove.places()), true;
@@ -61,11 +61,13 @@ const whole = (text) => (/^\d{1,12}$/.test(String(text)) ? Number(text) : undefi
61
61
 
62
62
  /* What "server room" printed, as facts; any other line is left out. */
63
63
  export function readRoom(text) {
64
- const facts = { places: [], memory: null, machines: [] };
64
+ const facts = { places: [], memory: null, machines: [], cpu: null, machineCpu: {} };
65
65
  for (const line of String(text ?? '').slice(0, 64 * 1024).split('\n').slice(0, 500)) {
66
66
  const p = line.trim().split(' ');
67
67
  if (p[0] === 'place' && p.length === 5 && PLACES.includes(p[1]) && [2, 3, 4].every((i) => whole(p[i]) !== undefined) && !facts.places.some((x) => x.what === p[1])) facts.places.push({ what: p[1], device: whole(p[2]), sizeMb: whole(p[3]), freeMb: whole(p[4]) });
68
68
  if (p[0] === 'memory' && p.length === 3 && whole(p[1]) > 0 && whole(p[2]) !== undefined) facts.memory = { totalMb: whole(p[1]), availableMb: whole(p[2]) };
69
+ if (p[0] === 'cpu' && p.length === 4 && [1, 2, 3].every((i) => whole(p[i]) !== undefined)) facts.cpu = { ticks: whole(p[1]), idle: whole(p[2]), cores: whole(p[3]) };
70
+ if (p[0] === 'machinecpu' && p.length === 3 && VM.test(p[1]) && whole(p[2]) !== undefined) facts.machineCpu[p[1]] = whole(p[2]);
69
71
  if (p[0] === 'machine' && p.length === 3 && VM.test(p[1]) && whole(p[2]) !== undefined && !facts.machines.some((m) => m.vm === p[1])) facts.machines.push({ vm: p[1], rssMb: whole(p[2]) });
70
72
  }
71
73
  return facts;
@@ -0,0 +1,117 @@
1
+ /* THE CURVES OF THE RESOURCES (Settings, This server, Resources; a conversation's
2
+ * Machine chapter): memory, CPU and disk, of this server and of each machine, one
3
+ * look a minute, kept seven days.
4
+ *
5
+ * Nothing is asked of any machine here: what the server knows already is taken --
6
+ * "server room" (capacity.mjs: memory, disks, the CPU time of the whole server
7
+ * and of each machine's process), and what health.mjs last saw inside a machine
8
+ * (its memory, its disk, the programs stopped for lack of memory). A machine
9
+ * frozen inside never holds a look back.
10
+ *
11
+ * sample(room, machines) one look: `machines` [{ name, vm, cores, memoryMb,
12
+ * health }] (health: health.mjs's last record, or null)
13
+ * series(of, span) { t: [ms...], <measure>: [percent or null...], marks: [ms...] }
14
+ * of: 'server' or a conversation's name; span: '1h' '24h' '7d'
15
+ *
16
+ * Kept: every minute for a day, then fifteen-minute blocks (their highest value:
17
+ * a peak stays seen) for a week. A few hundred kilobytes in a file of its own,
18
+ * written every few minutes; lost minutes at a restart are only a gap.
19
+ */
20
+ import { readFileSync, writeFileSync, renameSync } from 'node:fs';
21
+
22
+ export const STEP_MS = 60_000;
23
+ export const BLOCK_MS = 15 * 60_000;
24
+ const MINUTES = 24 * 60;
25
+ const BLOCKS = 7 * 24 * 4;
26
+ const SAVE_MS = 5 * 60_000;
27
+ /* What health.mjs saw inside a machine is used for this long, no more. */
28
+ const FRESH_MS = 15 * 60_000;
29
+ export const MEASURES = ['memory', 'cpu', 'disk'];
30
+ export const SPANS = { '1h': 60 * 60_000, '24h': 24 * 3600_000, '7d': 7 * 24 * 3600_000 };
31
+
32
+ const pct = (part, all) => (all > 0 ? Math.max(0, Math.min(100, Math.round((part / all) * 1000) / 10)) : null);
33
+
34
+ export class History {
35
+ #file; #now; #keys = new Map(); #last = null; #savedAt = 0;
36
+ constructor({ file = null, now = () => Date.now() } = {}) {
37
+ this.#file = file; this.#now = now;
38
+ if (file) {
39
+ try {
40
+ const kept = JSON.parse(readFileSync(file, 'utf8'));
41
+ for (const [key, v] of Object.entries(kept.keys ?? {})) if (Array.isArray(v.minutes) && Array.isArray(v.blocks)) this.#keys.set(key, { minutes: v.minutes, blocks: v.blocks, block: v.block ?? null, oom: v.oom ?? null });
42
+ } catch { /* none yet, or unreadable: a new history */ }
43
+ }
44
+ }
45
+
46
+ sample(room, machines = []) {
47
+ if (!room) return;
48
+ const t = this.#now();
49
+ const before = this.#last; this.#last = { t, cpu: room.cpu, machineCpu: room.machineCpu ?? {} };
50
+ const dTicks = before?.cpu && room.cpu ? room.cpu.ticks - before.cpu.ticks : 0;
51
+ const cores = room.cpu?.cores || 1;
52
+ /* This server: memory as the system says it, CPU since the last look, the machines' disk. */
53
+ const disk = room.places?.find((p) => p.what === 'machines') ?? room.places?.[0];
54
+ this.#push('server', t, {
55
+ memory: room.memory ? pct(room.memory.totalMb - room.memory.availableMb, room.memory.totalMb) : null,
56
+ cpu: dTicks > 0 ? pct(dTicks - (room.cpu.idle - before.cpu.idle), dTicks) : null,
57
+ disk: disk ? pct(disk.sizeMb - disk.freeMb, disk.sizeMb) : null,
58
+ }, false);
59
+ for (const m of machines) {
60
+ const h = m.health && t - Date.parse(m.health.at ?? 0) < FRESH_MS ? m.health : null;
61
+ const was = before?.machineCpu?.[m.vm]; const now = room.machineCpu?.[m.vm];
62
+ /* Its CPU as a share of the cores it was given: what one core of the server does in that time, times its cores. */
63
+ const cpu = dTicks > 0 && was !== undefined && now !== undefined && now >= was ? pct(now - was, (dTicks / cores) * (m.cores || 1)) : null;
64
+ const rss = room.machines?.find((x) => x.vm === m.vm)?.rssMb;
65
+ /* Its memory as seen inside when known (what its programs use), else what its process holds here. */
66
+ const memory = h?.memory?.totalMb ? pct(h.memory.totalMb - h.memory.availableMb, h.memory.totalMb) : rss !== undefined && m.memoryMb ? pct(rss, m.memoryMb) : null;
67
+ const d = h?.disks?.['/'];
68
+ const running = rss !== undefined;
69
+ const key = this.#keys.get(m.name);
70
+ /* A program stopped for lack of memory since the last look: a mark on the curve. */
71
+ const oom = Number.isInteger(h?.oomKills) && key?.oom !== null && key?.oom !== undefined && h.oomKills > key.oom;
72
+ this.#push(m.name, t, running ? { memory, cpu, disk: d ? pct(d.sizeMb - d.availableMb, d.sizeMb) : null } : { memory: null, cpu: null, disk: null }, oom);
73
+ if (Number.isInteger(h?.oomKills)) this.#keys.get(m.name).oom = h.oomKills;
74
+ }
75
+ if (this.#file && t - this.#savedAt >= SAVE_MS) this.save();
76
+ }
77
+
78
+ #push(key, t, values, mark) {
79
+ let k = this.#keys.get(key);
80
+ if (!k) { k = { minutes: [], blocks: [], block: null, oom: null }; this.#keys.set(key, k); }
81
+ const row = [t, ...MEASURES.map((x) => values[x] ?? null), mark ? 1 : 0];
82
+ k.minutes.push(row);
83
+ if (k.minutes.length > MINUTES) k.minutes.splice(0, k.minutes.length - MINUTES);
84
+ /* The block of fifteen minutes: its highest value of each, and any mark. */
85
+ const start = t - (t % BLOCK_MS);
86
+ if (k.block && k.block[0] !== start) {
87
+ k.blocks.push(k.block);
88
+ if (k.blocks.length > BLOCKS) k.blocks.splice(0, k.blocks.length - BLOCKS);
89
+ k.block = null;
90
+ }
91
+ if (!k.block) k.block = [start, ...MEASURES.map(() => null), 0];
92
+ MEASURES.forEach((_, i) => { const v = row[i + 1]; if (v !== null && (k.block[i + 1] === null || v > k.block[i + 1])) k.block[i + 1] = v; });
93
+ if (mark) k.block[MEASURES.length + 1] = 1;
94
+ }
95
+
96
+ series(of, span = '1h') {
97
+ const k = this.#keys.get(of);
98
+ const wide = SPANS[span] ?? SPANS['1h'];
99
+ const from = this.#now() - wide;
100
+ const rows = !k ? [] : span === '7d' ? [...k.blocks, ...(k.block ? [k.block] : [])] : k.minutes;
101
+ const kept = rows.filter((r) => r[0] >= from);
102
+ const out = { span: SPANS[span] ? span : '1h', from, to: this.#now(), t: kept.map((r) => r[0]), marks: kept.filter((r) => r[MEASURES.length + 1]).map((r) => r[0]) };
103
+ MEASURES.forEach((m, i) => { out[m] = kept.map((r) => r[i + 1]); });
104
+ return out;
105
+ }
106
+
107
+ forget(name) { this.#keys.delete(name); }
108
+
109
+ save() {
110
+ if (!this.#file) return;
111
+ this.#savedAt = this.#now();
112
+ try {
113
+ writeFileSync(`${this.#file}.tmp`, JSON.stringify({ keys: Object.fromEntries(this.#keys) }), { mode: 0o600 });
114
+ renameSync(`${this.#file}.tmp`, this.#file);
115
+ } catch { /* the next save tries again */ }
116
+ }
117
+ }
package/server/main.mjs CHANGED
@@ -60,6 +60,7 @@ import { Operators } from './operators.mjs';
60
60
  import { HealthReact } from './healthreact.mjs';
61
61
  import { MachinesMove } from './machinesmove.mjs';
62
62
  import { ServerLogs } from './serverlogs.mjs';
63
+ import { History, STEP_MS as HISTORY_STEP_MS } from './history.mjs';
63
64
  import { migrateData } from './dataformat.mjs';
64
65
  import { VmWatch } from './vmwatch.mjs';
65
66
 
@@ -121,7 +122,7 @@ const withoutTmux = (env) => Object.fromEntries(Object.entries(env).filter(([key
121
122
 
122
123
  const REFUSED = 'This Clavarium belongs to someone else: your account is not one of its operators.\n';
123
124
 
124
- function serve(port, conversations, resources, { gate = () => 'local', originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, repair, capacity, updates, instance = new Instance(), certificate, team, reacting, machinesMove, serverLogs } = {}) {
125
+ function serve(port, conversations, resources, { gate = () => 'local', originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, repair, capacity, updates, instance = new Instance(), certificate, team, reacting, machinesMove, serverLogs, history } = {}) {
125
126
  /* Its manifest carries the name of this Clavarium, or the one a device chose (instance.mjs). */
126
127
  const sendManifest = (response, url) => response.writeHead(200, { ...HEADERS, 'content-type': 'application/manifest+json' }).end(instance.manifest(new URL(url ?? '/', 'http://local').searchParams.get('name') ?? undefined));
127
128
  const sendFile = async (response, file) => {
@@ -159,7 +160,7 @@ function serve(port, conversations, resources, { gate = () => 'local', originOk,
159
160
  response.writeHead(403, { ...HEADERS, 'content-type': 'text/plain; charset=utf-8' }).end(REFUSED);
160
161
  return;
161
162
  }
162
- if (conversations && await handleApi(request, response, conversations, HEADERS, resources, originOk, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs)) return;
163
+ if (conversations && await handleApi(request, response, conversations, HEADERS, resources, originOk, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history)) return;
163
164
  if (pathname === '/manifest.webmanifest' && request.method === 'GET') { sendManifest(response, request.url); return; }
164
165
  const file = FILES[pathname];
165
166
  if (!file || (request.method !== 'GET' && request.method !== 'HEAD')) {
@@ -195,7 +196,7 @@ const PARLEY_WAIT_MS = 20_000;
195
196
  /* The product: conversations are VMs. `host` is how the host program is
196
197
  reached on this installation, as an argument vector: it is the ONLY thing
197
198
  this server runs with more rights than its own. */
198
- 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 }) {
199
+ 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, historyEveryMs = HISTORY_STEP_MS }) {
199
200
  /* The data, in the format this code reads, before anything reads it (dataformat.mjs). */
200
201
  const migrated = migrateData(dataDir);
201
202
  if (migrated.ran.length) console.log(`data: format ${migrated.from} -> ${migrated.to}`);
@@ -397,6 +398,10 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
397
398
  say: (name, text) => { try { talk.event(name, { kind: 'machine-problem', text, tone: 'warn', topic: 'Machine' }); } catch { /* its chat may be off */ } } });
398
399
  all.room = (ask) => capacity.check(ask);
399
400
  const stopWatch = capacity.start();
401
+ /* The curves of the resources (history.mjs): one look a minute, from what the server knows already. */
402
+ const history = new History({ file: `${dataDir}/history.json` });
403
+ const historyLook = () => capacity.room().then((room) => history.sample(room, all.list().filter((c) => c.phase === 'ready').map((c) => ({ name: c.name, vm: `clv-${c.name}`, cores: c.cpus ?? 1, memoryMb: c.memoryMb, health: health.of(c.name) })))).catch(() => {});
404
+ const historyTimer = setInterval(() => { void historyLook(); }, historyEveryMs); historyTimer.unref?.();
400
405
  /* The certificate the front serves, said in Settings (certificate.mjs). */
401
406
  const certificate = new Certificate({ origin: publicOrigin, alerts });
402
407
  /* All the machines to another disk, from Settings (machinesmove.mjs). */
@@ -408,8 +413,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
408
413
  void team.refresh().catch((error) => console.error(`operators: ${error.message}`));
409
414
  const watching = setInterval(() => { void team.watch().catch(() => {}); }, 60_000); watching.unref?.();
410
415
  }
411
- 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, certificate, team, reacting, machinesMove, serverLogs, repair: (name) => repairTerminal(name) });
412
- server.on('close', () => { closing = true; stopVmWatch(); stopShelf(); stopHealth(); stopUpdates(); stopWatch(); clearInterval(mailTimer); clearInterval(answerTimer); clearInterval(wakeTimer); clearInterval(gitTimer); talk.stop(); });
416
+ 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, certificate, team, reacting, machinesMove, serverLogs, history, repair: (name) => repairTerminal(name) });
417
+ server.on('close', () => { closing = true; clearInterval(historyTimer); history.save(); stopVmWatch(); stopShelf(); stopHealth(); stopUpdates(); stopWatch(); clearInterval(mailTimer); clearInterval(answerTimer); clearInterval(wakeTimer); clearInterval(gitTimer); talk.stop(); });
413
418
  let closing = false;
414
419
  bridge = attachBridge(server, {
415
420
  onRejoin: (name) => all.rejoin(name),
@@ -13,8 +13,9 @@
13
13
  * asked for alerts (alerts.mjs), and the line in Settings.
14
14
  */
15
15
  import { readFileSync, existsSync } from 'node:fs';
16
+ import { spawnSync } from 'node:child_process';
16
17
  import { Refusal } from './conversations.mjs';
17
- import { compareVersions } from '../deploy/updater.mjs';
18
+ import { compareVersions, inWindow } from '../deploy/updater.mjs';
18
19
 
19
20
  export const STATE_FILE = '/var/lib/clavarium/update/state.json';
20
21
  export const CONF_FILE = '/etc/clavarium/update.conf';
@@ -24,13 +25,43 @@ const VERSION = /^\d{1,4}\.\d{1,4}\.\d{1,6}(-[0-9A-Za-z.-]{1,40})?$/;
24
25
  const LOCAL = /^local-\d{8}-\d{6}$/;
25
26
  const WINDOW = /^([01]\d|2[0-3]):[0-5]\d-([01]\d|2[0-3]):[0-5]\d$/;
26
27
  const HISTORY_SHOWN = 8;
28
+ /* The updater's timer (install.sh): every 15 minutes, up to 3 more at random; the registry asked at most every 6 hours in mode "ask". */
29
+ export const LOOK_EVERY_MS = 15 * 60_000;
30
+ export const ASK_EVERY_MS = 6 * 3600_000;
31
+
32
+ /* WHEN IT WILL HAPPEN, for Settings: the updater's next look, and when an update may be installed. All times in
33
+ milliseconds; the window is in this server's own time, as the updater reads it. */
34
+ export function schedule({ mode, window, lastLookAt, checkedAt, now = new Date() }) {
35
+ const t = now.getTime();
36
+ let nextLookAt = Number.isFinite(lastLookAt) ? lastLookAt + LOOK_EVERY_MS : null;
37
+ if (nextLookAt !== null && nextLookAt < t) nextLookAt = null;
38
+ const out = { mode, lookEveryMs: LOOK_EVERY_MS, lastLookAt: Number.isFinite(lastLookAt) ? lastLookAt : null, nextLookAt };
39
+ if (mode === 'auto') {
40
+ const [from, to] = window.split('-');
41
+ const at = (hhmm, base) => { const [h, m] = hhmm.split(':').map(Number); const d = new Date(base); d.setHours(h, m, 0, 0); return d; };
42
+ out.inWindow = inWindow(window, now);
43
+ let opens = at(from, now); if (opens.getTime() <= t) opens = new Date(opens.getTime() + 86_400_000);
44
+ let closes = at(to, now); if (closes.getTime() <= t) closes = new Date(closes.getTime() + 86_400_000);
45
+ out.windowOpensAt = out.inWindow ? null : opens.getTime();
46
+ out.windowClosesAt = closes.getTime();
47
+ }
48
+ if (mode === 'ask') out.askNextAt = Number.isFinite(checkedAt) ? Math.max(t, checkedAt + ASK_EVERY_MS) : null;
49
+ return out;
50
+ }
51
+ /* When the updater's timer last ran (systemd says it to anybody), or null. */
52
+ function timerLastRun() {
53
+ const r = spawnSync('systemctl', ['show', 'clavarium-update.timer', '-p', 'LastTriggerUSec', '--value'], { encoding: 'utf8', timeout: 5000 });
54
+ const at = Date.parse(String(r.stdout ?? '').trim().replace(/^\w{3} /, ''));
55
+ return Number.isFinite(at) && at > 0 ? at : null;
56
+ }
27
57
  const firstLine = (text) => String(text ?? '').trim().split('\n').filter(Boolean).pop()?.replace(/^REFUSED: /, '').slice(0, 300) ?? '';
28
58
 
29
59
  export class Updates {
30
- #host; #state; #conf; #version; #store; #alerts; #timer;
60
+ #host; #state; #conf; #version; #store; #alerts; #timer; #lastLook; #lastLookCache = { at: 0, value: null };
31
61
 
32
62
  /* `host(argv)`: the host program. `store`: what was told already. */
33
- constructor({ host, version, stateFile = STATE_FILE, confFile = CONF_FILE, store, alerts }) {
63
+ constructor({ host, version, stateFile = STATE_FILE, confFile = CONF_FILE, store, alerts, lastLook = timerLastRun }) {
64
+ this.#lastLook = lastLook;
34
65
  this.#host = host; this.#version = version; this.#state = stateFile; this.#conf = confFile; this.#store = store; this.#alerts = alerts;
35
66
  }
36
67
 
@@ -57,6 +88,7 @@ export class Updates {
57
88
  ...this.#settings(),
58
89
  available: newer ? s.available : null,
59
90
  checkedAt: s.checkedAt ?? null,
91
+ when: schedule({ ...this.#settings(), lastLookAt: this.#timer_(), checkedAt: s.checkedAt ? Date.parse(s.checkedAt) : null }),
60
92
  checkError: s.checkError ?? null,
61
93
  running: s.running ?? null,
62
94
  refused: s.refused ?? null,
@@ -66,6 +98,12 @@ export class Updates {
66
98
  };
67
99
  }
68
100
 
101
+ /* The timer's last run, asked of systemd at most once a minute. */
102
+ #timer_() {
103
+ if (Date.now() - this.#lastLookCache.at > 60_000) this.#lastLookCache = { at: Date.now(), value: (() => { try { return this.#lastLook(); } catch { return null; } })() };
104
+ return this.#lastLookCache.value;
105
+ }
106
+
69
107
  async #ask(argv, what) {
70
108
  const r = await this.#host(['update', ...argv]);
71
109
  if (r.code !== 0) throw new Refusal(r.code === 78 ? 409 : 502, `${what}: ${firstLine(r.stderr) || firstLine(r.stdout) || `exit ${r.code}`}`);
package/web/app.js CHANGED
@@ -1866,6 +1866,10 @@
1866
1866
  });
1867
1867
  function paintMachine(here) {
1868
1868
  void paintReact(here);
1869
+ /* Its curves: asked again when it changes, or once in a while (paintCurves). */
1870
+ const curves = $('machine-curves');
1871
+ if (curves.dataset.of !== (here?.name ?? '')) { curves.dataset.of = here?.name ?? ''; curves.dataset.span = '1h'; for (const x of curves.querySelectorAll('.curves-span button')) x.setAttribute('aria-pressed', String(x.dataset.span === '1h')); }
1872
+ if (!DEVICE) void paintCurves(curves); else curves.hidden = true;
1869
1873
  /* General: what it is. */
1870
1874
  const facts = $('general-facts'); facts.replaceChildren();
1871
1875
  const fact = (term, value) => { const dt = document.createElement('dt'); dt.textContent = term; const dd = document.createElement('dd'); dd.textContent = value; facts.append(dt, dd); };
@@ -3459,6 +3463,23 @@
3459
3463
  : `Certificate of ${c.domain}: by ${c.issuer}, valid until ${day(c.validTo)} (${c.daysLeft} days); renewed by itself.${c.daysLeft < 10 ? ' It should have been renewed already: sudo clavarium doctor --certificate.' : ''}`;
3460
3464
  line.hidden = false;
3461
3465
  }
3466
+ /* WHEN IT HAPPENS, in words: the next look of the updater, and when a version that is out gets installed. */
3467
+ function paintUpdatesWhen(u) {
3468
+ const box = $('updates-when'); const w = u.when;
3469
+ box.hidden = !u.installed || !w; if (box.hidden) return;
3470
+ const clock = (ms) => new Date(ms).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
3471
+ const inWords = (ms) => { const m = Math.max(1, Math.round((ms - Date.now()) / 60_000)); return m < 60 ? `in ${m} min` : m < 36 * 60 ? `in ${Math.round(m / 60)} h` : `in ${Math.round(m / 1440)} days`; };
3472
+ const look = w.nextLookAt ? `the next look ${inWords(w.nextLookAt)} (around ${clock(w.nextLookAt)})` : 'the next look in a few minutes';
3473
+ const out = u.available ? `${u.available} is out. ` : '';
3474
+ const lines = {
3475
+ auto: w.inWindow ? `${out}Inside the update window now: ${u.available ? 'it is installed at' : 'a version that is out is installed at'} ${look}. The window closes at ${clock(w.windowClosesAt)}.`
3476
+ : `${out}${u.available ? 'It is installed' : 'Updates are installed'} in the window only: it opens ${inWords(w.windowOpensAt)} (at ${clock(w.windowOpensAt)}, until ${clock(w.windowClosesAt)}). Looked at every 15 minutes inside it.`,
3477
+ asap: `${out}Looked at every 15 minutes, ${look}: ${u.available ? 'it is installed then' : 'a version that is out is installed then'}.`,
3478
+ ask: `${out}The registry is asked about every 6 hours${w.askNextAt ? `, next ${inWords(w.askNextAt)}` : ''}; nothing is installed until you choose Update.`,
3479
+ off: 'Never by itself: use Check now, then Update.',
3480
+ };
3481
+ box.textContent = lines[w.mode] ?? '';
3482
+ }
3462
3483
  async function paintUpdates() {
3463
3484
  clearTimeout(updatesTimer);
3464
3485
  const u = await fetch(`${API}/updates`).then((r) => (r.ok ? r.json() : null)).catch(() => null);
@@ -3466,6 +3487,7 @@
3466
3487
  if (!u) { if (updatesBusy && !$('settings').hidden) updatesTimer = setTimeout(() => { void paintUpdates(); }, 3000); return; }
3467
3488
  lastUpdates = u;
3468
3489
  $('updates-version').textContent = `Clavarium ${u.version ?? ''}`;
3490
+ paintUpdatesWhen(u);
3469
3491
  void paintCertificate();
3470
3492
  for (const id of ['updates-check', 'updates-settings', 'updates-back']) $(id).hidden = !u.installed;
3471
3493
  if (!u.installed) {
@@ -3773,11 +3795,75 @@
3773
3795
  setTimeout(back, 5000);
3774
3796
  }).catch((error) => { $('server-restart-said').textContent = error.message; go.disabled = false; delete go.dataset.sure; go.textContent = 'Restart this server...'; });
3775
3797
  });
3798
+ /* THE CURVES (server/history.mjs): memory, CPU and disk over time, one small chart each, one
3799
+ line each on one scale (0 to 100 %); the reserve as a dotted level; a dot where a program
3800
+ was stopped for lack of memory. Hovered or touched: the value and the time under it. */
3801
+ const CURVES = [['memory', 'Memory'], ['cpu', 'CPU'], ['disk', 'Disk']];
3802
+ const svgEl = (tag, attrs) => { const e = document.createElementNS(SVG, tag); for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, String(v)); return e; };
3803
+ const curveTime = (t, span) => new Date(t).toLocaleString([], span === '7d' ? { weekday: 'short', hour: '2-digit', minute: '2-digit' } : { hour: '2-digit', minute: '2-digit' });
3804
+ function drawCurve(r, key, label) {
3805
+ const W = 300; const H = 72; const top = 4; const bottom = H - 4;
3806
+ const box = el('figure', 'curve'); box.dataset.measure = key;
3807
+ const values = r[key] ?? []; const known = values.filter((v) => v !== null);
3808
+ const head = el('figcaption', 'curve-head');
3809
+ const now = [...values].reverse().find((v) => v !== null);
3810
+ head.append(el('b', '', label), el('span', 'curve-now', now === undefined ? 'not measured yet' : `${Math.round(now)} %`), el('span', 'curve-max', known.length ? `highest ${Math.round(Math.max(...known))} %` : ''));
3811
+ const svg = svgEl('svg', { viewBox: `0 0 ${W} ${H}`, preserveAspectRatio: 'none', role: 'img', 'aria-label': `${label} over time: ${now === undefined ? 'not measured yet' : `${Math.round(now)} % now`}${known.length ? `, highest ${Math.round(Math.max(...known))} %` : ''}` });
3812
+ const x = (t) => ((t - r.from) / Math.max(1, r.to - r.from)) * W;
3813
+ const y = (v) => bottom - (v / 100) * (bottom - top);
3814
+ svg.append(svgEl('line', { x1: 0, x2: W, y1: bottom, y2: bottom, class: 'curve-base' }));
3815
+ const level = r.reserve?.[key];
3816
+ if (Number.isFinite(level)) svg.append(svgEl('line', { x1: 0, x2: W, y1: y(level), y2: y(level), class: 'curve-reserve' }));
3817
+ /* A gap in the looks (the server was down, the machine asleep) is a gap in the line. */
3818
+ const step = r.span === '7d' ? 15 * 60_000 : 60_000;
3819
+ let d = ''; let prev = null;
3820
+ r.t.forEach((t, i) => { const v = values[i]; if (v === null) { prev = null; return; } d += `${prev === null || t - prev > 3 * step ? 'M' : 'L'}${x(t).toFixed(1)},${y(v).toFixed(1)}`; prev = t; });
3821
+ if (d) svg.append(svgEl('path', { d, class: 'curve-line', 'vector-effect': 'non-scaling-stroke' }));
3822
+ for (const t of r.marks ?? []) { const m = svgEl('circle', { cx: x(t), cy: top + 3, r: 3, class: 'curve-mark' }); const title = svgEl('title', {}); title.textContent = `${curveTime(t, r.span)}: a program was stopped for lack of memory`; m.append(title); svg.append(m); }
3823
+ const cross = svgEl('line', { x1: 0, x2: 0, y1: top, y2: bottom, class: 'curve-cross' }); cross.style.display = 'none'; svg.append(cross);
3824
+ const tip = el('span', 'curve-tip'); tip.hidden = true;
3825
+ svg.addEventListener('pointermove', (event) => {
3826
+ if (!r.t.length) return;
3827
+ const at = svg.getBoundingClientRect(); const t = r.from + ((event.clientX - at.left) / at.width) * (r.to - r.from);
3828
+ let best = 0; r.t.forEach((u, i) => { if (Math.abs(u - t) < Math.abs(r.t[best] - t)) best = i; });
3829
+ cross.setAttribute('x1', x(r.t[best])); cross.setAttribute('x2', x(r.t[best])); cross.style.display = '';
3830
+ tip.textContent = `${curveTime(r.t[best], r.span)}: ${values[best] === null ? 'not measured' : `${Math.round(values[best])} %`}`; tip.hidden = false;
3831
+ });
3832
+ svg.addEventListener('pointerleave', () => { cross.style.display = 'none'; tip.hidden = true; });
3833
+ const plot = el('div', 'curve-plot'); plot.append(svg, tip);
3834
+ const foot = el('div', 'curve-foot'); foot.append(el('span', '', curveTime(r.from, r.span)), el('span', '', 'now'));
3835
+ box.append(head, plot, foot);
3836
+ if (Number.isFinite(level)) box.append(el('small', 'hint curve-legend', '..... the reserve: what must stay free'));
3837
+ return box;
3838
+ }
3839
+ const curvesAt = new WeakMap();
3840
+ async function paintCurves(box, { force = false } = {}) {
3841
+ const of = box.dataset.of; if (!of) { box.hidden = true; return; }
3842
+ const span = box.dataset.span || '1h';
3843
+ const was = curvesAt.get(box);
3844
+ if (!force && was && was.of === of && was.span === span && Date.now() - was.at < 30_000) return;
3845
+ curvesAt.set(box, { of, span, at: Date.now() });
3846
+ const r = await fetch(`${API}/history?of=${encodeURIComponent(of)}&span=${span}`).then((x) => (x.ok ? x.json() : null)).catch(() => null);
3847
+ if (box.dataset.of !== of) return;
3848
+ box.hidden = !r; if (!r) return;
3849
+ box.querySelector('.curves-row').replaceChildren(...CURVES.map(([key, label]) => drawCurve(r, key, label)));
3850
+ }
3851
+ for (const box of document.querySelectorAll('.curves')) {
3852
+ box.querySelector('.curves-span').addEventListener('click', (event) => {
3853
+ const b = event.target.closest('button[data-span]'); if (!b) return;
3854
+ box.dataset.span = b.dataset.span;
3855
+ for (const x of box.querySelectorAll('.curves-span button')) x.setAttribute('aria-pressed', String(x === b));
3856
+ void paintCurves(box, { force: true });
3857
+ });
3858
+ }
3859
+ /* Kept current while in sight: a new look a minute. */
3860
+ setInterval(() => { for (const box of document.querySelectorAll('.curves')) if (box.offsetParent !== null) void paintCurves(box, { force: true }); }, 60_000);
3776
3861
  async function paintServer() {
3777
3862
  clearTimeout(serverTimer);
3778
3863
  const r = await fetch(`${API}/server`).then((x) => (x.ok ? x.json() : null)).catch(() => null);
3779
3864
  $('settings-server-top').hidden = !r; $('settings-server').hidden = !r;
3780
3865
  if (!r) return;
3866
+ void paintCurves($('server-curves'));
3781
3867
  /* The two settings of each: a fixed amount and a share; the larger is kept free. */
3782
3868
  const set = r.settings ?? { ...r.reserve, diskPercent: 0, memoryPercent: 0 };
3783
3869
  const editing = ['reserve-disk', 'reserve-disk-percent', 'reserve-memory', 'reserve-memory-percent'].some((id) => $(id) === document.activeElement);
package/web/index.html CHANGED
@@ -177,6 +177,11 @@
177
177
  <div class="chapter-body">
178
178
  <div class="panel-top"><b>Health</b><button type="button" id="health-check">Look now</button></div>
179
179
  <ul id="machine-health" class="health-lines" aria-live="polite"></ul>
180
+ <!-- ITS CURVES: memory, CPU and disk over time (server/history.mjs). -->
181
+ <div class="curves" id="machine-curves" data-of="" hidden>
182
+ <div class="curves-head"><b>Over time</b><div class="levels curves-span" role="group" aria-label="Over"><button type="button" data-span="1h" aria-pressed="true">1 h</button><button type="button" data-span="24h" aria-pressed="false">24 h</button><button type="button" data-span="7d" aria-pressed="false">7 days</button></div></div>
183
+ <div class="curves-row"></div>
184
+ </div>
180
185
  <p id="machine-restarted" class="hint" role="status" hidden></p>
181
186
  <div class="row" id="machine-actions">
182
187
  <button type="button" id="restart" hidden>Restart the machine...</button>
@@ -651,6 +656,10 @@
651
656
  <div class="chapter-body">
652
657
  <div id="settings-server" tabindex="-1">
653
658
  <p id="server-unknown" class="hint" hidden>This server's disk and memory cannot be read just now. Nothing is refused for lack of room while they cannot.</p>
659
+ <div class="curves" id="server-curves" data-of="server" hidden>
660
+ <div class="curves-head"><b>Over time</b><div class="levels curves-span" role="group" aria-label="Over"><button type="button" data-span="1h" aria-pressed="true">1 h</button><button type="button" data-span="24h" aria-pressed="false">24 h</button><button type="button" data-span="7d" aria-pressed="false">7 days</button></div></div>
661
+ <div class="curves-row"></div>
662
+ </div>
654
663
  <div id="server-disks"></div>
655
664
  <!-- ALL THE MACHINES TO ANOTHER DISK (server/machinesmove.mjs). -->
656
665
  <details id="move-machines-box">
@@ -711,6 +720,8 @@
711
720
  <label for="updates-channel">Channel</label>
712
721
  <select id="updates-channel"><option value="latest">Stable</option><option value="next">Next (test versions)</option></select>
713
722
  </div>
723
+ <!-- WHEN: the updater's next look, and when a version that is out is installed (server/updates.mjs, schedule). -->
724
+ <p class="hint" id="updates-when" hidden></p>
714
725
  <p class="hint" id="updates-saved" role="status"></p>
715
726
  <div id="updates-back"></div>
716
727
  <details id="updates-history-box" hidden><summary>History</summary><ul id="updates-history" class="updates-history"></ul></details>
package/web/style.css CHANGED
@@ -1304,3 +1304,23 @@ select.pill { appearance: auto; }
1304
1304
  .disk-part > span { min-width: 0; overflow-wrap: anywhere; }
1305
1305
  .disk-prepare .row { flex-wrap: wrap; gap: 6px 8px; align-items: center; }
1306
1306
  .disk-prepare input { width: 9rem; }
1307
+
1308
+ /* THE CURVES: three small charts side by side, under each other on a phone. One line, one scale. */
1309
+ .curves { margin: 10px 0 12px; }
1310
+ .curves-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; flex-wrap: wrap; margin-bottom: 6px; }
1311
+ .curves-span button { padding: 2px 10px; font-size: .8125rem; }
1312
+ .curves-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(190px, 1fr)); gap: 10px; }
1313
+ .curve { margin: 0; padding: 8px 10px; border: 1px solid var(--line); border-radius: 8px; background: var(--bg); min-width: 0; }
1314
+ .curve-head { display: flex; align-items: baseline; gap: 4px 10px; flex-wrap: wrap; font-size: .8125rem; }
1315
+ .curve-now { font-variant-numeric: tabular-nums; color: var(--ink); }
1316
+ .curve-max { margin-left: auto; color: var(--ink2); font-variant-numeric: tabular-nums; }
1317
+ .curve-plot { position: relative; }
1318
+ .curve-plot svg { display: block; width: 100%; height: 72px; margin-top: 4px; touch-action: pan-y; }
1319
+ .curve-line { fill: none; stroke: var(--brass); stroke-width: 2; stroke-linejoin: round; stroke-linecap: round; }
1320
+ .curve-base { stroke: var(--line); stroke-width: 1; vector-effect: non-scaling-stroke; }
1321
+ .curve-reserve { stroke: var(--ink2); stroke-width: 1; stroke-dasharray: 3 3; vector-effect: non-scaling-stroke; }
1322
+ .curve-cross { stroke: var(--ink2); stroke-width: 1; vector-effect: non-scaling-stroke; }
1323
+ .curve-mark { fill: var(--danger); stroke: var(--bg); stroke-width: 2; }
1324
+ .curve-tip { position: absolute; top: 0; right: 0; padding: 1px 6px; border-radius: 4px; background: var(--panel); border: 1px solid var(--line); font-size: .75rem; color: var(--ink); font-variant-numeric: tabular-nums; pointer-events: none; }
1325
+ .curve-foot { display: flex; justify-content: space-between; font-size: .6875rem; color: var(--ink2); margin-top: 2px; }
1326
+ .curve-legend { display: block; margin-top: 2px; font-size: .6875rem; }