clavarium 0.2.486-next.1 → 0.2.487-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/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/server/conversations.mjs +3 -3
- package/server/gitkeeper.mjs +39 -7
- package/server/gitpush.mjs +5 -2
- package/server/health.mjs +26 -3
- package/server/main.mjs +54 -11
- package/server/network.mjs +8 -4
- package/server/secrets.mjs +17 -8
- package/server/vm.mjs +25 -16
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.487-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.487-next.1",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@xterm/addon-fit": "^0.11.0",
|
package/package.json
CHANGED
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/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,17 @@ 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
|
+
/* The looks of one tick start this far apart, one machine after another (at most a tick shared out
|
|
82
|
+
between them): a burst of probes lines up at the VM manager in front of every other command. */
|
|
83
|
+
export const STAGGER_MS = 5_000;
|
|
74
84
|
const PROBE_MS = 15_000;
|
|
75
85
|
/* What the clock waits for one conversation's look before it goes on. */
|
|
76
86
|
const LOOK_MS = 60_000;
|
|
@@ -105,6 +115,10 @@ export function readProbe(text, paths = []) {
|
|
|
105
115
|
if (parts[0] === 'stale' && parts.length === 2 && a !== undefined) facts.stale = true;
|
|
106
116
|
if (parts[0] === 'screen' && parts.length === 2 && a !== undefined) facts.screenLoose = a;
|
|
107
117
|
if (line.trim() === 'restart asked') facts.restartAsked = true;
|
|
118
|
+
/* A name that is not a plain one (the agent may put anything there) is kept as '?': it
|
|
119
|
+
matches nothing that is given, so the guard writes the folder again, as it would have. */
|
|
120
|
+
if (parts[0] === 'secrets' && parts.length === 2 && a !== undefined) facts.secrets = { count: a, names: [] };
|
|
121
|
+
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
122
|
}
|
|
109
123
|
return facts;
|
|
110
124
|
}
|
|
@@ -171,6 +185,9 @@ export class Health {
|
|
|
171
185
|
judged = () => {};
|
|
172
186
|
/* Set by the server: told a conversation is forgotten (what else is kept of its machine goes too). */
|
|
173
187
|
forgotten = () => {};
|
|
188
|
+
/* Set by the server: told what a probe that answered found (`facts`: readProbe's), not waited for.
|
|
189
|
+
The secrets' guard reads its names of /run/secrets there (main.mjs). */
|
|
190
|
+
probed = () => {};
|
|
174
191
|
|
|
175
192
|
/* `settleMs`: how long a missing folder is given before it is mounted
|
|
176
193
|
again (a machine that has just started may still be mounting it).
|
|
@@ -228,6 +245,7 @@ export class Health {
|
|
|
228
245
|
return this.#keep(name, { at, state, answering: false });
|
|
229
246
|
}
|
|
230
247
|
this.#quiet.delete(name);
|
|
248
|
+
try { void Promise.resolve(this.probed(name, facts)).catch(() => {}); } catch { /* told, nothing more */ }
|
|
231
249
|
const loose = () => paths.filter((p) => facts.mounts[p] !== 'ok');
|
|
232
250
|
const remounted = []; const failed = [];
|
|
233
251
|
if (loose().length > 0 && repair && this.#resources) {
|
|
@@ -316,18 +334,23 @@ export class Health {
|
|
|
316
334
|
|
|
317
335
|
/* Every so often, each conversation whose machine should run. A machine
|
|
318
336
|
that does not run is not touched (its state alone is asked). */
|
|
319
|
-
start(
|
|
337
|
+
/* `quietMs`: no look by the clock that soon after a start of the server (main.mjs, quietStartMs). */
|
|
338
|
+
start(everyMs = EVERY_MS, { quietMs = 0 } = {}) {
|
|
320
339
|
if (!everyMs) return () => {};
|
|
321
340
|
let going = false;
|
|
341
|
+
const quietUntil = Date.now() + quietMs;
|
|
322
342
|
const timer = setInterval(async () => {
|
|
323
|
-
if (going) return;
|
|
343
|
+
if (going || Date.now() < quietUntil) return;
|
|
324
344
|
going = true;
|
|
325
345
|
/* All at once, each within its own time: one machine slow to
|
|
326
346
|
answer (or a mount that hangs) does not hold up the others.
|
|
327
347
|
A look still going when its time is up goes on; the next tick
|
|
328
348
|
joins it rather than starting another (check). */
|
|
329
349
|
try {
|
|
330
|
-
|
|
350
|
+
const names = this.#conversations.awake();
|
|
351
|
+
const apart = Math.min(STAGGER_MS, Math.floor(everyMs / Math.max(1, names.length)));
|
|
352
|
+
await Promise.all(names.map(async (name, i) => {
|
|
353
|
+
if (i > 0 && apart > 0) await new Promise((resolve) => { setTimeout(resolve, i * apart).unref?.(); });
|
|
331
354
|
let timer;
|
|
332
355
|
const bound = new Promise((resolve) => { timer = setTimeout(resolve, this.#lookMs); timer.unref?.(); });
|
|
333
356
|
return Promise.race([this.check(name).catch(() => {}), bound]).finally(() => clearTimeout(timer));
|
package/server/main.mjs
CHANGED
|
@@ -309,11 +309,20 @@ export function start({ port, command, cwd, env = process.env }) {
|
|
|
309
309
|
const MAIL_EVERY_MS = 120_000;
|
|
310
310
|
/* An opening waits this long at most for Parley to be installed in its machine (toolbox.mjs). */
|
|
311
311
|
const PARLEY_WAIT_MS = 20_000;
|
|
312
|
+
/* A QUIET START (17-11): after the server starts, its background work on the machines (the
|
|
313
|
+
references' refreshes and the fetches into the machines, the health looks with the secrets'
|
|
314
|
+
names, the network watch, every machine's terminal opened beforehand) waits this long, then
|
|
315
|
+
comes one machine after another: the machines starting again, and the owner's first pages,
|
|
316
|
+
come first. What a page asks is never held. The server run as a service passes it; a test
|
|
317
|
+
or a bench that calls startHome itself gets none (quietStartMs: 0). */
|
|
318
|
+
export const QUIET_START_MS = 150_000;
|
|
319
|
+
/* Between two machines of that first round. */
|
|
320
|
+
const QUIET_STEP_MS = 5_000;
|
|
312
321
|
|
|
313
322
|
/* The product: conversations are VMs. `host` is how the host program is
|
|
314
323
|
reached on this installation, as an argument vector: it is the ONLY thing
|
|
315
324
|
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 }) {
|
|
325
|
+
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
326
|
/* The data, in the format this code reads, before anything reads it (dataformat.mjs). */
|
|
318
327
|
const migrated = migrateData(dataDir);
|
|
319
328
|
if (migrated.ran.length) console.log(`data: format ${migrated.from} -> ${migrated.to}`);
|
|
@@ -414,7 +423,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
414
423
|
and the tool is started through the runner. */
|
|
415
424
|
const network = new Network({ host: asHost, offline: () => all.offline() });
|
|
416
425
|
/* A machine the VM manager started by itself (after a reboot) is put in its silo too (04-11). */
|
|
417
|
-
const stopNetworkWatch = network.watch();
|
|
426
|
+
const stopNetworkWatch = network.watch(undefined, { quietMs: quietStartMs });
|
|
418
427
|
/* The rules follow what runs: applied now, and again each time a
|
|
419
428
|
conversation is opened, since a VM that just started has a new tap. */
|
|
420
429
|
const hostReady = (async () => { await hostSteps; await network.apply().catch((error) => console.error(`network rules: ${error.message}`)); })();
|
|
@@ -554,7 +563,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
554
563
|
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
564
|
thread: (conversation, event) => talk.event(conversation, event),
|
|
556
565
|
checks: new GitChecks({ vms, conversations: all, resources: folders }) });
|
|
557
|
-
const gitTimer = gitKeeper.start(gitEveryMs);
|
|
566
|
+
const gitTimer = gitKeeper.start(gitEveryMs, { quietMs: quietStartMs });
|
|
558
567
|
/* A conversation with a tool on a screen that is not its terminal: see talk.mjs. */
|
|
559
568
|
/* Voice boxes: what the tool says in their conversation is read aloud (boxes.mjs). */
|
|
560
569
|
let boxes; let rooms; let machineList;
|
|
@@ -598,6 +607,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
598
607
|
};
|
|
599
608
|
/* What an owner did to a machine (start, stop, sleep, force, restart): in the journal, and a line in its chat. */
|
|
600
609
|
all.machineSaid = (name, text, ok, chat) => {
|
|
610
|
+
/* What runs changed (a start, a stop, a sleep): the rules follow at once, not at the next watch. */
|
|
611
|
+
void network.apply().catch(() => {});
|
|
601
612
|
events.add({ kind: 'machine', text: `Machine of ${name}: ${text}`, conversation: name });
|
|
602
613
|
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
614
|
};
|
|
@@ -679,7 +690,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
679
690
|
if (all.list().find((c) => c.name === name)?.ai === true) void wakeups.say(name, line).catch(() => {});
|
|
680
691
|
};
|
|
681
692
|
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);
|
|
693
|
+
const stopHealth = health.start(healthEveryMs, { quietMs: quietStartMs });
|
|
683
694
|
/* What is wrong with its machine is said in its chat too, where it happened. */
|
|
684
695
|
/* And what its owner chose that it does on top (healthreact.mjs): its agent told, or a command run. */
|
|
685
696
|
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 +712,12 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
701
712
|
},
|
|
702
713
|
tell: (name, text, started) => all.renewed(name, text, started),
|
|
703
714
|
alert: (payload) => { events.add({ kind: 'machine', text: `${payload.title}: ${payload.body ?? ''}`.trim() }); void alerts.tell(payload)?.catch?.(() => {}); } });
|
|
715
|
+
/* A machine found running that was not (the VM manager started it by itself): its rules at once. */
|
|
716
|
+
const wasRunning = new Map();
|
|
704
717
|
health.judged = (name, record) => {
|
|
718
|
+
const running = record?.state === 'Running';
|
|
719
|
+
if (running && wasRunning.get(name) === false) void network.apply().catch(() => {});
|
|
720
|
+
if (record?.state !== undefined && record.state !== 'Unknown') wasRunning.set(name, running);
|
|
705
721
|
void watchdog.judged(name, record).catch(() => {});
|
|
706
722
|
try { revive.judged(name, record); } catch { /* its tool: nothing more */ }
|
|
707
723
|
talk.machine(name, record); void reacting.judged(name, record).catch(() => {});
|
|
@@ -782,12 +798,27 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
782
798
|
const history = new History({ file: `${dataDir}/history.json` });
|
|
783
799
|
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
800
|
const historyTimer = setInterval(() => { void historyLook(); }, historyEveryMs); historyTimer.unref?.();
|
|
785
|
-
/* THE SECRETS' GUARD:
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
801
|
+
/* THE SECRETS' GUARD: every machine that runs is looked at -- the names in its /run/secrets
|
|
802
|
+
against those it should hold now, and what was last put there against what would be now. A
|
|
803
|
+
missing one is put back, one too many taken away, a new value given: whatever path changed
|
|
804
|
+
them (a page, an expiry, a machine restarted behind our back).
|
|
805
|
+
The names are read by the health probe (health.mjs), in the look made anyway every few
|
|
806
|
+
minutes: no command of its own. Each minute, what would be put there now is weighed against
|
|
807
|
+
what was, with nothing asked of the machine: a change (a page, an expiry) is given within
|
|
808
|
+
the minute, as before. */
|
|
809
|
+
const guarding = new Set();
|
|
810
|
+
const guardOne = async (name, listed) => {
|
|
811
|
+
if (guarding.has(name)) return;
|
|
812
|
+
guarding.add(name);
|
|
813
|
+
try { const now = await secrets.reconcile(name, delivered.get(name), listed).catch(() => null); if (now !== null) delivered.set(name, now); } finally { guarding.delete(name); }
|
|
814
|
+
};
|
|
815
|
+
health.probed = (name, facts) => (facts?.secrets && all.awake().includes(name) ? guardOne(name, facts.secrets) : undefined);
|
|
789
816
|
const secretsGuard = async () => {
|
|
790
|
-
for (const name of all.awake()) {
|
|
817
|
+
for (const name of all.awake()) {
|
|
818
|
+
if (!delivered.has(name) || delivered.get(name) === secrets.signature(name)) continue;
|
|
819
|
+
/* What it should hold changed: given again whatever is there, so nothing is asked of it first. */
|
|
820
|
+
await guardOne(name, { count: 0, names: [] });
|
|
821
|
+
}
|
|
791
822
|
};
|
|
792
823
|
const secretsTimer = setInterval(() => { void secretsGuard().catch(() => {}); }, 60_000); secretsTimer.unref?.();
|
|
793
824
|
/* The machines' disks give back what was erased, every hour (conversations.trimAll, vm.mjs trim). */
|
|
@@ -988,7 +1019,19 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
988
1019
|
all.ready = (name) => { toolbox.forget(name); void bridge.warm(name); };
|
|
989
1020
|
/* Their health too: after a restart of the host, a folder may not have come back. */
|
|
990
1021
|
/* The tools are shown in them first: a machine made before /tools existed gets it now, not as "a folder that came loose". */
|
|
991
|
-
|
|
1022
|
+
/* After the quiet start, one machine after another (QUIET_STEP_MS apart). */
|
|
1023
|
+
const warmAll = async () => {
|
|
1024
|
+
let first = true;
|
|
1025
|
+
for (const name of all.awake()) {
|
|
1026
|
+
if (closing) return;
|
|
1027
|
+
if (!await all.running(name).catch(() => false)) continue;
|
|
1028
|
+
if (!first && quietStartMs > 0) await new Promise((r) => { setTimeout(r, QUIET_STEP_MS).unref?.(); });
|
|
1029
|
+
first = false;
|
|
1030
|
+
await toolbox.show(name).catch(() => {}); void health.check(name).catch(() => {}); await bridge.warm(name);
|
|
1031
|
+
}
|
|
1032
|
+
};
|
|
1033
|
+
if (quietStartMs > 0) setTimeout(() => { void warmAll().catch(() => {}); }, quietStartMs).unref?.();
|
|
1034
|
+
else void warmAll().catch(() => {});
|
|
992
1035
|
return listening;
|
|
993
1036
|
}
|
|
994
1037
|
|
|
@@ -1018,7 +1061,7 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
|
|
1018
1061
|
const mntDir = hostSetting('MNT') || dataDir;
|
|
1019
1062
|
/* --name: the name of this Clavarium until one is chosen in Settings (instance.mjs). */
|
|
1020
1063
|
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); });
|
|
1064
|
+
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
1065
|
console.log(`http://127.0.0.1:${server.address().port}/`);
|
|
1023
1066
|
} else {
|
|
1024
1067
|
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,9 +116,9 @@ 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
|
|
|
@@ -135,10 +139,14 @@ export class Vms {
|
|
|
135
139
|
|
|
136
140
|
/* EVERY MACHINE'S STATE, in one question to the VM manager, shared by every caller for a
|
|
137
141
|
few seconds (and by those who ask while it is being asked). */
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
if (this.#
|
|
141
|
-
this.#asking
|
|
142
|
+
/* An answer asked before a machine changed is neither kept nor joined after it (`#changed`). */
|
|
143
|
+
async #states(fresh = false, within = this.#freshMs) {
|
|
144
|
+
if (!fresh && this.#snapshot && this.#now() - this.#snapshot.at < Math.min(within, this.#freshMs)) return this.#snapshot;
|
|
145
|
+
if (this.#asking && this.#asking.changed === this.#changed) return this.#asking.run;
|
|
146
|
+
const changed = this.#changed;
|
|
147
|
+
const asking = { changed, run: null };
|
|
148
|
+
this.#asking = asking;
|
|
149
|
+
asking.run = (async () => {
|
|
142
150
|
const r = await this.#ask(['vm', 'states'], { timeoutMs: 130_000 }).catch((error) => ({ code: 1, stdout: '', stderr: String(error?.message ?? error) }));
|
|
143
151
|
let states = null; let why = '';
|
|
144
152
|
if (r.code === 0) {
|
|
@@ -146,10 +154,10 @@ export class Vms {
|
|
|
146
154
|
} else why = String(r.stderr || r.stdout || `exit ${r.code}`).trim().split('\n').pop().slice(0, 200);
|
|
147
155
|
const snap = { at: this.#now(), states, why };
|
|
148
156
|
/* Not kept when it did not answer: the next caller asks again. */
|
|
149
|
-
this.#snapshot = states ? snap : null;
|
|
157
|
+
if (changed === this.#changed) this.#snapshot = states ? snap : null;
|
|
150
158
|
return snap;
|
|
151
|
-
})().finally(() => { this.#asking = null; });
|
|
152
|
-
return
|
|
159
|
+
})().finally(() => { if (this.#asking === asking) this.#asking = null; });
|
|
160
|
+
return asking.run;
|
|
153
161
|
}
|
|
154
162
|
|
|
155
163
|
/* Whether it lives in a shared machine (#221). */
|
|
@@ -202,8 +210,8 @@ export class Vms {
|
|
|
202
210
|
}
|
|
203
211
|
|
|
204
212
|
/* 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);
|
|
213
|
+
async states({ fresh = false, within } = {}) {
|
|
214
|
+
const snap = await this.#states(fresh, within);
|
|
207
215
|
if (!snap.states) throw new VmUnknown(snap.why);
|
|
208
216
|
return new Map(snap.states);
|
|
209
217
|
}
|
|
@@ -213,10 +221,11 @@ export class Vms {
|
|
|
213
221
|
manager that does not answer (busy, timed out, restarting) says nothing of the machine:
|
|
214
222
|
that throws (VmUnknown), and is never taken for a machine that is gone (21-10: a machine
|
|
215
223
|
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
|
-
|
|
224
|
+
/* `fresh`: asked now (an owner opening it, building it again), not taken from a few seconds ago.
|
|
225
|
+
`within`: an answer at most this old does (a wait that looks again every few seconds). */
|
|
226
|
+
async state(conversation, { fresh = false, within } = {}) {
|
|
218
227
|
const name = this.vmOf(conversation);
|
|
219
|
-
const snap = await this.#states(fresh);
|
|
228
|
+
const snap = await this.#states(fresh, within);
|
|
220
229
|
if (!snap.states) throw new VmUnknown(snap.why);
|
|
221
230
|
return snap.states.get(name);
|
|
222
231
|
}
|