Добавить генератор нагрузки, сбор метрик реплик и сценарии экспериментов для отказов, rolling update и трека 1

This commit is contained in:
2026-11-02 17:44:59 +03:00
parent c5cdcb3377
commit b2973405f3
30 changed files with 2067 additions and 18 deletions
+61
View File
@@ -0,0 +1,61 @@
#!/bin/sh
# Level 4: one API replica fails under a constant write load. The generator
# sends messages at RATE for DURATION and retries uncertain sends with the
# same key; at FAULT_AT seconds the chosen replica is stopped (stop: SIGTERM,
# graceful) or killed (kill: SIGKILL, a crash), at RESTORE_AT it is started
# again. Afterwards the generator reads the history back: every confirmed
# message once.
#
# sh scripts/bench/failover.sh stop|kill <replica number, 1-based>
#
# Environment: RATE (50), DURATION (60s), FAULT_AT (15), RESTORE_AT (35),
# OUT (default evidence/failover). Results in <OUT>/<kind>-<n>/:
# timeline.json, seconds.csv (per-second outcomes, attributed by send time),
# faults.json (when and what was stopped), compose.log (the balancer's
# DOWN/UP lines and the replicas' shutdown/start lines), instances-*.txt.
# Runs on the current stand (`make up`) and leaves every replica running.
set -eu
cd "$(dirname "$0")/../.."
. scripts/bench/lib.sh
kind=${1:?usage: failover.sh stop|kill <replica number>}
n=${2:?usage: failover.sh stop|kill <replica number>}
case "$kind" in stop | kill) ;; *) echo "kind must be stop or kill" >&2; exit 2 ;; esac
rate=${RATE:-50}
duration=${DURATION:-60s}
fault_at=${FAULT_AT:-15}
restore_at=${RESTORE_AT:-35}
dir=${OUT:-evidence/failover}/$kind-$n
export MSYS_NO_PATHCONV=1
rm -rf "$dir"
mkdir -p "$dir"
docker compose up -d --wait >/dev/null 2>&1
target=$(docker compose ps -q api | sed -n "${n}p")
[ -n "$target" ] || { echo "no running replica number $n" >&2; exit 2; }
alias=$(sh scripts/api-instances.sh | awk -v id="$(printf '%s' "$target" | cut -c1-12)" '$1 == id { print $4 }')
meta "$dir/meta.json" "experiment=failover" "kind=$kind" "replica=$n" "rate=$rate" "duration=$duration" \
"fault_at_s=$fault_at" "restore_at_s=$restore_at"
sh scripts/instances.sh >"$dir/instances-before.txt"
since=$(date -u +%Y-%m-%dT%H:%M:%SZ)
BENCH_OUT=$(abspath "$dir") docker compose --profile bench run --rm loadgen timeline \
-rate "$rate" -duration "$duration" >"$dir/loadgen.log" 2>&1 &
generator=$!
# The generator seeds two users first; its timeline starts after that. The
# fault times below are absolute, as is started_at in timeline.json.
sleep "$fault_at"
fault=$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)
docker "$kind" "$target" >/dev/null
fault_done=$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)
sleep $((restore_at - fault_at))
restore=$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)
docker compose start api >/dev/null 2>&1
wait "$generator" || echo "generator reported a failed history check, see $dir/loadgen.log"
printf '{\n "kind": "%s",\n "container": "%s",\n "x_instance_id": "%s",\n "fault_utc": "%s",\n "fault_command_returned_utc": "%s",\n "restore_utc": "%s"\n}\n' \
"$kind" "$(printf '%s' "$target" | cut -c1-12)" "$alias" "$fault" "$fault_done" "$restore" >"$dir/faults.json"
docker compose logs --no-color --since "$since" lb api >"$dir/compose.log" 2>&1
sh scripts/instances.sh >"$dir/instances-after.txt"
cat "$dir/loadgen.log" | tail -n 1
echo "results in $dir"
+57
View File
@@ -0,0 +1,57 @@
# Shared helpers of the experiment scripts; sourced, not run.
# abspath prints the absolute path of an existing directory in the form the
# Docker CLI accepts for a bind mount (a Windows path under Git Bash).
abspath() {
(cd "$1" && (pwd -W 2>/dev/null || pwd))
}
# meta writes the header of one run: what ran, when, on which commit and
# host. Arguments: file, then key=value pairs added to the record.
meta() {
file=$1
shift
{
printf '{\n'
printf ' "date_utc": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
printf ' "commit": "%s",\n' "$(git rev-parse --short HEAD)"
printf ' "branch": "%s",\n' "$(git branch --show-current)"
printf ' "docker": "%s",\n' "$(docker version --format '{{.Server.Version}}')"
printf ' "host_cpus": "%s",\n' "$(docker info --format '{{.NCPU}}')"
printf ' "host_memory_bytes": "%s",\n' "$(docker info --format '{{.MemTotal}}')"
for pair in "$@"; do
printf ' "%s": "%s",\n' "${pair%%=*}" "${pair#*=}"
done
printf ' "go": "%s"\n' "$(go env GOVERSION 2>/dev/null || echo unknown)"
printf '}\n'
} >"$file"
}
# sample_docker_stats appends the CPU and memory of every container of the
# stand to a JSON-lines file, about every two seconds, until killed.
sample_docker_stats() {
while :; do
docker stats --no-stream --format "{\"t\":$(date +%s),\"name\":\"{{.Name}}\",\"cpu\":\"{{.CPUPerc}}\",\"mem\":\"{{.MemUsage}}\"}" \
$(docker ps -q --filter label=com.docker.compose.project=lab3) 2>/dev/null || true
done >>"$1"
}
# sample_postgres appends, every second, the database's commit counters and
# what its active sessions are waiting for (none: running on CPU).
sample_postgres() {
while :; do
docker compose exec -T postgres psql -U messenger -d messenger -XAtq -c "
SELECT json_build_object(
't', extract(epoch FROM now()),
'xact_commit', xact_commit, 'xact_rollback', xact_rollback,
'tup_inserted', tup_inserted, 'blks_read', blks_read, 'blks_hit', blks_hit,
'active', (SELECT count(*) FROM pg_stat_activity WHERE state = 'active' AND backend_type = 'client backend' AND pid <> pg_backend_pid()),
'waits', (SELECT coalesce(json_object_agg(w, n), '{}') FROM (
SELECT coalesce(wait_event_type || ':' || wait_event, 'cpu') AS w, count(*) AS n
FROM pg_stat_activity
WHERE state = 'active' AND backend_type = 'client backend' AND pid <> pg_backend_pid()
GROUP BY 1) AS x))
FROM pg_stat_database WHERE datname = 'messenger'" 2>/dev/null || true
sleep 1
done >>"$1"
}
+253
View File
@@ -0,0 +1,253 @@
#!/usr/bin/env python3
"""Tables and charts of track 1 from the raw results of run-series.sh.
python scripts/bench/plot.py <raw root> <output dir>
The raw root holds <series>/<config>/rep<k>/ directories. Written to the
output directory:
summary.csv one row per step of every run: offered and successful rate,
errors, latency percentiles, generator lag, mean CPU of each
component and pool waits during the step;
capacity.csv the capacity of every run and the median per configuration;
<series>-throughput.png, <series>-p99.png, capacity.png,
cpu-at-capacity.png, pool-waits.png.
Capacity is the highest valid step (generator on schedule) with less than 1 %
errors and a p99 of successful requests within 500 ms.
"""
import csv
import json
import pathlib
import statistics
import sys
from datetime import datetime
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt # noqa: E402
SLO_P99_MS = 500.0
MAX_ERROR_SHARE = 0.01
COMPONENTS = ("api", "lb", "postgres", "valkey", "loadgen")
def read_jsonl(path):
if not path.exists():
return []
rows = []
for line in path.read_text(encoding="utf-8").splitlines():
line = line.strip()
if line:
try:
rows.append(json.loads(line))
except json.JSONDecodeError:
pass
return rows
def component(name):
for c in COMPONENTS:
if f"-{c}-" in name:
return c
return None
def parse_time(value):
return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp()
def load_runs(root):
runs = []
for steps_path in sorted(root.glob("*/*/rep*/steps.json")):
d = steps_path.parent
report = json.loads(steps_path.read_text(encoding="utf-8"))
runs.append({
"series": d.parent.parent.name,
"config": d.parent.name,
"rep": d.name,
"start": parse_time(report["started_at"]),
"steps": report["steps"],
"docker": read_jsonl(d / "docker-stats.jsonl"),
"metrics": read_jsonl(d / "metrics.jsonl"),
})
return runs
def mean_cpu(run, t0, t1):
"""Mean CPU per component in [t0, t1); replicas of the API are summed."""
per_time = {}
for row in run["docker"]:
c = component(row.get("name", ""))
if c is None or not t0 <= row["t"] < t1:
continue
try:
cpu = float(row["cpu"].rstrip("%"))
except (ValueError, KeyError):
continue
per_time.setdefault(row["t"], {}).setdefault(c, 0.0)
per_time[row["t"]][c] += cpu
out = {}
for c in COMPONENTS:
values = [v[c] for v in per_time.values() if c in v]
out[c] = round(statistics.mean(values), 1) if values else ""
return out
def pool_waits(run, t0, t1):
"""Requests that waited for a pooled connection during [t0, t1), all
replicas together, per second."""
first, last = {}, {}
for row in run["metrics"]:
t = run["start"] + row["t"]
if not t0 <= t < t1:
continue
for replica in row.get("replicas") or []:
pool = replica.get("pgxpool") or {}
key = replica.get("instance")
if key and "empty_acquire_count" in pool:
first.setdefault(key, pool["empty_acquire_count"])
last[key] = pool["empty_acquire_count"]
if not last:
return ""
return round(sum(last[k] - first[k] for k in last) / max(t1 - t0, 1e-9), 1)
def is_capacity(step):
return step["valid"] and step["error_share"] < MAX_ERROR_SHARE and step["ok_p99_ms"] <= SLO_P99_MS
def main(root, out):
runs = load_runs(root)
if not runs:
sys.exit(f"no runs under {root}")
out.mkdir(parents=True, exist_ok=True)
rows, capacities = [], []
for run in runs:
best = None
for step in run["steps"]:
t0 = run["start"] + step["started_at_s"]
t1 = t0 + step["seconds"]
cpu = mean_cpu(run, t0, t1)
row = {
"series": run["series"], "config": run["config"], "rep": run["rep"],
"offered_rps": step["offered_rps"], "ok_rps": round(step["ok_rps"], 1),
"error_share": round(step["error_share"], 4), "ok_p50_ms": step["ok_p50_ms"],
"ok_p95_ms": step["ok_p95_ms"], "ok_p99_ms": step["ok_p99_ms"],
"lag_p99_ms": step["lag_p99_ms"], "valid": step["valid"],
**{f"cpu_{c}_pct": cpu[c] for c in COMPONENTS},
"pool_waits_per_s": pool_waits(run, t0, t1),
}
rows.append(row)
if is_capacity(step):
best = row
capacities.append({
"series": run["series"], "config": run["config"], "rep": run["rep"],
"capacity_rps": best["offered_rps"] if best else 0, "at": best,
})
with open(out / "summary.csv", "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=list(rows[0]))
w.writeheader()
w.writerows(rows)
configs = []
for c in capacities:
if (c["series"], c["config"]) not in configs:
configs.append((c["series"], c["config"]))
with open(out / "capacity.csv", "w", newline="", encoding="utf-8") as f:
w = csv.writer(f)
w.writerow(["series", "config", "capacity_rps_per_repeat", "capacity_rps_median"])
medians = {}
for key in configs:
values = [c["capacity_rps"] for c in capacities if (c["series"], c["config"]) == key]
medians[key] = statistics.median(values)
w.writerow([key[0], key[1], " ".join(f"{v:g}" for v in values), f"{medians[key]:g}"])
def median_by_offered(series, config, field):
points = {}
for r in rows:
if r["series"] == series and r["config"] == config and r["valid"] and r[field] != "":
points.setdefault(r["offered_rps"], []).append(float(r[field]))
xs = sorted(points)
return xs, [statistics.median(points[x]) for x in xs]
for series in sorted({s for s, _ in configs}):
names = [c for s, c in configs if s == series]
for field, title, filename, log in (
("ok_rps", "Successful requests per second", "throughput", False),
("ok_p99_ms", "p99 of successful requests, ms", "p99", True),
):
fig, ax = plt.subplots(figsize=(7, 4.5))
top = 0
for name in names:
xs, ys = median_by_offered(series, name, field)
ax.plot(xs, ys, marker="o", label=name)
top = max([top, *xs])
if field == "ok_rps" and top:
ax.plot([0, top], [0, top], linestyle=":", color="grey", label="offered")
if field == "ok_p99_ms":
ax.axhline(SLO_P99_MS, linestyle="--", color="grey", label="500 ms")
if log:
ax.set_yscale("log")
ax.set_xlabel("Offered requests per second")
ax.set_ylabel(title)
ax.set_title(f"Series {series}: median of repeats, valid steps only")
ax.grid(alpha=0.3)
ax.legend()
fig.tight_layout()
fig.savefig(out / f"{series}-{filename}.png", dpi=120)
plt.close(fig)
labels = [f"{s}/{c}" for s, c in configs]
fig, ax = plt.subplots(figsize=(max(6, len(labels) * 0.9), 4.5))
meds = [medians[k] for k in configs]
lows = [medians[k] - min(c["capacity_rps"] for c in capacities if (c["series"], c["config"]) == k) for k in configs]
highs = [max(c["capacity_rps"] for c in capacities if (c["series"], c["config"]) == k) - medians[k] for k in configs]
ax.bar(labels, meds, yerr=[lows, highs], capsize=4, color="#4c78a8")
ax.set_ylabel("Capacity, requests per second")
ax.set_title("Capacity per configuration (median, range of repeats)")
ax.tick_params(axis="x", rotation=30)
ax.grid(axis="y", alpha=0.3)
fig.tight_layout()
fig.savefig(out / "capacity.png", dpi=120)
plt.close(fig)
fig, ax = plt.subplots(figsize=(max(6, len(labels) * 1.1), 4.5))
width = 0.8 / len(COMPONENTS)
for i, comp in enumerate(COMPONENTS):
values = []
for key in configs:
at = [c["at"] for c in capacities if (c["series"], c["config"]) == key and c["at"]]
cpu = [float(a[f"cpu_{comp}_pct"]) for a in at if a[f"cpu_{comp}_pct"] != ""]
values.append(statistics.median(cpu) if cpu else 0)
ax.bar([j + i * width for j in range(len(configs))], values, width, label=comp)
ax.set_xticks([j + 0.4 - width / 2 for j in range(len(configs))], labels, rotation=30)
ax.set_ylabel("Mean CPU at capacity, % of one core")
ax.set_title("Which component is busy at capacity")
ax.grid(axis="y", alpha=0.3)
ax.legend()
fig.tight_layout()
fig.savefig(out / "cpu-at-capacity.png", dpi=120)
plt.close(fig)
fig, ax = plt.subplots(figsize=(7, 4.5))
for series, name in configs:
xs, ys = median_by_offered(series, name, "pool_waits_per_s")
if xs:
ax.plot(xs, ys, marker="o", label=f"{series}/{name}")
ax.set_xlabel("Offered requests per second")
ax.set_ylabel("Waits for a pooled connection per second")
ax.set_title("Connection pool waits, all replicas")
ax.grid(alpha=0.3)
ax.legend()
fig.tight_layout()
fig.savefig(out / "pool-waits.png", dpi=120)
plt.close(fig)
print(f"{len(runs)} runs, {len(rows)} steps -> {out}")
if __name__ == "__main__":
if len(sys.argv) != 3:
sys.exit(__doc__)
main(pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2]))
+47
View File
@@ -0,0 +1,47 @@
#!/bin/sh
# Level 4: a rolling update under a constant write load. The generator sends
# messages at RATE for DURATION, retrying uncertain sends with the same key;
# at UPDATE_AT seconds `scripts/rollout.sh` replaces every replica. Afterwards
# the generator reads the history back: every confirmed message once.
#
# sh scripts/bench/rollout-under-load.sh
#
# Environment: RATE (50), DURATION (60s), UPDATE_AT (15), OUT (default
# evidence/rollout). Results in <OUT>/: timeline.json, seconds.csv,
# rollout.log, update.json (when it ran), compose.log, instances-*.txt.
set -eu
cd "$(dirname "$0")/../.."
. scripts/bench/lib.sh
rate=${RATE:-50}
duration=${DURATION:-60s}
update_at=${UPDATE_AT:-15}
dir=${OUT:-evidence/rollout}
export MSYS_NO_PATHCONV=1
rm -rf "$dir"
mkdir -p "$dir"
docker compose up -d --wait >/dev/null 2>&1
# Build first, as a delivery pipeline would: the update under load then
# measures the replacement of the replicas, not the compiler.
docker compose build api >/dev/null 2>&1
meta "$dir/meta.json" "experiment=rolling-update" "rate=$rate" "duration=$duration" "update_at_s=$update_at"
sh scripts/instances.sh >"$dir/instances-before.txt"
since=$(date -u +%Y-%m-%dT%H:%M:%SZ)
BENCH_OUT=$(abspath "$dir") docker compose --profile bench run --rm loadgen timeline \
-rate "$rate" -duration "$duration" >"$dir/loadgen.log" 2>&1 &
generator=$!
sleep "$update_at"
started=$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)
status=0
sh scripts/rollout.sh >"$dir/rollout.log" 2>&1 || status=$?
finished=$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)
wait "$generator" || echo "generator reported a failed history check, see $dir/loadgen.log"
printf '{\n "update_started_utc": "%s",\n "update_finished_utc": "%s",\n "rollout_exit_code": %s\n}\n' \
"$started" "$finished" "$status" >"$dir/update.json"
docker compose logs --no-color --since "$since" lb api migrate >"$dir/compose.log" 2>&1
sh scripts/instances.sh >"$dir/instances-after.txt"
cat "$dir/loadgen.log" | tail -n 1
echo "results in $dir"
+58
View File
@@ -0,0 +1,58 @@
#!/bin/sh
# Track 1, the cost of scaling: runs every configuration of one series file,
# each repeated, each on a fresh stand (empty volumes, same seed), under the
# same grid of offered rates.
#
# RATES=200,400,800 sh scripts/bench/run-series.sh scripts/bench/series/A.conf [repeats]
#
# Environment: RATES (required), STEP (30s), WARMUP (30s), OUT (results root,
# default evidence/track1/raw). Fixed for every configuration: HAProxy
# LB_CPUS (1.0), PostgreSQL PG_CPUS/PG_MEMORY (1.0/1G), Valkey 0.5 CPU and the
# generator LOADGEN_CPUS (1.5). Results per run:
# <OUT>/<series>/<config>/rep<k>/{meta.json,steps.json,seconds.csv,
# metrics.jsonl,docker-stats.jsonl,postgres.jsonl,loadgen.log}
# The stand is removed at the end; `make up` brings the normal one back.
set -eu
cd "$(dirname "$0")/../.."
. scripts/bench/lib.sh
series=${1:?usage: run-series.sh <series.conf> [repeats]}
repeats=${2:-3}
: "${RATES:?set RATES, the offered requests per second of the steps, e.g. 200,400,800}"
step=${STEP:-30s}
warmup=${WARMUP:-30s}
root=${OUT:-evidence/track1/raw}/$(basename "$series" .conf)
export APP_DEBUG_ADDR=:9090 LB_QUIET=1
export LB_CPUS=${LB_CPUS:-1.0} PG_CPUS=${PG_CPUS:-1.0} PG_MEMORY=${PG_MEMORY:-1G} LOADGEN_CPUS=${LOADGEN_CPUS:-1.5}
export MSYS_NO_PATHCONV=1
grep -v '^#' "$series" | while read -r name replicas cpus memory gomemlimit pool; do
[ -n "$name" ] || continue
for rep in $(seq 1 "$repeats"); do
dir=$root/$name/rep$rep
rm -rf "$dir"
mkdir -p "$dir"
echo "== $name rep $rep: $replicas x $cpus CPU / $memory, pool $pool, rates $RATES"
export API_REPLICAS=$replicas API_CPUS=$cpus API_MEMORY=$memory API_GOMEMLIMIT=$gomemlimit DB_MAX_CONNS=$pool
docker compose down -v --remove-orphans >/dev/null 2>&1
docker compose up -d --build --wait >/dev/null 2>&1
meta "$dir/meta.json" "series=$(basename "$series" .conf)" "config=$name" "repeat=$rep" \
"api_replicas=$replicas" "api_cpus=$cpus" "api_memory=$memory" "gomemlimit=$gomemlimit" "db_max_conns=$pool" \
"lb_cpus=$LB_CPUS" "pg_cpus=$PG_CPUS" "pg_memory=$PG_MEMORY" "loadgen_cpus=$LOADGEN_CPUS" \
"rates=$RATES" "step=$step" "warmup=$warmup"
sample_docker_stats "$dir/docker-stats.jsonl" &
stats=$!
sample_postgres "$dir/postgres.jsonl" &
pg=$!
BENCH_OUT=$(abspath "$dir") docker compose --profile bench run --rm loadgen bench \
-rates "$RATES" -step "$step" -warmup "$warmup" -scrape >"$dir/loadgen.log" 2>&1 || echo " loadgen failed, see $dir/loadgen.log"
kill "$stats" "$pg" 2>/dev/null || true
wait "$stats" "$pg" 2>/dev/null || true
cat "$dir/loadgen.log" | grep '^step' || true
done
done
docker compose down -v --remove-orphans >/dev/null 2>&1
echo "results in $root"
+6
View File
@@ -0,0 +1,6 @@
# Series A: the same API budget, 2 CPU and 1 GiB, cut into 1, 2 or 4 replicas.
# The pool stays 10 per replica, so the total grows with the replicas.
# name replicas cpus_per_replica memory_per_replica gomemlimit pool_per_replica
A1 1 2.0 1024M 920MiB 10
A2 2 1.0 512M 460MiB 10
A4 4 0.5 256M 230MiB 10
+5
View File
@@ -0,0 +1,5 @@
# Series A': the budget of series A with the total pool fixed at 20
# connections. A'2 equals A2 and is not run again.
# name replicas cpus_per_replica memory_per_replica gomemlimit pool_per_replica
Ap1 1 2.0 1024M 920MiB 20
Ap4 4 0.5 256M 230MiB 5
+7
View File
@@ -0,0 +1,7 @@
# Series B: replicas of one fixed size (1 CPU, 512 MiB, pool 10) added one by
# one, so the API budget grows from 1 to 4 CPU. B2 equals A2 and is not run
# again.
# name replicas cpus_per_replica memory_per_replica gomemlimit pool_per_replica
B1 1 1.0 512M 460MiB 10
B3 3 1.0 512M 460MiB 10
B4 4 1.0 512M 460MiB 10
+4
View File
@@ -0,0 +1,4 @@
# Calibration: the smallest API budget of the study (one replica, one CPU)
# with a wide range of rates finds where the common rate grid must reach.
# name replicas cpus_per_replica memory_per_replica gomemlimit pool_per_replica
cal 1 1.0 512M 460MiB 10
+2 -1
View File
@@ -1,6 +1,7 @@
#!/bin/sh
# Restart hook of `make test-persistence` (tests/resilience.py): stops the
# API, PostgreSQL and Valkey gracefully and starts the same containers again.
# balancer, every API replica, PostgreSQL and Valkey gracefully and starts the
# same containers again (the one-shot migrate finds nothing to apply).
# Volumes and data are kept and nothing is re-seeded. The test hides the
# output, so failures surface through the exit code only.
set -eu