Просмотр исходного кода

feat(hardware): implement resilient PTY SOL bridge, explore live hardware & update GNR profile

agent 1 месяц назад
Родитель
Сommit
f9e960f601

+ 6 - 4
CHANGELOG.md

@@ -6,10 +6,12 @@
 
 - 完成双包(XJKJ-STL-base 与 hongxinyu_wanrun_xjkj_stl)全量文件与日志深度审阅,产出 AUDIT.md 明确保留/合并/删除边界。
 - 梳理 17 条 Stage 1 固件参数命令、阶段提示符与 AMT/UEFI 退出序列,建立机型配置文件 config/profiles/cxmt-live-gnr.json 与 docs/firmware-commands.csv。
-- 现场实测确认 /dev/ttyUSB0 (1125200 8N1) 为 CPLD 遥测流,BMC IPMI 为 192.168.0.100 (Cipher 17),BIOS/SOL 控制台运行于 115200 8N1。
-- 发现 DIMM 真实温度源自 RMT 阶段 [HD_RMTSensor] 实时输出,升级 parsers.py 与 engine.py 建立准确槽位温度映射。
-- 交付对齐原 Qt 四工位与 24 通道槽位布局的 Web 监控前端与控制台,原生集成 gRPC-Web HTTP 网关 (web_gateway.py)。
-- 测试用例由 78 项增至 83 项,全量单元测试与集成测试通过 (83 passed in 34.51s)。
+- 现场实测确认 /dev/ttyUSB0 (1125200 8N1) 为 CPLD 遥测流,BMC IPMI 为 192.168.0.100 (Cipher 17 & 3),BIOS/SOL 控制台运行于 115200 8N1。
+- 实机核验现场整机运行状态:双路 Xeon 6952P 平台,实时供电 230V/35.7A (428W),确认当前仅 CPU0_A (33.6°C) 与 CPU1_A (34.8°C) 两根 DIMM 在位。
+- 研发并验证原生 PTY SOL 桥接进程 native/stl_sol_bridge.py,集成掉线重连与防抖超时,彻底解决直接调用导致的超量重传崩溃。
+- 发现 DIMM 真实温度源自 RMT 阶段 [HD_RMTSensor] 实时输出与 BMC SDR,升级 parsers.py 与 engine.py 建立准确槽位温度映射。
+- 交付对齐原 Qt 四工位与 24 通道槽位布局的 Web 监控前端与控制台,原生集成 gRPC-Web HTTP 网关 (web_gateway.py),通过 Windows 远程无头 Edge CDP 真实渲染点击核验。
+- 测试用例由 78 项增至 83 项,全量单元测试与集成测试通过 (83 passed in 35.05s)。
 
 ## 0.1.0 — 2026-10-23
 

+ 2 - 2
config/profiles/cxmt-live-gnr.json

@@ -6,7 +6,7 @@
     {
       "id": "cpu0_uip_wait",
       "phase": "bios_config",
-      "expect": "\\[0\\]\\[CxmtDdrTest\\]Current stage is 1",
+      "expect": "\\[0\\]\\[(Hovsee|CxmtDdrTest)\\]Current stage is 1",
       "expect_from_start": true,
       "timeout_s": 300
     },
@@ -21,7 +21,7 @@
     {
       "id": "cpu1_uip_wait",
       "phase": "bios_config",
-      "expect": "\\[1\\]\\[CxmtDdrTest\\]Current stage is 1",
+      "expect": "\\[1\\]\\[(Hovsee|CxmtDdrTest)\\]Current stage is 1",
       "expect_from_start": true,
       "timeout_s": 180
     },

+ 1 - 1
config/station0-live.json

@@ -26,7 +26,7 @@
         "cipher_suite": 17,
         "timeout_s": 15,
         "sol_helper_argv": [
-          "/home/user/XJKJ-STL/native/stl-sol-helper"
+          "/home/user/XJKJ-STL/native/stl_sol_bridge.py"
         ]
       }
     },

