add level 5
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
rule_files:
|
||||
- /workspace/infra/prometheus/alerts.yaml
|
||||
evaluation_interval: 5s
|
||||
tests:
|
||||
- name: healthy
|
||||
interval: 5s
|
||||
input_series:
|
||||
- series: 'messenger_http_requests_total{route="/api/v1/users",status_class="2xx"}'
|
||||
values: '0+100x80'
|
||||
- series: 'messenger_http_requests_total{route="/api/v1/users",status_class="5xx"}'
|
||||
values: '0+0x80'
|
||||
- series: 'messenger_slo_ready_eligible_total{service_name="messenger-outbox"}'
|
||||
values: '0+100x80'
|
||||
- series: 'messenger_slo_ready_bad_total{service_name="messenger-outbox"}'
|
||||
values: '0+0x80'
|
||||
alert_rule_test:
|
||||
- {eval_time: 5m, alertname: MessengerApiBurnFast, exp_alerts: []}
|
||||
- {eval_time: 5m, alertname: MessengerApiBurnSlow, exp_alerts: []}
|
||||
- {eval_time: 5m, alertname: MessengerReadyBurnFast, exp_alerts: []}
|
||||
- {eval_time: 5m, alertname: MessengerReadyBurnSlow, exp_alerts: []}
|
||||
- name: brief severe spike and recovery
|
||||
interval: 5s
|
||||
input_series:
|
||||
- series: 'messenger_http_requests_total{route="/api/v1/users",status_class="2xx"}'
|
||||
values: '0+100x12 1200+0x8 1200+100x60'
|
||||
- series: 'messenger_http_requests_total{route="/api/v1/users",status_class="5xx"}'
|
||||
values: '0+0x12 0+100x8 800+0x60'
|
||||
alert_rule_test:
|
||||
- eval_time: 1m30s
|
||||
alertname: MessengerApiBurnFast
|
||||
exp_alerts:
|
||||
- exp_labels: {severity: critical, slo: api, burn: fast}
|
||||
exp_annotations: {summary: 'api SLO fast burn', runbook: 'See docs/slo-runbook.md'}
|
||||
- {eval_time: 3m, alertname: MessengerApiBurnFast, exp_alerts: []}
|
||||
- name: sustained moderate degradation
|
||||
interval: 5s
|
||||
input_series:
|
||||
- series: 'messenger_http_requests_total{route="/api/v1/users",status_class="2xx"}'
|
||||
values: '0+80x80'
|
||||
- series: 'messenger_http_requests_total{route="/api/v1/users",status_class="5xx"}'
|
||||
values: '0+20x80'
|
||||
- series: 'messenger_slo_ready_eligible_total{service_name="messenger-outbox"}'
|
||||
values: '0+100x80'
|
||||
- series: 'messenger_slo_ready_bad_total{service_name="messenger-outbox"}'
|
||||
values: '0+20x80'
|
||||
alert_rule_test:
|
||||
- {eval_time: 5m, alertname: MessengerApiBurnFast, exp_alerts: []}
|
||||
- {eval_time: 5m, alertname: MessengerReadyBurnFast, exp_alerts: []}
|
||||
- eval_time: 5m
|
||||
alertname: MessengerApiBurnSlow
|
||||
exp_alerts:
|
||||
- exp_labels: {severity: warning, slo: api, burn: slow}
|
||||
exp_annotations: {summary: 'api SLO slow burn', runbook: 'See docs/slo-runbook.md'}
|
||||
- eval_time: 5m
|
||||
alertname: MessengerReadyBurnSlow
|
||||
exp_alerts:
|
||||
- exp_labels: {severity: warning, slo: ready, burn: slow}
|
||||
exp_annotations: {summary: 'ready SLO slow burn', runbook: 'See docs/slo-runbook.md'}
|
||||
- name: low-volume guard
|
||||
interval: 5s
|
||||
input_series:
|
||||
- series: 'messenger_http_requests_total{route="/api/v1/users",status_class="5xx"}'
|
||||
values: '0+1x80'
|
||||
- series: 'messenger_slo_ready_eligible_total{service_name="messenger-outbox"}'
|
||||
values: '0+1x80'
|
||||
- series: 'messenger_slo_ready_bad_total{service_name="messenger-outbox"}'
|
||||
values: '0+1x80'
|
||||
alert_rule_test:
|
||||
- {eval_time: 5m, alertname: MessengerApiBurnFast, exp_alerts: []}
|
||||
- {eval_time: 5m, alertname: MessengerReadyBurnFast, exp_alerts: []}
|
||||
- name: late ready events fast burn
|
||||
interval: 5s
|
||||
input_series:
|
||||
- series: 'messenger_slo_ready_eligible_total{service_name="messenger-outbox"}'
|
||||
values: '0+100x30'
|
||||
- series: 'messenger_slo_ready_bad_total{service_name="messenger-outbox"}'
|
||||
values: '0+100x30'
|
||||
alert_rule_test:
|
||||
- eval_time: 1m
|
||||
alertname: MessengerReadyBurnFast
|
||||
exp_alerts:
|
||||
- exp_labels: {severity: critical, slo: ready, burn: fast}
|
||||
exp_annotations: {summary: 'ready SLO fast burn', runbook: 'See docs/slo-runbook.md'}
|
||||
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Summarize observed alert transitions; sampling bounds detection precision."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
data = json.loads((root / 'evidence/slo-incidents.json').read_text())
|
||||
samples = sorted((s for s in data['samples'] if 'firing' in s), key=lambda s: s['monotonic'])
|
||||
alerts = ['MessengerApiBurnFast', 'MessengerApiBurnSlow']
|
||||
output = {'sampling_interval_seconds': 5, 'monitor_errors': sum('monitor_error' in s for s in data['samples']), 'phases': {}}
|
||||
base = [s for s in samples if s['phase'] == 'baseline']
|
||||
output['baseline'] = {'samples': len(base), 'samples_with_burn_alert': sum(bool(s['firing']) for s in base), 'scope': 'one observed healthy baseline, not a long-term false-positive rate'}
|
||||
for name, period in data['periods'].items():
|
||||
start, end = period['lock_observed']['monotonic'], period['command_completed']['monotonic']
|
||||
active = [s for s in samples if start <= s['monotonic'] <= end]
|
||||
recovery = [s for s in samples if s['monotonic'] > end and s['phase'] == name + '_recovery']
|
||||
previous = [s for s in samples if s['monotonic'] < start]
|
||||
row = {'observed_lock_seconds': round(end-start, 3), 'alerts': {}}
|
||||
for alert in alerts:
|
||||
before = bool(previous and alert in previous[-1]['firing'])
|
||||
hits = [s for s in active + recovery if alert in s['firing']]
|
||||
clear = [s for s in recovery if hits and s['monotonic'] > hits[0]['monotonic'] and alert not in s['firing']]
|
||||
row['alerts'][alert] = {'active_before_lock': before,
|
||||
'first_firing': hits[0]['time'] if hits else None,
|
||||
'first_firing_after_incident': bool(hits and hits[0]['monotonic'] > end),
|
||||
'detection_seconds': round(hits[0]['monotonic']-start, 3) if hits and not before else None,
|
||||
'first_clear': clear[0]['time'] if hits and clear else None,
|
||||
'recovery_seconds': round(clear[0]['monotonic']-end, 3) if hits and clear else None}
|
||||
output['phases'][name] = row
|
||||
path = root / 'evidence/slo-analysis.json'
|
||||
path.write_text(json.dumps(output, ensure_ascii=False, indent=2) + '\n')
|
||||
print(json.dumps(output, ensure_ascii=False, indent=2))
|
||||
@@ -0,0 +1,121 @@
|
||||
#!/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
|
||||
all locks on exit. 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}
|
||||
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)]
|
||||
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')
|
||||
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()
|
||||
@@ -0,0 +1,70 @@
|
||||
#!/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', 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')),
|
||||
'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)
|
||||
deadline=time.monotonic()+100
|
||||
while time.monotonic()<deadline:
|
||||
s=sample('worker_stopped'); samples.append(s)
|
||||
if 'MessengerReadyBurnFast' in s['firing']: break
|
||||
time.sleep(5)
|
||||
else: raise RuntimeError('Ready fast burn did not fire in 100 seconds')
|
||||
docker('start','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']: 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('start','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