forked from mtusi2026/mtusi2026lab6
176 lines
4.4 KiB
Python
176 lines
4.4 KiB
Python
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()
|