okami.mom/strata

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

Niko1221merge f-split into f-split-s6326e39118

main
3.9 KiB86 linesraw
1#!/usr/bin/env python3
2"""A real ssh disconnect ends the server and its engine on a Linux box.
3
4    python tests/terminal/ssh_disconnect.py --host p2003ssh.claryel.space --src /data/split-life/src --python /data/venv/bin/python
5
6Runs from any machine with ssh: it starts `strata serve` on the box in an `ssh -tt` session (a pty, like an interactive
7login), kills the LOCAL ssh client (the connection drops, sshd hangs up the pty), and then checks on the box that the
8server and the fake engine are gone, the port is free and the lease is free. The engine is the fake package of
9lifecycle_matrix.py (no GPU, no model). It prints one line, `PASS ssh-disconnect ...` or `FAIL ...`, and exits 0/1.
10"""
11import argparse
12import json
13import subprocess
14import sys
15import time
16
17REMOTE_RIG = r'''
18import json, sys
19sys.path.insert(0, "%(src)s")
20from pathlib import Path
21from tests.terminal import lifecycle_matrix as m
22root = Path("/data/split-life/sshrig"); import shutil; shutil.rmtree(root, ignore_errors=True); root.mkdir(parents=True)
23rig = m.Rig(root)
24print(json.dumps({"argv": rig.serve_argv(), "env": {k: v for k, v in rig.env.items() if k.startswith(("STRATA_", "FAKE_", "XDG_", "LOCALAPPDATA", "PYTHONPATH"))}, "port": rig.port}))
25'''
26
27REMOTE_STATE = r'''
28import json, os, socket, sys
29sys.path.insert(0, "%(src)s")
30os.environ.update(json.loads(%(env)r))
31from strata_control import procs, runtime
32port = %(port)d
33left = [r for r in procs.records() if procs.start_token(r["pid"]) == r["token"]]
34import psutil
35fam = [p.pid for p in psutil.process_iter(["cmdline"]) if any("sshrig" in c or "serve.server" in c or "strata.py" in c for c in (p.info["cmdline"] or [])) and p.pid != os.getpid()]
36with socket.socket() as s:
37    s.settimeout(0.5); open_ = s.connect_ex(("127.0.0.1", port)) == 0
38try:
39    fd = runtime.acquire_activity_lease(shared=False); runtime._unlock_file(fd); os.close(fd); lease = True
40except Exception:
41    lease = False
42print(json.dumps({"records_alive": [r["pid"] for r in left], "processes": fam, "port_open": open_, "lease_free": lease}))
43'''
44
45
46def ssh(host, *args, stdin=None, timeout=120):
47    return subprocess.run(["ssh", "-o", "ConnectTimeout=30", host, *args], input=stdin, capture_output=True, text=True, timeout=timeout)
48
49
50def main():
51    ap = argparse.ArgumentParser()
52    ap.add_argument("--host", required=True)
53    ap.add_argument("--src", required=True)
54    ap.add_argument("--python", default="python3")
55    a = ap.parse_args()
56    rig = json.loads(ssh(a.host, a.python, "-", stdin=REMOTE_RIG % {"src": a.src}).stdout.strip().splitlines()[-1])
57    env = " ".join(f"{k}='{v}'" for k, v in rig["env"].items())
58    remote = f"cd {a.src} && env {env} {a.python} " + " ".join(rig["argv"][1:])
59    client = subprocess.Popen(["ssh", "-tt", "-o", "ConnectTimeout=30", a.host, remote], stdin=subprocess.PIPE,
60                              stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
61    ready = False
62    for _ in range(120):
63        probe = ssh(a.host, f"curl -s -o /dev/null -w '%{{http_code}}' http://127.0.0.1:{rig['port']}/health")
64        if probe.stdout.strip() == "200":
65            ready = True
66            break
67        time.sleep(1)
68    if not ready:
69        client.kill()
70        print("FAIL ssh-disconnect: the server did not come up")
71        return 1
72    client.kill()                                       # the connection drops; sshd hangs up the pty
73    client.wait(timeout=10)
74    state = {}
75    for _ in range(40):
76        time.sleep(1)
77        state = json.loads(ssh(a.host, a.python, "-", stdin=REMOTE_STATE % {"src": a.src, "env": json.dumps(rig["env"]), "port": rig["port"]}).stdout.strip().splitlines()[-1])
78        if not state["records_alive"] and not state["processes"] and not state["port_open"] and state["lease_free"]:
79            print("PASS ssh-disconnect", json.dumps(state))
80            return 0
81    print("FAIL ssh-disconnect", json.dumps(state))
82    return 1
83
84
85if __name__ == "__main__":
86    sys.exit(main())