clavarium 0.2.487-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.
- package/config/machine/clavarium-beat +44 -0
- package/config/machine/clavarium-beat-one +40 -0
- package/deploy/clavarium-host +34 -10
- package/deploy/updater.mjs +40 -8
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/server/api.mjs +3 -0
- package/server/beat.mjs +189 -0
- package/server/copywork.mjs +3 -2
- package/server/health.mjs +39 -8
- package/server/main.mjs +15 -5
- package/server/serverlogs.mjs +19 -4
- package/server/settingswords.mjs +7 -0
- package/server/updates.mjs +3 -0
- package/server/vm.mjs +62 -17
- package/web/app.js +46 -1
- package/web/index.html +12 -0
- package/web/style.css +4 -0
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
#!/bin/sh
|
|
2
|
+
# THE HEARTBEAT OF A MACHINE (step 6), run as root by its timer (clavarium-beat.timer, every minute or so):
|
|
3
|
+
# for the conversation of a machine of its own, or for each conversation living in a shared one, the look its
|
|
4
|
+
# server made by a command every two minutes (health.mjs, PROBE) is made here, as that conversation's own user,
|
|
5
|
+
# and written into its /work (beat-one). Its server reads it from its own side: no command into the machine.
|
|
6
|
+
#
|
|
7
|
+
# Root reads nothing that a conversation wrote: only its own settings (beat.conf, written at install) and its
|
|
8
|
+
# own counters (/var/lib/clavarium/beat). Each conversation is given a bounded time; a dead /work only stops
|
|
9
|
+
# its beat, and its server then looks the usual way.
|
|
10
|
+
set -u
|
|
11
|
+
lib=/usr/local/lib/clavarium
|
|
12
|
+
state=/var/lib/clavarium/beat
|
|
13
|
+
mode=""; conversation=""; version=""
|
|
14
|
+
[ -r "$lib/beat.conf" ] || exit 0
|
|
15
|
+
while IFS='=' read -r k v; do
|
|
16
|
+
case "$k" in mode) mode=$v ;; conversation) conversation=$v ;; version) version=$v ;; esac
|
|
17
|
+
done < "$lib/beat.conf"
|
|
18
|
+
printf '%s' "$version" | grep -Eq '^[0-9A-Za-z.+-]{1,64}$' || exit 0
|
|
19
|
+
ok_name() { printf '%s' "$1" | grep -Eq '^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$'; }
|
|
20
|
+
mkdir -p "$state"; chmod 700 "$state"
|
|
21
|
+
# Its next number: a beat that does not grow is not a new one (read by its server).
|
|
22
|
+
next() {
|
|
23
|
+
n=$(head -c 20 "$state/$1.seq" 2>/dev/null) || n=0
|
|
24
|
+
case "$n" in ''|*[!0-9]*) n=0 ;; esac
|
|
25
|
+
n=$((n + 1)); printf '%s\n' "$n" > "$state/$1.seq"; printf '%s' "$n"
|
|
26
|
+
}
|
|
27
|
+
case "$mode" in
|
|
28
|
+
own)
|
|
29
|
+
ok_name "$conversation" || exit 0
|
|
30
|
+
n=$(next "$conversation")
|
|
31
|
+
cd / && timeout -k 5 45 runuser -u ubuntu -- env HOME=/home/ubuntu sh "$lib/beat-one" "$conversation" "$n" "$version" </dev/null >/dev/null 2>&1 || true ;;
|
|
32
|
+
shared)
|
|
33
|
+
# Only a conversation whose work is shown here now (the host mounts it at /srv/clavarium/NAME/work);
|
|
34
|
+
# at most 64 of them, one after another.
|
|
35
|
+
i=0
|
|
36
|
+
for d in /srv/clavarium/*/; do
|
|
37
|
+
[ "$i" -lt 64 ] || break
|
|
38
|
+
c=$(basename "$d"); ok_name "$c" || continue
|
|
39
|
+
mountpoint -q "/srv/clavarium/$c/work" 2>/dev/null || continue
|
|
40
|
+
i=$((i + 1)); n=$(next "$c")
|
|
41
|
+
timeout -k 5 45 /usr/local/sbin/clavarium-enter "$c" -- sh "$lib/beat-one" "$c" "$n" "$version" </dev/null >/dev/null 2>&1 || true
|
|
42
|
+
done ;;
|
|
43
|
+
esac
|
|
44
|
+
exit 0
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
#!/bin/sh
|
|
2
|
+
# ONE BEAT OF ONE CONVERSATION, as its own user (ubuntu in a machine of its own, c-NAME behind its door):
|
|
3
|
+
# beat-one NAME SEQ VERSION
|
|
4
|
+
# Runs its server's look (probe.sh, exactly PROBE of health.mjs) with the paths its server expects mounted
|
|
5
|
+
# (/work/.clavarium/expected, written by the server), and writes what it printed, as JSON, to
|
|
6
|
+
# /work/.clavarium/beat.json -- whole or not at all (a file aside, then moved). Its server checks every word
|
|
7
|
+
# of it: the agent is root here, and may write anything there.
|
|
8
|
+
# CLAVARIUM_BEAT_WORK, CLAVARIUM_BEAT_LIB: other places, for its tests only.
|
|
9
|
+
set -u
|
|
10
|
+
name="$1"; seq="$2"; version="$3"
|
|
11
|
+
work="${CLAVARIUM_BEAT_WORK:-/work}"
|
|
12
|
+
lib="${CLAVARIUM_BEAT_LIB:-/usr/local/lib/clavarium}"
|
|
13
|
+
dir="$work/.clavarium"
|
|
14
|
+
[ -d "$work" ] || exit 0
|
|
15
|
+
# A link there is not followed: the agent may have put it.
|
|
16
|
+
[ -L "$dir" ] && exit 0
|
|
17
|
+
mkdir -p "$dir" 2>/dev/null || exit 0
|
|
18
|
+
set --
|
|
19
|
+
if [ -f "$dir/expected" ] && [ ! -L "$dir/expected" ]; then
|
|
20
|
+
n=0
|
|
21
|
+
while IFS= read -r p; do
|
|
22
|
+
[ "$n" -lt 100 ] || break
|
|
23
|
+
printf '%s' "$p" | grep -Eq '^/[A-Za-z0-9._/-]{1,200}$' || continue
|
|
24
|
+
set -- "$@" "$p"; n=$((n + 1))
|
|
25
|
+
done < "$dir/expected"
|
|
26
|
+
fi
|
|
27
|
+
out=$(timeout -k 2 30 sh "$lib/probe.sh" "$@" 2>/dev/null | head -c 12000)
|
|
28
|
+
# Its text as a JSON string: backslash and quote escaped, a tab written \t, lines joined by \n, any other
|
|
29
|
+
# control character left out. Character by character: every awk reads it the same way.
|
|
30
|
+
probe=$(printf '%s\n' "$out" | awk 'BEGIN { for (i = 1; i < 32; i++) drop[sprintf("%c", i)] = 1 }
|
|
31
|
+
{ s = ""; n = length($0)
|
|
32
|
+
for (i = 1; i <= n; i++) { c = substr($0, i, 1)
|
|
33
|
+
if (c == "\\") s = s "\\\\"; else if (c == "\"") s = s "\\\""; else if (c == "\t") s = s "\\t"; else if (!(c in drop)) s = s c }
|
|
34
|
+
all = all (NR > 1 ? "\\n" : "") s }
|
|
35
|
+
END { printf "%s", all }')
|
|
36
|
+
tmp="$dir/.beat.$$"
|
|
37
|
+
printf '{"v":1,"conversation":"%s","seq":%s,"version":"%s","probe":"%s"}\n' "$name" "$seq" "$version" "$probe" > "$tmp" || { rm -f "$tmp"; exit 0; }
|
|
38
|
+
# A share that does not replace a file by a rename: the old one taken away first.
|
|
39
|
+
mv -f "$tmp" "$dir/beat.json" 2>/dev/null || { rm -f "$dir/beat.json"; mv -f "$tmp" "$dir/beat.json"; } || rm -f "$tmp"
|
|
40
|
+
exit 0
|
package/deploy/clavarium-host
CHANGED
|
@@ -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"
|
|
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)
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
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 ${
|
|
1233
|
-
|
|
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
|
package/deploy/updater.mjs
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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.
|
|
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)) {
|
|
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
|
-
|
|
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}`); }
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
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.
|
|
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
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/beat.mjs
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
/* THE HEARTBEAT OF A MACHINE (step 6, phase 1): its health looked at from inside it, read from here.
|
|
2
|
+
*
|
|
3
|
+
* Every two minutes, each conversation's health was one command into its machine (health.mjs, PROBE): one
|
|
4
|
+
* more line at the VM manager, in front of every other command. Now a timer in the machine (root's,
|
|
5
|
+
* config/machine/clavarium-beat) runs that same probe every minute, as the conversation's own user, and
|
|
6
|
+
* writes what it printed into its work folder, /work/.clavarium/beat.json. The work folder is a folder of
|
|
7
|
+
* THIS server: the beat is read here, as a file (read), with no command at all.
|
|
8
|
+
*
|
|
9
|
+
* WHAT IS IN IT IS THE AGENT'S: it is root in its machine and may write anything there. So the folder must
|
|
10
|
+
* be a folder (never a link), the file a plain file of a few kilobytes, opened without following a link and
|
|
11
|
+
* without waiting (a pipe put there); its words checked one by one; its conversation the one whose folder it
|
|
12
|
+
* is; its age taken from THIS server's clock (the file's time here), never from what it says; its number
|
|
13
|
+
* growing. Nothing in it is ever run: its probe text is read by readProbe, as the probe's output always was.
|
|
14
|
+
*
|
|
15
|
+
* Put in a machine once (ensure): one command at its start or opening, skipped when a fresh beat already
|
|
16
|
+
* says this version. Only with CLAVARIUM_BEAT holding `health` (main.mjs): off, nothing here is used.
|
|
17
|
+
*/
|
|
18
|
+
import { lstatSync, openSync, fstatSync, readSync, closeSync, constants, writeFileSync, renameSync, rmSync, mkdirSync, readFileSync } from 'node:fs';
|
|
19
|
+
import { join } from 'node:path';
|
|
20
|
+
import { randomBytes } from 'node:crypto';
|
|
21
|
+
import { PROBE } from './health.mjs';
|
|
22
|
+
|
|
23
|
+
export const FOLDER = '.clavarium';
|
|
24
|
+
export const BEAT_FILE = 'beat.json';
|
|
25
|
+
export const EXPECTED_FILE = 'expected';
|
|
26
|
+
/* At most this big: a probe of 64 secrets' names is a few kilobytes. */
|
|
27
|
+
export const BEAT_BYTES = 16 * 1024;
|
|
28
|
+
/* Older than this (by this server's clock), it says nothing: its timer beats every minute or so. */
|
|
29
|
+
export const FRESH_MS = 180_000;
|
|
30
|
+
/* A file's time a little ahead of this server's clock is still now (a share's rounding); more is not believed. */
|
|
31
|
+
const AHEAD_MS = 10_000;
|
|
32
|
+
/* Where it is put in the machine (root's, never under /tools or /work). */
|
|
33
|
+
export const LIB = '/usr/local/lib/clavarium';
|
|
34
|
+
export const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
35
|
+
const INSTALL_MS = 90_000;
|
|
36
|
+
const NAME = /^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$/;
|
|
37
|
+
const VERSION_WORD = /^[0-9A-Za-z.+-]{1,64}$/;
|
|
38
|
+
|
|
39
|
+
/* Whether CLAVARIUM_BEAT asks for it (`health`; other words for the later phases). */
|
|
40
|
+
export const beatWanted = (value, what = 'health') => String(value ?? '').split(/[\s,]+/).includes(what);
|
|
41
|
+
|
|
42
|
+
const RUNNER = new URL('../config/machine/clavarium-beat', import.meta.url);
|
|
43
|
+
const ONE = new URL('../config/machine/clavarium-beat-one', import.meta.url);
|
|
44
|
+
export const SERVICE = `[Unit]
|
|
45
|
+
Description=Clavarium heartbeat: its health, for its server
|
|
46
|
+
[Service]
|
|
47
|
+
Type=oneshot
|
|
48
|
+
ExecStart=/bin/sh ${LIB}/beat-all
|
|
49
|
+
TimeoutStartSec=300
|
|
50
|
+
Nice=10
|
|
51
|
+
`;
|
|
52
|
+
export const TIMER = `[Unit]
|
|
53
|
+
Description=Clavarium heartbeat, every minute
|
|
54
|
+
[Timer]
|
|
55
|
+
OnBootSec=20s
|
|
56
|
+
OnUnitActiveSec=60s
|
|
57
|
+
RandomizedDelaySec=10s
|
|
58
|
+
AccuracySec=5s
|
|
59
|
+
[Install]
|
|
60
|
+
WantedBy=timers.target
|
|
61
|
+
`;
|
|
62
|
+
|
|
63
|
+
/* THE ONE COMMAND THAT PUTS IT IN A MACHINE, as root: its scripts and the probe in LIB, its settings, its
|
|
64
|
+
service and timer, started. Its arguments (mode, conversation, version) are checked again there. Each file
|
|
65
|
+
is written aside, then moved: a beat that runs meanwhile finds the old or the new, never half of one. */
|
|
66
|
+
const EOF = 'CLAVARIUM_BEAT_EOF';
|
|
67
|
+
function here(text) {
|
|
68
|
+
if (String(text).split('\n').includes(EOF)) throw new Error('a file of the beat holds its own end mark');
|
|
69
|
+
return `<<'${EOF}'\n${String(text).replace(/\n?$/, '\n')}${EOF}\n`;
|
|
70
|
+
}
|
|
71
|
+
export function installScript() {
|
|
72
|
+
return [
|
|
73
|
+
'set -eu',
|
|
74
|
+
'mode="$1"; name="$2"; version="$3"',
|
|
75
|
+
'case "$mode" in own) printf \'%s\' "$name" | grep -Eq \'^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$\' || exit 64 ;; shared) name=- ;; *) exit 64 ;; esac',
|
|
76
|
+
'printf \'%s\' "$version" | grep -Eq \'^[0-9A-Za-z.+-]{1,64}$\' || exit 64',
|
|
77
|
+
`lib=${LIB}`,
|
|
78
|
+
'mkdir -p "$lib"; chown root:root "$lib"; chmod 755 "$lib"',
|
|
79
|
+
'put() { tmp="$lib/.$1.$$"; cat > "$tmp"; chmod "$2" "$tmp"; mv -f "$tmp" "$lib/$1"; }',
|
|
80
|
+
`put probe.sh 0644 ${here(PROBE)}`,
|
|
81
|
+
`put beat-one 0755 ${here(readFileSync(ONE, 'utf8'))}`,
|
|
82
|
+
`put beat-all 0755 ${here(readFileSync(RUNNER, 'utf8'))}`,
|
|
83
|
+
'printf \'mode=%s\\nconversation=%s\\nversion=%s\\n\' "$mode" "$name" "$version" | put beat.conf 0644',
|
|
84
|
+
`cat > /etc/systemd/system/clavarium-beat.service ${here(SERVICE)}`,
|
|
85
|
+
`cat > /etc/systemd/system/clavarium-beat.timer ${here(TIMER)}`,
|
|
86
|
+
'systemctl daemon-reload',
|
|
87
|
+
'systemctl enable --now clavarium-beat.timer >/dev/null 2>&1',
|
|
88
|
+
'systemctl start --no-block clavarium-beat.service',
|
|
89
|
+
].join('\n');
|
|
90
|
+
}
|
|
91
|
+
export const INSTALL_NAME = 'clavarium-beat-install';
|
|
92
|
+
|
|
93
|
+
export class Beat {
|
|
94
|
+
#vms; #workFolder; #conversations; #now; #version; #seq = new Map(); #expected = new Map(); #tried = new Map(); #installing = new Map();
|
|
95
|
+
/* `on`: CLAVARIUM_BEAT holds `health`. `workFolder(name)`: its work folder on this server.
|
|
96
|
+
`conversations`: get(name) -- whether its work is kept here. */
|
|
97
|
+
constructor({ on = false, vms, workFolder, conversations, now = () => Date.now(), version = VERSION }) {
|
|
98
|
+
this.on = Boolean(on); this.#vms = vms; this.#workFolder = workFolder; this.#conversations = conversations; this.#now = now; this.#version = version;
|
|
99
|
+
}
|
|
100
|
+
get version() { return this.#version; }
|
|
101
|
+
|
|
102
|
+
#dir(name) { if (!NAME.test(String(name))) throw new Error('not a conversation name'); return join(this.#workFolder(name), FOLDER); }
|
|
103
|
+
/* Its folder, a folder of its own (never a link), or null; made when `make` and missing. */
|
|
104
|
+
#folder(name, make = false) {
|
|
105
|
+
let dir;
|
|
106
|
+
try { dir = this.#dir(name); } catch { return null; }
|
|
107
|
+
let s = lstatSync(dir, { throwIfNoEntry: false });
|
|
108
|
+
if (!s && make) { try { mkdirSync(dir, { mode: 0o755 }); } catch { return null; } s = lstatSync(dir, { throwIfNoEntry: false }); }
|
|
109
|
+
return s && s.isDirectory() && !s.isSymbolicLink() ? dir : null;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/* WHAT SHOULD BE MOUNTED, for the beat to look at (resources.expected): written when it changed. */
|
|
113
|
+
expect(name, paths) {
|
|
114
|
+
if (!this.on) return false;
|
|
115
|
+
const text = `${paths.filter((p) => /^\/[A-Za-z0-9._/-]{1,200}$/.test(p)).slice(0, 100).join('\n')}\n`;
|
|
116
|
+
try {
|
|
117
|
+
const dir = this.#folder(name, true);
|
|
118
|
+
if (!dir) return false;
|
|
119
|
+
const at = join(dir, EXPECTED_FILE);
|
|
120
|
+
const s = lstatSync(at, { throwIfNoEntry: false });
|
|
121
|
+
if (this.#expected.get(name) === text && s?.isFile()) return true;
|
|
122
|
+
/* Aside, then moved: a link put at its place is replaced, never followed. */
|
|
123
|
+
const tmp = join(dir, `.expected.${randomBytes(6).toString('hex')}`);
|
|
124
|
+
try { writeFileSync(tmp, text, { flag: 'wx', mode: 0o644 }); renameSync(tmp, at); } catch (error) { rmSync(tmp, { force: true }); throw error; }
|
|
125
|
+
this.#expected.set(name, text);
|
|
126
|
+
return true;
|
|
127
|
+
} catch { return false; }
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/* ITS LAST BEAT: { ok: true, text, version, seq, at } or { ok: false, why }. `peek`: its number not
|
|
131
|
+
taken as seen (the install's look). */
|
|
132
|
+
read(name, { peek = false } = {}) {
|
|
133
|
+
const dir = this.#folder(name);
|
|
134
|
+
if (!dir) return { ok: false, why: 'none' };
|
|
135
|
+
let fd;
|
|
136
|
+
try { fd = openSync(join(dir, BEAT_FILE), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); } catch (error) { return { ok: false, why: error.code === 'ENOENT' ? 'none' : 'unreadable' }; }
|
|
137
|
+
let s; let text;
|
|
138
|
+
try {
|
|
139
|
+
s = fstatSync(fd);
|
|
140
|
+
if (!s.isFile()) return { ok: false, why: 'not a file' };
|
|
141
|
+
if (s.size > BEAT_BYTES) return { ok: false, why: 'too big' };
|
|
142
|
+
const buf = Buffer.alloc(BEAT_BYTES + 1);
|
|
143
|
+
let n = 0;
|
|
144
|
+
for (let got = 1; got > 0 && n <= BEAT_BYTES; n += got) got = readSync(fd, buf, n, BEAT_BYTES + 1 - n, null);
|
|
145
|
+
if (n > BEAT_BYTES) return { ok: false, why: 'too big' };
|
|
146
|
+
text = buf.toString('utf8', 0, n);
|
|
147
|
+
} catch { return { ok: false, why: 'unreadable' }; } finally { closeSync(fd); }
|
|
148
|
+
const age = this.#now() - s.mtimeMs;
|
|
149
|
+
if (age > FRESH_MS) return { ok: false, why: 'stale' };
|
|
150
|
+
if (age < -AHEAD_MS) return { ok: false, why: 'ahead' };
|
|
151
|
+
let j;
|
|
152
|
+
try { j = JSON.parse(text); } catch { return { ok: false, why: 'not json' }; }
|
|
153
|
+
if (!j || typeof j !== 'object' || j.v !== 1) return { ok: false, why: 'not a beat' };
|
|
154
|
+
if (j.conversation !== name) return { ok: false, why: 'another conversation' };
|
|
155
|
+
if (!Number.isSafeInteger(j.seq) || j.seq < 1) return { ok: false, why: 'no number' };
|
|
156
|
+
if (typeof j.version !== 'string' || !VERSION_WORD.test(j.version)) return { ok: false, why: 'no version' };
|
|
157
|
+
if (typeof j.probe !== 'string') return { ok: false, why: 'no probe' };
|
|
158
|
+
/* ITS NUMBER GROWS: the same beat read again (same number, same time) is still it; a smaller one, or
|
|
159
|
+
the same number written again, is not believed -- and the next one is taken as a new start. */
|
|
160
|
+
const last = this.#seq.get(name);
|
|
161
|
+
if (last && !(j.seq > last.seq || (j.seq === last.seq && s.mtimeMs === last.at))) { if (!peek) this.#seq.delete(name); return { ok: false, why: 'number' }; }
|
|
162
|
+
if (!peek) this.#seq.set(name, { seq: j.seq, at: s.mtimeMs });
|
|
163
|
+
return { ok: true, text: j.probe, version: j.version, seq: j.seq, at: s.mtimeMs };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/* PUT IN ITS MACHINE, once: one command, as root. Skipped when its beat is fresh and says this version,
|
|
167
|
+
or when it was tried already for this version (`woke`: its machine has just started -- what was tried
|
|
168
|
+
is forgotten: a fresh beat may still be from before its start, and once it is stale the next call puts
|
|
169
|
+
it again). Never more than
|
|
170
|
+
one at a time per conversation. Resolves with what was done: 'off', 'fresh', 'tried', 'put', 'failed'. */
|
|
171
|
+
ensure(name, { woke = false } = {}) {
|
|
172
|
+
if (!this.on || this.#conversations?.get(name)?.work !== 'kept') return Promise.resolve('off');
|
|
173
|
+
if (woke) this.#tried.delete(name);
|
|
174
|
+
const going = this.#installing.get(name);
|
|
175
|
+
if (going) return going;
|
|
176
|
+
const beat = this.read(name, { peek: true });
|
|
177
|
+
if (beat.ok && beat.version === this.#version) return Promise.resolve('fresh');
|
|
178
|
+
if (this.#tried.get(name) === this.#version) return Promise.resolve('tried');
|
|
179
|
+
this.#tried.set(name, this.#version);
|
|
180
|
+
const mode = this.#vms.shared?.(name) ? 'shared' : 'own';
|
|
181
|
+
const run = this.#vms.execMachine(name, ['sudo', '-n', 'sh', '-c', installScript(), INSTALL_NAME, mode, mode === 'own' ? name : '-', this.#version], { timeoutMs: INSTALL_MS })
|
|
182
|
+
.then((r) => (r.code === 0 ? 'put' : 'failed'), () => 'failed')
|
|
183
|
+
.finally(() => this.#installing.delete(name));
|
|
184
|
+
this.#installing.set(name, run);
|
|
185
|
+
return run;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
forget(name) { this.#seq.delete(name); this.#expected.delete(name); this.#tried.delete(name); }
|
|
189
|
+
}
|
package/server/copywork.mjs
CHANGED
|
@@ -3,12 +3,13 @@
|
|
|
3
3
|
* what belongs to the original alone:
|
|
4
4
|
* .docket its reminders and what woke it: they would fire twice;
|
|
5
5
|
* .tether, .binder its asks to the keepers and their answers, being answered: the copy asks its own;
|
|
6
|
-
* .parley's live files its pulse, its voice boxes, its restart asked, its program (put again by the server)
|
|
6
|
+
* .parley's live files its pulse, its voice boxes, its restart asked, its program (put again by the server);
|
|
7
|
+
* .clavarium its machine's heartbeat and what it looks at (beat.mjs): the copy's machine beats its own.
|
|
7
8
|
* Only plain files, folders and links: anything else (a socket, a pipe) is no work. Its copy keeps their times. */
|
|
8
9
|
import { cp, lstat } from 'node:fs/promises';
|
|
9
10
|
import { relative, sep } from 'node:path';
|
|
10
11
|
|
|
11
|
-
export const NOT_COPIED = Object.freeze(['.docket', '.tether', '.binder', '.clavarium-carry', '.parley/pulse.json', '.parley/speakers.json', '.parley/restart-asked', '.parley/server.mjs']);
|
|
12
|
+
export const NOT_COPIED = Object.freeze(['.docket', '.tether', '.binder', '.clavarium', '.clavarium-carry', '.parley/pulse.json', '.parley/speakers.json', '.parley/restart-asked', '.parley/server.mjs']);
|
|
12
13
|
|
|
13
14
|
/* Whether a path of the work folder (relative, '' for the folder itself) is copied. */
|
|
14
15
|
export function copied(path) {
|
package/server/health.mjs
CHANGED
|
@@ -78,6 +78,9 @@ export const PROBE = [
|
|
|
78
78
|
export const PROBE_NAME = 'clavarium-health';
|
|
79
79
|
|
|
80
80
|
export const EVERY_MS = 120_000;
|
|
81
|
+
/* WITH A HEARTBEAT (beat.mjs), a look by command still, this often, whatever the beat says: what the agent
|
|
82
|
+
wrote in its /work is believed only between two looks of our own. */
|
|
83
|
+
export const SPOT_MS = 30 * 60_000;
|
|
81
84
|
/* The looks of one tick start this far apart, one machine after another (at most a tick shared out
|
|
82
85
|
between them): a burst of probes lines up at the VM manager in front of every other command. */
|
|
83
86
|
export const STAGGER_MS = 5_000;
|
|
@@ -180,7 +183,7 @@ export function judge(record) {
|
|
|
180
183
|
}
|
|
181
184
|
|
|
182
185
|
export class Health {
|
|
183
|
-
#vms; #conversations; #resources; #records = new Map(); #running = new Map(); #quiet = new Map(); #settleMs; #probeMs; #lookMs; #seen; #links;
|
|
186
|
+
#vms; #conversations; #resources; #records = new Map(); #running = new Map(); #quiet = new Map(); #settleMs; #probeMs; #lookMs; #seen; #links; #beat; #now; #execAt = new Map();
|
|
184
187
|
/* Set by the server: told each judgment (the chat of a conversation says what is wrong: talk.mjs). */
|
|
185
188
|
judged = () => {};
|
|
186
189
|
/* Set by the server: told a conversation is forgotten (what else is kept of its machine goes too). */
|
|
@@ -194,8 +197,9 @@ export class Health {
|
|
|
194
197
|
`lookMs`: how long the clock waits for one conversation's look. */
|
|
195
198
|
/* `seen`: a store of the problems its owner marked seen ("Seen"), by conversation. */
|
|
196
199
|
/* `links`: the guard of links its folders cannot serve (linkguard.mjs), or null. */
|
|
197
|
-
|
|
198
|
-
|
|
200
|
+
/* `beat`: the heartbeats read from the work folders (beat.mjs), or null: every look by command. */
|
|
201
|
+
constructor({ vms, conversations, resources, settleMs = 5000, probeMs = PROBE_MS, lookMs = LOOK_MS, seen = null, links = null, beat = null, now = () => Date.now() }) {
|
|
202
|
+
this.#seen = seen; this.#links = links; this.#beat = beat; this.#now = now;
|
|
199
203
|
this.#vms = vms; this.#conversations = conversations; this.#resources = resources; this.#settleMs = settleMs; this.#probeMs = probeMs; this.#lookMs = lookMs;
|
|
200
204
|
}
|
|
201
205
|
|
|
@@ -209,7 +213,7 @@ export class Health {
|
|
|
209
213
|
this.#seen?.put({ name, keys, at: new Date().toISOString() });
|
|
210
214
|
return this.of(name);
|
|
211
215
|
}
|
|
212
|
-
forget(name) { this.#records.delete(name); this.#quiet.delete(name); this.#seen?.remove?.(name); try { this.forgotten(name); } catch { /* told */ } }
|
|
216
|
+
forget(name) { this.#records.delete(name); this.#quiet.delete(name); this.#execAt.delete(name); this.#beat?.forget?.(name); this.#seen?.remove?.(name); try { this.forgotten(name); } catch { /* told */ } }
|
|
213
217
|
|
|
214
218
|
/* The look under way (it may be mounting a folder again), or null. */
|
|
215
219
|
busy(name) { return this.#running.get(name) ?? null; }
|
|
@@ -238,11 +242,20 @@ export class Health {
|
|
|
238
242
|
the VM manager for seconds, and every other machine waits behind it (21-10). */
|
|
239
243
|
const quiet = this.#quiet.get(name);
|
|
240
244
|
if (quiet && !asked && Date.now() < quiet.until) return this.#keep(name, { at, state, answering: false });
|
|
241
|
-
|
|
245
|
+
/* Its heartbeat, when it says enough (#fromBeat): no command. Else the look by command, as always. */
|
|
246
|
+
const beating = Boolean(this.#beat?.on) && c.work === 'kept';
|
|
247
|
+
let facts = beating ? this.#fromBeat(name, paths, asked) : undefined;
|
|
248
|
+
if (beating) this.#vms.noteBeat?.(Boolean(facts));
|
|
242
249
|
if (!facts) {
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
250
|
+
facts = await this.#probe(name, paths);
|
|
251
|
+
if (!facts) {
|
|
252
|
+
const times = (quiet?.times ?? 0) + 1;
|
|
253
|
+
this.#quiet.set(name, { times, until: Date.now() + Math.min(QUIET_MAX_MS, QUIET_MS * 2 ** (times - 1)) });
|
|
254
|
+
return this.#keep(name, { at, state, answering: false });
|
|
255
|
+
}
|
|
256
|
+
this.#execAt.set(name, this.#now());
|
|
257
|
+
/* Its beat put in its machine when it is not there or not of this version (bounded: beat.mjs, ensure). */
|
|
258
|
+
if (beating) void Promise.resolve().then(() => this.#beat.ensure?.(name)).catch(() => {});
|
|
246
259
|
}
|
|
247
260
|
this.#quiet.delete(name);
|
|
248
261
|
try { void Promise.resolve(this.probed(name, facts)).catch(() => {}); } catch { /* told, nothing more */ }
|
|
@@ -314,6 +327,24 @@ export class Health {
|
|
|
314
327
|
return { at: record.at, items, health: this.of(name) };
|
|
315
328
|
}
|
|
316
329
|
|
|
330
|
+
/* ITS HEARTBEAT AS THE PROBE'S ANSWER (beat.mjs), or undefined -- then the look is a command, as before:
|
|
331
|
+
a look asked (its owner, a start, a wake), the first look of a machine or one just back (not seen
|
|
332
|
+
running and answering at the last look), a spot check every SPOT_MS, a beat not newer than our own last
|
|
333
|
+
look, not fresh or not what it should be, or one that does not say each path that should be mounted. */
|
|
334
|
+
#fromBeat(name, paths, asked) {
|
|
335
|
+
this.#beat.expect?.(name, paths);
|
|
336
|
+
if (asked) return undefined;
|
|
337
|
+
const last = this.#records.get(name);
|
|
338
|
+
if (last?.state !== 'Running' || last.answering !== true) return undefined;
|
|
339
|
+
const ours = this.#execAt.get(name);
|
|
340
|
+
if (ours === undefined || this.#now() - ours >= SPOT_MS) return undefined;
|
|
341
|
+
const beat = this.#beat.read(name);
|
|
342
|
+
if (!beat.ok || !(beat.at > ours)) return undefined;
|
|
343
|
+
const facts = readProbe(beat.text, paths);
|
|
344
|
+
if (!facts.memory || paths.some((p) => facts.mounts[p] === undefined)) return undefined;
|
|
345
|
+
return facts;
|
|
346
|
+
}
|
|
347
|
+
|
|
317
348
|
async #probe(name, paths) {
|
|
318
349
|
/* Its output is the agent's: not more than a few pages of it are even taken in. */
|
|
319
350
|
const r = await this.#vms.exec(name, ['sh', '-c', PROBE, PROBE_NAME, ...paths], { timeoutMs: this.#probeMs, maxBytes: PROBE_BYTES * 4 }).catch(() => ({ code: 1, stdout: '' }));
|
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';
|
|
@@ -99,6 +99,7 @@ import { RelayJoin, handleRelayJoin, RELAY_JOIN_PATH } from './relayjoin.mjs';
|
|
|
99
99
|
import { WebSocketServer } from 'ws';
|
|
100
100
|
import { attachConsole } from './sshconsole.mjs';
|
|
101
101
|
import { copyWorkFolder } from './copywork.mjs';
|
|
102
|
+
import { Beat, beatWanted } from './beat.mjs';
|
|
102
103
|
import { accessesOf, relinkAccesses } from './carry.mjs';
|
|
103
104
|
import { Jobs, withUpdates } from './jobs.mjs';
|
|
104
105
|
|
|
@@ -332,11 +333,15 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
332
333
|
const originOk = makeOriginCheck(publicOrigin);
|
|
333
334
|
const instance = new Instance({ file: new JsonFile(`${dataDir}/instance.json`, {}), origin: publicOrigin, given: appName });
|
|
334
335
|
let repairTerminal = async () => { throw new Error('not ready'); };
|
|
335
|
-
|
|
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);
|
|
336
341
|
/* A conversation in a shared machine (#221) says which: the machine its VM operations reach. */
|
|
337
342
|
const jobs = new Jobs({ path: `${dataDir}/jobs.json` });
|
|
338
343
|
const conversationStore = new Store(`${dataDir}/conversations.json`, { onChange: (before, after) => jobs.seen(before, after) });
|
|
339
|
-
const vms = new Vms(
|
|
344
|
+
const vms = new Vms(hostRun, host, { tally: hostTally,
|
|
340
345
|
machineOf: (name) => { const m = conversationStore.get(name)?.sharedMachine; return typeof m === 'string' && m ? m : undefined; },
|
|
341
346
|
userOf: (name) => { const u = conversationStore.get(name)?.machineUser; return u && Number.isInteger(u.uid) && Number.isInteger(u.gid) ? u : undefined; },
|
|
342
347
|
});
|
|
@@ -442,7 +447,12 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
442
447
|
chat: (name) => Boolean(talk?.brief(name)), say: (name, line) => wakeups.say(name, line), reread: () => talk?.rereadCommand() ?? null });
|
|
443
448
|
/* Why Parley is not in a machine, said once in the log, not at each opening. */
|
|
444
449
|
const parleySaid = new Map();
|
|
450
|
+
/* ITS HEARTBEAT (beat.mjs): with CLAVARIUM_BEAT=health, its health read from its work folder instead of
|
|
451
|
+
a command every two minutes; put in its machine at an opening (once per version), never waited for. */
|
|
452
|
+
const beat = new Beat({ on: beatWanted(env.CLAVARIUM_BEAT, 'health'), vms, workFolder: (name) => folders.workFolder(name), conversations: all });
|
|
453
|
+
if (beat.on) console.log('beat: the health of the machines read from their heartbeat (CLAVARIUM_BEAT)');
|
|
445
454
|
all.prepare = async (name, woke) => {
|
|
455
|
+
void beat.ensure(name, { woke }).catch(() => {});
|
|
446
456
|
await hostReady;
|
|
447
457
|
secrets.check();
|
|
448
458
|
const wanted = secrets.signature(name);
|
|
@@ -689,7 +699,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
689
699
|
try { if (dockets.on(name)) { dockets.post(name, { kind: 'shared-folder', text: line, data: { folder: link.folder, path: link.path } }); return; } } catch { /* typed instead */ }
|
|
690
700
|
if (all.list().find((c) => c.name === name)?.ai === true) void wakeups.say(name, line).catch(() => {});
|
|
691
701
|
};
|
|
692
|
-
const health = new Health({ vms, conversations: all, resources: folders, links: linkGuard, seen: new Store(`${dataDir}/health-seen.json`), ...(healthSettleMs === undefined ? {} : { settleMs: healthSettleMs }) });
|
|
702
|
+
const health = new Health({ vms, conversations: all, resources: folders, links: linkGuard, beat, seen: new Store(`${dataDir}/health-seen.json`), ...(healthSettleMs === undefined ? {} : { settleMs: healthSettleMs }) });
|
|
693
703
|
const stopHealth = health.start(healthEveryMs, { quietMs: quietStartMs });
|
|
694
704
|
/* What is wrong with its machine is said in its chat too, where it happened. */
|
|
695
705
|
/* And what its owner chose that it does on top (healthreact.mjs): its agent told, or a command run. */
|
|
@@ -828,7 +838,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
828
838
|
/* All the machines to another disk, from Settings (machinesmove.mjs). */
|
|
829
839
|
const machinesMove = new MachinesMove({ host: asHost, usedMb: () => capacity.machinesUsedMb() });
|
|
830
840
|
/* What the server's programs said, and this server started again, from Settings (serverlogs.mjs). */
|
|
831
|
-
const serverLogs = new ServerLogs({ host: asHost });
|
|
841
|
+
const serverLogs = new ServerLogs({ host: asHost, load: () => hostTally.windows() });
|
|
832
842
|
/* This server's Wi-Fi, from Settings (wifi.mjs): how a switch ended, said in What happened. */
|
|
833
843
|
const wifi = new Wifi({ host: asHost, said: (text) => events.add({ kind: 'server', text }) });
|
|
834
844
|
/* The remote screen (MeshCentral), from Settings (meshcentral.mjs): how a turn-on ended, said in What happened. */
|
package/server/serverlogs.mjs
CHANGED
|
@@ -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)
|
|
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']);
|
package/server/settingswords.mjs
CHANGED
|
@@ -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',
|
package/server/updates.mjs
CHANGED
|
@@ -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
|
-
|
|
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,20 +178,9 @@ export class Vms {
|
|
|
122
178
|
};
|
|
123
179
|
}
|
|
124
180
|
|
|
125
|
-
/* HOW MUCH THIS SERVER ASKS OF THE HOST
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
#tally = new Map(); #tallyFrom = 0;
|
|
129
|
-
#count(argv, ms) {
|
|
130
|
-
const now = this.#now();
|
|
131
|
-
if (!this.#tallyFrom) this.#tallyFrom = now;
|
|
132
|
-
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)]);
|
|
133
|
-
if (now - this.#tallyFrom < COUNT_EVERY_MS) return;
|
|
134
|
-
const rows = [...this.#tally].sort((a, b) => b[1][1] - a[1][1]);
|
|
135
|
-
const all = rows.reduce((n, [, v]) => n + v[0], 0); const busy = rows.reduce((n, [, v]) => n + v[1], 0);
|
|
136
|
-
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('; ')}`);
|
|
137
|
-
this.#tally = new Map(); this.#tallyFrom = now;
|
|
138
|
-
}
|
|
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); }
|
|
139
184
|
|
|
140
185
|
/* EVERY MACHINE'S STATE, in one question to the VM manager, shared by every caller for a
|
|
141
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; }
|