"""lab6, уровни 3–4: сигналы своего приложения в хранилищах и связь запрос -> лог -> trace -> задание. make telemetry-check (= python student-tests/check_telemetry.py) 1. Контролируемый HTTP-запрос (POST сообщения): по X-Request-Id ответа в Loki находится структурный лог (event=http.request, severity, service.name, trace_id, span_id), по его trace_id в Tempo — server span того же запроса (тот же request_id) с дочерними SQL-спанами. 2. Upload с одной внедрённой временной ошибкой worker (точка worker_transient): одна трасса upload (SERVER) -> send (PRODUCER) -> process (CONSUMER, попытка 1, retry) -> jobs.retry -> send (PRODUCER) -> process (CONSUMER, попытка 2, ready) -> S3 PutObject + SQL COMMIT результата. Связь parent-child проверяется по span_id; логи worker по trace_id: job.retry и job.ready. 3. Метрики своего приложения: HTTP (метод, маршрут-шаблон, код), задания (тип, исход), длительности (histogram), очередь, пул БД, насыщение worker, CPU/RAM процессов. Ни у одной серии нет labels с ID (user/chat/message/attachment/request), маршрут — шаблон. 4. Запрещённые данные: текст сообщения, пароль и токен не находятся ни в логах (поиск по Loki), ни в атрибутах спанов этих трасс; query-строки (filename) в спанах нет. Токены и пароли в вывод не попадают: ищутся по значениям в памяти процесса. """ import re import time import uuid import obs import ops from filegen import wait_status from helpers import Client, check, idempotency, run UUID = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") FORBIDDEN_LABELS = {"user_id", "chat_id", "message_id", "attachment_id", "request_id", "url_path", "filename", "messenger_attachment_id", "messenger_request_id", "messenger_job_id", "job_id", "trace_id"} def child_of(spans, parent, **match): return [s for s in spans if s["parent"] == parent["span_id"] and all(s.get(k) == v or s["attrs"].get(k) == v for k, v in match.items())] def controlled_request(api, alice, chat, marker): response = api.call("POST", f"/api/v1/chats/{chat['id']}/messages", 201, actor=alice, headers=idempotency(), body={"text": marker}, schema="Message") request_id = response["headers"]["X-Request-Id"] logs = obs.wait_logs(f'{{service_name="messenger-api"}} | request_id="{request_id}"') entry = logs[-1]["labels"] for field in ("service_name", "trace_id", "span_id", "event", "severity_text"): check(entry.get(field), f"log for X-Request-Id has no {field}: {sorted(entry)}") check(entry["event"] == "http.request", f"unexpected event {entry['event']}") trace_id = entry["trace_id"] spans = obs.tempo_trace(trace_id) server = [s for s in spans if s["kind"] == "SERVER"] check(len(server) == 1, f"expected one server span, got {len(server)}") server = server[0] check(server["attrs"].get("messenger.request_id") == request_id, "server span request_id differs from header") check(server["attrs"].get("http.route") == "/api/v1/chats/{chat_id}/messages", "route template expected") check(entry["span_id"] == server["span_id"], "log span_id must be the server span") sql = [s for s in spans if s["kind"] == "CLIENT" and s["attrs"].get("db.system") == "postgresql"] check(any(s["name"] == "INSERT" for s in sql), "no INSERT span under the request") print(f"1. POST message: X-Request-Id={request_id} -> Loki: event={entry['event']} severity={entry['severity_text']} " f"service={entry['service_name']} instance={entry.get('service_instance_id')} trace_id={trace_id} " f"span_id={entry['span_id']}") print(f" Tempo: trace {trace_id}, server span {server['span_id']} (request_id matches), {len(sql)} SQL spans:") for line in obs.tree(spans): print(" " + line) return spans def upload_chain(api, alice, bob, chat): ops.arm("worker", "worker_transient", "1") att, _content = api.attachment(alice, chat) print(f"2. upload with one injected transient failure: attachment_id={att['id']} -> 202 queued") ready = wait_status(api, bob, att["id"], ("ready",), seconds=90) check(ready["status"] == "ready", "attachment must become ready after the retry") def complete(spans): return sum(1 for s in spans if s["kind"] == "CONSUMER") >= 2 and \ any(s["attrs"].get("messenger.job.outcome") == "ready" for s in spans) trace_id, spans = obs.wait_trace(f'{{ span.messenger.attachment.id = "{att["id"]}" && kind = server }}', complete, 90) by_kind = {k: [s for s in spans if s["kind"] == k] for k in ("SERVER", "PRODUCER", "CONSUMER")} upload = by_kind["SERVER"][0] check(upload["service"] == "messenger-api" and upload["attrs"].get("http.response.status_code") == 202, "upload server span expected") send1 = child_of(spans, upload, kind="PRODUCER") check(len(send1) == 1, "producer span must be a child of the upload span") consume1 = child_of(spans, send1[0], kind="CONSUMER") check(len(consume1) == 1 and consume1[0]["service"] == "messenger-worker", "consumer must be a child of producer") consume1 = consume1[0] check(consume1["attrs"].get("messenger.job.attempt") == 1 and consume1["attrs"].get("messenger.job.outcome") == "retry" and consume1["status"] == "ERROR", "attempt 1 must be a failed (retry) consumer span") retry = child_of(spans, consume1, name="jobs.retry") check(len(retry) == 1, "jobs.retry span expected under attempt 1") send2 = child_of(spans, retry[0], kind="PRODUCER") check(len(send2) == 1 and send2[0]["attrs"].get("messenger.job.attempt") == 2, "the retry message must be published as a child of jobs.retry") consume2 = child_of(spans, send2[0], kind="CONSUMER") check(len(consume2) == 1 and consume2[0]["attrs"].get("messenger.job.outcome") == "ready", "attempt 2 must be ready") consume2 = consume2[0] puts = [s for s in spans if s["attrs"].get("rpc.method") == "PutObject" and s["service"] == "messenger-worker"] check(len(puts) >= 4, "original + 3 variants must be written to S3 in the trace") completes = [s for s in spans if s["name"] == "jobs.complete" and s["parent"] == consume2["span_id"]] check(completes and [s for s in spans if s["parent"] == completes[0]["span_id"] and s["name"] == "UPDATE"], "COMMIT of the result (SQL UPDATE under jobs.complete) expected") check({s["service"] for s in spans} == {"messenger-api", "messenger-worker"}, "both services must be in one trace") print(f" one trace {trace_id}: SERVER -> PRODUCER -> CONSUMER(attempt 1, retry, ERROR) -> jobs.retry -> " f"PRODUCER(attempt 2) -> CONSUMER(attempt 2, ready) -> {len(puts)} x S3 PutObject, SQL under jobs.complete") for line in obs.tree([s for s in spans if not (s["kind"] == "CLIENT" and "rpc.method" not in s["attrs"])]): print(" " + line) worker_logs = obs.wait_logs(f'{{service_name="messenger-worker"}} | trace_id="{trace_id}"', count=2) events = [e["labels"].get("event") for e in worker_logs] check("job.retry" in events and "job.ready" in events, f"worker logs of the trace: {events}") api_logs = obs.loki(f'{{service_name="messenger-api"}} | trace_id="{trace_id}"') print(f" Loki by trace_id: worker events {events}; api events {[e['labels'].get('event') for e in api_logs]}") return spans, att def metrics_check(): wanted = { "HTTP requests (counter, method/route/code)": 'sum by (http_request_method, http_route, http_response_status_code) ' '(http_server_request_duration_seconds_count{job="messenger-api", http_route="/api/v1/chats/{chat_id}/messages"})', "HTTP duration histogram buckets": 'count(http_server_request_duration_seconds_bucket{job="messenger-api"})', "jobs processed by outcome": 'sum by (messenger_job_type, outcome) (messenger_jobs_processed_total)', "job duration histogram": 'sum by (outcome) (messenger_job_duration_seconds_count)', "time to ready histogram": 'sum(messenger_attachment_time_to_ready_seconds_count)', "queue depth": 'max by (queue, state) (messenger_queue_depth)', "oldest job age": 'max by (queue) (messenger_queue_oldest_age_seconds)', "DB pool": 'sum by (job, db_client_connection_state) (db_client_connection_count)', "worker busy/capacity": 'sum(messenger_worker_capacity)', "process CPU": 'sum by (job) (process_cpu_time_seconds_total{job=~"messenger-.*"})', "process RAM": 'sum by (job) (process_memory_usage_bytes{job=~"messenger-.*"})', } deadline = time.monotonic() + 40 # метрики уходят раз в 10 с while True: missing = [name for name, query in wanted.items() if not obs.prom(query)] outcomes = {r["metric"].get("outcome") for r in obs.prom(wanted["jobs processed by outcome"])} if not missing and {"ready", "retry"} <= outcomes: break check(time.monotonic() < deadline, f"metrics missing: {missing}, job outcomes {outcomes}") time.sleep(3) print("3. metrics of the application in Prometheus:") for name, query in wanted.items(): rows = obs.prom(query) sample = ", ".join(f"{ {k: v for k, v in r['metric'].items()} }={r['value']:g}" for r in rows[:3]) print(f" {name}: {len(rows)} series; {sample[:220]}") series = obs.get_json(obs.PROM_URL + "/api/v1/series?match[]=" + "%7Bjob%3D~%22messenger-.*%22%7D")["data"] labels = set().union(*(s.keys() for s in series)) check(not labels & FORBIDDEN_LABELS, f"forbidden labels in metrics: {labels & FORBIDDEN_LABELS}") routes = {s.get("http_route") for s in series if s.get("http_route")} check(not any(UUID.search(r) for r in routes), f"raw IDs in http_route: {routes}") print(f" {len(series)} series of messenger-api/worker; label names: {', '.join(sorted(labels))}") print(f" no ID labels; http_route values are templates: {', '.join(sorted(routes))}") def forbidden_data(alice, marker, traces): secrets = {"message text": marker, "password": alice["registration"]["password"], "session token": alice["token"]} for what, value in secrets.items(): found = obs.loki(f'{{service_name=~"messenger-api|messenger-worker"}} |= `{value}`', minutes=30) check(not found, f"{what} found in logs") for spans in traces: for span in spans: text = repr(span["attrs"]) for what, value in secrets.items(): check(value not in text, f"{what} found in span {span['name']}") check("filename=" not in text and "Bearer" not in text and "authorization" not in text.lower(), f"query string or auth header in span {span['name']}") print("4. message text, password and session token: 0 hits in Loki (30 min) and in span attributes; " "no query strings / Authorization in spans") def main(): api = Client(timeout=20) alice, bob, _eve, chat = api.bootstrap() marker = "секретный текст " + uuid.uuid4().hex message_spans = controlled_request(api, alice, chat, marker) upload_spans, _att = upload_chain(api, alice, bob, chat) metrics_check() forbidden_data(alice, marker, [message_spans, upload_spans]) print("PASS: request -> log -> trace by X-Request-Id/trace_id; upload -> publish -> consume -> retry -> S3/DB in one " "trace with parent-child links; app metrics without ID labels; no secrets or message bodies in telemetry") if __name__ == "__main__": run(main)