From 595521a7091b0c13df9d7d1c9481b37d20ee0b7e Mon Sep 17 00:00:00 2001 From: TIKOCI RouterOS Bots Date: Tue, 1 Dec 2026 16:21:58 -0800 Subject: [PATCH 1/8] =?UTF-8?q?feat(network):=20one-way=20drop=20on=20a=20?= =?UTF-8?q?NIC=20that=20keeps=20carrier=20=E2=80=94=20fault()=20/=20set=20?= =?UTF-8?q?--fault=20(#369)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit chr.fault("ether3", { drop: "egress" | "ingress" | "both" }) / null, a batch form, and quickchr set --fault etherN=egress|ingress|both|none. QEMU filter-redirector into a null chardev, one filter + sink per port (fault, fault-sink), added at run time at the head of the NIC's filter chain, direction switched in place with qom-set queue, cleared with object_del + chardev-remove. State is read from QEMU (qom-get … queue), never persisted. Mirrors link(): etherN, validate-all-then-apply, machine lock (op fault), any HMP reply text is a failure, partial setup undone. Read-back: chr.faults(), list and list --json (faults). Also: nicForPort() shared by link/capture/fault; StartOptions.qemuArgs JSDoc and MANUAL say [] means "not given" (#370 option b). Co-Authored-By: Claude Opus 5.5 --- .github/instructions/qemu.instructions.md | 27 +- CHANGELOG.md | 10 + DESIGN.md | 44 ++ MANUAL.md | 54 ++- src/cli/flags.ts | 16 +- src/cli/index.ts | 65 ++- src/index.ts | 2 + src/lib/capture.ts | 11 +- src/lib/fault.ts | 202 +++++++++ src/lib/link.ts | 28 +- src/lib/lock.ts | 3 +- src/lib/quickchr.ts | 141 +++++++ src/lib/types.ts | 50 +++ test/integration/link-fault.test.ts | 149 +++++++ test/unit/fault.test.ts | 481 ++++++++++++++++++++++ 15 files changed, 1248 insertions(+), 35 deletions(-) create mode 100644 src/lib/fault.ts create mode 100644 test/integration/link-fault.test.ts create mode 100644 test/unit/fault.test.ts diff --git a/.github/instructions/qemu.instructions.md b/.github/instructions/qemu.instructions.md index 1a0cfb01..2891b6a6 100644 --- a/.github/instructions/qemu.instructions.md +++ b/.github/instructions/qemu.instructions.md @@ -239,7 +239,32 @@ from `net/filter*.c` (QEMU master and 11.1.2) and `test/lab/link-impairment/REPO and QEMU logs nothing. `status` and `queue` switch it at run time. It is 100 % or nothing. Give each filter its own `null` chardev with a unique id: QEMU 11.1.2 refuses a second redirector on a chardev already in use. One port's both-ways blackhole needs only one - filter and sink (`queue=all`). + filter and sink (`queue=all`). quickchr exposes it as `fault()` / `set --fault` (#369): + `chardev-add null,id=fault-sink`, then + `object_add filter-redirector,id=fault,netdev=net,queue=rx|tx|all,outdev=fault-sink,position=head`, + with direction changes done by `qom-set /objects/fault queue …`, and clearing by + `object_del` and then `chardev-remove`. +- **HMP replies for the filter and chardev commands** (QEMU 11.1.2): success is an empty + reply for `chardev-add`, `object_add`, `qom-set`, `object_del` and `chardev-remove`. + Refusals are one `Error: …` line: a duplicate id is `attempt to add duplicate property + '' to object (type 'container')` (chardevs and objects have separate namespaces); + an unknown netdev is `Parameter 'netdev' expects a network backend id`; removing a + chardev a filter still uses is `Chardev '' is busy`; a missing one is `Chardev + '' not found` or `object '' not found`. `qom-get /objects/ queue` prints the + value as JSON (`"rx"`), or `Device '/objects/' not found`. `qom-list /objects` + and `qom-list /chardevs` print ` (child)` / + ` (child)` lines. +- **Filter order: the head is the wire side.** QEMU walks a netdev's filters head to tail + for frames delivered to the guest and tail to head for frames the guest sends. + `info network` lists each netdev's filters in chain order, with `position=` and + `queue=`. Filters from `-object` exist before any `object_add`, which appends at the tail + unless given `position=head` (or `position=id=,insert=before|behind`). Measured + with a boot `filter-dump` and an `object_add`ed `position=head` blackhole on one NIC + (QEMU 11.1.2, KVM, CHR 7.25.2): the capture held the LACPDUs the guest sent into an + egress drop, and none of the peer's under an ingress drop + (`test/integration/link-fault.test.ts`). +- **`info network` doesn't show carrier.** After `set_link off` its netdev line is + unchanged (QEMU 11.1.2), so HMP has no read-back for link state. - **A `filter-redirector` loop is QEMU's only per-frame hook.** `outdev` writes each frame to a socket chardev (4-byte big-endian length + frame, the `stream` netdev framing) and consumes it; `indev` reads frames back and sends them on from the filter's position. Use diff --git a/CHANGELOG.md b/CHANGELOG.md index 5c72e853..8909f918 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,16 @@ odd/even-minor scheme chose the tag; it was retired in 0.5.1.) ### Added +- 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 + dropped while both ends keep `running=yes`, as with a half-failed optic. `link()` + can't make that fault. QEMU's `filter-redirector` into a `null` chardev is added + and removed at run time, with no root, helper process or reboot, and nothing is + persisted. `chr.faults()`, `list ` and `list --json` (`faults`) read the + faults in place back from QEMU. A capture on the same NIC shows the guest's side of + the drop. + - Per-NIC packet capture (#338) with QEMU's `filter-dump`: a NIC option `capture: true | { start?: "on" | "off"; dir?: string }` (CLI `--add-network ,capture=on|off,capture-dir=`), set at creation and persisted. Every QEMU diff --git a/DESIGN.md b/DESIGN.md index 0025b827..b975de42 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1274,6 +1274,50 @@ spans and `loadvm` still shift the virtual clock (R2); that is documented, not c because the only fix is re-creating the filter, which truncates it. Analysis helpers stay out of quickchr (`tikoci/tzsp-sniff`). +### A NIC fault is a filter added at run time, at the head of the chain (#369) + +`fault()` / `set --fault` is a typed front for the blackhole that #339's research +found (`test/lab/link-impairment/REPORT.md`): a `filter-redirector` with only an +`outdev`, on a `null` chardev. It drops every frame one way and leaves carrier up on +both ends, which `link()` can't do. It follows `link()` in everything else: `etherN` +addressing, validate-all-then-apply, the machine lock (op `fault`), any HMP reply text +is a failure, the first failure stops the batch and names what applied, nothing +persisted, and refused next to other `set` flags. + +**One filter and one sink per port, switched in place.** `fault` on netdev `net`, +with its own chardev `fault-sink` (a chardev takes one frontend). The direction is +the filter's `queue` (`egress`=`rx`, `ingress`=`tx`, `both`=`all`, named from the +netdev's side), and `qom-set … queue` changes it per frame. So egress → both is one +command with no moment where frames pass, and a port never has two filters to keep +consistent. Clearing is `object_del` and then `chardev-remove`. + +**State is read from QEMU, never stored.** Each port's change starts with +`qom-get /objects/fault queue`: a value is the drop in place, and QEMU's +`Device … not found` means none. The plan from there is zero to three commands, so a +repeat is a no-op. A sink left behind by an earlier failure (`qom-list /chardevs`) is +removed before a new one is added. A filter QEMU refuses after its sink was added gets +the sink removed again. A clear whose sink QEMU keeps reports that the drop itself is +gone. `faults()` and `list ` read the same query for every NIC. HMP has no read-back +for carrier (`info network` doesn't show `set_link`), so status says "carrier +untouched", not "up". + +**Added at run time, unlike capture.** A capture filter is never `object_add`ed +because its timestamps would take a different base (#338). A drop has no such +property, and a fault that existed from boot would need persisted desired state (#58). + +**At the head of the chain, so a capture is the guest's view.** QEMU walks a netdev's +filters head to tail for frames delivered to the guest and tail to head for frames it +sends, so the head is the wire side. Boot filters (`cap`) are created first, and +`object_add` appends at the tail by default, which would have put the drop between the +guest and its capture: egress drops invisible, ingress drops captured. `position=head` +puts it on the wire side. A capture then shows what the guest sent, dropped or not, and +only what reached it, like a mirror port on the guest. The far end's capture shows what +crossed. `test/integration/link-fault.test.ts` checks both directions. + +**Only the blackhole.** Partial loss, delay, jitter and rate need a process outside +QEMU, which would be its own repo (decided 2026-12-01 on #369). `filter-buffer` and +virtio-net `tx=timer` were rejected in the research. + ### Background is not detachment, and `--bg` never claimed to be `spawnQemu()` backgrounds QEMU and calls `unref()`. That is enough for the parent to diff --git a/MANUAL.md b/MANUAL.md index b70a87ff..91bd2f83 100644 --- a/MANUAL.md +++ b/MANUAL.md @@ -650,6 +650,8 @@ flags that were asked for so it can be run as given. | `--receive ` | Reserve a guest→host receive port (repeatable). Running or stopped; no restart. §7 "Receive slots". | | `--no-receive ` | Drop a receive slot by name (repeatable). Applied before `--receive`. | | `--link =up\|down` | Drop or restore carrier on this machine's own NIC (repeatable). Running only; not combinable with the other flags. §7 "Link state". | +| `--capture =on\|off` | Switch packet capture on a NIC created with `capture` (repeatable). Running only; not combinable with the other flags. §7 "Packet capture". | +| `--fault =egress\|ingress\|both\|none` | Drop every frame one way (or both) on this machine's NIC, with carrier kept up; `none` clears it (repeatable). Running only; not combinable with the other flags. §7 "Faults that keep carrier". | **Device-mode restarts the machine.** RouterOS only applies a device-mode change across a power cycle, and quickchr owns the power button — which is why this lives @@ -1158,7 +1160,7 @@ redact before logging or attaching to bug reports. | `installDeps` | boolean | — | **Deprecated, ignored.** Never installed anything; run `quickchr doctor` for install hints | | `dryRun` | boolean | `false` | Print QEMU command and exit | | `timeoutExtra` | number | `0` | Extra **milliseconds** added to boot timeout | -| `qemuArgs` | string[] | — | Extra QEMU argv elements, one entry each, appended verbatim last. Recorded by `add()`; a `start()` value replaces stored args for that boot only | +| `qemuArgs` | string[] | — | Extra QEMU argv elements, one entry each, appended verbatim last. Recorded by `add()`; a `start()` value replaces stored args for that boot only. `[]` means not given, so the stored args are used; `set --clear-qemu-args` drops them (#370) | | `frozen` | boolean | `false` | Boot frozen at reset with a gdbstub; resume with `continue()`. Refused with provisioning or `background: false` | | `onProgress` | `(msg) => void` | `console.log` | `[debug]` lines only when `QUICKCHR_DEBUG=1` | @@ -1650,6 +1652,9 @@ quickchr list sw1 --json | jq .captures # { "ether2": "/…/caps/sw1-ether2-2 What a capture shows, and doesn't: +- **A NIC with a fault (`--fault`) captures from the guest's side of it**: what + the guest sent, dropped or not, and only what actually reached it. Capture the + far end to see what crossed. - **A NIC whose link is down captures nothing**, in either direction: QEMU drops the frame before the filter. A silent member (`set --link etherN=down`) shows in its far end's capture, where its peer's frames keep going out. @@ -1752,6 +1757,53 @@ await chr.link({ ether2: "up", ether3: "down" }); `examples/mlag/` uses both forms for its cable pulls and silent members. +### Faults that keep carrier (`set --fault`, `fault()`) + +Drop every frame one way, or both ways, on a running machine's own NIC while +carrier stays up on both ends: a half-failed optic or SFP. `--link` can't make +that fault, because it drops carrier. It is QEMU's `filter-redirector` into a +`null` chardev, added and removed over the monitor, with no root, helper +process or reboot: + +```sh +quickchr set lab-a --fault ether3=egress # frames lab-a sends on ether3 vanish +quickchr set lab-a --fault ether3=both --fault ether2=ingress +quickchr set lab-a --fault ether3=none --fault ether2=none # clear +quickchr list lab-a # Fault: ether3 dropping egress (carrier untouched) +``` + +```ts +await chr.fault("ether3", { drop: "egress" }); +await chr.fault({ ether3: { drop: "both" }, ether2: null }); // null clears +await chr.faults(); // { ether3: { drop: "both" } } +``` + +- **Directions are named from the guest.** `egress` is what this machine sends + on the port, `ingress` what is delivered to it, `both` is both. Ports are + `etherN`, as for `--link`. +- **Nothing tells either end.** Both keep `running=yes`, RouterOS logs nothing, + and only protocol timeouts notice. With an egress drop on one member of an + 802.3ad bond (`lacp-rate=1sec`), the far end took the member out of its bond + within 3–8 s (local KVM and CI runners), and the near end followed a few seconds + later once the far end's LACPDUs reported it out of sync. Clearing the drop + brought both back within about 2 s. +- **All or nothing.** Every frame in that direction is dropped. QEMU can't drop + a percentage, delay or rate-limit frames on its own (`test/lab/link-impairment/REPORT.md`). +- **After an `ingress` or `both` drop is cleared**, the first few frames can + still be lost while the peer re-resolves ARP: its requests went unanswered + during the drop. +- **Changes are in place.** Setting a port to what it has is a no-op, and a + change of direction switches the same filter, so frames don't get through in + between. `list ` (and `faults` in `list --json`) reads them back from QEMU. +- **Runtime only.** Nothing is saved. A new QEMU launch (`start`, or a + device-mode power cycle) starts with no fault; a guest reboot inside the same + QEMU keeps it. `--fault` can't be combined with the other `set` flags. +- **A capture on the same NIC shows the guest's side** (§ "Packet capture"): + what the guest sent, dropped or not, and only what reached it. +- **Validated first, then applied in order**, under the machine lock, like + `--link`. A failure stops the batch and names the ports already changed. If + QEMU refuses part of one port's setup, that part is undone. + ### Named L2 sockets `quickchr networks sockets create lab-sw1` registers a link in diff --git a/src/cli/flags.ts b/src/cli/flags.ts index f44022f2..387d09eb 100644 --- a/src/cli/flags.ts +++ b/src/cli/flags.ts @@ -45,7 +45,7 @@ const SET_ONLY_FLAGS = [ "device-mode", "device-mode-enable", "device-mode-disable", "qemu-arg", "clear-qemu-args", "receive", "no-receive", - "link", "capture", + "link", "capture", "fault", ] as const; export const ADD_FLAGS: readonly string[] = CREATE_FLAGS; @@ -90,8 +90,8 @@ export const VALUE_FLAGS: ReadonlySet = new Set([ "qemu-arg", // exec / qga / console "via", "user", "password", "timeout", "path", "data", "script", - // set --license / --package / --receive / --link / --capture - "account", "account-file", "password-file", "level", "package", "no-receive", "link", "capture", + // set --license / --package / --receive / --link / --capture / --fault + "account", "account-file", "password-file", "level", "package", "no-receive", "link", "capture", "fault", // networks sockets create "mode", "port", "group", // completions / logs @@ -141,7 +141,7 @@ export function identityFlagError(argv: readonly string[]): string | undefined { } /** Every occurrence of a repeatable `=` flag, in order, read from the raw - * arguments: `--link` (#334) and `--capture` (#338). + * arguments: `--link` (#334), `--capture` (#338) and `--fault` (#369). * * `parseFlags` merges repeats, and a bare occurrence (`true`) or `--no-` (`false`) * is overwritten by any later valued one — so `--link ether2 --link --link ether3=up` @@ -150,9 +150,13 @@ export function identityFlagError(argv: readonly string[]): string | undefined { * next argument unless it starts with `--`. Stops at `--`. */ export function portAssignmentFlagValues( argv: readonly string[], - name: "link" | "capture", + name: "link" | "capture" | "fault", ): { values: string[]; error?: string | undefined } { - const example = name === "link" ? { form: "=up|down", sample: "ether2=down", up: "ether2=up" } : { form: "=on|off", sample: "ether2=on", up: "ether2=on" }; + const example = { + link: { form: "=up|down", sample: "ether2=down", up: "ether2=up" }, + capture: { form: "=on|off", sample: "ether2=on", up: "ether2=on" }, + fault: { form: "=egress|ingress|both|none", sample: "ether3=egress", up: "ether3=none" }, + }[name]; const values: string[] = []; for (let i = 0; i < argv.length; i++) { const arg = argv[i]; diff --git a/src/cli/index.ts b/src/cli/index.ts index d63e1378..6af0f6e7 100755 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -3,7 +3,7 @@ * quickchr CLI entry point — command router. */ -import type { StartOptions, Arch, Channel, DeviceModeOptions, LicenseLevelInput, LicenseOptions, LinkState, CaptureState, ServiceName, NetworkInput, ReceivePort } from "../lib/types.ts"; +import type { StartOptions, Arch, Channel, DeviceModeOptions, LicenseLevelInput, LicenseOptions, LinkState, CaptureState, NicFault, ServiceName, NetworkInput, ReceivePort } from "../lib/types.ts"; import { join } from "node:path"; import { credentialInput } from "../lib/credential-input.ts"; import { licenseCredentialInputs } from "../lib/credentials.ts"; @@ -1829,6 +1829,7 @@ async function cmdList(argv: string[] = []) { if (name) { const { statusIcon, bold, dim, link, formatPorts, formatReceive, formatNetworks, machineNotFoundMessage, resolveDisplayCredentials, formatRestUrl, formatSshCommand } = await import("./format.ts"); const { captureFilesOf } = await import("../lib/capture.ts"); + const { describeDrop } = await import("../lib/fault.ts"); const instance = QuickCHR.get(name); if (!instance) { @@ -1838,6 +1839,16 @@ async function cmdList(argv: string[] = []) { const s = instance.state; const foreign = isMachineForeign(s); + // Faults live only in the running QEMU (#369). `null` when it can't be asked + // (another user's QEMU, a monitor that doesn't answer); a stopped machine has none. + let faults: Record | null = {}; + if (s.status === "running") { + try { + faults = foreign ? null : await instance.faults(); + } catch { + faults = null; + } + } if (asJson) { const creds = s.status === "running" ? await resolveDisplayCredentials(s) : null; @@ -1850,6 +1861,7 @@ async function cmdList(argv: string[] = []) { mem: s.mem, networks: s.networks, captures: captureFilesOf(s.networks), + faults, ports: s.ports, receivePorts: s.receivePorts ?? [], pid: s.pid ?? null, @@ -1872,6 +1884,8 @@ async function cmdList(argv: string[] = []) { console.log(` Ports: ${formatPorts(s.ports)}`); if (s.receivePorts?.length) console.log(` Receive: ${formatReceive(s.receivePorts)}`); for (const [port, file] of Object.entries(captureFilesOf(s.networks))) console.log(` Capture: ${port} → ${file}`); + if (faults === null) console.log(` Faults: ${dim("unknown (QEMU's monitor could not be asked)")}`); + for (const [port, f] of Object.entries(faults ?? {})) console.log(` Fault: ${port} ${describeDrop(f.drop)} (carrier untouched)`); console.log(` Status: ${s.status}${s.pid ? ` (PID ${s.pid}${foreign ? ", owned by another user" : ""})` : ""}`); if (s.frozen) { console.log(` Frozen: yes — awaiting quickchr continue`); @@ -2341,7 +2355,7 @@ async function cmdSet(argv: string[]) { // --license` printed a usage error while `quickchr license --name lab` worked. const name = positional[0] ?? flag(flags, "name"); - const usage = "Usage: quickchr set [--license [--level=p1|p10|p-unlimited]] [--package [,...]] [--device-mode ] [--device-mode-enable ] [--device-mode-disable ] [--qemu-arg ] [--clear-qemu-args] [--receive ] [--no-receive ] | quickchr set --link =up|down [--link ...] | quickchr set --capture =on|off [--capture ...]"; + const usage = "Usage: quickchr set [--license [--level=p1|p10|p-unlimited]] [--package [,...]] [--device-mode ] [--device-mode-enable ] [--device-mode-disable ] [--qemu-arg ] [--clear-qemu-args] [--receive ] [--no-receive ] | quickchr set --link =up|down [--link ...] | quickchr set --capture =on|off [--capture ...] | quickchr set --fault =egress|ingress|both|none [--fault ...]"; if (!name) { console.error(usage); process.exit(1); @@ -2391,11 +2405,15 @@ async function cmdSet(argv: string[]) { if (linkScan.error) throw new QuickCHRError("INVALID_ARGUMENT", linkScan.error); const captureScan = portAssignmentFlagValues(argv, "capture"); if (captureScan.error) throw new QuickCHRError("INVALID_ARGUMENT", captureScan.error); + const faultScan = portAssignmentFlagValues(argv, "fault"); + if (faultScan.error) throw new QuickCHRError("INVALID_ARGUMENT", faultScan.error); const linkValues = linkScan.values; const { parseLinkAssignments } = await import("../lib/link.ts"); const { parseCaptureAssignments } = await import("../lib/capture.ts"); + const { parseFaultAssignments } = await import("../lib/fault.ts"); const parsedLinks = linkValues.length > 0 ? parseLinkAssignments(linkValues) : undefined; const parsedCaptures = captureScan.values.length > 0 ? parseCaptureAssignments(captureScan.values) : undefined; + const parsedFaults = faultScan.values.length > 0 ? parseFaultAssignments(faultScan.values) : undefined; if (linkValues.length > 0) { const links = parsedLinks ?? {}; // A runtime carrier fault stays clear of reboots and stopped-only changes: a @@ -2422,8 +2440,19 @@ async function cmdSet(argv: string[]) { return; } + // --fault (#369): runtime only and on its own, like --link: a new QEMU starts with + // no fault, so a power cycle in the same call would silently undo it. + if (parsedFaults) { + const others = SET_FLAGS.filter((key) => key !== "fault" && key !== "name" && key in flags).map((key) => `--${key}`); + if (others.length > 0) { + throw new QuickCHRError("INVALID_ARGUMENT", `--fault cannot be combined with ${others.join(", ")}: run them as separate 'quickchr set' calls.`); + } + await applyFaultChange(name, parsedFaults); + return; + } + if (!wantsLicense && !deviceMode && packages.length === 0 && !wantsQemuArgs && !wantsReceive) { - console.error("Nothing to set. Available flags: --license, --package, --device-mode, --device-mode-enable, --device-mode-disable, --qemu-arg, --clear-qemu-args, --receive, --no-receive, --link, --capture"); + console.error("Nothing to set. Available flags: --license, --package, --device-mode, --device-mode-enable, --device-mode-disable, --qemu-arg, --clear-qemu-args, --receive, --no-receive, --link, --capture, --fault"); process.exit(1); } @@ -2484,6 +2513,23 @@ async function applyCaptureChange(name: string, captures: Record --fault etherN=egress|ingress|both|none…` (#369): drop frames one way + * (or both) on this machine's NICs with carrier kept up, through `ChrInstance.fault()`. + * Runtime only. */ +async function applyFaultChange(name: string, faults: Record) { + const { QuickCHR } = await import("../lib/quickchr.ts"); + const { bold, machineNotFoundMessage } = await import("./format.ts"); + const { formatFaultChanges, normalizeFaultChanges } = await import("../lib/fault.ts"); + + const instance = QuickCHR.get(name); + if (!instance) { + console.error(machineNotFoundMessage(name)); + process.exit(1); + } + await instance.fault(faults); + console.log(`Fault on ${bold(name)}: ${formatFaultChanges(normalizeFaultChanges(faults))}`); +} + /** `set --qemu-arg…` — the recovery route for recorded passthrough. * * Boot config, not provisioning: it takes effect on the next start, so the @@ -4400,6 +4446,11 @@ Flags: Switch packet capture on a NIC created with capture (repeatable). Running only; cannot be combined with the other flags. + --fault =egress|ingress|both|none + Drop every frame one way (or both) on this machine's NIC + while carrier stays up on both ends; none clears it + (repeatable). Running only; cannot be combined with the + other flags. Capture notes: Only a NIC created with ,capture=on|off (or capture-dir=) has a capture filter; @@ -4408,6 +4459,14 @@ Capture notes: in the capture-dir. quickchr list --json shows each NIC's captureFile. Example: quickchr set lab --capture ether2=on --capture ether3=on +Fault notes: + egress is what this machine sends on the port, ingress what it receives. Carrier + stays up and nothing is logged, so only protocol timeouts notice: a half-failed + optic, where --link is a pulled cable. Nothing is recorded (the next start has no + fault); quickchr list shows the faults in place. After an ingress or both + drop is cleared, the first frames can still be lost while the peer re-resolves ARP. + Example: quickchr set lab --fault ether3=egress (later: --fault ether3=none) + Link notes: is the NIC's default RouterOS name, etherN (ether1 is the first --add-network), even if RouterOS renamed it. Only this machine's end changes: diff --git a/src/index.ts b/src/index.ts index 24976a7a..62e24b43 100644 --- a/src/index.ts +++ b/src/index.ts @@ -55,6 +55,8 @@ export type { LinkState, CaptureState, NicCaptureOptions, + FaultDrop, + NicFault, MachineConfig, MachineState, NicDuplex, diff --git a/src/lib/capture.ts b/src/lib/capture.ts index cb14979f..3c6f9623 100644 --- a/src/lib/capture.ts +++ b/src/lib/capture.ts @@ -13,7 +13,7 @@ import { closeSync, mkdirSync, openSync, realpathSync, rmSync, statSync } from "node:fs"; import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path"; -import { normalizePort, portIndex } from "./link.ts"; +import { nicForPort, normalizePort } from "./link.ts"; import type { CaptureState, NetworkConfig, NicCaptureOptions } from "./types.ts"; import { QuickCHRError } from "./types.ts"; @@ -314,14 +314,7 @@ export function resolveCaptureTargets( machine: string, ): CaptureTarget[] { return changes.map((change) => { - const index = portIndex(change.port); - const nic = networks[index]; - if (!nic) { - const have = networks.length === 0 - ? "it has no quickchr NICs" - : `it has ${networks.length} quickchr NIC${networks.length === 1 ? "" : "s"} (ether1${networks.length > 1 ? `–ether${networks.length}` : ""})`; - throw new QuickCHRError("INVALID_ARGUMENT", `Machine "${machine}" has no ${change.port}: ${have}.`); - } + const nic = nicForPort(change.port, networks, machine); if (!nic.capture) { throw new QuickCHRError( "INVALID_ARGUMENT", diff --git a/src/lib/fault.ts b/src/lib/fault.ts new file mode 100644 index 00000000..ad2bfc72 --- /dev/null +++ b/src/lib/fault.ts @@ -0,0 +1,202 @@ +/** + * A one-way (or two-way) drop on a NIC that keeps carrier (#369): + * `chr.fault("ether3", { drop: "egress" })` and `quickchr set --fault ether3=egress`. + * + * QEMU's `filter-redirector` with only an `outdev`, on a `null` chardev, consumes every + * frame in its direction and writes it nowhere. Carrier stays up on both ends and QEMU + * logs nothing (`test/lab/link-impairment/REPORT.md`, "Blackhole"). One filter and one + * sink per port, `fault` and `fault-sink` for netdev `net`: a chardev takes + * one frontend, and `queue` is switched in place with `qom-set`, so a change of + * direction never lets frames through. The filter goes at the head of the NIC's chain, + * the wire side, so a capture (#338) on the same NIC is the guest's view: it shows the + * frames the guest sent and not the ones it never received. + * + * This module is pure — validation, ids, HMP commands and reply parsing. The locked + * runtime application lives in `quickchr.ts` (`applyFaultChanges`). + */ + +import { nicForPort, normalizePort } from "./link.ts"; +import type { FaultDrop, NetworkConfig, NicFault } from "./types.ts"; +import { QuickCHRError } from "./types.ts"; + +/** One requested change, normalized. `null` clears the port. */ +export interface FaultChange { + port: string; + drop: FaultDrop | null; +} + +/** A change resolved to the QEMU ids that carry it. */ +export interface FaultTarget extends FaultChange { + netdev: string; + filterId: string; + sinkId: string; +} + +const DROPS: readonly FaultDrop[] = ["egress", "ingress", "both"]; + +/** `queue=` is named from the netdev's side: `rx` holds the guest's outgoing frames. */ +const QUEUE_OF: Readonly> = { egress: "rx", ingress: "tx", both: "all" }; + +function describe(value: unknown): string { + try { + return JSON.stringify(value) ?? String(value); + } catch { + return String(value); + } +} + +function normalizeDrop(port: string, value: unknown): FaultDrop { + const lower = typeof value === "string" ? value.trim().toLowerCase() : value; + if (DROPS.includes(lower as FaultDrop)) return lower as FaultDrop; + throw new QuickCHRError( + "INVALID_ARGUMENT", + `Fault drop for ${port} must be "egress", "ingress" or "both", not ${describe(value)}.`, + ); +} + +/** `{ drop }` or `null`; anything else is refused with the accepted shape. */ +function normalizeFault(port: string, value: unknown): FaultDrop | null { + if (value === null) return null; + if (typeof value !== "object" || Array.isArray(value)) { + throw new QuickCHRError( + "INVALID_ARGUMENT", + `Fault for ${port} must be { drop: "egress" | "ingress" | "both" } or null to clear it, not ${describe(value)}.`, + ); + } + const { drop, ...rest } = value as Record; + const unknown = Object.keys(rest); + if (unknown.length > 0) { + throw new QuickCHRError("INVALID_ARGUMENT", `Fault for ${port} has unknown option ${unknown.map((k) => `"${k}"`).join(", ")} (supported: drop).`); + } + return normalizeDrop(port, drop); +} + +/** Validate either call form of `fault()` into an ordered change list. A port named + * twice keeps its last value at its first position, as `link()` does. */ +export function normalizeFaultChanges( + portOrChanges: string | Readonly>, + fault?: NicFault | null, +): FaultChange[] { + let entries: Array<[unknown, unknown]>; + if (typeof portOrChanges === "string") { + if (fault === undefined) { + throw new QuickCHRError("INVALID_ARGUMENT", "fault(port) needs a fault: { drop: \"egress\" | \"ingress\" | \"both\" }, or null to clear it."); + } + entries = [[portOrChanges, fault]]; + } else if (portOrChanges && typeof portOrChanges === "object" && !Array.isArray(portOrChanges)) { + if (fault !== undefined) { + throw new QuickCHRError("INVALID_ARGUMENT", "fault() takes either (port, fault) or one { port: fault } object, not both."); + } + entries = Object.entries(portOrChanges); + } else { + throw new QuickCHRError("INVALID_ARGUMENT", "fault() takes (port, fault) or a { port: fault } object, e.g. fault(\"ether3\", { drop: \"egress\" })."); + } + if (entries.length === 0) throw new QuickCHRError("INVALID_ARGUMENT", "fault() was given no ports to change."); + const byPort = new Map(); + for (const [rawPort, rawFault] of entries) { + const port = normalizePort(rawPort, "Fault"); + byPort.set(port, normalizeFault(port, rawFault)); + } + return [...byPort].map(([port, drop]) => ({ port, drop })); +} + +/** Parse the CLI's repeated `--fault =egress|ingress|both|none` values into the + * batch form. Every value is parsed before anything applies. */ +export function parseFaultAssignments(values: readonly string[]): Record { + const out: Record = {}; + for (const value of values) { + const eq = value.indexOf("="); + if (eq < 0 || value.indexOf("=", eq + 1) >= 0) { + throw new QuickCHRError("INVALID_ARGUMENT", `--fault takes =egress|ingress|both|none (e.g. --fault ether3=egress), not "${value}".`); + } + const port = normalizePort(value.slice(0, eq), "Fault"); + const raw = value.slice(eq + 1).trim().toLowerCase(); + out[port] = raw === "none" ? null : { drop: normalizeDrop(port, raw) }; + } + return out; +} + +/** The filter's QEMU object id and its sink chardev's id, for netdev `net`. */ +export function faultIds(netdev: string): { filterId: string; sinkId: string } { + const n = netdev.replace(/^net/, ""); + return { filterId: `fault${n}`, sinkId: `fault${n}-sink` }; +} + +/** Map each change to its NIC's netdev and the fault's ids. */ +export function resolveFaultTargets( + changes: readonly FaultChange[], + networks: readonly NetworkConfig[], + machine: string, +): FaultTarget[] { + return changes.map((change) => { + const netdev = nicForPort(change.port, networks, machine).id; + return { ...change, netdev, ...faultIds(netdev) }; + }); +} + +/** The HMP command that reads a port's current fault. */ +export function faultQueryCommand(filterId: string): string { + return `qom-get /objects/${filterId} queue`; +} + +/** What a {@link faultQueryCommand} reply says: the drop in place, `null` for no + * filter (QEMU 11.1.2: `Error: Device '/objects/fault2' not found`), or the reply as + * an error when it is neither. HMP prints the value as JSON (`"rx"`). */ +export function parseFaultQuery(reply: string, filterId: string): { drop: FaultDrop | null } | { error: string } { + const text = reply.trim(); + if (text === `Error: Device '/objects/${filterId}' not found`) return { drop: null }; + const queue = text.replace(/^"(.*)"$/, "$1"); + const drop = DROPS.find((d) => QUEUE_OF[d] === queue); + return drop ? { drop } : { error: text === "" ? "an empty reply" : `"${text}"` }; +} + +/** Chardev ids from an HMP `qom-list /chardevs` reply (`fault2-sink (child)`). */ +export function parseChardevList(reply: string): Set { + const ids = new Set(); + for (const line of reply.split(/\r?\n/)) { + const m = /^(\S+) \(child]+>\)$/.exec(line.trim()); + if (m?.[1]) ids.add(m[1]); + } + return ids; +} + +/** One HMP command in a fault change, and what it does (for messages). */ +export interface FaultStep { + command: string; + kind: "add-sink" | "add-filter" | "set-queue" | "del-filter" | "remove-sink"; +} + +/** The HMP steps that take a port from `current` to `target.drop`. Empty when it is + * already there. `staleSink` is a sink chardev left behind by an earlier failure, + * removed before a new one is added. */ +export function planFaultSteps(target: FaultTarget, current: FaultDrop | null, staleSink: boolean): FaultStep[] { + const want = target.drop; + if (want === current) return []; + if (want === null) { + return [ + { kind: "del-filter", command: `object_del ${target.filterId}` }, + { kind: "remove-sink", command: `chardev-remove ${target.sinkId}` }, + ]; + } + if (current !== null) { + return [{ kind: "set-queue", command: `qom-set /objects/${target.filterId} queue ${QUEUE_OF[want]}` }]; + } + return [ + ...(staleSink ? [{ kind: "remove-sink" as const, command: `chardev-remove ${target.sinkId}` }] : []), + { kind: "add-sink", command: `chardev-add null,id=${target.sinkId}` }, + { + kind: "add-filter", + command: `object_add filter-redirector,id=${target.filterId},netdev=${target.netdev},queue=${QUEUE_OF[want]},outdev=${target.sinkId},position=head`, + }, + ]; +} + +/** `ether3=egress, ether2=none` — for messages and the CLI's report. */ +export function formatFaultChanges(changes: readonly FaultChange[]): string { + return changes.map((c) => `${c.port}=${c.drop ?? "none"}`).join(", "); +} + +/** `dropping egress` / `dropping both ways` — for status output. */ +export function describeDrop(drop: FaultDrop): string { + return drop === "both" ? "dropping both ways" : `dropping ${drop}`; +} diff --git a/src/lib/link.ts b/src/lib/link.ts index 07487698..be442086 100644 --- a/src/lib/link.ts +++ b/src/lib/link.ts @@ -104,25 +104,25 @@ export function parseLinkAssignments(values: readonly string[]): Record 1 ? `–ether${networks.length}` : ""})`; + throw new QuickCHRError("INVALID_ARGUMENT", `Machine "${machine}" has no ${port}: ${have}.`); +} + +/** Map each change to the netdev of the quickchr NIC at that position. */ export function resolveLinkTargets( changes: readonly LinkChange[], networks: readonly NetworkConfig[], machine: string, ): LinkTarget[] { - return changes.map((change) => { - const index = portIndex(change.port); - const nic = networks[index]; - if (!nic) { - const have = networks.length === 0 - ? "it has no quickchr NICs" - : `it has ${networks.length} quickchr NIC${networks.length === 1 ? "" : "s"} (ether1${networks.length > 1 ? `–ether${networks.length}` : ""})`; - throw new QuickCHRError("INVALID_ARGUMENT", `Machine "${machine}" has no ${change.port}: ${have}.`); - } - return { ...change, netdev: nic.id }; - }); + return changes.map((change) => ({ ...change, netdev: nicForPort(change.port, networks, machine).id })); } /** The HMP command for one target. */ diff --git a/src/lib/lock.ts b/src/lib/lock.ts index e22398cb..0ff39c2a 100644 --- a/src/lib/lock.ts +++ b/src/lib/lock.ts @@ -75,7 +75,8 @@ export type LockOperation = | "storage" | "credentials" | "link" - | "capture"; + | "capture" + | "fault"; /** Resources a machine creation has claimed but not yet persisted in `machine.json`. * Carried in the creator's machine lock, so it lives exactly as long as the create diff --git a/src/lib/quickchr.ts b/src/lib/quickchr.ts index f469ab19..75d3ec22 100644 --- a/src/lib/quickchr.ts +++ b/src/lib/quickchr.ts @@ -18,9 +18,11 @@ import type { LicenseLevel, LinkState, CaptureState, + ErrorCode, MachineState, NetworkConfig, NetworkTopologyEntry, + NicFault, PlatformInfo, PortMapping, ProvisioningStep, @@ -75,6 +77,7 @@ import { pidLiveness } from "./pid.ts"; import { buildQemuArgs, spawnQemu, QemuEarlyExitError, stopQemu, foreignQemuError, liveQemuFor, clearStalePidfile, cleanupQemuSockets, waitForBoot, waitForApiReady, readinessProbeFor, type QemuLaunchConfig, type QemuSpawn } from "./qemu.ts"; import { bootDiskFormatOf, bootDiskPath, cleanDiskFiles, ensureConfiguredDisks, normalizeDiskOptions, writeBootDisk, parseSnapshotList, listSnapshots, mergeSnapshotMetadata, formatDiskSize } from "./disk.ts"; import { formatLinkChanges, normalizeLinkChanges, resolveLinkTargets, setLinkCommand, setLinkFailure, type LinkChange, type LinkTarget } from "./link.ts"; +import { faultIds, faultQueryCommand, formatFaultChanges, normalizeFaultChanges, parseChardevList, parseFaultQuery, planFaultSteps, resolveFaultTargets, type FaultChange, type FaultStep, type FaultTarget } from "./fault.ts"; import { assertCaptureDirsOutside, captureCommand, captureFilesOf, carryCaptureFiles, formatCaptureChanges, normalizeCaptureChanges, removeIfEmpty, reserveCaptureFiles, resolveCaptureTargets, type CaptureChange, type CaptureTarget } from "./capture.ts"; import { monitorCommand, serialStreams, qgaCommand, channelEndpoint, channelFileExists, channelPath, MONITOR_FAST_QUERY_TIMEOUT_MS, MONITOR_SAVEVM_TIMEOUT_MS, MONITOR_LOADVM_TIMEOUT_MS, MONITOR_DELVM_TIMEOUT_MS } from "./channels.ts"; import { captureBootFailure, newBootProbeStats, preserveOnFailure, type BootFailureReport, type BootProbeStats, type FailureTrigger } from "./diagnostics.ts"; @@ -1062,6 +1065,136 @@ function linkFailureMessage( return parts.join(" "); } +/** `fault()` (#369): validate against the locked, refreshed state, then bring each port + * in order from the fault QEMU has now (`qom-get … queue`) to the one asked for. A + * port already there costs no change. As with `link()`, the first failure stops the + * batch and names the ports already changed; a filter QEMU refuses after its sink was + * added has that sink removed again. Nothing is persisted: a new QEMU starts clean. */ +export async function applyFaultChanges(state: MachineState, changes: readonly FaultChange[]): Promise { + const actionArgs = changes.map((c) => `--fault ${c.port}=${c.drop ?? "none"}`).join(" "); + preflightOwnQemu(state, "set", actionArgs); + await withMachineLock(state, "fault", async () => { + assertOwnQemu(state, "set", actionArgs); + const targets = resolveFaultTargets(changes, state.networks, state.name); + if (!state.pid || !isMachineRunning(state)) { + throw new QuickCHRError( + "MACHINE_STOPPED", + `Machine "${state.name}" is not running — a fault is a runtime change to a running QEMU, and a new launch starts with none.`, + ); + } + let chardevs: Set | undefined; + const applied: FaultTarget[] = []; + for (const target of targets) { + const failure = (code: ErrorCode, reason: string, outcomeUnknown: boolean) => + new QuickCHRError(code, faultFailureMessage(state.name, target, reason, applied, targets, outcomeUnknown)); + const send = async (command: string, outcomeUnknown: boolean): Promise => { + try { + return (await monitorCommand(state.machineDir, command, undefined, state.portBase, { requirePrompt: true })).trim(); + } catch (err) { + const code = err instanceof QuickCHRError ? err.code : "PROCESS_FAILED"; + throw failure(code, err instanceof Error ? err.message : String(err), outcomeUnknown); + } + }; + const queryCommand = faultQueryCommand(target.filterId); + const query = parseFaultQuery(await send(queryCommand, false), target.filterId); + if ("error" in query) throw failure("PROCESS_FAILED", `QEMU answered ${query.error} to "${queryCommand}"`, false); + const current = query.drop; + let staleSink = false; + if (target.drop !== null && current === null) { + chardevs ??= parseChardevList(await send("qom-list /chardevs", false)); + staleSink = chardevs.has(target.sinkId); + } + const steps = planFaultSteps(target, current, staleSink); + for (const step of steps) { + const reply = await send(step.command, true); + if (reply !== "") { + const why = await faultStepRefusal(step, reply, target, current, send); + throw failure("PROCESS_FAILED", why, false); + } + if (step.kind === "add-sink") chardevs?.add(target.sinkId); + if (step.kind === "remove-sink") chardevs?.delete(target.sinkId); + } + applied.push(target); + } + }); +} + +/** Why a fault step failed, and where that leaves the port. A filter QEMU refused after + * its sink was added gets the sink removed again, so a refusal leaves nothing behind. */ +async function faultStepRefusal( + step: FaultStep, + reply: string, + target: FaultTarget, + current: FaultChange["drop"], + send: (command: string, outcomeUnknown: boolean) => Promise, +): Promise { + const refused = `QEMU answered "${reply}" to "${step.command}"`; + const now = current === null ? `${target.port} has no fault` : `${target.port} still drops ${current}`; + switch (step.kind) { + case "add-filter": { + let undo: string; + try { + undo = await send(`chardev-remove ${target.sinkId}`, true); + } catch (err) { + undo = err instanceof Error ? err.message : String(err); + } + return undo === "" + ? `${refused}. ${now}; its sink chardev was removed again` + : `${refused}. ${now}, but removing its sink chardev ${target.sinkId} failed too (${undo}); the next fault() on ${target.port} removes it`; + } + case "remove-sink": + if (target.drop === null) { + return `${refused}. The drop on ${target.port} is cleared; only its sink chardev ${target.sinkId} is left, and the next fault() on ${target.port} removes it`; + } + return `${refused}. ${now}`; + default: + return `${refused}. ${now}`; + } +} + +function faultFailureMessage( + machine: string, + failed: FaultTarget, + reason: string, + applied: readonly FaultTarget[], + targets: readonly FaultTarget[], + outcomeUnknown: boolean, +): string { + const pending = targets.slice(applied.length + 1); + const parts = [`Fault change on "${machine}" failed at ${formatFaultChanges([failed])} (${failed.filterId}): ${reason}.`]; + if (outcomeUnknown) parts.push(`Whether ${failed.port} changed is unknown.`); + parts.push(applied.length > 0 ? `Already applied: ${formatFaultChanges(applied)}.` : "No earlier port was changed."); + if (pending.length > 0) parts.push(`Not attempted: ${formatFaultChanges(pending)}.`); + return parts.join(" "); +} + +/** The faults QEMU has in place now, by port (#369): one `qom-get … queue` per quickchr + * NIC. Read from the machine's current record, so it follows a restart made elsewhere; + * a handle whose machine was removed (or replaced) is `MACHINE_NOT_FOUND`. */ +export async function readFaults(state: MachineState): Promise> { + const fresh = loadMachine(state.name); + if (!fresh || fresh.createdAt !== state.createdAt) { + throw new QuickCHRError( + "MACHINE_NOT_FOUND", + `Machine "${state.name}" was removed${fresh ? " and created again" : ""} since this handle was created.`, + ); + } + if (!fresh.pid || !isMachineRunning(fresh)) { + throw new QuickCHRError("MACHINE_STOPPED", `Machine "${state.name}" is not running — it has no faults to read.`); + } + const out: Record = {}; + for (const [i, nic] of fresh.networks.entries()) { + const { filterId } = faultIds(nic.id); + const command = faultQueryCommand(filterId); + const query = parseFaultQuery(await monitorCommand(fresh.machineDir, command, undefined, fresh.portBase, { requirePrompt: true }), filterId); + if ("error" in query) { + throw new QuickCHRError("PROCESS_FAILED", `Reading ether${i + 1}'s fault on "${state.name}": QEMU answered ${query.error} to "${command}".`); + } + if (query.drop) out[`ether${i + 1}`] = { drop: query.drop }; + } + return out; +} + async function continueUnderLock(state: MachineState, wait: boolean, timeoutExtra?: number): Promise { const pid = state.pid; if (!pid || !isMachineRunning(state)) { @@ -1504,6 +1637,14 @@ function createInstance(state: MachineState): ChrInstance { await applyCaptureChanges(state, normalizeCaptureChanges(portOrChanges, captureState)); }, + async fault(portOrChanges: string | Readonly>, nicFault?: NicFault | null): Promise { + await applyFaultChanges(state, normalizeFaultChanges(portOrChanges, nicFault)); + }, + + async faults(): Promise> { + return readFaults(state); + }, + captureFiles(): Record { // Read the record without refreshing this handle: copying a replacement // machine's fields (createdAt, pid) into it would let a stale handle pass diff --git a/src/lib/types.ts b/src/lib/types.ts index fa34b710..8290d9a8 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -96,6 +96,16 @@ export type LinkState = "up" | "down"; /** Packet-capture state of a NIC's filter (#338): recording or paused. */ export type CaptureState = "on" | "off"; +/** Which way `ChrInstance.fault()` drops frames on a NIC (#369), named from the guest: + * `egress` is what the guest sends, `ingress` what is delivered to it. */ +export type FaultDrop = "egress" | "ingress" | "both"; + +/** A fault on one NIC (#369): every frame in the given direction is dropped while + * carrier stays up on both ends — a half-failed optic, which `link()` can't make. */ +export interface NicFault { + drop: FaultDrop; +} + /** Packet capture on one NIC (#338): QEMU's `filter-dump` writes every frame that * crosses the NIC, both directions and full frames, to a libpcap file. Set when the * machine is created and persisted; every QEMU start creates the filter and a new file. @@ -666,6 +676,10 @@ export interface StartOptions { * with the same id). When `start()` creates the machine, the value is both * used for that boot and recorded, like every other creation option. * + * An empty array means "not given", like `undefined`: `start({ qemuArgs: [] })` + * on an existing machine boots with its stored args. To drop them, use + * `quickchr set --clear-qemu-args` (#370). + * * Ordering is load-bearing: passthrough goes last, so conflicting QEMU options * resolve last-wins (e.g. a duplicate `-M pc,...` merges over quickchr's `-M pc`). * A bad element surfaces as `SPAWN_FAILED` with the QEMU log tail. */ @@ -1041,6 +1055,42 @@ export interface ChrInstance { */ capture(port: string, state: CaptureState): Promise; capture(changes: Readonly>): Promise; + /** Drop every frame one way (or both) on this machine's NIC while carrier stays up + * on both ends (#369) — a half-failed optic, which `link()` can't make since it drops + * carrier. QEMU `filter-redirector` into a `null` chardev, added and removed at run + * time over HMP; no root, external process or reboot. + * + * `port` is `etherN`, as for `link()`. `drop` is named from the guest: `egress` is + * what it sends, `ingress` what is delivered to it, `both` is both. `null` clears the + * port. Setting a port to what it already has is a no-op, and a change of direction + * switches the filter in place, with no moment where frames get through. + * + * - Neither end logs anything and both keep `running=yes`; only protocol timeouts + * notice. An 802.3ad member whose egress is dropped leaves the far end's bond in + * about 4–8 s, and the near end's a few seconds later (RouterOS 7.25.2). + * - After an `ingress` or `both` drop is cleared the first frames can still be lost + * while the peer re-resolves ARP: its requests went unanswered during the drop. + * - A capture (#338) on the same NIC is the guest's view: it shows the frames the + * guest sent, dropped or not, and not the ones dropped before reaching it. + * - Nothing is recorded: a new QEMU launch (start, or a device-mode power cycle) + * starts with no fault. A guest reboot inside the same QEMU keeps it. + * + * The batch form validates every port first, then applies them in order under the + * machine lock; a failure stops the batch and names the ports already changed. A + * port's own setup is undone if QEMU refuses part of it. Throws `INVALID_ARGUMENT` + * for a bad port or fault, `MACHINE_STOPPED` when QEMU is not running, + * `PROCESS_FAILED` when QEMU refuses. + * @example + * await chr.fault("ether3", { drop: "egress" }); + * await chr.fault({ ether2: { drop: "both" }, ether3: null }); + */ + fault(port: string, fault: NicFault | null): Promise; + fault(changes: Readonly>): Promise; + /** The faults in place now, by port (`{ ether3: { drop: "egress" } }`), read from + * QEMU. Ports without one are left out. Throws `MACHINE_STOPPED` when QEMU is not + * running, and `MACHINE_NOT_FOUND` when the machine was removed (or removed and + * created again) since this handle was made. */ + faults(): Promise>; /** The capture file of each capturing NIC's latest QEMU start, by port * (`{ ether2: "/…/captures/ether2-20261201T160641Z.pcap" }`). Read from the * machine's record, so it follows a restart made elsewhere. Empty when no NIC diff --git a/test/integration/link-fault.test.ts b/test/integration/link-fault.test.ts new file mode 100644 index 00000000..a2130515 --- /dev/null +++ b/test/integration/link-fault.test.ts @@ -0,0 +1,149 @@ +import { describe, test, expect, beforeAll, afterAll } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { join } from "node:path"; +import { _resetSocketCache, removeNamedSocket } from "../../src/lib/socket-registry.ts"; +import type { ChrInstance } from "../../src/lib/types.ts"; +import { readPcap } from "../lab/filter-dump/pcap.ts"; +import { imageTarget } from "./image-target.ts"; +import { bootTestTimeout } from "./timeouts.ts"; + +/** + * Integration test — a one-way drop on a NIC that keeps carrier (#369). + * + * A ether2 ── L1 ── B ether2 } 802.3ad bond0 on both ends, lacp-rate=1sec + * A ether3 ── L2 ── B ether3 } (both ether3s captured) + * + * An egress drop on A's ether3 takes the member out of B's bond (the LACP timeout fires) + * while ether3 keeps `running=yes` on both ends and the bond keeps carrying traffic on + * ether2; clearing it brings the member back. The captures show where the filter sits: + * A's capture still has the LACPDUs A sends into the drop and B's gets none of them, and + * under an ingress drop A's capture has none of B's. `faults()` reads each state back, + * including a change of direction made in place. + */ + +const SKIP = !process.env.QUICKCHR_INTEGRATION; +const A = "integration-fault-a"; +const B = "integration-fault-b"; +const LINKS = [`${A}-l1`, `${A}-l2`]; +const SHARED = SKIP ? "" : mkdtempSync(join(import.meta.dir, ".tmp-fault-")); + +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(); + for (const link of LINKS) { + try { removeNamedSocket(link); } catch (e) { errors.push(e); } + } + if (errors.length > 0) throw new AggregateError(errors, "link-fault 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"; +} + +type Row = Record; + +/** Bond members that collect and distribute: LACP agreed with the partner (flags C and D). */ +async function inBond(chr: ChrInstance): Promise { + const raw = await chr.rest("/interface/bonding/monitor-slaves", { method: "POST", body: JSON.stringify({ bond: "bond0", once: "yes" }) }); + const rows = (Array.isArray(raw) ? raw : [raw]) as Row[]; + return rows.filter((r) => (r.flags ?? "").includes("C") && (r.flags ?? "").includes("D")).map((r) => r.port ?? "").sort(); +} + +async function until(what: string, predicate: () => Promise, timeoutMs: number): Promise { + const started = Date.now(); + for (;;) { + if (await predicate().catch(() => false)) return Date.now() - started; + if (Date.now() - started > timeoutMs) throw new Error(`Timed out after ${timeoutMs} ms waiting for ${what}`); + await Bun.sleep(1000); + } +} + +/** LACPDUs from `mac` in a capture file. */ +async function lacpFrom(file: string | undefined, mac: string | undefined): Promise { + if (!file || !mac) throw new Error("capture file or MAC missing"); + return (await readPcap(file)).frames.filter((f) => f.kind === "lacp" && f.src === mac.toLowerCase()).length; +} + +describe.skipIf(SKIP)("one-way drop that keeps carrier (#369)", () => { + beforeAll(cleanup); + afterAll(async () => { + await cleanup(); + rmSync(SHARED, { recursive: true, force: true }); + }); + + test("egress drop takes the member out of the far bond with carrier up; clear restores; captures are the guest's view", async () => { + const { QuickCHR } = await import("../../src/lib/quickchr.ts"); + const [l1 = "", l2 = ""] = LINKS; + const member = { speed: 10000, duplex: "full" as const }; + const networks = [ + "user" as const, + { type: "socket" as const, name: l1, ...member }, + { type: "socket" as const, name: l2, ...member, capture: { dir: SHARED } }, + ]; + const a = await QuickCHR.start({ ...imageTarget(), background: true, name: A, networks }); + const b = await QuickCHR.start({ ...imageTarget(), background: true, name: B, networks }); + const aMac = a.state.networks[2]?.mac; + const bMac = b.state.networks[2]?.mac; + const aCap = a.captureFiles().ether3; + const bCap = b.captureFiles().ether3; + + for (const [chr, ip] of [[a, "10.97.0.1"], [b, "10.97.0.2"]] as const) { + await run(chr, "/interface/bonding/add name=bond0 mode=802.3ad lacp-rate=1sec slaves=ether2,ether3"); + await run(chr, `/ip/address/add address=${ip}/24 interface=bond0`); + } + const whole = async () => (await inBond(a)).join() === "ether2,ether3" && (await inBond(b)).join() === "ether2,ether3"; + await until("both members in both bonds", whole, 120_000); + expect(await a.faults()).toEqual({}); + + // Egress on A's ether3: B stops hearing A's LACPDUs and takes the member out. + const aSent0 = await lacpFrom(aCap, aMac); + await a.fault("ether3", { drop: "egress" }); + const bHeard0 = await lacpFrom(bCap, aMac); + expect(await a.faults()).toEqual({ ether3: { drop: "egress" } }); + const out = await until("B to drop ether3 from its bond", async () => !(await inBond(b)).includes("ether3"), 60_000); + console.log(` B dropped ether3 ${(out / 1000).toFixed(1)} s after the egress drop`); + expect(await carrier(a, "ether3")).toBe(true); + expect(await carrier(b, "ether3")).toBe(true); + expect((await inBond(b))).toEqual(["ether2"]); + const ping = await run(a, ":put [/ping 10.97.0.2 count=3 interval=300ms]"); + expect(ping.split(/\r?\n/).at(-1)?.trim()).toBe("3"); + // A's capture is the guest's side of the drop: what A sent is in it, and none reached B. + expect(await lacpFrom(aCap, aMac) - aSent0).toBeGreaterThan(2); + expect(await lacpFrom(bCap, aMac)).toBe(bHeard0); + + await a.fault("ether3", null); + expect(await a.faults()).toEqual({}); + const back = await until("ether3 back in both bonds", whole, 60_000); + console.log(` ether3 back in both bonds ${(back / 1000).toFixed(1)} s after clearing`); + expect(await lacpFrom(bCap, aMac)).toBeGreaterThan(bHeard0); + + // Ingress on A's ether3: B's LACPDUs still leave B (in B's capture) and never reach A's. + await a.fault({ ether3: { drop: "ingress" } }); + const aHeard0 = await lacpFrom(aCap, bMac); + const bSent0 = await lacpFrom(bCap, bMac); + await Bun.sleep(4000); + expect(await lacpFrom(aCap, bMac)).toBe(aHeard0); + expect(await lacpFrom(bCap, bMac) - bSent0).toBeGreaterThan(1); + // A change of direction is made in place and reads back. + await a.fault("ether3", { drop: "both" }); + expect(await a.faults()).toEqual({ ether3: { drop: "both" } }); + expect(await carrier(a, "ether3")).toBe(true); + await a.fault("ether3", null); + await until("ether3 back in both bonds after ingress/both", whole, 60_000); + }, bootTestTimeout({ boots: 2, extraMs: 120_000 })); +}); diff --git a/test/unit/fault.test.ts b/test/unit/fault.test.ts new file mode 100644 index 00000000..34827666 --- /dev/null +++ b/test/unit/fault.test.ts @@ -0,0 +1,481 @@ +import { describe, test, expect, beforeEach, afterEach } from "bun:test"; +import { mkdirSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createServer, type Server } from "node:net"; +import { portAssignmentFlagValues } from "../../src/cli/flags.ts"; +import { QuickCHR } from "../../src/lib/quickchr.ts"; +import { + faultIds, + normalizeFaultChanges, + parseChardevList, + parseFaultAssignments, + parseFaultQuery, + planFaultSteps, + resolveFaultTargets, +} from "../../src/lib/fault.ts"; +import { loadMachine, saveMachine } from "../../src/lib/state.ts"; +import type { MachineState, NetworkConfig, NicFault } from "../../src/lib/types.ts"; + +/** + * NIC faults (#369) without a guest: validation, ids, the HMP plan, and the locked + * sequence against a fake HMP that keeps QEMU's object and chardev state and answers + * with QEMU 11.1.2's reply texts. Frames and carrier on a real CHR are in + * test/integration/link-fault.test.ts. + * + * The monitor fake binds a Unix socket, so those tests skip on Windows (as link.test.ts). + */ + +const TEST_DIR = join(tmpdir(), "quickchr-tmp-fault"); +const CLI = join(import.meta.dir, "../../src/cli/index.ts"); +const origDataDir = process.env.QUICKCHR_DATA_DIR; + +const THREE_PORTS: NetworkConfig[] = [ + { specifier: "user", id: "net0" }, + { specifier: { type: "socket", name: "a" }, id: "net1" }, + { specifier: { type: "socket", name: "b" }, id: "net2" }, +]; + +function machine(name: string, overrides: Partial = {}): MachineState { + return { + name, + version: "7.25.2", + arch: "x86", + cpu: 1, + mem: 512, + networks: THREE_PORTS, + ports: {}, + packages: [], + portBase: 9140, + excludePorts: [], + extraPorts: [], + createdAt: "2026-01-01T00:00:00.000Z", + status: "stopped", + machineDir: join(TEST_DIR, "machines", name), + ...overrides, + }; +} + +function running(name: string, overrides: Partial = {}): MachineState { + const state = machine(name, { status: "running", pid: process.pid, ...overrides }); + saveMachine(state); + return state; +} + +interface FakeQemu { + server: Server; + commands: string[]; + filters: Map; + chardevs: Set; +} + +/** A stand-in for QEMU's HMP over the filter and chardev commands `fault()` uses, with + * QEMU 11.1.2's reply texts. `refuse` answers a command with an error instead. */ +async function fakeQemu(machineDir: string, refuse: (command: string) => string | undefined = () => undefined): Promise { + const commands: string[] = []; + const filters = new Map(); + const chardevs = new Set(["compat_monitor0"]); + const netdevs = new Set(THREE_PORTS.map((n) => n.id)); + const routes: Array<[RegExp, (m: string[]) => string]> = [ + [/^qom-get \/objects\/(\S+) queue$/, ([, id = ""]) => { + const f = filters.get(id); + return f ? `"${f.queue}"` : `Error: Device '/objects/${id}' not found`; + }], + [/^qom-list \/chardevs$/, () => + ["type (string)", ...[...chardevs].map((id) => `${id} (child)`)].join("\r\n")], + [/^chardev-add null,id=(\S+)$/, ([, id = ""]) => { + if (chardevs.has(id)) return `Error: attempt to add duplicate property '${id}' to object (type 'container')`; + chardevs.add(id); + return ""; + }], + [/^object_add filter-redirector,id=([^,]+),netdev=([^,]+),queue=([^,]+),outdev=([^,]+),position=head$/, ([, id = "", netdev = "", queue = "", outdev = ""]) => { + if (filters.has(id)) return `Error: attempt to add duplicate property '${id}' to object (type 'container')`; + if (!netdevs.has(netdev)) return "Error: Parameter 'netdev' expects a network backend id"; + if (!chardevs.has(outdev)) return `Error: Device '${outdev}' not found`; + filters.set(id, { netdev, queue, outdev }); + return ""; + }], + [/^qom-set \/objects\/(\S+) queue (\S+)$/, ([, id = "", queue = ""]) => { + const f = filters.get(id); + if (!f) return `Error: Device '/objects/${id}' not found`; + f.queue = queue; + return ""; + }], + [/^object_del (\S+)$/, ([, id = ""]) => (filters.delete(id) ? "" : `Error: object '${id}' not found`)], + [/^chardev-remove (\S+)$/, ([, id = ""]) => { + if (!chardevs.has(id)) return `Error: Chardev '${id}' not found`; + if ([...filters.values()].some((f) => f.outdev === id)) return `Error: Chardev '${id}' is busy`; + chardevs.delete(id); + return ""; + }], + ]; + const answer = (command: string): string => { + const refused = refuse(command); + if (refused !== undefined) return refused; + for (const [re, handle] of routes) { + const m = re.exec(command); + if (m) return handle([...m]); + } + return `unknown command: '${command}'`; + }; + const server = createServer((sock) => { + sock.write("(qemu) "); + sock.on("data", (data) => { + const command = data.toString().trim(); + commands.push(command); + const reply = answer(command); + sock.write(`${command}\r\n${reply ? `${reply}\r\n` : ""}(qemu) `); + }); + }); + mkdirSync(machineDir, { recursive: true }); + await new Promise((resolve) => server.listen(join(machineDir, "monitor.sock"), resolve)); + return { server, commands, filters, chardevs }; +} + +async function closeServer(server: Server): Promise { + await new Promise((resolve, reject) => server.close((err) => (err ? reject(err) : resolve()))); +} + +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", + QUICKCHR_NO_TIPS: "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 instanceOf(name: string) { + const instance = QuickCHR.get(name); + if (!instance) throw new Error("seeded machine did not load"); + return instance; +} + +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; +}); + +describe("normalizeFaultChanges", () => { + test("single and batch forms produce the same change list", () => { + expect(normalizeFaultChanges("ether3", { drop: "egress" })).toEqual([{ port: "ether3", drop: "egress" }]); + expect(normalizeFaultChanges({ ether3: { drop: "egress" } })).toEqual([{ port: "ether3", drop: "egress" }]); + expect(normalizeFaultChanges("ether3", null)).toEqual([{ port: "ether3", drop: null }]); + }); + + test("port and drop are case-insensitive; a repeated port keeps its last value at its first position", () => { + expect(normalizeFaultChanges({ Ether3: { drop: "EGRESS" as NicFault["drop"] }, ether2: null, ether3: { drop: "both" } })).toEqual([ + { port: "ether3", drop: "both" }, + { port: "ether2", drop: null }, + ]); + }); + + test("refuses a missing fault, a string, an unknown key, a bad drop, a mixed call and an empty batch", () => { + expect(() => normalizeFaultChanges("ether3")).toThrow(/needs a fault/); + expect(() => normalizeFaultChanges("ether3", "egress" as unknown as NicFault)).toThrow(/must be \{ drop:/); + expect(() => normalizeFaultChanges("ether3", { drop: "egress", loss: 30 } as unknown as NicFault)).toThrow(/unknown option "loss"/); + expect(() => normalizeFaultChanges("ether3", { drop: "sideways" } as unknown as NicFault)).toThrow(/"egress", "ingress" or "both"/); + expect(() => normalizeFaultChanges("ether3", {} as NicFault)).toThrow(/"egress", "ingress" or "both"/); + expect(() => normalizeFaultChanges({ ether3: null }, null)).toThrow(/not both/); + expect(() => normalizeFaultChanges({})).toThrow(/no ports/); + expect(() => normalizeFaultChanges("bond0", null)).toThrow(/Unknown fault port "bond0"/); + }); +}); + +describe("parseFaultAssignments and --fault occurrences", () => { + test("none clears; last value per port wins; one bad value refuses all", () => { + expect(parseFaultAssignments(["ether3=egress", "ether2=Both", "ether3=none"])).toEqual({ ether3: null, ether2: { drop: "both" } }); + expect(() => parseFaultAssignments(["ether3=egress", "ether2"])).toThrow(/--fault takes =egress\|ingress\|both\|none/); + expect(() => parseFaultAssignments(["ether3=off"])).toThrow(/"egress", "ingress" or "both"/); + }); + + test("every occurrence is read from argv; a bare --fault or --no-fault is an error", () => { + expect(portAssignmentFlagValues(["lab", "--fault", "ether3=egress", "--fault=ether2=none"], "fault")).toEqual({ values: ["ether3=egress", "ether2=none"] }); + expect(portAssignmentFlagValues(["lab", "--fault"], "fault").error).toContain("--fault is missing its value: --fault =egress|ingress|both|none"); + expect(portAssignmentFlagValues(["lab", "--no-fault"], "fault").error).toContain("e.g. --fault ether3=none"); + }); +}); + +describe("ids, targets, plan and replies", () => { + test("etherN maps to net, with one filter and one sink id per port", () => { + expect(faultIds("net2")).toEqual({ filterId: "fault2", sinkId: "fault2-sink" }); + expect(resolveFaultTargets([{ port: "ether3", drop: "egress" }], THREE_PORTS, "m")).toEqual([ + { port: "ether3", drop: "egress", netdev: "net2", filterId: "fault2", sinkId: "fault2-sink" }, + ]); + expect(() => resolveFaultTargets([{ port: "ether4", drop: null }], THREE_PORTS, "m")).toThrow(/has no ether4: it has 3 quickchr NICs \(ether1–ether3\)/); + }); + + test("the plan goes from the current fault to the wanted one with the fewest steps", () => { + const t = (drop: NicFault["drop"] | null) => resolveFaultTargets([{ port: "ether2", drop }], THREE_PORTS, "m")[0] as NonNullable[0]>; + expect(planFaultSteps(t("egress"), "egress", false)).toEqual([]); + expect(planFaultSteps(t(null), null, false)).toEqual([]); + expect(planFaultSteps(t("egress"), null, false).map((s) => s.command)).toEqual([ + "chardev-add null,id=fault1-sink", + "object_add filter-redirector,id=fault1,netdev=net1,queue=rx,outdev=fault1-sink,position=head", + ]); + expect(planFaultSteps(t("ingress"), null, true).map((s) => s.command)).toEqual([ + "chardev-remove fault1-sink", + "chardev-add null,id=fault1-sink", + "object_add filter-redirector,id=fault1,netdev=net1,queue=tx,outdev=fault1-sink,position=head", + ]); + expect(planFaultSteps(t("both"), "egress", false).map((s) => s.command)).toEqual(["qom-set /objects/fault1 queue all"]); + expect(planFaultSteps(t(null), "ingress", false).map((s) => s.command)).toEqual(["object_del fault1", "chardev-remove fault1-sink"]); + }); + + test("QEMU 11.1.2 replies: a queue value, a missing filter, and anything else", () => { + expect(parseFaultQuery('"rx"', "fault1")).toEqual({ drop: "egress" }); + expect(parseFaultQuery('"tx"', "fault1")).toEqual({ drop: "ingress" }); + expect(parseFaultQuery('"all"\r\n', "fault1")).toEqual({ drop: "both" }); + expect(parseFaultQuery("Error: Device '/objects/fault1' not found", "fault1")).toEqual({ drop: null }); + expect(parseFaultQuery("Error: Device '/objects/fault2' not found", "fault1")).toEqual({ error: `"Error: Device '/objects/fault2' not found"` }); + expect(parseFaultQuery("", "fault1")).toEqual({ error: "an empty reply" }); + expect([...parseChardevList("type (string)\r\nx2 (child)\r\ncompat_monitor0 (child)\r\nfault1-sink (child)\r\n")]) + .toEqual(["x2", "compat_monitor0", "fault1-sink"]); + }); +}); + +describe("ChrInstance.fault() without a guest", () => { + test("a stopped machine is MACHINE_STOPPED, for fault() and faults()", async () => { + saveMachine(machine("fault-stopped")); + const instance = instanceOf("fault-stopped"); + await expect(instance.fault("ether3", { drop: "egress" })).rejects.toMatchObject({ code: "MACHINE_STOPPED" }); + await expect(instance.faults()).rejects.toMatchObject({ code: "MACHINE_STOPPED" }); + }); + + test("an invalid batch sends nothing", async () => { + if (process.platform === "win32") return; + const state = running("fault-invalid"); + const qemu = await fakeQemu(state.machineDir); + try { + const instance = instanceOf("fault-invalid"); + await expect(instance.fault({ ether2: { drop: "egress" }, ether9: null })).rejects.toMatchObject({ code: "INVALID_ARGUMENT" }); + await expect(instance.fault({ ether2: { drop: "egress" }, ether3: { drop: "loss" } as unknown as NicFault })).rejects.toMatchObject({ code: "INVALID_ARGUMENT" }); + expect(qemu.commands).toEqual([]); + } finally { + await closeServer(qemu.server); + } + }); + + test("add, repeat, change direction in place, read back, clear — and nothing persisted", async () => { + if (process.platform === "win32") return; + const state = running("fault-cycle"); + const before = JSON.stringify(loadMachine("fault-cycle")); + const qemu = await fakeQemu(state.machineDir); + try { + const instance = instanceOf("fault-cycle"); + await instance.fault("ether3", { drop: "egress" }); + expect(qemu.commands).toEqual([ + "qom-get /objects/fault2 queue", + "qom-list /chardevs", + "chardev-add null,id=fault2-sink", + "object_add filter-redirector,id=fault2,netdev=net2,queue=rx,outdev=fault2-sink,position=head", + ]); + expect(await instance.faults()).toEqual({ ether3: { drop: "egress" } }); + + qemu.commands.length = 0; + await instance.fault("ether3", { drop: "egress" }); + expect(qemu.commands).toEqual(["qom-get /objects/fault2 queue"]); + + qemu.commands.length = 0; + await instance.fault({ ether3: { drop: "both" }, ether2: { drop: "ingress" } }); + expect(qemu.commands).toEqual([ + "qom-get /objects/fault2 queue", + "qom-set /objects/fault2 queue all", + "qom-get /objects/fault1 queue", + "qom-list /chardevs", + "chardev-add null,id=fault1-sink", + "object_add filter-redirector,id=fault1,netdev=net1,queue=tx,outdev=fault1-sink,position=head", + ]); + expect(await instance.faults()).toEqual({ ether2: { drop: "ingress" }, ether3: { drop: "both" } }); + + await instance.fault({ ether2: null, ether3: null, ether1: null }); + expect(qemu.filters.size).toBe(0); + expect([...qemu.chardevs]).toEqual(["compat_monitor0"]); + expect(await instance.faults()).toEqual({}); + expect(JSON.stringify(loadMachine("fault-cycle"))).toBe(before); + } finally { + await closeServer(qemu.server); + } + }); + + test("a sink left behind by an earlier failure is removed before a new one is added", async () => { + if (process.platform === "win32") return; + const state = running("fault-stale"); + const qemu = await fakeQemu(state.machineDir); + qemu.chardevs.add("fault1-sink"); + try { + await instanceOf("fault-stale").fault("ether2", { drop: "egress" }); + expect(qemu.commands.slice(2)).toEqual([ + "chardev-remove fault1-sink", + "chardev-add null,id=fault1-sink", + "object_add filter-redirector,id=fault1,netdev=net1,queue=rx,outdev=fault1-sink,position=head", + ]); + expect(qemu.filters.get("fault1")).toEqual({ netdev: "net1", queue: "rx", outdev: "fault1-sink" }); + } finally { + await closeServer(qemu.server); + } + }); + + test("a refused filter removes its sink again and names what applied and what did not", async () => { + if (process.platform === "win32") return; + const state = running("fault-refused"); + const qemu = await fakeQemu(state.machineDir, (command) => + command.startsWith("object_add filter-redirector,id=fault2,") ? "Error: Vhost is not supported" : undefined, + ); + try { + const error = await instanceOf("fault-refused") + .fault({ ether2: { drop: "egress" }, ether3: { drop: "both" }, ether1: { drop: "ingress" } }) + .catch((e: unknown) => e); + expect(error).toMatchObject({ code: "PROCESS_FAILED" }); + const message = (error as Error).message; + expect(message).toContain("failed at ether3=both (fault2)"); + expect(message).toContain(`QEMU answered "Error: Vhost is not supported"`); + expect(message).toContain("ether3 has no fault; its sink chardev was removed again"); + expect(message).toContain("Already applied: ether2=egress."); + expect(message).toContain("Not attempted: ether1=ingress."); + expect(qemu.commands.at(-1)).toBe("chardev-remove fault2-sink"); + expect([...qemu.filters.keys()]).toEqual(["fault1"]); + expect([...qemu.chardevs]).toEqual(["compat_monitor0", "fault1-sink"]); + } finally { + await closeServer(qemu.server); + } + }); + + test("a refused direction change leaves the port's drop as it was", async () => { + if (process.platform === "win32") return; + const state = running("fault-requeue"); + const qemu = await fakeQemu(state.machineDir, (command) => (command.startsWith("qom-set") ? "Error: Property 'queue' is read-only" : undefined)); + try { + const instance = instanceOf("fault-requeue"); + await instance.fault("ether2", { drop: "egress" }); + await expect(instance.fault("ether2", { drop: "ingress" })).rejects.toThrow(/ether2 still drops egress\. No earlier port was changed\./); + expect(qemu.filters.get("fault1")?.queue).toBe("rx"); + } finally { + await closeServer(qemu.server); + } + }); + + test("a clear whose sink QEMU keeps says the drop itself is gone", async () => { + if (process.platform === "win32") return; + const state = running("fault-sink-kept"); + const qemu = await fakeQemu(state.machineDir, (command) => (command === "chardev-remove fault1-sink" ? "Error: Chardev 'fault1-sink' is busy" : undefined)); + try { + const instance = instanceOf("fault-sink-kept"); + await instance.fault("ether2", { drop: "both" }); + await expect(instance.fault("ether2", null)).rejects.toThrow(/The drop on ether2 is cleared; only its sink chardev fault1-sink is left/); + expect(qemu.filters.size).toBe(0); + } finally { + await closeServer(qemu.server); + } + }); + + test("an unexpected query reply refuses before any change", async () => { + if (process.platform === "win32") return; + const state = running("fault-odd"); + const qemu = await fakeQemu(state.machineDir, (command) => (command.startsWith("qom-get") ? `"off"` : undefined)); + try { + const instance = instanceOf("fault-odd"); + await expect(instance.fault("ether2", { drop: "egress" })).rejects.toThrow(`QEMU answered ""off"" to "qom-get /objects/fault1 queue". No earlier port was changed.`); + await expect(instance.faults()).rejects.toMatchObject({ code: "PROCESS_FAILED" }); + expect(qemu.commands.filter((c) => !c.startsWith("qom-get"))).toEqual([]); + } finally { + await closeServer(qemu.server); + } + }); + + test("a monitor that closes mid-change reports the port's outcome as unknown", async () => { + if (process.platform === "win32") return; + const state = running("fault-drop"); + const commands: string[] = []; + const server = createServer((sock) => { + sock.write("(qemu) "); + sock.on("data", (data) => { + const command = data.toString().trim(); + commands.push(command); + if (command.startsWith("object_add")) sock.destroy(); + else if (command.startsWith("qom-get")) sock.write(`${command}\r\nError: Device '/objects/fault1' not found\r\n(qemu) `); + else if (command === "qom-list /chardevs") sock.write(`${command}\r\ntype (string)\r\n(qemu) `); + else sock.write(`${command}\r\n(qemu) `); + }); + }); + mkdirSync(state.machineDir, { recursive: true }); + await new Promise((resolve) => server.listen(join(state.machineDir, "monitor.sock"), resolve)); + try { + const error = await instanceOf("fault-drop").fault({ ether2: { drop: "egress" }, ether3: null }).catch((e: unknown) => e); + expect(error).toMatchObject({ code: "PROCESS_FAILED" }); + expect((error as Error).message).toContain("Whether ether2 changed is unknown."); + expect((error as Error).message).toContain("Not attempted: ether3=none."); + } finally { + await closeServer(server); + } + }); +}); + +describe("quickchr set --fault and list", () => { + test("applies repeated assignments, and list shows the faults in place", async () => { + if (process.platform === "win32") return; + const state = running("cli-fault"); + const qemu = await fakeQemu(state.machineDir); + try { + const result = await runQuickchr(["set", "cli-fault", "--fault", "ether3=ingress", "--fault", "ether2=egress", "--fault", "ether3=both"]); + expect(result.stderr).toBe(""); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain("Fault on cli-fault: ether3=both, ether2=egress"); + expect(qemu.filters.get("fault2")?.queue).toBe("all"); + expect(qemu.filters.get("fault1")?.queue).toBe("rx"); + + const human = await runQuickchr(["list", "cli-fault"]); + expect(human.stdout).toContain("Fault: ether2 dropping egress (carrier untouched)"); + expect(human.stdout).toContain("Fault: ether3 dropping both ways (carrier untouched)"); + const json = JSON.parse((await runQuickchr(["list", "cli-fault", "--json"])).stdout); + expect(json.faults).toEqual({ ether2: { drop: "egress" }, ether3: { drop: "both" } }); + + expect((await runQuickchr(["set", "cli-fault", "--fault", "ether2=none", "--fault", "ether3=none"])).exitCode).toBe(0); + expect(qemu.filters.size).toBe(0); + } finally { + await closeServer(qemu.server); + } + }); + + test("a stopped machine lists no faults; a malformed or mixed call changes nothing", async () => { + if (process.platform === "win32") return; + saveMachine(machine("cli-fault-stopped")); + expect(JSON.parse((await runQuickchr(["list", "cli-fault-stopped", "--json"])).stdout).faults).toEqual({}); + + const state = running("cli-fault-bad"); + const qemu = await fakeQemu(state.machineDir); + try { + const malformed = await runQuickchr(["set", "cli-fault-bad", "--fault", "ether2=egress", "--fault", "ether3=lossy"]); + expect(malformed.exitCode).not.toBe(0); + expect(malformed.stderr).toContain(`must be "egress", "ingress" or "both"`); + const mixed = await runQuickchr(["set", "cli-fault-bad", "--fault", "ether2=egress", "--link", "ether3=down"]); + expect(mixed.exitCode).not.toBe(0); + expect(mixed.stderr).toMatch(/cannot be combined with --(fault|link)/); + const bare = await runQuickchr(["set", "cli-fault-bad", "--fault", "ether2=egress", "--no-fault"]); + expect(bare.exitCode).not.toBe(0); + expect(bare.stderr).toContain("--no-fault (not a supported negation — --fault takes a value)"); + expect(qemu.commands).toEqual([]); + } finally { + await closeServer(qemu.server); + } + }); +}); From c85fe6e49bea3a82431240b3bb9caa52ede88d92 Mon Sep 17 00:00:00 2001 From: TIKOCI RouterOS Bots Date: Tue, 1 Dec 2026 16:32:24 -0800 Subject: [PATCH 2/8] fix(network): fault state from one info-network snapshot, with ownership checks (#369) Review fixes (Codex Sol High on #373): - fault()/faults() read every port from one `info network` (+ `qom-list /chardevs` when applying). One monitor command is one snapshot, so faults() can't mix states across a concurrent batch, and it needs no machine lock (start --fg holds it). - A fault filter counts as quickchr's only if it is a filter-redirector on net writing to fault-sink with no indev; any other object or chardev with those ids is refused (STATE_ERROR) and never reported, changed or deleted. - A clear retried after chardev-remove failed now removes the leftover sink. - Integration: each one-way drop also asserts the other direction still delivers. - MANUAL example order. Co-Authored-By: Claude Opus 5.5 --- .github/instructions/qemu.instructions.md | 5 +- DESIGN.md | 23 ++-- MANUAL.md | 2 +- src/lib/fault.ts | 89 ++++++++++++--- src/lib/quickchr.ts | 53 +++++---- test/integration/link-fault.test.ts | 9 +- test/unit/fault.test.ts | 127 +++++++++++++++------- 7 files changed, 214 insertions(+), 94 deletions(-) diff --git a/.github/instructions/qemu.instructions.md b/.github/instructions/qemu.instructions.md index 2891b6a6..fbc12b76 100644 --- a/.github/instructions/qemu.instructions.md +++ b/.github/instructions/qemu.instructions.md @@ -253,7 +253,10 @@ from `net/filter*.c` (QEMU master and 11.1.2) and `test/lab/link-impairment/REPO '' not found` or `object '' not found`. `qom-get /objects/ queue` prints the value as JSON (`"rx"`), or `Device '/objects/' not found`. `qom-list /objects` and `qom-list /chardevs` print ` (child)` / - ` (child)` lines. + ` (child)` lines. `info network` prints every property of each filter + under its netdev's `filters:` line (` - fault1: type=filter-redirector,vnet_hdr_support=false,indev=,outdev=fault1-sink,position=head,status=on,insert=behind,netdev=net1,queue=all`), + so one command reads every port's state. quickchr's `fault()` and `faults()` use it, + since one monitor command can't interleave with commands from another connection. - **Filter order: the head is the wire side.** QEMU walks a netdev's filters head to tail for frames delivered to the guest and tail to head for frames the guest sends. `info network` lists each netdev's filters in chain order, with `position=` and diff --git a/DESIGN.md b/DESIGN.md index b975de42..ccdd8a04 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1291,15 +1291,20 @@ netdev's side), and `qom-set … queue` changes it per frame. So egress → both command with no moment where frames pass, and a port never has two filters to keep consistent. Clearing is `object_del` and then `chardev-remove`. -**State is read from QEMU, never stored.** Each port's change starts with -`qom-get /objects/fault queue`: a value is the drop in place, and QEMU's -`Device … not found` means none. The plan from there is zero to three commands, so a -repeat is a no-op. A sink left behind by an earlier failure (`qom-list /chardevs`) is -removed before a new one is added. A filter QEMU refuses after its sink was added gets -the sink removed again. A clear whose sink QEMU keeps reports that the drop itself is -gone. `faults()` and `list ` read the same query for every NIC. HMP has no read-back -for carrier (`info network` doesn't show `set_link`), so status says "carrier -untouched", not "up". +**State is read from QEMU, never stored.** A change starts, under the lock, from one +`info network` (every netdev's filters with type, `netdev`, `outdev` and `queue`) and one +`qom-list /chardevs` (ids with types). A `fault` counts as quickchr's only if it is a +`filter-redirector` on `net` writing to `fault-sink` with no `indev`. Anything else +holding the id, such as a `qemuArgs` filter that happens to be named `fault1`, is refused +with `STATE_ERROR` and never reported, changed or deleted. The plan from the snapshot is +zero to three commands, so a repeat is a no-op. A sink an earlier failure left behind (a +`null` chardev no filter uses) is removed before a new one is added, and by a clear, so +retrying a clear whose `chardev-remove` failed finishes it. A filter QEMU refuses after +its sink was added gets the sink removed again. `faults()` and `list ` read one +`info network` too: a single monitor command is one snapshot, so a batch applied from +another process is seen whole or not at all, without taking the machine lock (a +`start --fg` session holds that for its whole run). HMP has no read-back for carrier +(`info network` doesn't show `set_link`), so status says "carrier untouched", not "up". **Added at run time, unlike capture.** A capture filter is never `object_add`ed because its timestamps would take a different base (#338). A drop has no such diff --git a/MANUAL.md b/MANUAL.md index 91bd2f83..9a5f9913 100644 --- a/MANUAL.md +++ b/MANUAL.md @@ -1767,9 +1767,9 @@ process or reboot: ```sh quickchr set lab-a --fault ether3=egress # frames lab-a sends on ether3 vanish +quickchr list lab-a # Fault: ether3 dropping egress (carrier untouched) quickchr set lab-a --fault ether3=both --fault ether2=ingress quickchr set lab-a --fault ether3=none --fault ether2=none # clear -quickchr list lab-a # Fault: ether3 dropping egress (carrier untouched) ``` ```ts diff --git a/src/lib/fault.ts b/src/lib/fault.ts index ad2bfc72..1f3fa189 100644 --- a/src/lib/fault.ts +++ b/src/lib/fault.ts @@ -134,32 +134,83 @@ export function resolveFaultTargets( }); } -/** The HMP command that reads a port's current fault. */ -export function faultQueryCommand(filterId: string): string { - return `qom-get /objects/${filterId} queue`; +/** HMP command that lists every netdev's filters with their properties, in chain order. + * One command is one snapshot: QEMU runs a monitor command whole, so a batch applied + * from another monitor connection can't be half-seen within it. */ +export const FAULT_SNAPSHOT_COMMAND = "info network"; + +/** HMP command that lists chardevs with their types. */ +export const CHARDEV_LIST_COMMAND = "qom-list /chardevs"; + +/** One filter as `info network` prints it (` - fault2: type=filter-redirector,…,netdev=net2,queue=rx`). */ +export interface FilterInfo { + type: string; + props: Record; } -/** What a {@link faultQueryCommand} reply says: the drop in place, `null` for no - * filter (QEMU 11.1.2: `Error: Device '/objects/fault2' not found`), or the reply as - * an error when it is neither. HMP prints the value as JSON (`"rx"`). */ -export function parseFaultQuery(reply: string, filterId: string): { drop: FaultDrop | null } | { error: string } { - const text = reply.trim(); - if (text === `Error: Device '/objects/${filterId}' not found`) return { drop: null }; - const queue = text.replace(/^"(.*)"$/, "$1"); - const drop = DROPS.find((d) => QUEUE_OF[d] === queue); - return drop ? { drop } : { error: text === "" ? "an empty reply" : `"${text}"` }; +/** Every filter in an `info network` reply, by id. Values are split at commas, which + * is exact for the redirector's ids and enums (a `filter-dump` file path may break, + * but only its `type` is read). */ +export function parseFilters(reply: string): Map { + const filters = new Map(); + for (const line of reply.split(/\r?\n/)) { + const m = /^\s*- ([^:\s]+): type=([^,\s]+)(.*)$/.exec(line); + if (!m?.[1] || !m[2]) continue; + const props: Record = {}; + for (const pair of (m[3] ?? "").split(",")) { + const eq = pair.indexOf("="); + if (eq > 0) props[pair.slice(0, eq)] = pair.slice(eq + 1).trim(); + } + filters.set(m[1], { type: m[2], props }); + } + return filters; } -/** Chardev ids from an HMP `qom-list /chardevs` reply (`fault2-sink (child)`). */ -export function parseChardevList(reply: string): Set { - const ids = new Set(); +/** Chardev ids and types from a `qom-list /chardevs` reply (`fault2-sink (child)`). */ +export function parseChardevList(reply: string): Map { + const ids = new Map(); for (const line of reply.split(/\r?\n/)) { - const m = /^(\S+) \(child]+>\)$/.exec(line.trim()); - if (m?.[1]) ids.add(m[1]); + const m = /^(\S+) \(child<(chardev-[^>]+)>\)$/.exec(line.trim()); + if (m?.[1] && m[2]) ids.set(m[1], m[2]); } return ids; } +/** The fault quickchr has in place on a port, from a filter snapshot: `null` for none, + * or a conflict when something else holds the filter id — an object quickchr did not + * create (a `qemuArgs` filter named `fault`), which it neither reports nor touches. */ +export function faultInPlace( + ids: { netdev: string; filterId: string; sinkId: string }, + filters: ReadonlyMap, +): { drop: FaultDrop | null } | { conflict: string } { + const f = filters.get(ids.filterId); + if (!f) return { drop: null }; + const ours = f.type === "filter-redirector" && f.props.netdev === ids.netdev && f.props.outdev === ids.sinkId && !f.props.indev; + const drop = DROPS.find((d) => QUEUE_OF[d] === f.props.queue); + if (ours && drop) return { drop }; + return { + conflict: `QEMU already has a filter "${ids.filterId}" that quickchr did not create (type=${f.type}, netdev=${f.props.netdev ?? "?"}); ` + + "fault() leaves it alone. Rename it in the machine's qemuArgs", + }; +} + +/** Whether a port's sink id is free, held by a sink an earlier failure left behind + * (a `null` chardev no filter uses: removed before reuse), or held by something else. */ +export function sinkState( + sinkId: string, + chardevs: ReadonlyMap, + filters: ReadonlyMap, +): "free" | "stale" | { conflict: string } { + const type = chardevs.get(sinkId); + if (type === undefined) return "free"; + const user = [...filters].find(([, f]) => f.props.outdev === sinkId || f.props.indev === sinkId)?.[0]; + if (type === "chardev-null" && user === undefined) return "stale"; + return { + conflict: `QEMU already has a chardev "${sinkId}" (${type}${user ? `, used by filter ${user}` : ""}) that quickchr did not create; ` + + "fault() leaves it alone. Rename it in the machine's qemuArgs", + }; +} + /** One HMP command in a fault change, and what it does (for messages). */ export interface FaultStep { command: string; @@ -168,9 +219,11 @@ export interface FaultStep { /** The HMP steps that take a port from `current` to `target.drop`. Empty when it is * already there. `staleSink` is a sink chardev left behind by an earlier failure, - * removed before a new one is added. */ + * removed before a new one is added, or on its own by a clear. */ export function planFaultSteps(target: FaultTarget, current: FaultDrop | null, staleSink: boolean): FaultStep[] { const want = target.drop; + // A clear retried after QEMU kept the sink: the filter is gone, the sink isn't. + if (want === null && current === null) return staleSink ? [{ kind: "remove-sink", command: `chardev-remove ${target.sinkId}` }] : []; if (want === current) return []; if (want === null) { return [ diff --git a/src/lib/quickchr.ts b/src/lib/quickchr.ts index 75d3ec22..ae775d6c 100644 --- a/src/lib/quickchr.ts +++ b/src/lib/quickchr.ts @@ -77,7 +77,7 @@ import { pidLiveness } from "./pid.ts"; import { buildQemuArgs, spawnQemu, QemuEarlyExitError, stopQemu, foreignQemuError, liveQemuFor, clearStalePidfile, cleanupQemuSockets, waitForBoot, waitForApiReady, readinessProbeFor, type QemuLaunchConfig, type QemuSpawn } from "./qemu.ts"; import { bootDiskFormatOf, bootDiskPath, cleanDiskFiles, ensureConfiguredDisks, normalizeDiskOptions, writeBootDisk, parseSnapshotList, listSnapshots, mergeSnapshotMetadata, formatDiskSize } from "./disk.ts"; import { formatLinkChanges, normalizeLinkChanges, resolveLinkTargets, setLinkCommand, setLinkFailure, type LinkChange, type LinkTarget } from "./link.ts"; -import { faultIds, faultQueryCommand, formatFaultChanges, normalizeFaultChanges, parseChardevList, parseFaultQuery, planFaultSteps, resolveFaultTargets, type FaultChange, type FaultStep, type FaultTarget } from "./fault.ts"; +import { CHARDEV_LIST_COMMAND, FAULT_SNAPSHOT_COMMAND, faultIds, faultInPlace, formatFaultChanges, normalizeFaultChanges, parseChardevList, parseFilters, planFaultSteps, resolveFaultTargets, sinkState, type FaultChange, type FaultStep, type FaultTarget, type FilterInfo } from "./fault.ts"; import { assertCaptureDirsOutside, captureCommand, captureFilesOf, carryCaptureFiles, formatCaptureChanges, normalizeCaptureChanges, removeIfEmpty, reserveCaptureFiles, resolveCaptureTargets, type CaptureChange, type CaptureTarget } from "./capture.ts"; import { monitorCommand, serialStreams, qgaCommand, channelEndpoint, channelFileExists, channelPath, MONITOR_FAST_QUERY_TIMEOUT_MS, MONITOR_SAVEVM_TIMEOUT_MS, MONITOR_LOADVM_TIMEOUT_MS, MONITOR_DELVM_TIMEOUT_MS } from "./channels.ts"; import { captureBootFailure, newBootProbeStats, preserveOnFailure, type BootFailureReport, type BootProbeStats, type FailureTrigger } from "./diagnostics.ts"; @@ -1066,7 +1066,7 @@ function linkFailureMessage( } /** `fault()` (#369): validate against the locked, refreshed state, then bring each port - * in order from the fault QEMU has now (`qom-get … queue`) to the one asked for. A + * in order from the fault QEMU has now (one `info network` snapshot) to the one asked for. A * port already there costs no change. As with `link()`, the first failure stops the * batch and names the ports already changed; a filter QEMU refuses after its sink was * added has that sink removed again. Nothing is persisted: a new QEMU starts clean. */ @@ -1082,27 +1082,38 @@ export async function applyFaultChanges(state: MachineState, changes: readonly F `Machine "${state.name}" is not running — a fault is a runtime change to a running QEMU, and a new launch starts with none.`, ); } - let chardevs: Set | undefined; + // One snapshot of every filter and chardev, under the lock: no other quickchr + // writer can change them, so each port's plan is made from what QEMU has. + const hmp = (command: string) => monitorCommand(state.machineDir, command, undefined, state.portBase, { requirePrompt: true }); + let filters: Map; + let chardevs: Map; + try { + filters = parseFilters(await hmp(FAULT_SNAPSHOT_COMMAND)); + chardevs = parseChardevList(await hmp(CHARDEV_LIST_COMMAND)); + } catch (err) { + const code = err instanceof QuickCHRError ? err.code : "PROCESS_FAILED"; + throw new QuickCHRError(code, `Reading QEMU's filters on "${state.name}" failed: ${err instanceof Error ? err.message : String(err)}. No port was changed.`); + } const applied: FaultTarget[] = []; for (const target of targets) { const failure = (code: ErrorCode, reason: string, outcomeUnknown: boolean) => new QuickCHRError(code, faultFailureMessage(state.name, target, reason, applied, targets, outcomeUnknown)); const send = async (command: string, outcomeUnknown: boolean): Promise => { try { - return (await monitorCommand(state.machineDir, command, undefined, state.portBase, { requirePrompt: true })).trim(); + return (await hmp(command)).trim(); } catch (err) { const code = err instanceof QuickCHRError ? err.code : "PROCESS_FAILED"; throw failure(code, err instanceof Error ? err.message : String(err), outcomeUnknown); } }; - const queryCommand = faultQueryCommand(target.filterId); - const query = parseFaultQuery(await send(queryCommand, false), target.filterId); - if ("error" in query) throw failure("PROCESS_FAILED", `QEMU answered ${query.error} to "${queryCommand}"`, false); - const current = query.drop; + const inPlace = faultInPlace(target, filters); + if ("conflict" in inPlace) throw failure("STATE_ERROR", inPlace.conflict, false); + const current = inPlace.drop; let staleSink = false; - if (target.drop !== null && current === null) { - chardevs ??= parseChardevList(await send("qom-list /chardevs", false)); - staleSink = chardevs.has(target.sinkId); + if (current === null) { + const sink = sinkState(target.sinkId, chardevs, filters); + if (typeof sink === "object") throw failure("STATE_ERROR", sink.conflict, false); + staleSink = sink === "stale"; } const steps = planFaultSteps(target, current, staleSink); for (const step of steps) { @@ -1111,8 +1122,6 @@ export async function applyFaultChanges(state: MachineState, changes: readonly F const why = await faultStepRefusal(step, reply, target, current, send); throw failure("PROCESS_FAILED", why, false); } - if (step.kind === "add-sink") chardevs?.add(target.sinkId); - if (step.kind === "remove-sink") chardevs?.delete(target.sinkId); } applied.push(target); } @@ -1168,9 +1177,11 @@ function faultFailureMessage( return parts.join(" "); } -/** The faults QEMU has in place now, by port (#369): one `qom-get … queue` per quickchr - * NIC. Read from the machine's current record, so it follows a restart made elsewhere; - * a handle whose machine was removed (or replaced) is `MACHINE_NOT_FOUND`. */ +/** The faults quickchr has in place now, by port (#369), from one `info network`: a + * single monitor command, so a batch applied meanwhile is seen whole or not at all. + * A filter with a fault id that quickchr did not create is not reported. Read from + * the machine's current record, so it follows a restart made elsewhere; a handle + * whose machine was removed (or replaced) is `MACHINE_NOT_FOUND`. */ export async function readFaults(state: MachineState): Promise> { const fresh = loadMachine(state.name); if (!fresh || fresh.createdAt !== state.createdAt) { @@ -1182,15 +1193,11 @@ export async function readFaults(state: MachineState): Promise = {}; for (const [i, nic] of fresh.networks.entries()) { - const { filterId } = faultIds(nic.id); - const command = faultQueryCommand(filterId); - const query = parseFaultQuery(await monitorCommand(fresh.machineDir, command, undefined, fresh.portBase, { requirePrompt: true }), filterId); - if ("error" in query) { - throw new QuickCHRError("PROCESS_FAILED", `Reading ether${i + 1}'s fault on "${state.name}": QEMU answered ${query.error} to "${command}".`); - } - if (query.drop) out[`ether${i + 1}`] = { drop: query.drop }; + const inPlace = faultInPlace({ netdev: nic.id, ...faultIds(nic.id) }, filters); + if ("drop" in inPlace && inPlace.drop) out[`ether${i + 1}`] = { drop: inPlace.drop }; } return out; } diff --git a/test/integration/link-fault.test.ts b/test/integration/link-fault.test.ts index a2130515..a0e274bc 100644 --- a/test/integration/link-fault.test.ts +++ b/test/integration/link-fault.test.ts @@ -17,7 +17,8 @@ import { bootTestTimeout } from "./timeouts.ts"; * while ether3 keeps `running=yes` on both ends and the bond keeps carrying traffic on * ether2; clearing it brings the member back. The captures show where the filter sits: * A's capture still has the LACPDUs A sends into the drop and B's gets none of them, and - * under an ingress drop A's capture has none of B's. `faults()` reads each state back, + * under an ingress drop A's capture has none of B's. Each time the other direction keeps + * delivering, so the drop is one-way. `faults()` reads each state back, * including a change of direction made in place. */ @@ -114,6 +115,7 @@ describe.skipIf(SKIP)("one-way drop that keeps carrier (#369)", () => { const aSent0 = await lacpFrom(aCap, aMac); await a.fault("ether3", { drop: "egress" }); const bHeard0 = await lacpFrom(bCap, aMac); + const aHeardFromB0 = await lacpFrom(aCap, bMac); expect(await a.faults()).toEqual({ ether3: { drop: "egress" } }); const out = await until("B to drop ether3 from its bond", async () => !(await inBond(b)).includes("ether3"), 60_000); console.log(` B dropped ether3 ${(out / 1000).toFixed(1)} s after the egress drop`); @@ -125,6 +127,8 @@ describe.skipIf(SKIP)("one-way drop that keeps carrier (#369)", () => { // A's capture is the guest's side of the drop: what A sent is in it, and none reached B. expect(await lacpFrom(aCap, aMac) - aSent0).toBeGreaterThan(2); expect(await lacpFrom(bCap, aMac)).toBe(bHeard0); + // One way only: B's LACPDUs still reach A over the same port. + expect(await lacpFrom(aCap, bMac) - aHeardFromB0).toBeGreaterThan(2); await a.fault("ether3", null); expect(await a.faults()).toEqual({}); @@ -136,9 +140,12 @@ describe.skipIf(SKIP)("one-way drop that keeps carrier (#369)", () => { await a.fault({ ether3: { drop: "ingress" } }); const aHeard0 = await lacpFrom(aCap, bMac); const bSent0 = await lacpFrom(bCap, bMac); + const bHeardFromA0 = await lacpFrom(bCap, aMac); await Bun.sleep(4000); expect(await lacpFrom(aCap, bMac)).toBe(aHeard0); expect(await lacpFrom(bCap, bMac) - bSent0).toBeGreaterThan(1); + // One way only: A's LACPDUs still reach B. + expect(await lacpFrom(bCap, aMac) - bHeardFromA0).toBeGreaterThan(1); // A change of direction is made in place and reads back. await a.fault("ether3", { drop: "both" }); expect(await a.faults()).toEqual({ ether3: { drop: "both" } }); diff --git a/test/unit/fault.test.ts b/test/unit/fault.test.ts index 34827666..cba49800 100644 --- a/test/unit/fault.test.ts +++ b/test/unit/fault.test.ts @@ -10,13 +10,17 @@ import { normalizeFaultChanges, parseChardevList, parseFaultAssignments, - parseFaultQuery, + faultInPlace, + parseFilters, + sinkState, planFaultSteps, resolveFaultTargets, } from "../../src/lib/fault.ts"; import { loadMachine, saveMachine } from "../../src/lib/state.ts"; import type { MachineState, NetworkConfig, NicFault } from "../../src/lib/types.ts"; +type FakeFilter = { type: string; netdev: string; queue: string; outdev?: string; indev?: string }; + /** * NIC faults (#369) without a guest: validation, ids, the HMP plan, and the locked * sequence against a fake HMP that keeps QEMU's object and chardev state and answers @@ -65,34 +69,48 @@ function running(name: string, overrides: Partial = {}): MachineSt interface FakeQemu { server: Server; commands: string[]; - filters: Map; - chardevs: Set; + filters: Map; + chardevs: Map; +} + +/** `info network` as QEMU 11.1.2 prints it: each NIC and netdev, then its filters in order. */ +function infoNetwork(filters: ReadonlyMap): string { + const lines: string[] = []; + for (const [i, nic] of THREE_PORTS.entries()) { + lines.push(`virtio-net-pci.${i}: index=0,type=nic,model=virtio-net-pci,macaddr=52:54:00:12:34:5${i}`); + lines.push(` \\ ${nic.id}: index=0,type=${i === 0 ? "user,net=10.0.2.0,restrict=off" : `dgram,udp=/x/${nic.id}.0.sock:/x/${nic.id}.1.sock`}`); + const mine = [...filters].filter(([, f]) => f.netdev === nic.id); + if (mine.length > 0) lines.push("filters:"); + for (const [id, f] of mine) { + lines.push(f.type === "filter-redirector" + ? ` - ${id}: type=filter-redirector,vnet_hdr_support=false,indev=${f.indev ?? ""},outdev=${f.outdev ?? ""},position=head,status=on,insert=behind,netdev=${f.netdev},queue=${f.queue}` + : ` - ${id}: type=${f.type},file=/tmp/a,b.pcap,maxlen=65536,position=tail,status=on,insert=behind,netdev=${f.netdev},queue=${f.queue}`); + } + } + return lines.join("\r\n"); } /** A stand-in for QEMU's HMP over the filter and chardev commands `fault()` uses, with * QEMU 11.1.2's reply texts. `refuse` answers a command with an error instead. */ async function fakeQemu(machineDir: string, refuse: (command: string) => string | undefined = () => undefined): Promise { const commands: string[] = []; - const filters = new Map(); - const chardevs = new Set(["compat_monitor0"]); + const filters = new Map(); + const chardevs = new Map([["compat_monitor0", "chardev-socket"]]); const netdevs = new Set(THREE_PORTS.map((n) => n.id)); const routes: Array<[RegExp, (m: string[]) => string]> = [ - [/^qom-get \/objects\/(\S+) queue$/, ([, id = ""]) => { - const f = filters.get(id); - return f ? `"${f.queue}"` : `Error: Device '/objects/${id}' not found`; - }], + [/^info network$/, () => infoNetwork(filters)], [/^qom-list \/chardevs$/, () => - ["type (string)", ...[...chardevs].map((id) => `${id} (child)`)].join("\r\n")], + ["type (string)", ...[...chardevs].map(([id, type]) => `${id} (child<${type}>)`)].join("\r\n")], [/^chardev-add null,id=(\S+)$/, ([, id = ""]) => { if (chardevs.has(id)) return `Error: attempt to add duplicate property '${id}' to object (type 'container')`; - chardevs.add(id); + chardevs.set(id, "chardev-null"); return ""; }], [/^object_add filter-redirector,id=([^,]+),netdev=([^,]+),queue=([^,]+),outdev=([^,]+),position=head$/, ([, id = "", netdev = "", queue = "", outdev = ""]) => { if (filters.has(id)) return `Error: attempt to add duplicate property '${id}' to object (type 'container')`; if (!netdevs.has(netdev)) return "Error: Parameter 'netdev' expects a network backend id"; if (!chardevs.has(outdev)) return `Error: Device '${outdev}' not found`; - filters.set(id, { netdev, queue, outdev }); + filters.set(id, { type: "filter-redirector", netdev, queue, outdev }); return ""; }], [/^qom-set \/objects\/(\S+) queue (\S+)$/, ([, id = "", queue = ""]) => { @@ -104,7 +122,7 @@ async function fakeQemu(machineDir: string, refuse: (command: string) => string [/^object_del (\S+)$/, ([, id = ""]) => (filters.delete(id) ? "" : `Error: object '${id}' not found`)], [/^chardev-remove (\S+)$/, ([, id = ""]) => { if (!chardevs.has(id)) return `Error: Chardev '${id}' not found`; - if ([...filters.values()].some((f) => f.outdev === id)) return `Error: Chardev '${id}' is busy`; + if ([...filters.values()].some((f) => f.outdev === id || f.indev === id)) return `Error: Chardev '${id}' is busy`; chardevs.delete(id); return ""; }], @@ -241,15 +259,30 @@ describe("ids, targets, plan and replies", () => { expect(planFaultSteps(t(null), "ingress", false).map((s) => s.command)).toEqual(["object_del fault1", "chardev-remove fault1-sink"]); }); - test("QEMU 11.1.2 replies: a queue value, a missing filter, and anything else", () => { - expect(parseFaultQuery('"rx"', "fault1")).toEqual({ drop: "egress" }); - expect(parseFaultQuery('"tx"', "fault1")).toEqual({ drop: "ingress" }); - expect(parseFaultQuery('"all"\r\n', "fault1")).toEqual({ drop: "both" }); - expect(parseFaultQuery("Error: Device '/objects/fault1' not found", "fault1")).toEqual({ drop: null }); - expect(parseFaultQuery("Error: Device '/objects/fault2' not found", "fault1")).toEqual({ error: `"Error: Device '/objects/fault2' not found"` }); - expect(parseFaultQuery("", "fault1")).toEqual({ error: "an empty reply" }); - expect([...parseChardevList("type (string)\r\nx2 (child)\r\ncompat_monitor0 (child)\r\nfault1-sink (child)\r\n")]) - .toEqual(["x2", "compat_monitor0", "fault1-sink"]); + test("QEMU 11.1.2 snapshots: ours, none, someone else's filter or chardev", () => { + // Verbatim from QEMU 11.1.2 (a boot filter-dump on net1 and an added fault1). + const real = parseFilters([ + "virtio-net-pci.1: index=0,type=nic,model=virtio-net-pci,macaddr=52:54:00:12:34:57", + " \\ net1: index=0,type=user,net=10.0.2.0,restrict=off", + "filters:", + " - fault1: type=filter-redirector,vnet_hdr_support=false,indev=,outdev=fault1-sink,position=head,status=on,insert=behind,netdev=net1,queue=all", + " - cap1: type=filter-dump,file=/tmp/cap1.pcap,maxlen=65536,position=tail,status=on,insert=behind,netdev=net1,queue=all", + ].join("\r\n")); + expect([...real.keys()]).toEqual(["fault1", "cap1"]); + const ids = { netdev: "net1", ...faultIds("net1") }; + expect(faultInPlace(ids, real)).toEqual({ drop: "both" }); + expect(faultInPlace({ netdev: "net2", ...faultIds("net2") }, real)).toEqual({ drop: null }); + const foreign = new Map([["fault1", { type: "filter-dump", props: { netdev: "net1", queue: "rx" } }]]); + expect(faultInPlace(ids, foreign)).toMatchObject({ conflict: expect.stringContaining("did not create (type=filter-dump, netdev=net1)") }); + const elsewhere = new Map([["fault1", { type: "filter-redirector", props: { netdev: "net2", outdev: "fault1-sink", queue: "rx" } }]]); + expect(faultInPlace(ids, elsewhere)).toHaveProperty("conflict"); + + const chardevs = parseChardevList("type (string)\r\nx2 (child)\r\ncompat_monitor0 (child)\r\nfault1-sink (child)\r\n"); + expect([...chardevs]).toEqual([["x2", "chardev-null"], ["compat_monitor0", "chardev-socket"], ["fault1-sink", "chardev-null"]]); + expect(sinkState("fault2-sink", chardevs, new Map())).toBe("free"); + expect(sinkState("fault1-sink", chardevs, new Map())).toBe("stale"); + expect(sinkState("fault1-sink", chardevs, real)).toHaveProperty("conflict"); + expect(sinkState("compat_monitor0", chardevs, new Map())).toMatchObject({ conflict: expect.stringContaining("chardev-socket") }); }); }); @@ -284,7 +317,7 @@ describe("ChrInstance.fault() without a guest", () => { const instance = instanceOf("fault-cycle"); await instance.fault("ether3", { drop: "egress" }); expect(qemu.commands).toEqual([ - "qom-get /objects/fault2 queue", + "info network", "qom-list /chardevs", "chardev-add null,id=fault2-sink", "object_add filter-redirector,id=fault2,netdev=net2,queue=rx,outdev=fault2-sink,position=head", @@ -293,15 +326,14 @@ describe("ChrInstance.fault() without a guest", () => { qemu.commands.length = 0; await instance.fault("ether3", { drop: "egress" }); - expect(qemu.commands).toEqual(["qom-get /objects/fault2 queue"]); + expect(qemu.commands).toEqual(["info network", "qom-list /chardevs"]); qemu.commands.length = 0; await instance.fault({ ether3: { drop: "both" }, ether2: { drop: "ingress" } }); expect(qemu.commands).toEqual([ - "qom-get /objects/fault2 queue", - "qom-set /objects/fault2 queue all", - "qom-get /objects/fault1 queue", + "info network", "qom-list /chardevs", + "qom-set /objects/fault2 queue all", "chardev-add null,id=fault1-sink", "object_add filter-redirector,id=fault1,netdev=net1,queue=tx,outdev=fault1-sink,position=head", ]); @@ -309,7 +341,7 @@ describe("ChrInstance.fault() without a guest", () => { await instance.fault({ ether2: null, ether3: null, ether1: null }); expect(qemu.filters.size).toBe(0); - expect([...qemu.chardevs]).toEqual(["compat_monitor0"]); + expect([...qemu.chardevs.keys()]).toEqual(["compat_monitor0"]); expect(await instance.faults()).toEqual({}); expect(JSON.stringify(loadMachine("fault-cycle"))).toBe(before); } finally { @@ -321,7 +353,7 @@ describe("ChrInstance.fault() without a guest", () => { if (process.platform === "win32") return; const state = running("fault-stale"); const qemu = await fakeQemu(state.machineDir); - qemu.chardevs.add("fault1-sink"); + qemu.chardevs.set("fault1-sink", "chardev-null"); try { await instanceOf("fault-stale").fault("ether2", { drop: "egress" }); expect(qemu.commands.slice(2)).toEqual([ @@ -329,7 +361,7 @@ describe("ChrInstance.fault() without a guest", () => { "chardev-add null,id=fault1-sink", "object_add filter-redirector,id=fault1,netdev=net1,queue=rx,outdev=fault1-sink,position=head", ]); - expect(qemu.filters.get("fault1")).toEqual({ netdev: "net1", queue: "rx", outdev: "fault1-sink" }); + expect(qemu.filters.get("fault1")).toEqual({ type: "filter-redirector", netdev: "net1", queue: "rx", outdev: "fault1-sink" }); } finally { await closeServer(qemu.server); } @@ -354,7 +386,7 @@ describe("ChrInstance.fault() without a guest", () => { expect(message).toContain("Not attempted: ether1=ingress."); expect(qemu.commands.at(-1)).toBe("chardev-remove fault2-sink"); expect([...qemu.filters.keys()]).toEqual(["fault1"]); - expect([...qemu.chardevs]).toEqual(["compat_monitor0", "fault1-sink"]); + expect([...qemu.chardevs.keys()]).toEqual(["compat_monitor0", "fault1-sink"]); } finally { await closeServer(qemu.server); } @@ -374,29 +406,43 @@ describe("ChrInstance.fault() without a guest", () => { } }); - test("a clear whose sink QEMU keeps says the drop itself is gone", async () => { + test("a clear whose sink QEMU keeps says the drop is gone, and a retried clear removes the sink", async () => { if (process.platform === "win32") return; const state = running("fault-sink-kept"); - const qemu = await fakeQemu(state.machineDir, (command) => (command === "chardev-remove fault1-sink" ? "Error: Chardev 'fault1-sink' is busy" : undefined)); + let keepSink = true; + const qemu = await fakeQemu(state.machineDir, (command) => + keepSink && command === "chardev-remove fault1-sink" ? "Error: Chardev 'fault1-sink' is busy" : undefined); try { const instance = instanceOf("fault-sink-kept"); await instance.fault("ether2", { drop: "both" }); await expect(instance.fault("ether2", null)).rejects.toThrow(/The drop on ether2 is cleared; only its sink chardev fault1-sink is left/); expect(qemu.filters.size).toBe(0); + expect(await instance.faults()).toEqual({}); + keepSink = false; + qemu.commands.length = 0; + await instance.fault("ether2", null); + expect(qemu.commands).toEqual(["info network", "qom-list /chardevs", "chardev-remove fault1-sink"]); + expect([...qemu.chardevs.keys()]).toEqual(["compat_monitor0"]); } finally { await closeServer(qemu.server); } }); - test("an unexpected query reply refuses before any change", async () => { + test("a filter or chardev quickchr did not create is never reported or touched", async () => { if (process.platform === "win32") return; - const state = running("fault-odd"); - const qemu = await fakeQemu(state.machineDir, (command) => (command.startsWith("qom-get") ? `"off"` : undefined)); + const state = running("fault-foreign"); + const qemu = await fakeQemu(state.machineDir); + // A qemuArgs capture that happens to be called fault1, and a socket chardev named like a sink. + qemu.filters.set("fault1", { type: "filter-dump", netdev: "net1", queue: "rx" }); + qemu.chardevs.set("fault2-sink", "chardev-socket"); try { - const instance = instanceOf("fault-odd"); - await expect(instance.fault("ether2", { drop: "egress" })).rejects.toThrow(`QEMU answered ""off"" to "qom-get /objects/fault1 queue". No earlier port was changed.`); - await expect(instance.faults()).rejects.toMatchObject({ code: "PROCESS_FAILED" }); - expect(qemu.commands.filter((c) => !c.startsWith("qom-get"))).toEqual([]); + const instance = instanceOf("fault-foreign"); + expect(await instance.faults()).toEqual({}); + await expect(instance.fault("ether2", null)).rejects.toMatchObject({ code: "STATE_ERROR", message: expect.stringContaining(`filter "fault1" that quickchr did not create (type=filter-dump, netdev=net1)`) }); + await expect(instance.fault("ether2", { drop: "egress" })).rejects.toMatchObject({ code: "STATE_ERROR" }); + await expect(instance.fault("ether3", { drop: "egress" })).rejects.toThrow(`chardev "fault2-sink" (chardev-socket) that quickchr did not create`); + expect(qemu.commands.filter((c) => c !== "info network" && c !== "qom-list /chardevs")).toEqual([]); + expect(qemu.filters.get("fault1")?.type).toBe("filter-dump"); } finally { await closeServer(qemu.server); } @@ -412,7 +458,6 @@ describe("ChrInstance.fault() without a guest", () => { const command = data.toString().trim(); commands.push(command); if (command.startsWith("object_add")) sock.destroy(); - else if (command.startsWith("qom-get")) sock.write(`${command}\r\nError: Device '/objects/fault1' not found\r\n(qemu) `); else if (command === "qom-list /chardevs") sock.write(`${command}\r\ntype (string)\r\n(qemu) `); else sock.write(`${command}\r\n(qemu) `); }); From 0433d9c4d3b05a56a8b6e8e85ff2480a1cf7cd66 Mon Sep 17 00:00:00 2001 From: TIKOCI RouterOS Bots Date: Tue, 1 Dec 2026 16:45:39 -0800 Subject: [PATCH 3/8] fix(network): a fault filter is ours only with a null sink and status on (#369) CodeRabbit review on #373: - A fault filter whose sink is not a null chardev (e.g. a qemuArgs socket chardev named fault-sink) is refused, so a clear can't remove someone else's chardev. faults() reads qom-list /chardevs alongside info network for the same check. - A filter switched off outside fault() (status=off) is not reported as a drop, and fault() refuses to change it. - Docs: a read doesn't see a batch atomically (it is applied port by port); undoing a refused setup is best-effort. Co-Authored-By: Claude Opus 5.5 --- .github/instructions/qemu.instructions.md | 6 ++-- DESIGN.md | 9 ++++-- MANUAL.md | 4 ++- src/lib/fault.ts | 23 +++++++++++--- src/lib/quickchr.ts | 17 +++++++---- src/lib/types.ts | 5 +-- test/unit/fault.test.ts | 37 +++++++++++++++++++---- 7 files changed, 77 insertions(+), 24 deletions(-) diff --git a/.github/instructions/qemu.instructions.md b/.github/instructions/qemu.instructions.md index fbc12b76..33bbcc2d 100644 --- a/.github/instructions/qemu.instructions.md +++ b/.github/instructions/qemu.instructions.md @@ -255,8 +255,10 @@ from `net/filter*.c` (QEMU master and 11.1.2) and `test/lab/link-impairment/REPO and `qom-list /chardevs` print ` (child)` / ` (child)` lines. `info network` prints every property of each filter under its netdev's `filters:` line (` - fault1: type=filter-redirector,vnet_hdr_support=false,indev=,outdev=fault1-sink,position=head,status=on,insert=behind,netdev=net1,queue=all`), - so one command reads every port's state. quickchr's `fault()` and `faults()` use it, - since one monitor command can't interleave with commands from another connection. + so one command reads every port's state at one instant. quickchr's `fault()` and + `faults()` use it: one monitor command can't interleave with commands from another + connection, though a batch of several commands from another connection can be seen + half-applied. - **Filter order: the head is the wire side.** QEMU walks a netdev's filters head to tail for frames delivered to the guest and tail to head for frames the guest sends. `info network` lists each netdev's filters in chain order, with `position=` and diff --git a/DESIGN.md b/DESIGN.md index ccdd8a04..5c46e1c8 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1301,9 +1301,12 @@ zero to three commands, so a repeat is a no-op. A sink an earlier failure left b `null` chardev no filter uses) is removed before a new one is added, and by a clear, so retrying a clear whose `chardev-remove` failed finishes it. A filter QEMU refuses after its sink was added gets the sink removed again. `faults()` and `list ` read one -`info network` too: a single monitor command is one snapshot, so a batch applied from -another process is seen whole or not at all, without taking the machine lock (a -`start --fg` session holds that for its whole run). HMP has no read-back for carrier +`info network` and `qom-list /chardevs` too. A single monitor command reads every port +at one instant, without taking the machine lock (a `start --fg` session holds that for +its whole run). A batch is applied port by port, so a read in the middle of one can show +its first ports changed and not the rest. A filter that matches but writes to a sink that +isn't a `null` chardev, or one switched off outside `fault()` (`status=off`), counts as +not quickchr's: it is refused and not reported. HMP has no read-back for carrier (`info network` doesn't show `set_link`), so status says "carrier untouched", not "up". **Added at run time, unlike capture.** A capture filter is never `object_add`ed diff --git a/MANUAL.md b/MANUAL.md index 9a5f9913..6b274a21 100644 --- a/MANUAL.md +++ b/MANUAL.md @@ -1802,7 +1802,9 @@ await chr.faults(); // { ether3: { drop: " what the guest sent, dropped or not, and only what reached it. - **Validated first, then applied in order**, under the machine lock, like `--link`. A failure stops the batch and names the ports already changed. If - QEMU refuses part of one port's setup, that part is undone. + QEMU refuses part of one port's setup, quickchr tries to undo the rest. If QEMU + refuses that too, the error names what was left, and the next `--fault` on that + port removes it. ### Named L2 sockets diff --git a/src/lib/fault.ts b/src/lib/fault.ts index 1f3fa189..845b033b 100644 --- a/src/lib/fault.ts +++ b/src/lib/fault.ts @@ -176,18 +176,33 @@ export function parseChardevList(reply: string): Map { return ids; } -/** The fault quickchr has in place on a port, from a filter snapshot: `null` for none, - * or a conflict when something else holds the filter id — an object quickchr did not - * create (a `qemuArgs` filter named `fault`), which it neither reports nor touches. */ +/** The fault quickchr has in place on a port, from a filter and chardev snapshot: `null` + * for none, or a conflict when the filter id is held by something quickchr would not + * have made — a `qemuArgs` filter named `fault`, a sink that isn't a `null` chardev, + * or a filter switched off outside `fault()` — which it neither reports nor touches. */ export function faultInPlace( ids: { netdev: string; filterId: string; sinkId: string }, filters: ReadonlyMap, + chardevs: ReadonlyMap, ): { drop: FaultDrop | null } | { conflict: string } { const f = filters.get(ids.filterId); if (!f) return { drop: null }; - const ours = f.type === "filter-redirector" && f.props.netdev === ids.netdev && f.props.outdev === ids.sinkId && !f.props.indev; + const ours = f.type === "filter-redirector" && f.props.netdev === ids.netdev && f.props.outdev === ids.sinkId && !f.props.indev && + chardevs.get(ids.sinkId) === "chardev-null"; const drop = DROPS.find((d) => QUEUE_OF[d] === f.props.queue); + if (ours && drop && f.props.status === "off") { + return { + conflict: `Filter "${ids.filterId}" was switched off outside fault() (status=off), so it drops nothing. ` + + `Switch it back with monitor("qom-set /objects/${ids.filterId} status on") before changing it with fault()`, + }; + } if (ours && drop) return { drop }; + if (f.type === "filter-redirector" && f.props.outdev === ids.sinkId && chardevs.get(ids.sinkId) !== "chardev-null") { + return { + conflict: `QEMU's filter "${ids.filterId}" writes to "${ids.sinkId}", which is ${chardevs.has(ids.sinkId) ? `a ${chardevs.get(ids.sinkId)}` : "missing"}, ` + + "not the null chardev fault() creates; fault() leaves both alone. Rename them in the machine's qemuArgs", + }; + } return { conflict: `QEMU already has a filter "${ids.filterId}" that quickchr did not create (type=${f.type}, netdev=${f.props.netdev ?? "?"}); ` + "fault() leaves it alone. Rename it in the machine's qemuArgs", diff --git a/src/lib/quickchr.ts b/src/lib/quickchr.ts index ae775d6c..2156d709 100644 --- a/src/lib/quickchr.ts +++ b/src/lib/quickchr.ts @@ -1106,7 +1106,7 @@ export async function applyFaultChanges(state: MachineState, changes: readonly F throw failure(code, err instanceof Error ? err.message : String(err), outcomeUnknown); } }; - const inPlace = faultInPlace(target, filters); + const inPlace = faultInPlace(target, filters, chardevs); if ("conflict" in inPlace) throw failure("STATE_ERROR", inPlace.conflict, false); const current = inPlace.drop; let staleSink = false; @@ -1129,7 +1129,8 @@ export async function applyFaultChanges(state: MachineState, changes: readonly F } /** Why a fault step failed, and where that leaves the port. A filter QEMU refused after - * its sink was added gets the sink removed again, so a refusal leaves nothing behind. */ + * its sink was added gets the sink removed again, best-effort: if QEMU refuses that too, + * the message names the sink left behind, and the next `fault()` on the port removes it. */ async function faultStepRefusal( step: FaultStep, reply: string, @@ -1178,8 +1179,10 @@ function faultFailureMessage( } /** The faults quickchr has in place now, by port (#369), from one `info network`: a - * single monitor command, so a batch applied meanwhile is seen whole or not at all. - * A filter with a fault id that quickchr did not create is not reported. Read from + * single monitor command, so every port is read at the same instant. It takes no lock, + * so a batch being applied at that instant can show its first ports changed and not + * the rest. A filter with a fault id that quickchr did not create, or one switched off + * outside `fault()`, is not reported. Read from * the machine's current record, so it follows a restart made elsewhere; a handle * whose machine was removed (or replaced) is `MACHINE_NOT_FOUND`. */ export async function readFaults(state: MachineState): Promise> { @@ -1193,10 +1196,12 @@ export async function readFaults(state: MachineState): Promise monitorCommand(fresh.machineDir, command, undefined, fresh.portBase, { requirePrompt: true }); + const filters = parseFilters(await hmp(FAULT_SNAPSHOT_COMMAND)); + const chardevs = parseChardevList(await hmp(CHARDEV_LIST_COMMAND)); const out: Record = {}; for (const [i, nic] of fresh.networks.entries()) { - const inPlace = faultInPlace({ netdev: nic.id, ...faultIds(nic.id) }, filters); + const inPlace = faultInPlace({ netdev: nic.id, ...faultIds(nic.id) }, filters, chardevs); if ("drop" in inPlace && inPlace.drop) out[`ether${i + 1}`] = { drop: inPlace.drop }; } return out; diff --git a/src/lib/types.ts b/src/lib/types.ts index 8290d9a8..6422c38e 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -1076,8 +1076,9 @@ export interface ChrInstance { * starts with no fault. A guest reboot inside the same QEMU keeps it. * * The batch form validates every port first, then applies them in order under the - * machine lock; a failure stops the batch and names the ports already changed. A - * port's own setup is undone if QEMU refuses part of it. Throws `INVALID_ARGUMENT` + * machine lock; a failure stops the batch and names the ports already changed. If + * QEMU refuses part of a port's setup, quickchr tries to undo the rest, and names + * anything it couldn't remove. Throws `INVALID_ARGUMENT` * for a bad port or fault, `MACHINE_STOPPED` when QEMU is not running, * `PROCESS_FAILED` when QEMU refuses. * @example diff --git a/test/unit/fault.test.ts b/test/unit/fault.test.ts index cba49800..0a93ea0e 100644 --- a/test/unit/fault.test.ts +++ b/test/unit/fault.test.ts @@ -19,7 +19,7 @@ import { import { loadMachine, saveMachine } from "../../src/lib/state.ts"; import type { MachineState, NetworkConfig, NicFault } from "../../src/lib/types.ts"; -type FakeFilter = { type: string; netdev: string; queue: string; outdev?: string; indev?: string }; +type FakeFilter = { type: string; netdev: string; queue: string; outdev?: string; indev?: string; status?: string }; /** * NIC faults (#369) without a guest: validation, ids, the HMP plan, and the locked @@ -83,7 +83,7 @@ function infoNetwork(filters: ReadonlyMap): string { if (mine.length > 0) lines.push("filters:"); for (const [id, f] of mine) { lines.push(f.type === "filter-redirector" - ? ` - ${id}: type=filter-redirector,vnet_hdr_support=false,indev=${f.indev ?? ""},outdev=${f.outdev ?? ""},position=head,status=on,insert=behind,netdev=${f.netdev},queue=${f.queue}` + ? ` - ${id}: type=filter-redirector,vnet_hdr_support=false,indev=${f.indev ?? ""},outdev=${f.outdev ?? ""},position=head,status=${f.status ?? "on"},insert=behind,netdev=${f.netdev},queue=${f.queue}` : ` - ${id}: type=${f.type},file=/tmp/a,b.pcap,maxlen=65536,position=tail,status=on,insert=behind,netdev=${f.netdev},queue=${f.queue}`); } } @@ -270,12 +270,18 @@ describe("ids, targets, plan and replies", () => { ].join("\r\n")); expect([...real.keys()]).toEqual(["fault1", "cap1"]); const ids = { netdev: "net1", ...faultIds("net1") }; - expect(faultInPlace(ids, real)).toEqual({ drop: "both" }); - expect(faultInPlace({ netdev: "net2", ...faultIds("net2") }, real)).toEqual({ drop: null }); + const nullSink = new Map([["fault1-sink", "chardev-null"]]); + expect(faultInPlace(ids, real, nullSink)).toEqual({ drop: "both" }); + expect(faultInPlace({ netdev: "net2", ...faultIds("net2") }, real, nullSink)).toEqual({ drop: null }); const foreign = new Map([["fault1", { type: "filter-dump", props: { netdev: "net1", queue: "rx" } }]]); - expect(faultInPlace(ids, foreign)).toMatchObject({ conflict: expect.stringContaining("did not create (type=filter-dump, netdev=net1)") }); + expect(faultInPlace(ids, foreign, nullSink)).toMatchObject({ conflict: expect.stringContaining("did not create (type=filter-dump, netdev=net1)") }); const elsewhere = new Map([["fault1", { type: "filter-redirector", props: { netdev: "net2", outdev: "fault1-sink", queue: "rx" } }]]); - expect(faultInPlace(ids, elsewhere)).toHaveProperty("conflict"); + expect(faultInPlace(ids, elsewhere, nullSink)).toHaveProperty("conflict"); + // Our shape, but writing to someone else's socket chardev; or switched off by hand. + expect(faultInPlace(ids, real, new Map([["fault1-sink", "chardev-socket"]]))).toMatchObject({ conflict: expect.stringContaining("which is a chardev-socket") }); + expect(faultInPlace(ids, real, new Map())).toMatchObject({ conflict: expect.stringContaining("which is missing") }); + const off = new Map([["fault1", { type: "filter-redirector", props: { netdev: "net1", outdev: "fault1-sink", indev: "", queue: "rx", status: "off" } }]]); + expect(faultInPlace(ids, off, nullSink)).toMatchObject({ conflict: expect.stringContaining("switched off outside fault() (status=off)") }); const chardevs = parseChardevList("type (string)\r\nx2 (child)\r\ncompat_monitor0 (child)\r\nfault1-sink (child)\r\n"); expect([...chardevs]).toEqual([["x2", "chardev-null"], ["compat_monitor0", "chardev-socket"], ["fault1-sink", "chardev-null"]]); @@ -448,6 +454,25 @@ describe("ChrInstance.fault() without a guest", () => { } }); + test("a filter switched off outside fault() is not reported, and fault() refuses it", async () => { + if (process.platform === "win32") return; + const state = running("fault-off"); + const qemu = await fakeQemu(state.machineDir); + try { + const instance = instanceOf("fault-off"); + await instance.fault("ether2", { drop: "egress" }); + const filter = qemu.filters.get("fault1"); + if (!filter) throw new Error("fault1 was not created"); + filter.status = "off"; // what monitor("qom-set /objects/fault1 status off") leaves + expect(await instance.faults()).toEqual({}); + const before = qemu.commands.length; + await expect(instance.fault("ether2", null)).rejects.toMatchObject({ code: "STATE_ERROR", message: expect.stringContaining("status=off") }); + expect(qemu.commands.slice(before)).toEqual(["info network", "qom-list /chardevs"]); + } finally { + await closeServer(qemu.server); + } + }); + test("a monitor that closes mid-change reports the port's outcome as unknown", async () => { if (process.platform === "win32") return; const state = running("fault-drop"); From 74bafd1e54e1d30aaec5eb5ff8a9e9660e8d6c80 Mon Sep 17 00:00:00 2001 From: TIKOCI RouterOS Bots Date: Tue, 1 Dec 2026 16:51:43 -0800 Subject: [PATCH 4/8] fix(network): coherent fault read-back; retry wording; status=off covered live (#369) CodeRabbit follow-ups on #373: - faults() reads `info network` on both sides of `qom-list /chardevs` and keeps the pair only when the two filter reads agree (up to 5 attempts), so a batch applied between the commands can't mix one port's old filter with its new sink state. - A failed sink removal says the next fault() on the port tries again, not that it removes it. - Integration: a filter switched off through the raw monitor is not reported and fault() refuses it (STATE_ERROR), on real QEMU. Co-Authored-By: Claude Opus 5.5 --- DESIGN.md | 5 +++-- MANUAL.md | 2 +- src/lib/quickchr.ts | 31 ++++++++++++++++++++--------- test/integration/link-fault.test.ts | 7 +++++++ test/unit/fault.test.ts | 26 +++++++++++++++++++++++- 5 files changed, 58 insertions(+), 13 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 5c46e1c8..13d10eb5 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1301,8 +1301,9 @@ zero to three commands, so a repeat is a no-op. A sink an earlier failure left b `null` chardev no filter uses) is removed before a new one is added, and by a clear, so retrying a clear whose `chardev-remove` failed finishes it. A filter QEMU refuses after its sink was added gets the sink removed again. `faults()` and `list ` read one -`info network` and `qom-list /chardevs` too. A single monitor command reads every port -at one instant, without taking the machine lock (a `start --fg` session holds that for +`info network` and `qom-list /chardevs` too, reading the filters on both sides of the +chardevs and retrying until the two agree, so the pair is coherent. One `info network` +reads every port at one instant, without taking the machine lock (a `start --fg` session holds that for its whole run). A batch is applied port by port, so a read in the middle of one can show its first ports changed and not the rest. A filter that matches but writes to a sink that isn't a `null` chardev, or one switched off outside `fault()` (`status=off`), counts as diff --git a/MANUAL.md b/MANUAL.md index 6b274a21..b9f3cc7c 100644 --- a/MANUAL.md +++ b/MANUAL.md @@ -1804,7 +1804,7 @@ await chr.faults(); // { ether3: { drop: " `--link`. A failure stops the batch and names the ports already changed. If QEMU refuses part of one port's setup, quickchr tries to undo the rest. If QEMU refuses that too, the error names what was left, and the next `--fault` on that - port removes it. + port tries to remove it again. ### Named L2 sockets diff --git a/src/lib/quickchr.ts b/src/lib/quickchr.ts index 2156d709..4d65ac0a 100644 --- a/src/lib/quickchr.ts +++ b/src/lib/quickchr.ts @@ -1130,7 +1130,7 @@ export async function applyFaultChanges(state: MachineState, changes: readonly F /** Why a fault step failed, and where that leaves the port. A filter QEMU refused after * its sink was added gets the sink removed again, best-effort: if QEMU refuses that too, - * the message names the sink left behind, and the next `fault()` on the port removes it. */ + * the message names the sink left behind, and the next `fault()` on the port tries again. */ async function faultStepRefusal( step: FaultStep, reply: string, @@ -1150,11 +1150,11 @@ async function faultStepRefusal( } return undo === "" ? `${refused}. ${now}; its sink chardev was removed again` - : `${refused}. ${now}, but removing its sink chardev ${target.sinkId} failed too (${undo}); the next fault() on ${target.port} removes it`; + : `${refused}. ${now}, but removing its sink chardev ${target.sinkId} failed too (${undo}); the next fault() on ${target.port} tries to remove it again`; } case "remove-sink": if (target.drop === null) { - return `${refused}. The drop on ${target.port} is cleared; only its sink chardev ${target.sinkId} is left, and the next fault() on ${target.port} removes it`; + return `${refused}. The drop on ${target.port} is cleared; only its sink chardev ${target.sinkId} is left, and the next fault() on ${target.port} tries to remove it again`; } return `${refused}. ${now}`; default: @@ -1178,10 +1178,12 @@ function faultFailureMessage( return parts.join(" "); } -/** The faults quickchr has in place now, by port (#369), from one `info network`: a - * single monitor command, so every port is read at the same instant. It takes no lock, - * so a batch being applied at that instant can show its first ports changed and not - * the rest. A filter with a fault id that quickchr did not create, or one switched off +const FAULT_READ_ATTEMPTS = 5; + +/** The faults quickchr has in place now, by port (#369), from `info network` (every + * port at one instant) checked against `qom-list /chardevs`, with the filters read on + * both sides of the chardevs and retried until they agree. It takes no lock, so a batch + * being applied at that moment can show its first ports changed and not the rest. A filter with a fault id that quickchr did not create, or one switched off * outside `fault()`, is not reported. Read from * the machine's current record, so it follows a restart made elsewhere; a handle * whose machine was removed (or replaced) is `MACHINE_NOT_FOUND`. */ @@ -1197,8 +1199,19 @@ export async function readFaults(state: MachineState): Promise monitorCommand(fresh.machineDir, command, undefined, fresh.portBase, { requirePrompt: true }); - const filters = parseFilters(await hmp(FAULT_SNAPSHOT_COMMAND)); - const chardevs = parseChardevList(await hmp(CHARDEV_LIST_COMMAND)); + // Filters and chardevs are two commands. Read the filters on both sides of the + // chardevs and keep the pair only when they agree, so a batch applied in between + // can't combine one port's old filter with its new sink state. + let pair: { filters: Map; chardevs: Map } | undefined; + for (let attempt = 0; attempt < FAULT_READ_ATTEMPTS && !pair; attempt++) { + const before = await hmp(FAULT_SNAPSHOT_COMMAND); + const chardevReply = await hmp(CHARDEV_LIST_COMMAND); + if (before === await hmp(FAULT_SNAPSHOT_COMMAND)) pair = { filters: parseFilters(before), chardevs: parseChardevList(chardevReply) }; + } + if (!pair) { + throw new QuickCHRError("PROCESS_FAILED", `QEMU's filters on "${state.name}" kept changing while they were read (${FAULT_READ_ATTEMPTS} attempts); try again.`); + } + const { filters, chardevs } = pair; const out: Record = {}; for (const [i, nic] of fresh.networks.entries()) { const inPlace = faultInPlace({ netdev: nic.id, ...faultIds(nic.id) }, filters, chardevs); diff --git a/test/integration/link-fault.test.ts b/test/integration/link-fault.test.ts index a0e274bc..e7991816 100644 --- a/test/integration/link-fault.test.ts +++ b/test/integration/link-fault.test.ts @@ -150,6 +150,13 @@ describe.skipIf(SKIP)("one-way drop that keeps carrier (#369)", () => { await a.fault("ether3", { drop: "both" }); expect(await a.faults()).toEqual({ ether3: { drop: "both" } }); expect(await carrier(a, "ether3")).toBe(true); + // Switched off by hand (raw monitor): not a fault, and fault() won't touch it. + expect(await a.monitor("qom-set /objects/fault2 status off")).toBe(""); + expect(await a.faults()).toEqual({}); + await expect(a.fault("ether3", null)).rejects.toMatchObject({ code: "STATE_ERROR" }); + await expect(a.fault("ether3", { drop: "egress" })).rejects.toMatchObject({ code: "STATE_ERROR" }); + expect(await a.monitor("qom-set /objects/fault2 status on")).toBe(""); + expect(await a.faults()).toEqual({ ether3: { drop: "both" } }); await a.fault("ether3", null); await until("ether3 back in both bonds after ingress/both", whole, 60_000); }, bootTestTimeout({ boots: 2, extraMs: 120_000 })); diff --git a/test/unit/fault.test.ts b/test/unit/fault.test.ts index 0a93ea0e..b99ebe94 100644 --- a/test/unit/fault.test.ts +++ b/test/unit/fault.test.ts @@ -421,7 +421,7 @@ describe("ChrInstance.fault() without a guest", () => { try { const instance = instanceOf("fault-sink-kept"); await instance.fault("ether2", { drop: "both" }); - await expect(instance.fault("ether2", null)).rejects.toThrow(/The drop on ether2 is cleared; only its sink chardev fault1-sink is left/); + await expect(instance.fault("ether2", null)).rejects.toThrow(/The drop on ether2 is cleared; only its sink chardev fault1-sink is left, and the next fault\(\) on ether2 tries to remove it again/); expect(qemu.filters.size).toBe(0); expect(await instance.faults()).toEqual({}); keepSink = false; @@ -454,6 +454,30 @@ describe("ChrInstance.fault() without a guest", () => { } }); + test("faults() rereads the filters around the chardevs until both reads agree", async () => { + if (process.platform === "win32") return; + const state = running("fault-reread"); + let reads = 0; + let unstable = false; + const qemu = await fakeQemu(state.machineDir, (command) => { + if (command !== "info network") return undefined; + reads++; + if (unstable) return `changed ${reads}`; + return reads === 1 ? "filters:" : undefined; // the first read differs from the second + }); + try { + const instance = instanceOf("fault-reread"); + qemu.filters.set("fault1", { type: "filter-redirector", netdev: "net1", queue: "tx", outdev: "fault1-sink" }); + qemu.chardevs.set("fault1-sink", "chardev-null"); + expect(await instance.faults()).toEqual({ ether2: { drop: "ingress" } }); + expect(qemu.commands).toEqual(["info network", "qom-list /chardevs", "info network", "info network", "qom-list /chardevs", "info network"]); + unstable = true; + await expect(instance.faults()).rejects.toThrow(/kept changing while they were read \(5 attempts\)/); + } finally { + await closeServer(qemu.server); + } + }); + test("a filter switched off outside fault() is not reported, and fault() refuses it", async () => { if (process.platform === "win32") return; const state = running("fault-off"); From d921011f8a824584070af3bb5157d279251d51c3 Mon Sep 17 00:00:00 2001 From: TIKOCI RouterOS Bots Date: Tue, 1 Dec 2026 16:55:27 -0800 Subject: [PATCH 5/8] fix(network): fault read-back also requires each fault filter's sink in the chardev read (#369) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CodeRabbit follow-up on #373: an A → B → A pair of batches between the two filter reads could leave them identical while the chardev read in between lacked a sink. QEMU refuses to remove a chardev a filter uses, so a fault filter whose sink is missing from the chardev read means the reads came from different moments: retry. Regression test for that sequence. Co-Authored-By: Claude Opus 5.5 --- DESIGN.md | 5 ++++- src/lib/quickchr.ts | 19 +++++++++++++++---- test/unit/fault.test.ts | 21 +++++++++++++++++++++ 3 files changed, 40 insertions(+), 5 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 13d10eb5..c3e66150 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1302,7 +1302,10 @@ zero to three commands, so a repeat is a no-op. A sink an earlier failure left b retrying a clear whose `chardev-remove` failed finishes it. A filter QEMU refuses after its sink was added gets the sink removed again. `faults()` and `list ` read one `info network` and `qom-list /chardevs` too, reading the filters on both sides of the -chardevs and retrying until the two agree, so the pair is coherent. One `info network` +chardevs and retrying until the two agree and every fault filter's sink is listed. QEMU +refuses to remove a chardev a filter uses, so a missing sink means the reads came from +different moments, even when a batch and its undo (A → B → A) left both filter reads +identical. That makes the pair coherent against quickchr's own writers without a lock. One `info network` reads every port at one instant, without taking the machine lock (a `start --fg` session holds that for its whole run). A batch is applied port by port, so a read in the middle of one can show its first ports changed and not the rest. A filter that matches but writes to a sink that diff --git a/src/lib/quickchr.ts b/src/lib/quickchr.ts index 4d65ac0a..e3dd9908 100644 --- a/src/lib/quickchr.ts +++ b/src/lib/quickchr.ts @@ -1182,7 +1182,8 @@ const FAULT_READ_ATTEMPTS = 5; /** The faults quickchr has in place now, by port (#369), from `info network` (every * port at one instant) checked against `qom-list /chardevs`, with the filters read on - * both sides of the chardevs and retried until they agree. It takes no lock, so a batch + * both sides of the chardevs and retried until they agree and every fault filter's + * sink is listed. It takes no lock, so a batch * being applied at that moment can show its first ports changed and not the rest. A filter with a fault id that quickchr did not create, or one switched off * outside `fault()`, is not reported. Read from * the machine's current record, so it follows a restart made elsewhere; a handle @@ -1200,13 +1201,23 @@ export async function readFaults(state: MachineState): Promise monitorCommand(fresh.machineDir, command, undefined, fresh.portBase, { requirePrompt: true }); // Filters and chardevs are two commands. Read the filters on both sides of the - // chardevs and keep the pair only when they agree, so a batch applied in between - // can't combine one port's old filter with its new sink state. + // chardevs and keep the pair only when they agree and every fault filter's sink is + // in the chardev list: QEMU refuses to remove a chardev a filter uses, so a missing + // one means the reads came from different moments, even when a batch and its undo + // (A → B → A) left the two filter reads identical. + const faultIdsOf = fresh.networks.map((nic) => faultIds(nic.id)); let pair: { filters: Map; chardevs: Map } | undefined; for (let attempt = 0; attempt < FAULT_READ_ATTEMPTS && !pair; attempt++) { const before = await hmp(FAULT_SNAPSHOT_COMMAND); const chardevReply = await hmp(CHARDEV_LIST_COMMAND); - if (before === await hmp(FAULT_SNAPSHOT_COMMAND)) pair = { filters: parseFilters(before), chardevs: parseChardevList(chardevReply) }; + if (before !== await hmp(FAULT_SNAPSHOT_COMMAND)) continue; + const filters = parseFilters(before); + const chardevs = parseChardevList(chardevReply); + const sinkMissing = faultIdsOf.some(({ filterId }) => { + const outdev = filters.get(filterId)?.props.outdev; + return outdev !== undefined && outdev !== "" && !chardevs.has(outdev); + }); + if (!sinkMissing) pair = { filters, chardevs }; } if (!pair) { throw new QuickCHRError("PROCESS_FAILED", `QEMU's filters on "${state.name}" kept changing while they were read (${FAULT_READ_ATTEMPTS} attempts); try again.`); diff --git a/test/unit/fault.test.ts b/test/unit/fault.test.ts index b99ebe94..cfc8c62f 100644 --- a/test/unit/fault.test.ts +++ b/test/unit/fault.test.ts @@ -478,6 +478,27 @@ describe("ChrInstance.fault() without a guest", () => { } }); + test("faults() retries an A → B → A read whose chardev list lacks a filter's sink", async () => { + if (process.platform === "win32") return; + const state = running("fault-aba"); + let chardevReads = 0; + const qemu = await fakeQemu(state.machineDir, (command) => { + if (command !== "qom-list /chardevs") return undefined; + // First chardev read lands while a batch had cleared ether2 (sink gone) and a + // second had not yet restored it; both filter reads around it show fault1. + return ++chardevReads === 1 ? "type (string)\r\ncompat_monitor0 (child)" : undefined; + }); + try { + const instance = instanceOf("fault-aba"); + qemu.filters.set("fault1", { type: "filter-redirector", netdev: "net1", queue: "rx", outdev: "fault1-sink" }); + qemu.chardevs.set("fault1-sink", "chardev-null"); + expect(await instance.faults()).toEqual({ ether2: { drop: "egress" } }); + expect(chardevReads).toBe(2); + } finally { + await closeServer(qemu.server); + } + }); + test("a filter switched off outside fault() is not reported, and fault() refuses it", async () => { if (process.platform === "win32") return; const state = running("fault-off"); From de24c9e3df12562bfac831d43ea6d63c4e715edf Mon Sep 17 00:00:00 2001 From: TIKOCI RouterOS Bots Date: Tue, 1 Dec 2026 17:06:48 -0800 Subject: [PATCH 6/8] fix(network): one monitor session per fault operation; final review fixes (#369) - Windows integration (run 46782987405): after faults()'s three back-to-back monitor connections, the next connection got no prompt within 5 s (QEMU serves one monitor client at a time). New withMonitorSession() runs several HMP commands over one connection; fault() and faults() use one session each. - The session recognizes the prompt only at the start of the last line, so a filter-dump path containing "(qemu)" can't end an `info network` reply early. - faults() rechecks the machine record after reading: removed/replaced is MACHINE_NOT_FOUND, a restarted QEMU is an error, not a stale answer. - MANUAL/DESIGN: fault / fault-sink are reserved ids; start --fg holds the machine lock, so --fault from another shell is MACHINE_LOCKED. - Integration: the `both` drop is checked with frames in both directions. Co-Authored-By: Claude Opus 5.5 --- DESIGN.md | 11 ++- MANUAL.md | 7 ++ src/lib/channels.ts | 88 +++++++++++++++++++ src/lib/quickchr.ts | 127 ++++++++++++++++------------ test/integration/link-fault.test.ts | 9 +- test/unit/fault.test.ts | 31 +++++++ 6 files changed, 218 insertions(+), 55 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index c3e66150..d98a2c65 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1306,8 +1306,15 @@ chardevs and retrying until the two agree and every fault filter's sink is liste refuses to remove a chardev a filter uses, so a missing sink means the reads came from different moments, even when a batch and its undo (A → B → A) left both filter reads identical. That makes the pair coherent against quickchr's own writers without a lock. One `info network` -reads every port at one instant, without taking the machine lock (a `start --fg` session holds that for -its whole run). A batch is applied port by port, so a read in the middle of one can show +reads every port at one instant, without taking the machine lock, so a read never waits +behind a lock holder. The record is checked again afterwards, so a machine removed, +replaced or restarted during the read is an error, not a stale answer. `fault()` itself +takes the lock, so a `start --fg` session (which holds it for its whole run) refuses +`--fault` from another shell, as it does `--link`. Each operation runs over one monitor +connection (`withMonitorSession()`): QEMU serves one monitor client at a time, and on +Windows a burst of short connections left one waiting past its timeout. The ids +`fault` and `fault-sink` are reserved; an unused `null` chardev with a sink's id is +taken for one an earlier failure left behind. A batch is applied port by port, so a read in the middle of one can show its first ports changed and not the rest. A filter that matches but writes to a sink that isn't a `null` chardev, or one switched off outside `fault()` (`status=off`), counts as not quickchr's: it is refused and not reported. HMP has no read-back for carrier diff --git a/MANUAL.md b/MANUAL.md index b9f3cc7c..47200135 100644 --- a/MANUAL.md +++ b/MANUAL.md @@ -1800,6 +1800,13 @@ await chr.faults(); // { ether3: { drop: " QEMU keeps it. `--fault` can't be combined with the other `set` flags. - **A capture on the same NIC shows the guest's side** (§ "Packet capture"): what the guest sent, dropped or not, and only what reached it. +- **`fault` and `fault-sink` are quickchr's names** for the filter and the + sink chardev on the N+1th NIC (`ether2` is `fault1`). Don't give `--qemu-arg` + objects or chardevs those ids: a filter, or a non-null or in-use chardev, holding + one is refused, but an unused `null` chardev named `fault-sink` is taken for a + sink left behind and removed. +- **A foreground session (`start --fg`) holds the machine lock**, as for `--link`, + so `--fault` from another shell is refused with `MACHINE_LOCKED` while it runs. - **Validated first, then applied in order**, under the machine lock, like `--link`. A failure stops the batch and names the ports already changed. If QEMU refuses part of one port's setup, quickchr tries to undo the rest. If QEMU diff --git a/src/lib/channels.ts b/src/lib/channels.ts index 1b0bae72..5de736ea 100644 --- a/src/lib/channels.ts +++ b/src/lib/channels.ts @@ -187,6 +187,94 @@ export async function monitorCommand( }); } +/** Run several HMP commands over one monitor connection, in turn: `fn` gets a `send` + * that writes one command and resolves with its cleaned reply at the next prompt. + * + * QEMU's monitor serves one client at a time, and a new connection waits until QEMU + * has noticed the last one close. On Windows (TCP monitor) a burst of short connections + * left one waiting past its timeout with no prompt (#369, run 46782987405), so an + * operation that needs several commands opens one session instead. + * + * Errors match `monitorCommand(…, { requirePrompt: true })`: no socket or a refused + * connection is `MACHINE_STOPPED`, a command with no reply within `timeoutMs` is + * `BOOT_TIMEOUT`, and a monitor that closes after a command was sent is `PROCESS_FAILED`. */ +export async function withMonitorSession( + machineDir: string, + portBase: number | undefined, + fn: (send: (command: string) => Promise) => Promise, + timeoutMs: number = MONITOR_FAST_QUERY_TIMEOUT_MS, +): Promise { + if (!channelFileExists(channelPath(machineDir, "monitor"))) { + throw new QuickCHRError("MACHINE_STOPPED", "Monitor socket not found — is the machine running in background mode?"); + } + const endpoint = channelEndpoint(machineDir, "monitor", portBase); + const socket = typeof endpoint === "string" ? connect({ path: endpoint }) : connect(endpoint.port, endpoint.host); + let buffer = ""; + let ended: QuickCHRError | undefined; + let waiter: { command: string | undefined; resolve: (reply: string) => void; reject: (err: Error) => void; timer: ReturnType } | undefined; + + // The prompt is `(qemu) ` at the start of the last line. Matching "(qemu)" anywhere + // would end a reply early at a filter-dump path containing it, since QEMU flushes + // `info network` line by line. + const PROMPT_AT_END = /(?:^|\n)\(qemu\) ?$/; + const settle = (): void => { + // biome-ignore lint/suspicious/noControlCharactersInRegex: ANSI escapes are the point + if (!waiter || !PROMPT_AT_END.test(buffer.replace(/\u001b\[[0-9;?]*[A-Za-z]/g, ""))) return; + const w = waiter; + waiter = undefined; + clearTimeout(w.timer); + const text = buffer; + buffer = ""; + w.resolve(cleanMonitorResponse(text.replace(/\(qemu\) ?$/, ""))); + }; + const fail = (err: QuickCHRError): void => { + ended ??= err; + if (!waiter) return; + const w = waiter; + waiter = undefined; + clearTimeout(w.timer); + w.reject(err); + }; + socket.on("data", (data) => { + buffer += data.toString(); + settle(); + }); + socket.on("close", () => { + const command = waiter?.command; + fail(command !== undefined + ? new QuickCHRError("PROCESS_FAILED", `Monitor closed after "${command}" was sent, before QEMU answered.`) + : new QuickCHRError("MACHINE_STOPPED", "Monitor socket closed before a command could be sent.")); + }); + socket.on("error", (err) => { + const code = (err as NodeJS.ErrnoException).code; + fail(code === "ENOENT" || code === "ECONNREFUSED" + ? new QuickCHRError("MACHINE_STOPPED", "Monitor not available — is the machine running in background mode?") + : new QuickCHRError("PROCESS_FAILED", `Monitor connection failed: ${err.message}`)); + }); + + /** Wait for the next prompt, after writing `command` if one is given. */ + const next = (command: string | undefined): Promise => new Promise((resolve, reject) => { + if (ended) { + reject(ended); + return; + } + const timer = setTimeout(() => { + fail(new QuickCHRError("BOOT_TIMEOUT", `Monitor command timed out after ${timeoutMs}ms: "${command ?? "(waiting for the prompt)"}"`)); + socket.destroy(); + }, timeoutMs); + waiter = { command, resolve, reject, timer }; + if (command === undefined) settle(); + else socket.write(`${command}\n`); + }); + + try { + await next(undefined); + return await fn((command) => next(command)); + } finally { + socket.destroy(); + } +} + /** Get a readable/writable stream pair for the serial console. */ export function serialStreams(machineDir: string, portBase?: number): { readable: ReadableStream; diff --git a/src/lib/quickchr.ts b/src/lib/quickchr.ts index e3dd9908..840a26f7 100644 --- a/src/lib/quickchr.ts +++ b/src/lib/quickchr.ts @@ -79,7 +79,7 @@ import { bootDiskFormatOf, bootDiskPath, cleanDiskFiles, ensureConfiguredDisks, import { formatLinkChanges, normalizeLinkChanges, resolveLinkTargets, setLinkCommand, setLinkFailure, type LinkChange, type LinkTarget } from "./link.ts"; import { CHARDEV_LIST_COMMAND, FAULT_SNAPSHOT_COMMAND, faultIds, faultInPlace, formatFaultChanges, normalizeFaultChanges, parseChardevList, parseFilters, planFaultSteps, resolveFaultTargets, sinkState, type FaultChange, type FaultStep, type FaultTarget, type FilterInfo } from "./fault.ts"; import { assertCaptureDirsOutside, captureCommand, captureFilesOf, carryCaptureFiles, formatCaptureChanges, normalizeCaptureChanges, removeIfEmpty, reserveCaptureFiles, resolveCaptureTargets, type CaptureChange, type CaptureTarget } from "./capture.ts"; -import { monitorCommand, serialStreams, qgaCommand, channelEndpoint, channelFileExists, channelPath, MONITOR_FAST_QUERY_TIMEOUT_MS, MONITOR_SAVEVM_TIMEOUT_MS, MONITOR_LOADVM_TIMEOUT_MS, MONITOR_DELVM_TIMEOUT_MS } from "./channels.ts"; +import { monitorCommand, withMonitorSession, serialStreams, qgaCommand, channelEndpoint, channelFileExists, channelPath, MONITOR_FAST_QUERY_TIMEOUT_MS, MONITOR_SAVEVM_TIMEOUT_MS, MONITOR_LOADVM_TIMEOUT_MS, MONITOR_DELVM_TIMEOUT_MS } from "./channels.ts"; import { captureBootFailure, newBootProbeStats, preserveOnFailure, type BootFailureReport, type BootProbeStats, type FailureTrigger } from "./diagnostics.ts"; import { installPackages, installAllPackages, downloadAndListPackages, downloadPackages, findPackageFile, uploadPackages } from "./packages.ts"; import { ensureEmptySshConfig, provision } from "./provision.ts"; @@ -1082,52 +1082,66 @@ export async function applyFaultChanges(state: MachineState, changes: readonly F `Machine "${state.name}" is not running — a fault is a runtime change to a running QEMU, and a new launch starts with none.`, ); } - // One snapshot of every filter and chardev, under the lock: no other quickchr + // One monitor session for the whole change (see withMonitorSession), starting from + // one snapshot of every filter and chardev, under the lock: no other quickchr // writer can change them, so each port's plan is made from what QEMU has. - const hmp = (command: string) => monitorCommand(state.machineDir, command, undefined, state.portBase, { requirePrompt: true }); - let filters: Map; - let chardevs: Map; + let inSession = false; try { - filters = parseFilters(await hmp(FAULT_SNAPSHOT_COMMAND)); - chardevs = parseChardevList(await hmp(CHARDEV_LIST_COMMAND)); - } catch (err) { - const code = err instanceof QuickCHRError ? err.code : "PROCESS_FAILED"; - throw new QuickCHRError(code, `Reading QEMU's filters on "${state.name}" failed: ${err instanceof Error ? err.message : String(err)}. No port was changed.`); - } - const applied: FaultTarget[] = []; - for (const target of targets) { - const failure = (code: ErrorCode, reason: string, outcomeUnknown: boolean) => - new QuickCHRError(code, faultFailureMessage(state.name, target, reason, applied, targets, outcomeUnknown)); - const send = async (command: string, outcomeUnknown: boolean): Promise => { + await withMonitorSession(state.machineDir, state.portBase, async (hmp) => { + inSession = true; + let filters: Map; + let chardevs: Map; try { - return (await hmp(command)).trim(); + filters = parseFilters(await hmp(FAULT_SNAPSHOT_COMMAND)); + chardevs = parseChardevList(await hmp(CHARDEV_LIST_COMMAND)); } catch (err) { - const code = err instanceof QuickCHRError ? err.code : "PROCESS_FAILED"; - throw failure(code, err instanceof Error ? err.message : String(err), outcomeUnknown); + throw faultReadError(state.name, err); } - }; - const inPlace = faultInPlace(target, filters, chardevs); - if ("conflict" in inPlace) throw failure("STATE_ERROR", inPlace.conflict, false); - const current = inPlace.drop; - let staleSink = false; - if (current === null) { - const sink = sinkState(target.sinkId, chardevs, filters); - if (typeof sink === "object") throw failure("STATE_ERROR", sink.conflict, false); - staleSink = sink === "stale"; - } - const steps = planFaultSteps(target, current, staleSink); - for (const step of steps) { - const reply = await send(step.command, true); - if (reply !== "") { - const why = await faultStepRefusal(step, reply, target, current, send); - throw failure("PROCESS_FAILED", why, false); + const applied: FaultTarget[] = []; + for (const target of targets) { + const failure = (code: ErrorCode, reason: string, outcomeUnknown: boolean) => + new QuickCHRError(code, faultFailureMessage(state.name, target, reason, applied, targets, outcomeUnknown)); + const send = async (command: string, outcomeUnknown: boolean): Promise => { + try { + return (await hmp(command)).trim(); + } catch (err) { + const code = err instanceof QuickCHRError ? err.code : "PROCESS_FAILED"; + throw failure(code, err instanceof Error ? err.message : String(err), outcomeUnknown); + } + }; + const inPlace = faultInPlace(target, filters, chardevs); + if ("conflict" in inPlace) throw failure("STATE_ERROR", inPlace.conflict, false); + const current = inPlace.drop; + let staleSink = false; + if (current === null) { + const sink = sinkState(target.sinkId, chardevs, filters); + if (typeof sink === "object") throw failure("STATE_ERROR", sink.conflict, false); + staleSink = sink === "stale"; + } + const steps = planFaultSteps(target, current, staleSink); + for (const step of steps) { + const reply = await send(step.command, true); + if (reply !== "") { + const why = await faultStepRefusal(step, reply, target, current, send); + throw failure("PROCESS_FAILED", why, false); + } + } + applied.push(target); } - } - applied.push(target); + }); + } catch (err) { + // Failing to open the session (no prompt) changed nothing; anything later is + // already framed with what applied. + throw inSession ? err : faultReadError(state.name, err); } }); } +function faultReadError(machine: string, err: unknown): QuickCHRError { + const code = err instanceof QuickCHRError ? err.code : "PROCESS_FAILED"; + return new QuickCHRError(code, `Reading QEMU's filters on "${machine}" failed: ${err instanceof Error ? err.message : String(err)}. No port was changed.`); +} + /** Why a fault step failed, and where that leaves the port. A filter QEMU refused after * its sink was added gets the sink removed again, best-effort: if QEMU refuses that too, * the message names the sink left behind, and the next `fault()` on the port tries again. */ @@ -1199,29 +1213,38 @@ export async function readFaults(state: MachineState): Promise monitorCommand(fresh.machineDir, command, undefined, fresh.portBase, { requirePrompt: true }); - // Filters and chardevs are two commands. Read the filters on both sides of the + // One monitor session (see withMonitorSession). Filters and chardevs are two commands. Read the filters on both sides of the // chardevs and keep the pair only when they agree and every fault filter's sink is // in the chardev list: QEMU refuses to remove a chardev a filter uses, so a missing // one means the reads came from different moments, even when a batch and its undo // (A → B → A) left the two filter reads identical. const faultIdsOf = fresh.networks.map((nic) => faultIds(nic.id)); - let pair: { filters: Map; chardevs: Map } | undefined; - for (let attempt = 0; attempt < FAULT_READ_ATTEMPTS && !pair; attempt++) { - const before = await hmp(FAULT_SNAPSHOT_COMMAND); - const chardevReply = await hmp(CHARDEV_LIST_COMMAND); - if (before !== await hmp(FAULT_SNAPSHOT_COMMAND)) continue; - const filters = parseFilters(before); - const chardevs = parseChardevList(chardevReply); - const sinkMissing = faultIdsOf.some(({ filterId }) => { - const outdev = filters.get(filterId)?.props.outdev; - return outdev !== undefined && outdev !== "" && !chardevs.has(outdev); - }); - if (!sinkMissing) pair = { filters, chardevs }; - } + const pair = await withMonitorSession(fresh.machineDir, fresh.portBase, async (hmp) => { + for (let attempt = 0; attempt < FAULT_READ_ATTEMPTS; attempt++) { + const before = await hmp(FAULT_SNAPSHOT_COMMAND); + const chardevReply = await hmp(CHARDEV_LIST_COMMAND); + if (before !== await hmp(FAULT_SNAPSHOT_COMMAND)) continue; + const filters = parseFilters(before); + const chardevs = parseChardevList(chardevReply); + const sinkMissing = faultIdsOf.some(({ filterId }) => { + const outdev = filters.get(filterId)?.props.outdev; + return outdev !== undefined && outdev !== "" && !chardevs.has(outdev); + }); + if (!sinkMissing) return { filters, chardevs }; + } + return undefined; + }); if (!pair) { throw new QuickCHRError("PROCESS_FAILED", `QEMU's filters on "${state.name}" kept changing while they were read (${FAULT_READ_ATTEMPTS} attempts); try again.`); } + // No lock: the machine may have been replaced, or restarted, while it was read. + const after = loadMachine(state.name); + if (!after || after.createdAt !== state.createdAt) { + throw new QuickCHRError("MACHINE_NOT_FOUND", `Machine "${state.name}" was removed${after ? " and created again" : ""} while its faults were read.`); + } + if (after.pid !== fresh.pid) { + throw new QuickCHRError("PROCESS_FAILED", `Machine "${state.name}" restarted while its faults were read; a new QEMU starts with none. Try again.`); + } const { filters, chardevs } = pair; const out: Record = {}; for (const [i, nic] of fresh.networks.entries()) { diff --git a/test/integration/link-fault.test.ts b/test/integration/link-fault.test.ts index e7991816..a4e731b1 100644 --- a/test/integration/link-fault.test.ts +++ b/test/integration/link-fault.test.ts @@ -146,10 +146,17 @@ describe.skipIf(SKIP)("one-way drop that keeps carrier (#369)", () => { expect(await lacpFrom(bCap, bMac) - bSent0).toBeGreaterThan(1); // One way only: A's LACPDUs still reach B. expect(await lacpFrom(bCap, aMac) - bHeardFromA0).toBeGreaterThan(1); - // A change of direction is made in place and reads back. + // A change of direction is made in place and reads back, and drops both ways: + // each guest still sends (its own capture), and neither peer receives. await a.fault("ether3", { drop: "both" }); expect(await a.faults()).toEqual({ ether3: { drop: "both" } }); expect(await carrier(a, "ether3")).toBe(true); + const both0 = { aSent: await lacpFrom(aCap, aMac), aHeard: await lacpFrom(aCap, bMac), bSent: await lacpFrom(bCap, bMac), bHeard: await lacpFrom(bCap, aMac) }; + await Bun.sleep(4000); + expect(await lacpFrom(aCap, aMac) - both0.aSent).toBeGreaterThan(1); + expect(await lacpFrom(bCap, bMac) - both0.bSent).toBeGreaterThan(1); + expect(await lacpFrom(aCap, bMac)).toBe(both0.aHeard); + expect(await lacpFrom(bCap, aMac)).toBe(both0.bHeard); // Switched off by hand (raw monitor): not a fault, and fault() won't touch it. expect(await a.monitor("qom-set /objects/fault2 status off")).toBe(""); expect(await a.faults()).toEqual({}); diff --git a/test/unit/fault.test.ts b/test/unit/fault.test.ts index cfc8c62f..b24fc1bd 100644 --- a/test/unit/fault.test.ts +++ b/test/unit/fault.test.ts @@ -478,6 +478,37 @@ describe("ChrInstance.fault() without a guest", () => { } }); + test("a reply with \"(qemu)\" inside a line is not cut short at it", async () => { + if (process.platform === "win32") return; + const state = running("fault-prompt"); + // A capture in a directory named "lab (qemu)", printed (as QEMU flushes it) one line + // per chunk, then the fault line and the real prompt. + const capture = " - cap0: type=filter-dump,file=/tmp/lab (qemu)/x.pcap,maxlen=65536,position=tail,status=on,insert=behind,netdev=net0,queue=all"; + const fault = " - fault1: type=filter-redirector,vnet_hdr_support=false,indev=,outdev=fault1-sink,position=head,status=on,insert=behind,netdev=net1,queue=rx"; + const server = createServer((sock) => { + sock.write("QEMU monitor\r\n(qemu) "); + sock.on("data", async (data) => { + const command = data.toString().trim(); + if (command === "info network") { + sock.write(`${command}\r\nfilters:\r\n${capture}\r\n`); + await Bun.sleep(20); + sock.write(`filters:\r\n${fault}\r\n`); + await Bun.sleep(20); + sock.write("(qemu) "); + } else { + sock.write(`${command}\r\ntype (string)\r\nfault1-sink (child)\r\n(qemu) `); + } + }); + }); + mkdirSync(state.machineDir, { recursive: true }); + await new Promise((resolve) => server.listen(join(state.machineDir, "monitor.sock"), resolve)); + try { + expect(await instanceOf("fault-prompt").faults()).toEqual({ ether2: { drop: "egress" } }); + } finally { + await closeServer(server); + } + }); + test("faults() retries an A → B → A read whose chardev list lacks a filter's sink", async () => { if (process.platform === "win32") return; const state = running("fault-aba"); From cea976acb80c1486772d8bc2d0603d8a55c4dd09 Mon Sep 17 00:00:00 2001 From: TIKOCI RouterOS Bots Date: Tue, 1 Dec 2026 18:27:40 -0800 Subject: [PATCH 7/8] fix(network): 30 s monitor budget for fault sessions; correct the Windows diagnosis (#369) The windows-x86 TCG failure was not connection churn: a probe on the same runner (run 46794639948) made 102 back-to-back monitor connections and sessions, including after a `both` drop's filter was switched off, all answered within 10 ms. The failing step comes right after a two-way drop is lifted with two CHRs renegotiating LACP, which fits a loaded main loop, the pattern channels.ts already records for loaded CI legs. fault()/faults() sessions now get MONITOR_FAULT_TIMEOUT_MS (30 s) per command; withMonitorSession() takes its timeout explicitly, and its docs no longer claim the churn cause. Co-Authored-By: Claude Opus 5.5 --- DESIGN.md | 6 ++++-- src/lib/channels.ts | 18 ++++++++++++------ src/lib/quickchr.ts | 6 +++--- 3 files changed, 19 insertions(+), 11 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index d98a2c65..8bbad398 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1311,8 +1311,10 @@ behind a lock holder. The record is checked again afterwards, so a machine remov replaced or restarted during the read is an error, not a stale answer. `fault()` itself takes the lock, so a `start --fg` session (which holds it for its whole run) refuses `--fault` from another shell, as it does `--link`. Each operation runs over one monitor -connection (`withMonitorSession()`): QEMU serves one monitor client at a time, and on -Windows a burst of short connections left one waiting past its timeout. The ids +connection (`withMonitorSession()`), with a 30 s per-command budget +(`MONITOR_FAULT_TIMEOUT_MS`): on the windows-x86 TCG leg the monitor twice gave no +prompt within the usual 5 s right after a two-way drop was lifted under LACP load, while +an idle CHR on the same runner answered 102 rapid connections within 10 ms. The ids `fault` and `fault-sink` are reserved; an unused `null` chardev with a sink's id is taken for one an earlier failure left behind. A batch is applied port by port, so a read in the middle of one can show its first ports changed and not the rest. A filter that matches but writes to a sink that diff --git a/src/lib/channels.ts b/src/lib/channels.ts index 5de736ea..453026de 100644 --- a/src/lib/channels.ts +++ b/src/lib/channels.ts @@ -70,6 +70,14 @@ export const MONITOR_FAST_QUERY_TIMEOUT_MS = 5000; export const MONITOR_SAVEVM_TIMEOUT_MS = 120_000; export const MONITOR_LOADVM_TIMEOUT_MS = 120_000; export const MONITOR_DELVM_TIMEOUT_MS = 60_000; +/** Per-command budget for a `fault()` / `faults()` session (#369). Each command is a + * millisecond-scale filter change or read, but the windows-x86 TCG leg twice gave no + * prompt at all within 5 s right after a two-way drop was lifted, while two CHRs + * renegotiated LACP (runs 46782987405, 46784568862). On an idle CHR on the same runner, + * 102 back-to-back monitor connections and sessions all answered within 10 ms, including + * after that filter change (probe run 46794639948). That points at a loaded main loop, + * the pattern above, not at the connection. */ +export const MONITOR_FAULT_TIMEOUT_MS = 30_000; /** Strip ANSI escapes and the monitor's per-character command echo, leaving * just the response body. The echo hid real errors from callers: QEMU renders @@ -189,11 +197,9 @@ export async function monitorCommand( /** Run several HMP commands over one monitor connection, in turn: `fn` gets a `send` * that writes one command and resolves with its cleaned reply at the next prompt. - * - * QEMU's monitor serves one client at a time, and a new connection waits until QEMU - * has noticed the last one close. On Windows (TCP monitor) a burst of short connections - * left one waiting past its timeout with no prompt (#369, run 46782987405), so an - * operation that needs several commands opens one session instead. + * An operation that needs several commands (#369's `fault()` / `faults()`) runs them on + * one connection rather than reconnecting for each, and reads the prompt only at the + * start of the last line, so a reply that contains "(qemu)" isn't cut short. * * Errors match `monitorCommand(…, { requirePrompt: true })`: no socket or a refused * connection is `MACHINE_STOPPED`, a command with no reply within `timeoutMs` is @@ -201,8 +207,8 @@ export async function monitorCommand( export async function withMonitorSession( machineDir: string, portBase: number | undefined, + timeoutMs: number, fn: (send: (command: string) => Promise) => Promise, - timeoutMs: number = MONITOR_FAST_QUERY_TIMEOUT_MS, ): Promise { if (!channelFileExists(channelPath(machineDir, "monitor"))) { throw new QuickCHRError("MACHINE_STOPPED", "Monitor socket not found — is the machine running in background mode?"); diff --git a/src/lib/quickchr.ts b/src/lib/quickchr.ts index 840a26f7..7ba58ea4 100644 --- a/src/lib/quickchr.ts +++ b/src/lib/quickchr.ts @@ -79,7 +79,7 @@ import { bootDiskFormatOf, bootDiskPath, cleanDiskFiles, ensureConfiguredDisks, import { formatLinkChanges, normalizeLinkChanges, resolveLinkTargets, setLinkCommand, setLinkFailure, type LinkChange, type LinkTarget } from "./link.ts"; import { CHARDEV_LIST_COMMAND, FAULT_SNAPSHOT_COMMAND, faultIds, faultInPlace, formatFaultChanges, normalizeFaultChanges, parseChardevList, parseFilters, planFaultSteps, resolveFaultTargets, sinkState, type FaultChange, type FaultStep, type FaultTarget, type FilterInfo } from "./fault.ts"; import { assertCaptureDirsOutside, captureCommand, captureFilesOf, carryCaptureFiles, formatCaptureChanges, normalizeCaptureChanges, removeIfEmpty, reserveCaptureFiles, resolveCaptureTargets, type CaptureChange, type CaptureTarget } from "./capture.ts"; -import { monitorCommand, withMonitorSession, serialStreams, qgaCommand, channelEndpoint, channelFileExists, channelPath, MONITOR_FAST_QUERY_TIMEOUT_MS, MONITOR_SAVEVM_TIMEOUT_MS, MONITOR_LOADVM_TIMEOUT_MS, MONITOR_DELVM_TIMEOUT_MS } from "./channels.ts"; +import { monitorCommand, withMonitorSession, MONITOR_FAULT_TIMEOUT_MS, serialStreams, qgaCommand, channelEndpoint, channelFileExists, channelPath, MONITOR_FAST_QUERY_TIMEOUT_MS, MONITOR_SAVEVM_TIMEOUT_MS, MONITOR_LOADVM_TIMEOUT_MS, MONITOR_DELVM_TIMEOUT_MS } from "./channels.ts"; import { captureBootFailure, newBootProbeStats, preserveOnFailure, type BootFailureReport, type BootProbeStats, type FailureTrigger } from "./diagnostics.ts"; import { installPackages, installAllPackages, downloadAndListPackages, downloadPackages, findPackageFile, uploadPackages } from "./packages.ts"; import { ensureEmptySshConfig, provision } from "./provision.ts"; @@ -1087,7 +1087,7 @@ export async function applyFaultChanges(state: MachineState, changes: readonly F // writer can change them, so each port's plan is made from what QEMU has. let inSession = false; try { - await withMonitorSession(state.machineDir, state.portBase, async (hmp) => { + await withMonitorSession(state.machineDir, state.portBase, MONITOR_FAULT_TIMEOUT_MS, async (hmp) => { inSession = true; let filters: Map; let chardevs: Map; @@ -1219,7 +1219,7 @@ export async function readFaults(state: MachineState): Promise faultIds(nic.id)); - const pair = await withMonitorSession(fresh.machineDir, fresh.portBase, async (hmp) => { + const pair = await withMonitorSession(fresh.machineDir, fresh.portBase, MONITOR_FAULT_TIMEOUT_MS, async (hmp) => { for (let attempt = 0; attempt < FAULT_READ_ATTEMPTS; attempt++) { const before = await hmp(FAULT_SNAPSHOT_COMMAND); const chardevReply = await hmp(CHARDEV_LIST_COMMAND); From 3ee45f0e0ab6c4ffdded88979870b8346260eef7 Mon Sep 17 00:00:00 2001 From: TIKOCI RouterOS Bots Date: Tue, 1 Dec 2026 18:33:00 -0800 Subject: [PATCH 8/8] fix(network): revert the 30 s fault budget; skip the raw status-off step on Windows (#369) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The 30 s budget didn't help (run 46795212755: no prompt within 30 s), so the Windows hang is not load. Every Windows failure (3/3) is the first connection after a raw `qom-set … status off` on a redirector carrying LACP; runs that lifted the drop with object_del passed, and an idle probe with status off didn't hang. quickchr never sets status, so the live status-off step is skipped on Windows (the unit tests cover the refusal), the budget is back to 5 s, and the observation is recorded in qemu.instructions.md and MANUAL. Co-Authored-By: Claude Opus 5.5 --- .github/instructions/qemu.instructions.md | 9 +++++++++ DESIGN.md | 5 +---- MANUAL.md | 3 +++ src/lib/channels.ts | 8 -------- src/lib/quickchr.ts | 6 +++--- test/integration/link-fault.test.ts | 17 +++++++++++------ 6 files changed, 27 insertions(+), 21 deletions(-) diff --git a/.github/instructions/qemu.instructions.md b/.github/instructions/qemu.instructions.md index 33bbcc2d..a73529d2 100644 --- a/.github/instructions/qemu.instructions.md +++ b/.github/instructions/qemu.instructions.md @@ -268,6 +268,15 @@ from `net/filter*.c` (QEMU master and 11.1.2) and `test/lab/link-impairment/REPO (QEMU 11.1.2, KVM, CHR 7.25.2): the capture held the LACPDUs the guest sent into an egress drop, and none of the peer's under an ingress drop (`test/integration/link-fault.test.ts`). +- **Windows: the monitor stopped answering after a raw `status off` on a live redirector.** + On windows-latest (QEMU 11.1.0, TCG, `listen-connect` links, two CHRs with an LACP bond), + `qom-set /objects/fault2 status off` on a `queue=all` blackhole succeeded, and so did the + next monitor session. The connection after that was accepted but got no prompt within + 5 s, nor within 30 s, in 3 of 3 runs (46782987405, 46784568862, 46795212755). The same + runs passed when the drop was lifted with `object_del`. A probe on an idle CHR with no + traffic on the link saw no hang, including after `status off` (102 connections, all + under 10 ms; run 46794639948). The mechanism is unknown. quickchr never sets `status` + on its fault filters, and `link-fault.test.ts` skips this step on Windows. - **`info network` doesn't show carrier.** After `set_link off` its netdev line is unchanged (QEMU 11.1.2), so HMP has no read-back for link state. - **A `filter-redirector` loop is QEMU's only per-frame hook.** `outdev` writes each frame to diff --git a/DESIGN.md b/DESIGN.md index 8bbad398..23e32c62 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1311,10 +1311,7 @@ behind a lock holder. The record is checked again afterwards, so a machine remov replaced or restarted during the read is an error, not a stale answer. `fault()` itself takes the lock, so a `start --fg` session (which holds it for its whole run) refuses `--fault` from another shell, as it does `--link`. Each operation runs over one monitor -connection (`withMonitorSession()`), with a 30 s per-command budget -(`MONITOR_FAULT_TIMEOUT_MS`): on the windows-x86 TCG leg the monitor twice gave no -prompt within the usual 5 s right after a two-way drop was lifted under LACP load, while -an idle CHR on the same runner answered 102 rapid connections within 10 ms. The ids +connection (`withMonitorSession()`) with the usual 5 s per-command budget. The ids `fault` and `fault-sink` are reserved; an unused `null` chardev with a sink's id is taken for one an earlier failure left behind. A batch is applied port by port, so a read in the middle of one can show its first ports changed and not the rest. A filter that matches but writes to a sink that diff --git a/MANUAL.md b/MANUAL.md index 47200135..b86bc39e 100644 --- a/MANUAL.md +++ b/MANUAL.md @@ -1805,6 +1805,9 @@ await chr.faults(); // { ether3: { drop: " objects or chardevs those ids: a filter, or a non-null or in-use chardev, holding one is refused, but an unused `null` chardev named `fault-sink` is taken for a sink left behind and removed. +- **Don't switch a fault filter off through `monitor()`** (`qom-set … status off`). + quickchr then neither reports nor changes it, and on Windows QEMU's monitor stopped + answering after it while the link carried traffic. Clear a fault with `--fault …=none`. - **A foreground session (`start --fg`) holds the machine lock**, as for `--link`, so `--fault` from another shell is refused with `MACHINE_LOCKED` while it runs. - **Validated first, then applied in order**, under the machine lock, like diff --git a/src/lib/channels.ts b/src/lib/channels.ts index 453026de..9f388bc3 100644 --- a/src/lib/channels.ts +++ b/src/lib/channels.ts @@ -70,14 +70,6 @@ export const MONITOR_FAST_QUERY_TIMEOUT_MS = 5000; export const MONITOR_SAVEVM_TIMEOUT_MS = 120_000; export const MONITOR_LOADVM_TIMEOUT_MS = 120_000; export const MONITOR_DELVM_TIMEOUT_MS = 60_000; -/** Per-command budget for a `fault()` / `faults()` session (#369). Each command is a - * millisecond-scale filter change or read, but the windows-x86 TCG leg twice gave no - * prompt at all within 5 s right after a two-way drop was lifted, while two CHRs - * renegotiated LACP (runs 46782987405, 46784568862). On an idle CHR on the same runner, - * 102 back-to-back monitor connections and sessions all answered within 10 ms, including - * after that filter change (probe run 46794639948). That points at a loaded main loop, - * the pattern above, not at the connection. */ -export const MONITOR_FAULT_TIMEOUT_MS = 30_000; /** Strip ANSI escapes and the monitor's per-character command echo, leaving * just the response body. The echo hid real errors from callers: QEMU renders diff --git a/src/lib/quickchr.ts b/src/lib/quickchr.ts index 7ba58ea4..15669661 100644 --- a/src/lib/quickchr.ts +++ b/src/lib/quickchr.ts @@ -79,7 +79,7 @@ import { bootDiskFormatOf, bootDiskPath, cleanDiskFiles, ensureConfiguredDisks, import { formatLinkChanges, normalizeLinkChanges, resolveLinkTargets, setLinkCommand, setLinkFailure, type LinkChange, type LinkTarget } from "./link.ts"; import { CHARDEV_LIST_COMMAND, FAULT_SNAPSHOT_COMMAND, faultIds, faultInPlace, formatFaultChanges, normalizeFaultChanges, parseChardevList, parseFilters, planFaultSteps, resolveFaultTargets, sinkState, type FaultChange, type FaultStep, type FaultTarget, type FilterInfo } from "./fault.ts"; import { assertCaptureDirsOutside, captureCommand, captureFilesOf, carryCaptureFiles, formatCaptureChanges, normalizeCaptureChanges, removeIfEmpty, reserveCaptureFiles, resolveCaptureTargets, type CaptureChange, type CaptureTarget } from "./capture.ts"; -import { monitorCommand, withMonitorSession, MONITOR_FAULT_TIMEOUT_MS, serialStreams, qgaCommand, channelEndpoint, channelFileExists, channelPath, MONITOR_FAST_QUERY_TIMEOUT_MS, MONITOR_SAVEVM_TIMEOUT_MS, MONITOR_LOADVM_TIMEOUT_MS, MONITOR_DELVM_TIMEOUT_MS } from "./channels.ts"; +import { monitorCommand, withMonitorSession, serialStreams, qgaCommand, channelEndpoint, channelFileExists, channelPath, MONITOR_FAST_QUERY_TIMEOUT_MS, MONITOR_SAVEVM_TIMEOUT_MS, MONITOR_LOADVM_TIMEOUT_MS, MONITOR_DELVM_TIMEOUT_MS } from "./channels.ts"; import { captureBootFailure, newBootProbeStats, preserveOnFailure, type BootFailureReport, type BootProbeStats, type FailureTrigger } from "./diagnostics.ts"; import { installPackages, installAllPackages, downloadAndListPackages, downloadPackages, findPackageFile, uploadPackages } from "./packages.ts"; import { ensureEmptySshConfig, provision } from "./provision.ts"; @@ -1087,7 +1087,7 @@ export async function applyFaultChanges(state: MachineState, changes: readonly F // writer can change them, so each port's plan is made from what QEMU has. let inSession = false; try { - await withMonitorSession(state.machineDir, state.portBase, MONITOR_FAULT_TIMEOUT_MS, async (hmp) => { + await withMonitorSession(state.machineDir, state.portBase, MONITOR_FAST_QUERY_TIMEOUT_MS, async (hmp) => { inSession = true; let filters: Map; let chardevs: Map; @@ -1219,7 +1219,7 @@ export async function readFaults(state: MachineState): Promise faultIds(nic.id)); - const pair = await withMonitorSession(fresh.machineDir, fresh.portBase, MONITOR_FAULT_TIMEOUT_MS, async (hmp) => { + const pair = await withMonitorSession(fresh.machineDir, fresh.portBase, MONITOR_FAST_QUERY_TIMEOUT_MS, async (hmp) => { for (let attempt = 0; attempt < FAULT_READ_ATTEMPTS; attempt++) { const before = await hmp(FAULT_SNAPSHOT_COMMAND); const chardevReply = await hmp(CHARDEV_LIST_COMMAND); diff --git a/test/integration/link-fault.test.ts b/test/integration/link-fault.test.ts index a4e731b1..369e8363 100644 --- a/test/integration/link-fault.test.ts +++ b/test/integration/link-fault.test.ts @@ -158,12 +158,17 @@ describe.skipIf(SKIP)("one-way drop that keeps carrier (#369)", () => { expect(await lacpFrom(aCap, bMac)).toBe(both0.aHeard); expect(await lacpFrom(bCap, aMac)).toBe(both0.bHeard); // Switched off by hand (raw monitor): not a fault, and fault() won't touch it. - expect(await a.monitor("qom-set /objects/fault2 status off")).toBe(""); - expect(await a.faults()).toEqual({}); - await expect(a.fault("ether3", null)).rejects.toMatchObject({ code: "STATE_ERROR" }); - await expect(a.fault("ether3", { drop: "egress" })).rejects.toMatchObject({ code: "STATE_ERROR" }); - expect(await a.monitor("qom-set /objects/fault2 status on")).toBe(""); - expect(await a.faults()).toEqual({ ether3: { drop: "both" } }); + // Not on Windows: there QEMU's monitor stopped answering right after this raw + // `status off` on a redirector carrying LACP (qemu.instructions.md); quickchr + // itself never switches status. The unit tests cover the refusal everywhere. + if (process.platform !== "win32") { + expect(await a.monitor("qom-set /objects/fault2 status off")).toBe(""); + expect(await a.faults()).toEqual({}); + await expect(a.fault("ether3", null)).rejects.toMatchObject({ code: "STATE_ERROR" }); + await expect(a.fault("ether3", { drop: "egress" })).rejects.toMatchObject({ code: "STATE_ERROR" }); + expect(await a.monitor("qom-set /objects/fault2 status on")).toBe(""); + expect(await a.faults()).toEqual({ ether3: { drop: "both" } }); + } await a.fault("ether3", null); await until("ether3 back in both bonds after ingress/both", whole, 60_000); }, bootTestTimeout({ boots: 2, extraMs: 120_000 }));