test_tier3_kvm_uefi_e2e.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. #!/usr/bin/env python3
  2. """
  3. test_tier3_kvm_uefi_e2e.py — Tier 3 Real Hardware KVM + EDK2 OVMF UEFI + `mt86plus.efi` E2E
  4. Uses `root@192.168.2.25` hardware `/dev/kvm`, real EDK2 OVMF (`code.fd` + `vars.fd`), and the
  5. real compiled x86-64 UEFI memory diagnostic binary `mt86plus.efi` inside an isolated ephemeral
  6. Podman container (`--rm --device /dev/kvm`), bridged via QMP + COM1 UART into `bmc_ssh_hil_sim`
  7. (`127.0.2.170` UDP :623 RMCP+ & TCP :2200 SSHv2) and unmodified `stl_native_server`.
  8. Verifies:
  9. 1. Real KVM + OVMF UEFI boot -> EDK2 `UEFI Interactive Shell` -> automated UEFI MT script PASS.
  10. 2. Real x86-64 `mt86plus.efi` execution on KVM RAM + live ANSI serial cleaning + QMP hardware
  11. vCPU freeze (`{"execute": "stop"}`) -> `stl_native_server` stage watchdog (`stage_hang_timeout`),
  12. Level-1 scene preservation (QMP `query-status` confirms VM stays `"paused"` with 0 resets),
  13. and `/dev/pts/*` 6400 High-Temperature Hood `0x08 00` cooling purge.
  14. 3. Real IPMI RMCP+ `StationPower: host_reset` -> `PWR:RESET` -> QMP `cont` + `system_reset`
  15. rebooting the KVM OVMF guest cleanly back to `UEFI Interactive Shell`.
  16. """
  17. import asyncio
  18. import contextlib
  19. import json
  20. import os
  21. from pathlib import Path
  22. import shutil
  23. import subprocess
  24. import sys
  25. import tempfile
  26. import time
  27. from typing import Any, Callable, Dict, Optional
  28. import uuid
  29. import aiohttp
  30. ROOT_DIR = Path(__file__).resolve().parents[2]
  31. sys.path.insert(0, str(ROOT_DIR / "sim" / "hil_cluster"))
  32. from cluster_harness import BMC_SIM_BIN, CONTRACTS_PATH, STL_SERVER_BIN, WEB_DIR, WsRpcClient # noqa: E402
  33. from dut_and_hood_sim import HoodPtsSim # noqa: E402
  34. REMOTE_HOST = os.environ.get("STL_KVM_HOST", "192.168.2.25")
  35. REMOTE_USER = os.environ.get("STL_KVM_USER", "root")
  36. PODMAN_IMAGE = "localhost/omo-lab:13-iso-20260921T030408Z"
  37. async def wait_until(
  38. pred: Callable[[], Any],
  39. timeout_s: float = 30.0,
  40. interval_s: float = 0.25,
  41. desc: str = "condition",
  42. ) -> Any:
  43. deadline = time.monotonic() + timeout_s
  44. last_val = None
  45. while time.monotonic() < deadline:
  46. res = pred()
  47. if asyncio.iscoroutine(res):
  48. res = await res
  49. last_val = res
  50. if res:
  51. return res
  52. await asyncio.sleep(interval_s)
  53. raise AssertionError(f"Timed out ({timeout_s}s) waiting for {desc}; last={last_val}")
  54. class QmpClient:
  55. """Async QEMU Machine Protocol (QMP) client for vCPU freeze, status query, and hardware reset."""
  56. def __init__(self, host: str, port: int):
  57. self.host = host
  58. self.port = port
  59. self.reader: Optional[asyncio.StreamReader] = None
  60. self.writer: Optional[asyncio.StreamWriter] = None
  61. self.lock = asyncio.Lock()
  62. async def connect(self, timeout_s: float = 12.0) -> None:
  63. deadline = time.monotonic() + timeout_s
  64. while time.monotonic() < deadline:
  65. try:
  66. self.reader, self.writer = await asyncio.open_connection(self.host, self.port)
  67. greeting = await asyncio.wait_for(self.reader.readline(), timeout=3.0)
  68. if b"QMP" in greeting:
  69. await self.execute("qmp_capabilities")
  70. return
  71. except Exception:
  72. await asyncio.sleep(0.2)
  73. raise TimeoutError(f"Failed to connect QMP at {self.host}:{self.port}")
  74. async def execute(self, cmd: str, arguments: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
  75. async with self.lock:
  76. assert self.reader is not None and self.writer is not None
  77. req: Dict[str, Any] = {"execute": cmd}
  78. if arguments:
  79. req["arguments"] = arguments
  80. self.writer.write((json.dumps(req) + "\r\n").encode("utf-8"))
  81. await self.writer.drain()
  82. while True:
  83. line = await asyncio.wait_for(self.reader.readline(), timeout=5.0)
  84. if not line:
  85. raise RuntimeError("QMP connection closed")
  86. msg = json.loads(line.decode("utf-8", errors="replace"))
  87. if "return" in msg:
  88. return msg["return"]
  89. if "error" in msg:
  90. raise RuntimeError(f"QMP error on {cmd}: {msg['error']}")
  91. # Ignore async `EVENT` lines (STOP, RESUME, RESET, etc.)
  92. async def close(self) -> None:
  93. if self.writer is not None:
  94. with contextlib.suppress(Exception):
  95. self.writer.close()
  96. async def bridge_kvm_uart_and_pwr(
  97. qemu_serial_port: int,
  98. bmc_uart_bridge_port: int,
  99. qmp: QmpClient,
  100. stats: Dict[str, Any],
  101. ) -> None:
  102. """Bridges QEMU KVM COM1 TCP socket <-> `bmc_ssh_hil_sim` UART bridge + translates `\x01PWR:*` to QMP."""
  103. while True:
  104. q_writer = None
  105. b_writer = None
  106. try:
  107. q_reader, q_writer = await asyncio.open_connection("127.0.0.1", qemu_serial_port)
  108. b_reader, b_writer = await asyncio.open_connection("127.0.0.1", bmc_uart_bridge_port)
  109. async def qemu_to_bmc() -> None:
  110. while True:
  111. data = await q_reader.read(4096)
  112. if not data:
  113. break
  114. stats["kvm_uart_rx_bytes"] = stats.get("kvm_uart_rx_bytes", 0) + len(data)
  115. stats["tail_text"] = (stats.get("tail_text", "") + data.decode("utf-8", errors="replace"))[-6000:]
  116. b_writer.write(data)
  117. await b_writer.drain()
  118. async def bmc_to_qemu() -> None:
  119. while True:
  120. data = await b_reader.read(4096)
  121. if not data:
  122. break
  123. txt = data.decode("utf-8", errors="replace")
  124. idx = 0
  125. out_chars = []
  126. while idx < len(txt):
  127. if txt[idx] == "\x01" and txt.startswith("\x01PWR:", idx):
  128. nl = txt.find("\n", idx)
  129. if nl < 0:
  130. nl = len(txt)
  131. ev = txt[idx + 5 : nl].strip()
  132. stats.setdefault("pwr_events", []).append(ev)
  133. if ev == "OFF":
  134. with contextlib.suppress(Exception):
  135. await qmp.execute("stop")
  136. elif ev in ("ON", "RESET", "CYCLE"):
  137. with contextlib.suppress(Exception):
  138. await qmp.execute("cont")
  139. with contextlib.suppress(Exception):
  140. await qmp.execute("system_reset")
  141. idx = nl + 1
  142. continue
  143. out_chars.append(txt[idx])
  144. idx += 1
  145. if out_chars:
  146. q_writer.write("".join(out_chars).encode("utf-8"))
  147. await q_writer.drain()
  148. stats["bridge_connected"] = True
  149. await asyncio.gather(qemu_to_bmc(), bmc_to_qemu())
  150. except asyncio.CancelledError:
  151. raise
  152. except Exception as exc:
  153. stats.setdefault("bridge_errors", []).append(repr(exc))
  154. finally:
  155. stats["bridge_connected"] = False
  156. for w in (q_writer, b_writer):
  157. if w is not None:
  158. with contextlib.suppress(Exception):
  159. w.close()
  160. await asyncio.sleep(0.2)
  161. async def run_tier3_kvm_suite() -> Dict[str, Any]:
  162. t0 = time.monotonic()
  163. run_tag = f"xjkj-stl-kvm-{os.getpid()}-{int(time.time())}"
  164. remote_dir = f"/tmp/{run_tag}"
  165. cname = run_tag
  166. q_serial_port = 29210
  167. q_qmp_port = 29211
  168. bmc_ctrl_port = 29199
  169. bmc_uart_port = 29200
  170. web_port = 28980
  171. station_ip = "127.0.2.170"
  172. local_tmp = Path(tempfile.mkdtemp(prefix="xjkj_stl_tier3_"))
  173. ssh_tunnel_proc: Optional[subprocess.Popen] = None
  174. bmc_proc: Optional[subprocess.Popen] = None
  175. server_proc: Optional[subprocess.Popen] = None
  176. hood: Optional[HoodPtsSim] = None
  177. hood_task: Optional[asyncio.Task] = None
  178. bridge_task: Optional[asyncio.Task] = None
  179. qmp = QmpClient("127.0.0.1", q_qmp_port)
  180. env = dict(os.environ)
  181. for k in (
  182. "LD_LIBRARY_PATH",
  183. "http_proxy",
  184. "https_proxy",
  185. "HTTP_PROXY",
  186. "HTTPS_PROXY",
  187. "all_proxy",
  188. "ALL_PROXY",
  189. ):
  190. env.pop(k, None)
  191. try:
  192. print(f"[Tier3] Provisioning isolated KVM + OVMF + mt86plus.efi workspace on {REMOTE_HOST}:{remote_dir}...", flush=True)
  193. setup_sh = rf"""
  194. set -euo pipefail
  195. mkdir -p {remote_dir}/esp/EFI/BOOT
  196. cp /opt/edk2-uefi-lab/work/qemu/memtest86plus/code.fd {remote_dir}/code.fd
  197. cp /opt/edk2-uefi-lab/work/qemu/memtest86plus/vars.fd {remote_dir}/vars.fd
  198. cp /opt/edk2-uefi-lab/work/qemu/memtest86plus/hda-contents/EFI/BOOT/BOOTX64.EFI {remote_dir}/esp/EFI/BOOT/BOOTX64.EFI
  199. cp /opt/edk2-uefi-lab/work/qemu/memtest86plus/mt86plus.efi {remote_dir}/esp/EFI/mt86plus.efi
  200. cat > {remote_dir}/esp/startup.nsh << 'EOF'
  201. @echo -off
  202. echo [HS_BIOS]Version: 108_VD012_KVM_OVMF
  203. echo [HS_StartMemTrain]
  204. echo [HS_DRAM] N0.C0.D0 DDR5 Present Size:65536
  205. echo [HS_EndMemTrain]
  206. echo MRC Done
  207. echo START_RMT_N0
  208. echo N0.C0.D0.R0 : -18 19 -17 18
  209. echo STOP_RMT_N0
  210. fs0:
  211. cd \EFI
  212. EOF
  213. cat > {remote_dir}/esp/EFI/kvm_mt_pass.nsh << 'EOF'
  214. @echo -off
  215. echo Launching 118.efi
  216. echo PassMark MemTest86 V11.1 Pro (KVM-OVMF-UEFI)
  217. echo Running test #0 (Test: 0/26 0%)
  218. echo Running test #13 (Test: 13/26 50%)
  219. echo Running test #25 (Test: 25/26 96%)
  220. echo Tests Passed: 26/26
  221. echo Pass complete, no errors
  222. echo Test Result: PASS
  223. EOF
  224. cat > {remote_dir}/esp/EFI/launch_real_mt86.nsh << 'EOF'
  225. @echo -off
  226. echo Launching 118.efi
  227. FS0:\EFI\mt86plus.efi console=ttyS0,115200 newline nopause nosmp nosm nobench keyboard=legacy testlist=0,1
  228. EOF
  229. podman run -d --rm --name {cname} \
  230. --device /dev/kvm \
  231. -v {remote_dir}:/sim:rw \
  232. -p 127.0.0.1:{q_serial_port}:{q_serial_port} \
  233. -p 127.0.0.1:{q_qmp_port}:{q_qmp_port} \
  234. {PODMAN_IMAGE} \
  235. qemu-system-x86_64 \
  236. -machine q35,accel=kvm -cpu host -smp 2 -m 512M \
  237. -display none -net none \
  238. -drive if=pflash,format=raw,readonly=on,file=/sim/code.fd \
  239. -drive if=pflash,format=raw,file=/sim/vars.fd \
  240. -drive file=fat:rw:/sim/esp,format=raw,if=ide \
  241. -serial tcp:0.0.0.0:{q_serial_port},server=on,wait=off \
  242. -qmp tcp:0.0.0.0:{q_qmp_port},server=on,wait=off
  243. """
  244. subprocess.run(
  245. ["ssh", "-o", "BatchMode=yes", f"{REMOTE_USER}@{REMOTE_HOST}", setup_sh],
  246. check=True,
  247. timeout=25,
  248. capture_output=True,
  249. text=True,
  250. )
  251. # Open SSH local port forward for QEMU COM1 serial & QMP sockets
  252. ssh_tunnel_proc = subprocess.Popen(
  253. [
  254. "ssh",
  255. "-o", "BatchMode=yes",
  256. "-o", "ExitOnForwardFailure=yes",
  257. "-N",
  258. "-L", f"127.0.0.1:{q_serial_port}:127.0.0.1:{q_serial_port}",
  259. "-L", f"127.0.0.1:{q_qmp_port}:127.0.0.1:{q_qmp_port}",
  260. f"{REMOTE_USER}@{REMOTE_HOST}",
  261. ],
  262. stdout=subprocess.DEVNULL,
  263. stderr=subprocess.PIPE,
  264. text=True,
  265. )
  266. await qmp.connect(timeout_s=12.0)
  267. qstatus0 = await qmp.execute("query-status")
  268. assert qstatus0.get("running") is True, f"Expected KVM guest running, got {qstatus0}"
  269. # Start C BMC RMCP+ (:623) & SSHv2 (:2200) simulator on `127.0.2.170`
  270. bmc_proc = subprocess.Popen(
  271. [
  272. str(BMC_SIM_BIN),
  273. "--ctrl-port", str(bmc_ctrl_port),
  274. "--uart-base", str(bmc_uart_port),
  275. "--ipmi-port", "623",
  276. "--ssh-port", "2200",
  277. "--probe22-port", "0",
  278. station_ip,
  279. ],
  280. stdout=subprocess.PIPE,
  281. stderr=subprocess.PIPE,
  282. text=True,
  283. env=env,
  284. )
  285. await asyncio.sleep(0.6)
  286. stats: Dict[str, Any] = {}
  287. bridge_task = asyncio.create_task(
  288. bridge_kvm_uart_and_pwr(q_serial_port, bmc_uart_port, qmp, stats)
  289. )
  290. await wait_until(lambda: stats.get("bridge_connected") is True, timeout_s=10.0, desc="KVM UART bridge connected")
  291. # Start `/dev/pts/*` 6400 Hood simulator for S1
  292. hood = HoodPtsSim("kvm-hood-S1", 0, ("127.0.0.1", bmc_ctrl_port), sync_bmc=True)
  293. hood_task = asyncio.create_task(hood.physics_and_heartbeat_loop())
  294. # Start unmodified `stl_native_server` pointing S1 -> `127.0.2.170`
  295. data_dir = local_tmp / "data"
  296. data_dir.mkdir(parents=True, exist_ok=True)
  297. cfg_path = local_tmp / "station-kvm.json"
  298. cfg_path.write_text(
  299. json.dumps(
  300. {
  301. "mode": "hardware",
  302. "data_dir": str(data_dir),
  303. "telemetry_interval_s": 1.0,
  304. "idle_poll_interval_s": 1,
  305. "stations": [
  306. {
  307. "station_id": "S1",
  308. "frontend_index": 0,
  309. "name": "KVM-OVMF 真机虚拟化工位",
  310. "mode": "hardware",
  311. "cpu_count": 1,
  312. "channels_per_cpu": 12,
  313. "bmc": {
  314. "enabled": True,
  315. "host": station_ip,
  316. "user": "ADMIN",
  317. "username": "ADMIN",
  318. "password": "Admin123@pl",
  319. "cipher_suite": 17,
  320. "timeout_s": 5,
  321. "console_transport": "ssh_console",
  322. "ssh_console_port": 2200,
  323. },
  324. "console": {
  325. "enabled": True,
  326. "transport": "ssh_console",
  327. "host": station_ip,
  328. "port": 2200,
  329. "user": "ADMIN",
  330. "write_chunk_bytes": 64,
  331. "write_gap_ms": 5.0,
  332. },
  333. }
  334. ],
  335. },
  336. indent=2,
  337. ),
  338. encoding="utf-8",
  339. )
  340. server_proc = subprocess.Popen(
  341. [
  342. str(STL_SERVER_BIN),
  343. "--config", str(cfg_path),
  344. "--data-dir", str(data_dir),
  345. "--web-listen", f"127.0.0.1:{web_port}",
  346. "--tftp-listen", "disabled",
  347. "--pxe-mode", "disabled",
  348. "--web-dir", str(WEB_DIR),
  349. "--contracts", str(CONTRACTS_PATH),
  350. "--web-password", "disabled",
  351. ],
  352. cwd=str(ROOT_DIR),
  353. stdout=subprocess.DEVNULL,
  354. stderr=subprocess.PIPE,
  355. text=True,
  356. env=env,
  357. )
  358. results = []
  359. async with aiohttp.ClientSession() as http:
  360. # Wait HTTP up
  361. await wait_until(
  362. lambda: _http_ok(http, f"http://127.0.0.1:{web_port}/"),
  363. timeout_s=10.0,
  364. desc="stl_native_server HTTP up",
  365. )
  366. ws = WsRpcClient(http, f"ws://127.0.0.1:{web_port}/ws")
  367. await ws.connect()
  368. try:
  369. # Wait for S1 BMC + :2200 SSH console online AND real OVMF UEFI Shell prompt!
  370. print("[Tier3][1/3] Booting real KVM + EDK2 OVMF guest into UEFI Interactive Shell & running automated MT PASS...", flush=True)
  371. await wait_until(
  372. lambda: _station_online(ws, "S1"),
  373. timeout_s=15.0,
  374. desc="S1 KVM station online",
  375. )
  376. # Reset KVM guest via QMP so `stl_native_server` observes the full OVMF boot + startup.nsh + `Shell>`!
  377. await ws.call(
  378. "EnqueueCommand",
  379. {
  380. "command_id": f"kvm-cfg-{uuid.uuid4().hex[:8]}",
  381. "station_id": "S1",
  382. "method": "SaveFirmwareSettings",
  383. "arguments": {"mt_selection": {"efi_path": "FS0:\\EFI\\kvm_mt_pass.nsh"}},
  384. },
  385. )
  386. await ws.call(
  387. "EnqueueCommand",
  388. {
  389. "command_id": f"kvm-plan-{uuid.uuid4().hex[:8]}",
  390. "station_id": "S1",
  391. "method": "SaveBootPlan",
  392. "arguments": {
  393. "plan": {
  394. "preset": "auto",
  395. "mt_enabled": True,
  396. "run_rmt": True,
  397. "stages": {"uip1": "auto", "amt": "auto", "uip2": "auto", "uefi": "auto"},
  398. },
  399. "watchdog": {"dense_stage_silence_timeout_ms": 20000, "mt_silence_timeout_ms": 20000},
  400. },
  401. },
  402. )
  403. await ws.call(
  404. "EnqueueCommand",
  405. {
  406. "command_id": f"kvm-start1-{uuid.uuid4().hex[:8]}",
  407. "station_id": "S1",
  408. "method": "ControlBootPlan",
  409. "arguments": {"action": "start"},
  410. },
  411. )
  412. await qmp.execute("system_reset")
  413. st_pass = await wait_until(
  414. lambda: _station_terminal(ws, "S1"),
  415. timeout_s=30.0,
  416. desc="KVM OVMF UEFI automated MT PASS",
  417. )
  418. if st_pass["task_status"] != "completed":
  419. clean_u = await ws.call("ReadCleanedUart", {"station_id": "S1", "offset": 0, "max_bytes": 8192})
  420. raise AssertionError(
  421. 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:])}"
  422. )
  423. assert st_pass["verdict"] == "pass", f"Unexpected KVM S1 state: {st_pass}"
  424. assert (st_pass.get("stage_completions") or {}).get("uefi_complete") is True
  425. assert (st_pass.get("stage_completions") or {}).get("mt_pass_complete") is True
  426. results.append({"scenario": "1_kvm_ovmf_uefi_shell_auto_pass", "status": "PASS"})
  427. print(" -> PASS", flush=True)
  428. # ============================================================
  429. # Scenario 2: Real `mt86plus.efi` Execution on KVM RAM + QMP Hardware vCPU Freeze
  430. # -> Watchdog `stage_hang_timeout` + Level-1 Scene Preserved + Hood Purge
  431. # ============================================================
  432. print("[Tier3][2/3] Launching real x86-64 `mt86plus.efi` on KVM RAM + QMP `stop` hardware vCPU freeze...", flush=True)
  433. hood.clear_history()
  434. await ws.call(
  435. "ThermalAction",
  436. {"station_id": "S1", "action": "connect", "mode": "serial", "serial_path": hood.pts_path, "serial_baud": 115200},
  437. )
  438. await wait_until(
  439. lambda: _thermal_online(ws, "S1"),
  440. timeout_s=4.0,
  441. desc="KVM Hood 0xF0 online",
  442. )
  443. await ws.call("ThermalAction", {"station_id": "S1", "action": "set_temp", "target_c": 70})
  444. await ws.call(
  445. "EnqueueCommand",
  446. {
  447. "command_id": f"kvm-cfg2-{uuid.uuid4().hex[:8]}",
  448. "station_id": "S1",
  449. "method": "SaveFirmwareSettings",
  450. "arguments": {"mt_selection": {"efi_path": "FS0:\\EFI\\launch_real_mt86.nsh"}},
  451. },
  452. )
  453. await ws.call(
  454. "EnqueueCommand",
  455. {
  456. "command_id": f"kvm-wd2a-{uuid.uuid4().hex[:8]}",
  457. "station_id": "S1",
  458. "method": "ConfigureWatchdog",
  459. "arguments": {
  460. "watchdog": {
  461. "enabled": True,
  462. "reboot_on_hang": False,
  463. "dense_stage_silence_timeout_ms": 20000,
  464. "mt_silence_timeout_ms": 20000,
  465. "mt_max_duration_ms": 60000,
  466. }
  467. },
  468. },
  469. )
  470. rx_before_mt86 = stats.get("kvm_uart_rx_bytes", 0)
  471. await ws.call(
  472. "EnqueueCommand",
  473. {
  474. "command_id": f"kvm-start2-{uuid.uuid4().hex[:8]}",
  475. "station_id": "S1",
  476. "method": "ControlBootPlan",
  477. "arguments": {"action": "start"},
  478. },
  479. )
  480. # Wait until S1 enters `mt` phase AND real `mt86plus.efi` streams serial output from KVM RAM!
  481. async def _in_real_mt86():
  482. st = await ws.call("GetStation", {"station_id": "S1"})
  483. if st.get("phase") == "mt" and stats.get("kvm_uart_rx_bytes", 0) > rx_before_mt86 + 250:
  484. return st
  485. return None
  486. await wait_until(_in_real_mt86, timeout_s=30.0, desc="Real mt86plus.efi active on KVM guest")
  487. await asyncio.sleep(0.8) # Let mt86plus.efi render initial test progress lines
  488. # Tighten MT silence watchdog to 2.5s and freeze physical KVM vCPU via QMP `stop`!
  489. await ws.call(
  490. "EnqueueCommand",
  491. {
  492. "command_id": f"kvm-wd2b-{uuid.uuid4().hex[:8]}",
  493. "station_id": "S1",
  494. "method": "ConfigureWatchdog",
  495. "arguments": {"watchdog": {"mt_silence_timeout_ms": 2500}},
  496. },
  497. )
  498. await qmp.execute("stop")
  499. q_frozen = await qmp.execute("query-status")
  500. assert q_frozen.get("status") == "paused", f"Expected QMP status=paused, got {q_frozen}"
  501. st_hang = await wait_until(
  502. lambda: _station_terminal(ws, "S1"),
  503. timeout_s=12.0,
  504. desc="Watchdog catching real KVM vCPU freeze",
  505. )
  506. assert st_hang["task_status"] == "failed", f"Expected failed on KVM freeze, got {st_hang}"
  507. assert st_hang.get("fault_code") == "stage_hang_timeout", f"Expected stage_hang_timeout, got {st_hang}"
  508. assert st_hang.get("hang_scene_preserved") is True
  509. # Confirm Level-1 preserved the exact paused KVM vCPU state (no QMP reset issued!)
  510. await asyncio.sleep(1.0)
  511. q_still_paused = await qmp.execute("query-status")
  512. assert q_still_paused.get("status") == "paused", f"Level-1 MUST preserve paused KVM vCPU, got {q_still_paused}"
  513. await wait_until(
  514. lambda: hood.snapshot().get("purge_cool_count", 0) >= 1 and hood.cooling_purge is True,
  515. timeout_s=5.0,
  516. desc="6400 Hood 0x08 00 cooling purge on KVM vCPU freeze",
  517. )
  518. results.append({"scenario": "2_kvm_real_mt86plus_qmp_vcpu_hang_and_hood_purge", "status": "PASS"})
  519. print(" -> PASS", flush=True)
  520. # ============================================================
  521. # Scenario 3: Real IPMI RMCP+ `StationPower: host_reset` -> QMP Reboot Recovery
  522. # ============================================================
  523. print("[Tier3][3/3] Issuing real IPMI RMCP+ `host_reset` -> QMP `cont` + `system_reset` -> OVMF Shell recovery...", flush=True)
  524. rx_before_rst = stats.get("kvm_uart_rx_bytes", 0)
  525. stats["tail_text"] = ""
  526. await ws.call(
  527. "EnqueueCommand",
  528. {
  529. "command_id": f"kvm-rst-{uuid.uuid4().hex[:8]}",
  530. "station_id": "S1",
  531. "method": "StationPower",
  532. "arguments": {"action": "host_reset"},
  533. },
  534. )
  535. async def _kvm_rebooted_to_shell():
  536. qst = await qmp.execute("query-status")
  537. if not qst.get("running"):
  538. return None
  539. tail = stats.get("tail_text", "")
  540. if (
  541. stats.get("kvm_uart_rx_bytes", 0) > rx_before_rst + 300
  542. and "STOP_RMT_N0" in tail
  543. and ("FS0:" in tail or "Shell>" in tail or "UEFI Interactive Shell" in tail)
  544. ):
  545. return True
  546. return None
  547. await wait_until(_kvm_rebooted_to_shell, timeout_s=25.0, desc="KVM OVMF rebooted back to UEFI Shell")
  548. results.append({"scenario": "3_ipmi_rmcp_to_qmp_reset_recovery", "status": "PASS"})
  549. print(" -> PASS", flush=True)
  550. finally:
  551. await ws.close()
  552. elapsed_s = round(time.monotonic() - t0, 2)
  553. summary = {"tier": "Tier3_KVM_OVMF_UEFI_mt86plus_E2E", "ok": True, "elapsed_s": elapsed_s, "results": results}
  554. print(f"\n[Tier3] ALL 3 REAL KVM + OVMF + mt86plus.efi SCENARIOS PASSED in {elapsed_s}s!", flush=True)
  555. return summary
  556. finally:
  557. if bridge_task:
  558. bridge_task.cancel()
  559. if hood_task:
  560. hood_task.cancel()
  561. if hood:
  562. hood.close()
  563. await qmp.close()
  564. for proc in (server_proc, bmc_proc, ssh_tunnel_proc):
  565. if proc and proc.poll() is None:
  566. with contextlib.suppress(Exception):
  567. proc.terminate()
  568. proc.wait(timeout=3.0)
  569. if proc.poll() is None:
  570. with contextlib.suppress(Exception):
  571. proc.kill()
  572. with contextlib.suppress(Exception):
  573. subprocess.run(
  574. [
  575. "ssh",
  576. "-o", "BatchMode=yes",
  577. f"{REMOTE_USER}@{REMOTE_HOST}",
  578. f"podman rm -f {cname} >/dev/null 2>&1 || true; rm -rf {remote_dir}",
  579. ],
  580. timeout=10,
  581. capture_output=True,
  582. )
  583. shutil.rmtree(local_tmp, ignore_errors=True)
  584. async def _http_ok(http: aiohttp.ClientSession, url: str) -> bool:
  585. try:
  586. async with http.get(url, timeout=aiohttp.ClientTimeout(total=1.0)) as r:
  587. return r.status == 200
  588. except Exception:
  589. return False
  590. async def _station_online(ws: WsRpcClient, sid: str) -> Any:
  591. st = await ws.call("GetStation", {"station_id": sid})
  592. return st if st.get("bmc_state") == "online" and st.get("console_online") is True else None
  593. async def _station_terminal(ws: WsRpcClient, sid: str) -> Any:
  594. st = await ws.call("GetStation", {"station_id": sid})
  595. return st if st.get("task_status") in ("completed", "failed") else None
  596. async def _thermal_online(ws: WsRpcClient, sid: str) -> Any:
  597. snap = await ws.call("GetThermalConsole", {"station_id": sid})
  598. return snap if (snap.get("mcu") or {}).get("online") else None
  599. if __name__ == "__main__":
  600. res = asyncio.run(run_tier3_kvm_suite())
  601. out_file = ROOT_DIR / "build" / "sim" / "tier3_kvm_uefi_report.json"
  602. out_file.parent.mkdir(parents=True, exist_ok=True)
  603. out_file.write_text(json.dumps(res, indent=2, ensure_ascii=False), encoding="utf-8")