okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
3fa1b524d
main
1#!/usr/bin/env python3 2"""Build and manage the thin, read-only Strata monitor zipapp. 3 4The bundle contains no engine, model, installer or terminal framework. One-shot 5JSON status uses stdlib only; interactive mode needs the explicit Textual add-on. 6""" 7 8from __future__import annotations 9 10import argparse 11import hashlib 12import json 13import os 14import shutil 15import stat 16import tempfile 17import zipapp 18import zipfile 19from pathlib import Path 20 21 22ROOT = Path (__file__ ).resolve ().parents [1 ] 23SOURCES_V2 = ( 24"strata_cli/__init__.py" , 25"strata_cli/client.py" , 26"strata_cli/connections.py" , 27"strata_cli/render.py" , 28"strata_cli/monitor.py" , 29"strata_cli/monitor_commands.py" , 30"strata_cli/logs.py" , 31) 32SOURCES_V3 = (* SOURCES_V2 ,"strata_cli/dashboard.py" ) 33SOURCES_V4 = (* SOURCES_V3 ,"strata_cli/detail_dashboard.py" ) 34SOURCES_V5 = (* SOURCES_V4 ,"strata_cli/nav.py" )# schema 5: the view tabs every screen shares (strata_cli/nav.py) 35# schema 6: the two modules the interactive Monitor imports at run time (strata_cli/monitor.py, render.py) that earlier lists missed. 36# tests/terminal/test_monitor_bundle.py derives the import closure of the bundle's entry point and fails if this list falls behind. 37SOURCES = (* SOURCES_V5 ,"strata_cli/consoleinfo.py" ,"strata_cli/overview.py" ) 38BOOTSTRAP = b"from strata_cli.monitor_commands import main\nraise SystemExit(main())\n" 39MEMBERS_V1 = ("__main__.py" ,* SOURCES_V2 ) 40LICENSE_NOTICE = "LICENSE" 41MEMBERS_V2 = (* MEMBERS_V1 ,LICENSE_NOTICE ) 42MEMBERS_V3 = (* MEMBERS_V2 ,"strata_cli/dashboard.py" ) 43MEMBERS_V4 = (* MEMBERS_V3 ,"strata_cli/detail_dashboard.py" ) 44MEMBERS_V5 = (* MEMBERS_V4 ,"strata_cli/nav.py" ) 45MEMBERS = (* MEMBERS_V5 ,"strata_cli/consoleinfo.py" ,"strata_cli/overview.py" ) 46COMPATIBILITY = {"python_min" :"3.10" ,"telemetry_schema" : [1 ]} 47MAX_BUNDLE_BYTES = 1024 * 1024 48MAX_MANIFEST_BYTES = 64 * 1024 49MAX_MEMBER_BYTES = 256 * 1024 50 51 52def digest (data :bytes )-> str : 53return hashlib .sha256 (data ).hexdigest () 54 55 56def manifest_path (bundle :Path )-> Path : 57return bundle .with_name (bundle .name + ".manifest.json" ) 58 59 60def build (bundle :Path )-> dict : 61if bundle .exists ()or manifest_path (bundle ).exists (): 62raise FileExistsError ("bundle or manifest already exists; choose a new output path" ) 63bundle .parent .mkdir (parents = True ,exist_ok = True ) 64with tempfile .TemporaryDirectory (prefix = ".strata-monitor-build-" ,dir = bundle .parent )as directory : 65stage = Path (directory )/ "source" 66stage .mkdir () 67 (stage / "__main__.py" ).write_bytes (BOOTSTRAP ) 68for name in SOURCES : 69target = stage / name 70target .parent .mkdir (parents = True ,exist_ok = True ) 71shutil .copyfile (ROOT / name ,target ) 72shutil .copyfile (ROOT / LICENSE_NOTICE ,stage / LICENSE_NOTICE ) 73temp_bundle = Path (directory )/ bundle .name 74zipapp .create_archive (stage ,target = temp_bundle ,interpreter = "/usr/bin/env python3" , 75compressed = True ) 76with zipfile .ZipFile (temp_bundle )as archive : 77names = archive .namelist () 78if set (names )!= set ((* MEMBERS ,"strata_cli/" ))or len (names )!= len (MEMBERS )+ 1 : 79raise ValueError ("bundle member list changed during build" ) 80files = {name :digest (archive .read (name ))for name in MEMBERS } 81report = {"schema_version" :6 ,"kind" :"strata-monitor-bundle" , 82"bundle" :bundle .name ,"sha256" :digest (temp_bundle .read_bytes ()), 83"files" :files ,"interactive_dependency" :"textual==8.2.8" , 84"compatibility" :COMPATIBILITY ,"license" :"MIT" ,"license_file" :LICENSE_NOTICE , 85"publisher_signature" :None } 86temp_manifest = Path (directory )/ manifest_path (bundle ).name 87temp_manifest .write_text (json .dumps (report ,indent = 2 ,sort_keys = True )+ "\n" ) 88os .replace (temp_bundle ,bundle ) 89try : 90os .replace (temp_manifest ,manifest_path (bundle )) 91except OSError : 92bundle .unlink (missing_ok = True ) 93raise 94return report 95 96 97def verify (bundle :Path )-> dict : 98for path ,limit in ((bundle ,MAX_BUNDLE_BYTES ), (manifest_path (bundle ),MAX_MANIFEST_BYTES )): 99if not stat .S_ISREG (path .lstat ().st_mode )or path .stat ().st_size > limit : 100raise ValueError ("bundle and manifest must be bounded regular files" ) 101report = json .loads (manifest_path (bundle ).read_text ()) 102if (not isinstance (report ,dict )or type (report .get ("schema_version" ))is not int or 103report ["schema_version" ]not in (1 ,2 ,3 ,4 ,5 ,6 )or 104report .get ("kind" )!= "strata-monitor-bundle" or 105report .get ("publisher_signature" )is not None or 106report .get ("bundle" )!= bundle .name or report .get ("sha256" )!= digest (bundle .read_bytes ())): 107raise ValueError ("bundle manifest or SHA-256 mismatch" ) 108members = {1 :MEMBERS_V1 ,2 :MEMBERS_V2 ,3 :MEMBERS_V3 ,4 :MEMBERS_V4 , 1095 :MEMBERS_V5 ,6 :MEMBERS }[report ["schema_version" ]] 110if report ["schema_version" ]>= 2 : 111if (report .get ("compatibility" )!= COMPATIBILITY or report .get ("license" )!= "MIT" or 112report .get ("license_file" )!= LICENSE_NOTICE ): 113raise ValueError ("bundle compatibility or license notice mismatch" ) 114with zipfile .ZipFile (bundle )as archive : 115names = archive .namelist () 116if len (names )!= len (members )+ 1 or set (names )!= set ((* members ,"strata_cli/" )): 117raise ValueError ("bundle contains missing, duplicate or unexpected files" ) 118if any (info .flag_bits & 1 for info in archive .infolist ()): 119raise ValueError ("encrypted bundle members are unsupported" ) 120if any (info .file_size > MAX_MEMBER_BYTES for info in archive .infolist ()): 121raise ValueError ("bundle member exceeds the size limit" ) 122if archive .testzip ()is not None : 123raise ValueError ("bundle CRC failure" ) 124files = {name :digest (archive .read (name ))for name in members } 125if report ["schema_version" ]>= 2 and not archive .read (LICENSE_NOTICE ).replace (b"\r\n" ,b"\n" ).startswith (b"MIT License\n" ): 126raise ValueError ("bundle license notice is invalid" ) 127if report .get ("files" )!= files : 128raise ValueError ("bundle member checksum mismatch" ) 129return report 130 131 132def _target (target :Path )-> Path : 133target = target .expanduser () 134if not target .is_absolute ()or target .name in ("" ,"." ,".." ): 135raise ValueError ("install target must be an absolute new directory" ) 136parent = target .parent 137parent_info = parent .lstat () 138if not stat .S_ISDIR (parent_info .st_mode )or \ 139 (os .name == "posix" and (parent_info .st_uid != os .getuid ()or parent_info .st_mode & 0o022 )): 140raise ValueError ("install target parent must be an existing owner-controlled directory" ) 141return target 142 143 144def _present (path :Path )-> bool : 145return path .exists ()or path .is_symlink () 146 147 148def _previous (target :Path )-> Path : 149return target .with_name (target .name + ".previous" ) 150 151 152def _installed (target :Path )-> tuple [Path ,dict ]: 153if not stat .S_ISDIR (target .lstat ().st_mode ): 154raise ValueError ("install target must be a regular directory" ) 155candidates = [path for path in target .iterdir ()if path .name .endswith (".pyz" )] 156if len (candidates )!= 1 : 157raise ValueError ("install target has no unique monitor bundle; inspect it manually" ) 158bundle = candidates [0 ] 159expected = {bundle .name ,manifest_path (bundle ).name } 160if {path .name for path in target .iterdir ()}!= expected : 161raise ValueError ("install target has unexpected or missing files; inspect it manually" ) 162return bundle ,verify (bundle ) 163 164 165def _stage_copy (bundle :Path ,report :dict ,target :Path )-> Path : 166stage = Path (tempfile .mkdtemp (prefix = ".strata-monitor-install-" ,dir = target .parent )) 167try : 168staged_bundle = stage / bundle .name 169shutil .copyfile (bundle ,staged_bundle ,follow_symlinks = False ) 170shutil .copyfile (manifest_path (bundle ),manifest_path (staged_bundle ),follow_symlinks = False ) 171os .chmod (staged_bundle ,0o600 ) 172os .chmod (manifest_path (staged_bundle ),0o600 ) 173if verify (staged_bundle )["sha256" ]!= report ["sha256" ]: 174raise ValueError ("bundle changed during copy" ) 175return stage 176except Exception : 177shutil .rmtree (stage ) 178raise 179 180 181def _remove_install (bundle :Path )-> None : 182manifest_path (bundle ).unlink () 183bundle .unlink () 184bundle .parent .rmdir () 185 186 187def install (bundle :Path ,target :Path ,* ,plan :bool = False , 188if_candidate_sha256 :str | None = None )-> dict : 189"""Copy a verified client into a new directory without touching the server.""" 190report = verify (bundle ) 191target = _target (target ) 192if _present (target )or _present (_previous (target )): 193raise FileExistsError ("install target already exists; choose a new directory" ) 194result = {"target" :str (target ),"sha256" :report ["sha256" ], 195"bundle" :bundle .name ,"would_install" :plan } 196if plan : 197return result 198if if_candidate_sha256 != report ["sha256" ]: 199raise ValueError ("monitor install digest changed or is missing; preview again" ) 200stage = _stage_copy (bundle ,report ,target ) 201try : 202if _present (target )or _present (_previous (target )): 203raise FileExistsError ("install target appeared during copy; inspect it manually" ) 204os .rename (stage ,target ) 205finally : 206if stage .exists (): 207shutil .rmtree (stage ) 208return {** result ,"installed" :True ,"would_install" :False } 209 210 211def update (bundle :Path ,target :Path ,* ,plan :bool = False , 212if_current_sha256 :str | None = None ,if_candidate_sha256 :str | None = None )-> dict : 213"""Promote a verified candidate and retain one verified rollback copy.""" 214target = _target (target ) 215current_bundle ,current = _installed (target ) 216candidate = verify (bundle ) 217previous = _previous (target ) 218if _present (previous ): 219raise FileExistsError ("previous monitor version exists; rollback or commit it before another update" ) 220changed = candidate ["sha256" ]!= current ["sha256" ] 221result = {"target" :str (target ),"previous" :str (previous ), 222"current_sha256" :current ["sha256" ],"candidate_sha256" :candidate ["sha256" ], 223"current_bundle" :current_bundle .name ,"candidate_bundle" :bundle .name , 224"would_update" :plan and changed } 225if plan : 226return result 227if if_current_sha256 != current ["sha256" ]or if_candidate_sha256 != candidate ["sha256" ]: 228raise ValueError ("monitor update digests changed or are missing; preview again" ) 229if not changed : 230return result 231stage = _stage_copy (bundle ,candidate ,target ) 232try : 233if _present (previous ): 234raise FileExistsError ("previous monitor version appeared during copy" ) 235if _installed (target )[1 ]["sha256" ]!= current ["sha256" ]: 236raise ValueError ("active monitor changed during copy; preview again" ) 237os .rename (target ,previous ) 238try : 239os .rename (stage ,target ) 240except OSError as exc : 241try : 242os .rename (previous ,target ) 243except OSError : 244raise OSError (f"monitor update interrupted; inspect { previous } and { target } " )from exc 245raise 246finally : 247if stage .exists (): 248shutil .rmtree (stage ) 249return {** result ,"updated" :True ,"would_update" :False } 250 251 252def rollback (target :Path ,* ,plan :bool = False , 253if_active_sha256 :str | None = None ,if_rollback_sha256 :str | None = None )-> dict : 254"""Exchange the active and previous verified clients without deleting either.""" 255target = _target (target ) 256active_bundle ,active = _installed (target ) 257previous = _previous (target ) 258prior_bundle ,prior = _installed (previous ) 259result = {"target" :str (target ),"previous" :str (previous ), 260"active_sha256" :active ["sha256" ],"rollback_sha256" :prior ["sha256" ], 261"active_bundle" :active_bundle .name ,"rollback_bundle" :prior_bundle .name , 262"would_rollback" :plan } 263if plan : 264return result 265if if_active_sha256 != active ["sha256" ]or if_rollback_sha256 != prior ["sha256" ]: 266raise ValueError ("monitor rollback digests changed or are missing; preview again" ) 267swap = Path (tempfile .mkdtemp (prefix = ".strata-monitor-swap-" ,dir = target .parent )) 268if os .name == "nt" : 269# os.rename onto an existing directory fails on Windows (POSIX replaces an empty one): 270# keep only the unique name mkdtemp reserved. 271swap .rmdir () 272try : 273os .rename (target ,swap ) 274try : 275os .rename (previous ,target ) 276except OSError as exc : 277try : 278os .rename (swap ,target ) 279except OSError : 280raise OSError (f"monitor rollback interrupted; inspect { swap } and { previous } " )from exc 281raise 282try : 283os .rename (swap ,previous ) 284except OSError as exc : 285try : 286os .rename (target ,previous ) 287os .rename (swap ,target ) 288except OSError : 289raise OSError (f"monitor rollback interrupted; inspect { target } , { previous } and { swap } " )from exc 290raise 291finally : 292if swap .is_dir ()and not any (swap .iterdir ()): 293swap .rmdir () 294return {** result ,"rolled_back" :True ,"would_rollback" :False } 295 296 297def commit (target :Path ,* ,plan :bool = False , 298if_active_sha256 :str | None = None ,if_previous_sha256 :str | None = None )-> dict : 299"""Accept the active client and remove its verified rollback copy.""" 300target = _target (target ) 301_ ,active = _installed (target ) 302previous = _previous (target ) 303old_bundle ,old = _installed (previous ) 304result = {"target" :str (target ),"previous" :str (previous ), 305"active_sha256" :active ["sha256" ],"previous_sha256" :old ["sha256" ], 306"would_commit" :plan } 307if plan : 308return result 309if if_active_sha256 != active ["sha256" ]or if_previous_sha256 != old ["sha256" ]: 310raise ValueError ("monitor commit digests changed or are missing; preview again" ) 311_remove_install (old_bundle ) 312return {** result ,"committed" :True ,"would_commit" :False } 313 314 315def uninstall (target :Path ,* ,plan :bool = False , 316if_active_sha256 :str | None = None )-> dict : 317"""Remove only the two verified files installed by this command.""" 318target = _target (target ) 319bundle ,report = _installed (target ) 320if _present (_previous (target )): 321raise ValueError ("previous monitor version exists; commit or rollback it before uninstall" ) 322result = {"target" :str (target ),"sha256" :report ["sha256" ], 323"bundle" :bundle .name ,"would_remove" :plan } 324if plan : 325return result 326if if_active_sha256 != report ["sha256" ]: 327raise ValueError ("monitor uninstall digest changed or is missing; preview again" ) 328_remove_install (bundle ) 329return {** result ,"removed" :True ,"would_remove" :False } 330 331 332def main (argv :list [str ]| None = None )-> int : 333ap = argparse .ArgumentParser (description = "Build or locally manage a thin Strata monitor bundle" ) 334sp = ap .add_subparsers (dest = "action" ,required = True ) 335sp .add_parser ("build" ).add_argument ("bundle" ,type = Path ) 336sp .add_parser ("verify" ).add_argument ("bundle" ,type = Path ) 337install_parser = sp .add_parser ("install" ,help = "copy a verified bundle into a new local directory" ) 338install_parser .add_argument ("bundle" ,type = Path ) 339install_parser .add_argument ("--target" ,type = Path ,required = True ) 340install_parser .add_argument ("--plan" ,action = "store_true" ) 341install_parser .add_argument ("--if-candidate-sha256" ) 342update_parser = sp .add_parser ("update" ,help = "replace a verified monitor and retain one rollback copy" ) 343update_parser .add_argument ("bundle" ,type = Path ) 344update_parser .add_argument ("--target" ,type = Path ,required = True ) 345update_parser .add_argument ("--plan" ,action = "store_true" ) 346update_parser .add_argument ("--if-current-sha256" ) 347update_parser .add_argument ("--if-candidate-sha256" ) 348rollback_parser = sp .add_parser ("rollback" ,help = "exchange active and previous monitor clients" ) 349rollback_parser .add_argument ("--target" ,type = Path ,required = True ) 350rollback_parser .add_argument ("--plan" ,action = "store_true" ) 351rollback_parser .add_argument ("--if-active-sha256" ) 352rollback_parser .add_argument ("--if-rollback-sha256" ) 353commit_parser = sp .add_parser ("commit" ,help = "keep active client and discard previous" ) 354commit_parser .add_argument ("--target" ,type = Path ,required = True ) 355commit_parser .add_argument ("--plan" ,action = "store_true" ) 356commit_parser .add_argument ("--if-active-sha256" ) 357commit_parser .add_argument ("--if-previous-sha256" ) 358uninstall_parser = sp .add_parser ("uninstall" ,help = "remove a verified local monitor installation" ) 359uninstall_parser .add_argument ("--target" ,type = Path ,required = True ) 360uninstall_parser .add_argument ("--plan" ,action = "store_true" ) 361uninstall_parser .add_argument ("--if-active-sha256" ) 362args = ap .parse_args (argv ) 363try : 364if args .action == "build" : 365result = build (args .bundle ) 366elif args .action == "verify" : 367result = verify (args .bundle ) 368elif args .action == "install" : 369result = install (args .bundle ,args .target ,plan = args .plan , 370if_candidate_sha256 = args .if_candidate_sha256 ) 371elif args .action == "update" : 372result = update (args .bundle ,args .target ,plan = args .plan , 373if_current_sha256 = args .if_current_sha256 , 374if_candidate_sha256 = args .if_candidate_sha256 ) 375elif args .action == "rollback" : 376result = rollback (args .target ,plan = args .plan , 377if_active_sha256 = args .if_active_sha256 , 378if_rollback_sha256 = args .if_rollback_sha256 ) 379elif args .action == "commit" : 380result = commit (args .target ,plan = args .plan , 381if_active_sha256 = args .if_active_sha256 , 382if_previous_sha256 = args .if_previous_sha256 ) 383else : 384result = uninstall (args .target ,plan = args .plan , 385if_active_sha256 = args .if_active_sha256 ) 386except (OSError ,ValueError ,zipfile .BadZipFile ,json .JSONDecodeError )as exc : 387ap .exit (1 ,f"monitor bundle { args . action } failed: { exc } \n" ) 388json .dumps ({"ok" :True ,"action" :args .action , 389** ({"bundle" :str (args .bundle ),"files" :len (result ["files" ]), 390"sha256" :result ["sha256" ]} 391if args .action in ("build" ,"verify" )else result )},sort_keys = True )) 392return 0 393 394 395if __name__ == "__main__" : 396raise SystemExit (main ())