forked from mtusi2026/mtusi2026lab6
250 lines
9.4 KiB
Python
250 lines
9.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Track 1: Cost of Observability across off, always_on 100%, head 10%, and balanced tail-sampling."""
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
import json
|
|
import math
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import sys
|
|
import threading
|
|
import time
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / 'tests'))
|
|
sys.path.insert(0, str(ROOT / 'student-tests'))
|
|
|
|
from client import Client, Failure
|
|
from grafana_helper import GrafanaClient
|
|
|
|
PROFILES = [
|
|
{
|
|
'name': 'telemetry_off',
|
|
'env': {
|
|
'OTEL_SDK_DISABLED': 'true',
|
|
'OTEL_TRACES_SAMPLER': 'always_off',
|
|
'OTEL_TRACES_SAMPLER_ARG': '0.0',
|
|
'OTEL_COLLECTOR_CONFIG': './infra/otel/collector.yaml',
|
|
},
|
|
},
|
|
{
|
|
'name': 'always_on_100pct',
|
|
'env': {
|
|
'OTEL_SDK_DISABLED': 'false',
|
|
'OTEL_TRACES_SAMPLER': 'always_on',
|
|
'OTEL_TRACES_SAMPLER_ARG': '1.0',
|
|
'OTEL_COLLECTOR_CONFIG': './infra/otel/collector.yaml',
|
|
},
|
|
},
|
|
{
|
|
'name': 'head_sampling_10pct',
|
|
'env': {
|
|
'OTEL_SDK_DISABLED': 'false',
|
|
'OTEL_TRACES_SAMPLER': 'parentbased_traceidratio',
|
|
'OTEL_TRACES_SAMPLER_ARG': '0.1',
|
|
'OTEL_COLLECTOR_CONFIG': './infra/otel/collector.yaml',
|
|
},
|
|
},
|
|
{
|
|
'name': 'tail_sampling_balanced',
|
|
'env': {
|
|
'OTEL_SDK_DISABLED': 'false',
|
|
'OTEL_TRACES_SAMPLER': 'always_on',
|
|
'OTEL_TRACES_SAMPLER_ARG': '1.0',
|
|
'OTEL_COLLECTOR_CONFIG': './infra/otel/collector-tail-sampling.yaml',
|
|
},
|
|
},
|
|
]
|
|
|
|
def compose(*args, env_extra=None):
|
|
env = os.environ.copy()
|
|
if env_extra:
|
|
env.update(env_extra)
|
|
subprocess.run(['docker', 'compose', *args], cwd=ROOT, env=env, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
|
|
def wait_api_ready(c, timeout=45):
|
|
deadline = time.monotonic() + timeout
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
c.call('GET', '/health/ready', schema='Health')
|
|
time.sleep(2)
|
|
return
|
|
except Exception:
|
|
time.sleep(0.5)
|
|
raise RuntimeError('API did not become ready')
|
|
|
|
def prom_scalar(g, expr):
|
|
res = g.prom_query(expr).get('data', {}).get('result', [])
|
|
return float(res[0]['value'][1]) if res else 0.0
|
|
|
|
def sample_stats():
|
|
out = subprocess.check_output(
|
|
['docker', 'stats', '--no-stream', '--format', '{{.Name}}|{{.CPUPerc}}|{{.MemUsage}}',
|
|
'mtusi_lab6_solution-api-1', 'mtusi_lab6_solution-api-2', 'mtusi_lab6_solution-otel-collector-1'],
|
|
text=True,
|
|
).strip().splitlines()
|
|
parsed = {}
|
|
for line in out:
|
|
name, cpu, mem = line.split('|')
|
|
short = name.replace('mtusi_lab6_solution-', '')
|
|
parsed[short] = {'cpu_pct': float(cpu.strip().rstrip('%') or 0.0), 'mem': mem.split('/')[0].strip()}
|
|
return parsed
|
|
|
|
def trigger_503_batch(alice, chat, tag, count=5):
|
|
proc = subprocess.Popen(
|
|
['docker', 'compose', 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-Atq'],
|
|
cwd=ROOT, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True,
|
|
)
|
|
assert proc.stdin and proc.stdout
|
|
proc.stdin.write("BEGIN;\nLOCK TABLE messages IN SHARE MODE;\nSELECT 'LOCKED_NOW';\n")
|
|
proc.stdin.flush()
|
|
while True:
|
|
line = proc.stdout.readline()
|
|
if not line or 'LOCKED_NOW' in line:
|
|
break
|
|
def send_one(idx):
|
|
local = Client('http://localhost:8081', timeout=10)
|
|
try:
|
|
res = local.call('POST', f'/api/v1/chats/{chat["id"]}/messages', 503, actor=alice, body={'text': f'err-{tag}-{idx}'}, headers={'Idempotency-Key': f'err-{tag}-{idx}'})
|
|
return res['status']
|
|
except Failure:
|
|
return 0
|
|
with ThreadPoolExecutor(max_workers=count) as ex:
|
|
statuses = list(ex.map(send_one, range(count)))
|
|
proc.stdin.write("COMMIT;\n\\q\n")
|
|
proc.stdin.flush()
|
|
proc.communicate(timeout=10)
|
|
return sum(1 for s in statuses if s == 503)
|
|
|
|
def run_profile(g, prof, duration=20, concurrency=6):
|
|
print(f'=== Running Track 1 profile: {prof["name"]} ===')
|
|
compose('up', '-d', '--force-recreate', 'otel-collector', env_extra=prof['env'])
|
|
compose('up', '-d', '--force-recreate', '--wait', '--scale', 'api=2', 'api', 'worker', env_extra=prof['env'])
|
|
c = Client('http://localhost:8081')
|
|
wait_api_ready(c)
|
|
|
|
alice, _, _, chat = c.bootstrap()
|
|
for i in range(10):
|
|
c.message(alice, chat, f'warmup-{i}')
|
|
time.sleep(8)
|
|
|
|
accepted_before = prom_scalar(g, 'sum(otelcol_receiver_accepted_spans_total)')
|
|
sent_before = prom_scalar(g, 'sum(otelcol_exporter_sent_spans_total)')
|
|
|
|
samples = []
|
|
stop_sample = threading.Event()
|
|
def sampler():
|
|
while not stop_sample.is_set():
|
|
try:
|
|
samples.append(sample_stats())
|
|
except Exception:
|
|
pass
|
|
stop_sample.wait(5)
|
|
|
|
sam_th = threading.Thread(target=sampler, daemon=True)
|
|
sam_th.start()
|
|
|
|
barrier = threading.Barrier(concurrency)
|
|
def worker_fn(wid):
|
|
local = Client('http://localhost:8081', timeout=5)
|
|
barrier.wait()
|
|
deadline = time.monotonic() + duration
|
|
lats = []
|
|
errs = 0
|
|
idx = 0
|
|
while time.monotonic() < deadline:
|
|
t = time.monotonic()
|
|
try:
|
|
local.message(alice, chat, f't1-{prof["name"]}-{wid}-{idx}')
|
|
lats.append(time.monotonic() - t)
|
|
except Failure:
|
|
errs += 1
|
|
idx += 1
|
|
return lats, errs
|
|
|
|
t_start = time.time()
|
|
with ThreadPoolExecutor(max_workers=concurrency) as ex:
|
|
results = list(ex.map(worker_fn, range(concurrency)))
|
|
elapsed = time.time() - t_start
|
|
stop_sample.set()
|
|
sam_th.join(timeout=6)
|
|
|
|
err_captured = 0
|
|
slow_captured = 0
|
|
err_injected = 0
|
|
if prof['name'] != 'telemetry_off':
|
|
compose('up', '-d', '--force-recreate', '--wait', '--scale', 'api=2', 'api', env_extra={**prof['env'], 'FAULT_HANDLER_DELAY_MS': '200'})
|
|
wait_api_ready(c)
|
|
t_slow_start = time.time()
|
|
for k in range(5):
|
|
c.message(alice, chat, f'slow-{prof["name"]}-{k}')
|
|
t_slow_end = time.time()
|
|
compose('up', '-d', '--force-recreate', '--wait', '--scale', 'api=2', 'api', env_extra={**prof['env'], 'FAULT_HANDLER_DELAY_MS': '0'})
|
|
wait_api_ready(c)
|
|
|
|
t_err_start = time.time()
|
|
err_injected += trigger_503_batch(alice, chat, f'{prof["name"]}-b0', count=5)
|
|
err_injected += trigger_503_batch(alice, chat, f'{prof["name"]}-b1', count=5)
|
|
t_err_end = time.time()
|
|
|
|
time.sleep(10)
|
|
err_res = g.tempo_search('{ resource.service.name = "messenger-api" && status = error }', t_err_start - 5, t_err_end + 15, limit=50)
|
|
err_captured = len(err_res.get('traces', []))
|
|
slow_res = g.tempo_search('{ resource.service.name = "messenger-api" && duration > 150ms && status != error }', t_slow_start - 5, t_slow_end + 15, limit=50)
|
|
slow_captured = len(slow_res.get('traces', []))
|
|
else:
|
|
time.sleep(8)
|
|
|
|
accepted_after = prom_scalar(g, 'sum(otelcol_receiver_accepted_spans_total)')
|
|
sent_after = prom_scalar(g, 'sum(otelcol_exporter_sent_spans_total)')
|
|
accepted_delta = max(0, round(accepted_after - accepted_before))
|
|
sent_delta = max(0, round(sent_after - sent_before))
|
|
drop_ratio = max(0.0, round(1.0 - (sent_delta / accepted_delta), 4)) if accepted_delta > 0 else 0.0
|
|
|
|
lats = sorted(x for ls, _ in results for x in ls)
|
|
errs = sum(e for _, e in results)
|
|
def pct(p):
|
|
return round(1000 * lats[max(0, math.ceil(p * len(lats)) - 1)], 2) if lats else None
|
|
|
|
avg_cpu = {}
|
|
last_mem = {}
|
|
if samples:
|
|
for k in samples[0]:
|
|
avg_cpu[k] = round(sum(s[k]['cpu_pct'] for s in samples if k in s) / len(samples), 2)
|
|
last_mem[k] = samples[-1].get(k, {}).get('mem')
|
|
|
|
return {
|
|
'profile': prof['name'],
|
|
'duration_seconds': duration,
|
|
'concurrency': concurrency,
|
|
'successful_requests': len(lats),
|
|
'failed_requests': errs,
|
|
'rps': round(len(lats) / elapsed, 2),
|
|
'latency_ms': {'p50': pct(0.50), 'p95': pct(0.95), 'p99': pct(0.99)},
|
|
'collector_spans_accepted': accepted_delta,
|
|
'tempo_spans_exported': sent_delta,
|
|
'span_drop_ratio': drop_ratio,
|
|
'injected_5xx_errors_captured': f'{min(err_injected, err_captured)}/{err_injected}' if prof['name'] != 'telemetry_off' else '0/10 (disabled)',
|
|
'injected_slow_gt150ms_captured': f'{min(5, slow_captured)}/5' if prof['name'] != 'telemetry_off' else '0/5 (disabled)',
|
|
'avg_cpu_pct_under_load': avg_cpu,
|
|
'mem_under_load': last_mem,
|
|
}
|
|
|
|
def main():
|
|
g = GrafanaClient('http://localhost:3000')
|
|
g.wait_ready(timeout=90)
|
|
results = []
|
|
try:
|
|
for prof in PROFILES:
|
|
results.append(run_profile(g, prof))
|
|
finally:
|
|
compose('up', '-d', '--force-recreate', 'otel-collector', env_extra=PROFILES[3]['env'])
|
|
compose('up', '-d', '--force-recreate', '--wait', '--scale', 'api=2', 'api', 'worker', env_extra=PROFILES[3]['env'])
|
|
|
|
summary = {'track': 'cost-of-observability', 'profiles': results}
|
|
dest = ROOT / 'evidence/track1-observability-cost.json'
|
|
dest.write_text(json.dumps(summary, indent=2, ensure_ascii=False) + '\n', encoding='utf-8')
|
|
print(json.dumps(summary, indent=2, ensure_ascii=False))
|
|
|
|
if __name__ == '__main__':
|
|
main() |