| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446 |
- #!/usr/bin/env python3
- """
- cluster_harness.py — Full-Stack HIL Simulation Stack Manager (Tiers 2 & 4)
- Launches and orchestrates:
- 1. `build/sim/bmc_ssh_hil_sim` (C RMCP+ UDP :623 + SSHv2 TCP :2200 for S1..S4)
- 2. `sim/hil_cluster/dut_and_hood_sim.py` (4x Dual-Socket GNR DUTs + 4x `/dev/pts/*` 6400 Hoods)
- 3. `build/native/stl_native_server` (Unmodified production Rust+C+Zig+ASM+re2c server)
- 4. Async WebSocket RPC client for authenticated Web `/ws`
- """
- import asyncio
- import base64
- import contextlib
- import json
- import os
- from pathlib import Path
- import shutil
- import subprocess
- import tempfile
- import time
- from typing import Any, Dict, List, Optional
- import uuid
- import aiohttp
- ROOT_DIR = Path(__file__).resolve().parents[2]
- BMC_SIM_BIN = ROOT_DIR / "build" / "sim" / "bmc_ssh_hil_sim"
- DUT_HOOD_SCRIPT = ROOT_DIR / "sim" / "hil_cluster" / "dut_and_hood_sim.py"
- STL_SERVER_BIN = ROOT_DIR / "build" / "native" / "stl_native_server"
- CONTRACTS_PATH = ROOT_DIR / "contracts" / "firmware-vd012.json"
- WEB_DIR = ROOT_DIR / "web"
- DEFAULT_STATION_IPS = ["127.0.2.166", "127.0.2.165", "127.0.2.167", "127.0.2.168"]
- class WsRpcClient:
- """Async RFC 6455 JSON-RPC v1 client supporting push event capture (`state`, `task_complete`, `bios_uart`)."""
- def __init__(self, session: aiohttp.ClientSession, url: str, headers: Optional[Dict[str, str]] = None):
- self.session = session
- self.url = url
- self.headers = headers or {}
- self.ws: Optional[aiohttp.ClientWebSocketResponse] = None
- self.reader_task: Optional[asyncio.Task] = None
- self.pending: Dict[str, asyncio.Future] = {}
- self.seq = 0
- self.latest_state: Optional[Dict[str, Any]] = None
- self.task_completes: List[Dict[str, Any]] = []
- self.state_events: List[Dict[str, Any]] = []
- async def connect(self) -> None:
- self.ws = await self.session.ws_connect(self.url, heartbeat=20, headers=self.headers)
- self.reader_task = asyncio.create_task(self._read_loop())
- async def close(self) -> None:
- if self.ws is not None:
- with contextlib.suppress(Exception):
- await self.ws.close()
- if self.reader_task is not None:
- self.reader_task.cancel()
- with contextlib.suppress(asyncio.CancelledError, Exception):
- await self.reader_task
- async def _read_loop(self) -> None:
- assert self.ws is not None
- try:
- async for msg in self.ws:
- if msg.type != aiohttp.WSMsgType.TEXT:
- continue
- data = json.loads(msg.data)
- if not isinstance(data, dict):
- continue
- req_id = data.get("id")
- if req_id and req_id in self.pending:
- fut = self.pending.pop(req_id)
- if not fut.done():
- fut.set_result(data)
- continue
- ev = data.get("event")
- res = data.get("result")
- if ev == "state" and isinstance(res, dict):
- self.latest_state = res
- self.state_events.append(res)
- if len(self.state_events) > 300:
- self.state_events = self.state_events[-300:]
- elif ev == "task_complete" and isinstance(res, dict):
- self.task_completes.append(res)
- except Exception as exc:
- for fut in self.pending.values():
- if not fut.done():
- fut.set_exception(exc)
- async def call(self, method: str, params: Optional[Dict[str, Any]] = None, timeout: float = 20.0) -> Any:
- assert self.ws is not None
- self.seq += 1
- req_id = f"hil-{self.seq}-{uuid.uuid4().hex[:6]}"
- fut = asyncio.get_running_loop().create_future()
- self.pending[req_id] = fut
- await self.ws.send_json({"v": 1, "id": req_id, "method": method, "params": params or {}})
- try:
- resp = await asyncio.wait_for(fut, timeout=timeout)
- finally:
- self.pending.pop(req_id, None)
- if not resp.get("ok"):
- err = resp.get("error") or {}
- raise RuntimeError(f"RPC {method} failed: {err}")
- return resp.get("result")
- class HilClusterStack:
- def __init__(
- self,
- *,
- web_port: int = 18980,
- tftp_port: int = 19069,
- bmc_ctrl_port: int = 19199,
- hil_http_port: int = 19198,
- uart_base: int = 19200,
- web_password: str = "disabled",
- speed_scale: float = 0.25,
- station_ips: Optional[List[str]] = None,
- ):
- self.web_port = web_port
- self.tftp_port = tftp_port
- self.bmc_ctrl_port = bmc_ctrl_port
- self.hil_http_port = hil_http_port
- self.uart_base = uart_base
- self.web_password = web_password
- self.speed_scale = speed_scale
- self.station_ips = station_ips or list(DEFAULT_STATION_IPS)
- self.tmp_dir = Path(tempfile.mkdtemp(prefix="xjkj_stl_hil_"))
- self.data_dir = self.tmp_dir / "data"
- self.config_path = self.tmp_dir / "station-hil.json"
- self.manifest_path = self.tmp_dir / "hil_manifest.json"
- self.bmc_proc: Optional[subprocess.Popen] = None
- self.dut_proc: Optional[subprocess.Popen] = None
- self.server_proc: Optional[subprocess.Popen] = None
- self.backend_hood_pts: List[str] = []
- self.http_session: Optional[aiohttp.ClientSession] = None
- self.admin_ws: Optional[WsRpcClient] = None
- def _clean_env(self) -> Dict[str, str]:
- env = dict(os.environ)
- for k in (
- "LD_LIBRARY_PATH",
- "QT_PLUGIN_PATH",
- "QT_QPA_PLATFORM_PLUGIN_PATH",
- "QT_QPA_PLATFORM",
- "http_proxy",
- "https_proxy",
- "HTTP_PROXY",
- "HTTPS_PROXY",
- "all_proxy",
- "ALL_PROXY",
- ):
- env.pop(k, None)
- return env
- def _write_config(self) -> None:
- self.data_dir.mkdir(parents=True, exist_ok=True)
- pxe_dir = self.data_dir / "pxe_tftp"
- pxe_dir.mkdir(parents=True, exist_ok=True)
- (pxe_dir / "118.efi").write_bytes(b"MZ\x90\x00STL_118_EFI_SIM_STUB")
- stations = []
- for i, ip in enumerate(self.station_ips):
- sid = f"S{i + 1}"
- stations.append({
- "station_id": sid,
- "frontend_index": i,
- "name": f"仿真工位 00{i + 1} ({ip})",
- "mode": "hardware",
- "cpu_count": 2,
- "channels_per_cpu": 12,
- "target_min_c": 0.0,
- "target_max_c": 100.0,
- "supply_mode": "manual",
- "bmc": {
- "enabled": True,
- "host": ip,
- "user": "ADMIN",
- "username": "ADMIN",
- "password": "Admin123@pl",
- "cipher_suite": 17,
- "timeout_s": 5,
- "console_transport": "ssh_console",
- "ssh_console_port": 2200,
- },
- "console": {
- "enabled": True,
- "transport": "ssh_console",
- "host": ip,
- "port": 2200,
- "user": "ADMIN",
- "write_chunk_bytes": 64,
- "write_gap_ms": 2.0,
- },
- })
- cfg = {
- "mode": "hardware",
- "data_dir": str(self.data_dir),
- "telemetry_interval_s": 1.0,
- "idle_poll_interval_s": 1,
- "stations": stations,
- }
- self.config_path.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8")
- async def __aenter__(self) -> "HilClusterStack":
- await self.start()
- return self
- async def __aexit__(self, *exc: Any) -> None:
- await self.stop()
- async def start(self) -> None:
- self._write_config()
- env = self._clean_env()
- # 1. Start C BMC RMCP+ & SSHv2 :2200 Simulator
- self.bmc_proc = subprocess.Popen(
- [
- str(BMC_SIM_BIN),
- "--ctrl-port", str(self.bmc_ctrl_port),
- "--uart-base", str(self.uart_base),
- "--ipmi-port", "623",
- "--ssh-port", "2200",
- "--probe22-port", "0",
- *self.station_ips,
- ],
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- text=True,
- env=env,
- )
- await self._wait_proc_ready_line(self.bmc_proc, "READY", timeout_s=8.0)
- # 2. Start Python DUT State Machine + 8x `/dev/pts/*` 6400 Hood Simulator
- py_bin = "/opt/prod2u/venv/bin/python3" if os.path.exists("/opt/prod2u/venv/bin/python3") else "python3"
- self.dut_proc = subprocess.Popen(
- [
- py_bin,
- str(DUT_HOOD_SCRIPT),
- "--http-port", str(self.hil_http_port),
- "--bmc-ctrl-port", str(self.bmc_ctrl_port),
- "--uart-base", str(self.uart_base),
- "--num-stations", str(len(self.station_ips)),
- "--tftp-host", "127.0.0.1",
- "--tftp-port", str(self.tftp_port),
- "--speed-scale", str(self.speed_scale),
- "--manifest-out", str(self.manifest_path),
- ],
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- text=True,
- env=env,
- )
- await self._wait_proc_ready_line(self.dut_proc, "READY", timeout_s=8.0)
- manifest = json.loads(self.manifest_path.read_text(encoding="utf-8"))
- self.backend_hood_pts = manifest["backend_hood_pts"]
- # 3. Start Production `stl_native_server`
- self.server_proc = subprocess.Popen(
- [
- str(STL_SERVER_BIN),
- "--config", str(self.config_path),
- "--data-dir", str(self.data_dir),
- "--web-listen", f"127.0.0.1:{self.web_port}",
- "--tftp-listen", f"127.0.0.1:{self.tftp_port}",
- "--pxe-mode", "disabled",
- "--web-dir", str(WEB_DIR),
- "--contracts", str(CONTRACTS_PATH),
- "--web-password", self.web_password,
- ],
- cwd=str(ROOT_DIR),
- stdout=subprocess.DEVNULL,
- stderr=subprocess.PIPE,
- text=True,
- env=env,
- )
- self.http_session = aiohttp.ClientSession(cookie_jar=aiohttp.CookieJar(unsafe=True))
- try:
- await self._wait_http_up(f"http://127.0.0.1:{self.web_port}/", timeout_s=10.0)
- headers: Dict[str, str] = {}
- if self.web_password and self.web_password.lower() not in ("disabled", "none", "off"):
- b64 = base64.b64encode(f"admin:{self.web_password}".encode("utf-8")).decode("ascii")
- headers["Authorization"] = f"Basic {b64}"
- async with self.http_session.post(
- f"http://127.0.0.1:{self.web_port}/api/auth/login",
- json={"password": self.web_password},
- ) as resp:
- assert resp.status == 200, f"Login failed: {resp.status}"
- self.admin_ws = WsRpcClient(self.http_session, f"ws://127.0.0.1:{self.web_port}/ws", headers=headers)
- await self.admin_ws.connect()
- except Exception:
- await self.stop()
- raise
- async def _wait_proc_ready_line(self, proc: subprocess.Popen, prefix: str, timeout_s: float) -> str:
- deadline = time.monotonic() + timeout_s
- assert proc.stdout is not None
- while time.monotonic() < deadline:
- if proc.poll() is not None:
- err = proc.stderr.read() if proc.stderr else ""
- raise RuntimeError(f"Process exited early ({proc.returncode}): {err}")
- line = await asyncio.to_thread(proc.stdout.readline)
- if line and prefix in line:
- return line.strip()
- await asyncio.sleep(0.05)
- raise TimeoutError(f"Timed out waiting for {prefix}")
- async def _wait_http_up(self, url: str, timeout_s: float) -> None:
- assert self.http_session is not None
- deadline = time.monotonic() + timeout_s
- while time.monotonic() < deadline:
- try:
- async with self.http_session.get(url, timeout=aiohttp.ClientTimeout(total=1.0)) as r:
- if r.status in (200, 401):
- return
- except Exception:
- pass
- await asyncio.sleep(0.1)
- raise TimeoutError(f"Server did not listen at {url}")
- async def stop(self) -> None:
- if self.admin_ws is not None:
- await self.admin_ws.close()
- if self.http_session is not None:
- await self.http_session.close()
- for proc in (self.server_proc, self.dut_proc, self.bmc_proc):
- if proc is not None and proc.poll() is None:
- with contextlib.suppress(Exception):
- proc.terminate()
- proc.wait(timeout=3.0)
- if proc.poll() is None:
- with contextlib.suppress(Exception):
- proc.kill()
- with contextlib.suppress(Exception):
- shutil.rmtree(self.tmp_dir, ignore_errors=True)
- # ---- HIL Fault-Injection & Inspection Helpers ----
- async def hil_status(self) -> Dict[str, Any]:
- assert self.http_session is not None
- async with self.http_session.get(f"http://127.0.0.1:{self.hil_http_port}/api/status") as r:
- return await r.json()
- async def set_link(self, idx: int, *, bmc_up: bool, serial_up: bool) -> Dict[str, Any]:
- assert self.http_session is not None
- async with self.http_session.post(
- f"http://127.0.0.1:{self.hil_http_port}/api/bmc/set_link",
- json={"idx": idx, "bmc_up": bmc_up, "serial_up": serial_up},
- ) as r:
- return await r.json()
- async def set_power(self, idx: int, *, power_on: bool) -> Dict[str, Any]:
- assert self.http_session is not None
- async with self.http_session.post(
- f"http://127.0.0.1:{self.hil_http_port}/api/bmc/set_power",
- json={"idx": idx, "power_on": power_on},
- ) as r:
- return await r.json()
- async def configure_dut(self, idx: int, **kwargs: Any) -> Dict[str, Any]:
- assert self.http_session is not None
- payload = {"idx": idx, **kwargs}
- async with self.http_session.post(
- f"http://127.0.0.1:{self.hil_http_port}/api/dut/configure",
- json=payload,
- ) as r:
- return await r.json()
- async def trigger_dut_boot(self, idx: int, reason: str = "test_boot") -> Dict[str, Any]:
- assert self.http_session is not None
- async with self.http_session.post(
- f"http://127.0.0.1:{self.hil_http_port}/api/dut/trigger_boot",
- json={"idx": idx, "reason": reason},
- ) as r:
- return await r.json()
- async def clear_hood_history(self, idx: Optional[int] = None) -> None:
- assert self.http_session is not None
- async with self.http_session.post(
- f"http://127.0.0.1:{self.hil_http_port}/api/hood/clear_history",
- json={"idx": idx},
- ) as r:
- await r.json()
- async def connect_and_heat_backend_hood(self, station_id: str, idx: int, target_c: int = 70) -> None:
- """Bind `stl_native_server` ThermalMcuHub for `station_id` to `/dev/pts/*` hood & start heating."""
- assert self.admin_ws is not None
- pts = self.backend_hood_pts[idx]
- await self.admin_ws.call(
- "ThermalAction",
- {
- "station_id": station_id,
- "action": "connect",
- "mode": "serial",
- "serial_path": pts,
- "serial_baud": 115200,
- },
- )
- # Wait up to 3s for 0xF0 heartbeat so ThermalMcuHub marks MCU online
- deadline = time.monotonic() + 3.5
- while time.monotonic() < deadline:
- snap = await self.admin_ws.call("GetThermalConsole", {"station_id": station_id})
- if (snap.get("mcu") or {}).get("online"):
- break
- await asyncio.sleep(0.2)
- await self.admin_ws.call(
- "ThermalAction",
- {"station_id": station_id, "action": "set_temp", "target_c": target_c},
- )
- async def enqueue_cmd(self, station_id: str, method: str, arguments: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
- assert self.admin_ws is not None
- item = await self.admin_ws.call(
- "EnqueueCommand",
- {
- "command_id": f"hil-cmd-{uuid.uuid4().hex[:10]}",
- "station_id": station_id,
- "method": method,
- "arguments": arguments or {},
- },
- )
- if item.get("state") == "failed":
- raise RuntimeError(f"EnqueueCommand {method} on {station_id} failed: {item}")
- return item
- async def wait_station_online(self, station_id: str, timeout_s: float = 12.0) -> Dict[str, Any]:
- assert self.admin_ws is not None
- deadline = time.monotonic() + timeout_s
- while time.monotonic() < deadline:
- st = await self.admin_ws.call("GetStation", {"station_id": station_id})
- if st.get("bmc_state") == "online" and st.get("console_online") is True:
- return st
- await asyncio.sleep(0.25)
- raise TimeoutError(f"Station {station_id} did not bring BMC + :2200 online within {timeout_s}s")
|