lab6
This commit is contained in:
@@ -0,0 +1,178 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Controlled lab6 failures, with unconditional service recovery and sanitized evidence."""
|
||||
import argparse
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, check
|
||||
sys.path.insert(0, str(ROOT / 'student-tests'))
|
||||
from observability import get, eventually
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--base-url', default='http://localhost:8080')
|
||||
parser.add_argument('--prometheus-url', default='http://localhost:9090')
|
||||
parser.add_argument('--only', choices=['all', 'retry', 'backend'], default='all')
|
||||
args = parser.parse_args()
|
||||
compose = shlex.split(os.environ.get('COMPOSE', 'docker compose'))
|
||||
def command(*cmd):
|
||||
subprocess.run(compose + list(cmd), cwd=ROOT, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
def query(expr):
|
||||
return get(args.prometheus_url + '/api/v1/query?' + urllib.parse.urlencode({'query': expr}))['data']['result']
|
||||
def value(expr):
|
||||
rows = query(expr)
|
||||
return float(rows[0]['value'][1]) if rows else 0
|
||||
def firing(name):
|
||||
alerts = get(args.prometheus_url + '/api/v1/alerts')['data']['alerts']
|
||||
return any(a['labels']['alertname'] == name and a['state'] == 'firing' for a in alerts)
|
||||
c = Client(args.base_url)
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
events = json.loads((ROOT / "evidence/incidents.json").read_text()) if args.only != "all" else []
|
||||
def record(name, **fields):
|
||||
events.append({'event': name, 'timestamp': datetime.now(timezone.utc).isoformat(), **fields})
|
||||
(ROOT / 'evidence/incidents.json').write_text(json.dumps(events, indent=2) + '\n')
|
||||
print(name, flush=True)
|
||||
if args.only == "all":
|
||||
# 1. Durable queue ages while worker is stopped; resume drains the same job.
|
||||
command('stop', 'worker')
|
||||
try:
|
||||
att, _ = c.attachment(alice, chat)
|
||||
record('worker_stopped_upload_accepted')
|
||||
eventually(lambda: firing('QueueLagGrowing'), timeout=120)
|
||||
record('QueueLagGrowing_firing', depth=value('max(queue_depth)'), oldest_seconds=value('max(queue_oldest_age)'))
|
||||
finally:
|
||||
command('start', 'worker')
|
||||
c.wait_ready(bob, att)
|
||||
eventually(lambda: not firing('QueueLagGrowing') and value('max(queue_depth)') == 0, timeout=90)
|
||||
record('QueueLagGrowing_resolved_backlog_drained')
|
||||
# 2. PostgreSQL unavailable: valid authenticated reads must yield 5xx, never successful phantom writes.
|
||||
command('stop', 'db')
|
||||
statuses = {}
|
||||
try:
|
||||
record('database_stopped')
|
||||
deadline = time.monotonic() + 100
|
||||
while time.monotonic() < deadline:
|
||||
request = urllib.request.Request(args.base_url + '/api/v1/chats/' + chat['id'] + '/messages',
|
||||
headers={'Authorization': 'Bearer ' + alice['token']})
|
||||
try:
|
||||
response = urllib.request.urlopen(request, timeout=12)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
with response:
|
||||
code = response.status
|
||||
statuses[str(code)] = statuses.get(str(code), 0) + 1
|
||||
if firing('ApiHighErrorRate'):
|
||||
break
|
||||
time.sleep(0.5)
|
||||
check(firing('ApiHighErrorRate'), 'API error alert did not fire')
|
||||
check(any(int(code) >= 500 for code in statuses), 'No server errors observed')
|
||||
record('ApiHighErrorRate_firing', response_counts=statuses)
|
||||
finally:
|
||||
command('start', 'db')
|
||||
def recovered():
|
||||
return c.call('GET', '/health/ready', schema='Health')['status'] == 200
|
||||
eventually(recovered, timeout=90)
|
||||
# New traffic moves the one-minute failure window out of the rate calculation.
|
||||
deadline = time.monotonic() + 100
|
||||
while time.monotonic() < deadline:
|
||||
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages', actor=alice, schema='MessagePage')
|
||||
if not firing('ApiHighErrorRate'):
|
||||
break
|
||||
time.sleep(1)
|
||||
check(not firing('ApiHighErrorRate'), 'API alert did not resolve')
|
||||
record('ApiHighErrorRate_resolved_database_recovered')
|
||||
if args.only != "backend":
|
||||
# A retriable S3 failure must preserve the upload trace across the next outbox row.
|
||||
import base64
|
||||
import uuid
|
||||
trace = uuid.uuid4().hex
|
||||
command('pause', 'worker')
|
||||
paused = True
|
||||
try:
|
||||
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
att = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png', 202,
|
||||
actor=alice, raw=content, headers={'Content-Type': 'image/png',
|
||||
'traceparent': '00-' + trace + '-0123456789abcdef-01'}, schema='Attachment')['json']
|
||||
auth = os.environ.get('GRAFANA_ADMIN_USER', 'admin') + ':' + (ROOT / 'secrets/grafana_admin_password').read_text().strip()
|
||||
grafana = os.environ.get('GRAFANA_URL', 'http://localhost:3000')
|
||||
def retry_observed():
|
||||
data = get(grafana + '/api/datasources/proxy/uid/tempo/api/traces/' + trace, auth)
|
||||
def contains(obj):
|
||||
if isinstance(obj, dict):
|
||||
if obj.get('key') == 'job.outcome' and obj.get('value', {}).get('stringValue') == 'retry':
|
||||
return True
|
||||
return any(contains(v) for v in obj.values())
|
||||
return isinstance(obj, list) and any(contains(v) for v in obj)
|
||||
return contains(data)
|
||||
command('stop', 'minio')
|
||||
command('unpause', 'worker')
|
||||
paused = False
|
||||
eventually(retry_observed, timeout=45)
|
||||
record('s3_failure_scheduled_retry', trace_id=trace)
|
||||
finally:
|
||||
command('start', 'minio')
|
||||
if paused:
|
||||
command('unpause', 'worker')
|
||||
c.wait_ready(bob, att)
|
||||
auth = os.environ.get('GRAFANA_ADMIN_USER', 'admin') + ':' + (ROOT / 'secrets/grafana_admin_password').read_text().strip()
|
||||
grafana = os.environ.get('GRAFANA_URL', 'http://localhost:3000')
|
||||
def retry_trace():
|
||||
data = get(grafana + '/api/datasources/proxy/uid/tempo/api/traces/' + trace, auth)
|
||||
spans = []
|
||||
def walk(obj):
|
||||
if isinstance(obj, dict):
|
||||
if 'spanId' in obj and 'name' in obj:
|
||||
spans.append(obj)
|
||||
for value_ in obj.values():
|
||||
walk(value_)
|
||||
elif isinstance(obj, list):
|
||||
for value_ in obj:
|
||||
walk(value_)
|
||||
walk(data)
|
||||
by_id = {s['spanId']: s for s in spans}
|
||||
# consumer -> enqueue -> publish -> next consumer (all inside the same trace)
|
||||
for child in spans:
|
||||
if child['name'] != 'attachment.process':
|
||||
continue
|
||||
producer = by_id.get(child.get('parentSpanId'), {})
|
||||
enqueue = by_id.get(producer.get('parentSpanId'), {})
|
||||
prior = by_id.get(enqueue.get('parentSpanId'), {})
|
||||
if producer.get('name') == 'jobs:attachments publish' and enqueue.get('name') == 'attachment.enqueue' and prior.get('name') == 'attachment.process':
|
||||
return True
|
||||
return False
|
||||
eventually(retry_trace)
|
||||
record('retry_same_trace_ready_verified', trace_id=trace)
|
||||
# 3. Broken telemetry storage must not break either application process.
|
||||
before = value('sum(otelcol_exporter_send_failed_spans)')
|
||||
command('stop', 'tempo', 'loki')
|
||||
try:
|
||||
record('tempo_loki_stopped')
|
||||
att, _ = c.attachment(alice, chat)
|
||||
c.wait_ready(bob, att)
|
||||
for _ in range(20):
|
||||
c.message(alice, chat, 'Synthetic telemetry outage probe')
|
||||
time.sleep(1)
|
||||
eventually(lambda: value('sum(otelcol_exporter_send_failed_spans)') > before, timeout=45)
|
||||
record('telemetry_outage_api_worker_healthy',
|
||||
failed_span_exports=value('sum(otelcol_exporter_send_failed_spans)')-before,
|
||||
collector_rss_bytes=value('max(otelcol_process_memory_rss)'))
|
||||
finally:
|
||||
command('start', 'tempo', 'loki')
|
||||
record('tempo_loki_restarted')
|
||||
print('PASS: worker lag and DB error alerts fired/resolved; API and worker survived telemetry backend outage.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,133 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Live lab6 checks. No tokens, message contents or backend dumps are printed."""
|
||||
import argparse
|
||||
import base64
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, check
|
||||
|
||||
|
||||
def get(url, auth=None):
|
||||
headers = {'Accept': 'application/json'}
|
||||
if auth:
|
||||
headers['Authorization'] = 'Basic ' + base64.b64encode(auth.encode()).decode()
|
||||
with urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=15) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def eventually(fn, timeout=90):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
result = fn()
|
||||
if result:
|
||||
return result
|
||||
except (urllib.error.URLError, AssertionError, KeyError, ValueError):
|
||||
pass
|
||||
time.sleep(2)
|
||||
raise AssertionError('Telemetry check timed out')
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--base-url', default='http://localhost:8080')
|
||||
parser.add_argument('--prometheus-url', default='http://localhost:9090')
|
||||
parser.add_argument('--grafana-url', default='http://localhost:3000')
|
||||
parser.add_argument('--output', default='evidence/observability.json')
|
||||
args = parser.parse_args()
|
||||
auth = os.environ.get('GRAFANA_ADMIN_USER', 'admin') + ':' + (ROOT / 'secrets/grafana_admin_password').read_text().strip()
|
||||
proxy = args.grafana_url + '/api/datasources/proxy/uid/'
|
||||
def prom(query):
|
||||
return get(args.prometheus_url + '/api/v1/query?' + urllib.parse.urlencode({'query': query}))['data']['result']
|
||||
c = Client(args.base_url)
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
trace = uuid.uuid4().hex
|
||||
parent = '00-' + trace + '-0123456789abcdef-01'
|
||||
secret_marker = 'private-' + uuid.uuid4().hex
|
||||
c.message(alice, chat, secret_marker)
|
||||
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
att = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png', 202,
|
||||
actor=alice, raw=content, headers={'Content-Type': 'image/png', 'traceparent': parent}, schema='Attachment')['json']
|
||||
c.wait_ready(bob, att)
|
||||
def trace_complete():
|
||||
data = get(proxy + 'tempo/api/traces/' + trace, auth)
|
||||
spans = []
|
||||
def walk(obj):
|
||||
if isinstance(obj, dict):
|
||||
if 'spanId' in obj and 'name' in obj:
|
||||
spans.append(obj)
|
||||
for value in obj.values():
|
||||
walk(value)
|
||||
elif isinstance(obj, list):
|
||||
for value in obj:
|
||||
walk(value)
|
||||
walk(data)
|
||||
names = {span['name'] for span in spans}
|
||||
return (data, spans) if {'attachment.enqueue', 'jobs:attachments publish', 'attachment.process', 's3.put_object', 'postgresql.publish_ready'} <= names else None
|
||||
trace_data, spans = eventually(trace_complete)
|
||||
by_id = {span['spanId']: span for span in spans}
|
||||
consumer = next(span for span in spans if span['name'] == 'attachment.process')
|
||||
publish = by_id.get(consumer['parentSpanId'])
|
||||
check(publish and publish['name'] == 'jobs:attachments publish', 'consumer parent must be producer')
|
||||
enqueue = by_id.get(publish['parentSpanId'])
|
||||
check(enqueue and enqueue['name'] == 'attachment.enqueue', 'publish must continue durable outbox context')
|
||||
server = by_id.get(enqueue['parentSpanId'])
|
||||
check(server and server['name'].startswith('POST '), 'enqueue parent must be HTTP server')
|
||||
query = '{service_name=~"messenger-api|messenger-worker"} | trace_id="' + trace + '"'
|
||||
def correlated_logs():
|
||||
result = get(proxy + 'loki/loki/api/v1/query_range?' + urllib.parse.urlencode({'query': query, 'limit': 1000}), auth)['data']['result']
|
||||
services = {stream['stream'].get('service_name') for stream in result}
|
||||
return result if {'messenger-api', 'messenger-worker'} <= services else None
|
||||
logs = eventually(correlated_logs)
|
||||
required = ['http_server_requests_total', 'http_server_request_duration_seconds_bucket', 'worker_jobs_total',
|
||||
'worker_job_duration_seconds_bucket', 'attachment_ready_duration_seconds_bucket', 'queue_depth',
|
||||
'queue_oldest_age', 'db_pool_used', 'db_pool_waiting', 'worker_busy', 'worker_capacity',
|
||||
'process_memory_usage', 'process_cpu_time']
|
||||
for name in required:
|
||||
eventually(lambda: prom(name))
|
||||
panel_count = 0
|
||||
dashboard = get(args.grafana_url + '/api/dashboards/uid/messenger-observability', auth)['dashboard']
|
||||
check(len(dashboard['panels']) == len(json.loads((ROOT / 'infra/grafana/dashboards/messenger.json').read_text())['panels']), 'Provisioned dashboard differs')
|
||||
for panel in dashboard['panels']:
|
||||
if panel['datasource']['uid'] != 'prometheus':
|
||||
continue
|
||||
for target in panel['targets']:
|
||||
expr = target['expr'].replace('$__rate_interval', '1m')
|
||||
result = prom(expr)
|
||||
# Diagnostics are allowed to be absent when no failure has occurred.
|
||||
if 'otelcol_' not in expr:
|
||||
result = eventually(lambda: prom(expr), timeout=45)
|
||||
panel_count += 1
|
||||
for item in prom('http_server_requests_total'):
|
||||
labels = item['metric']
|
||||
check(not {'user_id','chat_id','message_id','attachment_id','request_id','filename'} & labels.keys(), 'High cardinality metric label')
|
||||
check(chat['id'] not in json.dumps(labels), 'Raw chat ID in labels')
|
||||
# Inspect full recent log/trace data in memory, never save private test values.
|
||||
all_logs = get(proxy + 'loki/loki/api/v1/query_range?' + urllib.parse.urlencode({
|
||||
'query': '{service_name=~"messenger-api|messenger-worker"}', 'limit': 5000}), auth)
|
||||
exported = json.dumps([all_logs, trace_data])
|
||||
for forbidden in [secret_marker, alice['token'], alice['registration']['password'], base64.b64encode(content).decode()]:
|
||||
check(forbidden not in exported, 'Private test data leaked to telemetry')
|
||||
report = {'timestamp': datetime.now(timezone.utc).isoformat(), 'result': 'PASS', 'trace_id': trace,
|
||||
'span_names': sorted({s['name'] for s in spans}), 'consumer_parent_is_producer': True,
|
||||
'log_services': sorted({s['stream']['service_name'] for s in logs}),
|
||||
'metric_names_checked': required, 'dashboard_queries_checked': panel_count,
|
||||
'privacy_canaries': 'absent in recent logs and upload trace'}
|
||||
(ROOT / args.output).write_text(json.dumps(report, indent=2) + '\n')
|
||||
print('PASS: real API -> outbox -> Redis -> worker -> S3/DB trace, correlated logs, metrics and dashboard queries; privacy canaries absent.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,33 @@
|
||||
#include "telemetry.hpp"
|
||||
#include <cassert>
|
||||
#include <regex>
|
||||
|
||||
int main() {
|
||||
telemetry::Runtime runtime("messenger-test");
|
||||
assert(telemetry::route_template("/api/v1/chats/private-id/messages") == "/api/v1/chats/{chat_id}/messages");
|
||||
assert(telemetry::route_template("/secret-token") == "unmatched");
|
||||
assert(telemetry::route_template("/api/v1/attachments/private/content") == "/api/v1/attachments/{attachment_id}/content");
|
||||
const std::string parent = "00-11223344556677889900aabbccddeeff-0123456789abcdef-01";
|
||||
std::string producer;
|
||||
{
|
||||
telemetry::Span request("test.server", opentelemetry::trace::SpanKind::kServer, parent);
|
||||
assert(telemetry::inject().substr(3,32) == parent.substr(3,32));
|
||||
{
|
||||
telemetry::Span publish("test.publish", opentelemetry::trace::SpanKind::kProducer);
|
||||
producer = telemetry::inject();
|
||||
assert(producer.substr(3,32) == parent.substr(3,32));
|
||||
assert(producer != parent);
|
||||
}
|
||||
assert(telemetry::inject() != producer);
|
||||
}
|
||||
{
|
||||
telemetry::Span consumer("test.consume", opentelemetry::trace::SpanKind::kConsumer, producer);
|
||||
assert(telemetry::inject().substr(3,32) == parent.substr(3,32));
|
||||
}
|
||||
for (const auto& invalid : {"garbage", "00-00000000000000000000000000000000-0000000000000000-01"}) {
|
||||
telemetry::Span span("test.invalid", opentelemetry::trace::SpanKind::kConsumer, invalid);
|
||||
const auto actual = telemetry::inject();
|
||||
assert(std::regex_match(actual, std::regex("00-[a-f0-9]{32}-[a-f0-9]{16}-01")));
|
||||
assert(actual.substr(3,32) != parent.substr(3,32));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user