2929from contextlib import ExitStack, nullcontext, redirect_stderr, redirect_stdout
3030from datetime import datetime
3131from pathlib import Path
32- from typing import Any, cast
32+ from typing import Any, NamedTuple, cast
3333from unittest.mock import MagicMock, patch
3434
3535sys.path.insert(0, str(Path(__file__).parent))
@@ -83,6 +83,21 @@ def _posix_shell() -> str | None:
8383 return shell
8484
8585
86+ class _ControlConsoleRun(NamedTuple):
87+ """What the interrupt-map script's traffic did with a control console."""
88+
89+ returncode: int
90+ output: str
91+ attaches: int
92+ rebinds: int
93+ unbound: str | None
94+ bound: str | None
95+
96+
97+ def _read_optional(path: Path) -> str | None:
98+ return path.read_text(encoding="ascii") if path.exists() else None
99+
100+
86101def _probe_environment(probe_dir: Path) -> dict[str, str]:
87102 """Return the environment of a run of an egress script in the host's
88103 shell, which then keeps its probes' results in `probe_dir`.
@@ -13229,11 +13244,11 @@ def test_interrupt_map_attaches_the_control_console_to_its_broker(self):
1322913244 ):
1323013245 script = microvm_tests._interrupt_map_script(devices, capture="")
1323113246 self.assertNotIn("@", script)
13232- # The control console's step writes the record, once, to the
13233- # console held open, raw, and silent until its interrupt.
13247+ # Each attach of the control console's step writes the record to
13248+ # the console held open, raw, and silent until its interrupt.
1323413249 steps = re.findall(
1323513250 r"\{ stty raw -echo <&3 && printf '([^']*)' >&3 &&\n"
13236- r' +await_irq "\$irq" "\$fired"; \} 3<>/dev/hvc2 \|\| fail 35 \n',
13251+ r' +await_irq "\$irq" "\$fired" && \n',
1323713252 script,
1323813253 )
1323913254 self.assertEqual(len(steps), 1)
@@ -13244,6 +13259,109 @@ def test_interrupt_map_attaches_the_control_console_to_its_broker(self):
1324413259 self.assertEqual(written, guest_attach)
1324513260 self.assertEqual(script.count("/dev/hvc2"), 1)
1324613261
13262+ def _run_control_console_traffic(
13263+ self, interrupting_attach: int | None
13264+ ) -> _ControlConsoleRun:
13265+ """Run the interrupt-map script's traffic through a control console
13266+ whose attach `interrupting_attach` is the first to interrupt, or none
13267+ if None, and return what the guest printed, how many times it
13268+ attached and rebound the console's driver, and its exit status."""
13269+ shell = _posix_shell()
13270+ if shell is None:
13271+ self.skipTest("POSIX shell is unavailable")
13272+ script = microvm_tests._interrupt_map_script(
13273+ len(microvm_tests.MICROVM_VIRTIO_DEVICES), capture=""
13274+ )
13275+ functions = script[: script.index("\ntries=0\n")]
13276+ functions = functions.replace(
13277+ "/sys/bus/virtio/devices/virtio*", '"$root"/devices/virtio*'
13278+ )
13279+ functions = functions.replace("/dev/hvc2", '"$root/hvc2"')
13280+ functions = functions.replace("nvx-exit", "nvx_exit")
13281+ with tempfile.TemporaryDirectory() as temporary:
13282+ root = Path(temporary)
13283+ driver = root / "devices" / "virtio5" / "driver"
13284+ driver.mkdir(parents=True)
13285+ for name in ("count", "attaches", "rebinds"):
13286+ (root / name).write_text("0\n", encoding="ascii")
13287+ result = subprocess.run(
13288+ [shell, "-s", "--", temporary, str(interrupting_attach or 0)],
13289+ input=(
13290+ "root=$1\nfire_at=$2\n"
13291+ f"{functions}\n"
13292+ "nvx_exit() { :; }\n"
13293+ "device_base() { echo d0007000; }\n"
13294+ "device_irq() { echo 23; }\n"
13295+ 'irq_count() { cat "$root/count"; }\n'
13296+ # The attach `fire_at` interrupts; await_irq returns at
13297+ # once.
13298+ "await_irq() {\n"
13299+ ' if [ "$fire_at" -gt 0 ] &&\n'
13300+ ' [ "$(cat "$root/attaches")" -ge "$fire_at" ]; then\n'
13301+ ' echo 1 >"$root/count"\n'
13302+ " fi\n"
13303+ "}\n"
13304+ "stty() {\n"
13305+ ' [ "$*" = "raw -echo" ] || return 0\n'
13306+ ' echo $(($(cat "$root/attaches") + 1)) >"$root/attaches"\n'
13307+ "}\n"
13308+ # Each rebind resets the console, which the bind records.
13309+ 'rebound() { echo $(($(cat "$root/rebinds") + 1)) >"$root/rebinds"; }\n'
13310+ "traffic\n"
13311+ ).replace(
13312+ 'echo "$name" >"$driver/bind"',
13313+ 'echo "$name" >"$driver/bind" && rebound',
13314+ ),
13315+ text=True,
13316+ capture_output=True,
13317+ timeout=30,
13318+ check=False,
13319+ )
13320+ return _ControlConsoleRun(
13321+ returncode=result.returncode,
13322+ output=result.stdout + result.stderr,
13323+ attaches=int((root / "attaches").read_text(encoding="ascii")),
13324+ rebinds=int((root / "rebinds").read_text(encoding="ascii")),
13325+ unbound=_read_optional(driver / "unbind"),
13326+ bound=_read_optional(driver / "bind"),
13327+ )
13328+
13329+ def test_interrupt_map_reattaches_a_control_console_that_did_not_interrupt(self):
13330+ # The driver can take the broker's answer by polling before the
13331+ # device reads the used event, and the device then rightly skips the
13332+ # interrupt (#1825). The broker answers once per device reset, so the
13333+ # guest rebinds the console's driver and attaches again until an
13334+ # attach interrupts.
13335+ run = self._run_control_console_traffic(3)
13336+ self.assertEqual(run.returncode, 0, run.output)
13337+ self.assertEqual((run.attaches, run.rebinds), (3, 2), run.output)
13338+ self.assertEqual((run.unbound, run.bound), ("virtio5\n", "virtio5\n"))
13339+ quiet = re.findall(
13340+ r"^NVX-INTERRUPT-MAP-CONTROL-QUIET attach=(\d+) status=0x\S+ "
13341+ r"answer=\S+$",
13342+ run.output,
13343+ re.MULTILINE,
13344+ )
13345+ self.assertEqual(quiet, ["1", "2"], run.output)
13346+ self.assertNotIn("NVX-INTERRUPT-MAP-FAIL", run.output)
13347+
13348+ run = self._run_control_console_traffic(1)
13349+ self.assertEqual(run.returncode, 0, run.output)
13350+ self.assertEqual((run.attaches, run.rebinds), (1, 0), run.output)
13351+ self.assertNotIn("NVX-INTERRUPT-MAP-CONTROL-QUIET", run.output)
13352+
13353+ def test_interrupt_map_fails_a_control_console_that_never_interrupts(self):
13354+ # A control console whose interrupt reaches no handler of its own
13355+ # never interrupts, however many times the guest attaches.
13356+ run = self._run_control_console_traffic(None)
13357+ self.assertEqual(run.returncode, 37, run.output)
13358+ self.assertEqual((run.attaches, run.rebinds), (8, 7), run.output)
13359+ self.assertIn(
13360+ "NVX-INTERRUPT-MAP-QUIET base=0xd0007000 device=virtio5 irq=23 count=0\n",
13361+ run.output,
13362+ )
13363+ self.assertIn("NVX-INTERRUPT-MAP-FAIL code=37\n", run.output)
13364+
1324713365 def test_smp_snapshot_runs_the_warp_probe_after_each_restore(self):
1324813366 def measure(command: list[str], **kwargs: object) -> None:
1324913367 processors = int(command[command.index("--processors") + 1])
0 commit comments