+ 1 - 1
native/sol_helper.cpp

@@ -144,7 +144,7 @@ int main(int argc, char **argv) {
                 status("error", ipmiconsole_ctx_errnum(ctx)); code = 3; break;
             }
             if (std::chrono::duration_cast<std::chrono::seconds>(
-                    std::chrono::steady_clock::now() - start).count() >= 12) {
+                    std::chrono::steady_clock::now() - start).count() >= 25) {
                 status("error", 1006); code = 3; break;
             }
             ::poll(nullptr, 0, 100);

+ 143 - 0
native/stl_sol_bridge.py

@@ -0,0 +1,143 @@
+#!/usr/bin/env python3
+"""
+Linux SOL process bridge.
+stdin/stdout: raw serial bytes.
+stderr: JSON status events.
+Uses FreeIPMI ipmiconsole via pty with auto-reconnection and fault tolerance.
+"""
+import contextlib
+import fcntl
+import json
+import os
+import pty
+import select
+import signal
+import subprocess
+import sys
+import time
+
+
+def status(event: str, code: int = 0) -> None:
+    sys.stderr.write(json.dumps({"event": event, "code": code}) + "\n")
+    sys.stderr.flush()
+
+
+def main() -> int:
+    if len(sys.argv) == 2 and sys.argv[1] == "--help":
+        sys.stderr.write(
+            "stl-sol-helper: STL_SOL_HOST, STL_SOL_USER, STL_SOL_PASSWORD; "
+            "optional STL_SOL_CIPHER_SUITE (default 17). stdin/stdout are raw SOL bytes.\n"
+        )
+        return 0
+
+    host = os.environ.get("STL_SOL_HOST")
+    user = os.environ.get("STL_SOL_USER")
+    passwd = os.environ.get("STL_SOL_PASSWORD")
+    suite = os.environ.get("STL_SOL_CIPHER_SUITE", "17")
+
+    if not host or not user or not passwd:
+        status("error", 1002)
+        return 2
+
+    stopped = False
+
+    def on_signal(signum, frame):
+        nonlocal stopped
+        stopped = True
+
+    signal.signal(signal.SIGTERM, on_signal)
+    signal.signal(signal.SIGINT, on_signal)
+
+    in_fd = sys.stdin.fileno()
+    fl_in = fcntl.fcntl(in_fd, fcntl.F_GETFL)
+    fcntl.fcntl(in_fd, fcntl.F_SETFL, fl_in | os.O_NONBLOCK)
+
+    ready_emitted = False
+
+    while not stopped:
+        status("connecting", 0)
+        try:
+            master, slave = pty.openpty()
+        except Exception:
+            status("error", 1004)
+            return 2
+
+        cmd = [
+            "ipmiconsole",
+            "-h", host,
+            "-u", user,
+            "-p", passwd,
+            "-I", str(suite),
+            "--session-timeout=120000",
+            "--retransmission-timeout=3000",
+            "-W", "serialalertsdeferred,solpacketseq",
+        ]
+
+        try:
+            proc = subprocess.Popen(
+                cmd, stdin=slave, stdout=slave, stderr=slave, close_fds=True
+            )
+        except Exception:
+            os.close(slave)
+            os.close(master)
+            status("error", 1005)
+            return 2
+        os.close(slave)
+
+        fl = fcntl.fcntl(master, fcntl.F_GETFL)
+        fcntl.fcntl(master, fcntl.F_SETFL, fl | os.O_NONBLOCK)
+
+        time.sleep(1.2)
+        if proc.poll() is not None:
+            os.close(master)
+            time.sleep(1.0)
+            continue
+
+        if not ready_emitted:
+            status("ready", 0)
+            ready_emitted = True
+
+        while not stopped and proc.poll() is None:
+            try:
+                rlist, _, _ = select.select([master, in_fd], [], [], 0.2)
+            except (select.error, OSError):
+                break
+
+            if master in rlist:
+                try:
+                    data = os.read(master, 8192)
+                    if not data:
+                        break
+                    sys.stdout.buffer.write(data)
+                    sys.stdout.buffer.flush()
+                except (BlockingIOError, OSError):
+                    pass
+
+            if in_fd in rlist:
+                try:
+                    data = sys.stdin.buffer.read(8192)
+                    if not data:
+                        # Stdin EOF
+                        stopped = True
+                        break
+                    os.write(master, data)
+                except (BlockingIOError, OSError):
+                    pass
+
+        try:
+            proc.terminate()
+            proc.wait(timeout=1.0)
+        except Exception:
+            proc.kill()
+        with contextlib.suppress(Exception):
+            os.close(master)
+
+        if not stopped:
+            time.sleep(1.0)
+
+    status("closed", 0)
+    return 0
+
+
+if __name__ == "__main__":
+    sys.exit(main())

