import base64 from datetime import datetime, timezone import json import os from pathlib import Path import sys import time from types import SimpleNamespace from urllib.parse import urlencode from urllib.request import Request from uuid import uuid4 sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from scripts import lab def arguments(): saved = lab.settings() return SimpleNamespace(project=os.environ.get('LAB6_PROJECT', saved['COMPOSE_PROJECT_NAME']), port=int(os.environ.get('LAB6_PORT', saved['HTTP_PORT'])), ttl=int(os.environ.get('LAB6_TTL', saved['SESSION_TTL_SECONDS'])), test_port=18089, grafana_port=int(os.environ["LAB6_GRAFANA_PORT"]) if "LAB6_GRAFANA_PORT" in os.environ else None) def wait(predicate, seconds=90): deadline = time.monotonic() + seconds last = None while time.monotonic() < deadline: try: result = predicate() if result: return result except (RuntimeError, ValueError, OSError) as error: last = type(error).__name__ time.sleep(1) raise RuntimeError('Telemetry condition timed out' + (': ' + last if last else '')) def backend(args, url): code = ('import sys,urllib.request; ' 'r=urllib.request.urlopen(urllib.request.Request(sys.argv[1],headers={"Accept":"application/json"}),timeout=8); ' 'print(r.read().decode())') return json.loads(lab.compose(args, 'exec', '-T', 'api1', 'python', '-c', code, url, quiet=True)) def backend_many(args, urls): code = ('import sys,json,urllib.request; ' 'print(json.dumps([json.load(urllib.request.urlopen(urllib.request.Request(u,headers={"Accept":"application/json"}),timeout=8)) for u in json.loads(sys.argv[1])]))') return json.loads(lab.compose(args, 'exec', '-T', 'api1', 'python', '-c', code, json.dumps(urls), quiet=True)) def prom(args, query, at=None): params = {'query': query} if at: params['time'] = at result = backend(args, 'http://prometheus:9090/api/v1/query?' + urlencode(params)) if result['status'] != 'success': raise RuntimeError('Prometheus query failed') return result['data']['result'] def logs(args, query, start=None): params = {'query': query, 'limit': 2000, 'start': str(int((start or time.time() - 300) * 1e9)), 'end': str(time.time_ns()), 'direction': 'backward'} result = backend(args, 'http://loki:3100/loki/api/v1/query_range?' + urlencode(params)) entries = [] for stream in result['data']['result']: for value in stream['values']: item = {**stream['stream'], 'timestamp_ns': value[0], 'body': value[1]} if len(value) > 2: item.update(value[2]) entries.append(item) return entries def trace_data(args, trace_id): return backend(args, 'http://tempo:3200/api/traces/' + trace_id) def spans(data): found = [] if isinstance(data, dict): if 'spanId' in data and 'name' in data: found.append(data) for value in data.values(): found.extend(spans(value)) elif isinstance(data, list): for value in data: found.extend(spans(value)) return found def correlated(args, query, kind, start=None): entry = wait(lambda: next((item for item in logs(args, query, start) if item.get('trace_id')), None)) data = wait(lambda: trace_data(args, entry['trace_id'])) candidates = [span for span in spans(data) if span.get('kind') in (kind, 'SPAN_KIND_' + kind)] if not candidates or not any(int(span['endTimeUnixNano']) > int(span['startTimeUnixNano']) for span in candidates): raise RuntimeError('Real span with required kind/duration not found') matched = next((span for span in candidates if (span['spanId'] if len(span['spanId']) == 16 else base64.b64decode(span['spanId']).hex()) == entry['span_id']), None) if matched is None: raise RuntimeError('Log span ID does not match the trace') return {'trace_id': entry['trace_id'], 'span_id': entry['span_id'], 'event': entry['body'], 'kind': kind, 'span_name': matched['name'], 'span_status': matched.get('status', {}), 'span_duration_seconds': (int(matched['endTimeUnixNano']) - int(matched['startTimeUnixNano'])) / 1e9, 'span_attributes': matched.get('attributes', []), 'log': entry} def sql(args, statement): return lab.compose(args, 'exec', '-T', 'db', 'psql', '-U', 'messenger', '-d', 'messenger', '-v', 'ON_ERROR_STOP=1', '-At', '-c', statement, quiet=True).strip() def job_id(args, attachment): return sql(args, "SELECT id FROM attachment_jobs WHERE attachment_id='" + attachment['id'] + "'") def grafana(args): port = int(lab.environment(args)['GRAFANA_PORT']) password = (lab.ROOT / 'secrets/grafana_password').read_text().strip() authorization = 'Basic ' + base64.b64encode(('admin:' + password).encode()).decode() def get(path): with lab.LOCAL_HTTP.open(Request('http://127.0.0.1:' + str(port) + path, headers={'Authorization': authorization}), timeout=10) as response: return json.load(response) sources = wait(lambda: get('/api/datasources')) if {source['uid'] for source in sources} != {'prometheus', 'loki', 'tempo'}: raise RuntimeError('Grafana data sources missing') dashboard = get('/api/dashboards/uid/messenger-lab6')['dashboard'] queries = [target['expr'] for panel in dashboard['panels'] for target in panel.get('targets', []) if panel.get('datasource', {}).get('uid') == 'prometheus'] for query in queries: prom(args, query.replace("$instance", ".*")) for source in sources: health = get('/api/datasources/uid/' + source['uid'] + '/health') if health['status'] != 'OK': raise RuntimeError('Grafana data source health failed') loki = next(source for source in sources if source['uid'] == 'loki') if loki['jsonData']['derivedFields'][0]['url'] != '${__value.raw}': raise RuntimeError('Loki trace link is not provisioned correctly') query_checks = [] for uid, query in (('loki', {'expr': '{service_name="messenger-api"}', 'queryType': 'range', 'maxLines': 5}), ('tempo', {'query': '{ resource.service.name = "messenger-api" }', 'queryType': 'traceql', 'limit': 5})): payload = json.dumps({'from': str(int((time.time() - 300) * 1000)), 'to': str(time.time_ns() // 1000000), 'queries': [{'refId': 'A', 'datasource': {'type': uid, 'uid': uid}, **query}]}).encode() request = Request('http://127.0.0.1:' + str(port) + '/api/ds/query', data=payload, headers={'Authorization': authorization, 'Content-Type': 'application/json'}) with lab.LOCAL_HTTP.open(request, timeout=15) as response: result = json.load(response)['results']['A'] if result.get('error') or result.get('status') != 200 or not result.get('frames'): raise RuntimeError('Grafana log/trace query failed') query_checks.append(uid) return {'log_trace_queries': query_checks, 'dashboard_uid': dashboard['uid'], 'data_sources': [s['uid'] for s in sources], 'prometheus_queries_valid': len(queries), 'source_health': 'PASS'} def telemetry(args): c = lab.client(args) start = time.time() actor, bob, eve, chat = c.bootstrap() marker = 'private-content-' + uuid4().hex c.message(actor, chat, marker) response = c.call('GET', '/api/v1/users/me', actor=actor) request_id = response['headers']['X-Request-Id'] api = correlated(args, '{service_name="messenger-api"} | request_id="' + request_id + '"', 'SERVER', start) filename = 'private-name-' + uuid4().hex + '.png' raw = (lab.ROOT / 'tests/fixtures/sample.png').read_bytes() attachment = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + filename, 202, actor=actor, raw=raw, headers={'Content-Type': 'image/png'}, schema='Attachment')['json'] c.wait_ready(actor, attachment) job = job_id(args, attachment) worker = correlated(args, '{service_name="messenger-worker"} | job_id="' + job + '" | event="job.completed"', 'CONSUMER', start) try: lab.compose(args, 'stop', '--timeout', '10', 'worker') broken, _ = c.attachment(actor, chat) stage = sql(args, "SELECT staging_key FROM attachment_jobs WHERE attachment_id='" + broken['id'] + "'") code = ("from src.objects import Objects; from io import BytesIO; o=Objects(); " "o.put(" + repr(stage) + ",BytesIO(b'broken'),6,'image/png'); o.close()") lab.compose(args, 'exec', '-T', 'api1', 'python', '-c', code, quiet=True) finally: lab.compose(args, 'start', 'worker') wait(lambda: sql(args, "SELECT status FROM attachments WHERE id='" + broken['id'] + "'") == 'failed') failed_job = job_id(args, broken) failed = correlated(args, '{service_name="messenger-worker"} | job_id="' + failed_job + '" | event="job.completed"', 'CONSUMER', start) failed_counter = wait(lambda: prom(args, 'messenger_jobs_total{outcome="failed"}')) for _ in range(4): c.call('GET', '/api/v1/chats/' + str(uuid4()), 404, actor=actor) c.call('GET', '/not-a-route-' + uuid4().hex, 404) c.call('GET', '/api/v1/users/me', 401) http = wait(lambda: prom(args, 'messenger_http_requests_total{route="/api/v1/users/me"}')) jobs = wait(lambda: prom(args, 'messenger_jobs_total{outcome="success"}')) histograms = wait(lambda: prom(args, 'messenger_job_duration_seconds_bucket')) http_histograms = wait(lambda: prom(args, 'messenger_http_duration_seconds_bucket')) series = prom(args, 'messenger_http_requests_total') forbidden = {'request_id', 'user_id', 'chat_id', 'message_id', 'attachment_id', 'filename', 'url', 'url_full'} for sample in series: labels = sample['metric'] if forbidden.intersection(labels) or any(value in labels.get('route', '') for value in (chat['id'], actor['id'])): raise RuntimeError('High cardinality metric attributes') current_instances = '|'.join(item['instance_id'] for item in lab.instance_map(args).values()) if prom(args, '{__name__=~"http_server_request_duration.*",service_instance_id=~"' + current_instances + '"}'): raise RuntimeError('Duplicate native FastAPI metrics found') records = logs(args, '{service_name=~"messenger-api|messenger-worker"}', start) ids = sorted({item['trace_id'] for item in records if item.get('trace_id')}) traces = wait(lambda: backend_many(args, ['http://tempo:3200/api/traces/' + value for value in ids])) exported = json.dumps(records, ensure_ascii=False) + json.dumps(traces, ensure_ascii=False) private = [marker, filename, actor['token'], actor['registration']['password'], actor['registration']['display_name']] if any(value in exported for value in private): raise RuntimeError('Private data exported') if not all(key in api['log'] for key in ('severity_text', 'service_name', 'event', 'trace_id', 'span_id')): raise RuntimeError('Required structured log fields missing') result = {'status': 'PASS', 'api': api, 'worker': worker, 'failed_worker': failed, 'failed_job_series': len(failed_counter), 'privacy': 'PASS', 'route_cardinality': 'PASS', 'no_duplicate_instrumentation': True, 'http_series': len(http), 'job_series': len(jobs), 'http_histogram_buckets': len(http_histograms), 'job_histogram_buckets': len(histograms), 'grafana': grafana(args), 'metric_time': time.time()} lab.evidence('telemetry.json', result) lab.say('PASS: real API/worker traces and related logs, metrics, privacy and Grafana provisioning') return result def incidents(args): c = lab.client(args) actor, bob, eve, chat = c.bootstrap() started = time.time() lab.run(args, [lab.interpreter(), '-X', 'utf8', 'tests/load.py', '--base-url', lab.base_url(args), '--duration', '30', '--concurrency', '4', '--output', 'evidence/load.json']) queue = [] try: lab.compose(args, 'stop', '--timeout', '10', 'worker') stopped_at = time.time() for _ in range(3): item, _ = c.attachment(actor, chat) state = c.call('GET', '/api/v1/attachments/' + item['id'], actor=actor, schema='Attachment')['json'] if state['status'] != 'queued': raise RuntimeError('Stopped worker processed a job') queue.append((item, job_id(args, item))) time.sleep(5) pending = logs(args, '{service_name="messenger-worker"} | event="job.started"', stopped_at) if any(record.get('job_id') in {job for _, job in queue} for record in pending): raise RuntimeError('Stopped worker emitted processing events') finally: lab.compose(args, 'start', 'worker') completed = [] for item, job in queue: c.wait_ready(actor, item) completed.append(correlated(args, '{service_name="messenger-worker"} | job_id="' + job + '" | event="job.completed"', 'CONSUMER', stopped_at)) worker_incident = {'started_at': stopped_at, 'queued_jobs': [job for _, job in queue], 'accepted_logs': wait(lambda: logs(args, '{service_name="messenger-api"} | event="job.accepted"', stopped_at)), 'recovered_jobs': completed, 'recovered_at': time.time()} try: lab.compose(args, 'stop', '--timeout', '10', 'db') db_at = time.time() response = c.call('GET', '/api/v1/users/me', 503, actor=actor) request_id = response['headers']['X-Request-Id'] db_trace = correlated(args, '{service_name="messenger-api"} | request_id="' + request_id + '"', 'SERVER', db_at) db_logs = wait(lambda: logs(args, '{service_name="messenger-api"} | event="dependency.postgresql_unavailable"', db_at)) errors = wait(lambda: prom(args, 'messenger_http_requests_total{status_class="5xx",route="/api/v1/users/me"}')) finally: lab.compose(args, 'start', 'db') lab.wait_ready(args) c.call('GET', '/api/v1/users/me', actor=actor) result = {'status': 'PASS', 'started_at': started, 'worker': worker_incident, 'postgresql': {'started_at': db_at, 'request': db_trace, 'dependency_logs': db_logs[:4], 'error_series': errors, 'recovered_at': time.time(), 'recovered_status': 200}} lab.evidence('incidents.json', result) lab.say('PASS: bounded worker and PostgreSQL incidents observed and recovered') return result def outage(args): c = lab.client(args) actor, bob, eve, chat = c.bootstrap() before = lab.states(args) cases = [] for service in ('otel-collector', 'loki'): try: lab.compose(args, 'stop', '--timeout', '10', service) start = time.monotonic() confirmations = [] for index in range(6): confirmations.append(c.message(actor, chat, 'telemetry-outage-' + str(index))['json']['id']) item, _ = c.attachment(actor, chat) c.wait_ready(actor, item) time.sleep(5) c.call('GET', '/health/ready', schema='Health') elapsed = time.monotonic() - start finally: lab.compose(args, 'start', service) response = c.call('GET', '/api/v1/users/me', actor=actor) observed = correlated(args, '{service_name="messenger-api"} | request_id="' + response['headers']['X-Request-Id'] + '"', 'SERVER') cases.append({'stopped': service, 'duration_seconds': round(elapsed, 2), 'confirmed_messages': len(confirmations), 'ready_attachments': 6, 'business_ready': 200, 'telemetry_recovered': observed}) preserved = telemetry(args) lab.restart(args) lab.wait_ready(args) wait(lambda: trace_data(args, preserved['api']['trace_id'])) wait(lambda: logs(args, '{service_name="messenger-api"} | trace_id="' + preserved['api']['trace_id'] + '"')) wait(lambda: prom(args, 'messenger_http_requests_total', preserved['metric_time'])) after = lab.states(args) if any(after[name]['oom_killed'] for name in after): raise RuntimeError('Container OOM observed') result = {'status': 'PASS', 'cases': cases, 'history_after_restart': 'PASS', 'oom_killed': False, 'preserved_trace_id': preserved['api']['trace_id'], 'same_volumes': all(before[name]['volumes'] == after[name]['volumes'] for name in before), 'loss_policy': 'Bounded in-memory SDK/Collector queues; telemetry during outage may be lost.'} lab.evidence('outage.json', result) lab.say('PASS: telemetry outages do not break messages/jobs; stored telemetry survives restart') return result if __name__ == '__main__': mode = sys.argv[1] {'telemetry': telemetry, 'incidents': incidents, 'outage': outage}[mode](arguments())