| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660 |
- #!/usr/bin/env python3
- """
- test_tier3_kvm_uefi_e2e.py — Tier 3 Real Hardware KVM + EDK2 OVMF UEFI + `mt86plus.efi` E2E
- Uses `root@192.168.2.25` hardware `/dev/kvm`, real EDK2 OVMF (`code.fd` + `vars.fd`), and the
- real compiled x86-64 UEFI memory diagnostic binary `mt86plus.efi` inside an isolated ephemeral
- Podman container (`--rm --device /dev/kvm`), bridged via QMP + COM1 UART into `bmc_ssh_hil_sim`
- (`127.0.2.170` UDP :623 RMCP+ & TCP :2200 SSHv2) and unmodified `stl_native_server`.
- Verifies:
- 1. Real KVM + OVMF UEFI boot -> EDK2 `UEFI Interactive Shell` -> automated UEFI MT script PASS.
- 2. Real x86-64 `mt86plus.efi` execution on KVM RAM + live ANSI serial cleaning + QMP hardware
- vCPU freeze (`{"execute": "stop"}`) -> `stl_native_server` stage watchdog (`stage_hang_timeout`),
- Level-1 scene preservation (QMP `query-status` confirms VM stays `"paused"` with 0 resets),
- and `/dev/pts/*` 6400 High-Temperature Hood `0x08 00` cooling purge.
- 3. Real IPMI RMCP+ `StationPower: host_reset` -> `PWR:RESET` -> QMP `cont` + `system_reset`
- rebooting the KVM OVMF guest cleanly back to `UEFI Interactive Shell`.
- """
- import asyncio
- import contextlib
- import json
- import os
- from pathlib import Path
- import shutil
- import subprocess
- import sys
- import tempfile
- import time
- from typing import Any, Callable, Dict, Optional
- import uuid
- import aiohttp
- ROOT_DIR = Path(__file__).resolve().parents[2]
- sys.path.insert(0, str(ROOT_DIR / "sim" / "hil_cluster"))
- from cluster_harness import BMC_SIM_BIN, CONTRACTS_PATH, STL_SERVER_BIN, WEB_DIR, WsRpcClient # noqa: E402
- from dut_and_hood_sim import HoodPtsSim # noqa: E402
- REMOTE_HOST = os.environ.get("STL_KVM_HOST", "192.168.2.25")
- REMOTE_USER = os.environ.get("STL_KVM_USER", "root")
- PODMAN_IMAGE = "localhost/omo-lab:13-iso-20260921T030408Z"
- async def wait_until(
- pred: Callable[[], Any],
- timeout_s: float = 30.0,
- interval_s: float = 0.25,
- desc: str = "condition",
- ) -> Any:
- deadline = time.monotonic() + timeout_s
- last_val = None
- while time.monotonic() < deadline:
- res = pred()
- if asyncio.iscoroutine(res):
- res = await res
- last_val = res
- if res:
- return res
- await asyncio.sleep(interval_s)
- raise AssertionError(f"Timed out ({timeout_s}s) waiting for {desc}; last={last_val}")
- class QmpClient:
- """Async QEMU Machine Protocol (QMP) client for vCPU freeze, status query, and hardware reset."""
- def __init__(self, host: str, port: int):
- self.host = host
- self.port = port
- self.reader: Optional[asyncio.StreamReader] = None
- self.writer: Optional[asyncio.StreamWriter] = None
- self.lock = asyncio.Lock()
- async def connect(self, timeout_s: float = 12.0) -> None:
- deadline = time.monotonic() + timeout_s
- while time.monotonic() < deadline:
- try:
- self.reader, self.writer = await asyncio.open_connection(self.host, self.port)
- greeting = await asyncio.wait_for(self.reader.readline(), timeout=3.0)
- if b"QMP" in greeting:
- await self.execute("qmp_capabilities")
- return
- except Exception:
- await asyncio.sleep(0.2)
- raise TimeoutError(f"Failed to connect QMP at {self.host}:{self.port}")
- async def execute(self, cmd: str, arguments: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
- async with self.lock:
- assert self.reader is not None and self.writer is not None
- req: Dict[str, Any] = {"execute": cmd}
- if arguments:
- req["arguments"] = arguments
- self.writer.write((json.dumps(req) + "\r\n").encode("utf-8"))
- await self.writer.drain()
- while True:
- line = await asyncio.wait_for(self.reader.readline(), timeout=5.0)
- if not line:
- raise RuntimeError("QMP connection closed")
- msg = json.loads(line.decode("utf-8", errors="replace"))
- if "return" in msg:
- return msg["return"]
- if "error" in msg:
- raise RuntimeError(f"QMP error on {cmd}: {msg['error']}")
- # Ignore async `EVENT` lines (STOP, RESUME, RESET, etc.)
- async def close(self) -> None:
- if self.writer is not None:
- with contextlib.suppress(Exception):
- self.writer.close()
- async def bridge_kvm_uart_and_pwr(
- qemu_serial_port: int,
- bmc_uart_bridge_port: int,
- qmp: QmpClient,
- stats: Dict[str, Any],
- ) -> None:
- """Bridges QEMU KVM COM1 TCP socket <-> `bmc_ssh_hil_sim` UART bridge + translates `\x01PWR:*` to QMP."""
- while True:
- q_writer = None
- b_writer = None
- try:
- q_reader, q_writer = await asyncio.open_connection("127.0.0.1", qemu_serial_port)
- b_reader, b_writer = await asyncio.open_connection("127.0.0.1", bmc_uart_bridge_port)
- async def qemu_to_bmc() -> None:
- while True:
- data = await q_reader.read(4096)
- if not data:
- break
- stats["kvm_uart_rx_bytes"] = stats.get("kvm_uart_rx_bytes", 0) + len(data)
- stats["tail_text"] = (stats.get("tail_text", "") + data.decode("utf-8", errors="replace"))[-6000:]
- b_writer.write(data)
- await b_writer.drain()
- async def bmc_to_qemu() -> None:
- while True:
- data = await b_reader.read(4096)
- if not data:
- break
- txt = data.decode("utf-8", errors="replace")
- idx = 0
- out_chars = []
- while idx < len(txt):
- if txt[idx] == "\x01" and txt.startswith("\x01PWR:", idx):
- nl = txt.find("\n", idx)
- if nl < 0:
- nl = len(txt)
- ev = txt[idx + 5 : nl].strip()
- stats.setdefault("pwr_events", []).append(ev)
- if ev == "OFF":
- with contextlib.suppress(Exception):
- await qmp.execute("stop")
- elif ev in ("ON", "RESET", "CYCLE"):
- with contextlib.suppress(Exception):
- await qmp.execute("cont")
- with contextlib.suppress(Exception):
- await qmp.execute("system_reset")
- idx = nl + 1
- continue
- out_chars.append(txt[idx])
- idx += 1
- if out_chars:
- q_writer.write("".join(out_chars).encode("utf-8"))
- await q_writer.drain()
- stats["bridge_connected"] = True
- await asyncio.gather(qemu_to_bmc(), bmc_to_qemu())
- except asyncio.CancelledError:
- raise
- except Exception as exc:
- stats.setdefault("bridge_errors", []).append(repr(exc))
- finally:
- stats["bridge_connected"] = False
- for w in (q_writer, b_writer):
- if w is not None:
- with contextlib.suppress(Exception):
- w.close()
- await asyncio.sleep(0.2)
- async def run_tier3_kvm_suite() -> Dict[str, Any]:
- t0 = time.monotonic()
- run_tag = f"xjkj-stl-kvm-{os.getpid()}-{int(time.time())}"
- remote_dir = f"/tmp/{run_tag}"
- cname = run_tag
- q_serial_port = 29210
- q_qmp_port = 29211
- bmc_ctrl_port = 29199
- bmc_uart_port = 29200
- web_port = 28980
- station_ip = "127.0.2.170"
- local_tmp = Path(tempfile.mkdtemp(prefix="xjkj_stl_tier3_"))
- ssh_tunnel_proc: Optional[subprocess.Popen] = None
- bmc_proc: Optional[subprocess.Popen] = None
- server_proc: Optional[subprocess.Popen] = None
- hood: Optional[HoodPtsSim] = None
- hood_task: Optional[asyncio.Task] = None
- bridge_task: Optional[asyncio.Task] = None
- qmp = QmpClient("127.0.0.1", q_qmp_port)
- env = dict(os.environ)
- for k in (
- "LD_LIBRARY_PATH",
- "http_proxy",
- "https_proxy",
- "HTTP_PROXY",
- "HTTPS_PROXY",
- "all_proxy",
- "ALL_PROXY",
- ):
- env.pop(k, None)
- try:
- print(f"[Tier3] Provisioning isolated KVM + OVMF + mt86plus.efi workspace on {REMOTE_HOST}:{remote_dir}...", flush=True)
- setup_sh = rf"""
- set -euo pipefail
- mkdir -p {remote_dir}/esp/EFI/BOOT
- cp /opt/edk2-uefi-lab/work/qemu/memtest86plus/code.fd {remote_dir}/code.fd
- cp /opt/edk2-uefi-lab/work/qemu/memtest86plus/vars.fd {remote_dir}/vars.fd
- cp /opt/edk2-uefi-lab/work/qemu/memtest86plus/hda-contents/EFI/BOOT/BOOTX64.EFI {remote_dir}/esp/EFI/BOOT/BOOTX64.EFI
- cp /opt/edk2-uefi-lab/work/qemu/memtest86plus/mt86plus.efi {remote_dir}/esp/EFI/mt86plus.efi
- cat > {remote_dir}/esp/startup.nsh << 'EOF'
- @echo -off
- echo [HS_BIOS]Version: 108_VD012_KVM_OVMF
- echo [HS_StartMemTrain]
- echo [HS_DRAM] N0.C0.D0 DDR5 Present Size:65536
- echo [HS_EndMemTrain]
- echo MRC Done
- echo START_RMT_N0
- echo N0.C0.D0.R0 : -18 19 -17 18
- echo STOP_RMT_N0
- fs0:
- cd \EFI
- EOF
- cat > {remote_dir}/esp/EFI/kvm_mt_pass.nsh << 'EOF'
- @echo -off
- echo Launching 118.efi
- echo PassMark MemTest86 V11.1 Pro (KVM-OVMF-UEFI)
- echo Running test #0 (Test: 0/26 0%)
- echo Running test #13 (Test: 13/26 50%)
- echo Running test #25 (Test: 25/26 96%)
- echo Tests Passed: 26/26
- echo Pass complete, no errors
- echo Test Result: PASS
- EOF
- cat > {remote_dir}/esp/EFI/launch_real_mt86.nsh << 'EOF'
- @echo -off
- echo Launching 118.efi
- FS0:\EFI\mt86plus.efi console=ttyS0,115200 newline nopause nosmp nosm nobench keyboard=legacy testlist=0,1
- EOF
- podman run -d --rm --name {cname} \
- --device /dev/kvm \
- -v {remote_dir}:/sim:rw \
- -p 127.0.0.1:{q_serial_port}:{q_serial_port} \
- -p 127.0.0.1:{q_qmp_port}:{q_qmp_port} \
- {PODMAN_IMAGE} \
- qemu-system-x86_64 \
- -machine q35,accel=kvm -cpu host -smp 2 -m 512M \
- -display none -net none \
- -drive if=pflash,format=raw,readonly=on,file=/sim/code.fd \
- -drive if=pflash,format=raw,file=/sim/vars.fd \
- -drive file=fat:rw:/sim/esp,format=raw,if=ide \
- -serial tcp:0.0.0.0:{q_serial_port},server=on,wait=off \
- -qmp tcp:0.0.0.0:{q_qmp_port},server=on,wait=off
- """
- subprocess.run(
- ["ssh", "-o", "BatchMode=yes", f"{REMOTE_USER}@{REMOTE_HOST}", setup_sh],
- check=True,
- timeout=25,
- capture_output=True,
- text=True,
- )
- # Open SSH local port forward for QEMU COM1 serial & QMP sockets
- ssh_tunnel_proc = subprocess.Popen(
- [
- "ssh",
- "-o", "BatchMode=yes",
- "-o", "ExitOnForwardFailure=yes",
- "-N",
- "-L", f"127.0.0.1:{q_serial_port}:127.0.0.1:{q_serial_port}",
- "-L", f"127.0.0.1:{q_qmp_port}:127.0.0.1:{q_qmp_port}",
- f"{REMOTE_USER}@{REMOTE_HOST}",
- ],
- stdout=subprocess.DEVNULL,
- stderr=subprocess.PIPE,
- text=True,
- )
- await qmp.connect(timeout_s=12.0)
- qstatus0 = await qmp.execute("query-status")
- assert qstatus0.get("running") is True, f"Expected KVM guest running, got {qstatus0}"
- # Start C BMC RMCP+ (:623) & SSHv2 (:2200) simulator on `127.0.2.170`
- bmc_proc = subprocess.Popen(
- [
- str(BMC_SIM_BIN),
- "--ctrl-port", str(bmc_ctrl_port),
- "--uart-base", str(bmc_uart_port),
- "--ipmi-port", "623",
- "--ssh-port", "2200",
- "--probe22-port", "0",
- station_ip,
- ],
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- text=True,
- env=env,
- )
- await asyncio.sleep(0.6)
- stats: Dict[str, Any] = {}
- bridge_task = asyncio.create_task(
- bridge_kvm_uart_and_pwr(q_serial_port, bmc_uart_port, qmp, stats)
- )
- await wait_until(lambda: stats.get("bridge_connected") is True, timeout_s=10.0, desc="KVM UART bridge connected")
- # Start `/dev/pts/*` 6400 Hood simulator for S1
- hood = HoodPtsSim("kvm-hood-S1", 0, ("127.0.0.1", bmc_ctrl_port), sync_bmc=True)
- hood_task = asyncio.create_task(hood.physics_and_heartbeat_loop())
- # Start unmodified `stl_native_server` pointing S1 -> `127.0.2.170`
- data_dir = local_tmp / "data"
- data_dir.mkdir(parents=True, exist_ok=True)
- cfg_path = local_tmp / "station-kvm.json"
- cfg_path.write_text(
- json.dumps(
- {
- "mode": "hardware",
- "data_dir": str(data_dir),
- "telemetry_interval_s": 1.0,
- "idle_poll_interval_s": 1,
- "stations": [
- {
- "station_id": "S1",
- "frontend_index": 0,
- "name": "KVM-OVMF 真机虚拟化工位",
- "mode": "hardware",
- "cpu_count": 1,
- "channels_per_cpu": 12,
- "bmc": {
- "enabled": True,
- "host": station_ip,
- "user": "ADMIN",
- "username": "ADMIN",
- "password": "Admin123@pl",
- "cipher_suite": 17,
- "timeout_s": 5,
- "console_transport": "ssh_console",
- "ssh_console_port": 2200,
- },
- "console": {
- "enabled": True,
- "transport": "ssh_console",
- "host": station_ip,
- "port": 2200,
- "user": "ADMIN",
- "write_chunk_bytes": 64,
- "write_gap_ms": 5.0,
- },
- }
- ],
- },
- indent=2,
- ),
- encoding="utf-8",
- )
- server_proc = subprocess.Popen(
- [
- str(STL_SERVER_BIN),
- "--config", str(cfg_path),
- "--data-dir", str(data_dir),
- "--web-listen", f"127.0.0.1:{web_port}",
- "--tftp-listen", "disabled",
- "--pxe-mode", "disabled",
- "--web-dir", str(WEB_DIR),
- "--contracts", str(CONTRACTS_PATH),
- "--web-password", "disabled",
- ],
- cwd=str(ROOT_DIR),
- stdout=subprocess.DEVNULL,
- stderr=subprocess.PIPE,
- text=True,
- env=env,
- )
- results = []
- async with aiohttp.ClientSession() as http:
- # Wait HTTP up
- await wait_until(
- lambda: _http_ok(http, f"http://127.0.0.1:{web_port}/"),
- timeout_s=10.0,
- desc="stl_native_server HTTP up",
- )
- ws = WsRpcClient(http, f"ws://127.0.0.1:{web_port}/ws")
- await ws.connect()
- try:
- # Wait for S1 BMC + :2200 SSH console online AND real OVMF UEFI Shell prompt!
- print("[Tier3][1/3] Booting real KVM + EDK2 OVMF guest into UEFI Interactive Shell & running automated MT PASS...", flush=True)
- await wait_until(
- lambda: _station_online(ws, "S1"),
- timeout_s=15.0,
- desc="S1 KVM station online",
- )
- # Reset KVM guest via QMP so `stl_native_server` observes the full OVMF boot + startup.nsh + `Shell>`!
- await ws.call(
- "EnqueueCommand",
- {
- "command_id": f"kvm-cfg-{uuid.uuid4().hex[:8]}",
- "station_id": "S1",
- "method": "SaveFirmwareSettings",
- "arguments": {"mt_selection": {"efi_path": "FS0:\\EFI\\kvm_mt_pass.nsh"}},
- },
- )
- await ws.call(
- "EnqueueCommand",
- {
- "command_id": f"kvm-plan-{uuid.uuid4().hex[:8]}",
- "station_id": "S1",
- "method": "SaveBootPlan",
- "arguments": {
- "plan": {
- "preset": "auto",
- "mt_enabled": True,
- "run_rmt": True,
- "stages": {"uip1": "auto", "amt": "auto", "uip2": "auto", "uefi": "auto"},
- },
- "watchdog": {"dense_stage_silence_timeout_ms": 20000, "mt_silence_timeout_ms": 20000},
- },
- },
- )
- await ws.call(
- "EnqueueCommand",
- {
- "command_id": f"kvm-start1-{uuid.uuid4().hex[:8]}",
- "station_id": "S1",
- "method": "ControlBootPlan",
- "arguments": {"action": "start"},
- },
- )
- await qmp.execute("system_reset")
- st_pass = await wait_until(
- lambda: _station_terminal(ws, "S1"),
- timeout_s=30.0,
- desc="KVM OVMF UEFI automated MT PASS",
- )
- if st_pass["task_status"] != "completed":
- clean_u = await ws.call("ReadCleanedUart", {"station_id": "S1", "offset": 0, "max_bytes": 8192})
- raise AssertionError(
- f"Unexpected KVM S1 state: {st_pass}\nBRIDGE={stats.get('bridge_connected')} ERRS={stats.get('bridge_errors')}\nRAW_TAIL={repr(stats.get('tail_text', '')[-1200:])}\nCLEAN_TAIL={repr(clean_u.get('text', '')[-1200:])}"
- )
- assert st_pass["verdict"] == "pass", f"Unexpected KVM S1 state: {st_pass}"
- assert (st_pass.get("stage_completions") or {}).get("uefi_complete") is True
- assert (st_pass.get("stage_completions") or {}).get("mt_pass_complete") is True
- results.append({"scenario": "1_kvm_ovmf_uefi_shell_auto_pass", "status": "PASS"})
- print(" -> PASS", flush=True)
- # ============================================================
- # Scenario 2: Real `mt86plus.efi` Execution on KVM RAM + QMP Hardware vCPU Freeze
- # -> Watchdog `stage_hang_timeout` + Level-1 Scene Preserved + Hood Purge
- # ============================================================
- print("[Tier3][2/3] Launching real x86-64 `mt86plus.efi` on KVM RAM + QMP `stop` hardware vCPU freeze...", flush=True)
- hood.clear_history()
- await ws.call(
- "ThermalAction",
- {"station_id": "S1", "action": "connect", "mode": "serial", "serial_path": hood.pts_path, "serial_baud": 115200},
- )
- await wait_until(
- lambda: _thermal_online(ws, "S1"),
- timeout_s=4.0,
- desc="KVM Hood 0xF0 online",
- )
- await ws.call("ThermalAction", {"station_id": "S1", "action": "set_temp", "target_c": 70})
- await ws.call(
- "EnqueueCommand",
- {
- "command_id": f"kvm-cfg2-{uuid.uuid4().hex[:8]}",
- "station_id": "S1",
- "method": "SaveFirmwareSettings",
- "arguments": {"mt_selection": {"efi_path": "FS0:\\EFI\\launch_real_mt86.nsh"}},
- },
- )
- await ws.call(
- "EnqueueCommand",
- {
- "command_id": f"kvm-wd2a-{uuid.uuid4().hex[:8]}",
- "station_id": "S1",
- "method": "ConfigureWatchdog",
- "arguments": {
- "watchdog": {
- "enabled": True,
- "reboot_on_hang": False,
- "dense_stage_silence_timeout_ms": 20000,
- "mt_silence_timeout_ms": 20000,
- "mt_max_duration_ms": 60000,
- }
- },
- },
- )
- rx_before_mt86 = stats.get("kvm_uart_rx_bytes", 0)
- await ws.call(
- "EnqueueCommand",
- {
- "command_id": f"kvm-start2-{uuid.uuid4().hex[:8]}",
- "station_id": "S1",
- "method": "ControlBootPlan",
- "arguments": {"action": "start"},
- },
- )
- # Wait until S1 enters `mt` phase AND real `mt86plus.efi` streams serial output from KVM RAM!
- async def _in_real_mt86():
- st = await ws.call("GetStation", {"station_id": "S1"})
- if st.get("phase") == "mt" and stats.get("kvm_uart_rx_bytes", 0) > rx_before_mt86 + 250:
- return st
- return None
- await wait_until(_in_real_mt86, timeout_s=30.0, desc="Real mt86plus.efi active on KVM guest")
- await asyncio.sleep(0.8) # Let mt86plus.efi render initial test progress lines
- # Tighten MT silence watchdog to 2.5s and freeze physical KVM vCPU via QMP `stop`!
- await ws.call(
- "EnqueueCommand",
- {
- "command_id": f"kvm-wd2b-{uuid.uuid4().hex[:8]}",
- "station_id": "S1",
- "method": "ConfigureWatchdog",
- "arguments": {"watchdog": {"mt_silence_timeout_ms": 2500}},
- },
- )
- await qmp.execute("stop")
- q_frozen = await qmp.execute("query-status")
- assert q_frozen.get("status") == "paused", f"Expected QMP status=paused, got {q_frozen}"
- st_hang = await wait_until(
- lambda: _station_terminal(ws, "S1"),
- timeout_s=12.0,
- desc="Watchdog catching real KVM vCPU freeze",
- )
- assert st_hang["task_status"] == "failed", f"Expected failed on KVM freeze, got {st_hang}"
- assert st_hang.get("fault_code") == "stage_hang_timeout", f"Expected stage_hang_timeout, got {st_hang}"
- assert st_hang.get("hang_scene_preserved") is True
- # Confirm Level-1 preserved the exact paused KVM vCPU state (no QMP reset issued!)
- await asyncio.sleep(1.0)
- q_still_paused = await qmp.execute("query-status")
- assert q_still_paused.get("status") == "paused", f"Level-1 MUST preserve paused KVM vCPU, got {q_still_paused}"
- await wait_until(
- lambda: hood.snapshot().get("purge_cool_count", 0) >= 1 and hood.cooling_purge is True,
- timeout_s=5.0,
- desc="6400 Hood 0x08 00 cooling purge on KVM vCPU freeze",
- )
- results.append({"scenario": "2_kvm_real_mt86plus_qmp_vcpu_hang_and_hood_purge", "status": "PASS"})
- print(" -> PASS", flush=True)
- # ============================================================
- # Scenario 3: Real IPMI RMCP+ `StationPower: host_reset` -> QMP Reboot Recovery
- # ============================================================
- print("[Tier3][3/3] Issuing real IPMI RMCP+ `host_reset` -> QMP `cont` + `system_reset` -> OVMF Shell recovery...", flush=True)
- rx_before_rst = stats.get("kvm_uart_rx_bytes", 0)
- stats["tail_text"] = ""
- await ws.call(
- "EnqueueCommand",
- {
- "command_id": f"kvm-rst-{uuid.uuid4().hex[:8]}",
- "station_id": "S1",
- "method": "StationPower",
- "arguments": {"action": "host_reset"},
- },
- )
- async def _kvm_rebooted_to_shell():
- qst = await qmp.execute("query-status")
- if not qst.get("running"):
- return None
- tail = stats.get("tail_text", "")
- if (
- stats.get("kvm_uart_rx_bytes", 0) > rx_before_rst + 300
- and "STOP_RMT_N0" in tail
- and ("FS0:" in tail or "Shell>" in tail or "UEFI Interactive Shell" in tail)
- ):
- return True
- return None
- await wait_until(_kvm_rebooted_to_shell, timeout_s=25.0, desc="KVM OVMF rebooted back to UEFI Shell")
- results.append({"scenario": "3_ipmi_rmcp_to_qmp_reset_recovery", "status": "PASS"})
- print(" -> PASS", flush=True)
- finally:
- await ws.close()
- elapsed_s = round(time.monotonic() - t0, 2)
- summary = {"tier": "Tier3_KVM_OVMF_UEFI_mt86plus_E2E", "ok": True, "elapsed_s": elapsed_s, "results": results}
- print(f"\n[Tier3] ALL 3 REAL KVM + OVMF + mt86plus.efi SCENARIOS PASSED in {elapsed_s}s!", flush=True)
- return summary
- finally:
- if bridge_task:
- bridge_task.cancel()
- if hood_task:
- hood_task.cancel()
- if hood:
- hood.close()
- await qmp.close()
- for proc in (server_proc, bmc_proc, ssh_tunnel_proc):
- if proc and proc.poll() is None:
- with contextlib.suppress(Exception):
- proc.terminate()
- proc.wait(timeout=3.0)
- if proc.poll() is None:
- with contextlib.suppress(Exception):
- proc.kill()
- with contextlib.suppress(Exception):
- subprocess.run(
- [
- "ssh",
- "-o", "BatchMode=yes",
- f"{REMOTE_USER}@{REMOTE_HOST}",
- f"podman rm -f {cname} >/dev/null 2>&1 || true; rm -rf {remote_dir}",
- ],
- timeout=10,
- capture_output=True,
- )
- shutil.rmtree(local_tmp, ignore_errors=True)
- async def _http_ok(http: aiohttp.ClientSession, url: str) -> bool:
- try:
- async with http.get(url, timeout=aiohttp.ClientTimeout(total=1.0)) as r:
- return r.status == 200
- except Exception:
- return False
- async def _station_online(ws: WsRpcClient, sid: str) -> Any:
- st = await ws.call("GetStation", {"station_id": sid})
- return st if st.get("bmc_state") == "online" and st.get("console_online") is True else None
- async def _station_terminal(ws: WsRpcClient, sid: str) -> Any:
- st = await ws.call("GetStation", {"station_id": sid})
- return st if st.get("task_status") in ("completed", "failed") else None
- async def _thermal_online(ws: WsRpcClient, sid: str) -> Any:
- snap = await ws.call("GetThermalConsole", {"station_id": sid})
- return snap if (snap.get("mcu") or {}).get("online") else None
- if __name__ == "__main__":
- res = asyncio.run(run_tier3_kvm_suite())
- out_file = ROOT_DIR / "build" / "sim" / "tier3_kvm_uefi_report.json"
- out_file.parent.mkdir(parents=True, exist_ok=True)
- out_file.write_text(json.dumps(res, indent=2, ensure_ascii=False), encoding="utf-8")
|