clavarium 0.2.488-next.1 → 0.2.489-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.
@@ -61,6 +61,9 @@ set -euo pipefail
61
61
  export LC_ALL=C
62
62
 
63
63
  MULTIPASS="multipass"
64
+ # SERVER LOGS: the journal reader, and how long it is given before what it said by then is shown.
65
+ JOURNALCTL="journalctl"
66
+ LOGS_SECONDS="60"
64
67
  # THE WAY DOWN (vm halt, vm hardstop): how long each step is given before the next, in seconds --
65
68
  # a polite stop, a stop by force asked of the VM manager, SIGTERM to the machine's own qemu, SIGKILL
66
69
  # to it; then how long multipass may take to answer a list, and to see the machine stopped after.
@@ -196,7 +199,8 @@ while [ $# -gt 0 ]; do
196
199
  DATA="$TEST"; MNT="$TEST"; WIFI_STATE="$TEST/wifi"; NM_KEYFILES="$TEST/system-connections"; WIFI_WAIT="3"; WIFI_UP_WAIT="3"; WIFI_STEP="0.2"
197
200
  HAND_STATE="$TEST/network"; NETPLAN_DIR="$TEST/netplan"; HAND_WAIT="3"; SYS_NET="$TEST/sys-net"
198
201
  MESH_DATA="$TEST/mesh"; MESH_STATE="$TEST/meshcentral"; CADDYFILE="$TEST/Caddyfile"; MESH_CADDY="$TEST/clavarium-meshcentral.caddy"
199
- HALT_POLITE="2"; HALT_FORCE="2"; HALT_TERM="1"; HALT_KILL="2"; HALT_LIST="2"; HALT_SETTLE="2"; QEMU_SEEN="$TEST/qemu"; shift 2 ;;
202
+ HALT_POLITE="2"; HALT_FORCE="2"; HALT_TERM="1"; HALT_KILL="2"; HALT_LIST="2"; HALT_SETTLE="2"; QEMU_SEEN="$TEST/qemu"
203
+ JOURNALCTL="$TEST/journalctl"; LOGS_SECONDS="2"; shift 2 ;;
200
204
  *) break ;;
201
205
  esac
202
206
  done
@@ -1216,21 +1220,41 @@ case "$AREA $VERB" in
1216
1220
  # source, over a span; read-only, bounded. The page masks what looks
1217
1221
  # like a secret before showing it.
1218
1222
  # server logs <clavarium|machines|updates|web|signin|tunnel|system> <10m|1|6|24|168|boot>
1223
+ # 17-11: a journal flooded by sudo (a line a second, the server's own calls of this program)
1224
+ # took more than the page waits. The server's unit is read by indexed fields, its own output
1225
+ # only (stdout), not sudo's syslog lines; sudo and PAM session lines are left out of any
1226
+ # source; the read is given LOGS_SECONDS, then what it said by then is shown, with a NOTE
1227
+ # on stderr -- never a bare failure.
1219
1228
  [ $# -eq 2 ] || usage
1229
+ # A unit by its fields: what it wrote, and what systemd said of it.
1230
+ unit() { printf '%s\n' "_SYSTEMD_UNIT=$1" + "UNIT=$1" "_PID=1" +; }
1220
1231
  case "$1" in
1221
- clavarium) units=(-u clavarium.service -u 'clavarium-view-*' -u clavarium-tools-view.service -u clavarium-move-machines.service) ;;
1222
- machines) units=(-u snap.multipass.multipassd.service) ;;
1223
- updates) units=(-u clavarium-update.service -u clavarium-certificate.service) ;;
1224
- web) units=(-u caddy.service -u oauth2-proxy.service) ;;
1225
- signin) units=(-u dex.service) ;;
1226
- tunnel) units=(-u clavarium-tunnel.service) ;;
1227
- system) units=(-k) ;;
1232
+ clavarium) matches=(_SYSTEMD_UNIT=clavarium.service _TRANSPORT=stdout _TRANSPORT=journal + UNIT=clavarium.service _PID=1 +)
1233
+ views=()
1234
+ if [ "$SAY" = "no" ]; then mapfile -t views < <(systemctl list-units --all --plain --no-legend 'clavarium-view-*' 2>/dev/null | awk '$1 ~ /^clavarium-view-[A-Za-z0-9_.@-]+$/ {print $1}' | head -50); fi
1235
+ for u in "${views[@]}" clavarium-tools-view.service clavarium-move-machines.service; do mapfile -t -O "${#matches[@]}" matches < <(unit "$u"); done
1236
+ unset 'matches[-1]' ;;
1237
+ machines) matches=(-u snap.multipass.multipassd.service) ;;
1238
+ updates) matches=(-u clavarium-update.service -u clavarium-certificate.service) ;;
1239
+ web) matches=(-u caddy.service -u oauth2-proxy.service) ;;
1240
+ signin) matches=(-u dex.service) ;;
1241
+ tunnel) matches=(-u clavarium-tunnel.service) ;;
1242
+ system) matches=(-k) ;;
1228
1243
  *) refuse "not a source of logs: $1" ;;
1229
1244
  esac
1230
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
1231
1246
  # The newest 20000 lines at most: more is too much to read on a page, and to send.
1232
- if [ "$SAY" = "yes" ]; then echo "journalctl ${units[*]} ${since[*]} -o short-iso --no-pager (the last 20000 lines)"; exit 0; fi
1233
- journalctl "${units[@]}" "${since[@]}" -o short-iso --no-pager -n 20000 2>/dev/null | cut -c1-2000 || true
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
1248
+ out="$(mktemp)"; err="$(mktemp)"
1249
+ trap 'rm -f -- "$out" "$err"' EXIT
1250
+ code=0
1251
+ timeout -k 5 "$LOGS_SECONDS" "$JOURNALCTL" "${matches[@]}" "${since[@]}" -o short-iso --no-pager -q -n 20000 >"$out" 2>"$err" || code=$?
1252
+ grep -avE ' (sudo|pkexec)\[[0-9]+\]: | pam_unix\((sudo|sudo-i|pkexec):session\)' "$out" | cut -c1-2000 || true
1253
+ case "$code" in
1254
+ 0) : ;;
1255
+ 124|137) echo "NOTE: the journal took more than ${LOGS_SECONDS}s: what it said by then" >&2 ;;
1256
+ *) echo "NOTE: journalctl ended with $code: $(grep -av '^$' "$err" | tail -n 1 | cut -c1-200)" >&2 ;;
1257
+ esac
1234
1258
  exit 0 ;;