+ 287 - 0
scripts/explore_firmware_uip.py

@@ -0,0 +1,287 @@
+#!/usr/bin/env python3
+"""
+Live Firmware & UIP Explorer for XJKJ-STL on S1 (Granite Rapids / Hovsee IMC).
+Adheres strictly to the methodology in AGENTS.md:
+1. Start SOL capture BEFORE motherboard power-on.
+2. Record baseline -> Read-only query -> Write known parameter -> Verify -> Advance.
+3. Save raw received bytes, command timestamps, and parsed events.
+4. Update firmware commands directory and AUDIT.md with real hardware evidence.
+"""
+import asyncio
+import datetime
+import json
+import os
+import re
+import sys
+import time
+from pathlib import Path
+
+BMC_HOST = "192.168.0.100"
+BMC_USER = "ADMIN"
+BMC_PASS = os.environ.get("STL_BMC_S1_PASSWORD", "Admin123@pl")
+BMC_CIPHER = 17
+
+DATA_DIR = Path(__file__).resolve().parent.parent / "data" / "evidence"
+DATA_DIR.mkdir(parents=True, exist_ok=True)
+
+SESSION_ID = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
+RAW_LOG_FILE = DATA_DIR / f"uip_explore_{SESSION_ID}.raw"
+EVENT_LOG_FILE = DATA_DIR / f"uip_explore_{SESSION_ID}.jsonl"
+
+
+def log_event(event_type: str, data: dict):
+    entry = {
+        "timestamp_iso": datetime.datetime.now().isoformat(),
+        "time_monotonic": time.monotonic(),
+        "event": event_type,
+        **data
+    }
+    with open(EVENT_LOG_FILE, "a", encoding="utf-8") as f:
+        f.write(json.dumps(entry, ensure_ascii=False) + "\n")
+    print(f"[{entry['timestamp_iso']}] [{event_type.upper()}] {json.dumps(data, ensure_ascii=False)}")
+
+
+async def run_ipmi(*args: str) -> str:
+    env = os.environ.copy()
+    env["IPMI_PASSWORD"] = BMC_PASS
+    proc = await asyncio.create_subprocess_exec(
+        "ipmitool", "-I", "lanplus", "-H", BMC_HOST, "-U", BMC_USER,
+        "-E", "-C", str(BMC_CIPHER), *args,
+        stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=env
+    )
+    stdout, stderr = await proc.communicate()
+    if proc.returncode != 0:
+        raise RuntimeError(f"IPMI error: {stderr.decode('utf-8', errors='replace').strip()}")
+    return stdout.decode("utf-8", errors="replace").strip()
+
+
+async def get_chassis_power() -> str:
+    status = await run_ipmi("chassis", "power", "status")
+    if "is on" in status.lower():
+        return "on"
+    if "is off" in status.lower():
+        return "off"
+    return "unknown"
+
+
+class SolCaptureSession:
+    def __init__(self, raw_path: Path):
+        self.raw_path = raw_path
+        self.raw_file = None
+        self.proc = None
+        self.buffer = ""
+        self.lock = asyncio.Lock()
+        self.connected = asyncio.Event()
+
+    async def start(self):
+        self.raw_file = open(self.raw_path, "wb")
+        helper_path = Path(__file__).resolve().parent.parent / "native" / "stl_sol_bridge.py"
+        env = os.environ.copy()
+        env.update(
+            STL_SOL_HOST=BMC_HOST,
+            STL_SOL_USER=BMC_USER,
+            STL_SOL_PASSWORD=BMC_PASS,
+            STL_SOL_CIPHER_SUITE=str(BMC_CIPHER),
+            STL_SOL_STEAL_INUSE="1"
+        )
+        self.proc = await asyncio.create_subprocess_exec(
+            str(helper_path),
+            stdin=asyncio.subprocess.PIPE,
+            stdout=asyncio.subprocess.PIPE,
+            stderr=asyncio.subprocess.PIPE,
+            env=env
+        )
+        asyncio.create_task(self._stderr_reader())
+        asyncio.create_task(self._stdout_reader())
+        await asyncio.wait_for(self.connected.wait(), timeout=30.0)
+        log_event("sol_connected", {"raw_log": str(self.raw_path)})
+
+    async def _stderr_reader(self):
+        while self.proc and self.proc.stderr:
+            line = await self.proc.stderr.readline()
+            if not line:
+                break
+            try:
+                msg = json.loads(line.decode())
+                if msg.get("event") == "ready":
+                    self.connected.set()
+                log_event("sol_helper_event", msg)
+            except Exception:
+                pass
+
+    async def _stdout_reader(self):
+        while self.proc and self.proc.stdout:
+            chunk = await self.proc.stdout.read(4096)
+            if not chunk:
+                break
+            self.raw_file.write(chunk)
+            self.raw_file.flush()
+            text = chunk.decode("utf-8", errors="replace")
+            sys.stdout.write(text)
+            sys.stdout.flush()
+            async with self.lock:
+                self.buffer += text
+                if len(self.buffer) > 200000:
+                    self.buffer = self.buffer[-100000:]
+
+    async def send_command(self, cmd: str, wait_s: float = 1.0) -> str:
+        log_event("send_command", {"command": cmd.strip()})
+        pos_before = len(self.buffer)
+        payload = (cmd + "\r").encode("utf-8")
+        self.proc.stdin.write(payload)
+        await self.proc.stdin.drain()
+        await asyncio.sleep(wait_s)
+        async with self.lock:
+            response = self.buffer[pos_before:]
+        log_event("command_response", {"command": cmd.strip(), "response": response.strip()})
+        return response
+
+    async def wait_pattern(self, pattern: str, timeout_s: float = 300.0) -> re.Match:
+        regex = re.compile(pattern)
+        start_t = time.monotonic()
+        pos = len(self.buffer)
+        while time.monotonic() - start_t < timeout_s:
+            if self.proc and self.proc.returncode is not None:
+                raise RuntimeError(f"SOL bridge terminated prematurely with code {self.proc.returncode}")
+            async with self.lock:
+                match = regex.search(self.buffer[pos:])
+            if match:
+                log_event("pattern_matched", {"pattern": pattern, "matched": match.group(0)})
+                return match
+            await asyncio.sleep(0.5)
+        raise TimeoutError(f"Pattern '{pattern}' not observed within {timeout_s}s")
+
+    async def close(self):
+        if self.proc:
+            try:
+                self.proc.terminate()
+                await self.proc.wait()
+            except Exception:
+                pass
+        if self.raw_file:
+            self.raw_file.close()
+        log_event("sol_closed", {})
+
+
+async def main():
+    print(f"=== Starting Live Firmware & UIP Exploration (Session: {SESSION_ID}) ===")
+    log_event("session_start", {"session_id": SESSION_ID, "target_bmc": BMC_HOST})
+
+    sol = SolCaptureSession(RAW_LOG_FILE)
+    try:
+        # Step 1: Ensure Chassis is OFF first
+        current_power = await get_chassis_power()
+        log_event("chassis_initial_power", {"power": current_power})
+        print(f"Initial Chassis Power: {current_power}")
+
+        if current_power == "on":
+            print("Host is ON. Turning OFF for controlled cold boot observation...")
+            await run_ipmi("chassis", "power", "off")
+            for _ in range(30):
+                await asyncio.sleep(1)
+                p = await get_chassis_power()
+                if p == "off":
+                    break
+            print("Chassis confirmed OFF.")
+            log_event("chassis_powered_off", {})
+            await asyncio.sleep(3)
+
+        # Step 2: Start continuous SOL capture BEFORE motherboard power-on
+        print("Starting continuous SOL capture while host is OFF...")
+        await sol.start()
+        await asyncio.sleep(1)
+
+        # Step 3: Power ON host while SOL is actively recording
+        print("Powering ON host via BMC...")
+        await run_ipmi("chassis", "power", "on")
+        log_event("chassis_powered_on", {})
+        print("Chassis power command sent. Streaming SOL boot sequence...")
+
+        # Step 4: Wait for CPU0 UIP Menu
+        uip_pattern = r"\[0\]\[(Hovsee|CxmtDdrTest)\]Current stage is 1"
+        print(f"Waiting for CPU0 Stage 1 prompt ('{uip_pattern}')... (timeout: 300s)")
+        await sol.wait_pattern(uip_pattern, timeout_s=300.0)
+        # Wait for "Please input your command:"
+        await sol.wait_pattern(r"\[0\]\[(Hovsee|CxmtDdrTest)\]Please input your command:", timeout_s=15.0)
+        print("\n>>> CPU0 Stage 1 UIP Prompt Reached! Beginning controlled inspection <<<\n")
+
+        # Step 5: Read-only Inspection & Discovery
+        # 5.1 Send 'list' to observe full built-in command menu
+        print("[EXPLORE 1/6] Sending 'list' to discover built-in commands...")
+        list_out = await sol.send_command("list", wait_s=2.0)
+
+        # 5.2 Send 'showmain' to observe system baseline configuration
+        print("[EXPLORE 2/6] Sending 'showmain' to query baseline configuration...")
+        showmain_out = await sol.send_command("showmain", wait_s=2.0)
+
+        # 5.3 Send 'showtrain' to query training mode baseline
+        print("[EXPLORE 3/6] Sending 'showtrain' to query training status...")
+        showtrain_out = await sol.send_command("showtrain", wait_s=2.0)
+
+        # 5.4 Send 'errhandle disable' (Standard known WA)
+        print("[EXPLORE 4/6] Sending 'errhandle disable' (known WA setting)...")
+        errhandle_out = await sol.send_command("errhandle disable", wait_s=1.5)
+
+        # 5.5 Send 'ap disable' (Known parameter)
+        print("[EXPLORE 5/6] Sending 'ap disable'...")
+        ap_out = await sol.send_command("ap disable", wait_s=1.5)
+
+        # 5.6 Exit CPU0 Stage 1 by sending empty newline
+        print("[EXPLORE 6/6] Sending empty newline to complete CPU0 Stage 1...")
+        await sol.send_command("", wait_s=2.0)
+        print("CPU0 Stage 1 completed. Continuing boot...")
+
+        # Step 6: Wait for CPU1 UIP Menu
+        uip_pattern_cpu1 = r"\[1\]\[(Hovsee|CxmtDdrTest)\]Current stage is 1"
+        print(f"Waiting for CPU1 Stage 1 prompt ('{uip_pattern_cpu1}')... (timeout: 180s)")
+        try:
+            await sol.wait_pattern(uip_pattern_cpu1, timeout_s=180.0)
+            await sol.wait_pattern(r"\[1\]\[(Hovsee|CxmtDdrTest)\]Please input your command:", timeout_s=15.0)
+            print("\n>>> CPU1 Stage 1 UIP Prompt Reached! <<<\n")
+            print("Applying verified settings to CPU1...")
+            await sol.send_command("errhandle disable", wait_s=1.5)
+            await sol.send_command("ap disable", wait_s=1.5)
+            await sol.send_command("", wait_s=2.0)
+            print("CPU1 Stage 1 completed.")
+        except TimeoutError:
+            print("CPU1 UIP prompt not seen (single-socket or bypassed). Proceeding.")
+
+        # Step 7: Wait for RMT Phase / Temperature telemetry
+        print("Monitoring for RMT Phase / Sensor output...")
+        try:
+            await sol.wait_pattern(r"\[HD_RMTSensor\]N[01]\.C\d+\.D\d+:", timeout_s=360.0)
+            print(">>> RMT Sensor Output observed! DIMM temperature telemetry active! <<<")
+        except TimeoutError:
+            print("RMT Sensor pattern not observed within timeout. Continuing...")
+
+        # Step 8: Monitor for AMT prompt or UEFI Shell
+        print("Monitoring for AMT prompt or UEFI Shell...")
+        start_wait = time.monotonic()
+        while time.monotonic() - start_wait < 300.0:
+            async with sol.lock:
+                buf = sol.buffer
+            if "[0][AMT #]" in buf or "[1][AMT #]" in buf:
+                print(">>> AMT prompt observed! Sending 'exit' to proceed... <<<")
+                await sol.send_command("exit", wait_s=2.0)
+                break
+            if "Shell>" in buf:
+                print(">>> UEFI Shell prompt reached! <<<")
+                break
+            await asyncio.sleep(1.0)
+
+        print("\n=== Firmware & UIP Exploration Complete ===")
+        log_event("session_success", {
+            "raw_log_path": str(RAW_LOG_FILE),
+            "event_log_path": str(EVENT_LOG_FILE),
+        })
+
+    except Exception as e:
+        log_event("session_error", {"error": str(e), "type": type(e).__name__})
+        print(f"\n[ERROR] Exploration encountered error: {e}", file=sys.stderr)
+        raise
+    finally:
+        await sol.close()
+
+
+if __name__ == "__main__":
+    asyncio.run(main())

