| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645 |
- #!/usr/bin/env python3
- """
- test_tier3b_diskless_pxe.py — Tier 3B Real 100% Diskless KVM + OVMF UEFI PXE Boot
- via Built-in ProxyDHCP under a Competing LAN DHCP Router
- Runs completely isolated inside an ephemeral Podman container (`--rm --network=none --device /dev/kvm --device /dev/net/tun`)
- on `root@192.168.2.25` so zero host network state is ever touched:
- 1. Real L2 Ethernet bridge `br0` (`10.99.77.1/24` = unmodified `stl_native_server --pxe-mode proxy --pxe-iface br0`)
- 2. Separate network namespace `lan_rtr` (`10.99.77.2/24`) running a real competing LAN DHCP Router (assigns IPs ONLY, no PXE)
- 3. Separate network namespace `office_pc` sending an ordinary non-PXE `DHCPDISCOVER` -> verifies ONLY the competing router
- replies and `stl_native_server` ignores it (`packets_ignored_non_pxe >= 1`)
- 4. `stl_native_server` 1-click LAN self-check (`ProbePxeNetwork`) -> verifies detection of external router `10.99.77.2`
- 5. 100% DISKLESS (`-drive` NONE — ZERO disks attached!) KVM + EDK2 OVMF VM on `tap0` (`mac=52:54:00:aa:bb:cc`) ->
- 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`),
- downloads real x86-64 `mt86plus.efi` via built-in UDP :69 TFTP, and boots it in RAM with zero local disks!
- """
- import json
- import os
- from pathlib import Path
- import re
- import subprocess
- import sys
- import tarfile
- import tempfile
- import time
- from typing import Any, Dict, List
- ROOT_DIR = Path(__file__).resolve().parents[2]
- STL_SERVER_BIN = ROOT_DIR / "build" / "native" / "stl_native_server"
- CONTRACTS_PATH = ROOT_DIR / "contracts" / "firmware-vd012.json"
- WEB_DIR = ROOT_DIR / "web"
- 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"
- SKIP_SO_PREFIXES = (
- "libc.so",
- "libm.so",
- "libdl.so",
- "libpthread.so",
- "librt.so",
- "libutil.so",
- "libgcc_s.so",
- "libresolv.so",
- "ld-linux",
- )
- IN_CONTAINER_RUNNER = r'''#!/usr/bin/env python3
- import base64
- import hashlib
- import json
- import os
- from pathlib import Path
- import socket
- import struct
- import subprocess
- import sys
- import threading
- import time
- import urllib.request
- SIM = Path("/sim")
- DHCP_COOKIE = b"\x63\x82\x53\x63"
- def sh(cmd: str, check: bool = True) -> subprocess.CompletedProcess:
- return subprocess.run(["bash", "-lc", cmd], check=check, capture_output=True, text=True)
- def run_competing_lan_dhcp_router() -> None:
- """Real RFC 2131 LAN DHCP Router (assigns 10.99.77.50..99, ZERO PXE options)."""
- srv_ip = socket.inet_aton("10.99.77.2")
- mask = socket.inet_aton("255.255.255.0")
- leases = {}
- next_host = [50]
- sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
- sock.setsockopt(socket.SOL_SOCKET, 25, b"veth-rtr\x00") # SO_BINDTODEVICE
- sock.bind(("0.0.0.0", 67))
- sock.settimeout(0.5)
- def parse_opts(data: bytes):
- opts = {}
- i = 240
- while i < len(data):
- c = data[i]
- i += 1
- if c == 0:
- continue
- if c == 255:
- break
- if i >= len(data):
- break
- ln = data[i]
- i += 1
- opts[c] = data[i : i + ln]
- i += ln
- return opts
- log_path = SIM / "router_dhcp.log"
- while not (SIM / "stop_router").exists():
- try:
- pkt, addr = sock.recvfrom(1500)
- except socket.timeout:
- continue
- except Exception as exc:
- with open(log_path, "a", encoding="utf-8") as fp:
- fp.write(f"ERR {exc!r}\n")
- continue
- if len(pkt) < 240 or pkt[0] != 1 or pkt[236:240] != DHCP_COOKIE:
- continue
- opts = parse_opts(pkt)
- mtype = opts.get(53, b"\x00")[0]
- if mtype not in (1, 3):
- continue
- mac = pkt[28:34]
- mac_str = ":".join(f"{b:02x}" for b in mac)
- if mac_str not in leases:
- ip_str = f"10.99.77.{next_host[0]}"
- next_host[0] += 1
- leases[mac_str] = ip_str
- yiaddr = socket.inet_aton(leases[mac_str])
- reply_type = 2 if mtype == 1 else 5 # OFFER or ACK
- resp = bytearray(240)
- resp[0] = 2 # BOOTREPLY
- resp[1] = 1
- resp[2] = 6
- resp[4:8] = pkt[4:8] # xid
- resp[10:12] = pkt[10:12] # flags
- resp[16:20] = yiaddr # yiaddr (client IP ONLY, siaddr=0.0.0.0, file="")
- resp[28:44] = pkt[28:44] # chaddr
- resp[236:240] = DHCP_COOKIE
- resp += bytes([53, 1, reply_type])
- resp += bytes([54, 4]) + srv_ip
- resp += bytes([51, 4]) + struct.pack("!I", 3600)
- resp += bytes([1, 4]) + mask
- resp += bytes([3, 4]) + srv_ip
- resp += bytes([255])
- if len(resp) < 300:
- resp += b"\x00" * (300 - len(resp))
- sock.sendto(bytes(resp), ("255.255.255.255", 68))
- with open(log_path, "a", encoding="utf-8") as fp:
- fp.write(f"{'OFFER' if reply_type == 2 else 'ACK'} mac={mac_str} ip={leases[mac_str]}\n")
- def run_office_pc_non_pxe_probe() -> dict:
- """Send ordinary MSFT 5.0 non-PXE DHCPDISCOVER and capture ALL UDP:68 replies via AF_PACKET (authentic unaddressed NIC)."""
- raw_rx = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0800))
- raw_rx.bind(("veth-pc", 0))
- raw_rx.settimeout(0.2)
- sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
- sock.setsockopt(socket.SOL_SOCKET, 25, b"veth-pc\x00") # SO_BINDTODEVICE
- sock.bind(("0.0.0.0", 68))
- xid = b"\xde\xad\xbe\xef"
- mac = bytes([0x02, 0xAA, 0xBB, 0xCC, 0xDD, 0x01])
- disc = bytearray(240)
- disc[0] = 1
- disc[1] = 1
- disc[2] = 6
- disc[4:8] = xid
- disc[10:12] = b"\x80\x00" # broadcast
- disc[28:34] = mac
- disc[236:240] = DHCP_COOKIE
- disc += bytes([53, 1, 1])
- vc = b"MSFT 5.0"
- disc += bytes([60, len(vc)]) + vc
- disc += bytes([55, 3, 1, 3, 6])
- disc += bytes([255])
- if len(disc) < 300:
- disc += b"\x00" * (300 - len(disc))
- sock.sendto(bytes(disc), ("255.255.255.255", 67))
- offers = []
- deadline = time.monotonic() + 1.1
- while time.monotonic() < deadline:
- try:
- frame = raw_rx.recv(2048)
- except socket.timeout:
- continue
- if len(frame) < 14 + 20 + 8:
- continue
- ihl = (frame[14] & 0x0F) * 4
- if frame[14 + 9] != 17 or len(frame) < 14 + ihl + 8:
- continue
- src_ip = socket.inet_ntoa(frame[14 + 12 : 14 + 16])
- udp_off = 14 + ihl
- src_port, dst_port = struct.unpack("!HH", frame[udp_off : udp_off + 4])
- if dst_port != 68:
- continue
- pkt = frame[udp_off + 8 :]
- if len(pkt) < 240 or pkt[0] != 2 or pkt[4:8] != xid:
- continue
- yiaddr = socket.inet_ntoa(pkt[16:20])
- siaddr = socket.inet_ntoa(pkt[20:24])
- file_field = pkt[108:236].split(b"\x00", 1)[0].decode("ascii", errors="replace")
- offers.append({"from": src_ip, "src_port": src_port, "yiaddr": yiaddr, "siaddr": siaddr, "file": file_field})
- sock.close()
- raw_rx.close()
- return {"offers": offers}
- def ws_rpc_call(port: int, method: str, params: dict) -> dict:
- """Minimal zero-dependency RFC 6455 WebSocket JSON-RPC client (no aiohttp needed inside container)."""
- s = socket.create_connection(("127.0.0.1", port), timeout=15.0)
- key = base64.b64encode(os.urandom(16)).decode("ascii")
- req = (
- f"GET /ws HTTP/1.1\r\n"
- f"Host: 127.0.0.1:{port}\r\n"
- f"Upgrade: websocket\r\n"
- f"Connection: Upgrade\r\n"
- f"Sec-WebSocket-Key: {key}\r\n"
- f"Sec-WebSocket-Version: 13\r\n\r\n"
- )
- s.sendall(req.encode("ascii"))
- hdr = b""
- while b"\r\n\r\n" not in hdr:
- chunk = s.recv(4096)
- if not chunk:
- raise RuntimeError("WS handshake closed")
- hdr += chunk
- if b"101 " not in hdr.split(b"\r\n", 1)[0]:
- raise RuntimeError(f"WS handshake failed: {hdr[:120]!r}")
- extra = hdr.split(b"\r\n\r\n", 1)[1]
- req_id = f"pxe3b-{int(time.time() * 1000)}"
- payload = json.dumps({"v": 1, "id": req_id, "method": method, "params": params}).encode("utf-8")
- mask_key = os.urandom(4)
- frame = bytearray([0x81])
- if len(payload) < 126:
- frame.append(0x80 | len(payload))
- elif len(payload) < 65536:
- frame.append(0x80 | 126)
- frame += struct.pack("!H", len(payload))
- else:
- frame.append(0x80 | 127)
- frame += struct.pack("!Q", len(payload))
- frame += mask_key
- frame += bytes(b ^ mask_key[i & 3] for i, b in enumerate(payload))
- s.sendall(bytes(frame))
- buf = bytearray(extra)
- def read_exact(n: int) -> bytes:
- while len(buf) < n:
- c = s.recv(4096)
- if not c:
- raise RuntimeError("WS EOF")
- buf.extend(c)
- out = bytes(buf[:n])
- del buf[:n]
- return out
- try:
- while True:
- b0, b1 = read_exact(2)
- op = b0 & 0x0F
- ln = b1 & 0x7F
- if ln == 126:
- ln = struct.unpack("!H", read_exact(2))[0]
- elif ln == 127:
- ln = struct.unpack("!Q", read_exact(8))[0]
- data = read_exact(ln)
- if op == 1:
- msg = json.loads(data.decode("utf-8"))
- if msg.get("id") == req_id:
- if not msg.get("ok"):
- raise RuntimeError(f"RPC {method} error: {msg.get('error')}")
- return msg.get("result") or {}
- finally:
- s.close()
- def main() -> None:
- if len(sys.argv) >= 2 and sys.argv[1] == "--router":
- run_competing_lan_dhcp_router()
- return
- if len(sys.argv) >= 2 and sys.argv[1] == "--office-pc":
- print(json.dumps(run_office_pc_non_pxe_probe()))
- return
- # 1. Build real 3-node Ethernet L2 topology on bridge br0
- sh(
- """
- set -euo pipefail
- ip link set lo up
- ip link add br0 type bridge
- ip link set br0 type bridge stp_state 0
- ip addr add 10.99.77.1/24 dev br0
- ip link set br0 up
- ip route add 255.255.255.255/32 dev br0
- ip netns add lan_rtr
- ip link add veth-rtr type veth peer name veth-rtr-br
- ip link set veth-rtr netns lan_rtr
- ip link set veth-rtr-br master br0 up
- ip netns exec lan_rtr ip link set lo up
- ip netns exec lan_rtr ip addr add 10.99.77.2/24 dev veth-rtr
- ip netns exec lan_rtr ip link set veth-rtr up
- ip netns exec lan_rtr ip route add 255.255.255.255/32 dev veth-rtr
- ip netns add office_pc
- ip link add veth-pc type veth peer name veth-pc-br
- ip link set veth-pc address 02:aa:bb:cc:dd:01
- ip link set veth-pc netns office_pc
- ip link set veth-pc-br master br0 up
- ip netns exec office_pc ip link set lo up
- ip netns exec office_pc ip link set veth-pc up
- ip netns exec office_pc ip route add 255.255.255.255/32 dev veth-pc
- ip tuntap add dev tap0 mode tap
- ip link set tap0 master br0
- ip link set tap0 up
- """
- )
- # 2. Start competing LAN DHCP Router in `lan_rtr` (10.99.77.2, NO PXE options)
- rtr_proc = subprocess.Popen(
- ["ip", "netns", "exec", "lan_rtr", "python3", str(SIM / "in_container_pxe_runner.py"), "--router"],
- stdout=subprocess.DEVNULL,
- stderr=subprocess.PIPE,
- text=True,
- )
- time.sleep(0.4)
- # 3. Prepare data dir with REAL compiled mt86plus.efi as 118.efi
- data_dir = SIM / "data"
- pxe_dir = data_dir / "pxe_tftp"
- pxe_dir.mkdir(parents=True, exist_ok=True)
- efi_bytes = (SIM / "mt86plus.efi").read_bytes()
- (pxe_dir / "118.efi").write_bytes(efi_bytes)
- efi_sha256 = hashlib.sha256(efi_bytes).hexdigest()
- cfg_path = SIM / "station.json"
- cfg_path.write_text(
- json.dumps(
- {
- "mode": "hardware",
- "data_dir": str(data_dir),
- "stations": [
- {
- "station_id": "S1",
- "name": "Diskless-PXE-KVM",
- "cpu_count": 1,
- "os_mac": "52:54:00:aa:bb:cc",
- "bmc": {"enabled": False, "host": ""},
- "console": {"enabled": False, "transport": "local_serial", "host": ""},
- }
- ],
- }
- ),
- encoding="utf-8",
- )
- srv_env = dict(os.environ)
- srv_env["LD_LIBRARY_PATH"] = str(SIM / "libs")
- srv_log = open(SIM / "stl_server.log", "w", encoding="utf-8")
- srv_proc = subprocess.Popen(
- [
- str(SIM / "stl_native_server"),
- "--config", str(cfg_path),
- "--data-dir", str(data_dir),
- "--web-listen", "0.0.0.0:18099",
- "--tftp-listen", "0.0.0.0:69",
- "--pxe-mode", "proxy",
- "--pxe-iface", "br0",
- "--web-dir", str(SIM / "web"),
- "--contracts", str(SIM / "contracts" / "firmware-vd012.json"),
- "--web-password", "disabled",
- "--detail-log", "on",
- ],
- env=srv_env,
- stdout=srv_log,
- stderr=subprocess.STDOUT,
- text=True,
- )
- qemu_proc = None
- try:
- # Wait until stl_native_server binds UDP 67, 4011, 69 & HTTP 18099
- st_pxe = None
- for _ in range(40):
- try:
- st_pxe = ws_rpc_call(18099, "GetPxeStatus", {})
- if st_pxe.get("dhcp67_bound") and st_pxe.get("proxy4011_bound") and st_pxe.get("tftp69_bound"):
- break
- except Exception:
- pass
- time.sleep(0.25)
- assert st_pxe and st_pxe.get("dhcp67_bound") and st_pxe.get("proxy4011_bound") and st_pxe.get("tftp69_bound"), (
- f"stl_native_server failed to bind PXE/TFTP ports: {st_pxe}\nLOG={Path(SIM / 'stl_server.log').read_text()}"
- )
- assert st_pxe.get("efi_present") is True and int(st_pxe.get("efi_bytes", 0)) == len(efi_bytes)
- # Verify HTTP Boot endpoint serves byte-identical 118.efi
- with urllib.request.urlopen("http://10.99.77.1:18099/pxe/118.efi", timeout=5) as r:
- dl_efi = r.read()
- assert hashlib.sha256(dl_efi).hexdigest() == efi_sha256, "HTTP Boot /pxe/118.efi SHA mismatch"
- # 4. Verify non-PXE office PC ONLY gets reply from competing router 10.99.77.2 (0 from stl_native_server)
- pc_out = subprocess.run(
- ["ip", "netns", "exec", "office_pc", "python3", str(SIM / "in_container_pxe_runner.py"), "--office-pc"],
- capture_output=True,
- text=True,
- timeout=10,
- )
- assert pc_out.returncode == 0, f"office_pc probe failed rc={pc_out.returncode}: stdout={pc_out.stdout} stderr={pc_out.stderr}"
- pc_res = json.loads(pc_out.stdout.strip())
- offers = pc_res.get("offers") or []
- assert len(offers) == 1, f"Office PC must get EXACTLY 1 offer (from competing router only!), got {offers}"
- assert offers[0]["from"] == "10.99.77.2" and offers[0]["yiaddr"].startswith("10.99.77.5"), f"Bad office PC offer: {offers}"
- assert offers[0]["file"] == ""
- st_after_pc = ws_rpc_call(18099, "GetPxeStatus", {})
- assert int(st_after_pc.get("packets_ignored_non_pxe", 0)) >= 1, f"ProxyDHCP must count ignored non-PXE packet: {st_after_pc}"
- # 5. Verify 1-click LAN DHCP/PXE self-check (`ProbePxeNetwork`) detects external router 10.99.77.2
- probe_res = ws_rpc_call(18099, "ProbePxeNetwork", {"iface": "br0", "timeout_ms": 1000})
- ext_srvs = probe_res.get("external_dhcp_servers") or []
- assert any(s.get("server_ip") == "10.99.77.2" and s.get("has_pxe_conflict") is False for s in ext_srvs), (
- f"ProbePxeNetwork must detect competing LAN DHCP router 10.99.77.2: {probe_res}"
- )
- assert probe_res.get("recommended_mode") == "proxy", f"Expected recommended_mode=proxy: {probe_res}"
- # 6. Boot 100% DISKLESS (`-drive` NONE — ZERO disks!) real KVM + EDK2 OVMF UEFI VM over PXE!
- serial_log_path = SIM / "vm_serial.log"
- serial_log_path.write_bytes(b"")
- qemu_cmd = [
- "qemu-system-x86_64",
- "-machine", "q35,accel=kvm",
- "-cpu", "host",
- "-smp", "2",
- "-m", "512M",
- "-display", "none",
- "-drive", f"if=pflash,format=raw,readonly=on,file={SIM / 'code.fd'}",
- "-drive", f"if=pflash,format=raw,file={SIM / 'vars.fd'}",
- "-netdev", "tap,id=net0,ifname=tap0,script=no,downscript=no",
- "-device", "e1000,netdev=net0,mac=52:54:00:aa:bb:cc,bootindex=1",
- "-serial", f"file:{serial_log_path}",
- ]
- qemu_proc = subprocess.Popen(qemu_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True)
- # 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!
- vm_serial = ""
- pxe_client_ack = None
- deadline = time.monotonic() + 45.0
- while time.monotonic() < deadline:
- if serial_log_path.is_file():
- vm_serial = serial_log_path.read_text(encoding="utf-8", errors="replace")
- st_now = ws_rpc_call(18099, "GetPxeStatus", {})
- clients = st_now.get("discovered_clients") or []
- for c in clients:
- if (
- c.get("mac") == "52:54:00:aa:bb:cc"
- and c.get("boot_target") == "118.efi"
- and int(c.get("reply_count", 0)) >= 1
- ):
- pxe_client_ack = c
- if (
- "Station IP address is 10.99.77." in vm_serial
- and "Server IP address is 10.99.77.1" in vm_serial
- and "NBP filename is 118.efi" in vm_serial
- and "NBP file downloaded successfully" in vm_serial
- and "BdsDxe: starting" in vm_serial
- and pxe_client_ack is not None
- ):
- # Give real mt86plus.efi 2.5s to run in KVM RAM after NBP handoff
- time.sleep(2.5)
- vm_serial = serial_log_path.read_text(encoding="utf-8", errors="replace")
- break
- time.sleep(0.5)
- st_final = ws_rpc_call(18099, "GetPxeStatus", {})
- router_log = (SIM / "router_dhcp.log").read_text(encoding="utf-8", errors="replace") if (SIM / "router_dhcp.log").is_file() else ""
- srv_log.flush()
- srv_txt = (SIM / "stl_server.log").read_text(encoding="utf-8", errors="replace")
- assert pxe_client_ack is not None, (
- f"Diskless KVM VM did not receive ProxyDHCP reply for 118.efi!\n"
- f"PXE_STATUS={json.dumps(st_final, ensure_ascii=False)}\nROUTER_LOG={router_log}\n"
- f"VM_SERIAL={vm_serial[-2000:]}\nSRV_LOG={srv_txt[-1500:]}"
- )
- assert "Station IP address is 10.99.77." in vm_serial, f"Missing competing router IP in OVMF output:\n{vm_serial[-2000:]}"
- 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:]}"
- assert "NBP filename is 118.efi" in vm_serial, f"Missing NBP 118.efi:\n{vm_serial[-2000:]}"
- assert "NBP file downloaded successfully" in vm_serial, f"TFTP download of 118.efi failed:\n{vm_serial[-2000:]}"
- assert "BdsDxe: starting" in vm_serial, f"OVMF did not start downloaded 118.efi:\n{vm_serial[-2000:]}"
- 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}"
- assert qemu_proc.poll() is None, "Diskless KVM VM crashed immediately after NBP execution"
- result = {
- "ok": True,
- "office_pc_offer": offers[0],
- "packets_ignored_non_pxe": st_final.get("packets_ignored_non_pxe"),
- "probe_detected_router": ext_srvs,
- "probe_recommended_mode": probe_res.get("recommended_mode"),
- "diskless_pxe_client": pxe_client_ack,
- "http_boot_efi_sha256": efi_sha256,
- "efi_bytes": len(efi_bytes),
- "vm_serial_excerpt": vm_serial[-1200:],
- "router_log": router_log.strip(),
- }
- (SIM / "tier3b_result.json").write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
- print("TIER3B_SUCCESS")
- finally:
- (SIM / "stop_router").write_text("1", encoding="utf-8")
- for p in (qemu_proc, srv_proc, rtr_proc):
- if p is not None and p.poll() is None:
- p.terminate()
- try:
- p.wait(timeout=3)
- except Exception:
- p.kill()
- srv_log.close()
- if __name__ == "__main__":
- main()
- '''
- def collect_non_glibc_libs(binary: Path) -> List[Path]:
- env = dict(os.environ)
- env.pop("LD_LIBRARY_PATH", None)
- out = subprocess.run(["ldd", str(binary)], check=True, capture_output=True, text=True, env=env).stdout
- libs: List[Path] = []
- seen = set()
- for line in out.splitlines():
- m = re.search(r"=>\s+(/\S+)\s+\(", line)
- if not m:
- continue
- p = Path(m.group(1))
- if any(p.name.startswith(pref) for pref in SKIP_SO_PREFIXES):
- continue
- real = p.resolve()
- if real.is_file() and p.name not in seen:
- seen.add(p.name)
- libs.append((p.name, real)) # type: ignore[arg-type]
- return libs # type: ignore[return-value]
- def run_tier3b_diskless_pxe() -> Dict[str, Any]:
- t0 = time.monotonic()
- run_tag = f"xjkj-stl-pxe3b-{os.getpid()}-{int(time.time())}"
- remote_dir = f"/tmp/{run_tag}"
- print(f"[Tier3B] Bundling stl_native_server + runtime libs for 100% diskless KVM+OVMF ProxyDHCP test on {REMOTE_HOST}...", flush=True)
- with tempfile.TemporaryDirectory(prefix="xjkj_tier3b_") as ltmp:
- tar_path = Path(ltmp) / "bundle.tar"
- runner_path = Path(ltmp) / "in_container_pxe_runner.py"
- runner_path.write_text(IN_CONTAINER_RUNNER, encoding="utf-8")
- libs = collect_non_glibc_libs(STL_SERVER_BIN)
- with tarfile.open(tar_path, "w") as tf:
- tf.add(STL_SERVER_BIN, arcname="stl_native_server")
- tf.add(runner_path, arcname="in_container_pxe_runner.py")
- tf.add(CONTRACTS_PATH, arcname="contracts/firmware-vd012.json")
- tf.add(WEB_DIR / "index.html", arcname="web/index.html")
- for soname, real_path in libs: # type: ignore[misc]
- tf.add(real_path, arcname=f"libs/{soname}")
- try:
- # Upload tarball to remote tmp dir
- with open(tar_path, "rb") as fp:
- subprocess.run(
- [
- "ssh", "-o", "BatchMode=yes", f"{REMOTE_USER}@{REMOTE_HOST}",
- f"mkdir -p {remote_dir} && tar -xf - -C {remote_dir} && "
- f"cp /opt/edk2-uefi-lab/work/qemu/memtest86plus/code.fd {remote_dir}/code.fd && "
- f"cp /opt/edk2-uefi-lab/work/qemu/memtest86plus/vars.fd {remote_dir}/vars.fd && "
- f"cp /opt/edk2-uefi-lab/work/qemu/memtest86plus/mt86plus.efi {remote_dir}/mt86plus.efi",
- ],
- stdin=fp,
- check=True,
- timeout=60,
- )
- print("[Tier3B] Executing isolated L2 LAN (Competing Router + ProxyDHCP + Office PC + 100% Diskless KVM OVMF)...", flush=True)
- run_cmd = (
- f"podman run --rm --name {run_tag} "
- f"--privileged --network=none "
- f"--device /dev/kvm --device /dev/net/tun "
- f"-v {remote_dir}:/sim:rw "
- f"{PODMAN_IMAGE} "
- f"python3 /sim/in_container_pxe_runner.py"
- )
- proc = subprocess.run(
- ["ssh", "-o", "BatchMode=yes", f"{REMOTE_USER}@{REMOTE_HOST}", run_cmd],
- capture_output=True,
- text=True,
- timeout=120,
- )
- if proc.returncode != 0 or "TIER3B_SUCCESS" not in proc.stdout:
- raise RuntimeError(
- f"Tier3B Diskless KVM PXE failed (rc={proc.returncode}):\nSTDOUT:\n{proc.stdout}\nSTDERR:\n{proc.stderr}"
- )
- res_raw = subprocess.run(
- ["ssh", "-o", "BatchMode=yes", f"{REMOTE_USER}@{REMOTE_HOST}", f"cat {remote_dir}/tier3b_result.json"],
- check=True,
- capture_output=True,
- text=True,
- timeout=15,
- ).stdout
- inner = json.loads(res_raw)
- finally:
- subprocess.run(
- [
- "ssh", "-o", "BatchMode=yes", f"{REMOTE_USER}@{REMOTE_HOST}",
- f"podman rm -f {run_tag} >/dev/null 2>&1 || true; rm -rf {remote_dir}",
- ],
- timeout=15,
- capture_output=True,
- )
- elapsed_s = round(time.monotonic() - t0, 2)
- summary = {
- "tier": "Tier3B_Diskless_KVM_OVMF_ProxyDHCP_CompetingRouter_E2E",
- "ok": True,
- "elapsed_s": elapsed_s,
- **inner,
- }
- print(
- f"[Tier3B] 100% DISKLESS KVM+OVMF PXE UNDER COMPETING LAN DHCP ROUTER PASSED in {elapsed_s}s!\n"
- f" OfficePC -> {inner['office_pc_offer']['from']} ({inner['office_pc_offer']['yiaddr']}), "
- f"ignored_non_pxe={inner['packets_ignored_non_pxe']}\n"
- f" Diskless VM -> Router IP + ProxyDHCP 10.99.77.1 -> TFTP 118.efi ({inner['efi_bytes']}B) downloaded & booted!",
- flush=True,
- )
- return summary
- if __name__ == "__main__":
- res = run_tier3b_diskless_pxe()
- out_file = ROOT_DIR / "build" / "sim" / "tier3b_diskless_pxe_report.json"
- out_file.parent.mkdir(parents=True, exist_ok=True)
- out_file.write_text(json.dumps(res, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|