forked from mtusi2026/mtusi2026lab6
142 lines
5.2 KiB
Python
142 lines
5.2 KiB
Python
import json
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
import urllib.request
|
|
import urllib.error
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
|
from client import Client
|
|
|
|
CONFIGS = [
|
|
{
|
|
"name": "telemetry_off",
|
|
"env": {"OTEL_SDK_DISABLED": "true", "OTEL_TRACES_SAMPLER": "always_off", "OTEL_TRACES_SAMPLER_ARG": "0.0"},
|
|
},
|
|
{
|
|
"name": "telemetry_on_100pct",
|
|
"env": {"OTEL_SDK_DISABLED": "false", "OTEL_TRACES_SAMPLER": "always_on", "OTEL_TRACES_SAMPLER_ARG": "1.0"},
|
|
},
|
|
{
|
|
"name": "telemetry_on_10pct",
|
|
"env": {"OTEL_SDK_DISABLED": "false", "OTEL_TRACES_SAMPLER": "parentbased_ratio", "OTEL_TRACES_SAMPLER_ARG": "0.1"},
|
|
},
|
|
{
|
|
"name": "telemetry_on_1pct",
|
|
"env": {"OTEL_SDK_DISABLED": "false", "OTEL_TRACES_SAMPLER": "parentbased_ratio", "OTEL_TRACES_SAMPLER_ARG": "0.01"},
|
|
},
|
|
]
|
|
|
|
TEMPO_URL = os.getenv("TEMPO_URL", "http://localhost:3200")
|
|
|
|
|
|
def run_cmd(cmd: str) -> str:
|
|
res = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
|
return res.stdout.strip()
|
|
|
|
|
|
def check_tempo_trace(trace_id: str) -> bool:
|
|
if not trace_id:
|
|
return False
|
|
try:
|
|
req = urllib.request.Request(f"{TEMPO_URL}/api/traces/{trace_id}")
|
|
with urllib.request.urlopen(req, timeout=3) as resp:
|
|
return resp.status == 200
|
|
except Exception:
|
|
return False
|
|
|
|
|
|
def get_docker_stats():
|
|
raw = run_cmd("docker stats --no-stream --format '{{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}'")
|
|
stats = {}
|
|
for line in raw.split("\n"):
|
|
parts = line.split("\t")
|
|
if len(parts) >= 3:
|
|
name, cpu, mem = parts[0], parts[1], parts[2]
|
|
if any(svc in name for svc in ("api-1", "api-2", "worker", "otel-collector", "tempo")):
|
|
stats[name] = {"cpu": cpu, "memory": mem}
|
|
return stats
|
|
|
|
|
|
def main():
|
|
os.makedirs("evidence", exist_ok=True)
|
|
results = {}
|
|
|
|
for cfg in CONFIGS:
|
|
mode_name = cfg["name"]
|
|
print(f"\n==========================================")
|
|
print(f"Запуск режима: {mode_name}")
|
|
print(f"==========================================")
|
|
|
|
env_args = " ".join(f"{k}={v}" for k, v in cfg["env"].items())
|
|
cmd_up = f"{env_args} docker compose up -d api-1 api-2 worker"
|
|
run_cmd(cmd_up)
|
|
|
|
time.sleep(4)
|
|
for _ in range(15):
|
|
try:
|
|
with urllib.request.urlopen("http://localhost:8080/health/ready", timeout=2) as resp:
|
|
if resp.status == 200:
|
|
break
|
|
except Exception:
|
|
time.sleep(1)
|
|
|
|
print("Запуск нагрузки tests/load.py...")
|
|
load_cmd = ".venv/bin/python tests/load.py --base-url 'http://localhost:8080'"
|
|
load_out = run_cmd(load_cmd)
|
|
try:
|
|
load_data = json.loads(load_out)
|
|
except Exception:
|
|
load_data = {"raw_output": load_out}
|
|
|
|
print("Запуск контрольного замера выборки трасс (50 запросов POST)...")
|
|
c = Client()
|
|
user, _, _, chat = c.bootstrap()
|
|
sample_trace_ids = []
|
|
for i in range(50):
|
|
res = c.message(user, chat, f"Benchmark sampling check {i}")
|
|
tid = res.get("headers", {}).get("x-trace-id")
|
|
if tid:
|
|
sample_trace_ids.append(tid)
|
|
|
|
time.sleep(4)
|
|
found_in_tempo = sum(1 for tid in sample_trace_ids if check_tempo_trace(tid))
|
|
total_sent = len(sample_trace_ids)
|
|
sampling_ratio = (found_in_tempo / total_sent) if total_sent > 0 else 0.0
|
|
print(f" Запросов отправлено: {total_sent}, найдено в Tempo: {found_in_tempo}, доля: {sampling_ratio:.2%}")
|
|
|
|
docker_stats = get_docker_stats()
|
|
tempo_size = run_cmd("docker compose exec tempo du -sk /var/tempo 2>/dev/null || echo '0'").split()[0]
|
|
|
|
results[mode_name] = {
|
|
"config": cfg["env"],
|
|
"load_benchmark": load_data,
|
|
"trace_sampling_verification": {
|
|
"sent_post_requests": total_sent,
|
|
"traces_retained_in_tempo": found_in_tempo,
|
|
"measured_sampling_fraction": round(sampling_ratio, 4),
|
|
},
|
|
"docker_stats": docker_stats,
|
|
"tempo_storage_kb": tempo_size,
|
|
}
|
|
|
|
print(f"Результаты для {mode_name}:")
|
|
if "successful_rps" in load_data:
|
|
print(f" RPS: {load_data['successful_rps']}")
|
|
print(f" Latency p50: {load_data['successful_latency_ms']['p50']} ms, p95: {load_data['successful_latency_ms']['p95']} ms, p99: {load_data['successful_latency_ms']['p99']} ms")
|
|
print(f" Tempo storage: {tempo_size} KB")
|
|
|
|
run_cmd("OTEL_SDK_DISABLED=false OTEL_TRACES_SAMPLER=always_on docker compose up -d api-1 api-2 worker")
|
|
|
|
out_file = "evidence/overhead_benchmarks.json"
|
|
with open(out_file, "w", encoding="utf-8") as f:
|
|
json.dump(results, f, indent=2, ensure_ascii=False)
|
|
|
|
print(f"\nЭксперимент Трека 1 успешно завершен! Результаты сохранены в {out_file}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|