#!/usr/bin/env python3 """Run two bounded DB-lock incidents against the local Compose project. Creates synthetic data, records only aggregate counts/alert states, and releases bounded locks; interrupted server-side sleeps may persist until their deadline. Run on the isolated lab6 stack, never a shared database. """ import base64 from concurrent.futures import ThreadPoolExecutor from datetime import datetime, timezone import json from pathlib import Path import subprocess import sys import threading import time import urllib.parse import urllib.request ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / 'tests')) from client import Client, Failure OUTPUT = ROOT / 'evidence' / 'slo-incidents.json' STOP = threading.Event() LOCK = threading.Lock() COUNTS = {'ok': 0, 'failed': 0} SCENARIO = {'phase': 'bootstrap'} SAMPLES = [] AUTH = 'Basic ' + base64.b64encode(('admin:' + (ROOT / 'secrets/grafana_password').read_text().strip()).encode()).decode() def utc(): return datetime.now(timezone.utc).isoformat() def get(path, params=None): url = 'http://127.0.0.1:3000/api/datasources/proxy/uid/prometheus/api/v1/' + path if params: url += '?' + urllib.parse.urlencode(params) with urllib.request.urlopen(urllib.request.Request(url, headers={'Authorization': AUTH}), timeout=5) as response: result = json.load(response) if result.get('status') != 'success': raise RuntimeError('Prometheus query failed') return result['data'] def monitor(): while not STOP.is_set(): try: alerts = get('alerts')['alerts'] firing = sorted(a['labels']['alertname'] for a in alerts if a['state'] == 'firing' and 'Burn' in a['labels']['alertname']) with LOCK: sample = {'time': utc(), 'monotonic': time.monotonic(), 'phase': SCENARIO['phase'], 'counts': dict(COUNTS), 'firing': firing, 'all_firing': sorted(a['labels']['alertname'] for a in alerts if a['state'] == 'firing')} SAMPLES.append(sample) except Exception as error: SAMPLES.append({'time': utc(), 'monotonic': time.monotonic(), 'phase': SCENARIO['phase'], 'monitor_error': type(error).__name__}) STOP.wait(5) def worker(actor, chat): client = Client(timeout=9) while not STOP.is_set(): try: client.message(actor, chat, 'synthetic SLO experiment') outcome = 'ok' except Failure: outcome = 'failed' with LOCK: COUNTS[outcome] += 1 STOP.wait(1) def phase(name): with LOCK: SCENARIO['phase'] = name print(utc(), name, flush=True) def db_is_locked(): result = subprocess.run(['docker','compose','exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atc', "SELECT EXISTS (SELECT 1 FROM pg_locks WHERE relation='users'::regclass AND mode='AccessExclusiveLock' AND granted)"], cwd=ROOT, capture_output=True, text=True, timeout=10, check=True) return result.stdout.strip() == 't' def incident(name, seconds): cmd = ['docker','compose','exec','-T','postgres','psql','-U','messenger','-d','messenger','-c', f'BEGIN; LOCK TABLE users IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep({seconds}); COMMIT;'] start_command = {'time': utc(), 'monotonic': time.monotonic()} proc = subprocess.Popen(cmd, cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) try: deadline = time.monotonic() + 15 while time.monotonic() < deadline: if proc.poll() is not None: raise RuntimeError('DB lock command ended early') if db_is_locked(): break time.sleep(.5) else: raise RuntimeError('DB lock was not observed') phase(name) start = {'time': utc(), 'monotonic': time.monotonic(), 'command_started': start_command} code = proc.wait(timeout=seconds+20) if code: raise RuntimeError('DB lock command failed') end = {'time': utc(), 'monotonic': time.monotonic()} phase(name + '_recovery') return {'lock_observed': start, 'command_completed': end} finally: if proc.poll() is None: proc.terminate() try: proc.wait(timeout=5) except subprocess.TimeoutExpired: proc.kill(); proc.wait() def main(): client = Client(timeout=9) actor, _, _, chat = client.bootstrap() result = {'description': 'controlled DB table lock; three synthetic clients; 5s alert sampling', 'periods': {}, 'samples': SAMPLES} monitor_thread = threading.Thread(target=monitor, daemon=True); monitor_thread.start() try: with ThreadPoolExecutor(max_workers=3) as pool: futures = [pool.submit(worker, actor, chat) for _ in range(3)] try: phase('baseline'); time.sleep(60) result['periods']['burst'] = incident('burst', 75) time.sleep(100) result['periods']['sustained'] = incident('sustained', 180) time.sleep(100) phase('complete') finally: STOP.set() for future in futures: future.result(timeout=15) finally: STOP.set(); monitor_thread.join(timeout=10) result['end_time'] = utc() result['final_counts'] = COUNTS OUTPUT.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n') print('Aggregate evidence:', OUTPUT, flush=True) if __name__ == '__main__': main()