From a41abe366a5dab676a322264690d0ba7e1e738d8 Mon Sep 17 00:00:00 2001 From: TIKOCI RouterOS Bots Date: Wed, 2 Dec 2026 05:12:02 -0800 Subject: [PATCH 1/3] =?UTF-8?q?feat(qemu):=20pause()=20and=20in-place=20re?= =?UTF-8?q?set()=20=E2=80=94=20paused=20marker,=20CLI=20verbs=20(#375)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - chr.pause() / quickchr pause: monitor `stop` under the machine lock; NICs keep carrier, the guest clock stops. Idempotent; sets a new `paused` marker (never `frozen`). - chr.reset() / quickchr reset [--no-wait] [-T]: monitor `system_reset` in place (same QEMU PID and sockets), REST-ready by default. A paused or frozen guest is resumed by the reset and both markers are cleared. - continue() clears `paused` as well as `frozen`; stop/clean/relaunch/status refresh clear it with the pid. - rest()/exec()/qga() fail fast with the new MACHINE_PAUSED code; shutdown() of a paused guest power-cuts at once and reports `forced`. - list/get show `(paused)`, a `Paused:` detail line and `paused` in --json; help, completions, MANUAL, DESIGN, qemu.instructions, CHANGELOG. Co-Authored-By: Claude Opus 5.5 --- .github/instructions/qemu.instructions.md | 23 ++ CHANGELOG.md | 12 + DESIGN.md | 31 ++- MANUAL.md | 82 ++++++- project-words.txt | 3 + src/cli/index.ts | 98 +++++++- src/index.ts | 1 + src/lib/completions.ts | 22 +- src/lib/lock.ts | 2 + src/lib/quickchr.ts | 123 ++++++++-- src/lib/state.ts | 6 +- src/lib/types.ts | 27 +++ test/integration/pause-reset.test.ts | 158 ++++++++++++ test/unit/cli-help-guard.test.ts | 2 +- test/unit/cli-pause-reset.test.ts | 184 ++++++++++++++ test/unit/completions.test.ts | 2 +- test/unit/pause-reset.test.ts | 283 ++++++++++++++++++++++ 17 files changed, 1018 insertions(+), 41 deletions(-) create mode 100644 test/integration/pause-reset.test.ts create mode 100644 test/unit/cli-pause-reset.test.ts create mode 100644 test/unit/pause-reset.test.ts diff --git a/.github/instructions/qemu.instructions.md b/.github/instructions/qemu.instructions.md index a73529d2..bef6fc27 100644 --- a/.github/instructions/qemu.instructions.md +++ b/.github/instructions/qemu.instructions.md @@ -158,6 +158,29 @@ accepted. A successful `set_link` answers with nothing; an unknown id answers `Error: Device '' not found` (QEMU 11.1.2, 7.25.2, `test/integration/link-state.test.ts`). quickchr exposes it by port name as `link()` / `set --link` (#334). +### Pausing a guest: monitor `stop` keeps carrier, stops the clock, backs up the peer + +HMP `stop` holds the vCPUs; QEMU, its monitor and QGA, and every NIC's carrier stay up, +so a link peer sees a hung box, not a cable pull. Grounded on Linux/KVM, RouterOS +7.25.2, QEMU 11.1.2 (#364); quickchr exposes it as `pause()` / `quickchr pause` (#375). + +- **The guest clock stops with it.** Uptime excludes the pause and the guest clock + falls behind by its length (51 s after a 50 s pause) until NTP corrects it. No + RouterOS watchdog reboot at 20, 50 or 60 s. +- **SIGSTOP of QEMU is a different fault.** Guest time jumps forward on SIGCONT, and + with RouterOS's default `/system/watchdog watchdog-timer=yes` a 20 s SIGSTOP rebooted + RouterOS (`kernel failure in previous boot`); 5 s did not, nor did 20 s with + `watchdog-timer=no`. SIGSTOP also freezes the monitor and QGA. +- **Backpressure reaches the peer on both socket transports.** The peer's NIC toward + the paused VM stops transmitting once the socket buffer fills: about 100 frames on + `dgram` (unix datagram), about 2 MB on `listen-connect` (TCP). The peer's guest then + drops at its queue (`tx-queue-drop`). Its monitor (~2 ms), QGA and other links keep + working. After `cont` the backlog (328 frames on dgram, 1574 on TCP in the probe) + arrives within 0.6 s. +- **`system_reset` keeps the process and its sockets.** Same PID, every socket link + kept, RouterOS ready again in 12–23 s on KVM. A reset of a held guest (`stop`, or + `-S`) leaves it in `paused (prelaunch)`; `cont` boots it. + ### `filter-dump`: a pcap of one NIC, from QEMU `-object filter-dump,id=,netdev=net,file=[,maxlen=…][,queue=…][,status=on|off]` diff --git a/CHANGELOG.md b/CHANGELOG.md index 8909f918..3b538bbb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,18 @@ odd/even-minor scheme chose the tag; it was retired in 0.5.1.) ### Added +- Pause and in-place reset (#375): `chr.pause()` / `quickchr pause ` holds the + guest (QEMU monitor `stop`) while QEMU, its sockets and every NIC's carrier stay up — + a hung switch, not a pulled cable. The guest clock stops too, so RouterOS never sees + the hang. `continue()` / `quickchr continue` resumes it. A new `paused` marker in + machine state (not `frozen`) shows in `list` (`(paused)`), the detail view and + `--json`, and is cleared by `continue`, `reset` and `stop`. While it is set, + `rest()`, `exec()` and `qga()` fail at once with the new `MACHINE_PAUSED` code, and + `shutdown` power-cuts immediately. `chr.reset()` / `quickchr reset + [--no-wait] [-T ]` is an in-place power cycle (`system_reset`): same QEMU PID and + sockets, RouterOS cold-boots, REST-ready by default; a paused or frozen guest is + resumed by it. + - One-way drop on a NIC that keeps carrier (#369): `chr.fault("ether3", { drop: "egress" | "ingress" | "both" })`, `null` to clear (and a batch form), and `quickchr set --fault etherN=egress|ingress|both|none`. Every frame in that direction is diff --git a/DESIGN.md b/DESIGN.md index 23e32c62..d2c4af70 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -144,7 +144,7 @@ A **receive slot** is a per-machine named port for traffic the guest sends to th - **Separate from forwards.** Stored as `MachineState.receivePorts`, never in `ports`/`extraPorts`: `buildHostfwdString` would otherwise emit a `hostfwd` for it, and `PortMapping.guest` has no meaning. Because there is no QEMU side, a slot can be added or removed on a running machine (contrast #141). - **Not in the block, for now.** Ports are explicit or registry defaults (`WELL_KNOWN_RECEIVE_PORTS`, kept apart from `WELL_KNOWN_GUEST_PORTS` so `--forward tzsp` cannot mean the wrong direction). The block has no spare offset (auto extras take `+6+i`; Windows IPC takes +6..+8), and receive slots will **not** draw from the extras pool (decided on #57): with one to four extra slots per block, they would mostly spill into a second block. Registry defaults below 1024 are replaced by an unprivileged stand-in (syslog → 5514) so a listener needs no root; `snmp-trap` is absent because RouterOS has no trap-port setting. - **Collisions** are checked against every machine's port block (whole block, so Windows IPC at +6..+8 is covered), forwards and receive ports, and against in-flight creations: the lock reservation carries the resolved forward hosts and receive ports. Reservations are read **before** `machine.json` — a creation saves before it releases its reservation, so it cannot be missed in both — and `saveMachine()` writes a uniquely named, exclusively created temp file and renames it, so a reader never sees a truncated file; the replacement keeps the old file's mode (and owner, when root saves), and a failed write or rename removes the temp file (a Windows rename refused by a scanner holding the file is retried by `renameWithRetry` for ~1.6 s, then the save fails with `STATE_ERROR` and leaves the old file — never an in-place write, which could publish a partial record the allocator would skip). An explicit `portBase` is checked offset by offset (all ten) against held ports. Blocks ruled out by a reservation do not count against the allocator's 20 live probes. The allocator also checks where auto extras land (`+6+i`, so a fifth is past the block) against reservations. Explicit forwards are checked against other machines' whole blocks. The block allocator skips a block containing any reserved port, mapped or not; an explicit `portBase` or fixed forward that clashes is a `PORT_CONFLICT`. A clash names the next free port. A change (removals + additions) is validated and saved once, under the machine lock then the allocation lock — creation takes them in the other order but never waits on an existing machine's lock, so this cannot deadlock. The change re-reads `machine.json` after the allocation-lock wait and replaces only `receivePorts`; `license()` runs entirely under the machine lock (renew, verification and record), so neither overwrites the other and a `clean` cannot reset the disk between the guest's verification and the record. Because a save can now fail (`STATE_ERROR`), the first save after a spawn stops the new QEMU on failure (`saveSpawnedState()`), and a status refresh treats its save as best effort. -- **Status refreshes patch, not rewrite.** `list`/`get` marking a dead QEMU stopped take the machine lock fail-fast, re-read `machine.json` and change only `status`/`pid`/`frozen` (`markMachineStopped()`); if another operation holds the lock they skip the write (the holder saves its own state). In turn `acquireLockNow` waits up to 2 s for a `status` holder instead of failing a `start` that races a `list`. So they cannot write back a stale record over a receive change. `set --qemu-arg` still rewrites the whole record without the lock (stopped machines only; pre-existing). +- **Status refreshes patch, not rewrite.** `list`/`get` marking a dead QEMU stopped take the machine lock fail-fast, re-read `machine.json` and change only `status`/`pid`/`frozen`/`paused` (`markMachineStopped()`); if another operation holds the lock they skip the write (the holder saves its own state). In turn `acquireLockNow` waits up to 2 s for a `status` holder instead of failing a `start` that races a `list`. So they cannot write back a stale record over a receive change. `set --qemu-arg` still rewrites the whole record without the lock (stopped machines only; pre-existing). Current consumers are all first-party tikoci projects (centrs, donny, restraml), so a port-scheme migration can be coordinated across them — but `@tikoci/quickchr` is published and public, so a change to the persisted port contract still needs an issue, a CHANGELOG/docs note, and (for the `ChrInstance`/`StartOptions` surface) a deprecation/migration path, not a silent break. @@ -1560,6 +1560,35 @@ is `MACHINE_STOPPED`; a wait that never reaches REST is a genuine and no `savevm` refusal on prelaunch VMs (snapshot is already tricky business; QEMU accepts or errors on its own). +## Pause and in-place reset (#375) + +Two in-process faults for lab topologies, researched in #364: a guest that hangs +while its NICs keep carrier (a hung switch), and a power cycle that keeps QEMU. + +- **`pause()` is monitor `stop`, not SIGSTOP.** `stop` freezes the guest clock, so + RouterOS never sees the hang and its watchdog cannot reboot it; the monitor and + QGA keep answering; and it works the same on Windows. SIGSTOP is a different + fault (a hang the watchdog ends with a reboot) and is not offered. +- **`paused` is its own marker, not `frozen`.** `frozen` means QEMU was launched + with `-S` and a gdbstub and the guest never booted; `paused` means a booted guest + was held. Both are live markers cleared with the pid (`finalizeStoppedState()`, + `markMachineStopped()`, `clean()`, a relaunch). `status` stays `"running"`, as for + `frozen`, so every running-machine check works unchanged. `continue()` clears both. +- **Guest requests fail fast on a paused machine.** `rest()`, `exec()` (every + transport) and `qga()` throw `MACHINE_PAUSED` instead of waiting out their own + timeout, reading the marker from disk so a handle made before a `quickchr pause` + in another process sees it. `shutdown()` power-cuts at once and reports `forced`: + the guest cannot act on `/system/shutdown`. The alternative — documenting the + wait — would make every `exec` against a hung switch in a test cost its timeout. +- **`reset()` is `system_reset` on that machine only.** QEMU, its PID and its sockets + stay up, so no link is re-established. It never touches far-end carrier: a lab + that wants the neighbor to see a cable drop calls `link()` on the peers, as + `examples/mlag`'s power-cut step does. **A reset always ends with RouterOS + booting**: QEMU leaves a held guest in `paused (prelaunch)` after `system_reset`, + so `reset()` resumes it and clears both markers. The other choice (reset but stay + held) has no use a `pause()` after the reset doesn't cover, and would make + `reset()`'s REST wait impossible to keep. + ## Managed macOS networks (#256, decided 2026-11-11) **Root lives in the network, once; machines stay unprivileged.** Every vmnet mode diff --git a/MANUAL.md b/MANUAL.md index b86bc39e..9e2219cb 100644 --- a/MANUAL.md +++ b/MANUAL.md @@ -342,11 +342,11 @@ quickchr start beep-lab --version 7.25 --arch x86 \ #### `continue [--no-wait] [--timeout-extra ]` -Resume a machine started with `start --frozen` (held at reset with a -gdbstub). Sends one monitor `cont`, then waits for RouterOS to become +Resume a machine paused with `pause`, or started with `start --frozen` (held +at reset with a gdbstub). Clears both markers. Sends one monitor `cont`, then waits for RouterOS to become ready — the same promise `start` makes. `--no-wait` returns right after resuming; `--timeout-extra`/`-T` extends the resume timeout like `start`. Idempotent: when the guest is already running (e.g. gdb -continued it), this just clears the frozen marker. A machine that never +continued it), this just clears the marker. A machine that never reaches readiness is a `BOOT_TIMEOUT`; it is stopped and preserved. A machine with no `user` NIC has no REST forward to wait on, so a waiting `continue` is refused (`INVALID_NETWORK`) before it resumes anything; use @@ -371,6 +371,71 @@ Note the vocabulary overlap: this `frozen` (QEMU held at reset) is a different domain from QGA `fsfreeze-status` (guest filesystems frozen for snapshots). +#### `pause ` + +Pause a running guest in place (QEMU monitor `stop`) and mark it `paused`. QEMU, +its sockets and every NIC's carrier stay up, so a link peer sees a hung box, not a +pulled cable — the hung-switch fault. Resume with `continue`, which waits for REST +like it does after `--frozen` (a paused guest answers within a moment of resuming). +Pausing a paused guest only sets the marker. + +`paused` is not `frozen`: a frozen guest never booted and its QEMU carries `-S` +and a gdbstub; a paused guest was running RouterOS. `status` stays `running`; +`list` marks it `(paused)`, the detail view adds a `Paused:` line, and +`list --json` carries `paused`. `stop` and `reset` work on a paused machine and +clear the marker. While it is set, guest requests — `exec`, `qga`, and `rest()` / +`exec()` / `qga()` in the library — fail at once with `MACHINE_PAUSED` instead of +waiting out their timeout, and `shutdown` power-cuts immediately (the guest cannot +act on `/system/shutdown`) and reports `forced`. + +What a paused guest and its peers see (grounded on Linux/KVM, RouterOS 7.25.2, +QEMU 11.1.2, #364; macOS/HVF in #375): + +- **The guest clock stops too.** Uptime excludes the pause, and the guest's + clock falls behind by its length (51 s after a 50 s pause) until NTP corrects + it. RouterOS never sees the hang: no watchdog reboot at 20, 50 or 60 s. +- **A real hang does not stop the clock.** SIGSTOP of the QEMU process stands in + for one, and with RouterOS's default `/system/watchdog watchdog-timer=yes`, a + 20 s SIGSTOP made RouterOS reboot on resume (`kernel failure in previous boot`); + 5 s did not. `pause` never triggers this. (SIGSTOP also freezes the monitor and + QGA, and Windows has no equivalent; quickchr does not offer it.) +- **Backpressure onto the peer.** On `dgram` and `listen-connect` links, the + peer's NIC toward the paused machine stops transmitting once the socket buffer + fills — about 100 frames on `dgram`, about 2 MB on `listen-connect` (TCP) — and + the peer's guest then drops at its queue (`tx-queue-drop`). Everything else on + the peer (its other links, monitor, QGA) keeps working. After `continue` the + backlog arrives within about 0.6 s and the link works again. + +```sh +quickchr pause sw1 # sw1 hangs; its neighbors keep carrier +sleep 20 +quickchr continue sw1 # REST-ready again +``` + +#### `reset [--no-wait] [--timeout-extra ]` + +In-place power cycle (QEMU monitor `system_reset`): the same QEMU process, PID and +sockets stay up and RouterOS cold-boots, so nothing is respawned and no socket +link is re-established. Waits for RouterOS to become ready again, like +`continue`; `--no-wait` returns right after the reset, and `--timeout-extra`/`-T` +extends the wait. A machine with no `user` NIC needs `--no-wait` +(`INVALID_NETWORK`), as for `continue`. + +A reset always ends with RouterOS booting: a paused or frozen guest is reset, +then resumed (QEMU leaves a held guest in `paused (prelaunch)` after +`system_reset`), and both markers are cleared. RAM state goes with the reboot; +the disk is untouched. + +The far end of each link keeps carrier through the reset; quickchr does not drop +it. To make a neighbor see the power cut as a cable drop, bracket the reset with +`set --link` on the peers, as `examples/mlag`'s power-cut step does: + +```sh +quickchr set sw2 --link ether2=down +quickchr reset sw1 +quickchr set sw2 --link ether2=up +``` + #### `stop [name | --all]` Power cut: sends SIGTERM to QEMU, waits up to 5 seconds, then SIGKILL if @@ -1048,7 +1113,7 @@ suggesting a kill (#294). |---|---|---| | Identity | `name`, `state`, `ports`, `restUrl`, `sshPort`, `portBase` | Static metadata persisted in `machine.json` | | Capture | `captureInterface`, `hostGatewayIp` | Platform-correct values for TZSP capture (`tshark -i …`) and the guest→host address any UDP emitter targets | -| Lifecycle | `waitForBoot()`, `waitFor(fn, ms?)`, `stop()`, `shutdown(opts?)`, `continue(opts?)`, `remove()`, `clean()`, `destroy()` | Boot readiness, custom polling, power-cut or guest-shutdown teardown, frozen resume | +| Lifecycle | `waitForBoot()`, `waitFor(fn, ms?)`, `stop()`, `shutdown(opts?)`, `continue(opts?)`, `pause()`, `reset(opts?)`, `remove()`, `clean()`, `destroy()` | Boot readiness, custom polling, power-cut or guest-shutdown teardown, pause/resume, in-place power cycle | | Comms | `rest()`, `exec()`, `monitor()`, `serial()`, `qga()` | REST, RouterOS CLI, QEMU monitor, serial console, QGA (x86 only) | | Provisioning | `license()`, `setDeviceMode()`, `availablePackages()`, `installPackage()` | Post-boot configuration | | Files | `upload()`, `download()` | SCP transfer to/from the CHR | @@ -1070,7 +1135,9 @@ interface ChrInstance { waitFor(condition: () => Promise, timeoutMs?: number): Promise; stop(): Promise; // power cut: SIGTERM, then SIGKILL shutdown(opts?: ShutdownOptions): Promise; // /system/shutdown, bounded fallback - continue(opts?: ContinueOptions): Promise; // resume a frozen start, REST-ready by default + continue(opts?: ContinueOptions): Promise; // resume a paused or frozen guest, REST-ready by default + pause(): Promise; // monitor `stop`: guest held, NICs keep carrier; sets state.paused + reset(opts?: ResetOptions): Promise; // monitor `system_reset`: same QEMU/PID, RouterOS cold-boots remove(): Promise; clean(): Promise; destroy(): Promise; // stop + remove @@ -1510,8 +1577,8 @@ reaches REST and SSH through the `user` NIC's port forwards, so a `start` that would wait for the boot refuses a machine without one (`INVALID_NETWORK`, before anything is downloaded or spawned). Pass `--no-wait` or `--fg` to boot such a machine anyway. Provisioning always needs the `user` NIC -(`NETWORK_UNAVAILABLE`, also before the download). Likewise `continue` on a -frozen machine without one needs `--no-wait`. +(`NETWORK_UNAVAILABLE`, also before the download). Likewise `continue` or +`reset` on a machine without one needs `--no-wait`. ### Which mechanism? (by traffic shape) @@ -2538,6 +2605,7 @@ present, then exits `1`. | `MACHINE_EXISTS` | name already in `machines/` | choose another name or `QuickCHR.get(name)` | | `MACHINE_NOT_FOUND` | name not in `machines/`, or a booted machine's disk file is missing | `quickchr list`; for a missing disk, restore it or `quickchr clean ` | | `MACHINE_RUNNING` / `MACHINE_STOPPED` | wrong lifecycle state | `start` or `stop` first | +| `MACHINE_PAUSED` | `exec`/`qga` (library: `rest()`/`exec()`/`qga()`) on a machine `pause` paused | `quickchr continue ` first | | `PERMISSION_DENIED` | `stop`/`shutdown`/`remove`/`clean`/`set --device-mode` (library: also `destroy()`) on a machine whose QEMU another user owns (e.g. started with `sudo quickchr start`); `list` shows it as `(other user)` | run the command as that user, pinned to the same data dir (`sudo` may reset `HOME`): `sudo env QUICKCHR_DATA_DIR= quickchr stop `. The error's hint prints that command for the refused operation; if your original command asked for more (say `set --device-mode … --package …`), rerun all of it that way | | `MACHINE_LOCKED` | another operation holds the machine (the message names it, its pid and age) | wait for it; a `foreground` holder must be quit from its console | | `EXEC_FAILED` | RouterOS rejected the command (auth, syntax) | check creds, command syntax | diff --git a/project-words.txt b/project-words.txt index 505953d9..438af893 100644 --- a/project-words.txt +++ b/project-words.txt @@ -41,6 +41,7 @@ autoselect awk backgrounded backoff +backpressure bak basicauth bavail @@ -518,9 +519,11 @@ shellcheck shopt siaddr sidegrade +sigcont sigill signalable sigsegv +sigstop skyfi slirp smccc diff --git a/src/cli/index.ts b/src/cli/index.ts index 6af0f6e7..ee64fdf9 100755 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -422,6 +422,12 @@ async function main() { case "continue": await cmdContinue(args.slice(1)); break; + case "pause": + await cmdPause(args.slice(1)); + break; + case "reset": + await cmdReset(args.slice(1)); + break; case "stop": await cmdStop(args.slice(1)); break; @@ -1744,6 +1750,47 @@ export async function cmdContinue(argv: string[]) { console.log(` SSH: ${formatSshCommand(creds.user, instance.sshPort)}`); } +export async function cmdPause(argv: string[]) { + const { flags, positional } = parseFlags(argv); + if (unknownFlags(flags, []).length) throw new QuickCHRError("INVALID_ARGUMENT", "pause accepts only "); + const name = positional[0]; + if (!name || positional.length !== 1) throw new QuickCHRError("INVALID_ARGUMENT", "Usage: quickchr pause "); + const { QuickCHR } = await import("../lib/quickchr.ts"); + const { machineNotFoundMessage, statusIcon, bold } = await import("./format.ts"); + const instance = QuickCHR.get(name); + if (!instance) { + console.error(machineNotFoundMessage(name)); + process.exit(1); + } + await instance.pause(); + console.log(`${statusIcon("running")} ${bold(name)} paused — NICs keep carrier; resume with ${bold(`quickchr continue ${name}`)}`); +} + +export async function cmdReset(argv: string[]) { + const { flags, positional } = parseFlags(argv); + applyTimeoutExtraShortFlag(argv, flags, positional); + const invalid = unknownFlags(flags, ["wait", "timeout-extra"]); + if (invalid.length) throw new QuickCHRError("INVALID_ARGUMENT", "reset accepts only , --no-wait and --timeout-extra "); + const name = positional[0]; + if (!name || positional.length !== 1) throw new QuickCHRError("INVALID_ARGUMENT", "Usage: quickchr reset [--no-wait] [--timeout-extra ]"); + const { QuickCHR } = await import("../lib/quickchr.ts"); + const { machineNotFoundMessage, statusIcon, bold } = await import("./format.ts"); + const instance = QuickCHR.get(name); + if (!instance) { + console.error(machineNotFoundMessage(name)); + process.exit(1); + } + const wait = flags.wait !== false; + const timeoutExtra = await resolveTimeoutExtraMs(flags); + await instance.reset({ wait, timeoutExtra }); + if (!wait) { + console.log(`${statusIcon("running")} ${bold(name)} reset — RouterOS is booting (--no-wait)`); + printReadinessTip(name, instance.state.version); + return; + } + console.log(`${statusIcon("running")} ${bold(name)} reset — RouterOS booted again (same QEMU, PID ${instance.state.pid})`); +} + async function cmdShutdown(argv: string[]) { const { flags, positional } = parseFlags(argv); const invalid = unknownFlags(flags, ["timeout"]); @@ -1867,6 +1914,7 @@ async function cmdList(argv: string[] = []) { pid: s.pid ?? null, foreign, frozen: s.frozen ?? false, + paused: s.paused ?? false, qemuArgs: s.qemuArgs ?? [], packages: s.packages, machineDir: s.machineDir, @@ -1891,6 +1939,7 @@ async function cmdList(argv: string[] = []) { console.log(` Frozen: yes — awaiting quickchr continue`); console.log(` GDB: ${dim(join(s.machineDir, "gdb.sock"))}`); } + if (s.paused) console.log(` Paused: yes — NICs keep carrier; resume with quickchr continue`); console.log(` Created: ${new Date(s.createdAt).toLocaleString()}`); if (s.lastStartedAt) console.log(` Started: ${new Date(s.lastStartedAt).toLocaleString()}`); if (s.packages.length > 0) console.log(` Packages: ${s.packages.join(", ")}`); @@ -1900,7 +1949,7 @@ async function cmdList(argv: string[] = []) { if (s.status === "running") { const creds = await resolveDisplayCredentials(s); console.log(); - if (s.frozen) console.log(` ${dim(`(endpoints answer after 'quickchr continue ${s.name}')`)}`); + if (s.frozen || s.paused) console.log(` ${dim(`(endpoints answer after 'quickchr continue ${s.name}')`)}`); console.log(` REST: ${link(formatRestUrl(instance.ports.http, creds.user, creds.password))}`); console.log(` WinBox: 127.0.0.1:${instance.ports.winbox}`); console.log(` SSH: ${formatSshCommand(creds.user, instance.sshPort)}`); @@ -1947,7 +1996,7 @@ async function cmdList(argv: string[] = []) { const headers = ["", "Name", "Version", "Arch", "Network", "Ports", "PID"]; const rows = machines.map((m) => [ statusIcon(m.status), - `${m.name}${m.frozen ? " (frozen)" : ""}${isMachineForeign(m) ? " (other user)" : ""}`, + `${m.name}${m.frozen ? " (frozen)" : ""}${m.paused ? " (paused)" : ""}${isMachineForeign(m) ? " (other user)" : ""}`, m.version, m.arch, formatNetworks(m.networks ?? []), @@ -3991,7 +4040,9 @@ Commands: setup Interactive setup wizard (TTY only) add [options] Create a new CHR machine (without starting) start [|options] Start or restart a CHR instance - continue Resume a machine started with --frozen + continue Resume a paused machine, or one started with --frozen + pause Pause the guest in place; NICs keep carrier (a hung box) + reset In-place power cycle: same QEMU, RouterOS cold-boots stop [|--all] Power cut — print list if no name shutdown Request guest shutdown, then bounded hard-stop fallback list [] [--json] List all instances, or detail for one @@ -4261,11 +4312,12 @@ guest's configuration, and reopens the first-boot window.`); case "continue": console.log(`quickchr continue [--no-wait] [--timeout-extra ] -Resume a machine started with 'start --frozen' (held at reset with a gdbstub -on /gdb.sock). Sends one monitor 'cont', then waits for RouterOS -to become ready — the same promise 'start' makes. +Resume a machine paused with 'quickchr pause', or started with 'start --frozen' +(held at reset with a gdbstub on /gdb.sock). Sends one monitor +'cont', then waits for RouterOS to become ready — the same promise 'start' +makes. Clears both the paused and the frozen marker. - Name of a frozen (or otherwise paused) running machine. + Name of a paused, frozen (or otherwise held) running machine. --no-wait Return right after resuming; do not wait for RouterOS. --timeout-extra , -T Add extra seconds to the auto-computed resume timeout. @@ -4274,6 +4326,38 @@ Resuming is idempotent: when the guest is already running (e.g. gdb continued it), this just clears the frozen marker. A wait that never reaches readiness is a BOOT_TIMEOUT; the machine is stopped and preserved.`); break; + case "pause": + console.log(`quickchr pause + +Pause a running guest in place (QEMU monitor 'stop'). QEMU, its sockets and +every NIC's carrier stay up, so a link peer sees a hung box, not a pulled +cable. Resume with 'quickchr continue '. + + Name of a running machine. + +The guest clock stops with it: RouterOS never sees the hang (uptime excludes +it, and the clock runs behind until NTP corrects it). While paused, 'exec', +'qga' and other guest requests fail with MACHINE_PAUSED; 'stop' and 'reset' +work, and 'shutdown' power-cuts at once. 'list' marks the machine (paused). +Pausing an already-paused guest only sets the marker.`); + break; + case "reset": + console.log(`quickchr reset [--no-wait] [--timeout-extra ] + +In-place power cycle (QEMU monitor 'system_reset'): the same QEMU process, +PID and sockets stay up, and RouterOS cold-boots. Waits for RouterOS to +become ready again, like 'continue'. + + Name of a running machine. + --no-wait Return right after the reset; do not wait for RouterOS. + --timeout-extra , -T + Add extra seconds to the auto-computed boot timeout. + +A paused or frozen guest is resumed by the reset, and both markers are +cleared. The far end of each link keeps carrier; to make a neighbor see the +cable drop too, use 'quickchr set --link =down' around the reset. +Unlike 'stop' + 'start', nothing is respawned.`); + break; case "stop": console.log(`quickchr stop [] [--all] diff --git a/src/index.ts b/src/index.ts index 62e24b43..c83e7d31 100644 --- a/src/index.ts +++ b/src/index.ts @@ -37,6 +37,7 @@ export type { ChrInstance, ChrPorts, ContinueOptions, + ResetOptions, CustomForward, Descriptor, DeviceModeOptions, diff --git a/src/lib/completions.ts b/src/lib/completions.ts index e01f7228..badbdd9d 100644 --- a/src/lib/completions.ts +++ b/src/lib/completions.ts @@ -322,7 +322,7 @@ _quickchr() { cword=${D}COMP_CWORD } - local commands="add start continue stop shutdown list ls status inspect env get set remove rm clean console exec qga license disk snapshot snap networks net cache doctor settings setup completions version help" + local commands="add start continue pause reset stop shutdown list ls status inspect env get set remove rm clean console exec qga license disk snapshot snap networks net cache doctor settings setup completions version help" if [[ ${D}cword -eq 1 ]]; then COMPREPLY=( $(compgen -W "${D}commands" -- "${D}cur") ) @@ -336,7 +336,7 @@ _quickchr() { machines=$(quickchr completions --machines 2>/dev/null) COMPREPLY=( $(compgen -W "${D}machines" -- "${D}cur") ) ;; - stop|shutdown) + stop|shutdown|pause|reset) local machines machines=$(quickchr completions --running 2>/dev/null) [[ -z "${D}machines" ]] && machines=$(quickchr completions --machines 2>/dev/null) @@ -381,7 +381,9 @@ _quickchr() { local commands=( 'add:Create a new CHR machine (without starting)' 'start:Start or restart a CHR instance' - 'continue:Resume a machine started with --frozen' + 'continue:Resume a paused or --frozen machine' + 'pause:Pause the guest in place (NICs keep carrier)' + 'reset:In-place power cycle (same QEMU)' 'stop:Power cut instance(s)' 'shutdown:Request guest shutdown' 'list:List all instances' @@ -421,7 +423,7 @@ _quickchr() { machines=(${D}{(f)"${D}(quickchr completions --machines 2>/dev/null)"}) _describe 'machine' machines ;; - stop|shutdown) + stop|shutdown|pause|reset) local machines machines=(${D}{(f)"${D}(quickchr completions --running 2>/dev/null)"}) (( ${D}{#machines} == 0 )) && machines=(${D}{(f)"${D}(quickchr completions --machines 2>/dev/null)"}) @@ -442,7 +444,7 @@ _quickchr() { _describe 'cache subcommand' subcommands ;; help) - local commands=(add start continue stop shutdown list status inspect env get set remove clean console exec qga license disk snapshot networks cache doctor settings setup completions version) + local commands=(add start continue pause reset stop shutdown list status inspect env get set remove clean console exec qga license disk snapshot networks cache doctor settings setup completions version) _describe 'command' commands ;; esac @@ -458,7 +460,7 @@ function generateFishCompletion(): string { return `# quickchr fish completion # Generated by quickchr. Fish auto-loads files from ~/.config/fish/completions/. -set -l quickchr_commands add start continue stop shutdown list ls status inspect env get set remove rm clean console exec qga license disk snapshot snap networks net cache doctor settings setup completions version help +set -l quickchr_commands add start continue pause reset stop shutdown list ls status inspect env get set remove rm clean console exec qga license disk snapshot snap networks net cache doctor settings setup completions version help # Disable file completions globally for quickchr complete -c quickchr -f @@ -469,7 +471,11 @@ complete -c quickchr -n "not __fish_seen_subcommand_from $quickchr_commands" \\ complete -c quickchr -n "not __fish_seen_subcommand_from $quickchr_commands" \\ -a "start" -d "Start or restart a CHR instance" complete -c quickchr -n "not __fish_seen_subcommand_from $quickchr_commands" \\ - -a "continue" -d "Resume a machine started with --frozen" + -a "continue" -d "Resume a paused or --frozen machine" +complete -c quickchr -n "not __fish_seen_subcommand_from $quickchr_commands" \\ + -a "pause" -d "Pause the guest in place (NICs keep carrier)" +complete -c quickchr -n "not __fish_seen_subcommand_from $quickchr_commands" \\ + -a "reset" -d "In-place power cycle (same QEMU)" complete -c quickchr -n "not __fish_seen_subcommand_from $quickchr_commands" \\ -a "stop" -d "Power cut instance(s)" complete -c quickchr -n "not __fish_seen_subcommand_from $quickchr_commands" \\ @@ -520,7 +526,7 @@ complete -c quickchr -n "not __fish_seen_subcommand_from $quickchr_commands" \\ -a "help" -d "Show help" # Machine name completions for commands that take a running machine -complete -c quickchr -n "__fish_seen_subcommand_from stop shutdown" \\ +complete -c quickchr -n "__fish_seen_subcommand_from stop shutdown pause reset" \\ -a "(quickchr completions --running 2>/dev/null; or quickchr completions --machines 2>/dev/null)" \\ -d "machine" diff --git a/src/lib/lock.ts b/src/lib/lock.ts index 0ff39c2a..1f62f7dc 100644 --- a/src/lib/lock.ts +++ b/src/lib/lock.ts @@ -63,6 +63,8 @@ export type LockOperation = | "stop" | "shutdown" | "continue" + | "pause" + | "reset" | "clean" | "remove" | "device-mode" diff --git a/src/lib/quickchr.ts b/src/lib/quickchr.ts index 15669661..7354d388 100644 --- a/src/lib/quickchr.ts +++ b/src/lib/quickchr.ts @@ -8,6 +8,7 @@ import type { ChrInstance, ChrLoadSample, ContinueOptions, + ResetOptions, CustomForward, Descriptor, DeviceModeOptions, @@ -924,29 +925,48 @@ function finalizeStoppedState(state: MachineState): void { // A background QEMU leaves qemu.pid behind; once it has exited, a stale pid there // could later be reused by an unrelated process (#294). clearStalePidfile(state.machineDir); - // A frozen marker belongs to a live QEMU held at reset — a stopped machine - // holds nothing, so the flag goes with the pid (#214). + // The frozen and paused markers belong to a live QEMU — a stopped machine + // holds nothing, so the flags go with the pid (#214, #375). const current = loadMachine(state.name); if (current) { current.status = "stopped"; current.pid = undefined; current.frozen = undefined; + current.paused = undefined; saveMachine(current); } state.status = "stopped"; state.pid = undefined; state.frozen = undefined; + state.paused = undefined; } -/** Drop the frozen marker after a resume, in state and on disk. Dual-write like - * the provisioning record: the caller's handle and the next reader agree. */ -function clearFrozenMarker(state: MachineState): void { +/** Set or drop the live run markers (`frozen`, `paused`), in state and on disk. + * Dual-write like the provisioning record: the caller's handle and the next reader + * agree. A key left out of `markers` is not touched. */ +function setRunMarkers(state: MachineState, markers: { frozen?: true | undefined; paused?: true | undefined }): void { const current = loadMachine(state.name); if (current) { - current.frozen = undefined; + if ("frozen" in markers) current.frozen = markers.frozen; + if ("paused" in markers) current.paused = markers.paused; saveMachine(current); } - state.frozen = undefined; + if ("frozen" in markers) state.frozen = markers.frozen; + if ("paused" in markers) state.paused = markers.paused; +} + +/** Refuse a guest operation on a paused machine (#375): the guest cannot answer + * until `continue()`, so the request would only wait out its own timeout. Reads the + * record on disk, since another process (`quickchr pause`) may have paused it after + * this handle was made. */ +function assertNotPaused(state: MachineState, operation: string): void { + const paused = loadMachine(state.name)?.paused ?? state.paused; + if (!paused) return; + throw new QuickCHRError( + "MACHINE_PAUSED", + `Machine "${state.name}" is paused — ${operation} needs the guest, which cannot answer until it is resumed. ` + + `Run 'quickchr continue ${shellQuote(state.name)}' (continue()) first.`, + ); } /** Best-effort QEMU argv for a continue-timeout forensics report: rebuilt from @@ -1279,9 +1299,64 @@ async function continueUnderLock(state: MachineState, wait: boolean, timeoutExtr } } const wasFrozen = state.frozen === true; - clearFrozenMarker(state); + setRunMarkers(state, { frozen: undefined, paused: undefined }); + if (!wait) return; + await waitAfterResume(state, pid, wasFrozen, "continue", timeoutExtra); +} + +/** The body of `pause()`, for a caller that already holds the machine lock. */ +async function pauseUnderLock(state: MachineState): Promise { + assertOwnQemu(state, "pause"); + if (!state.pid || !isMachineRunning(state)) { + finalizeStoppedState(state); + throw new QuickCHRError("MACHINE_STOPPED", `Machine "${state.name}" is not running — nothing to pause.`); + } + // Idempotent: a guest that is already held (an earlier pause, a frozen start, + // a raw monitor `stop`) only gets the marker. + const status = await monitorCommand(state.machineDir, "info status", undefined, state.portBase); + if (status.includes("running")) { + const stopOut = await monitorCommand(state.machineDir, "stop", undefined, state.portBase); + // Same /^error/i contract as `cont`: the guest did not pause, so no marker. + if (/^error[:\s]/i.test(stopOut)) { + throw new QuickCHRError("PROCESS_FAILED", `pause failed: ${stopOut.trim() || "(empty)"}`); + } + } + setRunMarkers(state, { paused: true }); +} + +/** The body of `reset()`, for a caller that already holds the machine lock. */ +async function resetUnderLock(state: MachineState, wait: boolean, timeoutExtra?: number): Promise { + assertOwnQemu(state, "reset"); + const pid = state.pid; + if (!pid || !isMachineRunning(state)) { + finalizeStoppedState(state); + throw new QuickCHRError("MACHINE_STOPPED", `Machine "${state.name}" is not running — nothing to reset. Start it with 'quickchr start ${shellQuote(state.name)}'.`); + } + assertBootWaitReachable(state.networks, wait, state.name, "reset", + `Reset it with 'quickchr reset ${shellQuote(state.name)} --no-wait' (wait: false).`); + const resetOut = await monitorCommand(state.machineDir, "system_reset", undefined, state.portBase); + if (/^error[:\s]/i.test(resetOut)) { + throw new QuickCHRError("PROCESS_FAILED", `reset failed: ${resetOut.trim() || "(empty)"}`); + } + // A reset of a held guest (paused, or frozen at -S) leaves it held in + // `paused (prelaunch)` (#364). A power cycle always ends with RouterOS booting, + // so resume it. + const status = await monitorCommand(state.machineDir, "info status", undefined, state.portBase); + if (!status.includes("running")) { + const contOut = await monitorCommand(state.machineDir, "cont", undefined, state.portBase); + if (/^error[:\s]/i.test(contOut)) { + throw new QuickCHRError("PROCESS_FAILED", `reset: the guest was reset but did not resume: ${contOut.trim() || "(empty)"}`); + } + } + const wasFrozen = state.frozen === true; + setRunMarkers(state, { frozen: undefined, paused: undefined }); if (!wait) return; + await waitAfterResume(state, pid, wasFrozen, "reset", timeoutExtra); +} +/** The REST-ready wait after `continue()` or `reset()`, with the same failure + * capture: a `BOOT_TIMEOUT` that preserves the (previously booted) machine. */ +async function waitAfterResume(state: MachineState, pid: number, wasFrozen: boolean, phase: "continue" | "reset", timeoutExtra?: number): Promise { const instance = createInstance(state); // The frozen launch's accelerator when recorded: detectAccel() prefers the // current process's override, which may differ from the launch's. @@ -1302,7 +1377,7 @@ async function continueUnderLock(state: MachineState, wait: boolean, timeoutExtr portBase: state.portBase, qemuArgs: await launchedQemuArgsForReport(state, wasFrozen), probe, - phase: "continue", + phase, reportDir: bootFailureReportDir(), monitorQuery: (cmd) => monitorCommand(state.machineDir, cmd, 3000, state.portBase), forwards: Object.values(state.ports), @@ -1311,7 +1386,7 @@ async function continueUnderLock(state: MachineState, wait: boolean, timeoutExtr }); throw new QuickCHRError( "BOOT_TIMEOUT", - `CHR did not respond within ${bootTimeout / 1000}s (accel=${accel}) after continue.` + + `CHR did not respond within ${bootTimeout / 1000}s (accel=${accel}) after ${phase}.` + await cleanupAfterBootFailure(instance, state.name, failure, { kind: "preserve-existing" }) + `\n${failure.summary}`, ); @@ -1384,6 +1459,7 @@ async function cleanUnderLock(state: MachineState): Promise { current.status = "stopped"; current.pid = undefined; current.frozen = undefined; + current.paused = undefined; current.user = undefined; current.managedSshKey = undefined; current.disableAdmin = undefined; @@ -1396,6 +1472,7 @@ async function cleanUnderLock(state: MachineState): Promise { state.status = "stopped"; state.pid = undefined; state.frozen = undefined; + state.paused = undefined; state.user = undefined; state.managedSshKey = undefined; state.disableAdmin = undefined; @@ -1663,10 +1740,13 @@ function createInstance(state: MachineState): ChrInstance { return { outcome: "already-stopped" }; } const pid = state.pid; - const result = await shutdownGuest(timeoutMs, async (requestTimeoutMs) => { + // A paused guest cannot act on /system/shutdown (#375): power-cut it now + // rather than wait out the whole timeout for an exit that cannot happen. + const request = state.paused + ? () => Promise.reject(new Error(`Machine "${state.name}" is paused; the guest cannot shut itself down`)) // Rebuild after the locked refresh: a waiting handle may predate a relaunch. - return createInstance(state).exec("/system/shutdown", { via: "rest", timeout: requestTimeoutMs }); - }, () => isMachineRunning(state), () => stopQemu(pid)); + : (requestTimeoutMs: number) => createInstance(state).exec("/system/shutdown", { via: "rest", timeout: requestTimeoutMs }); + const result = await shutdownGuest(state.paused ? 0 : timeoutMs, request, () => isMachineRunning(state), () => stopQemu(pid)); finalizeStoppedState(state); return result; }); @@ -1676,6 +1756,16 @@ function createInstance(state: MachineState): ChrInstance { await withMachineLock(state, "continue", () => continueUnderLock(state, options?.wait ?? true, options?.timeoutExtra)); }, + async pause(): Promise { + preflightOwnQemu(state, "pause"); + await withMachineLock(state, "pause", () => pauseUnderLock(state)); + }, + + async reset(options?: ResetOptions): Promise { + preflightOwnQemu(state, "reset"); + await withMachineLock(state, "reset", () => resetUnderLock(state, options?.wait ?? true, options?.timeoutExtra)); + }, + async remove(): Promise { await withMachineLock(state, "remove", () => removeUnderLock(state)); }, @@ -1723,11 +1813,13 @@ function createInstance(state: MachineState): ChrInstance { }, async qga(command: QgaCommand, args?: object): Promise { + assertNotPaused(state, "qga()"); return qgaCommand(state.machineDir, state.arch, command, args, undefined, state.portBase); }, async rest(path: string, opts?: RequestInit): Promise { assertRestAvailable(state, "rest()"); + assertNotPaused(state, "rest()"); const url = `${restUrl}/rest${path.startsWith("/") ? path : "/" + path}`; // Retry on ECONNRESET — RouterOS can transiently reset connections in the @@ -1781,6 +1873,7 @@ function createInstance(state: MachineState): ChrInstance { async exec(command: string, opts?: ExecOptions): Promise { const via = opts?.via ?? "auto"; + assertNotPaused(state, "exec"); if (via === "qga") { if (state.arch === "arm64") { @@ -2565,8 +2658,9 @@ async function hardRebootMachine( state.status = "running"; state.lastStartedAt = new Date().toISOString(); // A power-cycle always boots normally: the replacement QEMU carries no -S, - // so a frozen marker from before must not survive it. + // so a frozen or paused marker from before must not survive it. state.frozen = undefined; + state.paused = undefined; await saveSpawnedState(state, pid); return method; @@ -4258,6 +4352,7 @@ export class QuickCHR { // not frozen must not inherit a stale one (e.g. a kill -9'd frozen // machine rebooted normally still listing as frozen). state.frozen = launch?.frozen ? true : undefined; + state.paused = undefined; // Frozen returns before the post-boot lastAccel recording below, so a // frozen relaunch records the launch accelerator for continue(). if (launch?.frozen) state.lastAccel = accel; diff --git a/src/lib/state.ts b/src/lib/state.ts index 20823537..be474d31 100644 --- a/src/lib/state.ts +++ b/src/lib/state.ts @@ -191,18 +191,19 @@ export function saveMachine(state: MachineState, io: SaveMachineIo = {}): void { } } -/** Record that a machine's QEMU is gone: status `stopped`, no pid, not frozen. +/** Record that a machine's QEMU is gone: status `stopped`, no pid, not frozen or paused. * * Takes the machine lock without waiting, then re-reads `machine.json` and changes only * those fields, so a status refresh cannot write back stale config over a change made * meanwhile — a receive slot added by `set --receive` while `list` was running, for one * (#299). Every writer of a live record (`set --receive`, `start`, `stop`, …) holds that * lock, so while it is held the refresh skips the write: the holder saves its own state, - * and the next refresh retries. The caller's object gets the three fields either way. */ + * and the next refresh retries. The caller's object gets those fields either way. */ export function markMachineStopped(state: MachineState): void { state.status = "stopped"; state.pid = undefined; state.frozen = undefined; + state.paused = undefined; let lock: HeldLock; try { lock = acquireLockNow(machineLockPath(state.machineDir), "status", { @@ -219,6 +220,7 @@ export function markMachineStopped(state: MachineState): void { current.status = "stopped"; current.pid = undefined; current.frozen = undefined; + current.paused = undefined; // Best effort: the caller already has the computed status, and a save refused // (a scanner holding the file on Windows, a read-only directory) must not fail // `list()`/`get()`. The next refresh tries again. diff --git a/src/lib/types.ts b/src/lib/types.ts index 6422c38e..58566a4a 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -495,6 +495,12 @@ export interface MachineState extends MachineConfig { * `wait: false`, not persisted config — stopping clears it, and a later * plain `start` boots normally. `status` stays `"running"` while frozen. */ frozen?: boolean | undefined; + /** Live marker: a booted guest was paused by `pause()` (`quickchr pause`, monitor + * `stop`) and awaits `continue()`. Not `frozen`: a frozen guest never booted and + * QEMU carries `-S` and a gdbstub; a paused guest was running RouterOS and its + * QEMU is an ordinary launch. Cleared by `continue()`, `reset()` and anything + * that stops QEMU. `status` stays `"running"` while paused. */ + paused?: boolean | undefined; /** Path to the machine directory. */ machineDir: string; /** Accelerator resolved for the most recent boot ("kvm" | "hvf" | "tcg"). */ @@ -884,6 +890,9 @@ export interface ContinueOptions { timeoutExtra?: number | undefined; } +/** Options for `ChrInstance.reset()` — the same knobs as `continue()`. */ +export type ResetOptions = ContinueOptions; + /** * Runtime handle for a CHR virtual machine. * @@ -995,6 +1004,20 @@ export interface ChrInstance { * running (e.g. gdb continued it) this just clears the frozen marker. Throws * `MACHINE_STOPPED` when QEMU is gone. */ continue(options?: ContinueOptions): Promise; + /** Pause the guest in place (monitor `stop`) and set the `paused` marker. QEMU, + * its sockets and the NICs' carrier stay up, so a link peer sees a hung box, not + * a cable pull. The guest clock stops too, so RouterOS never sees the hang. + * Resume with `continue()`. Idempotent: an already-paused guest only gets the + * marker. While paused, `rest()`, `exec()` and `qga()` throw `MACHINE_PAUSED`. + * Throws `MACHINE_STOPPED` when QEMU is gone. */ + pause(): Promise; + /** In-place power cycle (monitor `system_reset`): QEMU, its PID and every socket + * stay up, and RouterOS cold-boots. A paused or frozen guest is resumed by the + * reset and both markers are cleared — a reset always ends with RouterOS + * booting. Waits for REST-ready by default, like `continue()`. Far-end carrier + * is not touched; drop a peer's link with `link()` around it when the test + * needs one. Throws `MACHINE_STOPPED` when QEMU is gone. */ + reset(options?: ResetOptions): Promise; remove(): Promise; clean(): Promise; /** Stop and permanently delete this instance (disk + state). Equivalent to stop() then remove(). */ @@ -1286,6 +1309,10 @@ export type ErrorCode = | "MACHINE_NOT_FOUND" | "MACHINE_RUNNING" | "MACHINE_STOPPED" + // A guest operation (`rest()`, `exec()`, `qga()`) on a machine `pause()` paused: + // the guest cannot answer until `continue()`, so the request is refused up front + // instead of waiting out its timeout (#375). + | "MACHINE_PAUSED" | "INVALID_VERSION" | "INVALID_ARCH" | "INVALID_NAME" diff --git a/test/integration/pause-reset.test.ts b/test/integration/pause-reset.test.ts new file mode 100644 index 00000000..1fa00168 --- /dev/null +++ b/test/integration/pause-reset.test.ts @@ -0,0 +1,158 @@ +import { describe, test, expect, beforeAll, afterAll } from "bun:test"; +import { existsSync } from "node:fs"; +import { _resetSocketCache, removeNamedSocket, socketEndpointPath } from "../../src/lib/socket-registry.ts"; +import type { ChrInstance } from "../../src/lib/types.ts"; +import { imageTarget } from "./image-target.ts"; +import { bootTestTimeout } from "./timeouts.ts"; + +/** + * Integration test — `pause()`, `continue()` and in-place `reset()` (#375). + * + * Two CHRs joined by one named socket link (A ether2 ── B ether2). B is the machine + * under test; A watches the link from the far end: + * + * - pause keeps carrier: A's ether2 stays `running` for the whole pause, while traffic + * to B stops — a hung box, not a pulled cable. Guest requests to B fail fast. + * - continue returns REST-ready, and traffic flows again. + * - reset cold-boots B in place: same QEMU PID, RAM state gone, the link works. + * - reset of a paused B resumes it and clears the marker. + * + * A (first to start, the listener on listen-connect hosts) is never reset. + */ + +const SKIP = !process.env.QUICKCHR_INTEGRATION; +const A = "integration-pause-a"; +const B = "integration-pause-b"; +const LINK = `${A}-l1`; +const B_ADDR = "10.98.1.2"; + +async function cleanup(): Promise { + const { QuickCHR } = await import("../../src/lib/quickchr.ts"); + const errors: unknown[] = []; + for (const name of [B, A]) { + const existing = QuickCHR.get(name); + if (!existing) continue; + try { await existing.stop(); } catch { /* already stopped */ } + try { await existing.remove(); } catch (e) { errors.push(e); } + } + _resetSocketCache(); + try { removeNamedSocket(LINK); } catch (e) { errors.push(e); } + for (const slot of [0, 1]) { + const path = socketEndpointPath(LINK, slot); + if (existsSync(path)) errors.push(new Error(`cleanup left socket endpoint ${path} behind`)); + } + if (errors.length > 0) throw new AggregateError(errors, "pause-reset cleanup left resources behind"); +} + +async function run(chr: ChrInstance, command: string): Promise { + const { output } = await chr.exec(command); + if (/failure|syntax error|bad command|no such item|expected /i.test(output)) { + throw new Error(`${chr.name}: ${command}\n${output}`); + } + return output.trim(); +} + +async function carrier(chr: ChrInstance, port: string): Promise { + return (await run(chr, `:put [/interface/ethernet/get [find default-name=${port}] running]`)) === "true"; +} + +async function waitCarrier(chr: ChrInstance, port: string, want: boolean): Promise { + const deadline = Date.now() + 20_000; + for (;;) { + if (await carrier(chr, port) === want) return; + if (Date.now() > deadline) throw new Error(`${chr.name} ${port}: running never became ${want}`); + await Bun.sleep(500); + } +} + +async function replies(chr: ChrInstance, target: string): Promise { + const out = await run(chr, `:put [/ping ${target} count=3 interval=300ms]`); + const last = out.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).at(-1) ?? ""; + if (!/^\d+$/.test(last)) throw new Error(`${chr.name}: no reply count from /ping ${target}:\n${out}`); + return Number(last); +} + +async function waitReplies(chr: ChrInstance, target: string, atLeast: number): Promise { + const deadline = Date.now() + 30_000; + let got = 0; + for (;;) { + got = await replies(chr, target); + if (got >= atLeast || Date.now() > deadline) return got; + await Bun.sleep(500); + } +} + +/** A RouterOS global variable lives in RAM: set before a reset, gone after a real reboot. */ +async function bootMark(chr: ChrInstance): Promise { + return run(chr, ":global quickchrBootMark; :put [:typeof $quickchrBootMark]"); +} + +describe.skipIf(SKIP)("pause / continue / reset (#375)", () => { + beforeAll(cleanup); + afterAll(cleanup); + + test("pause keeps carrier, continue is REST-ready, reset cold-boots in place", async () => { + const { QuickCHR } = await import("../../src/lib/quickchr.ts"); + const networks = ["user" as const, { type: "socket" as const, name: LINK }]; + const a = await QuickCHR.start({ ...imageTarget(), background: true, name: A, networks }); + const b = await QuickCHR.start({ ...imageTarget(), background: true, name: B, networks }); + + await run(a, "/ip/address/add address=10.98.1.1/24 interface=ether2"); + await run(b, `/ip/address/add address=${B_ADDR}/24 interface=ether2`); + await waitCarrier(a, "ether2", true); + await waitCarrier(b, "ether2", true); + expect(await waitReplies(a, B_ADDR, 3)).toBe(3); + + // Pause: B's guest stops, A's end of the link keeps carrier the whole time. + const pid = b.state.pid; + await b.pause(); + expect(b.state.paused).toBe(true); + expect(b.state.frozen).toBeFalsy(); + expect(QuickCHR.get(B)?.state.status).toBe("running"); + expect(QuickCHR.get(B)?.state.paused).toBe(true); + expect(await b.monitor("info status")).toContain("paused"); + for (let i = 0; i < 4; i++) { + expect(await carrier(a, "ether2")).toBe(true); + await Bun.sleep(1000); + } + expect(await replies(a, B_ADDR)).toBe(0); + const refusedAt = Date.now(); + await expect(b.exec(":put 1")).rejects.toMatchObject({ code: "MACHINE_PAUSED" }); + await expect(b.rest("/system/resource")).rejects.toMatchObject({ code: "MACHINE_PAUSED" }); + expect(Date.now() - refusedAt).toBeLessThan(2_000); + // Idempotent. + await b.pause(); + expect(b.state.paused).toBe(true); + + // Continue: REST-ready on return, traffic flows again. + await b.continue(); + expect(b.state.paused).toBeFalsy(); + const resource = await b.rest("/system/resource") as Record; + expect(String(resource["board-name"])).toContain("CHR"); + expect(await waitReplies(a, B_ADDR, 3)).toBe(3); + + // Reset: same QEMU, RouterOS boots again (RAM state gone), disk config kept. + await run(b, ":global quickchrBootMark \"set\""); + expect(await bootMark(b)).toBe("str"); + await b.reset(); + expect(b.state.pid).toBe(pid); + expect(QuickCHR.get(B)?.state.pid).toBe(pid); + expect(await bootMark(b)).toBe("nothing"); + expect(await waitReplies(a, B_ADDR, 3)).toBe(3); + + // Reset of a paused machine resumes it and clears the marker. + await b.pause(); + await b.reset(); + expect(b.state.paused).toBeFalsy(); + expect(QuickCHR.get(B)?.state.paused).toBeFalsy(); + expect(b.state.pid).toBe(pid); + expect(await b.monitor("info status")).toContain("running"); + expect(await waitReplies(a, B_ADDR, 3)).toBe(3); + + // Stop clears the marker. + await b.pause(); + await b.stop(); + expect(QuickCHR.get(B)?.state.paused).toBeFalsy(); + expect(QuickCHR.get(B)?.state.status).toBe("stopped"); + }, bootTestTimeout({ boots: 4 })); +}); diff --git a/test/unit/cli-help-guard.test.ts b/test/unit/cli-help-guard.test.ts index 480c6c3e..6475f200 100644 --- a/test/unit/cli-help-guard.test.ts +++ b/test/unit/cli-help-guard.test.ts @@ -97,7 +97,7 @@ describe("--help is handled before any side effect (#156)", () => { // The guard lives in the dispatcher so a new subcommand cannot miss it; this // pins that for the commands that exist today. const commands = [ - "add", "start", "continue", "stop", "shutdown", "list", "remove", "clean", "console", "exec", "qga", + "add", "start", "continue", "pause", "reset", "stop", "shutdown", "list", "remove", "clean", "console", "exec", "qga", "get", "set", "inspect", "env", "disk", "snapshot", "doctor", "logs", "completions", "networks", "cache", "settings", "version", ]; diff --git a/test/unit/cli-pause-reset.test.ts b/test/unit/cli-pause-reset.test.ts new file mode 100644 index 00000000..a2bd3c0b --- /dev/null +++ b/test/unit/cli-pause-reset.test.ts @@ -0,0 +1,184 @@ +import { describe, test, expect, beforeEach, afterEach, mock, spyOn } from "bun:test"; +import { mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { saveMachine } from "../../src/lib/state.ts"; +import type { MachineState } from "../../src/lib/types.ts"; + +/** + * `quickchr pause` / `quickchr reset` and the `(paused)` list marker (#375), + * without a guest. A fixture whose pid is this test process reads as running. + */ + +const TEST_DIR = join(import.meta.dir, ".tmp-cli-pause-reset"); +const CLI = join(import.meta.dir, "../../src/cli/index.ts"); + +async function runQuickchr(args: string[]) { + const proc = Bun.spawn([process.execPath, CLI, ...args], { + env: { + ...process.env, + QUICKCHR_DATA_DIR: TEST_DIR, + HOME: join(TEST_DIR, "home"), + NO_COLOR: "1", + QUICKCHR_NO_PROMPT: "1", + }, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([ + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + proc.exited, + ]); + return { stdout, stderr, exitCode }; +} + +function pausedMachine(): MachineState { + return { + name: "hung", + version: "7.24.5", + arch: "x86", + cpu: 1, + mem: 512, + networks: [{ specifier: "user", id: "net0" }], + ports: {}, + packages: [], + portBase: 9130, + excludePorts: [], + extraPorts: [], + createdAt: "2026-01-01T00:00:00.000Z", + status: "running", + pid: process.pid, + paused: true, + machineDir: join(TEST_DIR, "machines", "hung"), + }; +} + +beforeEach(() => { + rmSync(TEST_DIR, { recursive: true, force: true }); + mkdirSync(TEST_DIR, { recursive: true }); + process.env.QUICKCHR_DATA_DIR = TEST_DIR; + saveMachine(pausedMachine()); + writeFileSync(join(TEST_DIR, "machines", "hung", "monitor.sock"), ""); +}); + +afterEach(() => { + rmSync(TEST_DIR, { recursive: true, force: true }); + delete process.env.QUICKCHR_DATA_DIR; +}); + +describe("list paused markers", () => { + test("table row carries (paused), not (frozen)", async () => { + const result = await runQuickchr(["list"]); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain("hung (paused)"); + expect(result.stdout).not.toContain("(frozen)"); + }); + + test("detail view shows a Paused line and no GDB line", async () => { + const result = await runQuickchr(["list", "hung"]); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain("Paused: yes"); + expect(result.stdout).toContain("endpoints answer after 'quickchr continue hung'"); + expect(result.stdout).not.toContain("gdb.sock"); + }); + + test("--json carries paused next to frozen", async () => { + const one = JSON.parse((await runQuickchr(["list", "hung", "--json"])).stdout) as Record; + expect(one["paused"]).toBe(true); + expect(one["frozen"]).toBe(false); + const all = JSON.parse((await runQuickchr(["list", "--json"])).stdout) as Array>; + expect(all.find((m) => m["name"] === "hung")?.["paused"]).toBe(true); + }); +}); + +describe("pause / reset argument handling", () => { + test("pause with no name is a usage error", async () => { + const result = await runQuickchr(["pause"]); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain("Usage: quickchr pause "); + }); + + test("pause takes no flags", async () => { + const result = await runQuickchr(["pause", "hung", "--no-wait"]); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain("pause accepts only "); + }); + + test("reset rejects flags other than --no-wait/--timeout-extra", async () => { + const result = await runQuickchr(["reset", "hung", "--force"]); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain("reset accepts only"); + }); + + test("on a missing machine both name it", async () => { + for (const cmd of ["pause", "reset"]) { + const result = await runQuickchr([cmd, "nope"]); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain("nope"); + } + }); + + test("exec on a paused machine fails fast with MACHINE_PAUSED", async () => { + const result = await runQuickchr(["exec", "hung", ":put 1"]); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain("MACHINE_PAUSED"); + }); + + test("help documents the verbs and continue names pause", async () => { + expect((await runQuickchr(["pause", "--help"])).stdout).toContain("quickchr continue"); + expect((await runQuickchr(["reset", "--help"])).stdout).toContain("system_reset"); + expect((await runQuickchr(["continue", "--help"])).stdout).toContain("quickchr pause"); + const top = (await runQuickchr(["--help"])).stdout; + expect(top).toContain("pause "); + expect(top).toContain("reset "); + }); +}); + +describe("reset options (mocked QuickCHR boundary)", () => { + let lines: string[]; + + beforeEach(() => { + lines = []; + process.env.NO_COLOR = "1"; + process.env.QUICKCHR_NO_TIPS = "1"; + spyOn(console, "log").mockImplementation((...args: unknown[]) => { + lines.push(args.map(String).join(" ")); + }); + spyOn(console, "error").mockImplementation(() => {}); + }); + + afterEach(() => { + mock.restore(); + delete process.env.NO_COLOR; + delete process.env.QUICKCHR_NO_TIPS; + }); + + test("reset forwards --no-wait and -T to instance.reset", async () => { + const { QuickCHR } = await import("../../src/lib/quickchr.ts"); + const { cmdReset } = await import("../../src/cli/index.ts"); + const seen: unknown[] = []; + spyOn(QuickCHR, "get").mockImplementation(() => ({ + name: "lab", + state: { name: "lab", version: "7.24.5", arch: "x86", status: "running", pid: 4242 }, + reset: async (opts: unknown) => { seen.push(opts); }, + }) as never); + await cmdReset(["lab", "-T", "15"]); + await cmdReset(["lab", "--no-wait"]); + expect(seen).toEqual([{ wait: true, timeoutExtra: 15_000 }, { wait: false, timeoutExtra: 0 }]); + expect(lines[0]).toContain("PID 4242"); + }); + + test("pause calls instance.pause once", async () => { + const { QuickCHR } = await import("../../src/lib/quickchr.ts"); + const { cmdPause } = await import("../../src/cli/index.ts"); + let calls = 0; + spyOn(QuickCHR, "get").mockImplementation(() => ({ + name: "lab", + state: { name: "lab", version: "7.24.5", arch: "x86", status: "running" }, + pause: async () => { calls++; }, + }) as never); + await cmdPause(["lab"]); + expect(calls).toBe(1); + expect(lines[0]).toContain("quickchr continue lab"); + }); +}); diff --git a/test/unit/completions.test.ts b/test/unit/completions.test.ts index 27a520b6..1e5d66dc 100644 --- a/test/unit/completions.test.ts +++ b/test/unit/completions.test.ts @@ -161,7 +161,7 @@ describe("generateCompletionScript", () => { }); test("scripts include all main subcommands", () => { - const subcommands = ["start", "continue", "stop", "shutdown", "list", "remove", "console", "exec", "cache", "doctor", "completions"]; + const subcommands = ["start", "continue", "pause", "reset", "stop", "shutdown", "list", "remove", "console", "exec", "cache", "doctor", "completions"]; for (const shell of SHELLS) { const script = generateCompletionScript(shell); for (const cmd of subcommands) { diff --git a/test/unit/pause-reset.test.ts b/test/unit/pause-reset.test.ts new file mode 100644 index 00000000..10ef754c --- /dev/null +++ b/test/unit/pause-reset.test.ts @@ -0,0 +1,283 @@ +import { describe, test, expect, beforeEach, afterEach } from "bun:test"; +import { mkdirSync, rmSync } from "node:fs"; +import { join } from "node:path"; +import { createServer, type Server } from "node:net"; +import { QuickCHR } from "../../src/lib/quickchr.ts"; +import { loadMachine, saveMachine } from "../../src/lib/state.ts"; +import type { MachineState } from "../../src/lib/types.ts"; + +/** + * `pause()` / `reset()` and the `paused` marker (#375) without a guest. A fake + * QEMU monitor models the run state (`running` / `paused` / `prelaunch`) so the + * marker lifecycle can be checked: pause sets it, continue/reset/stop clear it, + * and it never touches `frozen`. The live paths (carrier kept, REST-ready after + * continue, same PID across reset) are in test/integration/pause-reset.test.ts. + * + * The monitor mock binds a Unix socket, so socket tests skip on Windows (same + * rule as continue.test.ts). + */ + +const TEST_DIR = join(import.meta.dir, ".tmp-pause-reset"); +const origDataDir = process.env.QUICKCHR_DATA_DIR; +const POSIX = process.platform !== "win32"; + +function machine(name: string, overrides: Partial = {}): MachineState { + return { + name, + version: "7.24.5", + arch: "x86", + cpu: 1, + mem: 512, + networks: [{ specifier: "user", id: "net0" }], + ports: {}, + packages: [], + portBase: 9130, + excludePorts: [], + extraPorts: [], + createdAt: "2026-01-01T00:00:00.000Z", + status: "running", + // process.pid is alive, so the dead-pid branches cannot trigger. + pid: process.pid, + machineDir: join(TEST_DIR, "machines", name), + ...overrides, + }; +} + +beforeEach(() => { + rmSync(TEST_DIR, { recursive: true, force: true }); + mkdirSync(TEST_DIR, { recursive: true }); + process.env.QUICKCHR_DATA_DIR = TEST_DIR; +}); + +afterEach(() => { + rmSync(TEST_DIR, { recursive: true, force: true }); + if (origDataDir === undefined) delete process.env.QUICKCHR_DATA_DIR; + else process.env.QUICKCHR_DATA_DIR = origDataDir; +}); + +type RunState = "running" | "paused" | "prelaunch"; + +/** A QEMU monitor stand-in that tracks the guest's run state the way HMP does. */ +async function fakeMonitor(machineDir: string, initial: RunState, overrides: Record = {}) { + const vm = { state: initial, commands: [] as string[] }; + const server = createServer((sock) => { + sock.write("(qemu) "); + sock.on("data", (data) => { + const command = data.toString().trim(); + vm.commands.push(command); + let reply = overrides[command]; + if (reply === undefined) { + reply = ""; + if (command === "info status") reply = vm.state === "running" ? "VM status: running" : vm.state === "paused" ? "VM status: paused" : "VM status: paused (prelaunch)"; + else if (command === "stop") vm.state = "paused"; + else if (command === "cont") vm.state = "running"; + // #364: a reset of a held guest leaves it in prelaunch. + else if (command === "system_reset" && vm.state !== "running") vm.state = "prelaunch"; + } + sock.write(`${command}\n${reply}\n(qemu) `); + }); + }); + await new Promise((resolve) => server.listen(join(machineDir, "monitor.sock"), resolve)); + return { vm, server }; +} + +async function closeServer(server: Server): Promise { + await new Promise((resolve, reject) => server.close((err) => (err ? reject(err) : resolve()))); +} + +function get(name: string) { + const instance = QuickCHR.get(name); + if (!instance) throw new Error("seeded machine did not load"); + return instance; +} + +describe("pause()", () => { + test.skipIf(!POSIX)("pauses a running guest and sets the marker, leaving frozen alone", async () => { + saveMachine(machine("p-run")); + const { vm, server } = await fakeMonitor(join(TEST_DIR, "machines", "p-run"), "running"); + try { + const instance = get("p-run"); + await instance.pause(); + expect(vm.commands).toContain("stop"); + expect(vm.state).toBe("paused"); + expect(instance.state.paused).toBe(true); + expect(loadMachine("p-run")?.paused).toBe(true); + expect(loadMachine("p-run")?.frozen).toBeUndefined(); + expect(loadMachine("p-run")?.status).toBe("running"); + } finally { + await closeServer(server); + } + }); + + test.skipIf(!POSIX)("an already-held guest only gets the marker; a frozen marker survives", async () => { + saveMachine(machine("p-held", { frozen: true })); + const { vm, server } = await fakeMonitor(join(TEST_DIR, "machines", "p-held"), "prelaunch"); + try { + await get("p-held").pause(); + expect(vm.commands).not.toContain("stop"); + expect(loadMachine("p-held")?.paused).toBe(true); + expect(loadMachine("p-held")?.frozen).toBe(true); + } finally { + await closeServer(server); + } + }); + + test.skipIf(!POSIX)("a QEMU-level stop error is PROCESS_FAILED and sets no marker", async () => { + saveMachine(machine("p-err")); + const { server } = await fakeMonitor(join(TEST_DIR, "machines", "p-err"), "running", { stop: "Error: cannot stop" }); + try { + await expect(get("p-err").pause()).rejects.toMatchObject({ code: "PROCESS_FAILED", message: expect.stringContaining("pause failed") }); + expect(loadMachine("p-err")?.paused).toBeUndefined(); + } finally { + await closeServer(server); + } + }); + + test("a dead pid is MACHINE_STOPPED and leaves clean state", async () => { + saveMachine(machine("p-dead", { pid: 999_999_999, paused: true })); + await expect(get("p-dead").pause()).rejects.toMatchObject({ code: "MACHINE_STOPPED" }); + const after = loadMachine("p-dead"); + expect(after?.status).toBe("stopped"); + expect(after?.pid).toBeUndefined(); + expect(after?.paused).toBeUndefined(); + }); +}); + +describe("continue() after pause()", () => { + test.skipIf(!POSIX)("resumes and clears the paused marker", async () => { + saveMachine(machine("c-paused")); + const { vm, server } = await fakeMonitor(join(TEST_DIR, "machines", "c-paused"), "running"); + try { + const instance = get("c-paused"); + await instance.pause(); + await instance.continue({ wait: false }); + expect(vm.state).toBe("running"); + expect(instance.state.paused).toBeUndefined(); + expect(loadMachine("c-paused")?.paused).toBeUndefined(); + } finally { + await closeServer(server); + } + }); + + test.skipIf(!POSIX)("a handle made before pause sees the marker on disk and continue clears it", async () => { + saveMachine(machine("c-stale")); + const { server } = await fakeMonitor(join(TEST_DIR, "machines", "c-stale"), "running"); + try { + const stale = get("c-stale"); + await get("c-stale").pause(); + await expect(stale.rest("/system/resource")).rejects.toMatchObject({ code: "MACHINE_PAUSED" }); + await stale.continue({ wait: false }); + expect(loadMachine("c-stale")?.paused).toBeUndefined(); + } finally { + await closeServer(server); + } + }); +}); + +describe("guest requests on a paused machine", () => { + test("rest(), exec() and qga() fail fast with MACHINE_PAUSED", async () => { + saveMachine(machine("g-paused", { paused: true })); + const instance = get("g-paused"); + const started = Date.now(); + await expect(instance.rest("/system/resource")).rejects.toMatchObject({ code: "MACHINE_PAUSED", message: expect.stringContaining("quickchr continue g-paused") }); + await expect(instance.exec(":put 1")).rejects.toMatchObject({ code: "MACHINE_PAUSED" }); + await expect(instance.exec(":put 1", { via: "console" })).rejects.toMatchObject({ code: "MACHINE_PAUSED" }); + await expect(instance.qga("guest-ping")).rejects.toMatchObject({ code: "MACHINE_PAUSED" }); + expect(Date.now() - started).toBeLessThan(2_000); + }); +}); + +describe("reset()", () => { + test.skipIf(!POSIX)("a running guest gets system_reset and no cont", async () => { + saveMachine(machine("r-run")); + const { vm, server } = await fakeMonitor(join(TEST_DIR, "machines", "r-run"), "running"); + try { + await get("r-run").reset({ wait: false }); + expect(vm.commands).toContain("system_reset"); + expect(vm.commands).not.toContain("cont"); + expect(vm.state).toBe("running"); + expect(loadMachine("r-run")?.pid).toBe(process.pid); + } finally { + await closeServer(server); + } + }); + + test.skipIf(!POSIX)("a paused guest is reset, resumed, and both markers are cleared", async () => { + saveMachine(machine("r-paused", { paused: true, frozen: true })); + const { vm, server } = await fakeMonitor(join(TEST_DIR, "machines", "r-paused"), "paused"); + try { + const instance = get("r-paused"); + await instance.reset({ wait: false }); + expect(vm.commands.indexOf("system_reset")).toBeLessThan(vm.commands.indexOf("cont")); + expect(vm.state).toBe("running"); + expect(instance.state.paused).toBeUndefined(); + expect(instance.state.frozen).toBeUndefined(); + expect(loadMachine("r-paused")?.paused).toBeUndefined(); + expect(loadMachine("r-paused")?.frozen).toBeUndefined(); + } finally { + await closeServer(server); + } + }); + + test.skipIf(!POSIX)("a QEMU-level system_reset error is PROCESS_FAILED and keeps the marker", async () => { + saveMachine(machine("r-err", { paused: true })); + const { server } = await fakeMonitor(join(TEST_DIR, "machines", "r-err"), "paused", { system_reset: "Error: reset refused" }); + try { + await expect(get("r-err").reset({ wait: false })).rejects.toMatchObject({ code: "PROCESS_FAILED", message: expect.stringContaining("reset failed") }); + expect(loadMachine("r-err")?.paused).toBe(true); + } finally { + await closeServer(server); + } + }); + + test("a dead pid is MACHINE_STOPPED and leaves clean state", async () => { + saveMachine(machine("r-dead", { pid: 999_999_999, paused: true })); + await expect(get("r-dead").reset({ wait: false })).rejects.toMatchObject({ code: "MACHINE_STOPPED" }); + expect(loadMachine("r-dead")?.status).toBe("stopped"); + expect(loadMachine("r-dead")?.paused).toBeUndefined(); + }); + + test("a waiting reset of a machine with no user NIC is refused before it resets", async () => { + saveMachine(machine("r-no-user-nic", { networks: [{ specifier: { type: "socket", name: "lab" }, id: "net0" }], paused: true })); + await expect(get("r-no-user-nic").reset()).rejects.toMatchObject({ code: "INVALID_NETWORK" }); + expect(loadMachine("r-no-user-nic")?.paused).toBe(true); + }); +}); + +describe("stopping clears the paused marker", () => { + test.skipIf(!POSIX)("stop() on a paused machine", async () => { + const child = Bun.spawn(["sleep", "60"]); + try { + saveMachine(machine("s-paused", { pid: child.pid, paused: true })); + const instance = get("s-paused"); + await instance.stop(); + expect(instance.state.paused).toBeUndefined(); + expect(loadMachine("s-paused")?.paused).toBeUndefined(); + expect(loadMachine("s-paused")?.status).toBe("stopped"); + } finally { + child.kill(); + } + }); + + test.skipIf(!POSIX)("shutdown() of a paused machine power-cuts at once instead of waiting its timeout", async () => { + const child = Bun.spawn(["sleep", "60"]); + try { + saveMachine(machine("sd-paused", { pid: child.pid, paused: true })); + const started = Date.now(); + const result = await get("sd-paused").shutdown({ timeoutMs: 30_000 }); + expect(Date.now() - started).toBeLessThan(10_000); + expect(result.outcome).toBe("forced"); + expect(result.requestError).toContain("paused"); + expect(loadMachine("sd-paused")?.paused).toBeUndefined(); + } finally { + child.kill(); + } + }); + + test("a status refresh that finds QEMU gone drops the marker", () => { + saveMachine(machine("s-gone", { pid: 999_999_999, paused: true })); + const instance = get("s-gone"); + expect(instance.state.status).toBe("stopped"); + expect(loadMachine("s-gone")?.paused).toBeUndefined(); + }); +}); From 279327d89a31572de03d3c10cb6dbc9db37194f0 Mon Sep 17 00:00:00 2001 From: TIKOCI RouterOS Bots Date: Wed, 2 Dec 2026 05:24:35 -0800 Subject: [PATCH 2/3] =?UTF-8?q?fix(qemu):=20address=20#376=20review=20?= =?UTF-8?q?=E2=80=94=20strict=20monitor=20replies,=20fresh=20markers,=20re?= =?UTF-8?q?set=20keeps=20QEMU=20on=20timeout?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - assertNotPaused: the on-disk record wins in both directions, so a handle that saw `paused` stops refusing once another process resumes the VM. - pause/reset/continue: `info status` must parse and every `stop`/`cont`/ `system_reset` needs the final prompt; `/^error/i` replies fail; the marker is set only once QEMU reports the guest held. - buildAndSpawnQemu clears `paused` and sets `frozen` from the launch before any pid or record is saved; the foreground exit also drops the old pid. - snapshot.load: a failed loadvm resumes the guest only if it was running. - reset: a REST-wait timeout keeps QEMU and its links up (BOOT_TIMEOUT with the report), instead of the continue-style stop. - CLI: `get` prints a paused report instead of live reads; `qga` refuses a paused machine; `continue`/`reset` refuse a valueless --timeout-extra/-T. - Tests: exact monitor sequences, strict-reply cases, reverse stale handle, snapshot-load on a paused guest, spawn markers, CLI get/qga/-T, and a RAM sentinel across the live paused reset. snapshot-budgets stub grows `info status`. Co-Authored-By: Claude Opus 5.5 --- .github/instructions/qemu.instructions.md | 6 ++ DESIGN.md | 13 ++- MANUAL.md | 12 ++- src/cli/index.ts | 50 +++++++++- src/lib/quickchr.ts | 91 +++++++++++------- test/integration/pause-reset.test.ts | 6 +- test/unit/cli-pause-reset.test.ts | 31 ++++++ test/unit/pause-reset.test.ts | 110 +++++++++++++++++++++- test/unit/snapshot-budgets.test.ts | 3 + 9 files changed, 276 insertions(+), 46 deletions(-) diff --git a/.github/instructions/qemu.instructions.md b/.github/instructions/qemu.instructions.md index bef6fc27..d12b07c1 100644 --- a/.github/instructions/qemu.instructions.md +++ b/.github/instructions/qemu.instructions.md @@ -177,6 +177,12 @@ so a link peer sees a hung box, not a cable pull. Grounded on Linux/KVM, RouterO drops at its queue (`tx-queue-drop`). Its monitor (~2 ms), QGA and other links keep working. After `cont` the backlog (328 frames on dgram, 1574 on TCP in the probe) arrives within 0.6 s. +- **The paused VM's own channels stay up, its guest does not answer.** The monitor + works throughout, and the QGA chardev socket (QEMU's) still accepts a connection, + but the agent inside the guest cannot reply, so a QGA call waits out its timeout. + quickchr refuses guest requests on a paused machine instead (`MACHINE_PAUSED`). +- **A failed `loadvm` leaves the VM held** (`paused (restore-vm)`); quickchr's + `snapshot.load()` resumes it with `cont` only if the guest was running before. - **`system_reset` keeps the process and its sockets.** Same PID, every socket link kept, RouterOS ready again in 12–23 s on KVM. A reset of a held guest (`stop`, or `-S`) leaves it in `paused (prelaunch)`; `cont` boots it. diff --git a/DESIGN.md b/DESIGN.md index d2c4af70..ff0e62d1 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1587,7 +1587,18 @@ while its NICs keep carrier (a hung switch), and a power cycle that keeps QEMU. booting**: QEMU leaves a held guest in `paused (prelaunch)` after `system_reset`, so `reset()` resumes it and clears both markers. The other choice (reset but stay held) has no use a `pause()` after the reset doesn't cover, and would make - `reset()`'s REST wait impossible to keep. + `reset()`'s REST wait impossible to keep. A reset whose REST wait times out is a + `BOOT_TIMEOUT` with the usual report, but QEMU is left running: stopping it, as + `continue()`'s timeout does, would pull every link the reset exists to keep. +- **Every QEMU spawn starts with fresh markers.** `buildAndSpawnQemu()` clears + `paused` and sets `frozen` from the launch config before any path can record the + new pid or save the record, so neither a foreground exit nor a still-running + spawn failure can carry the previous process's marker. +- **Monitor replies are confirmed, not assumed.** `pause`, `reset` and `continue` + read `info status` and send `stop`/`cont`/`system_reset` with the final prompt + required; an unrecognised status, a close before the prompt, or an `error…` reply + is `PROCESS_FAILED`, and the `paused` marker is set only after QEMU reports the + guest held. ## Managed macOS networks (#256, decided 2026-11-11) diff --git a/MANUAL.md b/MANUAL.md index 9e2219cb..f1ddc1ec 100644 --- a/MANUAL.md +++ b/MANUAL.md @@ -385,8 +385,11 @@ and a gdbstub; a paused guest was running RouterOS. `status` stays `running`; `list --json` carries `paused`. `stop` and `reset` work on a paused machine and clear the marker. While it is set, guest requests — `exec`, `qga`, and `rest()` / `exec()` / `qga()` in the library — fail at once with `MACHINE_PAUSED` instead of -waiting out their timeout, and `shutdown` power-cuts immediately (the guest cannot -act on `/system/shutdown`) and reports `forced`. +waiting out their timeout (the QGA socket belongs to QEMU and still accepts a +connection, but the agent inside the guest cannot answer). `get` prints what it +knows locally with a `paused` note instead of its live reads, `shutdown` +power-cuts immediately (the guest cannot act on `/system/shutdown`) and reports +`forced`, and a failed `snapshot load` leaves the guest paused. What a paused guest and its peers see (grounded on Linux/KVM, RouterOS 7.25.2, QEMU 11.1.2, #364; macOS/HVF in #375): @@ -419,7 +422,10 @@ sockets stay up and RouterOS cold-boots, so nothing is respawned and no socket link is re-established. Waits for RouterOS to become ready again, like `continue`; `--no-wait` returns right after the reset, and `--timeout-extra`/`-T` extends the wait. A machine with no `user` NIC needs `--no-wait` -(`INVALID_NETWORK`), as for `continue`. +(`INVALID_NETWORK`), as for `continue`. A wait that never reaches readiness is a +`BOOT_TIMEOUT` with the usual failure report, but unlike `continue`, QEMU is left +running: stopping it would pull every link the reset kept. Wait longer, reset +again, or `stop` it. A reset always ends with RouterOS booting: a paused or frozen guest is reset, then resumed (QEMU leaves a held guest in `paused (prelaunch)` after diff --git a/src/cli/index.ts b/src/cli/index.ts index ee64fdf9..ce1335f9 100755 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -334,6 +334,20 @@ export function applyTimeoutExtraShortFlag( * Callers merge the `-T` short-flag alias into `flags["timeout-extra"]` before * calling this — `-T` is single-dash and parseFlags only recognizes `--` flags * (same reason cmdLogs scans argv directly for its own `-f`/`-n` aliases). */ +/** `continue`/`reset`: a `--timeout-extra` or `-T` with no value is refused before the + * machine is touched, rather than read as "no extra time" (#375 review). Call before + * `applyTimeoutExtraShortFlag()`, which would take the next flag as the value. */ +export function assertTimeoutExtraHasValue(argv: readonly string[], flags: Record, command: string): void { + const end = argv.indexOf("--"); + const args = end === -1 ? argv : argv.slice(0, end); + const tIdx = args.indexOf("-T"); + const short = tIdx !== -1 && (args[tIdx + 1] === undefined || args[tIdx + 1]?.startsWith("-")); + const valueless = valuelessFlags(flags, ["timeout-extra"]); + if (short || valueless.length > 0) { + throw new QuickCHRError("INVALID_ARGUMENT", `${command}: --timeout-extra (-T) needs a value in seconds, e.g. -T 60`); + } +} + export async function resolveTimeoutExtraMs(flags: Record): Promise { const { resolveSetting, parseTimeoutExtraSeconds } = await import("../lib/settings.ts"); const flagRaw = flag(flags, "timeout-extra"); @@ -996,6 +1010,10 @@ Options: console.error(`Machine "${name}" is not running. Start it first: quickchr start ${name}`); process.exit(1); } + // The QGA socket is QEMU's and accepts a connection while the guest is paused; + // the agent inside cannot answer, so refuse instead of waiting out --timeout. + const { assertNotPaused } = await import("../lib/quickchr.ts"); + assertNotPaused(machine.state, "qga"); const timeoutMs = flag(flags, "timeout") ? Number(flag(flags, "timeout")) * 1000 : 10_000; const { @@ -1719,6 +1737,7 @@ export async function cmdStart(argv: string[]) { export async function cmdContinue(argv: string[]) { const { flags, positional } = parseFlags(argv); + assertTimeoutExtraHasValue(argv, flags, "continue"); applyTimeoutExtraShortFlag(argv, flags, positional); const invalid = unknownFlags(flags, ["wait", "timeout-extra"]); if (invalid.length) throw new QuickCHRError("INVALID_ARGUMENT", "continue accepts only , --no-wait and --timeout-extra "); @@ -1768,6 +1787,7 @@ export async function cmdPause(argv: string[]) { export async function cmdReset(argv: string[]) { const { flags, positional } = parseFlags(argv); + assertTimeoutExtraHasValue(argv, flags, "reset"); applyTimeoutExtraShortFlag(argv, flags, positional); const invalid = unknownFlags(flags, ["wait", "timeout-extra"]); if (invalid.length) throw new QuickCHRError("INVALID_ARGUMENT", "reset accepts only , --no-wait and --timeout-extra "); @@ -2129,6 +2149,29 @@ async function cmdGet(argv: string[]) { return; } + if (s.paused) { + // A paused guest cannot answer REST; every live read would only time out (#375). + const pausedData = { + name: s.name, + status: s.status, + paused: true, + version: s.version, + arch: s.arch, + ...(hasCaptures ? { captures } : {}), + note: `machine is paused — live properties unavailable until 'quickchr continue ${s.name}'`, + }; + if (asJson) { + console.log(JSON.stringify(pausedData, null, 2)); + } else { + console.log(`\n${bold(s.name)} (running, paused)`); + console.log(` Version: ${s.version} (${s.arch})`); + for (const [port, file] of Object.entries(captures)) console.log(` Capture: ${port} → ${file}`); + console.log(` ${dim(`Resume it with quickchr continue ${s.name} to query live properties.`)}`); + console.log(); + } + return; + } + // Every live group is a REST read. Refused here rather than left to fetchGroup(), // which swallows errors and would print an empty report for a v6 machine (#182). const { assertRestAvailable } = await import("../lib/versions.ts"); @@ -4337,8 +4380,8 @@ cable. Resume with 'quickchr continue '. The guest clock stops with it: RouterOS never sees the hang (uptime excludes it, and the clock runs behind until NTP corrects it). While paused, 'exec', -'qga' and other guest requests fail with MACHINE_PAUSED; 'stop' and 'reset' -work, and 'shutdown' power-cuts at once. 'list' marks the machine (paused). +'qga' and other guest requests fail with MACHINE_PAUSED and 'get' skips its +live reads; 'stop' and 'reset' work, and 'shutdown' power-cuts at once. 'list' marks the machine (paused). Pausing an already-paused guest only sets the marker.`); break; case "reset": @@ -4356,7 +4399,8 @@ become ready again, like 'continue'. A paused or frozen guest is resumed by the reset, and both markers are cleared. The far end of each link keeps carrier; to make a neighbor see the cable drop too, use 'quickchr set --link =down' around the reset. -Unlike 'stop' + 'start', nothing is respawned.`); +Unlike 'stop' + 'start', nothing is respawned. A wait that never reaches +readiness is a BOOT_TIMEOUT, and QEMU is left running with its links.`); break; case "stop": console.log(`quickchr stop [] [--all] diff --git a/src/lib/quickchr.ts b/src/lib/quickchr.ts index 7354d388..260e4dee 100644 --- a/src/lib/quickchr.ts +++ b/src/lib/quickchr.ts @@ -538,6 +538,11 @@ async function spawnCheckedQemu( * copies, and the paths are recorded on `state.networks` for the caller's save. On any * failure, files QEMU never opened are deleted and forgotten. Exported for tests. */ export async function buildAndSpawnQemu(state: MachineState, config: QemuLaunchConfig): Promise<{ pid: number; qemuArgs: string[] }> { + // The run markers describe one QEMU process. A new one is never paused and is + // frozen only when launched so; set them before any path can record its pid + // (the still-running spawn failure saves it) or save the record (foreground exit). + state.paused = undefined; + state.frozen = config.frozen ? true : undefined; // The previous launch's paths: a reservation rolled back below restores them, so the // last capture that exists stays discoverable. const prior = state.networks.map((n) => n.captureFile); @@ -957,10 +962,13 @@ function setRunMarkers(state: MachineState, markers: { frozen?: true | undefined /** Refuse a guest operation on a paused machine (#375): the guest cannot answer * until `continue()`, so the request would only wait out its own timeout. Reads the - * record on disk, since another process (`quickchr pause`) may have paused it after - * this handle was made. */ -function assertNotPaused(state: MachineState, operation: string): void { - const paused = loadMachine(state.name)?.paused ?? state.paused; + * record on disk, since another process (`quickchr pause`, `quickchr continue`) may + * have changed it after this handle was made. */ +export function assertNotPaused(state: MachineState, operation: string): void { + // The record wins in both directions: another process may have paused the + // machine, or resumed one this handle saw paused. + const fresh = loadMachine(state.name); + const paused = fresh ? fresh.paused === true : state.paused === true; if (!paused) return; throw new QuickCHRError( "MACHINE_PAUSED", @@ -1274,6 +1282,28 @@ export async function readFaults(state: MachineState): Promise { + const reply = await monitorCommand(state.machineDir, "info status", undefined, state.portBase, { requirePrompt: true }); + const match = /VM status:\s*(running|paused)/i.exec(reply); + if (!match) { + throw new QuickCHRError("PROCESS_FAILED", `QEMU answered "info status" with "${reply.trim() || "(empty)"}" — cannot tell whether the guest is running.`); + } + return match[1]?.toLowerCase() === "running" ? "running" : "held"; +} + +/** One state-changing HMP command (`stop`, `cont`, `system_reset`). Success is an + * empty reply with the prompt back; a close before the prompt or any `error…` + * reply throws `PROCESS_FAILED`, with `label` naming the operation. */ +async function monitorMutation(state: MachineState, command: string, label: string): Promise { + const reply = (await monitorCommand(state.machineDir, command, undefined, state.portBase, { requirePrompt: true })).trim(); + if (/^error/i.test(reply)) { + throw new QuickCHRError("PROCESS_FAILED", `${label}: ${reply}`); + } +} + async function continueUnderLock(state: MachineState, wait: boolean, timeoutExtra?: number): Promise { const pid = state.pid; if (!pid || !isMachineRunning(state)) { @@ -1288,16 +1318,9 @@ async function continueUnderLock(state: MachineState, wait: boolean, timeoutExtr assertBootWaitReachable(state.networks, wait, state.name, "continue", `Resume it with 'quickchr continue ${shellQuote(state.name)} --no-wait' (wait: false).`); // Idempotent: gdb (or an earlier continue) may have resumed the guest already. - const status = await monitorCommand(state.machineDir, "info status", undefined, state.portBase); - if (!status.includes("running")) { - const contOut = await monitorCommand(state.machineDir, "cont", undefined, state.portBase); - // A QEMU-level `cont` error is the answer, not a cue to wait: the guest - // never resumed, so the marker stays and no boot wait is burned. Same - // /^error/i contract as savevm/loadvm/delvm. - if (/^error[:\s]/i.test(contOut)) { - throw new QuickCHRError("PROCESS_FAILED", `continue failed: ${contOut.trim() || "(empty)"}`); - } - } + // A QEMU-level `cont` error is the answer, not a cue to wait: the guest never + // resumed, so the marker stays and no boot wait is burned. + if (await guestRunState(state) === "held") await monitorMutation(state, "cont", "continue failed"); const wasFrozen = state.frozen === true; setRunMarkers(state, { frozen: undefined, paused: undefined }); if (!wait) return; @@ -1313,13 +1336,10 @@ async function pauseUnderLock(state: MachineState): Promise { } // Idempotent: a guest that is already held (an earlier pause, a frozen start, // a raw monitor `stop`) only gets the marker. - const status = await monitorCommand(state.machineDir, "info status", undefined, state.portBase); - if (status.includes("running")) { - const stopOut = await monitorCommand(state.machineDir, "stop", undefined, state.portBase); - // Same /^error/i contract as `cont`: the guest did not pause, so no marker. - if (/^error[:\s]/i.test(stopOut)) { - throw new QuickCHRError("PROCESS_FAILED", `pause failed: ${stopOut.trim() || "(empty)"}`); - } + // The marker is set only once QEMU has confirmed the guest is held. + if (await guestRunState(state) === "running") await monitorMutation(state, "stop", "pause failed"); + if (await guestRunState(state) !== "held") { + throw new QuickCHRError("PROCESS_FAILED", `pause failed: QEMU still reports machine "${state.name}" running after "stop".`); } setRunMarkers(state, { paused: true }); } @@ -1334,20 +1354,11 @@ async function resetUnderLock(state: MachineState, wait: boolean, timeoutExtra?: } assertBootWaitReachable(state.networks, wait, state.name, "reset", `Reset it with 'quickchr reset ${shellQuote(state.name)} --no-wait' (wait: false).`); - const resetOut = await monitorCommand(state.machineDir, "system_reset", undefined, state.portBase); - if (/^error[:\s]/i.test(resetOut)) { - throw new QuickCHRError("PROCESS_FAILED", `reset failed: ${resetOut.trim() || "(empty)"}`); - } + await monitorMutation(state, "system_reset", "reset failed"); // A reset of a held guest (paused, or frozen at -S) leaves it held in // `paused (prelaunch)` (#364). A power cycle always ends with RouterOS booting, // so resume it. - const status = await monitorCommand(state.machineDir, "info status", undefined, state.portBase); - if (!status.includes("running")) { - const contOut = await monitorCommand(state.machineDir, "cont", undefined, state.portBase); - if (/^error[:\s]/i.test(contOut)) { - throw new QuickCHRError("PROCESS_FAILED", `reset: the guest was reset but did not resume: ${contOut.trim() || "(empty)"}`); - } - } + if (await guestRunState(state) === "held") await monitorMutation(state, "cont", "reset: the guest was reset but did not resume"); const wasFrozen = state.frozen === true; setRunMarkers(state, { frozen: undefined, paused: undefined }); if (!wait) return; @@ -1355,7 +1366,8 @@ async function resetUnderLock(state: MachineState, wait: boolean, timeoutExtra?: } /** The REST-ready wait after `continue()` or `reset()`, with the same failure - * capture: a `BOOT_TIMEOUT` that preserves the (previously booted) machine. */ + * capture. A timeout is `BOOT_TIMEOUT`; after `continue()` the machine is stopped + * and preserved, after `reset()` QEMU is left running. */ async function waitAfterResume(state: MachineState, pid: number, wasFrozen: boolean, phase: "continue" | "reset", timeoutExtra?: number): Promise { const instance = createInstance(state); // The frozen launch's accelerator when recorded: detectAccel() prefers the @@ -1384,10 +1396,16 @@ async function waitAfterResume(state: MachineState, pid: number, wasFrozen: bool guestExec: guest?.exec, guestUser: guest?.users.join(" → "), }); + // A reset promises the same QEMU and its links, so a slow reboot leaves both up: + // stopping it would turn the in-place power cycle into a cable pull on every peer. + const cleanup = phase === "reset" + ? ` QEMU (PID ${pid}) and its links were left running — wait on it with \`quickchr list ${shellQuote(state.name)}\` or a REST probe, ` + + `reset it again, or stop it with \`quickchr stop ${shellQuote(state.name)}\`.` + : await cleanupAfterBootFailure(instance, state.name, failure, { kind: "preserve-existing" }); throw new QuickCHRError( "BOOT_TIMEOUT", `CHR did not respond within ${bootTimeout / 1000}s (accel=${accel}) after ${phase}.` + - await cleanupAfterBootFailure(instance, state.name, failure, { kind: "preserve-existing" }) + + cleanup + `\n${failure.summary}`, ); } @@ -2268,8 +2286,11 @@ function createInstance(state: MachineState): ChrInstance { throw new QuickCHRError("MACHINE_STOPPED", `Machine "${state.name}" must be running to load a snapshot.`); } + // A guest held before the load (pause(), --frozen) stays held if it fails. + const wasHeld = await guestRunState(state) === "held"; const out = await monitorCommand(state.machineDir, `loadvm ${name}`, MONITOR_LOADVM_TIMEOUT_MS, state.portBase); if (/^error[:\s]/i.test(out)) { + if (wasHeld) throw new QuickCHRError("PROCESS_FAILED", `loadvm failed: ${out.trim()}`); // A failed loadvm leaves the VM in "paused (restore-vm)" — resume // it so the guest isn't wedged (REST dead) on top of the error. try { @@ -4339,6 +4360,8 @@ export class QuickCHR { // See the same branch in start(): QEMU has exited, so the endpoint goes back. unregisterSocketMembers(state); state.status = "stopped"; + state.pid = undefined; + state.frozen = undefined; state.lastStartedAt = new Date().toISOString(); saveMachine(state); unpersistedSocketClaim = undefined; diff --git a/test/integration/pause-reset.test.ts b/test/integration/pause-reset.test.ts index 1fa00168..f7e12431 100644 --- a/test/integration/pause-reset.test.ts +++ b/test/integration/pause-reset.test.ts @@ -140,9 +140,13 @@ describe.skipIf(SKIP)("pause / continue / reset (#375)", () => { expect(await bootMark(b)).toBe("nothing"); expect(await waitReplies(a, B_ADDR, 3)).toBe(3); - // Reset of a paused machine resumes it and clears the marker. + // Reset of a paused machine reboots it (RAM state gone), resumes it and + // clears the marker — a bare `cont` would keep the RAM value. + await run(b, ":global quickchrBootMark \"set\""); + expect(await bootMark(b)).toBe("str"); await b.pause(); await b.reset(); + expect(await bootMark(b)).toBe("nothing"); expect(b.state.paused).toBeFalsy(); expect(QuickCHR.get(B)?.state.paused).toBeFalsy(); expect(b.state.pid).toBe(pid); diff --git a/test/unit/cli-pause-reset.test.ts b/test/unit/cli-pause-reset.test.ts index a2bd3c0b..b0f96686 100644 --- a/test/unit/cli-pause-reset.test.ts +++ b/test/unit/cli-pause-reset.test.ts @@ -124,6 +124,33 @@ describe("pause / reset argument handling", () => { expect(result.stderr).toContain("MACHINE_PAUSED"); }); + test("qga on a paused machine fails fast with MACHINE_PAUSED", async () => { + const started = Date.now(); + const result = await runQuickchr(["qga", "hung", "ping", "--timeout", "5"]); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain("MACHINE_PAUSED"); + expect(Date.now() - started).toBeLessThan(4_000); + }); + + test("get reports the pause instead of attempting live reads", async () => { + const started = Date.now(); + const json = JSON.parse((await runQuickchr(["get", "hung", "--json"])).stdout) as Record; + expect(json["paused"]).toBe(true); + expect(String(json["note"])).toContain("quickchr continue hung"); + const text = await runQuickchr(["get", "hung"]); + expect(text.exitCode).toBe(0); + expect(text.stdout).toContain("(running, paused)"); + expect(Date.now() - started).toBeLessThan(4_000); + }); + + test("a missing --timeout-extra / -T value is refused before anything is reset", async () => { + for (const args of [["reset", "hung", "--no-wait", "--timeout-extra"], ["reset", "hung", "-T"], ["reset", "hung", "-T", "--no-wait"], ["continue", "hung", "-T"]]) { + const result = await runQuickchr(args); + expect({ args, exitCode: result.exitCode }).toEqual({ args, exitCode: 1 }); + expect(result.stderr).toContain("needs a value"); + } + }); + test("help documents the verbs and continue names pause", async () => { expect((await runQuickchr(["pause", "--help"])).stdout).toContain("quickchr continue"); expect((await runQuickchr(["reset", "--help"])).stdout).toContain("system_reset"); @@ -165,6 +192,10 @@ describe("reset options (mocked QuickCHR boundary)", () => { await cmdReset(["lab", "-T", "15"]); await cmdReset(["lab", "--no-wait"]); expect(seen).toEqual([{ wait: true, timeoutExtra: 15_000 }, { wait: false, timeoutExtra: 0 }]); + let called = false; + spyOn(QuickCHR, "get").mockImplementation(() => ({ name: "lab", state: { name: "lab" }, reset: async () => { called = true; } }) as never); + await expect(cmdReset(["lab", "--timeout-extra"])).rejects.toMatchObject({ code: "INVALID_ARGUMENT" }); + expect(called).toBe(false); expect(lines[0]).toContain("PID 4242"); }); diff --git a/test/unit/pause-reset.test.ts b/test/unit/pause-reset.test.ts index 10ef754c..ab8b5b70 100644 --- a/test/unit/pause-reset.test.ts +++ b/test/unit/pause-reset.test.ts @@ -2,7 +2,7 @@ import { describe, test, expect, beforeEach, afterEach } from "bun:test"; import { mkdirSync, rmSync } from "node:fs"; import { join } from "node:path"; import { createServer, type Server } from "node:net"; -import { QuickCHR } from "../../src/lib/quickchr.ts"; +import { buildAndSpawnQemu, QuickCHR } from "../../src/lib/quickchr.ts"; import { loadMachine, saveMachine } from "../../src/lib/state.ts"; import type { MachineState } from "../../src/lib/types.ts"; @@ -57,6 +57,9 @@ afterEach(() => { type RunState = "running" | "paused" | "prelaunch"; +/** Reply override that closes the socket after the command, before QEMU's prompt. */ +const CLOSE = "__close__"; + /** A QEMU monitor stand-in that tracks the guest's run state the way HMP does. */ async function fakeMonitor(machineDir: string, initial: RunState, overrides: Record = {}) { const vm = { state: initial, commands: [] as string[] }; @@ -66,6 +69,10 @@ async function fakeMonitor(machineDir: string, initial: RunState, overrides: Rec const command = data.toString().trim(); vm.commands.push(command); let reply = overrides[command]; + if (reply === CLOSE) { + sock.end(`${command}\n`); + return; + } if (reply === undefined) { reply = ""; if (command === "info status") reply = vm.state === "running" ? "VM status: running" : vm.state === "paused" ? "VM status: paused" : "VM status: paused (prelaunch)"; @@ -133,6 +140,35 @@ describe("pause()", () => { } }); + for (const [label, overrides] of [ + ["a monitor that closes before answering stop", { stop: CLOSE }], + ["an unrecognised info status reply", { "info status": "Error: unavailable" }], + ["an ERROR… reply without a colon", { stop: "ERROR_REJECTED" }], + ] as const) { + test.skipIf(!POSIX)(`${label} is PROCESS_FAILED and sets no marker`, async () => { + saveMachine(machine("p-strict")); + const { server } = await fakeMonitor(join(TEST_DIR, "machines", "p-strict"), "running", overrides); + try { + await expect(get("p-strict").pause()).rejects.toMatchObject({ code: "PROCESS_FAILED" }); + expect(loadMachine("p-strict")?.paused).toBeUndefined(); + } finally { + await closeServer(server); + } + }); + } + + test.skipIf(!POSIX)("a stop QEMU acknowledges but does not apply sets no marker", async () => { + saveMachine(machine("p-ignored")); + // `stop` answers with the prompt, but the guest keeps running. + const { server } = await fakeMonitor(join(TEST_DIR, "machines", "p-ignored"), "running", { stop: "" }); + try { + await expect(get("p-ignored").pause()).rejects.toMatchObject({ code: "PROCESS_FAILED", message: expect.stringContaining("still reports") }); + expect(loadMachine("p-ignored")?.paused).toBeUndefined(); + } finally { + await closeServer(server); + } + }); + test("a dead pid is MACHINE_STOPPED and leaves clean state", async () => { saveMachine(machine("p-dead", { pid: 999_999_999, paused: true })); await expect(get("p-dead").pause()).rejects.toMatchObject({ code: "MACHINE_STOPPED" }); @@ -168,6 +204,15 @@ describe("continue() after pause()", () => { await expect(stale.rest("/system/resource")).rejects.toMatchObject({ code: "MACHINE_PAUSED" }); await stale.continue({ wait: false }); expect(loadMachine("c-stale")?.paused).toBeUndefined(); + + // Reverse: a handle that saw the marker must not keep refusing once + // another handle has resumed the machine. + const sawPaused = get("c-stale"); + await sawPaused.pause(); + expect(sawPaused.state.paused).toBe(true); + await get("c-stale").continue({ wait: false }); + const err = await sawPaused.qga("guest-ping").then(() => undefined, (e: unknown) => e); + expect((err as { code?: string } | undefined)?.code).not.toBe("MACHINE_PAUSED"); } finally { await closeServer(server); } @@ -193,8 +238,7 @@ describe("reset()", () => { const { vm, server } = await fakeMonitor(join(TEST_DIR, "machines", "r-run"), "running"); try { await get("r-run").reset({ wait: false }); - expect(vm.commands).toContain("system_reset"); - expect(vm.commands).not.toContain("cont"); + expect(vm.commands).toEqual(["system_reset", "info status"]); expect(vm.state).toBe("running"); expect(loadMachine("r-run")?.pid).toBe(process.pid); } finally { @@ -208,7 +252,7 @@ describe("reset()", () => { try { const instance = get("r-paused"); await instance.reset({ wait: false }); - expect(vm.commands.indexOf("system_reset")).toBeLessThan(vm.commands.indexOf("cont")); + expect(vm.commands).toEqual(["system_reset", "info status", "cont"]); expect(vm.state).toBe("running"); expect(instance.state.paused).toBeUndefined(); expect(instance.state.frozen).toBeUndefined(); @@ -281,3 +325,61 @@ describe("stopping clears the paused marker", () => { expect(loadMachine("s-gone")?.paused).toBeUndefined(); }); }); + +describe("snapshot.load() on a paused machine", () => { + test.skipIf(!POSIX)("a failed loadvm leaves a paused guest paused and its marker set", async () => { + saveMachine(machine("snap-paused", { bootDiskFormat: "qcow2", paused: true })); + const { vm, server } = await fakeMonitor(join(TEST_DIR, "machines", "snap-paused"), "paused", { + "loadvm nope": "Error: Snapshot 'nope' does not exist", + }); + try { + await expect(get("snap-paused").snapshot.load("nope")).rejects.toMatchObject({ code: "PROCESS_FAILED" }); + expect(vm.commands).not.toContain("cont"); + expect(vm.state).toBe("paused"); + expect(loadMachine("snap-paused")?.paused).toBe(true); + } finally { + await closeServer(server); + } + }); + + test.skipIf(!POSIX)("a failed loadvm on a running guest still resumes it", async () => { + saveMachine(machine("snap-running", { bootDiskFormat: "qcow2" })); + const { vm, server } = await fakeMonitor(join(TEST_DIR, "machines", "snap-running"), "running", { + "loadvm nope": "Error: Snapshot 'nope' does not exist", + }); + try { + await expect(get("snap-running").snapshot.load("nope")).rejects.toMatchObject({ code: "PROCESS_FAILED" }); + expect(vm.commands).toContain("cont"); + } finally { + await closeServer(server); + } + }); +}); + +describe("a new QEMU spawn starts with fresh run markers", () => { + test("the previous process's markers are gone even when the spawn fails early", async () => { + const state = machine("spawn-fresh", { paused: true, frozen: true }); + // A capture directory inside the data dir is refused before anything spawns. + const networks = [{ specifier: "user" as const, id: "net0", capture: { start: "on" as const, dir: join(TEST_DIR, "inside") } }]; + state.networks = networks; + const err = await buildAndSpawnQemu(state, { + arch: "x86", machineDir: state.machineDir, bootDisk: { path: join(state.machineDir, "disk.img"), format: "raw" }, mem: 256, cpu: 1, + ports: {}, networks: networks.map((n) => ({ ...n })), background: false, portBase: state.portBase, accel: "tcg", + }).then(() => undefined, (e: unknown) => e); + expect((err as { code?: string }).code).toBe("INVALID_NETWORK"); + expect(state.paused).toBeUndefined(); + expect(state.frozen).toBeUndefined(); + }); + + test("a frozen launch records frozen, never paused", async () => { + const state = machine("spawn-frozen", { paused: true }); + const networks = [{ specifier: "user" as const, id: "net0", capture: { start: "on" as const, dir: join(TEST_DIR, "inside") } }]; + state.networks = networks; + await buildAndSpawnQemu(state, { + arch: "x86", machineDir: state.machineDir, bootDisk: { path: join(state.machineDir, "disk.img"), format: "raw" }, mem: 256, cpu: 1, + ports: {}, networks: networks.map((n) => ({ ...n })), background: true, portBase: state.portBase, accel: "tcg", frozen: true, + }).catch(() => undefined); + expect(state.paused).toBeUndefined(); + expect(state.frozen).toBe(true); + }); +}); diff --git a/test/unit/snapshot-budgets.test.ts b/test/unit/snapshot-budgets.test.ts index 80278fc0..b9cc59e6 100644 --- a/test/unit/snapshot-budgets.test.ts +++ b/test/unit/snapshot-budgets.test.ts @@ -52,6 +52,8 @@ mock.module("../../src/lib/channels.ts", () => ({ throw error; } if (command === "info snapshots") return LISTING; + // load() reads the run state first, so a failed loadvm can leave a held guest held (#375). + if (command === "info status") return "VM status: running"; return ""; }, channelPath: notStubbed("channelPath"), @@ -130,6 +132,7 @@ describe("snapshot monitor budgets (issue #80)", () => { await instance.snapshot.delete("snap1"); await instance.snapshot.list(); expect(calls.find((c) => c.command === "loadvm snap1")?.timeoutMs).toBe(MONITOR_LOADVM_TIMEOUT_MS); + expect(calls.map((c) => c.command)).toContain("info status"); expect(calls.find((c) => c.command === "delvm snap1")?.timeoutMs).toBe(MONITOR_DELVM_TIMEOUT_MS); // list() inherits the fast-query default — explicitly or by passing // undefined. Either way it must not take a snapshot-sized budget. From 0e7760ad18bffc344c205161283097fbe3060915 Mon Sep 17 00:00:00 2001 From: TIKOCI RouterOS Bots Date: Wed, 2 Dec 2026 05:38:35 -0800 Subject: [PATCH 3/3] docs(qemu): macOS/HVF first-pause caveat from the #375 grounding; test pause survives without a reboot - Morpheus (Intel Mac, HVF, QEMU 11.1.1): the first `stop` after a boot does not freeze guest time, and a first pause of 20 s or more crashes the guest kernel on `cont` (RouterOS reboots in the same QEMU). Later pauses freeze the clock as on KVM. Linux/KVM re-checked: a 30 s first pause straight after boot is clean. Documented in MANUAL and qemu.instructions; follow-up #377. - pause-reset integration: a RAM :global set before pause() must survive continue(), so a resume that came back through a reboot fails the test. Co-Authored-By: Claude Opus 5.5 --- .github/instructions/qemu.instructions.md | 14 +++++++++++--- CHANGELOG.md | 3 ++- MANUAL.md | 16 +++++++++++++--- test/integration/pause-reset.test.ts | 7 +++++-- 4 files changed, 31 insertions(+), 9 deletions(-) diff --git a/.github/instructions/qemu.instructions.md b/.github/instructions/qemu.instructions.md index d12b07c1..86aa1fb3 100644 --- a/.github/instructions/qemu.instructions.md +++ b/.github/instructions/qemu.instructions.md @@ -164,9 +164,17 @@ HMP `stop` holds the vCPUs; QEMU, its monitor and QGA, and every NIC's carrier s so a link peer sees a hung box, not a cable pull. Grounded on Linux/KVM, RouterOS 7.25.2, QEMU 11.1.2 (#364); quickchr exposes it as `pause()` / `quickchr pause` (#375). -- **The guest clock stops with it.** Uptime excludes the pause and the guest clock - falls behind by its length (51 s after a 50 s pause) until NTP corrects it. No - RouterOS watchdog reboot at 20, 50 or 60 s. +- **The guest clock stops with it (KVM).** Uptime excludes the pause and the guest + clock falls behind by its length (51 s after a 50 s pause) until NTP corrects it. + No RouterOS reboot at 20, 30, 50 or 60 s, including a 30 s pause straight after + boot (#375). +- **HVF (x86, Intel Mac, QEMU 11.1.1): the first `stop` after a boot does not freeze + guest time.** On the first `cont` the guest sees the whole pause at once: 3 and + 10 s were harmless, 20 and 30 s made the kernel fail and RouterOS reboot in the + same QEMU process (same PID, `kernel failure in previous boot`). Every later + `stop` in that boot froze the clock like KVM. Suspected: the TSC keeps counting + across the first stop under HVF and the jump trips the soft-lockup limit; + unconfirmed. Not tested on Apple Silicon/TCG. Follow-up: #377. - **SIGSTOP of QEMU is a different fault.** Guest time jumps forward on SIGCONT, and with RouterOS's default `/system/watchdog watchdog-timer=yes` a 20 s SIGSTOP rebooted RouterOS (`kernel failure in previous boot`); 5 s did not, nor did 20 s with diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b538bbb..9700ed33 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,7 +23,8 @@ odd/even-minor scheme chose the tag; it was retired in 0.5.1.) `shutdown` power-cuts immediately. `chr.reset()` / `quickchr reset [--no-wait] [-T ]` is an in-place power cycle (`system_reset`): same QEMU PID and sockets, RouterOS cold-boots, REST-ready by default; a paused or frozen guest is - resumed by it. + resumed by it. Known limitation: on macOS/HVF (x86), the first pause after a boot + that lasts 20 s or more makes the guest reboot on `continue` (#377). - One-way drop on a NIC that keeps carrier (#369): `chr.fault("ether3", { drop: "egress" | "ingress" | "both" })`, `null` to clear (and a batch form), and `quickchr diff --git a/MANUAL.md b/MANUAL.md index f1ddc1ec..dc7557ee 100644 --- a/MANUAL.md +++ b/MANUAL.md @@ -392,15 +392,25 @@ power-cuts immediately (the guest cannot act on `/system/shutdown`) and reports `forced`, and a failed `snapshot load` leaves the guest paused. What a paused guest and its peers see (grounded on Linux/KVM, RouterOS 7.25.2, -QEMU 11.1.2, #364; macOS/HVF in #375): +QEMU 11.1.2, #364 and #375; macOS/HVF on an Intel Mac in #375): - **The guest clock stops too.** Uptime excludes the pause, and the guest's clock falls behind by its length (51 s after a 50 s pause) until NTP corrects - it. RouterOS never sees the hang: no watchdog reboot at 20, 50 or 60 s. + it. On Linux/KVM RouterOS never sees the hang: no reboot at 20, 30, 50 or 60 s, + including a 30 s pause right after boot. +- **macOS/HVF (x86): keep the first pause after a boot under 10 s.** On HVF the + guest sees the whole length of the *first* pause after each boot pass at once + when it resumes. 3 and 10 s were harmless; at 20 and 30 s the guest kernel + failed on `continue` and RouterOS rebooted inside the same QEMU process (same + PID, `kernel failure in previous boot` in `/log`). `continue` still returns + success, after the reboot's REST wait. Every later pause in the same boot froze + the clock as on KVM (five 30 s pauses, no reboot). A short first pause (say + `pause`, then `continue` after a second) avoids it; follow-up in #377. - **A real hang does not stop the clock.** SIGSTOP of the QEMU process stands in for one, and with RouterOS's default `/system/watchdog watchdog-timer=yes`, a 20 s SIGSTOP made RouterOS reboot on resume (`kernel failure in previous boot`); - 5 s did not. `pause` never triggers this. (SIGSTOP also freezes the monitor and + 5 s did not. `pause` does not trigger this on Linux/KVM; see the HVF caveat + above. (SIGSTOP also freezes the monitor and QGA, and Windows has no equivalent; quickchr does not offer it.) - **Backpressure onto the peer.** On `dgram` and `listen-connect` links, the peer's NIC toward the paused machine stops transmitting once the socket buffer diff --git a/test/integration/pause-reset.test.ts b/test/integration/pause-reset.test.ts index f7e12431..d52d553b 100644 --- a/test/integration/pause-reset.test.ts +++ b/test/integration/pause-reset.test.ts @@ -104,7 +104,11 @@ describe.skipIf(SKIP)("pause / continue / reset (#375)", () => { expect(await waitReplies(a, B_ADDR, 3)).toBe(3); // Pause: B's guest stops, A's end of the link keeps carrier the whole time. + // The RAM mark set first must survive the pause: a resume that came back + // through a guest reboot (seen on macOS HVF after a long first pause) would + // still pass the REST check below. const pid = b.state.pid; + await run(b, ":global quickchrBootMark \"set\""); await b.pause(); expect(b.state.paused).toBe(true); expect(b.state.frozen).toBeFalsy(); @@ -129,11 +133,10 @@ describe.skipIf(SKIP)("pause / continue / reset (#375)", () => { expect(b.state.paused).toBeFalsy(); const resource = await b.rest("/system/resource") as Record; expect(String(resource["board-name"])).toContain("CHR"); + expect(await bootMark(b)).toBe("str"); expect(await waitReplies(a, B_ADDR, 3)).toBe(3); // Reset: same QEMU, RouterOS boots again (RAM state gone), disk config kept. - await run(b, ":global quickchrBootMark \"set\""); - expect(await bootMark(b)).toBe("str"); await b.reset(); expect(b.state.pid).toBe(pid); expect(QuickCHR.get(B)?.state.pid).toBe(pid);