Compare commits

...
Author SHA1 Message Date
BFE EngineeringandClaude Opus 5.5 a9f2b9b26a qemu: ui-drive waits for the chain start on an init-chain boot (flare-edge#2295)
ci / test (pull_request) Successful in 24s
ci / mcdc (pull_request) Successful in 17s
ci / badges (push) Skipped
ci / test (push) Successful in 9s
ci / qemu-tools (push) Successful in 1m27s
ci / bench (pull_request) Successful in 5s
ci / mcdc (push) Successful in 12s
ci / bench (push) Successful in 5s
ci / prune-artifacts (push) Skipped
ci / kernel-build (push) Skipped
ci / patches-apply (push) Successful in 43s
ci / prune-artifacts (pull_request) Skipped
ci / kernel-build (pull_request) Skipped
ci / patches-apply (pull_request) Successful in 24s
ci / quality (pull_request) Successful in 2m35s
ci / kernel-symbols (pull_request) Successful in 5m7s
ci / quality (push) Successful in 1m28s
ci / qemu-tools (pull_request) Successful in 1m36s
ci / badges (pull_request) Skipped
ci / kernel-symbols (push) Successful in 5m2s
ui-drive.sh --init-chain boots with warden.initchain, where sbin/init starts
the UI through the panel's S99lvgl and prints "init: chain started N
script(s)"; the direct-start line "init: starting warden-ui" is never
printed. ui-drive.sh still waited for that line, so the first flare-edge
"QEMU UI shipped init chain" run (job 99350) gave "warden-ui never started"
after 180 s on a chain that had booted cleanly.

The wait moves to qemu/tests/ui-start.sh (sourced by ui-drive.sh and
ui-shot.sh): wait_ui_started picks the marker by mode and, on a chain boot,
fails at once on WARDEN-QEMU-INITCHAIN-EMPTY or a failed S99lvgl instead of
at the deadline.

Tests: new qemu/tests/ui-start-test.sh (27 checks, in CI): every marker is
the one sbin/init or warden-lib.sh prints in that mode, the job 99350
console counts as started in chain mode, empty and failed chains fail fast,
a dead VM and a silent console fail with their own messages, and both
drivers wait through the helper. The old ui-drive.sh fails 4 checks.

Fixes flare-edge#2295

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KerYPVh72hhNgKi3wS5ijG
2026-10-28 17:17:14 -06:00
noah 6e51f1a0e5 Merge pull request 'qemu: ui-drive --init-chain and the assert_ui_chain verb (flare-edge#2210)' (#33) from rb/ln-init-chain-boot into rebuild
ci / test (push) Successful in 27s
ci / bench (push) Successful in 5s
ci / mcdc (push) Successful in 14s
ci / prune-artifacts (push) Skipped
ci / kernel-build (push) Skipped
ci / patches-apply (push) Successful in 22s
ci / qemu-tools (push) Successful in 2m58s
ci / quality (push) Successful in 58s
ci / badges (push) Skipped
ci / kernel-symbols (push) Successful in 7m35s
2026-10-28 12:30:24 -06:00
BFE Engineering 333c237949 Merge remote-tracking branch 'origin/rebuild' into rb/ln-init-chain-boot
ci / test (push) Skipped
ci / mcdc (push) Skipped
ci / bench (push) Skipped
ci / qemu-tools (push) Skipped
ci / kernel-symbols (push) Skipped
ci / patches-apply (push) Skipped
ci / prune-artifacts (push) Skipped
ci / kernel-build (push) Skipped
ci / quality (push) Skipped
ci / badges (push) Skipped
ci / bench (pull_request) Successful in 20s
ci / prune-artifacts (pull_request) Skipped
ci / kernel-build (pull_request) Skipped
ci / quality (pull_request) Successful in 42s
ci / test (pull_request) Successful in 15s
ci / mcdc (pull_request) Successful in 1m3s
ci / kernel-symbols (pull_request) Successful in 5m24s
ci / qemu-tools (pull_request) Successful in 1m58s
ci / patches-apply (pull_request) Successful in 31s
ci / badges (pull_request) Skipped
2026-10-28 11:38:54 -06:00
noah f46a3519aa Merge pull request 'qemu: boot the UI through the panel shipped init chain (flare-edge#2210)' (#32) from rb/ln-init-chain into rebuild
ci / test (push) Successful in 17s
ci / qemu-tools (push) Successful in 3m14s
ci / patches-apply (push) Successful in 50s
ci / bench (push) Successful in 6s
ci / mcdc (push) Successful in 23s
ci / prune-artifacts (push) Skipped
ci / kernel-build (push) Skipped
ci / quality (push) Successful in 37s
ci / badges (push) Skipped
ci / kernel-symbols (push) Successful in 2m3s
2026-10-28 11:32:36 -06:00
BFE EngineeringandClaude Opus 5.5 f04a31dc06 qemu: ui-drive --init-chain and the assert_ui_chain verb (flare-edge#2210)
ci / qemu-tools (push) Successful in 3m26s
ci / test (push) Successful in 25s
ci / bench (push) Successful in 18s
ci / mcdc (push) Successful in 32s
ci / quality (push) Successful in 35s
ci / badges (push) Skipped
ci / prune-artifacts (push) Skipped
ci / kernel-build (push) Skipped
ci / patches-apply (push) Successful in 24s
ci / kernel-symbols (push) Successful in 5m45s
ui-drive.sh --init-chain DIR lays the panel's scripts over the rootfs
(ROOTFS_OVERLAY) and boots with warden.initchain; it refuses a missing
directory or one without etc/init.d/S99lvgl before anything is built.

qmp.py assert_ui_chain [ACCOUNT] reads the guest over the control channel
(@procs, @cat) and fails unless exactly one warden-ui and one warden-ui-run
loop run, the UI's real, effective, saved and filesystem uids are all the
account's (never 0), the safe-mode flag is absent and /tmp/warden-ui.log
holds no exit or refusal of warden-ui-run. tests/scripts/init-chain-ui.txt
runs it at about T+120 s.

Tests: UiChainVerb in test_qmp_drive.py (12 cases, among them the #1903
case: no UI, safe mode, three exits); 6 of 6 mutants caught.
rootfs-overlay.sh gains the three ui-drive.sh --init-chain checks.

Refs flare-edge#2210

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KerYPVh72hhNgKi3wS5ijG
2026-10-28 10:39:31 -06:00
BFE EngineeringandClaude Opus 5.5 a4bbfbd83b qemu: boot the UI through the panel's shipped init chain (flare-edge#2210)
ci / prune-artifacts (push) Skipped
ci / patches-apply (push) Successful in 24s
ci / bench (pull_request) Successful in 16s
ci / test (push) Successful in 24s
ci / mcdc (push) Successful in 29s
ci / kernel-build (push) Skipped
ci / test (pull_request) Successful in 10s
ci / quality (push) Successful in 39s
ci / badges (push) Skipped
ci / mcdc (pull_request) Successful in 30s
ci / bench (push) Successful in 10s
ci / qemu-tools (push) Successful in 3m16s
ci / qemu-tools (pull_request) Successful in 2m34s
ci / kernel-symbols (pull_request) Successful in 1m54s
ci / prune-artifacts (pull_request) Skipped
ci / kernel-build (pull_request) Skipped
ci / patches-apply (pull_request) Successful in 55s
ci / quality (pull_request) Successful in 1m36s
ci / badges (pull_request) Skipped
ci / kernel-symbols (push) Successful in 4m24s
The rig's stage-2 init starts /usr/bin/warden-ui directly as root, so it
never ran S03warden-accounts, S99lvgl or warden-ui-run: no privilege drop,
respawn loop or safe mode was exercised, and the BusyBox setpriv bug of
flare-edge #1903 left every rebuild image without a UI while CI was green.

- mkimage.sh: ROOTFS_OVERLAY lays a directory of panel files over the
  rootfs of both slots, modes kept. Only etc/ and usr/ at its top, no
  symlinks; a refused overlay writes no image.
- sbin/init: with warden.initchain on the command line it runs
  /etc/init.d/S00-S09 before the bus and S10-S99 after the payload daemons,
  in place of the direct UI start (warden_init_chain in warden-lib.sh). The
  splash handover is marked done and warden-ui-run gets "-b fbdev". A chain
  boot without scripts prints WARDEN-QEMU-INITCHAIN-EMPTY and starts no UI.
- warden_rig_bus_owners: when the accounts exist, cred/ui belongs to
  warden-ui and the cred directory to group warden-bus, as S10bus does.
- Tests: init-chain-test.sh (19 checks, also under busybox sh) and
  rootfs-overlay.sh (17 scenarios, images read back with debugfs), both in CI.

Refs flare-edge#2210

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KerYPVh72hhNgKi3wS5ijG
2026-10-28 10:35:29 -06:00
noah 7d5686e287 Merge pull request 'qemu: PAYLOAD_DIR lets one run boot its own payload set' (#31) from rb/ln-hook-payload into rebuild
ci / qemu-tools (push) Successful in 1m32s
ci / test (push) Successful in 21s
ci / mcdc (push) Successful in 23s
ci / patches-apply (push) Successful in 21s
ci / badges (push) Skipped
ci / prune-artifacts (push) Skipped
ci / kernel-build (push) Skipped
ci / bench (push) Successful in 17s
ci / quality (push) Successful in 1m25s
ci / kernel-symbols (push) Successful in 4m58s
2026-10-27 19:37:41 -06:00
BFE Engineering de1b973aa4 Merge remote-tracking branch 'origin/rebuild' into rb/ln-hook-payload
ci / test (pull_request) Successful in 33s
ci / kernel-build (pull_request) Skipped
ci / patches-apply (pull_request) Successful in 44s
ci / mcdc (push) Skipped
ci / bench (push) Skipped
ci / test (push) Skipped
ci / patches-apply (push) Skipped
ci / kernel-build (push) Skipped
ci / qemu-tools (push) Skipped
ci / kernel-symbols (push) Skipped
ci / prune-artifacts (push) Skipped
ci / quality (push) Skipped
ci / badges (push) Skipped
ci / mcdc (pull_request) Successful in 26s
ci / bench (pull_request) Successful in 9s
ci / quality (pull_request) Successful in 2m10s
ci / prune-artifacts (pull_request) Skipped
ci / qemu-tools (pull_request) Successful in 2m36s
ci / badges (pull_request) Skipped
ci / kernel-symbols (pull_request) Successful in 4m29s
2026-10-27 19:04:26 -06:00
noah bd4eb5c201 Merge pull request 'qemu: drive a flow override step through the UI test hook' (#29) from rb/ln-hook-override into rebuild
ci / mcdc (push) Successful in 29s
ci / quality (push) Successful in 1m45s
ci / badges (push) Skipped
ci / test (push) Successful in 9s
ci / bench (push) Successful in 17s
ci / prune-artifacts (push) Skipped
ci / kernel-build (push) Skipped
ci / kernel-symbols (push) Successful in 4m51s
ci / qemu-tools (push) Successful in 1m8s
ci / patches-apply (push) Successful in 56s
2026-10-27 18:13:14 -06:00
BFE EngineeringandClaude Opus 5.5 eebfd23a96 qemu: test_qmp_drive.py removes its temp dirs (Fixes #30)
ci / mcdc (push) Successful in 13s
ci / bench (push) Successful in 5s
ci / prune-artifacts (push) Skipped
ci / test (push) Successful in 10s
ci / qemu-tools (push) Successful in 1m22s
ci / kernel-build (push) Skipped
ci / patches-apply (push) Successful in 48s
ci / quality (push) Successful in 57s
ci / badges (push) Skipped
ci / kernel-symbols (push) Successful in 4m7s
Every temp dir the module makes (a drive's out dir per run_script, the
console and QMP socket dirs) now lands under one root per run, removed at
exit; a run used to leave about 40 dirs in $TMPDIR. TempDirs runs one test
of each kind in a child under a fresh TMPDIR and checks it is empty after.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KerYPVh72hhNgKi3wS5ijG
2026-10-27 18:11:14 -06:00
BFE EngineeringandClaude Opus 5.5 06b86e68b4 qemu: payload-dir.sh uses if blocks (shellcheck SC2015)
ci / test (push) Successful in 19s
ci / bench (push) Successful in 13s
ci / quality (push) Successful in 1m35s
ci / badges (push) Skipped
ci / mcdc (push) Successful in 14s
ci / qemu-tools (push) Successful in 2m47s
ci / prune-artifacts (push) Skipped
ci / kernel-build (push) Skipped
ci / patches-apply (push) Successful in 39s
ci / kernel-symbols (push) Canceled after 4m16s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KerYPVh72hhNgKi3wS5ijG
2026-10-27 17:56:23 -06:00
BFE EngineeringandClaude Opus 5.5 9998182ef5 qemu: PAYLOAD_DIR lets one run boot its own payload set
ci / kernel-build (push) Canceled after 0s
ci / quality (push) Canceled after 0s
ci / badges (push) Canceled after 0s
ci / test (push) Canceled after 0s
ci / mcdc (push) Canceled after 0s
ci / bench (push) Canceled after 0s
ci / qemu-tools (push) Canceled after 0s
ci / kernel-symbols (push) Canceled after 0s
ci / patches-apply (push) Canceled after 0s
ci / prune-artifacts (push) Canceled after 0s
mkimage.sh copies PAYLOAD_DIR (default qemu/payload) into /usr/bin of both
slots and fails closed when it is not a directory; ui-drive.sh checks for
warden-ui in the same directory. flare-edge boots the hook set (production
payload plus the test-flavor UI and wthctl) for a flow that pins documents
while the other flows of a batch keep reading qemu/payload (flare-edge#2054).

qemu/tests/payload-dir.sh builds the images on a copy of qemu/ and reads
both rootfs slots back with debugfs; wired into CI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KerYPVh72hhNgKi3wS5ijG
2026-10-27 17:55:23 -06:00
BFE EngineeringandClaude Opus 5.5 dd15eac1a8 qemu: drive a flow's override step through the UI test hook
ci / kernel-build (push) Skipped
ci / patches-apply (push) Successful in 59s
ci / test (pull_request) Successful in 29s
ci / bench (pull_request) Successful in 5s
ci / bench (push) Successful in 13s
ci / qemu-tools (push) Successful in 1m56s
ci / prune-artifacts (pull_request) Skipped
ci / kernel-build (pull_request) Skipped
ci / patches-apply (pull_request) Successful in 1m5s
ci / kernel-symbols (push) Successful in 4m0s
ci / quality (pull_request) Successful in 1m51s
ci / test (push) Successful in 15s
ci / mcdc (push) Successful in 30s
ci / prune-artifacts (push) Skipped
ci / mcdc (pull_request) Successful in 30s
ci / qemu-tools (pull_request) Successful in 1m18s
ci / badges (pull_request) Skipped
ci / quality (push) Successful in 2m5s
ci / badges (push) Skipped
ci / kernel-symbols (pull_request) Successful in 5m14s
flowc compiles a flow's `override` action to `override TOPIC DOC|null`,
and a test-flavor warden-ui answers the override verb on test/req/ui, but
the rig driver had no such verb and the control bridge only reached the
UI's old FIFO, so a flow using it failed with an unknown command
(flare-edge #2054).

qmp.py `override` sends the request through the control bridge: the args
JSON in `@hookdoc` / `@hookdoc+` pieces of 2000 bytes (the ctl port is a
cooked tty that cuts a line at 4095 bytes; a document may be 16 KiB),
then `@hook override`. The bridge runs the payload's wthctl as bus user
testhook and answers its reply. ok:true passes, ok:false fails with the
hook's err, and a request that never reached the hook (no client, no
bus, no reply, a reply that is not a hook envelope) is fatal. The rig bus
writes a testhook credential. Only plain words reach the client.

ctl-bridge-test.sh covers the pieces, single use of the args, the word
filter, ok:false, no reply and no client, now also under busybox sh in
CI; test_qmp_drive.py covers the verb's ok, fail and fatal rows.

Refs flare-edge #2054.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KerYPVh72hhNgKi3wS5ijG
2026-10-27 13:46:00 -06:00
noah eeb779b41b Merge pull request 'qemu: start the device bus when the payload carries a broker' (#28) from rb/lf-rig-bus into rebuild
ci / mcdc (push) Successful in 31s
ci / prune-artifacts (push) Skipped
ci / patches-apply (push) Successful in 52s
ci / quality (push) Successful in 31s
ci / test (push) Successful in 24s
ci / bench (push) Successful in 14s
ci / badges (push) Skipped
ci / qemu-tools (push) Successful in 2m8s
ci / kernel-build (push) Skipped
ci / kernel-symbols (push) Successful in 6m0s
2026-10-26 16:00:20 -06:00
BFE EngineeringandClaude Opus 5.5 5494b87dc3 qemu: start the device bus when the payload carries a broker
ci / test (push) Successful in 28s
ci / prune-artifacts (push) Skipped
ci / patches-apply (push) Successful in 1m2s
ci / mcdc (push) Successful in 29s
ci / bench (push) Successful in 12s
ci / mcdc (pull_request) Successful in 11s
ci / prune-artifacts (pull_request) Skipped
ci / kernel-build (pull_request) Skipped
ci / kernel-build (push) Skipped
ci / quality (push) Successful in 27s
ci / badges (push) Skipped
ci / qemu-tools (pull_request) Successful in 1m9s
ci / patches-apply (pull_request) Successful in 57s
ci / test (pull_request) Successful in 26s
ci / bench (pull_request) Successful in 16s
ci / quality (pull_request) Successful in 1m29s
ci / kernel-symbols (pull_request) Successful in 6m50s
ci / qemu-tools (push) Successful in 2m15s
ci / kernel-symbols (push) Successful in 4m42s
ci / badges (pull_request) Skipped
A panel runs one mosquitto on /run/warden/bus/bus.sock (flare-edge S10bus)
and every daemon and the UI talk over it; the rig had no broker, so the
Rust warden-modbus and the UI's bus client could not run there (flare-edge
#1754, the #1050 QEMU half). Stage-2 init now starts the broker before the
payload daemons when the payload carries a static mosquitto, with the
panel's paths: the socket under sock/ with the bus.sock link, and a fresh
0400 credential file per bus user under cred/. The rig broker takes any
user and loads no plugin (the rig is a test instrument; a static broker
loads none). A payload without a broker boots as before.

qemu/tests/init-rig-bus-test.sh covers no broker, a listening broker (layout,
modes, config), a broker that exits or never listens, bad user names and the
init order, under sh and busybox sh; with WARDEN_TEST_MOSQUITTO_DIR a real
mosquitto carries a message between two users logged in by credential file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KerYPVh72hhNgKi3wS5ijG
2026-10-26 15:32:51 -06:00
noah 13cd0c63be Merge pull request 'qemu: name the cause when warden-ui stops answering a flow' (#26) from rb/ln-stall-diag into rebuild
ci / test (push) Successful in 17s
ci / bench (push) Successful in 16s
ci / kernel-build (push) Skipped
ci / patches-apply (push) Successful in 1m0s
ci / mcdc (push) Successful in 35s
ci / quality (push) Successful in 2m33s
ci / badges (push) Skipped
ci / prune-artifacts (push) Skipped
ci / qemu-tools (push) Successful in 2m16s
ci / kernel-symbols (push) Successful in 2m42s
2026-10-23 08:49:18 -06:00
noah d279bc4c9f Merge pull request 'qemu, build: bound the busybox and kernel fetches' (#27) from rb/lc2-fix-1588 into rebuild
ci / test (push) Successful in 28s
ci / mcdc (push) Successful in 39s
ci / kernel-build (push) Skipped
ci / bench (push) Successful in 19s
ci / qemu-tools (push) Successful in 2m54s
ci / patches-apply (push) Successful in 56s
ci / badges (push) Skipped
ci / kernel-symbols (push) Successful in 8m3s
ci / prune-artifacts (push) Skipped
ci / quality (push) Successful in 1m56s
2026-10-23 04:35:52 -06:00
BFE EngineeringandClaude Opus 5.5 44b96074ed qemu, build: bound the busybox and kernel fetches
ci / kernel-symbols (push) Successful in 7m23s
ci / bench (pull_request) Successful in 31s
ci / mcdc (pull_request) Successful in 38s
ci / patches-apply (pull_request) Successful in 59s
ci / kernel-symbols (pull_request) Successful in 5m20s
ci / bench (push) Successful in 34s
ci / patches-apply (push) Successful in 1m6s
ci / qemu-tools (push) Successful in 2m37s
ci / prune-artifacts (push) Skipped
ci / kernel-build (push) Skipped
ci / prune-artifacts (pull_request) Skipped
ci / kernel-build (pull_request) Skipped
ci / qemu-tools (pull_request) Successful in 2m46s
ci / test (push) Successful in 40s
ci / mcdc (push) Successful in 33s
ci / test (pull_request) Successful in 43s
ci / quality (push) Successful in 1m56s
ci / badges (push) Skipped
ci / quality (pull_request) Successful in 1m27s
ci / badges (pull_request) Skipped
qemu_get_busybox and fetch-kernel-tarball.sh ran curl with no connect
timeout, stall limit or total cap. A server that answered and then went
silent held the flare-edge QEMU UI gate build job until its 30 minute
timeout, with no retry (flare-edge #1588, run 7391 job 63953).

- qemu/lib.sh: each attempt gives up below 1 KiB/s for 20 s, or after
  60 s in all; curl retries once, the 3-attempt loop stays. Limits are
  overridable through BB_FETCH_* for the tests.
- build/fetch-kernel-tarball.sh: 20 s connect timeout, abort below
  10 KiB/s for 30 s, 600 s cap. The download lands in a temp file and is
  renamed on success, so a failed fetch no longer leaves a partial
  tarball that the next run takes as present and rejects on its sha256.
- Tests: busybox-fetch.sh serves a stalling local HTTP endpoint to the
  real curl (hung for the full 60 s guard before, fails in about 9 s
  after); new tests/fetch-kernel-tarball suite (bounded argv, no partial
  file, refetch after a failure, reuse of a matching tarball; 6 of 9
  checks red before). Both wired into CI and shellcheck.

Refs blueflare/flare-edge#1588

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KerYPVh72hhNgKi3wS5ijG
2026-10-23 00:23:47 -06:00
BFE EngineeringandClaude Opus 5.5 b7be6f7fbe qemu: name the cause when warden-ui stops answering a flow
ci / patches-apply (pull_request) Successful in 52s
ci / mcdc (push) Successful in 32s
ci / test (push) Successful in 24s
ci / kernel-build (pull_request) Skipped
ci / bench (push) Successful in 14s
ci / qemu-tools (push) Successful in 2m29s
ci / prune-artifacts (push) Skipped
ci / test (pull_request) Successful in 24s
ci / quality (push) Successful in 1m52s
ci / mcdc (pull_request) Successful in 31s
ci / bench (pull_request) Successful in 18s
ci / kernel-build (push) Skipped
ci / patches-apply (push) Successful in 52s
ci / badges (push) Skipped
ci / kernel-symbols (push) Successful in 5m55s
ci / qemu-tools (pull_request) Successful in 2m6s
ci / prune-artifacts (pull_request) Skipped
ci / quality (pull_request) Successful in 1m38s
ci / badges (pull_request) Skipped
ci / kernel-symbols (pull_request) Successful in 6m17s
flare-edge #1528: on the lenovo QEMU runner warden-ui stopped answering for
30 to 60 s at a time (bridge no-reply, presses not consumed) and then
recovered. Re-run jobs lose their failed-flow artifacts, so nothing showed
whether the host starved the VM, the guest CPU was saturated, the guest
waited on I/O, or warden-ui was blocked in an idle guest.

qmp.py drive() now probes the first three such failures of a run: over 2 s
it samples host load and PSI, the VM's vCPU thread CPU (query-cpus-fast
thread-id), the guest /proc/stat and every guest process's stat line, and
appends one line to the step's detail (verdict, numbers, top guest
processes, processes in D state). The detail reaches the job log, so the
answer survives a re-run. The control bridge answers the new `@procs`
command itself, so the probe works while the UI is stuck.

Tests: test_qmp_drive.py StallProbe (parsers, verdicts, CPU deltas, the
vCPU thread sampler, a bounded probe on no-reply steps and none on a plain
mismatch); ctl-bridge-test.sh checks `@procs` with no UI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KerYPVh72hhNgKi3wS5ijG
2026-10-22 06:31:07 -06:00
noah 7d18896a0d Merge pull request 'qemu: control bridge waits out a slow UI and never hands on a late reply' (#25) from rb/ln-ctl-bridge into rebuild
ci / test (push) Successful in 45s
ci / mcdc (push) Successful in 32s
ci / bench (push) Successful in 18s
ci / qemu-tools (push) Successful in 2m6s
ci / patches-apply (push) Successful in 1m5s
ci / prune-artifacts (push) Skipped
ci / kernel-build (push) Skipped
ci / quality (push) Successful in 1m47s
ci / badges (push) Skipped
ci / kernel-symbols (push) Successful in 11m1s
2026-10-21 01:49:13 -06:00
BFE EngineeringandClaude Opus 5.5 b94fd156b4 qemu: control bridge waits out a slow UI and never hands on a late reply
ci / test (push) Successful in 2m34s
ci / mcdc (push) Successful in 48s
ci / bench (push) Successful in 25s
ci / qemu-tools (push) Successful in 4m5s
ci / patches-apply (push) Successful in 2m26s
ci / quality (push) Successful in 1m36s
ci / prune-artifacts (pull_request) Skipped
ci / kernel-build (pull_request) Skipped
ci / prune-artifacts (push) Skipped
ci / kernel-build (push) Skipped
ci / kernel-symbols (push) Successful in 7m19s
ci / badges (push) Skipped
ci / mcdc (pull_request) Successful in 56s
ci / bench (pull_request) Successful in 17s
ci / test (pull_request) Successful in 2m29s
ci / patches-apply (pull_request) Successful in 1m25s
ci / qemu-tools (pull_request) Successful in 4m54s
ci / quality (pull_request) Successful in 2m16s
ci / badges (pull_request) Skipped
ci / kernel-symbols (pull_request) Successful in 5m57s
The bridge waited 5 s for warden-ui's reply. On the lenovo QEMU host a
page build outran it: the bridge answered an empty reply, and the UI's
late reply then landed after the next command's remove and was read as
that command's answer (flare-edge#1448: "page is ''", a nav answered
with the previous hit).

The loop moves to warden_ctl_bridge in etc/warden-lib.sh so a host test
reaches it. The wait is 30 s (WARDEN_CTL_WAIT_S); a timeout answers
"bridge: no reply from warden-ui ...", which qmp.py raises as a rig
fault, and the next command first drains the late reply. Replies slower
than 5 s are logged on the console with their time. qmp.py's control
socket timeout is 90 s so it outlasts the bridge's wait.

Tests: qemu/tests/ctl-bridge-test.sh (new, in CI), test_qmp_drive.py.

Refs flare-edge#1448

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KerYPVh72hhNgKi3wS5ijG
2026-10-21 00:32:37 -06:00
noah f435a7d665 Merge pull request 'qemu: power-signal test waits for the trap install (rebuild)' (#23) from rb/lf-fix-sdk22 into rebuild
ci / test (push) Successful in 9s
ci / mcdc (push) Successful in 15s
ci / qemu-tools (push) Successful in 52s
ci / patches-apply (push) Successful in 22s
ci / prune-artifacts (push) Skipped
ci / kernel-build (push) Skipped
ci / quality (push) Successful in 30s
ci / badges (push) Skipped
ci / bench (push) Successful in 9s
ci / kernel-symbols (push) Successful in 2m33s
2026-10-17 21:19:12 -06:00
BFE EngineeringandClaude Opus 5.5 be4ad86230 qemu: power-signal test waits for the trap install (#22)
ci / mcdc (pull_request) Successful in 16s
ci / test (push) Successful in 10s
ci / mcdc (push) Successful in 17s
ci / bench (push) Successful in 5s
ci / qemu-tools (push) Successful in 50s
ci / patches-apply (push) Successful in 24s
ci / prune-artifacts (push) Skipped
ci / kernel-build (push) Skipped
ci / kernel-symbols (push) Successful in 2m40s
ci / test (pull_request) Successful in 9s
ci / quality (push) Successful in 34s
ci / badges (push) Skipped
ci / bench (pull_request) Successful in 7s
ci / qemu-tools (pull_request) Successful in 54s
ci / prune-artifacts (pull_request) Skipped
ci / patches-apply (pull_request) Successful in 27s
ci / kernel-symbols (pull_request) Successful in 2m30s
ci / kernel-build (pull_request) Skipped
ci / quality (pull_request) Successful in 44s
ci / badges (pull_request) Skipped
init-power-signals-test.sh slept a fixed 0.5 s before sending each signal.
On a loaded runner the shell had not installed its traps yet, so SIGTERM
took its default action and the case failed with nothing written.

Each case now polls /proc/<pid>/status until SigCgt has the signal's bit
(10 s hang backstop, WARDEN_TEST_TRAP_WAIT_S), and fails clearly if the
handler never appears. Regression: a case whose handler install is held
back 1.5 s (fails on the old fixed sleep), plus a check that the wait gives
up on a shell without a handler.

Fixes #22

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KerYPVh72hhNgKi3wS5ijG
2026-10-17 17:51:08 -06:00
noah aadf0e7f07 Merge pull request 'qemu: input consumption wait is a hang backstop (flare-edge#1138)' (#20) from rb/lf-fix-1138 into rebuild
ci / test (push) Successful in 12s
ci / bench (push) Successful in 8s
ci / patches-apply (push) Successful in 24s
ci / mcdc (push) Successful in 20s
ci / qemu-tools (push) Successful in 1m12s
ci / quality (push) Successful in 31s
ci / kernel-symbols (push) Successful in 2m15s
ci / prune-artifacts (push) Skipped
ci / kernel-build (push) Skipped
ci / badges (push) Skipped
2026-10-17 17:19:08 -06:00
BFE EngineeringandClaude Opus 5.5 6f931bf3ad qemu: input consumption wait is a hang backstop (flare-edge#1138)
ci / bench (push) Successful in 8s
ci / qemu-tools (push) Successful in 57s
ci / patches-apply (push) Successful in 23s
ci / test (push) Successful in 12s
ci / mcdc (push) Successful in 21s
ci / prune-artifacts (push) Skipped
ci / kernel-build (push) Skipped
ci / quality (push) Successful in 55s
ci / kernel-symbols (push) Successful in 2m45s
ci / kernel-symbols (pull_request) Successful in 2m17s
ci / badges (push) Skipped
ci / qemu-tools (pull_request) Successful in 55s
ci / patches-apply (pull_request) Successful in 24s
ci / prune-artifacts (pull_request) Skipped
ci / kernel-build (pull_request) Skipped
ci / quality (pull_request) Successful in 28s
ci / badges (pull_request) Skipped
ci / test (pull_request) Successful in 11s
ci / bench (pull_request) Successful in 6s
ci / mcdc (pull_request) Successful in 13s
The runner waited 2 s for the guest to count an injected press or
release. On a loaded runner the release that opens the drawer took
longer, so navigation/drawer-drag-release-policy failed both attempts
although the UI handled the swipe. The wait is now a 20 s hang backstop;
a wait over 2 s still passes and puts "slow guest: input consumed after
N s" in the step's detail.

Regression: test_swipe_release_counted_late_on_a_loaded_guest_passes
(release counted 2.5 s after the drag; fails with the 2 s bound), plus
a prompt-release case and a never-counted case bounded by the backstop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KerYPVh72hhNgKi3wS5ijG
2026-10-17 14:24:59 -06:00
noahandClaude Sonnet 5.5 5507842878 Merge pull request 'Single M0 kernel batch with CONFIG_SUSPEND off' (#17) from rb/w04-kernel-options into rebuild
ci / kernel-symbols (push) Successful in 1m40s
ci / patches-apply (push) Successful in 15s
ci / prune-artifacts (push) Skipped
ci / kernel-build (push) Skipped
ci / quality (push) Successful in 25s
ci / badges (push) Skipped
ci / test (push) Successful in 8s
ci / mcdc (push) Successful in 13s
ci / bench (push) Successful in 5s
ci / qemu-tools (push) Successful in 46s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cxh2piVufTWbzKTmUafTkk
2026-10-09 20:08:37 -06:00
23 changed files with 2665 additions and 98 deletions
+46 -1
View File
@@ -112,7 +112,7 @@ jobs:
qemu/rootfs/etc/warden-lib.sh qemu/rootfs/etc/rc \
qemu/rootfs/sbin/init qemu/rootfs/init tests/mk-bootimg/*.sh \
tests/fetch-vendor/*.sh tests/fetch-buildroot-tarball/*.sh \
tests/unpack-buildroot/*.sh
tests/fetch-kernel-tarball/*.sh tests/unpack-buildroot/*.sh
- name: qemu init shellcheck regression test
run: bash tests/qemu-init/run-init-shellcheck-tests.sh
- name: cache apt archives (python3-pil)
@@ -155,11 +155,48 @@ jobs:
run: bash qemu/tests/init-power-signals-test.sh
- name: rig init daemon order matches the panel (flare-edge#348)
run: bash qemu/tests/init-daemon-order-test.sh
- name: rig bus starts when the payload carries a broker (flare-edge#1754)
# A stub broker stands in for mosquitto (the runner has none), and
# once more under busybox sh, the rig's own shell.
run: |
bash qemu/tests/init-rig-bus-test.sh
if command -v busybox >/dev/null; then
WARDEN_TEST_SH="busybox sh" bash qemu/tests/init-rig-bus-test.sh
fi
- name: rig control bridge waits out a slow UI and reaches the test hook (flare-edge#1448, #2054)
# Once more under busybox sh, the rig's own shell.
run: |
bash qemu/tests/ctl-bridge-test.sh
if command -v busybox >/dev/null; then
WARDEN_TEST_SH="busybox sh" bash qemu/tests/ctl-bridge-test.sh
fi
- name: rig init boots through the shipped init chain (flare-edge#2210)
# warden_init_chain against stub scripts and the warden.initchain
# wiring in sbin/init; once more under busybox sh, the rig's own shell.
run: |
bash qemu/tests/init-chain-test.sh
if command -v busybox >/dev/null; then
WARDEN_TEST_SH="busybox sh" bash qemu/tests/init-chain-test.sh
fi
- name: ui-drive.sh / ui-shot.sh UI start wait regression test (flare-edge#2295)
# The console line that means "UI started" differs between a direct
# start and a shipped init chain boot; every marker is checked
# against sbin/init, and a chain failure fails at once.
run: bash qemu/tests/ui-start-test.sh
- name: mkimage.sh ROOTFS_OVERLAY regression test (flare-edge#2210)
# The panel's scripts land in both slots with their modes; an overlay
# reaching outside etc/ and usr/, or holding a symlink, writes no image.
run: bash qemu/tests/rootfs-overlay.sh
- name: mkimage.sh SEED_DIR regression test
# Only ui-drive.sh --seed (a real VM boot) exercises this hook
# otherwise; this builds the same unprivileged mkfs.ext4 image and
# reads it back with debugfs, no VM needed.
run: bash qemu/tests/seed-dir.sh
- name: mkimage.sh PAYLOAD_DIR regression test (flare-edge#2054)
# A run's own payload set (the hook set) lands in both slots, the
# default still reads qemu/payload, and ui-drive.sh checks the same
# directory; images read back with debugfs, no VM.
run: bash qemu/tests/payload-dir.sh
- name: qemu_stage_rootfs permission regression test
# Git tracks only the executable bit, so a fresh checkout can land
# the source etc/shadow world-readable under a permissive umask;
@@ -173,6 +210,14 @@ jobs:
# Retry-on-mismatch, cleanup, and the already-verified
# short-circuit, against a fake curl on PATH: no network.
run: bash tests/fetch-buildroot-tarball/run-fetch-buildroot-tarball-tests.sh
- name: fetch-kernel-tarball regression tests
# Bounded curl and no partial tarball after a failed fetch (#1588),
# against a fake curl on PATH: no network.
run: bash tests/fetch-kernel-tarball/run-fetch-kernel-tarball-tests.sh
- name: QEMU busybox fetch regression tests
# Retry on a bad sha256, the cached copy, and a server that answers
# and then stalls (#1588), against local listeners: no network.
run: bash qemu/tests/busybox-fetch.sh
- name: unpack-buildroot regression tests
# Fresh unpack, leave-existing-tree-alone, and every refusal path
# (unpatched selectors, bad tarball, half-present tree, failed
+10 -1
View File
@@ -22,7 +22,16 @@ TB="${1:?usage: fetch-kernel-tarball.sh <destination-path>}"
}
if [ ! -f "$TB" ]; then
echo "== downloading $URL"
curl --retry 3 --retry-delay 5 --retry-connrefused -fSL "$URL" -o "$TB"
# Bounded (#1588): a connection that opens and then stalls gives up after
# 30 s below 10 KiB/s and is retried, instead of holding the job until its
# own timeout. The download lands beside $TB and is renamed only when curl
# succeeds, so a failed fetch never leaves a partial tarball that the next
# run would take as present and then reject on its sha256.
tmp="$TB.download.$$"
trap 'rm -f "$tmp"' EXIT
curl --retry 2 --retry-delay 5 --retry-connrefused --connect-timeout 20 \
--speed-limit 10240 --speed-time 30 --max-time 600 -fSL "$URL" -o "$tmp"
mv -f "$tmp" "$TB"
fi
want="$(cat "$SHA_FILE")"
got="$(sha256sum "$TB" | awk '{print $1}')"
+32
View File
@@ -73,6 +73,16 @@ daemons a bench panel already runs: flare-edge `tools/rig-pull-daemons.sh
chardev without `--rs485`), so `warden-modbus` polls a port with nothing on
it, as on a panel with an empty header, and never the control channel.
A `mosquitto` in the payload starts the panel's device bus first (socket
`/run/warden/bus/bus.sock`, one credential file per bus user under
`/run/warden/bus/cred/`), as S10bus does before every bus client on a panel;
see `payload/README.md`. The rig broker takes any user and loads no plugin.
With a test-flavor `warden-ui` and `wthctl` (flare-edge `tools/wthctl.c`, the
test hook client) in the payload as well, a flow's `override` step pins a
state document inside the UI: qmp.py hands the request to the control bridge
(`@hookdoc` pieces, then `@hook override`), which sends it to `test/req/ui`
as bus user `testhook` and answers the hook's reply.
The VT cursor is kept off (`vt.global_cursor_default=0`): fbcon shares the
virtio-gpu framebuffer with warden-ui and its blinking cursor would otherwise
show up in screendumps at random (issue #18).
@@ -85,6 +95,23 @@ does on a panel instead of rejecting every attempt. `qemu_stage_rootfs()`
the executable bit, so the checked-out source file's own mode depends on the
checking-out umask and cannot be trusted to arrive non-world-readable.
`--append warden.initchain` boots the UI the way a panel does (flare-edge
#2210). The caller lays the panel's own scripts over the rootfs with
`ROOTFS_OVERLAY=<dir> mkimage.sh` (only `etc/` and `usr/` at its top, no
symlinks). Stage-2 init then starts `/etc/init.d/S00`-`S09` with `start`
before the bus (S03warden-accounts creates the platform accounts, and the
bus hands `cred/ui` to `warden-ui`), and `S10`-`S99` after the payload
daemons in place of its direct root start of `warden-ui`. S99lvgl then runs
`warden-ui-run`, which drops the UI to its account and respawns it. Rig
differences: the splash handover is marked done (no S09splash) and
warden-ui-run passes `-b fbdev`, not the panel's `-b drm`. A chain boot
with no script prints `WARDEN-QEMU-INITCHAIN-EMPTY` and starts no UI.
`tests/ui-drive.sh --init-chain <dir>` does both steps, and the drive verb
`assert_ui_chain` judges the result: one `warden-ui` and one `warden-ui-run`,
the UI's four uids all `warden-ui`'s, no safe-mode flag, and no exit or
refusal in `/tmp/warden-ui.log`. `tests/scripts/init-chain-ui.txt` runs the
check at about T+120 s.
A flow seed may contain `qemu-flow-setup.sh`. Stage-2 init runs it inside the
disposable guest after mounting userdata and before starting daemons or the
UI. A nonzero exit stops the boot. Use it only for test devices and commands
@@ -98,6 +125,7 @@ All take the virt-fragment `<zImage>`; `FLARE_EDGE=<checkout>` where noted.
|---|---|---|
| `stage-rootfs-perms.sh` | - | offline, no VM: `qemu_stage_rootfs()` always lands `etc/shadow` at 0600, even staged from a source copy deliberately left 0644 |
| `seed-dir.sh` | - | offline, no VM: `mkimage.sh`'s `SEED_DIR` hook lands every seeded file under userdata/warden with its original mode (a 0600 secret included), a seeded file beats a same-named `--state` value, a `SEED_DIR` that isn't a directory fails closed, and so does an individual entry that is a symlink, a subdirectory, or named outside `[A-Za-z0-9_.-]+` -- a hyphenated key such as `gas-plant.devices` still seeds cleanly |
| `payload-dir.sh` | - | offline, no VM: `mkimage.sh`'s `PAYLOAD_DIR` hook puts the run's own payload set (symlinked entries included, as regular 0755 files; its README.md skipped) into `/usr/bin` of both slots and nothing from `qemu/payload`, the default still reads `qemu/payload`, a `PAYLOAD_DIR` that is not a directory fails closed, and `ui-drive.sh` looks for `warden-ui` in the same directory |
| `boot-smoke.sh` | - | sentinel-asserting boot; runs in CI inside kernel-build |
| `portal-scenario.sh` | `FLARE_EDGE` | real flared against the desk mock portal: authenticated check-in, desired-state pull, signed tier-1 `.wfw` download; verify/stage/APPLYING as a dry run (no `WARDEN_FW_ALLOW_APPLY`) |
| `ota-apply.sh` | `FLARE_EDGE` | the FULL apply: the `.wfw`'s bootable rootfs payload is written to rootfs_b (`run.sh --allow-apply` gates it per boot), the AvbABData in `misc` flips, and slot `_b` boots the applied version |
@@ -105,7 +133,11 @@ All take the virt-fragment `<zImage>`; `FLARE_EDGE=<checkout>` where noted.
| `ui-drive.sh <script>` | - | the same rig for a SEQUENCE: boots once, runs a `qmp.py drive` script of taps/swipes/screenshots in panel pixels, and FAILS if warden-ui died on the way (stage-2 init announces the exit on the console). `tests/scripts/nav-stress.txt` is the navigation regression: it reproduces the s_row_left overflow that segfaulted the UI on returning to Settings > Apps; `tests/scripts/home-leaves-fullscreen.txt` proves the `home` verb clears dashboard fullscreen, the state a hardware wake tap leaves behind (flare-edge #176); `tests/scripts/fullscreen-toggle-tracks-real-state.txt` proves a `fullscreen toggle` right after `home` (or a real tap) reads the dashboard's actual state rather than a belief `home` bypassed -- `test_qmp_drive.py`'s `FullscreenToggleTracksRealState` pins the same contract offline |
| `real-image-boot.sh` | matched `rootfs.img` + `oem.img` | an ACTUAL flare-edge build (placed by `mkimage.sh --rootfs-image/--oem-image`) boots its own init chain to getty; binaries predating known fixes reproduce their bugs faithfully, a time machine for field issues |
| `test-ui-drive-rs485.sh` | - | offline, no VM: a fake `run.sh` and (for one case) a fake `socat` stand in so `ui-drive.sh --rs485-devices`'s startup fails closed instead of printing a false "== rs485 simulator: ..." over a bus nothing is serving, for each of a qemu rs.sock that never appears, a socat that never links rs.pty, and an mbsim.py that dies before opening rs.ctl; also proves `cleanup()` escalates to SIGKILL for a sim process that ignores SIGTERM |
| `rootfs-overlay.sh` | - | offline, no VM: `mkimage.sh`'s `ROOTFS_OVERLAY` hook lays a directory of panel files (flare-edge's S03warden-accounts, S99lvgl, warden-ui-run) over the rootfs of both slots with their modes kept, beside the skeleton's own files; without it there is no `/etc/init.d`; an overlay that is not a directory, names anything but `etc/` and `usr/` at its top, or holds a symlink fails closed and writes no image; `ui-drive.sh --init-chain` refuses a missing directory or one without `etc/init.d/S99lvgl` before boot |
| `init-chain-test.sh` | - | offline, no VM: `warden_init_chain` (rootfs/etc/warden-lib.sh) starts the executable `S<NN>*` scripts of a number range in name order, names a failing one and goes on, and counts them; `warden_rig_bus_owners` hands a bus credential to its account only when the rootfs has it; sbin/init runs S00-S09 before the bus and S10-S99 instead of the direct UI start on a `warden.initchain` boot (flare-edge #2210) |
| `run-sh-args-test.sh` | - | offline, no VM: a fake `qemu-system-arm` captures run.sh's own argv and pins the ctl/rs485 pci-serial ordering contract rootfs/sbin/init's ttyS0-vs-ttyS1 alias depends on -- the ctl device always enumerates before rs485, warden.ctl only lands on the cmdline when --ctl is given, and an rs485 pci-serial device (real or null-backed) is always present so the port count never shifts |
| `ctl-bridge-test.sh` | - | offline, no VM: runs the control bridge (`warden_ctl_bridge` in rootfs/etc/warden-lib.sh) against a fake warden-ui that answers some commands late. A reply slower than the old 5 s bound still arrives (the bound is now 30 s, `WARDEN_CTL_WAIT_S`), a timeout answers `bridge: no reply from warden-ui ...` (qmp.py raises it as a rig fault), and a timed-out command's late reply is drained instead of being read as the next command's answer (flare-edge #1448). A fake `wthctl` stands in for the hook client behind `@hookdoc`/`@hook` (flare-edge #2054): the pieces join into one request whose args are used once, only plain words reach the client, and a missing client or a request with no reply answers a `bridge:` line. CI runs it under bash's `sh` and busybox `sh` |
| `init-rig-bus-test.sh` | - | offline, no VM: `warden_rig_bus` in rootfs/etc/warden-lib.sh against stub brokers. No broker in the payload creates nothing; a broker that listens gets the panel's layout (the `bus.sock` link, a 0400 64-hex credential per bus user, a config without password file, ACL or plugin); a broker that exits or never listens is reported within the bound; init starts the bus before the payload daemons. `WARDEN_TEST_MOSQUITTO_DIR` adds a real mosquitto carrying one message between two users logged in by credential file (flare-edge #1754) |
| watchdog (`run.sh --watchdog`) | - | arm `/dev/watchdog`, don't pet: the VM resets ~30 s later (verified) |
Scenario fine print:
+10 -1
View File
@@ -33,11 +33,20 @@ qemu_get_busybox() {
qemu_log "cached busybox failed verification; fetching a clean copy"
fi
# Every attempt is bounded: a server that answers and then stalls would
# otherwise hold the job until its own timeout, with no retry (#1588). Below
# 1 KiB/s for the stall window, or past the total cap, curl gives up and the
# loop moves on. Defaults cap the worst case near 6 minutes; the tests
# shorten them through the environment.
local stall="${BB_FETCH_STALL_SECS:-20}" max="${BB_FETCH_MAX_SECS:-60}"
local delay="${BB_FETCH_RETRY_DELAY:-5}"
local attempt tmp="${BB}.download.$$"
rm -f "$tmp"
for attempt in 1 2 3; do
qemu_log "downloading $BB_URL (attempt $attempt/3)"
if curl --retry 3 --retry-delay 5 --retry-connrefused -fSL "$BB_URL" -o "$tmp"; then
if curl --retry 1 --retry-delay "$delay" --retry-connrefused \
--connect-timeout "$stall" --speed-limit 1024 --speed-time "$stall" \
--max-time "$max" -fSL "$BB_URL" -o "$tmp"; then
got="$(sha256sum "$tmp" | awk '{print $1}')"
if [ "$want" = "$got" ]; then
mv -f "$tmp" "$BB"
+34 -1
View File
@@ -17,6 +17,20 @@
# Env:
# BUSYBOX path to a local busybox binary (skips the download; still verified)
# OUT output dir (default: qemu/out); image at $OUT/disk.img
# PAYLOAD_DIR the directory whose binaries land in /usr/bin of both slots
# (default qemu/payload). Lets one run boot its own payload set
# (flare-edge's hook set for a flow that pins documents: the
# production payload plus the test-flavor UI and wthctl) while
# other runs read qemu/payload at the same time. Not a
# directory: fails closed.
# ROOTFS_OVERLAY a directory laid over the staged rootfs of both slots,
# after the payload, with its modes kept (cp -a). Only etc/ and
# usr/ may appear at its top, and no entry may be a symlink, so
# it can neither replace the rig's own /init and /sbin/init nor
# point outside the image. flare-edge #2210 stages the panel's
# S03warden-accounts, S99lvgl and /usr/lib/warden/warden-ui-run
# this way for a boot with warden.initchain (rootfs/sbin/init).
# Not a directory, or a disallowed entry: fails closed.
# SEED_DIR a directory of pre-built userdata/warden files (one file per
# settings key, e.g. flare-edge tools/seed-fixtures.py's output)
# copied in VERBATIM, after --portal-url/--state. Lets a caller
@@ -72,12 +86,31 @@ trap 'rm -rf "$SCRATCH"' EXIT
# both slots so A and B start byte-identical, like a factory flash.
ROOT="$SCRATCH/root"
qemu_stage_rootfs "$ROOT"
for p in "$QEMU_DIR"/payload/*; do
PAYLOAD_DIR="${PAYLOAD_DIR:-$QEMU_DIR/payload}"
[ -d "$PAYLOAD_DIR" ] || { echo "FATAL: PAYLOAD_DIR '$PAYLOAD_DIR' is not a directory" >&2; exit 1; }
for p in "$PAYLOAD_DIR"/*; do
[ -f "$p" ] || continue
case "$(basename "$p")" in README.md) continue ;; esac
install -m 0755 "$p" "$ROOT/usr/bin/$(basename "$p")"
done
# ROOTFS_OVERLAY (see the Env note above): checked whole before anything of
# it is copied, so a refused overlay leaves no partial tree and no image.
if [ -n "${ROOTFS_OVERLAY:-}" ]; then
[ -d "$ROOTFS_OVERLAY" ] || { echo "FATAL: ROOTFS_OVERLAY '$ROOTFS_OVERLAY' is not a directory" >&2; exit 1; }
for entry in "$ROOTFS_OVERLAY"/* "$ROOTFS_OVERLAY"/.[!.]*; do
[ -e "$entry" ] || [ -L "$entry" ] || continue
case "$(basename "$entry")" in
etc|usr) [ -d "$entry" ] && [ ! -L "$entry" ] && continue ;;
esac
echo "FATAL: ROOTFS_OVERLAY may hold only the directories etc/ and usr/ at its top, not '$(basename "$entry")'" >&2
exit 1
done
links="$(find "$ROOTFS_OVERLAY" -type l)"
[ -z "$links" ] || { echo "FATAL: ROOTFS_OVERLAY holds symlinks: $links" >&2; exit 1; }
cp -a "$ROOTFS_OVERLAY"/. "$ROOT/"
fi
# Firmware version stamp: same path the device build writes; flared reads its
# running version here (downgrade rules key off it).
printf '%s\n' "$FW_VERSION" > "$ROOT/etc/warden-firmware-version"
+11
View File
@@ -3,6 +3,10 @@
Drop **static musl armv7** binaries in this directory (contents are
gitignored; binaries are never committed); `qemu/mkimage.sh` copies everything
in this directory (except this README) into `/usr/bin/` of both rootfs slots.
`PAYLOAD_DIR=<dir>` points one run (`mkimage.sh`, `tests/ui-drive.sh`) at
another directory instead, so a caller can boot its own set, such as
flare-edge's hook set for a flow that pins documents, while other runs read
this one.
Static musl is the same target the device uses for its Rust daemons, so the
exact production binaries run unmodified in the VM.
@@ -26,6 +30,13 @@ musl binary, so flare-edge `tools/rig-pull-daemons.sh --host <panel>` copies
release and each md5 in `PULLED.txt`), minus `warden-ui`, which the rig
needs as the fbdev+evdev build.
A `mosquitto` here (the static armhf broker of flare-edge
`tools/mosquitto-build.sh armhf`) gives the guest the panel's device bus:
stage-2 init starts it on `/run/warden/bus/bus.sock` before any daemon and
writes a credential file per bus user to `/run/warden/bus/cred/<user>`
(`warden_rig_bus` in `qemu/rootfs/etc/warden-lib.sh`; the broker log is
`/tmp/mosquitto.log`). Without it the guest has no bus, as before.
Stage-2 init starts every `warden-*` daemon it finds here, in the panel's
own S-number order (ai, automation, modbus, mikrotik, asic, starlink,
stratum, flared), then `warden-ui` (the UI also needs `--display
+304
View File
@@ -62,3 +62,307 @@ warden_idle_forever() {
wait $!
done
}
# The control bridge's command loop (/sbin/init runs it on the ctl serial
# port): one command per line on stdin, the reply then the sentinel line
# <<END>> on stdout. qmp.py's Ctl matches the sentinel byte for byte.
#
# `@cat PATH` is answered here and never forwarded: PATH's contents (or one
# "bridge: no such file: PATH" line), which is how the json flow channel
# reads webstatus.c's snapshot from outside the VM. `@procs` is answered
# here too: every /proc/<pid>/stat line, for qmp.py's stall probe
# (flare-edge #1528). Everything else goes to
# warden-ui's FIFO, and the bridge waits for the reply file the UI renames
# into place whole. The previous reply is removed BEFORE sending: a fixed
# settle handed back the previous command's reply (flare-edge #152).
#
# The wait is bounded by WARDEN_CTL_WAIT_S (default 30 s of polling). It was
# 5 s, and a slow QEMU host (lenovo-x3650, two TCG guests) let a page build
# outrun it: the bridge answered an empty reply, and the UI's late reply
# then landed after the NEXT command's remove and was read as that
# command's answer (flare-edge #1448). Now a timeout answers one
# "bridge: no reply from warden-ui ..." line (qmp.py treats it as a rig
# fault), and the next command first waits, on the same bound, for the late
# reply and discards it. A reply slower than 5 s is logged on stderr (the
# console) with its time, for the host-speed baselines.
#
# `@hook WORDS` is answered here too: one request to the UI's test hook on
# the device bus (test/req/ui, flare-edge docs/bus-test-hook.md), sent by the
# payload's hook client (wthctl, as bus user testhook) and answered with its
# reply JSON. WORDS are the client's own words, the verb last (`override`,
# or `--to flared VERB` for flared's hook); the request's args JSON is the
# text the `@hookdoc TEXT` / `@hookdoc+ TEXT` lines before it wrote (the first
# starts it, each `+` appends), or `{}` when there were none. The args come in
# pieces because the ctl port is a tty in cooked mode, which cuts a line at
# 4095 bytes, and an override document may be 16 KiB. A hook request that
# never reached the hook (no client in the payload, no bus, no reply) answers
# one "bridge: ..." line, which qmp.py treats as a rig fault, not a verdict.
#
# WARDEN_CTL_FIFO, WARDEN_CTL_REPLY, WARDEN_CTL_HOOKDOC, WARDEN_WTHCTL and
# WARDEN_BUS_RUN exist for the host test only.
warden_ctl_bridge() {
_wcb_fifo="${WARDEN_CTL_FIFO:-/tmp/warden-ui.ctl}"
_wcb_reply="${WARDEN_CTL_REPLY:-/tmp/warden-ui.dbg}"
_wcb_hookdoc="${WARDEN_CTL_HOOKDOC:-/tmp/warden-ctl-hook.args}"
_wcb_limit=$(( ${WARDEN_CTL_WAIT_S:-30} * 20 ))
_wcb_stale=0
while IFS= read -r cmd; do
[ -n "$cmd" ] || continue
case "$cmd" in
"@cat "*)
path="${cmd#@cat }"
if [ -f "$path" ]; then
cat "$path"
# The status json has no trailing newline; without this
# the sentinel would share its line and the line-based
# reader would never see it.
echo
else
echo "bridge: no such file: $path"
fi
;;
"@hookdoc "*)
printf '%s' "${cmd#@hookdoc }" > "$_wcb_hookdoc"
echo "hookdoc: $(wc -c < "$_wcb_hookdoc") bytes"
;;
"@hookdoc+ "*)
if [ -f "$_wcb_hookdoc" ]; then
printf '%s' "${cmd#@hookdoc+ }" >> "$_wcb_hookdoc"
echo "hookdoc: $(wc -c < "$_wcb_hookdoc") bytes"
else
echo "bridge: @hookdoc+ without a @hookdoc before it"
fi
;;
"@hook "*)
_wcb_hook "${cmd#@hook }"
;;
"@procs")
# Every process's stat line, for the driver's stall probe
# (qmp.py stall_report, flare-edge #1528); needs no UI.
cat /proc/[0-9]*/stat 2>/dev/null
;;
*)
if [ -p "$_wcb_fifo" ]; then
if [ "$_wcb_stale" = 1 ]; then
_wcb_wait_reply
_wcb_stale=0
fi
rm -f "$_wcb_reply"
printf '%s\n' "$cmd" > "$_wcb_fifo"
if _wcb_wait_reply; then
cat "$_wcb_reply" 2>/dev/null
else
echo "bridge: no reply from warden-ui within $((_wcb_limit / 20)) s: $cmd"
_wcb_stale=1
fi
if [ "$_wcb_n" -gt 100 ]; then
echo "ctl bridge: slow reply, $((_wcb_n / 20)) s of polling: $cmd" >&2
fi
else
echo "bridge: warden-ui control FIFO not present"
fi
;;
esac
echo "<<END>>"
done
}
# One test hook request for `@hook WORDS` (see warden_ctl_bridge). The args
# file is used once: removed before the client runs, so a later request
# never inherits it.
_wcb_hook() {
_wch_words="$1"
_wch_args='{}'
if [ -f "$_wcb_hookdoc" ]; then
_wch_args="$(cat "$_wcb_hookdoc")"
rm -f "$_wcb_hookdoc"
fi
# The words reach the client unquoted (one argument each), so only plain
# verb and flag characters pass: no glob or quote can reach the shell.
if [ -z "$(printf '%s' "$_wch_words" | tr -d ' ')" ] ||
[ -n "$(printf '%s' "$_wch_words" | tr -d 'A-Za-z0-9_ -')" ]; then
echo "bridge: bad hook request: $_wch_words"
return 0
fi
_wch_client="${WARDEN_WTHCTL:-/usr/bin/wthctl}"
_wch_bus="${WARDEN_BUS_RUN:-/run/warden/bus}"
if [ ! -x "$_wch_client" ]; then
echo "bridge: no hook client in the payload ($_wch_client)"
return 0
fi
# shellcheck disable=SC2086 # one argument per checked word, see above
_wch_out="$("$_wch_client" "$_wch_bus/bus.sock" "$_wch_bus/cred/testhook" $_wch_words "$_wch_args" 2>&1)"
_wch_rc=$?
# wthctl: 0 ok:true, 1 ok:false (both are the hook's answer), 2 no
# connection or no reply.
if [ "$_wch_rc" -le 1 ]; then
printf '%s\n' "$_wch_out"
else
echo "bridge: hook request got no answer (client exit $_wch_rc): $(printf '%s' "$_wch_out" | tr '\n' ' ')"
fi
}
# Polls for a non-empty reply file every 0.05 s, up to the bridge's bound;
# leaves the poll count in _wcb_n.
_wcb_wait_reply() {
_wcb_n=0
while [ ! -s "$_wcb_reply" ]; do
[ "$_wcb_n" -ge "$_wcb_limit" ] && return 1
sleep 0.05
_wcb_n=$((_wcb_n + 1))
done
}
# The rig's device bus (flare-edge #1754, the #1050 QEMU half). A panel runs
# one mosquitto on /run/warden/bus/bus.sock (flare-edge S10bus) and every
# daemon, the UI included, talks over it. The rig starts the same broker
# when the payload carries one (/usr/bin/mosquitto, the static armhf build of
# flare-edge tools/mosquitto-build.sh); a payload without it boots exactly as
# before, with no bus.
#
# Same paths as the panel, so the production clients need no rig switch:
# the socket at <bus>/sock/bus.sock with the <bus>/bus.sock link clients
# dial, and one credential file per bus user at <bus>/cred/<user>, which a
# client reads at every CONNECT. What the rig leaves out, on purpose: the
# password file and ACL (the broker takes any user; the rig is a test
# instrument and every process in it runs as root anyway) and the retain gate
# plugin (a static broker loads no plugins). The credential files hold a
# fresh random secret all the same, so a client finds what it expects.
#
# WARDEN_RIG_BUS_USERS lists the bus users that get a credential file: the
# panel's /etc/warden/bus/users and bundled-users (flare-edge busgen output),
# plus testhook, the user the control bridge's `@hook` client logs in as (a
# test-flavor panel has it too).
# WARDEN_RIG_BROKER, WARDEN_BUS_RUN, WARDEN_RIG_BUS_LOG and
# WARDEN_RIG_BUS_WAIT_S exist for the host test only.
warden_rig_bus() {
_wrb_broker="${WARDEN_RIG_BROKER:-/usr/bin/mosquitto}"
[ -x "$_wrb_broker" ] || return 0
_wrb_dir="${WARDEN_BUS_RUN:-/run/warden/bus}"
_wrb_log="${WARDEN_RIG_BUS_LOG:-/tmp/mosquitto.log}"
_wrb_users="${WARDEN_RIG_BUS_USERS:-flared ui io modbus appd telemetry automation.main testhook}"
if ! mkdir -p "$_wrb_dir/cred" "$_wrb_dir/sock"; then
echo "init: rig bus FAILED: cannot create $_wrb_dir"
return 1
fi
chmod 0751 "$_wrb_dir"
chmod 0710 "$_wrb_dir/cred"
# The panel's broker settings (flare-edge
# overlay-flare-warden-ui/etc/warden/bus/mosquitto.conf) minus the
# password file, ACL and plugin lines (see above). `user root` keeps the
# broker from dropping to an account the rig rootfs does not have.
cat > "$_wrb_dir/mosquitto.conf" <<WRB_CONF
# QEMU rig broker, written by warden_rig_bus (qemu/rootfs/etc/warden-lib.sh).
user root
listener 0 $_wrb_dir/sock/bus.sock
allow_anonymous true
pid_file $_wrb_dir/sock/mosquitto.pid
use_username_as_clientid true
persistence false
message_size_limit 131072
max_packet_size 135168
max_connections 128
max_queued_messages 1000
max_queued_bytes 2097152
max_inflight_messages 20
max_qos 1
max_keepalive 60
sys_interval 0
connection_messages false
log_dest stderr
log_type error
log_type warning
WRB_CONF
for _wrb_u in $_wrb_users; do
case "$_wrb_u" in
''|*/*|.*) echo "init: rig bus: bad user name '$_wrb_u' skipped"; continue ;;
esac
rm -f "$_wrb_dir/cred/$_wrb_u"
(umask 077; od -An -tx1 -N32 /dev/urandom | tr -d ' \n' > "$_wrb_dir/cred/$_wrb_u")
chmod 0400 "$_wrb_dir/cred/$_wrb_u"
done
warden_rig_bus_owners "$_wrb_dir"
ln -sfn sock/bus.sock "$_wrb_dir/bus.sock"
ln -sfn sock/mosquitto.pid "$_wrb_dir/mosquitto.pid"
"$_wrb_broker" -c "$_wrb_dir/mosquitto.conf" > "$_wrb_log" 2>&1 &
_wrb_pid=$!
# Clients retry a missing socket, but a daemon started before the broker
# listens logs a refused first dial: wait for the socket (0.1 s polls,
# bounded) so the payload daemons find it on their first try.
_wrb_n=0
_wrb_limit=$(( ${WARDEN_RIG_BUS_WAIT_S:-10} * 10 ))
while [ ! -S "$_wrb_dir/sock/bus.sock" ]; do
if ! kill -0 "$_wrb_pid" 2>/dev/null; then
echo "init: rig bus FAILED: the broker exited; log tail:"
tail -n 5 "$_wrb_log" 2>/dev/null
return 1
fi
if [ "$_wrb_n" -ge "$_wrb_limit" ]; then
echo "init: rig bus FAILED: no socket after $((_wrb_limit / 10)) s"
return 1
fi
sleep 0.1
_wrb_n=$((_wrb_n + 1))
done
echo "init: rig bus up on $_wrb_dir/bus.sock (broker pid $_wrb_pid)"
}
# warden_rig_bus_owners <bus dir>: give a credential file to the account that
# reads it, when the rootfs has that account. The rig rootfs has none of the
# platform accounts, so by default this changes nothing and every client runs
# as root. A boot through the shipped init chain (warden.initchain, see
# warden_init_chain) creates them first with S03warden-accounts; then the UI
# runs as warden-ui, as on a panel, and needs its own credential: S10bus there
# makes cred/<user> 0400 owned by the daemon's account in a cred directory of
# group warden-bus, mode 0710. Pairs are user=account.
# WARDEN_RIG_BUS_OWNERS, WARDEN_RIG_PASSWD and WARDEN_RIG_GROUP exist for the
# host test only.
warden_rig_bus_owners() {
_wro_passwd="${WARDEN_RIG_PASSWD:-/etc/passwd}"
_wro_group="${WARDEN_RIG_GROUP:-/etc/group}"
if grep -q '^warden-bus:' "$_wro_group" 2>/dev/null; then
chgrp warden-bus "$1/cred" || echo "init: rig bus: chgrp warden-bus $1/cred failed"
fi
for _wro_pair in ${WARDEN_RIG_BUS_OWNERS:-ui=warden-ui}; do
_wro_user="${_wro_pair%%=*}"
_wro_acct="${_wro_pair#*=}"
[ -f "$1/cred/$_wro_user" ] || continue
grep -q "^$_wro_acct:" "$_wro_passwd" 2>/dev/null || continue
if chown "$_wro_acct" "$1/cred/$_wro_user"; then
echo "init: rig bus: cred/$_wro_user belongs to $_wro_acct"
else
echo "init: rig bus: chown $_wro_acct cred/$_wro_user failed"
fi
done
}
# warden_init_chain <first> <last>: start the shipped SysV scripts numbered
# <first> to <last> (S<NN>name, both bounds included), in name order, each
# with `start`, as the panel's rcS does. Used only on a boot with
# warden.initchain on the command line, where the caller laid the panel's own
# scripts into /etc/init.d with mkimage.sh's ROOTFS_OVERLAY (flare-edge #2210:
# S03warden-accounts, S99lvgl and /usr/lib/warden/warden-ui-run, so the UI
# starts through its privilege drop, respawn loop and safe mode instead of
# directly as root). The rig skeleton itself has no /etc/init.d. A script
# that fails is named on the console and the chain goes on, as rcS does.
# Prints how many scripts it started. WARDEN_INITD exists for the host test.
warden_init_chain() {
_wic_dir="${WARDEN_INITD:-/etc/init.d}"
_wic_ran=0
for _wic_s in "$_wic_dir"/S[0-9][0-9]*; do
if [ ! -f "$_wic_s" ] || [ ! -x "$_wic_s" ]; then continue; fi
_wic_name="${_wic_s##*/}"
_wic_n="${_wic_name#S}"
_wic_n="${_wic_n%"${_wic_n#??}"}"
# test(1) reads "08" as decimal eight, so no leading zero is cut.
if [ "$_wic_n" -lt "$1" ] || [ "$_wic_n" -gt "$2" ]; then continue; fi
echo "init: chain $_wic_name start" >&2
if "$_wic_s" start >&2; then
:
else
echo "init: chain $_wic_name start FAILED rc=$?" >&2
fi
_wic_ran=$((_wic_ran + 1))
done
echo "$_wic_ran"
}
+36 -50
View File
@@ -108,6 +108,28 @@ export WARDEN_HARD_RESET=0
# Production init scripts create this volatile socket directory before their
# daemons start. The compact QEMU rootfs must provide the same contract.
mkdir -p /run/warden
# warden.initchain (flare-edge #2210): the UI starts through the panel's own
# scripts, laid into /etc/init.d and /usr/lib/warden by mkimage.sh's
# ROOTFS_OVERLAY, not directly as root below. Scripts S00 to S09 (the
# accounts) run before the bus, which then hands each account its
# credential, and S10 to S99 run where the direct UI start would. The rig
# has no S09splash, so the splash handover is marked done, and its UI is the
# fbdev build, so warden-ui-run passes "-b fbdev" instead of the panel's
# "-b drm". A chain boot without any script fails loudly: a direct start
# there would pass a check that asked for the shipped chain.
initchain=0
if grep -qw warden.initchain /proc/cmdline; then
initchain=1
echo "init: shipped init chain (warden.initchain)"
export WARDEN_UI_ARGS="-b fbdev"
: > /tmp/splash.done
chain_early="$(warden_init_chain 0 9)"
fi
# The device bus, when the payload carries a broker (warden_rig_bus): up
# before the daemons, as S10bus is before every bus client on the panel. A
# failed start is logged and the boot goes on: the clients keep dialing, and
# a flow that needs the bus fails on its own checks.
warden_rig_bus || true
# OTA apply is opt-in per boot (run.sh --allow-apply): writing rootfs_b is
# safe inside disk.img but must never be the default posture.
if grep -qw warden.fwapply /proc/cmdline; then
@@ -132,10 +154,19 @@ for d in /usr/bin/warden-modbus /usr/bin/warden-automation /usr/bin/warden-ai \
fi
done
if [ "$initchain" = 1 ]; then
chain_late="$(warden_init_chain 10 99)"
if [ "$((chain_early + chain_late))" -eq 0 ]; then
echo "WARDEN-QEMU-INITCHAIN-EMPTY: warden.initchain but no /etc/init.d/S* script; the UI is not started"
else
echo "init: chain started $((chain_early + chain_late)) script(s)"
fi
fi
# The UI (LVGL fbdev+evdev build from flare-edge tools/build-ui-vm.sh) needs
# virtio-gpu's fbdev: present only with run.sh --display on|headless AND the
# virt.fragment kernel.
if [ -x /usr/bin/warden-ui ] && [ -c /dev/fb0 ]; then
# virt.fragment kernel. A chain boot started it above, through S99lvgl.
if [ "$initchain" = 0 ] && [ -x /usr/bin/warden-ui ] && [ -c /dev/fb0 ]; then
echo "init: starting warden-ui (fbdev)"
# Announce the exit on the CONSOLE, not just in the log. A UI that dies
# mid-scenario otherwise looks exactly like a UI that stopped repainting:
@@ -192,54 +223,9 @@ if grep -qw warden.ctl /proc/cmdline && [ -c /dev/ttyS0 ]; then
# mode: the host discards echoed input, and a whole line arrives per
# read.
exec 3<> "$ctl"
while IFS= read -r cmd <&3; do
[ -n "$cmd" ] || continue
case "$cmd" in
"@cat "*)
# A bridge-local command, never forwarded to warden-ui's
# FIFO: `@cat PATH` reads PATH directly off the GUEST's
# own filesystem and answers with it, which is how the
# json flow channel gets webstatus.c's snapshot out to
# the host driving the VM from outside. `-f` so a
# directory or device node reports as missing rather than
# cat hanging or erroring oddly.
path="${cmd#@cat }"
if [ -f "$path" ]; then
cat "$path" >&3
# Force a newline after the file's own bytes: the
# status json (webstatus.c) is written with NO
# trailing newline, and without this the sentinel
# below would land on the SAME line as the content
# and the reader (qmp.py Ctl.send, line-based) would
# block forever waiting for a line that never comes.
echo >&3
else
echo "bridge: no such file: $path" >&3
fi
;;
*)
if [ -p /tmp/warden-ui.ctl ]; then
# Remove the previous reply BEFORE sending, then wait
# for the new one to appear (the UI renames it into
# place whole). A fixed settle used to hand back the
# previous command's reply whenever a page took longer
# than 0.3 s to build (flare-edge #152); this is the
# same recipe tools/warden-ctl uses over SSH.
rm -f /tmp/warden-ui.dbg
printf '%s\n' "$cmd" > /tmp/warden-ui.ctl
n=0
while [ ! -s /tmp/warden-ui.dbg ] && [ "$n" -lt 100 ]; do
sleep 0.05
n=$((n + 1))
done
cat /tmp/warden-ui.dbg 2>/dev/null >&3
else
echo "bridge: warden-ui control FIFO not present" >&3
fi
;;
esac
echo "<<END>>" >&3
done
# The loop itself is warden_ctl_bridge (/etc/warden-lib.sh), where
# the host test reaches it.
warden_ctl_bridge <&3 >&3
) &
fi
+50
View File
@@ -69,4 +69,54 @@ cp "$SCRATCH/good" "$SCRATCH/cached/busybox-armv7l"
OUT="$SCRATCH/cached" qemu_get_busybox
test "$(cat "$FAKE_CURL_COUNT")" = 0
# A server that answers and then stalls must not hang the fetch (#1588). This
# runs the real curl against a local listener that sends headers and a few
# bytes, then goes silent; the short limits keep the test fast.
PATH="${PATH//"$FAKE_BIN:"/}"
python3 - "$SCRATCH/stall-port" <<'STALL' &
import os, socket, sys, threading, time
srv = socket.socket()
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(("127.0.0.1", 0))
srv.listen(16)
with open(sys.argv[1] + ".tmp", "w") as f:
f.write(str(srv.getsockname()[1]))
os.rename(sys.argv[1] + ".tmp", sys.argv[1])
held = []
def serve(conn):
try:
conn.recv(4096)
conn.sendall(b"HTTP/1.1 200 OK\r\nContent-Length: 1000000\r\n\r\nstall")
held.append(conn)
time.sleep(600)
except OSError:
pass
while True:
c, _ = srv.accept()
threading.Thread(target=serve, args=(c,), daemon=True).start()
STALL
STALL_PID=$!
trap 'kill "$STALL_PID" 2>/dev/null || true; rm -rf "$SCRATCH"' EXIT
for _ in $(seq 100); do [ -s "$SCRATCH/stall-port" ] && break; sleep 0.1; done
test -s "$SCRATCH/stall-port"
BB_URL="http://127.0.0.1:$(cat "$SCRATCH/stall-port")/busybox"
start=$SECONDS
# The bash -c program expands its own positional arguments.
# shellcheck disable=SC2016
if (OUT="$SCRATCH/stalled" BB_FETCH_STALL_SECS=1 BB_FETCH_MAX_SECS=3 \
BB_FETCH_RETRY_DELAY=1 timeout 60 bash -c \
'set -euo pipefail; source "$1"; QEMU_DIR="$2"; BB_URL="$3"; qemu_get_busybox' \
_ "$TEST_DIR/../lib.sh" "$QEMU_DIR" "$BB_URL") >"$SCRATCH/stall.log" 2>&1; then
echo "FAIL: a stalled download was accepted" >&2
exit 1
fi
elapsed=$((SECONDS - start))
if ! grep -q 'after 3 verified attempts' "$SCRATCH/stall.log"; then
echo "FAIL: a stalled download hung instead of failing (${elapsed}s)" >&2
cat "$SCRATCH/stall.log" >&2
exit 1
fi
test "$elapsed" -lt 45
test ! -e "$SCRATCH/stalled/busybox-armv7l"
echo "busybox fetch tests passed"
+183
View File
@@ -0,0 +1,183 @@
#!/usr/bin/env bash
# Host test for the rig's control bridge, warden_ctl_bridge in
# qemu/rootfs/etc/warden-lib.sh (flare-edge #1448). A fake warden-ui reads
# the FIFO and renames each reply into place, as warden_debug.c does; some
# commands answer late. Checks: a reply slower than the old 5 s bound still
# arrives, a timeout answers the explicit no-reply line, and the late reply
# of a timed-out command is never handed to the next command. A fake hook
# client stands in for wthctl behind `@hookdoc` / `@hook` (the test hook
# over the device bus, flare-edge #2054).
set -uo pipefail
# Job control: the fake UI leads its own process group, so one kill stops
# its pending sleep too.
set -m
HERE="$(cd "$(dirname "$0")" && pwd)"
LIB="$HERE/../rootfs/etc/warden-lib.sh"
# Unquoted where it runs: WARDEN_TEST_SH may be "busybox sh", the rig's shell.
SH="${WARDEN_TEST_SH:-sh}"
WORK="$(mktemp -d)" || exit 1
UI_PID=
stop_ui() {
[ -n "$UI_PID" ] || return 0
{ kill -KILL -- "-$UI_PID"; wait "$UI_PID"; } 2>/dev/null
UI_PID=
}
cleanup() {
stop_ui
rm -rf "$WORK"
}
trap cleanup EXIT
FAIL=0
CHECKS=0
check() { # check <label> <command...>
CHECKS=$((CHECKS + 1))
if "${@:2}"; then
echo "[PASS] $1"
else
echo "[FAIL] $1"
FAIL=1
fi
}
# The fake UI: "slowN" answers after N tenths of a second, anything else at
# once. Replies are "reply:<command>", written to a temp file and renamed.
start_ui() {
mkfifo "$WORK/ctl"
(
while :; do
IFS= read -r cmd < "$WORK/ctl" || continue
case "$cmd" in
slow*) sleep "$(awk -v t="${cmd#slow}" 'BEGIN { print t / 10 }')" ;;
esac
printf 'reply:%s\n' "$cmd" > "$WORK/dbg.tmp"
mv "$WORK/dbg.tmp" "$WORK/dbg"
done
) &
UI_PID=$!
}
run_bridge() { # run_bridge <name> <wait s or ""> <lines...>
local name="$1" wait="$2"
shift 2
# $SH unquoted (it may be "busybox sh"); the quoted script is meant literally.
# shellcheck disable=SC2086,SC2016
printf '%s\n' "$@" |
env WARDEN_CTL_FIFO="$WORK/ctl" WARDEN_CTL_REPLY="$WORK/dbg" \
${wait:+WARDEN_CTL_WAIT_S="$wait"} \
$SH -c '. "$1"; warden_ctl_bridge' sh "$LIB" > "$WORK/$name.out" 2> "$WORK/$name.err"
}
same() { # same <file> <expected lines...>
local file="$1"
shift
diff <(printf '%s\n' "$@") "$file" > "$WORK/diff" || { cat "$WORK/diff"; return 1; }
}
start_ui
# A 1 s bound, a 1.5 s reply: the explicit no-reply line, then the next
# command gets ITS reply, not the late one (the desync behind #1448).
run_bridge timeout 1 fast1 slow15 fast2
check "timeout answers no-reply; the late reply is not the next answer" \
same "$WORK/timeout.out" reply:fast1 '<<END>>' \
'bridge: no reply from warden-ui within 1 s: slow15' '<<END>>' \
reply:fast2 '<<END>>'
# The default bound: a 6 s reply (over the old 5 s) still arrives, and the
# console note gives its time.
run_bridge slow "" slow60 after
check "default bound: a 6 s reply arrives" \
same "$WORK/slow.out" reply:slow60 '<<END>>' reply:after '<<END>>'
check "slow reply logged on stderr" grep -Eq "^ctl bridge: slow reply, [5-7] s of polling: slow60\$" "$WORK/slow.err"
check "fast reply not logged" bash -c "! grep -q after '$WORK/slow.err'"
# @cat is answered by the bridge itself, with a newline after the file.
printf '{"a":1}' > "$WORK/status.json"
run_bridge cat 1 "@cat $WORK/status.json" "@cat $WORK/missing"
check "@cat answers the file and a missing-file line" \
same "$WORK/cat.out" '{"a":1}' '<<END>>' "bridge: no such file: $WORK/missing" '<<END>>'
# No FIFO: one line, no wait.
stop_ui
rm -f "$WORK/ctl"
run_bridge nofifo 1 page
check "missing FIFO answers at once" \
same "$WORK/nofifo.out" 'bridge: warden-ui control FIFO not present' '<<END>>'
# @procs: the process table for the stall probe (flare-edge #1528), answered
# by the bridge itself, so it works with no UI at all.
procs_ok() {
grep -Eq '^[0-9]+ \(.*\) [A-Z] ' "$WORK/procs.out" &&
[ "$(tail -n 1 "$WORK/procs.out")" = '<<END>>' ] &&
! grep -q 'FIFO not present' "$WORK/procs.out"
}
run_bridge procs 1 @procs
check "@procs lists process stat lines without the UI" procs_ok
# @hookdoc / @hookdoc+ / @hook: the fake client logs its argv one per line
# and answers by verb (ok:true, ok:false with exit 1, or no reply, exit 2).
cat > "$WORK/wthctl" <<'FAKE'
#!/bin/sh
log="$(dirname "$0")/hook.log"
printf '%s\n' "$@" "--" >> "$log"
for last; do :; done
case "$*" in
*" refuse "*) echo '{"v":1,"ok":false,"err":{"code":"E_NOT_FOUND"}}'; exit 1 ;;
*" silent "*) echo "wthctl: no reply (-3)" >&2; exit 2 ;;
esac
printf '{"v":1,"ok":true,"data":{"args":%s}}\n' "$last"
FAKE
chmod +x "$WORK/wthctl"
run_hook() { # run_hook <name> <client> <lines...>
local name="$1" client="$2"
shift 2
rm -f "$WORK/hook.log" "$WORK/hook.args"
# $SH unquoted (it may be "busybox sh"); the quoted script is meant literally.
# shellcheck disable=SC2086,SC2016
printf '%s\n' "$@" |
env WARDEN_CTL_FIFO="$WORK/ctl" WARDEN_CTL_REPLY="$WORK/dbg" WARDEN_CTL_WAIT_S=1 \
WARDEN_CTL_HOOKDOC="$WORK/hook.args" WARDEN_WTHCTL="$client" WARDEN_BUS_RUN="$WORK/bus" \
$SH -c '. "$1"; warden_ctl_bridge' sh "$LIB" > "$WORK/$name.out" 2> "$WORK/$name.err"
}
run_hook pieces "$WORK/wthctl" '@hookdoc {"topic":"io/state/x",' '@hookdoc+ "doc":{"why":"two words"}}' \
'@hook override' '@hook override'
check "@hookdoc pieces join into one request; the args are used once" \
same "$WORK/pieces.out" 'hookdoc: 22 bytes' '<<END>>' 'hookdoc: 49 bytes' '<<END>>' \
'{"v":1,"ok":true,"data":{"args":{"topic":"io/state/x","doc":{"why":"two words"}}}}' '<<END>>' \
'{"v":1,"ok":true,"data":{"args":{}}}' '<<END>>'
check "the client gets the bus socket, the testhook credential, the verb and the args" \
same "$WORK/hook.log" "$WORK/bus/bus.sock" "$WORK/bus/cred/testhook" override \
'{"topic":"io/state/x","doc":{"why":"two words"}}' -- \
"$WORK/bus/bus.sock" "$WORK/bus/cred/testhook" override '{}' --
run_hook words "$WORK/wthctl" '@hook --to flared guard_evidence' '@hook override;touch x' \
'@hook ov*' '@hook ' '@hookdoc+ {}'
check "client words pass one by one; a word with other characters is refused" \
same "$WORK/words.out" '{"v":1,"ok":true,"data":{"args":{}}}' '<<END>>' \
'bridge: bad hook request: override;touch x' '<<END>>' 'bridge: bad hook request: ov*' '<<END>>' \
'bridge: bad hook request: ' '<<END>>' \
'bridge: @hookdoc+ without a @hookdoc before it' '<<END>>'
check "the refused words never ran the client" \
same "$WORK/hook.log" "$WORK/bus/bus.sock" "$WORK/bus/cred/testhook" --to flared guard_evidence '{}' --
run_hook answers "$WORK/wthctl" '@hook refuse' '@hook silent'
check "ok:false is the hook's answer; no reply is a bridge line" \
same "$WORK/answers.out" '{"v":1,"ok":false,"err":{"code":"E_NOT_FOUND"}}' '<<END>>' \
'bridge: hook request got no answer (client exit 2): wthctl: no reply (-3)' '<<END>>'
run_hook noclient "$WORK/absent" '@hookdoc {}' '@hook override' '@hook override'
check "no client in the payload answers a bridge line and drops the args" \
same "$WORK/noclient.out" 'hookdoc: 2 bytes' '<<END>>' \
"bridge: no hook client in the payload ($WORK/absent)" '<<END>>' \
"bridge: no hook client in the payload ($WORK/absent)" '<<END>>'
check "the args file is gone after a request" test ! -e "$WORK/hook.args"
if [ "$FAIL" = 0 ]; then
echo "ctl-bridge tests: OK ($CHECKS checks)"
else
echo "ctl-bridge tests: FAILED"
exit 1
fi
+124
View File
@@ -0,0 +1,124 @@
#!/usr/bin/env bash
# Host test for the rig's shipped-init-chain boot (flare-edge #2210):
# warden_init_chain and warden_rig_bus_owners in qemu/rootfs/etc/warden-lib.sh,
# and the warden.initchain wiring in qemu/rootfs/sbin/init. Offline, no VM.
#
# warden_init_chain <first> <last> starts the executable S<NN>* scripts of
# that number range in name order with `start`, names a failing one and
# goes on, reads "08" and "09" as decimal (test, not shell arithmetic), and prints how many it started.
# warden_rig_bus_owners hands a credential file to its account only when
# the passwd database has that account.
# sbin/init runs S00-S09 before the bus and S10-S99 before the direct UI
# start, which a chain boot skips, and says so when the chain is empty.
#
# bash init-chain-test.sh (WARDEN_TEST_SH="busybox sh" for the rig shell)
set -uo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
LIB="$HERE/../rootfs/etc/warden-lib.sh"
INIT="$HERE/../rootfs/sbin/init"
SH="${WARDEN_TEST_SH:-sh}"
WORK="$(mktemp -d "${TMPDIR:-/tmp}/warden-init-chain.XXXXXX")" || exit 1
trap 'rm -rf "$WORK"' EXIT
FAIL=0
CHECKS=0
check() { # check <label> <command...>
CHECKS=$((CHECKS + 1))
if "${@:2}"; then echo "[PASS] $1"; else echo "[FAIL] $1"; FAIL=1; fi
}
# Stub scripts: each appends "<name> <arg>" to the log; S20bad fails.
D="$WORK/init.d"
mkdir -p "$D"
# shellcheck disable=SC2016 # $1 belongs to the stub script
stub() { # stub <name> [rc]
printf '#!/bin/sh\necho "%s $1" >> "%s"\nexit %s\n' "$1" "$WORK/log" "${2:-0}" > "$D/$1"
chmod 0755 "$D/$1"
}
stub S03warden-accounts
stub S08eight
stub S09splash
stub S10bus
stub S20bad 3
stub S99lvgl
stub S01runtime
# shellcheck disable=SC2016 # $1 belongs to the stub script
printf '#!/bin/sh\necho "S50off $1" >> "%s"\n' "$WORK/log" > "$D/S50off" # not executable
printf 'x\n' > "$D/README"
mkdir -p "$D/S60dir"
chain() { # chain <first> <last>: stdout to $WORK/out, stderr to $WORK/err
: > "$WORK/log"
# shellcheck disable=SC2086,SC2016
WARDEN_INITD="$D" $SH -c '. "$1"; warden_init_chain "$2" "$3"' sh "$LIB" "$1" "$2" \
> "$WORK/out" 2> "$WORK/err"
}
chain 0 9
check "early range starts S01, S03, S08, S09 in name order" \
test "$(cat "$WORK/log")" = "S01runtime start
S03warden-accounts start
S08eight start
S09splash start"
check "early range prints its count (4)" test "$(cat "$WORK/out")" = 4
check "early range names each start on the console" grep -q '^init: chain S08eight start$' "$WORK/err"
chain 10 99
check "late range starts S10, S20, S99 and skips the non-executable S50 and the directory S60" \
test "$(cat "$WORK/log")" = "S10bus start
S20bad start
S99lvgl start"
check "late range counts the failed script as started (3)" test "$(cat "$WORK/out")" = 3
check "a failing script is named with its status" grep -q '^init: chain S20bad start FAILED rc=3$' "$WORK/err"
chain 9 9
check "a one-number range starts only that number" test "$(cat "$WORK/log")" = "S09splash start"
rm -rf "$D"; mkdir -p "$D"
chain 0 99
check "no scripts: nothing runs and the count is 0" test "$(cat "$WORK/out")" = 0
# shellcheck disable=SC2086,SC2016
WARDEN_INITD="$WORK/none" $SH -c '. "$1"; warden_init_chain 0 99' sh "$LIB" > "$WORK/out" 2>&1
check "a missing init.d directory counts 0" test "$(cat "$WORK/out")" = 0
# warden_rig_bus_owners: the test's own account stands in for warden-ui
# (chown to oneself needs no root).
me="$(id -un)"
B="$WORK/bus"
mkdir -p "$B/cred"
: > "$B/cred/ui"; : > "$B/cred/flared"
printf '%s:x:%s:%s::/:/bin/sh\n' "$me" "$(id -u)" "$(id -g)" > "$WORK/passwd"
printf 'root:x:0:\n' > "$WORK/group"
owners() { # owners <pairs>
# shellcheck disable=SC2086,SC2016
WARDEN_RIG_BUS_OWNERS="$1" WARDEN_RIG_PASSWD="$WORK/passwd" WARDEN_RIG_GROUP="$WORK/group" \
$SH -c '. "$1"; warden_rig_bus_owners "$2"' sh "$LIB" "$B" > "$WORK/out" 2>&1
}
owners "ui=$me"
check "a credential whose account exists is handed to it" grep -qx "init: rig bus: cred/ui belongs to $me" "$WORK/out"
owners "ui=warden-ui-absent flared=$me-absent"
check "accounts the rootfs lacks change nothing (the rig default)" test ! -s "$WORK/out"
owners "nosuch=$me"
check "a user without a credential file is skipped" test ! -s "$WORK/out"
owners ""
check "the default pair is ui=warden-ui" test ! -s "$WORK/out"
# sbin/init wiring, read from the script itself.
line_of() { grep -n -m1 -e "$1" "$INIT" | cut -d: -f1; }
early="$(line_of 'warden_init_chain 0 9')"
bus="$(line_of '^warden_rig_bus ')"
late="$(line_of 'warden_init_chain 10 99')"
daemons="$(line_of '^for d in /usr/bin/warden-')"
ui="$(line_of 'if .*-x /usr/bin/warden-ui')"
check "init runs S00-S09 before the rig bus" test -n "$early" -a -n "$bus" -a "${early:-0}" -lt "${bus:-0}"
check "init runs S10-S99 after the payload daemons and before the direct UI start" \
test -n "$late" -a -n "$daemons" -a -n "$ui" -a "${daemons:-0}" -lt "${late:-0}" -a "${late:-0}" -lt "${ui:-0}"
# shellcheck disable=SC2016 # a literal pattern
check "the direct UI start is skipped on a chain boot" grep -q '^if \[ "$initchain" = 0 \] && \[ -x /usr/bin/warden-ui \]' "$INIT"
check "the chain is armed only by warden.initchain on the command line" grep -q 'grep -qw warden.initchain /proc/cmdline' "$INIT"
check "a chain boot passes the fbdev backend to warden-ui-run" grep -q 'export WARDEN_UI_ARGS="-b fbdev"' "$INIT"
check "an empty chain is reported, not replaced by the direct start" grep -q 'WARDEN-QEMU-INITCHAIN-EMPTY' "$INIT"
echo "init-chain: $CHECKS checks"
if [ "$FAIL" -ne 0 ]; then echo "init-chain: FAILED"; exit 1; fi
echo "init-chain: all checks passed"
+47 -5
View File
@@ -3,7 +3,9 @@
# busybox reboot/poweroff/halt, which only signal PID 1. Runs the real
# helpers from qemu/rootfs/etc/warden-lib.sh in a plain sh with stub
# commands, idles it the way /sbin/init does, sends each signal and requires
# the matching action within two seconds.
# the matching action within two seconds. Each signal goes out only once the
# shell has its handler installed (SigCgt), so a slow start cannot turn the
# signal's default action into a false failure (bfe-core1106-sdk#22).
set -uo pipefail
# Job control: each case's shell leads its own process group, so cleanup can
# kill the whole group. An orphaned `sleep 3600` would otherwise keep this
@@ -16,15 +18,41 @@ SH="${WARDEN_TEST_SH:-sh}"
WORK="$(mktemp -d)" || exit 1
trap 'rm -rf "$WORK"' EXIT
FAIL=0
# Hang backstop for the handler install; a quiet host takes milliseconds.
TRAP_WAIT_S="${WARDEN_TEST_TRAP_WAIT_S:-10}"
run_case() { # run_case <signal> <expected marker> <label>
local sig="$1" want="$2" label="$3" out="$WORK/$1.out"
# Succeeds once <pid> catches <signal>: its bit is set in /proc SigCgt.
catches() { # catches <pid> <signal name>
local mask num
mask="$(awk '/^SigCgt:/ { print $2 }' "/proc/$1/status" 2>/dev/null)"
num="$(kill -l "$2")" || return 1
[ -n "$mask" ] && (( (16#$mask >> (num - 1)) & 1 ))
}
# Waits up to TRAP_WAIT_S for <pid> to catch <signal>.
wait_trapped() { # wait_trapped <pid> <signal name>
local n=0 limit=$((TRAP_WAIT_S * 10))
until catches "$1" "$2"; do
[ "$n" -ge "$limit" ] && return 1
sleep 0.1; n=$((n + 1))
done
}
# <delay> holds the handler install back, as a loaded runner does.
run_case() { # run_case <signal> <expected marker> <label> [delay s]
local sig="$1" want="$2" label="$3" delay="${4:-0}" out="$WORK/$1.out"
: > "$out"
WARDEN_REBOOT_CMD="eval echo reboot >> $out; exit 0" \
WARDEN_POWEROFF_CMD="eval echo poweroff >> $out; exit 0" \
"$SH" -c ". '$LIB'; warden_trap_power_signals; warden_idle_forever" &
"$SH" -c "sleep $delay; . '$LIB'; warden_trap_power_signals; warden_idle_forever" &
local pid=$!
sleep 0.5
if ! wait_trapped "$pid" "$sig"; then
echo "[FAIL] $label (SIG$sig handler not installed within ${TRAP_WAIT_S} s)"
FAIL=1
kill -KILL -- "-$pid" 2>/dev/null
wait "$pid" 2>/dev/null
return
fi
kill -"$sig" "$pid"
local n=0
while ! grep -qx "$want" "$out" && [ "$n" -lt 20 ]; do
@@ -42,5 +70,19 @@ run_case() { # run_case <signal> <expected marker> <label>
run_case TERM reboot "SIGTERM (busybox reboot) reboots at once"
run_case USR2 poweroff "SIGUSR2 (busybox poweroff) powers off at once"
run_case USR1 poweroff "SIGUSR1 (busybox halt) powers off at once"
# Regression for bfe-core1106-sdk#22: the old fixed 0.5 s sleep sent SIGTERM
# before this shell installed its trap, killing it with nothing written.
run_case TERM reboot "SIGTERM after a slow handler install still reboots" 1.5
# The wait itself must fail, not hang or pass, when no handler ever appears.
"$SH" -c 'sleep 3600' &
pid=$!
if TRAP_WAIT_S=1 wait_trapped "$pid" TERM; then
echo "[FAIL] wait_trapped reported a handler a plain shell never installs"; FAIL=1
else
echo "[PASS] wait_trapped gives up on a shell without a handler"
fi
kill -KILL -- "-$pid" 2>/dev/null
wait "$pid" 2>/dev/null
exit "$FAIL"
+176
View File
@@ -0,0 +1,176 @@
#!/usr/bin/env bash
# shellcheck disable=SC2317 # the checks and the cleanup run through check() and trap
# Host test for the rig's device bus, warden_rig_bus in
# qemu/rootfs/etc/warden-lib.sh (flare-edge #1754, #1050). Checks:
# - a payload without a broker boots as before: nothing created, status 0
# - with a broker: the panel's layout (sock/bus.sock and the bus.sock link,
# one 0400 credential file of 64 hex digits per bus user, each its own),
# a config with the listener and no password file, ACL or plugin
# - a broker that exits, or never listens, is reported and returns 1
# within the wait bound
# - a user name that is not a plain file name gets no file
# - /sbin/init starts the bus before the payload daemons
# A stub broker (python3, binds the configured listener) stands in for
# mosquitto. With WARDEN_TEST_MOSQUITTO_DIR set to a directory holding
# mosquitto, mosquitto_pub and mosquitto_sub (flare-edge
# tools/build-host-mosquitto.sh), the real broker also carries one message
# between two users that log in with their credential files.
set -uo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
LIB="$HERE/../rootfs/etc/warden-lib.sh"
INIT="$HERE/../rootfs/sbin/init"
SH="${WARDEN_TEST_SH:-sh}"
WORK="$(mktemp -d)" || exit 1
cleanup() {
# The brokers outlive the shell that started them, as on the rig; each
# has this test's folder in its argv (the stub that never listens writes
# its pid instead).
pkill -f -- "$WORK/" 2>/dev/null
[ -f "$STUB/mute.pid" ] && kill "$(cat "$STUB/mute.pid")" 2>/dev/null
rm -rf "$WORK"
}
trap cleanup EXIT
STUB="$WORK/stubs"
mkdir -p "$STUB"
FAIL=0
check() { # check <label> <command...>
if "${@:2}"; then
echo "[PASS] $1"
else
echo "[FAIL] $1"
FAIL=1
fi
}
# Stub brokers: argv is "-c <conf>", as the lib calls mosquitto.
# good: binds the listener path from the config and stays.
# exits: dies at once. mute: stays and never listens.
cat > "$STUB/good" <<'PY'
#!/usr/bin/env python3
import socket, sys, time
conf = sys.argv[sys.argv.index("-c") + 1]
lines = open(conf).read().splitlines()
path = [l.split()[2] for l in lines if l.startswith("listener ")][0]
time.sleep(0.3)
s = socket.socket(socket.AF_UNIX)
s.bind(path)
s.listen(1)
print("stub broker listening", flush=True)
time.sleep(600)
PY
printf '#!/bin/sh\necho "Error: stub broker refused" >&2\nexit 3\n' > "$STUB/exits"
cat > "$STUB/mute" <<'EOF'
#!/bin/sh
echo $$ > "${0%/*}/mute.pid"
exec sleep 600
EOF
chmod +x "$STUB/good" "$STUB/exits" "$STUB/mute"
run_bus() { # run_bus <case> <broker> [VAR=value...]: output in <case>/out, status in <case>/rc
local name="$1" broker="$2"
shift 2
mkdir -p "$WORK/$name"
# $SH unquoted: WARDEN_TEST_SH may be "busybox sh". The lib is sourced
# inside, so the quoted script is meant literally.
# shellcheck disable=SC2086,SC2016
env WARDEN_RIG_BROKER="$broker" WARDEN_BUS_RUN="$WORK/$name/bus" \
WARDEN_RIG_BUS_LOG="$WORK/$name/broker.log" "$@" \
$SH -c '. "$1"; warden_rig_bus' sh "$LIB" > "$WORK/$name/out" 2>&1
echo $? > "$WORK/$name/rc"
}
rc_is() { [ "$(cat "$WORK/$1/rc")" = "$2" ]; }
out_has() { grep -qF -- "$2" "$WORK/$1/out"; }
# 1. No broker in the payload.
run_bus none "$WORK/no-such-broker"
check "no broker: status 0" rc_is none 0
check "no broker: nothing created" test ! -e "$WORK/none/bus"
check "no broker: silent" test ! -s "$WORK/none/out"
# 2. A broker that listens.
run_bus good "$STUB/good" WARDEN_RIG_BUS_USERS="flared ui modbus ../evil .hidden automation.main"
B="$WORK/good/bus"
check "broker up: status 0" rc_is good 0
check "broker up: reported" out_has good "init: rig bus up on $B/bus.sock"
check "broker up: socket listens" test -S "$B/sock/bus.sock"
check "broker up: bus.sock link resolves to the socket" test "$(readlink "$B/bus.sock")" = sock/bus.sock -a -S "$B/bus.sock"
creds_ok() {
local u f seen=""
for u in flared ui modbus automation.main; do
f="$B/cred/$u"
[ -f "$f" ] || { echo "missing $f"; return 1; }
[ "$(stat -c %a "$f")" = 400 ] || { echo "$f mode $(stat -c %a "$f")"; return 1; }
grep -qxE '[0-9a-f]{64}' "$f" || { echo "$f is not 64 hex digits"; return 1; }
case " $seen " in *" $(cat "$f") "*) echo "$f repeats a secret"; return 1 ;; esac
seen="$seen $(cat "$f")"
done
}
check "broker up: one 0400 64-hex credential per user, all different" creds_ok
check "broker up: a name with a slash gets no file" test ! -e "$B/evil"
check "broker up: a dot name gets no file" test ! -e "$B/cred/.hidden"
check "broker up: bad names reported" out_has good "bad user name '../evil' skipped"
check "broker up: cred/ is 0710" test "$(stat -c %a "$B/cred")" = 710
conf_ok() {
local c="$B/mosquitto.conf"
grep -qx "listener 0 $B/sock/bus.sock" "$c" &&
grep -qx 'allow_anonymous true' "$c" &&
grep -qx 'use_username_as_clientid true' "$c" &&
! grep -qE '^(password_file|acl_file|plugin)' "$c"
}
check "broker up: config has the listener and no password file, ACL or plugin" conf_ok
# 3. A broker that exits at once.
run_bus exits "$STUB/exits" WARDEN_RIG_BUS_WAIT_S=5
check "broker exits: status 1" rc_is exits 1
check "broker exits: reported with its log" out_has exits "init: rig bus FAILED: the broker exited"
check "broker exits: log tail shown" out_has exits "stub broker refused"
# 4. A broker that never listens.
start=$(date +%s)
run_bus mute "$STUB/mute" WARDEN_RIG_BUS_WAIT_S=1
took=$(( $(date +%s) - start ))
[ -f "$STUB/mute.pid" ] && kill "$(cat "$STUB/mute.pid")" 2>/dev/null
check "silent broker: status 1" rc_is mute 1
check "silent broker: reported" out_has mute "init: rig bus FAILED: no socket after 1 s"
check "silent broker: gave up within the bound (${took} s)" test "$took" -le 4
# 5. /sbin/init: the bus before the payload daemon loop.
order_ok() {
local bus loop
bus=$(grep -n '^warden_rig_bus' "$INIT" | head -1 | cut -d: -f1)
loop=$(grep -n '^for d in /usr/bin/warden-' "$INIT" | head -1 | cut -d: -f1)
[ -n "$bus" ] && [ -n "$loop" ] && [ "$bus" -lt "$loop" ]
}
check "init: the rig bus starts before the payload daemons" order_ok
# 6. The real broker, when one is given.
MQ="${WARDEN_TEST_MOSQUITTO_DIR:-}"
if [ -n "$MQ" ] && [ -x "$MQ/mosquitto" ] && [ -x "$MQ/mosquitto_sub" ] && [ -x "$MQ/mosquitto_pub" ]; then
run_bus real "$MQ/mosquitto" WARDEN_RIG_BUS_USERS="modbus ui"
R="$WORK/real/bus"
check "real broker: up" rc_is real 0
real_message() {
local got
"$MQ/mosquitto_sub" --unix "$R/bus.sock" -u ui -P "$(cat "$R/cred/ui")" \
-t 'modbus/state/test' -C 1 -W 10 > "$WORK/real/sub.out" 2>&1 &
local sub=$!
sleep 0.5
"$MQ/mosquitto_pub" --unix "$R/bus.sock" -u modbus -P "$(cat "$R/cred/modbus")" \
-t 'modbus/state/test' -m rig-bus-ok || return 1
wait "$sub"
got=$(cat "$WORK/real/sub.out")
[ "$got" = rig-bus-ok ] || { echo "subscriber got: $got"; return 1; }
}
check "real broker: ui receives what modbus publishes, both logged in by credential file" real_message
else
echo "[SKIP] real broker (set WARDEN_TEST_MOSQUITTO_DIR)"
fi
if [ "$FAIL" -eq 0 ]; then
echo "PASS: rig bus"
else
echo "FAIL: rig bus"
fi
exit "$FAIL"
+179
View File
@@ -0,0 +1,179 @@
#!/usr/bin/env bash
# Regression test for mkimage.sh's PAYLOAD_DIR hook (see its Env note): a run
# may boot its own payload set instead of qemu/payload, so flare-edge can boot
# the hook set (production payload plus the test-flavor UI and wthctl) for a
# flow that pins documents while other flows of the same batch read
# qemu/payload at the same time (flare-edge #2054).
#
# Works on a copy of qemu/ (no payload, no out/) so the default payload
# directory is the copy's own and nothing in the checkout is touched. Builds
# real disk images the same way mkimage.sh always does (unprivileged
# mkfs.ext4 -d), then reads rootfs_a and rootfs_b back with debugfs -R
# (read-only, no mount or loop device) to check what actually landed.
#
# bash payload-dir.sh
set -uo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" # qemu/tests/
SRC_QEMU="$(cd "$HERE/.." && pwd)" # qemu/
FAIL=0
pass() { printf '[PASS] %s\n' "$1"; }
fail() { printf '[FAIL] %s\n' "$1"; FAIL=1; }
# mkfs.ext4 and debugfs live in sbin, which user shells on Debian do not put
# on PATH; mkimage.sh applies the same fix.
PATH="$PATH:/usr/sbin:/sbin"
command -v debugfs >/dev/null || {
echo "FATAL: debugfs (e2fsprogs) not found: needed to read the rootfs partitions back" >&2
exit 1
}
SCRATCH="$(mktemp -d "${TMPDIR:-/tmp}/warden-qemu-payload-dir.XXXXXX")"
trap 'rm -rf "$SCRATCH"' EXIT
# The copy: everything mkimage.sh reads, without the build outputs or any
# payload a developer dropped into the checkout.
QEMU_DIR="$SCRATCH/qemu"
mkdir -p "$QEMU_DIR/payload"
for entry in "$SRC_QEMU"/*; do
case "$(basename "$entry")" in out|payload) continue ;; esac
cp -a "$entry" "$QEMU_DIR/"
done
# shellcheck source=../lib.sh disable=SC1091
. "$QEMU_DIR/lib.sh"
# shellcheck source=../blkdevparts.conf disable=SC1091
. "$QEMU_DIR/blkdevparts.conf"
declare -A PART_OFF PART_SIZE
capture_part() { PART_OFF[$1]="$2"; PART_SIZE[$1]="$3"; return 0; }
qemu_each_partition capture_part
for name in rootfs_a rootfs_b; do
[ -n "${PART_OFF[$name]:-}" ] || { echo "FATAL: no '$name' entry in blkdevparts.conf" >&2; exit 1; }
done
# extract_part DISK NAME OUTFILE: one partition window, sparse.
extract_part() {
dd if="$1" of="$3" bs=4096 skip=$((PART_OFF[$2] / 4096)) \
count=$((PART_SIZE[$2] / 4096)) conv=sparse status=none
}
# Reuse an already-verified busybox wherever a prior build produced one; a
# checkout that never ran mkimage.sh fetches and verifies it once here.
BUSYBOX_BIN="$SRC_QEMU/out/busybox-armv7l"
if [ ! -f "$BUSYBOX_BIN" ]; then
OUT="$SCRATCH/bb" qemu_get_busybox
BUSYBOX_BIN="$BB"
fi
# The default set and the run's own set name the same binary differently,
# so each image shows which directory it was built from.
printf 'default-ui\n' > "$QEMU_DIR/payload/warden-ui"
printf 'default only\n' > "$QEMU_DIR/payload/warden-default-only"
ALT="$SCRATCH/alt"
mkdir -p "$ALT"
printf 'alt-ui\n' > "$ALT/warden-ui"
printf 'readme\n' > "$ALT/README.md"
printf 'linked tool\n' > "$SCRATCH/wthctl.real"
ln -s "$SCRATCH/wthctl.real" "$ALT/wthctl"
# --- scenario 1: PAYLOAD_DIR replaces qemu/payload in both slots ---
OUT1="$SCRATCH/out1"
if OUT="$OUT1" BUSYBOX="$BUSYBOX_BIN" PAYLOAD_DIR="$ALT" \
bash "$QEMU_DIR/mkimage.sh" > "$SCRATCH/mkimage1.log" 2>&1; then
for slot in rootfs_a rootfs_b; do
IMG="$SCRATCH/$slot.1.img"
extract_part "$OUT1/disk.img" "$slot" "$IMG"
ui="$(debugfs -R "cat /usr/bin/warden-ui" "$IMG" 2>/dev/null)"
if [ "$ui" = "alt-ui" ]; then
pass "PAYLOAD_DIR: $slot carries the run's own warden-ui"
else
fail "PAYLOAD_DIR: $slot warden-ui = '$ui', want 'alt-ui'"
fi
tool="$(debugfs -R "cat /usr/bin/wthctl" "$IMG" 2>/dev/null)"
if [ "$tool" = "linked tool" ]; then
pass "PAYLOAD_DIR: $slot gets a symlinked entry's content"
else
fail "PAYLOAD_DIR: $slot wthctl = '$tool', want the symlink target's content"
fi
mode="$(debugfs -R "stat /usr/bin/wthctl" "$IMG" 2>/dev/null | grep -oE 'Mode: *[0-7]+' | grep -oE '[0-7]+$')"
if [ "$mode" = "0755" ]; then
pass "PAYLOAD_DIR: $slot installs a regular 0755 file for the symlink"
else
fail "PAYLOAD_DIR: $slot wthctl mode '$mode', want 0755"
fi
if debugfs -R "stat /usr/bin/warden-default-only" "$IMG" 2>&1 | grep -q 'File not found'; then
pass "PAYLOAD_DIR: $slot has nothing from qemu/payload"
else
fail "PAYLOAD_DIR: $slot carries qemu/payload's warden-default-only"
fi
if debugfs -R "stat /usr/bin/README.md" "$IMG" 2>&1 | grep -q 'File not found'; then
pass "PAYLOAD_DIR: $slot skips the set's README.md"
else
fail "PAYLOAD_DIR: $slot carries the set's README.md"
fi
done
else
fail "PAYLOAD_DIR: mkimage.sh exited nonzero with a valid payload dir (see $SCRATCH/mkimage1.log)"
fi
# --- scenario 2: no PAYLOAD_DIR still reads qemu/payload ---
OUT2="$SCRATCH/out2"
if OUT="$OUT2" BUSYBOX="$BUSYBOX_BIN" \
bash "$QEMU_DIR/mkimage.sh" > "$SCRATCH/mkimage2.log" 2>&1; then
IMG="$SCRATCH/rootfs_a.2.img"
extract_part "$OUT2/disk.img" rootfs_a "$IMG"
ui="$(debugfs -R "cat /usr/bin/warden-ui" "$IMG" 2>/dev/null)"
if [ "$ui" = "default-ui" ]; then
pass "no PAYLOAD_DIR: rootfs_a carries qemu/payload's warden-ui"
else
fail "no PAYLOAD_DIR: rootfs_a warden-ui = '$ui', want 'default-ui'"
fi
else
fail "no PAYLOAD_DIR: mkimage.sh exited nonzero (see $SCRATCH/mkimage2.log)"
fi
# --- scenario 3: a PAYLOAD_DIR that is not a directory fails closed ---
NOTADIR="$SCRATCH/notadir"
: > "$NOTADIR"
OUT3="$SCRATCH/out3"
err3="$(OUT="$OUT3" BUSYBOX="$BUSYBOX_BIN" PAYLOAD_DIR="$NOTADIR" \
bash "$QEMU_DIR/mkimage.sh" 2>&1 1>/dev/null)"
rc3=$?
if [ "$rc3" -ne 0 ] && printf '%s' "$err3" | grep -qF "FATAL: PAYLOAD_DIR '$NOTADIR' is not a directory"; then
pass "PAYLOAD_DIR: a non-directory path fails closed with the FATAL message"
else
fail "PAYLOAD_DIR: non-directory path gave rc=$rc3, stderr='$err3' (want nonzero + the FATAL message)"
fi
[ -e "$OUT3/disk.img" ] && fail "PAYLOAD_DIR: a disk image was written for a non-directory payload dir"
# --- scenario 4: ui-drive.sh looks for warden-ui in PAYLOAD_DIR ---
# An empty set fails its warden-ui check before anything is built; the set
# with a warden-ui gets past it and stops at the next check, because the
# PATH it runs with holds only dirname (no qemu-system-arm), so no VM boots.
EMPTY="$SCRATCH/empty"
mkdir -p "$EMPTY" "$SCRATCH/nobin"
ln -s "$(command -v dirname)" "$SCRATCH/nobin/dirname"
BASH_BIN="$(command -v bash)"
printf 'page Demo\n' > "$SCRATCH/drive.txt"
: > "$SCRATCH/zImage"
err4="$(PAYLOAD_DIR="$EMPTY" PATH="$SCRATCH/nobin" "$BASH_BIN" "$QEMU_DIR/tests/ui-drive.sh" \
"$SCRATCH/zImage" "$SCRATCH/drive.txt" "$SCRATCH/drive-out" 2>&1)"
if printf '%s' "$err4" | grep -qF "FATAL: no warden-ui in $EMPTY"; then
pass "ui-drive.sh: a PAYLOAD_DIR without warden-ui is refused, naming the directory"
else
fail "ui-drive.sh: PAYLOAD_DIR without warden-ui gave '$err4'"
fi
chmod +x "$ALT/warden-ui"
err5="$(PAYLOAD_DIR="$ALT" PATH="$SCRATCH/nobin" "$BASH_BIN" "$QEMU_DIR/tests/ui-drive.sh" \
"$SCRATCH/zImage" "$SCRATCH/drive.txt" "$SCRATCH/drive-out" 2>&1)"
if printf '%s' "$err5" | grep -qF "qemu-system-arm not on PATH" && ! printf '%s' "$err5" | grep -q "no warden-ui"; then
pass "ui-drive.sh: a PAYLOAD_DIR with warden-ui passes the payload check"
else
fail "ui-drive.sh: PAYLOAD_DIR with an executable warden-ui gave '$err5' (want the qemu-system-arm check next)"
fi
if [ "$FAIL" -ne 0 ]; then
echo "payload-dir: FAILED"
exit 1
fi
echo "payload-dir: all scenarios passed"
+394 -14
View File
@@ -42,6 +42,28 @@ a real panel, so these verbs mean the same thing on the rig and on hardware:
address, answers nothing) or put it back; needs
--rs485-control (ui-drive.sh --rs485-devices)
ctl WORDS... raw passthrough for anything the channel grows
override TOPIC DOC|null
pin the state document TOPIC inside warden-ui
(DOC: one compact JSON object or array) or unpin
it (null), through the UI's test hook on the
device bus (flare-edge docs/bus-test-hook.md),
which the bridge's `@hook` reaches with the
payload's wthctl. ok when the hook answers
ok:true, fail on its ok:false (the err is the
detail), fatal when the request never reached
the hook (no bus, no wthctl, no reply). Needs a
broker, wthctl and a test-flavor warden-ui in the
payload
assert_ui_chain [ACCOUNT]
the UI runs the way a panel starts it (a boot
through ui-drive.sh --init-chain, flare-edge
#2210): exactly one warden-ui and one
warden-ui-run loop, the UI's real, effective,
saved and filesystem uids all ACCOUNT's
(default warden-ui, never 0), no safe-mode flag
(/run/warden/ui-safe-mode) and no exit or
refusal in /tmp/warden-ui.log. Read with
`@procs` and `@cat` over the control channel
assert_page MENU/TAB the active page is exactly this
assert_hit X Y CLASS [box=X1,Y1,WxH] [TEXT...]
a real tap at X,Y lands on an object of CLASS,
@@ -154,7 +176,13 @@ def _load_imgtools():
AXIS_MAX = 32767
TAP_HOLD_S = 0.35
TAP_OBSERVE_TIMEOUT_S = 2.0
# How long the runner waits for the guest to count an injected press or
# release. A behaviour check, not a budget: a loaded runner (two TCG VMs on a
# shared host) has taken longer than 2 s to count the release that opens the
# drawer (flare-edge#1138), so the wait is a hang backstop. A wait longer than
# INPUT_SLOW_NOTE_S still passes and says so in the step's detail.
TAP_OBSERVE_TIMEOUT_S = 20.0
INPUT_SLOW_NOTE_S = 2.0
# Bounds every blocking read on the QMP socket -- the greeting banner, the
# qmp_capabilities handshake, and every screendump/tap/quit round trip --
@@ -166,6 +194,17 @@ TAP_OBSERVE_TIMEOUT_S = 2.0
# wedged qemu-system-arm cannot outlive the script.
QMP_TIMEOUT_S = 20.0
# Bounds each recv() on the control channel. It must outlast the bridge's
# own reply wait (WARDEN_CTL_WAIT_S, 30 s of 0.05 s polls, which take longer
# in wall time on a slow TCG guest), so a slow UI reaches the driver as the
# bridge's explicit "no reply" line rather than a bare socket timeout.
CTL_TIMEOUT_S = 90.0
# The bridge's own answer when warden-ui did not reply within its bound
# (Ctl.NO_REPLY; a module constant too because the offline tests swap the
# Ctl class out).
BRIDGE_NO_REPLY = "bridge: no reply from warden-ui"
# Where webstatus.c (ui-src/src/warden/webstatus.c) publishes its atomic
# snapshot inside the guest. assert_json/wait_json `@cat` this path over the
# control channel; see the bridge in rootfs/sbin/init.
@@ -223,19 +262,36 @@ def do_tap(s, f, ax, ay, hold=TAP_HOLD_S):
def wait_input_count(ctx, field, before):
"""Wait until one guest input counter advances."""
"""Wait until one guest input counter advances.
Records the longest wait of the current verb in ctx.input_wait_s, so a
slow guest shows in the results without failing the step."""
if before is None:
time.sleep(0.05)
return True
deadline = time.monotonic() + TAP_OBSERVE_TIMEOUT_S
start = time.monotonic()
deadline = start + TAP_OBSERVE_TIMEOUT_S
while time.monotonic() < deadline:
now = parse_stats(ctx.ctl.send("stats")).get(field)
if now is not None and now != before:
waited = time.monotonic() - start
ctx.input_wait_s = max(getattr(ctx, "input_wait_s", 0.0), waited)
return True
time.sleep(0.02)
return False
def input_verdict(ctx, observed):
"""The (status, detail) of a tap, swipe or fling from its observation."""
if not observed:
return ("fail", "input press or release was not consumed within "
f"{TAP_OBSERVE_TIMEOUT_S:g} seconds")
waited = getattr(ctx, "input_wait_s", 0.0)
if waited > INPUT_SLOW_NOTE_S:
return "ok", f"slow guest: input consumed after {waited:.1f} s"
return "ok", ""
def do_observed_tap(ctx, ax, ay):
"""Wait until the guest consumes both halves of a tap."""
before = parse_stats(ctx.ctl.send("stats"))
@@ -327,12 +383,12 @@ class Ctl:
# rootfs/sbin/init's ctl bridge (the FIFO-to-socket relay this class
# talks to). Nothing enforces the two staying in sync -- a sentinel
# changed on one side and not the other means send() below blocks until
# its own 15s timeout on every ctl-dependent step, with nothing at that
# its own CTL_TIMEOUT_S on every ctl-dependent step, with nothing at that
# point pointing back at this mismatch as the cause.
SENTINEL = "<<END>>"
# A real reply (a hit's box, the status JSON) is at most a few KB. The
# 15s socket timeout below bounds each individual recv(), not the total
# socket timeout below bounds each individual recv(), not the total
# bytes accepted, so a peer that keeps streaming data fast enough to beat
# that per-call timeout, but never emits a newline or SENTINEL, would
# otherwise grow self.buf without limit and exhaust host memory before
@@ -340,7 +396,13 @@ class Ctl:
# silent or closes outright already does.
MAX_BUF = 256 * 1024
def __init__(self, path, timeout=15.0):
# The bridge's own answer when warden-ui did not reply within its bound
# (warden_ctl_bridge in rootfs/etc/warden-lib.sh, flare-edge #1448).
NO_REPLY = BRIDGE_NO_REPLY
def __init__(self, path, timeout=None):
if timeout is None:
timeout = CTL_TIMEOUT_S
self.sock = socket.socket(socket.AF_UNIX)
self.sock.settimeout(timeout)
self.sock.connect(path)
@@ -369,7 +431,177 @@ class Ctl:
if line.strip() == cmd.strip():
continue
lines.append(line)
return "\n".join(lines).strip()
reply = "\n".join(lines).strip()
# A UI that did not answer in time is a rig fault, not evidence: an
# empty reply judged as "page is ''" hid it (flare-edge #1448).
if reply.startswith(self.NO_REPLY):
raise RuntimeError(f"control channel: {reply}")
return reply
# Stall probe (flare-edge #1528). When a step fails because warden-ui did not
# answer (the bridge's no-reply line) or did not consume an injected press,
# the driver samples the host, the VM's vCPU thread and the guest over
# STALL_WINDOW_S and appends one line to the step's detail, so the job log
# itself says whether the host starved the VM, the guest CPU was saturated
# (and by which processes), the guest waited on I/O, or the guest sat idle
# while warden-ui was blocked. Re-run jobs lose their artifacts; the job log
# keeps this line. At most STALL_REPORTS_MAX probes per run, since each one
# costs the window.
STALL_WINDOW_S = 2.0
STALL_REPORTS_MAX = 3
INPUT_NOT_CONSUMED = "was not consumed within"
def is_stall(detail):
"""Whether a failed step's detail is warden-ui not answering."""
return BRIDGE_NO_REPLY in detail or INPUT_NOT_CONSUMED in detail
def parse_proc_stat(text):
"""Guest /proc/stat -> (cpu jiffies list, procs_running, procs_blocked);
None when the text has no aggregate cpu line."""
cpu, running, blocked = None, None, None
for line in text.splitlines():
parts = line.split()
if not parts:
continue
if parts[0] == "cpu":
cpu = [int(x) for x in parts[1:] if x.isdigit()]
elif parts[0] == "procs_running" and len(parts) > 1:
running = int(parts[1])
elif parts[0] == "procs_blocked" and len(parts) > 1:
blocked = int(parts[1])
if not cpu or len(cpu) < 5:
return None
return cpu, running, blocked
def parse_procs(text):
"""/proc/<pid>/stat lines (the bridge's `@procs`) -> {pid: (comm, state,
utime + stime)}. The comm may hold spaces or parentheses, so the fields
are counted from its last ')'."""
out = {}
for line in text.splitlines():
head, sep, tail = line.rpartition(")")
if not sep or " (" not in head:
continue
pid, _, comm = head.partition(" (")
fields = tail.split()
if not pid.strip().isdigit() or len(fields) < 13:
continue
try:
ticks = int(fields[11]) + int(fields[12])
except ValueError:
continue
out[int(pid)] = (comm, fields[0], ticks)
return out
def guest_cpu_delta(a, b):
"""Two parse_proc_stat() samples -> (busy share, iowait share) of the
guest CPU over the window, or None when nothing was counted."""
if a is None or b is None:
return None
d = [y - x for x, y in zip(a[0], b[0])]
total = sum(d)
if total <= 0:
return None
idle, iowait = d[3], d[4]
return (total - idle - iowait) / total, iowait / total
def top_procs(a, b, total_ticks, n=3):
"""The N guest processes that used the most CPU between two parse_procs()
samples, as 'comm share%' strings, and the comms in state D at the end."""
used = []
for pid, (comm, _state, ticks) in b.items():
before = a.get(pid)
if before is not None and ticks > before[2]:
used.append((ticks - before[2], comm))
used.sort(reverse=True)
top = [f"{comm} {100 * t / total_ticks:.0f}%" for t, comm in used[:n]] if total_ticks > 0 else []
dstate = sorted({comm for comm, state, _ in b.values() if state == "D"})
return top, dstate
def stall_verdict(vcpu_share, guest, blocked, dstate):
"""One phrase naming the most likely cause from the probe's numbers."""
if vcpu_share is not None and vcpu_share < 0.6:
return "the host starves the VM (its vCPU thread ran under 60% of a core)"
if guest is None:
return "the guest did not answer the probe"
busy, iowait = guest
if busy >= 0.9:
return "the guest CPU is saturated"
if iowait >= 0.3 or blocked or dstate:
return "the guest waits on I/O"
return "the guest is mostly idle: warden-ui is blocked, not starved"
def _read(path):
try:
with open(path) as fh:
return fh.read()
except OSError:
return ""
def _host_psi(kind):
m = re.search(r"some avg10=([0-9.]+)", _read(f"/proc/pressure/{kind}"))
return f"{float(m.group(1)):.0f}%" if m else "n/a"
def _thread_ticks(tids):
total = 0
for tid in tids:
fields = _read(f"/proc/{tid}/stat").rpartition(")")[2].split()
if len(fields) < 13:
return None
total += int(fields[11]) + int(fields[12])
return total
def _guest_sample(ctl):
try:
return parse_proc_stat(ctl.send("@cat /proc/stat")), parse_procs(ctl.send("@procs"))
except (RuntimeError, OSError):
return None, {}
def stall_report(ctx):
"""Sample the host, the vCPU thread and the guest over STALL_WINDOW_S and
describe them in one line (see the block comment above STALL_WINDOW_S)."""
try:
tids = [c["thread-id"] for c in rpc(ctx.s, ctx.f, {"execute": "query-cpus-fast"})]
except (RuntimeError, OSError, KeyError, TypeError, ValueError):
tids = []
hz = os.sysconf("SC_CLK_TCK")
v0 = _thread_ticks(tids) if tids else None
g0, p0 = _guest_sample(ctx.ctl) if ctx.ctl else (None, {})
t0 = time.monotonic()
time.sleep(STALL_WINDOW_S)
v1 = _thread_ticks(tids) if tids else None
g1, p1 = _guest_sample(ctx.ctl) if ctx.ctl else (None, {})
window = time.monotonic() - t0
vcpu = (v1 - v0) / (hz * window) if v0 is not None and v1 is not None else None
guest = guest_cpu_delta(g0, g1)
blocked = g1[2] if g1 else None
total_ticks = sum(y - x for x, y in zip(g0[0], g1[0])) if g0 and g1 else 0
top, dstate = top_procs(p0, p1, total_ticks)
load = os.getloadavg()[0]
parts = [f"stall probe ({window:.1f} s): {stall_verdict(vcpu, guest, blocked, dstate)}",
f"host load {load:.1f}/{os.cpu_count()} cpus, psi cpu {_host_psi('cpu')} "
f"io {_host_psi('io')}",
"vcpu " + (f"{100 * vcpu:.0f}% of a core" if vcpu is not None else "n/a")]
if guest is None:
parts.append("guest n/a")
else:
parts.append(f"guest busy {100 * guest[0]:.0f}% iowait {100 * guest[1]:.0f}%, "
f"running {g1[1]} blocked {g1[2]}")
parts.append("top " + (", ".join(top) if top else "n/a"))
parts.append("D " + (", ".join(dstate) if dstate else "none"))
return "; ".join(parts)
HIT_RE = re.compile(r'^hit \d+,\d+: (\S+)(?: text="(.*)" box=(-?\d+),(-?\d+),(\d+)x(\d+))?$')
@@ -402,7 +634,7 @@ def poll_until(check, timeout_s, period=0.5):
they all mean the same thing by a timeout.
A CHECK that raises RuntimeError or OSError -- the control channel
dying mid-poll, e.g. a socket.timeout past Ctl's own 15s per-call
dying mid-poll, e.g. a socket.timeout past Ctl's own CTL_TIMEOUT_S per-call
timeout -- stops polling right there instead of retrying a channel
that is probably gone, and comes back with FATAL true so the caller
records a `fatal` row (the same idea as ConsoleWatch.check() turning a
@@ -733,6 +965,10 @@ class Ctx:
# console size when the step before this one began (flare-edge#233).
self.next_cmd = None
self.prev_step_console = 0
# The longest input-count wait of the current tap, swipe or fling.
self.input_wait_s = 0.0
# Stall probes run so far (STALL_REPORTS_MAX bounds them).
self.stall_reports = 0
def need_ctl(self, lineno, cmd):
if self.ctl is None:
@@ -792,6 +1028,7 @@ def verb_shot(ctx, lineno, cmd, args, line):
def verb_tap(ctx, lineno, cmd, args, line):
x, y = int(args[0]), int(args[1])
ctx.tap_sent = False
ctx.input_wait_s = 0.0
try:
observed = do_observed_tap(ctx, to_axis(x, ctx.size), to_axis(y, ctx.size))
except (RuntimeError, OSError):
@@ -804,23 +1041,22 @@ def verb_tap(ctx, lineno, cmd, args, line):
if ctx.next_cmd == "expect_reboot" and ctx.tap_sent:
return "ok", "tap sent; the control channel closed as the guest went down"
raise
return (("ok", "") if observed else
("fail", "input press or release was not consumed within 2 seconds"))
return input_verdict(ctx, observed)
def verb_swipe(ctx, lineno, cmd, args, line):
ms = int(args[4]) if len(args) > 4 else 400
ctx.input_wait_s = 0.0
observed = do_observed_swipe(
ctx, int(args[0]), int(args[1]), int(args[2]), int(args[3]), ms)
return (("ok", "") if observed else
("fail", "input press or release was not consumed within 2 seconds"))
return input_verdict(ctx, observed)
def verb_fling(ctx, lineno, cmd, args, line):
ctx.input_wait_s = 0.0
observed = do_observed_swipe(
ctx, int(args[0]), int(args[1]), int(args[2]), int(args[3]), ms=120)
return (("ok", "") if observed else
("fail", "input press or release was not consumed within 2 seconds"))
return input_verdict(ctx, observed)
def verb_sleep(ctx, lineno, cmd, args, line):
@@ -944,6 +1180,140 @@ def verb_rs485(ctx, lineno, cmd, args, line):
return ("ok" if reply.startswith("ok") else "fail"), reply
# The bridge's `@hookdoc` piece size: the ctl port is a tty in cooked mode,
# which cuts a line at 4095 bytes, and an override document may be 16 KiB.
HOOK_PIECE = 2000
# A concrete topic: no wildcard, no empty level, no leading slash, nothing a
# drive line could not carry as one word.
HOOK_TOPIC = re.compile(r"^[A-Za-z0-9_.%-]+(/[A-Za-z0-9_.%-]+)*$")
def hook_request(ctl, words, args):
"""One request to a test hook through the bridge (`@hookdoc` pieces, then
`@hook WORDS`) -> the reply text. A refused piece is a channel fault."""
text = json.dumps(args, separators=(",", ":"), ensure_ascii=True)
for at in range(0, len(text), HOOK_PIECE):
op = "@hookdoc" if at == 0 else "@hookdoc+"
reply = ctl.send(f"{op} {text[at:at + HOOK_PIECE]}")
if not reply.startswith("hookdoc: "):
raise RuntimeError(f"control channel: hook args refused: {reply}")
return ctl.send(f"@hook {words}")
def judge_hook_reply(reply):
"""(status, detail) for a hook reply: ok:true passes, ok:false fails with
the hook's err, and anything else (a bridge line, no JSON) is fatal: the
step never reached a hook that could judge it."""
if reply.startswith("bridge: "):
return "fatal", reply
try:
doc = json.loads(reply)
except ValueError:
return "fatal", f"hook reply is not JSON: {reply!r}"
if not isinstance(doc, dict) or not isinstance(doc.get("ok"), bool):
return "fatal", f"hook reply has no ok member: {reply!r}"
if doc["ok"]:
return "ok", ""
return "fail", json.dumps(doc.get("err"), sort_keys=True)
def verb_override(ctx, lineno, cmd, args, line):
# override TOPIC DOC|null (flowc.py action_override). The document is
# the rest of the line, which may hold spaces inside its strings.
ctx.need_ctl(lineno, cmd)
topic, _, doc_text = line[len(cmd):].strip().partition(" ")
if not HOOK_TOPIC.match(topic):
return "fatal", f"override topic {topic!r} is not one concrete topic"
try:
doc = json.loads(doc_text)
except ValueError:
return "fatal", f"override document is not JSON: {doc_text!r}"
if doc is not None and not isinstance(doc, (dict, list)):
return "fatal", "override document must be an object, an array or null"
return judge_hook_reply(hook_request(ctx.ctl, "override", {"topic": topic, "doc": doc}))
UI_CHAIN_SAFE_FLAG = "/run/warden/ui-safe-mode"
UI_CHAIN_LOG = "/tmp/warden-ui.log"
UI_CHAIN_NO_FILE = "bridge: no such file: "
# warden-ui-run's own lines in the log S99lvgl points it at: a restart
# ("warden-ui exited N") or the end of the loop ("refusing to run the UI").
UI_CHAIN_LOG_BAD = re.compile(r"warden-ui-run: .*(exited|refusing|already running)|exited \d+")
def account_uid(passwd_text, account):
"""The account's uid from passwd text, or None."""
for line in passwd_text.splitlines():
f = line.split(":")
if len(f) >= 3 and f[0] == account and f[2].isdigit():
return int(f[2])
return None
def status_uids(status_text):
"""The four uids of a /proc/<pid>/status Uid line, or None."""
for line in status_text.splitlines():
parts = line.split()
if parts and parts[0] == "Uid:" and len(parts) >= 5:
try:
return [int(x) for x in parts[1:5]]
except ValueError:
return None
return None
def judge_ui_chain(procs_text, passwd_text, status_of, safe_reply, log_text, account):
"""Problems with a UI started through the shipped init chain; empty
when it runs as a panel runs it. status_of(pid) -> that pid's
/proc/<pid>/status text."""
problems = []
want = account_uid(passwd_text, account)
if want is None:
problems.append(f"no account {account} in /etc/passwd (S03warden-accounts did not run)")
elif want == 0:
problems.append(f"account {account} has uid 0")
procs = parse_procs(procs_text)
live = {pid: comm for pid, (comm, state, _t) in procs.items() if state != "Z"}
uis = sorted(pid for pid, comm in live.items() if comm == "warden-ui")
loops = sorted(pid for pid, comm in live.items() if comm == "warden-ui-run")
if len(uis) != 1:
problems.append(f"{len(uis)} warden-ui processes, want 1 (pids {uis})")
if len(loops) != 1:
problems.append(f"{len(loops)} warden-ui-run loops, want 1 (pids {loops})")
for pid in uis:
seen = status_uids(status_of(pid))
if seen is None:
problems.append(f"warden-ui pid {pid}: no Uid line")
elif want not in (None, 0) and seen != [want] * 4:
problems.append(f"warden-ui pid {pid} runs with uids {seen}, not {account} ({want})")
if not safe_reply.startswith(UI_CHAIN_NO_FILE):
problems.append(f"safe mode is on ({UI_CHAIN_SAFE_FLAG} exists)")
if log_text.startswith(UI_CHAIN_NO_FILE):
problems.append(f"no {UI_CHAIN_LOG}: S99lvgl never started the UI")
else:
bad = [line for line in log_text.splitlines() if UI_CHAIN_LOG_BAD.search(line)]
if bad:
problems.append(f"{UI_CHAIN_LOG}: {bad[0]!r}" + (f" (+{len(bad) - 1} more)" if len(bad) > 1 else ""))
return problems
def verb_assert_ui_chain(ctx, lineno, cmd, args, line):
# assert_ui_chain [ACCOUNT] (flare-edge #2210): the UI came up through
# S03warden-accounts, S99lvgl and warden-ui-run, and stays up as its
# account. A missing process is a `fail`: that is exactly the bug class
# (#1903's setpriv left no UI), not a rig fault.
ctx.need_ctl(lineno, cmd)
account = args[0] if args else "warden-ui"
problems = judge_ui_chain(
ctx.ctl.send("@procs"),
ctx.ctl.send("@cat /etc/passwd"),
lambda pid: ctx.ctl.send(f"@cat /proc/{pid}/status"),
ctx.ctl.send(f"@cat {UI_CHAIN_SAFE_FLAG}"),
ctx.ctl.send(f"@cat {UI_CHAIN_LOG}"),
account)
return ("fail", "; ".join(problems)) if problems else ("ok", "")
def verb_assert_page(ctx, lineno, cmd, args, line):
ctx.need_ctl(lineno, cmd)
want = " ".join(args)
@@ -1163,6 +1533,7 @@ VERBS = {
"ctl": verb_query,
"rs485": verb_rs485,
"assert_page": verb_assert_page,
"assert_ui_chain": verb_assert_ui_chain,
"assert_hit": verb_assert_hit,
"wait_hit": verb_wait_hit,
"assert_json": verb_assert_json,
@@ -1174,6 +1545,7 @@ VERBS = {
"wait_region": verb_wait_region,
"assert_ocr": verb_assert_ocr,
"expect_reboot": verb_expect_reboot,
"override": verb_override,
}
@@ -1247,6 +1619,14 @@ def drive(s, f, script_path, outdir, size, ctl_path=None, console_path=None, ref
# Recorded the same as any other fatal row: the run keeps going
# past it.
result = ("fatal", str(e))
if (result is not None and result[0] != "ok" and len(result) > 1
and is_stall(str(result[1])) and ctx.stall_reports < STALL_REPORTS_MAX):
ctx.stall_reports += 1
try:
probe = stall_report(ctx)
except (RuntimeError, OSError, ValueError) as e:
probe = f"stall probe failed: {e}"
result = (result[0], f"{result[1]}; {probe}")
if result is not None:
record(lineno, line, *result)
+179
View File
@@ -0,0 +1,179 @@
#!/usr/bin/env bash
# Regression test for mkimage.sh's ROOTFS_OVERLAY hook (see its Env note): a
# run lays the panel's own init scripts over the rig rootfs of both slots, so
# a warden.initchain boot starts the UI through S99lvgl and warden-ui-run
# (flare-edge #2210). Only etc/ and usr/ may appear at the overlay's top and
# no entry may be a symlink; a refused overlay writes no image.
#
# Works on a copy of qemu/ (no payload, no out/) so the default payload
# directory is the copy's own and nothing in the checkout is touched. Builds
# real disk images the same way mkimage.sh always does (unprivileged
# mkfs.ext4 -d), then reads rootfs_a and rootfs_b back with debugfs -R
# (read-only, no mount or loop device) to check what actually landed.
#
# bash rootfs-overlay.sh
set -uo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" # qemu/tests/
SRC_QEMU="$(cd "$HERE/.." && pwd)" # qemu/
FAIL=0
pass() { printf '[PASS] %s\n' "$1"; }
fail() { printf '[FAIL] %s\n' "$1"; FAIL=1; }
# mkfs.ext4 and debugfs live in sbin, which user shells on Debian do not put
# on PATH; mkimage.sh applies the same fix.
PATH="$PATH:/usr/sbin:/sbin"
command -v debugfs >/dev/null || {
echo "FATAL: debugfs (e2fsprogs) not found: needed to read the rootfs partitions back" >&2
exit 1
}
SCRATCH="$(mktemp -d "${TMPDIR:-/tmp}/warden-qemu-rootfs-overlay.XXXXXX")"
trap 'rm -rf "$SCRATCH"' EXIT
# The copy: everything mkimage.sh reads, without the build outputs or any
# payload a developer dropped into the checkout.
QEMU_DIR="$SCRATCH/qemu"
mkdir -p "$QEMU_DIR/payload"
for entry in "$SRC_QEMU"/*; do
case "$(basename "$entry")" in out|payload) continue ;; esac
cp -a "$entry" "$QEMU_DIR/"
done
# shellcheck source=../lib.sh disable=SC1091
. "$QEMU_DIR/lib.sh"
# shellcheck source=../blkdevparts.conf disable=SC1091
. "$QEMU_DIR/blkdevparts.conf"
declare -A PART_OFF PART_SIZE
capture_part() { PART_OFF[$1]="$2"; PART_SIZE[$1]="$3"; return 0; }
qemu_each_partition capture_part
for name in rootfs_a rootfs_b; do
[ -n "${PART_OFF[$name]:-}" ] || { echo "FATAL: no '$name' entry in blkdevparts.conf" >&2; exit 1; }
done
# extract_part DISK NAME OUTFILE: one partition window, sparse.
extract_part() {
dd if="$1" of="$3" bs=4096 skip=$((PART_OFF[$2] / 4096)) \
count=$((PART_SIZE[$2] / 4096)) conv=sparse status=none
}
# Reuse an already-verified busybox wherever a prior build produced one; a
# checkout that never ran mkimage.sh fetches and verifies it once here.
BUSYBOX_BIN="$SRC_QEMU/out/busybox-armv7l"
if [ ! -f "$BUSYBOX_BIN" ]; then
OUT="$SCRATCH/bb" qemu_get_busybox
BUSYBOX_BIN="$BB"
fi
OV="$SCRATCH/overlay"
mkdir -p "$OV/etc/init.d" "$OV/usr/lib/warden"
printf '#!/bin/sh\necho lvgl\n' > "$OV/etc/init.d/S99lvgl"
chmod 0755 "$OV/etc/init.d/S99lvgl"
printf '#!/bin/sh\necho run\n' > "$OV/usr/lib/warden/warden-ui-run"
chmod 0750 "$OV/usr/lib/warden/warden-ui-run"
printf 'ui=1\n' > "$OV/etc/flare.conf"
chmod 0640 "$OV/etc/flare.conf"
mode_of() { # mode_of IMG PATH
debugfs -R "stat $2" "$1" 2>/dev/null | grep -oE 'Mode: *[0-7]+' | grep -oE '[0-7]+$'
}
# --- scenario 1: the overlay lands in both slots with its modes ---
OUT1="$SCRATCH/out1"
if OUT="$OUT1" BUSYBOX="$BUSYBOX_BIN" ROOTFS_OVERLAY="$OV" \
bash "$QEMU_DIR/mkimage.sh" > "$SCRATCH/mkimage1.log" 2>&1; then
for slot in rootfs_a rootfs_b; do
IMG="$SCRATCH/$slot.1.img"
extract_part "$OUT1/disk.img" "$slot" "$IMG"
got="$(debugfs -R "cat /etc/init.d/S99lvgl" "$IMG" 2>/dev/null | tail -n 1)"
if [ "$got" = "echo lvgl" ]; then pass "overlay: $slot carries etc/init.d/S99lvgl"
else fail "overlay: $slot S99lvgl = '$got'"; fi
m="$(mode_of "$IMG" /usr/lib/warden/warden-ui-run)"
if [ "$m" = "0750" ]; then pass "overlay: $slot keeps warden-ui-run's mode 0750"
else fail "overlay: $slot warden-ui-run mode '$m', want 0750"; fi
m="$(mode_of "$IMG" /etc/flare.conf)"
if [ "$m" = "0640" ]; then pass "overlay: $slot keeps a data file's mode 0640"
else fail "overlay: $slot flare.conf mode '$m', want 0640"; fi
if debugfs -R "stat /sbin/init" "$IMG" 2>&1 | grep -q 'File not found'; then
fail "overlay: $slot lost the rig's own /sbin/init"
else
pass "overlay: $slot still has the rig's /sbin/init"
fi
if debugfs -R "stat /etc/passwd" "$IMG" 2>&1 | grep -q 'File not found'; then
fail "overlay: $slot lost the skeleton's /etc/passwd"
else
pass "overlay: $slot keeps the skeleton's /etc/passwd beside the overlay's etc/"
fi
done
else
fail "overlay: mkimage.sh exited nonzero with a valid overlay (see $SCRATCH/mkimage1.log)"
fi
# --- scenario 2: no overlay leaves /etc/init.d out ---
OUT2="$SCRATCH/out2"
if OUT="$OUT2" BUSYBOX="$BUSYBOX_BIN" bash "$QEMU_DIR/mkimage.sh" > "$SCRATCH/mkimage2.log" 2>&1; then
IMG="$SCRATCH/rootfs_a.2.img"
extract_part "$OUT2/disk.img" rootfs_a "$IMG"
if debugfs -R "stat /etc/init.d" "$IMG" 2>&1 | grep -q 'File not found'; then
pass "no overlay: rootfs_a has no /etc/init.d (the rig's direct start)"
else
fail "no overlay: rootfs_a has an /etc/init.d"
fi
else
fail "no overlay: mkimage.sh exited nonzero (see $SCRATCH/mkimage2.log)"
fi
# --- scenario 3: refused overlays fail closed and write no image ---
refused() { # refused <label> <dir> <stderr text>
local out="$SCRATCH/out-$1" err rc
err="$(OUT="$out" BUSYBOX="$BUSYBOX_BIN" ROOTFS_OVERLAY="$2" bash "$QEMU_DIR/mkimage.sh" 2>&1 1>/dev/null)"
rc=$?
if [ "$rc" -ne 0 ] && printf '%s' "$err" | grep -qF "$3" && [ ! -e "$out/disk.img" ]; then
pass "overlay refused ($1): nonzero, '$3', no image"
else
fail "overlay $1: rc=$rc stderr='$err' image=$([ -e "$out/disk.img" ] && echo yes || echo no)"
fi
}
: > "$SCRATCH/notadir"
refused notadir "$SCRATCH/notadir" "is not a directory"
mkdir -p "$SCRATCH/sbin-ov/sbin"; printf 'x\n' > "$SCRATCH/sbin-ov/sbin/init"
refused sbin "$SCRATCH/sbin-ov" "not 'sbin'"
mkdir -p "$SCRATCH/init-ov"; printf 'x\n' > "$SCRATCH/init-ov/init"
refused init "$SCRATCH/init-ov" "not 'init'"
mkdir -p "$SCRATCH/link-ov/etc"; ln -s /etc/shadow "$SCRATCH/link-ov/etc/shadow"
refused link "$SCRATCH/link-ov" "holds symlinks"
mkdir -p "$SCRATCH/toplink-ov"; ln -s "$OV/etc" "$SCRATCH/toplink-ov/etc"
refused toplink "$SCRATCH/toplink-ov" "not 'etc'"
mkdir -p "$SCRATCH/dot-ov/etc"; printf 'x\n' > "$SCRATCH/dot-ov/.hidden"
refused dot "$SCRATCH/dot-ov" "not '.hidden'"
# --- scenario 4: ui-drive.sh --init-chain checks its directory before boot ---
# Its PATH holds only dirname, so a directory that passes stops at the
# qemu-system-arm check and no VM boots.
mkdir -p "$SCRATCH/nobin" "$SCRATCH/pl"
ln -s "$(command -v dirname)" "$SCRATCH/nobin/dirname"
BASH_BIN="$(command -v bash)"
printf 'sleep 1\n' > "$SCRATCH/drive.txt"
: > "$SCRATCH/zImage"
printf '#!/bin/sh\n' > "$SCRATCH/pl/warden-ui"; chmod +x "$SCRATCH/pl/warden-ui"
drive_err() { # drive_err <init-chain dir>
PAYLOAD_DIR="$SCRATCH/pl" PATH="$SCRATCH/nobin" "$BASH_BIN" "$QEMU_DIR/tests/ui-drive.sh" \
--init-chain "$1" "$SCRATCH/zImage" "$SCRATCH/drive.txt" "$SCRATCH/drive-out" 2>&1
}
err="$(drive_err "$SCRATCH/no-such-dir")"
if printf '%s' "$err" | grep -qF "is not a directory"; then pass "ui-drive.sh: --init-chain with no directory is refused"
else fail "ui-drive.sh: --init-chain missing dir gave '$err'"; fi
mkdir -p "$SCRATCH/no-lvgl/etc/init.d"
err="$(drive_err "$SCRATCH/no-lvgl")"
if printf '%s' "$err" | grep -qF "has no etc/init.d/S99lvgl"; then pass "ui-drive.sh: --init-chain without S99lvgl is refused"
else fail "ui-drive.sh: --init-chain without S99lvgl gave '$err'"; fi
err="$(drive_err "$OV")"
if printf '%s' "$err" | grep -qF "qemu-system-arm not on PATH"; then pass "ui-drive.sh: a chain directory with S99lvgl passes its checks"
else fail "ui-drive.sh: --init-chain with S99lvgl gave '$err'"; fi
if [ "$FAIL" -ne 0 ]; then
echo "rootfs-overlay: FAILED"
exit 1
fi
echo "rootfs-overlay: all scenarios passed"
+11
View File
@@ -0,0 +1,11 @@
# The UI as a panel starts it (flare-edge #2210), run with
# ui-drive.sh --init-chain <dir with the panel's S03warden-accounts,
# S99lvgl, /usr/lib/warden/warden-ui-run and uid-check.sh> <zImage> this
# ui-drive.sh hands this script over once the UI has drawn a frame and the
# control bridge is up, about 20 to 40 s after boot under TCG. The sleep
# brings the check to roughly T+120 s, past three restarts and the 5 s
# hold-down, so a UI that only lives a few seconds per start is not seen as
# up, and a loop that gave up has had time to set safe mode.
echo init chain: waiting to about T+120 s
sleep 90
assert_ui_chain warden-ui
+477
View File
@@ -13,8 +13,11 @@ was never compared with the one the reference was captured under.
python3 test_qmp_drive.py
"""
import atexit
import json
import os
import re
import shutil
import socket
import subprocess
import sys
@@ -28,6 +31,15 @@ HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import qmp # noqa: E402
# Every temp dir this module makes (a drive's out dir per run_script, the
# console and QMP socket dirs) lands under one root per run, removed at exit,
# so a run leaves $TMPDIR as it found it (bfe-core1106-sdk#30: about 40 dirs
# per run used to stay behind). The prefix is short: an AF_UNIX socket path
# under it must stay inside about 108 bytes.
_TMP_ROOT = tempfile.mkdtemp(prefix="qdt.")
tempfile.tempdir = _TMP_ROOT
atexit.register(shutil.rmtree, _TMP_ROOT, True)
SIZE = 64
@@ -339,6 +351,52 @@ class PureHelpers(unittest.TestCase):
self.assertEqual(len(calls), 2)
self.assertEqual(calls[-1], [qmp.btn_ev(False)])
def _swipe_on_fake_clock(self, release_at_s):
"""verb_swipe against a guest that counts the press at once and the
release only once release_at_s of fake time has passed (None: never).
Returns the verdict and the fake time the verb took."""
clock = [0.0]
replies = iter(["presses: 0\nreleases: 0"]) # the baseline read
def send(cmd):
late = release_at_s is not None and clock[0] >= release_at_s
return next(replies, f"presses: 1\nreleases: {1 if late else 0}")
ctx = SimpleNamespace(s=None, f=None, size=720,
ctl=SimpleNamespace(send=send), input_wait_s=0.0)
def sleep(seconds):
clock[0] += seconds
saved = qmp.send_events, qmp.time.sleep, qmp.time.monotonic
qmp.send_events = lambda _s, _f, _events: None
qmp.time.sleep = sleep
qmp.time.monotonic = lambda: clock[0]
try:
verdict = qmp.verb_swipe(ctx, 1, "swipe", ["2", "350", "520", "352", "3000"], "")
finally:
qmp.send_events, qmp.time.sleep, qmp.time.monotonic = saved
return verdict, clock[0]
def test_swipe_release_counted_late_on_a_loaded_guest_passes(self):
# flare-edge#1138: the release that opens the drawer was counted
# after more than 2 s on a loaded runner; the old 2 s bound failed
# the swipe although the guest handled it. It passes, with a note.
(status, detail), _ = self._swipe_on_fake_clock(release_at_s=3.0 + 2.5)
self.assertEqual(status, "ok")
self.assertIn("slow guest: input consumed after 2.5 s", detail)
def test_swipe_release_counted_promptly_has_no_note(self):
(status, detail), _ = self._swipe_on_fake_clock(release_at_s=3.0 + 0.5)
self.assertEqual((status, detail), ("ok", ""))
def test_swipe_release_never_counted_fails_at_the_backstop(self):
(status, detail), took = self._swipe_on_fake_clock(release_at_s=None)
self.assertEqual(status, "fail")
self.assertIn(f"within {qmp.TAP_OBSERVE_TIMEOUT_S:g} seconds", detail)
# Bounded: the 3 s drag plus the backstop, and not much more.
self.assertLess(took, 3.0 + qmp.TAP_OBSERVE_TIMEOUT_S + 1.0)
def test_every_pixel_round_trips_through_lvgl_calibration(self):
# lv_evdev.c _evdev_calibrate: px = axis * (width - 1) / AXIS_MAX,
# integer division. A tap requested at px must land at px, for every
@@ -800,6 +858,254 @@ class DriveVerbs(unittest.TestCase):
self.assertEqual([r["status"] for r in rows], ["ok"])
class HookCtl(FakeCtl):
"""The bridge's `@hookdoc` / `@hook` commands (warden_ctl_bridge) over a
fake test hook: the pieces are joined as the bridge joins them, and the
hook's answer is whatever ANSWERS maps the joined args to."""
sent = []
answer = staticmethod(lambda words, args: '{"v":1,"ok":true,"data":{}}')
refuse_pieces = False
def __init__(self, path, timeout=15.0):
super().__init__(path, timeout)
self.doc = None
def send(self, cmd):
HookCtl.sent.append(cmd)
if cmd.startswith("@hookdoc+ "):
self.doc += cmd[len("@hookdoc+ "):]
return f"hookdoc: {len(self.doc)} bytes"
if cmd.startswith("@hookdoc "):
if HookCtl.refuse_pieces:
return "bridge: something else"
self.doc = cmd[len("@hookdoc "):]
return f"hookdoc: {len(self.doc)} bytes"
if cmd.startswith("@hook "):
args, self.doc = json.loads(self.doc or "{}"), None
return HookCtl.answer(cmd[len("@hook "):], args)
return super().send(cmd)
class OverrideVerb(unittest.TestCase):
def setUp(self):
HookCtl.sent = []
HookCtl.answer = staticmethod(lambda words, args: '{"v":1,"ok":true,"data":{}}')
HookCtl.refuse_pieces = False
def test_pin_and_unpin_reach_the_hook_as_one_request_each(self):
seen = []
def answer(words, args):
seen.append((words, args))
return '{"v":1,"ok":true,"data":{"pinned":1}}'
HookCtl.answer = staticmethod(answer)
rc, by, rows = run_script(
'override io/state/failsafe {"last_trip":{"why":"two words"},"ack":false}\n'
"override io/state/failsafe null\n", ctl_cls=HookCtl)
self.assertIsNone(rc, rows)
self.assertEqual([r["status"] for r in rows], ["ok", "ok"])
self.assertEqual(seen, [
("override", {"topic": "io/state/failsafe",
"doc": {"last_trip": {"why": "two words"}, "ack": False}}),
("override", {"topic": "io/state/failsafe", "doc": None}),
])
def test_a_large_document_goes_in_pieces_under_the_tty_line_limit(self):
seen = []
def answer(words, args):
seen.append(args)
return '{"v":1,"ok":true}'
HookCtl.answer = staticmethod(answer)
doc = {"rows": ["x" * 100] * 120}
rc, by, rows = run_script(
"override cfg/state/big " + json.dumps(doc, separators=(",", ":")) + "\n",
ctl_cls=HookCtl)
self.assertEqual(rows[0]["status"], "ok", rows)
self.assertEqual(seen, [{"topic": "cfg/state/big", "doc": doc}])
pieces = [c for c in HookCtl.sent if c.startswith("@hookdoc")]
self.assertGreater(len(pieces), 5)
self.assertTrue(pieces[0].startswith("@hookdoc {"))
self.assertTrue(all(c.startswith("@hookdoc+ ") for c in pieces[1:]))
self.assertTrue(all(len(c) < 4095 for c in HookCtl.sent), "a line over the tty limit")
self.assertEqual(HookCtl.sent[-1], "@hook override")
def test_the_hooks_refusal_is_a_fail_with_its_err(self):
HookCtl.answer = staticmethod(lambda words, args: json.dumps(
{"v": 1, "ok": False, "err": {"code": "E_NOT_FOUND", "msg": "no filter covers it"}}))
rc, by, rows = run_script('override io/state/nope {"a":1}\n', ctl_cls=HookCtl)
self.assertEqual(rc, 1)
self.assertEqual(rows[0]["status"], "fail")
self.assertIn("E_NOT_FOUND", rows[0]["detail"])
def test_a_request_that_never_reached_the_hook_is_fatal(self):
for reply in ("bridge: no hook client in the payload (/usr/bin/wthctl)",
"bridge: hook request got no answer (client exit 2): wthctl: no reply (-3)",
"not json", '{"v":1}', "[true]"):
HookCtl.answer = staticmethod(lambda words, args, r=reply: r)
rc, by, rows = run_script('override io/state/x {"a":1}\n', ctl_cls=HookCtl)
self.assertEqual(rows[0]["status"], "fatal", reply)
def test_a_refused_piece_is_fatal_for_the_step_only(self):
HookCtl.refuse_pieces = True
rc, by, rows = run_script('override io/state/x {"a":1}\nwake\n', ctl_cls=HookCtl)
self.assertEqual([r["status"] for r in rows], ["fatal", "ok"])
self.assertIn("hook args refused", rows[0]["detail"])
self.assertNotIn("@hook override", HookCtl.sent)
def test_a_malformed_line_is_fatal_and_sends_nothing(self):
rc, by, rows = run_script(
'override io/state/+ {"a":1}\n'
'override /io/state {"a":1}\n'
"override io//state null\n"
"override io/state/x {broken\n"
"override io/state/x 5\n"
'override io/state/x "text"\n'
"override io/state/x\n", ctl_cls=HookCtl)
self.assertEqual([r["status"] for r in rows], ["fatal"] * 7, rows)
self.assertEqual(HookCtl.sent, [])
def stat_line(pid, comm, state="S"):
"""A /proc/<pid>/stat line with enough fields for parse_procs."""
return f"{pid} ({comm}) {state} 1 1 1 0 -1 4194560 0 0 0 0 7 3 0 0 20 0 1 0 100"
class ChainCtl(FakeCtl):
"""A guest booted through the shipped init chain: what `@procs` and
`@cat` answer there. Class attributes are the scenario."""
procs = [stat_line(1, "init"), stat_line(310, "warden-ui-run"), stat_line(311, "warden-ui")]
passwd = "root:x:0:0:root:/root:/bin/sh\nwarden-ui:x:970:970::/var/empty:/bin/false\n"
uids = {311: "970\t970\t970\t970"}
files = {"/tmp/warden-ui.log": "Starting\nLVGL up\n"}
sent = []
def send(self, cmd):
ChainCtl.sent.append(cmd)
if cmd == "@procs":
return "\n".join(ChainCtl.procs)
if cmd == "@cat /etc/passwd":
return ChainCtl.passwd
m = re.match(r"@cat /proc/(\d+)/status$", cmd)
if m:
pid = int(m.group(1))
if pid not in ChainCtl.uids:
return f"bridge: no such file: /proc/{pid}/status"
return f"Name:\twarden-ui\nState:\tS (sleeping)\nUid:\t{ChainCtl.uids[pid]}\nGid:\t970\t970\t970\t970\n"
if cmd.startswith("@cat "):
path = cmd[len("@cat "):]
if path in ChainCtl.files:
return ChainCtl.files[path]
return f"bridge: no such file: {path}"
return super().send(cmd)
class UiChainVerb(unittest.TestCase):
"""assert_ui_chain (flare-edge #2210): the UI started through
S03warden-accounts, S99lvgl and warden-ui-run, and runs as its account."""
def setUp(self):
ChainCtl.procs = [stat_line(1, "init"), stat_line(310, "warden-ui-run"), stat_line(311, "warden-ui")]
ChainCtl.passwd = "root:x:0:0:root:/root:/bin/sh\nwarden-ui:x:970:970::/var/empty:/bin/false\n"
ChainCtl.uids = {311: "970\t970\t970\t970"}
ChainCtl.files = {"/tmp/warden-ui.log": "Starting\nLVGL up\n"}
ChainCtl.sent = []
def verdict(self, line="assert_ui_chain"):
rc, by, rows = run_script(line + "\n", ctl_cls=ChainCtl)
return rc, rows[0]
def test_a_ui_running_as_its_account_passes(self):
rc, row = self.verdict()
self.assertIsNone(rc, row)
self.assertEqual(row["status"], "ok", row)
self.assertIn("@cat /proc/311/status", ChainCtl.sent)
self.assertIn("@cat /run/warden/ui-safe-mode", ChainCtl.sent)
def test_the_1903_class_no_ui_after_the_loop_gave_up_fails(self):
# BusyBox setpriv without --reuid: every start exits 1, the loop
# sets safe mode, and the log has the exits.
ChainCtl.procs = [stat_line(1, "init"), stat_line(310, "warden-ui-run")]
ChainCtl.uids = {}
ChainCtl.files = {
"/tmp/warden-ui.log": "setpriv: unrecognized option '--reuid=warden-ui'\n"
"warden-ui-run: warden-ui exited 1\n" * 3,
"/run/warden/ui-safe-mode": "",
}
rc, row = self.verdict()
self.assertEqual(rc, 1)
self.assertEqual(row["status"], "fail")
self.assertIn("0 warden-ui processes, want 1", row["detail"])
self.assertIn("safe mode is on", row["detail"])
self.assertIn("warden-ui exited 1", row["detail"])
self.assertIn("(+2 more)", row["detail"])
def test_a_ui_left_running_as_root_fails(self):
ChainCtl.uids = {311: "0\t0\t0\t0"}
rc, row = self.verdict()
self.assertEqual(row["status"], "fail")
self.assertIn("runs with uids [0, 0, 0, 0], not warden-ui (970)", row["detail"])
def test_one_uid_of_four_left_behind_fails(self):
ChainCtl.uids = {311: "970\t970\t0\t970"}
rc, row = self.verdict()
self.assertIn("uids [970, 970, 0, 970]", row["detail"])
def test_no_account_fails(self):
ChainCtl.passwd = "root:x:0:0:root:/root:/bin/sh\n"
rc, row = self.verdict()
self.assertIn("no account warden-ui in /etc/passwd", row["detail"])
def test_an_account_with_uid_0_fails(self):
ChainCtl.passwd = "warden-ui:x:0:0::/:/bin/false\n"
rc, row = self.verdict()
self.assertIn("account warden-ui has uid 0", row["detail"])
def test_the_direct_start_without_a_loop_fails(self):
# The rig's own direct start: no warden-ui-run, no log.
ChainCtl.procs = [stat_line(1, "init"), stat_line(311, "warden-ui")]
ChainCtl.files = {}
rc, row = self.verdict()
self.assertIn("0 warden-ui-run loops, want 1", row["detail"])
self.assertIn("no /tmp/warden-ui.log", row["detail"])
def test_two_uis_or_two_loops_fail_and_zombies_do_not_count(self):
ChainCtl.procs = [stat_line(310, "warden-ui-run"), stat_line(320, "warden-ui-run"),
stat_line(311, "warden-ui"), stat_line(312, "warden-ui"),
stat_line(313, "warden-ui", "Z")]
ChainCtl.uids = {311: "970\t970\t970\t970", 312: "970\t970\t970\t970"}
rc, row = self.verdict()
self.assertIn("2 warden-ui processes, want 1 (pids [311, 312])", row["detail"])
self.assertIn("2 warden-ui-run loops", row["detail"])
def test_a_restart_in_the_log_fails_even_with_the_ui_back_up(self):
ChainCtl.files = {"/tmp/warden-ui.log": "warden-ui-run: warden-ui exited 139\n"}
rc, row = self.verdict()
self.assertEqual(row["status"], "fail")
self.assertIn("exited 139", row["detail"])
def test_a_refused_start_in_the_log_fails(self):
ChainCtl.files = {"/tmp/warden-ui.log":
"warden-ui-run: no setpriv with --reuid and no su; refusing to run the UI as root\n"}
rc, row = self.verdict()
self.assertIn("refusing", row["detail"])
def test_another_account_can_be_named(self):
ChainCtl.passwd = "kiosk:x:980:980::/:/bin/false\n"
ChainCtl.uids = {311: "980\t980\t980\t980"}
rc, row = self.verdict("assert_ui_chain kiosk")
self.assertEqual(row["status"], "ok", row)
def test_pure_helpers(self):
self.assertEqual(qmp.account_uid("a:x:5:5::/:/bin/sh\nb:x:x:1::/:/\n", "a"), 5)
self.assertIsNone(qmp.account_uid("a:x:5:5::/:/bin/sh\n", "b"))
self.assertIsNone(qmp.account_uid("b:x:nope:1::/:/\n", "b"))
self.assertEqual(qmp.status_uids("Uid:\t1\t2\t3\t4\n"), [1, 2, 3, 4])
self.assertIsNone(qmp.status_uids("Gid:\t1\t2\t3\t4\n"))
class ConsoleWatchTests(unittest.TestCase):
"""ConsoleWatch replaced a ui_exited() that reread and rescanned the
WHOLE console log on every one of drive()'s per-step checks -- O(steps *
@@ -1113,6 +1419,49 @@ class CtlSocketProtocol(unittest.TestCase):
th.join(timeout=2)
self.assertEqual(got, "the actual reply")
def test_bridge_no_reply_line_raises_as_a_rig_fault(self):
# flare-edge #1448: a UI slower than the bridge's wait came back as
# an empty reply and was judged "page is ''". The bridge now says
# so, and that line must stop the flow as a rig fault.
def server():
self.server_sock.recv(4096)
self.server_sock.sendall(
b"bridge: no reply from warden-ui within 30 s: page\n<<END>>\n")
th = threading.Thread(target=server, daemon=True)
th.start()
try:
with self.assertRaises(RuntimeError) as cm:
self.ctl.send("page")
finally:
th.join(timeout=2)
self.assertIn("no reply from warden-ui", str(cm.exception))
def test_bridge_no_such_file_stays_an_ordinary_reply(self):
# Only the no-reply line is a fault; @cat's missing-file answer is
# a detail the json channel handles itself.
def server():
self.server_sock.recv(4096)
self.server_sock.sendall(b"bridge: no such file: /x\n<<END>>\n")
th = threading.Thread(target=server, daemon=True)
th.start()
try:
got = self.ctl.send("@cat /x")
finally:
th.join(timeout=2)
self.assertEqual(got, "bridge: no such file: /x")
def test_ctl_timeout_outlasts_the_bridge_wait(self):
# The bridge polls up to 30 s (more wall time on a slow guest); a
# shorter socket timeout would turn its explicit answer into a bare
# socket.timeout. Read the bridge default from the rootfs itself.
lib = os.path.join(HERE, "..", "rootfs", "etc", "warden-lib.sh")
with open(lib) as f:
m = re.search(r"WARDEN_CTL_WAIT_S:-(\d+)", f.read())
self.assertIsNotNone(m, "warden_ctl_bridge default wait not found")
self.assertGreaterEqual(qmp.CTL_TIMEOUT_S, 2 * int(m.group(1)))
def test_leftover_bytes_after_sentinel_carry_over_to_the_next_send(self):
# One write carries this reply's SENTINEL immediately followed by
# bytes belonging to the NEXT command's reply -- proving self.buf
@@ -1271,5 +1620,133 @@ class JsonStatusFetch(unittest.TestCase):
self.assertGreaterEqual(time.monotonic() - t0, 0.6)
def _proc_stat(user, idle, iowait=0, running=1, blocked=0):
return (f"cpu {user} 0 0 {idle} {iowait} 0 0 0 0 0\ncpu0 {user} 0 0 {idle} {iowait} 0 0 0 0 0\n"
f"ctxt 1\nprocs_running {running}\nprocs_blocked {blocked}\n")
def _pid_line(pid, comm, state, utime, stime=0):
rest = " ".join(["0"] * 10)
return f"{pid} ({comm}) {state} 1 1 1 0 -1 0 0 0 0 0 {utime} {stime} {rest}"
class StallProbe(unittest.TestCase):
"""flare-edge #1528: a step that fails because warden-ui did not answer
carries one probe line saying why (host starving the VM, guest CPU
saturated, guest I/O wait, or an idle guest with a blocked UI)."""
def test_parsers(self):
st = qmp.parse_proc_stat(_proc_stat(5, 7, 2, running=3, blocked=1))
self.assertEqual(st, ([5, 0, 0, 7, 2, 0, 0, 0, 0, 0], 3, 1))
self.assertIsNone(qmp.parse_proc_stat("bridge: no such file: /proc/stat"))
procs = qmp.parse_procs(_pid_line(7, "warden ui) x", "R", 40, 2) + "\n"
+ _pid_line(9, "sh", "D", 1) + "\njunk\n")
self.assertEqual(procs, {7: ("warden ui) x", "R", 42), 9: ("sh", "D", 1)})
def test_verdicts(self):
self.assertIn("starves the VM", qmp.stall_verdict(0.3, (1.0, 0.0), 0, []))
self.assertIn("did not answer", qmp.stall_verdict(0.99, None, None, []))
self.assertIn("saturated", qmp.stall_verdict(0.99, (0.95, 0.0), 0, []))
self.assertIn("I/O", qmp.stall_verdict(0.99, (0.2, 0.5), 1, ["warden-ui"]))
self.assertIn("I/O", qmp.stall_verdict(None, (0.1, 0.0), 0, ["warden-ui"]))
self.assertIn("idle", qmp.stall_verdict(0.99, (0.05, 0.0), 0, []))
def test_cpu_delta_and_top(self):
a = qmp.parse_proc_stat(_proc_stat(100, 100))
b = qmp.parse_proc_stat(_proc_stat(190, 110))
busy, iowait = qmp.guest_cpu_delta(a, b)
self.assertAlmostEqual(busy, 0.9)
self.assertEqual(iowait, 0.0)
p0 = qmp.parse_procs(_pid_line(7, "warden-ui", "R", 10) + "\n" + _pid_line(8, "flared", "S", 5))
p1 = qmp.parse_procs(_pid_line(7, "warden-ui", "R", 80) + "\n" + _pid_line(8, "flared", "D", 25))
top, dstate = qmp.top_procs(p0, p1, 100)
self.assertEqual(top, ["warden-ui 70%", "flared 20%"])
self.assertEqual(dstate, ["flared"])
def _drive_no_reply(self, script):
class NoReplyCtl(FakeCtl):
samples = 0
def send(self, cmd):
if cmd == "@cat /proc/stat":
NoReplyCtl.samples += 1
n = NoReplyCtl.samples
return _proc_stat(100 * n, 10)
if cmd == "@procs":
n = NoReplyCtl.samples
return _pid_line(7, "warden-ui", "R", 95 * n) + "\n" + _pid_line(8, "sh", "S", 5 * n)
if cmd == "page":
raise RuntimeError("control channel: bridge: no reply from warden-ui "
"within 30 s: page")
return super().send(cmd)
def rpc_fn(sock, sock_file, obj):
if obj.get("execute") == "query-cpus-fast":
# No vCPU thread to sample here (test_vcpu_thread_ticks
# covers the sampling); the verdict then rests on the guest.
return []
return fake_rpc(sock, sock_file, obj)
saved = qmp.STALL_WINDOW_S
qmp.STALL_WINDOW_S = 0.05
try:
return run_script(script, ctl_cls=NoReplyCtl, rpc_fn=rpc_fn)
finally:
qmp.STALL_WINDOW_S = saved
def test_no_reply_steps_carry_a_bounded_probe(self):
rc, _by, rows = self._drive_no_reply("assert_page Demo/Rows\n" * 4 + "assert_stat fps lt 0\n")
self.assertEqual(rc, 1)
self.assertEqual([r["status"] for r in rows], ["fatal"] * 4 + ["fail"])
probed = [r["detail"] for r in rows if "stall probe" in r["detail"]]
self.assertEqual(len(probed), qmp.STALL_REPORTS_MAX, rows)
first = rows[0]["detail"]
self.assertTrue(first.startswith("control channel: bridge: no reply"), first)
self.assertIn("the guest CPU is saturated", first)
self.assertIn("top warden-ui 95%, sh 5%", first)
self.assertIn("vcpu n/a", first)
self.assertIn("guest busy 100% iowait 0%", first)
# A plain mismatch is not a stall and gets no probe.
self.assertNotIn("stall probe", rows[4]["detail"])
def test_vcpu_thread_ticks(self):
tid = threading.get_native_id()
before = qmp._thread_ticks([tid])
end = time.process_time() + 0.3
while time.process_time() < end:
pass
self.assertGreater(qmp._thread_ticks([tid]), before)
self.assertIsNone(qmp._thread_ticks([2 ** 22 + 12345]))
def test_unconsumed_input_is_a_stall(self):
self.assertTrue(qmp.is_stall(qmp.input_verdict(SimpleNamespace(), False)[1]))
self.assertTrue(qmp.is_stall("control channel: bridge: no reply from warden-ui within 30 s: hit"))
self.assertFalse(qmp.is_stall("obj moved: box=1,2,3x4"))
class TempDirs(unittest.TestCase):
# One test per kind of temp dir this module makes: a drive's out dir
# (run_script), a console dir and a QMP socket dir.
CHILD_TESTS = (
"DriveVerbs.test_shot_and_region_names_cannot_escape_outdir",
"ConsoleWatchTests.test_finds_a_marker_split_across_two_reads_and_caches_it",
"QmpSocketTimeout.test_main_bounds_a_wedged_qmp_peer_instead_of_hanging_forever",
)
@unittest.skipIf(os.environ.get("QMP_DRIVE_TEMP_CHILD"), "the child run itself")
def test_a_run_leaves_tmpdir_as_it_found_it(self):
fresh = tempfile.mkdtemp(prefix="fresh.", dir=os.path.dirname(_TMP_ROOT))
try:
env = dict(os.environ, TMPDIR=fresh, QMP_DRIVE_TEMP_CHILD="1")
child = subprocess.run(
[sys.executable, os.path.abspath(__file__), *self.CHILD_TESTS],
env=env, capture_output=True, text=True, timeout=120)
self.assertEqual(child.returncode, 0, child.stderr[-2000:])
self.assertIn(f"Ran {len(self.CHILD_TESTS)} tests", child.stderr)
self.assertEqual(os.listdir(fresh), [])
finally:
shutil.rmtree(fresh, ignore_errors=True)
if __name__ == "__main__":
unittest.main(verbosity=1)
+26 -14
View File
@@ -36,24 +36,35 @@
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" # qemu/tests/
QDIR="$(cd "$HERE/.." && pwd)" # qemu/
# shellcheck source=qemu/tests/ui-start.sh disable=SC1091
. "$HERE/ui-start.sh"
SEED_FILE=""
REFS_FILE=""
RS485_DEVICES=""
INIT_CHAIN=""
ARGS=()
while [ $# -gt 0 ]; do
case "$1" in
--seed) SEED_FILE="${2:?--seed needs a manifest path}"; shift 2 ;;
--refs) REFS_FILE="${2:?--refs needs a path}"; shift 2 ;;
--rs485-devices) RS485_DEVICES="${2:?--rs485-devices needs ADDR:SLUG[,...]}"; shift 2 ;;
--init-chain) INIT_CHAIN="${2:?--init-chain needs a directory}"; shift 2 ;;
--) shift; ARGS+=("$@"); break ;;
-*) echo "FATAL: unknown option '$1' (usage: $0 [--seed FILE] [--refs FILE] [--rs485-devices LIST] <zImage> <script> [out-dir])" >&2; exit 1 ;;
-*) echo "FATAL: unknown option '$1' (usage: $0 [--seed FILE] [--refs FILE] [--rs485-devices LIST] [--init-chain DIR] <zImage> <script> [out-dir])" >&2; exit 1 ;;
*) ARGS+=("$1"); shift ;;
esac
done
ZIMAGE="${ARGS[0]:-}"
SCRIPT="${ARGS[1]:-}"
OUTDIR="${ARGS[2]:-$QDIR/out/ui-drive}"
if [ -n "$INIT_CHAIN" ]; then
[ -d "$INIT_CHAIN" ] || { echo "FATAL: --init-chain '$INIT_CHAIN' is not a directory" >&2; exit 1; }
[ -f "$INIT_CHAIN/etc/init.d/S99lvgl" ] || {
echo "FATAL: --init-chain '$INIT_CHAIN' has no etc/init.d/S99lvgl: the UI would never start" >&2; exit 1; }
ROOTFS_OVERLAY="$(cd "$INIT_CHAIN" && pwd)"
export ROOTFS_OVERLAY
fi
if [ -z "$ZIMAGE" ] || [ ! -f "$ZIMAGE" ]; then
echo "FATAL: usage: $0 [--seed FILE] [--refs FILE] [--rs485-devices LIST] <zImage> <script> [out-dir]: the virt.fragment kernel variant" >&2
@@ -71,8 +82,16 @@ if [ -n "$SEED_FILE" ] && { [ -z "${FLARE_EDGE:-}" ] || [ ! -f "$FLARE_EDGE/tool
echo "FATAL: --seed needs FLARE_EDGE to point at a flare-edge checkout (seed-fixtures.py not found under '${FLARE_EDGE:-}')" >&2
exit 1
fi
[ -x "$QDIR/payload/warden-ui" ] || {
echo "FATAL: no qemu/payload/warden-ui: build it with flare-edge tools/build-ui-vm.sh" >&2
# --init-chain DIR
# boot the UI through the panel's shipped init scripts
# (flare-edge #2210): DIR is laid over the rootfs with
# mkimage.sh's ROOTFS_OVERLAY and the VM boots with
# warden.initchain, so stage-2 init starts /etc/init.d/S*
# instead of warden-ui directly. qmp.py's assert_ui_chain
# verb judges the result.
# PAYLOAD_DIR (mkimage.sh's Env note) picks another payload set for this run.
[ -x "${PAYLOAD_DIR:-$QDIR/payload}/warden-ui" ] || {
echo "FATAL: no warden-ui in ${PAYLOAD_DIR:-qemu/payload}: build it with flare-edge tools/build-ui-vm.sh" >&2
exit 1
}
command -v qemu-system-arm >/dev/null || {
@@ -171,6 +190,7 @@ for _attempt in 1 2 3; do
: > "$WORK/console.log"
bash "$QDIR/run.sh" --kernel "$ZIMAGE" --display headless --qmp "$WORK/qmp.sock" \
--ctl "$WORK/ctl.sock" ${RS485_DEVICES:+--rs485 "$WORK/rs.sock"} \
${INIT_CHAIN:+--append warden.initchain} \
--ssh-port "$PORT" --http-port $((PORT + 1)) --api-port $((PORT + 2)) \
> "$WORK/console.log" 2>&1 &
QEMU_PID=$!
@@ -234,17 +254,9 @@ if [ -n "$RS485_DEVICES" ]; then
fi
echo "== waiting for warden-ui"
deadline=$((SECONDS + 180))
while [ $SECONDS -lt $deadline ]; do
grep -aq 'init: starting warden-ui' "$WORK/console.log" && break
kill -0 "$QEMU_PID" 2>/dev/null || { echo "FATAL: VM exited early" >&2; tail -25 "$WORK/console.log" >&2; exit 1; }
sleep 2
done
grep -aq 'init: starting warden-ui' "$WORK/console.log" || {
echo "FATAL: warden-ui never started (no fb0? wrong kernel?)" >&2
tail -25 "$WORK/console.log" >&2
exit 1
}
# A chain boot reports the start through the chain, not the direct-start line
# (ui-start.sh, flare-edge#2295).
wait_ui_started "$WORK/console.log" "$QEMU_PID" 180 "$([ -n "$INIT_CHAIN" ] && echo 1 || echo 0)" || exit 1
# A started process is not a rendered frame. Poll screendumps until the panel
# stops being a single flat colour, on a bounded deadline: TCG renders CPU-bound
+3 -11
View File
@@ -13,6 +13,8 @@ set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" # qemu/tests/
QDIR="$(cd "$HERE/.." && pwd)" # qemu/
# shellcheck source=qemu/tests/ui-start.sh disable=SC1091
. "$HERE/ui-start.sh"
ZIMAGE="${1:-}"
OUTDIR="${2:-$QDIR/out}"
@@ -66,17 +68,7 @@ if [ -z "$QEMU_PID" ] || ! kill -0 "$QEMU_PID" 2>/dev/null; then
exit 1
fi
deadline=$((SECONDS + 120))
while [ $SECONDS -lt $deadline ]; do
grep -aq 'init: starting warden-ui' "$WORK/console.log" && break
kill -0 "$QEMU_PID" 2>/dev/null || { echo "FATAL: VM exited early" >&2; tail -25 "$WORK/console.log" >&2; exit 1; }
sleep 2
done
grep -aq 'init: starting warden-ui' "$WORK/console.log" || {
echo "FATAL: warden-ui never started (no fb0? wrong kernel?)" >&2
tail -25 "$WORK/console.log" >&2
exit 1
}
wait_ui_started "$WORK/console.log" "$QEMU_PID" 120 0 || exit 1
qmp() { python3 "$HERE/qmp.py" "$WORK/qmp.sock" "$@"; }
+152
View File
@@ -0,0 +1,152 @@
#!/usr/bin/env bash
# shellcheck disable=SC2016 # the single-quoted $ strings are literal patterns and child-shell args
# Host test for qemu/tests/ui-start.sh (flare-edge#2295): the console line
# ui-drive.sh and ui-shot.sh wait for before driving the UI. Offline, no VM.
#
# flare-edge job 99350 (the first "QEMU UI shipped init chain" run) booted
# the chain cleanly but ui-drive.sh waited 180 s for the direct-start line,
# which a warden.initchain boot never prints. This test pins:
# - every marker ui-start.sh waits for is printed by rootfs/sbin/init or
# rootfs/etc/warden-lib.sh, in the mode it is used for;
# - a chain-boot console (the 99350 lines) counts as started in chain
# mode, and a direct-start console in direct mode;
# - an empty chain and a failed S99lvgl fail at once, not at the deadline;
# - a dead VM and a silent console fail with their own messages;
# - ui-drive.sh and ui-shot.sh wait through ui-start.sh only, and
# ui-drive.sh passes chain mode exactly when --init-chain is given.
#
# bash ui-start-test.sh
set -uo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
INIT="$HERE/../rootfs/sbin/init"
LIB="$HERE/../rootfs/etc/warden-lib.sh"
WORK="$(mktemp -d "${TMPDIR:-/tmp}/warden-ui-start.XXXXXX")" || exit 1
VMPID=""
# shellcheck disable=SC2317 # called from the EXIT trap
cleanup() { [ -n "$VMPID" ] && kill "$VMPID" 2>/dev/null; rm -rf "$WORK"; }
trap cleanup EXIT
FAIL=0
CHECKS=0
check() { # check <label> <command...>
CHECKS=$((CHECKS + 1))
if "${@:2}"; then echo "[PASS] $1"; else echo "[FAIL] $1"; FAIL=1; fi
}
# shellcheck source=qemu/tests/ui-start.sh disable=SC1091
. "$HERE/ui-start.sh"
UI_START_POLL=0.1
export UI_START_POLL
# --- the markers are the ones init prints -----------------------------------
check "direct-start marker is echoed by sbin/init" \
grep -qF "echo \"$UI_START_DIRECT" "$INIT"
check "chain marker is echoed by sbin/init" \
grep -qF "echo \"$UI_START_CHAIN" "$INIT"
check "empty-chain marker is echoed by sbin/init" \
grep -qF "echo \"$UI_FAIL_CHAIN_EMPTY" "$INIT"
check "the chain marker is printed only on a chain boot" \
awk -v m="echo \"$UI_START_CHAIN" '
/^if \[ "\$initchain" = 1 \]; then/ { inchain = 1 }
inchain && /^fi$/ { inchain = 0 }
index($0, m) { found = 1; if (!inchain) bad = 1 }
END { exit !(found && !bad) }' "$INIT"
check "the direct-start marker is printed only on a direct boot" \
awk -v m="echo \"$UI_START_DIRECT" '
/^if \[ "\$initchain" = 0 \]/ { indirect = 1 }
indirect && /^fi$/ { indirect = 0 }
index($0, m) { found = 1; if (!indirect) bad = 1 }
END { exit !(found && !bad) }' "$INIT"
check "ui_start_marker picks the mode's marker" \
test "$(ui_start_marker 0)|$(ui_start_marker 1)" = "$UI_START_DIRECT|$UI_START_CHAIN"
# The S99lvgl failure line, from the real warden_init_chain with a failing stub.
D="$WORK/init.d"
mkdir -p "$D"
printf '#!/bin/sh\nexit 4\n' > "$D/S99lvgl"
chmod 0755 "$D/S99lvgl"
WARDEN_INITD="$D" sh -c '. "$1"; warden_init_chain 10 99' sh "$LIB" > /dev/null 2> "$WORK/lvgl-fail.err"
check "warden_init_chain prints the S99lvgl failure line ui-start.sh watches for" \
grep -qF "$UI_FAIL_CHAIN_LVGL rc=4" "$WORK/lvgl-fail.err"
# --- console fixtures -------------------------------------------------------
# Chain boot, as flare-edge job 99350 printed it.
cat > "$WORK/chain.log" <<'EOF'
WARDEN-QEMU-ROOTFS-OK slot=_a
init: shipped init chain (warden.initchain)
init: chain S03warden-accounts start
Creating platform accounts: OK
init: rig bus up on /run/warden/bus/bus.sock (broker pid 253)
init: starting warden-modbus
init: starting warden-flared
init: chain S99lvgl start
warden-ui: no backlight device
Starting Warden UI: OK
init: chain started 2 script(s)
init: control bridge on /dev/ttyS0
EOF
cat > "$WORK/direct.log" <<'EOF'
WARDEN-QEMU-ROOTFS-OK slot=_a
init: starting warden-modbus
init: starting warden-ui (fbdev)
EOF
cat > "$WORK/empty-chain.log" <<'EOF'
init: shipped init chain (warden.initchain)
init: starting warden-flared
WARDEN-QEMU-INITCHAIN-EMPTY: warden.initchain but no /etc/init.d/S* script; the UI is not started
EOF
{ head -n 8 "$WORK/chain.log"; cat "$WORK/lvgl-fail.err"; } > "$WORK/lvgl-fail.log"
: > "$WORK/silent.log"
sleep 60 &
VMPID=$!
run_wait() { # run_wait <log> <secs> <chain>: rc in $RC, stderr in $WORK/err, seconds in $TOOK
local t0=$SECONDS
wait_ui_started "$WORK/$1" "$VMPID" "$2" "$3" 2> "$WORK/err"
RC=$?
TOOK=$((SECONDS - t0))
}
run_wait chain.log 5 1
check "chain console counts as started in chain mode (flare-edge#2295)" test "$RC" = 0
run_wait chain.log 0 0
check "the same console is not a direct start (the 99350 failure)" test "$RC" = 1
check "a direct-mode timeout names the direct start" \
grep -qF "warden-ui never started" "$WORK/err"
run_wait direct.log 5 0
check "direct console counts as started in direct mode" test "$RC" = 0
run_wait direct.log 0 1
check "a direct console is not a chain start" test "$RC" = 1
check "a chain-mode timeout names the chain marker" \
grep -qF "the shipped init chain never reported its start" "$WORK/err"
run_wait empty-chain.log 30 1
check "an empty chain fails" test "$RC" = 1
check "an empty chain fails at once, not at the deadline" test "$TOOK" -lt 5
check "an empty chain says why" grep -qF "has no /etc/init.d/S* script" "$WORK/err"
run_wait lvgl-fail.log 30 1
check "a failed S99lvgl fails" test "$RC" = 1
check "a failed S99lvgl fails at once" test "$TOOK" -lt 5
check "a failed S99lvgl names its status" grep -qF "S99lvgl start FAILED rc=4" "$WORK/err"
run_wait silent.log 1 1
check "a silent console times out" test "$RC" = 1
kill "$VMPID" 2>/dev/null
wait "$VMPID" 2>/dev/null
run_wait silent.log 30 1
check "a dead VM fails at once with its own message" \
sh -c 'test "$1" = 1 && test "$2" -lt 5 && grep -qF "VM exited early" "$3"' sh "$RC" "$TOOK" "$WORK/err"
VMPID=""
# --- the drivers use it -----------------------------------------------------
for s in ui-drive.sh ui-shot.sh; do
check "$s sources ui-start.sh" grep -qF '. "$HERE/ui-start.sh"' "$HERE/$s"
check "$s waits through wait_ui_started" grep -q '^wait_ui_started ' "$HERE/$s"
done
check "no driver greps a UI start marker of its own" \
sh -c '! grep -lF "init: starting warden-ui" "$1"/*.sh | grep -v "/ui-start.sh$" | grep -v "/ui-start-test.sh$" | grep -q .' sh "$HERE"
check "ui-drive.sh waits in chain mode exactly when --init-chain is given" \
grep -qF 'wait_ui_started "$WORK/console.log" "$QEMU_PID" 180 "$([ -n "$INIT_CHAIN" ] && echo 1 || echo 0)"' "$HERE/ui-drive.sh"
echo "ui-start: $CHECKS checks, $([ "$FAIL" = 0 ] && echo OK || echo FAILED)"
exit "$FAIL"
+61
View File
@@ -0,0 +1,61 @@
# shellcheck shell=bash
# Sourced by ui-drive.sh and ui-shot.sh: wait for stage-2 init to report the
# UI started, from the VM console log.
#
# The console line depends on how the UI is started (rootfs/sbin/init):
# direct start (default) "init: starting warden-ui (fbdev)"
# shipped chain (warden.initchain, ui-drive.sh --init-chain)
# "init: chain started N script(s)", after
# the panel's S99lvgl ran; the direct start
# line is never printed (flare-edge#2295)
# A chain boot that cannot start the UI says so at once, so these fail fast
# instead of spending the whole deadline:
# "WARDEN-QEMU-INITCHAIN-EMPTY" no /etc/init.d/S* script at all
# "init: chain S99lvgl start FAILED rc=N" the UI's own script failed
# qemu/tests/ui-start-test.sh checks every marker here against sbin/init.
UI_START_DIRECT='init: starting warden-ui'
UI_START_CHAIN='init: chain started '
UI_FAIL_CHAIN_EMPTY='WARDEN-QEMU-INITCHAIN-EMPTY'
UI_FAIL_CHAIN_LVGL='init: chain S99lvgl start FAILED'
# ui_start_marker <initchain 0|1>: the console line that means "UI started".
ui_start_marker() {
if [ "${1:-0}" = 1 ]; then printf '%s' "$UI_START_CHAIN"; else printf '%s' "$UI_START_DIRECT"; fi
}
# wait_ui_started <console.log> <qemu pid> <seconds> <initchain 0|1>
# Returns 0 once the UI is reported started; prints a FATAL line and the
# console tail to stderr and returns 1 on a VM exit, a chain failure or the
# deadline.
wait_ui_started() {
local log="$1" pid="$2" secs="$3" chain="${4:-0}" marker deadline
marker="$(ui_start_marker "$chain")"
deadline=$((SECONDS + secs))
while :; do
grep -aqF "$marker" "$log" && return 0
if [ "$chain" = 1 ]; then
if grep -aqF "$UI_FAIL_CHAIN_EMPTY" "$log"; then
echo "FATAL: the init chain has no /etc/init.d/S* script, so warden-ui is not started" >&2
tail -25 "$log" >&2
return 1
fi
if grep -aqF "$UI_FAIL_CHAIN_LVGL" "$log"; then
echo "FATAL: S99lvgl failed in the shipped init chain: $(grep -aF "$UI_FAIL_CHAIN_LVGL" "$log" | head -1)" >&2
tail -25 "$log" >&2
return 1
fi
fi
kill -0 "$pid" 2>/dev/null || { echo "FATAL: VM exited early" >&2; tail -25 "$log" >&2; return 1; }
[ $SECONDS -lt $deadline ] || break
sleep "${UI_START_POLL:-2}"
done
grep -aqF "$marker" "$log" && return 0
if [ "$chain" = 1 ]; then
echo "FATAL: the shipped init chain never reported its start ('$marker' not on the console)" >&2
else
echo "FATAL: warden-ui never started (no fb0? wrong kernel?)" >&2
fi
tail -25 "$log" >&2
return 1
}
@@ -0,0 +1,120 @@
#!/usr/bin/env bash
# Regression tests for build/fetch-kernel-tarball.sh (#1588).
#
# Runs the real script, copied into a fixture dir so its own HERE-relative pin
# lookup finds a pin we control, with a fake curl first on PATH: no network,
# and the outcome of each fetch is exact. Covers:
# - curl is bounded (connect timeout, stall abort, total cap), so a server
# that answers and then stalls cannot hold the job until its timeout;
# - a failed fetch leaves no partial tarball behind, so the next run fetches
# again instead of taking the partial file as present;
# - a good fetch is verified and kept; a present, matching tarball is reused.
set -uo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
SCRIPT="$HERE/../../build/fetch-kernel-tarball.sh"
[ -f "$SCRIPT" ] || { echo "FAIL: script not found at $SCRIPT"; exit 1; }
KVER="$(sed -n 's/^KVER=//p' "$SCRIPT")"
[ -n "$KVER" ] || { echo "FAIL: no KVER in $SCRIPT"; exit 1; }
FAIL=0
ok() { printf '[PASS] %s\n' "$1"; }
bad() { printf '[FAIL] %s\n' "$1"; FAIL=1; }
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT
setup() { # setup <case-name> -> prints the fixture dir
local dir="$TMP/$1"
mkdir -p "$dir/bin"
cp "$SCRIPT" "$dir/fetch-kernel-tarball.sh"
printf 'good-bytes' | sha256sum | awk '{print $1}' \
> "$dir/linux-$KVER.tar.xz.sha256"
printf '%s' "$dir"
}
# fake_curl <dir> <mode>: records its argv in <dir>/argv and its call count in
# <dir>/count. Modes: good (writes the pinned bytes), partial (writes a few
# bytes, then fails the way curl does on a timeout), never (must not run).
fake_curl() {
local dir="$1" mode="$2"
# These single-quoted lines are the literal source of the fake program.
# shellcheck disable=SC2016
printf '%s\n' '#!/bin/sh' \
'dir=$(dirname "$(dirname "$0")")' \
'printf "%s\n" "$*" > "$dir/argv"' \
'echo x >> "$dir/count"' \
'out=' \
'while [ "$#" -gt 0 ]; do' \
' if [ "$1" = "-o" ]; then shift; out="$1"; fi' \
' shift' \
'done' \
'[ -n "$out" ] || exit 2' \
"case $mode in" \
' good) printf good-bytes > "$out" ;;' \
' partial) printf good > "$out"; exit 28 ;;' \
' *) echo "curl should not have run" >&2; exit 1 ;;' \
'esac' > "$dir/bin/curl"
chmod +x "$dir/bin/curl"
}
run() { # run <dir> <dest> -> output in $OUT, status in $RC
local dir="$1" dest="$2"
OUT="$(PATH="$dir/bin:$PATH" bash "$dir/fetch-kernel-tarball.sh" "$dest" 2>&1)"
RC=$?
}
# --- case A: a good fetch is bounded, verified and kept ---------------------
dir="$(setup case-a)"
fake_curl "$dir" good
run "$dir" "$dir/linux.tar.xz"
if [ "$RC" -eq 0 ] && [ -f "$dir/linux.tar.xz" ] \
&& printf '%s' "$OUT" | grep -q 'tarball sha256 verified'; then
ok "good fetch: verified and kept"
else
bad "good fetch: verified and kept (rc=$RC, out=$OUT)"
fi
for flag in --connect-timeout --speed-limit --speed-time --max-time; do
if grep -q -- "$flag" "$dir/argv"; then
ok "curl carries $flag"
else
bad "curl carries $flag (argv: $(cat "$dir/argv"))"
fi
done
if ls "$dir"/linux.tar.xz.download.* >/dev/null 2>&1; then
bad "good fetch: no download temp file left"
else
ok "good fetch: no download temp file left"
fi
# --- case B: a failed fetch leaves nothing, and the next run fetches again --
dir="$(setup case-b)"
fake_curl "$dir" partial
run "$dir" "$dir/linux.tar.xz"
if [ "$RC" -ne 0 ] && [ ! -e "$dir/linux.tar.xz" ] \
&& ! ls "$dir"/linux.tar.xz.download.* >/dev/null 2>&1; then
ok "failed fetch: no partial tarball left"
else
bad "failed fetch: no partial tarball left (rc=$RC, files: $(ls "$dir"))"
fi
fake_curl "$dir" good
run "$dir" "$dir/linux.tar.xz"
if [ "$RC" -eq 0 ] && [ "$(wc -l < "$dir/count")" -eq 2 ]; then
ok "run after a failed fetch downloads again and passes"
else
bad "run after a failed fetch downloads again and passes (rc=$RC, out=$OUT)"
fi
# --- case C: a present, matching tarball is reused without curl -------------
dir="$(setup case-c)"
printf 'good-bytes' > "$dir/linux.tar.xz"
fake_curl "$dir" never
run "$dir" "$dir/linux.tar.xz"
if [ "$RC" -eq 0 ] && [ ! -e "$dir/count" ]; then
ok "present tarball: reused, curl never invoked"
else
bad "present tarball: reused, curl never invoked (rc=$RC, out=$OUT)"
fi
[ "$FAIL" -eq 0 ] && echo "fetch-kernel-tarball tests passed"
exit "$FAIL"