Перенесите реализацию lab3 и сохраните серии нагрузочных экспериментов
This commit is contained in:
Executable
+30
@@ -0,0 +1,30 @@
|
||||
#!/bin/sh
|
||||
# Lists the API containers: <id> <name> <state> <X-Instance-Id> <image>. The
|
||||
# alias is random per process, so each running replica is asked over
|
||||
# /health/live, in parallel: the failover hook must return within 10 seconds.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
ids=$(docker compose ps -aq api)
|
||||
[ -n "$ids" ] || exit 0
|
||||
tmp=$(mktemp -d)
|
||||
trap 'rm -rf "$tmp"' EXIT
|
||||
|
||||
docker inspect --format '{{.Id}} {{.Name}} {{.State.Status}} {{.Image}}' $ids >"$tmp/containers"
|
||||
while read -r id name state image; do
|
||||
if [ "$state" = running ]; then
|
||||
# wget prints the response headers on stderr; the body is dropped.
|
||||
(docker exec "$id" wget -S -q -O - http://127.0.0.1:8080/health/live 2>&1 >/dev/null |
|
||||
sed -n 's/^ *[Xx]-[Ii]nstance-[Ii]d: *//p' | tr -d '\r' | head -n 1 >"$tmp/$id") &
|
||||
fi
|
||||
done <"$tmp/containers"
|
||||
wait
|
||||
|
||||
while read -r id name state image; do
|
||||
alias=-
|
||||
if [ -s "$tmp/$id" ]; then
|
||||
alias=$(cat "$tmp/$id")
|
||||
fi
|
||||
image=${image#sha256:}
|
||||
printf '%s %s %s %s %s\n' "$(printf '%s' "$id" | cut -c1-12)" "${name#/}" "$state" "$alias" "$(printf '%s' "$image" | cut -c1-12)"
|
||||
done <"$tmp/containers"
|
||||
Executable
+56
@@ -0,0 +1,56 @@
|
||||
#!/bin/sh
|
||||
# Level 4: one replica stopped (SIGTERM) or killed (SIGKILL) at FAULT_AT and
|
||||
# started again at RESTORE_AT, under a constant write load that retries
|
||||
# uncertain sends with the same key; then every confirmed message must be in
|
||||
# the history once.
|
||||
#
|
||||
# sh scripts/bench/failover.sh stop|kill <replica number, 1-based>
|
||||
#
|
||||
# Environment: RATE (50), DURATION (60s), FAULT_AT (15), RESTORE_AT (35), OUT
|
||||
# (evidence/failover). Times come from the Docker VM clock; the Windows clock
|
||||
# differs by a fraction of a second and is kept for reference only.
|
||||
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"
|
||||
# A margin for the host clock, which may run ahead of the VM's.
|
||||
since=$(date -u -d '-10 seconds' +%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 "$fault_at"
|
||||
fault_host=$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)
|
||||
docker "$kind" "$target" >/dev/null
|
||||
exited=$(docker inspect --format '{{.State.FinishedAt}}' "$target")
|
||||
sleep $((restore_at - fault_at))
|
||||
restore_host=$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)
|
||||
docker compose start api >/dev/null 2>&1
|
||||
started=$(docker inspect --format '{{.State.StartedAt}}' "$target")
|
||||
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 "process_exited_vm_utc": "%s",\n "restarted_vm_utc": "%s",\n "fault_command_host_utc": "%s",\n "restore_command_host_utc": "%s"\n}\n' \
|
||||
"$kind" "$(printf '%s' "$target" | cut -c1-12)" "$alias" "$exited" "$started" "$fault_host" "$restore_host" >"$dir/faults.json"
|
||||
docker compose logs --no-color --timestamps --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"
|
||||
@@ -0,0 +1,77 @@
|
||||
# Shared helpers of the experiment scripts; sourced, not run.
|
||||
|
||||
# The generator and the knobs the experiments vary live in compose.bench.yaml.
|
||||
export COMPOSE_PATH_SEPARATOR=: COMPOSE_FILE=compose.yaml:compose.bench.yaml
|
||||
# The balancer logs errors and state changes only, not every request.
|
||||
export LB_QUIET=1
|
||||
|
||||
# abspath prints a directory in the form the Docker CLI mounts (a Windows path
|
||||
# under Git Bash).
|
||||
abspath() {
|
||||
(cd "$1" && (pwd -W 2>/dev/null || pwd))
|
||||
}
|
||||
|
||||
# meta writes what ran, when, on which commit and host: file, then key=value.
|
||||
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"
|
||||
}
|
||||
|
||||
# host_probe prints the seconds a fixed CPU loop takes in a one-CPU container:
|
||||
# the same work every time, so a slow spell of the host shows in the results.
|
||||
host_probe() {
|
||||
docker run --rm --cpus 1 --entrypoint sh mtusi-messenger:lab4 \
|
||||
-c 'time -p awk "BEGIN{for(i=0;i<5000000;i++)s+=i}"' 2>&1 | awk '/^real/ { print $2 }'
|
||||
}
|
||||
|
||||
# state_log keeps from `compose logs` (stdin) what explains a run: the
|
||||
# balancer's server state changes and the replicas' start and stop. An
|
||||
# overloaded run logs every failed request, gigabytes over a series; those
|
||||
# lines are only counted.
|
||||
state_log() {
|
||||
awk '/is DOWN|is UP|UP\/READY|maintenance|"msg":"(starting|shutdown started|shutdown completed)"/ { print; next }
|
||||
{ dropped++ } END { printf "# %d other lines dropped\n", dropped }'
|
||||
}
|
||||
|
||||
# sample_docker_stats appends the CPU and memory of every container 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=lab4) 2>/dev/null || true
|
||||
done >>"$1"
|
||||
}
|
||||
|
||||
# sample_postgres appends, every second, the database counters and what the
|
||||
# active sessions wait for ("cpu": nothing).
|
||||
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,
|
||||
'sessions', sessions, 'sessions_abandoned', sessions_abandoned,
|
||||
'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"
|
||||
}
|
||||
Executable
+336
@@ -0,0 +1,336 @@
|
||||
#!/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;
|
||||
capacity.csv the capacity of every run and the median per configuration;
|
||||
control.csv the noise checks of every run, the host speed probe and the
|
||||
loadgen CPU per request at the first step, each flagged when
|
||||
more than 25 % off its median;
|
||||
cost.csv CPU milliseconds per request of each component at the
|
||||
COST_RATES steps (valid, error-free, unflagged runs only), and
|
||||
the rate one database CPU would serve at that cost;
|
||||
<series>-throughput.png, <series>-p99.png, capacity.png,
|
||||
cpu-at-capacity.png, pool-waits.png, cost-per-request.png.
|
||||
Capacity is the highest step that passed the criterion loadgen applies (valid,
|
||||
under 1 % errors, p99 of successful requests within 500 ms). Charts show the
|
||||
median of the repeats; a hollow marker means the generator fell behind.
|
||||
"""
|
||||
import csv
|
||||
import gzip
|
||||
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
|
||||
CONTROL_TOLERANCE = 0.25
|
||||
# Below saturation in every configuration, so the cost is not inflated by
|
||||
# queueing.
|
||||
COST_RATES = (800, 1000)
|
||||
COMPONENTS = ("api", "lb", "postgres", "valkey", "loadgen")
|
||||
|
||||
|
||||
def read_jsonl(path):
|
||||
packed = path.with_name(path.name + ".gz")
|
||||
if packed.exists():
|
||||
text = gzip.decompress(packed.read_bytes()).decode("utf-8")
|
||||
elif path.exists():
|
||||
text = path.read_text(encoding="utf-8")
|
||||
else:
|
||||
return []
|
||||
rows = []
|
||||
for line in text.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"),
|
||||
"meta": json.loads((d / "meta.json").read_text(encoding="utf-8")) if (d / "meta.json").exists() else {},
|
||||
})
|
||||
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_rate(run, t0, t1, counter):
|
||||
"""Growth of a pgxpool counter during [t0, t1), all replicas, 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 counter in pool:
|
||||
first.setdefault(key, pool[counter])
|
||||
last[key] = pool[counter]
|
||||
if not last:
|
||||
return ""
|
||||
return round(sum(last[k] - first[k] for k in last) / max(t1 - t0, 1e-9), 1)
|
||||
|
||||
|
||||
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)
|
||||
classes = step["classes"]
|
||||
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"], "passed": step["passed"],
|
||||
"client_timeouts": classes.get("client_timeout", 0),
|
||||
"lb_errors": sum(n for c, n in classes.items() if c.endswith("_lb")),
|
||||
"api_errors": sum(n for c, n in classes.items() if c.startswith("http_") and not c.endswith("_lb")),
|
||||
**{f"cpu_{c}_pct": cpu[c] for c in COMPONENTS},
|
||||
"pool_waits_per_s": pool_rate(run, t0, t1, "empty_acquire_count"),
|
||||
"new_conns_per_s": pool_rate(run, t0, t1, "new_conns_count"),
|
||||
}
|
||||
rows.append(row)
|
||||
if step["passed"] and (best is None or step["offered_rps"] > best["offered_rps"]):
|
||||
best = row
|
||||
capacities.append({
|
||||
"series": run["series"], "config": run["config"], "rep": run["rep"],
|
||||
"capacity_rps": best["offered_rps"] if best else 0, "at": best,
|
||||
"invalid_below": sum(1 for s in run["steps"] if not s["valid"] and (best is None or s["offered_rps"] < best["offered_rps"])),
|
||||
})
|
||||
|
||||
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", "invalid_steps_below_capacity"])
|
||||
medians = {}
|
||||
for key in configs:
|
||||
mine = [c for c in capacities if (c["series"], c["config"]) == key]
|
||||
values = [c["capacity_rps"] for c in mine]
|
||||
medians[key] = statistics.median(values)
|
||||
w.writerow([key[0], key[1], " ".join(f"{v:g}" for v in values), f"{medians[key]:g}",
|
||||
sum(c["invalid_below"] for c in mine)])
|
||||
|
||||
control = []
|
||||
for run in runs:
|
||||
first = [r for r in rows if (r["series"], r["config"], r["rep"]) == (run["series"], run["config"], run["rep"])][:1]
|
||||
if first and first[0]["cpu_loadgen_pct"] != "":
|
||||
probe = run["meta"].get("host_probe_s", "")
|
||||
control.append([run["series"], run["config"], run["rep"], float(probe) if probe else None,
|
||||
round(float(first[0]["cpu_loadgen_pct"]) * 10000 / first[0]["offered_rps"])])
|
||||
if control:
|
||||
probes = [c[3] for c in control if c[3] is not None]
|
||||
probe_median = statistics.median(probes) if probes else None
|
||||
cpu_median = statistics.median(c[4] for c in control)
|
||||
with open(out / "control.csv", "w", newline="", encoding="utf-8") as f:
|
||||
w = csv.writer(f)
|
||||
w.writerow(["series", "config", "rep", "host_probe_s", "probe_deviation",
|
||||
"loadgen_cpu_ms_per_1000_requests", "cpu_deviation", "flagged"])
|
||||
flagged = set()
|
||||
for series, config, rep, probe, cpu in control:
|
||||
probe_dev = probe / probe_median - 1 if probe is not None else 0.0
|
||||
cpu_dev = cpu / cpu_median - 1
|
||||
noisy = max(abs(probe_dev), abs(cpu_dev)) > CONTROL_TOLERANCE
|
||||
if noisy:
|
||||
flagged.add((series, config, rep))
|
||||
w.writerow([series, config, rep, probe if probe is not None else "", f"{probe_dev:+.2f}", cpu,
|
||||
f"{cpu_dev:+.2f}", noisy])
|
||||
|
||||
cost = {}
|
||||
for r in rows:
|
||||
if (r["series"], r["config"], r["rep"]) in flagged or r["offered_rps"] not in COST_RATES:
|
||||
continue
|
||||
if not r["valid"] or r["error_share"] > 0:
|
||||
continue
|
||||
per = cost.setdefault((r["series"], r["config"]), {"runs": set()})
|
||||
per["runs"].add(r["rep"])
|
||||
for c in ("api", "postgres", "lb"):
|
||||
if r[f"cpu_{c}_pct"] != "":
|
||||
per.setdefault(c, []).append(float(r[f"cpu_{c}_pct"]) * 10 / r["offered_rps"])
|
||||
with open(out / "cost.csv", "w", newline="", encoding="utf-8") as f:
|
||||
w = csv.writer(f)
|
||||
w.writerow(["series", "config", "runs", "api_cpu_ms_per_request", "postgres_cpu_ms_per_request",
|
||||
"lb_cpu_ms_per_request", "rps_per_database_cpu"])
|
||||
for (series, config), per in cost.items():
|
||||
med = {c: statistics.median(per[c]) for c in ("api", "postgres", "lb") if per.get(c)}
|
||||
w.writerow([series, config, " ".join(sorted(per["runs"])),
|
||||
*(round(med[c], 2) if c in med else "" for c in ("api", "postgres", "lb")),
|
||||
round(1000 / med["postgres"]) if med.get("postgres") else ""])
|
||||
if cost:
|
||||
keys = list(cost)
|
||||
fig, ax = plt.subplots(figsize=(max(6, len(keys) * 0.9), 4.5))
|
||||
width = 0.27
|
||||
for i, c in enumerate(("api", "postgres", "lb")):
|
||||
ax.bar([j + i * width for j in range(len(keys))],
|
||||
[statistics.median(cost[k][c]) if cost[k].get(c) else 0 for k in keys], width, label=c)
|
||||
ax.set_xticks([j + width for j in range(len(keys))], [f"{s_}/{c_}" for s_, c_ in keys], rotation=30)
|
||||
ax.set_ylabel("CPU ms per request")
|
||||
ax.set_title(f"Cost per request at {'/'.join(map(str, COST_RATES))} rps (clean runs)")
|
||||
ax.grid(axis="y", alpha=0.3)
|
||||
ax.legend()
|
||||
fig.tight_layout()
|
||||
fig.savefig(out / "cost-per-request.png", dpi=120)
|
||||
plt.close(fig)
|
||||
|
||||
def median_by_offered(series, config, field):
|
||||
points, valid = {}, {}
|
||||
for r in rows:
|
||||
if r["series"] == series and r["config"] == config and r[field] != "":
|
||||
points.setdefault(r["offered_rps"], []).append(float(r[field]))
|
||||
valid[r["offered_rps"]] = valid.get(r["offered_rps"], True) and r["valid"]
|
||||
xs = sorted(points)
|
||||
return xs, [statistics.median(points[x]) for x in xs], [valid[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, valid = median_by_offered(series, name, field)
|
||||
line, = ax.plot(xs, ys, label=name)
|
||||
ax.scatter([x for x, v in zip(xs, valid) if v], [y for y, v in zip(ys, valid) if v], color=line.get_color())
|
||||
ax.scatter([x for x, v in zip(xs, valid) if not v], [y for y, v in zip(ys, valid) if not v],
|
||||
facecolors="none", edgecolors=line.get_color())
|
||||
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 (hollow: generator fell behind)")
|
||||
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]))
|
||||
Executable
+50
@@ -0,0 +1,50 @@
|
||||
#!/bin/sh
|
||||
# Level 4: scripts/rollout.sh replaces every replica at UPDATE_AT under a
|
||||
# constant write load that retries uncertain sends with the same key; then
|
||||
# every confirmed message must be in the history once.
|
||||
#
|
||||
# sh scripts/bench/rollout-under-load.sh
|
||||
#
|
||||
# Environment: RATE (50), DURATION (60s), UPDATE_AT (15), OUT (evidence/rollout).
|
||||
# Times come from the Docker VM clock, as in failover.sh.
|
||||
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
|
||||
# Built beforehand, as by a delivery pipeline: the update replaces replicas.
|
||||
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"
|
||||
# A margin for the host clock, which may run ahead of the VM's.
|
||||
since=$(date -u -d '-10 seconds' +%Y-%m-%dT%H:%M:%SZ)
|
||||
old=$(docker compose ps -q api | cut -c1-12 | tr '\n' ' ')
|
||||
|
||||
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_host=$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)
|
||||
status=0
|
||||
sh scripts/rollout.sh >"$dir/rollout.log" 2>&1 || status=$?
|
||||
finished_host=$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)
|
||||
wait "$generator" || echo "generator reported a failed history check, see $dir/loadgen.log"
|
||||
|
||||
new=""
|
||||
for id in $(docker compose ps -q api); do
|
||||
new="$new{\"container\": \"$(printf '%s' "$id" | cut -c1-12)\", \"started_vm_utc\": \"$(docker inspect --format '{{.State.StartedAt}}' "$id")\"}, "
|
||||
done
|
||||
printf '{\n "rollout_exit_code": %s,\n "old_containers": "%s",\n "new_containers": [%s],\n "command_started_host_utc": "%s",\n "command_finished_host_utc": "%s"\n}\n' \
|
||||
"$status" "$old" "${new%, }" "$started_host" "$finished_host" >"$dir/update.json"
|
||||
docker compose logs --no-color --timestamps --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"
|
||||
Executable
+88
@@ -0,0 +1,88 @@
|
||||
#!/bin/sh
|
||||
# Track 1: every configuration of the given series files, each on a fresh
|
||||
# stand, under one grid of offered rates. Repeats are interleaved (repeat 1
|
||||
# of every configuration, then repeat 2), so a slow spell of the host does not
|
||||
# fall on one configuration.
|
||||
#
|
||||
# RATES=400,800,1200 sh scripts/bench/run-series.sh scripts/bench/series/A.conf [...]
|
||||
#
|
||||
# Environment: RATES (required), REPEATS (3), STEP (30s), WARMUP (30s),
|
||||
# STOP_ON_FAIL (1: end a ladder at its first failing step), OUT
|
||||
# (evidence/track1/raw). Results: <OUT>/<series>/<config>/rep<k>/.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/../.."
|
||||
. scripts/bench/lib.sh
|
||||
|
||||
[ $# -gt 0 ] || { echo "usage: RATES=... run-series.sh <series.conf>..." >&2; exit 2; }
|
||||
: "${RATES:?set RATES, the offered requests per second of the steps, e.g. 400,800,1200}"
|
||||
repeats=${REPEATS:-3}
|
||||
step=${STEP:-30s}
|
||||
warmup=${WARMUP:-30s}
|
||||
out=${OUT:-evidence/track1/raw}
|
||||
stop=
|
||||
[ "${STOP_ON_FAIL:-1}" = 1 ] && stop=-stop-on-fail
|
||||
|
||||
# Fixed for every configuration; the API, its pool, maxconn and the database
|
||||
# CPU come from the series line.
|
||||
export LB_CPUS=1.0 PG_MEMORY=1G LOADGEN_CPUS=2.0
|
||||
export MSYS_NO_PATHCONV=1
|
||||
|
||||
# One series line: name replicas cpus memory gomemlimit pool maxconn pg_cpus.
|
||||
run_config() {
|
||||
series=$1 rep=$2 name=$3 replicas=$4 cpus=$5 memory=$6 gomemlimit=$7 pool=$8 maxconn=$9 pg_cpus=${10}
|
||||
dir=$out/$series/$name/rep$rep
|
||||
rm -rf "$dir"
|
||||
mkdir -p "$dir"
|
||||
echo "== $series/$name rep $rep: $replicas x $cpus CPU / $memory, pool $pool, maxconn $maxconn, PostgreSQL $pg_cpus CPU"
|
||||
export API_REPLICAS=$replicas API_CPUS=$cpus API_MEMORY=$memory API_GOMEMLIMIT=$gomemlimit \
|
||||
DB_MAX_CONNS=$pool API_MAXCONN=$maxconn PG_CPUS=$pg_cpus
|
||||
|
||||
docker compose down -v --remove-orphans >/dev/null 2>&1
|
||||
if ! docker compose up -d --build --wait >"$dir/up.log" 2>&1; then
|
||||
echo " the stand did not start, see $dir/up.log" >&2
|
||||
exit 1
|
||||
fi
|
||||
meta "$dir/meta.json" "series=$series" "config=$name" "repeat=$rep" \
|
||||
"api_replicas=$replicas" "api_cpus=$cpus" "api_memory=$memory" "gomemlimit=$gomemlimit" \
|
||||
"db_max_conns=$pool" "api_maxconn=$maxconn" "pg_cpus=$pg_cpus" "pg_memory=$PG_MEMORY" \
|
||||
"lb_cpus=$LB_CPUS" "loadgen_cpus=$LOADGEN_CPUS" "rates=$RATES" "step=$step" "warmup=$warmup" \
|
||||
"stop_on_fail=${STOP_ON_FAIL:-1}" "host_probe_s=$(host_probe)"
|
||||
|
||||
sample_docker_stats "$dir/docker-stats.jsonl" &
|
||||
stats=$!
|
||||
sample_postgres "$dir/postgres.jsonl" &
|
||||
pg=$!
|
||||
# stdin closed: `compose run` would otherwise read it.
|
||||
BENCH_OUT=$(abspath "$dir") docker compose --profile bench run --rm loadgen bench \
|
||||
-rates "$RATES" -step "$step" -warmup "$warmup" -scrape $stop >"$dir/loadgen.log" 2>&1 </dev/null ||
|
||||
echo " loadgen failed, see $dir/loadgen.log"
|
||||
kill "$stats" "$pg" 2>/dev/null || true
|
||||
wait "$stats" "$pg" 2>/dev/null || true
|
||||
docker compose logs --no-color --timestamps lb api 2>&1 | state_log >"$dir/compose.log"
|
||||
gzip -9 "$dir"/*.jsonl
|
||||
grep '^step' "$dir/loadgen.log" || true
|
||||
}
|
||||
|
||||
for conf in "$@"; do
|
||||
[ -r "$conf" ] || { echo "cannot read $conf" >&2; exit 2; }
|
||||
bad=$(grep -v '^#' "$conf" | awk 'NF && NF != 8')
|
||||
[ -z "$bad" ] || { echo "$conf: a line needs 8 fields: $bad" >&2; exit 2; }
|
||||
done
|
||||
docker compose --profile bench build loadgen >/dev/null
|
||||
default_ifs=$IFS
|
||||
newline='
|
||||
'
|
||||
for rep in $(seq 1 "$repeats"); do
|
||||
for conf in "$@"; do
|
||||
lines=$(grep -v '^#' "$conf" | sed '/^[[:space:]]*$/d')
|
||||
IFS=$newline
|
||||
for line in $lines; do
|
||||
IFS=$default_ifs
|
||||
# shellcheck disable=SC2086 # the line splits into the fields
|
||||
run_config "$(basename "$conf" .conf)" "$rep" $line
|
||||
done
|
||||
IFS=$default_ifs
|
||||
done
|
||||
done
|
||||
docker compose down -v --remove-orphans >/dev/null 2>&1
|
||||
echo "results in $out"
|
||||
@@ -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 memory gomemlimit pool maxconn pg_cpus
|
||||
A1 1 2.0 1024M 920MiB 10 0 1.0
|
||||
A2 2 1.0 512M 460MiB 10 0 1.0
|
||||
A4 4 0.5 256M 230MiB 10 0 1.0
|
||||
@@ -0,0 +1,5 @@
|
||||
# Series A': the budget of series A with the total pool fixed at 20 connections;
|
||||
# A'2 equals A2.
|
||||
# name replicas cpus memory gomemlimit pool maxconn pg_cpus
|
||||
Ap1 1 2.0 1024M 920MiB 20 0 1.0
|
||||
Ap4 4 0.5 256M 230MiB 5 0 1.0
|
||||
@@ -0,0 +1,5 @@
|
||||
# Series B: replicas of 1 CPU, 512 MiB and pool 10 added one by one; B2 equals A2.
|
||||
# name replicas cpus memory gomemlimit pool maxconn pg_cpus
|
||||
B1 1 1.0 512M 460MiB 10 0 1.0
|
||||
B3 3 1.0 512M 460MiB 10 0 1.0
|
||||
B4 4 1.0 512M 460MiB 10 0 1.0
|
||||
@@ -0,0 +1,10 @@
|
||||
# Improvement C: maxconn per replica on the balancer, before (0, no limit) and
|
||||
# after (20) on 1 and 4 replicas, under an overload ladder (STOP_ON_FAIL=0);
|
||||
# 10 and 40 show how much the value matters.
|
||||
# name replicas cpus memory gomemlimit pool maxconn pg_cpus
|
||||
R1m0 1 1.0 512M 460MiB 10 0 1.0
|
||||
R1m20 1 1.0 512M 460MiB 10 20 1.0
|
||||
R4m0 4 1.0 512M 460MiB 10 0 1.0
|
||||
R4m20 4 1.0 512M 460MiB 10 20 1.0
|
||||
R1m10 1 1.0 512M 460MiB 10 10 1.0
|
||||
R1m40 1 1.0 512M 460MiB 10 40 1.0
|
||||
@@ -0,0 +1,6 @@
|
||||
# Control: A2 next to A2 with twice the database CPU, interleaved, run with
|
||||
# STOP_ON_FAIL=0 so that one noisy step does not end a ladder. If the database
|
||||
# is the bottleneck, the capacity rises.
|
||||
# name replicas cpus memory gomemlimit pool maxconn pg_cpus
|
||||
A2 2 1.0 512M 460MiB 10 0 1.0
|
||||
A2pg2 2 1.0 512M 460MiB 10 0 2.0
|
||||
@@ -0,0 +1,75 @@
|
||||
-- EXPLAIN evidence for the message history query (make explain).
|
||||
--
|
||||
-- Everything runs in one transaction that is rolled back: it seeds 12 000
|
||||
-- messages in one chat and 90 000 in 300 other chats, so the plan is measured
|
||||
-- on a realistic volume without leaving data on the stand. The PREPARE text
|
||||
-- is the statement of Messages.ListByChat in internal/chat/store/postgres.go;
|
||||
-- keep them identical.
|
||||
\set ON_ERROR_STOP on
|
||||
\pset pager off
|
||||
BEGIN;
|
||||
|
||||
SELECT uuidv7() AS author \gset
|
||||
SELECT uuidv7() AS big_chat \gset
|
||||
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES (:'author', 'explain_' || substr(md5(random()::text), 1, 12), 'EXPLAIN', 'not-a-password-hash',
|
||||
uuid_extract_timestamp(:'author'));
|
||||
|
||||
CREATE TEMP TABLE noise_chats ON COMMIT DROP AS
|
||||
SELECT uuidv7() AS id FROM generate_series(1, 300);
|
||||
|
||||
INSERT INTO chats (id, title, created_at)
|
||||
SELECT :'big_chat'::uuid, 'explain: big chat', uuid_extract_timestamp(:'big_chat')
|
||||
UNION ALL
|
||||
SELECT id, 'explain: other chat', uuid_extract_timestamp(id) FROM noise_chats;
|
||||
|
||||
INSERT INTO chat_members (chat_id, user_id)
|
||||
SELECT id, :'author' FROM chats WHERE title LIKE 'explain:%';
|
||||
|
||||
-- Rows are inserted ordered by n, so the messages of all chats interleave in
|
||||
-- the heap as they would under real traffic; ids stay increasing per chat.
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT id, chat_id, :'author', 'message ' || n, uuid_extract_timestamp(id)
|
||||
FROM (
|
||||
SELECT uuidv7() AS id, chat_id, n
|
||||
FROM (
|
||||
SELECT :'big_chat'::uuid AS chat_id, n FROM generate_series(1, 12000) AS n
|
||||
UNION ALL
|
||||
SELECT c.id, n FROM noise_chats AS c, generate_series(1, 300) AS n
|
||||
) AS planned
|
||||
ORDER BY n
|
||||
) AS generated;
|
||||
|
||||
ANALYZE users, chats, chat_members, messages;
|
||||
|
||||
SELECT (SELECT count(*) FROM messages WHERE chat_id = :'big_chat') AS big_chat_messages,
|
||||
(SELECT count(*) FROM messages) AS all_messages;
|
||||
|
||||
PREPARE history(uuid, uuid, int) AS
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
AND id > COALESCE($2, '00000000-0000-0000-0000-000000000000'::uuid)
|
||||
ORDER BY id
|
||||
LIMIT $3;
|
||||
|
||||
\echo
|
||||
\echo == First page: no cursor, limit 50 (+1 row that tells whether a next page exists)
|
||||
EXPLAIN (ANALYZE, BUFFERS) EXECUTE history(:'big_chat', NULL, 51);
|
||||
|
||||
SELECT id AS deep_cursor FROM messages WHERE chat_id = :'big_chat' ORDER BY id OFFSET 10000 LIMIT 1 \gset
|
||||
\echo
|
||||
\echo == Deep page: cursor after the 10 001st message of the chat
|
||||
EXPLAIN (ANALYZE, BUFFERS) EXECUTE history(:'big_chat', :'deep_cursor', 51);
|
||||
|
||||
\echo
|
||||
\echo == For contrast, OFFSET pagination of the same page reads every skipped row
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = :'big_chat'
|
||||
ORDER BY id
|
||||
OFFSET 10001 LIMIT 51;
|
||||
|
||||
ROLLBACK;
|
||||
Executable
+42
@@ -0,0 +1,42 @@
|
||||
#!/bin/sh
|
||||
# Creates the local credentials of the compose stand in ./secrets, which git
|
||||
# ignores. Existing secrets are kept: PostgreSQL applies its password only
|
||||
# when the volume is first initialised, so a new password would lock the API
|
||||
# out of an existing database. To start over: make destroy, then delete
|
||||
# ./secrets and run this again.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
files="postgres_password database_url valkey_auth.conf session_store_url"
|
||||
present=0
|
||||
for f in $files; do
|
||||
if [ -e "secrets/$f" ]; then
|
||||
present=$((present + 1))
|
||||
fi
|
||||
done
|
||||
if [ "$present" -eq 4 ]; then
|
||||
echo "secrets already exist in ./secrets, kept"
|
||||
exit 0
|
||||
fi
|
||||
if [ "$present" -ne 0 ]; then
|
||||
echo "./secrets is incomplete: delete it (and run make destroy if the stand holds data), then run again" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 24 random bytes as hex: URL-safe without escaping.
|
||||
random() {
|
||||
od -An -tx1 -N24 /dev/urandom | tr -d ' \n'
|
||||
}
|
||||
pg=$(random)
|
||||
kv=$(random)
|
||||
|
||||
# The directory is private; the files stay readable for the unprivileged
|
||||
# users inside the containers, which see them through bind mounts.
|
||||
umask 022
|
||||
mkdir -p secrets
|
||||
chmod 700 secrets
|
||||
printf '%s\n' "$pg" > secrets/postgres_password
|
||||
printf 'postgres://messenger:%s@postgres:5432/messenger?sslmode=disable\n' "$pg" > secrets/database_url
|
||||
printf 'requirepass %s\n' "$kv" > secrets/valkey_auth.conf
|
||||
printf 'redis://:%s@valkey:6379/0\n' "$kv" > secrets/session_store_url
|
||||
echo "created ./secrets"
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
# Which container answers under which X-Instance-Id.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
printf '%-12s %-14s %-8s %-16s %s\n' CONTAINER NAME STATE X-INSTANCE-ID IMAGE
|
||||
sh scripts/api-instances.sh | while read -r id name state alias image; do
|
||||
printf '%-12s %-14s %-8s %-16s %s\n' "$id" "$name" "$state" "$alias" "$image"
|
||||
done
|
||||
@@ -0,0 +1,5 @@
|
||||
@echo off
|
||||
rem Windows entry point of scripts/restart.sh: tests/resilience.py starts the
|
||||
rem hook without a shell, and Windows cannot execute a .sh file directly.
|
||||
sh "%~dp0restart.sh"
|
||||
exit /b %errorlevel%
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
# Restart hook of `make test-persistence`: stops the whole stand gracefully and
|
||||
# starts the same containers again; volumes are kept.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose stop
|
||||
docker compose up -d --wait
|
||||
Executable
+44
@@ -0,0 +1,44 @@
|
||||
#!/bin/sh
|
||||
# Rolling update of the API with docker rollout (github.com/wowu/docker-rollout,
|
||||
# MIT): new replicas start next to the old ones, and the old ones go once all
|
||||
# new ones are healthy; if one is not, the new ones are removed instead.
|
||||
#
|
||||
# With a stopped replica docker rollout would replace only that one and leave
|
||||
# two versions running, so the script refuses. The migrate container is
|
||||
# recreated from the new image without starting: the `up` of docker rollout
|
||||
# then applies the new migrations once, before any new replica starts.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
idle=$(docker compose ps -aq --status exited --status created --status paused --status dead api)
|
||||
if [ -n "$idle" ]; then
|
||||
echo "some API replicas are not running; start them first: docker compose start api" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
version=v0.14
|
||||
checksum=cdeaba6ae9eee3b0b606286e585bbda6787283d801a6ad6d9b9d2bc347fda05b
|
||||
tool=bin/docker-rollout
|
||||
|
||||
if ! printf '%s %s\n' "$checksum" "$tool" | sha256sum -c - >/dev/null 2>&1; then
|
||||
mkdir -p bin
|
||||
curl -fsSL -o "$tool.download" "https://github.com/wowu/docker-rollout/releases/download/$version/docker-rollout"
|
||||
if ! printf '%s %s\n' "$checksum" "$tool.download" | sha256sum -c - >/dev/null 2>&1; then
|
||||
rm -f "$tool.download"
|
||||
echo "docker-rollout $version: checksum mismatch, not used" >&2
|
||||
exit 1
|
||||
fi
|
||||
mv "$tool.download" "$tool"
|
||||
fi
|
||||
|
||||
docker compose build api
|
||||
docker compose up --no-start --no-deps --force-recreate migrate
|
||||
# Run through sh: Windows cannot use the script as a docker CLI plugin.
|
||||
if ! sh "$tool" rollout --wait-after-healthy 4 api; then
|
||||
# A failed migration leaves the new containers created but not started.
|
||||
created=$(docker compose ps -aq --status created api)
|
||||
if [ -n "$created" ]; then
|
||||
docker rm $created >/dev/null
|
||||
fi
|
||||
exit 1
|
||||
fi
|
||||
@@ -0,0 +1,5 @@
|
||||
@echo off
|
||||
rem Windows entry point of scripts/stop-one.sh: tests/resilience.py starts the
|
||||
rem hook without a shell, and Windows cannot execute a .sh file directly.
|
||||
sh "%~dp0stop-one.sh"
|
||||
exit /b %errorlevel%
|
||||
Executable
+27
@@ -0,0 +1,27 @@
|
||||
#!/bin/sh
|
||||
# Failover hook of `make test-failover`: gracefully stops the one running API
|
||||
# replica whose X-Instance-Id is $TARGET_INSTANCE_ID, and nothing else.
|
||||
# Restore it with: docker compose start api
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
target=${TARGET_INSTANCE_ID:-}
|
||||
case "$target" in
|
||||
'' | *[!0-9a-f]*)
|
||||
echo "TARGET_INSTANCE_ID must be the 16 lowercase hex characters of an X-Instance-Id" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
if [ ${#target} -ne 16 ]; then
|
||||
echo "TARGET_INSTANCE_ID must be the 16 lowercase hex characters of an X-Instance-Id" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
matches=$(sh scripts/api-instances.sh | awk -v t="$target" '$3 == "running" && $4 == t { print $1 }')
|
||||
count=$(printf '%s\n' "$matches" | grep -c . || true)
|
||||
if [ "$count" -ne 1 ]; then
|
||||
echo "expected one running API replica with X-Instance-Id $target, found $count" >&2
|
||||
exit 2
|
||||
fi
|
||||
docker stop "$matches" >/dev/null
|
||||
echo "stopped API container $matches (X-Instance-Id $target)"
|
||||
Reference in New Issue
Block a user