test_tier3b_diskless_pxe.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. #!/usr/bin/env python3
  2. """
  3. test_tier3b_diskless_pxe.py — Tier 3B Real 100% Diskless KVM + OVMF UEFI PXE Boot
  4. via Built-in ProxyDHCP under a Competing LAN DHCP Router
  5. Runs completely isolated inside an ephemeral Podman container (`--rm --network=none --device /dev/kvm --device /dev/net/tun`)
  6. on `root@192.168.2.25` so zero host network state is ever touched:
  7. 1. Real L2 Ethernet bridge `br0` (`10.99.77.1/24` = unmodified `stl_native_server --pxe-mode proxy --pxe-iface br0`)
  8. 2. Separate network namespace `lan_rtr` (`10.99.77.2/24`) running a real competing LAN DHCP Router (assigns IPs ONLY, no PXE)
  9. 3. Separate network namespace `office_pc` sending an ordinary non-PXE `DHCPDISCOVER` -> verifies ONLY the competing router
  10. replies and `stl_native_server` ignores it (`packets_ignored_non_pxe >= 1`)
  11. 4. `stl_native_server` 1-click LAN self-check (`ProbePxeNetwork`) -> verifies detection of external router `10.99.77.2`
  12. 5. 100% DISKLESS (`-drive` NONE — ZERO disks attached!) KVM + EDK2 OVMF VM on `tap0` (`mac=52:54:00:aa:bb:cc`) ->
  13. gets IP `10.99.77.5x` from competing router `10.99.77.2`, gets ProxyDHCP `118.efi` from `stl_native_server` (`10.99.77.1`),
  14. downloads real x86-64 `mt86plus.efi` via built-in UDP :69 TFTP, and boots it in RAM with zero local disks!
  15. """
  16. import json
  17. import os
  18. from pathlib import Path
  19. import re
  20. import subprocess
  21. import sys
  22. import tarfile
  23. import tempfile
  24. import time
  25. from typing import Any, Dict, List
  26. ROOT_DIR = Path(__file__).resolve().parents[2]
  27. STL_SERVER_BIN = ROOT_DIR / "build" / "native" / "stl_native_server"
  28. CONTRACTS_PATH = ROOT_DIR / "contracts" / "firmware-vd012.json"
  29. WEB_DIR = ROOT_DIR / "web"
  30. REMOTE_HOST = os.environ.get("STL_KVM_HOST", "192.168.2.25")
  31. REMOTE_USER = os.environ.get("STL_KVM_USER", "root")
  32. PODMAN_IMAGE = "localhost/omo-lab:13-iso-20260921T030408Z"
  33. SKIP_SO_PREFIXES = (
  34. "libc.so",
  35. "libm.so",
  36. "libdl.so",
  37. "libpthread.so",
  38. "librt.so",
  39. "libutil.so",
  40. "libgcc_s.so",
  41. "libresolv.so",
  42. "ld-linux",
  43. )
  44. IN_CONTAINER_RUNNER = r'''#!/usr/bin/env python3
  45. import base64
  46. import hashlib
  47. import json
  48. import os
  49. from pathlib import Path
  50. import socket
  51. import struct
  52. import subprocess
  53. import sys
  54. import threading
  55. import time
  56. import urllib.request
  57. SIM = Path("/sim")
  58. DHCP_COOKIE = b"\x63\x82\x53\x63"
  59. def sh(cmd: str, check: bool = True) -> subprocess.CompletedProcess:
  60. return subprocess.run(["bash", "-lc", cmd], check=check, capture_output=True, text=True)
  61. def run_competing_lan_dhcp_router() -> None:
  62. """Real RFC 2131 LAN DHCP Router (assigns 10.99.77.50..99, ZERO PXE options)."""
  63. srv_ip = socket.inet_aton("10.99.77.2")
  64. mask = socket.inet_aton("255.255.255.0")
  65. leases = {}
  66. next_host = [50]
  67. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  68. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  69. sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
  70. sock.setsockopt(socket.SOL_SOCKET, 25, b"veth-rtr\x00") # SO_BINDTODEVICE
  71. sock.bind(("0.0.0.0", 67))
  72. sock.settimeout(0.5)
  73. def parse_opts(data: bytes):
  74. opts = {}
  75. i = 240
  76. while i < len(data):
  77. c = data[i]
  78. i += 1
  79. if c == 0:
  80. continue
  81. if c == 255:
  82. break
  83. if i >= len(data):
  84. break
  85. ln = data[i]
  86. i += 1
  87. opts[c] = data[i : i + ln]
  88. i += ln
  89. return opts
  90. log_path = SIM / "router_dhcp.log"
  91. while not (SIM / "stop_router").exists():
  92. try:
  93. pkt, addr = sock.recvfrom(1500)
  94. except socket.timeout:
  95. continue
  96. except Exception as exc:
  97. with open(log_path, "a", encoding="utf-8") as fp:
  98. fp.write(f"ERR {exc!r}\n")
  99. continue
  100. if len(pkt) < 240 or pkt[0] != 1 or pkt[236:240] != DHCP_COOKIE:
  101. continue
  102. opts = parse_opts(pkt)
  103. mtype = opts.get(53, b"\x00")[0]
  104. if mtype not in (1, 3):
  105. continue
  106. mac = pkt[28:34]
  107. mac_str = ":".join(f"{b:02x}" for b in mac)
  108. if mac_str not in leases:
  109. ip_str = f"10.99.77.{next_host[0]}"
  110. next_host[0] += 1
  111. leases[mac_str] = ip_str
  112. yiaddr = socket.inet_aton(leases[mac_str])
  113. reply_type = 2 if mtype == 1 else 5 # OFFER or ACK
  114. resp = bytearray(240)
  115. resp[0] = 2 # BOOTREPLY
  116. resp[1] = 1
  117. resp[2] = 6
  118. resp[4:8] = pkt[4:8] # xid
  119. resp[10:12] = pkt[10:12] # flags
  120. resp[16:20] = yiaddr # yiaddr (client IP ONLY, siaddr=0.0.0.0, file="")
  121. resp[28:44] = pkt[28:44] # chaddr
  122. resp[236:240] = DHCP_COOKIE
  123. resp += bytes([53, 1, reply_type])
  124. resp += bytes([54, 4]) + srv_ip
  125. resp += bytes([51, 4]) + struct.pack("!I", 3600)
  126. resp += bytes([1, 4]) + mask
  127. resp += bytes([3, 4]) + srv_ip
  128. resp += bytes([255])
  129. if len(resp) < 300:
  130. resp += b"\x00" * (300 - len(resp))
  131. sock.sendto(bytes(resp), ("255.255.255.255", 68))
  132. with open(log_path, "a", encoding="utf-8") as fp:
  133. fp.write(f"{'OFFER' if reply_type == 2 else 'ACK'} mac={mac_str} ip={leases[mac_str]}\n")
  134. def run_office_pc_non_pxe_probe() -> dict:
  135. """Send ordinary MSFT 5.0 non-PXE DHCPDISCOVER and capture ALL UDP:68 replies via AF_PACKET (authentic unaddressed NIC)."""
  136. raw_rx = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0800))
  137. raw_rx.bind(("veth-pc", 0))
  138. raw_rx.settimeout(0.2)
  139. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  140. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  141. sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
  142. sock.setsockopt(socket.SOL_SOCKET, 25, b"veth-pc\x00") # SO_BINDTODEVICE
  143. sock.bind(("0.0.0.0", 68))
  144. xid = b"\xde\xad\xbe\xef"
  145. mac = bytes([0x02, 0xAA, 0xBB, 0xCC, 0xDD, 0x01])
  146. disc = bytearray(240)
  147. disc[0] = 1
  148. disc[1] = 1
  149. disc[2] = 6
  150. disc[4:8] = xid
  151. disc[10:12] = b"\x80\x00" # broadcast
  152. disc[28:34] = mac
  153. disc[236:240] = DHCP_COOKIE
  154. disc += bytes([53, 1, 1])
  155. vc = b"MSFT 5.0"
  156. disc += bytes([60, len(vc)]) + vc
  157. disc += bytes([55, 3, 1, 3, 6])
  158. disc += bytes([255])
  159. if len(disc) < 300:
  160. disc += b"\x00" * (300 - len(disc))
  161. sock.sendto(bytes(disc), ("255.255.255.255", 67))
  162. offers = []
  163. deadline = time.monotonic() + 1.1
  164. while time.monotonic() < deadline:
  165. try:
  166. frame = raw_rx.recv(2048)
  167. except socket.timeout:
  168. continue
  169. if len(frame) < 14 + 20 + 8:
  170. continue
  171. ihl = (frame[14] & 0x0F) * 4
  172. if frame[14 + 9] != 17 or len(frame) < 14 + ihl + 8:
  173. continue
  174. src_ip = socket.inet_ntoa(frame[14 + 12 : 14 + 16])
  175. udp_off = 14 + ihl
  176. src_port, dst_port = struct.unpack("!HH", frame[udp_off : udp_off + 4])
  177. if dst_port != 68:
  178. continue
  179. pkt = frame[udp_off + 8 :]
  180. if len(pkt) < 240 or pkt[0] != 2 or pkt[4:8] != xid:
  181. continue
  182. yiaddr = socket.inet_ntoa(pkt[16:20])
  183. siaddr = socket.inet_ntoa(pkt[20:24])
  184. file_field = pkt[108:236].split(b"\x00", 1)[0].decode("ascii", errors="replace")
  185. offers.append({"from": src_ip, "src_port": src_port, "yiaddr": yiaddr, "siaddr": siaddr, "file": file_field})
  186. sock.close()
  187. raw_rx.close()
  188. return {"offers": offers}
  189. def ws_rpc_call(port: int, method: str, params: dict) -> dict:
  190. """Minimal zero-dependency RFC 6455 WebSocket JSON-RPC client (no aiohttp needed inside container)."""
  191. s = socket.create_connection(("127.0.0.1", port), timeout=15.0)
  192. key = base64.b64encode(os.urandom(16)).decode("ascii")
  193. req = (
  194. f"GET /ws HTTP/1.1\r\n"
  195. f"Host: 127.0.0.1:{port}\r\n"
  196. f"Upgrade: websocket\r\n"
  197. f"Connection: Upgrade\r\n"
  198. f"Sec-WebSocket-Key: {key}\r\n"
  199. f"Sec-WebSocket-Version: 13\r\n\r\n"
  200. )
  201. s.sendall(req.encode("ascii"))
  202. hdr = b""
  203. while b"\r\n\r\n" not in hdr:
  204. chunk = s.recv(4096)
  205. if not chunk:
  206. raise RuntimeError("WS handshake closed")
  207. hdr += chunk
  208. if b"101 " not in hdr.split(b"\r\n", 1)[0]:
  209. raise RuntimeError(f"WS handshake failed: {hdr[:120]!r}")
  210. extra = hdr.split(b"\r\n\r\n", 1)[1]
  211. req_id = f"pxe3b-{int(time.time() * 1000)}"
  212. payload = json.dumps({"v": 1, "id": req_id, "method": method, "params": params}).encode("utf-8")
  213. mask_key = os.urandom(4)
  214. frame = bytearray([0x81])
  215. if len(payload) < 126:
  216. frame.append(0x80 | len(payload))
  217. elif len(payload) < 65536:
  218. frame.append(0x80 | 126)
  219. frame += struct.pack("!H", len(payload))
  220. else:
  221. frame.append(0x80 | 127)
  222. frame += struct.pack("!Q", len(payload))
  223. frame += mask_key
  224. frame += bytes(b ^ mask_key[i & 3] for i, b in enumerate(payload))
  225. s.sendall(bytes(frame))
  226. buf = bytearray(extra)
  227. def read_exact(n: int) -> bytes:
  228. while len(buf) < n:
  229. c = s.recv(4096)
  230. if not c:
  231. raise RuntimeError("WS EOF")
  232. buf.extend(c)
  233. out = bytes(buf[:n])
  234. del buf[:n]
  235. return out
  236. try:
  237. while True:
  238. b0, b1 = read_exact(2)
  239. op = b0 & 0x0F
  240. ln = b1 & 0x7F
  241. if ln == 126:
  242. ln = struct.unpack("!H", read_exact(2))[0]
  243. elif ln == 127:
  244. ln = struct.unpack("!Q", read_exact(8))[0]
  245. data = read_exact(ln)
  246. if op == 1:
  247. msg = json.loads(data.decode("utf-8"))
  248. if msg.get("id") == req_id:
  249. if not msg.get("ok"):
  250. raise RuntimeError(f"RPC {method} error: {msg.get('error')}")
  251. return msg.get("result") or {}
  252. finally:
  253. s.close()
  254. def main() -> None:
  255. if len(sys.argv) >= 2 and sys.argv[1] == "--router":
  256. run_competing_lan_dhcp_router()
  257. return
  258. if len(sys.argv) >= 2 and sys.argv[1] == "--office-pc":
  259. print(json.dumps(run_office_pc_non_pxe_probe()))
  260. return
  261. # 1. Build real 3-node Ethernet L2 topology on bridge br0
  262. sh(
  263. """
  264. set -euo pipefail
  265. ip link set lo up
  266. ip link add br0 type bridge
  267. ip link set br0 type bridge stp_state 0
  268. ip addr add 10.99.77.1/24 dev br0
  269. ip link set br0 up
  270. ip route add 255.255.255.255/32 dev br0
  271. ip netns add lan_rtr
  272. ip link add veth-rtr type veth peer name veth-rtr-br
  273. ip link set veth-rtr netns lan_rtr
  274. ip link set veth-rtr-br master br0 up
  275. ip netns exec lan_rtr ip link set lo up
  276. ip netns exec lan_rtr ip addr add 10.99.77.2/24 dev veth-rtr
  277. ip netns exec lan_rtr ip link set veth-rtr up
  278. ip netns exec lan_rtr ip route add 255.255.255.255/32 dev veth-rtr
  279. ip netns add office_pc
  280. ip link add veth-pc type veth peer name veth-pc-br
  281. ip link set veth-pc address 02:aa:bb:cc:dd:01
  282. ip link set veth-pc netns office_pc
  283. ip link set veth-pc-br master br0 up
  284. ip netns exec office_pc ip link set lo up
  285. ip netns exec office_pc ip link set veth-pc up
  286. ip netns exec office_pc ip route add 255.255.255.255/32 dev veth-pc
  287. ip tuntap add dev tap0 mode tap
  288. ip link set tap0 master br0
  289. ip link set tap0 up
  290. """
  291. )
  292. # 2. Start competing LAN DHCP Router in `lan_rtr` (10.99.77.2, NO PXE options)
  293. rtr_proc = subprocess.Popen(
  294. ["ip", "netns", "exec", "lan_rtr", "python3", str(SIM / "in_container_pxe_runner.py"), "--router"],
  295. stdout=subprocess.DEVNULL,
  296. stderr=subprocess.PIPE,
  297. text=True,
  298. )
  299. time.sleep(0.4)
  300. # 3. Prepare data dir with REAL compiled mt86plus.efi as 118.efi
  301. data_dir = SIM / "data"
  302. pxe_dir = data_dir / "pxe_tftp"
  303. pxe_dir.mkdir(parents=True, exist_ok=True)
  304. efi_bytes = (SIM / "mt86plus.efi").read_bytes()
  305. (pxe_dir / "118.efi").write_bytes(efi_bytes)
  306. efi_sha256 = hashlib.sha256(efi_bytes).hexdigest()
  307. cfg_path = SIM / "station.json"
  308. cfg_path.write_text(
  309. json.dumps(
  310. {
  311. "mode": "hardware",
  312. "data_dir": str(data_dir),
  313. "stations": [
  314. {
  315. "station_id": "S1",
  316. "name": "Diskless-PXE-KVM",
  317. "cpu_count": 1,
  318. "os_mac": "52:54:00:aa:bb:cc",
  319. "bmc": {"enabled": False, "host": ""},
  320. "console": {"enabled": False, "transport": "local_serial", "host": ""},
  321. }
  322. ],
  323. }
  324. ),
  325. encoding="utf-8",
  326. )
  327. srv_env = dict(os.environ)
  328. srv_env["LD_LIBRARY_PATH"] = str(SIM / "libs")
  329. srv_log = open(SIM / "stl_server.log", "w", encoding="utf-8")
  330. srv_proc = subprocess.Popen(
  331. [
  332. str(SIM / "stl_native_server"),
  333. "--config", str(cfg_path),
  334. "--data-dir", str(data_dir),
  335. "--web-listen", "0.0.0.0:18099",
  336. "--tftp-listen", "0.0.0.0:69",
  337. "--pxe-mode", "proxy",
  338. "--pxe-iface", "br0",
  339. "--web-dir", str(SIM / "web"),
  340. "--contracts", str(SIM / "contracts" / "firmware-vd012.json"),
  341. "--web-password", "disabled",
  342. "--detail-log", "on",
  343. ],
  344. env=srv_env,
  345. stdout=srv_log,
  346. stderr=subprocess.STDOUT,
  347. text=True,
  348. )
  349. qemu_proc = None
  350. try:
  351. # Wait until stl_native_server binds UDP 67, 4011, 69 & HTTP 18099
  352. st_pxe = None
  353. for _ in range(40):
  354. try:
  355. st_pxe = ws_rpc_call(18099, "GetPxeStatus", {})
  356. if st_pxe.get("dhcp67_bound") and st_pxe.get("proxy4011_bound") and st_pxe.get("tftp69_bound"):
  357. break
  358. except Exception:
  359. pass
  360. time.sleep(0.25)
  361. assert st_pxe and st_pxe.get("dhcp67_bound") and st_pxe.get("proxy4011_bound") and st_pxe.get("tftp69_bound"), (
  362. f"stl_native_server failed to bind PXE/TFTP ports: {st_pxe}\nLOG={Path(SIM / 'stl_server.log').read_text()}"
  363. )
  364. assert st_pxe.get("efi_present") is True and int(st_pxe.get("efi_bytes", 0)) == len(efi_bytes)
  365. # Verify HTTP Boot endpoint serves byte-identical 118.efi
  366. with urllib.request.urlopen("http://10.99.77.1:18099/pxe/118.efi", timeout=5) as r:
  367. dl_efi = r.read()
  368. assert hashlib.sha256(dl_efi).hexdigest() == efi_sha256, "HTTP Boot /pxe/118.efi SHA mismatch"
  369. # 4. Verify non-PXE office PC ONLY gets reply from competing router 10.99.77.2 (0 from stl_native_server)
  370. pc_out = subprocess.run(
  371. ["ip", "netns", "exec", "office_pc", "python3", str(SIM / "in_container_pxe_runner.py"), "--office-pc"],
  372. capture_output=True,
  373. text=True,
  374. timeout=10,
  375. )
  376. assert pc_out.returncode == 0, f"office_pc probe failed rc={pc_out.returncode}: stdout={pc_out.stdout} stderr={pc_out.stderr}"
  377. pc_res = json.loads(pc_out.stdout.strip())
  378. offers = pc_res.get("offers") or []
  379. assert len(offers) == 1, f"Office PC must get EXACTLY 1 offer (from competing router only!), got {offers}"
  380. assert offers[0]["from"] == "10.99.77.2" and offers[0]["yiaddr"].startswith("10.99.77.5"), f"Bad office PC offer: {offers}"
  381. assert offers[0]["file"] == ""
  382. st_after_pc = ws_rpc_call(18099, "GetPxeStatus", {})
  383. assert int(st_after_pc.get("packets_ignored_non_pxe", 0)) >= 1, f"ProxyDHCP must count ignored non-PXE packet: {st_after_pc}"
  384. # 5. Verify 1-click LAN DHCP/PXE self-check (`ProbePxeNetwork`) detects external router 10.99.77.2
  385. probe_res = ws_rpc_call(18099, "ProbePxeNetwork", {"iface": "br0", "timeout_ms": 1000})
  386. ext_srvs = probe_res.get("external_dhcp_servers") or []
  387. assert any(s.get("server_ip") == "10.99.77.2" and s.get("has_pxe_conflict") is False for s in ext_srvs), (
  388. f"ProbePxeNetwork must detect competing LAN DHCP router 10.99.77.2: {probe_res}"
  389. )
  390. assert probe_res.get("recommended_mode") == "proxy", f"Expected recommended_mode=proxy: {probe_res}"
  391. # 6. Boot 100% DISKLESS (`-drive` NONE — ZERO disks!) real KVM + EDK2 OVMF UEFI VM over PXE!
  392. serial_log_path = SIM / "vm_serial.log"
  393. serial_log_path.write_bytes(b"")
  394. qemu_cmd = [
  395. "qemu-system-x86_64",
  396. "-machine", "q35,accel=kvm",
  397. "-cpu", "host",
  398. "-smp", "2",
  399. "-m", "512M",
  400. "-display", "none",
  401. "-drive", f"if=pflash,format=raw,readonly=on,file={SIM / 'code.fd'}",
  402. "-drive", f"if=pflash,format=raw,file={SIM / 'vars.fd'}",
  403. "-netdev", "tap,id=net0,ifname=tap0,script=no,downscript=no",
  404. "-device", "e1000,netdev=net0,mac=52:54:00:aa:bb:cc,bootindex=1",
  405. "-serial", f"file:{serial_log_path}",
  406. ]
  407. qemu_proc = subprocess.Popen(qemu_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True)
  408. # Wait up to 45s for OVMF UEFI PXE to obtain IP from router 10.99.77.2 + ProxyDHCP 118.efi from 10.99.77.1 + TFTP download!
  409. vm_serial = ""
  410. pxe_client_ack = None
  411. deadline = time.monotonic() + 45.0
  412. while time.monotonic() < deadline:
  413. if serial_log_path.is_file():
  414. vm_serial = serial_log_path.read_text(encoding="utf-8", errors="replace")
  415. st_now = ws_rpc_call(18099, "GetPxeStatus", {})
  416. clients = st_now.get("discovered_clients") or []
  417. for c in clients:
  418. if (
  419. c.get("mac") == "52:54:00:aa:bb:cc"
  420. and c.get("boot_target") == "118.efi"
  421. and int(c.get("reply_count", 0)) >= 1
  422. ):
  423. pxe_client_ack = c
  424. if (
  425. "Station IP address is 10.99.77." in vm_serial
  426. and "Server IP address is 10.99.77.1" in vm_serial
  427. and "NBP filename is 118.efi" in vm_serial
  428. and "NBP file downloaded successfully" in vm_serial
  429. and "BdsDxe: starting" in vm_serial
  430. and pxe_client_ack is not None
  431. ):
  432. # Give real mt86plus.efi 2.5s to run in KVM RAM after NBP handoff
  433. time.sleep(2.5)
  434. vm_serial = serial_log_path.read_text(encoding="utf-8", errors="replace")
  435. break
  436. time.sleep(0.5)
  437. st_final = ws_rpc_call(18099, "GetPxeStatus", {})
  438. router_log = (SIM / "router_dhcp.log").read_text(encoding="utf-8", errors="replace") if (SIM / "router_dhcp.log").is_file() else ""
  439. srv_log.flush()
  440. srv_txt = (SIM / "stl_server.log").read_text(encoding="utf-8", errors="replace")
  441. assert pxe_client_ack is not None, (
  442. f"Diskless KVM VM did not receive ProxyDHCP reply for 118.efi!\n"
  443. f"PXE_STATUS={json.dumps(st_final, ensure_ascii=False)}\nROUTER_LOG={router_log}\n"
  444. f"VM_SERIAL={vm_serial[-2000:]}\nSRV_LOG={srv_txt[-1500:]}"
  445. )
  446. assert "Station IP address is 10.99.77." in vm_serial, f"Missing competing router IP in OVMF output:\n{vm_serial[-2000:]}"
  447. assert "Server IP address is 10.99.77.1" in vm_serial, f"Missing ProxyDHCP server IP 10.99.77.1:\n{vm_serial[-2000:]}"
  448. assert "NBP filename is 118.efi" in vm_serial, f"Missing NBP 118.efi:\n{vm_serial[-2000:]}"
  449. assert "NBP file downloaded successfully" in vm_serial, f"TFTP download of 118.efi failed:\n{vm_serial[-2000:]}"
  450. assert "BdsDxe: starting" in vm_serial, f"OVMF did not start downloaded 118.efi:\n{vm_serial[-2000:]}"
  451. assert f"ACK mac=52:54:00:aa:bb:cc ip=10.99.77." in router_log, f"Competing router did not lease IP to VM:\n{router_log}"
  452. assert qemu_proc.poll() is None, "Diskless KVM VM crashed immediately after NBP execution"
  453. result = {
  454. "ok": True,
  455. "office_pc_offer": offers[0],
  456. "packets_ignored_non_pxe": st_final.get("packets_ignored_non_pxe"),
  457. "probe_detected_router": ext_srvs,
  458. "probe_recommended_mode": probe_res.get("recommended_mode"),
  459. "diskless_pxe_client": pxe_client_ack,
  460. "http_boot_efi_sha256": efi_sha256,
  461. "efi_bytes": len(efi_bytes),
  462. "vm_serial_excerpt": vm_serial[-1200:],
  463. "router_log": router_log.strip(),
  464. }
  465. (SIM / "tier3b_result.json").write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
  466. print("TIER3B_SUCCESS")
  467. finally:
  468. (SIM / "stop_router").write_text("1", encoding="utf-8")
  469. for p in (qemu_proc, srv_proc, rtr_proc):
  470. if p is not None and p.poll() is None:
  471. p.terminate()
  472. try:
  473. p.wait(timeout=3)
  474. except Exception:
  475. p.kill()
  476. srv_log.close()
  477. if __name__ == "__main__":
  478. main()
  479. '''
  480. def collect_non_glibc_libs(binary: Path) -> List[Path]:
  481. env = dict(os.environ)
  482. env.pop("LD_LIBRARY_PATH", None)
  483. out = subprocess.run(["ldd", str(binary)], check=True, capture_output=True, text=True, env=env).stdout
  484. libs: List[Path] = []
  485. seen = set()
  486. for line in out.splitlines():
  487. m = re.search(r"=>\s+(/\S+)\s+\(", line)
  488. if not m:
  489. continue
  490. p = Path(m.group(1))
  491. if any(p.name.startswith(pref) for pref in SKIP_SO_PREFIXES):
  492. continue
  493. real = p.resolve()
  494. if real.is_file() and p.name not in seen:
  495. seen.add(p.name)
  496. libs.append((p.name, real)) # type: ignore[arg-type]
  497. return libs # type: ignore[return-value]
  498. def run_tier3b_diskless_pxe() -> Dict[str, Any]:
  499. t0 = time.monotonic()
  500. run_tag = f"xjkj-stl-pxe3b-{os.getpid()}-{int(time.time())}"
  501. remote_dir = f"/tmp/{run_tag}"
  502. print(f"[Tier3B] Bundling stl_native_server + runtime libs for 100% diskless KVM+OVMF ProxyDHCP test on {REMOTE_HOST}...", flush=True)
  503. with tempfile.TemporaryDirectory(prefix="xjkj_tier3b_") as ltmp:
  504. tar_path = Path(ltmp) / "bundle.tar"
  505. runner_path = Path(ltmp) / "in_container_pxe_runner.py"
  506. runner_path.write_text(IN_CONTAINER_RUNNER, encoding="utf-8")
  507. libs = collect_non_glibc_libs(STL_SERVER_BIN)
  508. with tarfile.open(tar_path, "w") as tf:
  509. tf.add(STL_SERVER_BIN, arcname="stl_native_server")
  510. tf.add(runner_path, arcname="in_container_pxe_runner.py")
  511. tf.add(CONTRACTS_PATH, arcname="contracts/firmware-vd012.json")
  512. tf.add(WEB_DIR / "index.html", arcname="web/index.html")
  513. for soname, real_path in libs: # type: ignore[misc]
  514. tf.add(real_path, arcname=f"libs/{soname}")
  515. try:
  516. # Upload tarball to remote tmp dir
  517. with open(tar_path, "rb") as fp:
  518. subprocess.run(
  519. [
  520. "ssh", "-o", "BatchMode=yes", f"{REMOTE_USER}@{REMOTE_HOST}",
  521. f"mkdir -p {remote_dir} && tar -xf - -C {remote_dir} && "
  522. f"cp /opt/edk2-uefi-lab/work/qemu/memtest86plus/code.fd {remote_dir}/code.fd && "
  523. f"cp /opt/edk2-uefi-lab/work/qemu/memtest86plus/vars.fd {remote_dir}/vars.fd && "
  524. f"cp /opt/edk2-uefi-lab/work/qemu/memtest86plus/mt86plus.efi {remote_dir}/mt86plus.efi",
  525. ],
  526. stdin=fp,
  527. check=True,
  528. timeout=60,
  529. )
  530. print("[Tier3B] Executing isolated L2 LAN (Competing Router + ProxyDHCP + Office PC + 100% Diskless KVM OVMF)...", flush=True)
  531. run_cmd = (
  532. f"podman run --rm --name {run_tag} "
  533. f"--privileged --network=none "
  534. f"--device /dev/kvm --device /dev/net/tun "
  535. f"-v {remote_dir}:/sim:rw "
  536. f"{PODMAN_IMAGE} "
  537. f"python3 /sim/in_container_pxe_runner.py"
  538. )
  539. proc = subprocess.run(
  540. ["ssh", "-o", "BatchMode=yes", f"{REMOTE_USER}@{REMOTE_HOST}", run_cmd],
  541. capture_output=True,
  542. text=True,
  543. timeout=120,
  544. )
  545. if proc.returncode != 0 or "TIER3B_SUCCESS" not in proc.stdout:
  546. raise RuntimeError(
  547. f"Tier3B Diskless KVM PXE failed (rc={proc.returncode}):\nSTDOUT:\n{proc.stdout}\nSTDERR:\n{proc.stderr}"
  548. )
  549. res_raw = subprocess.run(
  550. ["ssh", "-o", "BatchMode=yes", f"{REMOTE_USER}@{REMOTE_HOST}", f"cat {remote_dir}/tier3b_result.json"],
  551. check=True,
  552. capture_output=True,
  553. text=True,
  554. timeout=15,
  555. ).stdout
  556. inner = json.loads(res_raw)
  557. finally:
  558. subprocess.run(
  559. [
  560. "ssh", "-o", "BatchMode=yes", f"{REMOTE_USER}@{REMOTE_HOST}",
  561. f"podman rm -f {run_tag} >/dev/null 2>&1 || true; rm -rf {remote_dir}",
  562. ],
  563. timeout=15,
  564. capture_output=True,
  565. )
  566. elapsed_s = round(time.monotonic() - t0, 2)
  567. summary = {
  568. "tier": "Tier3B_Diskless_KVM_OVMF_ProxyDHCP_CompetingRouter_E2E",
  569. "ok": True,
  570. "elapsed_s": elapsed_s,
  571. **inner,
  572. }
  573. print(
  574. f"[Tier3B] 100% DISKLESS KVM+OVMF PXE UNDER COMPETING LAN DHCP ROUTER PASSED in {elapsed_s}s!\n"
  575. f" OfficePC -> {inner['office_pc_offer']['from']} ({inner['office_pc_offer']['yiaddr']}), "
  576. f"ignored_non_pxe={inner['packets_ignored_non_pxe']}\n"
  577. f" Diskless VM -> Router IP + ProxyDHCP 10.99.77.1 -> TFTP 118.efi ({inner['efi_bytes']}B) downloaded & booted!",
  578. flush=True,
  579. )
  580. return summary
  581. if __name__ == "__main__":
  582. res = run_tier3b_diskless_pxe()
  583. out_file = ROOT_DIR / "build" / "sim" / "tier3b_diskless_pxe_report.json"
  584. out_file.parent.mkdir(parents=True, exist_ok=True)
  585. out_file.write_text(json.dumps(res, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")