Files
mtusi2026lab7/student-tests/observability.py
T
sashadugina06 11390b65fd
Skeleton contracts / contracts (pull_request) Blocked by required conditions
feat: complete lab 7 for grade 4
2026-12-04 13:55:32 +03:00

452 lines
20 KiB
Python

#!/usr/bin/env python3
"""Read live Grafana data sources and run bounded faults in Compose lab6."""
import argparse
import base64
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
import json
import ssl
import os
from pathlib import Path
import subprocess
import sys
import time
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from uuid import uuid4
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, check
COMPOSE = ROOT / 'scripts/compose.sh'
FIXTURE = (ROOT / 'tests/fixtures/sample.png').read_bytes()
ROUTE = '/api/v1/chats/{chat_id}/messages'
SUPPRESS = (HTTPError, URLError, TimeoutError)
def now():
return datetime.now(timezone.utc).isoformat()
def compose(*args, capture=True):
result = subprocess.run([COMPOSE, *args], cwd=ROOT, check=True, text=True,
capture_output=capture, timeout=75)
return result.stdout
def sql_command(statement):
return [COMPOSE, 'exec', '-T', '--user', 'postgres', 'postgres', 'psql', '-XAt', '-v', 'ON_ERROR_STOP=1',
'-U', 'postgres', '-d', 'messenger', '-c', statement]
def sql(statement):
return subprocess.check_output(sql_command(statement), text=True, timeout=10).strip()
def wait(action, timeout=60):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
result = action()
except SUPPRESS:
result = None
if result:
return result
time.sleep(1)
raise AssertionError(f'timeout after {timeout}s')
class Grafana:
def __init__(self, url):
self.url = url
state = Path(os.getenv("LAB7_STATE", f"/private/tmp/mtusi2026lab7-{os.getuid()}"))
password = (state / "grafana/admin").read_text().strip()
self.context = ssl.create_default_context(cafile=str(state / "trust/ca.crt"))
self.headers = {'Authorization': 'Basic ' + base64.b64encode(f'admin:{password}'.encode()).decode()}
def get(self, path, **params):
query = '?' + urlencode(params) if params else ''
with urlopen(Request(self.url + path + query, headers=self.headers), timeout=10, context=self.context) as response:
return json.load(response)
def proxy(self, uid, path, **params):
return self.get(f'/api/datasources/proxy/uid/{uid}{path}', **params)
def prom(self, expression, timestamp=None):
params = {'query': expression}
if timestamp is not None:
params['time'] = timestamp
return self.proxy('prometheus', '/api/v1/query', **params)['data']['result']
def scalar(self, expression):
values = self.prom(expression)
return float(values[0]['value'][1]) if values else None
def alerts(self):
return {item['labels']['alertname']: item['state']
for item in self.proxy('prometheus', '/api/v1/alerts')['data']['alerts']}
def logs(self, query):
data = self.proxy('loki', '/loki/api/v1/query_range', query=query, limit=50,
start=int((time.time()-600)*1e9), end=time.time_ns())['data']['result']
return [json.loads(line) for stream in data for _, line, *_ in stream['values']]
def trace(self, trace_id):
trace = self.proxy('tempo', f'/api/traces/{trace_id}')
spans = []
for batch in trace.get('batches', trace.get('resourceSpans', [])):
resource = {item['key']: next(iter(item['value'].values()))
for item in batch['resource']['attributes']}
for scope in batch['scopeSpans']:
for span in scope['spans']:
spans.append(dict(span, service_name=resource['service.name']))
return spans
def save(name, data):
(ROOT / 'evidence' / (name + '.json')).write_text(json.dumps(data, indent=2, ensure_ascii=False,
allow_nan=False) + '\n')
def upload(client, actor, chat, trace_id=None):
headers = {'Content-Type': 'image/png'}
if trace_id:
headers.update(traceparent=f'00-{trace_id}-0123456789abcdef-01', tracestate='lab=synthetic')
return client.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png',
202, actor=actor, raw=FIXTURE, headers=headers, schema='Attachment')
def raw_read(client, actor, chat, trace_id=None):
headers = {'Authorization': 'Bearer ' + actor['token']}
if trace_id:
headers['traceparent'] = f'00-{trace_id}-0123456789abcdef-01'
request = Request(client.base + ROUTE.format(chat_id=chat['id']), headers=headers)
started = time.monotonic()
try:
response = urlopen(request, timeout=10, context=ssl.create_default_context(cafile=os.environ["CA_FILE"]))
except HTTPError as exc:
response = exc
except (URLError, TimeoutError):
return {'status': 0, 'seconds': time.monotonic()-started}
with response:
response.read()
return {'status': response.code, 'seconds': time.monotonic()-started,
'request_id': response.headers.get('X-Request-Id')}
def verify(client, grafana, retry):
actor, _, _, chat = client.bootstrap()
trace_id = uuid4().hex
marker = upload(client, actor, chat, trace_id)
started = time.time()
client.wait_ready(actor, marker['json'])
if retry:
# Stop uses a local, fixed Compose service. Resume even after an assertion.
compose('stop', 'worker')
try:
trace_id = uuid4().hex
marker = upload(client, actor, chat, trace_id)
attachment_id = marker['json']['id']
sql(f"""INSERT INTO pipeline_faults(attachment_id,pipeline_version,point,action)
VALUES ('{attachment_id}',1,'before_s3','temporary')""")
finally:
compose('start', 'worker')
client.wait_ready(actor, marker['json'])
request_id = marker['headers']['X-Request-Id']
required = {'attachment.accept', 'outbox.enqueue', 's3.put_object', 's3.read_original',
'job.claim', 'job.publish_ready', 'postgresql.execute', 'postgresql.transaction.close'}
def complete_trace():
spans = grafana.trace(trace_id)
by_id = {item['spanId']: item for item in spans}
consumers = [item for item in spans if item['kind'] in (5, 'SPAN_KIND_CONSUMER')]
if len(consumers) < (2 if retry else 1):
return None
for consumer in consumers:
producer = by_id.get(consumer.get('parentSpanId'))
if not producer or producer.get('parentSpanId') not in by_id:
return None
return spans if required <= {item['name'] for item in spans} else None
spans = wait(complete_trace)
check(required <= {s['name'] for s in spans}, 'missing spans along upload path')
by_id = {s['spanId']: s for s in spans}
consumers = [s for s in spans if s['kind'] in (5, 'SPAN_KIND_CONSUMER')]
check(len(consumers) >= (2 if retry else 1), 'consumer / retry span absent')
for consumer in consumers:
producer = by_id[consumer['parentSpanId']]
check(producer['kind'] in (4, 'SPAN_KIND_PRODUCER'), 'consumer parent must be producer')
check(by_id[producer['parentSpanId']]['name'] == 'attachment.accept', 'producer parent mismatch')
query = '{service_name=~"messenger-api|messenger-worker|messenger-publisher"} | json | trace_id="' + trace_id + '"'
logs = wait(lambda: (rows if (rows := grafana.logs(query)) and
{'messenger-api', 'messenger-worker', 'messenger-publisher'}
<= {row['service.name'] for row in rows} else None))
check(any(row.get('request_id') == request_id for row in logs), 'request id not correlated')
check(all(row['trace_id'] == trace_id for row in logs), 'different trace IDs in Loki')
if retry:
check({'retry','ready'} <= {row.get('outcome') for row in logs}, 'retry and ready should be in one trace')
prometheus = grafana.proxy('prometheus', '/api/v1/query_exemplars', query='lab_http_duration_seconds_bucket',
start=started-15, end=time.time())['data']
dashboard = grafana.get('/api/dashboards/uid/messenger-lab6')['dashboard']
metrics = {}
for panel in dashboard['panels']:
if panel['datasource']['uid'] != 'prometheus':
continue
metrics[panel['title']] = {target['expr']: grafana.prom(target['expr']) for target in panel['targets']}
save('signals-retry' if retry else 'signals', {
'timestamp': now(), 'trace_id': trace_id, 'request_id': request_id, 'spans': spans, 'logs': logs,
'dashboard_queries': metrics, 'exemplar_count': sum(len(x['exemplars']) for x in prometheus),
})
class Incident:
queries = {
'queue_depth': 'max(lab_queue_depth)', 'oldest_seconds': 'max(lab_oldest_job_age_seconds)',
'api_waiting': 'sum(lab_db_pool_waiting{service_name="messenger-api"})',
'api_pool_used': 'sum(lab_db_pool_used{service_name="messenger-api"})',
'workers': 'sum(lab_worker_capacity)', 'api_p95': 'histogram_quantile(0.95,sum by(le)(rate(lab_http_duration_seconds_bucket[30s])))',
'api_burn_30s': 'lab:burn_api:30s', 'api_burn_2m': 'lab:burn_api:2m',
'api_burn_5m': 'lab:burn_api:5m',
'ready_burn_30s': 'lab:burn_ready:30s', 'ready_burn_2m': 'lab:burn_ready:2m',
'ready_burn_5m': 'lab:burn_ready:5m',
'ready_burn_1h': 'lab:burn_ready:1h', 'api_burn_1h': 'lab:burn_api:1h',
'ready_cohort_1h': 'lab:sli_ready_total:1h', 'api_cohort_1h': 'lab:sli_api_total:1h',
'collector_rss': 'otelcol_process_memory_rss_bytes',
'tempo_queue': 'sum(otelcol_exporter_queue_size{exporter="otlphttp/tempo"})',
'tempo_queue_limit': 'sum(otelcol_exporter_queue_capacity{exporter="otlphttp/tempo"})',
'tempo_drop': 'sum(otelcol_exporter_send_failed_spans_total{exporter="otlphttp/tempo"})',
'tempo_enqueue_drop': 'sum(otelcol_exporter_enqueue_failed_spans_total{exporter="otlphttp/tempo"})',
}
def __init__(self, grafana, name):
self.grafana, self.name = grafana, name
self.started = time.time()
self.data = {'started': now(), 'samples': [], 'markers': {}}
def mark(self, name):
self.data['markers'][name] = {'timestamp': now(), 't': round(time.time()-self.started, 2)}
def sample(self, phase):
t = time.time()
alerts = self.grafana.alerts()
row = {'phase': phase, 't': round(t-self.started, 2), 'timestamp': now(), 'alerts': alerts}
# A single Prometheus query gets metrics at the same evaluation timestamp.
expression = ' or '.join(f'label_replace(({expr}),"measurement","{key}","","")'
for key, expr in self.queries.items())
for result in self.grafana.prom(expression, t):
value = float(result['value'][1])
if abs(value) < float('inf'):
row[result['metric']['measurement']] = value
self.data['samples'].append(row)
save(self.name, self.data)
return row
def settle(self, names, phase='recovery', timeout=330, predicate=None):
deadline = time.monotonic()+timeout
while time.monotonic() < deadline:
row = self.sample(phase)
if names.isdisjoint(row['alerts']) and (predicate is None or predicate(row)):
self.mark('resolved')
return
time.sleep(5)
raise AssertionError('alerts did not resolve')
def finish(self):
transitions = {}
names = {name for row in self.data['samples'] for name in row['alerts']}
for name in sorted(names):
fired = next((row for row in self.data['samples']
if row['alerts'].get(name) == 'firing'), None)
if fired is None:
continue
resolved = next((row for row in self.data['samples']
if row['t'] > fired['t'] and name not in row['alerts']), None)
transitions[name] = {'firing_t': fired['t'], 'resolved_t': resolved['t'] if resolved else None}
self.data['transitions'] = transitions
save(self.name, self.data)
def queue_incident(client, grafana):
actor, _, _, chat = client.bootstrap()
trial = Incident(grafana, 'incident-queue')
target = {'QueueLag', 'ReadyBurnFast', 'ReadyBurnSlow'}
trial.settle(target, phase='baseline', timeout=330)
attachments = []
compose('stop', 'worker')
trial.mark('worker_stopped')
fired = set()
try:
deadline = time.monotonic()+140
while time.monotonic() < deadline:
start = time.monotonic()
attachments.append(upload(client, actor, chat)['json'])
if len(attachments) % 3 == 1:
row = trial.sample('worker_stopped')
fired.update(name for name, state in row['alerts'].items() if state == 'firing')
time.sleep(max(0, 2 - (time.monotonic()-start)))
check(target <= fired, 'queue / ready burn alerts did not all fire')
samples = [row for row in trial.data['samples'] if row['phase'] == 'worker_stopped']
check(max(row.get('queue_depth', 0) for row in samples) > 10, 'no backlog growth')
check(max(row.get('oldest_seconds', 0) for row in samples) > 30, 'no age growth')
finally:
compose('start', 'worker')
trial.mark('worker_restarted')
trial.finish()
for attachment in attachments:
client.wait_ready(actor, attachment)
trial.mark('all_ready')
trial.data['accepted'] = len(attachments)
trial.settle(target, predicate=lambda row: row.get('queue_depth') == 0 and row.get('oldest_seconds') == 0)
trial.finish()
def db_incident(client, grafana, spike):
actor, _, _, chat = client.bootstrap()
trial = Incident(grafana, 'incident-db-spike' if spike else 'incident-db-long')
target = {'HighHTTPErrorRate', 'APIBurnFast', 'APIBurnSlow'}
trial.settle(target, phase='baseline')
statuses = Counter()
trace_id = uuid4().hex
if spike:
# A real short PostgreSQL lock. First warm the same route at 3 requests/s.
deadline = time.monotonic() + 125
while time.monotonic() < deadline:
start = time.monotonic()
reading = raw_read(client, actor, chat)
statuses[f'baseline_{reading["status"]}'] += 1
time.sleep(max(0, 1/3-(time.monotonic()-start)))
lock_seconds = 7 if spike else 140
# The transaction lock is released by PostgreSQL even if this client exits.
statement = (f"SET statement_timeout='{lock_seconds+2}s'; "
f'BEGIN; LOCK TABLE messages IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep({lock_seconds}); ROLLBACK')
lock = subprocess.Popen(sql_command(statement), cwd=ROOT, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
fired = set()
probe = None
try:
wait(lambda: sql("""SELECT count(*) FROM pg_locks
WHERE relation='messages'::regclass AND mode='AccessExclusiveLock'
AND granted""") == '1', timeout=6)
trial.mark('db_lock_acquired')
with ThreadPoolExecutor(max_workers=32) as pool:
first = pool.submit(raw_read, client, actor, chat, trace_id)
concurrency = 11 if spike else 30
load = [pool.submit(raw_read, client, actor, chat) for _ in range(concurrency)]
trial.sample('db_lock')
for response in load:
statuses[str(response.result()['status'])] += 1
probe = first.result()
statuses[str(probe['status'])] += 1
while lock.poll() is None:
start = time.monotonic()
# Fixed number of in-flight requests, no client retries.
if spike:
reads = [pool.submit(raw_read, client, actor, chat)]
else:
reads = [pool.submit(raw_read, client, actor, chat) for _ in range(6)]
row = trial.sample('db_lock')
fired.update(name for name, state in row['alerts'].items() if state == 'firing')
for response in reads:
statuses[str(response.result()['status'])] += 1
time.sleep(max(0, 1-(time.monotonic()-start)))
finally:
lock.wait(timeout=lock_seconds+5)
trial.mark('db_lock_released')
trial.finish()
check(probe and probe['status'] == 503, 'locked SQL did not yield expected API 503')
spans = wait(lambda: grafana.trace(trace_id))
sql_spans = [span for span in spans if span['name'] == 'postgresql.execute']
check(any(int(span['endTimeUnixNano'])-int(span['startTimeUnixNano']) >= 4e9 for span in sql_spans),
'trace does not distinguish a slow DB query')
request_id = probe['request_id']
logs = wait(lambda: grafana.logs('{service_name="messenger-api"} | json | request_id="' + request_id + '"'))
check(any(row['trace_id'] == trace_id and row['status'] == 503 for row in logs), 'no correlated HTTP error log')
trial.data.update(statuses=dict(statuses), failing_probe=probe, trace_id=trace_id, spans=spans, logs=logs)
check(raw_read(client, actor, chat)['status'] == 200, 'DB did not recover')
if spike:
deadline = time.monotonic()+45
while time.monotonic() < deadline:
trial.sample('post_spike')
for _ in range(9):
reading = raw_read(client, actor, chat)
statuses[f'recovery_{reading["status"]}'] += 1
time.sleep(1/3)
observations = [row['alerts'] for row in trial.data['samples']]
check(not any(set(row) & {'APIBurnFast','APIBurnSlow'} for row in observations),
'short spike caused an API burn alert')
else:
check(target <= fired, 'sustained DB incident did not fire all API alerts')
trial.data['statuses'] = dict(statuses)
trial.finish()
trial.settle(target)
trial.finish()
def telemetry_incident(client, grafana):
actor, _, _, chat = client.bootstrap()
trial = Incident(grafana, 'incident-telemetry')
base = trial.sample('baseline')
check(base.get('collector_rss', 0) > 0, 'collector RSS metric missing')
compose('stop', 'tempo')
trial.mark('tempo_stopped')
confirmed = 0
try:
deadline = time.monotonic()+50
while time.monotonic() < deadline:
client.message(actor, chat, 'synthetic upload during trace outage')
marker = upload(client, actor, chat)
client.wait_ready(actor, marker['json'])
confirmed += 1
if confirmed % 3 == 1:
trial.sample('tempo_stopped')
time.sleep(1)
finally:
compose('start', 'tempo')
trial.mark('tempo_restarted')
trial.finish()
trial.data['writes_and_ready'] = confirmed
loss = lambda row: row.get('tempo_drop', 0)+row.get('tempo_enqueue_drop', 0)
check(max(map(loss, trial.data['samples'])) > loss(base), 'trace losses not observed')
wait(lambda: trace_after_recovery(client, grafana, actor, chat),
timeout=100)
trial.mark('new_trace_available')
trial.settle({'TelemetryExportLoss'})
trial.finish()
def trace_after_recovery(client, grafana, actor, chat):
trace_id = uuid4().hex
upload(client, actor, chat, trace_id)
try:
return wait(lambda: grafana.trace(trace_id), timeout=8)
except AssertionError:
return None
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('test', choices=['signals', 'retry', 'queue', 'spike', 'db', 'telemetry'])
parser.add_argument('--base-url', default='https://localhost:8443')
parser.add_argument('--grafana', default='https://localhost:3007')
args = parser.parse_args()
client, grafana = Client(args.base_url), Grafana(args.grafana)
if args.test in ('signals', 'retry'):
verify(client, grafana, args.test == 'retry')
else:
{
'queue': queue_incident,
'spike': lambda c,g: db_incident(c,g,True),
'db': lambda c,g: db_incident(c,g,False),
'telemetry': telemetry_incident,
}[args.test](client, grafana)
print(f'PASS {args.test} {now()}')
if __name__ == '__main__':
main()