spark-supervisor
Process supervisor and health monitor for sovereign daemons
Brought by drakestapleton
spark-supervisor / tests / contract.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Independent Linux/process/HTTP/inotify observer; never used by production binaries. |
| 3 | Run: python3 tests/contract.py [CASE]. Every wait subscribes before inspecting state. |
| 4 | The parent gate supplies an inherited address-space ceiling; services are throwaways only. |
| 5 | """ |
| 6 | import ctypes, os, pathlib, select, shutil, signal, socket, subprocess, sys, tempfile, time |
| 7 | B = pathlib.Path(os.environ.get('SUPERVISE_BIN', pathlib.Path(__file__).resolve().parents[1] / 'out/aien-supervise')).resolve() |
| 8 | CASE = sys.argv[1] if len(sys.argv) > 1 else 'all' |
| 9 | libc = ctypes.CDLL(None, use_errno=True) |
| 10 | libc.inotify_init1.argtypes = [ctypes.c_int] |
| 11 | libc.inotify_add_watch.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_uint32] |
| 12 | |
| 13 | class Trial: |
| 14 | def __init__(self): |
| 15 | self.root = pathlib.Path(tempfile.mkdtemp(prefix='aien-contract.')) |
| 16 | for name in ('state', 'user', 'root'): (self.root / name).mkdir() |
| 17 | self.env = dict(os.environ, AIEN_SUPERVISE_STATE=str(self.root/'state'), AIEN_SUPERVISE_USERDIR=str(self.root/'user'), AIEN_SUPERVISE_ROOTDIR=str(self.root/'root'), PRIVATE_POISON='must-not-leak') |
| 18 | self.env.pop('AIEN_SUPERVISE_CGROUP', None) |
| 19 | self.fd = libc.inotify_init1(os.O_CLOEXEC | os.O_NONBLOCK) |
| 20 | assert self.fd >= 0 |
| 21 | self.watched = set() |
| 22 | self.daemon = None |
| 23 | self.log = open(self.root/'daemon.log', 'wb') |
| 24 | self.refresh() |
| 25 | def refresh(self): |
| 26 | for p in (self.root, self.root/'state', self.root/'user', self.root/'state/st', self.root/'state/log'): |
| 27 | if p.is_dir() and p not in self.watched: |
| 28 | assert libc.inotify_add_watch(self.fd, os.fsencode(p), 0xfff) >= 0 |
| 29 | self.watched.add(p) |
| 30 | def write(self, name, value): |
| 31 | p = self.root/name; p.write_text(value); return p |
| 32 | def svc(self, name, text): return self.write('user/'+name+'.svc', text) |
| 33 | def script(self, name, text): return self.write(name+'.sh', text) |
| 34 | def start(self): self.daemon = subprocess.Popen([str(B), 'run'], env=self.env, stdout=self.log, stderr=self.log) |
| 35 | def state(self, name): |
| 36 | try: return (self.root/'state/st'/name).read_text() |
| 37 | except FileNotFoundError: return '' |
| 38 | def text(self, name): |
| 39 | try: return (self.root/name).read_text() |
| 40 | except FileNotFoundError: return '' |
| 41 | def wait(self, predicate, timeout=12): |
| 42 | deadline = time.monotonic()+timeout |
| 43 | while True: |
| 44 | self.refresh() |
| 45 | if predicate(): return |
| 46 | left = deadline-time.monotonic() |
| 47 | assert left > 0, ('event deadline', str(self.root), self.text('daemon.log')) |
| 48 | ready, _, _ = select.select([self.fd], [], [], left) |
| 49 | assert ready, ('event deadline', str(self.root), self.text('daemon.log')) |
| 50 | try: os.read(self.fd, 65536) |
| 51 | except BlockingIOError: pass |
| 52 | def cmd(self, *args, expected=0): |
| 53 | p = subprocess.run([str(B), *args], env=self.env, capture_output=True, timeout=15) |
| 54 | assert p.returncode == expected, (args, p.returncode, p.stdout, p.stderr) |
| 55 | return p.stdout.decode() |
| 56 | def close(self): |
| 57 | if self.daemon is not None and self.daemon.poll() is None: |
| 58 | self.cmd('shutdown') |
| 59 | assert self.daemon.wait(timeout=15) == 0 |
| 60 | if (self.root/'leader').exists(): |
| 61 | try: os.killpg(int((self.root/'leader').read_text()), signal.SIGKILL) |
| 62 | except ProcessLookupError: pass |
| 63 | self.log.close(); os.close(self.fd) |
| 64 | |
| 65 | |
| 66 | def environment(): |
| 67 | t=Trial() |
| 68 | try: |
| 69 | script=t.script('env', 'env; printf "stderr-record\\n" >&2; exec /usr/bin/sleep 30\n') |
| 70 | t.svc('env', f'exec /usr/bin/sh {script}\nenv DECLARED=yes\nrestart never\n') |
| 71 | t.start(); t.wait(lambda: 'stderr-record' in t.text('state/log/env.log')) |
| 72 | content=t.text('state/log/env.log') |
| 73 | assert 'DECLARED=yes' in content and 'PRIVATE_POISON' not in content and 'HOME=' not in content |
| 74 | print('PASS environment: cleared plus declared, stdout/stderr captured') |
| 75 | finally: t.close() |
| 76 | |
| 77 | |
| 78 | def policies(): |
| 79 | t=Trial() |
| 80 | try: |
| 81 | for name, policy, code in [('always','always',0), ('failure','on-failure',3), ('success','on-failure',0), ('never','never',3)]: |
| 82 | script=t.script(name, f'echo {name}; exit {code}\n') |
| 83 | t.svc(name, f'exec /usr/bin/sh {script}\nrestart {policy}\nbackoff 1 2\n') |
| 84 | t.start() |
| 85 | t.wait(lambda: t.text('daemon.log').count('always exited status=0') >= 4 and t.text('daemon.log').count('failure exited status=3') >= 4) |
| 86 | assert 'runs=1 ' in t.state('success') and 'state=stopped' in t.state('success') |
| 87 | assert 'runs=1 ' in t.state('never') and 'state=failed' in t.state('never') |
| 88 | assert 'next_in_s=4' not in t.text('daemon.log') |
| 89 | print('PASS policies: always, on-failure, never and bounded backoff') |
| 90 | finally: t.close() |
| 91 | |
| 92 | |
| 93 | def order_health(): |
| 94 | t=Trial() |
| 95 | try: |
| 96 | probe=socket.socket(); probe.bind(('127.0.0.1',0)); port=probe.getsockname()[1]; probe.close() |
| 97 | server=t.write('server.py', 'import http.server,pathlib,sys\nclass H(http.server.BaseHTTPRequestHandler):\n def do_GET(self):\n pathlib.Path(sys.argv[2]+".probed").touch()\n self.send_response(200 if pathlib.Path(sys.argv[2]).exists() else 503);self.end_headers()\n def log_message(self,*args):pass\nhttp.server.HTTPServer(("127.0.0.1",int(sys.argv[1])),H).serve_forever()\n') |
| 98 | # The dependent takes 1 s to finish its stop: a supervisor that signals both at once records base first. |
| 99 | dependent=t.script('dependent', f'trap "/usr/bin/sleep 1; echo dependent >> {t.root}/stops; exit 0" TERM\necho dependent-started\nwhile :; do /usr/bin/sleep 30; done\n') |
| 100 | base=t.script('base', f'trap "echo base >> {t.root}/stops; exit 0" TERM\n/usr/bin/python3 {server} {port} {t.root}/ready &\nwait\n') |
| 101 | t.svc('a-dependent', f'exec /usr/bin/sh {dependent}\nafter z-base\nrestart never\nstoptime 2\n') |
| 102 | t.svc('z-base', f'exec /usr/bin/sh {base}\nhealth-http {port} /health\nrestart never\nstoptime 2\n') |
| 103 | t.start(); t.wait(lambda: 'state=running' in t.state('z-base') and (t.root/'ready.probed').exists()) |
| 104 | assert 'state=running' not in t.state('a-dependent'), 'dependent started before HTTP healthy' |
| 105 | t.write('ready', 'ready') |
| 106 | t.wait(lambda: 'dependent-started' in t.text('state/log/a-dependent.log')) |
| 107 | t.wait(lambda: 'healthy=1' in t.state('a-dependent')) |
| 108 | lines=t.cmd('status').splitlines() |
| 109 | assert sum(line.startswith('a-dependent ') for line in lines)==1 |
| 110 | assert sum(line.startswith('z-base ') for line in lines)==1 |
| 111 | t.cmd('shutdown'); assert t.daemon.wait(timeout=15)==0 |
| 112 | assert t.text('stops').splitlines()==['dependent','base'], t.text('stops') |
| 113 | print('PASS order_health: waits for HTTP 200, one status line each, reverse stop') |
| 114 | finally: t.close() |
| 115 | |
| 116 | |
| 117 | def logs_stop(): |
| 118 | t=Trial() |
| 119 | try: |
| 120 | script=t.script('tree', f'trap "" TERM\n/usr/bin/sh -c \'trap "" TERM; echo $$ > {t.root}/grandchild; exec /usr/bin/sleep 60\' &\ni=0; while [ "$i" -lt 700 ]; do echo "stdout-$i-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; echo "stderr-$i-yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy" >&2; i=$((i+1)); done\necho $$ > {t.root}/leader\nwait\n') |
| 121 | t.svc('tree', f'exec /usr/bin/sh {script}\nrestart never\nstoptime 1\nlog-max 1000\nlog-keep 2\n') |
| 122 | t.start(); t.wait(lambda: t.text('leader') and (t.root/'state/log/tree.log.2').exists()) |
| 123 | leader=int(t.text('leader')); grandchild=int(t.text('grandchild')) |
| 124 | t.cmd('stop','tree'); t.wait(lambda: 'last=signal:9' in t.state('tree')) |
| 125 | for pid in (leader,grandchild): |
| 126 | try: state=pathlib.Path(f'/proc/{pid}/stat').read_text().rsplit(')',1)[1].split()[0] |
| 127 | except FileNotFoundError: continue |
| 128 | assert state=='Z', ('surviving process',pid,state) |
| 129 | assert 'tree stop timeout, killing' in t.text('daemon.log') |
| 130 | # Checked after the stop events were logged: event lines obey log-max too. |
| 131 | assert all(p.stat().st_size<=1000 for p in (t.root/'state/log').glob('tree.log*')), [p.stat().st_size for p in (t.root/'state/log').glob('tree.log*')] |
| 132 | print('PASS logs_stop: bounded stdout/stderr rotation, grace then whole-group kill, no live orphan') |
| 133 | finally: t.close() |
| 134 | |
| 135 | |
| 136 | def missing_trigger(): |
| 137 | t=Trial() |
| 138 | try: |
| 139 | t.svc('stable', 'exec /usr/bin/sleep 30\nrestart never\n') |
| 140 | t.start(); t.wait(lambda: 'state=running' in t.state('stable')) |
| 141 | before=t.state('stable') |
| 142 | assert 'change-trigger=MISSING_IMPLEMENTATION' in before |
| 143 | t.svc('stable', 'exec /usr/bin/sleep 60\nrestart never\n') |
| 144 | # Observe a bounded quiet interval. This is an assertion deadline, never a reload timer. |
| 145 | deadline=time.monotonic()+1 |
| 146 | while time.monotonic()<deadline: |
| 147 | select.select([t.fd],[],[],max(0,deadline-time.monotonic())) |
| 148 | try: os.read(t.fd,65536) |
| 149 | except BlockingIOError: pass |
| 150 | assert 'runs=1 ' in t.state('stable') |
| 151 | assert 'pid='+before.split('pid=')[1].split()[0] in t.state('stable') |
| 152 | t.svc('added', 'exec /usr/bin/sleep 30\nrestart never\n') |
| 153 | assert t.state('added')=='' |
| 154 | t.cmd('reload'); t.wait(lambda: 'state=running' in t.state('added')) |
| 155 | assert 'runs=1 ' in t.state('stable') |
| 156 | print('PASS missing_trigger: honest MISSING_IMPLEMENTATION, no polling fallback; explicit reload adds a new file') |
| 157 | finally: t.close() |
| 158 | |
| 159 | |
| 160 | def fail_closed(): |
| 161 | t=Trial() |
| 162 | try: |
| 163 | fake=t.root/'fake'; (fake/'manager').mkdir(parents=True) |
| 164 | (fake/'manager/cgroup.procs').write_text(''); (fake/'manager/cgroup.procs').chmod(0o400) |
| 165 | t.env['AIEN_SUPERVISE_CGROUP']=str(fake) |
| 166 | t.svc('refused','exec /usr/bin/touch '+str(t.root/'must-not-exist')+'\nmemory-max 67108864\n') |
| 167 | t.start(); t.wait(lambda: 'state=error' in t.state('refused')) |
| 168 | assert 'LIMIT_NOT_APPLIED errno=-13' in t.state('refused') |
| 169 | assert not (t.root/'must-not-exist').exists() |
| 170 | p=subprocess.run([str(B),'run-limited','--memory','67108864','--','/usr/bin/touch',str(t.root/'must-not-exist')],env=t.env,capture_output=True,timeout=15) |
| 171 | assert p.returncode==125 and b'LIMIT_NOT_APPLIED' in p.stderr and not (t.root/'must-not-exist').exists(), (p.returncode,p.stderr) |
| 172 | print('PASS fail_closed: refused fake-root writes, service and one-shot never exec') |
| 173 | finally: t.close() |
| 174 | |
| 175 | functions={f.__name__:f for f in (environment,policies,order_health,logs_stop,missing_trigger,fail_closed)} |
| 176 | if CASE=='all': |
| 177 | for f in functions.values(): f() |
| 178 | else: functions[CASE]() |
| 179 | print('CONTRACT PASS cases='+str(len(functions) if CASE=='all' else 1)) |