#!/bin/bash set -eu cd "$(dirname "$0")/.." BASE_URL="${BASE_URL:-http://localhost:8080}" DURATION="${DURATION:-30}" CONCURRENCY="${CONCURRENCY:-16}" RUNS="${RUNS:-3}" OUT="${OUT:-evidence/scaling}" CONFIGS="${CONFIGS:-A1:1:1.00:512M A2:2:0.50:256M A4:4:0.25:128M B1:1:0.50:256M B4:4:0.50:256M}" mkdir -p "$OUT" wait_instances() { local want=$1 deadline=$((SECONDS + 90)) seen while [ $SECONDS -lt $deadline ]; do seen=$(for _ in $(seq 1 $((want * 4))); do curl -s -D - -o /dev/null "$BASE_URL/health/ready" | tr -d '\r' | awk -F': ' 'tolower($1)=="x-instance-id"{print $2}' done | sort -u | grep -c . || true) [ "$seen" -eq "$want" ] && return 0 sleep 2 done echo "ERROR: expected $want instances, saw $seen" >&2 return 1 } for cfg in $CONFIGS; do IFS=: read -r label replicas cpus mem <<< "$cfg" export REPLICAS=$replicas API_CPUS=$cpus API_MEM=$mem files=(-f compose.yaml -f infra/scaling/limits.yaml) [ "$replicas" -eq 4 ] && files+=(-f infra/scaling/replicas-4.yaml) apis=$(seq -f "api-%g" 1 "$replicas" | tr '\n' ' ') echo "=== $label: $replicas x ${cpus} CPU / $mem ===" docker compose "${files[@]}" up -d --force-recreate $apis >/dev/null 2>&1 for extra in api-2 api-3 api-4; do n=${extra#api-} [ "$n" -gt "$replicas" ] && docker compose -f compose.yaml -f infra/scaling/limits.yaml -f infra/scaling/replicas-4.yaml stop "$extra" >/dev/null 2>&1 || true done docker compose "${files[@]}" up -d --no-deps --force-recreate nginx >/dev/null 2>&1 wait_instances "$replicas" { echo "config=$label replicas=$replicas api_cpus=$cpus api_mem=$mem concurrency=$CONCURRENCY duration=$DURATION" for c in $apis; do docker inspect --format "$c NanoCpus={{.HostConfig.NanoCpus}} Memory={{.HostConfig.Memory}}" \ "$(docker compose "${files[@]}" ps -q "$c")" done } > "$OUT/${label}_limits.txt" python3 tests/load.py --base-url "$BASE_URL" --duration 5 --concurrency "$CONCURRENCY" >/dev/null since=$(date -u +%Y-%m-%dT%H:%M:%SZ) for run in $(seq 1 "$RUNS"); do (sleep $((DURATION / 2)); docker stats --no-stream --format '{{.Name}} {{.CPUPerc}} {{.MemUsage}}' \ > "$OUT/${label}_run${run}_stats.txt") & python3 tests/load.py --base-url "$BASE_URL" --duration "$DURATION" --concurrency "$CONCURRENCY" \ --output "$OUT/${label}_run${run}.json" >/dev/null wait python3 -c "import json;d=json.load(open('$OUT/${label}_run${run}.json'));l=d['successful_latency_ms'];print(' run $run: rps=%s err=%s p50=%s p95=%s p99=%s'%(d['successful_rps'],d['failed_requests'],l['p50'],l['p95'],l['p99']))" done docker compose "${files[@]}" logs --since "$since" nginx 2>&1 \ | grep -E '" [45][0-9][0-9] |\[(error|warn)\]' > "$OUT/${label}_nginx_problems.txt" || true done export REPLICAS=2 API_CPUS=0.50 API_MEM=256M docker compose -f compose.yaml -f infra/scaling/replicas-4.yaml rm -sf api-3 api-4 >/dev/null 2>&1 || true docker compose up -d --force-recreate api-1 api-2 nginx >/dev/null 2>&1 wait_instances 2 python3 student-tests/scaling_summary.py "$OUT"