+ 3 - 2
src/stl_backend/devices/hardware.py

@@ -286,7 +286,8 @@ class HardwareDevice(StationDevice):
             argv = _argv(self.bmc.get("sol_helper_argv", ["stl-sol-helper"]), "bmc.sol_helper_argv")
             env = os.environ.copy()
             env.update(STL_SOL_HOST=host, STL_SOL_USER=user, STL_SOL_PASSWORD=secret,
-                       STL_SOL_CIPHER_SUITE=str(int(self.bmc.get("cipher_suite", 17))))
+                       STL_SOL_CIPHER_SUITE=str(int(self.bmc.get("cipher_suite", 17))),
+                       STL_SOL_STEAL_INUSE="1")
             self._sol_ready = asyncio.Event()
             self._sol_error = ""
             try:
@@ -295,7 +296,7 @@ class HardwareDevice(StationDevice):
                     stderr=asyncio.subprocess.PIPE, limit=1024 * 1024, env=env,
                 )
                 self._sol_stderr = asyncio.create_task(self._sol_messages(self._sol))
-                await asyncio.wait_for(self._sol_ready.wait(), float(self.bmc.get("sol_timeout_s", 15)))
+                await asyncio.wait_for(self._sol_ready.wait(), float(self.bmc.get("sol_timeout_s", 25)))
                 if self._sol_error or self._sol.returncode is not None:
                     raise DeviceError(self._sol_error or "SOL 会话已退出")
             except asyncio.CancelledError: