diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..468e1d1 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# The dashboard is a single demo page; this repo is about the Go backend. +frontend/index.html linguist-detectable=false diff --git a/.github/workflows/backend.yml b/.github/workflows/backend.yml new file mode 100644 index 0000000..7b0d87d --- /dev/null +++ b/.github/workflows/backend.yml @@ -0,0 +1,26 @@ +name: backend + +on: + push: + paths: ["backend/**", ".github/workflows/backend.yml"] + pull_request: + paths: ["backend/**", ".github/workflows/backend.yml"] + +jobs: + test-and-build: + runs-on: ubuntu-latest + defaults: + run: + working-directory: backend + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - run: go vet ./... + - run: go test -race -count=1 ./... + - name: Build images (no push) + run: | + docker build -t loadlab-backend:ci --build-arg VERSION=${GITHUB_SHA::7} . + docker build -t loadlab-backend:bad --build-arg VERSION=bad --build-arg FAULT_LATENCY_MS=300 --build-arg FAULT_ERROR_RATE=0.1 . diff --git a/README.md b/README.md index 406e277..a80b6f0 100644 --- a/README.md +++ b/README.md @@ -85,7 +85,10 @@ All routes are reached through Nginx under `/api/`. | Route | What it does | What it stresses | |---|---|---| +| `GET /api/work` | Burns `WORK_CPU_MS` of CPU, then waits `WORK_DURATION_MS`; cancelled after `WORK_TIMEOUT_MS` | A realistic mixed request; the autoscaling target | | `GET /api/health` | Returns `{"status":"ok"}` | Nothing; the baseline | +| `GET /api/livez` | Liveness probe | — | +| `GET /api/readyz` | Readiness probe; fails while the server drains on shutdown | — | | `GET /api/cpu` | Counts primes up to 1,000,000 by trial division | One CPU core per request | | `GET /api/memory` | Allocates a slice of 1,000,000 structs | Heap and garbage collector | | `GET /api/slow` | Sleeps for 3 seconds | Open connections and goroutines | @@ -93,6 +96,39 @@ All routes are reached through Nginx under `/api/`. | `GET /api/status` | Probes Prometheus and Grafana from inside the Docker network | — | | `GET /api/metrics` | Prometheus metrics: request count and latency histogram per route | — | +### Admin port (internal only) + +The backend also listens on `:9091` for fault switches. It is not published by Compose and must never be exposed publicly; the same paths on `:3000` return 404. + +| Route | What it does | +|---|---| +| `POST /admin/leak?mb_per_min=N` | Starts leaking N MiB of memory per minute | +| `POST /admin/leak/stop` | Stops the leak | + +### Configuration + +| Env var | Default | Meaning | +|---|---|---| +| `WORK_CPU_MS` | 20 | CPU time burned per `/work` request (0–1000) | +| `WORK_DURATION_MS` | 30 | Wait time per `/work` request (0–10000) | +| `WORK_TIMEOUT_MS` | 5000 | `/work` deadline (100–30000) | +| `FAULT_LATENCY_MS` | 0 | Extra latency per request, except probes, `/health` and `/metrics` (0–10000) | +| `FAULT_ERROR_RATE` | 0 | Fraction of those requests answered with 500 (0–1) | +| `APP_VERSION` | build version | Version reported by `/info` and metrics | +| `SHUTDOWN_DRAIN_S` | 20 | Seconds to drain in-flight requests on SIGTERM (1–25) | +| `STATUS_TARGETS` | Prometheus and Grafana | `name=url,...` probed by `/status` | + +Invalid values fall back to the default with a warning; values above the range are clamped. + +### Images + +The backend image is a static binary on distroless, running as non-root. The `:bad` image is the same code with faults baked in, for testing rollbacks: + +```bash +docker build -t loadlab-backend:local --build-arg VERSION=local backend +docker build -t loadlab-backend:bad --build-arg VERSION=bad --build-arg FAULT_LATENCY_MS=300 --build-arg FAULT_ERROR_RATE=0.1 backend +``` + ## Load tests Scripts target `http://localhost` by default. Pass `-e BASE_URL=...` to aim them elsewhere. diff --git a/backend/Dockerfile b/backend/Dockerfile index 2c80f66..9d49910 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -1,5 +1,6 @@ # Build stage FROM golang:1.24-alpine AS builder +ARG VERSION=dev WORKDIR /app @@ -7,14 +8,18 @@ COPY go.mod go.sum ./ RUN go mod download COPY . . -RUN CGO_ENABLED=0 go build -o server . +RUN CGO_ENABLED=0 go build -trimpath -ldflags "-s -w -X main.buildVersion=${VERSION}" -o /server . # Runtime stage -FROM alpine:3.21 +FROM gcr.io/distroless/static:nonroot +# Defaults are a healthy image; the :bad image sets FAULT_LATENCY_MS=300 FAULT_ERROR_RATE=0.1 +ARG FAULT_LATENCY_MS=0 +ARG FAULT_ERROR_RATE=0 +ENV FAULT_LATENCY_MS=${FAULT_LATENCY_MS} FAULT_ERROR_RATE=${FAULT_ERROR_RATE} -WORKDIR /app -COPY --from=builder /app/server . - -EXPOSE 3000 +COPY --from=builder /server /server +USER nonroot:nonroot +# 3000 public; 9091 admin, internal only (never publish it) +EXPOSE 3000 9091 -CMD ["./server"] +ENTRYPOINT ["/server"] diff --git a/backend/config.go b/backend/config.go new file mode 100644 index 0000000..d60c8cb --- /dev/null +++ b/backend/config.go @@ -0,0 +1,70 @@ +package main + +import ( + "math" + "strconv" + "strings" + "time" +) + +type Config struct { + WorkCPU, WorkWait, WorkTimeout time.Duration + FaultLatency time.Duration + FaultErrorRate float64 + Version string + StatusTargets map[string]string + Drain time.Duration +} + +// LoadConfig reads settings via getenv. Unset values use the default silently; +// unparsable or below-range values fall back to the default and values above +// the range are clamped, each with exactly one warning through logf. +func LoadConfig(getenv func(string) string, logf func(string, ...any)) Config { + num := func(key string, def, lo, hi float64) float64 { + s := getenv(key) + if s == "" { + return def + } + v, err := strconv.ParseFloat(s, 64) + switch { + case err != nil || math.IsNaN(v) || v < lo: + logf("config: %s=%q invalid, using default %v", key, s, def) + return def + case v > hi: + logf("config: %s=%q above max, clamped to %v", key, s, hi) + return hi + } + return v + } + ms := func(key string, def, lo, hi float64) time.Duration { + return time.Duration(num(key, def, lo, hi) * float64(time.Millisecond)) + } + + c := Config{ + WorkCPU: ms("WORK_CPU_MS", 20, 0, 1000), + WorkWait: ms("WORK_DURATION_MS", 30, 0, 10000), + WorkTimeout: ms("WORK_TIMEOUT_MS", 5000, 100, 30000), + FaultLatency: ms("FAULT_LATENCY_MS", 0, 0, 10000), + FaultErrorRate: num("FAULT_ERROR_RATE", 0, 0, 1), + Version: getenv("APP_VERSION"), + Drain: time.Duration(num("SHUTDOWN_DRAIN_S", 20, 1, 25) * float64(time.Second)), + StatusTargets: map[string]string{ + "prometheus": "http://prometheus:9090/-/healthy", + "grafana": "http://grafana:3000/api/health", + }, + } + if c.Version == "" { + c.Version = buildVersion + } + if s := getenv("STATUS_TARGETS"); s != "" { + c.StatusTargets = map[string]string{} + for _, pair := range strings.Split(s, ",") { + if name, url, ok := strings.Cut(pair, "="); ok && name != "" && url != "" { + c.StatusTargets[strings.TrimSpace(name)] = strings.TrimSpace(url) + } else { + logf("config: STATUS_TARGETS entry %q ignored, want name=url", pair) + } + } + } + return c +} diff --git a/backend/config_test.go b/backend/config_test.go new file mode 100644 index 0000000..d7875d0 --- /dev/null +++ b/backend/config_test.go @@ -0,0 +1,45 @@ +package main + +import ( + "fmt" + "testing" + "time" +) + +func TestLoadConfig_Defaults(t *testing.T) { + c := LoadConfig(func(string) string { return "" }, t.Logf) + assertEq(t, c.WorkCPU, 20*time.Millisecond) + assertEq(t, c.WorkWait, 30*time.Millisecond) + assertEq(t, c.WorkTimeout, 5*time.Second) + assertEq(t, c.FaultLatency, time.Duration(0)) + assertEq(t, c.FaultErrorRate, 0.0) + assertEq(t, c.Version, "dev") + assertEq(t, c.Drain, 20*time.Second) + assertEq(t, c.StatusTargets["prometheus"], "http://prometheus:9090/-/healthy") + assertEq(t, c.StatusTargets["grafana"], "http://grafana:3000/api/health") +} + +func TestLoadConfig_ClampsAndFallsBack(t *testing.T) { + env := map[string]string{"WORK_CPU_MS": "-5", "WORK_DURATION_MS": "abc", "FAULT_ERROR_RATE": "1.5", "FAULT_LATENCY_MS": "999999", "WORK_TIMEOUT_MS": "NaN"} + var logged []string + c := LoadConfig(func(k string) string { return env[k] }, func(f string, a ...any) { logged = append(logged, fmt.Sprintf(f, a...)) }) + assertEq(t, c.WorkCPU, 20*time.Millisecond) // negative -> default + assertEq(t, c.WorkWait, 30*time.Millisecond) // unparsable -> default + assertEq(t, c.FaultErrorRate, 1.0) // clamped to [0,1] + assertEq(t, c.FaultLatency, 10*time.Second) // clamped to 10 s + assertEq(t, c.WorkTimeout, 5*time.Second) // NaN -> default + if len(logged) != 5 { + t.Fatalf("want 5 warnings, got %v", logged) + } +} + +func TestLoadConfig_StatusTargetsFromEnv(t *testing.T) { + c := LoadConfig(func(k string) string { + if k == "STATUS_TARGETS" { + return "prometheus=http://p:9090/-/healthy,keda=http://k:8080/healthz" + } + return "" + }, t.Logf) + assertEq(t, len(c.StatusTargets), 2) + assertEq(t, c.StatusTargets["keda"], "http://k:8080/healthz") +} diff --git a/backend/faults.go b/backend/faults.go new file mode 100644 index 0000000..0feafd5 --- /dev/null +++ b/backend/faults.go @@ -0,0 +1,94 @@ +package main + +import ( + "net/http" + "runtime/debug" + "sync" + "time" +) + +const mb = 1 << 20 + +// Leaker grows resident memory at a set rate until stopped. +type Leaker struct { + mu sync.Mutex + mbMin int + chunks [][]byte + held int // bytes +} + +func NewLeaker(tick <-chan time.Time) *Leaker { + l := &Leaker{} + go func() { + for range tick { + l.grow() + } + }() + return l +} + +func (l *Leaker) grow() { + l.mu.Lock() + defer l.mu.Unlock() + n := l.mbMin * mb / 60 + if n == 0 { + return + } + b := make([]byte, n) + for i := 0; i < len(b); i += 4096 { // touch every page so it is really resident + b[i] = 1 + } + l.chunks = append(l.chunks, b) + l.held += n +} + +func (l *Leaker) Start(mbPerMin int) { + l.mu.Lock() + l.mbMin = mbPerMin + l.mu.Unlock() +} + +func (l *Leaker) Stop() { + l.mu.Lock() + l.mbMin, l.chunks, l.held = 0, nil, 0 + l.mu.Unlock() + debug.FreeOSMemory() +} + +func (l *Leaker) HeldMB() int { + l.mu.Lock() + defer l.mu.Unlock() + return l.held / mb +} + +func (l *Leaker) rate() int { + l.mu.Lock() + defer l.mu.Unlock() + return l.mbMin +} + +// FaultMiddleware injects latency and errors, sparing probes and metrics. +func FaultMiddleware(cfg Config, rnd func() float64, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/livez", "/readyz", "/health", "/metrics": + next.ServeHTTP(w, r) + return + } + if cfg.FaultLatency > 0 { + t := time.NewTimer(cfg.FaultLatency) + select { + case <-t.C: + case <-r.Context().Done(): + t.Stop() + return + } + } + if rnd() < cfg.FaultErrorRate { + w.WriteHeader(http.StatusInternalServerError) + writeJSON(w, map[string]string{"status": "injected fault"}) + return + } + next.ServeHTTP(w, r) + }) +} diff --git a/backend/faults_test.go b/backend/faults_test.go new file mode 100644 index 0000000..8ab0676 --- /dev/null +++ b/backend/faults_test.go @@ -0,0 +1,56 @@ +package main + +import ( + "testing" + "time" +) + +func TestLeaker_GrowsPerTickAndStopReleases(t *testing.T) { + tick := make(chan time.Time) + l := NewLeaker(tick) + l.Start(60) // 60 MB/min = 1 MB per 1 s tick + for i := 0; i < 3; i++ { + tick <- time.Now() + } + waitFor(t, func() bool { return l.HeldMB() == 3 }) + l.Stop() + assertEq(t, l.HeldMB(), 0) +} + +func TestAdminLeak_ClampsAndValidates(t *testing.T) { + l := NewLeaker(make(chan time.Time)) + mux := AdminMux(l) + assertEq(t, post(mux, "/admin/leak?mb_per_min=100000").Code, 202) + assertEq(t, l.rate(), 200) // clamped + assertEq(t, post(mux, "/admin/leak").Code, 400) + assertEq(t, post(mux, "/admin/leak?mb_per_min=-3").Code, 400) + assertEq(t, get(mux, "/admin/leak").Code, 405) + assertEq(t, post(mux, "/admin/leak/stop").Code, 202) +} + +func TestFaultMiddleware_OffByDefault(t *testing.T) { + h := FaultMiddleware(Config{}, func() float64 { return 0 }, ok200()) + t0 := time.Now() + rec := serve(h, "/work") + assertEq(t, rec.Code, 200) + if time.Since(t0) > 20*time.Millisecond { + t.Fatal("added latency with faults off") + } +} + +func TestFaultMiddleware_AddsLatencyAndErrors(t *testing.T) { + cfg := Config{FaultLatency: 50 * time.Millisecond, FaultErrorRate: 0.1} + t0 := time.Now() + assertEq(t, serve(FaultMiddleware(cfg, func() float64 { return 0.05 }, ok200()), "/work").Code, 500) // 0.05 < 0.1 → error + if time.Since(t0) < 50*time.Millisecond { + t.Fatal("latency not applied") + } + assertEq(t, serve(FaultMiddleware(cfg, func() float64 { return 0.5 }, ok200()), "/work").Code, 200) +} + +func TestFaultMiddleware_SparesProbesAndMetrics(t *testing.T) { + cfg := Config{FaultErrorRate: 1} + for _, p := range []string{"/livez", "/readyz", "/metrics"} { + assertEq(t, serve(FaultMiddleware(cfg, func() float64 { return 0 }, ok200()), p).Code, 200) + } +} diff --git a/backend/go.mod b/backend/go.mod index 4ed1434..7e8df18 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -2,13 +2,16 @@ module loadlab go 1.24 -require github.com/prometheus/client_golang v1.22.0 +require ( + github.com/prometheus/client_golang v1.22.0 + github.com/prometheus/client_model v0.6.1 +) require ( github.com/beorn7/perks v1.0.1 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/kylelemons/godebug v1.1.0 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect - github.com/prometheus/client_model v0.6.1 // indirect github.com/prometheus/common v0.62.0 // indirect github.com/prometheus/procfs v0.15.1 // indirect golang.org/x/sys v0.30.0 // indirect diff --git a/backend/handlers.go b/backend/handlers.go new file mode 100644 index 0000000..f7fd258 --- /dev/null +++ b/backend/handlers.go @@ -0,0 +1,230 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "math" + "net/http" + "os" + "runtime" + "sync" + "sync/atomic" + "time" +) + +func writeJSON(w http.ResponseWriter, v any) { + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(v) +} + +func healthHandler(w http.ResponseWriter, r *http.Request) { + writeJSON(w, map[string]string{ + "status": "ok", + "timestamp": time.Now().UTC().Format(time.RFC3339Nano), + }) +} + +// Health tracks readiness for the Kubernetes probes. +type Health struct{ ready, draining atomic.Bool } + +func (h *Health) SetReady(v bool) { h.ready.Store(v) } +func (h *Health) SetDraining() { h.draining.Store(true) } + +func (h *Health) Live(w http.ResponseWriter, r *http.Request) { + writeJSON(w, map[string]string{"status": "ok"}) +} + +func (h *Health) Ready(w http.ResponseWriter, r *http.Request) { + switch { + case h.draining.Load(): + w.WriteHeader(http.StatusServiceUnavailable) + writeJSON(w, map[string]string{"status": "draining"}) + case !h.ready.Load(): + w.WriteHeader(http.StatusServiceUnavailable) + writeJSON(w, map[string]string{"status": "not ready"}) + default: + writeJSON(w, map[string]string{"status": "ok"}) + } +} + +var ( + cpuSink atomic.Uint64 // keeps the compiler from eliminating mix; atomic because requests run concurrently + calibrate sync.Once + itersPerNs float64 +) + +// mix runs n xorshift iterations: a fixed unit of CPU work. +func mix(n int64) { + x := cpuSink.Load() | 1 + for range n { + x ^= x << 13 + x ^= x >> 7 + x ^= x << 17 + } + cpuSink.Store(x) +} + +// calibrateCPU measures mix's speed once: the fastest of 10 windows of 5ms, so a +// busy node at scale-up still calibrates close to its uncontended speed. +// ponytail: if all 10 windows are contended, per-request cost is still underestimated. +func calibrateCPU() { + calibrate.Do(func() { + for range 10 { + var n int64 + t0 := time.Now() + for time.Since(t0) < 5*time.Millisecond { + mix(10_000) + n += 10_000 + } + itersPerNs = max(itersPerNs, float64(n)/float64(time.Since(t0))) + } + }) +} + +// burnCPU does d worth of calibrated CPU work, checking for cancellation about every millisecond. +func burnCPU(ctx context.Context, d time.Duration) error { + calibrateCPU() + left := int64(float64(d) * itersPerNs) + chunk := max(int64(itersPerNs*float64(time.Millisecond)), 1) + for left > 0 { + if err := ctx.Err(); err != nil { + return err + } + k := min(chunk, left) + mix(k) + left -= k + } + return nil +} + +// Work costs real CPU then holds the request open, like a request awaiting a dependency. +func Work(cfg Config) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), cfg.WorkTimeout) + defer cancel() + err := burnCPU(ctx, cfg.WorkCPU) + if err == nil { + t := time.NewTimer(cfg.WorkWait) + defer t.Stop() + select { + case <-t.C: + case <-ctx.Done(): + err = ctx.Err() + } + } + if errors.Is(err, context.DeadlineExceeded) { + w.WriteHeader(http.StatusGatewayTimeout) + writeJSON(w, map[string]string{"status": "timeout"}) + return + } + if err != nil { // client gone + return + } + writeJSON(w, map[string]any{ + "status": "ok", + "cpu_ms": cfg.WorkCPU.Milliseconds(), + "wait_ms": cfg.WorkWait.Milliseconds(), + }) + } +} + +// Slow simulates a slow upstream dependency. +func Slow(delay time.Duration) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + t := time.NewTimer(delay) + defer t.Stop() + select { + case <-t.C: + case <-r.Context().Done(): + return + } + writeJSON(w, map[string]any{"endpoint": "slow", "delay_ms": delay.Milliseconds()}) + } +} + +// CPU counts primes below limit, stopping if the client goes away. +func CPU(limit int) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + count := 0 + for i := 2; i < limit; i++ { + if i%10000 == 0 && r.Context().Err() != nil { + return + } + prime := true + for j, s := 2, int(math.Sqrt(float64(i))); j <= s; j++ { + if i%j == 0 { + prime = false + break + } + } + if prime { + count++ + } + } + writeJSON(w, map[string]any{"endpoint": "cpu", "primes_found": count}) + } +} + +// Memory allocates a large slice. +func Memory(w http.ResponseWriter, r *http.Request) { + type obj struct { + Index int `json:"index"` + Value float64 `json:"value"` + } + arr := make([]obj, 0, 1_000_000) + for i := 0; i < 1_000_000; i++ { + arr = append(arr, obj{Index: i, Value: float64(i) * 0.1}) + } + writeJSON(w, map[string]any{"endpoint": "memory", "allocated": len(arr)}) +} + +func Info(cfg Config, start time.Time) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + env := os.Getenv("APP_ENV") + if env == "" { + env = "development" + } + writeJSON(w, map[string]any{ + "app": "LoadLab", + "version": cfg.Version, + "go": runtime.Version(), + "uptime_seconds": int(time.Since(start).Seconds()), + "timestamp": time.Now().UTC().Format(time.RFC3339Nano), + "environment": env, + }) + } +} + +// Status probes each configured target concurrently. +func Status(cfg Config, client *http.Client) http.HandlerFunc { + type result struct { + Status string `json:"status"` + Ms int `json:"ms"` + } + return func(w http.ResponseWriter, r *http.Request) { + var mu sync.Mutex + var wg sync.WaitGroup + out := make(map[string]result, len(cfg.StatusTargets)) + for name, url := range cfg.StatusTargets { + wg.Add(1) + go func() { + defer wg.Done() + t0 := time.Now() + res := result{Status: "offline"} + if resp, err := client.Get(url); err == nil { + resp.Body.Close() + if resp.StatusCode < 500 { + res.Status = "online" + } + } + res.Ms = int(time.Since(t0).Milliseconds()) + mu.Lock() + out[name] = res + mu.Unlock() + }() + } + wg.Wait() + writeJSON(w, out) + } +} diff --git a/backend/handlers_test.go b/backend/handlers_test.go new file mode 100644 index 0000000..df1f557 --- /dev/null +++ b/backend/handlers_test.go @@ -0,0 +1,95 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "runtime" + "sync" + "testing" + "time" +) + +func TestWork_SpendsCPUThenWaits(t *testing.T) { + cfg := Config{WorkCPU: 30 * time.Millisecond, WorkWait: 20 * time.Millisecond, WorkTimeout: time.Second} + rec := httptest.NewRecorder() + t0 := time.Now() + Work(cfg)(rec, httptest.NewRequest("GET", "/work", nil)) + assertEq(t, rec.Code, 200) + if d := time.Since(t0); d < 45*time.Millisecond || d > 250*time.Millisecond { // calibrated CPU cost jitters a few % + t.Fatalf("took %v", d) + } +} + +func TestWork_TimeoutReturns504(t *testing.T) { + cfg := Config{WorkCPU: 0, WorkWait: 500 * time.Millisecond, WorkTimeout: 50 * time.Millisecond} + rec := httptest.NewRecorder() + Work(cfg)(rec, httptest.NewRequest("GET", "/work", nil)) + assertEq(t, rec.Code, http.StatusGatewayTimeout) +} + +func TestBurnCPU_StopsOnCancel(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + t0 := time.Now() + err := burnCPU(ctx, 5*time.Second) + if !errors.Is(err, context.DeadlineExceeded) || time.Since(t0) > 100*time.Millisecond { + t.Fatalf("err=%v after %v", err, time.Since(t0)) + } +} + +func TestBurnCPU_FixedWorkUnderContention(t *testing.T) { + defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(1)) + var wg sync.WaitGroup + t0 := time.Now() + for range 2 { + wg.Add(1) + go func() { + defer wg.Done() + if err := burnCPU(context.Background(), 30*time.Millisecond); err != nil { + t.Error(err) + } + }() + } + wg.Wait() + // Two 30ms CPU jobs sharing one P need ~60ms of wall time. + if d := time.Since(t0); d < 50*time.Millisecond { + t.Fatalf("two 30ms burns on one P finished in %v; want >= 50ms", d) + } +} + +func TestSlowAndCPU_StopWhenClientGoes(t *testing.T) { + for name, h := range map[string]http.HandlerFunc{"slow": Slow(3 * time.Second), "cpu": CPU(1 << 40)} { + ctx, cancel := context.WithCancel(context.Background()) + go func() { time.Sleep(20 * time.Millisecond); cancel() }() + t0 := time.Now() + h(httptest.NewRecorder(), httptest.NewRequest("GET", "/", nil).WithContext(ctx)) + if time.Since(t0) > 200*time.Millisecond { + t.Fatalf("%s kept running %v after cancel", name, time.Since(t0)) + } + } +} + +func TestReady_FollowsLifecycle(t *testing.T) { + var h Health + assertEq(t, code(h.Ready), 503) + h.SetReady(true) + assertEq(t, code(h.Ready), 200) + h.SetDraining() + assertEq(t, code(h.Ready), 503) + assertEq(t, code(h.Live), 200) +} + +func TestStatus_UsesConfiguredTargets(t *testing.T) { + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + defer up.Close() + cfg := Config{StatusTargets: map[string]string{"prometheus": up.URL, "ghost": "http://127.0.0.1:1"}} + rec := httptest.NewRecorder() + Status(cfg, &http.Client{Timeout: time.Second})(rec, httptest.NewRequest("GET", "/status", nil)) + var got map[string]struct{ Status string } + _ = json.NewDecoder(rec.Body).Decode(&got) + assertEq(t, got["prometheus"].Status, "online") + assertEq(t, got["ghost"].Status, "offline") +} diff --git a/backend/helpers_test.go b/backend/helpers_test.go new file mode 100644 index 0000000..a043666 --- /dev/null +++ b/backend/helpers_test.go @@ -0,0 +1,127 @@ +package main + +import ( + "context" + "net" + "net/http" + "net/http/httptest" + "slices" + "testing" + "time" + + "github.com/prometheus/client_golang/prometheus" + dto "github.com/prometheus/client_model/go" +) + +func assertEq[T comparable](t *testing.T, got, want T) { + t.Helper() + if got != want { + t.Errorf("got %v, want %v", got, want) + } +} + +func findMetric(t *testing.T, reg *prometheus.Registry, name string, labels map[string]string) *dto.Metric { + t.Helper() + mfs, err := reg.Gather() + if err != nil { + t.Fatal(err) + } + for _, mf := range mfs { + if mf.GetName() != name { + continue + } + for _, m := range mf.GetMetric() { + ok := true + for k, v := range labels { + found := false + for _, lp := range m.GetLabel() { + found = found || (lp.GetName() == k && lp.GetValue() == v) + } + ok = ok && found + } + if ok { + return m + } + } + } + t.Fatalf("metric %s %v not found", name, labels) + return nil +} + +func assertBuckets(t *testing.T, reg *prometheus.Registry, name string, want []float64) { + t.Helper() + var got []float64 + for _, b := range findMetric(t, reg, name, nil).GetHistogram().GetBucket() { + got = append(got, b.GetUpperBound()) + } + if !slices.Equal(got, want) { + t.Errorf("buckets %v, want %v", got, want) + } +} + +func gaugeValue(t *testing.T, reg *prometheus.Registry, name string, labels map[string]string) float64 { + t.Helper() + return findMetric(t, reg, name, labels).GetGauge().GetValue() +} + +func code(h http.HandlerFunc) int { + rec := httptest.NewRecorder() + h(rec, httptest.NewRequest("GET", "/", nil)) + return rec.Code +} + +func serve(h http.Handler, path string) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest("GET", path, nil)) + return rec +} + +// serveCancelled sends a request whose context is already cancelled, so slow handlers return at once. +func serveCancelled(h http.Handler, path string) *httptest.ResponseRecorder { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest("GET", path, nil).WithContext(ctx)) + return rec +} + +func get(h http.Handler, path string) *httptest.ResponseRecorder { return serve(h, path) } + +func post(h http.Handler, path string) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest("POST", path, nil)) + return rec +} + +func ok200() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) +} + +func waitFor(t *testing.T, cond func() bool) { + t.Helper() + for end := time.Now().Add(2 * time.Second); time.Now().Before(end); time.Sleep(5 * time.Millisecond) { + if cond() { + return + } + } + t.Fatal("condition not met within 2s") +} + +func listen(t *testing.T) net.Listener { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ln.Close() }) + return ln +} + +// waitListening waits until Run has marked h ready, then returns srv's base URL. +// Run stores the bound address into srv.Addr before the atomic SetReady, so the +// read below happens-after the write. +func waitListening(t *testing.T, h *Health, srv *http.Server) string { + t.Helper() + waitFor(t, func() bool { return code(h.Ready) == http.StatusOK }) + return "http://" + srv.Addr +} diff --git a/backend/main.go b/backend/main.go index d08af13..f63dfc5 100644 --- a/backend/main.go +++ b/backend/main.go @@ -1,191 +1,36 @@ package main import ( - "encoding/json" - "fmt" - "math" + "context" + "log" "net/http" "os" - "runtime" - "strconv" + "os/signal" + "syscall" "time" "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/promauto" - "github.com/prometheus/client_golang/prometheus/promhttp" ) -var startTime = time.Now() - -// --- Metrics --- - -var requestCounter = promauto.NewCounterVec( - prometheus.CounterOpts{ - Name: "http_requests_total", - Help: "Total number of HTTP requests", - }, - []string{"route", "status"}, -) - -var requestDuration = promauto.NewHistogramVec( - prometheus.HistogramOpts{ - Name: "http_request_duration_seconds", - Help: "Duration of HTTP requests in seconds", - Buckets: []float64{0.05, 0.1, 0.3, 0.5, 1, 2, 5, 10}, - }, - []string{"route"}, -) - -// --- Middleware: track duration for all routes --- - -func instrumentHandler(route string, handler http.HandlerFunc) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - timer := prometheus.NewTimer(requestDuration.WithLabelValues(route)) - defer timer.ObserveDuration() - - rec := &statusRecorder{ResponseWriter: w, statusCode: http.StatusOK} - handler(rec, r) - - requestCounter.WithLabelValues(route, strconv.Itoa(rec.statusCode)).Inc() - } -} - -// statusRecorder wraps http.ResponseWriter to capture the status code. -type statusRecorder struct { - http.ResponseWriter - statusCode int -} - -func (r *statusRecorder) WriteHeader(code int) { - r.statusCode = code - r.ResponseWriter.WriteHeader(code) -} - -// --- Helpers --- - -func writeJSON(w http.ResponseWriter, v any) { - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(v) -} - -// --- Routes --- - -// Basic health check — fast, always succeeds -func healthHandler(w http.ResponseWriter, r *http.Request) { - writeJSON(w, map[string]string{ - "status": "ok", - "timestamp": time.Now().UTC().Format(time.RFC3339Nano), - }) -} - -// Simulates a slow upstream dependency (3s delay) -func slowHandler(w http.ResponseWriter, r *http.Request) { - time.Sleep(3 * time.Second) - writeJSON(w, map[string]any{ - "endpoint": "slow", - "delay_ms": 3000, - }) -} - -// CPU-intensive: counts primes up to 1,000,000 -func cpuHandler(w http.ResponseWriter, r *http.Request) { - count := 0 - for i := 2; i < 1_000_000; i++ { - prime := true - limit := int(math.Sqrt(float64(i))) - for j := 2; j <= limit; j++ { - if i%j == 0 { - prime = false - break - } - } - if prime { - count++ - } - } - writeJSON(w, map[string]any{ - "endpoint": "cpu", - "primes_found": count, - }) -} - -// Memory-intensive: allocates a large slice -func memoryHandler(w http.ResponseWriter, r *http.Request) { - type obj struct { - Index int `json:"index"` - Value float64 `json:"value"` - } - arr := make([]obj, 0, 1_000_000) - for i := 0; i < 1_000_000; i++ { - arr = append(arr, obj{Index: i, Value: float64(i) * 0.1}) - } - writeJSON(w, map[string]any{ - "endpoint": "memory", - "allocated": len(arr), - }) -} - -// Server info -func infoHandler(w http.ResponseWriter, r *http.Request) { - env := os.Getenv("APP_ENV") - if env == "" { - env = "development" - } - writeJSON(w, map[string]any{ - "app": "LoadLab", - "go": runtime.Version(), - "uptime_seconds": int(time.Since(startTime).Seconds()), - "timestamp": time.Now().UTC().Format(time.RFC3339Nano), - "environment": env, - }) -} - -var probeClient = &http.Client{Timeout: 3 * time.Second} - -// Service health status — pings Prometheus and Grafana from inside Docker network -func statusHandler(w http.ResponseWriter, r *http.Request) { - type result struct { - Status string `json:"status"` - Ms int `json:"ms"` - } - - probe := func(url string) result { - t0 := time.Now() - resp, err := probeClient.Get(url) - ms := int(time.Since(t0).Milliseconds()) - if err != nil { - return result{Status: "offline", Ms: ms} - } - resp.Body.Close() - if resp.StatusCode >= 500 { - return result{Status: "offline", Ms: ms} - } - return result{Status: "online", Ms: ms} - } - - writeJSON(w, map[string]any{ - "prometheus": probe("http://prometheus:9090/-/healthy"), - "grafana": probe("http://grafana:3000/api/health"), - }) -} - -// --- Start --- +// buildVersion is set at link time with -X main.buildVersion=...; APP_VERSION overrides it. +var buildVersion = "dev" func main() { - mux := http.NewServeMux() - - mux.HandleFunc("/health", instrumentHandler("/health", healthHandler)) - mux.HandleFunc("/slow", instrumentHandler("/slow", slowHandler)) - mux.HandleFunc("/cpu", instrumentHandler("/cpu", cpuHandler)) - mux.HandleFunc("/memory", instrumentHandler("/memory", memoryHandler)) - mux.HandleFunc("/info", instrumentHandler("/info", infoHandler)) - mux.HandleFunc("/status", instrumentHandler("/status", statusHandler)) - - // Prometheus metrics scrape endpoint - mux.Handle("/metrics", promhttp.Handler()) - - fmt.Println("LoadLab backend running on port 3000") - if err := http.ListenAndServe(":3000", mux); err != nil { - fmt.Printf("Server failed: %v\n", err) + cfg := LoadConfig(os.Getenv, log.Printf) + var health Health + public := NewPublicServer(":3000", PublicMux(cfg, NewMetrics(prometheus.DefaultRegisterer, cfg.Version), &health, time.Now())) + admin := &http.Server{ // internal-only admin listener; not exposed by the Service + Addr: ":9091", + Handler: AdminMux(NewLeaker(time.Tick(time.Second))), + ReadHeaderTimeout: 5 * time.Second, + } + + calibrateCPU() // before serving, so the first request is not slowed + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + err := Run(ctx, cfg, &health, public, admin, log.Printf) + stop() + if err != nil { + log.Printf("server: %v", err) + os.Exit(1) } } diff --git a/backend/metrics.go b/backend/metrics.go new file mode 100644 index 0000000..583ada2 --- /dev/null +++ b/backend/metrics.go @@ -0,0 +1,64 @@ +package main + +import ( + "net/http" + "strconv" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promauto" +) + +type Metrics struct { + requests *prometheus.CounterVec + duration *prometheus.HistogramVec + inFlight prometheus.Gauge +} + +func NewMetrics(reg prometheus.Registerer, version string) *Metrics { + f := promauto.With(reg) + f.NewGaugeVec(prometheus.GaugeOpts{ + Name: "build_info", + Help: "Build information; value is always 1", + }, []string{"version"}).WithLabelValues(version).Set(1) + return &Metrics{ + requests: f.NewCounterVec(prometheus.CounterOpts{ + Name: "http_requests_total", + Help: "Total number of HTTP requests", + }, []string{"route", "status"}), + duration: f.NewHistogramVec(prometheus.HistogramOpts{ + Name: "http_request_duration_seconds", + Help: "Duration of HTTP requests in seconds", + Buckets: []float64{0.01, 0.025, 0.05, 0.075, 0.1, 0.15, 0.2, 0.25, 0.3, 0.4, 0.5, 0.75, 1, 2, 5}, + }, []string{"route"}), + inFlight: f.NewGauge(prometheus.GaugeOpts{ + Name: "http_requests_in_flight", + Help: "Number of HTTP requests currently being served", + }), + } +} + +// Instrument records count, duration and in-flight gauge around h. +func (m *Metrics) Instrument(route string, h http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + m.inFlight.Inc() + defer m.inFlight.Dec() + timer := prometheus.NewTimer(m.duration.WithLabelValues(route)) + defer timer.ObserveDuration() + + rec := &statusRecorder{ResponseWriter: w, statusCode: http.StatusOK} + h(rec, r) + + m.requests.WithLabelValues(route, strconv.Itoa(rec.statusCode)).Inc() + } +} + +// statusRecorder wraps http.ResponseWriter to capture the status code. +type statusRecorder struct { + http.ResponseWriter + statusCode int +} + +func (r *statusRecorder) WriteHeader(code int) { + r.statusCode = code + r.ResponseWriter.WriteHeader(code) +} diff --git a/backend/metrics_test.go b/backend/metrics_test.go new file mode 100644 index 0000000..b330171 --- /dev/null +++ b/backend/metrics_test.go @@ -0,0 +1,33 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/testutil" +) + +func TestMetrics_BucketsMatchSLO(t *testing.T) { + reg := prometheus.NewRegistry() + m := NewMetrics(reg, "v1") + m.Instrument("/work", func(w http.ResponseWriter, r *http.Request) {})(httptest.NewRecorder(), httptest.NewRequest("GET", "/work", nil)) + want := []float64{0.01, 0.025, 0.05, 0.075, 0.1, 0.15, 0.2, 0.25, 0.3, 0.4, 0.5, 0.75, 1, 2, 5} + assertBuckets(t, reg, "http_request_duration_seconds", want) +} + +func TestMetrics_InstrumentCountsStatusAndInFlight(t *testing.T) { + reg := prometheus.NewRegistry() + m := NewMetrics(reg, "v1") + seen := -1.0 + h := m.Instrument("/work", func(w http.ResponseWriter, r *http.Request) { + seen = testutil.ToFloat64(m.inFlight) + w.WriteHeader(http.StatusTeapot) + }) + h(httptest.NewRecorder(), httptest.NewRequest("GET", "/work", nil)) + assertEq(t, seen, 1.0) // gauge raised during the request + assertEq(t, testutil.ToFloat64(m.inFlight), 0.0) // and lowered after + assertEq(t, testutil.ToFloat64(m.requests.WithLabelValues("/work", "418")), 1.0) + assertEq(t, gaugeValue(t, reg, "build_info", map[string]string{"version": "v1"}), 1.0) +} diff --git a/backend/routes.go b/backend/routes.go new file mode 100644 index 0000000..7cef672 --- /dev/null +++ b/backend/routes.go @@ -0,0 +1,56 @@ +package main + +import ( + "math/rand/v2" + "net/http" + "os" + "strconv" + "time" + + "github.com/prometheus/client_golang/prometheus/promhttp" +) + +// PublicMux serves the app routes on the public port. It has no admin routes. +func PublicMux(cfg Config, m *Metrics, h *Health, start time.Time) http.Handler { + routes := map[string]http.HandlerFunc{ + "/work": Work(cfg), + "/slow": Slow(3 * time.Second), + "/cpu": CPU(1_000_000), + "/memory": Memory, + "/info": Info(cfg, start), + "/status": Status(cfg, &http.Client{Timeout: 3 * time.Second}), + "/health": healthHandler, // Compose frontend; body kept as before + "/livez": h.Live, + "/readyz": h.Ready, + "/metrics": promhttp.Handler().ServeHTTP, + } + mux := http.NewServeMux() + for route, fn := range routes { + mux.HandleFunc(route, m.Instrument(route, FaultMiddleware(cfg, rand.Float64, fn).ServeHTTP)) + } + return mux +} + +// AdminMux is the internal-only listener: the memory-leak switch. +func AdminMux(l *Leaker) http.Handler { + pod, _ := os.Hostname() + mux := http.NewServeMux() + mux.HandleFunc("POST /admin/leak", func(w http.ResponseWriter, r *http.Request) { + n, err := strconv.Atoi(r.URL.Query().Get("mb_per_min")) + if err != nil || n < 1 { + w.WriteHeader(http.StatusBadRequest) + writeJSON(w, map[string]string{"error": "mb_per_min must be an integer >= 1"}) + return + } + n = min(n, 200) + l.Start(n) + w.WriteHeader(http.StatusAccepted) + writeJSON(w, map[string]any{"mb_per_min": n, "pod": pod}) + }) + mux.HandleFunc("POST /admin/leak/stop", func(w http.ResponseWriter, r *http.Request) { + l.Stop() + w.WriteHeader(http.StatusAccepted) + writeJSON(w, map[string]string{"status": "stopped", "pod": pod}) + }) + return mux +} diff --git a/backend/routes_test.go b/backend/routes_test.go new file mode 100644 index 0000000..ced9528 --- /dev/null +++ b/backend/routes_test.go @@ -0,0 +1,48 @@ +package main + +import ( + "encoding/json" + "os" + "testing" + "time" + + "github.com/prometheus/client_golang/prometheus" +) + +func TestPublicMux_HasNoAdminRoutes(t *testing.T) { + mux := PublicMux(Config{}, NewMetrics(prometheus.NewRegistry(), "t"), &Health{}, time.Now()) + assertEq(t, post(mux, "/admin/leak?mb_per_min=10").Code, 404) + for _, p := range []string{"/work", "/slow", "/cpu", "/memory", "/info", "/status", "/health", "/livez", "/readyz", "/metrics"} { + if serveCancelled(mux, p).Code == 404 { + t.Errorf("%s missing", p) + } + } +} + +func TestPublicMux_InjectedFaultsReachMetrics(t *testing.T) { + reg := prometheus.NewRegistry() + mux := PublicMux(Config{FaultErrorRate: 1}, NewMetrics(reg, "t"), &Health{}, time.Now()) + assertEq(t, get(mux, "/info").Code, 500) + assertEq(t, get(mux, "/livez").Code, 200) + got := findMetric(t, reg, "http_requests_total", map[string]string{"route": "/info", "status": "500"}) + assertEq(t, got.GetCounter().GetValue(), 1.0) +} + +func TestAdminMux_ResponsesNamePod(t *testing.T) { + want, err := os.Hostname() + if err != nil { + t.Fatal(err) + } + mux := AdminMux(NewLeaker(make(chan time.Time))) + for _, p := range []string{"/admin/leak?mb_per_min=1", "/admin/leak/stop"} { + rec := post(mux, p) + assertEq(t, rec.Code, 202) + var body struct { + Pod string `json:"pod"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + assertEq(t, body.Pod, want) + } +} diff --git a/backend/server.go b/backend/server.go new file mode 100644 index 0000000..435bc45 --- /dev/null +++ b/backend/server.go @@ -0,0 +1,73 @@ +package main + +import ( + "context" + "errors" + "net" + "net/http" + "time" +) + +// NewPublicServer bounds how long a client may take to send headers and body, +// so slow or stuck clients cannot pin connections. +func NewPublicServer(addr string, h http.Handler) *http.Server { + return &http.Server{ + Addr: addr, + Handler: h, + ReadHeaderTimeout: 5 * time.Second, + ReadTimeout: 10 * time.Second, + WriteTimeout: 15 * time.Second, + IdleTimeout: 60 * time.Second, + MaxHeaderBytes: 64 << 10, + } +} + +// Run binds both servers, marks the pod ready and serves until ctx is done or a +// server fails. It then fails readiness and drains in-flight requests for up to +// cfg.Drain. Each server's Addr is rewritten to the bound address before +// SetReady(true), so a reader that has seen readiness sees the real port. +func Run(ctx context.Context, cfg Config, health *Health, public, admin *http.Server, logf func(string, ...any)) error { + servers := []*http.Server{public, admin} + lns := make([]net.Listener, 0, len(servers)) + for _, s := range servers { + ln, err := net.Listen("tcp", s.Addr) + if err != nil { + for _, l := range lns { + l.Close() + } + return err + } + s.Addr = ln.Addr().String() + lns = append(lns, ln) + } + health.SetReady(true) + + serveErr := make(chan error, len(servers)) + for i, s := range servers { + go func() { serveErr <- s.Serve(lns[i]) }() + } + logf("listening: public=%s admin=%s", public.Addr, admin.Addr) + + var err error + select { + case <-ctx.Done(): + case err = <-serveErr: // Serve only returns early on failure; it is never ErrServerClosed here + logf("serve failed: %v", err) + } + + health.SetDraining() + logf("draining (up to %v)", cfg.Drain) + sctx, cancel := context.WithTimeout(context.Background(), cfg.Drain) + defer cancel() + shutErr := make(chan error, len(servers)) + for _, s := range servers { + go func() { shutErr <- s.Shutdown(sctx) }() + } + for range servers { + if e := <-shutErr; err == nil && !errors.Is(e, http.ErrServerClosed) { + err = e + } + } + logf("stopped") + return err +} diff --git a/backend/server_test.go b/backend/server_test.go new file mode 100644 index 0000000..f449d69 --- /dev/null +++ b/backend/server_test.go @@ -0,0 +1,66 @@ +package main + +import ( + "context" + "net" + "net/http" + "testing" + "time" + + "github.com/prometheus/client_golang/prometheus" +) + +func TestPublicServer_Timeouts(t *testing.T) { + s := NewPublicServer(":0", http.NewServeMux()) + assertEq(t, s.ReadHeaderTimeout, 5*time.Second) + assertEq(t, s.ReadTimeout, 10*time.Second) + assertEq(t, s.WriteTimeout, 15*time.Second) + assertEq(t, s.IdleTimeout, 60*time.Second) + assertEq(t, s.MaxHeaderBytes, 64<<10) +} + +func TestPublicServer_ClosesSlowHeaderClient(t *testing.T) { + s := NewPublicServer("127.0.0.1:0", http.NewServeMux()) + s.ReadHeaderTimeout = 200 * time.Millisecond // shortened for the test + ln := listen(t) + go s.Serve(ln) + defer s.Close() + c, err := net.Dial("tcp", ln.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer c.Close() + _, _ = c.Write([]byte("GET / HTTP/1.1\r\nHost: x\r\n")) // never finishes the headers + _ = c.SetReadDeadline(time.Now().Add(2 * time.Second)) + t0 := time.Now() + _, err = c.Read(make([]byte, 1)) + if err == nil || time.Since(t0) > time.Second { + t.Fatalf("slow client not cut off: err=%v after %v", err, time.Since(t0)) + } +} + +func TestRun_DrainsInFlightRequest(t *testing.T) { + cfg := Config{WorkWait: 300 * time.Millisecond, WorkTimeout: 2 * time.Second, Drain: 2 * time.Second} + var h Health + pub := NewPublicServer("127.0.0.1:0", PublicMux(cfg, NewMetrics(prometheus.NewRegistry(), "t"), &h, time.Now())) + adm := &http.Server{Addr: "127.0.0.1:0", Handler: AdminMux(NewLeaker(make(chan time.Time)))} + ctx, stop := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { done <- Run(ctx, cfg, &h, pub, adm, t.Logf) }() + base := waitListening(t, &h, pub) // readiness true, then Addr holds the bound address + resp := make(chan int, 1) + go func() { + r, err := http.Get(base + "/work") + if err != nil { + resp <- -1 + return + } + r.Body.Close() + resp <- r.StatusCode + }() + time.Sleep(50 * time.Millisecond) + stop() // SIGTERM equivalent, mid-request + assertEq(t, <-resp, 200) // in-flight request finished + assertEq(t, <-done, nil) + assertEq(t, code(h.Ready), 503) // readiness went false +} diff --git a/docker-compose.yml b/docker-compose.yml index b82af39..0614761 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -36,8 +36,7 @@ services: environment: - GF_AUTH_ANONYMOUS_ENABLED=true - GF_AUTH_ANONYMOUS_ORG_ROLE=Viewer - - GF_SERVER_DOMAIN=43.204.103.85 - - GF_SERVER_ROOT_URL=http://43.204.103.85/grafana/ + - GF_SERVER_ROOT_URL=%(protocol)s://%(domain)s:%(http_port)s/grafana/ - GF_SERVER_SERVE_FROM_SUB_PATH=true - GF_SERVER_ENABLE_GZIP=true - GF_DASHBOARDS_DEFAULT_HOME_DASHBOARD_PATH=/etc/grafana/dashboards/loadlab.json diff --git a/k6/capacity-test.js b/k6/capacity-test.js new file mode 100644 index 0000000..fc9f214 --- /dev/null +++ b/k6/capacity-test.js @@ -0,0 +1,34 @@ +import http from "k6/http"; +import { check } from "k6"; + +// One step of the per-pod capacity test: a fixed arrival rate against /work. +// Driven by scripts/capacity.py, which steps RATE up until the SLO breaks. +export const options = { + scenarios: { + step: { + executor: "constant-arrival-rate", + rate: Number(__ENV.RATE || 10), + timeUnit: "1s", + duration: __ENV.DURATION || "60s", + preAllocatedVUs: 200, + }, + }, +}; + +const BASE_URL = __ENV.BASE_URL || "http://localhost:3000"; + +export default function () { + const res = http.get(`${BASE_URL}/work`); + + check(res, { + "status is 200": (r) => r.status === 200, + }); +} + +export function handleSummary(data) { + const out = { + p95_ms: data.metrics.http_req_duration.values["p(95)"], + failed_rate: data.metrics.http_req_failed.values.rate, + }; + return { [__ENV.OUT || "capacity-step.json"]: JSON.stringify(out) }; +} diff --git a/results/capacity.json b/results/capacity.json new file mode 100644 index 0000000..acc2d9d --- /dev/null +++ b/results/capacity.json @@ -0,0 +1,34 @@ +{ + "rps_per_pod": 40, + "slo_ms": 200, + "image": "loadlab-backend:local", + "levels": [ + { + "rps": 10, + "p95_ms": 55.98, + "failed_rate": 0 + }, + { + "rps": 20, + "p95_ms": 54.94, + "failed_rate": 0 + }, + { + "rps": 30, + "p95_ms": 54.04, + "failed_rate": 0 + }, + { + "rps": 40, + "p95_ms": 53.65, + "failed_rate": 0 + }, + { + "rps": 50, + "p95_ms": 11491.61, + "failed_rate": 0.0543 + } + ], + "measured_at": "2026-11-01T06:09:54+00:00", + "step_duration_s": 60 +} diff --git a/scripts/capacity.py b/scripts/capacity.py new file mode 100644 index 0000000..6f78601 --- /dev/null +++ b/scripts/capacity.py @@ -0,0 +1,109 @@ +"""Per-pod capacity step test: highest /work rps one 1 CPU / 128 MiB container +serves with p95 <= SLO and <= 1% failures. Stdlib only.""" +import argparse +import json +import os +import shutil +import subprocess +import tempfile +import time +import urllib.request +from datetime import datetime, timezone + +IMAGE = "loadlab-backend:local" +SLO_MS = 200 +MAX_FAILED_RATE = 0.01 +STEP_RPS = 10 +CEILING_RPS = 300 # safety cap so a misconfigured run can't step forever +BASE_URL = "http://localhost:3000" +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +def passes(level, slo_ms): + return level["p95_ms"] <= slo_ms and level["failed_rate"] <= MAX_FAILED_RATE + + +def capacity_from_levels(levels, slo_ms): + """rps of the last consecutive passing level before the first failure.""" + best = None + for level in levels: + if not passes(level, slo_ms): + break + best = level["rps"] + if best is None: + raise ValueError("first level already fails the SLO; no capacity measured") + return best + + +def wait_ready(timeout_s=60): + deadline = time.monotonic() + timeout_s + while time.monotonic() < deadline: + try: + with urllib.request.urlopen(f"{BASE_URL}/readyz", timeout=2) as r: + if r.status == 200: + return + except OSError: + pass + time.sleep(0.5) + raise RuntimeError(f"/readyz not ready after {timeout_s}s") + + +def run_step(k6, rps, duration_s, tmpdir): + out = os.path.join(tmpdir, f"step-{rps}.json") + subprocess.run( + [k6, "run", "--quiet", + "-e", f"RATE={rps}", "-e", f"DURATION={duration_s}s", + "-e", f"BASE_URL={BASE_URL}", "-e", f"OUT={out}", + os.path.join(ROOT, "k6", "capacity-test.js")], + check=True, + ) + with open(out) as f: + s = json.load(f) + return {"rps": rps, "p95_ms": round(s["p95_ms"], 2), "failed_rate": round(s["failed_rate"], 4)} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--duration", type=int, default=60, help="seconds per step") + args = ap.parse_args() + + docker, k6 = shutil.which("docker"), shutil.which("k6") + if not docker or not k6: + raise SystemExit("docker and k6 must be on PATH") + + cid = subprocess.run( + [docker, "run", "-d", "--cpus", "1", "-m", "128m", "-p", "3000:3000", IMAGE], + check=True, capture_output=True, text=True, + ).stdout.strip() + levels = [] + try: + wait_ready() + with tempfile.TemporaryDirectory() as tmpdir: + for rps in range(STEP_RPS, CEILING_RPS + 1, STEP_RPS): + level = run_step(k6, rps, args.duration, tmpdir) + levels.append(level) + print(f"rps={level['rps']} p95_ms={level['p95_ms']} failed_rate={level['failed_rate']}", flush=True) + if not passes(level, SLO_MS): + break + else: + print(f"NOTE: reached {CEILING_RPS} rps ceiling without breaking the SLO") + finally: + subprocess.run([docker, "rm", "-f", cid], capture_output=True) + + rps_per_pod = capacity_from_levels(levels, SLO_MS) + os.makedirs(os.path.join(ROOT, "results"), exist_ok=True) + with open(os.path.join(ROOT, "results", "capacity.json"), "w") as f: + json.dump({ + "rps_per_pod": rps_per_pod, + "slo_ms": SLO_MS, + "image": IMAGE, + "levels": levels, + "measured_at": datetime.now(timezone.utc).isoformat(timespec="seconds"), + "step_duration_s": args.duration, + }, f, indent=2) + f.write("\n") + print(f"rps_per_pod={rps_per_pod}") + + +if __name__ == "__main__": + main() diff --git a/scripts/test_capacity.py b/scripts/test_capacity.py new file mode 100644 index 0000000..165631a --- /dev/null +++ b/scripts/test_capacity.py @@ -0,0 +1,25 @@ +import os +import sys +import unittest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from capacity import capacity_from_levels # noqa: E402 + + +class CapacityFromLevels(unittest.TestCase): + def test_last_level_under_slo(self): + levels = [{"rps": 10, "p95_ms": 60, "failed_rate": 0}, {"rps": 20, "p95_ms": 120, "failed_rate": 0}, + {"rps": 30, "p95_ms": 240, "failed_rate": 0}] + self.assertEqual(capacity_from_levels(levels, slo_ms=200), 20) + + def test_failures_disqualify_a_level(self): + levels = [{"rps": 10, "p95_ms": 60, "failed_rate": 0}, {"rps": 20, "p95_ms": 90, "failed_rate": 0.02}] + self.assertEqual(capacity_from_levels(levels, slo_ms=200), 10) + + def test_first_level_already_over_slo_is_an_error(self): + with self.assertRaises(ValueError): + capacity_from_levels([{"rps": 10, "p95_ms": 500, "failed_rate": 0}], slo_ms=200) + + +if __name__ == "__main__": + unittest.main()