forked from mtusi2026/mtusi2026lab6
docs(REPORT): stash squish lab6 write report
This commit is contained in:
@@ -0,0 +1,299 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
export PYTHONUTF8=1
|
||||
|
||||
cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.."
|
||||
mode=${1:-}
|
||||
case "$mode" in
|
||||
load|worker|postgres|minio|opensearch) ;;
|
||||
*)
|
||||
printf 'Использование: bash student-tests/lab6-evidence.sh {load|worker|postgres|minio|opensearch}\n' >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
|
||||
base_url=${BASE_URL:-http://localhost:${LB_PORT:-8080}}
|
||||
if command -v python >/dev/null 2>&1; then
|
||||
py=python
|
||||
else
|
||||
py=python3
|
||||
fi
|
||||
|
||||
compose_running=$(docker compose ps --status running --services)
|
||||
out="evidence/runs/$mode-$(date -u +%Y%m%dT%H%M%SZ)"
|
||||
mkdir -p "$out"
|
||||
printf 'Результаты: %s\n' "$out"
|
||||
|
||||
if [[ $mode == load ]]; then
|
||||
printf 'Запускаю публичный smoke-тест.\n'
|
||||
"$py" tests/smoke.py --base-url "$base_url" 2>&1 | tee "$out/smoke.txt"
|
||||
printf 'Запускаю нагрузку на 60 секунд с четырьмя клиентами.\n'
|
||||
"$py" tests/load.py --base-url "$base_url" --duration 60 --concurrency 4 \
|
||||
--output "$out/load.json"
|
||||
printf 'Smoke-тест и нагрузка завершены. Результаты в %s.\n' "$out"
|
||||
exit
|
||||
fi
|
||||
|
||||
if ! grep -qx "$mode" <<< "$compose_running"; then
|
||||
printf 'Сервис %s должен быть запущен перед опытом.\n' "$mode" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ $mode == worker ]]; then
|
||||
if [[ -f student-tests/hand_alert.sh ]]; then
|
||||
hand_alert=student-tests/hand_alert.sh
|
||||
elif [[ -f students-tests/hand_alert.sh ]]; then
|
||||
hand_alert=students-tests/hand_alert.sh
|
||||
else
|
||||
printf 'Положи свой hand_alert.sh в student-tests/.\n' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
start=$(date -u +%s)
|
||||
trap 'docker compose start worker >&2 || true' EXIT
|
||||
BASE_URL="$base_url" bash "$hand_alert" 2>&1 | tee "$out/worker-run.txt"
|
||||
docker compose start worker
|
||||
trap - EXIT
|
||||
|
||||
printf 'Собираю точки за 90 секунд после запуска worker.\n'
|
||||
sleep 45
|
||||
sleep 45
|
||||
|
||||
"$py" - "$start" "$(date -u +%s)" "$out" <<'PY'
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
from urllib.parse import urlencode
|
||||
|
||||
start, end, output = sys.argv[1:]
|
||||
folder = Path(output)
|
||||
queue = '{queue="attachments.process"}'
|
||||
queries = {
|
||||
"alerts": 'ALERTS{alertname="MessengerGrowingAttachmentQueue"}',
|
||||
"queue": "rabbitmq_detailed_queue_messages_ready" + queue,
|
||||
"queue-age": "clamp_min(time() - (rabbitmq_detailed_queue_head_message_timestamp" + queue + " > 0), 0)",
|
||||
"consumers": "rabbitmq_detailed_queue_consumer_capacity" + queue,
|
||||
}
|
||||
|
||||
for name, query in queries.items():
|
||||
params = urlencode(dict(query=query, start=start, end=end, step=15))
|
||||
url = "http://localhost:9090/api/v1/query_range?" + params
|
||||
raw = subprocess.check_output(
|
||||
["docker", "compose", "exec", "-T", "prometheus", "wget", "-qO-", url],
|
||||
env=dict(os.environ, MSYS2_ARG_CONV_EXCL="*"),
|
||||
)
|
||||
result = json.loads(raw)
|
||||
(folder / (name + ".json")).write_bytes(raw)
|
||||
if result["status"] != "success":
|
||||
sys.exit(f"Ошибка запроса Prometheus ({name}).")
|
||||
print(f"{name}: сохранено рядов — {len(result['data']['result'])}.")
|
||||
PY
|
||||
exit
|
||||
fi
|
||||
|
||||
"$py" - "$mode" "$base_url" "$out" <<'PY'
|
||||
import datetime as dt
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
sys.path.insert(0, "tests")
|
||||
from client import Client, Failure
|
||||
|
||||
service, base, output = sys.argv[1:]
|
||||
folder = Path(output)
|
||||
client = Client(base, timeout=8)
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
image = Path("tests/fixtures/sample.png").read_bytes()
|
||||
path = f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png"
|
||||
started = dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
trace_ids = set()
|
||||
trace_candidates = {}
|
||||
collector = None
|
||||
|
||||
if service == "opensearch":
|
||||
collector = subprocess.check_output(
|
||||
["docker", "compose", "ps", "-q", "otel-collector"], text=True
|
||||
).strip()
|
||||
if not collector:
|
||||
sys.exit("Запусти otel-collector перед экспериментом.")
|
||||
|
||||
|
||||
def emit(event, **fields):
|
||||
row = dict(utc=dt.datetime.now(dt.timezone.utc).isoformat(), event=event, **fields)
|
||||
with (folder / "events.jsonl").open("a", encoding="utf-8") as log:
|
||||
log.write(json.dumps(row) + "\n")
|
||||
|
||||
labels = {
|
||||
"http": "Ответ API",
|
||||
"ready": "Вложение готово",
|
||||
"client_error": "Ошибка запроса",
|
||||
"matching_logs": "Сохранены записи журнала",
|
||||
"trace_unavailable": "Трасса недоступна",
|
||||
"stopped": "Сервис остановлен",
|
||||
"started": "Сервис запущен",
|
||||
"collector_stats": "Ресурсы Collector",
|
||||
}
|
||||
field_labels = {
|
||||
"phase": "этап",
|
||||
"status": "код HTTP",
|
||||
"elapsed_ms": "время, мс",
|
||||
"count": "количество",
|
||||
"service": "сервис",
|
||||
"cpu_memory": "CPU и память",
|
||||
"error": "детали",
|
||||
}
|
||||
phases = {
|
||||
"before": "до отказа",
|
||||
"during": "во время отказа",
|
||||
"after": "после восстановления",
|
||||
}
|
||||
details = ", ".join(
|
||||
f"{field_labels.get(key, key)}={phases.get(value, value) if key == 'phase' else value}"
|
||||
for key, value in fields.items()
|
||||
if value is not None
|
||||
)
|
||||
print(f"{row['utc']} {labels[event]}. {details}", flush=True)
|
||||
|
||||
|
||||
def compose(action):
|
||||
subprocess.run(["docker", "compose", action, service], check=True)
|
||||
|
||||
|
||||
def probe(phase):
|
||||
trace_id = secrets.token_hex(16)
|
||||
trace_ids.add(trace_id)
|
||||
headers = {"traceparent": f"00-{trace_id}-{secrets.token_hex(8)}-01"}
|
||||
start = time.monotonic()
|
||||
|
||||
try:
|
||||
expected = [200, 202, 500, 502, 503, 504]
|
||||
if service == "postgres":
|
||||
reply = client.call(
|
||||
"GET", "/api/v1/chats", expected, actor=actor, headers=headers
|
||||
)
|
||||
else:
|
||||
headers["Content-Type"] = "image/png"
|
||||
reply = client.call(
|
||||
"POST", path, expected, actor=actor, headers=headers, raw=image
|
||||
)
|
||||
trace_candidates[(phase, reply["status"])] = trace_id
|
||||
emit(
|
||||
"http",
|
||||
phase=phase,
|
||||
trace_id=trace_id,
|
||||
status=reply["status"],
|
||||
request_id=reply["headers"].get("X-Request-Id"),
|
||||
elapsed_ms=round(1000 * (time.monotonic() - start)),
|
||||
)
|
||||
if reply["status"] == 202:
|
||||
client.wait_ready(actor, json.loads(reply["bytes"]), wait_seconds=30)
|
||||
emit("ready", phase=phase, trace_id=trace_id)
|
||||
return reply["status"] in (200, 202)
|
||||
except Failure as error:
|
||||
trace_candidates[(phase, "client_error")] = trace_id
|
||||
emit("client_error", phase=phase, trace_id=trace_id, error=str(error))
|
||||
return False
|
||||
|
||||
|
||||
def save_logs():
|
||||
logs = subprocess.check_output(
|
||||
["docker", "compose", "logs", "--since", started,
|
||||
"--no-color", "--no-log-prefix", "api", "worker"]
|
||||
)
|
||||
keys = (
|
||||
"time", "level", "event", "instance_id", "request_id", "trace_id",
|
||||
"span_id", "http.route", "http.response.status_code", "outcome",
|
||||
)
|
||||
count = 0
|
||||
with (folder / "logs.jsonl").open("w", encoding="utf-8") as out:
|
||||
for line in logs.splitlines():
|
||||
try:
|
||||
row = json.loads(line)
|
||||
except (ValueError, UnicodeError):
|
||||
continue
|
||||
if isinstance(row, dict) and row.get("trace_id") in trace_ids:
|
||||
out.write(json.dumps({key: row[key] for key in keys if key in row}) + "\n")
|
||||
count += 1
|
||||
emit("matching_logs", count=count)
|
||||
|
||||
|
||||
def save_traces():
|
||||
for trace_id in sorted(set(trace_candidates.values())):
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "exec", "-T", "prometheus", "wget", "-qO-",
|
||||
"http://jaeger:16686/api/traces/" + trace_id],
|
||||
capture_output=True,
|
||||
env=dict(os.environ, MSYS2_ARG_CONV_EXCL="*"),
|
||||
)
|
||||
if result.returncode != 0:
|
||||
emit("trace_unavailable", trace_id=trace_id)
|
||||
continue
|
||||
data = json.loads(result.stdout).get("data") or []
|
||||
if not data:
|
||||
emit("trace_unavailable", trace_id=trace_id)
|
||||
continue
|
||||
|
||||
trace = data[0]
|
||||
spans = []
|
||||
for span in trace["spans"]:
|
||||
tags = {tag["key"]: tag["value"] for tag in span.get("tags", [])}
|
||||
spans.append(dict(
|
||||
span_id=span["spanID"],
|
||||
operation=span["operationName"].split("?")[0],
|
||||
service=trace["processes"][span["processID"]]["serviceName"],
|
||||
duration_us=span["duration"],
|
||||
references=span.get("references", []),
|
||||
error=tags.get("error"),
|
||||
status=tags.get("otel.status_code"),
|
||||
))
|
||||
(folder / ("trace-" + trace_id + ".json")).write_text(
|
||||
json.dumps(spans, indent=2) + "\n", encoding="utf-8"
|
||||
)
|
||||
|
||||
|
||||
if not probe("before"):
|
||||
sys.exit("Проверочный запрос до остановки сервиса завершился ошибкой.")
|
||||
|
||||
try:
|
||||
try:
|
||||
compose("stop")
|
||||
emit("stopped", service=service)
|
||||
for _ in range(12 if collector else 6):
|
||||
probe("during")
|
||||
if collector:
|
||||
sample = subprocess.check_output(
|
||||
["docker", "stats", "--no-stream", "--format",
|
||||
"{{.CPUPerc}} {{.MemUsage}}", collector],
|
||||
text=True,
|
||||
)
|
||||
emit("collector_stats", cpu_memory=sample.strip())
|
||||
time.sleep(5)
|
||||
finally:
|
||||
compose("start")
|
||||
emit("started", service=service)
|
||||
|
||||
for _ in range(30):
|
||||
try:
|
||||
client.call("GET", "/health/ready", 200)
|
||||
break
|
||||
except Failure:
|
||||
time.sleep(3)
|
||||
else:
|
||||
sys.exit("API не вернулся в состояние готовности после запуска сервиса.")
|
||||
|
||||
if not probe("after"):
|
||||
sys.exit("Проверочный запрос после запуска сервиса завершился ошибкой.")
|
||||
|
||||
# Даём SDK и Collector время отправить данные последнего запроса.
|
||||
time.sleep(15)
|
||||
save_traces()
|
||||
finally:
|
||||
save_logs()
|
||||
PY
|
||||
Reference in New Issue
Block a user