1235
1259
  "server restart")
1236
1260
  # THIS SERVER STARTED AGAIN, asked from the page: in two seconds, by
@@ -155,31 +155,53 @@ export const SUDOERS = '/etc/sudoers.d/clavarium';
155
155
  export const QUIET_SETTINGS = ['!syslog, !pam_session', '!pam_session'];
156
156
  export const quietLine = (account, setting = QUIET_SETTINGS[0]) => `Defaults:${account} ${setting}`;
157
157
  const QUIET_COMMENT = '# Added by the Clavarium updater: its probes every few seconds are not written to the system log.';
158
- export async function ensureQuietSudo({ file = SUDOERS, run = runCommand } = {}) {
158
+ /* `told(outcome)`: what is in place after this turn, for Settings (sudo-quiet.json beside the state, server/updates.mjs):
159
+ { on: true, setting } or { on: false, why } -- the file missing, no account in it, visudo refusing (its words). */
160
+ export async function ensureQuietSudo({ file = SUDOERS, run = runCommand, told = () => {} } = {}) {
159
161
  let text;
160
- try { text = readFileSync(file, 'utf8'); } catch { return false; }
162
+ try { text = readFileSync(file, 'utf8'); } catch (error) { told({ on: false, why: `${file} not readable (${error.code ?? error.message})` }); return false; }
161
163
  const account = text.match(/^([a-z_][a-z0-9_-]*)\s+ALL=\(root\)\s+NOPASSWD:/m)?.[1];
162
- if (!account) return false;
164
+ if (!account) { told({ on: false, why: `no "<account> ALL=(root) NOPASSWD:" line in ${file}` }); return false; }
165
+ let refusal = '';
163
166
  const accepted = async (candidate) => {
164
167
  rmSync(`${file}.new`, { force: true });
165
168
  writeFileSync(`${file}.new`, candidate, { mode: 0o440 });
166
169
  const r = await run(['visudo', '-cf', `${file}.new`], { timeoutMs: 30_000 });
167
- return r.code === 0 && !/unknown setting|syntax error|parse error/i.test(`${r.stdout}\n${r.stderr}`);
170
+ const said = `${r.stdout ?? ''}\n${r.stderr ?? ''}`;
171
+ const ok = r.code === 0 && !/unknown setting|syntax error|parse error/i.test(said);
172
+ if (!ok) refusal = said.split('\n').map((l) => l.trim()).filter(Boolean).pop()?.slice(0, 200) || `visudo exit ${r.code}`;
173
+ return ok;
168
174
  };
169
175
  /* The rule as it is, without any line of ours. */
170
176
  const base = text.split('\n').filter((l) => l !== QUIET_COMMENT && !l.startsWith(`Defaults:${account} `)).join('\n').replace(/\n*$/, '\n');
171
- const current = QUIET_SETTINGS.map((q) => quietLine(account, q)).find((l) => text.includes(l));
177
+ const current = QUIET_SETTINGS.find((q) => text.includes(quietLine(account, q)));
172
178
  try {
173
- if (current && await accepted(text)) return false; /* ours, and taken as it is */
179
+ if (current && await accepted(text)) { told({ on: true, setting: current, account }); return false; } /* ours, and taken as it is */
180
+ const refused = [];
174
181
  for (const setting of QUIET_SETTINGS) {
175
182
  const next = `${base}${QUIET_COMMENT}\n${quietLine(account, setting)}\n`;
176
- if (await accepted(next)) { renameSync(`${file}.new`, file); return true; }
183
+ if (await accepted(next)) {
184
+ try { renameSync(`${file}.new`, file); } catch (error) { told({ on: false, why: `${file} not replaced (${error.code ?? error.message})` }); throw error; }
185
+ told({ on: true, setting, account }); return true;
186
+ }
187
+ refused.push(`${setting}: ${refusal}`);
177
188
  }
178
189
  /* None taken: the rule alone, as install.sh wrote it -- never a file sudo complains about. */
190
+ told({ on: false, why: `visudo refused ${refused.join('; ')}`.slice(0, 300) });
179
191
  if (current && await accepted(base)) { renameSync(`${file}.new`, file); return true; }
180
192
  return false;
181
193
  } finally { rmSync(`${file}.new`, { force: true }); }
182
194
  }
195
+ /* WHETHER IT WORKS, for Settings (17-11: the owner's journal still had a sudo line a second, the rule said to be
196
+ written): which sudo this is (`sudo --version`, its first line), and how many sudo lines the journal got over
197
+ the last ten minutes -- read by its own field, which the journal indexes: no long read. */
198
+ export async function sudoSeen({ run = runCommand } = {}) {
199
+ const v = await run(['sudo', '--version'], { timeoutMs: 10_000 }).catch(() => ({ code: 1, stdout: '' }));
200
+ const sudo = String(v.stdout ?? '').split('\n')[0].trim().slice(0, 80) || null;
201
+ const j = await run(['journalctl', 'SYSLOG_IDENTIFIER=sudo', '--since', '-10min', '-o', 'cat', '--no-pager', '-q'], { timeoutMs: 20_000 }).catch(() => ({ code: 1, stdout: '' }));
202
+ const lines10m = j.code === 0 ? String(j.stdout ?? '').split('\n').filter((l) => l.trim()).length : null;
203
+ return { sudo, lines10m };
204
+ }
183
205
 
184
206
  /* FFMPEG, kept by the updater: the voice boxes play a radio, a podcast, a music file through it
185
207
  (server/boxes.mjs, listen). Installed by install.sh; added once to a machine installed before. */
@@ -1071,7 +1093,17 @@ async function main(argv) {
1071
1093
  try { const [{ installWatch }, { realSys }] = await Promise.all([import('./doctor.mjs'), import('./online.mjs')]); if (await installWatch(realSys())) console.error('updater: the certificate timer set up'); } catch (error) { console.error(`updater: the certificate timer could not be set up: ${error.message}`); }
1072
1094
  try { if (await u.ensureDropIn()) console.error('updater: the drop-in of the server\'s unit written'); } catch (error) { console.error(`updater: the drop-in could not be written: ${error.message}`); }
1073
1095
  try { if (await ensureFfmpeg()) console.error('updater: ffmpeg installed, for the sounds the voice boxes play'); } catch (error) { console.error(`updater: ffmpeg could not be installed: ${error.message}`); }
1074
- try { if (await ensureQuietSudo()) console.error('updater: sudo no longer logs the host program\'s probes'); } catch (error) { console.error(`updater: sudo could not be made quiet: ${error.message}`); }
1096
+ /* What became of it is kept beside the state, for Settings (server/updates.mjs: sudoQuiet). */
1097
+ {
1098
+ let outcome = { on: false, why: 'not looked at' };
1099
+ try { if (await ensureQuietSudo({ told: (o) => { outcome = o; } })) console.error('updater: sudo no longer logs the host program\'s probes'); } catch (error) { console.error(`updater: sudo could not be made quiet: ${error.message}`); if (outcome.on) outcome = { on: false, why: error.message.slice(0, 200) }; }
1100
+ if (!outcome.on) console.error(`updater: sudo quiet: not applied: ${outcome.why}`);
1101
+ try {
1102
+ const seen = await sudoSeen();
1103
+ writeFileSync(join(PATHS.stateDir, 'sudo-quiet.json.new'), `${JSON.stringify({ ...outcome, ...seen, at: new Date().toISOString() })}\n`, { mode: 0o644 });
1104
+ renameSync(join(PATHS.stateDir, 'sudo-quiet.json.new'), join(PATHS.stateDir, 'sudo-quiet.json'));
1105
+ } catch (error) { console.error(`updater: the sudo quiet state could not be kept: ${error.message}`); }
1106
+ }
1075
1107
  try { if (await ensureProxySettings()) console.error('updater: the sign-in proxy set (one CSRF cookie per sign-in; /api/ext/ for API keys)'); } catch (error) { console.error(`updater: the sign-in proxy could not be set: ${error.message}`); }
1076
1108
  try { const c = await ensureGenericClientId({ run: runCommand }); if (c.changed.length) console.error('updater: the sign-in client id was made generic (nothing names the product in the open)'); } catch (error) { console.error(`updater: the sign-in client id could not be made generic: ${error.message}`); }
1077
1109
  try { if (await ensureTunnel({ run: runCommand })) console.error('updater: the tunnel to the relay notices a cut sooner'); } catch (error) { console.error(`updater: the tunnel could not be set: ${error.message}`); }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.488-next.1",
3
+ "version": "0.2.489-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.488-next.1",
9
+ "version": "0.2.489-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.488-next.1",
3
+ "version": "0.2.489-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
@@ -142,6 +142,7 @@
142
142
  * POST /api/server/machines/<name>/force its machine forced off, as from its conversation (202)
143
143
  * POST /api/server/vm-manager {mode: night|always|ask}: when it hangs, restarted by itself at night (default), always, or never
144
144
  * POST /api/server/vm-manager/restart {confirm: true}: restarted now; every machine is suspended and resumed
145
+ * GET /api/server/load host commands by 5-minute window, event-loop delay
145
146
  * GET /api/server/logs?source=&span= what the server's programs said POST /api/server/restart POST /api/server/reboot (the whole server)
146
147
  * GET /api/operators who may sign in POST /api/operators {email} -> {email, password}: shown once
147
148
  * POST /api/operators/<email>/password -> {email, password} POST /api/operators/<email>/disable|enable|remove
@@ -478,6 +479,8 @@ export async function handleApi(request, response, conversations, headers, resou
478
479
  }));
