forked from mtusi2026/mtusi2026lab6
лаба на 5
This commit is contained in:
@@ -0,0 +1,162 @@
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from collections import Counter
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
|
||||
from client import Client, Failure
|
||||
|
||||
local = threading.local()
|
||||
|
||||
|
||||
def percentile(values, p):
|
||||
if not values:
|
||||
return None
|
||||
values = sorted(values)
|
||||
index = max(0, math.ceil(len(values) * p) - 1)
|
||||
return round(values[index], 3)
|
||||
|
||||
|
||||
def latency_summary(values):
|
||||
return {
|
||||
"p50": percentile(values, 0.50),
|
||||
"p95": percentile(values, 0.95),
|
||||
"p99": percentile(values, 0.99),
|
||||
"mean": round(sum(values) / len(values), 3)
|
||||
if values else None,
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--requests", type=int, default=600)
|
||||
parser.add_argument("--rate", type=float, default=20)
|
||||
parser.add_argument("--workers", type=int, default=16)
|
||||
parser.add_argument("--warmup", type=int, default=50)
|
||||
parser.add_argument("--start-marker", default=None)
|
||||
parser.add_argument("--settle", type=float, default=10)
|
||||
parser.add_argument("--mode", required=True)
|
||||
parser.add_argument("--output", required=True)
|
||||
args = parser.parse_args()
|
||||
|
||||
if min(args.requests, args.rate, args.workers) <= 0:
|
||||
parser.error("requests, rate and workers must be positive")
|
||||
|
||||
client = Client(args.base_url)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
|
||||
def request(index, scheduled):
|
||||
if not hasattr(local, "client"):
|
||||
local.client = Client(args.base_url, timeout=10)
|
||||
|
||||
started = time.perf_counter()
|
||||
outcome = "success"
|
||||
|
||||
try:
|
||||
local.client.message(
|
||||
alice, chat, f"benchmark-message-{index:08d}"
|
||||
)
|
||||
except Failure:
|
||||
outcome = "error"
|
||||
|
||||
finished = time.perf_counter()
|
||||
|
||||
return {
|
||||
"outcome": outcome,
|
||||
"latency_ms": (finished - started) * 1000,
|
||||
"scheduled_latency_ms": (finished - scheduled) * 1000,
|
||||
"queue_delay_ms": (started - scheduled) * 1000,
|
||||
}
|
||||
|
||||
with ThreadPoolExecutor(max_workers=args.workers) as pool:
|
||||
for index in range(args.warmup):
|
||||
result = pool.submit(
|
||||
request, -index - 1, time.perf_counter()
|
||||
).result()
|
||||
|
||||
if result["outcome"] != "success":
|
||||
raise RuntimeError("Warmup failed")
|
||||
|
||||
time.sleep(args.settle)
|
||||
|
||||
if args.start_marker:
|
||||
marker = Path(args.start_marker)
|
||||
marker.parent.mkdir(parents=True, exist_ok=True)
|
||||
marker.write_text(str(time.time()))
|
||||
|
||||
deadline = time.monotonic() + 120
|
||||
while marker.exists():
|
||||
if time.monotonic() > deadline:
|
||||
raise RuntimeError("Measurement handshake timeout")
|
||||
time.sleep(0.05)
|
||||
|
||||
started_at = time.time()
|
||||
started = time.perf_counter()
|
||||
futures = []
|
||||
|
||||
for index in range(args.requests):
|
||||
scheduled = started + index / args.rate
|
||||
delay = scheduled - time.perf_counter()
|
||||
|
||||
if delay > 0:
|
||||
time.sleep(delay)
|
||||
|
||||
futures.append(pool.submit(request, index, scheduled))
|
||||
|
||||
results = [future.result() for future in futures]
|
||||
elapsed = time.perf_counter() - started
|
||||
finished_at = time.time()
|
||||
|
||||
counts = Counter(row["outcome"] for row in results)
|
||||
|
||||
successful = [
|
||||
row["latency_ms"]
|
||||
for row in results
|
||||
if row["outcome"] == "success"
|
||||
]
|
||||
|
||||
report = {
|
||||
"mode": args.mode,
|
||||
"workload": "fixed-rate POST messages",
|
||||
"started_at_unix": started_at,
|
||||
"finished_at_unix": finished_at,
|
||||
"requested_requests": args.requests,
|
||||
"target_rps": args.rate,
|
||||
"workers": args.workers,
|
||||
"warmup_requests": args.warmup,
|
||||
"elapsed_seconds": round(elapsed, 3),
|
||||
"successful_requests": counts["success"],
|
||||
"failed_requests": counts["error"],
|
||||
"error_ratio": round(counts["error"] / args.requests, 6),
|
||||
"actual_rps": round(args.requests / elapsed, 3),
|
||||
"successful_rps": round(counts["success"] / elapsed, 3),
|
||||
"successful_latency_ms": latency_summary(successful),
|
||||
"all_latency_ms": latency_summary([
|
||||
row["latency_ms"] for row in results
|
||||
]),
|
||||
"scheduled_latency_ms": latency_summary([
|
||||
row["scheduled_latency_ms"] for row in results
|
||||
]),
|
||||
"client_queue_delay_ms": latency_summary([
|
||||
row["queue_delay_ms"] for row in results
|
||||
]),
|
||||
}
|
||||
|
||||
output = Path(args.output)
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
text = json.dumps(report, indent=2, ensure_ascii=False)
|
||||
output.write_text(text + "\n")
|
||||
print(text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,175 @@
|
||||
import argparse
|
||||
import json
|
||||
import random
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def request(scenario):
|
||||
replica = random.choice(["api-1", "api-2"])
|
||||
url = f"http://{replica}:8080/api/v1/_benchmark/{scenario}"
|
||||
started = time.perf_counter()
|
||||
|
||||
try:
|
||||
response = urllib.request.urlopen(url, timeout=10)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
|
||||
with response:
|
||||
status = response.code
|
||||
body = response.read().decode("utf-8", errors="replace")
|
||||
|
||||
try:
|
||||
data = json.loads(body)
|
||||
except json.JSONDecodeError as error:
|
||||
raise RuntimeError(
|
||||
f"Scenario={scenario}, HTTP={status}, body={body[:500]!r}"
|
||||
) from error
|
||||
|
||||
elapsed = (time.perf_counter() - started) * 1000
|
||||
|
||||
expected = 503 if scenario == "error" else 200
|
||||
|
||||
if status != expected:
|
||||
raise RuntimeError(f"Unexpected status: {scenario} {status}")
|
||||
|
||||
trace_id = data["trace_id"]
|
||||
|
||||
if len(trace_id) != 32 or int(trace_id, 16) == 0:
|
||||
raise RuntimeError("Invalid trace ID")
|
||||
|
||||
return {
|
||||
"scenario": scenario,
|
||||
"status": status,
|
||||
"trace_id": trace_id,
|
||||
"sampled": data["sampled"],
|
||||
"latency_ms": round(elapsed, 3),
|
||||
}
|
||||
|
||||
|
||||
def lookup_traces(trace_ids):
|
||||
code = """
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
ids = json.load(sys.stdin)
|
||||
|
||||
def lookup(trace_id):
|
||||
url = "http://tempo:3200/api/traces/" + trace_id
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=10) as response:
|
||||
data = json.load(response)
|
||||
return trace_id, bool(
|
||||
data.get("batches") or data.get("resourceSpans")
|
||||
)
|
||||
except urllib.error.HTTPError as error:
|
||||
if error.code == 404:
|
||||
return trace_id, False
|
||||
raise
|
||||
|
||||
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||
print(json.dumps(dict(pool.map(lookup, ids))))
|
||||
"""
|
||||
|
||||
result = subprocess.run(
|
||||
[
|
||||
sys.executable, "-c", code,
|
||||
],
|
||||
input=json.dumps(trace_ids),
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
)
|
||||
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--mode", required=True)
|
||||
parser.add_argument("--count", type=int, default=100)
|
||||
parser.add_argument("--output", required=True)
|
||||
args = parser.parse_args()
|
||||
|
||||
scenarios = ["normal", "error", "slow"]
|
||||
workload = scenarios * args.count
|
||||
random.Random(42).shuffle(workload)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
rows = list(pool.map(request, workload))
|
||||
|
||||
ids = [row["trace_id"] for row in rows]
|
||||
|
||||
if len(set(ids)) != len(ids):
|
||||
raise RuntimeError("Duplicate trace IDs")
|
||||
|
||||
print("Waiting for telemetry export...", flush=True)
|
||||
time.sleep(45 if args.mode == "balanced" else 20)
|
||||
|
||||
found = lookup_traces(ids)
|
||||
|
||||
missing = [
|
||||
trace_id for trace_id in ids
|
||||
if not found[trace_id]
|
||||
]
|
||||
|
||||
if missing:
|
||||
time.sleep(15)
|
||||
found.update(lookup_traces(missing))
|
||||
|
||||
for row in rows:
|
||||
row["found_in_tempo"] = found[row["trace_id"]]
|
||||
|
||||
summary = {}
|
||||
|
||||
for scenario in scenarios:
|
||||
group = [
|
||||
row for row in rows
|
||||
if row["scenario"] == scenario
|
||||
]
|
||||
|
||||
total = len(group)
|
||||
sampled = sum(row["sampled"] for row in group)
|
||||
saved = sum(row["found_in_tempo"] for row in group)
|
||||
|
||||
export_missing = sum(
|
||||
row["sampled"] and not row["found_in_tempo"]
|
||||
for row in group
|
||||
)
|
||||
|
||||
summary[scenario] = {
|
||||
"total": total,
|
||||
"sampled": sampled,
|
||||
"saved_in_tempo": saved,
|
||||
"not_sampled": total - sampled,
|
||||
"sampled_but_not_found": export_missing,
|
||||
"collector_filtered_or_missing": (
|
||||
export_missing if args.mode == "balanced" else 0
|
||||
),
|
||||
"retention_percent": round(saved / total * 100, 2),
|
||||
"missing_percent": round((total - saved) / total * 100, 2),
|
||||
}
|
||||
|
||||
report = {
|
||||
"mode": args.mode,
|
||||
"summary": summary,
|
||||
"requests": rows,
|
||||
}
|
||||
|
||||
path = Path(args.output)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(report, indent=2) + "\n")
|
||||
|
||||
print(json.dumps(summary, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,177 @@
|
||||
import json
|
||||
import statistics
|
||||
from pathlib import Path
|
||||
|
||||
import matplotlib
|
||||
|
||||
matplotlib.use("Agg")
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
EVIDENCE = ROOT / "evidence"
|
||||
|
||||
MODES = ["baseline", "full", "optimized", "balanced"]
|
||||
LABELS = ["Baseline", "Full", "Head 10%", "Tail"]
|
||||
COLORS = ["#94a3b8", "#5794f2", "#eab308", "#16a34a"]
|
||||
|
||||
plt.rcParams.update({
|
||||
"font.family": "DejaVu Sans",
|
||||
"font.size": 11,
|
||||
"figure.dpi": 150,
|
||||
"axes.spines.top": False,
|
||||
"axes.spines.right": False,
|
||||
})
|
||||
|
||||
data = {
|
||||
mode: [
|
||||
json.loads(
|
||||
(EVIDENCE / f"grade5-{mode}-{i}.json").read_text()
|
||||
)
|
||||
for i in range(1, 4)
|
||||
]
|
||||
for mode in MODES
|
||||
}
|
||||
|
||||
for mode, rows in data.items():
|
||||
assert len(rows) == 3
|
||||
assert all(r["requested_requests"] == 1200 for r in rows)
|
||||
assert all(r["successful_requests"] == 1200 for r in rows)
|
||||
assert all(r["failed_requests"] == 0 for r in rows)
|
||||
|
||||
|
||||
def save(fig, name):
|
||||
fig.tight_layout()
|
||||
path = EVIDENCE / name
|
||||
fig.savefig(path, dpi=180, bbox_inches="tight")
|
||||
plt.close(fig)
|
||||
print(f"Saved: {path}")
|
||||
|
||||
|
||||
def bars(ax, values, title, ylabel):
|
||||
result = ax.bar(LABELS, values, color=COLORS)
|
||||
ax.set_title(title)
|
||||
ax.set_ylabel(ylabel)
|
||||
ax.grid(axis="y", alpha=0.2)
|
||||
ax.set_axisbelow(True)
|
||||
ax.bar_label(result, fmt="%.2f", padding=3)
|
||||
ax.set_ylim(0, max(values) * 1.2 if max(values) else 1)
|
||||
|
||||
|
||||
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
|
||||
|
||||
for ax, metric in zip(axes, ["p50", "p95", "p99"]):
|
||||
values = [
|
||||
statistics.mean(
|
||||
r["successful_latency_ms"][metric]
|
||||
for r in data[mode]
|
||||
)
|
||||
for mode in MODES
|
||||
]
|
||||
|
||||
bars(ax, values, metric, "Latency, ms")
|
||||
|
||||
fig.suptitle("HTTP latency: mean of three experiments")
|
||||
save(fig, "grade5-latency.png")
|
||||
|
||||
|
||||
fig, axes = plt.subplots(2, 2, figsize=(12, 9))
|
||||
|
||||
for ax, group, metric, title, unit in [
|
||||
(
|
||||
axes[0][0], "application_total", "cpu_mean_percent",
|
||||
"Application CPU", "CPU, %"
|
||||
),
|
||||
(
|
||||
axes[0][1], "observability_total", "cpu_mean_percent",
|
||||
"Observability CPU", "CPU, %"
|
||||
),
|
||||
(
|
||||
axes[1][0], "application_total", "ram_mean_mib",
|
||||
"Application RAM", "RAM, MiB"
|
||||
),
|
||||
(
|
||||
axes[1][1], "observability_total", "ram_mean_mib",
|
||||
"Observability RAM", "RAM, MiB"
|
||||
),
|
||||
]:
|
||||
values = [
|
||||
statistics.mean(
|
||||
r["resources"][group][metric]
|
||||
for r in data[mode]
|
||||
)
|
||||
for mode in MODES
|
||||
]
|
||||
|
||||
bars(ax, values, title, unit)
|
||||
|
||||
fig.suptitle("Resource consumption under identical workload")
|
||||
save(fig, "grade5-resources.png")
|
||||
|
||||
|
||||
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
|
||||
|
||||
for ax, metric, title in [
|
||||
(
|
||||
axes[0],
|
||||
"otelcol_receiver_accepted_spans",
|
||||
"Collector ingress",
|
||||
),
|
||||
(
|
||||
axes[1],
|
||||
"otelcol_exporter_sent_spans",
|
||||
"Collector export",
|
||||
),
|
||||
]:
|
||||
values = [
|
||||
sum(r["collector_deltas"][metric] for r in data[mode])
|
||||
for mode in MODES
|
||||
]
|
||||
|
||||
result = ax.bar(LABELS, values, color=COLORS)
|
||||
ax.bar_label(result, fmt="%.0f", padding=3)
|
||||
ax.set_title(title)
|
||||
ax.set_ylabel("Spans")
|
||||
ax.set_ylim(0, max(values) * 1.2)
|
||||
ax.grid(axis="y", alpha=0.2)
|
||||
ax.set_axisbelow(True)
|
||||
|
||||
fig.suptitle("Trace volume: total across three experiments")
|
||||
save(fig, "grade5-ingest.png")
|
||||
|
||||
|
||||
fig, ax = plt.subplots(figsize=(10, 6))
|
||||
|
||||
scenarios = ["normal", "error", "slow"]
|
||||
positions = list(range(len(scenarios)))
|
||||
width = 0.24
|
||||
|
||||
for index, mode in enumerate(MODES[1:]):
|
||||
report = json.loads(
|
||||
(EVIDENCE / f"grade5-retention-{mode}.json").read_text()
|
||||
)
|
||||
|
||||
values = [
|
||||
report["summary"][scenario]["retention_percent"]
|
||||
for scenario in scenarios
|
||||
]
|
||||
|
||||
result = ax.bar(
|
||||
[x + (index - 1) * width for x in positions],
|
||||
values,
|
||||
width,
|
||||
label=LABELS[index + 1],
|
||||
color=COLORS[index + 1],
|
||||
)
|
||||
|
||||
ax.bar_label(result, fmt="%.0f%%", padding=3)
|
||||
|
||||
ax.set_xticks(positions, ["Normal", "Error", "Slow"])
|
||||
ax.set_ylabel("Trace retention, %")
|
||||
ax.set_ylim(0, 115)
|
||||
ax.set_title("Retention of controlled HTTP traces")
|
||||
ax.legend()
|
||||
ax.grid(axis="y", alpha=0.2)
|
||||
ax.set_axisbelow(True)
|
||||
|
||||
save(fig, "grade5-retention.png")
|
||||
@@ -0,0 +1,379 @@
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
os.chdir(ROOT)
|
||||
|
||||
SERVICES = [
|
||||
"api-1",
|
||||
"api-2",
|
||||
"dispatcher",
|
||||
"worker",
|
||||
]
|
||||
|
||||
MONITORED = SERVICES + [
|
||||
"otel-collector",
|
||||
"prometheus",
|
||||
"loki",
|
||||
"tempo",
|
||||
]
|
||||
|
||||
MODES = {
|
||||
"baseline": ("0", "0.0"),
|
||||
"full": ("1", "1.0"),
|
||||
"optimized": ("1", "0.1"),
|
||||
"balanced": ("1", "1.0"),
|
||||
}
|
||||
|
||||
METRICS = [
|
||||
"otelcol_receiver_accepted_spans",
|
||||
"otelcol_receiver_refused_spans",
|
||||
"otelcol_exporter_sent_spans",
|
||||
"otelcol_exporter_send_failed_spans",
|
||||
"otelcol_receiver_accepted_log_records",
|
||||
"otelcol_receiver_refused_log_records",
|
||||
"otelcol_exporter_sent_log_records",
|
||||
"otelcol_exporter_send_failed_log_records",
|
||||
"otelcol_receiver_accepted_metric_points",
|
||||
"otelcol_receiver_refused_metric_points",
|
||||
]
|
||||
|
||||
|
||||
def command(args, **kwargs):
|
||||
return subprocess.run(args, check=True, **kwargs)
|
||||
|
||||
|
||||
def prometheus(query):
|
||||
url = (
|
||||
"http://localhost:9090/api/v1/query?"
|
||||
+ urllib.parse.urlencode({"query": query})
|
||||
)
|
||||
|
||||
with urllib.request.urlopen(url, timeout=10) as response:
|
||||
result = json.load(response)
|
||||
|
||||
if result["status"] != "success":
|
||||
raise RuntimeError("Prometheus query failed")
|
||||
|
||||
return result["data"]["result"]
|
||||
|
||||
|
||||
def snapshot():
|
||||
result = {}
|
||||
|
||||
for name in METRICS:
|
||||
rows = prometheus(f"sum({name})")
|
||||
result[name] = float(rows[0]["value"][1]) if rows else 0.0
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def switch_mode(mode):
|
||||
enabled, ratio = MODES[mode]
|
||||
|
||||
env = dict(os.environ)
|
||||
env["TELEMETRY_ENABLED"] = enabled
|
||||
env["TELEMETRY_TRACE_SAMPLE_RATIO"] = ratio
|
||||
env["TELEMETRY_BENCHMARK_ENABLED"] = "0"
|
||||
env["TELEMETRY_COLLECTOR_CONFIG"] = (
|
||||
"config-balanced.yaml"
|
||||
if mode == "balanced"
|
||||
else "config.yaml"
|
||||
)
|
||||
|
||||
command(
|
||||
[
|
||||
"docker", "compose", "up", "-d",
|
||||
"--no-deps", "otel-collector",
|
||||
],
|
||||
env=env,
|
||||
)
|
||||
|
||||
time.sleep(20)
|
||||
|
||||
command(
|
||||
[
|
||||
"docker", "compose", "up", "-d",
|
||||
"--no-deps", *SERVICES,
|
||||
],
|
||||
env=env,
|
||||
)
|
||||
|
||||
deadline = time.monotonic() + 120
|
||||
|
||||
while time.monotonic() < deadline:
|
||||
ready = True
|
||||
|
||||
for service in ["api-1", "api-2"]:
|
||||
cid = subprocess.check_output(
|
||||
["docker", "compose", "ps", "-q", service],
|
||||
text=True,
|
||||
).strip()
|
||||
|
||||
if not cid:
|
||||
ready = False
|
||||
break
|
||||
|
||||
status = subprocess.check_output(
|
||||
[
|
||||
"docker", "inspect",
|
||||
"--format", "{{.State.Health.Status}}",
|
||||
cid,
|
||||
],
|
||||
text=True,
|
||||
).strip()
|
||||
|
||||
if status != "healthy":
|
||||
ready = False
|
||||
break
|
||||
|
||||
if ready:
|
||||
break
|
||||
|
||||
time.sleep(3)
|
||||
else:
|
||||
raise RuntimeError("API replicas are not healthy")
|
||||
|
||||
command(["make", "test"])
|
||||
time.sleep(15)
|
||||
|
||||
|
||||
def container_ids():
|
||||
result = {}
|
||||
|
||||
for service in MONITORED:
|
||||
cid = subprocess.check_output(
|
||||
["docker", "compose", "ps", "-q", service],
|
||||
text=True,
|
||||
).strip()
|
||||
|
||||
if not cid:
|
||||
raise RuntimeError(f"Container missing: {service}")
|
||||
|
||||
result[cid[:12]] = service
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def memory_mib(value):
|
||||
value = value.split("/")[0].strip()
|
||||
match = re.fullmatch(r"([\d.]+)\s*([A-Za-z]+)", value)
|
||||
|
||||
if not match:
|
||||
raise ValueError(f"Unknown memory format: {value}")
|
||||
|
||||
number, unit = match.groups()
|
||||
|
||||
factors = {
|
||||
"B": 1 / 1048576,
|
||||
"KiB": 1 / 1024,
|
||||
"MiB": 1,
|
||||
"GiB": 1024,
|
||||
"kB": 1000 / 1048576,
|
||||
"MB": 1000000 / 1048576,
|
||||
"GB": 1000000000 / 1048576,
|
||||
}
|
||||
|
||||
return float(number) * factors[unit]
|
||||
|
||||
|
||||
def docker_sample(ids):
|
||||
output = subprocess.check_output(
|
||||
[
|
||||
"docker", "stats", "--no-stream",
|
||||
"--format", "{{json .}}",
|
||||
*ids,
|
||||
],
|
||||
text=True,
|
||||
)
|
||||
|
||||
result = {"timestamp": time.time(), "services": {}}
|
||||
|
||||
for line in output.splitlines():
|
||||
row = json.loads(line)
|
||||
service = ids[row["ID"][:12]]
|
||||
|
||||
result["services"][service] = {
|
||||
"cpu_percent": float(row["CPUPerc"].rstrip("%")),
|
||||
"memory_mib": memory_mib(row["MemUsage"]),
|
||||
}
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def summarize_resources(samples):
|
||||
result = {}
|
||||
|
||||
groups = {
|
||||
**{service: [service] for service in MONITORED},
|
||||
"application_total": SERVICES,
|
||||
"observability_total": [
|
||||
"otel-collector", "prometheus", "loki", "tempo"
|
||||
],
|
||||
}
|
||||
|
||||
for name, services in groups.items():
|
||||
cpu = []
|
||||
ram = []
|
||||
|
||||
for sample in samples:
|
||||
rows = sample["services"]
|
||||
|
||||
if all(service in rows for service in services):
|
||||
cpu.append(sum(
|
||||
rows[service]["cpu_percent"]
|
||||
for service in services
|
||||
))
|
||||
ram.append(sum(
|
||||
rows[service]["memory_mib"]
|
||||
for service in services
|
||||
))
|
||||
|
||||
if cpu:
|
||||
result[name] = {
|
||||
"samples": len(cpu),
|
||||
"cpu_mean_percent": round(statistics.mean(cpu), 3),
|
||||
"cpu_peak_percent": round(max(cpu), 3),
|
||||
"ram_mean_mib": round(statistics.mean(ram), 3),
|
||||
"ram_peak_mib": round(max(ram), 3),
|
||||
}
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def experiment(mode, repeat, args):
|
||||
name = f"{mode}-{repeat}"
|
||||
output = ROOT / "evidence" / f"grade5-{name}.json"
|
||||
|
||||
print(f"\n=== Experiment {name} ===", flush=True)
|
||||
|
||||
switch_mode(mode)
|
||||
ids = container_ids()
|
||||
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
marker = Path(directory) / "start"
|
||||
|
||||
process = subprocess.Popen([
|
||||
sys.executable,
|
||||
"scripts/benchmark_telemetry.py",
|
||||
"--mode", name,
|
||||
"--requests", str(args.requests),
|
||||
"--rate", str(args.rate),
|
||||
"--workers", str(args.workers),
|
||||
"--warmup", str(args.warmup),
|
||||
"--start-marker", str(marker),
|
||||
"--output", str(output),
|
||||
])
|
||||
|
||||
try:
|
||||
deadline = time.monotonic() + 180
|
||||
|
||||
while not marker.exists():
|
||||
if process.poll() is not None:
|
||||
raise RuntimeError("Benchmark exited before measurement")
|
||||
|
||||
if time.monotonic() > deadline:
|
||||
raise RuntimeError("Benchmark warmup timeout")
|
||||
|
||||
time.sleep(0.1)
|
||||
|
||||
before = snapshot()
|
||||
marker.unlink()
|
||||
|
||||
samples = []
|
||||
|
||||
while process.poll() is None:
|
||||
samples.append(docker_sample(ids))
|
||||
time.sleep(1)
|
||||
|
||||
if process.wait() != 0:
|
||||
raise RuntimeError("Benchmark failed")
|
||||
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
process.wait()
|
||||
|
||||
time.sleep(40 if mode == "balanced" else 15)
|
||||
after = snapshot()
|
||||
|
||||
report = json.loads(output.read_text())
|
||||
|
||||
samples = [
|
||||
sample for sample in samples
|
||||
if report["started_at_unix"]
|
||||
<= sample["timestamp"]
|
||||
<= report["finished_at_unix"]
|
||||
]
|
||||
|
||||
if not samples:
|
||||
raise RuntimeError("No resource samples")
|
||||
|
||||
deltas = {
|
||||
name: round(after[name] - before[name], 3)
|
||||
for name in METRICS
|
||||
}
|
||||
|
||||
if any(value < 0 for value in deltas.values()):
|
||||
raise RuntimeError("Collector counter reset detected")
|
||||
|
||||
report["collector_before"] = before
|
||||
report["collector_after"] = after
|
||||
report["collector_deltas"] = deltas
|
||||
report["resources"] = summarize_resources(samples)
|
||||
report["resource_samples"] = samples
|
||||
|
||||
output.write_text(
|
||||
json.dumps(report, indent=2, ensure_ascii=False) + "\n"
|
||||
)
|
||||
|
||||
print(f"Saved: {output}", flush=True)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--requests", type=int, default=1200)
|
||||
parser.add_argument("--rate", type=float, default=20)
|
||||
parser.add_argument("--workers", type=int, default=16)
|
||||
parser.add_argument("--warmup", type=int, default=100)
|
||||
parser.add_argument("--repeats", type=int, default=3)
|
||||
parser.add_argument("--mode", choices=list(MODES))
|
||||
args = parser.parse_args()
|
||||
|
||||
if min(
|
||||
args.requests, args.rate, args.workers, args.repeats
|
||||
) <= 0 or args.warmup < 0:
|
||||
parser.error("Invalid experiment parameters")
|
||||
|
||||
orders = [
|
||||
["baseline", "full", "optimized"],
|
||||
["full", "optimized", "baseline"],
|
||||
["optimized", "baseline", "full"],
|
||||
]
|
||||
|
||||
try:
|
||||
for repeat in range(1, args.repeats + 1):
|
||||
selected = (
|
||||
[args.mode] if args.mode
|
||||
else orders[(repeat - 1) % len(orders)]
|
||||
)
|
||||
for mode in selected:
|
||||
experiment(mode, repeat, args)
|
||||
|
||||
finally:
|
||||
print("\nRestoring full telemetry", flush=True)
|
||||
switch_mode("full")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user