interplane.Get Omega
Read in your language

interplane-forge

INTERPLANE Forge

Brought by drakestapleton

branch main Branches Tags History

interplane-forge / infra / test / restart-hold.py

152 lines · 5749 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Requests fired across an automatic restart of the sandboxed forged (a new repository set).
3
4Usage: 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
10Starts the supervisor loop, fires 200 requests for / on fresh connections, one every 40 ms, and
11adds a repository to RIDS.md 1 s in, which makes the supervisor restart forged. A monitor samples
12every 5 ms whether 127.0.0.1:PORT is in LISTEN state (/proc/net/tcp) and which forged runs.
13Prints one summary line and exits 0 when every request got 200, the forged process changed while
14the requests were in flight, and the listener was present in every sample; 1 otherwise.
15"""
16import http.client
17import json
18import os
19from pathlib import Path
20import signal
21import subprocess
22import sys
23import threading
24import time
25
26T, SERVICE, PORT, LABEL = Path(sys.argv[1]), sys.argv[2], int(sys.argv[3]), sys.argv[4]
27H = T / 'home'
28RIDS = H / 'handoffs/radicle/RIDS.md'
29RID = 'z631r2JJiVT8it4tST7RK24hpowi'
30N, SPACING, TRIGGER = 200, 0.04, 25
31LISTEN = '0100007F:%04X' % PORT
32
33
34def atomic(path, body):
35 tmp = path.with_name(path.name + '.tmp')
36 tmp.write_bytes(body)
37 os.replace(tmp, path)
38
39
40def 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
48def 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
63def 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
75env = 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')
78log = (T / f'restart-hold-{LABEL}.process.log').open('wb')
79proc = subprocess.Popen(['bash', SERVICE, '_loop'], env=env, stdout=log, stderr=subprocess.STDOUT,
80 start_new_session=True)
81rows, samples, halt = [None] * N, [], threading.Event()
82rid = RID + LABEL
83try:
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()
121finally:
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
131first, last = rows[0]['start_ns'], max(r['end_ns'] for r in rows)
132window = [s for s in samples if first <= s[0] <= last]
133pids = []
134for s in window:
135 if s[2] is not None and (not pids or pids[-1] != s[2]):
136 pids.append(s[2])
137nochild = sum(1 for s in window if s[2] is None)
138absent = sum(1 for s in window if not s[1])
139ok = sum(1 for r in rows if r['status'] == 200)
140failed = [r for r in rows if r['status'] != 200]
141lat = sorted(r['end_ns'] - r['start_ns'] for r in rows)
142summary = 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')
148print(json.dumps(summary))
149restarted = len(pids) >= 2
150print(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}')
152sys.exit(0 if ok == N and restarted and absent == 0 else 1)