Закрыть требования ЛР6 на оценку 4
This commit is contained in:
+5
-1
@@ -24,6 +24,7 @@ python3 tests/smoke.py --base-url http://localhost:8080
|
||||
|
||||
```sh
|
||||
make test-observability # dashboard, alerts, Prometheus, Loki и Tempo
|
||||
make test-retry-trace # временная S3-ошибка и retry в одной трассе
|
||||
make test-alert-worker # временно останавливает и восстанавливает worker
|
||||
make test-alert-database # временно останавливает и восстанавливает PostgreSQL
|
||||
make test-telemetry-outage # временно останавливает и восстанавливает Loki/Tempo
|
||||
@@ -31,8 +32,11 @@ make test-telemetry-outage # временно останавливает и
|
||||
|
||||
Отказные сценарии изменяют состояние только перечисленных контейнеров и всегда
|
||||
выполняют восстановление в `finally`. Используются уникальные синтетические данные;
|
||||
секреты и tokens не печатаются. Worker-тест ждёт `QueueOldestJobGrowing` в
|
||||
секреты и tokens не печатаются. Retry-тест временно отключает S3 и проверяет
|
||||
две producer/consumer попытки в одной трассе. Worker-тест ждёт `QueueOldestJobGrowing` в
|
||||
`Alerting`, затем `Normal`; DB-тест аналогично проверяет `ApiHighServerErrorRate`.
|
||||
Тест telemetry outage держит backends выключенными более 30 с и фиксирует RSS
|
||||
Collector и `send_failed` counters.
|
||||
Окна alerts намеренно делают эти два теста не мгновенными. Запускайте их
|
||||
последовательно, а не параллельно.
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.parse
|
||||
|
||||
from client import Client
|
||||
|
||||
@@ -40,6 +41,70 @@ def grafana_rules() -> dict:
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def internal_json(url: str) -> dict:
|
||||
"""Читает JSON из внутреннего observability-сервиса через Grafana-контейнер."""
|
||||
|
||||
result = compose(
|
||||
"exec", "-T", "grafana", "wget", "-qO-", url, capture=True
|
||||
)
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def database_failure_evidence(start_ns: int) -> dict[str, str]:
|
||||
"""Находит связанный лог и ошибочный PostgreSQL CLIENT span."""
|
||||
|
||||
deadline = time.monotonic() + 30
|
||||
while time.monotonic() < deadline:
|
||||
query = urllib.parse.urlencode({
|
||||
"query": (
|
||||
'{service_name="messenger-api"} | json '
|
||||
'| logger="app.error" | message=~".*(database|socket).*"'
|
||||
),
|
||||
"start": str(start_ns),
|
||||
"end": str(time.time_ns()),
|
||||
"direction": "backward",
|
||||
"limit": "20",
|
||||
})
|
||||
loki = internal_json(
|
||||
"http://loki:3100/loki/api/v1/query_range?" + query
|
||||
)
|
||||
streams = loki.get("data", {}).get("result", [])
|
||||
if not streams:
|
||||
time.sleep(2)
|
||||
continue
|
||||
entry = streams[0]["values"][0]
|
||||
metadata = entry[2] if len(entry) > 2 else {}
|
||||
body = json.loads(entry[1])
|
||||
trace_id = metadata.get("trace_id") or body.get("trace_id")
|
||||
if not trace_id:
|
||||
time.sleep(2)
|
||||
continue
|
||||
trace = internal_json(f"http://tempo:3200/api/traces/{trace_id}")
|
||||
for batch in trace.get("batches", []):
|
||||
scopes = batch.get(
|
||||
"scopeSpans", batch.get("instrumentationLibrarySpans", [])
|
||||
)
|
||||
for scope in scopes:
|
||||
for span in scope.get("spans", []):
|
||||
attributes = {
|
||||
item["key"]: next(iter(item.get("value", {}).values()), "")
|
||||
for item in span.get("attributes", [])
|
||||
}
|
||||
if (
|
||||
span.get("kind") == "SPAN_KIND_CLIENT"
|
||||
and attributes.get("db.system") == "postgresql"
|
||||
and span.get("status", {}).get("code") == "STATUS_CODE_ERROR"
|
||||
):
|
||||
return {
|
||||
"trace_id": trace_id,
|
||||
"log_message": body.get("message", ""),
|
||||
"db_span": span.get("name", ""),
|
||||
"db_system": "postgresql",
|
||||
}
|
||||
time.sleep(2)
|
||||
raise RuntimeError("linked PostgreSQL error log/trace was not found")
|
||||
|
||||
|
||||
def rule_state(title: str) -> str:
|
||||
"""Находит alert по заголовку и возвращает его текущее состояние."""
|
||||
|
||||
@@ -98,6 +163,7 @@ def database_scenario(base_url: str):
|
||||
"""Останавливает PostgreSQL и проверяет firing/resolved для alert по 5xx."""
|
||||
|
||||
Client(base_url).call("GET", "/health/ready", schema="Health")
|
||||
incident_started_ns = time.time_ns()
|
||||
compose("stop", "postgres")
|
||||
load = subprocess.Popen(
|
||||
[
|
||||
@@ -108,10 +174,12 @@ def database_scenario(base_url: str):
|
||||
],
|
||||
cwd=ROOT,
|
||||
)
|
||||
evidence = None
|
||||
try:
|
||||
firing, detect_seconds = wait_state(
|
||||
"ApiHighServerErrorRate", {"alerting", "firing"}, 130
|
||||
)
|
||||
evidence = database_failure_evidence(incident_started_ns)
|
||||
finally:
|
||||
load.terminate()
|
||||
try:
|
||||
@@ -137,6 +205,10 @@ def database_scenario(base_url: str):
|
||||
"detect_seconds": round(detect_seconds, 1),
|
||||
"resolved_state": normal,
|
||||
"recover_seconds": round(recover_seconds, 1),
|
||||
"trace_id": evidence["trace_id"],
|
||||
"log_message": evidence["log_message"],
|
||||
"db_span": evidence["db_span"],
|
||||
"db_system": evidence["db_system"],
|
||||
"result": "PASS",
|
||||
}, ensure_ascii=False))
|
||||
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Создаёт временную S3-ошибку и доказывает retry в одной Tempo-трассе."""
|
||||
import argparse
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.parse
|
||||
|
||||
from client import Client
|
||||
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
|
||||
def compose(*args: str, capture: bool = False):
|
||||
"""Запускает Docker Compose и при необходимости возвращает его вывод."""
|
||||
|
||||
return subprocess.run(
|
||||
["docker", "compose", *args], cwd=ROOT, check=True, text=True,
|
||||
capture_output=capture,
|
||||
)
|
||||
|
||||
|
||||
def internal_json(url: str) -> dict:
|
||||
"""Читает Loki/Tempo JSON через внутреннюю сеть Compose."""
|
||||
|
||||
result = compose(
|
||||
"exec", "-T", "grafana", "wget", "-qO-", url, capture=True
|
||||
)
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def wait_retry_log(since: str, timeout: int = 45) -> None:
|
||||
"""Ждёт запись worker о планировании повторной попытки."""
|
||||
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
result = compose("logs", "--since", since, "worker", capture=True)
|
||||
if "job.retry_scheduled" in result.stdout + result.stderr:
|
||||
return
|
||||
time.sleep(1)
|
||||
raise RuntimeError("worker did not schedule retry")
|
||||
|
||||
|
||||
def trace_id_for_attachment(attachment_id: str) -> str:
|
||||
"""Находит trace_id лога приёма конкретного синтетического вложения."""
|
||||
|
||||
deadline = time.monotonic() + 45
|
||||
while time.monotonic() < deadline:
|
||||
now_ns = time.time_ns()
|
||||
query = urllib.parse.urlencode(
|
||||
{
|
||||
"query": (
|
||||
'{service_name="messenger-api"} | json '
|
||||
f'| event="attachment.accepted" | attachment_id="{attachment_id}"'
|
||||
),
|
||||
"start": str(now_ns - 600_000_000_000),
|
||||
"end": str(now_ns),
|
||||
"direction": "backward",
|
||||
"limit": "5",
|
||||
}
|
||||
)
|
||||
payload = internal_json(
|
||||
"http://loki:3100/loki/api/v1/query_range?" + query
|
||||
)
|
||||
streams = payload.get("data", {}).get("result", [])
|
||||
if streams:
|
||||
entry = streams[0]["values"][0]
|
||||
metadata = entry[2] if len(entry) > 2 else {}
|
||||
trace_id = metadata.get("trace_id")
|
||||
if not trace_id:
|
||||
trace_id = json.loads(entry[1]).get("trace_id")
|
||||
if trace_id:
|
||||
return trace_id
|
||||
time.sleep(2)
|
||||
raise RuntimeError("attachment trace_id is absent in Loki")
|
||||
|
||||
|
||||
def trace_span_names(trace_id: str) -> list[str]:
|
||||
"""Ждёт полную трассу и возвращает имена всех её spans."""
|
||||
|
||||
deadline = time.monotonic() + 60
|
||||
last: list[str] = []
|
||||
while time.monotonic() < deadline:
|
||||
payload = internal_json(f"http://tempo:3200/api/traces/{trace_id}")
|
||||
names: list[str] = []
|
||||
for batch in payload.get("batches", []):
|
||||
scopes = batch.get(
|
||||
"scopeSpans", batch.get("instrumentationLibrarySpans", [])
|
||||
)
|
||||
for scope in scopes:
|
||||
names.extend(span.get("name", "") for span in scope.get("spans", []))
|
||||
last = names
|
||||
if names.count("attachments publish") >= 2 and names.count("attachments process") >= 2:
|
||||
return names
|
||||
time.sleep(2)
|
||||
raise RuntimeError(f"retry spans are incomplete: {last}")
|
||||
|
||||
|
||||
def main():
|
||||
"""Внедряет временный отказ S3, восстанавливает его и проверяет retry trace."""
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
args = parser.parse_args()
|
||||
client = Client(args.base_url, timeout=10)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
compose("stop", "-t", "1", "worker")
|
||||
attachment = None
|
||||
retry_seen = False
|
||||
try:
|
||||
attachment, _ = client.attachment(alice, chat)
|
||||
since = datetime.now(timezone.utc).isoformat()
|
||||
compose("stop", "s3")
|
||||
compose("up", "-d", "--no-deps", "worker")
|
||||
wait_retry_log(since)
|
||||
retry_seen = True
|
||||
finally:
|
||||
compose("start", "s3")
|
||||
compose("up", "-d", "--no-deps", "worker")
|
||||
if attachment is None or not retry_seen:
|
||||
raise RuntimeError("retry scenario was not created")
|
||||
time.sleep(5)
|
||||
ready = client.wait_ready(bob, attachment, wait_seconds=120)
|
||||
trace_id = trace_id_for_attachment(ready["id"])
|
||||
names = trace_span_names(trace_id)
|
||||
if not any(name.startswith("s3 ") for name in names):
|
||||
raise RuntimeError("S3 spans are absent from retry trace")
|
||||
if not any(name.startswith(("SELECT ", "INSERT ", "UPDATE ", "connect")) for name in names):
|
||||
raise RuntimeError("SQL spans are absent from retry trace")
|
||||
print(json.dumps({
|
||||
"scenario": "retry_trace",
|
||||
"attachment_id": ready["id"],
|
||||
"trace_id": trace_id,
|
||||
"producer_spans": names.count("attachments publish"),
|
||||
"consumer_spans": names.count("attachments process"),
|
||||
"result": "PASS",
|
||||
}))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -5,6 +5,7 @@ import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.parse
|
||||
|
||||
from client import Client
|
||||
|
||||
@@ -21,24 +22,57 @@ def compose(*args: str, capture: bool = False):
|
||||
)
|
||||
|
||||
|
||||
def prometheus_value(query: str) -> float:
|
||||
"""Читает одно числовое значение Prometheus через внутреннюю сеть Compose."""
|
||||
|
||||
url = "http://prometheus:9090/api/v1/query?" + urllib.parse.urlencode(
|
||||
{"query": query}
|
||||
)
|
||||
result = compose(
|
||||
"exec", "-T", "grafana", "wget", "-qO-", url, capture=True
|
||||
)
|
||||
payload = json.loads(result.stdout)
|
||||
series = payload.get("data", {}).get("result", [])
|
||||
if not series:
|
||||
return 0.0
|
||||
return float(series[0]["value"][1])
|
||||
|
||||
|
||||
def main():
|
||||
"""Отключает telemetry backends, запускает smoke и гарантированно восстанавливает их."""
|
||||
"""Держит backends недоступными >30 с и проверяет бизнес-контур и RSS."""
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
args = parser.parse_args()
|
||||
rss_query = 'max(otelcol_process_memory_rss_bytes{job="otel-collector"})'
|
||||
failed_logs_query = "sum(otelcol_exporter_send_failed_log_records_total) or vector(0)"
|
||||
failed_spans_query = "sum(otelcol_exporter_send_failed_spans_total) or vector(0)"
|
||||
rss_before = prometheus_value(rss_query)
|
||||
failed_logs_before = prometheus_value(failed_logs_query)
|
||||
failed_spans_before = prometheus_value(failed_spans_query)
|
||||
compose("stop", "loki", "tempo")
|
||||
started = time.monotonic()
|
||||
rss_samples = [rss_before]
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["python3", "tests/smoke.py", "--base-url", args.base_url],
|
||||
cwd=ROOT, check=True, text=True, capture_output=True,
|
||||
)
|
||||
time.sleep(10)
|
||||
while time.monotonic() - started < 45:
|
||||
time.sleep(5)
|
||||
rss_samples.append(prometheus_value(rss_query))
|
||||
Client(args.base_url).call("GET", "/health/ready", schema="Health")
|
||||
running = compose("ps", "--status", "running", "--services", capture=True).stdout.split()
|
||||
if "otel-collector" not in running:
|
||||
raise RuntimeError("OTel Collector stopped while exporters were retrying")
|
||||
failed_logs = prometheus_value(failed_logs_query) - failed_logs_before
|
||||
failed_spans = prometheus_value(failed_spans_query) - failed_spans_before
|
||||
if failed_logs + failed_spans <= 0:
|
||||
raise RuntimeError("Collector did not account for telemetry loss")
|
||||
rss_peak = max(rss_samples)
|
||||
memory_limit = 256 * 1024 * 1024
|
||||
if rss_peak >= memory_limit:
|
||||
raise RuntimeError("Collector reached its container memory limit")
|
||||
finally:
|
||||
compose("start", "loki", "tempo")
|
||||
print(json.dumps({
|
||||
@@ -46,6 +80,11 @@ def main():
|
||||
"business_smoke": "PASS" if "PASS:" in result.stdout else "UNKNOWN",
|
||||
"collector": "running",
|
||||
"duration_seconds": round(time.monotonic() - started, 1),
|
||||
"rss_before_mib": round(rss_before / 1024 / 1024, 1),
|
||||
"rss_peak_mib": round(rss_peak / 1024 / 1024, 1),
|
||||
"memory_limit_mib": 256,
|
||||
"failed_log_records": int(failed_logs),
|
||||
"failed_spans": int(failed_spans),
|
||||
"result": "PASS",
|
||||
}))
|
||||
|
||||
|
||||
Reference in New Issue
Block a user