okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Portable monitor bundle: carries consoleinfo.py and overview.py (manifest schema 6), the plain Monitor runs when launch is not bundled, smokes accept the Overview's /metrics read, test derives the bundle's import closure3fa1b524d

main
4.9 KiB127 linesraw
1#!/usr/bin/env python3
2"""Check packaged Monitor detach and terminal restoration on a POSIX PTY.
3
4Run with the Python environment that has the optional Textual dependency.
5This exercises an actual terminal session against loopback fake telemetry; it
6does not qualify a physical terminal, Windows console or inference engine.
7"""
8
9from __future__ import annotations
10
11import argparse
12import fcntl
13import hashlib
14import json
15import os
16import platform
17import pty
18import select
19import struct
20import subprocess
21import sys
22import termios
23import threading
24import time
25import urllib.request
26from pathlib import Path
27
28from portable_monitor_smoke import _server
29
30
31def _case(bundle: Path, url: str, paths: list[str], key: bytes) -> dict:
32    master, slave = pty.openpty()
33    process = None
34    before_count = len(paths)
35    try:
36        fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", 30, 110, 0, 0))
37        before = termios.tcgetattr(slave)
38        env = os.environ.copy()
39        env["TERM"] = "xterm-256color"
40        process = subprocess.Popen(
41            [sys.executable, "-I", str(bundle), "monitor", "--url", url,
42             "--interval", "0.5", "--glyphs", "ascii"],
43            stdin=slave, stdout=slave, stderr=slave, close_fds=True, env=env)
44        output = bytearray()
45        bytes_read = 0
46        sent = False
47        active_raw = False
48        deadline = time.monotonic() + 12
49        while time.monotonic() < deadline:
50            ready, _, _ = select.select([master], [], [], 0.1)
51            if ready:
52                try:
53                    chunk = os.read(master, 65536)
54                except OSError:
55                    chunk = b""
56                bytes_read += len(chunk)
57                output.extend(chunk)
58                if len(output) > 65536:
59                    del output[:-65536]
60            if not sent and len(paths) > before_count and b"STRATA" in output:
61                active = termios.tcgetattr(slave)
62                active_raw = not bool(active[3] & termios.ICANON) and not bool(active[3] & termios.ECHO)
63                if active_raw:
64                    os.write(master, key)
65                    sent = True
66            if process.poll() is not None:
67                break
68        if process.poll() is None:
69            process.kill()
70        exit_code = process.wait(timeout=3)
71        restored = termios.tcgetattr(slave) == before
72        if exit_code != 0 or not sent or not active_raw or not restored:
73            raise RuntimeError(f"PTY detach failed: key={key!r}, exit={exit_code}, "
74                               f"sent={sent}, raw={active_raw}, restored={restored}")
75        return {"key": "ctrl-c" if key == b"\x03" else "q", "exit_code": exit_code,
76                "terminal_went_raw": active_raw, "terminal_restored": restored,
77                "telemetry_gets": len(paths) - before_count, "terminal_output_bytes": bytes_read}
78    finally:
79        if process is not None and process.poll() is None:
80            process.kill()
81            process.wait(timeout=3)
82        os.close(master)
83        os.close(slave)
84
85
86def smoke(bundle: Path) -> dict:
87    bundle = bundle.resolve(strict=True)
88    server, paths, _ = _server()
89    worker = threading.Thread(target=server.serve_forever, daemon=True)
90    worker.start()
91    try:
92        url = f"http://127.0.0.1:{server.server_port}"
93        cases = [_case(bundle, url, paths, key) for key in (b"q", b"\x03")]
94        with urllib.request.urlopen(url + "/v1/telemetry", timeout=3) as response:
95            server_alive = response.status == 200
96    finally:
97        server.shutdown()
98        server.server_close()
99        worker.join(timeout=3)
100    if not server_alive or any(path not in ("GET /v1/telemetry", "GET /metrics") for path in paths):
101        raise RuntimeError("Monitor detach changed or stopped the telemetry server")
102    return {"schema_version": 1, "scope": "portable_monitor_posix_pty_smoke",
103            "bundle_sha256": hashlib.sha256(bundle.read_bytes()).hexdigest(),
104            "python": platform.python_version(), "platform": platform.platform(),
105            "cases": cases, "server_alive_after_detach": True,
106            "http_gets": len(paths), "other_http_methods": 0, "passed": True}
107
108
109def main() -> int:
110    ap = argparse.ArgumentParser(description=__doc__)
111    ap.add_argument("--bundle", type=Path, required=True)
112    ap.add_argument("--report", type=Path, required=True, help="new absolute JSON report file")
113    args = ap.parse_args()
114    if os.name != "posix":
115        ap.error("this pseudo-terminal check requires a POSIX host")
116    if not args.report.is_absolute() or args.report.exists():
117        ap.error("--report must be a new absolute file path")
118    report = smoke(args.bundle)
119    with args.report.open("x", encoding="utf-8") as stream:
120        json.dump(report, stream, indent=2, sort_keys=True)
121        stream.write("\n")
122    print(json.dumps({"report": str(args.report), "passed": True}))
123    return 0
124
125
126if __name__ == "__main__":
127    raise SystemExit(main())