forked from mtusi2026/mtusi2026lab6
lab6
This commit is contained in:
Executable
+46
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Scan committed evidence for credentials, signed URLs and raw identifiers."""
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PATTERNS = {
|
||||
'aws signature': re.compile(r'X-Amz-(?:Signature|Credential|Security-Token)='),
|
||||
'inline password': re.compile(r'(?i)(password|passwd|secret|token)\s*[=:]\s*["\']?[^\s"\']{6,}'),
|
||||
'url credentials': re.compile(r'://[^/\s:@]+:[^@\s]+@'),
|
||||
'private key': re.compile(r'BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY'),
|
||||
'bearer token': re.compile(r'Bearer\s+[A-Za-z0-9._-]{20,}'),
|
||||
}
|
||||
ALLOW = {
|
||||
'PASSWORD=messenger',
|
||||
'PASSWORD=messenger',
|
||||
'password: messenger',
|
||||
'POSTGRES_PASSWORD: messenger',
|
||||
}
|
||||
|
||||
def main():
|
||||
failures = []
|
||||
for path in (ROOT / 'evidence').rglob('*'):
|
||||
if not path.is_file() or path.suffix in {'.png', '.jpg', '.jpeg', '.webp'}:
|
||||
continue
|
||||
try:
|
||||
text = path.read_text(errors='replace')
|
||||
except OSError:
|
||||
continue
|
||||
for name, pattern in PATTERNS.items():
|
||||
for match in pattern.finditer(text):
|
||||
line = text[text.rfind('\n', 0, match.start()) + 1:text.find('\n', match.end())].strip()
|
||||
if any(allowed in line for allowed in ALLOW):
|
||||
continue
|
||||
failures.append(f'{path.relative_to(ROOT)}: {name}: {line[:160]}')
|
||||
if failures:
|
||||
print('FAIL: evidence scanner found possible secrets/signatures')
|
||||
for item in failures:
|
||||
print(' ', item)
|
||||
return 1
|
||||
print('PASS: evidence has no obvious secrets, signed URLs or bearer tokens')
|
||||
return 0
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
mkdir -p "$ROOT_DIR/secrets"
|
||||
if [ ! -s "$ROOT_DIR/secrets/grafana.env" ]; then
|
||||
(umask 077; printf 'GF_SECURITY_ADMIN_PASSWORD=%s\n' "$(openssl rand -hex 16)" > "$ROOT_DIR/secrets/grafana.env")
|
||||
echo "created secrets/grafana.env"
|
||||
fi
|
||||
Executable
+72
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Poll Prometheus alert state and write a firing/resolved timeline."""
|
||||
import argparse
|
||||
import os
|
||||
import csv
|
||||
import json
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
# The lab tools always target loopback; ignore ambient corporate proxies.
|
||||
for _proxy_key in ('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy'):
|
||||
os.environ.pop(_proxy_key, None)
|
||||
os.environ['NO_PROXY'] = 'localhost,127.0.0.1,::1'
|
||||
os.environ['no_proxy'] = 'localhost,127.0.0.1,::1'
|
||||
urllib.request.getproxies = lambda: {}
|
||||
|
||||
|
||||
def get(url):
|
||||
with urllib.request.urlopen(url, timeout=5) as response:
|
||||
return json.loads(response.read())
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Poll Prometheus alerts')
|
||||
parser.add_argument('--prometheus', default='http://localhost:9090')
|
||||
parser.add_argument('--duration', type=float, default=600)
|
||||
parser.add_argument('--interval', type=float, default=5)
|
||||
parser.add_argument('--output', default='evidence/lab6/alerts.csv')
|
||||
parser.add_argument('--injection-utc', default='')
|
||||
args = parser.parse_args()
|
||||
path = Path(args.output)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
started = time.time()
|
||||
active = set()
|
||||
had_error = False
|
||||
with path.open('w', newline='') as handle:
|
||||
writer = csv.writer(handle)
|
||||
writer.writerow(['observed_utc', 'alert', 'state', 'active_at', 'value', 'injection_utc'])
|
||||
while time.time() - started < args.duration:
|
||||
try:
|
||||
payload = get(args.prometheus.rstrip('/') + '/api/v1/alerts')
|
||||
current = set()
|
||||
for alert in payload.get('data', {}).get('alerts', []):
|
||||
name = alert.get('labels', {}).get('alertname', '')
|
||||
state = alert.get('state', '')
|
||||
current.add((name, state))
|
||||
if (name, state) not in active:
|
||||
writer.writerow([
|
||||
time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
|
||||
name, state, alert.get('activeAt', ''),
|
||||
json.dumps(alert.get('value', ''), separators=(',', ':')), args.injection_utc,
|
||||
])
|
||||
for name, state in sorted(active - current):
|
||||
writer.writerow([
|
||||
time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
|
||||
name, 'resolved', '', '', args.injection_utc,
|
||||
])
|
||||
active = current
|
||||
handle.flush()
|
||||
except Exception as exc:
|
||||
had_error = True
|
||||
print('WARN: alert poll failed:', exc)
|
||||
time.sleep(args.interval)
|
||||
print('alert timeline:', path)
|
||||
return 1 if had_error else 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
Executable
+169
@@ -0,0 +1,169 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Open-loop lab6 load: fixed arrival rate, messages and attachment uploads.
|
||||
|
||||
Unlike tests/load.py this schedules arrivals instead of running a closed loop,
|
||||
so a degraded server cannot reduce the offered rate. It is intentionally small
|
||||
and standard-library only; use k6/wrk2 for capacity claims.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import os
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
# The lab tools always target loopback; ignore ambient corporate proxies.
|
||||
for _proxy_key in ('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy'):
|
||||
os.environ.pop(_proxy_key, None)
|
||||
os.environ['NO_PROXY'] = 'localhost,127.0.0.1,::1'
|
||||
os.environ['no_proxy'] = 'localhost,127.0.0.1,::1'
|
||||
urllib.request.getproxies = lambda: {}
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
|
||||
|
||||
def percentile(values, p):
|
||||
if not values:
|
||||
return None
|
||||
values = sorted(values)
|
||||
rank = max(0, min(len(values) - 1, int(math.ceil(p / 100.0 * len(values))) - 1))
|
||||
return values[rank]
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Open-loop lab6 load')
|
||||
parser.add_argument('--base-url', default='http://localhost:8080')
|
||||
parser.add_argument('--rate', type=float, default=1.0, help='arrivals per second')
|
||||
parser.add_argument('--duration', type=float, default=60.0, help='seconds')
|
||||
parser.add_argument('--upload-ratio', type=float, default=0.25)
|
||||
parser.add_argument('--deadline', type=float, default=10.0)
|
||||
parser.add_argument('--workers', type=int, default=32)
|
||||
parser.add_argument('--output', default=None)
|
||||
parser.add_argument('--token-refresh-seconds', type=float, default=3000.0)
|
||||
args = parser.parse_args()
|
||||
|
||||
from client import Client, Failure
|
||||
bootstrap = Client(args.base_url, timeout=args.deadline)
|
||||
alice, _, _, chat = bootstrap.bootstrap()
|
||||
|
||||
lock = threading.Lock()
|
||||
token_lock = threading.Lock()
|
||||
last_refresh = [time.monotonic()]
|
||||
|
||||
def refresh_session():
|
||||
# Sessions live one hour; refresh well before expiry so a 70m warmup
|
||||
# does not turn into 401s halfway through.
|
||||
if time.monotonic() - last_refresh[0] < args.token_refresh_seconds:
|
||||
return
|
||||
with token_lock:
|
||||
if time.monotonic() - last_refresh[0] < args.token_refresh_seconds:
|
||||
return
|
||||
registration = alice['registration']
|
||||
credential = base64.b64encode(
|
||||
(registration['username'] + ':' + registration['password']).encode()).decode()
|
||||
refresher = Client(args.base_url, timeout=args.deadline)
|
||||
session = refresher.call(
|
||||
'POST', '/api/v1/auth/sessions', 201,
|
||||
headers={'Authorization': 'Basic ' + credential}, schema='Session')['json']
|
||||
alice['token'] = session['token']
|
||||
last_refresh[0] = time.monotonic()
|
||||
latencies, ttr, failures = [], [], []
|
||||
counters = {'accepted': 0, 'ready': 0, 'failed': 0, 'messages': 0, 'uploads': 0, 'dropped': 0}
|
||||
sem = threading.Semaphore(args.workers)
|
||||
|
||||
def record(kind, elapsed, ok, detail=''):
|
||||
with lock:
|
||||
if kind == 'message':
|
||||
counters['messages'] += 1
|
||||
if ok:
|
||||
latencies.append(elapsed)
|
||||
else:
|
||||
counters['failed'] += 1
|
||||
failures.append(detail)
|
||||
else:
|
||||
if ok:
|
||||
counters['ready'] += 1
|
||||
ttr.append(elapsed)
|
||||
else:
|
||||
counters['failed'] += 1
|
||||
failures.append(detail)
|
||||
|
||||
def run_one(kind, index):
|
||||
client = Client(args.base_url, timeout=args.deadline)
|
||||
started = time.monotonic()
|
||||
try:
|
||||
refresh_session()
|
||||
if kind == 'message':
|
||||
client.message(alice, chat, 'lab6 load %d %s' % (index, uuid.uuid4().hex[:8]))
|
||||
record(kind, time.monotonic() - started, True)
|
||||
else:
|
||||
att, _ = client.attachment(alice, chat)
|
||||
with lock:
|
||||
counters['uploads'] += 1
|
||||
counters['accepted'] += 1
|
||||
try:
|
||||
client.wait_ready(alice, att, wait_seconds=args.deadline)
|
||||
record(kind, time.monotonic() - started, True)
|
||||
except Exception as exc:
|
||||
with lock:
|
||||
counters['failed'] += 1
|
||||
failures.append('ready: ' + type(exc).__name__ + ': ' + str(exc)[:120])
|
||||
except Exception as exc:
|
||||
record(kind, time.monotonic() - started, False, type(exc).__name__ + ': ' + str(exc)[:120])
|
||||
finally:
|
||||
sem.release()
|
||||
|
||||
total = max(0, int(args.rate * args.duration))
|
||||
started = time.monotonic()
|
||||
threads = []
|
||||
for index in range(total):
|
||||
target = started + index / max(args.rate, 0.001)
|
||||
delay = target - time.monotonic()
|
||||
if delay > 0:
|
||||
time.sleep(delay)
|
||||
if not sem.acquire(blocking=False):
|
||||
with lock:
|
||||
counters['dropped'] += 1
|
||||
continue
|
||||
kind = 'upload' if ((index * 37) % 100) < int(args.upload_ratio * 100) else 'message'
|
||||
thread = threading.Thread(target=run_one, args=(kind, index), daemon=True)
|
||||
threads.append(thread)
|
||||
thread.start()
|
||||
|
||||
for thread in threads:
|
||||
thread.join()
|
||||
|
||||
summary = {
|
||||
'base_url': args.base_url,
|
||||
'rate': args.rate,
|
||||
'duration_s': round(time.monotonic() - started, 2),
|
||||
'scheduled': total,
|
||||
'counters': counters,
|
||||
'failures': len(failures),
|
||||
'failure_samples': failures[:10],
|
||||
'latency_ms': {
|
||||
'p50': round(percentile(latencies, 50) * 1000, 1) if latencies else None,
|
||||
'p95': round(percentile(latencies, 95) * 1000, 1) if latencies else None,
|
||||
'p99': round(percentile(latencies, 99) * 1000, 1) if latencies else None,
|
||||
},
|
||||
'ttr_ms': {
|
||||
'p50': round(percentile(ttr, 50) * 1000, 1) if ttr else None,
|
||||
'p95': round(percentile(ttr, 95) * 1000, 1) if ttr else None,
|
||||
'p99': round(percentile(ttr, 99) * 1000, 1) if ttr else None,
|
||||
},
|
||||
}
|
||||
if args.output:
|
||||
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(args.output).write_text(json.dumps(summary, indent=2) + '\n')
|
||||
print(json.dumps(summary, indent=2))
|
||||
return 0 if not failures else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
Executable
+91
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab6 track 2 scenario driver: burst, sustained outage and false-positive phases.
|
||||
|
||||
It starts the open-loop load, injects a PostgreSQL fault, records alert state and
|
||||
restores the stand. Use --quick for a short evidence run; the full 15-minute
|
||||
sustained phase is the graded scenario.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
# The lab tools always target loopback; ignore ambient corporate proxies.
|
||||
for _proxy_key in ('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy'):
|
||||
os.environ.pop(_proxy_key, None)
|
||||
os.environ['NO_PROXY'] = 'localhost,127.0.0.1,::1'
|
||||
os.environ['no_proxy'] = 'localhost,127.0.0.1,::1'
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def compose(*args, check=True):
|
||||
command = ['docker', 'compose', '--env-file', '.env', '-f', 'compose.yaml', *args]
|
||||
return subprocess.run(command, cwd=ROOT, check=check)
|
||||
|
||||
|
||||
def stamp():
|
||||
return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Lab6 track 2 scenarios')
|
||||
parser.add_argument('--scenario', choices=['burst', 'sustained', 'false-positive'], default='burst')
|
||||
parser.add_argument('--quick', action='store_true', help='short 20s phases')
|
||||
parser.add_argument('--base-url', default='http://localhost:8080')
|
||||
parser.add_argument('--load-rate', type=float, default=0.5)
|
||||
parser.add_argument('--output-dir', default='evidence/lab6/track2')
|
||||
args = parser.parse_args()
|
||||
out = ROOT / args.output_dir
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
duration = 20 if args.quick else (120 if args.scenario == 'burst' else 900)
|
||||
if args.scenario == 'false-positive':
|
||||
duration = 20 if args.quick else 300
|
||||
|
||||
load = subprocess.Popen([
|
||||
sys.executable, str(ROOT / 'scripts/lab6_load.py'),
|
||||
'--base-url', args.base_url, '--rate', str(args.load_rate),
|
||||
'--duration', str(duration + 20), '--upload-ratio', '0.2',
|
||||
'--output', str(out / (args.scenario + '-load.json')),
|
||||
], cwd=ROOT)
|
||||
alerts = subprocess.Popen([
|
||||
sys.executable, str(ROOT / 'scripts/lab6_alerts.py'),
|
||||
'--duration', str(duration + 20), '--output', str(out / (args.scenario + '-alerts.csv')),
|
||||
], cwd=ROOT)
|
||||
|
||||
time.sleep(5)
|
||||
injection = stamp()
|
||||
try:
|
||||
if args.scenario == 'burst':
|
||||
compose('pause', 'postgres')
|
||||
elif args.scenario == 'sustained':
|
||||
compose('stop', 'worker')
|
||||
compose('stop', 'postgres')
|
||||
time.sleep(duration)
|
||||
finally:
|
||||
if args.scenario == 'burst':
|
||||
compose('unpause', 'postgres', check=False)
|
||||
elif args.scenario == 'sustained':
|
||||
compose('start', 'postgres', check=False)
|
||||
time.sleep(5)
|
||||
compose('up', '-d', '--no-deps', 'worker', check=False)
|
||||
restore = stamp()
|
||||
Path(out / (args.scenario + '-phases.json')).write_text(json.dumps({
|
||||
'scenario': args.scenario,
|
||||
'injection_utc': injection,
|
||||
'restore_utc': restore,
|
||||
'duration_seconds': duration,
|
||||
}, indent=2) + '\n')
|
||||
time.sleep(10)
|
||||
|
||||
load_rc = load.wait(timeout=duration + 60)
|
||||
alerts_rc = alerts.wait(timeout=duration + 60)
|
||||
print('track2 evidence:', out, 'load_rc=', load_rc, 'alerts_rc=', alerts_rc)
|
||||
return 1 if alerts_rc != 0 else 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
Executable
+388
@@ -0,0 +1,388 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Full Track 2 timeline with fail-fast, preflight and guaranteed restore.
|
||||
|
||||
Warmup >= 70m, baseline, 2m burst, 15m sustained outage, resolution, TTR and
|
||||
false-positive phases. The script records injection/restore timestamps, alert
|
||||
transitions and Prometheus snapshots before and after each fault.
|
||||
"""
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
for _key in ('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy'):
|
||||
os.environ.pop(_key, None)
|
||||
os.environ['NO_PROXY'] = 'localhost,127.0.0.1,::1'
|
||||
os.environ['no_proxy'] = 'localhost,127.0.0.1,::1'
|
||||
# tests/client.py builds its own opener; make it ignore macOS system proxies too.
|
||||
urllib.request.getproxies = lambda: {}
|
||||
OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ACTIVE_LOAD = [None]
|
||||
|
||||
|
||||
def utc(ts=None):
|
||||
return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(ts if ts is not None else time.time()))
|
||||
|
||||
|
||||
def http_json(url, timeout=15):
|
||||
with OPENER.open(url, timeout=timeout) as response:
|
||||
return json.loads(response.read())
|
||||
|
||||
|
||||
def prom(expr):
|
||||
url = 'http://localhost:9090/api/v1/query?' + urllib.parse.urlencode({'query': expr})
|
||||
return http_json(url).get('data', {}).get('result', [])
|
||||
|
||||
|
||||
def alerts():
|
||||
return http_json('http://localhost:9090/api/v1/alerts').get('data', {}).get('alerts', [])
|
||||
|
||||
|
||||
def compose(*args, check=True):
|
||||
result = subprocess.run(
|
||||
['docker', 'compose', '--env-file', '.env', '-f', 'compose.yaml', *args],
|
||||
cwd=ROOT, capture_output=True, text=True, check=False,
|
||||
)
|
||||
(ROOT / 'evidence/lab6/track2').mkdir(parents=True, exist_ok=True)
|
||||
with (ROOT / 'evidence/lab6/track2/full-compose.log').open('a') as log:
|
||||
log.write(utc() + ' docker compose ' + ' '.join(args) + ' rc=' + str(result.returncode) + '\n')
|
||||
if result.stderr:
|
||||
log.write(result.stderr[-2000:] + '\n')
|
||||
if check and result.returncode != 0:
|
||||
raise RuntimeError('docker compose %s failed rc=%d: %s' % (' '.join(args), result.returncode, result.stderr[-500:]))
|
||||
return result
|
||||
|
||||
|
||||
def wait_ready(timeout=120):
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
with OPENER.open('http://localhost:8080/health/ready', timeout=5) as response:
|
||||
if response.status == 200:
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(2)
|
||||
return False
|
||||
|
||||
|
||||
class AlertTimeline:
|
||||
def __init__(self, path):
|
||||
self.path = path
|
||||
self.stop = threading.Event()
|
||||
self.active = set()
|
||||
self.changes = []
|
||||
self.injection = ''
|
||||
self.lock = threading.Lock()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self.handle = path.open('w', newline='')
|
||||
self.writer = csv.writer(self.handle)
|
||||
self.writer.writerow(['observed_utc', 'alert', 'state', 'active_at', 'value', 'injection_utc'])
|
||||
self.thread = threading.Thread(target=self.run, daemon=True)
|
||||
|
||||
def start(self):
|
||||
self.thread.start()
|
||||
|
||||
def run(self):
|
||||
while not self.stop.is_set():
|
||||
try:
|
||||
current = set()
|
||||
for alert in alerts():
|
||||
name = alert.get('labels', {}).get('alertname', '')
|
||||
state = alert.get('state', '')
|
||||
current.add((name, state))
|
||||
if (name, state) not in self.active:
|
||||
row = [utc(), name, state, alert.get('activeAt', ''), alert.get('value', ''), self.injection]
|
||||
with self.lock:
|
||||
self.changes.append(row)
|
||||
self.writer.writerow(row)
|
||||
self.handle.flush()
|
||||
for name, state in sorted(self.active - current):
|
||||
row = [utc(), name, 'resolved', '', '', self.injection]
|
||||
with self.lock:
|
||||
self.changes.append(row)
|
||||
self.writer.writerow(row)
|
||||
self.handle.flush()
|
||||
self.active = current
|
||||
except Exception as exc:
|
||||
with self.lock:
|
||||
self.writer.writerow([utc(), 'POLL_ERROR', str(exc)[:160], '', '', self.injection])
|
||||
self.handle.flush()
|
||||
self.stop.wait(10)
|
||||
|
||||
def finish(self):
|
||||
self.stop.set()
|
||||
self.thread.join(timeout=20)
|
||||
self.handle.close()
|
||||
return self.changes
|
||||
|
||||
|
||||
def snapshot(out, label):
|
||||
values = {}
|
||||
errors = []
|
||||
for name, expr in {
|
||||
'api_error_5m': 'slo:api_error_ratio:5m',
|
||||
'api_error_1h': 'slo:api_error_ratio:1h',
|
||||
'api_error_30m': 'slo:api_error_ratio:30m',
|
||||
'api_error_6h': 'slo:api_error_ratio:6h',
|
||||
'ttr_bad_5m': 'slo:ttr_bad_ratio:5m',
|
||||
'ttr_bad_1h': 'slo:ttr_bad_ratio:1h',
|
||||
'queue_oldest': 'max(messenger_queue_oldest_job_age_seconds)',
|
||||
'queue_depth': 'max(rabbitmq_queue_messages_ready{queue="attachment.process.v1"})',
|
||||
'jobs_overdue': 'max(messenger_jobs_overdue)',
|
||||
'worker_busy': 'max(messenger_worker_busy)',
|
||||
}.items():
|
||||
try:
|
||||
result = prom(expr)
|
||||
values[name] = result[0]['value'][1] if result else None
|
||||
except Exception as exc:
|
||||
values[name] = None
|
||||
errors.append(name + ': ' + str(exc)[:100])
|
||||
(out / 'snapshots').mkdir(parents=True, exist_ok=True)
|
||||
(out / 'snapshots' / (label + '-' + utc().replace(':', '-') + '.json')).write_text(json.dumps(values, indent=2) + '\n')
|
||||
if errors:
|
||||
raise RuntimeError('Prometheus snapshot failed: ' + '; '.join(errors))
|
||||
return values
|
||||
|
||||
|
||||
def run_load(out, label, duration, ratio=0.2, rate=0.2):
|
||||
log_path = out / (label + '-load.log')
|
||||
output_path = out / (label + '-load.json')
|
||||
cmd = [sys.executable, str(ROOT / 'scripts/lab6_load.py'),
|
||||
'--base-url', 'http://localhost:8080', '--rate', str(rate),
|
||||
'--duration', str(duration), '--upload-ratio', str(ratio),
|
||||
'--deadline', '10', '--output', str(output_path)]
|
||||
log = log_path.open('w')
|
||||
process = subprocess.Popen(cmd, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT)
|
||||
ACTIVE_LOAD[0] = (process, log, output_path)
|
||||
return process, log, output_path
|
||||
|
||||
|
||||
def finish_load(process, log, output_path, label, expected_s, allow_failures=False):
|
||||
try:
|
||||
rc = process.wait(timeout=expected_s + 300)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
rc = process.wait()
|
||||
log.close()
|
||||
ACTIVE_LOAD[0] = None
|
||||
if not output_path.exists():
|
||||
raise RuntimeError(label + ': load produced no JSON (rc=' + str(rc) + ')')
|
||||
summary = json.loads(output_path.read_text())
|
||||
minimum = 0.85 * expected_s if expected_s >= 30 else 0.5 * expected_s
|
||||
if summary.get('duration_s', 0) < minimum:
|
||||
raise RuntimeError(label + ': load ran only ' + str(summary.get('duration_s')) + 's, expected ~' + str(expected_s))
|
||||
if not allow_failures and (rc != 0 or summary.get('failures', 0)):
|
||||
raise RuntimeError(label + ': load failed rc=' + str(rc) + ' failures=' + str(summary.get('failures')))
|
||||
return summary
|
||||
|
||||
|
||||
def restore_stand():
|
||||
compose('unpause', 'postgres', check=False)
|
||||
compose('start', 'postgres', check=False)
|
||||
compose('up', '-d', '--wait', '--no-deps', 'worker', check=False)
|
||||
return wait_ready(120)
|
||||
|
||||
|
||||
def phase(out, phases, name, started, injection='', restore=''):
|
||||
value = {
|
||||
'phase': name,
|
||||
'started_utc': utc(started),
|
||||
'finished_utc': utc(),
|
||||
'duration_s': round(time.time() - started, 1),
|
||||
'injection_utc': injection,
|
||||
'restore_utc': restore,
|
||||
}
|
||||
phases.append(value)
|
||||
(out / 'phases.json').write_text(json.dumps(phases, indent=2) + '\n')
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Full lab6 Track 2 timeline')
|
||||
parser.add_argument('--warmup', type=int, default=4200)
|
||||
parser.add_argument('--baseline', type=int, default=1200)
|
||||
parser.add_argument('--burst', type=int, default=120)
|
||||
parser.add_argument('--settle', type=int, default=600)
|
||||
parser.add_argument('--sustained', type=int, default=900)
|
||||
parser.add_argument('--resolution', type=int, default=3600)
|
||||
parser.add_argument('--ttr', type=int, default=900)
|
||||
parser.add_argument('--false-positive', type=int, default=1200)
|
||||
parser.add_argument('--out', default='evidence/lab6/track2/full')
|
||||
args = parser.parse_args()
|
||||
out = ROOT / args.out
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
phases = []
|
||||
timeline = AlertTimeline(out / 'alerts.csv')
|
||||
timeline.start()
|
||||
interrupted = False
|
||||
exit_code = 0
|
||||
try:
|
||||
def on_signal(signum, _frame):
|
||||
raise KeyboardInterrupt('signal %d' % signum)
|
||||
signal.signal(signal.SIGINT, on_signal)
|
||||
signal.signal(signal.SIGTERM, on_signal)
|
||||
|
||||
if not wait_ready(120):
|
||||
raise RuntimeError('preflight: /health/ready is not ready')
|
||||
preflight = run_load(out, 'preflight', 3, ratio=0.5, rate=1.0)
|
||||
finish_load(*preflight, 'preflight', 3, allow_failures=False)
|
||||
print(utc(), 'preflight OK; start full track', flush=True)
|
||||
|
||||
t = time.time()
|
||||
load = run_load(out, 'warmup', args.warmup)
|
||||
print(utc(), 'warmup started', flush=True)
|
||||
finish_load(*load, 'warmup', args.warmup)
|
||||
phase(out, phases, 'warmup', t)
|
||||
snapshot(out, 'warmup')
|
||||
|
||||
t = time.time()
|
||||
load = run_load(out, 'baseline', args.baseline)
|
||||
print(utc(), 'baseline started', flush=True)
|
||||
finish_load(*load, 'baseline', args.baseline)
|
||||
phase(out, phases, 'baseline', t)
|
||||
(out / 'baseline.json').write_text(json.dumps(snapshot(out, 'baseline'), indent=2) + '\n')
|
||||
|
||||
t = time.time()
|
||||
load = run_load(out, 'burst', args.burst + args.settle)
|
||||
time.sleep(10)
|
||||
injection = utc()
|
||||
timeline.injection = injection
|
||||
print(utc(), 'burst: pause postgres', flush=True)
|
||||
compose('pause', 'postgres')
|
||||
time.sleep(min(30, args.burst))
|
||||
burst_active = snapshot(out, 'burst-active')
|
||||
if args.burst > 30:
|
||||
time.sleep(args.burst - 30)
|
||||
compose('unpause', 'postgres')
|
||||
restore = utc()
|
||||
print(utc(), 'burst: unpause postgres', flush=True)
|
||||
finish_load(*load, 'burst', args.burst + args.settle, allow_failures=True)
|
||||
phase(out, phases, 'burst', t, injection, restore)
|
||||
burst_after = snapshot(out, 'burst-after')
|
||||
(out / 'burst.json').write_text(json.dumps({'active': burst_active, 'after': burst_after}, indent=2) + '\n')
|
||||
|
||||
t = time.time()
|
||||
compose('stop', 'worker')
|
||||
load = run_load(out, 'sustained', args.sustained + 300)
|
||||
time.sleep(10)
|
||||
injection = utc()
|
||||
timeline.injection = injection
|
||||
print(utc(), 'sustained: stop postgres', flush=True)
|
||||
compose('stop', 'postgres')
|
||||
time.sleep(min(30, args.sustained))
|
||||
sustained_active = snapshot(out, 'sustained-active')
|
||||
if args.sustained > 30:
|
||||
time.sleep(args.sustained - 30)
|
||||
compose('start', 'postgres')
|
||||
if not wait_ready(180):
|
||||
raise RuntimeError('sustained: readiness did not recover')
|
||||
compose('up', '-d', '--no-deps', 'worker')
|
||||
restore = utc()
|
||||
print(utc(), 'sustained: postgres and worker restored', flush=True)
|
||||
finish_load(*load, 'sustained', args.sustained + 300, allow_failures=True)
|
||||
drained = wait_queue_drain(300)
|
||||
phase(out, phases, 'sustained', t, injection, restore)
|
||||
sustained_after = snapshot(out, 'sustained-after')
|
||||
(out / 'sustained.json').write_text(json.dumps({'active': sustained_active, 'after': sustained_after, 'queue_drained': drained}, indent=2) + '\n')
|
||||
|
||||
print(utc(), 'resolution under normal load', flush=True)
|
||||
t = time.time()
|
||||
load = run_load(out, 'resolution', args.resolution)
|
||||
finish_load(*load, 'resolution', args.resolution)
|
||||
phase(out, phases, 'resolution_wait', t)
|
||||
snapshot(out, 'resolution')
|
||||
|
||||
t = time.time()
|
||||
compose('stop', 'worker')
|
||||
load = run_load(out, 'ttr', args.ttr, ratio=1.0)
|
||||
time.sleep(10)
|
||||
injection = utc()
|
||||
timeline.injection = injection
|
||||
print(utc(), 'ttr: worker stopped and uploads started', flush=True)
|
||||
time.sleep(args.ttr)
|
||||
compose('up', '-d', '--no-deps', 'worker')
|
||||
restore = utc()
|
||||
finish_load(*load, 'ttr', args.ttr, allow_failures=True)
|
||||
wait_queue_drain(300)
|
||||
phase(out, phases, 'ttr', t, injection, restore)
|
||||
snapshot(out, 'ttr-after')
|
||||
|
||||
t = time.time()
|
||||
load = run_load(out, 'false-positive', args.false_positive)
|
||||
print(utc(), 'false-positive phase started', flush=True)
|
||||
finish_load(*load, 'false-positive', args.false_positive)
|
||||
phase(out, phases, 'false-positive', t)
|
||||
final = snapshot(out, 'final')
|
||||
(out / 'final.json').write_text(json.dumps(final, indent=2) + '\n')
|
||||
|
||||
except BaseException as exc:
|
||||
interrupted = True
|
||||
(out / 'aborted.json').write_text(json.dumps({'aborted_utc': utc(), 'error': repr(exc)}, indent=2) + '\n')
|
||||
print(utc(), 'ABORT', repr(exc), flush=True)
|
||||
raise
|
||||
finally:
|
||||
if ACTIVE_LOAD[0] is not None:
|
||||
process, log, _ = ACTIVE_LOAD[0]
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait()
|
||||
log.close()
|
||||
ACTIVE_LOAD[0] = None
|
||||
restored = restore_stand()
|
||||
if not restored and not interrupted:
|
||||
exit_code = 1
|
||||
changes = timeline.finish()
|
||||
(out / 'alerts.json').write_text(json.dumps(changes, indent=2) + '\n')
|
||||
try:
|
||||
final_summary = snapshot(out, 'final-summary')
|
||||
except Exception as exc:
|
||||
final_summary = {'error': str(exc)[:200]}
|
||||
(out / 'summary.md').write_text(
|
||||
'# Full Track 2 run\n\nPhases:\n```json\n' + json.dumps(phases, indent=2) +
|
||||
'\n```\n\nFinal snapshot:\n```json\n' + json.dumps(final_summary, indent=2) +
|
||||
'\n```\n\nAborted: ' + str(interrupted) + '\nRestored: ' + str(restored) + '\n')
|
||||
print(utc(), 'done; evidence', out, flush=True)
|
||||
return exit_code
|
||||
|
||||
|
||||
def wait_queue_drain(timeout=300):
|
||||
deadline = time.time() + timeout
|
||||
good = 0
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
oldest = prom('max(messenger_queue_oldest_job_age_seconds)')
|
||||
depth = prom('max(rabbitmq_queue_messages_ready{queue="attachment.process.v1"})')
|
||||
if not oldest or not depth:
|
||||
good = 0
|
||||
time.sleep(10)
|
||||
continue
|
||||
oldest_v = float(oldest[0]['value'][1])
|
||||
depth_v = float(depth[0]['value'][1])
|
||||
if oldest_v < 5 and depth_v < 5:
|
||||
good += 1
|
||||
if good >= 2:
|
||||
return True
|
||||
else:
|
||||
good = 0
|
||||
except Exception:
|
||||
good = 0
|
||||
time.sleep(10)
|
||||
return False
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
Executable
+270
@@ -0,0 +1,270 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Strict lab6 observability gate.
|
||||
|
||||
It creates a fresh message and attachment, waits for all three signals, checks
|
||||
route/template cardinality, Grafana provisioning and rules, and verifies that
|
||||
user content and credentials never reached Loki. A missing signal is a failure,
|
||||
not a warning.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import base64
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
# The lab tools always target loopback; ignore ambient corporate proxies.
|
||||
for _proxy_key in ('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy'):
|
||||
os.environ.pop(_proxy_key, None)
|
||||
os.environ['NO_PROXY'] = 'localhost,127.0.0.1,::1'
|
||||
os.environ['no_proxy'] = 'localhost,127.0.0.1,::1'
|
||||
urllib.request.getproxies = lambda: {}
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
UUID_RE = re.compile(r'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}', re.I)
|
||||
FORBIDDEN_LABELS = {'user_id', 'chat_id', 'message_id', 'attachment_id', 'filename', 'request_id', 'object_key', 'path', 'query'}
|
||||
|
||||
|
||||
def request(url, auth=None, timeout=10):
|
||||
headers = {'Accept': 'application/json'}
|
||||
if auth:
|
||||
headers['Authorization'] = 'Basic ' + base64.b64encode(auth.encode()).decode()
|
||||
req = urllib.request.Request(url, headers=headers)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as response:
|
||||
return response.status, response.read()
|
||||
|
||||
|
||||
def prom(base, expr):
|
||||
url = base.rstrip('/') + '/api/v1/query?' + urllib.parse.urlencode({'query': expr})
|
||||
_, raw = request(url)
|
||||
return json.loads(raw).get('data', {}).get('result', [])
|
||||
|
||||
|
||||
def prom_series(base, match):
|
||||
url = base.rstrip('/') + '/api/v1/series?' + urllib.parse.urlencode({'match[]': match})
|
||||
_, raw = request(url)
|
||||
return json.loads(raw).get('data', [])
|
||||
|
||||
|
||||
def loki_query(base, query, start_ns, end_ns, limit=20):
|
||||
params = urllib.parse.urlencode({'query': query, 'start': start_ns, 'end': end_ns, 'limit': limit})
|
||||
_, raw = request(base.rstrip('/') + '/loki/api/v1/query_range?' + params)
|
||||
return json.loads(raw).get('data', {}).get('result', [])
|
||||
|
||||
|
||||
def grafana_password():
|
||||
path = ROOT / 'secrets/grafana.env'
|
||||
if not path.exists():
|
||||
return None
|
||||
for line in path.read_text().splitlines():
|
||||
if '=' in line and line.split('=', 1)[0].strip() == 'GF_SECURITY_ADMIN_PASSWORD':
|
||||
return line.split('=', 1)[1].strip()
|
||||
return None
|
||||
|
||||
|
||||
def wait_for(fn, attempts=30, delay=2):
|
||||
last = None
|
||||
for _ in range(attempts):
|
||||
try:
|
||||
value = fn()
|
||||
if value:
|
||||
return value
|
||||
except Exception as exc: # noqa: BLE001 - retry the external endpoint
|
||||
last = exc
|
||||
time.sleep(delay)
|
||||
if last:
|
||||
raise last
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Strict lab6 telemetry gate')
|
||||
parser.add_argument('--base-url', default='http://localhost:8080')
|
||||
parser.add_argument('--prometheus', default='http://localhost:9090')
|
||||
parser.add_argument('--loki', default='http://localhost:3100')
|
||||
parser.add_argument('--tempo', default='http://localhost:3200')
|
||||
parser.add_argument('--grafana', default='http://localhost:3000')
|
||||
parser.add_argument('--wait-seconds', type=int, default=60)
|
||||
args = parser.parse_args()
|
||||
failures = []
|
||||
notes = []
|
||||
|
||||
# 1. Generate a controlled request, a message and a job.
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client
|
||||
client = Client(args.base_url, timeout=15)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
request_id = 'lab6-verify-' + uuid.uuid4().hex
|
||||
sentinel = 'SENTINEL-TELEMETRY-' + uuid.uuid4().hex
|
||||
client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
|
||||
body={'text': sentinel}, headers={'Idempotency-Key': uuid.uuid4().hex, 'X-Request-ID': request_id})
|
||||
att, content = client.attachment(alice, chat)
|
||||
client.wait_ready(alice, att, wait_seconds=60)
|
||||
filename = 'sentinel-' + uuid.uuid4().hex + '.png'
|
||||
from urllib.parse import quote
|
||||
client.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + quote(filename), 202,
|
||||
actor=alice, raw=content, headers={'Content-Type': 'image/png'}, schema='Attachment')
|
||||
token = alice.get('token', '')
|
||||
notes.append('created request_id=' + request_id)
|
||||
|
||||
# 2. Required metric series. Counter/histogram series can take one export
|
||||
# and one scrape interval to appear.
|
||||
required = [
|
||||
('messenger_http_server_requests_total', 'API request counter'),
|
||||
('http_server_request_duration_seconds_bucket', 'HTTP duration histogram'),
|
||||
('messenger_jobs_processed_total', 'job attempt counter'),
|
||||
('messenger_jobs_accepted_total', 'accepted jobs'),
|
||||
('messenger_jobs_ready_within_budget_total', 'ready-within-budget'),
|
||||
('messenger_job_duration_seconds_bucket', 'job duration histogram'),
|
||||
('messenger_job_time_to_ready_seconds_bucket', 'time-to-ready histogram'),
|
||||
('messenger_jobs_overdue', 'overdue jobs'),
|
||||
('messenger_worker_busy', 'worker saturation'),
|
||||
('messenger_db_pool_used', 'DB pool'),
|
||||
('messenger_queue_oldest_job_age_seconds', 'oldest job age'),
|
||||
('messenger_outbox_oldest_unpublished_age_seconds', 'outbox age'),
|
||||
('messenger_process_cpu_seconds_total', 'process CPU'),
|
||||
('rabbitmq_queue_messages_ready', 'RabbitMQ queue depth'),
|
||||
('otelcol_exporter_queue_size', 'collector queue self-metric'),
|
||||
]
|
||||
for metric, label in required:
|
||||
try:
|
||||
found = wait_for(lambda m=metric: prom(args.prometheus, 'count(' + m + ')'), attempts=max(1, args.wait_seconds // 3), delay=3)
|
||||
if not found:
|
||||
failures.append(label + ': no samples (' + metric + ')')
|
||||
except Exception as exc:
|
||||
failures.append(label + ': ' + str(exc))
|
||||
|
||||
try:
|
||||
up = prom(args.prometheus, 'up{job=~"otel-collector|haproxy|rabbitmq"} == 1')
|
||||
jobs = {item.get('metric', {}).get('job') for item in up}
|
||||
for job in ('otel-collector', 'haproxy', 'rabbitmq'):
|
||||
if job not in jobs:
|
||||
failures.append('Prometheus target is not up: ' + job)
|
||||
except Exception as exc:
|
||||
failures.append('Prometheus targets: ' + str(exc))
|
||||
|
||||
try:
|
||||
series = prom_series(args.prometheus, 'messenger_http_server_requests_total')
|
||||
routes = [item.get('http_route', '') for item in series]
|
||||
if not series:
|
||||
failures.append('HTTP metric has no series')
|
||||
for route in routes:
|
||||
if not route:
|
||||
failures.append('HTTP metric has an empty http_route label')
|
||||
if UUID_RE.search(route):
|
||||
failures.append('HTTP route label contains a UUID: ' + route)
|
||||
labels = {key for item in series for key in item}
|
||||
forbidden = labels & FORBIDDEN_LABELS
|
||||
if forbidden:
|
||||
failures.append('HTTP metric has forbidden labels: ' + ', '.join(sorted(forbidden)))
|
||||
methods = {item.get('http_request_method', '') for item in series}
|
||||
if len(methods) > 7:
|
||||
failures.append('HTTP method label cardinality is too high: ' + str(len(methods)))
|
||||
for method in methods:
|
||||
if method not in {'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS', 'OTHER'}:
|
||||
failures.append('HTTP method is not normalized: ' + method)
|
||||
except Exception as exc:
|
||||
failures.append('HTTP label check: ' + str(exc))
|
||||
|
||||
# 3. Loki must contain the access log for the controlled request and must
|
||||
# not contain the message text, session token or file bytes.
|
||||
end = int(time.time() * 1e9)
|
||||
start = end - 15 * 60 * int(1e9)
|
||||
try:
|
||||
found = wait_for(lambda: loki_query(args.loki, '{service_name=~"messenger-api|messenger-worker|messenger-relay"} | request_id="' + request_id + '"', start, end), attempts=20, delay=2)
|
||||
if not found:
|
||||
failures.append('Loki: no log with the generated request_id (trace/log correlation)')
|
||||
for needle, label in ((sentinel, 'message text'), (token, 'session token'), (filename, 'filename')):
|
||||
if needle and loki_query(args.loki, '{service_name=~"messenger-api|messenger-worker|messenger-relay"} |= "' + needle + '"', start, end):
|
||||
failures.append('Loki contains forbidden ' + label)
|
||||
except Exception as exc:
|
||||
failures.append('Loki query: ' + str(exc))
|
||||
|
||||
# 4. Tempo must contain real application traces, including the worker span.
|
||||
# Tempo's search `name=` matches root spans only. job.process is a child of
|
||||
# the controlled API trace, so resolve its trace_id from the worker log and
|
||||
# fetch that trace directly.
|
||||
try:
|
||||
def tempo_search(tag):
|
||||
q = urllib.parse.quote(tag)
|
||||
_, raw = request(args.tempo.rstrip('/') + '/api/search?tags=' + q + '&limit=20')
|
||||
return json.loads(raw).get('traces', [])
|
||||
|
||||
def worker_job_trace():
|
||||
result = loki_query(
|
||||
args.loki,
|
||||
'{service_name="messenger-worker"} | event="attachment ready"',
|
||||
start, end, limit=50,
|
||||
)
|
||||
for stream in result:
|
||||
for _, line in stream.get('values', []):
|
||||
try:
|
||||
entry = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
entry = {}
|
||||
trace_id = entry.get('trace_id') or stream.get('stream', {}).get('trace_id', '')
|
||||
if not re.fullmatch(r'[0-9a-f]{32}', trace_id):
|
||||
continue
|
||||
try:
|
||||
_, raw = request(args.tempo.rstrip('/') + '/api/traces/' + trace_id)
|
||||
except Exception:
|
||||
continue
|
||||
if 'job.process' in raw.decode('utf-8', 'replace'):
|
||||
return trace_id
|
||||
return None
|
||||
|
||||
if not wait_for(lambda: tempo_search('service.name=messenger-api'), attempts=15, delay=2):
|
||||
failures.append('Tempo: no messenger-api traces')
|
||||
if not wait_for(worker_job_trace, attempts=20, delay=2):
|
||||
failures.append('Tempo: no worker job.process trace linked to worker log')
|
||||
except Exception as exc:
|
||||
failures.append('Tempo query: ' + str(exc))
|
||||
|
||||
# 5. Grafana provisioning and rules.
|
||||
try:
|
||||
password = grafana_password()
|
||||
if not password:
|
||||
failures.append('Grafana admin secret is missing (secrets/grafana.env)')
|
||||
else:
|
||||
_, raw = request(args.grafana.rstrip('/') + '/api/health')
|
||||
if json.loads(raw).get('database') != 'ok':
|
||||
failures.append('Grafana health is not ok')
|
||||
_, raw = request(args.grafana.rstrip('/') + '/api/datasources', auth='admin:' + password)
|
||||
names = {item.get('name') for item in json.loads(raw)}
|
||||
for required_name in ('Prometheus', 'Loki', 'Tempo'):
|
||||
if required_name not in names:
|
||||
failures.append('Grafana datasource missing: ' + required_name)
|
||||
for uid in ('lab6-overview', 'lab6-jobs', 'lab6-infra'):
|
||||
_, raw = request(args.grafana.rstrip('/') + '/api/dashboards/uid/' + uid, auth='admin:' + password)
|
||||
if json.loads(raw).get('dashboard', {}).get('uid') != uid:
|
||||
failures.append('Grafana dashboard missing: ' + uid)
|
||||
except Exception as exc:
|
||||
failures.append('Grafana: ' + str(exc))
|
||||
|
||||
try:
|
||||
_, raw = request(args.prometheus.rstrip('/') + '/api/v1/rules')
|
||||
rule_names = {r.get('name') for g in json.loads(raw).get('data', {}).get('groups', []) for r in g.get('rules', [])}
|
||||
for name in ('APIErrorBudgetFastBurn', 'APIErrorBudgetSlowBurn', 'QueueOldestJobAgeHigh', 'TTRErrorBudgetFastBurn'):
|
||||
if name not in rule_names:
|
||||
failures.append('Prometheus rule missing: ' + name)
|
||||
except Exception as exc:
|
||||
failures.append('Prometheus rules: ' + str(exc))
|
||||
|
||||
for note in notes:
|
||||
print('NOTE:', note)
|
||||
if failures:
|
||||
for item in failures:
|
||||
print('FAIL:', item)
|
||||
return 1
|
||||
print('PASS: lab6 strict telemetry gate (signals, trace/log correlation, labels, Grafana, rules, privacy sentinels)')
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -24,11 +24,11 @@ if [ -f .env ]; then
|
||||
fi
|
||||
|
||||
OUT=${OUT:-evidence/lab5/lb-readiness-detail.txt}
|
||||
PROJECT=${COMPOSE_PROJECT_NAME:-mtusi-messenger-lab5}
|
||||
PROJECT=${COMPOSE_PROJECT_NAME:-mtusi-messenger-lab6}
|
||||
NET=${PROJECT}_default
|
||||
IMAGE=${IMAGE:-mtusi-messenger:lab5}
|
||||
STATS=${STATS:-http://127.0.0.1:8404/stats;csv}
|
||||
BASE_URL=${BASE_URL:-http://localhost:8080}
|
||||
IMAGE=${IMAGE:-mtusi-messenger:lab6}
|
||||
STATS=${STATS:-http://127.0.0.1:${LB_STATS_PORT:-8404}/stats;csv}
|
||||
BASE_URL=${BASE_URL:-http://localhost:${SERVER_PORT:-8080}}
|
||||
CANDIDATE=lb-readiness-candidate
|
||||
PROXY=lb-readiness-pgproxy
|
||||
REQUESTS=${REQUESTS:-40}
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ set -eu
|
||||
# No credentials are printed.
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
|
||||
PROJECT=${COMPOSE_PROJECT_NAME:-mtusi-messenger-lab5}
|
||||
PROJECT=${COMPOSE_PROJECT_NAME:-mtusi-messenger-lab6}
|
||||
|
||||
candidates=$(docker ps -q \
|
||||
--filter "label=com.docker.compose.project=${PROJECT}" \
|
||||
|
||||
Reference in New Issue
Block a user