forked from mtusi2026/mtusi2026lab6
- api и worker отдают traces, metrics и logs по OTLP в Collector (memory_limiter, redaction, batch, ограниченная очередь и retry); хранилища: Prometheus (OTLP receiver), Loki, Tempo; Grafana с provisioning datasources и dashboard «Messenger lab6» - W3C trace context через outbox и RabbitMQ: producer/consumer spans связывают upload, публикации и попытки worker в одном trace - SLO доступности API (SLI на HAProxy) и времени до ready, multiwindow burn-rate alerts, ApiHighErrorRate, JobQueueLagGrowing, DbPoolSaturated, TelemetryExportFailing; unit-тесты promtool, runbooks - кампания трека 2 (k6, 6 отказов по расписанию), разбор и графики; проверки сигналов и истории telemetry, evidence и REPORT.md
112 lines
5.5 KiB
JavaScript
112 lines
5.5 KiB
JavaScript
// Нагрузка lab6, open model (constant-arrival-rate, без coordinated omission): каждая итерация — одна операция.
|
||
// UPLOAD_SHARE — загрузка PNG (202, дальше pipeline worker-а), WRITE_SHARE — сообщение с новым Idempotency-Key,
|
||
// остальное — чтение страницы истории (limit 20). Запуск: scripts/load.sh (k6 в docker внутри сети frontend стенда).
|
||
// Основа — research/k6/messenger.js из lab3 (+ загрузки, разбивка ответов по статусу).
|
||
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 || 20);
|
||
const WRITE_SHARE = Number(__ENV.WRITE_SHARE || 0.3);
|
||
const UPLOAD_SHARE = Number(__ENV.UPLOAD_SHARE || 0.05);
|
||
const PAIRS = Number(__ENV.PAIRS || 5);
|
||
const DURATION = __ENV.DURATION || '60s';
|
||
const PNG = open('/fixtures/sample.png', 'b');
|
||
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(20, RATE)),
|
||
maxVUs: Number(__ENV.MAX_VUS || 500),
|
||
gracefulStop: '15s',
|
||
},
|
||
},
|
||
setupTimeout: '120s',
|
||
// Пороги нужны только для подметрик: трафик setup() не попадает в итоговые числа.
|
||
thresholds: {
|
||
'http_reqs{scenario:load}': ['count>=0'],
|
||
'http_req_duration{scenario:load}': ['max>=0'],
|
||
'http_req_duration{op:read}': ['max>=0'],
|
||
'http_req_duration{op:write}': ['max>=0'],
|
||
'http_req_duration{op:upload}': ['max>=0'],
|
||
'failed_requests{op:read}': ['count>=0'],
|
||
'failed_requests{op:write}': ['count>=0'],
|
||
'failed_requests{op:upload}': ['count>=0'],
|
||
},
|
||
summaryTrendStats: ['avg', 'p(50)', 'p(95)', 'p(99)', 'max'],
|
||
};
|
||
|
||
const json = { 'Content-Type': 'application/json' };
|
||
|
||
function user(tag) {
|
||
const username = `k6_${tag}_${Math.random().toString(36).slice(2, 12)}`;
|
||
const password = 'Load-' + Math.random().toString(36).slice(2) + 'xx';
|
||
const created = http.post(`${BASE}/api/v1/users`, JSON.stringify({ username, display_name: 'load ' + tag, password }), { headers: json });
|
||
if (created.status !== 201) throw new Error('register ' + created.status);
|
||
const s = http.post(`${BASE}/api/v1/auth/sessions`, null,
|
||
{ headers: { Authorization: 'Basic ' + encoding.b64encode(`${username}:${password}`) } });
|
||
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: 'load ' + i, member_ids: [a.id, b.id] }),
|
||
{ headers: { ...json, Authorization: 'Bearer ' + a.token } });
|
||
if (chat.status !== 201) throw new Error('chat ' + chat.status);
|
||
actors.push({ token: a.token, chatId: chat.json('id') }, { token: b.token, chatId: chat.json('id') });
|
||
}
|
||
return { actors };
|
||
}
|
||
|
||
export default function (data) {
|
||
const actor = data.actors[Math.floor(Math.random() * data.actors.length)];
|
||
const auth = { Authorization: 'Bearer ' + actor.token };
|
||
const chat = `${BASE}/api/v1/chats/${actor.chatId}`;
|
||
const r = Math.random();
|
||
let op, res, expected;
|
||
if (r < UPLOAD_SHARE) {
|
||
[op, expected] = ['upload', 202];
|
||
res = http.post(`${chat}/attachments?filename=load.png`, PNG,
|
||
{ headers: { ...auth, 'Content-Type': 'image/png' }, timeout: '15s', tags: { op } });
|
||
} else if (r < UPLOAD_SHARE + WRITE_SHARE) {
|
||
[op, expected] = ['write', 201];
|
||
res = http.post(`${chat}/messages`, JSON.stringify({ text: `load ${__VU}-${__ITER}` }),
|
||
{ headers: { ...json, ...auth, 'Idempotency-Key': `k6-${__VU}-${__ITER}-${Date.now()}` }, timeout: '15s', tags: { op } });
|
||
} else {
|
||
[op, expected] = ['read', 200];
|
||
res = http.get(`${chat}/messages?limit=20`, { headers: auth, timeout: '15s', tags: { op } });
|
||
}
|
||
if (res.status !== expected) failed.add(1, { op, status: String(res.status) });
|
||
}
|
||
|
||
export function handleSummary(data) {
|
||
const m = data.metrics;
|
||
const pick = (name) => {
|
||
const v = m[name] && m[name].values;
|
||
return v ? { avg: v.avg, p50: v['p(50)'], p95: v['p(95)'], p99: v['p(99)'], max: v.max } : null;
|
||
};
|
||
const count = (name) => (m[name] ? m[name].values.count : 0);
|
||
const reqs = count('http_reqs{scenario:load}');
|
||
const fails = { read: count('failed_requests{op:read}'), write: count('failed_requests{op:write}'), upload: count('failed_requests{op:upload}') };
|
||
const total = fails.read + fails.write + fails.upload;
|
||
const summary = {
|
||
offered_rps: RATE, write_share: WRITE_SHARE, upload_share: UPLOAD_SHARE, duration: DURATION,
|
||
requests: reqs, failed: total, failed_by_op: fails, error_ratio: reqs ? Number((total / reqs).toFixed(6)) : null,
|
||
dropped_iterations: m.dropped_iterations ? m.dropped_iterations.values.count : 0,
|
||
latency_ms: pick('http_req_duration{scenario:load}'),
|
||
read_ms: pick('http_req_duration{op:read}'), write_ms: pick('http_req_duration{op:write}'), upload_ms: pick('http_req_duration{op:upload}'),
|
||
max_vus: m.vus_max ? m.vus_max.values.max : null,
|
||
};
|
||
return { stdout: JSON.stringify(summary) + '\n' };
|
||
}
|