226 lines
8.3 KiB
Python
226 lines
8.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Track 5.1 - the cost of observability.
|
|
|
|
Compares identical load with telemetry:
|
|
* OFF (no SDK providers);
|
|
* ON, sampler = always_on (keep 100% of traces);
|
|
* ON, sampler = ratio 0.1 (head sampling keeps ~10%);
|
|
* ON, Collector tail_sampling (keep all errors + slow, 10% baseline).
|
|
|
|
For each configuration it recreates the API + worker (and the Collector when the
|
|
sampling strategy changes), runs the same closed-loop load, and reports client
|
|
p50/p95 latency, successful RPS, API+worker CPU/RAM, and Collector span ingest /
|
|
loss from the Collector's own metrics.
|
|
|
|
Run from the repository root (docker CLI + running lab6 stand).
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import base64
|
|
import concurrent.futures
|
|
import json
|
|
import os
|
|
import statistics
|
|
import subprocess
|
|
import threading
|
|
import time
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
import uuid
|
|
|
|
BASE = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/")
|
|
PROM = os.environ.get("PROM_URL", "http://localhost:9090").rstrip("/")
|
|
|
|
CONFIGS = [
|
|
{"name": "off", "env": {"TELEMETRY_ENABLED": "0"}, "collector": None},
|
|
{"name": "on_always_on", "env": {"TELEMETRY_ENABLED": "1", "OTEL_TRACES_SAMPLER": "always_on"}, "collector": None},
|
|
{"name": "on_ratio_0.1", "env": {"TELEMETRY_ENABLED": "1", "OTEL_TRACES_SAMPLER": "parentbased_traceidratio", "OTEL_TRACES_SAMPLER_ARG": "0.1"}, "collector": None},
|
|
{"name": "on_tail_balanced", "env": {"TELEMETRY_ENABLED": "1", "OTEL_TRACES_SAMPLER": "parentbased_always_on"}, "collector": "/etc/otelcol/otel-collector-tailsampling.yaml"},
|
|
]
|
|
|
|
RESULTS = []
|
|
|
|
|
|
def call(method, path, token=None, body=None):
|
|
headers = {"Accept": "application/json"}
|
|
data = None
|
|
if body is not None:
|
|
data = json.dumps(body).encode()
|
|
headers["Content-Type"] = "application/json"
|
|
if token:
|
|
headers["Authorization"] = "Bearer " + token
|
|
req = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
|
|
start = time.perf_counter()
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=20) as resp:
|
|
resp.read()
|
|
return resp.status, time.perf_counter() - start
|
|
except urllib.error.HTTPError as error:
|
|
return error.code, time.perf_counter() - start
|
|
|
|
|
|
def login():
|
|
username = "cost_" + uuid.uuid4().hex[:8]
|
|
password = "T3st-" + uuid.uuid4().hex
|
|
call("POST", "/api/v1/users", body={"username": username, "display_name": "Cost", "password": password})
|
|
credential = base64.b64encode(f"{username}:{password}".encode()).decode()
|
|
req = urllib.request.Request(BASE + "/api/v1/auth/sessions",
|
|
headers={"Authorization": "Basic " + credential, "Accept": "application/json"},
|
|
method="POST")
|
|
with urllib.request.urlopen(req, timeout=20) as resp:
|
|
return json.loads(resp.read())["token"]
|
|
|
|
|
|
def wait_ready(timeout=120):
|
|
deadline = time.time() + timeout
|
|
while time.time() < deadline:
|
|
try:
|
|
if call("GET", "/health/ready")[0] == 200:
|
|
return
|
|
except Exception: # noqa: BLE001
|
|
pass
|
|
time.sleep(2)
|
|
raise SystemExit("stand not ready")
|
|
|
|
|
|
def recreate(env_overrides, collector):
|
|
env = dict(os.environ)
|
|
env.update(env_overrides)
|
|
if collector:
|
|
env["COLLECTOR_CONFIG"] = collector
|
|
subprocess.run(["docker", "compose", "up", "-d", "--force-recreate", "api", "worker"],
|
|
env=env, check=True, capture_output=True, text=True)
|
|
if collector:
|
|
subprocess.run(["docker", "compose", "up", "-d", "--force-recreate", "otel-collector"],
|
|
env=env, check=True, capture_output=True, text=True)
|
|
time.sleep(6)
|
|
|
|
|
|
def container_stats():
|
|
out = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.Name}}|{{.CPUPerc}}|{{.MemUsage}}"],
|
|
capture_output=True, text=True).stdout
|
|
cpu = 0.0
|
|
mem = 0.0
|
|
for line in out.splitlines():
|
|
name, _, rest = line.partition("|")
|
|
if "api" not in name and "worker" not in name:
|
|
continue
|
|
cpu_part, _, mem_part = rest.partition("|")
|
|
try:
|
|
cpu += float(cpu_part.strip().rstrip("%"))
|
|
except ValueError:
|
|
pass
|
|
value = mem_part.split("/")[0].strip()
|
|
number = "".join(ch for ch in value if ch.isdigit() or ch == ".")
|
|
if value.endswith("GiB"):
|
|
mem += float(number) * 1024
|
|
elif value.endswith("MiB"):
|
|
mem += float(number)
|
|
return cpu, mem
|
|
|
|
|
|
def prom_sum(expr):
|
|
try:
|
|
with urllib.request.urlopen(PROM + "/api/v1/query?" + urllib.parse.urlencode({"query": expr}), timeout=10) as resp:
|
|
data = json.loads(resp.read())
|
|
result = data["data"]["result"]
|
|
return float(result[0]["value"][1]) if result else 0.0
|
|
except Exception: # noqa: BLE001
|
|
return 0.0
|
|
|
|
|
|
def run_case(config, duration, threads):
|
|
print(f"\n== config {config['name']} ==", flush=True)
|
|
recreate(config["env"], config["collector"])
|
|
wait_ready()
|
|
token = login()
|
|
|
|
accepted_before = prom_sum("sum(otelcol_receiver_accepted_spans)")
|
|
sent_before = prom_sum("sum(otelcol_exporter_sent_spans)")
|
|
|
|
latencies = []
|
|
errors = 0
|
|
lock = threading.Lock()
|
|
stop = threading.Event()
|
|
peak = {"cpu": 0.0, "mem": 0.0}
|
|
|
|
def sampler():
|
|
while not stop.is_set():
|
|
cpu, mem = container_stats()
|
|
peak["cpu"] = max(peak["cpu"], cpu)
|
|
peak["mem"] = max(peak["mem"], mem)
|
|
time.sleep(0.5)
|
|
|
|
def worker():
|
|
nonlocal errors
|
|
deadline = time.time() + duration
|
|
while time.time() < deadline:
|
|
status, latency = call("GET", "/api/v1/users/me", token=token)
|
|
with lock:
|
|
if status == 200:
|
|
latencies.append(latency)
|
|
else:
|
|
errors += 1
|
|
|
|
thread = threading.Thread(target=sampler, daemon=True)
|
|
thread.start()
|
|
start = time.time()
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=threads) as pool:
|
|
list(pool.map(lambda _: worker(), range(threads)))
|
|
elapsed = time.time() - start
|
|
stop.set()
|
|
thread.join(timeout=2)
|
|
|
|
accepted_after = prom_sum("sum(otelcol_receiver_accepted_spans)")
|
|
sent_after = prom_sum("sum(otelcol_exporter_sent_spans)")
|
|
failed = prom_sum("sum(otelcol_exporter_send_failed_spans)")
|
|
|
|
result = {
|
|
"config": config["name"],
|
|
"requests": len(latencies) + errors,
|
|
"errors": errors,
|
|
"rps": round((len(latencies) + errors) / max(0.001, elapsed), 1),
|
|
"p50_ms": round(statistics.median(latencies) * 1000, 2) if latencies else None,
|
|
"p95_ms": round(sorted(latencies)[min(len(latencies) - 1, int(0.95 * (len(latencies) - 1)))] * 1000, 2) if latencies else None,
|
|
"api_worker_cpu_peak_pct": round(peak["cpu"], 1),
|
|
"api_worker_mem_peak_mb": round(peak["mem"], 1),
|
|
"spans_accepted_delta": int(accepted_after - accepted_before),
|
|
"spans_sent_delta": int(sent_after - sent_before),
|
|
"spans_failed_total": int(failed),
|
|
}
|
|
RESULTS.append(result)
|
|
print(json.dumps(result, ensure_ascii=False), flush=True)
|
|
return result
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--duration", type=int, default=15)
|
|
parser.add_argument("--threads", type=int, default=8)
|
|
parser.add_argument("--output", default="evidence/lab6-cost.json")
|
|
args = parser.parse_args()
|
|
|
|
for config in CONFIGS:
|
|
run_case(config, args.duration, args.threads)
|
|
|
|
# Restore the default balanced setup.
|
|
recreate({}, "/etc/otelcol/otel-collector.yaml")
|
|
|
|
os.makedirs(os.path.dirname(args.output), exist_ok=True)
|
|
with open(args.output, "w", encoding="utf-8") as handle:
|
|
json.dump({"duration": args.duration, "threads": args.threads, "results": RESULTS},
|
|
handle, ensure_ascii=False, indent=2)
|
|
|
|
print("\nconfig rps p50_ms p95_ms cpu%_peak memMB_peak spans_accepted spans_sent")
|
|
for r in RESULTS:
|
|
print(f"{r['config']:<16} {r['rps']:>5} {str(r['p50_ms']):>6} {str(r['p95_ms']):>6} "
|
|
f"{r['api_worker_cpu_peak_pct']:>8} {r['api_worker_mem_peak_mb']:>9} "
|
|
f"{r['spans_accepted_delta']:>14} {r['spans_sent_delta']:>10}")
|
|
print(json.dumps({"output": args.output}))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|