okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
3fa1b524d
main
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 : 32master ,slave = pty .openpty () 33process = None 34before_count = len (paths ) 35try : 36fcntl .ioctl (slave ,termios .TIOCSWINSZ ,struct .pack ("HHHH" ,30 ,110 ,0 ,0 )) 37before = termios .tcgetattr (slave ) 38env = os .environ .copy () 39env ["TERM" ]= "xterm-256color" 40process = subprocess .Popen ( 41 [sys .executable ,"-I" ,str (bundle ),"monitor" ,"--url" ,url , 42"--interval" ,"0.5" ,"--glyphs" ,"ascii" ], 43stdin = slave ,stdout = slave ,stderr = slave ,close_fds = True ,env = env ) 44output = bytearray () 45bytes_read = 0 46sent = False 47active_raw = False 48deadline = time .monotonic ()+ 12 49while time .monotonic ()< deadline : 50ready ,_ ,_ = select .select ([master ], [], [],0.1 ) 51if ready : 52try : 53chunk = os .read (master ,65536 ) 54except OSError : 55chunk = b"" 56bytes_read += len (chunk ) 57output .extend (chunk ) 58if len (output )> 65536 : 59del output [:- 65536 ] 60if not sent and len (paths )> before_count and b"STRATA" in output : 61active = termios .tcgetattr (slave ) 62active_raw = not bool (active [3 ]& termios .ICANON )and not bool (active [3 ]& termios .ECHO ) 63if active_raw : 64os .write (master ,key ) 65sent = True 66if process .poll ()is not None : 67break 68if process .poll ()is None : 69process .kill () 70exit_code = process .wait (timeout = 3 ) 71restored = termios .tcgetattr (slave )== before 72if exit_code != 0 or not sent or not active_raw or not restored : 73raise RuntimeError (f"PTY detach failed: key= { key !r } , exit= { exit_code } , " 74f"sent= { sent } , raw= { active_raw } , restored= { restored } " ) 75return {"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 } 78finally : 79if process is not None and process .poll ()is None : 80process .kill () 81process .wait (timeout = 3 ) 82os .close (master ) 83os .close (slave ) 84 85 86def smoke (bundle :Path )-> dict : 87bundle = bundle .resolve (strict = True ) 88server ,paths ,_ = _server () 89worker = threading .Thread (target = server .serve_forever ,daemon = True ) 90worker .start () 91try : 92url = f"http://127.0.0.1: { server . server_port } " 93cases = [_case (bundle ,url ,paths ,key )for key in (b"q" ,b"\x03" )] 94with urllib .request .urlopen (url + "/v1/telemetry" ,timeout = 3 )as response : 95server_alive = response .status == 200 96finally : 97server .shutdown () 98server .server_close () 99worker .join (timeout = 3 ) 100if not server_alive or any (path not in ("GET /v1/telemetry" ,"GET /metrics" )for path in paths ): 101raise RuntimeError ("Monitor detach changed or stopped the telemetry server" ) 102return {"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 : 110ap = argparse .ArgumentParser (description = __doc__ ) 111ap .add_argument ("--bundle" ,type = Path ,required = True ) 112ap .add_argument ("--report" ,type = Path ,required = True ,help = "new absolute JSON report file" ) 113args = ap .parse_args () 114if os .name != "posix" : 115ap .error ("this pseudo-terminal check requires a POSIX host" ) 116if not args .report .is_absolute ()or args .report .exists (): 117ap .error ("--report must be a new absolute file path" ) 118report = smoke (args .bundle ) 119with args .report .open ("x" ,encoding = "utf-8" )as stream : 120json .dump (report ,stream ,indent = 2 ,sort_keys = True ) 121stream .write ("\n" ) 122json .dumps ({"report" :str (args .report ),"passed" :True })) 123return 0 124 125 126if __name__ == "__main__" : 127raise SystemExit (main ())