333 lines
13 KiB
Python
333 lines
13 KiB
Python
"""Optional read-only Mentor Verify status bridge client.
|
|
|
|
The Mentor EE 7.9 libraries are 32-bit MFC binaries. This module deliberately
|
|
does not load them from Python. It talks to a separately compiled x86 helper
|
|
over one JSON line at a time and treats a missing or malformed helper as an
|
|
unavailable authoritative source.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
import json
|
|
import ntpath
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import queue
|
|
import sys
|
|
import threading
|
|
from typing import Any, Sequence
|
|
from uuid import uuid4
|
|
|
|
from .network_path import absolute_preserving_drive
|
|
|
|
|
|
class BridgeResponseError(RuntimeError):
|
|
"""The helper returned a response that cannot prove Verify state."""
|
|
|
|
|
|
class BridgeUnavailable(RuntimeError):
|
|
"""The optional x86 helper is not available on this machine."""
|
|
|
|
def __init__(self, path: Path, detail: str = "未找到可用的 32-bit Mentor 状态桥") -> None:
|
|
self.path = Path(path)
|
|
super().__init__(f"{detail}: {self.path}")
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class BridgeResult:
|
|
status: str
|
|
source: str
|
|
raw_status: int | str | None = None
|
|
detail: str = ""
|
|
response: dict[str, Any] | None = None
|
|
request_id: str = ""
|
|
block_name: str = ""
|
|
lmc_file: str = ""
|
|
|
|
|
|
def _normalized_path(value: str | Path) -> str:
|
|
raw = str(value).strip().replace("/", "\\")
|
|
if raw.startswith("\\\\"):
|
|
raw = "\\\\" + "\\".join(
|
|
part for part in raw.lstrip("\\").split("\\") if part
|
|
)
|
|
return ntpath.normcase(ntpath.normpath(raw))
|
|
|
|
|
|
def parse_bridge_response(
|
|
line: str,
|
|
*,
|
|
expected_request_id: str | None = None,
|
|
expected_block: str | None = None,
|
|
expected_lmc: str | Path | None = None,
|
|
) -> BridgeResult:
|
|
"""Parse one bridge response and require an authoritative status.
|
|
|
|
``UNKNOWN`` is intentionally rejected here. The caller can represent a
|
|
missing bridge separately, but a helper must never claim success without a
|
|
concrete Mentor status source.
|
|
"""
|
|
try:
|
|
payload = json.loads(line)
|
|
except (TypeError, ValueError) as error:
|
|
raise BridgeResponseError(f"状态桥返回非法 JSON: {error}") from error
|
|
if not isinstance(payload, dict):
|
|
raise BridgeResponseError("状态桥响应不是 JSON 对象")
|
|
if not payload.get("ok"):
|
|
raise BridgeResponseError(str(payload.get("error") or "状态桥调用失败"))
|
|
request_id = str(payload.get("request_id") or "")
|
|
block_name = str(payload.get("block_name") or "")
|
|
lmc_file = str(payload.get("mentor_lmc_file") or payload.get("lmc_file") or "")
|
|
if expected_request_id is not None and request_id != expected_request_id:
|
|
raise BridgeResponseError(
|
|
f"状态桥请求标识不匹配: expected={expected_request_id!r}, actual={request_id!r}"
|
|
)
|
|
if expected_block is not None and block_name != expected_block:
|
|
raise BridgeResponseError(
|
|
f"状态桥 CBB 标识不匹配: expected={expected_block!r}, actual={block_name!r}"
|
|
)
|
|
if expected_lmc is not None and (
|
|
not lmc_file or _normalized_path(lmc_file) != _normalized_path(expected_lmc)
|
|
):
|
|
raise BridgeResponseError(
|
|
f"状态桥中心库路径不匹配: expected={str(expected_lmc)!r}, actual={lmc_file!r}"
|
|
)
|
|
status = str(payload.get("status") or "").upper()
|
|
source = str(payload.get("source") or "").strip()
|
|
if status not in {"READY", "PENDING"} or not source:
|
|
raise BridgeResponseError(
|
|
"状态桥未返回 authoritative Verify 状态"
|
|
)
|
|
return BridgeResult(
|
|
status=status,
|
|
source=source,
|
|
raw_status=payload.get("raw_status"),
|
|
detail=str(payload.get("detail") or ""),
|
|
response=payload,
|
|
request_id=request_id,
|
|
block_name=block_name,
|
|
lmc_file=lmc_file,
|
|
)
|
|
|
|
|
|
def default_bridge_path() -> Path:
|
|
configured = os.environ.get("CBB_STATUS_BRIDGE", "").strip()
|
|
if configured:
|
|
return Path(configured).expanduser()
|
|
package_root = Path(__file__).resolve().parent
|
|
frozen_root = Path(getattr(sys, "_MEIPASS", package_root))
|
|
candidates = (
|
|
package_root / "status_bridge32.exe",
|
|
package_root / "bridge" / "CbbStatusBridge32.exe",
|
|
Path(sys.executable).resolve().parent / "tools" / "status_bridge" / "bin" / "CbbStatusBridge32.exe",
|
|
frozen_root / "tools" / "status_bridge" / "bin" / "CbbStatusBridge32.exe",
|
|
package_root.parent.parent / "tools" / "status_bridge" / "bin" / "CbbStatusBridge32.exe",
|
|
)
|
|
for candidate in candidates:
|
|
if candidate.is_file():
|
|
return candidate
|
|
return candidates[0]
|
|
|
|
|
|
class StatusBridgeClient:
|
|
"""Query a compiled x86 bridge without importing Mentor DLLs in Python."""
|
|
|
|
def __init__(self, executable: Path | None = None, *, env: dict[str, str] | None = None) -> None:
|
|
self.executable = Path(executable) if executable is not None else default_bridge_path()
|
|
self.env = dict(env or {})
|
|
|
|
def query(
|
|
self,
|
|
lmc_file: Path,
|
|
block_name: str,
|
|
*,
|
|
block_type: str = "RULP",
|
|
timeout_seconds: float = 10,
|
|
) -> BridgeResult:
|
|
if not self.executable.is_file():
|
|
raise BridgeUnavailable(self.executable)
|
|
request_id = uuid4().hex
|
|
resolved_lmc = str(absolute_preserving_drive(lmc_file))
|
|
request = {
|
|
"op": "is_verified",
|
|
"request_id": request_id,
|
|
"lmc_file": resolved_lmc,
|
|
"block_name": str(block_name),
|
|
"block_type": str(block_type),
|
|
}
|
|
creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
|
|
child_env = os.environ.copy()
|
|
child_env.update(self.env)
|
|
try:
|
|
process = subprocess.Popen(
|
|
[str(self.executable)],
|
|
stdin=subprocess.PIPE,
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.PIPE,
|
|
text=True,
|
|
encoding="utf-8",
|
|
errors="replace",
|
|
creationflags=creationflags,
|
|
env=child_env,
|
|
)
|
|
except OSError as error:
|
|
raise BridgeUnavailable(self.executable, f"无法启动 32-bit Mentor 状态桥: {error}") from error
|
|
try:
|
|
stdout, stderr = process.communicate(
|
|
json.dumps(request, ensure_ascii=False) + "\n",
|
|
timeout=max(0.1, float(timeout_seconds)),
|
|
)
|
|
except subprocess.TimeoutExpired as error:
|
|
try:
|
|
process.kill()
|
|
except OSError:
|
|
pass
|
|
try:
|
|
process.communicate(timeout=5)
|
|
except subprocess.TimeoutExpired:
|
|
pass
|
|
raise BridgeResponseError("状态桥响应超时") from error
|
|
if process.returncode not in (0, None):
|
|
detail = (stderr or stdout).strip() or f"退出码 {process.returncode}"
|
|
raise BridgeResponseError(f"状态桥进程失败: {detail}")
|
|
line = next((item.strip() for item in stdout.splitlines() if item.strip()), "")
|
|
if not line:
|
|
raise BridgeResponseError("状态桥没有返回 JSON 响应")
|
|
return parse_bridge_response(
|
|
line,
|
|
expected_request_id=request_id,
|
|
expected_block=str(block_name),
|
|
expected_lmc=resolved_lmc,
|
|
)
|
|
|
|
|
|
class StatusBridgeServer:
|
|
"""Persistent JSONL bridge process with per-request deadlines."""
|
|
|
|
def __init__(self, executable: Path | None = None, *, env: dict[str, str] | None = None,
|
|
extra_args: Sequence[str] = ()) -> None:
|
|
self.executable = Path(executable) if executable is not None else default_bridge_path()
|
|
self.env = dict(env or {})
|
|
self.extra_args = tuple(extra_args)
|
|
self.process: subprocess.Popen[str] | None = None
|
|
self._responses: queue.Queue[str | BaseException | None] = queue.Queue()
|
|
self._reader: threading.Thread | None = None
|
|
self.restart_count = 0
|
|
self._warmup = False
|
|
|
|
def _command(self) -> list[str]:
|
|
if self.executable.suffix.casefold() == ".py":
|
|
return [sys.executable, str(self.executable), "--server", *self.extra_args]
|
|
return [str(self.executable), "--server", *self.extra_args]
|
|
|
|
def start(self) -> None:
|
|
if self.process is not None and self.process.poll() is None:
|
|
return
|
|
if not self.executable.is_file():
|
|
raise BridgeUnavailable(self.executable)
|
|
creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
|
|
child_env = os.environ.copy()
|
|
child_env.update(self.env)
|
|
try:
|
|
self.process = subprocess.Popen(
|
|
self._command(), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
|
stderr=subprocess.DEVNULL, text=True, encoding="utf-8", errors="replace",
|
|
bufsize=1, creationflags=creationflags, env=child_env,
|
|
)
|
|
except OSError as error:
|
|
raise BridgeUnavailable(self.executable, f"无法启动常驻状态桥: {error}") from error
|
|
self._responses = queue.Queue()
|
|
self._warmup = True
|
|
self._reader = threading.Thread(target=self._read_responses, daemon=True)
|
|
self._reader.start()
|
|
|
|
def _read_responses(self) -> None:
|
|
process = self.process
|
|
responses = self._responses
|
|
if process is None or process.stdout is None:
|
|
return
|
|
try:
|
|
for line in process.stdout:
|
|
responses.put(line.strip())
|
|
except BaseException as error: # the supervisor converts this to one item failure
|
|
responses.put(error)
|
|
finally:
|
|
responses.put(None)
|
|
|
|
def query(self, lmc_file: Path, block_name: str, *, block_type: str = "RULP",
|
|
timeout_seconds: float = 10) -> BridgeResult:
|
|
self.start()
|
|
process = self.process
|
|
if process is None or process.stdin is None:
|
|
raise BridgeUnavailable(self.executable, "状态桥进程未运行")
|
|
request_id = uuid4().hex
|
|
resolved_lmc = str(absolute_preserving_drive(lmc_file))
|
|
request = {
|
|
"op": "is_verified", "request_id": request_id, "lmc_file": resolved_lmc,
|
|
"block_name": str(block_name), "block_type": str(block_type),
|
|
}
|
|
try:
|
|
process.stdin.write(json.dumps(request, ensure_ascii=False) + "\n")
|
|
process.stdin.flush()
|
|
except (OSError, ValueError) as error:
|
|
raise BridgeResponseError(f"状态桥写入失败: {error}") from error
|
|
try:
|
|
deadline = max(0.1, float(timeout_seconds))
|
|
# Process startup is outside the item operation. Give a freshly
|
|
# spawned Python/x86 helper a small one-time warm-up allowance so
|
|
# a short item deadline cannot turn interpreter startup into a
|
|
# false timeout.
|
|
if self._warmup:
|
|
deadline = max(deadline, 2.0)
|
|
response = self._responses.get(timeout=deadline)
|
|
except queue.Empty as error:
|
|
self.close()
|
|
raise BridgeResponseError("状态桥响应超时") from error
|
|
if response is None:
|
|
detail = f"退出码 {process.poll()}"
|
|
self.close()
|
|
raise BridgeResponseError(f"状态桥进程提前退出: {detail}")
|
|
if isinstance(response, BaseException):
|
|
self.close()
|
|
raise BridgeResponseError(f"状态桥读取失败: {response}") from response
|
|
self._warmup = False
|
|
return parse_bridge_response(
|
|
response,
|
|
expected_request_id=request_id,
|
|
expected_block=str(block_name),
|
|
expected_lmc=resolved_lmc,
|
|
)
|
|
|
|
def restart(self) -> None:
|
|
self.close()
|
|
self.restart_count += 1
|
|
self.start()
|
|
|
|
def close(self) -> None:
|
|
process, self.process = self.process, None
|
|
if process is None:
|
|
return
|
|
try:
|
|
if process.stdin is not None:
|
|
process.stdin.close()
|
|
except OSError:
|
|
pass
|
|
if process.poll() is None:
|
|
try:
|
|
process.wait(timeout=2)
|
|
except subprocess.TimeoutExpired:
|
|
process.terminate()
|
|
try:
|
|
process.wait(timeout=2)
|
|
except subprocess.TimeoutExpired:
|
|
try:
|
|
process.kill()
|
|
except OSError:
|
|
pass
|
|
try:
|
|
process.wait(timeout=2)
|
|
except subprocess.TimeoutExpired:
|
|
pass
|