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
18.5 KiB396 linesraw
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:
53    return hashlib.sha256(data).hexdigest()
54
55
56def manifest_path(bundle: Path) -> Path:
57    return bundle.with_name(bundle.name + ".manifest.json")
58
59
60def build(bundle: Path) -> dict:
61    if bundle.exists() or manifest_path(bundle).exists():
62        raise FileExistsError("bundle or manifest already exists; choose a new output path")
63    bundle.parent.mkdir(parents=True, exist_ok=True)
64    with tempfile.TemporaryDirectory(prefix=".strata-monitor-build-", dir=bundle.parent) as directory:
65        stage = Path(directory) / "source"
66        stage.mkdir()
67        (stage / "__main__.py").write_bytes(BOOTSTRAP)
68        for name in SOURCES:
69            target = stage / name
70            target.parent.mkdir(parents=True, exist_ok=True)
71            shutil.copyfile(ROOT / name, target)
72        shutil.copyfile(ROOT / LICENSE_NOTICE, stage / LICENSE_NOTICE)
73        temp_bundle = Path(directory) / bundle.name
74        zipapp.create_archive(stage, target=temp_bundle, interpreter="/usr/bin/env python3",
75                              compressed=True)
76        with zipfile.ZipFile(temp_bundle) as archive:
77            names = archive.namelist()
78            if set(names) != set((*MEMBERS, "strata_cli/")) or len(names) != len(MEMBERS) + 1:
79                raise ValueError("bundle member list changed during build")
80            files = {name: digest(archive.read(name)) for name in MEMBERS}
81        report = {"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}
86        temp_manifest = Path(directory) / manifest_path(bundle).name
87        temp_manifest.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n")
88        os.replace(temp_bundle, bundle)
89        try:
90            os.replace(temp_manifest, manifest_path(bundle))
91        except OSError:
92            bundle.unlink(missing_ok=True)
93            raise
94    return report
95
96
97def verify(bundle: Path) -> dict:
98    for path, limit in ((bundle, MAX_BUNDLE_BYTES), (manifest_path(bundle), MAX_MANIFEST_BYTES)):
99        if not stat.S_ISREG(path.lstat().st_mode) or path.stat().st_size > limit:
100            raise ValueError("bundle and manifest must be bounded regular files")
101    report = json.loads(manifest_path(bundle).read_text())
102    if (not isinstance(report, dict) or type(report.get("schema_version")) is not int or
103            report["schema_version"] not in (1, 2, 3, 4, 5, 6) or
104            report.get("kind") != "strata-monitor-bundle" or
105            report.get("publisher_signature") is not None or
106            report.get("bundle") != bundle.name or report.get("sha256") != digest(bundle.read_bytes())):
107        raise ValueError("bundle manifest or SHA-256 mismatch")
108    members = {1: MEMBERS_V1, 2: MEMBERS_V2, 3: MEMBERS_V3, 4: MEMBERS_V4,
109               5: MEMBERS_V5, 6: MEMBERS}[report["schema_version"]]
110    if report["schema_version"] >= 2:
111        if (report.get("compatibility") != COMPATIBILITY or report.get("license") != "MIT" or
112                report.get("license_file") != LICENSE_NOTICE):
113            raise ValueError("bundle compatibility or license notice mismatch")
114    with zipfile.ZipFile(bundle) as archive:
115        names = archive.namelist()
116        if len(names) != len(members) + 1 or set(names) != set((*members, "strata_cli/")):
117            raise ValueError("bundle contains missing, duplicate or unexpected files")
118        if any(info.flag_bits & 1 for info in archive.infolist()):
119            raise ValueError("encrypted bundle members are unsupported")
120        if any(info.file_size > MAX_MEMBER_BYTES for info in archive.infolist()):
121            raise ValueError("bundle member exceeds the size limit")
122        if archive.testzip() is not None:
123            raise ValueError("bundle CRC failure")
124        files = {name: digest(archive.read(name)) for name in members}
125        if report["schema_version"] >= 2 and not archive.read(LICENSE_NOTICE).replace(b"\r\n", b"\n").startswith(b"MIT License\n"):
126            raise ValueError("bundle license notice is invalid")
127    if report.get("files") != files:
128        raise ValueError("bundle member checksum mismatch")
129    return report
130
131
132def _target(target: Path) -> Path:
133    target = target.expanduser()
134    if not target.is_absolute() or target.name in ("", ".", ".."):
135        raise ValueError("install target must be an absolute new directory")
136    parent = target.parent
137    parent_info = parent.lstat()
138    if 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)):
140        raise ValueError("install target parent must be an existing owner-controlled directory")
141    return target
142
143
144def _present(path: Path) -> bool:
145    return path.exists() or path.is_symlink()
146
147
148def _previous(target: Path) -> Path:
149    return target.with_name(target.name + ".previous")
150
151
152def _installed(target: Path) -> tuple[Path, dict]:
153    if not stat.S_ISDIR(target.lstat().st_mode):
154        raise ValueError("install target must be a regular directory")
155    candidates = [path for path in target.iterdir() if path.name.endswith(".pyz")]
156    if len(candidates) != 1:
157        raise ValueError("install target has no unique monitor bundle; inspect it manually")
158    bundle = candidates[0]
159    expected = {bundle.name, manifest_path(bundle).name}
160    if {path.name for path in target.iterdir()} != expected:
161        raise ValueError("install target has unexpected or missing files; inspect it manually")
162    return bundle, verify(bundle)
163
164
165def _stage_copy(bundle: Path, report: dict, target: Path) -> Path:
166    stage = Path(tempfile.mkdtemp(prefix=".strata-monitor-install-", dir=target.parent))
167    try:
168        staged_bundle = stage / bundle.name
169        shutil.copyfile(bundle, staged_bundle, follow_symlinks=False)
170        shutil.copyfile(manifest_path(bundle), manifest_path(staged_bundle), follow_symlinks=False)
171        os.chmod(staged_bundle, 0o600)
172        os.chmod(manifest_path(staged_bundle), 0o600)
173        if verify(staged_bundle)["sha256"] != report["sha256"]:
174            raise ValueError("bundle changed during copy")
175        return stage
176    except Exception:
177        shutil.rmtree(stage)
178        raise
179
180
181def _remove_install(bundle: Path) -> None:
182    manifest_path(bundle).unlink()
183    bundle.unlink()
184    bundle.parent.rmdir()
185
186
187def install(bundle: Path, target: Path, *, plan: bool = False,
188            if_candidate_sha256: str | None = None) -> dict:
189    """Copy a verified client into a new directory without touching the server."""
190    report = verify(bundle)
191    target = _target(target)
192    if _present(target) or _present(_previous(target)):
193        raise FileExistsError("install target already exists; choose a new directory")
194    result = {"target": str(target), "sha256": report["sha256"],
195              "bundle": bundle.name, "would_install": plan}
196    if plan:
197        return result
198    if if_candidate_sha256 != report["sha256"]:
199        raise ValueError("monitor install digest changed or is missing; preview again")
200    stage = _stage_copy(bundle, report, target)
201    try:
202        if _present(target) or _present(_previous(target)):
203            raise FileExistsError("install target appeared during copy; inspect it manually")
204        os.rename(stage, target)
205    finally:
206        if stage.exists():
207            shutil.rmtree(stage)
208    return {**result, "installed": True, "would_install": False}
209
210
211def update(bundle: Path, target: Path, *, plan: bool = False,
212           if_current_sha256: str | None = None, if_candidate_sha256: str | None = None) -> dict:
213    """Promote a verified candidate and retain one verified rollback copy."""
214    target = _target(target)
215    current_bundle, current = _installed(target)
216    candidate = verify(bundle)
217    previous = _previous(target)
218    if _present(previous):
219        raise FileExistsError("previous monitor version exists; rollback or commit it before another update")
220    changed = candidate["sha256"] != current["sha256"]
221    result = {"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}
225    if plan:
226        return result
227    if if_current_sha256 != current["sha256"] or if_candidate_sha256 != candidate["sha256"]:
228        raise ValueError("monitor update digests changed or are missing; preview again")
229    if not changed:
230        return result
231    stage = _stage_copy(bundle, candidate, target)
232    try:
233        if _present(previous):
234            raise FileExistsError("previous monitor version appeared during copy")
235        if _installed(target)[1]["sha256"] != current["sha256"]:
236            raise ValueError("active monitor changed during copy; preview again")
237        os.rename(target, previous)
238        try:
239            os.rename(stage, target)
240        except OSError as exc:
241            try:
242                os.rename(previous, target)
243            except OSError:
244                raise OSError(f"monitor update interrupted; inspect {previous} and {target}") from exc
245            raise
246    finally:
247        if stage.exists():
248            shutil.rmtree(stage)
249    return {**result, "updated": True, "would_update": False}
250
251
252def rollback(target: Path, *, plan: bool = False,
253             if_active_sha256: str | None = None, if_rollback_sha256: str | None = None) -> dict:
254    """Exchange the active and previous verified clients without deleting either."""
255    target = _target(target)
256    active_bundle, active = _installed(target)
257    previous = _previous(target)
258    prior_bundle, prior = _installed(previous)
259    result = {"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}
263    if plan:
264        return result
265    if if_active_sha256 != active["sha256"] or if_rollback_sha256 != prior["sha256"]:
266        raise ValueError("monitor rollback digests changed or are missing; preview again")
267    swap = Path(tempfile.mkdtemp(prefix=".strata-monitor-swap-", dir=target.parent))
268    if 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.
271        swap.rmdir()
272    try:
273        os.rename(target, swap)
274        try:
275            os.rename(previous, target)
276        except OSError as exc:
277            try:
278                os.rename(swap, target)
279            except OSError:
280                raise OSError(f"monitor rollback interrupted; inspect {swap} and {previous}") from exc
281            raise
282        try:
283            os.rename(swap, previous)
284        except OSError as exc:
285            try:
286                os.rename(target, previous)
287                os.rename(swap, target)
288            except OSError:
289                raise OSError(f"monitor rollback interrupted; inspect {target}, {previous} and {swap}") from exc
290            raise
291    finally:
292        if swap.is_dir() and not any(swap.iterdir()):
293            swap.rmdir()
294    return {**result, "rolled_back": True, "would_rollback": False}
295
296
297def commit(target: Path, *, plan: bool = False,
298           if_active_sha256: str | None = None, if_previous_sha256: str | None = None) -> dict:
299    """Accept the active client and remove its verified rollback copy."""
300    target = _target(target)
301    _, active = _installed(target)
302    previous = _previous(target)
303    old_bundle, old = _installed(previous)
304    result = {"target": str(target), "previous": str(previous),
305              "active_sha256": active["sha256"], "previous_sha256": old["sha256"],
306              "would_commit": plan}
307    if plan:
308        return result
309    if if_active_sha256 != active["sha256"] or if_previous_sha256 != old["sha256"]:
310        raise ValueError("monitor commit digests changed or are missing; preview again")
311    _remove_install(old_bundle)
312    return {**result, "committed": True, "would_commit": False}
313
314
315def uninstall(target: Path, *, plan: bool = False,
316              if_active_sha256: str | None = None) -> dict:
317    """Remove only the two verified files installed by this command."""
318    target = _target(target)
319    bundle, report = _installed(target)
320    if _present(_previous(target)):
321        raise ValueError("previous monitor version exists; commit or rollback it before uninstall")
322    result = {"target": str(target), "sha256": report["sha256"],
323              "bundle": bundle.name, "would_remove": plan}
324    if plan:
325        return result
326    if if_active_sha256 != report["sha256"]:
327        raise ValueError("monitor uninstall digest changed or is missing; preview again")
328    _remove_install(bundle)
329    return {**result, "removed": True, "would_remove": False}
330
331
332def main(argv: list[str] | None = None) -> int:
333    ap = argparse.ArgumentParser(description="Build or locally manage a thin Strata monitor bundle")
334    sp = ap.add_subparsers(dest="action", required=True)
335    sp.add_parser("build").add_argument("bundle", type=Path)
336    sp.add_parser("verify").add_argument("bundle", type=Path)
337    install_parser = sp.add_parser("install", help="copy a verified bundle into a new local directory")
338    install_parser.add_argument("bundle", type=Path)
339    install_parser.add_argument("--target", type=Path, required=True)
340    install_parser.add_argument("--plan", action="store_true")
341    install_parser.add_argument("--if-candidate-sha256")
342    update_parser = sp.add_parser("update", help="replace a verified monitor and retain one rollback copy")
343    update_parser.add_argument("bundle", type=Path)
344    update_parser.add_argument("--target", type=Path, required=True)
345    update_parser.add_argument("--plan", action="store_true")
346    update_parser.add_argument("--if-current-sha256")
347    update_parser.add_argument("--if-candidate-sha256")
348    rollback_parser = sp.add_parser("rollback", help="exchange active and previous monitor clients")
349    rollback_parser.add_argument("--target", type=Path, required=True)
350    rollback_parser.add_argument("--plan", action="store_true")
351    rollback_parser.add_argument("--if-active-sha256")
352    rollback_parser.add_argument("--if-rollback-sha256")
353    commit_parser = sp.add_parser("commit", help="keep active client and discard previous")
354    commit_parser.add_argument("--target", type=Path, required=True)
355    commit_parser.add_argument("--plan", action="store_true")
356    commit_parser.add_argument("--if-active-sha256")
357    commit_parser.add_argument("--if-previous-sha256")
358    uninstall_parser = sp.add_parser("uninstall", help="remove a verified local monitor installation")
359    uninstall_parser.add_argument("--target", type=Path, required=True)
360    uninstall_parser.add_argument("--plan", action="store_true")
361    uninstall_parser.add_argument("--if-active-sha256")
362    args = ap.parse_args(argv)
363    try:
364        if args.action == "build":
365            result = build(args.bundle)
366        elif args.action == "verify":
367            result = verify(args.bundle)
368        elif args.action == "install":
369            result = install(args.bundle, args.target, plan=args.plan,
370                             if_candidate_sha256=args.if_candidate_sha256)
371        elif args.action == "update":
372            result = update(args.bundle, args.target, plan=args.plan,
373                            if_current_sha256=args.if_current_sha256,
374                            if_candidate_sha256=args.if_candidate_sha256)
375        elif args.action == "rollback":
376            result = rollback(args.target, plan=args.plan,
377                              if_active_sha256=args.if_active_sha256,
378                              if_rollback_sha256=args.if_rollback_sha256)
379        elif args.action == "commit":
380            result = commit(args.target, plan=args.plan,
381                            if_active_sha256=args.if_active_sha256,
382                            if_previous_sha256=args.if_previous_sha256)
383        else:
384            result = uninstall(args.target, plan=args.plan,
385                               if_active_sha256=args.if_active_sha256)
386    except (OSError, ValueError, zipfile.BadZipFile, json.JSONDecodeError) as exc:
387        ap.exit(1, f"monitor bundle {args.action} failed: {exc}\n")
388    print(json.dumps({"ok": True, "action": args.action,
389                      **({"bundle": str(args.bundle), "files": len(result["files"]),
390                          "sha256": result["sha256"]}
391                         if args.action in ("build", "verify") else result)}, sort_keys=True))
392    return 0
393
394
395if __name__ == "__main__":
396    raise SystemExit(main())