479
480
  return send(200, history.together(query.get('span') ?? '1h', machines, { memoryMb: a?.memory?.totalMb, cores: room?.cpu?.cores, diskMb: a?.disk?.sizeMb })), true;
480
481
  }
482
+ /* What this server asked of the host, by 5-minute window, and its own event loop (vm.mjs HostTally). */
483
+ if (pathname === '/api/server/load' && serverLogs) return send(200, serverLogs.load()), true;
481
484
  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; }
482
485
  if (pathname === '/api/machines/disks' && machinesMove) return send(200, await machinesMove.disks()), true;
483
486
  if (pathname === '/api/machines/places' && machinesMove) return send(200, await machinesMove.places()), true;
package/server/main.mjs CHANGED
@@ -28,7 +28,7 @@ import { Store, JsonFile } from './store.mjs';
28
28
  import { Instance } from './instance.mjs';
29
29
  import { loadTools, screenRules } from './tools.mjs';
30
30
  import { SigninHelp, typeInto } from './signinhelp.mjs';
31
- import { Vms, runner } from './vm.mjs';
31
+ import { Vms, runner, HostTally } from './vm.mjs';
32
32
  import { Resources, WORK_TAB } from './resources.mjs';
33
33
  import { download } from './files.mjs';
34
34
  import { makeGate, makeOriginCheck, readOperators } from './gate.mjs';
@@ -333,11 +333,15 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
333
333
  const originOk = makeOriginCheck(publicOrigin);
334
334
  const instance = new Instance({ file: new JsonFile(`${dataDir}/instance.json`, {}), origin: publicOrigin, given: appName });
335
335
  let repairTerminal = async () => { throw new Error('not ready'); };
336
- const asHost = runner(host);
336
+ /* Every command to the host counted (vm.mjs HostTally): said in the log every 5 minutes, and in Settings
337
+ (Diagnostics, Load). The machines' own commands are counted by Vms, with the same tally. */
338
+ const hostTally = new HostTally({ loop: true });
339
+ const hostRun = runner(host);
340
+ const asHost = hostTally.wrap(hostRun);
337
341
  /* A conversation in a shared machine (#221) says which: the machine its VM operations reach. */
