Completed for a grade of four

This commit is contained in:
2026-10-23 16:08:53 +03:00
parent 92c2fdc254
commit af184cabe3
50 changed files with 1297 additions and 92 deletions
+55
View File
@@ -0,0 +1,55 @@
#!/bin/sh
# One replica fault under constant load through the balancer, then its restoration.
# MODE=stop docker stop (SIGTERM: drain, graceful shutdown) MODE=kill docker kill (SIGKILL: crash)
# TARGET=api-1|api-2 RATE=150 req/s DURATION=45 s fault at 10 s, restore at 25 s
# Output: evidence/load/failover-<mode>-<target>/{k6.txt,events.json,haproxy.log,per-second.csv,summary.json}
set -eu
cd "$(dirname "$0")/../.."
MODE=${MODE:-stop}
TARGET=${TARGET:-api-1}
RATE=${RATE:-150}
DURATION=${DURATION:-45}
FAULT_AT=${FAULT_AT:-10}
RESTORE_AT=${RESTORE_AT:-25}
out=evidence/load/failover-$MODE-$TARGET
rm -rf "$out" && mkdir -p "$out"
now() { python3 -c 'import time; print(int(time.time() * 1000))'; }
# Sleeps until <seconds> after the load started, so the schedule does not drift with slow docker commands.
sleep_until() { python3 -c "import time; time.sleep(max(0, $start / 1000 + $1 - time.time()))"; }
container=mtusi-messenger-lab3-$TARGET
target_instance=$(docker inspect -f '{{.Config.Hostname}}' "$container")
since=$(date -u +%Y-%m-%dT%H:%M:%SZ)
K6_CSV_TIME_FORMAT=unix_milli k6 run --quiet --out csv="$out/requests.csv" \
-e RATE="$RATE" -e DURATION="${DURATION}s" scripts/load/mixed.js > "$out/k6.txt" 2>&1 &
k6_pid=$!
# Load starts after k6 setup (users, sessions, chat): wait for the first request of the scenario.
until grep -q ',load,' "$out/requests.csv" 2>/dev/null; do sleep 0.2; done
start=$(now)
sleep_until "$FAULT_AT"
fault=$(now)
if [ "$MODE" = kill ]; then docker kill "$container" >/dev/null; else docker stop --time 9 "$container" >/dev/null; fi
fault_done=$(now)
sleep_until "$RESTORE_AT"
restore_begin=$(now)
docker start "$container" >/dev/null
until [ "$(docker inspect -f '{{.State.Health.Status}}' "$container")" = healthy ]; do sleep 0.2; done
restore_healthy=$(now)
restored_instance=$(docker inspect -f '{{.Config.Hostname}}' "$container")
wait "$k6_pid" || true
docker compose logs --timestamps --no-log-prefix --since "$since" lb 2>/dev/null | grep -E 'Server api/|SH--|5[0-9][0-9] ' > "$out/haproxy.log" || true
cat > "$out/events.json" <<JSON
{"mode": "$MODE", "target": "$TARGET", "target_instance": "$target_instance", "restored_instance": "$restored_instance",
"load_start": $start, "fault": $fault, "fault_done": $fault_done, "restore_begin": $restore_begin, "restore_healthy": $restore_healthy}
JSON
python3 scripts/load/summarize.py "$out" > /dev/null
# Raw per-request data stays out of Git (evidence keeps aggregates only); KEEP_RAW=1 keeps it for analysis.
[ "${KEEP_RAW:-0}" = 1 ] || rm -f "$out/requests.csv"
cat "$out/summary.json"
+67
View File
@@ -0,0 +1,67 @@
// Open-model load through the balancer: RATE requests per second regardless of response time.
// 70 % GET /users/me (session lookup), 30 % POST message with a unique Idempotency-Key.
// Every response adds a `served_by` sample tagged with X-Instance-Id and status, so the summary can show
// which replica answered each second. Tokens live only in this process.
import http from 'k6/http';
import encoding from 'k6/encoding';
import { Counter } from 'k6/metrics';
const BASE = __ENV.BASE_URL || 'http://localhost:8080';
const RATE = Number(__ENV.RATE || 150);
const DURATION = __ENV.DURATION || '40s';
const USERS = 10;
const PASSWORD = 'load-test-password';
const servedBy = new Counter('served_by');
export const options = {
scenarios: {
load: {
executor: 'constant-arrival-rate',
rate: RATE,
timeUnit: '1s',
duration: DURATION,
preAllocatedVUs: 50,
maxVUs: 300,
},
},
summaryTrendStats: ['avg', 'med', 'p(95)', 'p(99)', 'max'],
};
export function setup() {
const json = { headers: { 'Content-Type': 'application/json' } };
const users = [];
for (let i = 0; i < USERS; i++) {
const username = `load_${Date.now().toString(36)}_${i}`;
const user = http.post(`${BASE}/api/v1/users`, JSON.stringify({ username, display_name: 'load', password: PASSWORD }), json).json();
const basic = encoding.b64encode(`${username}:${PASSWORD}`);
const session = http.post(`${BASE}/api/v1/auth/sessions`, null, { headers: { Authorization: `Basic ${basic}` } }).json();
users.push({ id: user.id, token: session.token });
}
const chat = http.post(`${BASE}/api/v1/chats`, JSON.stringify({ title: 'load', member_ids: users.map((u) => u.id) }), {
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${users[0].token}` },
}).json();
return { users, chatId: chat.id };
}
export default function (data) {
const user = data.users[Math.floor(Math.random() * data.users.length)];
const auth = { Authorization: `Bearer ${user.token}` };
let response;
if (Math.random() < 0.7) {
response = http.get(`${BASE}/api/v1/users/me`, { headers: auth, tags: { name: 'me' }, timeout: '5s' });
} else {
response = http.post(
`${BASE}/api/v1/chats/${data.chatId}/messages`,
JSON.stringify({ text: `load ${__VU}-${__ITER}` }),
{
headers: { ...auth, 'Content-Type': 'application/json', 'Idempotency-Key': `load-${__VU}-${__ITER}-${Date.now()}` },
tags: { name: 'send' },
timeout: '5s',
},
);
}
servedBy.add(1, { instance: response.headers['X-Instance-Id'] || 'none', code: String(response.status) });
}
+34
View File
@@ -0,0 +1,34 @@
#!/bin/sh
# scripts/rolling-update.sh while k6 keeps RATE req/s through the balancer.
# Output: evidence/load/rolling-update/{k6.txt,rolling.log,events.json,per-second.csv,summary.json}
set -eu
cd "$(dirname "$0")/../.."
RATE=${RATE:-150}
DURATION=${DURATION:-70}
out=evidence/load/rolling-update
rm -rf "$out" && mkdir -p "$out"
now() { python3 -c 'import time; print(int(time.time() * 1000))'; }
# Build outside the measured window: compiling would compete with the API for CPU.
docker compose build --quiet api
{ echo "# before"; docker compose ps api --format '{{.Name}} {{.ID}} {{.Image}}'; } > "$out/rolling.log"
K6_CSV_TIME_FORMAT=unix_milli k6 run --quiet --out csv="$out/requests.csv" \
-e RATE="$RATE" -e DURATION="${DURATION}s" scripts/load/mixed.js > "$out/k6.txt" 2>&1 &
k6_pid=$!
until grep -q ',load,' "$out/requests.csv" 2>/dev/null; do sleep 0.2; done
start=$(now)
sleep 10
begin=$(now)
scripts/rolling-update.sh >> "$out/rolling.log" 2>&1
end=$(now)
wait "$k6_pid" || true
{ echo "# after"; docker compose ps api --format '{{.Name}} {{.ID}} {{.Image}}'; } >> "$out/rolling.log"
echo "{\"load_start\": $start, \"rolling_begin\": $begin, \"rolling_end\": $end}" > "$out/events.json"
python3 scripts/load/summarize.py "$out" > /dev/null
# Raw per-request data stays out of Git (evidence keeps aggregates only); KEEP_RAW=1 keeps it for analysis.
[ "${KEEP_RAW:-0}" = 1 ] || rm -f "$out/requests.csv"
cat "$out/rolling.log" "$out/summary.json"
+110
View File
@@ -0,0 +1,110 @@
#!/usr/bin/env python3
"""Per-second view of one k6 run (requests.csv) plus the events of the experiment (events.json).
Writes per-second.csv and summary.json next to the input. An error is any response that is not 2xx
(including k6 status 0: connection reset or timeout). Times are seconds from the start of the load.
"""
import csv
import json
import math
import sys
from collections import Counter, defaultdict
from pathlib import Path
from urllib.parse import parse_qsl
run = Path(sys.argv[1])
events = json.loads((run / 'events.json').read_text()) if (run / 'events.json').exists() else {}
durations = [] # (t_ms, duration_ms, status)
served = [] # (t_ms, instance, status)
with open(run / 'requests.csv') as f:
for row in csv.DictReader(f):
if row['metric_name'] == 'http_req_duration' and row['scenario'] == 'load':
durations.append((int(row['timestamp']), float(row['metric_value']), int(row['status'] or 0)))
elif row['metric_name'] == 'served_by':
tags = dict(parse_qsl(row['extra_tags']))
served.append((int(row['timestamp']), tags.get('instance', 'none'), int(tags.get('code', 0))))
t0 = min(t for t, _, _ in durations)
rel = lambda ms: (ms - t0) / 1000
def percentile(values, p):
if not values:
return None
values = sorted(values)
return values[min(len(values) - 1, math.ceil(p / 100 * len(values)) - 1)]
per_second = defaultdict(lambda: {'ok': 0, 'errors': 0, 'durations': [], 'instances': Counter()})
for t, d, status in durations:
second = per_second[math.floor(rel(t))]
second['durations'].append(d)
if 200 <= status < 300:
second['ok'] += 1
else:
second['errors'] += 1
for t, instance, status in served:
if 200 <= status < 300:
per_second[math.floor(rel(t))]['instances'][instance] += 1
instances = sorted({i for s in per_second.values() for i in s['instances']})
with open(run / 'per-second.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['second', 'ok', 'errors', 'p99_ms', 'max_ms'] + instances)
for second in sorted(per_second):
s = per_second[second]
writer.writerow([second, s['ok'], s['errors'], round(percentile(s['durations'], 99), 1), round(max(s['durations']), 1)]
+ [s['instances'].get(i, 0) for i in instances])
errors = sorted(rel(t) for t, _, status in durations if not 200 <= status < 300)
seconds = max(per_second) + 1
summary = {
'requests': len(durations),
'ok': len(durations) - len(errors),
'errors': len(errors),
'error_codes': dict(Counter(str(status) for _, _, status in durations if not 200 <= status < 300)),
'ok_rps': round((len(durations) - len(errors)) / seconds, 1),
'p50_ms': round(percentile([d for _, d, _ in durations], 50), 1),
'p95_ms': round(percentile([d for _, d, _ in durations], 95), 1),
'p99_ms': round(percentile([d for _, d, _ in durations], 99), 1),
'max_ms': round(max(d for _, d, _ in durations), 1),
'requests_per_instance': dict(Counter(i for _, i, status in served if 200 <= status < 300)),
}
for name, value in events.items():
if isinstance(value, (int, float)):
summary[f'event_{name}_s'] = round(rel(value), 2)
if 'fault' in events:
fault = rel(events['fault'])
after = [e - fault for e in errors if e >= fault - 0.5]
summary['errors_after_fault'] = len(after)
summary['last_error_after_fault_s'] = round(max(after), 2) if after else None
target = events.get('target_instance')
end = rel(events['restore_begin']) if 'restore_begin' in events else float('inf')
last = [rel(t) - fault for t, i, status in served if i == target and fault <= rel(t) < end]
summary['target_last_response_after_fault_s'] = round(max(last), 2) if last else None
if 'restore_begin' in events and events.get('restored_instance'):
begin = rel(events['restore_begin'])
first = [rel(t) - begin for t, i, status in served
if i == events['restored_instance'] and 200 <= status < 300 and rel(t) >= begin]
summary['restored_replica_first_response_after_start_s'] = round(min(first), 2) if first else None
# HAProxy state changes (docker log timestamps): when the balancer took the target out and put it back.
log = run / 'haproxy.log'
if log.exists() and 'fault' in events:
from datetime import datetime
def at(line):
stamp = line.split()[0].rstrip('Z')
whole, _, fraction = stamp.partition('.')
return datetime.fromisoformat(whole + '+00:00').timestamp() * 1000 + float('0.' + (fraction or '0')) * 1000
changes = [(at(line), line) for line in log.read_text().splitlines() if 'Server api/' in line and '[WARNING]' not in line]
down = [t for t, line in changes if ('is DOWN' in line or 'going DOWN' in line) and t >= events['fault']]
summary['lb_marked_down_after_fault_s'] = round((min(down) - events['fault']) / 1000, 2) if down else None
if 'restore_begin' in events:
up = [t for t, line in changes if 'is UP, reason' in line and t >= events['restore_begin']]
summary['lb_marked_up_after_start_s'] = round((min(up) - events['restore_begin']) / 1000, 2) if up else None
(run / 'summary.json').write_text(json.dumps(summary, indent=2, ensure_ascii=False))
print(json.dumps(summary, indent=2, ensure_ascii=False))
+40
View File
@@ -0,0 +1,40 @@
#!/usr/bin/env bash
# Replaces the API replicas one by one with a freshly built image while the balancer keeps serving.
# 1. build the new image, 2. apply migrations once (they must be compatible with the running version),
# 3. for every old replica: start one new replica, wait until HAProxy has it UP, then stop (drain) and remove the old.
# The number of serving replicas never drops below the configured count.
set -euo pipefail
cd "$(dirname "$0")/.."
build_id=${BUILD_ID:-$(git rev-parse --short HEAD)-$(date +%s)}
log() { echo "$(date -u +%H:%M:%S) $*"; }
up_in_lb() {
docker compose exec -T lb wget -qO- 'http://127.0.0.1:8404/stats;csv' | awk -F, '$1 == "api" && $2 != "BACKEND" && $18 == "UP"' | wc -l
}
log "build image (BUILD_ID=$build_id)"
docker compose build --quiet --build-arg BUILD_ID="$build_id" api
log "migrate"
docker compose run --rm --no-deps migrate > /dev/null
old=$(docker compose ps -q api)
count=$(echo "$old" | wc -l | tr -d ' ')
for container in $old; do
before=$(docker compose ps -q api | sort)
docker compose up -d --no-deps --no-recreate --scale api=$((count + 1)) api 2> /dev/null
new=$(comm -13 <(echo "$before") <(docker compose ps -q api | sort))
log "started $(docker inspect -f '{{.Name}}' "$new") ($(echo "$new" | cut -c1-12))"
until [ "$(docker inspect -f '{{.State.Health.Status}}' "$new")" = healthy ]; do sleep 0.5; done
until [ "$(up_in_lb)" -ge $((count + 1)) ]; do sleep 0.5; done
log "new replica is UP in HAProxy"
docker stop --time 9 "$container" > /dev/null
docker rm "$container" > /dev/null
log "stopped and removed $(echo "$container" | cut -c1-12)"
done
log "done: $(docker compose ps -q api | while read -r c; do docker inspect -f '{{.Name}} {{index .Config.Labels "org.opencontainers.image.revision"}}' "$c"; done | tr '\n' ' ')"
+1 -1
View File
@@ -19,4 +19,4 @@ if [ -z "$container" ] || [ "$(printf '%s\n' "$container" | wc -l)" -ne 1 ]; the
exit 1
fi
docker stop --time 8 "$container" >/dev/null
docker stop --time 9 "$container" >/dev/null