interplane-forge
INTERPLANE Forge
Brought by drakestapleton
interplane-forge / infra / test / restart-hold.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Requests fired across an automatic restart of the sandboxed forged (a new repository set). |
| 3 | |
| 4 | Usage: restart-hold.py T SERVICE PORT LABEL |
| 5 | T the gate's run directory (T/forged, T/home, T/source) |
| 6 | SERVICE the forged-service.sh to run as the supervisor (this tree's, or the old one as control) |
| 7 | PORT the private port |
| 8 | LABEL names the evidence files T/restart-hold-LABEL.json and the added repository |
| 9 | |
| 10 | Starts the supervisor loop, fires 200 requests for / on fresh connections, one every 40 ms, and |
| 11 | adds a repository to RIDS.md 1 s in, which makes the supervisor restart forged. A monitor samples |
| 12 | every 5 ms whether 127.0.0.1:PORT is in LISTEN state (/proc/net/tcp) and which forged runs. |
| 13 | Prints one summary line and exits 0 when every request got 200, the forged process changed while |
| 14 | the requests were in flight, and the listener was present in every sample; 1 otherwise. |
| 15 | """ |
| 16 | import http.client |
| 17 | import json |
| 18 | import os |
| 19 | from pathlib import Path |
| 20 | import signal |
| 21 | import subprocess |
| 22 | import sys |
| 23 | import threading |
| 24 | import time |
| 25 | |
| 26 | T, SERVICE, PORT, LABEL = Path(sys.argv[1]), sys.argv[2], int(sys.argv[3]), sys.argv[4] |
| 27 | H = T / 'home' |
| 28 | RIDS = H / 'handoffs/radicle/RIDS.md' |
| 29 | RID = 'z631r2JJiVT8it4tST7RK24hpowi' |
| 30 | N, SPACING, TRIGGER = 200, 0.04, 25 |
| 31 | LISTEN = '0100007F:%04X' % PORT |
| 32 | |
| 33 | |
| 34 | def atomic(path, body): |
| 35 | tmp = path.with_name(path.name + '.tmp') |
| 36 | tmp.write_bytes(body) |
| 37 | os.replace(tmp, path) |
| 38 | |
| 39 | |
| 40 | def listening(): |
| 41 | for line in Path('/proc/net/tcp').read_text().splitlines()[1:]: |
| 42 | f = line.split() |
| 43 | if f[1] == LISTEN and f[3] == '0A': |
| 44 | return True |
| 45 | return False |
| 46 | |
| 47 | |
| 48 | def forged(sup): |
| 49 | """The /app/forged process below the supervisor, or None.""" |
| 50 | todo, seen = [sup], [] |
| 51 | while todo: |
| 52 | p = todo.pop() |
| 53 | try: |
| 54 | for t in Path(f'/proc/{p}/task').iterdir(): |
| 55 | todo += [int(c) for c in (t / 'children').read_text().split()] |
| 56 | if p != sup and Path(f'/proc/{p}/cmdline').read_bytes().startswith(b'/app/forged\0'): |
| 57 | seen.append(p) |
| 58 | except (FileNotFoundError, ProcessLookupError, NotADirectoryError): |
| 59 | pass |
| 60 | return seen[0] if seen else None |
| 61 | |
| 62 | |
| 63 | def get(): |
| 64 | try: |
| 65 | c = http.client.HTTPConnection('127.0.0.1', PORT, timeout=30) |
| 66 | c.request('GET', '/') |
| 67 | r = c.getresponse() |
| 68 | r.read() |
| 69 | c.close() |
| 70 | return r.status |
| 71 | except Exception as e: # recorded, counted as a failure |
| 72 | return f'{type(e).__name__}: {e}' |
| 73 | |
| 74 | |
| 75 | env = dict(os.environ, FORGED_BIN=str(T / 'forged'), FORGED_PORT=str(PORT), |
| 76 | FORGED_CPUS=os.environ.get('FORGED_CPUS', '12,13'), FORGED_MIRROR_INTERVAL='1', |
| 77 | FORGED_COUNTS_INTERVAL='1800') |
| 78 | log = (T / f'restart-hold-{LABEL}.process.log').open('wb') |
| 79 | proc = subprocess.Popen(['bash', SERVICE, '_loop'], env=env, stdout=log, stderr=subprocess.STDOUT, |
| 80 | start_new_session=True) |
| 81 | rows, samples, halt = [None] * N, [], threading.Event() |
| 82 | rid = RID + LABEL |
| 83 | try: |
| 84 | deadline = time.monotonic() + 20 |
| 85 | while get() != 200: |
| 86 | if time.monotonic() > deadline or proc.poll() is not None: |
| 87 | print(f'FAIL {LABEL}: the service did not answer 200 within 20 s') |
| 88 | sys.exit(1) |
| 89 | time.sleep(.1) |
| 90 | subprocess.run(['git', 'clone', '-q', '--bare', '--no-hardlinks', str(T / 'source'), |
| 91 | str(H / '.radicle/storage' / rid)], check=True) |
| 92 | |
| 93 | def monitor(): |
| 94 | while not halt.is_set(): |
| 95 | samples.append((time.monotonic_ns(), listening(), forged(proc.pid))) |
| 96 | time.sleep(.005) |
| 97 | |
| 98 | def fire(i): |
| 99 | start = time.monotonic_ns() |
| 100 | status = get() |
| 101 | rows[i] = dict(i=i, start_ns=start, end_ns=time.monotonic_ns(), status=status) |
| 102 | |
| 103 | mon = threading.Thread(target=monitor) |
| 104 | mon.start() |
| 105 | time.sleep(.05) |
| 106 | t0, threads = time.monotonic(), [] |
| 107 | for i in range(N): |
| 108 | delay = t0 + i * SPACING - time.monotonic() |
| 109 | if delay > 0: |
| 110 | time.sleep(delay) |
| 111 | if i == TRIGGER: |
| 112 | atomic(RIDS, RIDS.read_bytes() + f'| hold{LABEL} | rad:{rid} | main | - | - | - |\n'.encode()) |
| 113 | th = threading.Thread(target=fire, args=(i,)) |
| 114 | th.start() |
| 115 | threads.append(th) |
| 116 | for th in threads: |
| 117 | th.join() |
| 118 | time.sleep(.2) |
| 119 | halt.set() |
| 120 | mon.join() |
| 121 | finally: |
| 122 | halt.set() |
| 123 | proc.terminate() |
| 124 | try: |
| 125 | proc.wait(timeout=15) |
| 126 | except subprocess.TimeoutExpired: |
| 127 | os.killpg(proc.pid, signal.SIGKILL) |
| 128 | proc.wait() |
| 129 | log.close() |
| 130 | |
| 131 | first, last = rows[0]['start_ns'], max(r['end_ns'] for r in rows) |
| 132 | window = [s for s in samples if first <= s[0] <= last] |
| 133 | pids = [] |
| 134 | for s in window: |
| 135 | if s[2] is not None and (not pids or pids[-1] != s[2]): |
| 136 | pids.append(s[2]) |
| 137 | nochild = sum(1 for s in window if s[2] is None) |
| 138 | absent = sum(1 for s in window if not s[1]) |
| 139 | ok = sum(1 for r in rows if r['status'] == 200) |
| 140 | failed = [r for r in rows if r['status'] != 200] |
| 141 | lat = sorted(r['end_ns'] - r['start_ns'] for r in rows) |
| 142 | summary = dict(label=LABEL, service=SERVICE, requests=N, ok=ok, failed=len(failed), |
| 143 | forged_processes_in_window=pids, samples=len(window), samples_without_forged=nochild, |
| 144 | samples_without_listener=absent, latency_ns_max=lat[-1], latency_ns_median=lat[N // 2], |
| 145 | failures=failed[:20]) |
| 146 | (T / f'restart-hold-{LABEL}.json').write_text(json.dumps(dict(summary=summary, rows=rows, |
| 147 | samples=window), indent=1) + '\n') |
| 148 | print(json.dumps(summary)) |
| 149 | restarted = len(pids) >= 2 |
| 150 | print(f'{LABEL}: requests {N} ok {ok} failed {len(failed)}; forged processes during the requests ' |
| 151 | f'{len(pids)}; monitor samples {len(window)}, without forged {nochild}, without listener {absent}') |
| 152 | sys.exit(0 if ok == N and restarted and absent == 0 else 1) |