338
342
  const jobs = new Jobs({ path: `${dataDir}/jobs.json` });
339
343
  const conversationStore = new Store(`${dataDir}/conversations.json`, { onChange: (before, after) => jobs.seen(before, after) });
340
- const vms = new Vms(asHost, host, {
344
+ const vms = new Vms(hostRun, host, { tally: hostTally,
341
345
  machineOf: (name) => { const m = conversationStore.get(name)?.sharedMachine; return typeof m === 'string' && m ? m : undefined; },
342
346
  userOf: (name) => { const u = conversationStore.get(name)?.machineUser; return u && Number.isInteger(u.uid) && Number.isInteger(u.gid) ? u : undefined; },
343
347
  });
@@ -834,7 +838,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
834
838
  /* All the machines to another disk, from Settings (machinesmove.mjs). */
835
839
  const machinesMove = new MachinesMove({ host: asHost, usedMb: () => capacity.machinesUsedMb() });
836
840
  /* What the server's programs said, and this server started again, from Settings (serverlogs.mjs). */
837
- const serverLogs = new ServerLogs({ host: asHost });
841
+ const serverLogs = new ServerLogs({ host: asHost, load: () => hostTally.windows() });
838
842
  /* This server's Wi-Fi, from Settings (wifi.mjs): how a switch ended, said in What happened. */
839
843
  const wifi = new Wifi({ host: asHost, said: (text) => events.add({ kind: 'server', text }) });
840
844
  /* The remote screen (MeshCentral), from Settings (meshcentral.mjs): how a turn-on ended, said in What happened. */
@@ -6,6 +6,8 @@
6
6
  * read(source, span) { source, span, text, lines, cut } -- what looks like a
7
7
  * secret masked: a value after password=, token:, Bearer...;
8
8
  * any run of 32 letters and digits or more (a key, a token)
9
+ * `note`: why it may be short (the journal too slow, journalctl's last word)
10
+ * load() the host commands of the last windows (vm.mjs HostTally): Settings, Load
9
11
  * restart() this server starts again in two seconds (its machines go on)
10
12
  */
11
13
  import { Refusal } from './conversations.mjs';
@@ -27,9 +29,16 @@ export function mask(text) {
27
29
  export const WAIT_MS = 12_000;
28
30
  export const KEPT_MS = 120_000;
29
31
 
32
+ /* Sudo's and PAM's lines for each call of the host program: a line a second on a busy server, nothing to read
33
+ (the host program leaves them out too: these are for one older than it). */
34
+ export const NOISE = / (sudo|pkexec)\[\d+\]: | pam_unix\((sudo|sudo-i|pkexec):session\)/;
35
+ /* The last line of what it said, without the host program's REFUSED:. */
36
+ const lastWord = (text) => String(text ?? '').trim().split('\n').pop()?.replace(/^(REFUSED|NOTE): /, '').slice(0, 200) ?? '';
37
+
30
38
  export class ServerLogs {
31
- #host; #reads = new Map(); #now;
32
- constructor({ host, now = () => Date.now() }) { this.#host = host; this.#now = now; }
39
+ #host; #reads = new Map(); #now; #load;
40
+ constructor({ host, now = () => Date.now(), load = () => ({ everyMs: 0, windows: [] }) }) { this.#host = host; this.#now = now; this.#load = load; }
41
+ load() { return this.#load(); }
33
42
 
34
43
  /* The same read asked again while it runs is the same read; once done, kept a moment for
35
44
  the page that comes back for it. Resolves { pending: true } past `wait`. */
@@ -54,13 +63,19 @@ export class ServerLogs {
54
63
  if (!SOURCES.includes(source)) throw new Refusal(400, `Not a source of logs: say one of ${SOURCES.join(', ')}.`);
55
64
  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).');
56
65
  const r = await this.#host(['server', 'logs', source, String(span)], { timeoutMs: 120_000, maxBytes: TEXT_MAX * 2 });
57
- if (r.code !== 0) throw new Refusal(502, `The logs could not be read: ${String(r.stderr ?? '').trim().split('\n').pop()?.replace(/^REFUSED: /, '').slice(0, 200) || `exit ${r.code}`}`);
66
+ if (r.code !== 0) {
67
+ const why = r.timedOut ? 'no answer in 120 s' : r.tooLong ? 'more than 8 MB' : lastWord(r.stderr) || `exit ${r.code}`;
68
+ throw new Refusal(502, `The logs could not be read: ${why}`);
69
+ }
70
+ /* What may make it short (the host program's NOTE: lines): said beside it. */
71
+ const note = String(r.stderr ?? '').split('\n').filter((l) => l.startsWith('NOTE: ')).map((l) => l.slice(6).slice(0, 200)).join('; ') || null;
58
72
  let text = String(r.stdout ?? '');
73
+ if (NOISE.test(text)) text = text.split('\n').filter((l) => !NOISE.test(l)).join('\n');
59
74
  /* The newest kept when there is too much: they matter most. */
60
75
  const cut = text.length > TEXT_MAX;
61
76
  if (cut) text = text.slice(text.length - TEXT_MAX).replace(/^[^\n]*\n/, '');
62
77
  text = mask(text);
63
- return { source, span: String(span), text, lines: text ? text.split('\n').filter(Boolean).length : 0, cut };
78
+ return { source, span: String(span), text, lines: text ? text.split('\n').filter(Boolean).length : 0, cut, ...(note ? { note } : {}) };
64
79
  }
65
80
  async restart() {
66
81
  const r = await this.#host(['server', 'restart']);
@@ -57,6 +57,13 @@ export const SETTINGS_WORDS_FR = {
57
57
  'set-binders-max': 'Les agents en font {n} au plus', 'set-admin-1': '1 administrateur', 'set-admins': '{n} administrateurs',
58
58
  'set-backup-now': 'Exporter · importer', 'set-git-key': '1 clé git', 'set-git-keys': '{n} clés git', 'set-restart': 'redémarrer',
59
59
  'set-logs-now': 'Clavarium, machines, système',
60
+ /* Diagnostics › Charge (vm.mjs HostTally): les commandes à l'hôte, par fenêtre de 5 minutes. */
61
+ 'set-ch-s-load': 'Charge', 'set-load-about': 'Commandes à l\'hôte, par 5 minutes', 'set-load-copy': 'Copier',
62
+ 'set-load-open': 'maintenant', 'set-load-line': '{n} commandes · {s} s', 'set-load-loop': 'boucle {p50}/{p99} ms',
63
+ 'set-load-none': 'Rien de compté pour le moment', 'set-load-unread': 'Illisible pour le moment', 'set-load-copied': 'Copié',
64
+ /* Mises à jour: sudo discret (deploy/updater.mjs ensureQuietSudo). */
65
+ 'set-sudo-on': 'Sudo discret : oui ({setting})', 'set-sudo-off': 'Sudo discret : non appliqué : {why}',
66
+ 'set-sudo-seen': '{n} lignes sudo en 10 min',
60
67
  'set-dict-backup': 'Secours en service', 'set-dict-expired': 'Clé expirée', 'set-dict-with-backup': 'avec secours', 'set-dict-server': 'réglée sur le serveur',
61
68
  'set-offline': 'hors ligne',
62
69
  'set-device': '1 appareil', 'set-devices': '{n} appareils', 'set-no-device': 'Aucun appareil', 'set-chat': 'Chat',
@@ -109,6 +109,9 @@ export class Updates {
109
109
  back: releases.filter((r) => !r.current && (VERSION.test(r.id) || LOCAL.test(r.id))).map((r) => ({ id: r.id, version: r.version })),
110
110
  /* What became of the relay at the updater's last turn (deploy/updater.mjs, relay.json beside the state). */
111
111
  relay: (() => { try { const r = JSON.parse(readFileSync(join(dirname(this.#state), 'relay.json'), 'utf8')); return RELAY_STATES.includes(r.state) ? { state: r.state, version: typeof r.version === 'string' ? r.version : null, why: typeof r.why === 'string' ? r.why.slice(0, 300) : null, at: typeof r.at === 'string' ? r.at : null } : null; } catch { return null; } })(),
112
+ /* Whether sudo keeps the host program's calls out of the system log, at the updater's last turn
113
+ (deploy/updater.mjs ensureQuietSudo, sudoSeen; sudo-quiet.json beside the state). */
114
+ sudoQuiet: (() => { try { const q = JSON.parse(readFileSync(join(dirname(this.#state), 'sudo-quiet.json'), 'utf8')); const str = (x, n) => (typeof x === 'string' ? x.slice(0, n) : null); return typeof q.on === 'boolean' ? { on: q.on, setting: str(q.setting, 60), why: str(q.why, 300), sudo: str(q.sudo, 80), lines10m: Number.isInteger(q.lines10m) ? q.lines10m : null, at: str(q.at, 40) } : null; } catch { return null; } })(),
112
115
  /* `fetch`: nothing of that version ran (npm could not fetch it): the page says it is tried again by itself
113
116
  (app.js, updates-retry-note). Left out before 17-11, every such failure read "It did not start here". */
114
117
  history: (Array.isArray(s.history) ? s.history : []).slice(0, HISTORY_SHOWN).map(({ at, action, from, to, result, why, log, fetch }) => ({ at, action, from, to, result, why: why ?? null, log: typeof log === 'string' ? log : null, fetch: fetch === true })),
package/server/vm.mjs CHANGED
@@ -8,6 +8,7 @@
8
8
  * before it gets here, and it is checked again, because this is where it
9
9
  * turns into a command. */
10
10
  import { execFile } from 'node:child_process';
11
+ import { monitorEventLoopDelay } from 'node:perf_hooks';
11
12
  import { isConversationName } from './names.mjs';
12
13
 
13
14
  /* Where the tool starts, in its VM. At the root rather than in a home
@@ -64,7 +65,9 @@ export function runner(prefix) {
64
65
  return (argv, { input, timeoutMs = 120_000, maxBytes = 8 * 1024 * 1024, onLine, signal } = {}) => new Promise((resolve) => {
65
66
  const all = [...prefix, ...argv];
66
67
  const child = execFile(all[0], all.slice(1), { timeout: timeoutMs, maxBuffer: maxBytes, encoding: 'utf8', ...(signal ? { signal } : {}) },
67
- (error, stdout, stderr) => resolve({ code: error ? (typeof error.code === 'number' ? error.code : 1) : 0, stdout, stderr, ...(error?.name === 'AbortError' ? { aborted: true } : {}) }));
68
+ (error, stdout, stderr) => resolve({ code: error ? (typeof error.code === 'number' ? error.code : 1) : 0, stdout, stderr, ...(error?.name === 'AbortError' ? { aborted: true } : {}),
69
+ /* Why it ended without an exit of its own: cut at `timeoutMs`, or more output than `maxBytes`. */
70
+ ...(error?.killed && error?.name !== 'AbortError' ? { timedOut: true } : {}), ...(error?.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER' ? { tooLong: true } : {}) }));
68
71
  if (onLine) {
69
72
  let rest = '';
70
73
  child.stdout.on('data', (chunk) => {
@@ -104,13 +107,66 @@ export class VmUnknown extends Error {
104
107
  constructor(why) { super(`The VM manager does not answer just now (${why}): try again in a moment.`); this.status = 503; this.retry = true; }
105
108
  }
106
109
 
110
+ /* HOW MUCH THIS SERVER ASKS OF THE HOST (17-11: the owner saw a page wait 10-15 s with an idle CPU --
111
+ every command to a machine goes through the VM manager, one after another): each command counted by
112
+ what it is, with its time; every COUNT_EVERY_MS the tally is said in the log, the busiest first, and
113
+ the last LOAD_KEPT windows kept for Settings (Diagnostics, Load: GET /api/server/load) -- the journal
114
+ may be too big to read there. `loop`: this server's own event loop measured too (its delay, p50/p99:
115
+ a server stalled by itself, not by the host). */
116
+ export const LOAD_KEPT = 12;
117
+ export class HostTally {
118
+ #now; #log; #kinds = new Map(); #from = 0; #beats = [0, 0]; #kept = []; #loop = null;
119
+ constructor({ now = () => Date.now(), log = (line) => console.log(line), loop = false } = {}) {
120
+ this.#now = now; this.#log = log;
121
+ if (loop) { this.#loop = monitorEventLoopDelay({ resolution: 20 }); this.#loop.enable(); }
122
+ }
123
+ /* A look of health answered by its heartbeat (`read`: no command; beat.mjs), or by a command after all. */
124
+ noteBeat(read) { this.#beats[read ? 0 : 1] += 1; }
125
+ /* `run`, each of its commands counted. */
126
+ wrap(run) {
127
+ return async (argv, options) => { const began = this.#now(); try { return await run(argv, options); } finally { this.count(argv, this.#now() - began); } };
128
+ }
129
+ count(argv, ms) {
130
+ const now = this.#now();
131
+ if (!this.#from) this.#from = now;
132
+ const kind = commandKind(argv); const was = this.#kinds.get(kind) ?? [0, 0, 0];
133
+ this.#kinds.set(kind, [was[0] + 1, was[1] + ms, Math.max(was[2], ms)]);
134
+ if (now - this.#from >= COUNT_EVERY_MS) this.#close(now);
135
+ }
136
+ #window(now) {
137
+ const kinds = [...this.#kinds].sort((a, b) => b[1][1] - a[1][1]).map(([kind, [count, ms, maxMs]]) => ({ kind, count, ms, maxMs }));
138
+ const ms = (n) => Math.round(n / 1e6);
139
+ const loop = this.#loop && this.#loop.count ? { p50: ms(this.#loop.percentile(50)), p99: ms(this.#loop.percentile(99)), max: ms(this.#loop.max) } : null;
140
+ return { from: this.#from || now, to: now, commands: kinds.reduce((n, k) => n + k.count, 0), ms: kinds.reduce((n, k) => n + k.ms, 0), kinds, beats: { read: this.#beats[0], fallback: this.#beats[1] }, loop };
141
+ }
142
+ #close(now) {
143
+ const w = this.#window(now);
144
+ const beats = w.beats.read + w.beats.fallback ? `; beat read ${w.beats.read}x, fallback ${w.beats.fallback}x` : '';
145
+ const loop = w.loop ? `; loop p50 ${w.loop.p50}ms p99 ${w.loop.p99}ms` : '';
146
+ this.#log(`host: ${w.commands} commands in ${Math.round((now - w.from) / 60_000)} min, ${Math.round(w.ms / 1000)} s spent; ${w.kinds.slice(0, 8).map((k) => `${k.kind} ${k.count}x ${Math.round(k.ms / 1000)}s max ${Math.round(k.maxMs / 1000)}s`).join('; ')}${beats}${loop}`);
147
+ this.#kept = [{ ...w, kinds: w.kinds.slice(0, 20) }, ...this.#kept].slice(0, LOAD_KEPT);
148
+ this.#kinds = new Map(); this.#from = now; this.#beats = [0, 0]; this.#loop?.reset();
149
+ }
150
+ /* The windows, the newest first: the one under way (`open`), then the closed ones. A window past its
151
+ time with no command since is closed here: an idle server still says so. */
152
+ windows() {
153
+ const now = this.#now();
154
+ if (this.#from && now - this.#from >= COUNT_EVERY_MS) this.#close(now);
155
+ const open = { ...this.#window(now), open: true };
156
+ if (!this.#from) open.from = now;
157
+ return { everyMs: COUNT_EVERY_MS, windows: [{ ...open, kinds: open.kinds.slice(0, 20) }, ...this.#kept] };
158
+ }
159
+ }
160
+
107
161
  export class Vms {
108
162
  /* `run(argv, options)` reaches the host program; `prefix` is the same
109
163
  route as an argument vector, for the one caller that needs a terminal. */
110
- #ask; #snapshot = null; #asking = null; #changed = 0; #now; #freshMs; #machineOf; #userOf;
164
+ #ask; #snapshot = null; #asking = null; #changed = 0; #now; #freshMs; #machineOf; #userOf; tally;
111
165
  /* `freshMs`: how long one answer serves every caller (0: only those asking meanwhile). */
112
166
  /* `machineOf(conversation)`: the shared machine it lives in (#221), or nothing -- its own, `clv-<conversation>`. */
113
- constructor(run, prefix, { now = () => Date.now(), freshMs = STATES_FRESH_MS, machineOf = () => undefined, userOf = () => undefined } = {}) {
167
+ /* `tally`: where its commands are counted (HostTally), shared with the server's other commands to the host. */
168
+ constructor(run, prefix, { now = () => Date.now(), freshMs = STATES_FRESH_MS, machineOf = () => undefined, userOf = () => undefined, tally } = {}) {
169
+ this.tally = tally ?? new HostTally({ now });
114
170
  /* `userOf(conversation)`: its own user in a shared machine, { uid, gid } -- what its mounts are owned by there. */
115
171
  this.#ask = run; this.prefix = prefix; this.#now = now; this.#freshMs = freshMs; this.#machineOf = machineOf; this.#userOf = userOf;
116
172
  /* What changes a machine makes the states asked again (not taken from before it). */
@@ -122,23 +178,9 @@ export class Vms {
122
178
  };
123
179
  }
124
180
 
125
- /* HOW MUCH THIS SERVER ASKS OF THE HOST (17-11: the owner saw a page wait 10-15 s with an idle CPU --
126
- every command to a machine goes through the VM manager, one after another): each command counted by
127
- what it is, with its time; every COUNT_EVERY_MS the tally is said in the log, the busiest first. */
128
- #tally = new Map(); #tallyFrom = 0; #beats = [0, 0];
129
- /* A look of health answered by its heartbeat (`read`: no command; beat.mjs), or by a command after all. */
130
- noteBeat(read) { this.#beats[read ? 0 : 1] += 1; }
131
- #count(argv, ms) {
132
- const now = this.#now();
133
- if (!this.#tallyFrom) this.#tallyFrom = now;
134
- this.#tally.set(commandKind(argv), [(this.#tally.get(commandKind(argv))?.[0] ?? 0) + 1, (this.#tally.get(commandKind(argv))?.[1] ?? 0) + ms, Math.max(this.#tally.get(commandKind(argv))?.[2] ?? 0, ms)]);
135
- if (now - this.#tallyFrom < COUNT_EVERY_MS) return;
136
- const rows = [...this.#tally].sort((a, b) => b[1][1] - a[1][1]);
137
- const all = rows.reduce((n, [, v]) => n + v[0], 0); const busy = rows.reduce((n, [, v]) => n + v[1], 0);
138
- const beats = this.#beats[0] + this.#beats[1] ? `; beat read ${this.#beats[0]}x, fallback ${this.#beats[1]}x` : '';
139
- console.log(`host: ${all} commands in ${Math.round((now - this.#tallyFrom) / 60_000)} min, ${Math.round(busy / 1000)} s spent; ${rows.slice(0, 8).map(([k, v]) => `${k} ${v[0]}x ${Math.round(v[1] / 1000)}s max ${Math.round(v[2] / 1000)}s`).join('; ')}${beats}`);
140
- this.#tally = new Map(); this.#tallyFrom = now; this.#beats = [0, 0];
141
- }
181
+ /* HOW MUCH THIS SERVER ASKS OF THE HOST: the tally (HostTally, below), its own unless one is given. */
182
+ noteBeat(read) { this.tally.noteBeat(read); }
183
+ #count(argv, ms) { this.tally.count(argv, ms); }
142
184
 
143
185
  /* EVERY MACHINE'S STATE, in one question to the VM manager, shared by every caller for a
144
186
  few seconds (and by those who ask while it is being asked). */
package/web/app.js CHANGED
@@ -9063,6 +9063,15 @@
9063
9063
  relayBox.className = asks ? 'callout' : 'hint';
9064
9064
  relayBox.dataset.state = relay.state;
9065
9065
  }
9066
+ /* Whether sudo keeps the host program's calls out of the system log, at the updater's last turn: one line. */
9067
+ const q = u.sudoQuiet;
9068
+ $('updates-sudo').hidden = !q;
9069
+ if (q) {
9070
+ const seen = [Number.isInteger(q.lines10m) ? uiSaid('set-sudo-seen', '{n} sudo lines in 10 min', { n: q.lines10m }) : '', q.sudo ?? ''].filter(Boolean).join(' · ');
9071
+ $('updates-sudo').textContent = [q.on ? uiSaid('set-sudo-on', 'Sudo quiet: on ({setting})', { setting: q.setting ?? '' }) : uiSaid('set-sudo-off', 'Sudo quiet: not applied: {why}', { why: q.why ?? '?' }), seen].filter(Boolean).join(' · ');
9072
+ /* Said loud when the journal still gets them: a line a second or more is the trouble seen 17-11. */
9073
+ $('updates-sudo').className = !q.on || q.lines10m >= 300 ? 'callout' : 'hint';
9074
+ }
9066
9075
  paintUpdatesWhen(u);
9067
9076
  void paintCertificate();
9068
9077
  for (const id of ['updates-check', 'updates-settings', 'updates-back']) $(id).hidden = !u.installed;
@@ -9642,6 +9651,42 @@
9642
9651
  const text = eventsShown.map((e) => `${e.at}\t${e.kind}\t${e.conversation ?? ''}\t${e.text}${e.who ? `\t${e.who}` : ''}`).join('\n');
9643
9652
  try { await navigator.clipboard.writeText(text); $('events-said').textContent = `Copied: ${eventsShown.length} lines.`; } catch { $('events-said').textContent = 'The clipboard is not available here.'; }
9644
9653
  });
9654
+ /* LOAD: what this server asked of the host, by 5-minute window, the busiest commands first, and its own
9655
+ event loop (server/vm.mjs HostTally; GET /api/server/load) -- when the journal is too big to read. */
9656
+ let loadShown = null; let loadTimer;
9657
+ const loadClock = (at) => new Date(at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false });
9658
+ const loadSec = (ms) => (ms >= 10_000 ? Math.round(ms / 1000) : Math.round(ms / 100) / 10);
9659
+ const loadKind = (k) => `${k.kind} ${k.count}× ${loadSec(k.ms)} s (max ${loadSec(k.maxMs)} s)`;
9660
+ const loadHead = (w) => [`${loadClock(w.from)}–${w.open ? uiSaid('set-load-open', 'now') : loadClock(w.to)}`,
9661
+ uiSaid('set-load-line', '{n} commands · {s} s', { n: w.commands, s: loadSec(w.ms) }),
9662
+ w.loop ? uiSaid('set-load-loop', 'loop {p50}/{p99} ms', { p50: w.loop.p50, p99: w.loop.p99 }) : ''].filter(Boolean).join(' · ');
9663
+ async function paintLoad() {
9664
+ clearTimeout(loadTimer);
9665
+ if (!$('settings-load-top').open) return;
9666
+ const got = await fetch(`${API}/server/load`).then((r) => (r.ok ? r.json() : null)).catch(() => null);
9667
+ if (!got) { $('load-said').textContent = uiSaid('set-load-unread', 'Unreadable for now'); return; }
9668
+ loadShown = got;
9669
+ const rows = (got.windows ?? []).map((w) => {
9670
+ const row = el('div', 'load-row');
9671
+ row.append(el('span', '', loadHead(w)));
9672
+ if (w.kinds?.length) row.append(el('span', 'load-kinds', w.kinds.slice(0, 3).map(loadKind).join(' · ')));
9673
+ return row;
9674
+ });
9675
+ $('load-list').replaceChildren(...rows);
9676
+ const any = (got.windows ?? []).some((w) => w.commands);
9677
+ $('load-said').textContent = any ? '' : uiSaid('set-load-none', 'Nothing counted yet');
9678
+ $('load-copy').hidden = !rows.length;
9679
+ loadTimer = setTimeout(() => { void paintLoad(); }, 30_000);
9680
+ }
9681
+ $('settings-load-top').addEventListener('toggle', () => { void paintLoad(); });
9682
+ $('load-copy').addEventListener('click', async () => {
9683
+ if (!loadShown) return;
9684
+ /* All of it, as text: each window, then every kind it counted. */
9685
+ const text = (loadShown.windows ?? []).map((w) => [loadHead(w), ...(w.kinds ?? []).map((k) => ` ${loadKind(k)}`),
9686
+ ...(w.beats && (w.beats.read || w.beats.fallback) ? [` beat read ${w.beats.read}×, fallback ${w.beats.fallback}×`] : []),
9687
+ ...(w.loop ? [` loop max ${w.loop.max} ms`] : [])].join('\n')).join('\n');
9688
+ try { await navigator.clipboard.writeText(text); $('load-said').textContent = uiSaid('set-load-copied', 'Copied'); } catch { $('load-said').textContent = 'The clipboard is not available here.'; }
9689
+ });
9645
9690
  /* WHAT THE SERVER'S PROGRAMS SAID: one source over a span, to read, copy whole or keep as a file. */
9646
9691
  let logsShown = null;
9647
9692
  $('logs-show').addEventListener('click', async () => {
@@ -9661,7 +9706,7 @@
9661
9706
  logsShown = body;
9662
9707
  $('logs-text').textContent = body.text || '';
9663
9708
  $('logs-text').hidden = !body.text; $('logs-acts').hidden = !body.text;
9664
- $('logs-said').textContent = body.lines ? `${body.lines} line${body.lines > 1 ? 's' : ''}${body.cut ? ' (the newest only: there were more)' : ''}.` : 'Nothing was said over that span.';
9709
+ $('logs-said').textContent = `${body.lines ? `${body.lines} line${body.lines > 1 ? 's' : ''}${body.cut ? ' (the newest only: there were more)' : ''}.` : 'Nothing was said over that span.'}${body.note ? ` ${body.note}.` : ''}`;
9665
9710
  /* The newest at the bottom, in sight. */
9666
9711
  $('logs-text').scrollTop = $('logs-text').scrollHeight;
9667
9712
  } catch (error) { $('logs-said').textContent = error.message; }
package/web/index.html CHANGED
@@ -1312,6 +1312,8 @@
1312
1312
  <div class="set-row updates-head"><div class="status-line" id="updates-line"><b id="updates-version">…</b><span id="updates-state" class="hint" role="status"></span></div><div class="set-control"><button type="button" id="updates-check">Check now</button></div></div>
1313
1313
  <p id="updates-news" class="updates-news callout" hidden></p>
1314
1314
  <div id="updates-relay" class="hint" hidden></div>
1315
+ <!-- Whether sudo keeps the host program's calls out of the system log (deploy/updater.mjs ensureQuietSudo). -->
1316
+ <p id="updates-sudo" class="hint" hidden></p>
1315
1317
  <div class="action-row" id="updates-offer" hidden><span class="hint" id="updates-retry-note" hidden></span><button type="button" id="updates-retry-no" hidden>Cancel</button><button type="button" id="updates-retry-yes" class="primary" hidden>Try again</button><button type="button" id="updates-apply" class="primary"></button></div>
1316
1318
  <div id="updates-settings" class="set-rows">
1317
1319
  <div class="set-row"><div class="set-what"><label for="updates-mode">Mode</label><small>When updates are installed</small></div><div class="set-control"><select id="updates-mode"><option value="auto">Automatic, in a window</option><option value="asap">As soon as out</option><option value="ask">Ask me</option><option value="off">Off</option></select></div></div>
@@ -1368,6 +1370,16 @@
1368
1370
  <p class="hint" id="jobs-said" role="status"></p>
1369
1371
  </div>
1370
1372
  </details>
1373
+ <!-- LOAD: what this server asked of the host, by 5-minute window, and its own event loop (server/vm.mjs
1374
+ HostTally; GET /api/server/load) -- readable when the journal is too big to read. -->
1375
+ <details class="chapter" id="settings-load-top" data-chapter="s-load">
1376
+ <summary><span class="chapter-title" data-said="set-ch-s-load">Load</span><span class="chapter-about" data-said="set-load-about">Host commands, by 5 minutes.</span></summary>
1377
+ <div class="chapter-body">
1378
+ <div id="load-list" class="load-list" aria-live="polite"></div>
1379
+ <p class="hint" id="load-said" role="status"></p>
1380
+ <div class="row"><button type="button" id="load-copy" data-said="set-load-copy" hidden>Copy</button></div>
1381
+ </div>
1382
+ </details>
1371
1383
  <!-- WHAT THE SERVER'S PROGRAMS SAID, to read, copy whole or keep (server/serverlogs.mjs);
1372
1384
  and this server started again. -->
1373
1385
  <details class="chapter" id="settings-logs-top" data-chapter="s-logs">
package/web/style.css CHANGED
@@ -1762,6 +1762,10 @@ svg.u-spark .u-oom { fill: var(--danger); stroke: var(--panel); stroke-width: 1.
1762
1762
  /* Settings, Jobs: one line each, as in the badge's list; opened, its log, one line a step. */
1763
1763
  .jobs-list { display: flex; flex-direction: column; margin: 8px 0; font-size: .875rem; }
1764
1764
  .jobs-list h3 { margin: 10px 0 2px; font-size: .8125rem; color: var(--ink2); }
1765
+ /* Settings, Diagnostics, Load: one window a row, its busiest commands under it, small. */
1766
+ .load-list { display: flex; flex-direction: column; gap: 6px; margin: 8px 0; font-size: .875rem; }
1767
+ .load-list .load-row { display: flex; flex-direction: column; min-width: 0; }
1768
+ .load-list .load-kinds { font-size: .75rem; color: var(--ink2); overflow-wrap: anywhere; }
1765
1769
  .job-line { border-bottom: 1px solid var(--line); }
1766
1770
  .job-line > summary { display: grid; grid-template-columns: 16px 1fr; gap: 2px 8px; padding: 4px 0; cursor: pointer; list-style: none; }
1767
1771
  .job-line > summary::-webkit-details-marker { display: none; }