clavarium 0.2.389-next.1 → 0.2.391-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/deploy/clavarium-host +83 -19
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/server/api.mjs +22 -2
- package/server/capacity.mjs +33 -10
- package/server/conversations.mjs +41 -8
- package/server/machinelist.mjs +58 -0
- package/server/main.mjs +24 -6
- package/server/settingswords.mjs +13 -0
- package/server/vm.mjs +7 -0
- package/server/vmwatch.mjs +82 -23
- package/server/watchdog.mjs +102 -0
- package/web/app.js +117 -1
- package/web/index.html +20 -1
- package/web/style.css +7 -0
package/deploy/clavarium-host
CHANGED
|
@@ -70,6 +70,9 @@ HALT_TERM="5"
|
|
|
70
70
|
HALT_KILL="5"
|
|
71
71
|
HALT_LIST="20"
|
|
72
72
|
HALT_SETTLE="10"
|
|
73
|
+
# Where the qemu processes seen for each machine are noted (root's, in memory): a qemu ended but not
|
|
74
|
+
# reaped by a VM manager that hangs (a zombie) has no command line left to tell whose it was.
|
|
75
|
+
QEMU_SEEN="/run/clavarium/qemu"
|
|
73
76
|
# The bounds of the plain verbs (a VM manager that hangs must not hold a call for ever).
|
|
74
77
|
START_SECONDS="180"
|
|
75
78
|
STOP_SECONDS="120"
|
|
@@ -193,7 +196,7 @@ while [ $# -gt 0 ]; do
|
|
|
193
196
|
DATA="$TEST"; MNT="$TEST"; WIFI_STATE="$TEST/wifi"; NM_KEYFILES="$TEST/system-connections"; WIFI_WAIT="3"; WIFI_UP_WAIT="3"; WIFI_STEP="0.2"
|
|
194
197
|
HAND_STATE="$TEST/network"; NETPLAN_DIR="$TEST/netplan"; HAND_WAIT="3"; SYS_NET="$TEST/sys-net"
|
|
195
198
|
MESH_DATA="$TEST/mesh"; MESH_STATE="$TEST/meshcentral"; CADDYFILE="$TEST/Caddyfile"; MESH_CADDY="$TEST/clavarium-meshcentral.caddy"
|
|
196
|
-
HALT_POLITE="2"; HALT_FORCE="2"; HALT_TERM="1"; HALT_KILL="2"; HALT_LIST="2"; HALT_SETTLE="2"; shift 2 ;;
|
|
199
|
+
HALT_POLITE="2"; HALT_FORCE="2"; HALT_TERM="1"; HALT_KILL="2"; HALT_LIST="2"; HALT_SETTLE="2"; QEMU_SEEN="$TEST/qemu"; shift 2 ;;
|
|
197
200
|
*) break ;;
|
|
198
201
|
esac
|
|
199
202
|
done
|
|
@@ -239,6 +242,8 @@ vm_qemu_pids() {
|
|
|
239
242
|
vm="$(tr '\0' '\n' < "/proc/$pid/cmdline" 2>/dev/null | grep -oE '/instances/clv(shelf)?-[a-z0-9-]+/' | head -1 | cut -d/ -f3)" || vm=""
|
|
240
243
|
[ "$vm" = "$want" ] && printf '%s\n' "$pid"
|
|
241
244
|
done
|
|
245
|
+
# (Its status is never that of the last process looked at: callers assign it under set -e.)
|
|
246
|
+
return 0
|
|
242
247
|
}
|
|
243
248
|
# No qemu left for this machine after a short grace: its RAM has been freed.
|
|
244
249
|
vm_freed() { local v="$1" i; for i in $(seq 1 24); do [ -z "$(vm_qemu_pids "$v")" ] && return 0; sleep 0.5; done; return 1; }
|
|
@@ -263,24 +268,66 @@ vm_state_of() {
|
|
|
263
268
|
out="$(printf '%s\n' "$out" | awk -F, -v n="$1" '$1 == n { print $2; exit }')"
|
|
264
269
|
echo "${out:-absent}"
|
|
265
270
|
}
|
|
266
|
-
#
|
|
267
|
-
|
|
271
|
+
# A process's state letter (R, S, D, T stopped, t traced, Z ended but not reaped), or nothing when gone.
|
|
272
|
+
proc_state() { sed -n 's/^State:[[:space:]]*\([A-Za-z]\).*/\1/p' "/proc/$1/status" 2>/dev/null || true; }
|
|
273
|
+
# Still running (frozen included): its /proc entry is there and it is not a zombie.
|
|
274
|
+
pid_alive() { local st; [ -d "/proc/$1" ] || return 1; st="$(proc_state "$1")"; [ -n "$st" ] && [ "$st" != "Z" ]; }
|
|
275
|
+
# Its qemu, noted as seen (vm_qemu_unreaped reads it back).
|
|
276
|
+
vm_qemu_note() {
|
|
277
|
+
local v="$1" pids
|
|
278
|
+
pids="$(vm_qemu_pids "$v")"
|
|
279
|
+
[ -n "$pids" ] || return 0
|
|
280
|
+
install -d -m 0700 "$QEMU_SEEN" 2>/dev/null || return 0
|
|
281
|
+
printf '%s\n' $pids > "$QEMU_SEEN/$v" 2>/dev/null || true
|
|
282
|
+
}
|
|
283
|
+
# A qemu of it that has ended but that the VM manager has not reaped (a zombie: it holds no memory,
|
|
284
|
+
# and no signal can do more to it). The VM manager is the one stuck.
|
|
285
|
+
vm_qemu_unreaped() {
|
|
286
|
+
local v="$1" pid
|
|
287
|
+
[ -r "$QEMU_SEEN/$v" ] || return 0
|
|
288
|
+
while read -r pid; do
|
|
289
|
+
[[ "$pid" =~ ^[0-9]+$ ]] || continue
|
|
290
|
+
[ "$(proc_state "$pid")" = "Z" ] && [[ "$(cat "/proc/$pid/comm" 2>/dev/null)" == qemu-system* ]] && printf '%s\n' "$pid"
|
|
291
|
+
done < "$QEMU_SEEN/$v"
|
|
292
|
+
return 0
|
|
293
|
+
}
|
|
294
|
+
# A qemu of it that is FROZEN (stopped, or traced): it answers nothing, a suspend asked of it hangs the VM manager.
|
|
295
|
+
vm_qemu_frozen() { local pid; for pid in $(vm_qemu_pids "$1"); do [[ "$(proc_state "$pid")" == [Tt] ]] && return 0; done; return 1; }
|
|
296
|
+
# NOTHING LEFT TO STOP -- the same proof as the signals: no live qemu of it (after a grace of $2
|
|
297
|
+
# seconds), none ended and left unreaped, and the VM manager saying Stopped (or not there, or not
|
|
298
|
+
# answering: then there is nothing more it can do). Asleep, or anything else (Suspending, Running,
|
|
299
|
+
# Unknown...) with no qemu: not gone -- the steps go on, and the check says what is wrong.
|
|
268
300
|
halt_gone() {
|
|
269
|
-
local v="$1" i
|
|
301
|
+
local v="$1" i state
|
|
270
302
|
for i in $(seq 0 "$2"); do [ -z "$(vm_qemu_pids "$v")" ] && break; [ "$i" -lt "$2" ] && sleep 1; done
|
|
271
303
|
[ -z "$(vm_qemu_pids "$v")" ] || return 1
|
|
272
|
-
[ "$(
|
|
304
|
+
[ -z "$(vm_qemu_unreaped "$v")" ] || return 1
|
|
305
|
+
state="$(vm_state_of "$v")"
|
|
306
|
+
[ "$state" = "Stopped" ] || [ "$state" = "absent" ] || [ "$state" = "unknown" ]
|
|
273
307
|
}
|
|
274
308
|
# One step that asks the VM manager, in the background, so that a TERM of this program (the server
|
|
275
309
|
# moving on: "Force now") ends it at once instead of leaving it to run its whole bound.
|
|
276
310
|
HALT_CHILD=""
|
|
277
311
|
halt_run() { local rc=0; "$@" >/dev/null 2>&1 & HALT_CHILD=$!; wait "$HALT_CHILD" || rc=$?; HALT_CHILD=""; return "$rc"; }
|
|
278
|
-
# A signal to its qemu, each process proven first; then waited for, up to $3 seconds
|
|
312
|
+
# A signal to its qemu, each process proven first; then waited for, up to $3 seconds, by each
|
|
313
|
+
# process's own /proc entry (gone, or ended) and by its name again. A FROZEN qemu (stopped: SIGSTOP,
|
|
314
|
+
# or traced) keeps a TERM pending until it runs: it is let run (SIGCONT) right after. A signal
|
|
315
|
+
# refused is said on the error output.
|
|
279
316
|
halt_signal() {
|
|
280
|
-
local v="$1" sig="$2" wait="$3" pid i
|
|
281
|
-
|
|
282
|
-
for
|
|
283
|
-
|
|
317
|
+
local v="$1" sig="$2" wait="$3" pid i st pids left
|
|
318
|
+
pids="$(vm_qemu_pids "$v")"
|
|
319
|
+
for pid in $pids; do
|
|
320
|
+
vm_qemu_is "$pid" "$v" || continue
|
|
321
|
+
st="$(proc_state "$pid")"
|
|
322
|
+
kill "-$sig" "$pid" 2>/dev/null || echo "signal $sig to $pid refused" >&2
|
|
323
|
+
if [[ "$st" == [Tt] ]]; then kill -CONT "$pid" 2>/dev/null || echo "signal CONT to $pid refused" >&2; fi
|
|
324
|
+
done
|
|
325
|
+
for i in $(seq 1 $((wait * 4))); do
|
|
326
|
+
left=""; for pid in $pids; do pid_alive "$pid" && left="$left $pid"; done
|
|
327
|
+
[ -z "$left" ] && [ -z "$(vm_qemu_pids "$v")" ] && return 0
|
|
328
|
+
sleep 0.25
|
|
329
|
+
done
|
|
330
|
+
return 1
|
|
284
331
|
}
|
|
285
332
|
# THE WAY DOWN, from step $2 to step $3 (polite, force, term, kill), then the check. One line per
|
|
286
333
|
# step on the output, for the server and its page:
|
|
@@ -292,6 +339,7 @@ halt_signal() {
|
|
|
292
339
|
halt_steps() {
|
|
293
340
|
local v="$1" from="$2" until="$3" kb s on="no" t rc res grace=0 state
|
|
294
341
|
trap '[ -n "$HALT_CHILD" ] && kill "$HALT_CHILD" 2>/dev/null; exit 143' TERM INT
|
|
342
|
+
vm_qemu_note "$v"
|
|
295
343
|
# shellcheck disable=SC2046
|
|
296
344
|
kb="$(vm_rss_kb $(vm_qemu_pids "$v"))"
|
|
297
345
|
for s in polite force term kill; do
|
|
@@ -299,14 +347,18 @@ halt_steps() {
|
|
|
299
347
|
[ "$on" = "yes" ] || continue
|
|
300
348
|
if halt_gone "$v" "$grace"; then echo "step $s skip 0s gone"; break; fi
|
|
301
349
|
grace=0
|
|
350
|
+
# Nothing alive to signal: said why (a qemu ended but left unreaped: the VM manager is stuck).
|
|
351
|
+
if { [ "$s" = "term" ] || [ "$s" = "kill" ]; } && [ -z "$(vm_qemu_pids "$v")" ]; then
|
|
352
|
+
if [ -n "$(vm_qemu_unreaped "$v")" ]; then echo "step $s skip 0s unreaped"; else echo "step $s skip 0s none"; fi
|
|
353
|
+
[ "$s" = "$until" ] && break; continue
|
|
354
|
+
fi
|
|
302
355
|
echo "step $s start"; t=$SECONDS; rc=0
|
|
303
356
|
case "$s" in
|
|
304
|
-
polite) if [ -z "$(vm_qemu_pids "$v")" ]; then echo "step polite skip 0s asleep"; [ "$s" = "$until" ] && break; continue; fi
|
|
357
|
+
polite) if [ -z "$(vm_qemu_pids "$v")" ] && [ "$(vm_state_of "$v")" = "Suspended" ]; then echo "step polite skip 0s asleep"; [ "$s" = "$until" ] && break; continue; fi
|
|
305
358
|
halt_run timeout "$HALT_POLITE" "$MULTIPASS" stop "$v" || rc=$? ;;
|
|
306
359
|
force) halt_run timeout "$HALT_FORCE" "$MULTIPASS" stop --force "$v" || rc=$? ;;
|
|
307
|
-
term)
|
|
308
|
-
halt_signal "$v" TERM "$HALT_TERM" || rc=124 ;;
|
|
309
|
-
kill) halt_signal "$v" KILL "$HALT_KILL" || rc=124 ;;
|
|
360
|
+
term|kill)
|
|
361
|
+
if [ "$s" = "term" ]; then halt_signal "$v" TERM "$HALT_TERM" || rc=124; else halt_signal "$v" KILL "$HALT_KILL" || rc=124; fi ;;
|
|
310
362
|
esac
|
|
311
363
|
case "$rc" in 0) res="ok"; grace=3 ;; 124) res="timeout" ;; *) res="fail" ;; esac
|
|
312
364
|
echo "step $s $res $((SECONDS - t))s"
|
|
@@ -315,12 +367,13 @@ halt_steps() {
|
|
|
315
367
|
echo "step check start"; t=$SECONDS
|
|
316
368
|
for _ in $(seq 0 "$HALT_SETTLE"); do
|
|
317
369
|
state="$(vm_state_of "$v")"
|
|
318
|
-
[ -z "$(vm_qemu_pids "$v")" ] && [ "$state" = "Stopped" ] && { echo "step check ok $((SECONDS - t))s freed $(gb_of_kb "$kb")"; exit 0; }
|
|
370
|
+
[ -z "$(vm_qemu_pids "$v")" ] && [ -z "$(vm_qemu_unreaped "$v")" ] && [ "$state" = "Stopped" ] && { echo "step check ok $((SECONDS - t))s freed $(gb_of_kb "$kb")"; exit 0; }
|
|
319
371
|
# A VM manager that does not answer is not asked again and again.
|
|
320
372
|
[ "$state" = "unknown" ] && break
|
|
321
373
|
sleep 1
|
|
322
374
|
done
|
|
323
375
|
if [ -n "$(vm_qemu_pids "$v")" ]; then echo "step check fail $((SECONDS - t))s qemu-left freed 0.0G"
|
|
376
|
+
elif [ -n "$(vm_qemu_unreaped "$v")" ]; then echo "step check fail $((SECONDS - t))s qemu-unreaped freed $(gb_of_kb "$kb")"
|
|
324
377
|
elif [ "$state" = "unknown" ]; then echo "step check fail $((SECONDS - t))s mute freed $(gb_of_kb "$kb")"
|
|
325
378
|
else echo "step check fail $((SECONDS - t))s state $state freed $(gb_of_kb "$kb")"; fi
|
|
326
379
|
exit 1
|
|
@@ -892,12 +945,15 @@ case "$AREA $VERB" in
|
|
|
892
945
|
run "$MULTIPASS" exec "$vm" -- "$@" ;;
|
|
893
946
|
"vm ping")
|
|
894
947
|
# Does the VM manager answer at all? Asked now and then by the server
|
|
895
|
-
# (vmwatch.mjs); bounded, so that a VM manager that hangs is an answer
|
|
948
|
+
# (vmwatch.mjs); bounded, so that a VM manager that hangs is an answer:
|
|
949
|
+
# mute for 30 s is mute.
|
|
896
950
|
[ $# -eq 0 ] || usage
|
|
897
|
-
run timeout
|
|
951
|
+
run timeout 30 "$MULTIPASS" list --format csv ;;
|
|
898
952
|
"vm revive")
|
|
899
|
-
# The VM manager has not answered for minutes: its daemon restarted
|
|
900
|
-
#
|
|
953
|
+
# The VM manager has not answered for minutes: its daemon restarted
|
|
954
|
+
# (every machine is suspended and resumed). Asked by the server as its
|
|
955
|
+
# owner chose (vmwatch.mjs: at night, always, or never by itself), at
|
|
956
|
+
# most once in hours; or by its owner, confirmed in Settings, Machines.
|
|
901
957
|
[ $# -eq 0 ] || usage
|
|
902
958
|
run timeout 170 snap restart multipass.multipassd ;;
|
|
903
959
|
"vm states")
|
|
@@ -951,6 +1007,9 @@ case "$AREA $VERB" in
|
|
|
951
1007
|
"if it still does: $MULTIPASS stop $1 (free it; it wakes by a boot)"
|
|
952
1008
|
exit 0
|
|
953
1009
|
fi
|
|
1010
|
+
# FROZEN (its qemu stopped): a suspend would hang the VM manager ("Suspending" for good). Refused
|
|
1011
|
+
# at once: what frees it is Force stop.
|
|
1012
|
+
if vm_qemu_frozen "$1"; then echo "step suspend start"; echo "step suspend fail 0s frozen"; refuse "its qemu is frozen: a suspend would hang the VM manager; use Force stop"; fi
|
|
954
1013
|
# One line per step, as vm halt says them (the server shows them to the page).
|
|
955
1014
|
echo "step suspend start"; t=$SECONDS
|
|
956
1015
|
timeout "$SUSPEND_SECONDS" "$MULTIPASS" suspend "$1" || { echo "step suspend fail $((SECONDS - t))s"; refuse "suspend of $1 failed"; }
|
|
@@ -977,6 +1036,8 @@ case "$AREA $VERB" in
|
|
|
977
1036
|
fi
|
|
978
1037
|
# Each step that frees the RAM says how, so the server can tell the owner.
|
|
979
1038
|
vm_freed "$1" && { echo "freed-already"; exit 0; }
|
|
1039
|
+
# Frozen: waking it and putting it back to sleep would hang the VM manager.
|
|
1040
|
+
vm_qemu_frozen "$1" && refuse "its qemu is frozen: use Force stop"
|
|
980
1041
|
"$MULTIPASS" start "$1" >/dev/null 2>&1 && "$MULTIPASS" suspend "$1" >/dev/null 2>&1
|
|
981
1042
|
vm_freed "$1" && { echo "freed-resleep"; exit 0; }
|
|
982
1043
|
"$MULTIPASS" stop "$1" >/dev/null 2>&1 || true
|
|
@@ -1179,6 +1240,7 @@ OOMScoreAdjust=-900'
|
|
|
1179
1240
|
# place <machines|data|folders> <device> <size MB> <free MB>
|
|
1180
1241
|
# memory <total MB> <available MB>
|
|
1181
1242
|
# machine <one of our VMs> <resident MB>
|
|
1243
|
+
# machineage <one of our VMs> <seconds its qemu has run>
|
|
1182
1244
|
# cpu <total ticks> <idle ticks> <cores> (for the curves: a difference of two looks)
|
|
1183
1245
|
# machinecpu <one of our VMs> <ticks it used>
|
|
1184
1246
|
[ $# -eq 0 ] || usage
|
|
@@ -1197,6 +1259,8 @@ OOMScoreAdjust=-900'
|
|
|
1197
1259
|
[ -n "$vm" ] || continue
|
|
1198
1260
|
rss="$(awk '/^VmRSS:/{print int($2/1024)}' "/proc/$pid/status" 2>/dev/null)" || rss=""
|
|
1199
1261
|
[ -n "$rss" ] && printf 'machine %s %s\n' "$vm" "$rss"
|
|
1262
|
+
age="$(ps -o etimes= -p "$pid" 2>/dev/null | tr -d ' ')" || age=""
|
|
1263
|
+
case "$age" in ''|*[!0-9]*) ;; *) printf 'machineage %s %s\n' "$vm" "$age" ;; esac
|
|
1200
1264
|
ticks="$(awk '{print $14 + $15}' "/proc/$pid/stat" 2>/dev/null)" || ticks=""
|
|
1201
1265
|
[ -n "$ticks" ] && printf 'machinecpu %s %s\n' "$vm" "$ticks"
|
|
1202
1266
|
done
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.391-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.391-next.1",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@xterm/addon-fit": "^0.11.0",
|
package/package.json
CHANGED
package/server/api.mjs
CHANGED
|
@@ -12,7 +12,8 @@
|
|
|
12
12
|
* one at a time (force takes the place of any other; force-now: the next
|
|
13
13
|
* step of the one running) -> its state (202), as below
|
|
14
14
|
* POST /api/conversations/<name>/machine {escalate: true|false}: a stop that hangs goes on to its qemu by itself (default) or asks
|
|
15
|
-
*
|
|
15
|
+
* POST /api/conversations/<name>/machine {watchdog: {on?, delayMin?}}: mute or full that long, its machine is forced off and started, once
|
|
16
|
+
* GET /api/conversations/<name>/machine {action: {kind, since, until, steps: [{id, state, since, s}]} | null, report, limits, escalate, watchdog}
|
|
16
17
|
* POST /api/conversations/<name>/machine/cancel the size kept for its wake, given up
|
|
17
18
|
* GET /api/conversations/<name>/health what was last seen of its machine
|
|
18
19
|
* POST /api/conversations/<name>/health look now (never wakes a machine)
|
|
@@ -123,6 +124,11 @@
|
|
|
123
124
|
* GET /api/history?of=server|<name>&span=1h|24h|7d the curves of memory, CPU and disk (and the reserve, for the server)
|
|
124
125
|
* GET /api/history/all?span=1h|24h|7d Settings, Usage: the server and every machine (asleep too) on one time axis,
|
|
125
126
|
* in GB and cores: {t, capacity, server, itself, machines: [{name, alloc, asleep, ...}]}
|
|
127
|
+
* POST /api/server/pressure {way: force|sleep|alert}: memory short, the machine that takes the most forced off (default), put to sleep, or only said
|
|
128
|
+
* GET /api/server/machines {machines: [{name, state, rssMb, sizeMb, since, action}], manager: {ok, downSince, mode, asked, last, reviving}, pressure}
|
|
129
|
+
* POST /api/server/machines/<name>/force its machine forced off, as from its conversation (202)
|
|
130
|
+
* POST /api/server/vm-manager {mode: night|always|ask}: when it hangs, restarted by itself at night (default), always, or never
|
|
131
|
+
* POST /api/server/vm-manager/restart {confirm: true}: restarted now; every machine is suspended and resumed
|
|
126
132
|
* GET /api/server/logs?source=&span= what the server's programs said POST /api/server/restart POST /api/server/reboot (the whole server)
|
|
127
133
|
* GET /api/operators who may sign in POST /api/operators {email} -> {email, password}: shown once
|
|
128
134
|
* POST /api/operators/<email>/password -> {email, password} POST /api/operators/<email>/disable|enable|remove
|
|
@@ -195,7 +201,7 @@ function readBody(request, max = BODY_MAX) {
|
|
|
195
201
|
/* This run of the server: a page's count of binder changes is of one run, and starts again with the next. */
|
|
196
202
|
const BOOT = Math.random().toString(36).slice(2, 10);
|
|
197
203
|
|
|
198
|
-
export async function handleApi(request, response, conversations, headers, resources, originOk = sameOrigin, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral, tethers, accounts, groups, catalogue, rooms) {
|
|
204
|
+
export async function handleApi(request, response, conversations, headers, resources, originOk = sameOrigin, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral, tethers, accounts, groups, catalogue, rooms, machineList) {
|
|
199
205
|
const { pathname } = new URL(request.url ?? '/', 'http://local');
|
|
200
206
|
if (!pathname.startsWith('/api/')) return false;
|
|
201
207
|
let send = (status, body) => {
|
|
@@ -429,6 +435,8 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
429
435
|
if (pathname === '/api/certificate' && certificate) return send(200, await certificate.about({ fresh: query.get('fresh') === '1' })), true;
|
|
430
436
|
/* This server's disk and memory (capacity.mjs): everything for Settings; only whether it is high for the list. */
|
|
431
437
|
if (pathname === '/api/server' && capacity) return send(200, await capacity.about()), true;
|
|
438
|
+
/* Settings, Machines: each machine, the VM manager, this server's two choices (machinelist.mjs). */
|
|
439
|
+
if (pathname === '/api/server/machines' && machineList) return send(200, await machineList.list()), true;
|
|
432
440
|
if (pathname === '/api/server/brief' && capacity) return send(200, { ...(await capacity.brief()), machines: platform?.machines ?? true }), true;
|
|
433
441
|
if (pathname === '/api/alerts' && alerts) return send(200, alerts.about()), true;
|
|
434
442
|
if (pathname === '/api/flows' && setup) return send(200, setup.graph()), true;
|
|
@@ -590,6 +598,16 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
590
598
|
if (pathname === '/api/updates/settings' && updates) return send(200, await updates.settings({ mode: body.mode, channel: body.channel, window: body.window })), true;
|
|
591
599
|
if (pathname === '/api/updates/apply' && updates) return send(202, await updates.apply(body.version)), true;
|
|
592
600
|
if (pathname === '/api/updates/back' && updates) return send(202, await updates.back(body.version)), true;
|
|
601
|
+
/* Memory short: the machine that takes the most forced off (default), put to sleep, or only said. */
|
|
602
|
+
if (pathname === '/api/server/pressure' && capacity) { capacity.setPressureWay(body.way); return send(200, await capacity.about()), true; }
|
|
603
|
+
/* Settings, Machines: Force stop from the list; the VM manager restarted (confirmed: every machine is resumed); what is done when it hangs. */
|
|
604
|
+
const forcedOf = /^\/api\/server\/machines\/([^/]+)\/force$/.exec(pathname);
|
|
605
|
+
if (forcedOf && machineList) return send(202, await machineList.force(decodeURIComponent(forcedOf[1]))), true;
|
|
606
|
+
if (pathname === '/api/server/vm-manager/restart' && machineList) {
|
|
607
|
+
if (body?.confirm !== true) throw new Refusal(400, 'Restarting the machine manager resumes every machine: confirm it.');
|
|
608
|
+
return send(200, await machineList.revive()), true;
|
|
609
|
+
}
|
|
610
|
+
if (pathname === '/api/server/vm-manager' && machineList) return send(200, await machineList.setManagerMode(body?.mode)), true;
|
|
593
611
|
if (pathname === '/api/server/reserve' && capacity) { capacity.setReserve({ diskMb: body.diskMb, diskPercent: body.diskPercent, memoryMb: body.memoryMb, memoryPercent: body.memoryPercent }); return send(200, await capacity.about()), true; }
|
|
594
612
|
if (pathname === '/api/git-hosts/forget' && gitAccess) return send(200, gitAccess.forgetHost(body.host)), true;
|
|
595
613
|
const unkeyed = /^\/api\/git-keys\/([a-z0-9-]{1,32})\/remove$/.exec(pathname);
|
|
@@ -921,6 +939,8 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
921
939
|
/* One action on its machine, or the owner's choice for its way down (conversations.mjs, machineAction). */
|
|
922
940
|
if (typeof body?.action === 'string') return send(202, await conversations.machineAction(conversation, body.action)), true;
|
|
923
941
|
if (typeof body?.escalate === 'boolean') return send(200, conversations.setStopEscalate(conversation, body.escalate)), true;
|
|
942
|
+
/* Its watchdog (watchdog.mjs): on or off, and how long it waits. */
|
|
943
|
+
if (body?.watchdog && typeof body.watchdog === 'object') return send(200, conversations.setWatchdog(conversation, { on: typeof body.watchdog.on === 'boolean' ? body.watchdog.on : undefined, delayMin: body.watchdog.delayMin })), true;
|
|
924
944
|
const resized = await conversations.resize(conversation, { memoryMb: body.memoryMb, diskGb: body.diskGb, cpus: body.cpus });
|
|
925
945
|
/* Asleep, nothing was started: the choice is only kept, for its wake. */
|
|
926
946
|
return send(resized.phase === 'restarting' ? 202 : 200, resized), true;
|
package/server/capacity.mjs
CHANGED
|
@@ -39,6 +39,8 @@ import { Refusal, DISK_GB } from './conversations.mjs';
|
|
|
39
39
|
import { MIN_FREE_MB } from './shelf.mjs';
|
|
40
40
|
|
|
41
41
|
export const RESERVE_DISK_MB = 5 * 1024;
|
|
42
|
+
/* Short of memory: what is done to the machine that takes the most (pressureWay). */
|
|
43
|
+
export const PRESSURE_WAYS = Object.freeze(['force', 'sleep', 'alert']);
|
|
42
44
|
export const RESERVE_MEMORY_MB = 1024;
|
|
43
45
|
export const RESERVE_DISK_PERCENT = 5;
|
|
44
46
|
export const RESERVE_MEMORY_PERCENT = 5;
|
|
@@ -69,12 +71,13 @@ const whole = (text) => (/^\d{1,12}$/.test(String(text)) ? Number(text) : undefi
|
|
|
69
71
|
|
|
70
72
|
/* What "server room" printed, as facts; any other line is left out. */
|
|
71
73
|
export function readRoom(text) {
|
|
72
|
-
const facts = { places: [], memory: null, machines: [], cpu: null, machineCpu: {} };
|
|
74
|
+
const facts = { places: [], memory: null, machines: [], cpu: null, machineCpu: {}, machineAge: {} };
|
|
73
75
|
for (const line of String(text ?? '').slice(0, 64 * 1024).split('\n').slice(0, 500)) {
|
|
74
76
|
const p = line.trim().split(' ');
|
|
75
77
|
if (p[0] === 'place' && p.length === 5 && PLACES.includes(p[1]) && [2, 3, 4].every((i) => whole(p[i]) !== undefined) && !facts.places.some((x) => x.what === p[1])) facts.places.push({ what: p[1], device: whole(p[2]), sizeMb: whole(p[3]), freeMb: whole(p[4]) });
|
|
76
78
|
if (p[0] === 'memory' && p.length === 3 && whole(p[1]) > 0 && whole(p[2]) !== undefined) facts.memory = { totalMb: whole(p[1]), availableMb: whole(p[2]) };
|
|
77
79
|
if (p[0] === 'cpu' && p.length === 4 && [1, 2, 3].every((i) => whole(p[i]) !== undefined)) facts.cpu = { ticks: whole(p[1]), idle: whole(p[2]), cores: whole(p[3]) };
|
|
80
|
+
if (p[0] === 'machineage' && p.length === 3 && VM.test(p[1]) && whole(p[2]) !== undefined) facts.machineAge[p[1]] = whole(p[2]);
|
|
78
81
|
if (p[0] === 'machinecpu' && p.length === 3 && VM.test(p[1]) && whole(p[2]) !== undefined) facts.machineCpu[p[1]] = whole(p[2]);
|
|
79
82
|
if (p[0] === 'machine' && p.length === 3 && VM.test(p[1]) && whole(p[2]) !== undefined && !facts.machines.some((m) => m.vm === p[1])) facts.machines.push({ vm: p[1], rssMb: whole(p[2]) });
|
|
80
83
|
}
|
|
@@ -99,7 +102,7 @@ const percent = (part, all) => (all > 0 ? Math.round((part / all) * 100) : 0);
|
|
|
99
102
|
export class Capacity {
|
|
100
103
|
/* What the machines take on their disk, as last measured (MB), or undefined. */
|
|
101
104
|
machinesUsedMb() { const u = this.#usage; if (!u) return undefined; return Object.values(u.machines ?? {}).reduce((a, b) => a + b, 0) + (u.shelf ?? 0) + (u.images ?? 0); }
|
|
102
|
-
#run; #store; #conversations; #shelf; #now; #roomMs; #sleep; #alert; #say; #reclaim; #reclaimEveryMs; #sweeping = false; #short = { disk: false, memory: false }; #room = null; #roomAt = -Infinity; #usage = null; #usageAt = -Infinity; #going = null; #measuring = null;
|
|
105
|
+
#run; #store; #conversations; #shelf; #now; #roomMs; #sleep; #force; #alert; #say; #reclaim; #reclaimEveryMs; #sweeping = false; #short = { disk: false, memory: false }; #room = null; #roomAt = -Infinity; #usage = null; #usageAt = -Infinity; #going = null; #measuring = null;
|
|
103
106
|
|
|
104
107
|
/* `run(argv)`: the host program. `store`: where the reserve is kept.
|
|
105
108
|
`conversations`: what each machine was given. `shelf`: how large a
|
|
@@ -107,8 +110,8 @@ export class Capacity {
|
|
|
107
110
|
/* `roomMs`: how long what is free is taken as known (ROOM_MS). */
|
|
108
111
|
/* `sleep(name)`, `alert(payload)`, `say(name, text)`: what watch() does
|
|
109
112
|
when what is free falls under the reserve. */
|
|
110
|
-
constructor({ run, store, conversations, shelf = null, now = () => Date.now(), roomMs = ROOM_MS, sleep = null, alert = null, say = null, reclaim = null, reclaimEveryMs = RECLAIM_EVERY_MS }) {
|
|
111
|
-
this.#roomMs = roomMs; this.#sleep = sleep; this.#alert = alert; this.#say = say; this.#reclaim = reclaim; this.#reclaimEveryMs = reclaimEveryMs;
|
|
113
|
+
constructor({ run, store, conversations, shelf = null, now = () => Date.now(), roomMs = ROOM_MS, sleep = null, force = null, alert = null, say = null, reclaim = null, reclaimEveryMs = RECLAIM_EVERY_MS }) {
|
|
114
|
+
this.#roomMs = roomMs; this.#sleep = sleep; this.#force = force; this.#alert = alert; this.#say = say; this.#reclaim = reclaim; this.#reclaimEveryMs = reclaimEveryMs;
|
|
112
115
|
this.#run = run; this.#store = store; this.#conversations = conversations; this.#shelf = shelf; this.#now = now;
|
|
113
116
|
}
|
|
114
117
|
|
|
@@ -135,6 +138,17 @@ export class Capacity {
|
|
|
135
138
|
return this.reserve();
|
|
136
139
|
}
|
|
137
140
|
|
|
141
|
+
/* SHORT OF MEMORY (under the reserve), WHAT IS DONE to the running machine that takes the most, as
|
|
142
|
+
its owner chose (09-11): forced off ('force', the default: quick, and sure for this server), put
|
|
143
|
+
to sleep ('sleep': keeps its state, but writes all its memory to disk at the worst time; a frozen
|
|
144
|
+
one, which cannot be put to sleep, is forced off), or nothing but the alert ('alert'). */
|
|
145
|
+
pressureWay() { const w = this.#store.get('pressure')?.way; return PRESSURE_WAYS.includes(w) ? w : 'force'; }
|
|
146
|
+
setPressureWay(way) {
|
|
147
|
+
if (!PRESSURE_WAYS.includes(way)) throw new Refusal(400, 'Short of memory, a machine is forced off (force), put to sleep (sleep), or only said (alert).');
|
|
148
|
+
this.#store.put({ name: 'pressure', way });
|
|
149
|
+
return this.pressureWay();
|
|
150
|
+
}
|
|
151
|
+
|
|
138
152
|
/* What is free now. `fresh`: asked again whatever the cache says. */
|
|
139
153
|
async room({ fresh = false } = {}) {
|
|
140
154
|
if (!fresh && this.#room && this.#now() - this.#roomAt < this.#roomMs) return this.#room;
|
|
@@ -168,7 +182,7 @@ export class Capacity {
|
|
|
168
182
|
const records = new Map(all.map((c) => [`clv-${c.name}`, c]));
|
|
169
183
|
const machines = room.machines.map((m) => {
|
|
170
184
|
const c = records.get(m.vm);
|
|
171
|
-
return { name: c ? c.name : null, shelf: m.vm.startsWith('clvshelf-'), rssMb: m.rssMb, sizeMb: c?.memoryMb ?? null };
|
|
185
|
+
return { name: c ? c.name : null, shelf: m.vm.startsWith('clvshelf-'), rssMb: m.rssMb, sizeMb: c?.memoryMb ?? null, ...(room.machineAge?.[m.vm] !== undefined ? { ageS: room.machineAge[m.vm] } : {}) };
|
|
172
186
|
});
|
|
173
187
|
/* What the system says is available: the machines' own use is in it already. */
|
|
174
188
|
const memory = room.memory ? { totalMb: room.memory.totalMb, freeMb: room.memory.availableMb, usedPercent: percent(room.memory.totalMb - room.memory.availableMb, room.memory.totalMb) } : null;
|
|
@@ -215,7 +229,7 @@ export class Capacity {
|
|
|
215
229
|
machines: { disksMb: Object.values(u.machines).reduce((a, b) => a + b, 0), each: Object.entries(u.machines).map(([name, mb]) => ({ name, mb })).sort((a, b) => b.mb - a.mb), shelfMb: u.shelf ?? null, imagesMb: u.images ?? null, othersMb: u.others ?? null },
|
|
216
230
|
at: new Date(this.#usageAt).toISOString(),
|
|
217
231
|
} : null;
|
|
218
|
-
return { known: Boolean(figures), reserve: { diskMb: this.reserve().diskMb, memoryMb: this.reserve().memoryMb }, settings: this.reserve(), ...(figures ?? {}), usage, measuring: Boolean(this.#measuring) };
|
|
232
|
+
return { known: Boolean(figures), reserve: { diskMb: this.reserve().diskMb, memoryMb: this.reserve().memoryMb }, settings: this.reserve(), pressure: this.pressureWay(), ...(figures ?? {}), usage, measuring: Boolean(this.#measuring) };
|
|
219
233
|
}
|
|
220
234
|
|
|
221
235
|
/* For the list: only whether it is high, and how much. Cheap: what is
|
|
@@ -285,12 +299,21 @@ export class Capacity {
|
|
|
285
299
|
const running = f.machines.filter((m) => m.name && awake.has(m.name));
|
|
286
300
|
const takes = (m) => (what === 'disk' ? this.#usage?.machines?.[m.name] ?? -1 : m.rssMb);
|
|
287
301
|
const most = running.sort((a, b) => takes(b) - takes(a) || b.rssMb - a.rssMb)[0] ?? null;
|
|
288
|
-
let slept = null;
|
|
289
|
-
|
|
302
|
+
let slept = null; let frozen = null; let forced = null; let held = null;
|
|
303
|
+
/* Memory: as its owner chose (pressureWay). Disk: put to sleep, as before. */
|
|
304
|
+
const way = what === 'memory' ? this.pressureWay() : 'sleep';
|
|
305
|
+
if (most && way === 'alert') held = most.name;
|
|
306
|
+
if (most && way === 'force' && this.#force) forced = await Promise.resolve(this.#force(most.name)).then((ok) => (ok === false ? null : most.name), () => null);
|
|
307
|
+
if (most && way === 'sleep' && this.#sleep) slept = await Promise.resolve(this.#sleep(most.name)).then(() => most.name, (error) => { if (/frozen/.test(String(error?.message ?? ''))) frozen = most.name; return null; });
|
|
308
|
+
/* Frozen: never suspended (it would hang the VM manager); forced off instead. */
|
|
309
|
+
if (frozen && this.#force) forced = await Promise.resolve(this.#force(frozen)).then((ok) => (ok === false ? null : frozen), () => null);
|
|
290
310
|
const figures = `${gb(free)} free, ${gb(f.reserve[`${what}Mb`])} kept in reserve`;
|
|
291
|
-
|
|
311
|
+
const did = slept ? ` ${slept} was put to sleep.` : forced ? ` ${forced} was forced off${frozen ? ' (frozen)' : ''}.` : frozen ? ` ${frozen} takes the most but is frozen: Force stop frees it.` : held ? ` ${held} takes the most: nothing was done, as you chose.` : '';
|
|
312
|
+
this.#alert?.({ title: `This server is short of ${what}`, body: `${figures}.${did}`, url: '/?open=settings&at=resources' });
|
|
292
313
|
if (slept) this.#say?.(slept, `This server ran short of ${what} (${figures}). This machine took the most, so it was put to sleep. Wake it once there is room again.`);
|
|
293
|
-
|
|
314
|
+
if (forced) this.#say?.(forced, `This server ran short of ${what} (${figures}). This machine took the most${frozen ? ' and was frozen' : ''}, so it was forced off, as after a power cut. Start it again once there is room.`);
|
|
315
|
+
else if (frozen) this.#say?.(frozen, `This server ran short of ${what} (${figures}). This machine took the most but is frozen: it could not be put to sleep. Force stop frees it.`);
|
|
316
|
+
done.push({ what, way, slept, ...(forced ? { forced } : {}), ...(frozen ? { frozen } : {}), ...(held ? { held } : {}) });
|
|
294
317
|
}
|
|
295
318
|
return done;
|
|
296
319
|
}
|
package/server/conversations.mjs
CHANGED
|
@@ -66,6 +66,12 @@ const DOWN = ['polite', 'force', 'term', 'kill', 'check'];
|
|
|
66
66
|
const NEXT = Object.freeze({ polite: 'force', force: 'term', term: 'kill' });
|
|
67
67
|
/* Each step in words, for the journal and the chat (the page has its own, web/app.js). */
|
|
68
68
|
const STEP_WORDS = Object.freeze({ polite: 'polite stop', force: 'forced stop', term: 'SIGTERM', kill: 'SIGKILL', check: 'check', start: 'start', suspend: 'sleep', resleep: 'wake and sleep again', stop: 'clean stop' });
|
|
69
|
+
const KIND_DOING = Object.freeze({ start: 'starting', stop: 'stopping', restart: 'restarting', sleep: 'going to sleep', force: 'being forced off', resize: 'being resized' });
|
|
70
|
+
/* THE WATCHDOG of a machine (watchdog.mjs), as its owner set it: on, with how long it may stay mute or
|
|
71
|
+
full before it is forced off and started again. The defaults, and what may be chosen (minutes). */
|
|
72
|
+
export const WATCHDOG_DELAY_MIN = 60;
|
|
73
|
+
export const WATCHDOG_MIN = 10;
|
|
74
|
+
export const WATCHDOG_MAX = 24 * 60;
|
|
69
75
|
const KIND_WORDS = Object.freeze({ start: ['Started', 'Not started'], stop: ['Stopped', 'Not stopped'], restart: ['Restarted', 'Not restarted'], sleep: ['Asleep', 'Not asleep'], force: ['Stopped by force', 'Not stopped by force'], resize: ['Resized', 'Not resized'] });
|
|
70
76
|
|
|
71
77
|
export class Refusal extends Error {
|
|
@@ -1006,7 +1012,7 @@ export class Conversations {
|
|
|
1006
1012
|
if (!c) throw new Refusal(404, 'No such conversation.');
|
|
1007
1013
|
if (c.phase !== 'ready') throw new Refusal(409, c.phase === 'restarting' ? 'Its machine is being restarted already.' : c.phase === 'moving' ? 'It is moving its work folder.' : 'This conversation is not ready.');
|
|
1008
1014
|
if (this.#resizing.has(name)) throw new Refusal(409, 'Its machine is being given its new size as it wakes.', { retry: true });
|
|
1009
|
-
if (this.#acts.has(name)) throw
|
|
1015
|
+
if (this.#acts.has(name)) throw this.#busy(name);
|
|
1010
1016
|
return c;
|
|
1011
1017
|
}
|
|
1012
1018
|
|
|
@@ -1297,7 +1303,7 @@ export class Conversations {
|
|
|
1297
1303
|
Resolves once asleep; throws, in words, when it could not be. */
|
|
1298
1304
|
async sleep(name) {
|
|
1299
1305
|
if (!this.#store.get(name)) throw new Refusal(404, 'No such conversation.');
|
|
1300
|
-
if (this.#acts.has(name)) throw
|
|
1306
|
+
if (this.#acts.has(name)) throw this.#busy(name);
|
|
1301
1307
|
const act = this.#take(name, 'sleep');
|
|
1302
1308
|
const report = await this.#perform(name, act);
|
|
1303
1309
|
if (!report.ok) throw new Refusal(502, `The machine did not go to sleep: ${report.why ?? 'it did not answer.'}`);
|
|
@@ -1313,6 +1319,12 @@ export class Conversations {
|
|
|
1313
1319
|
this.#acts.set(name, act);
|
|
1314
1320
|
return act;
|
|
1315
1321
|
}
|
|
1322
|
+
/* Refused while another action runs: which one, since when, and what can be done. */
|
|
1323
|
+
#busy(name) {
|
|
1324
|
+
const act = this.#acts.get(name);
|
|
1325
|
+
const s = act ? Math.max(0, Math.round((Date.now() - Date.parse(act.since)) / 1000)) : 0;
|
|
1326
|
+
return new Refusal(409, `Its machine is busy: ${KIND_DOING[act?.kind] ?? 'another action'} for ${s} s. Wait, or force it off.`, { retry: true });
|
|
1327
|
+
}
|
|
1316
1328
|
#give(name, act) { if (this.#acts.get(name) === act) this.#acts.delete(name); act.finish(); }
|
|
1317
1329
|
/* The steps the page shows, in order: done, running, to come (`todo`). */
|
|
1318
1330
|
#plan(name, act, ids) {
|
|
@@ -1382,12 +1394,14 @@ export class Conversations {
|
|
|
1382
1394
|
to its next step). Answers at once with what the page reads (machineState); the action goes
|
|
1383
1395
|
on, its steps on the record (`machine`), its report kept after it (`machineReport`), said in
|
|
1384
1396
|
the journal and in its chat. `this.acted`: its end, for whoever waits for it. */
|
|
1385
|
-
|
|
1397
|
+
/* `wait`: resolves with its report instead, once it is done (the watchdog, the memory watch, the
|
|
1398
|
+
server's list: callers that act on it, so that no other action's end is taken for theirs). */
|
|
1399
|
+
async machineAction(name, kind, { wait = false } = {}) {
|
|
1386
1400
|
const c = this.#store.get(name);
|
|
1387
1401
|
if (!c) throw new Refusal(404, 'No such conversation.');
|
|
1388
1402
|
if (kind === 'force-now') return this.#forceNow(name);
|
|
1389
1403
|
if (!MACHINE_KINDS.includes(kind)) throw new Refusal(400, 'Not an action of a machine.');
|
|
1390
|
-
if (kind === 'restart') { await this.restart(name);
|
|
1404
|
+
if (kind === 'restart') { await this.restart(name); const done = this.restarted; this.acted = done; return wait ? done : this.machineState(name); }
|
|
1391
1405
|
const running = this.#acts.get(name);
|
|
1392
1406
|
if (kind !== 'force') this.#busyCheck(name);
|
|
1393
1407
|
else {
|
|
@@ -1396,10 +1410,11 @@ export class Conversations {
|
|
|
1396
1410
|
}
|
|
1397
1411
|
if (kind === 'start' && (c.asleep !== true && (await this.#vms.state(name).catch(() => undefined)) === 'Running')) throw new Refusal(409, 'Its machine runs already.');
|
|
1398
1412
|
if (kind === 'start') await this.room({ kind: 'start', name, memoryMb: c.memoryMb });
|
|
1399
|
-
if (this.#acts.has(name)) throw
|
|
1413
|
+
if (this.#acts.has(name)) throw this.#busy(name);
|
|
1400
1414
|
const act = this.#take(name, kind);
|
|
1401
|
-
|
|
1402
|
-
|
|
1415
|
+
const done = this.#perform(name, act);
|
|
1416
|
+
this.acted = done;
|
|
1417
|
+
return wait ? done : this.machineState(name);
|
|
1403
1418
|
}
|
|
1404
1419
|
|
|
1405
1420
|
/* "FORCE NOW": the step running is ended and the next one started (polite -> forced -> SIGTERM ->
|
|
@@ -1425,7 +1440,25 @@ export class Conversations {
|
|
|
1425
1440
|
machineState(name) {
|
|
1426
1441
|
const c = this.#store.get(name);
|
|
1427
1442
|
if (!c) throw new Refusal(404, 'No such conversation.');
|
|
1428
|
-
return { action: c.machine ?? null, report: c.machineReport ?? null, limits: STEP_LIMITS, escalate: c.stopEscalate !== false };
|
|
1443
|
+
return { action: c.machine ?? null, report: c.machineReport ?? null, limits: STEP_LIMITS, escalate: c.stopEscalate !== false, watchdog: this.watchdog(name) };
|
|
1444
|
+
}
|
|
1445
|
+
|
|
1446
|
+
/* ITS WATCHDOG, as its owner set it (a default, changed per conversation): on, and how long its
|
|
1447
|
+
machine may stay mute or full before it is forced off and started again (watchdog.mjs). */
|
|
1448
|
+
watchdog(name) {
|
|
1449
|
+
const w = this.#store.get(name)?.watchdog;
|
|
1450
|
+
return { on: w?.on !== false, delayMin: Number.isInteger(w?.delayMin) ? w.delayMin : WATCHDOG_DELAY_MIN };
|
|
1451
|
+
}
|
|
1452
|
+
setWatchdog(name, { on, delayMin } = {}) {
|
|
1453
|
+
if (!this.#store.get(name)) throw new Refusal(404, 'No such conversation.');
|
|
1454
|
+
const now = this.watchdog(name);
|
|
1455
|
+
const minutes = delayMin === undefined ? now.delayMin : delayMin;
|
|
1456
|
+
if (!Number.isInteger(minutes) || minutes < WATCHDOG_MIN || minutes > WATCHDOG_MAX) throw new Refusal(400, `The watchdog waits ${WATCHDOG_MIN} to ${WATCHDOG_MAX} minutes.`);
|
|
1457
|
+
const next = { on: on === undefined ? now.on : on !== false, delayMin: minutes };
|
|
1458
|
+
/* Kept only where it differs from the default. */
|
|
1459
|
+
const kept = { ...(next.on ? {} : { on: false }), ...(next.delayMin === WATCHDOG_DELAY_MIN ? {} : { delayMin: next.delayMin }) };
|
|
1460
|
+
this.#store.patch(name, { watchdog: Object.keys(kept).length ? kept : undefined });
|
|
1461
|
+
return this.machineState(name);
|
|
1429
1462
|
}
|
|
1430
1463
|
|
|
1431
1464
|
/* THE WAY DOWN, AS ITS OWNER CHOSE (a default, changed per conversation): on (the default), a stop
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/* SETTINGS, MACHINES (09-11): every conversation's machine at a glance -- its state, the memory its
|
|
2
|
+
* qemu holds on this server, and since when -- each one forced off from there; then the VM manager
|
|
3
|
+
* (does it answer, restarted by its owner) and the two choices of this server: what is done when the
|
|
4
|
+
* VM manager hangs (vmwatch.mjs) and when memory is short (capacity.mjs).
|
|
5
|
+
*
|
|
6
|
+
* Nothing here asks a machine anything: the states come in one question to the VM manager (shared with
|
|
7
|
+
* every caller for a few seconds), the memory from the host's own figures. A VM manager that does not
|
|
8
|
+
* answer gives "Unknown" for each, never "gone".
|
|
9
|
+
*/
|
|
10
|
+
import { Refusal } from './conversations.mjs';
|
|
11
|
+
|
|
12
|
+
export class MachineList {
|
|
13
|
+
#conversations; #vms; #capacity; #vmWatch; #now;
|
|
14
|
+
constructor({ conversations, vms, capacity, vmWatch, now = () => Date.now() }) {
|
|
15
|
+
this.#conversations = conversations; this.#vms = vms; this.#capacity = capacity; this.#vmWatch = vmWatch; this.#now = now;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/* { machines: [{ name, state, rssMb, sizeMb, since, action }], manager, pressure }. `since`: when its qemu
|
|
19
|
+
started (running, or asleep and still holding memory), else when it was last stopped or put to
|
|
20
|
+
sleep here, else null. */
|
|
21
|
+
async list() {
|
|
22
|
+
const states = await this.#vms.states().catch(() => null);
|
|
23
|
+
const room = await this.#capacity?.room().catch(() => null) ?? null;
|
|
24
|
+
const held = new Map((room?.machines ?? []).map((m) => [m.vm, m]));
|
|
25
|
+
const machines = this.#conversations.list().filter((c) => c.phase === 'ready').map((c) => {
|
|
26
|
+
const vm = `clv-${c.name}`;
|
|
27
|
+
const state = states ? (states.get(vm) ?? 'Gone') : 'Unknown';
|
|
28
|
+
const rssMb = held.get(vm)?.rssMb ?? 0;
|
|
29
|
+
const age = room?.machineAge?.[vm];
|
|
30
|
+
const report = c.machineReport;
|
|
31
|
+
const ended = report?.ok && ((state === 'Stopped' && ['stop', 'force'].includes(report.kind)) || (state === 'Suspended' && report.kind === 'sleep')) ? report.at : null;
|
|
32
|
+
const since = age !== undefined && rssMb > 0 ? new Date(this.#now() - age * 1000).toISOString() : ended;
|
|
33
|
+
return { name: c.name, state, rssMb, sizeMb: c.memoryMb ?? null, since, action: c.machine?.kind ?? null };
|
|
34
|
+
}).sort((a, b) => b.rssMb - a.rssMb || a.name.localeCompare(b.name));
|
|
35
|
+
return { machines, manager: this.#vmWatch?.about() ?? null, pressure: this.#capacity?.pressureWay() ?? null };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/* "Force stop" from the list: the same as from its conversation (one lock per machine). */
|
|
39
|
+
async force(name) {
|
|
40
|
+
if (!this.#conversations.get(name)) throw new Refusal(404, 'No such conversation.');
|
|
41
|
+
await this.#conversations.machineAction(name, 'force');
|
|
42
|
+
return this.list();
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/* "Restart the manager", confirmed in the page: every machine is suspended and resumed. */
|
|
46
|
+
async revive() {
|
|
47
|
+
if (!this.#vmWatch) throw new Refusal(404, 'No machine manager here.');
|
|
48
|
+
try { await this.#vmWatch.revive(); } catch (error) { throw new Refusal(error.status ?? 500, error.message); }
|
|
49
|
+
return this.list();
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
setManagerMode(mode) {
|
|
53
|
+
try { this.#vmWatch?.setMode(mode); } catch (error) { throw new Refusal(error.status ?? 400, error.message); }
|
|
54
|
+
return this.list();
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
setPressure(way) { this.#capacity?.setPressureWay(way); return this.list(); }
|
|
58
|
+
}
|
package/server/main.mjs
CHANGED
|
@@ -81,6 +81,8 @@ import { Events } from './events.mjs';
|
|
|
81
81
|
import { Bundles } from './bundle.mjs';
|
|
82
82
|
import { migrateData } from './dataformat.mjs';
|
|
83
83
|
import { VmWatch } from './vmwatch.mjs';
|
|
84
|
+
import { Watchdog } from './watchdog.mjs';
|
|
85
|
+
import { MachineList } from './machinelist.mjs';
|
|
84
86
|
import { WakeLearn } from './wakelearn.mjs';
|
|
85
87
|
import { BoxCollect } from './boxcollect.mjs';
|
|
86
88
|
import { Boxes, handleBoxes, voiceboxConnector, syncTargets, PAIR_PATH as BOX_PAIR_PATH, FIRMWARE_PATH as BOX_FIRMWARE_PATH } from './boxes.mjs';
|
|
@@ -186,7 +188,7 @@ const withoutTmux = (env) => Object.fromEntries(Object.entries(env).filter(([key
|
|
|
186
188
|
|
|
187
189
|
const REFUSED = 'This Clavarium belongs to someone else: your account is not one of its operators.\n';
|
|
188
190
|
|
|
189
|
-
function serve(port, conversations, resources, { gate = () => 'local', originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, repair, capacity, updates, instance = new Instance(), certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral, tethers, accounts, groups, boxes, catalogue, rooms, features, apikeys, relayJoin } = {}) {
|
|
191
|
+
function serve(port, conversations, resources, { gate = () => 'local', originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, repair, capacity, updates, instance = new Instance(), certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral, tethers, accounts, groups, boxes, catalogue, rooms, machineList, features, apikeys, relayJoin } = {}) {
|
|
190
192
|
/* Its manifest carries the name of this Clavarium, or the one a device chose (instance.mjs). */
|
|
191
193
|
const sendManifest = (response, url) => response.writeHead(200, { ...HEADERS, 'content-type': 'application/manifest+json' }).end(instance.manifest(new URL(url ?? '/', 'http://local').searchParams.get('name') ?? undefined));
|
|
192
194
|
const sendFile = async (response, file) => {
|
|
@@ -261,7 +263,7 @@ function serve(port, conversations, resources, { gate = () => 'local', originOk,
|
|
|
261
263
|
/* Settings, Access, API keys: made and revoked by an administrator only (past the gate). */
|
|
262
264
|
if (apikeys && pathname.startsWith('/api/apikeys') && await handleApiKeys(request, response, apikeys.keys, originOk, HEADERS, events)) return;
|
|
263
265
|
if (boxes && pathname.startsWith('/api/boxes') && await handleBoxes(request, response, boxes, originOk, HEADERS, (text) => QRCode.toString(text, { type: 'svg', margin: 1, errorCorrectionLevel: 'M' }))) return;
|
|
264
|
-
if (conversations && await handleApi(request, response, conversations, HEADERS, resources, originOk, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral, tethers, accounts, groups, catalogue, rooms)) return;
|
|
266
|
+
if (conversations && await handleApi(request, response, conversations, HEADERS, resources, originOk, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral, tethers, accounts, groups, catalogue, rooms, machineList)) return;
|
|
265
267
|
if (pathname === '/manifest.webmanifest' && request.method === 'GET') { sendManifest(response, request.url); return; }
|
|
266
268
|
const file = FILES[pathname];
|
|
267
269
|
if (!file || (request.method !== 'GET' && request.method !== 'HEAD')) {
|
|
@@ -520,7 +522,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
520
522
|
const gitTimer = gitKeeper.start(gitEveryMs);
|
|
521
523
|
/* A conversation with a tool on a screen that is not its terminal: see talk.mjs. */
|
|
522
524
|
/* Voice boxes: what the tool says in their conversation is read aloud (boxes.mjs). */
|
|
523
|
-
let boxes; let rooms;
|
|
525
|
+
let boxes; let rooms; let machineList;
|
|
524
526
|
const talk = new Talk({ spoke: (name, text, to, how) => { void boxes?.agentSaid(name, text, to, how); }, inRoom: (name, entry, kind) => rooms?.answered(name, entry, kind), store: talkStore, words: new Store(`${dataDir}/talk-words.json`), keptDir: `${dataDir}/talk-kept`, vms, conversations: all, resources: folders, toolbox, warm: (name) => bridge?.warm(name), ...(talkEveryMs ? { listenEveryMs: talkEveryMs } : {}),
|
|
525
527
|
...(rereadAfterMs === undefined ? {} : { rereadAfterMs }),
|
|
526
528
|
/* A line typed down the terminal already open when there is one, and
|
|
@@ -607,10 +609,22 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
607
609
|
/* Where its chat is on, its agent is given an event when its disk or memory crosses a level (healthdocket.mjs);
|
|
608
610
|
not where its owner turned on its own reaction (above): one way of telling it, not two. */
|
|
609
611
|
const healthDocket = new HealthDocket({ store: new Store(`${dataDir}/health-docket.json`), dockets, reacting: (name) => reacting.settings(name).on });
|
|
610
|
-
health.forgotten = (name) => healthDocket.forget(name);
|
|
612
|
+
health.forgotten = (name) => { healthDocket.forget(name); watchdog.forget(name); };
|
|
611
613
|
/* A machine's problems worth keeping in What happened: said once, until they went away. */
|
|
612
614
|
const problemsSaid = new Map();
|
|
615
|
+
/* ITS WATCHDOG (watchdog.mjs): mute or full for as long as its owner set, forced off then started, once;
|
|
616
|
+
its AI told in its chat, its owner alerted with the report. */
|
|
617
|
+
const watchdog = new Watchdog({ conversations: all, store: new Store(`${dataDir}/watchdog.json`),
|
|
618
|
+
act: async (name) => {
|
|
619
|
+
events.add({ kind: 'machine', text: `Machine of ${name}: mute or full for too long, forced off and started by its watchdog`, conversation: name });
|
|
620
|
+
const forced = await all.machineAction(name, 'force', { wait: true });
|
|
621
|
+
if (!forced?.ok) return forced;
|
|
622
|
+
return all.machineAction(name, 'start', { wait: true });
|
|
623
|
+
},
|
|
624
|
+
tell: (name, text, started) => all.renewed(name, text, started),
|
|
625
|
+
alert: (payload) => { events.add({ kind: 'machine', text: `${payload.title}: ${payload.body ?? ''}`.trim() }); void alerts.tell(payload)?.catch?.(() => {}); } });
|
|
613
626
|
health.judged = (name, record) => {
|
|
627
|
+
void watchdog.judged(name, record).catch(() => {});
|
|
614
628
|
talk.machine(name, record); void reacting.judged(name, record).catch(() => {});
|
|
615
629
|
/* A folder that came loose and was put back: said once, in its chat (the look that put it back). */
|
|
616
630
|
for (const path of record?.remounted ?? []) { try { talk.event(name, { kind: 'machine-ok', text: `Le dossier ${path} s'était détaché de la machine : il a été remonté.`, topic: 'Machine', brief: 'Shared folder' }); } catch { /* its chat is off */ } }
|
|
@@ -640,7 +654,9 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
640
654
|
/* This server's disk and memory, and the reserve no machine may eat into: see capacity.mjs. */
|
|
641
655
|
const capacity = new Capacity({ run: asHost, store: new Store(`${dataDir}/server.json`), conversations: all, shelf, ...(serverRoomMs === undefined ? {} : { roomMs: serverRoomMs }),
|
|
642
656
|
/* Under the reserve: the machine that takes the most put to sleep, the owner told, and its chat. */
|
|
643
|
-
sleep: (name) => { events.add({ kind: 'machine', text: `Machine of ${name} put to sleep: this server was short of room`, conversation: name }); return all.sleep(name); },
|
|
657
|
+
sleep: (name) => { events.add({ kind: 'machine', text: `Machine of ${name} put to sleep: this server was short of room`, conversation: name }); return all.sleep(name); },
|
|
658
|
+
/* Memory short, forced off (capacity.mjs, pressureWay: the default), or frozen and so not put to sleep: through the one lock of its machine. */
|
|
659
|
+
force: async (name) => { events.add({ kind: 'machine', text: `Machine of ${name} forced off: this server was short of memory`, conversation: name }); return (await all.machineAction(name, 'force', { wait: true }))?.ok === true; }, alert: (payload) => { events.add({ kind: 'server', text: `${payload.title}: ${payload.body ?? ''}`.trim() }); void alerts.tell(payload); },
|
|
644
660
|
/* A machine asleep but still holding its RAM (a suspend that did not free it): its memory reclaimed, only that machine touched. */
|
|
645
661
|
reclaim: (name) => { events.add({ kind: 'machine', text: `Machine of ${name}: memory reclaimed (it was asleep but still held RAM)`, conversation: name }); return vms.reclaim(name).then((r) => (r.stdout || '').trim()); },
|
|
646
662
|
say: (name, text) => { try { talk.event(name, { kind: 'machine-problem', text, tone: 'warn', topic: 'Machine' }); } catch { /* its chat may be off */ } } });
|
|
@@ -655,6 +671,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
655
671
|
try { talk.event(name, { kind: 'machine-problem', text, tone: 'warn', topic: 'Machine', brief: 'Out of memory', actions: ['memory', 'restart', 'terminal'] }); } catch { /* its chat may be off */ }
|
|
656
672
|
};
|
|
657
673
|
const stopWatch = capacity.start();
|
|
674
|
+
/* Settings, Machines: each machine, the VM manager, this server's choices (machinelist.mjs). */
|
|
675
|
+
machineList = new MachineList({ conversations: all, vms, capacity, vmWatch });
|
|
658
676
|
/* The curves of the resources (history.mjs): one look a minute, from what the server knows already. */
|
|
659
677
|
const history = new History({ file: `${dataDir}/history.json` });
|
|
660
678
|
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(() => {});
|
|
@@ -799,7 +817,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
799
817
|
answerer: answererConfig(env)?.models.length ?? 0, updates: updates.about(), team: team ? team.list().length : null,
|
|
800
818
|
screen: await quick(screenNow(), 1500, null), catalogue: await quick(catalogue.providers().catch(() => []), 1500, []),
|
|
801
819
|
}) });
|
|
802
|
-
const { server, listening } = serve(port, all, folders, { gate, originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, wifi, binders, meshcentral, tethers, accounts, groups, boxes, catalogue, rooms, features, apikeys, relayJoin: host.length ? new RelayJoin({ host: asHost }) : null, bundles: new Bundles({ dir: `${dataDir}/imports`, folder: (name) => folders.folder(name) }), repair: (name) => repairTerminal(name) });
|
|
820
|
+
const { server, listening } = serve(port, all, folders, { gate, originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, wifi, binders, meshcentral, tethers, accounts, groups, boxes, catalogue, rooms, machineList, features, apikeys, relayJoin: host.length ? new RelayJoin({ host: asHost }) : null, bundles: new Bundles({ dir: `${dataDir}/imports`, folder: (name) => folders.folder(name) }), repair: (name) => repairTerminal(name) });
|
|
803
821
|
server.on('close', () => { closing = true; stopBinders(); stopTethers(); clearInterval(historyTimer); clearInterval(secretsTimer); history.save(); stopVmWatch(); stopShelf(); stopHealth(); stopNetworkWatch(); stopUpdates(); stopWatch(); clearInterval(mailTimer); clearInterval(restartTimer); clearInterval(expiryTimer); clearInterval(answerTimer); clearInterval(wakeTimer); clearInterval(docketTimer); dockets.stop(); clearInterval(gitTimer); talk.stop(); });
|
|
804
822
|
let closing = false;
|
|
805
823
|
boxes.attach(server, WebSocketServer);
|
package/server/settingswords.mjs
CHANGED
|
@@ -253,5 +253,18 @@ export const SETTINGS_WORDS_FR = {
|
|
|
253
253
|
'set-mrep-freed': '{gb} Go rendus', 'set-mrep-replaced': 'Remplacée par Forcer l’arrêt',
|
|
254
254
|
'set-mt-stop': 'Arrêt de sa machine', 'set-mt-force': 'Arrêt forcé de sa machine', 'set-mt-sleep': 'Mise en veille', 'set-mt-start': 'Démarrage de sa machine',
|
|
255
255
|
'set-stopped-page': 'Arrêtée. Elle démarre quand vous la démarrez.',
|
|
256
|
+
/* Its watchdog (watchdog.mjs, 09-11). */
|
|
257
|
+
'set-mdog': 'Chien de garde', 'set-mdog-what': 'La redémarre si elle bloque', 'set-mdog-off': 'Désactivé', 'set-mdog-custom': 'Autre',
|
|
258
|
+
/* Settings, Machines (machinelist.mjs, 09-11): the list, the machine manager, the server's two choices. */
|
|
259
|
+
'set-ch-s-machines': 'Machines', 'set-ml-about': 'État et mémoire.', 'set-ml-none': 'Aucune machine',
|
|
260
|
+
'set-ml-now': '{n} en marche sur {all}', 'set-ml-since': 'depuis {t}', 'set-ml-busy': 'Occupée',
|
|
261
|
+
'set-ml-running': 'En marche', 'set-ml-asleep': 'Endormie', 'set-ml-stopped': 'Arrêtée', 'set-ml-starting': 'Démarre',
|
|
262
|
+
'set-ml-stopping': 'S’arrête', 'set-ml-unknown': 'Inconnu', 'set-ml-gone': 'Disparue',
|
|
263
|
+
'set-ml-manager': 'Gestionnaire de machines', 'set-ml-revive': 'Redémarrer le gestionnaire', 'set-ml-revive-yes': 'Redémarrer',
|
|
264
|
+
'set-ml-revive-q': 'Redémarrer ? Toutes les machines sont reprises.', 'set-ml-reviving': 'Redémarrage…',
|
|
265
|
+
'set-ml-answers': 'Répond', 'set-ml-last': 'redémarré {t}', 'set-ml-mute': 'Ne répond pas', 'set-ml-asked': 'attend votre accord',
|
|
266
|
+
'set-ml-force-q': 'Forcer l’arrêt de {name} ? Rien n’est sauvé.',
|
|
267
|
+
'set-ml-hang': 'S’il bloque', 'set-ml-hang-what': 'Nuit : de 0 h à 7 h', 'set-ml-night': 'La nuit', 'set-ml-always': 'Toujours', 'set-ml-ask': 'Me demander',
|
|
268
|
+
'set-ml-short': 'Manque de mémoire', 'set-ml-short-what': 'La plus grosse machine', 'set-ml-force': 'Forcer l’arrêt', 'set-ml-sleep': 'Mettre en veille', 'set-ml-alert': 'Alerter seulement',
|
|
256
269
|
};
|
|
257
270
|
export const settingsWords = (lang) => (String(lang ?? '').toLowerCase().split('-')[0] === 'fr' ? { ...SETTINGS_WORDS_FR } : {});
|
package/server/vm.mjs
CHANGED
|
@@ -136,6 +136,13 @@ export class Vms {
|
|
|
136
136
|
return [...this.prefix, 'vm', 'exec', vmName(conversation), '--', ...argv];
|
|
137
137
|
}
|
|
138
138
|
|
|
139
|
+
/* Every machine's state, by VM name (a Map); throws VmUnknown when the VM manager did not answer. */
|
|
140
|
+
async states({ fresh = false } = {}) {
|
|
141
|
+
const snap = await this.#states(fresh);
|
|
142
|
+
if (!snap.states) throw new VmUnknown(snap.why);
|
|
143
|
+
return new Map(snap.states);
|
|
144
|
+
}
|
|
145
|
+
|
|
139
146
|
/* "Running", "Stopped", "Suspended", ... or undefined when there is no VM. */
|
|
140
147
|
/* Its state, or undefined when the VM manager lists every machine and not this one. A VM
|
|
141
148
|
manager that does not answer (busy, timed out, restarting) says nothing of the machine:
|
package/server/vmwatch.mjs
CHANGED
|
@@ -1,56 +1,115 @@
|
|
|
1
1
|
/* THE VM MANAGER, WATCHED. Every machine goes through it; when it stops
|
|
2
2
|
* answering, nothing about a machine can be done, while this server itself
|
|
3
3
|
* must go on serving its pages. So it is asked now and then (host program:
|
|
4
|
-
* `vm ping`, bounded), and:
|
|
4
|
+
* `vm ping`: `multipass list`, bounded to 30 s), and:
|
|
5
5
|
* - while it does not answer, `ok` is false: the pages say "the machines
|
|
6
6
|
* cannot be reached just now";
|
|
7
|
-
* - when it has not answered for STUCK_MS
|
|
8
|
-
* (
|
|
9
|
-
*
|
|
7
|
+
* - when it has not answered for STUCK_MS it is HUNG, and its owner's
|
|
8
|
+
* choice (`mode`, kept here) says what is done (09-11):
|
|
9
|
+
* night (the default) its daemon restarted by itself only between
|
|
10
|
+
* NIGHT_FROM and NIGHT_UNTIL, this server's local time; by day
|
|
11
|
+
* its owner is alerted and asked (Settings, Machines);
|
|
12
|
+
* always restarted by itself, at any hour;
|
|
13
|
+
* ask never by itself: alerted and asked.
|
|
14
|
+
* By itself, ONCE (host program: `vm revive`), recorded, the owner told;
|
|
15
|
+
* not again within REVIVE_EVERY_MS, so that it never loops.
|
|
16
|
+
* - its owner may restart it by hand (`revive`), confirmed in the page:
|
|
17
|
+
* every machine is suspended and resumed, every terminal drops.
|
|
10
18
|
*/
|
|
11
19
|
export const EVERY_MS = 60_000;
|
|
12
20
|
/* Restarting it suspends and resumes EVERY machine: every terminal drops (21-10). Only when it
|
|
13
|
-
has said nothing at all for this long. */
|
|
14
|
-
export const STUCK_MS =
|
|
21
|
+
has said nothing at all for this long: mute (30 s each) on three looks in a row. */
|
|
22
|
+
export const STUCK_MS = 2 * 60_000;
|
|
15
23
|
export const REVIVE_EVERY_MS = 6 * 3600_000;
|
|
24
|
+
export const MANAGER_MODES = Object.freeze(['night', 'always', 'ask']);
|
|
25
|
+
export const NIGHT_FROM = 0;
|
|
26
|
+
export const NIGHT_UNTIL = 7;
|
|
27
|
+
/* What a look waits for the host program, which bounds `multipass list` to 30 s itself. */
|
|
28
|
+
const PING_MS = 40_000;
|
|
16
29
|
|
|
17
30
|
const said = (r) => String(r?.stderr || r?.stdout || '').trim().split('\n').filter(Boolean).pop()?.slice(0, 200) || `exit ${r?.code}`;
|
|
18
31
|
|
|
19
32
|
export class VmWatch {
|
|
20
|
-
#run; #store; #now; #log; #alert; #stuckMs; #reviveEveryMs; #downSince = null;
|
|
33
|
+
#run; #store; #now; #hour; #log; #alert; #stuckMs; #reviveEveryMs; #downSince = null; #reviving = null;
|
|
21
34
|
ok = true;
|
|
22
|
-
|
|
23
|
-
|
|
35
|
+
/* `hour()`: this server's local hour, 0-23 (injected for tests). */
|
|
36
|
+
constructor({ run, store, now = () => Date.now(), hour = () => new Date().getHours(), log = (line) => console.error(line), alert = () => {}, stuckMs = STUCK_MS, reviveEveryMs = REVIVE_EVERY_MS }) {
|
|
37
|
+
this.#run = run; this.#store = store; this.#now = now; this.#hour = hour; this.#log = log; this.#alert = alert; this.#stuckMs = stuckMs; this.#reviveEveryMs = reviveEveryMs;
|
|
24
38
|
}
|
|
25
39
|
|
|
26
|
-
/* What the last restart of the VM manager was, if any: { at, why, result }. */
|
|
27
|
-
last() { const r = this.#store.get('revive'); return r ? { at: r.at, why: r.why, result: r.result ?? null } : null; }
|
|
40
|
+
/* What the last restart of the VM manager was, if any: { at, why, result, by }. */
|
|
41
|
+
last() { const r = this.#store.get('revive'); return r ? { at: r.at, why: r.why, result: r.result ?? null, by: r.by ?? 'server' } : null; }
|
|
28
42
|
|
|
29
|
-
/*
|
|
43
|
+
/* Its owner's choice when it hangs: night (the default), always, ask. */
|
|
44
|
+
mode() { const m = this.#store.get('mode')?.mode; return MANAGER_MODES.includes(m) ? m : 'night'; }
|
|
45
|
+
setMode(mode) {
|
|
46
|
+
if (!MANAGER_MODES.includes(mode)) { const e = new Error('Choose night, always or ask.'); e.status = 400; throw e; }
|
|
47
|
+
this.#store.put({ name: 'mode', mode });
|
|
48
|
+
return this.about();
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/* For Settings, Machines: does it answer, since when not, what its owner chose, whether it waits for
|
|
52
|
+
its owner (`asked`), the last restart, and one running now. */
|
|
53
|
+
about() {
|
|
54
|
+
const asked = this.#store.get('asked');
|
|
55
|
+
return { ok: this.ok, downSince: this.#downSince === null ? null : new Date(this.#downSince).toISOString(), mode: this.mode(), asked: asked?.at && !this.ok ? { at: asked.at, why: asked.why } : null, last: this.last(), reviving: Boolean(this.#reviving) };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
#night() { const h = this.#hour(); return h >= NIGHT_FROM && h < NIGHT_UNTIL; }
|
|
59
|
+
|
|
60
|
+
/* One look: 'ok', 'down', 'down; restarted already', 'asked', 'down; asked already', 'revived' or 'revive failed'. */
|
|
30
61
|
async look() {
|
|
31
|
-
const r = await this.#run(['vm', 'ping'], { timeoutMs:
|
|
62
|
+
const r = await this.#run(['vm', 'ping'], { timeoutMs: PING_MS }).catch((e) => ({ code: 1, stderr: e.message }));
|
|
32
63
|
if (r.code === 0) {
|
|
33
64
|
if (!this.ok) this.#log('vm manager: it answers again');
|
|
34
65
|
this.ok = true; this.#downSince = null;
|
|
66
|
+
this.#store.remove?.('asked');
|
|
35
67
|
return 'ok';
|
|
36
68
|
}
|
|
37
69
|
if (this.ok) this.#log(`vm manager: it does not answer (${said(r)})`);
|
|
38
70
|
this.ok = false;
|
|
39
71
|
this.#downSince ??= this.#now();
|
|
40
72
|
if (this.#now() - this.#downSince < this.#stuckMs) return 'down';
|
|
73
|
+
if (this.#reviving) return 'down';
|
|
74
|
+
const minutes = Math.max(1, Math.round((this.#now() - this.#downSince) / 60_000));
|
|
75
|
+
const why = `the VM manager did not answer for ${minutes} minute${minutes === 1 ? '' : 's'} (${said(r)})`;
|
|
76
|
+
const mode = this.mode();
|
|
77
|
+
/* By day (night), or never by itself (ask): its owner asked, once a hang. */
|
|
78
|
+
if (mode === 'ask' || (mode === 'night' && !this.#night())) {
|
|
79
|
+
if (this.#store.get('asked')) return 'down; asked already';
|
|
80
|
+
this.#store.put({ name: 'asked', at: new Date(this.#now()).toISOString(), why });
|
|
81
|
+
this.#log(`vm manager: ${why}: its owner is asked`);
|
|
82
|
+
this.#alert({ title: 'The machine manager is stuck', body: `${why}. Restarting it resumes every machine: Settings, Machines.`, url: '/?open=settings&at=machines' });
|
|
83
|
+
return 'asked';
|
|
84
|
+
}
|
|
41
85
|
const before = this.#store.get('revive');
|
|
42
86
|
if (before?.at && this.#now() - Date.parse(before.at) < this.#reviveEveryMs) return 'down; restarted already';
|
|
43
|
-
const minutes = Math.round((this.#now() - this.#downSince) / 60_000);
|
|
44
|
-
const why = `the VM manager did not answer for ${minutes} minutes (${said(r)})`;
|
|
45
|
-
this.#store.put({ name: 'revive', at: new Date(this.#now()).toISOString(), why, result: null });
|
|
46
87
|
this.#log(`vm manager: ${why}: its daemon is restarted, once`);
|
|
47
|
-
const
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
88
|
+
const result = await this.#revive(why, 'server');
|
|
89
|
+
this.#alert({ title: 'The machines could not be reached', body: `${why}: it was restarted (${result}).`, url: '/?open=settings&at=machines' });
|
|
90
|
+
return result === 'done' ? 'revived' : 'revive failed';
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/* RESTARTED BY ITS OWNER (Settings, Machines; confirmed there): now, whatever the hour or the last one.
|
|
94
|
+
One at a time. Resolves with what the server records: { at, why, result, by }. */
|
|
95
|
+
async revive() {
|
|
96
|
+
if (this.#reviving) { const e = new Error('The machine manager is being restarted already.'); e.status = 409; throw e; }
|
|
97
|
+
this.#log('vm manager: restarted by its owner');
|
|
98
|
+
await this.#revive('asked by its owner', 'owner');
|
|
99
|
+
return this.about();
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
#revive(why, by) {
|
|
103
|
+
this.#reviving = (async () => {
|
|
104
|
+
this.#store.put({ name: 'revive', at: new Date(this.#now()).toISOString(), why, result: null, by });
|
|
105
|
+
const done = await this.#run(['vm', 'revive'], { timeoutMs: 180_000 }).catch((e) => ({ code: 1, stderr: e.message }));
|
|
106
|
+
const result = done.code === 0 ? 'done' : `failed: ${said(done)}`;
|
|
107
|
+
this.#store.put({ name: 'revive', at: new Date(this.#now()).toISOString(), why, result, by });
|
|
108
|
+
this.#log(`vm manager: restart ${result}`);
|
|
109
|
+
if (done.code === 0) { this.#store.remove?.('asked'); this.#downSince = null; }
|
|
110
|
+
return result;
|
|
111
|
+
})().finally(() => { this.#reviving = null; });
|
|
112
|
+
return this.#reviving;
|
|
54
113
|
}
|
|
55
114
|
|
|
56
115
|
/* Looked at every `everyMs` (0: never), one look at a time. */
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/* THE WATCHDOG OF A MACHINE (09-11): a machine that stays mute, or whose memory stays full, is forced
|
|
2
|
+
* off and started again, once, by this server -- never by its AI, which is the thing stuck.
|
|
3
|
+
*
|
|
4
|
+
* What it looks at is what health.mjs found (told each look: `judged`): the machine runs, and either it
|
|
5
|
+
* did not answer the probe, or its memory had less than FULL_PERCENT free. Nothing more is asked of it.
|
|
6
|
+
*
|
|
7
|
+
* - Its owner's setting, per conversation (conversations.mjs, watchdog): on by default, after an hour.
|
|
8
|
+
* - Seen so for the whole delay (a look that finds it well, or not running, starts the count again):
|
|
9
|
+
* forced off (`vm hardstop`, as a power cut: it is the one way that works on a frozen machine), then
|
|
10
|
+
* started -- both through the one lock of its machine (machineAction), so never during another action.
|
|
11
|
+
* - Its AI told in its chat (the tool reads it again once started), its owner alerted with the report.
|
|
12
|
+
* - NEVER A LOOP: not again on the same machine within AGAIN_MS, nor before it was seen well once
|
|
13
|
+
* since. Stuck again within that time: its owner is told, once, and nothing else is done.
|
|
14
|
+
* - A machine that is starting, being restarted or moved is not judged (health says it busy).
|
|
15
|
+
*/
|
|
16
|
+
export const FULL_PERCENT = 5;
|
|
17
|
+
export const AGAIN_MS = 6 * 3600_000;
|
|
18
|
+
|
|
19
|
+
/* "1 h", "30 min", "1 h 30". */
|
|
20
|
+
export function delayWords(minutes) {
|
|
21
|
+
const h = Math.floor(minutes / 60); const m = minutes % 60;
|
|
22
|
+
return h === 0 ? `${m} min` : m === 0 ? `${h} h` : `${h} h ${String(m).padStart(2, '0')}`;
|
|
23
|
+
}
|
|
24
|
+
const hhmm = (ms) => { const d = new Date(ms); return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`; };
|
|
25
|
+
|
|
26
|
+
/* What one look says: 'mute', 'full', 'well', or null (nothing to judge: not running, busy). */
|
|
27
|
+
export function lookOf(record) {
|
|
28
|
+
if (!record || record.busy || record.state !== 'Running') return null;
|
|
29
|
+
if (record.answering === false) return 'mute';
|
|
30
|
+
const m = record.memory;
|
|
31
|
+
if (record.answering === true && m && m.totalMb > 0 && m.availableMb < (m.totalMb * FULL_PERCENT) / 100) return 'full';
|
|
32
|
+
return record.answering === true ? 'well' : null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export class Watchdog {
|
|
36
|
+
#conversations; #store; #act; #tell; #alert; #now; #trouble = new Map(); #acting = new Set();
|
|
37
|
+
|
|
38
|
+
/* `conversations`: get(name), watchdog(name). `store`: the last time each machine was restarted
|
|
39
|
+
(kept across a restart of this server, so that it never loops). `act(name)`: forced off then
|
|
40
|
+
started, resolves with { ok, said }. `tell(name, text, started)`: its chat, read by its AI.
|
|
41
|
+
`alert(payload)`: its owner's alerts. */
|
|
42
|
+
constructor({ conversations, store, act, tell = () => {}, alert = () => {}, now = () => Date.now() }) {
|
|
43
|
+
this.#conversations = conversations; this.#store = store; this.#act = act; this.#tell = tell; this.#alert = alert; this.#now = now;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/* What is known of one machine: since when it is mute or full, its last restart by the watchdog. */
|
|
47
|
+
of(name) {
|
|
48
|
+
const t = this.#trouble.get(name);
|
|
49
|
+
const last = this.#store.get(name);
|
|
50
|
+
return { trouble: t ? { kind: t.kind, since: new Date(t.since).toISOString() } : null, last: last ? { at: last.at, ok: last.ok, why: last.why } : null, acting: this.#acting.has(name) };
|
|
51
|
+
}
|
|
52
|
+
forget(name) { this.#trouble.delete(name); this.#store.remove?.(name); }
|
|
53
|
+
|
|
54
|
+
/* One look of health.mjs. Resolves with what was done: null, 'watching', 'restarted', 'failed',
|
|
55
|
+
'held' (stuck again too soon: said, not done). */
|
|
56
|
+
async judged(name, record) {
|
|
57
|
+
const c = this.#conversations.get(name);
|
|
58
|
+
const set = c ? this.#conversations.watchdog(name) : null;
|
|
59
|
+
const look = lookOf(record);
|
|
60
|
+
if (!c || !set?.on || look === null || look === 'well') {
|
|
61
|
+
this.#trouble.delete(name);
|
|
62
|
+
/* Seen well since its last restart: the watchdog may act again, after AGAIN_MS. */
|
|
63
|
+
const last = this.#store.get(name);
|
|
64
|
+
if (look === 'well' && last && !last.wellSince) this.#store.put({ ...last, wellSince: new Date(this.#now()).toISOString() });
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
if (this.#acting.has(name)) return null;
|
|
68
|
+
const now = this.#now();
|
|
69
|
+
const t = this.#trouble.get(name) ?? { since: now, kind: look, full: false };
|
|
70
|
+
t.kind = look; t.full ||= look === 'full';
|
|
71
|
+
this.#trouble.set(name, t);
|
|
72
|
+
if (now - t.since < set.delayMin * 60_000) return 'watching';
|
|
73
|
+
const last = this.#store.get(name);
|
|
74
|
+
if (last && (now - Date.parse(last.at) < AGAIN_MS || !last.wellSince)) {
|
|
75
|
+
if (last.held) return null;
|
|
76
|
+
this.#store.put({ ...last, held: true });
|
|
77
|
+
this.#alert({ title: `${name}: its machine is stuck again`, body: `Restarted by its watchdog at ${hhmm(Date.parse(last.at))}, stuck again: not restarted twice. Force stop or restart it yourself.`, url: `/?c=${encodeURIComponent(name)}&open=settings` });
|
|
78
|
+
return 'held';
|
|
79
|
+
}
|
|
80
|
+
return this.#restart(name, set, t);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async #restart(name, set, t) {
|
|
84
|
+
this.#acting.add(name);
|
|
85
|
+
const at = this.#now();
|
|
86
|
+
const why = t.kind === 'mute' ? (t.full ? 'memory full' : 'no answer') : 'memory full';
|
|
87
|
+
this.#store.put({ name, at: new Date(at).toISOString(), why, ok: null });
|
|
88
|
+
try {
|
|
89
|
+
const report = await Promise.resolve(this.#act(name)).catch((error) => ({ ok: false, said: String(error?.message ?? error) }));
|
|
90
|
+
const when = hhmm(this.#now());
|
|
91
|
+
const head = t.kind === 'mute' ? `Your machine did not answer for ${delayWords(set.delayMin)}${t.full ? ' (memory full)' : ''}` : `Your machine's memory stayed full for ${delayWords(set.delayMin)}`;
|
|
92
|
+
const text = report?.ok ? `${head}: it was restarted automatically at ${when}.` : `${head}: it was forced off at ${when} but did not start again. ${report?.said ?? ''}`.trim();
|
|
93
|
+
this.#store.put({ name, at: new Date(at).toISOString(), why, ok: Boolean(report?.ok) });
|
|
94
|
+
try { this.#tell(name, text, Boolean(report?.ok)); } catch { /* its chat may be off */ }
|
|
95
|
+
this.#alert({ title: report?.ok ? `${name}: restarted by its watchdog` : `${name}: its watchdog could not restart it`, body: `${text}${report?.said ? ` ${report.said}` : ''}`.slice(0, 200), url: `/?c=${encodeURIComponent(name)}&open=settings` });
|
|
96
|
+
return report?.ok ? 'restarted' : 'failed';
|
|
97
|
+
} finally {
|
|
98
|
+
this.#trouble.delete(name);
|
|
99
|
+
this.#acting.delete(name);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
package/web/app.js
CHANGED
|
@@ -2929,6 +2929,8 @@
|
|
|
2929
2929
|
for (const b of $('resume-on').children) b.setAttribute('aria-pressed', String((b.dataset.on === 'true') === (here?.resume !== false)));
|
|
2930
2930
|
/* A stop that hangs: forced by itself (the default), or asked first. */
|
|
2931
2931
|
for (const b of $('m-escalate').children) b.setAttribute('aria-pressed', String((b.dataset.on === 'true') === (here?.stopEscalate !== false)));
|
|
2932
|
+
/* Its watchdog: off, or how long it waits (a custom one shown in its field). */
|
|
2933
|
+
paintWatchdog(here);
|
|
2932
2934
|
/* Whether its tool asks before acting -- for a tool that can be given every right in its machine. */
|
|
2933
2935
|
$('rights-box').hidden = DEVICE || !here?.rights;
|
|
2934
2936
|
for (const b of $('ask-first').children) b.setAttribute('aria-pressed', String((b.dataset.on === 'true') === (here?.askFirst === true)));
|
|
@@ -7263,7 +7265,7 @@
|
|
|
7263
7265
|
if ($('settings-wifi-top').open) void paintWifi();
|
|
7264
7266
|
if ($('settings-mesh-top').open) void paintScreen();
|
|
7265
7267
|
if ($('settings-usage-top').open) void paintUsage();
|
|
7266
|
-
await Promise.all([paintHosts(), paintShelf(), paintServer(), paintUpdates()]);
|
|
7268
|
+
await Promise.all([paintHosts(), paintShelf(), paintServer(), paintUpdates(), paintMachines()]);
|
|
7267
7269
|
await paintSettingsStates();
|
|
7268
7270
|
}
|
|
7269
7271
|
|
|
@@ -8500,6 +8502,87 @@
|
|
|
8500
8502
|
try { await post(`${API}/server/reserve`, { diskMb, diskPercent, memoryMb, memoryPercent }); $('reserve-saved').textContent = 'Saved.'; } catch (error) { $('reserve-error').textContent = error.message; $('reserve-error').hidden = false; return; }
|
|
8501
8503
|
await paintServer(); void paintGauge();
|
|
8502
8504
|
});
|
|
8505
|
+
/* SETTINGS, MACHINES (server/machinelist.mjs): each machine, its state, the memory its qemu holds, since
|
|
8506
|
+
when, and Force stop (confirmed here); the machine manager, and Restart the manager (confirmed: every
|
|
8507
|
+
machine is resumed); what is done when it hangs, and when memory is short. */
|
|
8508
|
+
const ML_STATE = { Running: ['set-ml-running', 'Running', 'ok'], Suspended: ['set-ml-asleep', 'Asleep', 'ok'], Stopped: ['set-ml-stopped', 'Stopped', 'ok'],
|
|
8509
|
+
Starting: ['set-ml-starting', 'Starting', 'warn'], Stopping: ['set-ml-stopping', 'Stopping', 'warn'], Unknown: ['set-ml-unknown', 'Unknown', 'warn'], Gone: ['set-ml-gone', 'Gone', 'bad'] };
|
|
8510
|
+
const sinceSaid = (iso) => {
|
|
8511
|
+
const d = new Date(iso);
|
|
8512
|
+
const today = d.toDateString() === new Date().toDateString();
|
|
8513
|
+
return uiSaid('set-ml-since', 'since {t}', { t: today ? d.toLocaleTimeString([], { timeStyle: 'short' }) : d.toLocaleDateString([], { day: 'numeric', month: 'short' }) });
|
|
8514
|
+
};
|
|
8515
|
+
let machinesAsk = null;
|
|
8516
|
+
let machinesTimer;
|
|
8517
|
+
async function paintMachines() {
|
|
8518
|
+
clearTimeout(machinesTimer);
|
|
8519
|
+
if (DEVICE) { $('settings-ch-machines').hidden = true; return; }
|
|
8520
|
+
const r = await fetch(`${API}/server/machines`).then((x) => (x.ok ? x.json() : null)).catch(() => null);
|
|
8521
|
+
$('settings-ch-machines').hidden = !r;
|
|
8522
|
+
if (!r) return;
|
|
8523
|
+
const running = r.machines.filter((m) => m.state === 'Running').length;
|
|
8524
|
+
chapterNow('s-machines', uiSaid('set-ml-now', '{n} running of {all}', { n: running, all: r.machines.length }));
|
|
8525
|
+
const rows = $('machines-rows'); rows.replaceChildren();
|
|
8526
|
+
$('machines-none').hidden = r.machines.length > 0;
|
|
8527
|
+
for (const m of r.machines) {
|
|
8528
|
+
const row = el('div', 'list-item machine-item'); row.dataset.name = m.name;
|
|
8529
|
+
const [key, en, tone] = ML_STATE[m.state] ?? ['set-ml-unknown', m.state, 'warn'];
|
|
8530
|
+
const what = el('div', 'set-what');
|
|
8531
|
+
what.append(el('b', '', machineTitle(m.name)));
|
|
8532
|
+
const line = el('small', 'status-line'); line.dataset.tone = tone;
|
|
8533
|
+
line.textContent = [m.action ? uiSaid('set-ml-busy', 'Busy') : uiSaid(key, en), m.rssMb > 0 ? GB(m.rssMb) : '', m.since ? sinceSaid(m.since) : ''].filter(Boolean).join(' · ');
|
|
8534
|
+
what.append(line);
|
|
8535
|
+
const acts = el('div', 'set-control');
|
|
8536
|
+
const force = el('button', 'danger', uiSaid('set-m-force', 'Force stop')); force.type = 'button'; force.dataset.act = 'force';
|
|
8537
|
+
force.disabled = m.state === 'Stopped' || m.state === 'Gone';
|
|
8538
|
+
force.addEventListener('click', () => askMachines({ kind: 'force', name: m.name }));
|
|
8539
|
+
acts.append(force);
|
|
8540
|
+
row.append(what, acts);
|
|
8541
|
+
rows.append(row);
|
|
8542
|
+
}
|
|
8543
|
+
/* The machine manager: does it answer, since when not, waiting for its owner, the last restart. */
|
|
8544
|
+
const g = r.manager;
|
|
8545
|
+
const ml = $('manager-line');
|
|
8546
|
+
if (g) {
|
|
8547
|
+
ml.dataset.tone = g.reviving ? 'warn' : g.ok ? 'ok' : 'bad';
|
|
8548
|
+
ml.textContent = g.reviving ? uiSaid('set-ml-reviving', 'Restarting…')
|
|
8549
|
+
: g.ok ? [uiSaid('set-ml-answers', 'Answers'), g.last?.at ? uiSaid('set-ml-last', 'restarted {t}', { t: agoSaid(g.last.at) }) : ''].filter(Boolean).join(' · ')
|
|
8550
|
+
: [uiSaid('set-ml-mute', 'Not answering'), g.downSince ? sinceSaid(g.downSince) : '', g.asked ? uiSaid('set-ml-asked', 'waits for you') : ''].filter(Boolean).join(' · ');
|
|
8551
|
+
$('manager-restart').disabled = Boolean(g.reviving);
|
|
8552
|
+
$('manager-restart').classList.toggle('primary', Boolean(g.asked));
|
|
8553
|
+
for (const b of $('manager-mode').children) b.setAttribute('aria-pressed', String(b.dataset.mode === g.mode));
|
|
8554
|
+
}
|
|
8555
|
+
$('manager-row').hidden = !g;
|
|
8556
|
+
for (const b of $('pressure-way').children) b.setAttribute('aria-pressed', String(b.dataset.way === r.pressure));
|
|
8557
|
+
/* While it is in sight and something moves (an action, a restart of the manager): looked at again. */
|
|
8558
|
+
if ($('settings-ch-machines').open && !$('settings').hidden && (g?.reviving || r.machines.some((m) => m.action))) machinesTimer = setTimeout(() => { void paintMachines(); }, 3000);
|
|
8559
|
+
}
|
|
8560
|
+
/* Asked in the page, in one line: what is lost. */
|
|
8561
|
+
function askMachines(ask) {
|
|
8562
|
+
machinesAsk = ask;
|
|
8563
|
+
$('machines-confirm-text').textContent = ask.kind === 'force'
|
|
8564
|
+
? uiSaid('set-ml-force-q', 'Force stop {name}? Nothing is saved.', { name: machineTitle(ask.name) })
|
|
8565
|
+
: uiSaid('set-ml-revive-q', 'Restart the manager? All machines are resumed.');
|
|
8566
|
+
$('machines-confirm-yes').textContent = ask.kind === 'force' ? uiSaid('set-m-force', 'Force stop') : uiSaid('set-ml-revive-yes', 'Restart');
|
|
8567
|
+
$('machines-confirm').hidden = false;
|
|
8568
|
+
$('machines-confirm-yes').focus();
|
|
8569
|
+
}
|
|
8570
|
+
async function machinesPost(path, body) {
|
|
8571
|
+
$('machines-error').hidden = true;
|
|
8572
|
+
try { await post(`${API}${path}`, body); } catch (error) { $('machines-error').textContent = error.message; $('machines-error').hidden = false; }
|
|
8573
|
+
await paintMachines();
|
|
8574
|
+
}
|
|
8575
|
+
$('machines-confirm-no').addEventListener('click', () => { machinesAsk = null; $('machines-confirm').hidden = true; });
|
|
8576
|
+
$('machines-confirm-yes').addEventListener('click', () => {
|
|
8577
|
+
const ask = machinesAsk; machinesAsk = null; $('machines-confirm').hidden = true;
|
|
8578
|
+
if (!ask) return;
|
|
8579
|
+
if (ask.kind === 'force') void machinesPost(`/server/machines/${encodeURIComponent(ask.name)}/force`, {});
|
|
8580
|
+
else { $('manager-restart').disabled = true; $('manager-line').dataset.tone = 'warn'; $('manager-line').textContent = uiSaid('set-ml-reviving', 'Restarting…'); void machinesPost('/server/vm-manager/restart', { confirm: true }); }
|
|
8581
|
+
});
|
|
8582
|
+
$('manager-restart').addEventListener('click', () => askMachines({ kind: 'revive' }));
|
|
8583
|
+
for (const b of $('manager-mode').children) b.addEventListener('click', () => void machinesPost('/server/vm-manager', { mode: b.dataset.mode }));
|
|
8584
|
+
for (const b of $('pressure-way').children) b.addEventListener('click', () => void machinesPost('/server/pressure', { way: b.dataset.way }));
|
|
8585
|
+
$('settings-ch-machines').addEventListener('toggle', () => { if ($('settings-ch-machines').open) void paintMachines(); });
|
|
8503
8586
|
/* THE SMALL GAUGE at the bottom of the list: only when disk or memory is
|
|
8504
8587
|
short. A click opens Settings, at This server. */
|
|
8505
8588
|
async function paintGauge() {
|
|
@@ -11663,6 +11746,39 @@
|
|
|
11663
11746
|
catch (error) { $('panel-error').textContent = error.message; $('panel-error').hidden = false; }
|
|
11664
11747
|
});
|
|
11665
11748
|
}
|
|
11749
|
+
/* ITS WATCHDOG (server/watchdog.mjs): Off, 30 min, 1 h (the default), 2 h, or minutes of its own. */
|
|
11750
|
+
const DOG_CHOICES = [30, 60, 120];
|
|
11751
|
+
function paintWatchdog(here) {
|
|
11752
|
+
const on = here?.watchdog?.on !== false;
|
|
11753
|
+
const min = Number.isInteger(here?.watchdog?.delayMin) ? here.watchdog.delayMin : 60;
|
|
11754
|
+
const custom = on && !DOG_CHOICES.includes(min);
|
|
11755
|
+
if ($('m-dog').dataset.of !== (here?.name ?? '')) { $('m-dog').dataset.of = here?.name ?? ''; $('m-dog').dataset.custom = 'false'; }
|
|
11756
|
+
const choosing = $('m-dog').dataset.custom === 'true';
|
|
11757
|
+
for (const b of $('m-dog').children) {
|
|
11758
|
+
const pressed = b.dataset.min === '0' ? !on : b.dataset.min === 'custom' ? custom || (on && choosing) : on && !choosing && Number(b.dataset.min) === min;
|
|
11759
|
+
b.setAttribute('aria-pressed', String(pressed));
|
|
11760
|
+
}
|
|
11761
|
+
$('m-dog-custom').hidden = !(custom || (on && choosing));
|
|
11762
|
+
if (document.activeElement !== $('m-dog-min')) $('m-dog-min').value = String(min);
|
|
11763
|
+
}
|
|
11764
|
+
async function setWatchdog(watchdog) {
|
|
11765
|
+
$('panel-error').hidden = true;
|
|
11766
|
+
try { await post(`${API}/conversations/${encodeURIComponent(current)}/machine`, { watchdog }); await refresh(); paintMachine(conversations.find((x) => x.name === current)); }
|
|
11767
|
+
catch (error) { $('panel-error').textContent = error.message; $('panel-error').hidden = false; }
|
|
11768
|
+
}
|
|
11769
|
+
for (const b of $('m-dog').children) {
|
|
11770
|
+
b.addEventListener('click', () => {
|
|
11771
|
+
const m = b.dataset.min;
|
|
11772
|
+
$('m-dog').dataset.custom = String(m === 'custom');
|
|
11773
|
+
if (m === 'custom') { paintWatchdog({ ...conversations.find((x) => x.name === current), watchdog: { on: true, delayMin: Number($('m-dog-min').value) || 60 } }); $('m-dog-min').focus(); return; }
|
|
11774
|
+
void setWatchdog(m === '0' ? { on: false } : { on: true, delayMin: Number(m) });
|
|
11775
|
+
});
|
|
11776
|
+
}
|
|
11777
|
+
$('m-dog-min').addEventListener('change', () => {
|
|
11778
|
+
const n = Math.round(Number($('m-dog-min').value));
|
|
11779
|
+
if (!Number.isFinite(n)) return;
|
|
11780
|
+
void setWatchdog({ on: true, delayMin: Math.min(1440, Math.max(10, n)) });
|
|
11781
|
+
});
|
|
11666
11782
|
/* The quick actions at the top of the panel do the same as the Machine chapter's. */
|
|
11667
11783
|
$('hand-terminal').addEventListener('click', () => { leavePanel(); seeTerminal(); });
|
|
11668
11784
|
$('quick-wake').addEventListener('click', () => { leavePanel(); seeTerminal(); });
|
package/web/index.html
CHANGED
|
@@ -205,6 +205,8 @@
|
|
|
205
205
|
</div>
|
|
206
206
|
<!-- A STOP THAT HANGS: forced by itself (the default), or asked first (conversations.mjs, stopEscalate). -->
|
|
207
207
|
<div class="set-row"><div class="set-what"><b data-said="set-mesc">If a stop hangs</b></div><div class="set-control"><div class="levels" id="m-escalate" role="group" aria-label="If a stop hangs"><button type="button" data-on="true" data-said="set-mesc-auto">Force it</button><button type="button" data-on="false" data-said="set-mesc-ask">Ask me</button></div></div></div>
|
|
208
|
+
<!-- ITS WATCHDOG (server/watchdog.mjs): mute or full that long, forced off then started, once. -->
|
|
209
|
+
<div class="set-row" id="m-dog-row"><div class="set-what"><b data-said="set-mdog">Watchdog</b><small data-said="set-mdog-what">Restarts it if stuck</small></div><div class="set-control"><div class="levels" id="m-dog" role="group" aria-label="Watchdog"><button type="button" data-min="0" data-said="set-mdog-off">Off</button><button type="button" data-min="30">30 min</button><button type="button" data-min="60">1 h</button><button type="button" data-min="120">2 h</button><button type="button" data-min="custom" data-said="set-mdog-custom">Custom</button></div><label class="m-dog-min" id="m-dog-custom" hidden><input type="number" id="m-dog-min" min="10" max="1440" step="5" inputmode="numeric" aria-label="Minutes"> min</label></div></div>
|
|
208
210
|
<div class="panel-top"><b>Memory, cores and disk</b></div>
|
|
209
211
|
<form id="machine-size" autocomplete="off">
|
|
210
212
|
<label for="machine-memory">Memory</label>
|
|
@@ -1057,7 +1059,7 @@
|
|
|
1057
1059
|
<span class="hint" id="reserve-saved" role="status"></span>
|
|
1058
1060
|
</div>
|
|
1059
1061
|
<p class="server-note" id="reserve-now"></p>
|
|
1060
|
-
<p class="hint"><span>The larger of the two</span><span class="tip" hidden>No machine is created, started or enlarged into it. Below it you are alerted and the largest running machine is
|
|
1062
|
+
<p class="hint"><span>The larger of the two</span><span class="tip" hidden>No machine is created, started or enlarged into it. Below it you are alerted, and the largest running machine is forced off (Machines). Waking is always allowed, to clean up.</span></p>
|
|
1061
1063
|
<p class="server-note promised" id="promised-disk" hidden></p>
|
|
1062
1064
|
<p class="server-note promised" id="promised-memory" hidden></p>
|
|
1063
1065
|
<p id="reserve-error" class="error" role="alert" hidden></p>
|
|
@@ -1067,6 +1069,23 @@
|
|
|
1067
1069
|
(server/updates.mjs; the updater, as root: deploy/updater.mjs). -->
|
|
1068
1070
|
</div>
|
|
1069
1071
|
</details>
|
|
1072
|
+
<!-- MACHINES (server/machinelist.mjs): each one, its state, the memory its qemu holds, since when, and
|
|
1073
|
+
Force stop; the machine manager, restarted when confirmed; what is done when it hangs, when memory is short. -->
|
|
1074
|
+
<details class="chapter" id="settings-ch-machines" data-chapter="s-machines">
|
|
1075
|
+
<summary><span class="chapter-title" data-said="set-ch-s-machines">Machines</span><span class="chapter-about" data-said="set-ml-about">State and memory.</span></summary>
|
|
1076
|
+
<div class="chapter-body">
|
|
1077
|
+
<div id="machines-rows"></div>
|
|
1078
|
+
<p id="machines-none" class="hint" data-said="set-ml-none" hidden>No machine yet</p>
|
|
1079
|
+
<div id="machines-confirm" class="callout confirm" role="alertdialog" aria-labelledby="machines-confirm-text" hidden>
|
|
1080
|
+
<b id="machines-confirm-text"></b>
|
|
1081
|
+
<div class="action-row"><button type="button" id="machines-confirm-no" data-said="set-mconf-no">Cancel</button><button type="button" id="machines-confirm-yes" class="danger"></button></div>
|
|
1082
|
+
</div>
|
|
1083
|
+
<div class="set-row" id="manager-row"><div class="set-what"><b data-said="set-ml-manager">Machine manager</b><p class="status-line" id="manager-line" role="status"></p></div><div class="set-control"><button type="button" id="manager-restart" data-said="set-ml-revive">Restart the manager</button></div></div>
|
|
1084
|
+
<div class="set-row"><div class="set-what"><b data-said="set-ml-hang">If it hangs</b><small data-said="set-ml-hang-what">Night: 0 to 7 h</small></div><div class="set-control"><div class="levels" id="manager-mode" role="group" aria-label="If it hangs"><button type="button" data-mode="night" data-said="set-ml-night">At night</button><button type="button" data-mode="always" data-said="set-ml-always">Always</button><button type="button" data-mode="ask" data-said="set-ml-ask">Ask me</button></div></div></div>
|
|
1085
|
+
<div class="set-row"><div class="set-what"><b data-said="set-ml-short">Memory short</b><small data-said="set-ml-short-what">The largest machine</small></div><div class="set-control"><div class="levels" id="pressure-way" role="group" aria-label="Memory short"><button type="button" data-way="force" data-said="set-ml-force">Force stop</button><button type="button" data-way="sleep" data-said="set-ml-sleep">Sleep</button><button type="button" data-way="alert" data-said="set-ml-alert">Alert only</button></div></div></div>
|
|
1086
|
+
<p id="machines-error" class="error" role="alert" hidden></p>
|
|
1087
|
+
</div>
|
|
1088
|
+
</details>
|
|
1070
1089
|
</section>
|
|
1071
1090
|
<section class="settings-group" id="settings-group-access" data-group="access" role="tabpanel" aria-label="Access">
|
|
1072
1091
|
<!-- WHO MAY SIGN IN (server/operators.mjs): hidden on this machine alone. -->
|
package/web/style.css
CHANGED
|
@@ -3012,3 +3012,10 @@ button.kit-switch[aria-checked="true"]::after { left: 18px; background: var(--ok
|
|
|
3012
3012
|
.mstep li.arr { display: none; }
|
|
3013
3013
|
#notice .m-live { justify-items: stretch; }
|
|
3014
3014
|
}
|
|
3015
|
+
|
|
3016
|
+
/* ITS WATCHDOG's own minutes (a conversation's Machine chapter), and SETTINGS, MACHINES (machinelist.mjs). */
|
|
3017
|
+
.m-dog-min { display: inline-flex; align-items: center; gap: 6px; font-size: .875rem; color: var(--ink2); }
|
|
3018
|
+
.m-dog-min input { width: 5.5em; min-height: 40px; font: .875rem var(--sans); color: var(--ink); background: var(--bg); border: 1px solid var(--line); border-radius: 7px; padding: 7px 9px; }
|
|
3019
|
+
.list-item.machine-item > .set-what > small.status-line { font-size: .75rem; margin: 0; }
|
|
3020
|
+
#manager-row .status-line { margin: 2px 0 0; font-size: .75rem; }
|
|
3021
|
+
#machines-confirm { margin: 8px 16px; }
|