cluster_harness.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. #!/usr/bin/env python3
  2. """
  3. cluster_harness.py — Full-Stack HIL Simulation Stack Manager (Tiers 2 & 4)
  4. Launches and orchestrates:
  5. 1. `build/sim/bmc_ssh_hil_sim` (C RMCP+ UDP :623 + SSHv2 TCP :2200 for S1..S4)
  6. 2. `sim/hil_cluster/dut_and_hood_sim.py` (4x Dual-Socket GNR DUTs + 4x `/dev/pts/*` 6400 Hoods)
  7. 3. `build/native/stl_native_server` (Unmodified production Rust+C+Zig+ASM+re2c server)
  8. 4. Async WebSocket RPC client for authenticated Web `/ws`
  9. """
  10. import asyncio
  11. import base64
  12. import contextlib
  13. import json
  14. import os
  15. from pathlib import Path
  16. import shutil
  17. import subprocess
  18. import tempfile
  19. import time
  20. from typing import Any, Dict, List, Optional
  21. import uuid
  22. import aiohttp
  23. ROOT_DIR = Path(__file__).resolve().parents[2]
  24. BMC_SIM_BIN = ROOT_DIR / "build" / "sim" / "bmc_ssh_hil_sim"
  25. DUT_HOOD_SCRIPT = ROOT_DIR / "sim" / "hil_cluster" / "dut_and_hood_sim.py"
  26. STL_SERVER_BIN = ROOT_DIR / "build" / "native" / "stl_native_server"
  27. CONTRACTS_PATH = ROOT_DIR / "contracts" / "firmware-vd012.json"
  28. WEB_DIR = ROOT_DIR / "web"
  29. DEFAULT_STATION_IPS = ["127.0.2.166", "127.0.2.165", "127.0.2.167", "127.0.2.168"]
  30. class WsRpcClient:
  31. """Async RFC 6455 JSON-RPC v1 client supporting push event capture (`state`, `task_complete`, `bios_uart`)."""
  32. def __init__(self, session: aiohttp.ClientSession, url: str, headers: Optional[Dict[str, str]] = None):
  33. self.session = session
  34. self.url = url
  35. self.headers = headers or {}
  36. self.ws: Optional[aiohttp.ClientWebSocketResponse] = None
  37. self.reader_task: Optional[asyncio.Task] = None
  38. self.pending: Dict[str, asyncio.Future] = {}
  39. self.seq = 0
  40. self.latest_state: Optional[Dict[str, Any]] = None
  41. self.task_completes: List[Dict[str, Any]] = []
  42. self.state_events: List[Dict[str, Any]] = []
  43. async def connect(self) -> None:
  44. self.ws = await self.session.ws_connect(self.url, heartbeat=20, headers=self.headers)
  45. self.reader_task = asyncio.create_task(self._read_loop())
  46. async def close(self) -> None:
  47. if self.ws is not None:
  48. with contextlib.suppress(Exception):
  49. await self.ws.close()
  50. if self.reader_task is not None:
  51. self.reader_task.cancel()
  52. with contextlib.suppress(asyncio.CancelledError, Exception):
  53. await self.reader_task
  54. async def _read_loop(self) -> None:
  55. assert self.ws is not None
  56. try:
  57. async for msg in self.ws:
  58. if msg.type != aiohttp.WSMsgType.TEXT:
  59. continue
  60. data = json.loads(msg.data)
  61. if not isinstance(data, dict):
  62. continue
  63. req_id = data.get("id")
  64. if req_id and req_id in self.pending:
  65. fut = self.pending.pop(req_id)
  66. if not fut.done():
  67. fut.set_result(data)
  68. continue
  69. ev = data.get("event")
  70. res = data.get("result")
  71. if ev == "state" and isinstance(res, dict):
  72. self.latest_state = res
  73. self.state_events.append(res)
  74. if len(self.state_events) > 300:
  75. self.state_events = self.state_events[-300:]
  76. elif ev == "task_complete" and isinstance(res, dict):
  77. self.task_completes.append(res)
  78. except Exception as exc:
  79. for fut in self.pending.values():
  80. if not fut.done():
  81. fut.set_exception(exc)
  82. async def call(self, method: str, params: Optional[Dict[str, Any]] = None, timeout: float = 20.0) -> Any:
  83. assert self.ws is not None
  84. self.seq += 1
  85. req_id = f"hil-{self.seq}-{uuid.uuid4().hex[:6]}"
  86. fut = asyncio.get_running_loop().create_future()
  87. self.pending[req_id] = fut
  88. await self.ws.send_json({"v": 1, "id": req_id, "method": method, "params": params or {}})
  89. try:
  90. resp = await asyncio.wait_for(fut, timeout=timeout)
  91. finally:
  92. self.pending.pop(req_id, None)
  93. if not resp.get("ok"):
  94. err = resp.get("error") or {}
  95. raise RuntimeError(f"RPC {method} failed: {err}")
  96. return resp.get("result")
  97. class HilClusterStack:
  98. def __init__(
  99. self,
  100. *,
  101. web_port: int = 18980,
  102. tftp_port: int = 19069,
  103. bmc_ctrl_port: int = 19199,
  104. hil_http_port: int = 19198,
  105. uart_base: int = 19200,
  106. web_password: str = "disabled",
  107. speed_scale: float = 0.25,
  108. station_ips: Optional[List[str]] = None,
  109. ):
  110. self.web_port = web_port
  111. self.tftp_port = tftp_port
  112. self.bmc_ctrl_port = bmc_ctrl_port
  113. self.hil_http_port = hil_http_port
  114. self.uart_base = uart_base
  115. self.web_password = web_password
  116. self.speed_scale = speed_scale
  117. self.station_ips = station_ips or list(DEFAULT_STATION_IPS)
  118. self.tmp_dir = Path(tempfile.mkdtemp(prefix="xjkj_stl_hil_"))
  119. self.data_dir = self.tmp_dir / "data"
  120. self.config_path = self.tmp_dir / "station-hil.json"
  121. self.manifest_path = self.tmp_dir / "hil_manifest.json"
  122. self.bmc_proc: Optional[subprocess.Popen] = None
  123. self.dut_proc: Optional[subprocess.Popen] = None
  124. self.server_proc: Optional[subprocess.Popen] = None
  125. self.backend_hood_pts: List[str] = []
  126. self.http_session: Optional[aiohttp.ClientSession] = None
  127. self.admin_ws: Optional[WsRpcClient] = None
  128. def _clean_env(self) -> Dict[str, str]:
  129. env = dict(os.environ)
  130. for k in (
  131. "LD_LIBRARY_PATH",
  132. "QT_PLUGIN_PATH",
  133. "QT_QPA_PLATFORM_PLUGIN_PATH",
  134. "QT_QPA_PLATFORM",
  135. "http_proxy",
  136. "https_proxy",
  137. "HTTP_PROXY",
  138. "HTTPS_PROXY",
  139. "all_proxy",
  140. "ALL_PROXY",
  141. ):
  142. env.pop(k, None)
  143. return env
  144. def _write_config(self) -> None:
  145. self.data_dir.mkdir(parents=True, exist_ok=True)
  146. pxe_dir = self.data_dir / "pxe_tftp"
  147. pxe_dir.mkdir(parents=True, exist_ok=True)
  148. (pxe_dir / "118.efi").write_bytes(b"MZ\x90\x00STL_118_EFI_SIM_STUB")
  149. stations = []
  150. for i, ip in enumerate(self.station_ips):
  151. sid = f"S{i + 1}"
  152. stations.append({
  153. "station_id": sid,
  154. "frontend_index": i,
  155. "name": f"仿真工位 00{i + 1} ({ip})",
  156. "mode": "hardware",
  157. "cpu_count": 2,
  158. "channels_per_cpu": 12,
  159. "target_min_c": 0.0,
  160. "target_max_c": 100.0,
  161. "supply_mode": "manual",
  162. "bmc": {
  163. "enabled": True,
  164. "host": ip,
  165. "user": "ADMIN",
  166. "username": "ADMIN",
  167. "password": "Admin123@pl",
  168. "cipher_suite": 17,
  169. "timeout_s": 5,
  170. "console_transport": "ssh_console",
  171. "ssh_console_port": 2200,
  172. },
  173. "console": {
  174. "enabled": True,
  175. "transport": "ssh_console",
  176. "host": ip,
  177. "port": 2200,
  178. "user": "ADMIN",
  179. "write_chunk_bytes": 64,
  180. "write_gap_ms": 2.0,
  181. },
  182. })
  183. cfg = {
  184. "mode": "hardware",
  185. "data_dir": str(self.data_dir),
  186. "telemetry_interval_s": 1.0,
  187. "idle_poll_interval_s": 1,
  188. "stations": stations,
  189. }
  190. self.config_path.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8")
  191. async def __aenter__(self) -> "HilClusterStack":
  192. await self.start()
  193. return self
  194. async def __aexit__(self, *exc: Any) -> None:
  195. await self.stop()
  196. async def start(self) -> None:
  197. self._write_config()
  198. env = self._clean_env()
  199. # 1. Start C BMC RMCP+ & SSHv2 :2200 Simulator
  200. self.bmc_proc = subprocess.Popen(
  201. [
  202. str(BMC_SIM_BIN),
  203. "--ctrl-port", str(self.bmc_ctrl_port),
  204. "--uart-base", str(self.uart_base),
  205. "--ipmi-port", "623",
  206. "--ssh-port", "2200",
  207. "--probe22-port", "0",
  208. *self.station_ips,
  209. ],
  210. stdout=subprocess.PIPE,
  211. stderr=subprocess.PIPE,
  212. text=True,
  213. env=env,
  214. )
  215. await self._wait_proc_ready_line(self.bmc_proc, "READY", timeout_s=8.0)
  216. # 2. Start Python DUT State Machine + 8x `/dev/pts/*` 6400 Hood Simulator
  217. py_bin = "/opt/prod2u/venv/bin/python3" if os.path.exists("/opt/prod2u/venv/bin/python3") else "python3"
  218. self.dut_proc = subprocess.Popen(
  219. [
  220. py_bin,
  221. str(DUT_HOOD_SCRIPT),
  222. "--http-port", str(self.hil_http_port),
  223. "--bmc-ctrl-port", str(self.bmc_ctrl_port),
  224. "--uart-base", str(self.uart_base),
  225. "--num-stations", str(len(self.station_ips)),
  226. "--tftp-host", "127.0.0.1",
  227. "--tftp-port", str(self.tftp_port),
  228. "--speed-scale", str(self.speed_scale),
  229. "--manifest-out", str(self.manifest_path),
  230. ],
  231. stdout=subprocess.PIPE,
  232. stderr=subprocess.PIPE,
  233. text=True,
  234. env=env,
  235. )
  236. await self._wait_proc_ready_line(self.dut_proc, "READY", timeout_s=8.0)
  237. manifest = json.loads(self.manifest_path.read_text(encoding="utf-8"))
  238. self.backend_hood_pts = manifest["backend_hood_pts"]
  239. # 3. Start Production `stl_native_server`
  240. self.server_proc = subprocess.Popen(
  241. [
  242. str(STL_SERVER_BIN),
  243. "--config", str(self.config_path),
  244. "--data-dir", str(self.data_dir),
  245. "--web-listen", f"127.0.0.1:{self.web_port}",
  246. "--tftp-listen", f"127.0.0.1:{self.tftp_port}",
  247. "--pxe-mode", "disabled",
  248. "--web-dir", str(WEB_DIR),
  249. "--contracts", str(CONTRACTS_PATH),
  250. "--web-password", self.web_password,
  251. ],
  252. cwd=str(ROOT_DIR),
  253. stdout=subprocess.DEVNULL,
  254. stderr=subprocess.PIPE,
  255. text=True,
  256. env=env,
  257. )
  258. self.http_session = aiohttp.ClientSession(cookie_jar=aiohttp.CookieJar(unsafe=True))
  259. try:
  260. await self._wait_http_up(f"http://127.0.0.1:{self.web_port}/", timeout_s=10.0)
  261. headers: Dict[str, str] = {}
  262. if self.web_password and self.web_password.lower() not in ("disabled", "none", "off"):
  263. b64 = base64.b64encode(f"admin:{self.web_password}".encode("utf-8")).decode("ascii")
  264. headers["Authorization"] = f"Basic {b64}"
  265. async with self.http_session.post(
  266. f"http://127.0.0.1:{self.web_port}/api/auth/login",
  267. json={"password": self.web_password},
  268. ) as resp:
  269. assert resp.status == 200, f"Login failed: {resp.status}"
  270. self.admin_ws = WsRpcClient(self.http_session, f"ws://127.0.0.1:{self.web_port}/ws", headers=headers)
  271. await self.admin_ws.connect()
  272. except Exception:
  273. await self.stop()
  274. raise
  275. async def _wait_proc_ready_line(self, proc: subprocess.Popen, prefix: str, timeout_s: float) -> str:
  276. deadline = time.monotonic() + timeout_s
  277. assert proc.stdout is not None
  278. while time.monotonic() < deadline:
  279. if proc.poll() is not None:
  280. err = proc.stderr.read() if proc.stderr else ""
  281. raise RuntimeError(f"Process exited early ({proc.returncode}): {err}")
  282. line = await asyncio.to_thread(proc.stdout.readline)
  283. if line and prefix in line:
  284. return line.strip()
  285. await asyncio.sleep(0.05)
  286. raise TimeoutError(f"Timed out waiting for {prefix}")
  287. async def _wait_http_up(self, url: str, timeout_s: float) -> None:
  288. assert self.http_session is not None
  289. deadline = time.monotonic() + timeout_s
  290. while time.monotonic() < deadline:
  291. try:
  292. async with self.http_session.get(url, timeout=aiohttp.ClientTimeout(total=1.0)) as r:
  293. if r.status in (200, 401):
  294. return
  295. except Exception:
  296. pass
  297. await asyncio.sleep(0.1)
  298. raise TimeoutError(f"Server did not listen at {url}")
  299. async def stop(self) -> None:
  300. if self.admin_ws is not None:
  301. await self.admin_ws.close()
  302. if self.http_session is not None:
  303. await self.http_session.close()
  304. for proc in (self.server_proc, self.dut_proc, self.bmc_proc):
  305. if proc is not None and proc.poll() is None:
  306. with contextlib.suppress(Exception):
  307. proc.terminate()
  308. proc.wait(timeout=3.0)
  309. if proc.poll() is None:
  310. with contextlib.suppress(Exception):
  311. proc.kill()
  312. with contextlib.suppress(Exception):
  313. shutil.rmtree(self.tmp_dir, ignore_errors=True)
  314. # ---- HIL Fault-Injection & Inspection Helpers ----
  315. async def hil_status(self) -> Dict[str, Any]:
  316. assert self.http_session is not None
  317. async with self.http_session.get(f"http://127.0.0.1:{self.hil_http_port}/api/status") as r:
  318. return await r.json()
  319. async def set_link(self, idx: int, *, bmc_up: bool, serial_up: bool) -> Dict[str, Any]:
  320. assert self.http_session is not None
  321. async with self.http_session.post(
  322. f"http://127.0.0.1:{self.hil_http_port}/api/bmc/set_link",
  323. json={"idx": idx, "bmc_up": bmc_up, "serial_up": serial_up},
  324. ) as r:
  325. return await r.json()
  326. async def set_power(self, idx: int, *, power_on: bool) -> Dict[str, Any]:
  327. assert self.http_session is not None
  328. async with self.http_session.post(
  329. f"http://127.0.0.1:{self.hil_http_port}/api/bmc/set_power",
  330. json={"idx": idx, "power_on": power_on},
  331. ) as r:
  332. return await r.json()
  333. async def configure_dut(self, idx: int, **kwargs: Any) -> Dict[str, Any]:
  334. assert self.http_session is not None
  335. payload = {"idx": idx, **kwargs}
  336. async with self.http_session.post(
  337. f"http://127.0.0.1:{self.hil_http_port}/api/dut/configure",
  338. json=payload,
  339. ) as r:
  340. return await r.json()
  341. async def trigger_dut_boot(self, idx: int, reason: str = "test_boot") -> Dict[str, Any]:
  342. assert self.http_session is not None
  343. async with self.http_session.post(
  344. f"http://127.0.0.1:{self.hil_http_port}/api/dut/trigger_boot",
  345. json={"idx": idx, "reason": reason},
  346. ) as r:
  347. return await r.json()
  348. async def clear_hood_history(self, idx: Optional[int] = None) -> None:
  349. assert self.http_session is not None
  350. async with self.http_session.post(
  351. f"http://127.0.0.1:{self.hil_http_port}/api/hood/clear_history",
  352. json={"idx": idx},
  353. ) as r:
  354. await r.json()
  355. async def connect_and_heat_backend_hood(self, station_id: str, idx: int, target_c: int = 70) -> None:
  356. """Bind `stl_native_server` ThermalMcuHub for `station_id` to `/dev/pts/*` hood & start heating."""
  357. assert self.admin_ws is not None
  358. pts = self.backend_hood_pts[idx]
  359. await self.admin_ws.call(
  360. "ThermalAction",
  361. {
  362. "station_id": station_id,
  363. "action": "connect",
  364. "mode": "serial",
  365. "serial_path": pts,
  366. "serial_baud": 115200,
  367. },
  368. )
  369. # Wait up to 3s for 0xF0 heartbeat so ThermalMcuHub marks MCU online
  370. deadline = time.monotonic() + 3.5
  371. while time.monotonic() < deadline:
  372. snap = await self.admin_ws.call("GetThermalConsole", {"station_id": station_id})
  373. if (snap.get("mcu") or {}).get("online"):
  374. break
  375. await asyncio.sleep(0.2)
  376. await self.admin_ws.call(
  377. "ThermalAction",
  378. {"station_id": station_id, "action": "set_temp", "target_c": target_c},
  379. )
  380. async def enqueue_cmd(self, station_id: str, method: str, arguments: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
  381. assert self.admin_ws is not None
  382. item = await self.admin_ws.call(
  383. "EnqueueCommand",
  384. {
  385. "command_id": f"hil-cmd-{uuid.uuid4().hex[:10]}",
  386. "station_id": station_id,
  387. "method": method,
  388. "arguments": arguments or {},
  389. },
  390. )
  391. if item.get("state") == "failed":
  392. raise RuntimeError(f"EnqueueCommand {method} on {station_id} failed: {item}")
  393. return item
  394. async def wait_station_online(self, station_id: str, timeout_s: float = 12.0) -> Dict[str, Any]:
  395. assert self.admin_ws is not None
  396. deadline = time.monotonic() + timeout_s
  397. while time.monotonic() < deadline:
  398. st = await self.admin_ws.call("GetStation", {"station_id": station_id})
  399. if st.get("bmc_state") == "online" and st.get("console_online") is True:
  400. return st
  401. await asyncio.sleep(0.25)
  402. raise TimeoutError(f"Station {station_id} did not bring BMC + :2200 online within {timeout_s}s")