lab6 done
This commit is contained in:
Executable
+20
@@ -0,0 +1,20 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
umask 077
|
||||
mkdir -p secrets
|
||||
chmod 700 secrets
|
||||
for name in postgres_password cursor_key s3_root_secret_key s3_secret_key; do
|
||||
if [ ! -s "secrets/$name" ]; then
|
||||
openssl rand -hex 32 > "secrets/$name"
|
||||
fi
|
||||
done
|
||||
for name in s3_root_access_key s3_access_key; do
|
||||
if [ ! -s "secrets/$name" ]; then
|
||||
openssl rand -hex 8 > "secrets/$name"
|
||||
fi
|
||||
done
|
||||
# Compose mounts files directly on Linux; the unprivileged API must read them.
|
||||
# The host directory remains private (0700).
|
||||
chmod 444 secrets/postgres_password secrets/cursor_key secrets/s3_root_access_key secrets/s3_root_secret_key secrets/s3_access_key secrets/s3_secret_key
|
||||
printf '%s\n' 'Local secrets are ready.'
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
if docker compose version >/dev/null 2>&1; then
|
||||
exec docker compose --env-file /dev/null -f compose.yaml "$@"
|
||||
fi
|
||||
exec docker-compose --env-file /dev/null -f compose.yaml "$@"
|
||||
@@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Measure actual trace retention and bounded buffering during a backend outage."""
|
||||
import datetime
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
from observability_common import ROOT, compose, get_json, ready, save, scalar, start_services
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client
|
||||
|
||||
|
||||
def snapshot():
|
||||
return {'failed_spans': scalar('sum(otelcol_exporter_send_failed_spans_total)'),
|
||||
'refused_spans': scalar('sum(otelcol_receiver_refused_spans_total)'),
|
||||
'queued_batches': scalar('otelcol_exporter_queue_size{exporter="otlphttp/tempo"}'),
|
||||
'rss_bytes': scalar('otelcol_process_memory_rss_bytes')}
|
||||
|
||||
|
||||
def main():
|
||||
ready()
|
||||
c = Client('http://127.0.0.1:18086')
|
||||
actor = c.user('backend')
|
||||
chat = c.call('POST', '/api/v1/chats', 201, actor=actor,
|
||||
body={'title': 'Backend outage', 'member_ids': [actor['id']]}, schema='Chat')['json']
|
||||
report = {'started_at': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'before': snapshot()}
|
||||
trace_ids, timeline = [], []
|
||||
try:
|
||||
compose('stop', 'tempo')
|
||||
started = time.monotonic()
|
||||
for index in range(35):
|
||||
response = c.message(actor, chat, 'synthetic backend outage')
|
||||
trace_ids.append(response['headers']['X-Trace-Id'])
|
||||
if index % 5 == 0:
|
||||
timeline.append({'seconds': round(time.monotonic()-started, 2), **snapshot()})
|
||||
time.sleep(1)
|
||||
report['during'] = timeline
|
||||
report['successful_writes'] = len(trace_ids)
|
||||
finally:
|
||||
start_services('tempo')
|
||||
for _ in range(24):
|
||||
time.sleep(2)
|
||||
if snapshot()['queued_batches'] == 0:
|
||||
break
|
||||
time.sleep(6)
|
||||
report['after'] = snapshot()
|
||||
retained = 0
|
||||
trace_results = []
|
||||
for trace_id in trace_ids:
|
||||
found = False
|
||||
try:
|
||||
d = get_json('http://127.0.0.1:13200/api/traces/' + trace_id)
|
||||
found = bool(d.get('batches') or d.get('resourceSpans'))
|
||||
except Exception:
|
||||
pass
|
||||
retained += int(found)
|
||||
trace_results.append({'trace_id': trace_id, 'found': found})
|
||||
report['request_trace_results'] = trace_results
|
||||
report['retained_request_traces'] = retained
|
||||
report['missing_request_traces'] = len(trace_ids)-retained
|
||||
report['exporter_failed_spans_delta'] = report['after']['failed_spans']-report['before']['failed_spans']
|
||||
report['receiver_refused_spans_delta'] = report['after']['refused_spans']-report['before']['refused_spans']
|
||||
info = json.loads(subprocess.check_output(['docker', 'inspect', '--format',
|
||||
'{"oom":{{json .State.OOMKilled}},"memory_limit":{{.HostConfig.Memory}}}', 'mtusi2026lab6-collector-1'], text=True))
|
||||
report['collector'] = info
|
||||
assert len(trace_ids) == 35, 'business writes failed'
|
||||
assert not info['oom'], 'Collector exceeded memory cgroup'
|
||||
assert max(x['queued_batches'] for x in timeline) <= 256, 'unbounded export queue'
|
||||
assert report['after']['queued_batches'] == 0, 'export queue did not drain'
|
||||
assert max(x['rss_bytes'] for x in timeline) < info['memory_limit'], 'RSS exceeded cgroup'
|
||||
report['status'] = 'PASS'
|
||||
report['finished_at'] = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||
save('evidence/lab6-backend-outage.json', report)
|
||||
print(json.dumps({k: report[k] for k in ('status', 'successful_writes', 'retained_request_traces', 'missing_request_traces', 'exporter_failed_spans_delta')}))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Local lab6 evidence helpers. Never persist credentials or response bodies."""
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def compose(*args, check=True):
|
||||
return subprocess.run([str(ROOT / 'scripts/compose.sh'), *args], cwd=ROOT,
|
||||
check=check, capture_output=True, text=True)
|
||||
|
||||
|
||||
def start_services(*services):
|
||||
# Compose `start` may start dependencies as well. Fault injection must keep
|
||||
# an intentionally stopped dependency stopped until its explicit recovery.
|
||||
for service in services:
|
||||
ids = compose('ps', '-a', '-q', service).stdout.split()
|
||||
if not ids:
|
||||
raise RuntimeError('Service container not created: ' + service)
|
||||
subprocess.run(['docker', 'start', *ids], check=True, stdout=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def get_json(url, timeout=10):
|
||||
with urllib.request.urlopen(urllib.request.Request(url, headers={'Accept': 'application/json'}), timeout=timeout) as r:
|
||||
return json.load(r)
|
||||
|
||||
|
||||
def prom(query):
|
||||
result = get_json('http://127.0.0.1:19090/api/v1/query?' + urllib.parse.urlencode({'query': query}))
|
||||
if result.get('status') != 'success':
|
||||
raise RuntimeError('Prometheus query failed')
|
||||
return result['data']['result']
|
||||
|
||||
|
||||
def scalar(query):
|
||||
return sum(float(x['value'][1]) for x in prom(query))
|
||||
|
||||
|
||||
def ready(base='http://127.0.0.1:18086', timeout=120):
|
||||
end = time.monotonic() + timeout
|
||||
while time.monotonic() < end:
|
||||
try:
|
||||
if get_json(base + '/health/ready'):
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
raise RuntimeError('API readiness deadline exceeded')
|
||||
|
||||
|
||||
def save(path, value):
|
||||
path = ROOT / path
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n')
|
||||
@@ -0,0 +1,189 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Track 1: fixed-rate, equal-sized trials with measured sampling retention."""
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import datetime
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from observability_common import ROOT, compose, get_json, prom, ready, save
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client
|
||||
|
||||
|
||||
def percentile(values, p):
|
||||
return round(sorted(values)[max(0, math.ceil(len(values) * p) - 1)] * 1000, 3) if values else None
|
||||
|
||||
|
||||
def snapshot():
|
||||
queries = {
|
||||
'exported_spans': 'sum(otelcol_exporter_sent_spans_total)',
|
||||
'failed_spans': 'sum(otelcol_exporter_send_failed_spans_total)',
|
||||
'accepted_spans': 'sum(otelcol_receiver_accepted_spans_total)',
|
||||
'refused_spans': 'sum(otelcol_receiver_refused_spans_total)',
|
||||
'tempo_ingested_bytes': 'sum(tempo_distributor_bytes_received_total)',
|
||||
'loki_ingested_bytes': 'sum(loki_distributor_bytes_received_total)',
|
||||
'prometheus_samples': 'sum(prometheus_tsdb_head_samples_appended_total)',
|
||||
}
|
||||
result = {}
|
||||
for key, query in queries.items():
|
||||
rows = prom(query)
|
||||
result[key] = sum(float(x['value'][1]) for x in rows) if rows else None
|
||||
return result
|
||||
|
||||
|
||||
def samples(stop, output):
|
||||
while not stop.is_set():
|
||||
result = subprocess.run(['docker', 'stats', '--no-stream', '--format', '{{json .}}'], capture_output=True, text=True)
|
||||
for line in result.stdout.splitlines():
|
||||
row = json.loads(line)
|
||||
if row['Name'].startswith('mtusi2026lab6-'):
|
||||
output.append({'at': time.time(), **{k: row[k] for k in ('Name', 'CPUPerc', 'MemUsage')}})
|
||||
stop.wait(1)
|
||||
|
||||
|
||||
def configure(disabled, ratio):
|
||||
# Compose interpolation only; no secrets or .env files are read.
|
||||
os.environ['OTEL_SDK_DISABLED'] = str(disabled).lower()
|
||||
os.environ['OTEL_TRACES_SAMPLER_ARG'] = str(ratio)
|
||||
compose('up', '-d', '--no-deps', '--force-recreate', 'api', 'worker')
|
||||
ready()
|
||||
time.sleep(8)
|
||||
|
||||
|
||||
def trial(name, disabled, ratio, args, repetition):
|
||||
configure(disabled, ratio)
|
||||
c = Client(args.base_url)
|
||||
actor = c.user('research')
|
||||
chat = c.call('POST', '/api/v1/chats', 201, actor=actor,
|
||||
body={'title': 'Synthetic research', 'member_ids': [actor['id']]}, schema='Chat')['json']
|
||||
# Equal warmup before every trial, including telemetry off.
|
||||
for _ in range(20):
|
||||
c.call('GET', '/api/v1/users/me', actor=actor, schema='User')
|
||||
time.sleep(6)
|
||||
before = snapshot()
|
||||
stop, resource = threading.Event(), []
|
||||
sampler = threading.Thread(target=samples, args=(stop, resource), daemon=True)
|
||||
sampler.start()
|
||||
known, latency, errors, uploads = [], [], [], []
|
||||
lock = threading.Lock()
|
||||
started = time.monotonic()
|
||||
|
||||
def request(index):
|
||||
scheduled = started + index / args.rate
|
||||
time.sleep(max(0, scheduled - time.monotonic()))
|
||||
client = Client(args.base_url)
|
||||
trace_id = None
|
||||
headers = {}
|
||||
begin = time.monotonic()
|
||||
outcome, kind = 'ok', 'read'
|
||||
try:
|
||||
if index % 20 == 0:
|
||||
kind = 'upload'
|
||||
headers['Content-Type'] = 'image/png'
|
||||
response = client.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=synthetic.png',
|
||||
202, actor=actor, raw=(ROOT / 'tests/fixtures/sample.png').read_bytes(),
|
||||
headers=headers, schema='Attachment')
|
||||
att = response['json']
|
||||
with lock:
|
||||
uploads.append(att)
|
||||
elif index % 20 == 1:
|
||||
kind = 'client_error'
|
||||
response = client.call('GET', '/api/v1/users/me', 401, headers=headers)
|
||||
elif index % 5 == 0:
|
||||
kind = 'write'
|
||||
headers['Idempotency-Key'] = uuid.uuid4().hex
|
||||
response = client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=actor,
|
||||
body={'text': 'synthetic fixed-size benchmark message'}, headers=headers, schema='Message')
|
||||
else:
|
||||
response = client.call('GET', '/api/v1/users/me', actor=actor, headers=headers, schema='User')
|
||||
trace_id = response['headers'].get('X-Trace-Id')
|
||||
except Exception as exc:
|
||||
outcome = type(exc).__name__
|
||||
with lock:
|
||||
elapsed_request = time.monotonic() - begin
|
||||
latency.append(elapsed_request)
|
||||
known.append({'trace_id': trace_id, 'kind': kind, 'outcome': outcome, 'elapsed_seconds': elapsed_request})
|
||||
if outcome != 'ok':
|
||||
errors.append(outcome)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
|
||||
list(pool.map(request, range(args.requests)))
|
||||
elapsed = time.monotonic() - started
|
||||
for att in uploads:
|
||||
c.wait_ready(actor, att)
|
||||
stop.set()
|
||||
sampler.join(timeout=10)
|
||||
# Flush SDK batches, Collector and backend scrape before taking counters.
|
||||
time.sleep(12)
|
||||
after = snapshot()
|
||||
retained = {kind: {'sent': 0, 'found': 0} for kind in ('read', 'write', 'upload', 'client_error')}
|
||||
slow = {'definition': 'slowest 5 percent of this trial by measured client latency', 'sent': 0, 'found': 0}
|
||||
slow_ids = {id(x) for x in sorted(known, key=lambda x: x['elapsed_seconds'], reverse=True)[:max(1, math.ceil(.05*len(known)))]}
|
||||
for row in known:
|
||||
retained[row['kind']]['sent'] += 1
|
||||
is_slow = id(row) in slow_ids
|
||||
slow['sent'] += int(is_slow)
|
||||
try:
|
||||
trace = get_json('http://127.0.0.1:13200/api/traces/' + (row['trace_id'] or 'missing'))
|
||||
if trace.get('batches') or trace.get('resourceSpans'):
|
||||
retained[row['kind']]['found'] += 1
|
||||
slow['found'] += int(is_slow)
|
||||
except Exception:
|
||||
pass
|
||||
return {'configuration': name, 'repetition': repetition, 'disabled': disabled, 'sampling_ratio': ratio,
|
||||
'requests': args.requests, 'target_rps': args.rate, 'concurrency_limit': args.concurrency,
|
||||
'elapsed_seconds': round(elapsed, 3), 'successful_rps': round((args.requests-len(errors))/elapsed, 3),
|
||||
'unexpected_errors': len(errors), 'error_types': errors,
|
||||
'all_request_latency_ms': {f'p{int(p*100)}': percentile(latency, p) for p in (.5, .95, .99)},
|
||||
'ready_uploads': len(uploads), 'counter_before': before, 'counter_after': after,
|
||||
'counter_delta': {k: after[k]-before[k] if after[k] is not None and before[k] is not None else None for k in before},
|
||||
'trace_retention': retained, 'slow_request_trace_retention': slow, 'resources': resource}
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('--base-url', default='http://127.0.0.1:18086')
|
||||
p.add_argument('--requests', type=int, default=120)
|
||||
p.add_argument('--rate', type=float, default=8)
|
||||
p.add_argument('--concurrency', type=int, default=4)
|
||||
p.add_argument('--repetitions', type=int, default=2)
|
||||
args = p.parse_args()
|
||||
if args.requests < 20 or args.rate <= 0 or args.concurrency < 1 or args.repetitions < 1:
|
||||
p.error('requests>=20, rate>0, concurrency>=1, repetitions>=1 required')
|
||||
result = {'started_at': datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
||||
'method': 'Fixed-rate schedule, fixed request count/mix; 20 warmups; SDK and backend flush; sampled IDs queried from Tempo.',
|
||||
'trials': []}
|
||||
try:
|
||||
configs = [('off', True, 1), ('full', False, 1), ('ten_percent', False, .1), ('balanced', False, .5)]
|
||||
for rep in range(args.repetitions):
|
||||
# Counterbalance order on second repetition.
|
||||
for name, disabled, ratio in (configs if rep % 2 == 0 else list(reversed(configs))):
|
||||
print('Running', name, 'repetition', rep + 1, flush=True)
|
||||
row = trial(name, disabled, ratio, args, rep + 1)
|
||||
result['trials'].append(row)
|
||||
save('evidence/lab6-research.json', result)
|
||||
print(json.dumps({k: row[k] for k in ('configuration', 'unexpected_errors', 'all_request_latency_ms', 'trace_retention')}), flush=True)
|
||||
assert row['unexpected_errors'] == 0, 'Unexpected business errors during research'
|
||||
found = sum(x['found'] for x in row['trace_retention'].values())
|
||||
if name == 'off':
|
||||
assert found == 0, 'SDK off still exported request traces'
|
||||
elif name == 'full':
|
||||
assert found == args.requests, 'Full sampling lost request traces'
|
||||
else:
|
||||
assert 0 < found < args.requests, 'Sampling setting had no observed effect'
|
||||
result['status'] = 'PASS'
|
||||
finally:
|
||||
configure(False, 1)
|
||||
result['finished_at'] = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||
save('evidence/lab6-research.json', result)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,149 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Repeatable worker/DB/backend faults on this lab's isolated Compose project."""
|
||||
import argparse
|
||||
import datetime
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from observability_common import ROOT, compose, get_json, prom, ready, save, start_services
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client
|
||||
|
||||
|
||||
def alerts():
|
||||
return get_json('http://127.0.0.1:19090/api/v1/alerts')['data']['alerts']
|
||||
|
||||
|
||||
def collect_trace(trace_id):
|
||||
for _ in range(20):
|
||||
try:
|
||||
trace = get_json('http://127.0.0.1:13200/api/traces/' + trace_id)
|
||||
if trace.get('batches') or trace.get('resourceSpans'):
|
||||
save('evidence/trace-' + trace_id + '.json', trace)
|
||||
query = '{service_name=~"messenger-api|messenger-worker"} | trace_id = "' + trace_id + '"'
|
||||
logs = get_json('http://127.0.0.1:13100/loki/api/v1/query_range?' + urllib.parse.urlencode({'query': query, 'since': '1h', 'limit': 100}))
|
||||
if not logs['data']['result']:
|
||||
raise RuntimeError('correlated logs not yet available')
|
||||
save('evidence/logs-' + trace_id + '.json', logs)
|
||||
return {'trace_id': trace_id, 'trace_file': 'evidence/trace-' + trace_id + '.json',
|
||||
'log_streams': len(logs['data']['result']), 'logs_file': 'evidence/logs-' + trace_id + '.json'}
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(2)
|
||||
raise RuntimeError('trace/log correlation not found in backend')
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('--base-url', default='http://127.0.0.1:18086')
|
||||
args = p.parse_args()
|
||||
ready(args.base_url)
|
||||
c = Client(args.base_url)
|
||||
actor = c.user('incidents')
|
||||
chat = c.call('POST', '/api/v1/chats', 201, actor=actor,
|
||||
body={'title': 'Synthetic incidents', 'member_ids': [actor['id']]}, schema='Chat')['json']
|
||||
report = {'started_at': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'cases': {}}
|
||||
traces = []
|
||||
try:
|
||||
print('Worker outage', flush=True)
|
||||
compose('stop', 'worker')
|
||||
attachments = []
|
||||
started = time.monotonic()
|
||||
for _ in range(6):
|
||||
trace_id = uuid.uuid4().hex
|
||||
result = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=synthetic.png',
|
||||
202, actor=actor, raw=(ROOT / 'tests/fixtures/sample.png').read_bytes(),
|
||||
headers={'Content-Type': 'image/png', 'traceparent': '00-' + trace_id + '-1234567890123456-01'},
|
||||
schema='Attachment')
|
||||
attachments.append(result['json'])
|
||||
traces.append(trace_id)
|
||||
timeline = []
|
||||
for _ in range(6):
|
||||
time.sleep(5)
|
||||
timeline.append({'seconds': round(time.monotonic()-started, 2), 'alerts': alerts(),
|
||||
'queue': prom('messenger_queue_depth'), 'age': prom('messenger_queue_oldest_age_seconds')})
|
||||
# Keep S3 unavailable for the first attempt; the same durable trace must
|
||||
# cover the failed attempt, retry publication and eventual ready.
|
||||
compose('stop', 'minio')
|
||||
start_services('worker')
|
||||
time.sleep(10)
|
||||
report['cases']['s3_retry'] = {'alerts_during': alerts(), 'jobs': prom('messenger_jobs_total')}
|
||||
start_services('minio')
|
||||
ready(args.base_url)
|
||||
for att in attachments:
|
||||
c.wait_ready(actor, att)
|
||||
time.sleep(35)
|
||||
report['cases']['worker_stop'] = {'queued': len(attachments), 'ready_after_recovery': len(attachments),
|
||||
'timeline': timeline, 'resolved': alerts(),
|
||||
'queue_after': prom('messenger_queue_depth')}
|
||||
save('evidence/lab6-faults.json', report)
|
||||
print('DB lock', flush=True)
|
||||
lock = subprocess.Popen([str(ROOT / 'scripts/compose.sh'), 'exec', '-T', 'postgres', 'psql', '-U', 'messenger',
|
||||
'-d', 'messenger', '-v', 'ON_ERROR_STOP=1', '-c',
|
||||
'BEGIN; LOCK TABLE messages IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep(45); COMMIT;'],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
time.sleep(2)
|
||||
observations = []
|
||||
def write(index):
|
||||
trace_id = uuid.uuid4().hex
|
||||
result = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', [201, 500, 503], actor=actor,
|
||||
body={'text': 'synthetic incident'}, headers={'Idempotency-Key': uuid.uuid4().hex,
|
||||
'traceparent': '00-' + trace_id + '-1234567890123456-01'})
|
||||
return {'status': result['status'], 'elapsed': result['elapsed'], 'trace_id': trace_id}
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
for block in range(7):
|
||||
observations.extend(pool.map(write, range(4)))
|
||||
report['cases']['db_lock'] = {'requests': observations, 'alerts_during': alerts()}
|
||||
save('evidence/lab6-faults.json', report)
|
||||
lock.wait(timeout=60)
|
||||
c.message(actor, chat, 'synthetic recovery')
|
||||
recovery_timeline = []
|
||||
for _ in range(24):
|
||||
time.sleep(5)
|
||||
state = alerts()
|
||||
recovery_timeline.append(state)
|
||||
if not any(a['state'] == 'firing' for a in state):
|
||||
break
|
||||
c.message(actor, chat, 'synthetic recovery probe')
|
||||
report['cases']['db_lock']['recovery_alerts'] = recovery_timeline
|
||||
report['cases']['db_lock']['alerts_after'] = alerts()
|
||||
failed = next((x for x in observations if x['status'] >= 500), None)
|
||||
if failed:
|
||||
traces.append(failed['trace_id'])
|
||||
report['correlation'] = [collect_trace(t) for t in (traces[0], traces[-1])]
|
||||
print('Telemetry backend outage', flush=True)
|
||||
compose('stop', 'tempo')
|
||||
successful = 0
|
||||
for _ in range(30):
|
||||
c.message(actor, chat, 'synthetic telemetry outage')
|
||||
successful += 1
|
||||
time.sleep(.5)
|
||||
report['cases']['tempo_stop'] = {'successful_writes': successful,
|
||||
'exporter_failed': prom('otelcol_exporter_send_failed_spans_total'),
|
||||
'queue_size': prom('otelcol_exporter_queue_size'),
|
||||
'collector_memory': prom('otelcol_process_memory_rss_bytes')}
|
||||
start_services('tempo')
|
||||
time.sleep(20)
|
||||
report['cases']['tempo_stop']['after'] = {'queue_size': prom('otelcol_exporter_queue_size'),
|
||||
'collector_memory': prom('otelcol_process_memory_rss_bytes')}
|
||||
assert any(a['labels']['alertname'] == 'QueueLagGrowing' and a['state'] == 'firing'
|
||||
for row in report['cases']['worker_stop']['timeline'] for a in row['alerts']), 'queue alert never fired'
|
||||
assert any(a['labels']['alertname'] == 'APIHighErrorRate' and a['state'] == 'firing'
|
||||
for a in report['cases']['db_lock']['alerts_during']), 'API alert never fired'
|
||||
assert not any(a['state'] == 'firing' for a in report['cases']['db_lock']['alerts_after']), 'alerts did not resolve'
|
||||
assert all(float(x['value'][1]) == 0 for x in report['cases']['worker_stop']['queue_after']), 'backlog not empty'
|
||||
report['status'] = 'PASS'
|
||||
finally:
|
||||
start_services('worker', 'tempo', 'minio')
|
||||
report['finished_at'] = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||
save('evidence/lab6-faults.json', report)
|
||||
print(json.dumps({'status': report['status'], 'cases': list(report['cases'])}), flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
exec ./scripts/compose.sh restart postgres redis minio worker api gateway collector prometheus loki tempo grafana
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
: "${TARGET_INSTANCE_ID:?target instance is required}"
|
||||
for container in $(./scripts/compose.sh ps -q api); do
|
||||
alias=$(docker inspect --format '{{.Config.Hostname}}' "$container")
|
||||
if [ "$alias" = "$TARGET_INSTANCE_ID" ]; then
|
||||
docker stop --time 8 "$container" >/dev/null
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
printf '%s\n' 'No matching API replica in this project' >&2
|
||||
exit 1
|
||||
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Create a compact, reproducible table from measured track-1 JSON."""
|
||||
import csv
|
||||
import json
|
||||
import re
|
||||
import statistics
|
||||
|
||||
from observability_common import ROOT
|
||||
|
||||
|
||||
def mib(value):
|
||||
match = re.fullmatch(r'([0-9.]+)([A-Za-z]+)', value.strip())
|
||||
if not match:
|
||||
raise ValueError('Unrecognized Docker memory unit')
|
||||
factor = {'B': 1/1048576, 'KiB': 1/1024, 'MiB': 1, 'GiB': 1024,
|
||||
'kB': 1000/1048576, 'MB': 1000000/1048576, 'GB': 1000000000/1048576}
|
||||
return float(match[1]) * factor[match[2]]
|
||||
|
||||
|
||||
def summarize(row):
|
||||
by_container = {}
|
||||
for resource in row['resources']:
|
||||
group = by_container.setdefault(resource['Name'], {'cpu': [], 'mem': []})
|
||||
group['cpu'].append(float(resource['CPUPerc'].rstrip('%')))
|
||||
group['mem'].append(mib(resource['MemUsage'].split('/')[0]))
|
||||
app = [v for k, v in by_container.items() if '-api-' in k or '-worker-' in k]
|
||||
telemetry = [v for k, v in by_container.items() if any('-' + service + '-' in k for service in ('collector', 'prometheus', 'loki', 'tempo', 'grafana'))]
|
||||
def resources(items):
|
||||
return round(sum(statistics.mean(v['cpu']) for v in items), 3), round(sum(max(v['mem']) for v in items), 3)
|
||||
app_cpu, app_ram = resources(app)
|
||||
telemetry_cpu, telemetry_ram = resources(telemetry)
|
||||
sent = sum(v['sent'] for v in row['trace_retention'].values())
|
||||
found = sum(v['found'] for v in row['trace_retention'].values())
|
||||
return {'configuration': row['configuration'], 'repetition': row['repetition'],
|
||||
'rps': row['successful_rps'], 'unexpected_errors': row['unexpected_errors'],
|
||||
**row['all_request_latency_ms'], 'app_cpu_percent_sum_mean': app_cpu,
|
||||
'app_ram_mib_sum_peak': app_ram, 'telemetry_cpu_percent_sum_mean': telemetry_cpu,
|
||||
'telemetry_ram_mib_sum_peak': telemetry_ram,
|
||||
'sent_requests': sent, 'retained_request_traces': found,
|
||||
'missing_request_traces': sent-found,
|
||||
**{k: v for k, v in row['counter_delta'].items()}}
|
||||
|
||||
|
||||
def main():
|
||||
report = json.loads((ROOT / 'evidence/lab6-research.json').read_text())
|
||||
rows = [summarize(row) for row in report['trials']]
|
||||
if not rows:
|
||||
raise RuntimeError('No completed trials')
|
||||
with (ROOT / 'evidence/lab6-research.csv').open('w', newline='') as f:
|
||||
writer = csv.DictWriter(f, fieldnames=list(rows[0]))
|
||||
writer.writeheader()
|
||||
writer.writerows(rows)
|
||||
print('| Config | Repeat | RPS | p50 ms | p95 ms | p99 ms | App CPU % | App MiB | Telemetry CPU % | Telemetry MiB | Request traces |')
|
||||
print('| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |')
|
||||
for row in rows:
|
||||
print('| {configuration} | {repetition} | {rps} | {p50} | {p95} | {p99} | {app_cpu_percent_sum_mean} | {app_ram_mib_sum_peak} | {telemetry_cpu_percent_sum_mean} | {telemetry_ram_mib_sum_peak} | {retained_request_traces}/{sent_requests} |'.format(**row))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify live provisioned sources, dashboard queries and metric label policy."""
|
||||
import datetime
|
||||
import json
|
||||
import re
|
||||
import urllib.parse
|
||||
|
||||
from observability_common import get_json, prom, save
|
||||
|
||||
|
||||
def main():
|
||||
targets = get_json('http://127.0.0.1:19090/api/v1/targets')['data']['activeTargets']
|
||||
assert targets and all(t['health'] == 'up' for t in targets), 'Prometheus target is down'
|
||||
dashboard = get_json('http://127.0.0.1:13000/api/dashboards/uid/messenger')['dashboard']
|
||||
assert dashboard['uid'] == 'messenger' and len(dashboard['panels']) >= 10
|
||||
results = []
|
||||
for panel in dashboard['panels']:
|
||||
if panel.get('datasource', {}).get('uid') != 'prometheus':
|
||||
continue
|
||||
for target in panel.get('targets', []):
|
||||
query = target['expr'].replace('$__rate_interval', '1m')
|
||||
rows = prom(query)
|
||||
results.append({'panel': panel['title'], 'query': query, 'series': len(rows)})
|
||||
query = '{__name__=~"messenger_.*"}'
|
||||
series = get_json('http://127.0.0.1:19090/api/v1/series?' + urllib.parse.urlencode({'match[]': query}))['data']
|
||||
prohibited = {'user_id', 'chat_id', 'message_id', 'attachment_id', 'request_id', 'filename', 'url', 'http_target'}
|
||||
for row in series:
|
||||
assert not prohibited.intersection(row), 'Forbidden metric label'
|
||||
assert not re.search(r'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}', row.get('route', '')), 'Raw UUID in route'
|
||||
required = {'messenger_http_requests_total', 'messenger_http_duration_seconds_bucket', 'messenger_jobs_total',
|
||||
'messenger_job_duration_seconds_bucket', 'messenger_attachment_ready_seconds_bucket',
|
||||
'messenger_queue_depth', 'messenger_queue_oldest_age_seconds', 'messenger_db_pool_used',
|
||||
'messenger_db_pool_waiting', 'messenger_worker_capacity', 'messenger_worker_busy'}
|
||||
names = {row['__name__'] for row in series}
|
||||
assert required <= names, 'Required metrics absent: ' + str(sorted(required-names))
|
||||
report = {'at': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'status': 'PASS',
|
||||
'targets': {t['labels']['job']: t['health'] for t in targets}, 'dashboard_uid': dashboard['uid'],
|
||||
'panel_count': len(dashboard['panels']), 'queries': results,
|
||||
'metric_series_checked': len(series), 'required_metrics': sorted(required), 'label_policy': 'PASS'}
|
||||
save('evidence/lab6-provisioning.json', report)
|
||||
print(json.dumps({'status': 'PASS', 'panels': report['panel_count'], 'queries': len(results), 'label_policy': 'PASS'}))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,17 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Wait for the local gateway without disclosing application configuration."""
|
||||
import argparse
|
||||
import time
|
||||
import urllib.request
|
||||
p=argparse.ArgumentParser();p.add_argument('--base-url',default='http://localhost:18086');args=p.parse_args()
|
||||
deadline=time.monotonic()+120
|
||||
while time.monotonic()<deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(args.base_url+'/health/ready',timeout=3) as response:
|
||||
if response.status==200:
|
||||
print('API is ready');break
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
else:
|
||||
raise SystemExit('API did not become ready within 120 seconds')
|
||||
Reference in New Issue
Block a user