This commit is contained in:
Vladislav Kunetskiy
2026-10-16 16:39:00 +03:00
parent 4e84354642
commit 1ed57cd49f
98 changed files with 6574 additions and 449 deletions
+177
View File
@@ -0,0 +1,177 @@
#!/bin/sh
# Проверка критерия «LB исключает неготовую реплику» (lab3).
#
# Рядом с рабочими репликами поднимается третья с тем же сетевым alias, но её
# доступ к БД идёт через временный TCP-прокси. Пока прокси жив, реплика готова и
# получает трафик через LB. После остановки прокси реплика остаётся доступной по
# сети (процесс жив, порт открыт), но /health/ready отвечает 503 — и балансировщик
# обязан убрать её из ротации и не отправлять ей ни одного запроса.
#
# scripts/lb_readiness_check.sh # стенд поднят (make up)
# OUT=evidence/lb-readiness.txt scripts/lb_readiness_check.sh
set -eu
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$ROOT_DIR"
OUT=${OUT:-evidence/lb-readiness.txt}
PROJECT=${COMPOSE_PROJECT_NAME:-mtusi-messenger-lab3}
NET=${PROJECT}_default
IMAGE=${IMAGE:-mtusi-messenger:lab3}
STATS=${STATS:-http://127.0.0.1:8404/stats;csv}
BASE_URL=${BASE_URL:-http://localhost:8080}
CANDIDATE=lb-readiness-candidate
PROXY=lb-readiness-pgproxy
REQUESTS=${REQUESTS:-40}
NO_PROXY_ENV="env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy"
NO_PROXY_ENV="$NO_PROXY_ENV NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1"
cleanup() {
docker rm -f "$CANDIDATE" "$PROXY" >/dev/null 2>&1 || true
}
trap cleanup EXIT INT TERM
cleanup
instances() {
tries=${1:-$REQUESTS}
i=0
while [ "$i" -lt "$tries" ]; do
curl -fsS --noproxy '*' -D - -o /dev/null "$BASE_URL/health/live" 2>/dev/null \
| awk 'tolower($1) == "x-instance-id:" { print $2 }'
i=$((i + 1))
done | sort | uniq -c
}
stats() {
curl -s --noproxy '*' "$STATS" | awk -F, '$1 ~ /^api/ { printf "%s=%s ", $2, $18 }'
}
readiness() {
docker exec "$CANDIDATE" wget -qO- -S -T 3 http://127.0.0.1:8080/health/ready 2>&1 \
| awk '/^ HTTP\//{print $2; exit}'
}
wait_readiness() {
want=$1
attempt=0
while [ "$attempt" -lt 30 ]; do
[ "$(readiness)" = "$want" ] && return 0
attempt=$((attempt + 1))
sleep 1
done
return 1
}
up_slots() {
curl -s --noproxy '*' "$STATS" | awk -F, '$1 ~ /^api/ && $18 == "UP" && $2 != "BACKEND" { printf "%s ", $2 }'
}
wait_new_up_slot() {
before=$1
attempt=0
while [ "$attempt" -lt 30 ]; do
for slot in $(up_slots); do
case " $before " in
*" $slot "*) ;;
*) echo "$slot"; return 0 ;;
esac
done
attempt=$((attempt + 1))
sleep 1
done
return 1
}
wait_slot_status() {
slot=$1
want=$2
attempt=0
while [ "$attempt" -lt 30 ]; do
status=$(curl -s --noproxy '*' "$STATS" | awk -F, -v s="$slot" '$1 ~ /^api/ && $2 == s { print $18; exit }')
[ "$status" = "$want" ] && return 0
attempt=$((attempt + 1))
sleep 1
done
return 1
}
{
echo "# LB excludes a not-ready but reachable replica (lab3)"
echo "# generated: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo "# lb: $(docker inspect -f '{{.Config.Image}}' "$(docker ps -q --filter label=com.docker.compose.service=lb)" 2>/dev/null)"
echo
echo "## 1. baseline: requests through LB by replica"
instances
baseline_slots=$(up_slots)
echo " stats: $(stats)"
echo
echo "## 2. start a temporary TCP proxy to postgres and a candidate replica behind the same network alias"
docker run -d --name "$PROXY" --network "$NET" alpine/socat \
tcp-listen:5432,fork,reuseaddr tcp-connect:postgres:5432 >/dev/null
docker run -d --name "$CANDIDATE" --network "$NET" --network-alias api-replica \
-e APP_CONFIG=/etc/messenger/dev/config.yaml \
-e POSTGRES_HOST="$PROXY" -e POSTGRES_PORT=5432 \
-e POSTGRES_DATABASE=messenger -e POSTGRES_USER=messenger \
-e POSTGRES_PASSWORD=messenger -e POSTGRES_SSL_MODE=disable \
-e REDIS_ENABLED=true -e REDIS_HOST=redis -e CACHE_ENABLED=true \
"$IMAGE" >/dev/null
if ! wait_readiness 200; then
echo " candidate did not become ready" >&2
exit 1
fi
echo " instance-id: $(docker inspect -f '{{.Config.Hostname}}' "$CANDIDATE"), readiness while its database is reachable: 200"
slot=$(wait_new_up_slot "$baseline_slots" || true)
if [ -z "$slot" ]; then
echo " candidate did not appear UP in the load balancer" >&2
exit 1
fi
echo " load balancer slot for the candidate: $slot, stats: $(stats)"
echo
echo "## 3. cut the candidate's database access (stop only the TCP proxy)"
docker stop "$PROXY" >/dev/null
if ! wait_readiness 503; then
echo " candidate readiness did not become 503" >&2
exit 1
fi
echo " candidate is still running: $(docker inspect -f '{{.State.Status}}' "$CANDIDATE"), readiness: 503"
echo " waiting for the load balancer to mark $slot DOWN"
if ! wait_slot_status "$slot" DOWN; then
echo " WARNING: $slot is still not DOWN" >&2
fi
echo " stats after failure: $(stats)"
echo
echo "## 4. ${REQUESTS} requests through LB while the candidate is not ready"
instances
echo " (the candidate must not appear above)"
echo
echo "## 5. business writes through LB during the exclusion"
# shellcheck disable=SC2086
$NO_PROXY_ENV python3 tests/load.py --base-url "$BASE_URL" --duration 5 --concurrency 2 \
| grep -E '"successful_rps"|"failed_requests"|"error_ratio"'
echo
echo "## 6. cleanup"
cleanup
sleep 5
echo " stats after cleanup: $(stats)"
} > "$OUT" 2>&1
cat "$OUT"
printf 'lb_readiness_check.sh: evidence in %s\n' "$OUT"
Regular → Executable
+44 -6
View File
@@ -1,11 +1,49 @@
#!/bin/sh
set -eu
# Restart hook: bounce API replicas and every state store of the lab3 stand.
#
# scripts/restart.sh
#
# Persistent volumes are kept: no `down -v`, no flush, no re-seed. The one-shot
# `migrate` service is not re-run (schema stays as it is, data and sessions
# survive). The script exits 0 only after /health/ready answers through the LB.
# No credentials are printed.
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
COMPOSE_BIN=${COMPOSE_BIN:-docker-compose}
cd "$ROOT_DIR"
"$COMPOSE_BIN" -f docker-compose.local.yaml restart postgres redis
"$COMPOSE_BIN" -f docker-compose.local.yaml up -d --wait postgres redis
"$COMPOSE_BIN" -f docker-compose.local.yaml up -d --force-recreate api
COMPOSE_BIN=${COMPOSE_BIN:-docker compose}
PORT=${SERVER_PORT:-8080}
# shellcheck disable=SC2086
compose() {
# shellcheck disable=SC2086
$COMPOSE_BIN --env-file .env -f compose.yaml "$@"
}
# 1. State stores: restart the running ones, then make sure they are healthy.
# Volumes are attached as before, nothing is dropped or re-seeded.
compose up -d --wait postgres redis
compose restart postgres redis
compose up -d --wait postgres redis
# 2. API replicas: restart in place (same containers, same addresses) and bring
# back any replica that was stopped by the fault-injection hook.
compose restart api
compose up -d --wait --no-deps api
# 3. Load balancer keeps its upstream; re-resolve in case addresses changed.
compose restart lb
# 4. Wait for readiness through the public entry point.
attempt=0
while [ "$attempt" -lt 60 ]; do
if curl -fsS --noproxy '*' -o /dev/null "http://127.0.0.1:${PORT}/health/ready"; then
printf 'restart.sh: stack restarted, http://127.0.0.1:%s/health/ready is ready\n' "$PORT"
exit 0
fi
attempt=$((attempt + 1))
sleep 1
done
printf 'restart.sh: /health/ready did not become ready through the LB\n' >&2
exit 1
+141
View File
@@ -0,0 +1,141 @@
#!/bin/sh
# Rolling update of the API replicas under load (lab3, level 4).
#
# The image is rebuilt, then every replica is deleted and recreated one at a
# time. Between the steps the script waits until the replacement is healthy and
# until the load balancer really serves through the declared number of replicas,
# so two replicas are never replaced at once. Nginx resolves the shared network
# alias `api-replica`, therefore recreated containers may get new names and IPs.
#
# scripts/rolling_update.sh # requires a running stand (make up)
# DURATION=45 CONCURRENCY=8 scripts/rolling_update.sh
set -eu
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$ROOT_DIR"
COMPOSE_BIN=${COMPOSE_BIN:-docker compose}
PYTHON=${PYTHON:-python3}
DURATION=${DURATION:-60}
CONCURRENCY=${CONCURRENCY:-8}
BASE_URL=${BASE_URL:-http://localhost:8080}
OUT=${OUT:-evidence/rolling-update}
# Профиль без насыщения: 2 реплики по 1 CPU. На насыщающем профиле (0.5 CPU на
# реплику) проба готовности сама подходит к таймауту, и «unhealthy» перестаёт
# означать «сломан».
API_REPLICAS=${API_REPLICAS:-2}
API_CPU_LIMIT=${API_CPU_LIMIT:-1.0}
API_MEM_LIMIT=${API_MEM_LIMIT:-512M}
export API_REPLICAS API_CPU_LIMIT API_MEM_LIMIT
NO_PROXY_ENV="env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy"
NO_PROXY_ENV="$NO_PROXY_ENV NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1"
mkdir -p "$OUT"
rm -f "$OUT/load.json" "$OUT/load.txt"
compose() {
# shellcheck disable=SC2086
$COMPOSE_BIN --env-file .env -f compose.yaml "$@"
}
api_containers() {
docker ps -q --filter 'label=com.docker.compose.service=api'
}
healthy_replicas() {
docker ps -q --filter 'label=com.docker.compose.service=api' --filter health=healthy | wc -l | tr -d ' '
}
lb_container() {
docker ps -q --filter 'label=com.docker.compose.service=lb' | head -n 1
}
observe_instances() {
tries=${1:-10}
attempt=0
while [ "$attempt" -lt "$tries" ]; do
curl -fsS --noproxy '*' -D - -o /dev/null "$BASE_URL/health/live" 2>/dev/null \
| awk 'tolower($1) == "x-instance-id:" { print $2 }'
attempt=$((attempt + 1))
done | sort -u | wc -l | tr -d ' '
}
wait_for() {
# wait_for <expected replicas>: healthy containers and LB-visible replicas
want=$1
attempt=0
while [ "$attempt" -lt 60 ]; do
if [ "$(healthy_replicas)" -ge "$want" ] && [ "$(observe_instances 10)" -ge "$want" ]; then
return 0
fi
attempt=$((attempt + 1))
sleep 1
done
return 1
}
{
echo "# Rolling update under load"
echo "# generated: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo "# load: tests/load.py duration=${DURATION}s concurrency=${CONCURRENCY} (closed loop)"
echo "# steps: delete one replica, recreate it from the freshly built image, wait for health + LB"
echo
compose build api
compose up -d --no-deps api
replicas=$(api_containers | wc -l | tr -d ' ')
if ! wait_for "$replicas"; then
echo "stand is not ready on the declared profile" >&2
exit 1
fi
echo "replicas before: ${replicas}; instances seen through LB: $(observe_instances 20)"
lb_5xx_before=$(docker logs "$(lb_container)" 2>&1 | grep -c '" 50[0-9] ' || true)
# Load keeps writing while replicas are replaced one by one. The tolerant
# generator counts transitional errors instead of failing on them.
# shellcheck disable=SC2086
$NO_PROXY_ENV $PYTHON student-tests/rolling_update_load.py --base-url "$BASE_URL" \
--duration "$DURATION" --concurrency "$CONCURRENCY" \
--output "$OUT/load.json" > "$OUT/load.txt" 2>&1 &
load_pid=$!
step=0
for container in $(api_containers); do
step=$((step + 1))
instance=$(docker inspect --format '{{.Config.Hostname}}' "$container")
started=$(date -u +%Y-%m-%dT%H:%M:%SZ)
docker rm -f "$container" >/dev/null
compose up -d --no-deps api >/dev/null
if ! wait_for "$replicas"; then
echo " step ${step}: replacement of ${instance} did not become ready" >&2
exit 1
fi
printf ' step %s: removed %s at %s, %s healthy replicas served again at %s\n' \
"$step" "$instance" "$started" "$(healthy_replicas)" "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
done
wait "$load_pid" || true
lb_5xx_after=$(docker logs "$(lb_container)" 2>&1 | grep -c '" 50[0-9] ' || true)
echo
echo "load summary (tolerant generator):"
cat "$OUT/load.txt"
echo
echo "LB responses with 5xx during the update: $((lb_5xx_after - lb_5xx_before))"
echo
echo "API containers after the update:"
docker ps --format '{{.Names}} {{.Status}}' --filter 'label=com.docker.compose.service=api'
} > "$OUT/rolling-update.txt" 2>&1
cat "$OUT/rolling-update.txt"
printf 'rolling_update.sh: evidence in %s\n' "$OUT"
+72
View File
@@ -0,0 +1,72 @@
#!/bin/sh
set -eu
# Fault-injection hook: stop exactly ONE api replica of the lab3 stand.
#
# TARGET_INSTANCE_ID=<hostname|container name|short id> scripts/stop-one.sh
#
# The task value is the instance alias the API reports in X-Instance-Id, i.e.
# the container hostname (docker's default = short container id). Container
# names of the api service are matched too. The container is only stopped
# (docker stop); databases, the load balancer and volumes are left untouched,
# and the replica stays down until it is started again explicitly, e.g.
# docker compose --env-file .env up -d --no-deps api
# No credentials are printed.
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
PROJECT=${COMPOSE_PROJECT_NAME:-mtusi-messenger-lab3}
candidates=$(docker ps -q \
--filter "label=com.docker.compose.project=${PROJECT}" \
--filter "label=com.docker.compose.service=api")
if [ -z "$candidates" ]; then
printf 'stop-one.sh: no api containers of project %s are running\n' "$PROJECT" >&2
exit 1
fi
# Matches the requested alias against every reasonable identifier of a replica:
# container hostname (= X-Instance-Id), full/short container id, full container
# name (mtusi-messenger-lab3-api-1) and the service-local suffix (api-1).
match_replica() {
target=$1
full_id=$2
short_id=$3
name=$4
hostname=$5
suffix=${name#${PROJECT}-}
[ "$target" = "$hostname" ] && return 0
[ "$target" = "$full_id" ] && return 0
[ "$target" = "$short_id" ] && return 0
[ "$target" = "$name" ] && return 0
[ "$target" = "$suffix" ] && return 0
return 1
}
matched=""
matched_names=""
for id in $candidates; do
info=$(docker inspect --format '{{.Id}} {{.Name}} {{.Config.Hostname}}' "$id")
full_id=$(printf '%s' "$info" | cut -d' ' -f1)
name=$(printf '%s' "$info" | cut -d' ' -f2 | sed 's|^/||')
hostname=$(printf '%s' "$info" | cut -d' ' -f3)
short_id=$(printf '%s' "$full_id" | cut -c1-12)
if match_replica "$TARGET_INSTANCE_ID" "$full_id" "$short_id" "$name" "$hostname"; then
matched="$matched $id"
matched_names="$matched_names $name"
fi
done
if [ -z "$matched" ]; then
printf 'stop-one.sh: no api replica matches TARGET_INSTANCE_ID=%s\n' "$TARGET_INSTANCE_ID" >&2
exit 1
fi
# Shut down cleanly (SIGTERM) but never hang the caller for long.
for id in $matched; do
docker stop --time 5 "$id" >/dev/null
done
printf 'stop-one.sh: stopped api replica(s):%s\n' "$matched_names"
exit 0
-267
View File
@@ -1,267 +0,0 @@
import argparse
import concurrent.futures
import json
import os
from pathlib import Path
import signal
import socket
import subprocess
import tempfile
import threading
import time
import urllib.error
import urllib.request
import uuid
ROOT = Path(__file__).resolve().parents[1]
FAST_PATH = """\tif len(history) == 0 || compareKeyset(
\t\thistory[len(history)-1].CreatedAt,
\t\thistory[len(history)-1].ID,
\t\tmessage.CreatedAt,
\t\tmessage.ID,
\t) < 0 {
\t\ts.messagesByChat[message.ChatID] = append(history, message)
\t\treturn message, nil
\t}
"""
def request(opener, base, method, path, body=None, user=None):
data = json.dumps(body, ensure_ascii=False).encode() if body is not None else None
headers = {}
if data is not None:
headers["Content-Type"] = "application/json"
if user is not None:
headers["X-User-Id"] = user
req = urllib.request.Request(base + path, data=data, headers=headers, method=method)
with opener.open(req, timeout=10) as response:
return json.loads(response.read())
def available_port():
with socket.socket() as listener:
listener.bind(("127.0.0.1", 0))
return listener.getsockname()[1]
def descendants(root_pid):
result = subprocess.run(
["ps", "-axo", "pid=,ppid=,rss=,command="],
capture_output=True,
text=True,
check=True,
)
entries = []
for line in result.stdout.splitlines():
fields = line.strip().split(None, 3)
if len(fields) == 4:
try:
entries.append((int(fields[0]), int(fields[1]), int(fields[2]), fields[3]))
except ValueError:
continue
children = {root_pid}
while True:
discovered = children | {pid for pid, ppid, _, _ in entries if ppid in children}
if discovered == children:
break
children = discovered
return [entry for entry in entries if entry[0] in children and entry[0] != root_pid]
def server_rss_kib(go_run_pid):
servers = [rss for _, _, rss, command in descendants(go_run_pid) if command.rstrip().endswith("/messenger")]
if not servers:
raise RuntimeError("go run server process was not found")
return max(servers)
def wait_ready(process, opener, base):
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
if process.poll() is not None:
raise RuntimeError(f"go run exited with code {process.returncode}")
try:
request(opener, base, "GET", "/health/live")
server_rss_kib(process.pid)
return
except (OSError, RuntimeError):
time.sleep(0.1)
raise RuntimeError("go run server did not become ready")
def percentile(latencies, fraction):
ordered = sorted(latencies)
index = max(0, min(len(ordered) - 1, (len(ordered) * int(fraction * 100) + 99) // 100 - 1))
return round(ordered[index] * 1000, 3)
def setup(opener, base, history):
users = []
for _ in range(10):
user = request(opener, base, "POST", "/api/v1/users", {
"username": "b" + uuid.uuid4().hex[:20],
"display_name": "Benchmark",
})
users.append(user)
chat = request(opener, base, "POST", "/api/v1/chats", {
"title": "Benchmark",
"member_ids": [user["id"] for user in users],
}, users[0]["id"])
for index in range(history):
request(opener, base, "POST", f"/api/v1/chats/{chat['id']}/messages", {
"text": f"history-{index}",
}, users[index % len(users)]["id"])
return chat, users
def launch(mode, port, overlay):
command = ["go", "run"]
if mode == "baseline":
command.extend(["-overlay", str(overlay)])
command.append("./cmd/messenger")
process = subprocess.Popen(
command,
cwd=ROOT,
env={**os.environ, "APP_HOST": "127.0.0.1", "APP_PORT": str(port)},
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
start_new_session=True,
)
return process, command
def run_case(mode, history, concurrency, requests, overlay):
port = available_port()
base = f"http://127.0.0.1:{port}"
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
process, command = launch(mode, port, overlay)
try:
wait_ready(process, opener, base)
chat, users = setup(opener, base, history)
rss = []
stop_sampling = threading.Event()
sampling_errors = []
def sample():
while not stop_sampling.is_set():
try:
rss.append(server_rss_kib(process.pid))
except RuntimeError as exc:
sampling_errors.append(str(exc))
stop_sampling.wait(0.1)
sampler = threading.Thread(target=sample)
sampler.start()
warmup = min(100, max(10, requests // 100))
for index in range(warmup):
request(opener, base, "POST", f"/api/v1/chats/{chat['id']}/messages", {
"text": f"warmup-{index}",
}, users[index % len(users)]["id"])
started = time.monotonic()
def worker(worker_id):
latencies = []
failures = 0
worker_requests = requests // concurrency + (1 if worker_id < requests % concurrency else 0)
for index in range(worker_requests):
request_started = time.perf_counter()
try:
request(opener, base, "POST", f"/api/v1/chats/{chat['id']}/messages", {
"text": f"load-{worker_id}-{index}",
}, users[worker_id % len(users)]["id"])
latencies.append(time.perf_counter() - request_started)
except (OSError, ValueError, urllib.error.HTTPError):
failures += 1
index += 1
return latencies, failures
try:
with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as pool:
results = list(pool.map(worker, range(concurrency)))
finally:
elapsed = time.monotonic() - started
stop_sampling.set()
sampler.join()
latencies = [value for values, _ in results for value in values]
failures = sum(value for _, value in results)
if not latencies or not rss or sampling_errors:
raise RuntimeError(f"invalid sample: successes={len(latencies)} rss={len(rss)} errors={sampling_errors}")
return {
"history": history,
"concurrency": concurrency,
"duration_seconds": round(elapsed, 3),
"requested_requests": requests,
"warmup_requests": warmup,
"successful_requests": len(latencies),
"failed_requests": failures,
"rps": round(len(latencies) / elapsed, 3),
"p50_ms": percentile(latencies, 0.50),
"p95_ms": percentile(latencies, 0.95),
"p99_ms": percentile(latencies, 0.99),
"rss_min_kib": min(rss),
"rss_max_kib": max(rss),
"rss_delta_kib": max(rss) - min(rss),
}, command
finally:
os.killpg(process.pid, signal.SIGTERM)
try:
process.wait(timeout=10)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
def baseline_overlay(directory):
source = (ROOT / "internal/storage/memory/message_repository.go").resolve()
content = source.read_text()
if content.count(FAST_PATH) != 1:
raise RuntimeError("expected exactly one optimized append block")
replacement = directory / "message_repository_baseline.go"
replacement.write_text(content.replace(FAST_PATH, "", 1))
overlay = directory / "overlay.json"
overlay.write_text(json.dumps({"Replace": {str(source): str(replacement)}}))
return overlay
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--mode", choices=("baseline", "optimized"), required=True)
parser.add_argument("--requests", type=int, default=10000)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
if args.requests <= 0:
parser.error("--requests must be positive")
with tempfile.TemporaryDirectory(prefix="messenger-track1-") as temp_dir:
overlay = baseline_overlay(Path(temp_dir))
rows = []
for history in (1000, 10000, 50000):
for concurrency in (1, 4, 16, 32):
row, command = run_case(args.mode, history, concurrency, args.requests, overlay)
rows.append(row)
print(json.dumps(row, ensure_ascii=False), flush=True)
result = {
"mode": args.mode,
"command": command,
"go_version": subprocess.check_output(["go", "version"], text=True).strip(),
"os_arch": subprocess.check_output(["go", "env", "GOOS", "GOARCH"], text=True).split(),
"requests_per_case": args.requests,
"rss_source": "ps RSS of go run child executable, KiB; sampled every 100 ms",
"rows": rows,
}
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
if __name__ == "__main__":
main()
+189
View File
@@ -0,0 +1,189 @@
#!/usr/bin/env python3
"""Сводка трека 1: артефакты `evidence/track1/*` -> таблица и графики.
Читает `load-<label>.json` (tests/load.py) и `stats-<label>.csv` (docker stats)
и печатает метрики профиля: успешный RPS, p50/p95/p99 успешных запросов, доля
ошибок, суммарный CPU API, максимум памяти API, CPU PostgreSQL и LB.
.venv/bin/python scripts/track1_report.py
Графики (PNG) требуют matplotlib; без него печатается только таблица.
"""
import argparse
import csv
import json
import re
from collections import defaultdict
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_DIR = ROOT / 'evidence/track1'
MEMORY_UNITS = {'B': 1 / 1024 / 1024, 'KiB': 1 / 1024, 'MiB': 1, 'GiB': 1024}
def parse_cpu(value):
return float(value.rstrip('%')) if value else 0.0
def parse_memory(value):
"""'123.4MiB / 256MiB' -> 123.4 MiB."""
match = re.match(r'([\d.]+)\s*([KMG]?i?B)', value.strip())
if not match:
return 0.0
return float(match.group(1)) * MEMORY_UNITS.get(match.group(2), 1)
def service_of(container):
"""mtusi-messenger-lab3-api-12 -> api"""
return container.rsplit('-', 1)[0].split('-')[-1] if '-' in container else container
def read_stats(path):
"""Профиль -> агрегаты по сервисам.
Внутри одного timestamp значения всех контейнеров сервиса складываются: две-три
реплики — это общий ресурс профиля, а не выборка. Затем CPU усредняется по
timestamp'ам, а память берётся пиковой (сумма по репликам).
"""
samples = defaultdict(lambda: defaultdict(lambda: {'cpu': 0.0, 'mem': 0.0}))
with path.open() as handle:
for row in csv.DictReader(handle):
service = service_of(row['container'])
bucket = samples[service][row['timestamp']]
bucket['cpu'] += parse_cpu(row['cpu_percent'])
bucket['mem'] += parse_memory(row['mem_usage'])
cpu = {service: [values['cpu'] for values in by_timestamp.values()] for service, by_timestamp in samples.items()}
memory = {service: max(values['mem'] for values in by_timestamp.values()) for service, by_timestamp in samples.items()}
return cpu, memory
def aggregate(label, directory):
load_path = directory / f'load-{label}.json'
stats_path = directory / f'stats-{label}.csv'
profile_path = directory / f'profile-{label}.json'
if not load_path.is_file() or not stats_path.is_file():
return None
report = json.loads(load_path.read_text())
profile = json.loads(profile_path.read_text()) if profile_path.is_file() else {}
cpu, memory = read_stats(stats_path)
api_cpu = cpu.get('api', [])
api_memory = memory.get('api', 0.0)
def average(values):
return round(sum(values) / len(values), 2) if values else None
sampled = max((len(values) for values in cpu.values()), default=0)
return {
'label': label,
'replicas': profile.get('replicas', 0),
'total_cpu': profile.get('total_cpu'),
'cpu_per_replica': round(profile['total_cpu'] / max(1, profile['replicas']), 2)
if profile.get('total_cpu') else None,
'successful_rps': report['successful_rps'],
'p50_ms': report['successful_latency_ms']['p50'],
'p95_ms': report['successful_latency_ms']['p95'],
'p99_ms': report['successful_latency_ms']['p99'],
'errors': report['failed_requests'],
'error_ratio': report['error_ratio'],
'api_cpu_sum': average(api_cpu),
'api_cpu_per_replica': round(average(api_cpu) / max(1, profile.get('replicas') or 1), 2)
if api_cpu else None,
'api_memory_max_sum_mib': round(api_memory, 1) if api_memory else None,
'postgres_cpu': average(cpu.get('postgres', [])),
'lb_cpu': average(cpu.get('lb', [])),
'stats_samples': sampled,
'load_seconds': report['elapsed_seconds'],
}
def markdown(rows):
header = (
'| профиль | реплик | бюджет CPU | CPU/реплика | успешный RPS | p50 мс | p95 мс | p99 мс | ошибки | '
'API CPU (сумма) | API RAM max (сумма, MiB) | PG CPU | LB CPU |\n'
'| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n'
)
lines = [
'| {label} | {replicas} | {total_cpu} | {cpu_per_replica} | {successful_rps} | {p50_ms} | {p95_ms} | {p99_ms} | '
'{errors} | {api_cpu_sum} | {api_memory_max_sum_mib} | {postgres_cpu} | {lb_cpu} |'.format(**row)
for row in rows
]
return header + '\n'.join(lines) + '\n'
def plot(rows, directory):
try:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
except ImportError:
print('matplotlib недоступен: графики не построены (pip install matplotlib)')
return
series = {
'fixed-budget': [row for row in rows if row['label'].startswith('r') and row['total_cpu']],
'growth': [row for row in rows if row['label'].startswith('g') and row['total_cpu']],
}
for name, points in series.items():
if len(points) < 2:
continue
axis = 'replicas' if name == 'fixed-budget' else 'total_cpu'
points = sorted(points, key=lambda row: row[axis])
ticks = [str(row[axis]) for row in points]
figure, (left, right) = plt.subplots(1, 2, figsize=(10, 4))
left.plot(ticks, [row['successful_rps'] for row in points], marker='o')
left.set_xlabel('API реплик' if axis == 'replicas' else 'суммарный бюджет CPU')
left.set_ylabel('успешный RPS')
left.grid(True)
left.set_title('Пропускная способность')
right.plot(ticks, [row['p95_ms'] for row in points], marker='o', color='tab:red')
right.set_xlabel('API реплик' if axis == 'replicas' else 'суммарный бюджет CPU')
right.set_ylabel('p95 успешных, мс')
right.grid(True)
right.set_title('Задержка p95')
figure.suptitle(('Фиксированный бюджет' if name == 'fixed-budget' else 'Рост ресурсов') + ' (трек 1)')
figure.tight_layout()
target = directory / ('scaling-' + name + '.png')
figure.savefig(target, dpi=120)
print('график:', target)
def main():
parser = argparse.ArgumentParser(description='Сводка трека 1 по артефактам стенда')
parser.add_argument('--dir', type=Path, default=DEFAULT_DIR)
args = parser.parse_args()
labels = sorted(
path.stem.removeprefix('load-') for path in args.dir.glob('load-*.json')
)
rows = [row for row in (aggregate(label, args.dir) for label in labels) if row]
if not rows:
raise SystemExit('нет артефактов в ' + str(args.dir))
table = markdown(rows)
print(table)
(args.dir / 'summary.md').write_text('# Трек 1: цена масштабирования\n\n' + table)
plot(rows, args.dir)
if __name__ == '__main__':
main()
+140
View File
@@ -0,0 +1,140 @@
#!/bin/sh
# Track 1: the price of scaling. Runs one and the same closed-loop write profile
# against 1/2/4 API replicas while the TOTAL API budget stays fixed, and records
# raw metrics. The stand has to be built already (make up).
#
# scripts/track1_scaling.sh
# REPLICAS="2 4" DURATION=30 CONCURRENCY=8 scripts/track1_scaling.sh
#
# Artifacts: evidence/track1/{load,stats}-r<N>.json|csv plus summary.txt
set -eu
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$ROOT_DIR"
COMPOSE_BIN=${COMPOSE_BIN:-docker compose}
PYTHON=${PYTHON:-python3}
REPLICAS=${REPLICAS:-"1 2 4"}
TOTAL_CPU=${TOTAL_CPU:-2.0}
TOTAL_MEM_MB=${TOTAL_MEM_MB:-1024}
DURATION=${DURATION:-60}
CONCURRENCY=${CONCURRENCY:-16}
WARMUP=${WARMUP:-15}
BASE_URL=${BASE_URL:-http://localhost:8080}
LABEL=${LABEL:-}
OUT=evidence/track1
# The author's shell exports HTTP(S)_PROXY, which breaks localhost clients.
NO_PROXY_ENV="env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy"
NO_PROXY_ENV="$NO_PROXY_ENV NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1"
mkdir -p "$OUT"
compose() {
# shellcheck disable=SC2086
$COMPOSE_BIN --env-file .env -f compose.yaml "$@"
}
wait_ready() {
attempt=0
while [ "$attempt" -lt 90 ]; do
if curl -fsS --noproxy '*' -o /dev/null "$BASE_URL/health/ready"; then
return 0
fi
attempt=$((attempt + 1))
sleep 1
done
printf 'track1_scaling.sh: %s/health/ready did not become ready\n' "$BASE_URL" >&2
return 1
}
per_replica_cpu() {
awk "BEGIN{printf \"%.2f\", $TOTAL_CPU/$1}"
}
per_replica_mem() {
awk "BEGIN{printf \"%.0fM\", $TOTAL_MEM_MB/$1}"
}
SUMMARY="$OUT/summary.txt"
if [ ! -f "$SUMMARY" ]; then
{
echo "# Track 1: the price of scaling"
echo "# generated: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo "# host: $(uname -sm)"
echo "# cpu: $(sysctl -n machdep.cpu.brand_string 2>/dev/null || printf unknown)"
echo "# ram bytes: $(sysctl -n hw.memsize 2>/dev/null || printf unknown)"
echo "# load: tests/load.py closed loop; postgres/redis/lb limits are fixed in compose.yaml"
echo "# each profile line below records the budget it was run with"
docker version --format 'docker engine {{.Server.Version}}'
# shellcheck disable=SC2086
$COMPOSE_BIN version
echo
} > "$SUMMARY"
fi
{
echo "=== invocation $(date -u +%Y-%m-%dT%H:%M:%SZ): REPLICAS=\"$REPLICAS\" TOTAL_CPU=$TOTAL_CPU TOTAL_MEM_MB=$TOTAL_MEM_MB DURATION=$DURATION CONCURRENCY=$CONCURRENCY WARMUP=$WARMUP ==="
echo
} >> "$SUMMARY"
for replicas in $REPLICAS; do
cpu=$(per_replica_cpu "$replicas")
mem=$(per_replica_mem "$replicas")
label=${LABEL:-r$replicas}
printf '=== profile label=%s replicas=%s cpu=%s mem=%s ===\n' "$label" "$replicas" "$cpu" "$mem" | tee -a "$SUMMARY"
API_REPLICAS="$replicas" API_CPU_LIMIT="$cpu" API_MEM_LIMIT="$mem" compose up -d --no-deps api
wait_ready
# Warm up caches, connection pools and the JIT-free query plans; the warmup
# data stays in the table, so every profile grows the same history shape.
# shellcheck disable=SC2086
$NO_PROXY_ENV $PYTHON tests/load.py --base-url "$BASE_URL" \
--duration "$WARMUP" --concurrency "$CONCURRENCY" >/dev/null
STATS="$OUT/stats-$label.csv"
printf 'timestamp,container,cpu_percent,mem_usage\n' > "$STATS"
PROFILE="$OUT/profile-$label.json"
printf '{"label":"%s","replicas":%s,"total_cpu":%s,"total_mem_mb":%s,"duration":%s,"concurrency":%s,"warmup":%s}\n' \
"$label" "$replicas" "$TOTAL_CPU" "$TOTAL_MEM_MB" "$DURATION" "$CONCURRENCY" "$WARMUP" > "$PROFILE"
(
while :; do
docker stats --no-stream \
--format '{{.Name}},{{.CPUPerc}},{{.MemUsage}}' \
| sed "s|^|$(date -u +%Y-%m-%dT%H:%M:%SZ),|" >> "$STATS"
sleep 1
done
) &
sampler=$!
trap 'kill "$sampler" 2>/dev/null || true' EXIT INT TERM
# shellcheck disable=SC2086
$NO_PROXY_ENV $PYTHON tests/load.py --base-url "$BASE_URL" \
--duration "$DURATION" --concurrency "$CONCURRENCY" \
--output "$OUT/load-$label.json" | tee -a "$SUMMARY"
kill "$sampler" 2>/dev/null || true
wait "$sampler" 2>/dev/null || true
trap - EXIT INT TERM
# Shared-dependency view right after the run: connections, pool pressure and
# how much history the profile wrote into.
compose exec -T postgres psql -U "${POSTGRES_USER:-messenger}" -d "${POSTGRES_DB:-messenger}" -Atc \
"SELECT 'postgres_connections=' || count(*) FROM pg_stat_activity;
SELECT 'postgres_max_connections=' || current_setting('max_connections');
SELECT 'messages_rows=' || count(*) FROM messages;
SELECT 'idempotency_rows=' || count(*) FROM message_idempotency;" | tee -a "$SUMMARY"
printf '\n' >> "$SUMMARY"
done
printf 'track1_scaling.sh: artifacts in %s\n' "$OUT"