forked from mtusi2026/mtusi2026lab3
ЛР 3 — БПИ2303 — Морару — на 5: API на TypeScript/Node, HAProxy, failover, трек 1
This commit is contained in:
Executable
+23
@@ -0,0 +1,23 @@
|
||||
#!/bin/sh
|
||||
# Трек 1: для каждой конфигурации "реплики cpu пул" ступенчато повышает нагрузку, сохраняет итог k6 и снимок CPU.
|
||||
# Запуск: research/bench.sh OUT_DIR "N CPUS POOL" ... (ступени RPS — переменная RATES)
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
out=$1; shift
|
||||
mkdir -p "$out"
|
||||
RATES=${RATES:-"400 800 1200 1600 2400"}
|
||||
for cfg in "$@"; do
|
||||
set -- $cfg
|
||||
n=$1 cpus=$2 pool=$3
|
||||
mem=$((512 / n))m
|
||||
API_REPLICAS=$n API_CPUS=$cpus API_MEMORY=$mem DB_POOL_MAX=$pool docker compose --env-file .env up -d --wait api lb >/dev/null 2>&1
|
||||
sleep 3
|
||||
for rate in $RATES; do
|
||||
tag="n${n}_c${cpus}_p${pool}_r${rate}"
|
||||
( sleep 8; docker stats --no-stream --format '{{.Name}} {{.CPUPerc}}' | grep messenger-lab3 > "$out/$tag.cpu" ) &
|
||||
docker run --rm --cpus 3 --network messenger-lab3_frontend -v "$PWD/research/k6:/k6:ro" \
|
||||
-e RATE="$rate" -e DURATION=15s -e PAIRS=10 grafana/k6:1.8.2 run -q /k6/messenger.js 2>/dev/null | tail -1 > "$out/$tag.json"
|
||||
wait
|
||||
echo "$tag $(cat "$out/$tag.json")"
|
||||
done
|
||||
done
|
||||
@@ -0,0 +1,108 @@
|
||||
// Профиль нагрузки open model (постоянная интенсивность, без coordinated omission):
|
||||
// доля WRITE_SHARE итераций отправляет сообщение с новым Idempotency-Key, остальные читают страницу истории (limit 20).
|
||||
// Запускается в docker в сети стенда, см. REPORT.md (трек 1).
|
||||
import http from 'k6/http';
|
||||
import encoding from 'k6/encoding';
|
||||
import { Counter } from 'k6/metrics';
|
||||
|
||||
const BASE = __ENV.BASE_URL || 'http://lb:8080';
|
||||
const RATE = Number(__ENV.RATE || 200);
|
||||
const WRITE_SHARE = Number(__ENV.WRITE_SHARE || 0.5);
|
||||
const PAIRS = Number(__ENV.PAIRS || 20);
|
||||
const OUT = __ENV.OUT || '';
|
||||
const DURATION = __ENV.DURATION || '30s';
|
||||
const byInstance = new Counter('by_instance');
|
||||
const failed = new Counter('failed_requests');
|
||||
|
||||
export const options = {
|
||||
scenarios: {
|
||||
load: {
|
||||
executor: 'constant-arrival-rate',
|
||||
rate: RATE,
|
||||
timeUnit: '1s',
|
||||
duration: DURATION,
|
||||
preAllocatedVUs: Number(__ENV.VUS || Math.max(50, RATE / 4)),
|
||||
maxVUs: Number(__ENV.MAX_VUS || 2000),
|
||||
gracefulStop: '5s',
|
||||
},
|
||||
},
|
||||
setupTimeout: '180s',
|
||||
// Пороги нужны только для подметрик: так трафик setup() не попадает в итоговые числа.
|
||||
thresholds: {
|
||||
'http_reqs{scenario:load}': ['count>=0'],
|
||||
'http_req_duration{scenario:load}': ['max>=0'],
|
||||
'http_req_duration{op:write}': ['max>=0'],
|
||||
'http_req_duration{op:read}': ['max>=0'],
|
||||
},
|
||||
summaryTrendStats: ['avg', 'p(50)', 'p(95)', 'p(99)', 'max'],
|
||||
};
|
||||
|
||||
const json = { headers: { 'Content-Type': 'application/json' }, timeout: '10s' };
|
||||
|
||||
function user(tag) {
|
||||
const username = `k6_${tag}_${Math.random().toString(36).slice(2, 12)}`;
|
||||
const password = 'Bench-' + Math.random().toString(36).slice(2) + 'xx';
|
||||
const created = http.post(`${BASE}/api/v1/users`, JSON.stringify({ username, display_name: 'bench ' + tag, password }), json);
|
||||
if (created.status !== 201) throw new Error('register ' + created.status);
|
||||
const basic = encoding.b64encode(`${username}:${password}`);
|
||||
const s = http.post(`${BASE}/api/v1/auth/sessions`, null, { headers: { Authorization: 'Basic ' + basic } });
|
||||
if (s.status !== 201) throw new Error('login ' + s.status);
|
||||
return { id: created.json('id'), token: s.json('token') };
|
||||
}
|
||||
|
||||
export function setup() {
|
||||
const actors = [];
|
||||
for (let i = 0; i < PAIRS; i++) {
|
||||
const a = user(`a${i}`);
|
||||
const b = user(`b${i}`);
|
||||
const chat = http.post(`${BASE}/api/v1/chats`, JSON.stringify({ title: 'bench ' + i, member_ids: [a.id, b.id] }),
|
||||
{ headers: { ...json.headers, Authorization: 'Bearer ' + a.token } });
|
||||
if (chat.status !== 201) throw new Error('chat ' + chat.status);
|
||||
const chatId = chat.json('id');
|
||||
for (let m = 0; m < 20; m++) { // непустая первая страница истории
|
||||
http.post(`${BASE}/api/v1/chats/${chatId}/messages`, JSON.stringify({ text: 'seed ' + m }),
|
||||
{ headers: { ...json.headers, Authorization: 'Bearer ' + a.token, 'Idempotency-Key': `seed-${chatId}-${m}` } });
|
||||
}
|
||||
actors.push({ token: a.token, chatId }, { token: b.token, chatId });
|
||||
}
|
||||
return { actors };
|
||||
}
|
||||
|
||||
export default function (data) {
|
||||
const actor = data.actors[Math.floor(Math.random() * data.actors.length)];
|
||||
const auth = { Authorization: 'Bearer ' + actor.token };
|
||||
const write = Math.random() < WRITE_SHARE;
|
||||
const res = write
|
||||
? http.post(`${BASE}/api/v1/chats/${actor.chatId}/messages`, JSON.stringify({ text: `load ${__VU}-${__ITER}` }),
|
||||
{ headers: { ...json.headers, ...auth, 'Idempotency-Key': `k6-${__VU}-${__ITER}-${Date.now()}` }, timeout: '10s', tags: { op: 'write' } })
|
||||
: http.get(`${BASE}/api/v1/chats/${actor.chatId}/messages?limit=20`, { headers: auth, timeout: '10s', tags: { op: 'read' } });
|
||||
const ok = res.status === (write ? 201 : 200);
|
||||
if (!ok) failed.add(1, { status: String(res.status) });
|
||||
byInstance.add(1, { instance: res.headers['X-Instance-Id'] || 'none', ok: String(ok) });
|
||||
}
|
||||
|
||||
export function handleSummary(data) {
|
||||
const m = data.metrics;
|
||||
const pick = (v) => ({ avg: v.avg, p50: v['p(50)'], p95: v['p(95)'], p99: v['p(99)'], max: v.max });
|
||||
const d = m['http_req_duration{scenario:load}'].values;
|
||||
const reqs = m['http_reqs{scenario:load}'].values.count;
|
||||
const fails = m.failed_requests ? m.failed_requests.values.count : 0;
|
||||
const seconds = parseFloat(DURATION); // секунды, например '30s'
|
||||
const summary = {
|
||||
offered_rps: RATE,
|
||||
write_share: WRITE_SHARE,
|
||||
duration_s: Number(seconds.toFixed(2)),
|
||||
requests: reqs,
|
||||
failed: fails,
|
||||
error_ratio: reqs ? Number((fails / reqs).toFixed(6)) : null,
|
||||
successful_rps: Number(((reqs - fails) / seconds).toFixed(1)),
|
||||
dropped_iterations: m.dropped_iterations ? m.dropped_iterations.values.count : 0,
|
||||
latency_ms: pick(d),
|
||||
write_latency_ms: pick(m['http_req_duration{op:write}'].values),
|
||||
read_latency_ms: pick(m['http_req_duration{op:read}'].values),
|
||||
max_vus: m.vus_max ? m.vus_max.values.max : null,
|
||||
};
|
||||
const out = { stdout: JSON.stringify(summary) + '\n' };
|
||||
if (OUT) out[OUT] = JSON.stringify(summary, null, 2);
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Сводит итоги k6 (*.json) и снимки CPU (*.cpu) в Markdown-таблицу и SVG-график."""
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
raw = Path(sys.argv[1] if len(sys.argv) > 1 else 'evidence/track1/raw')
|
||||
rows = []
|
||||
for f in sorted(raw.glob('*.json')):
|
||||
m = re.match(r'n(\d+)_c([\d.]+)_p(\d+)_r(\d+)', f.stem)
|
||||
if not m or not f.read_text().strip():
|
||||
continue
|
||||
d = json.loads(f.read_text())
|
||||
cpu = {}
|
||||
for line in (f.with_suffix('.cpu').read_text().splitlines() if f.with_suffix('.cpu').exists() else []):
|
||||
name, pct = line.split()
|
||||
role = name.split('-')[2]
|
||||
cpu[role] = cpu.get(role, 0) + float(pct.rstrip('%'))
|
||||
rows.append((f'{m[1]}×{m[2]} CPU, pool {m[3]}', int(m[4]), d, cpu))
|
||||
rows.sort(key=lambda r: (r[0], r[1]))
|
||||
|
||||
print('| Конфигурация API | Offered RPS | Успешные RPS | Ошибки | Dropped | p50 мс | p95 мс | p99 мс | CPU api % | CPU postgres % | CPU lb % |')
|
||||
print('|---|---|---|---|---|---|---|---|---|---|---|')
|
||||
for cfg, rate, d, cpu in rows:
|
||||
l = d['latency_ms']
|
||||
print(f"| {cfg} | {rate} | {d['successful_rps']} | {d['failed']} | {d['dropped_iterations']} | {l['p50']:.1f} | {l['p95']:.1f} | {l['p99']:.1f} | "
|
||||
f"{cpu.get('api', 0):.0f} | {cpu.get('postgres', 0):.0f} | {cpu.get('lb', 0):.0f} |")
|
||||
|
||||
# SVG: успешные RPS от поданной нагрузки, по линии на конфигурацию.
|
||||
W, H, P = 640, 380, 50
|
||||
series = {}
|
||||
for cfg, rate, d, _ in rows:
|
||||
series.setdefault(cfg, []).append((rate, d['successful_rps']))
|
||||
xmax = max(r for _, r, _, _ in rows)
|
||||
ymax = xmax
|
||||
sx = lambda x: P + x / xmax * (W - 2 * P)
|
||||
sy = lambda y: H - P - y / ymax * (H - 2 * P)
|
||||
colors = ['#2a6fdb', '#d9480f', '#2b8a3e', '#862e9c', '#495057']
|
||||
svg = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}" font-family="sans-serif" font-size="12">',
|
||||
'<rect width="100%" height="100%" fill="white"/>',
|
||||
f'<line x1="{P}" y1="{H-P}" x2="{W-P}" y2="{H-P}" stroke="black"/><line x1="{P}" y1="{P}" x2="{P}" y2="{H-P}" stroke="black"/>',
|
||||
f'<line x1="{sx(0)}" y1="{sy(0)}" x2="{sx(xmax)}" y2="{sy(xmax)}" stroke="#aaa" stroke-dasharray="4"/>',
|
||||
f'<text x="{W/2}" y="{H-12}" text-anchor="middle">offered RPS</text>',
|
||||
f'<text x="14" y="{H/2}" transform="rotate(-90 14 {H/2})" text-anchor="middle">successful RPS</text>']
|
||||
for t in range(0, xmax + 1, 400):
|
||||
svg.append(f'<text x="{sx(t)}" y="{H-P+16}" text-anchor="middle">{t}</text><text x="{P-6}" y="{sy(t)+4}" text-anchor="end">{t}</text>')
|
||||
for i, (cfg, pts) in enumerate(series.items()):
|
||||
c = colors[i % len(colors)]
|
||||
svg.append(f'<polyline fill="none" stroke="{c}" stroke-width="2" points="{" ".join(f"{sx(x):.0f},{sy(y):.0f}" for x, y in pts)}"/>')
|
||||
svg.append(f'<text x="{P+10}" y="{P+16*i}" fill="{c}">{cfg}</text>')
|
||||
svg.append('</svg>')
|
||||
(raw.parent / 'throughput.svg').write_text('\n'.join(svg))
|
||||
Reference in New Issue
Block a user