Add lab 3 scaling research and database bottleneck evidence
This commit is contained in:
@@ -0,0 +1,204 @@
|
||||
// A fixed-rate HTTP workload for the lab 3 scaling experiment.
|
||||
// Credentials are read from a local file and never written to output.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type credentials struct {
|
||||
Token string `json:"token"`
|
||||
ChatID string `json:"chat_id"`
|
||||
}
|
||||
|
||||
type result struct {
|
||||
kind string
|
||||
status int
|
||||
latency time.Duration
|
||||
lag time.Duration
|
||||
full time.Duration
|
||||
instanceID string
|
||||
}
|
||||
|
||||
type percentiles struct {
|
||||
P50 float64 `json:"p50"`
|
||||
P95 float64 `json:"p95"`
|
||||
P99 float64 `json:"p99"`
|
||||
}
|
||||
|
||||
func quantiles(values []float64) percentiles {
|
||||
if len(values) == 0 {
|
||||
return percentiles{}
|
||||
}
|
||||
sort.Float64s(values)
|
||||
get := func(p float64) float64 {
|
||||
index := int(math.Ceil(p*float64(len(values)))) - 1
|
||||
return math.Round(values[index]*1000) / 1000
|
||||
}
|
||||
return percentiles{P50: get(.50), P95: get(.95), P99: get(.99)}
|
||||
}
|
||||
|
||||
func main() {
|
||||
baseURL := flag.String("base-url", "", "public load balancer URL")
|
||||
authFile := flag.String("auth-file", "", "local JSON file with token and chat_id")
|
||||
rate := flag.Float64("rate", 0, "scheduled requests per second")
|
||||
duration := flag.Duration("duration", 20*time.Second, "scheduling window")
|
||||
maxInFlight := flag.Int("max-inflight", 256, "maximum concurrent requests")
|
||||
timeout := flag.Duration("timeout", 5*time.Second, "per-request timeout")
|
||||
flag.Parse()
|
||||
if *baseURL == "" || *authFile == "" || *rate <= 0 || *duration <= 0 || *maxInFlight <= 0 || *timeout <= 0 {
|
||||
fmt.Fprintln(os.Stderr, "base-url, auth-file, positive rate, duration, max-inflight and timeout are required")
|
||||
os.Exit(2)
|
||||
}
|
||||
content, err := os.ReadFile(*authFile)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "could not read auth file")
|
||||
os.Exit(2)
|
||||
}
|
||||
var auth credentials
|
||||
if err := json.Unmarshal(content, &auth); err != nil || auth.Token == "" || auth.ChatID == "" {
|
||||
fmt.Fprintln(os.Stderr, "invalid auth file")
|
||||
os.Exit(2)
|
||||
}
|
||||
nonce := make([]byte, 8)
|
||||
if _, err := rand.Read(nonce); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "could not create workload identifier")
|
||||
os.Exit(2)
|
||||
}
|
||||
runID := hex.EncodeToString(nonce)
|
||||
payload, _ := json.Marshal(map[string]string{"text": "grade5-" + runID})
|
||||
transport := &http.Transport{
|
||||
MaxIdleConns: *maxInFlight,
|
||||
MaxIdleConnsPerHost: *maxInFlight,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
}
|
||||
client := &http.Client{Transport: transport}
|
||||
defer transport.CloseIdleConnections()
|
||||
url := strings.TrimRight(*baseURL, "/") + "/api/v1/chats/" + auth.ChatID + "/messages"
|
||||
count := int(math.Round(*rate * duration.Seconds()))
|
||||
if count <= 0 || count > 2_000_000 {
|
||||
fmt.Fprintln(os.Stderr, "request count is outside 1..2000000")
|
||||
os.Exit(2)
|
||||
}
|
||||
results := make(chan result, count)
|
||||
semaphore := make(chan struct{}, *maxInFlight)
|
||||
var workers sync.WaitGroup
|
||||
started := time.Now()
|
||||
for i := 0; i < count; i++ {
|
||||
planned := started.Add(time.Duration(float64(i) / *rate * float64(time.Second)))
|
||||
if delay := time.Until(planned); delay > 0 {
|
||||
time.Sleep(delay)
|
||||
}
|
||||
lag := time.Since(planned)
|
||||
if lag > 250*time.Millisecond {
|
||||
results <- result{kind: "dropped_scheduler", lag: lag}
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case semaphore <- struct{}{}:
|
||||
default:
|
||||
results <- result{kind: "dropped_inflight", lag: lag}
|
||||
continue
|
||||
}
|
||||
workers.Add(1)
|
||||
go func(sequence int, planned time.Time) {
|
||||
defer workers.Done()
|
||||
defer func() { <-semaphore }()
|
||||
scheduleLag := time.Since(planned)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
results <- result{kind: "client_request", lag: scheduleLag}
|
||||
return
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+auth.Token)
|
||||
req.Header.Set("Idempotency-Key", "g5-"+runID+"-"+strconv.Itoa(sequence))
|
||||
requestStarted := time.Now()
|
||||
response, err := client.Do(req)
|
||||
if err != nil {
|
||||
kind := "connection"
|
||||
var networkError net.Error
|
||||
if errors.Is(err, context.DeadlineExceeded) || errors.As(err, &networkError) && networkError.Timeout() {
|
||||
kind = "timeout"
|
||||
}
|
||||
results <- result{kind: kind, latency: time.Since(requestStarted), lag: scheduleLag, full: time.Since(planned)}
|
||||
return
|
||||
}
|
||||
_, readErr := io.Copy(io.Discard, io.LimitReader(response.Body, 1<<20))
|
||||
response.Body.Close()
|
||||
if readErr != nil {
|
||||
results <- result{kind: "response_read", status: response.StatusCode, latency: time.Since(requestStarted), lag: scheduleLag, full: time.Since(planned)}
|
||||
return
|
||||
}
|
||||
results <- result{kind: "response", status: response.StatusCode, latency: time.Since(requestStarted), lag: scheduleLag, full: time.Since(planned), instanceID: response.Header.Get("X-Instance-Id")}
|
||||
}(i, planned)
|
||||
}
|
||||
workers.Wait()
|
||||
close(results)
|
||||
wall := time.Since(started)
|
||||
counts := map[string]int{}
|
||||
instances := map[string]int{}
|
||||
latencies := make([]float64, 0, count)
|
||||
lags := make([]float64, 0, count)
|
||||
fullLatencies := make([]float64, 0, count)
|
||||
success := 0
|
||||
for item := range results {
|
||||
if item.full > 0 {
|
||||
fullLatencies = append(fullLatencies, float64(item.full)/float64(time.Millisecond))
|
||||
}
|
||||
if item.kind == "response" && item.status == http.StatusCreated {
|
||||
success++
|
||||
latencies = append(latencies, float64(item.latency)/float64(time.Millisecond))
|
||||
if item.instanceID != "" {
|
||||
instances[item.instanceID]++
|
||||
}
|
||||
} else if item.kind == "response" {
|
||||
counts["http_"+strconv.Itoa(item.status)]++
|
||||
} else {
|
||||
counts[item.kind]++
|
||||
}
|
||||
lags = append(lags, float64(item.lag)/float64(time.Millisecond))
|
||||
}
|
||||
report := map[string]any{
|
||||
"workload": "fixed-rate POST messages, unique Idempotency-Key, no retries",
|
||||
"started_at_utc": started.UTC().Format(time.RFC3339Nano),
|
||||
"run_id": runID,
|
||||
"scheduled_rps": *rate,
|
||||
"scheduled_duration_s": duration.Seconds(),
|
||||
"wall_duration_s": math.Round(wall.Seconds()*1000) / 1000,
|
||||
"scheduled_requests": count,
|
||||
"successful_requests": success,
|
||||
"failure_counts": counts,
|
||||
"success_ratio": math.Round(float64(success)/float64(count)*1_000_000) / 1_000_000,
|
||||
"successful_rps_window": math.Round(float64(success)/duration.Seconds()*1000) / 1000,
|
||||
"successful_rps_wall": math.Round(float64(success)/wall.Seconds()*1000) / 1000,
|
||||
"success_latency_ms": quantiles(latencies),
|
||||
"schedule_lag_ms": quantiles(lags),
|
||||
"completed_full_latency_ms": quantiles(fullLatencies),
|
||||
"instance_responses": instances,
|
||||
"max_inflight": *maxInFlight,
|
||||
"request_timeout_s": timeout.Seconds(),
|
||||
}
|
||||
output, _ := json.MarshalIndent(report, "", " ")
|
||||
fmt.Println(string(output))
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
{
|
||||
"seed_messages": 100000,
|
||||
"warmup_seconds": 10,
|
||||
"warmup_rate": "target",
|
||||
"settle_seconds": 3,
|
||||
"max_inflight": 1024,
|
||||
"runs": [
|
||||
{
|
||||
"name": "commit-0-repeat1",
|
||||
"phase": "wal_group_commit",
|
||||
"replicas": 2,
|
||||
"api_total_cpus": 4,
|
||||
"api_total_memory_mib": 1024,
|
||||
"pool_max_conns": 8,
|
||||
"commit_delay_us": 0,
|
||||
"rate": 3000,
|
||||
"duration_seconds": 30
|
||||
},
|
||||
{
|
||||
"name": "commit-1000-repeat2",
|
||||
"phase": "wal_group_commit",
|
||||
"replicas": 2,
|
||||
"api_total_cpus": 4,
|
||||
"api_total_memory_mib": 1024,
|
||||
"pool_max_conns": 8,
|
||||
"commit_delay_us": 1000,
|
||||
"rate": 3000,
|
||||
"duration_seconds": 30
|
||||
},
|
||||
{
|
||||
"name": "commit-1000-repeat3",
|
||||
"phase": "wal_group_commit",
|
||||
"replicas": 2,
|
||||
"api_total_cpus": 4,
|
||||
"api_total_memory_mib": 1024,
|
||||
"pool_max_conns": 8,
|
||||
"commit_delay_us": 1000,
|
||||
"rate": 3000,
|
||||
"duration_seconds": 30
|
||||
},
|
||||
{
|
||||
"name": "commit-0-repeat4",
|
||||
"phase": "wal_group_commit",
|
||||
"replicas": 2,
|
||||
"api_total_cpus": 4,
|
||||
"api_total_memory_mib": 1024,
|
||||
"pool_max_conns": 8,
|
||||
"commit_delay_us": 0,
|
||||
"rate": 3000,
|
||||
"duration_seconds": 30
|
||||
},
|
||||
{
|
||||
"name": "commit-0-repeat5",
|
||||
"phase": "wal_group_commit",
|
||||
"replicas": 2,
|
||||
"api_total_cpus": 4,
|
||||
"api_total_memory_mib": 1024,
|
||||
"pool_max_conns": 8,
|
||||
"commit_delay_us": 0,
|
||||
"rate": 3000,
|
||||
"duration_seconds": 30
|
||||
},
|
||||
{
|
||||
"name": "commit-1000-repeat6",
|
||||
"phase": "wal_group_commit",
|
||||
"replicas": 2,
|
||||
"api_total_cpus": 4,
|
||||
"api_total_memory_mib": 1024,
|
||||
"pool_max_conns": 8,
|
||||
"commit_delay_us": 1000,
|
||||
"rate": 3000,
|
||||
"duration_seconds": 30
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Repeatable, disposable Compose experiment for lab 3 scaling research."""
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[3]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client # noqa: E402
|
||||
|
||||
|
||||
def utc_now():
|
||||
return datetime.now(timezone.utc).isoformat(timespec="milliseconds")
|
||||
|
||||
|
||||
def command(argv, *, timeout=180, allow_failure=False, log=None):
|
||||
result = subprocess.run(argv, cwd=ROOT, capture_output=True, text=True, timeout=timeout)
|
||||
if log is not None:
|
||||
log.write_text(result.stdout + result.stderr)
|
||||
if result.returncode and not allow_failure:
|
||||
detail = (result.stderr or result.stdout)[-1200:]
|
||||
raise RuntimeError("command failed (%s): %s" % (result.returncode, detail))
|
||||
return result.stdout
|
||||
|
||||
|
||||
def free_port():
|
||||
with socket.socket() as listener:
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
return listener.getsockname()[1]
|
||||
|
||||
|
||||
def write_override(path, *, lb_port, replicas, total_cpus, total_memory_mib, postgres_cpus,
|
||||
database_url_file=None):
|
||||
if replicas not in (1, 2, 4) or total_cpus <= 0 or total_memory_mib < 256:
|
||||
raise ValueError("invalid replica count or API budget")
|
||||
if total_memory_mib % replicas:
|
||||
raise ValueError("API memory budget must divide evenly between replicas")
|
||||
per_cpu = total_cpus / replicas
|
||||
per_memory = total_memory_mib // replicas
|
||||
source = (
|
||||
"services:\n"
|
||||
" api:\n"
|
||||
" scale: %d\n"
|
||||
" cpus: \"%.3f\"\n"
|
||||
" mem_limit: %dm\n"
|
||||
" secrets: !override\n"
|
||||
" - source: database_url_api\n"
|
||||
" target: database_url\n"
|
||||
" lb:\n"
|
||||
" ports: !override\n"
|
||||
" - \"127.0.0.1:%d:8080\"\n"
|
||||
" postgres:\n"
|
||||
" cpus: \"%.3f\"\n"
|
||||
" ports: !reset []\n"
|
||||
" command: [\"postgres\", \"-c\", \"shared_preload_libraries=pg_stat_statements\", \"-c\", \"track_io_timing=on\", \"-c\", \"track_wal_io_timing=on\"]\n"
|
||||
% (replicas, per_cpu, per_memory, lb_port, postgres_cpus)
|
||||
)
|
||||
if database_url_file:
|
||||
source += "secrets:\n database_url_api:\n file: %s\n" % json.dumps(str(database_url_file))
|
||||
path.write_text(source)
|
||||
|
||||
|
||||
def write_database_url(path, pool_max_conns):
|
||||
original = (ROOT / "secrets" / "database_url").read_text().strip()
|
||||
if pool_max_conns is None:
|
||||
path.write_text(original + "\n")
|
||||
else:
|
||||
if not isinstance(pool_max_conns, int) or pool_max_conns <= 0:
|
||||
raise ValueError("pool_max_conns must be positive")
|
||||
parsed = urlsplit(original)
|
||||
query = dict(parse_qsl(parsed.query, keep_blank_values=True))
|
||||
query["pool_max_conns"] = str(pool_max_conns)
|
||||
path.write_text(urlunsplit(parsed._replace(query=urlencode(query))) + "\n")
|
||||
os.chmod(path, 0o600)
|
||||
|
||||
|
||||
def psql(compose, sql, *, timeout=60):
|
||||
output = command(compose + ["exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-v", "ON_ERROR_STOP=1", "-Atc", sql], timeout=timeout)
|
||||
return output.strip()
|
||||
|
||||
|
||||
def message_count(compose):
|
||||
return int(psql(compose, "SELECT count(*) FROM messages"))
|
||||
|
||||
|
||||
def reset_dataset(compose, chat_id, user_id, seed_count):
|
||||
chat_id, user_id = str(UUID(chat_id)), str(UUID(user_id))
|
||||
psql(compose, "TRUNCATE message_idempotency, messages")
|
||||
if seed_count:
|
||||
sql = ("INSERT INTO messages (chat_id, sender_id, text, created_at) "
|
||||
"SELECT '%s'::uuid, '%s'::uuid, 'seed-' || g, now() - interval '1 day' "
|
||||
"FROM generate_series(1, %d) AS g" % (chat_id, user_id, seed_count))
|
||||
psql(compose, sql, timeout=180)
|
||||
psql(compose, "ANALYZE messages; ANALYZE message_idempotency")
|
||||
actual = message_count(compose)
|
||||
if actual != seed_count:
|
||||
raise RuntimeError("dataset reset produced %d messages, expected %d" % (actual, seed_count))
|
||||
|
||||
|
||||
def api_ids(compose):
|
||||
return command(compose + ["ps", "-q", "api"]).splitlines()
|
||||
|
||||
|
||||
def api_limits(compose):
|
||||
identifiers = api_ids(compose)
|
||||
output = command(["docker", "inspect", "--format",
|
||||
"{{.Id}} {{.HostConfig.NanoCpus}} {{.HostConfig.Memory}}"] + identifiers,
|
||||
timeout=15)
|
||||
return [dict(zip(("container_id", "nano_cpus", "memory_bytes"), line.split()))
|
||||
for line in output.splitlines()]
|
||||
|
||||
|
||||
def wait_instances(base_url, expected, seconds=60):
|
||||
client = Client(base_url, timeout=3)
|
||||
found = set()
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
response = client.call("GET", "/health/ready", schema="Health")
|
||||
found.add(response["headers"].get("X-Instance-Id"))
|
||||
if len(found) == expected:
|
||||
return sorted(found)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(.15)
|
||||
raise RuntimeError("LB observed %d of %d API instances" % (len(found), expected))
|
||||
|
||||
|
||||
def sample_loop(stop, compose, path):
|
||||
ids = []
|
||||
for service in ("api", "lb", "postgres", "redis"):
|
||||
ids += command(compose + ["ps", "-q", service], timeout=10).splitlines()
|
||||
lb = command(compose + ["ps", "-q", "lb"], timeout=10).strip()
|
||||
with path.open("w") as output:
|
||||
while not stop.is_set():
|
||||
sample = {"at_utc": utc_now()}
|
||||
try:
|
||||
raw = command(["docker", "stats", "--no-stream", "--format", "{{json .}}"] + ids, timeout=15)
|
||||
sample["docker_stats"] = [json.loads(line) for line in raw.splitlines() if line.strip()]
|
||||
sample["docker_at_utc"] = utc_now()
|
||||
except Exception as exc:
|
||||
sample["docker_error"] = type(exc).__name__
|
||||
try:
|
||||
raw = psql(compose, "SELECT json_build_object('connections', count(*), 'active', count(*) FILTER (WHERE state='active'), 'lock_wait', count(*) FILTER (WHERE wait_event_type='Lock'), 'io_wait', count(*) FILTER (WHERE wait_event_type='IO')) FROM pg_stat_activity WHERE datname=current_database()", timeout=10)
|
||||
sample["postgres_activity"] = json.loads(raw)
|
||||
sample["postgres_at_utc"] = utc_now()
|
||||
except Exception as exc:
|
||||
sample["postgres_error"] = type(exc).__name__
|
||||
try:
|
||||
raw = command(["docker", "exec", lb, "sh", "-c", "printf 'show stat\\n' | socat - TCP4:127.0.0.1:9999"], timeout=10)
|
||||
rows = list(csv.DictReader(io.StringIO(raw.lstrip("# "))))
|
||||
sample["haproxy"] = [
|
||||
{key: row.get(key) for key in ("pxname", "svname", "status", "scur", "qcur", "stot", "ereq", "econ", "eresp", "wretr")}
|
||||
for row in rows if row.get("pxname") == "api_replicas"
|
||||
]
|
||||
sample["haproxy_at_utc"] = utc_now()
|
||||
except Exception as exc:
|
||||
sample["haproxy_error"] = type(exc).__name__
|
||||
output.write(json.dumps(sample, ensure_ascii=False) + "\n")
|
||||
output.flush()
|
||||
stop.wait(.5)
|
||||
|
||||
|
||||
def diagnostic_snapshot(compose):
|
||||
snapshot = {"at_utc": utc_now(), "cgroups": {}}
|
||||
snapshot["durability"] = json.loads(psql(compose, "SELECT json_build_object('fsync',current_setting('fsync'),'synchronous_commit',current_setting('synchronous_commit'),'commit_delay',current_setting('commit_delay'),'commit_siblings',current_setting('commit_siblings'))"))
|
||||
for service in ("api", "postgres", "lb", "redis"):
|
||||
for identifier in command(compose + ["ps", "-q", service]).splitlines():
|
||||
raw = command(["docker", "exec", identifier, "cat", "/sys/fs/cgroup/cpu.stat"], timeout=10)
|
||||
snapshot["cgroups"][identifier] = {"service": service,
|
||||
**{line.split()[0]: int(line.split()[1]) for line in raw.splitlines()}}
|
||||
snapshot["wal_io"] = json.loads(psql(compose, "SELECT coalesce(json_agg(row_to_json(i)), '[]'::json) FROM pg_stat_io i WHERE object='wal'"))
|
||||
snapshot["wal"] = json.loads(psql(compose, "SELECT row_to_json(w) FROM pg_stat_wal w"))
|
||||
return snapshot
|
||||
|
||||
|
||||
def pg_stat_statements(compose):
|
||||
sql = ("SELECT coalesce(json_agg(row_to_json(q)), '[]'::json) FROM "
|
||||
"(SELECT queryid, calls, round(total_exec_time::numeric,3) AS total_exec_ms, "
|
||||
"round(mean_exec_time::numeric,3) AS mean_exec_ms, rows, shared_blks_hit, "
|
||||
"shared_blks_read, temp_blks_written, left(query,160) AS query "
|
||||
"FROM pg_stat_statements WHERE dbid=(SELECT oid FROM pg_database WHERE datname=current_database()) "
|
||||
"ORDER BY total_exec_time DESC LIMIT 15) AS q")
|
||||
return json.loads(psql(compose, sql))
|
||||
|
||||
|
||||
def run_load(binary, base_url, auth_file, rate, duration, max_inflight, output_path):
|
||||
raw = command([str(binary), "-base-url", base_url, "-auth-file", str(auth_file),
|
||||
"-rate", str(rate), "-duration", str(duration) + "s",
|
||||
"-max-inflight", str(max_inflight), "-timeout", "5s"], timeout=duration + 40)
|
||||
result = json.loads(raw)
|
||||
output_path.write_text(json.dumps(result, indent=2, ensure_ascii=False) + "\n")
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--plan", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
plan = json.loads(args.plan.read_text())
|
||||
runs = plan["runs"]
|
||||
if not runs or not all(run["replicas"] in (1, 2, 4) for run in runs):
|
||||
raise ValueError("plan must have runs with 1, 2, or 4 replicas")
|
||||
output_dir = args.output.resolve()
|
||||
if output_dir.exists() and any(output_dir.iterdir()):
|
||||
raise FileExistsError("output directory must be empty")
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
(output_dir / "plan.json").write_text(json.dumps(plan, indent=2, ensure_ascii=False) + "\n")
|
||||
project = "lab3-grade5-" + uuid4().hex[:10]
|
||||
lb_port = free_port()
|
||||
base_url = "http://127.0.0.1:%d" % lb_port
|
||||
summary = {"project": project, "base_url": base_url, "started_at_utc": utc_now(),
|
||||
"host": {"platform": platform.platform(), "machine": platform.machine()},
|
||||
"runs": [], "cleanup": "not_started"}
|
||||
(output_dir / "summary.json").write_text(json.dumps(summary, indent=2, ensure_ascii=False) + "\n")
|
||||
with tempfile.TemporaryDirectory(prefix="lab3-grade5-") as temporary:
|
||||
temporary = Path(temporary)
|
||||
override = temporary / "override.yaml"
|
||||
auth_file = temporary / "auth.json"
|
||||
database_url_file = temporary / "database_url"
|
||||
binary = temporary / "grade5-load"
|
||||
first = runs[0]
|
||||
write_database_url(database_url_file, first.get("pool_max_conns"))
|
||||
write_override(override, lb_port=lb_port, replicas=first["replicas"],
|
||||
total_cpus=first["api_total_cpus"], total_memory_mib=first["api_total_memory_mib"],
|
||||
postgres_cpus=first.get("postgres_cpus", 2), database_url_file=database_url_file)
|
||||
compose = ["docker", "compose", "-p", project, "--env-file", ".env",
|
||||
"-f", "compose.yaml", "-f", str(override)]
|
||||
try:
|
||||
command(["go", "build", "-o", str(binary), "student-tests/lab3/grade5/load.go"], timeout=180,
|
||||
log=output_dir / "go-build.log")
|
||||
command(compose + ["config", "--quiet"], timeout=30)
|
||||
print("Building and starting disposable project", project, flush=True)
|
||||
command(compose + ["up", "-d", "--build"], timeout=900, log=output_dir / "compose-up.log")
|
||||
wait_instances(base_url, first["replicas"])
|
||||
psql(compose, "CREATE EXTENSION IF NOT EXISTS pg_stat_statements")
|
||||
client = Client(base_url)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
auth_file.write_text(json.dumps({"token": alice["token"], "chat_id": chat["id"]}))
|
||||
os.chmod(auth_file, 0o600)
|
||||
summary["chat_id"] = chat["id"]
|
||||
summary["seed_messages"] = plan["seed_messages"]
|
||||
summary["docker_server"] = command(["docker", "version", "--format", "{{.Server.Version}}"], timeout=15).strip()
|
||||
summary["compose_version"] = command(["docker", "compose", "version", "--short"], timeout=15).strip()
|
||||
summary["docker_resources"] = command(["docker", "info", "--format", "{{.NCPU}} CPUs, {{.MemTotal}} bytes RAM"], timeout=15).strip()
|
||||
previous_postgres_cpus = first.get("postgres_cpus", 2)
|
||||
for index, run in enumerate(runs, 1):
|
||||
name = run["name"]
|
||||
if not name.replace("-", "").replace("_", "").isalnum():
|
||||
raise ValueError("unsafe run name")
|
||||
run_dir = output_dir / ("%02d-%s" % (index, name))
|
||||
run_dir.mkdir()
|
||||
write_database_url(database_url_file, run.get("pool_max_conns"))
|
||||
write_override(override, lb_port=lb_port, replicas=run["replicas"],
|
||||
total_cpus=run["api_total_cpus"], total_memory_mib=run["api_total_memory_mib"],
|
||||
postgres_cpus=run.get("postgres_cpus", 2), database_url_file=database_url_file)
|
||||
command(compose + ["config", "--quiet"], timeout=30)
|
||||
print("Run %d/%d: %s" % (index, len(runs), name), flush=True)
|
||||
delay = run.get("commit_delay_us", 0)
|
||||
if not isinstance(delay, int) or not 0 <= delay <= 100000:
|
||||
raise ValueError("invalid commit_delay_us")
|
||||
psql(compose, "ALTER SYSTEM SET commit_delay='%d'" % delay)
|
||||
psql(compose, "SELECT pg_reload_conf()")
|
||||
if run.get("postgres_cpus", 2) != previous_postgres_cpus:
|
||||
command(compose + ["up", "-d", "--no-deps", "--no-build", "--force-recreate", "postgres"],
|
||||
timeout=120, log=run_dir / "compose-postgres.log")
|
||||
deadline = time.monotonic() + 60
|
||||
while True:
|
||||
try:
|
||||
if psql(compose, "SELECT 1", timeout=5) == "1":
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
if time.monotonic() > deadline:
|
||||
raise RuntimeError("PostgreSQL did not become ready after budget change")
|
||||
time.sleep(1)
|
||||
previous_postgres_cpus = run.get("postgres_cpus", 2)
|
||||
command(compose + ["up", "-d", "--no-deps", "--no-build", "--force-recreate", "--scale", "api=%d" % run["replicas"], "api"],
|
||||
timeout=180, log=run_dir / "compose-scale.log")
|
||||
instances = wait_instances(base_url, run["replicas"])
|
||||
warmup = plan.get("warmup_seconds", 3)
|
||||
reset_dataset(compose, chat["id"], alice["id"], plan["seed_messages"])
|
||||
if warmup:
|
||||
warmup_rate = plan.get("warmup_rate", min(200, run["rate"]))
|
||||
if warmup_rate == "target":
|
||||
warmup_rate = run["rate"]
|
||||
run_load(binary, base_url, auth_file, warmup_rate, warmup,
|
||||
plan.get("max_inflight", 1024),
|
||||
run_dir / "warmup.json")
|
||||
reset_dataset(compose, chat["id"], alice["id"], plan["seed_messages"])
|
||||
if plan.get("settle_seconds", 0):
|
||||
psql(compose, "CHECKPOINT")
|
||||
time.sleep(plan["settle_seconds"])
|
||||
psql(compose, "SELECT pg_stat_statements_reset()")
|
||||
before = message_count(compose)
|
||||
(run_dir / "diagnostics-before.json").write_text(json.dumps(diagnostic_snapshot(compose), indent=2) + "\n")
|
||||
stop = threading.Event()
|
||||
sampler = threading.Thread(target=sample_loop, args=(stop, compose, run_dir / "samples.jsonl"))
|
||||
sampler.start()
|
||||
try:
|
||||
load = run_load(binary, base_url, auth_file, run["rate"], run["duration_seconds"],
|
||||
run.get("max_inflight", plan.get("max_inflight", 1024)),
|
||||
run_dir / "load.json")
|
||||
finally:
|
||||
stop.set()
|
||||
sampler.join(timeout=30)
|
||||
after = message_count(compose)
|
||||
(run_dir / "diagnostics-after.json").write_text(json.dumps(diagnostic_snapshot(compose), indent=2) + "\n")
|
||||
sql_stats = pg_stat_statements(compose)
|
||||
(run_dir / "postgres-statements.json").write_text(json.dumps(sql_stats, indent=2, ensure_ascii=False) + "\n")
|
||||
item = {"name": name, "phase": run.get("phase", "unspecified"),
|
||||
"replicas": run["replicas"], "api_total_cpus": run["api_total_cpus"],
|
||||
"api_total_memory_mib": run["api_total_memory_mib"],
|
||||
"postgres_cpus": run.get("postgres_cpus", 2), "rate": run["rate"],
|
||||
"pool_max_conns_per_replica": run.get("pool_max_conns", "pgx_default"),
|
||||
"commit_delay_us": delay,
|
||||
"duration_seconds": run["duration_seconds"], "instances": instances,
|
||||
"api_limits": api_limits(compose),
|
||||
"messages_before": before, "messages_after": after,
|
||||
"messages_added": after-before, "load": load}
|
||||
summary["runs"].append(item)
|
||||
(output_dir / "summary.json").write_text(json.dumps(summary, indent=2, ensure_ascii=False) + "\n")
|
||||
print(" success=%d/%d, rps=%.1f, p99=%.1f ms" %
|
||||
(load["successful_requests"], load["scheduled_requests"],
|
||||
load["successful_rps_window"], load["success_latency_ms"]["p99"]), flush=True)
|
||||
except Exception as exc:
|
||||
summary["error"] = str(exc)
|
||||
raise
|
||||
finally:
|
||||
print("Cleaning disposable project", project, flush=True)
|
||||
try:
|
||||
command(compose + ["down", "-v", "--remove-orphans"], timeout=180,
|
||||
log=output_dir / "cleanup.log")
|
||||
remaining_containers = command(["docker", "ps", "-aq", "--filter",
|
||||
"label=com.docker.compose.project=" + project], timeout=15).splitlines()
|
||||
remaining_volumes = command(["docker", "volume", "ls", "-q", "--filter",
|
||||
"label=com.docker.compose.project=" + project], timeout=15).splitlines()
|
||||
after = {"project": project, "containers": remaining_containers,
|
||||
"volumes": remaining_volumes, "at_utc": utc_now()}
|
||||
(output_dir / "environment-after.json").write_text(json.dumps(after, indent=2) + "\n")
|
||||
summary["cleanup"] = "PASS" if not remaining_containers and not remaining_volumes else "FAIL: resources remain"
|
||||
except Exception as exc:
|
||||
summary["cleanup"] = "FAIL: " + str(exc)
|
||||
summary["finished_at_utc"] = utc_now()
|
||||
(output_dir / "summary.json").write_text(json.dumps(summary, indent=2, ensure_ascii=False) + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user