clavarium 0.2.486-next.1 → 0.2.488-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/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/server/beat.mjs +189 -0
- package/server/conversations.mjs +3 -3
- package/server/copywork.mjs +3 -2
- package/server/gitkeeper.mjs +39 -7
- package/server/gitpush.mjs +5 -2
- package/server/health.mjs +65 -11
- package/server/main.mjs +61 -12
- package/server/network.mjs +8 -4
- package/server/secrets.mjs +17 -8
- package/server/vm.mjs +31 -19
|
@@ -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/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.488-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.488-next.1",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@xterm/addon-fit": "^0.11.0",
|
package/package.json
CHANGED
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/conversations.mjs
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
import { isConversationName, identifierFrom, titleProblem, groupProblem } from './names.mjs';
|
|
10
10
|
import { JsonFile } from './store.mjs';
|
|
11
11
|
import { attachCommand, SOCKET } from './tmux.mjs';
|
|
12
|
-
import { WORK, VM_USER, SHARING_STEP, stepLine, vmName } from './vm.mjs';
|
|
12
|
+
import { WORK, VM_USER, SHARING_STEP, stepLine, vmName, WAIT_FRESH_MS } from './vm.mjs';
|
|
13
13
|
import { resumeOrFresh } from './tools.mjs';
|
|
14
14
|
import { TOOLS_PATH, LAUNCH } from './toolbox.mjs';
|
|
15
15
|
import { homeExcludes, wholeStream, readManifest, workEmpty, unpackHere, restoreWork, CARRY } from './carry.mjs';
|
|
@@ -254,7 +254,7 @@ export class Conversations {
|
|
|
254
254
|
while (!done) {
|
|
255
255
|
await new Promise((r) => { setTimeout(r, this.#pollMs).unref?.(); });
|
|
256
256
|
if (done) return;
|
|
257
|
-
const state = await this.#vms.state(name).catch(() => undefined);
|
|
257
|
+
const state = await this.#vms.state(name, { within: WAIT_FRESH_MS }).catch(() => undefined);
|
|
258
258
|
if (done) return;
|
|
259
259
|
if (how === 'stop' && (state === 'Stopping' || state === 'Suspending')) this.#reach(name, 'stopping');
|
|
260
260
|
if (how === 'start' && state === 'Running') this.#reach(name, 'answering');
|
|
@@ -899,7 +899,7 @@ export class Conversations {
|
|
|
899
899
|
async #until(name, done, ms) {
|
|
900
900
|
const end = Date.now() + ms;
|
|
901
901
|
for (;;) {
|
|
902
|
-
const state = await this.#vms.state(name).catch(() => 'Unknown');
|
|
902
|
+
const state = await this.#vms.state(name, { within: WAIT_FRESH_MS }).catch(() => 'Unknown');
|
|
903
903
|
if (done(state) || Date.now() >= end) return state;
|
|
904
904
|
await new Promise((r) => setTimeout(r, this.#pollMs));
|
|
905
905
|
}
|
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/gitkeeper.mjs
CHANGED
|
@@ -65,6 +65,16 @@ import { GitFailure, waiversProblem } from './gitrunner.mjs';
|
|
|
65
65
|
import { SECONDS_MIN, SECONDS_MAX, COMMAND_MAX } from './gitchecks.mjs';
|
|
66
66
|
|
|
67
67
|
export const TICK_MS = 30_000;
|
|
68
|
+
/* Each repository's refresh comes up to this much after its period, the same for a
|
|
69
|
+
repository every time (from its name): fifteen repositories do not all reach their
|
|
70
|
+
remote, and then every machine, at the same tick. */
|
|
71
|
+
export const SPREAD_MS = 60_000;
|
|
72
|
+
export function spread(name, within = SPREAD_MS) {
|
|
73
|
+
if (!(within > 0)) return 0;
|
|
74
|
+
let h = 0;
|
|
75
|
+
for (const ch of String(name)) h = (h * 31 + ch.charCodeAt(0)) >>> 0;
|
|
76
|
+
return h % within;
|
|
77
|
+
}
|
|
68
78
|
/* A read waits this long after the last change of the marks. */
|
|
69
79
|
export const READ_DELAY_MS = 5_000;
|
|
70
80
|
/* And happens at least this often while a machine uses the repository. */
|
|
@@ -221,6 +231,13 @@ export const SENDING_KEEP_MS = 60_000;
|
|
|
221
231
|
|
|
222
232
|
export class GitKeeper {
|
|
223
233
|
#store; #review; #resources; #checks; #alerts; #now; #tellAgent; #thread; #last; #held = new Map(); #results = new Map(); #running = new Set(); #telling = new Map(); #inFlight = new Map(); #sending = new Map();
|
|
234
|
+
/* The reference's branches after its last refresh that worked (its `mark`), by repository; and,
|
|
235
|
+
by "conversation repository", the mark its machine was last fetched at (see #fetchInMachines). */
|
|
236
|
+
#marks = new Map(); #fetchedAt = new Map();
|
|
237
|
+
/* Set by start: no refresh before this (the keeper's clock), each repository a little after it (spread). */
|
|
238
|
+
#since = 0;
|
|
239
|
+
/* Set by start: how far the refreshes are spread (two ticks at most; none before a start). */
|
|
240
|
+
#spreadMs = 0;
|
|
224
241
|
|
|
225
242
|
/* `review`: GitReview (reads, the reference, Send). `checks`: GitChecks.
|
|
226
243
|
`alerts`: what tells the owner's phone. `tellAgent(repository, line,
|
|
@@ -444,6 +461,7 @@ export class GitKeeper {
|
|
|
444
461
|
const record = this.#record(name);
|
|
445
462
|
const failures = result.ok ? 0 : (record.refreshFailures ?? 0) + 1;
|
|
446
463
|
this.#patch(name, { mirror: { at, ok: result.ok, message: result.ok ? 'Up to date with the origin.' : result.message }, refreshFailures: failures });
|
|
464
|
+
if (result.ok && typeof result.mark === 'string') this.#marks.set(name, result.mark);
|
|
447
465
|
if (!result.ok && failures === 3) this.#tell(`${name}: the remote does not answer`, result.message);
|
|
448
466
|
if (result.stale?.length) this.#log(name, { ok: false, what: `A refresh was stopped by its time limit; stale lock files removed: ${result.stale.join(', ')}.` });
|
|
449
467
|
for (const w of result.rewritten ?? []) {
|
|
@@ -787,7 +805,7 @@ export class GitKeeper {
|
|
|
787
805
|
if (!await this.#inUse(r.name)) return;
|
|
788
806
|
/* The reference, when due; its upkeep once a day. */
|
|
789
807
|
const last = this.#record(r.name).mirror?.at;
|
|
790
|
-
if (s.refreshMinutes > 0 && (!last || now - new Date(last).getTime() >= s.refreshMinutes * 60_000)) {
|
|
808
|
+
if (s.refreshMinutes > 0 && now >= this.#since + spread(r.name, this.#spreadMs) && (!last || now - new Date(last).getTime() >= s.refreshMinutes * 60_000 + spread(r.name, this.#spreadMs))) {
|
|
791
809
|
await this.#review.refresh(r.name).catch(() => {});
|
|
792
810
|
await this.#fetchInMachines(r.name, s).catch(() => {});
|
|
793
811
|
const upkeep = this.#record(r.name).upkeepAt;
|
|
@@ -811,11 +829,19 @@ export class GitKeeper {
|
|
|
811
829
|
/* THE AGENTS' OWN COPIES, after each refresh of the reference: brought up to date in each machine
|
|
812
830
|
that runs with the repository attached for writing (gitchecks.mjs, fetchIn), origin/* only.
|
|
813
831
|
A branch it follows that moved is said to its agent, once per move, unless the owner turned
|
|
814
|
-
that line off (tellMoves).
|
|
832
|
+
that line off (tellMoves).
|
|
833
|
+
Only when there is something new for it: a machine already fetched at the reference's
|
|
834
|
+
current branches (its mark) is not asked again -- each fetch is a command to the host,
|
|
835
|
+
for every machine, every few minutes. Unknown (no refresh has worked since the server
|
|
836
|
+
started), or a machine that stopped since: fetched, as before. */
|
|
815
837
|
async #fetchInMachines(name, s) {
|
|
838
|
+
const mark = this.#marks.get(name);
|
|
816
839
|
for (const c of this.#writers(name)) {
|
|
817
|
-
|
|
840
|
+
const key = `${c} ${name}`;
|
|
841
|
+
if (!await this.#runs(c, name)) { this.#fetchedAt.delete(key); continue; }
|
|
842
|
+
if (mark !== undefined && this.#fetchedAt.get(key) === mark) continue;
|
|
818
843
|
const got = await this.#checks.fetchIn?.(c, name).catch(() => undefined);
|
|
844
|
+
if (got?.ok && mark !== undefined) this.#fetchedAt.set(key, mark); else this.#fetchedAt.delete(key);
|
|
819
845
|
if (!got?.ok || !s.tellMoves || got.moved.length === 0) continue;
|
|
820
846
|
const said = got.moved.slice(0, 3).map((m) => `${plain(m.upstream)} moved (${m.from.slice(0, 7)} -> ${m.to.slice(0, 7)}), your branch ${plain(m.branch)} follows it`).join('; ');
|
|
821
847
|
this.#toAgent(name, `${said}; fetched for you into origin/*, nothing of yours changed`, c);
|
|
@@ -833,7 +859,10 @@ export class GitKeeper {
|
|
|
833
859
|
return removed;
|
|
834
860
|
}
|
|
835
861
|
|
|
836
|
-
start(
|
|
862
|
+
/* `quietMs`: how long after a start of the server nothing is looked at (main.mjs, quietStartMs):
|
|
863
|
+
the machines starting again come first. The refreshes then come one repository after
|
|
864
|
+
another over SPREAD_MS, not all at the first tick. */
|
|
865
|
+
start(everyMs = TICK_MS, { quietMs = 0 } = {}) {
|
|
837
866
|
/* A read the server gave up on when it stopped is stopped on the host;
|
|
838
867
|
a fetch it killed may have left lock files in the reference, which
|
|
839
868
|
would refuse every later refresh. No git of ours runs there yet:
|
|
@@ -842,10 +871,13 @@ export class GitKeeper {
|
|
|
842
871
|
void this.#review.runner?.stopReads(r.name);
|
|
843
872
|
void this.#staleLocks(r.name).catch(() => {});
|
|
844
873
|
}
|
|
845
|
-
|
|
874
|
+
this.#since = this.#now().getTime() + quietMs;
|
|
875
|
+
this.#spreadMs = Math.min(SPREAD_MS, everyMs * 2);
|
|
876
|
+
const quietUntil = Date.now() + quietMs;
|
|
877
|
+
const timer = setInterval(() => { if (Date.now() >= quietUntil) void this.tick(); }, everyMs);
|
|
846
878
|
timer.unref?.();
|
|
847
|
-
/* Looked at soon after a start, not a whole period later. */
|
|
848
|
-
setTimeout(() => { void this.tick(); }, Math.min(everyMs, 5000)).unref?.();
|
|
879
|
+
/* Looked at soon after a start (once it is quiet no more), not a whole period later. */
|
|
880
|
+
setTimeout(() => { void this.tick(); }, Math.max(quietMs, Math.min(everyMs, 5000))).unref?.();
|
|
849
881
|
return timer;
|
|
850
882
|
}
|
|
851
883
|
}
|
package/server/gitpush.mjs
CHANGED
|
@@ -207,7 +207,7 @@ export class GitReview {
|
|
|
207
207
|
|
|
208
208
|
/* Fetches the remote's branches into the reference, making it the first
|
|
209
209
|
time. Under the reference's lock. Resolves { ok, message, rewritten,
|
|
210
|
-
made, brought }; `rewritten`: branches whose tip before is not an
|
|
210
|
+
made, brought, mark }; `rewritten`: branches whose tip before is not an
|
|
211
211
|
ancestor of their tip now, or that are gone; `brought`: branches that
|
|
212
212
|
came with commits the reference did not have, { branch, commits }.
|
|
213
213
|
The only writer of the reference. */
|
|
@@ -289,7 +289,10 @@ export class GitReview {
|
|
|
289
289
|
await this.#learnDefault(r, remote).catch(() => {});
|
|
290
290
|
/* When the reference was last brought up to date: the list shown at once says "as of" it. */
|
|
291
291
|
this.#store.put({ ...this.#record(r.name), name: r.name, fetchedAt: this.#now().toISOString() });
|
|
292
|
-
|
|
292
|
+
/* `mark`: the reference's branches as they are now, so that a caller can tell a
|
|
293
|
+
refresh that changed nothing (gitkeeper.mjs: no fetch into the machines then). */
|
|
294
|
+
const mark = [...after].map(([b, id]) => `${b} ${id}`).sort().join('\n');
|
|
295
|
+
return said({ ok: true, message: 'Up to date with the remote.', rewritten, made, brought, mark });
|
|
293
296
|
}
|
|
294
297
|
|
|
295
298
|
/* Is `tip` of the agent's branch `b` something the remote lacks? Not
|
package/server/health.mjs
CHANGED
|
@@ -27,6 +27,7 @@ import { SHARING_STEP } from './vm.mjs';
|
|
|
27
27
|
import { WHY } from './linkguard.mjs';
|
|
28
28
|
import { SOCKET } from './tmux.mjs';
|
|
29
29
|
import { SESSION } from './conversations.mjs';
|
|
30
|
+
import { SECRETS_DIR } from './secrets.mjs';
|
|
30
31
|
|
|
31
32
|
/* A FILE OUTSIDE /work where its tool may ask to be restarted when /work itself is dead (16-11): the
|
|
32
33
|
one in its chat's folder (talk.mjs, RESTART_ASKED) cannot be written then. Read by the probe. */
|
|
@@ -42,6 +43,8 @@ export const STUCK_MOUNT = /already mounted|terminate SSHFS mount process/i;
|
|
|
42
43
|
|
|
43
44
|
/* How long installing the shared-folder helper in a machine may take (it comes from the snap store). */
|
|
44
45
|
export const SHARING_MS = 180_000;
|
|
46
|
+
/* At most this many names of its secrets are listed by the probe (their number always is). */
|
|
47
|
+
export const SECRETS_LISTED = 64;
|
|
45
48
|
export const PROBE = [
|
|
46
49
|
'awk \'/^MemTotal:/{t=$2} /^MemAvailable:/{a=$2} END{print "memory", t+0, a+0}\' /proc/meminfo',
|
|
47
50
|
'awk \'$1=="oom_kill"{n=$2} END{print "oom", n+0}\' /proc/vmstat',
|
|
@@ -67,10 +70,20 @@ export const PROBE = [
|
|
|
67
70
|
`for p in $(pgrep -f '${TOOLS_HOST_PATTERN}' 2>/dev/null); do [ -d "/proc/$p/cwd/." ] || { echo "stale $p"; break; }; done`,
|
|
68
71
|
`tmux -L ${SOCKET} capture-pane -p -t '=${SESSION}:' 2>/dev/null | grep -c -i -E '${LOOSE_WORDS}' | awk '{print "screen", $1+0}'`,
|
|
69
72
|
`if [ -f ${RESTART_OUTSIDE} ]; then echo "restart asked"; fi`,
|
|
73
|
+
/* THE NAMES IN ITS /run/secrets, for the secrets' guard (main.mjs, secrets.mjs reconcile): read
|
|
74
|
+
here, in the look made anyway, not by a command of their own. How many, then the first of them. */
|
|
75
|
+
`echo "secrets $(ls -1 ${SECRETS_DIR} 2>/dev/null | wc -l)"`,
|
|
76
|
+
`ls -1 ${SECRETS_DIR} 2>/dev/null | head -n ${SECRETS_LISTED} | sed 's/^/secret /'`,
|
|
70
77
|
].join('\n');
|
|
71
78
|
export const PROBE_NAME = 'clavarium-health';
|
|
72
79
|
|
|
73
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;
|
|
84
|
+
/* The looks of one tick start this far apart, one machine after another (at most a tick shared out
|
|
85
|
+
between them): a burst of probes lines up at the VM manager in front of every other command. */
|
|
86
|
+
export const STAGGER_MS = 5_000;
|
|
74
87
|
const PROBE_MS = 15_000;
|
|
75
88
|
/* What the clock waits for one conversation's look before it goes on. */
|
|
76
89
|
const LOOK_MS = 60_000;
|
|
@@ -105,6 +118,10 @@ export function readProbe(text, paths = []) {
|
|
|
105
118
|
if (parts[0] === 'stale' && parts.length === 2 && a !== undefined) facts.stale = true;
|
|
106
119
|
if (parts[0] === 'screen' && parts.length === 2 && a !== undefined) facts.screenLoose = a;
|
|
107
120
|
if (line.trim() === 'restart asked') facts.restartAsked = true;
|
|
121
|
+
/* A name that is not a plain one (the agent may put anything there) is kept as '?': it
|
|
122
|
+
matches nothing that is given, so the guard writes the folder again, as it would have. */
|
|
123
|
+
if (parts[0] === 'secrets' && parts.length === 2 && a !== undefined) facts.secrets = { count: a, names: [] };
|
|
124
|
+
if (parts[0] === 'secret' && facts.secrets && facts.secrets.names.length < SECRETS_LISTED) facts.secrets.names.push(parts.length === 2 && /^[A-Za-z0-9_.-]{1,64}$/.test(parts[1]) ? parts[1] : '?');
|
|
108
125
|
}
|
|
109
126
|
return facts;
|
|
110
127
|
}
|
|
@@ -166,19 +183,23 @@ export function judge(record) {
|
|
|
166
183
|
}
|
|
167
184
|
|
|
168
185
|
export class Health {
|
|
169
|
-
#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();
|
|
170
187
|
/* Set by the server: told each judgment (the chat of a conversation says what is wrong: talk.mjs). */
|
|
171
188
|
judged = () => {};
|
|
172
189
|
/* Set by the server: told a conversation is forgotten (what else is kept of its machine goes too). */
|
|
173
190
|
forgotten = () => {};
|
|
191
|
+
/* Set by the server: told what a probe that answered found (`facts`: readProbe's), not waited for.
|
|
192
|
+
The secrets' guard reads its names of /run/secrets there (main.mjs). */
|
|
193
|
+
probed = () => {};
|
|
174
194
|
|
|
175
195
|
/* `settleMs`: how long a missing folder is given before it is mounted
|
|
176
196
|
again (a machine that has just started may still be mounting it).
|
|
177
197
|
`lookMs`: how long the clock waits for one conversation's look. */
|
|
178
198
|
/* `seen`: a store of the problems its owner marked seen ("Seen"), by conversation. */
|
|
179
199
|
/* `links`: the guard of links its folders cannot serve (linkguard.mjs), or null. */
|
|
180
|
-
|
|
181
|
-
|
|
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;
|
|
182
203
|
this.#vms = vms; this.#conversations = conversations; this.#resources = resources; this.#settleMs = settleMs; this.#probeMs = probeMs; this.#lookMs = lookMs;
|
|
183
204
|
}
|
|
184
205
|
|
|
@@ -192,7 +213,7 @@ export class Health {
|
|
|
192
213
|
this.#seen?.put({ name, keys, at: new Date().toISOString() });
|
|
193
214
|
return this.of(name);
|
|
194
215
|
}
|
|
195
|
-
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 */ } }
|
|
196
217
|
|
|
197
218
|
/* The look under way (it may be mounting a folder again), or null. */
|
|
198
219
|
busy(name) { return this.#running.get(name) ?? null; }
|
|
@@ -221,13 +242,23 @@ export class Health {
|
|
|
221
242
|
the VM manager for seconds, and every other machine waits behind it (21-10). */
|
|
222
243
|
const quiet = this.#quiet.get(name);
|
|
223
244
|
if (quiet && !asked && Date.now() < quiet.until) return this.#keep(name, { at, state, answering: false });
|
|
224
|
-
|
|
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));
|
|
225
249
|
if (!facts) {
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
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(() => {});
|
|
229
259
|
}
|
|
230
260
|
this.#quiet.delete(name);
|
|
261
|
+
try { void Promise.resolve(this.probed(name, facts)).catch(() => {}); } catch { /* told, nothing more */ }
|
|
231
262
|
const loose = () => paths.filter((p) => facts.mounts[p] !== 'ok');
|
|
232
263
|
const remounted = []; const failed = [];
|
|
233
264
|
if (loose().length > 0 && repair && this.#resources) {
|
|
@@ -296,6 +327,24 @@ export class Health {
|
|
|
296
327
|
return { at: record.at, items, health: this.of(name) };
|
|
297
328
|
}
|
|
298
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
|
+
|
|
299
348
|
async #probe(name, paths) {
|
|
300
349
|
/* Its output is the agent's: not more than a few pages of it are even taken in. */
|
|
301
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: '' }));
|
|
@@ -316,18 +365,23 @@ export class Health {
|
|
|
316
365
|
|
|
317
366
|
/* Every so often, each conversation whose machine should run. A machine
|
|
318
367
|
that does not run is not touched (its state alone is asked). */
|
|
319
|
-
start(
|
|
368
|
+
/* `quietMs`: no look by the clock that soon after a start of the server (main.mjs, quietStartMs). */
|
|
369
|
+
start(everyMs = EVERY_MS, { quietMs = 0 } = {}) {
|
|
320
370
|
if (!everyMs) return () => {};
|
|
321
371
|
let going = false;
|
|
372
|
+
const quietUntil = Date.now() + quietMs;
|
|
322
373
|
const timer = setInterval(async () => {
|
|
323
|
-
if (going) return;
|
|
374
|
+
if (going || Date.now() < quietUntil) return;
|
|
324
375
|
going = true;
|
|
325
376
|
/* All at once, each within its own time: one machine slow to
|
|
326
377
|
answer (or a mount that hangs) does not hold up the others.
|
|
327
378
|
A look still going when its time is up goes on; the next tick
|
|
328
379
|
joins it rather than starting another (check). */
|
|
329
380
|
try {
|
|
330
|
-
|
|
381
|
+
const names = this.#conversations.awake();
|
|
382
|
+
const apart = Math.min(STAGGER_MS, Math.floor(everyMs / Math.max(1, names.length)));
|
|
383
|
+
await Promise.all(names.map(async (name, i) => {
|
|
384
|
+
if (i > 0 && apart > 0) await new Promise((resolve) => { setTimeout(resolve, i * apart).unref?.(); });
|
|
331
385
|
let timer;
|
|
332
386
|
const bound = new Promise((resolve) => { timer = setTimeout(resolve, this.#lookMs); timer.unref?.(); });
|
|
333
387
|
return Promise.race([this.check(name).catch(() => {}), bound]).finally(() => clearTimeout(timer));
|
package/server/main.mjs
CHANGED
|
@@ -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
|
|
|
@@ -309,11 +310,20 @@ export function start({ port, command, cwd, env = process.env }) {
|
|
|
309
310
|
const MAIL_EVERY_MS = 120_000;
|
|
310
311
|
/* An opening waits this long at most for Parley to be installed in its machine (toolbox.mjs). */
|
|
311
312
|
const PARLEY_WAIT_MS = 20_000;
|
|
313
|
+
/* A QUIET START (17-11): after the server starts, its background work on the machines (the
|
|
314
|
+
references' refreshes and the fetches into the machines, the health looks with the secrets'
|
|
315
|
+
names, the network watch, every machine's terminal opened beforehand) waits this long, then
|
|
316
|
+
comes one machine after another: the machines starting again, and the owner's first pages,
|
|
317
|
+
come first. What a page asks is never held. The server run as a service passes it; a test
|
|
318
|
+
or a bench that calls startHome itself gets none (quietStartMs: 0). */
|
|
319
|
+
export const QUIET_START_MS = 150_000;
|
|
320
|
+
/* Between two machines of that first round. */
|
|
321
|
+
const QUIET_STEP_MS = 5_000;
|
|
312
322
|
|
|
313
323
|
/* The product: conversations are VMs. `host` is how the host program is
|
|
314
324
|
reached on this installation, as an argument vector: it is the ONLY thing
|
|
315
325
|
this server runs with more rights than its own. */
|
|
316
|
-
export async function startHome({ port, host, dataDir, mntDir = dataDir, gitReserveBytes, env = process.env, conversations, resources, operators = [], publicOrigin, vaultKey, tools = loadTools(), stopDelayMs, mailReader, gitLocalRemotes = false, gitSsh, answerFetcher, answerEveryMs, wakeEveryMs, alertSend, talkEveryMs, gitEveryMs, shelfEveryMs, shelfFirstMs, healthEveryMs, healthSettleMs, setupPollMs, rereadAfterMs, serverRoomMs, updateState, updateConf, appName, startWaitMs = 20_000, vmWatchEveryMs, historyEveryMs = HISTORY_STEP_MS, tetherConnectors, sshProbe }) {
|
|
326
|
+
export async function startHome({ port, host, dataDir, mntDir = dataDir, gitReserveBytes, env = process.env, conversations, resources, operators = [], publicOrigin, vaultKey, tools = loadTools(), stopDelayMs, mailReader, gitLocalRemotes = false, gitSsh, answerFetcher, answerEveryMs, wakeEveryMs, alertSend, talkEveryMs, gitEveryMs, shelfEveryMs, shelfFirstMs, healthEveryMs, healthSettleMs, setupPollMs, rereadAfterMs, serverRoomMs, updateState, updateConf, appName, startWaitMs = 20_000, vmWatchEveryMs, historyEveryMs = HISTORY_STEP_MS, tetherConnectors, sshProbe, quietStartMs = 0 }) {
|
|
317
327
|
/* The data, in the format this code reads, before anything reads it (dataformat.mjs). */
|
|
318
328
|
const migrated = migrateData(dataDir);
|
|
319
329
|
if (migrated.ran.length) console.log(`data: format ${migrated.from} -> ${migrated.to}`);
|
|
@@ -414,7 +424,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
414
424
|
and the tool is started through the runner. */
|
|
415
425
|
const network = new Network({ host: asHost, offline: () => all.offline() });
|
|
416
426
|
/* A machine the VM manager started by itself (after a reboot) is put in its silo too (04-11). */
|
|
417
|
-
const stopNetworkWatch = network.watch();
|
|
427
|
+
const stopNetworkWatch = network.watch(undefined, { quietMs: quietStartMs });
|
|
418
428
|
/* The rules follow what runs: applied now, and again each time a
|
|
419
429
|
conversation is opened, since a VM that just started has a new tap. */
|
|
420
430
|
const hostReady = (async () => { await hostSteps; await network.apply().catch((error) => console.error(`network rules: ${error.message}`)); })();
|
|
@@ -433,7 +443,12 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
433
443
|
chat: (name) => Boolean(talk?.brief(name)), say: (name, line) => wakeups.say(name, line), reread: () => talk?.rereadCommand() ?? null });
|
|
434
444
|
/* Why Parley is not in a machine, said once in the log, not at each opening. */
|
|
435
445
|
const parleySaid = new Map();
|
|
446
|
+
/* ITS HEARTBEAT (beat.mjs): with CLAVARIUM_BEAT=health, its health read from its work folder instead of
|
|
447
|
+
a command every two minutes; put in its machine at an opening (once per version), never waited for. */
|
|
448
|
+
const beat = new Beat({ on: beatWanted(env.CLAVARIUM_BEAT, 'health'), vms, workFolder: (name) => folders.workFolder(name), conversations: all });
|
|
449
|
+
if (beat.on) console.log('beat: the health of the machines read from their heartbeat (CLAVARIUM_BEAT)');
|
|
436
450
|
all.prepare = async (name, woke) => {
|
|
451
|
+
void beat.ensure(name, { woke }).catch(() => {});
|
|
437
452
|
await hostReady;
|
|
438
453
|
secrets.check();
|
|
439
454
|
const wanted = secrets.signature(name);
|
|
@@ -554,7 +569,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
554
569
|
const gitKeeper = new GitKeeper({ store: new Store(`${dataDir}/git-keep.json`), last: new Store(`${dataDir}/git-checks.json`), review: gitReview, resources: folders, alerts, tellAgent,
|
|
555
570
|
thread: (conversation, event) => talk.event(conversation, event),
|
|
556
571
|
checks: new GitChecks({ vms, conversations: all, resources: folders }) });
|
|
557
|
-
const gitTimer = gitKeeper.start(gitEveryMs);
|
|
572
|
+
const gitTimer = gitKeeper.start(gitEveryMs, { quietMs: quietStartMs });
|
|
558
573
|
/* A conversation with a tool on a screen that is not its terminal: see talk.mjs. */
|
|
559
574
|
/* Voice boxes: what the tool says in their conversation is read aloud (boxes.mjs). */
|
|
560
575
|
let boxes; let rooms; let machineList;
|
|
@@ -598,6 +613,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
598
613
|
};
|
|
599
614
|
/* What an owner did to a machine (start, stop, sleep, force, restart): in the journal, and a line in its chat. */
|
|
600
615
|
all.machineSaid = (name, text, ok, chat) => {
|
|
616
|
+
/* What runs changed (a start, a stop, a sleep): the rules follow at once, not at the next watch. */
|
|
617
|
+
void network.apply().catch(() => {});
|
|
601
618
|
events.add({ kind: 'machine', text: `Machine of ${name}: ${text}`, conversation: name });
|
|
602
619
|
if (chat) try { talk.event(name, ok ? { kind: 'machine-ok', text, topic: 'Machine' } : { kind: 'machine-problem', text, tone: 'warn', topic: 'Machine', brief: 'Machine action failed' }); } catch { /* its chat is off */ }
|
|
603
620
|
};
|
|
@@ -678,8 +695,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
678
695
|
try { if (dockets.on(name)) { dockets.post(name, { kind: 'shared-folder', text: line, data: { folder: link.folder, path: link.path } }); return; } } catch { /* typed instead */ }
|
|
679
696
|
if (all.list().find((c) => c.name === name)?.ai === true) void wakeups.say(name, line).catch(() => {});
|
|
680
697
|
};
|
|
681
|
-
const health = new Health({ vms, conversations: all, resources: folders, links: linkGuard, seen: new Store(`${dataDir}/health-seen.json`), ...(healthSettleMs === undefined ? {} : { settleMs: healthSettleMs }) });
|
|
682
|
-
const stopHealth = health.start(healthEveryMs);
|
|
698
|
+
const health = new Health({ vms, conversations: all, resources: folders, links: linkGuard, beat, seen: new Store(`${dataDir}/health-seen.json`), ...(healthSettleMs === undefined ? {} : { settleMs: healthSettleMs }) });
|
|
699
|
+
const stopHealth = health.start(healthEveryMs, { quietMs: quietStartMs });
|
|
683
700
|
/* What is wrong with its machine is said in its chat too, where it happened. */
|
|
684
701
|
/* And what its owner chose that it does on top (healthreact.mjs): its agent told, or a command run. */
|
|
685
702
|
const reacting = new HealthReact({ store: new Store(`${dataDir}/health-react.json`), say: (name, line) => wakeups.say(name, line), exec: (name, argv, options) => vms.exec(name, argv, options),
|
|
@@ -701,7 +718,12 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
701
718
|
},
|
|
702
719
|
tell: (name, text, started) => all.renewed(name, text, started),
|
|
703
720
|
alert: (payload) => { events.add({ kind: 'machine', text: `${payload.title}: ${payload.body ?? ''}`.trim() }); void alerts.tell(payload)?.catch?.(() => {}); } });
|
|
721
|
+
/* A machine found running that was not (the VM manager started it by itself): its rules at once. */
|
|
722
|
+
const wasRunning = new Map();
|
|
704
723
|
health.judged = (name, record) => {
|
|
724
|
+
const running = record?.state === 'Running';
|
|
725
|
+
if (running && wasRunning.get(name) === false) void network.apply().catch(() => {});
|
|
726
|
+
if (record?.state !== undefined && record.state !== 'Unknown') wasRunning.set(name, running);
|
|
705
727
|
void watchdog.judged(name, record).catch(() => {});
|
|
706
728
|
try { revive.judged(name, record); } catch { /* its tool: nothing more */ }
|
|
707
729
|
talk.machine(name, record); void reacting.judged(name, record).catch(() => {});
|
|
@@ -782,12 +804,27 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
782
804
|
const history = new History({ file: `${dataDir}/history.json` });
|
|
783
805
|
const historyLook = () => capacity.room().then((room) => history.sample(room, all.list().filter((c) => c.phase === 'ready').map((c) => ({ name: c.name, vm: `clv-${c.name}`, cores: c.cpus ?? 1, memoryMb: c.memoryMb, health: health.of(c.name) })))).catch(() => {});
|
|
784
806
|
const historyTimer = setInterval(() => { void historyLook(); }, historyEveryMs); historyTimer.unref?.();
|
|
785
|
-
/* THE SECRETS' GUARD:
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
807
|
+
/* THE SECRETS' GUARD: every machine that runs is looked at -- the names in its /run/secrets
|
|
808
|
+
against those it should hold now, and what was last put there against what would be now. A
|
|
809
|
+
missing one is put back, one too many taken away, a new value given: whatever path changed
|
|
810
|
+
them (a page, an expiry, a machine restarted behind our back).
|
|
811
|
+
The names are read by the health probe (health.mjs), in the look made anyway every few
|
|
812
|
+
minutes: no command of its own. Each minute, what would be put there now is weighed against
|
|
813
|
+
what was, with nothing asked of the machine: a change (a page, an expiry) is given within
|
|
814
|
+
the minute, as before. */
|
|
815
|
+
const guarding = new Set();
|
|
816
|
+
const guardOne = async (name, listed) => {
|
|
817
|
+
if (guarding.has(name)) return;
|
|
818
|
+
guarding.add(name);
|
|
819
|
+
try { const now = await secrets.reconcile(name, delivered.get(name), listed).catch(() => null); if (now !== null) delivered.set(name, now); } finally { guarding.delete(name); }
|
|
820
|
+
};
|
|
821
|
+
health.probed = (name, facts) => (facts?.secrets && all.awake().includes(name) ? guardOne(name, facts.secrets) : undefined);
|
|
789
822
|
const secretsGuard = async () => {
|
|
790
|
-
for (const name of all.awake()) {
|
|
823
|
+
for (const name of all.awake()) {
|
|
824
|
+
if (!delivered.has(name) || delivered.get(name) === secrets.signature(name)) continue;
|
|
825
|
+
/* What it should hold changed: given again whatever is there, so nothing is asked of it first. */
|
|
826
|
+
await guardOne(name, { count: 0, names: [] });
|
|
827
|
+
}
|
|
791
828
|
};
|
|
792
829
|
const secretsTimer = setInterval(() => { void secretsGuard().catch(() => {}); }, 60_000); secretsTimer.unref?.();
|
|
793
830
|
/* The machines' disks give back what was erased, every hour (conversations.trimAll, vm.mjs trim). */
|
|
@@ -988,7 +1025,19 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
988
1025
|
all.ready = (name) => { toolbox.forget(name); void bridge.warm(name); };
|
|
989
1026
|
/* Their health too: after a restart of the host, a folder may not have come back. */
|
|
990
1027
|
/* The tools are shown in them first: a machine made before /tools existed gets it now, not as "a folder that came loose". */
|
|
991
|
-
|
|
1028
|
+
/* After the quiet start, one machine after another (QUIET_STEP_MS apart). */
|
|
1029
|
+
const warmAll = async () => {
|
|
1030
|
+
let first = true;
|
|
1031
|
+
for (const name of all.awake()) {
|
|
1032
|
+
if (closing) return;
|
|
1033
|
+
if (!await all.running(name).catch(() => false)) continue;
|
|
1034
|
+
if (!first && quietStartMs > 0) await new Promise((r) => { setTimeout(r, QUIET_STEP_MS).unref?.(); });
|
|
1035
|
+
first = false;
|
|
1036
|
+
await toolbox.show(name).catch(() => {}); void health.check(name).catch(() => {}); await bridge.warm(name);
|
|
1037
|
+
}
|
|
1038
|
+
};
|
|
1039
|
+
if (quietStartMs > 0) setTimeout(() => { void warmAll().catch(() => {}); }, quietStartMs).unref?.();
|
|
1040
|
+
else void warmAll().catch(() => {});
|
|
992
1041
|
return listening;
|
|
993
1042
|
}
|
|
994
1043
|
|
|
@@ -1018,7 +1067,7 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
|
|
1018
1067
|
const mntDir = hostSetting('MNT') || dataDir;
|
|
1019
1068
|
/* --name: the name of this Clavarium until one is chosen in Settings (instance.mjs). */
|
|
1020
1069
|
const name = option(argv, 'name', '') || undefined;
|
|
1021
|
-
const server = await startHome({ port, host: host.split(' ').filter(Boolean), dataDir, mntDir, operators, publicOrigin, vaultKey, appName: name }).catch((error) => { console.error(`start: FAILED: ${error.message}`); process.exit(1); });
|
|
1070
|
+
const server = await startHome({ port, host: host.split(' ').filter(Boolean), dataDir, mntDir, operators, publicOrigin, vaultKey, appName: name, quietStartMs: QUIET_START_MS }).catch((error) => { console.error(`start: FAILED: ${error.message}`); process.exit(1); });
|
|
1022
1071
|
console.log(`http://127.0.0.1:${server.address().port}/`);
|
|
1023
1072
|
} else {
|
|
1024
1073
|
const command = option(argv, 'command', 'bash').split(' ').filter(Boolean);
|
package/server/network.mjs
CHANGED
|
@@ -42,8 +42,10 @@ export const isAddress = (v) => typeof v === 'string' && ADDRESS.test(v) && v.sp
|
|
|
42
42
|
/* An address a VM may hold: not 0.0.0.0, not broadcast, not multicast. */
|
|
43
43
|
const isHostAddress = (v) => isAddress(v) && v.split('.')[0] !== '0' && Number(v.split('.')[0]) < 224;
|
|
44
44
|
|
|
45
|
-
/* How often what runs is looked at, for the rules (see watch)
|
|
46
|
-
|
|
45
|
+
/* How often what runs is looked at, for the rules (see watch): three commands to the host each
|
|
46
|
+
time. Every opening applies them anyway, and so does every action on a machine and a machine
|
|
47
|
+
found running that was not (main.mjs): this is only for what nothing told. */
|
|
48
|
+
export const WATCH_MS = 120_000;
|
|
47
49
|
export const RELOAD_MS = 10 * 60_000;
|
|
48
50
|
|
|
49
51
|
/* The running conversation VMs, read from the process list:
|
|
@@ -185,8 +187,10 @@ export class Network {
|
|
|
185
187
|
/* KEPT UP TO DATE (04-11): a machine started by the VM manager itself -- after the server
|
|
186
188
|
restarted -- has a new tap that no opening told: looked at every `everyMs`, the table loaded
|
|
187
189
|
again only when what runs changed. Returns the stop. */
|
|
188
|
-
|
|
189
|
-
|
|
190
|
+
/* `quietMs`: none that soon after a start of the server (main.mjs, quietStartMs; it applies them once anyway). */
|
|
191
|
+
watch(everyMs = WATCH_MS, { quietMs = 0 } = {}) {
|
|
192
|
+
const quietUntil = Date.now() + quietMs;
|
|
193
|
+
const timer = setInterval(() => { if (Date.now() >= quietUntil) void this.apply().catch(() => {}); }, everyMs);
|
|
190
194
|
timer.unref?.();
|
|
191
195
|
return () => clearInterval(timer);
|
|
192
196
|
}
|
package/server/secrets.mjs
CHANGED
|
@@ -262,14 +262,23 @@ export class Secrets {
|
|
|
262
262
|
return this.#given(conversation).map((s) => `${s.name}=${s.sealed}`).sort().join('|');
|
|
263
263
|
}
|
|
264
264
|
|
|
265
|
-
/* THE GUARD (main.mjs, each
|
|
266
|
-
against those it should hold, and `last` (the signature of what was
|
|
267
|
-
what it would be now. Delivered again when either differs. Resolves
|
|
268
|
-
there, or null when the machine could not be looked at.
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
265
|
+
/* THE GUARD (main.mjs, at each look of its machine's health, for each machine that runs): the
|
|
266
|
+
names in its /run/secrets against those it should hold, and `last` (the signature of what was
|
|
267
|
+
last put there) against what it would be now. Delivered again when either differs. Resolves
|
|
268
|
+
with the signature now there, or null when the machine could not be looked at.
|
|
269
|
+
`listed`: { count, names } as the health probe read them (health.mjs), so that no command of
|
|
270
|
+
its own is sent; without it, the machine is asked. */
|
|
271
|
+
async reconcile(conversation, last, listed) {
|
|
272
|
+
let names;
|
|
273
|
+
if (listed && Number.isInteger(listed.count) && Array.isArray(listed.names)) {
|
|
274
|
+
/* More than were listed: never "in order". */
|
|
275
|
+
names = listed.count === listed.names.length ? listed.names.map(String) : null;
|
|
276
|
+
} else {
|
|
277
|
+
const seen = await this.#vms.exec(conversation, ['sh', '-c', `ls -1 ${SECRETS_DIR} 2>/dev/null; true`], { timeoutMs: 10_000 }).catch(() => null);
|
|
278
|
+
if (!seen || seen.code !== 0) return null;
|
|
279
|
+
names = String(seen.stdout ?? '').split('\n').map((x) => x.trim()).filter(Boolean);
|
|
280
|
+
}
|
|
281
|
+
const there = names === null ? null : [...names].sort().join('|');
|
|
273
282
|
const wanted = this.signature(conversation);
|
|
274
283
|
if (there === this.given(conversation).sort().join('|') && last === wanted) return wanted;
|
|
275
284
|
await this.deliver(conversation);
|
package/server/vm.mjs
CHANGED
|
@@ -94,7 +94,11 @@ export function commandKind(argv) {
|
|
|
94
94
|
return `vm exec ${String(prog ?? '').slice(0, 40)}`;
|
|
95
95
|
}
|
|
96
96
|
const CHANGES = new Set(['launch', 'clone', 'start', 'stop', 'suspend', 'kill', 'halt', 'hardstop', 'delete', 'purge', 'set', 'rename', 'restore', 'snapshot', 'revive', 'reclaim']);
|
|
97
|
-
|
|
97
|
+
/* How long one answer of the VM manager serves every caller. Each command that changes a machine
|
|
98
|
+
asks again (run, below); a caller that must see a change soon passes `fresh`, or `within`
|
|
99
|
+
(a wait for a machine to start or stop: WAIT_FRESH_MS, as before this was 15 s). */
|
|
100
|
+
export const STATES_FRESH_MS = 15_000;
|
|
101
|
+
export const WAIT_FRESH_MS = 3000;
|
|
98
102
|
/* The VM manager did not say what a machine is in: not an answer about the machine. */
|
|
99
103
|
export class VmUnknown extends Error {
|
|
100
104
|
constructor(why) { super(`The VM manager does not answer just now (${why}): try again in a moment.`); this.status = 503; this.retry = true; }
|
|
@@ -103,7 +107,7 @@ export class VmUnknown extends Error {
|
|
|
103
107
|
export class Vms {
|
|
104
108
|
/* `run(argv, options)` reaches the host program; `prefix` is the same
|
|
105
109
|
route as an argument vector, for the one caller that needs a terminal. */
|
|
106
|
-
#ask; #snapshot = null; #asking = null; #now; #freshMs; #machineOf; #userOf;
|
|
110
|
+
#ask; #snapshot = null; #asking = null; #changed = 0; #now; #freshMs; #machineOf; #userOf;
|
|
107
111
|
/* `freshMs`: how long one answer serves every caller (0: only those asking meanwhile). */
|
|
108
112
|
/* `machineOf(conversation)`: the shared machine it lives in (#221), or nothing -- its own, `clv-<conversation>`. */
|
|
109
113
|
constructor(run, prefix, { now = () => Date.now(), freshMs = STATES_FRESH_MS, machineOf = () => undefined, userOf = () => undefined } = {}) {
|
|
@@ -112,16 +116,18 @@ export class Vms {
|
|
|
112
116
|
/* What changes a machine makes the states asked again (not taken from before it). */
|
|
113
117
|
this.run = async (argv, options) => {
|
|
114
118
|
const changes = argv[0] === 'vm' && CHANGES.has(argv[1]);
|
|
115
|
-
if (changes) this.#snapshot = null;
|
|
119
|
+
if (changes) { this.#snapshot = null; this.#changed += 1; }
|
|
116
120
|
const began = this.#now();
|
|
117
|
-
try { return await this.#ask(argv, options); } finally { if (changes) this.#snapshot = null; this.#count(argv, this.#now() - began); }
|
|
121
|
+
try { return await this.#ask(argv, options); } finally { if (changes) { this.#snapshot = null; this.#changed += 1; } this.#count(argv, this.#now() - began); }
|
|
118
122
|
};
|
|
119
123
|
}
|
|
120
124
|
|
|
121
125
|
/* HOW MUCH THIS SERVER ASKS OF THE HOST (17-11: the owner saw a page wait 10-15 s with an idle CPU --
|
|
122
126
|
every command to a machine goes through the VM manager, one after another): each command counted by
|
|
123
127
|
what it is, with its time; every COUNT_EVERY_MS the tally is said in the log, the busiest first. */
|
|
124
|
-
#tally = new Map(); #tallyFrom = 0;
|
|
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; }
|
|
125
131
|
#count(argv, ms) {
|
|
126
132
|
const now = this.#now();
|
|
127
133
|
if (!this.#tallyFrom) this.#tallyFrom = now;
|
|
@@ -129,16 +135,21 @@ export class Vms {
|
|
|
129
135
|
if (now - this.#tallyFrom < COUNT_EVERY_MS) return;
|
|
130
136
|
const rows = [...this.#tally].sort((a, b) => b[1][1] - a[1][1]);
|
|
131
137
|
const all = rows.reduce((n, [, v]) => n + v[0], 0); const busy = rows.reduce((n, [, v]) => n + v[1], 0);
|
|
132
|
-
|
|
133
|
-
this.#
|
|
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];
|
|
134
141
|
}
|
|
135
142
|
|
|
136
143
|
/* EVERY MACHINE'S STATE, in one question to the VM manager, shared by every caller for a
|
|
137
144
|
few seconds (and by those who ask while it is being asked). */
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
if (this.#
|
|
141
|
-
this.#asking
|
|
145
|
+
/* An answer asked before a machine changed is neither kept nor joined after it (`#changed`). */
|
|
146
|
+
async #states(fresh = false, within = this.#freshMs) {
|
|
147
|
+
if (!fresh && this.#snapshot && this.#now() - this.#snapshot.at < Math.min(within, this.#freshMs)) return this.#snapshot;
|
|
148
|
+
if (this.#asking && this.#asking.changed === this.#changed) return this.#asking.run;
|
|
149
|
+
const changed = this.#changed;
|
|
150
|
+
const asking = { changed, run: null };
|
|
151
|
+
this.#asking = asking;
|
|
152
|
+
asking.run = (async () => {
|
|
142
153
|
const r = await this.#ask(['vm', 'states'], { timeoutMs: 130_000 }).catch((error) => ({ code: 1, stdout: '', stderr: String(error?.message ?? error) }));
|
|
143
154
|
let states = null; let why = '';
|
|
144
155
|
if (r.code === 0) {
|
|
@@ -146,10 +157,10 @@ export class Vms {
|
|
|
146
157
|
} else why = String(r.stderr || r.stdout || `exit ${r.code}`).trim().split('\n').pop().slice(0, 200);
|
|
147
158
|
const snap = { at: this.#now(), states, why };
|
|
148
159
|
/* Not kept when it did not answer: the next caller asks again. */
|
|
149
|
-
this.#snapshot = states ? snap : null;
|
|
160
|
+
if (changed === this.#changed) this.#snapshot = states ? snap : null;
|
|
150
161
|
return snap;
|
|
151
|
-
})().finally(() => { this.#asking = null; });
|
|
152
|
-
return
|
|
162
|
+
})().finally(() => { if (this.#asking === asking) this.#asking = null; });
|
|
163
|
+
return asking.run;
|
|
153
164
|
}
|
|
154
165
|
|
|
155
166
|
/* Whether it lives in a shared machine (#221). */
|
|
@@ -202,8 +213,8 @@ export class Vms {
|
|
|
202
213
|
}
|
|
203
214
|
|
|
204
215
|
/* Every machine's state, by VM name (a Map); throws VmUnknown when the VM manager did not answer. */
|
|
205
|
-
async states({ fresh = false } = {}) {
|
|
206
|
-
const snap = await this.#states(fresh);
|
|
216
|
+
async states({ fresh = false, within } = {}) {
|
|
217
|
+
const snap = await this.#states(fresh, within);
|
|
207
218
|
if (!snap.states) throw new VmUnknown(snap.why);
|
|
208
219
|
return new Map(snap.states);
|
|
209
220
|
}
|
|
@@ -213,10 +224,11 @@ export class Vms {
|
|
|
213
224
|
manager that does not answer (busy, timed out, restarting) says nothing of the machine:
|
|
214
225
|
that throws (VmUnknown), and is never taken for a machine that is gone (21-10: a machine
|
|
215
226
|
frozen inside had "multipass info" fail, read as "no longer exists"). */
|
|
216
|
-
/* `fresh`: asked now (an owner opening it, building it again), not taken from a few seconds ago.
|
|
217
|
-
|
|
227
|
+
/* `fresh`: asked now (an owner opening it, building it again), not taken from a few seconds ago.
|
|
228
|
+
`within`: an answer at most this old does (a wait that looks again every few seconds). */
|
|
229
|
+
async state(conversation, { fresh = false, within } = {}) {
|
|
218
230
|
const name = this.vmOf(conversation);
|
|
219
|
-
const snap = await this.#states(fresh);
|
|
231
|
+
const snap = await this.#states(fresh, within);
|
|
220
232
|
if (!snap.states) throw new VmUnknown(snap.why);
|
|
221
233
|
return snap.states.get(name);
|
|
222
234
|
}
|