add lab6
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Stop only this project's idle worker, submit 8 jobs, verify ready SLO."""
|
||||
import base64
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
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
|
||||
|
||||
secret = (ROOT / 'secrets/grafana_password').read_text().strip()
|
||||
auth = 'Basic ' + base64.b64encode(('admin:' + secret).encode()).decode()
|
||||
def utc(): return datetime.now(timezone.utc).isoformat()
|
||||
def prom(path, query=None):
|
||||
url = 'http://127.0.0.1:3000/api/datasources/proxy/uid/prometheus/api/v1/' + path
|
||||
if query is not None: url += '?' + urllib.parse.urlencode({'query': query})
|
||||
with urllib.request.urlopen(urllib.request.Request(url, headers={'Authorization': auth}), timeout=5) as r: return json.load(r)['data']
|
||||
def metric(name):
|
||||
result = prom('query', 'max(' + name + '{service_name="messenger-outbox"})')['result']
|
||||
return float(result[0]['value'][1]) if result else None
|
||||
def sample(phase):
|
||||
alerts = prom('alerts')['alerts']
|
||||
return {'time': utc(), 'monotonic': time.monotonic(), 'phase': phase,
|
||||
'firing': sorted(a['labels']['alertname'] for a in alerts if a['state']=='firing' and a['labels']['alertname'].startswith('MessengerReadyBurn')),
|
||||
'all_firing': sorted(a['labels']['alertname'] for a in alerts if a['state']=='firing'),
|
||||
'queue_depth': metric('messenger_queue_depth'), 'queue_age': metric('messenger_queue_age_seconds'),
|
||||
'eligible': metric('messenger_slo_ready_eligible_total'), 'bad': metric('messenger_slo_ready_bad_total')}
|
||||
def docker(*args): subprocess.run(['docker','compose',*args], cwd=ROOT, check=True, stdout=subprocess.DEVNULL)
|
||||
def run():
|
||||
status = subprocess.run(['docker','compose','exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atc',
|
||||
"SELECT count(*) FROM attachment_jobs WHERE status IN ('queued','processing')"], cwd=ROOT, check=True, capture_output=True, text=True)
|
||||
if int(status.stdout.strip()): raise RuntimeError('Pending jobs exist; refusing to stop worker')
|
||||
client=Client(); actor,_,_,chat=client.bootstrap(); samples=[]; out={'samples':samples,'jobs':8}
|
||||
worker_stopped=False
|
||||
try:
|
||||
samples.append(sample('baseline'))
|
||||
docker('stop','-t','5','worker'); worker_stopped=True
|
||||
accepted=[]
|
||||
for _ in range(8): accepted.append(client.attachment(actor,chat)[0])
|
||||
out['accepted_at']={'time':utc(),'monotonic':time.monotonic()}
|
||||
print('8 synthetic jobs accepted; waiting for burn alert', flush=True)
|
||||
seen=set()
|
||||
deadline=time.monotonic()+100
|
||||
while time.monotonic()<deadline:
|
||||
s=sample('worker_stopped'); samples.append(s)
|
||||
seen.update(s['all_firing'])
|
||||
if {'MessengerReadyBurnFast','MessengerQueueLag'} <= seen: break
|
||||
time.sleep(5)
|
||||
else: raise RuntimeError('Both ready fast burn and QueueLag were not observed in 100 seconds')
|
||||
docker('up','-d','--no-deps','worker'); worker_stopped=False
|
||||
out['worker_started']={'time':utc(),'monotonic':time.monotonic()}
|
||||
for att in accepted: client.wait_ready(actor,att,wait_seconds=90)
|
||||
out['all_ready']={'time':utc(),'monotonic':time.monotonic()}
|
||||
print('all jobs ready; waiting for alert to clear', flush=True)
|
||||
deadline=time.monotonic()+100
|
||||
while time.monotonic()<deadline:
|
||||
s=sample('recovery');samples.append(s)
|
||||
if not s['firing'] and 'MessengerQueueLag' not in s['all_firing']: break
|
||||
time.sleep(5)
|
||||
else: raise RuntimeError('Ready burn alert did not clear in 100 seconds')
|
||||
out['result']='PASS'
|
||||
finally:
|
||||
if worker_stopped:
|
||||
try: docker('up','-d','--no-deps','worker')
|
||||
except Exception: out['worker_restore_failed']=True
|
||||
(ROOT/'evidence/slo-ready-incident.json').write_text(json.dumps(out,ensure_ascii=False,indent=2)+'\n')
|
||||
print('PASS: ready SLO incident; evidence/slo-ready-incident.json',flush=True)
|
||||
if __name__=='__main__':run()
|
||||
Reference in New Issue
Block a user