Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# The dashboard is a single demo page; this repo is about the Go backend.
frontend/index.html linguist-detectable=false
26 changes: 26 additions & 0 deletions .github/workflows/backend.yml
Original file line number Diff line number Diff line change
@@ -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 .
36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,14 +85,50 @@ 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 |
| `GET /api/info` | Go version, uptime, environment | — |
| `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.
Expand Down
19 changes: 12 additions & 7 deletions backend/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,20 +1,25 @@
# Build stage
FROM golang:1.24-alpine AS builder
ARG VERSION=dev

WORKDIR /app

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"]
70 changes: 70 additions & 0 deletions backend/config.go
Original file line number Diff line number Diff line change
@@ -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
}
45 changes: 45 additions & 0 deletions backend/config_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
94 changes: 94 additions & 0 deletions backend/faults.go
Original file line number Diff line number Diff line change
@@ -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)
})
}
56 changes: 56 additions & 0 deletions backend/faults_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
Loading
Loading