Files
urutau/internal/probeagent/probe_test.go
T
Lucas RayanandClaude Opus 5.5 8546d14cef
CI / Format and vet (pull_request) Failing after 53s
CI / Dependency audit (pull_request) Successful in 33s
CI / Tests (Linux, race detector) (pull_request) Successful in 2m1s
CI / Docker images (build and smoke test) (pull_request) Failing after 47s
feat!: Urutau 2.0.0, ultralight probes and a single analysis hub
Each server runs an ultralight probe (scratch image, ~7 MiB RSS) that
tails the logs, ships raw lines to the hub over HTTPS with an on-disk
spool, and applies enforce decisions locally. The hub keeps one node per
probe (primary node = the 1.x data dir, unchanged), does all analysis and
serves the UI. Peer federation is removed. 'urutau import' brings 1.x
data dirs in with hash and count verification. UI: probes page, host
qualified incidents, IPs never wrap, egress heatmap labels, live and
replay globes no longer auto-rotate, replay repeat, live traffic metrics.

BREAKING CHANGE: URUTAU_PEERS, URUTAU_PEER_* and /api/v1/peer/* are gone;
log path variables move from the hub to the probe. See docs/migration-2.0.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 22:14:50 -03:00

743 lines
21 KiB
Go

package probeagent
import (
"bufio"
"bytes"
"compress/gzip"
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
const testToken = "urp_test"
// fakeHub is the smallest hub that speaks the protocol: it applies batches
// idempotently by seq, keeps the lines, and serves a command queue.
type fakeHub struct {
mu sync.Mutex
lines []wire.Line
files map[string]string
ack uint64
offsets map[string]wire.Pos
cmds []wire.Cmd
status *wire.Status
hellos []wire.Hello
gzipSeen int
pushes int
fail503 int // next N pushes answer 503 Retry-After: 1
flushMS int
discard bool // do not keep lines (memory test)
nlines int
}
func newFakeHub() *fakeHub {
return &fakeHub{files: map[string]string{}, offsets: map[string]wire.Pos{}, flushMS: 30}
}
func (h *fakeHub) handler() http.Handler {
mux := http.NewServeMux()
auth := func(w http.ResponseWriter, r *http.Request) bool {
if r.Header.Get("Authorization") != "Bearer "+testToken || r.Header.Get(wire.HeaderProbe) != "p1" {
w.WriteHeader(401)
return false
}
return true
}
mux.HandleFunc(wire.PathHello, func(w http.ResponseWriter, r *http.Request) {
if !auth(w, r) {
return
}
var hello wire.Hello
json.NewDecoder(r.Body).Decode(&hello)
if hello.Proto != wire.Proto {
w.WriteHeader(409)
return
}
h.mu.Lock()
defer h.mu.Unlock()
h.hellos = append(h.hellos, hello)
json.NewEncoder(w).Encode(wire.HelloResp{Proto: wire.Proto, HubVer: "t", Offsets: h.offsets, AckSeq: h.ack, FlushMS: h.flushMS})
})
mux.HandleFunc(wire.PathPush, func(w http.ResponseWriter, r *http.Request) {
if !auth(w, r) {
return
}
var body io.Reader = r.Body
if r.Header.Get("Content-Encoding") == "gzip" {
gz, err := gzip.NewReader(r.Body)
if err != nil {
w.WriteHeader(400)
return
}
body = gz
h.mu.Lock()
h.gzipSeen++
h.mu.Unlock()
}
var b wire.Batch
if err := json.NewDecoder(body).Decode(&b); err != nil {
w.WriteHeader(400)
return
}
h.mu.Lock()
defer h.mu.Unlock()
h.pushes++
if h.fail503 > 0 {
h.fail503--
w.Header().Set("Retry-After", "1")
w.WriteHeader(503)
return
}
h.status = b.Status
resp := wire.PushResp{}
if b.Seq > 0 && b.Seq > h.ack {
for _, l := range b.Lines {
h.nlines++
if !h.discard {
h.lines = append(h.lines, l)
}
h.offsets[l.Src] = l.End
}
for _, f := range b.Files {
h.files[f.Name] = f.Data
}
h.ack = b.Seq
resp.Accepted = len(b.Lines)
} else if b.Seq > 0 {
resp.Dup = len(b.Lines)
}
resp.Ack = h.ack
if n := len(h.cmds); n > 0 {
resp.PendCmd = h.cmds[n-1].Seq
}
json.NewEncoder(w).Encode(resp)
})
mux.HandleFunc(wire.PathCommands, func(w http.ResponseWriter, r *http.Request) {
if !auth(w, r) {
return
}
after, _ := strconv.ParseUint(r.URL.Query().Get("after"), 10, 64)
deadline := time.Now().Add(300 * time.Millisecond)
for {
h.mu.Lock()
var out []wire.Cmd
for _, c := range h.cmds {
if c.Seq > after {
out = append(out, c)
}
}
h.mu.Unlock()
if len(out) > 0 || time.Now().After(deadline) || r.Context().Err() != nil {
json.NewEncoder(w).Encode(wire.CmdResp{Cmds: out})
return
}
time.Sleep(10 * time.Millisecond)
}
})
return mux
}
func (h *fakeHub) texts() []string {
h.mu.Lock()
defer h.mu.Unlock()
var out []string
for _, l := range h.lines {
out = append(out, l.Src+":"+l.Text)
}
return out
}
func (h *fakeHub) count() int { h.mu.Lock(); defer h.mu.Unlock(); return h.nlines }
func quiet() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) }
func eventually(t *testing.T, what string, d time.Duration, f func() bool) {
t.Helper()
end := time.Now().Add(d)
for time.Now().Before(end) {
if f() {
return
}
time.Sleep(10 * time.Millisecond)
}
t.Fatalf("timeout waiting for %s", what)
}
type env struct {
dir, state string
cfg Config
}
func newEnv(t *testing.T, hubURL string) *env {
d := t.TempDir()
e := &env{dir: d, state: filepath.Join(d, "state")}
e.cfg = Config{
Hub: hubURL, Name: "p1", Token: testToken, StateDir: e.state,
Paths: map[string]string{
wire.SrcTraefik: filepath.Join(d, "traefik.log"),
wire.SrcAuth: filepath.Join(d, "auth.log"),
},
DecisionsLog: filepath.Join(d, "decisions.log"),
UnbanLog: filepath.Join(d, "unban.log"),
Poll: 10 * time.Millisecond,
SpoolMax: 64 << 20,
}
return e
}
func appendFile(t *testing.T, path string, lines ...string) {
t.Helper()
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
t.Fatal(err)
}
defer f.Close()
for _, l := range lines {
f.WriteString(l + "\n")
}
}
func startRun(ctx context.Context, c Config) chan error {
done := make(chan error, 1)
go func() { done <- Run(ctx, c, quiet()) }()
return done
}
func TestEndToEnd(t *testing.T) {
hub := newFakeHub()
srv := httptest.NewServer(hub.handler())
defer srv.Close()
e := newEnv(t, srv.URL)
e.cfg.Containers = filepath.Join(e.dir, "containers.map")
os.WriteFile(e.cfg.Containers, []byte("172.18.0.2 web\n"), 0o644)
e.cfg.Location = &wire.Location{Lat: 1, Lon: 2, Label: "x"}
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "t1", "t2")
ctx, cancel := context.WithCancel(context.Background())
done := startRun(ctx, e.cfg)
appendFile(t, e.cfg.Paths[wire.SrcAuth], "a1")
eventually(t, "3 lines", 5*time.Second, func() bool { return hub.count() == 3 })
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "t3\xff")
eventually(t, "4 lines", 5*time.Second, func() bool { return hub.count() == 4 })
eventually(t, "file", 2*time.Second, func() bool {
hub.mu.Lock()
defer hub.mu.Unlock()
return hub.files[wire.FileContainers] == "172.18.0.2 web\n"
})
hub.mu.Lock()
h := hub.hellos[0]
last := hub.lines[len(hub.lines)-1]
st := hub.status
hub.mu.Unlock()
if h.Name != "p1" || h.Location == nil || h.Location.Label != "x" || len(h.Sources) != 2 {
t.Errorf("hello %+v", h)
}
if !strings.HasSuffix(last.Text, "�") || last.End.Offset != 10 {
t.Errorf("last %+v", last)
}
if st == nil || len(st.Sources) != 2 || st.RSSBytes == 0 {
t.Errorf("status %+v", st)
}
cancel()
if err := <-done; err != nil {
t.Fatal(err)
}
if err := Check(e.state); err != nil {
t.Errorf("Check after run: %v", err)
}
}
func TestHubOutageNoLossNoDuplicates(t *testing.T) {
hub := newFakeHub()
var down sync.Mutex
isDown := false
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
down.Lock()
d := isDown
down.Unlock()
if d {
hj, _ := w.(http.Hijacker)
c, _, _ := hj.Hijack()
c.Close()
return
}
hub.handler().ServeHTTP(w, r)
}))
defer srv.Close()
e := newEnv(t, srv.URL)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
startRun(ctx, e.cfg)
tp := e.cfg.Paths[wire.SrcTraefik]
appendFile(t, tp, "first")
eventually(t, "first", 5*time.Second, func() bool { return hub.count() == 1 })
down.Lock()
isDown = true
down.Unlock()
for i := 0; i < 1000; i++ {
appendFile(t, tp, fmt.Sprintf("line-%04d", i))
}
time.Sleep(400 * time.Millisecond)
down.Lock()
isDown = false
down.Unlock()
eventually(t, "1001 lines", 15*time.Second, func() bool { return hub.count() == 1001 })
time.Sleep(200 * time.Millisecond)
got := hub.texts()
if len(got) != 1001 {
t.Fatalf("%d lines", len(got))
}
for i := 0; i < 1000; i++ {
if got[i+1] != fmt.Sprintf("traefik:line-%04d", i) {
t.Fatalf("line %d = %s", i, got[i+1])
}
}
}
func TestRestartResumesFromState(t *testing.T) {
hub := newFakeHub()
srv := httptest.NewServer(hub.handler())
defer srv.Close()
e := newEnv(t, srv.URL)
tp := e.cfg.Paths[wire.SrcTraefik]
appendFile(t, tp, "a", "b", "c")
ctx, cancel := context.WithCancel(context.Background())
done := startRun(ctx, e.cfg)
eventually(t, "3", 5*time.Second, func() bool { return hub.count() == 3 })
cancel()
<-done
appendFile(t, tp, "d")
ctx2, cancel2 := context.WithCancel(context.Background())
defer cancel2()
startRun(ctx2, e.cfg)
eventually(t, "4", 5*time.Second, func() bool { return hub.count() >= 4 })
time.Sleep(200 * time.Millisecond)
if got := hub.texts(); len(got) != 4 || got[3] != "traefik:d" {
t.Fatalf("%v", got)
}
}
func TestFreshProbeStartsAtHubOffsets(t *testing.T) {
hub := newFakeHub()
srv := httptest.NewServer(hub.handler())
defer srv.Close()
e := newEnv(t, srv.URL)
tp := e.cfg.Paths[wire.SrcTraefik]
appendFile(t, tp, "old1", "old2", "new1")
fi, _ := os.Stat(tp)
ino := inodeFor(fi)
hub.offsets[wire.SrcTraefik] = wire.Pos{Inode: ino, Offset: int64(len("old1\nold2\n"))}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
startRun(ctx, e.cfg)
eventually(t, "new1", 5*time.Second, func() bool { return hub.count() >= 1 })
time.Sleep(200 * time.Millisecond)
if got := hub.texts(); len(got) != 1 || got[0] != "traefik:new1" {
t.Fatalf("%v", got)
}
}
func TestHubAckAheadRaisesSeq(t *testing.T) {
hub := newFakeHub()
hub.ack = 50 // probe lost its state; hub remembers
srv := httptest.NewServer(hub.handler())
defer srv.Close()
e := newEnv(t, srv.URL)
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "x")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
startRun(ctx, e.cfg)
eventually(t, "x", 5*time.Second, func() bool { return hub.count() == 1 })
}
func TestPushBackpressure503RetryAfter(t *testing.T) {
hub := newFakeHub()
hub.fail503 = 1
srv := httptest.NewServer(hub.handler())
defer srv.Close()
e := newEnv(t, srv.URL)
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "x")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
start := time.Now()
startRun(ctx, e.cfg)
eventually(t, "x", 8*time.Second, func() bool { return hub.count() == 1 })
if el := time.Since(start); el < 900*time.Millisecond {
t.Errorf("retried after %v, Retry-After: 1 not honored", el)
}
hub.mu.Lock()
n := len(hub.hellos)
hub.mu.Unlock()
if n != 1 {
t.Errorf("%d hellos: a 503 must not force a reconnect", n)
}
}
func TestUnauthorizedStopsRun(t *testing.T) {
hub := newFakeHub()
srv := httptest.NewServer(hub.handler())
defer srv.Close()
e := newEnv(t, srv.URL)
e.cfg.Token = "wrong"
var logbuf strings.Builder
done := make(chan error, 1)
go func() { done <- Run(context.Background(), e.cfg, slog.New(slog.NewTextHandler(&logbuf, nil))) }()
select {
case err := <-done:
if err != ErrUnauthorized {
t.Fatalf("err = %v", err)
}
case <-time.After(5 * time.Second):
t.Fatal("Run did not stop on 401")
}
if !strings.Contains(logbuf.String(), "401") {
t.Errorf("401 not logged: %s", logbuf.String())
}
if strings.Contains(logbuf.String(), "wrong") {
t.Error("token leaked in log")
}
}
func TestUnauthorizedRevokedMidSession(t *testing.T) {
hub := newFakeHub()
var revoked sync.Mutex
rev := false
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
revoked.Lock()
x := rev
revoked.Unlock()
if x {
w.WriteHeader(401)
return
}
hub.handler().ServeHTTP(w, r)
}))
defer srv.Close()
e := newEnv(t, srv.URL)
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "x")
done := startRun(context.Background(), e.cfg)
eventually(t, "x", 5*time.Second, func() bool { return hub.count() == 1 })
revoked.Lock()
rev = true
revoked.Unlock()
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "y")
select {
case err := <-done:
if err != ErrUnauthorized {
t.Fatalf("err = %v", err)
}
case <-time.After(30 * time.Second):
t.Fatal("Run kept going after token revocation")
}
}
func TestGzipOverThreshold(t *testing.T) {
hub := newFakeHub()
srv := httptest.NewServer(hub.handler())
defer srv.Close()
e := newEnv(t, srv.URL)
big := strings.Repeat("abcdefghij", 200)
for i := 0; i < 20; i++ {
appendFile(t, e.cfg.Paths[wire.SrcTraefik], fmt.Sprintf("%d%s", i, big))
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
startRun(ctx, e.cfg)
eventually(t, "20", 5*time.Second, func() bool { return hub.count() == 20 })
hub.mu.Lock()
defer hub.mu.Unlock()
if hub.gzipSeen == 0 {
t.Error("large push was not gzipped")
}
if hub.lines[19].Text != "19"+big {
t.Error("gzip round trip altered the line")
}
}
func TestSmallPushNotGzipped(t *testing.T) {
hub := newFakeHub()
srv := httptest.NewServer(hub.handler())
defer srv.Close()
e := newEnv(t, srv.URL)
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "tiny")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
startRun(ctx, e.cfg)
eventually(t, "1", 5*time.Second, func() bool { return hub.count() == 1 })
hub.mu.Lock()
defer hub.mu.Unlock()
if hub.gzipSeen != 0 {
t.Error("small push gzipped")
}
}
func TestCommandsApplied(t *testing.T) {
hub := newFakeHub()
srv := httptest.NewServer(hub.handler())
defer srv.Close()
e := newEnv(t, srv.URL)
good := "2026-11-15T10:20:30Z urutau decision=ban ip=203.0.113.9 reason=rce score=90 ttl=300 host=h src=local\n"
unban := "2026-11-15T10:21:30Z urutau unban ip=203.0.113.9 allow=60\n"
evil := "2026-11-15T10:20:30Z urutau decision=ban ip=203.0.113.9 reason=rce score=90 ttl=300 host=h src=local\nrm -rf /\n"
hub.cmds = []wire.Cmd{
{Seq: 1, Kind: wire.CmdDecision, Line: good},
{Seq: 2, Kind: wire.CmdDecision, Line: evil},
{Seq: 3, Kind: wire.CmdDecision, Line: "garbage\n"},
{Seq: 4, Kind: wire.CmdUnban, Line: unban},
{Seq: 5, Kind: "other", Line: good},
}
ctx, cancel := context.WithCancel(context.Background())
done := startRun(ctx, e.cfg)
eventually(t, "cmds", 5*time.Second, func() bool {
s, err := loadState(e.state)
return err == nil && s.s.LastCmd == 5
})
cancel()
<-done
dec, _ := os.ReadFile(e.cfg.DecisionsLog)
if string(dec) != good {
t.Errorf("decisions.log = %q", dec)
}
ub, _ := os.ReadFile(e.cfg.UnbanLog)
if string(ub) != unban {
t.Errorf("unban.log = %q", ub)
}
// restart: the hub redelivers everything, nothing is applied twice
ctx2, cancel2 := context.WithCancel(context.Background())
done2 := startRun(ctx2, e.cfg)
time.Sleep(600 * time.Millisecond)
cancel2()
<-done2
dec, _ = os.ReadFile(e.cfg.DecisionsLog)
if string(dec) != good {
t.Errorf("decision duplicated after restart: %q", dec)
}
}
func TestApplyCmdsDirect(t *testing.T) {
e := newEnv(t, "http://127.0.0.1:1")
p, err := newProbe(e.cfg, quiet())
if err != nil {
t.Fatal(err)
}
good := "2026-11-15T10:20:30Z urutau decision=ban ip=2001:db8::1 reason=rce score=90 ttl=300 host=h src=peer:o\n"
cmds := []wire.Cmd{{Seq: 1, Kind: wire.CmdDecision, Line: good}, {Seq: 1, Kind: wire.CmdDecision, Line: good}, {Seq: 2, Kind: wire.CmdDecision, Line: "x\n"}}
if err := p.applyCmds(cmds); err != nil {
t.Fatal(err)
}
if err := p.applyCmds(cmds); err != nil {
t.Fatal(err)
}
b, _ := os.ReadFile(e.cfg.DecisionsLog)
if string(b) != good {
t.Errorf("%q", b)
}
if p.cmdErrors.Load() != 1 {
t.Errorf("cmdErrors = %d", p.cmdErrors.Load())
}
if p.st.lastCmd() != 2 {
t.Errorf("lastCmd = %d", p.st.lastCmd())
}
// no unban log configured: counted, not written
p.cfg.UnbanLog = ""
p.applyCmds([]wire.Cmd{{Seq: 3, Kind: wire.CmdUnban, Line: "2026-11-15T10:21:30Z urutau unban ip=1.2.3.4 allow=1\n"}})
if p.cmdErrors.Load() != 2 {
t.Errorf("cmdErrors = %d", p.cmdErrors.Load())
}
}
func TestBackoff(t *testing.T) {
for n, base := range map[int]float64{1: 1, 2: 2, 3: 4, 6: 32, 7: 60, 20: 60} {
for _, r := range []float64{0, 0.5, 0.999} {
d := backoff(n, func() float64 { return r }).Seconds()
if d < base*0.8-1e-9 || d > base*1.2+1e-9 {
t.Errorf("backoff(%d, %v) = %v, want %v +-20%%", n, r, d, base)
}
}
}
if backoff(3, func() float64 { return 0.5 }) != 4*time.Second {
t.Error("middle of jitter should be the base")
}
}
func TestOversizeLineCountedNotSent(t *testing.T) {
hub := newFakeHub()
srv := httptest.NewServer(hub.handler())
defer srv.Close()
e := newEnv(t, srv.URL)
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "ok", strings.Repeat("z", wire.MaxLine+10), "after")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
startRun(ctx, e.cfg)
eventually(t, "2 lines", 5*time.Second, func() bool { return hub.count() == 2 })
time.Sleep(100 * time.Millisecond)
if got := hub.texts(); len(got) != 2 || got[1] != "traefik:after" {
t.Fatalf("%v", got)
}
}
func TestMissingSourceWaitsAndNoPathLeak(t *testing.T) {
hub := newFakeHub()
srv := httptest.NewServer(hub.handler())
defer srv.Close()
e := newEnv(t, srv.URL)
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "x") // auth.log never created
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
startRun(ctx, e.cfg)
eventually(t, "x", 5*time.Second, func() bool { return hub.count() == 1 })
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "y")
eventually(t, "status", 5*time.Second, func() bool {
hub.mu.Lock()
defer hub.mu.Unlock()
if hub.status == nil {
return false
}
for _, s := range hub.status.Sources {
if s.Src == wire.SrcAuth && s.State == "waiting" {
return true
}
}
return false
})
hub.mu.Lock()
b, _ := json.Marshal(hub.status)
hub.mu.Unlock()
if strings.Contains(string(b), e.dir) {
t.Errorf("path leaked in status: %s", b)
}
}
func TestConfigValidation(t *testing.T) {
e := newEnv(t, "https://hub.example.com")
bad := func(m func(*Config)) {
c := e.cfg
m(&c)
if _, err := newProbe(c, quiet()); err == nil {
t.Error("invalid config accepted")
}
}
bad(func(c *Config) { c.Hub = "http://example.com" })
bad(func(c *Config) { c.Name = "Bad Name" })
bad(func(c *Config) { c.Token = "" })
bad(func(c *Config) { c.StateDir = "" })
}
func TestCheck(t *testing.T) {
d := t.TempDir()
if Check(d) == nil {
t.Error("missing state accepted")
}
st, _ := loadState(d)
st.touch()
if err := Check(d); err != nil {
t.Error(err)
}
st.s.Alive = time.Now().Add(-10 * time.Minute).Unix()
b, _ := json.Marshal(&st.s)
os.WriteFile(filepath.Join(d, "state.json"), b, 0o600)
if Check(d) == nil {
t.Error("stale state accepted")
}
}
// TestHelperProbe is the probe process of TestMemoryFootprint, run in a child
// so that nothing but the probe (and the test binary baseline) is measured.
func TestHelperProbe(t *testing.T) {
if os.Getenv("URUTAU_TEST_PROBE_CHILD") == "" {
t.Skip("helper for TestMemoryFootprint")
}
var cfg Config
if err := json.Unmarshal([]byte(os.Getenv("URUTAU_TEST_PROBE_CFG")), &cfg); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
done := startRun(ctx, cfg)
io.Copy(io.Discard, os.Stdin) // parent closes stdin when done
cancel()
<-done
var m runtime.MemStats
runtime.ReadMemStats(&m)
hwm := uint64(0)
if b, err := os.ReadFile("/proc/self/status"); err == nil {
for _, l := range strings.Split(string(b), "\n") {
if v, ok := strings.CutPrefix(l, "VmHWM:"); ok {
kb, _ := strconv.ParseUint(strings.Fields(v)[0], 10, 64)
hwm = kb << 10
}
}
}
fmt.Printf("RESULT sys=%d hwm=%d\n", m.Sys, hwm)
}
// 5 sources, 50k lines: the probe must stay small (target RSS < 20 MB).
func TestMemoryFootprint(t *testing.T) {
if raceOn {
t.Skip("the race detector inflates RSS; measured in the plain run")
}
hub := newFakeHub()
hub.discard = true
srv := httptest.NewServer(hub.handler())
defer srv.Close()
e := newEnv(t, srv.URL)
e.cfg.Paths = map[string]string{}
srcs := wire.Sources
line := `203.0.113.7 - - [15/Nov/2026:10:20:30 +0000] "GET /wp-login.php HTTP/1.1" 404 153 "-" "Mozilla/5.0 (X11; Linux x86_64)" 1234 "web@docker" "http://172.18.0.5:80" 3ms`
const per = 10000
for _, s := range srcs {
e.cfg.Paths[s] = filepath.Join(e.dir, s+".log")
f, _ := os.Create(e.cfg.Paths[s])
w := bufio.NewWriter(f)
for i := 0; i < per; i++ {
fmt.Fprintf(w, "%s %d\n", line, i)
}
w.Flush()
f.Close()
}
cfgJSON, _ := json.Marshal(e.cfg)
cmd := exec.Command(os.Args[0], "-test.run=^TestHelperProbe$", "-test.v")
cmd.Env = append(os.Environ(), "URUTAU_TEST_PROBE_CHILD=1", "URUTAU_TEST_PROBE_CFG="+string(cfgJSON))
stdin, _ := cmd.StdinPipe()
var out bytes.Buffer
cmd.Stdout = &out
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
eventually(t, "50k lines", 60*time.Second, func() bool { return hub.count() == per*len(srcs) })
time.Sleep(300 * time.Millisecond)
stdin.Close()
if err := cmd.Wait(); err != nil {
t.Fatalf("child: %v\n%s", err, out.String())
}
var sys, hwm uint64
for _, l := range strings.Split(out.String(), "\n") {
if strings.HasPrefix(l, "RESULT ") {
fmt.Sscanf(l, "RESULT sys=%d hwm=%d", &sys, &hwm)
}
}
if sys == 0 {
t.Fatalf("no result from child:\n%s", out.String())
}
t.Logf("50k lines, 5 sources: runtime MemStats.Sys = %.1f MB, peak RSS (VmHWM) = %.1f MB", float64(sys)/(1<<20), float64(hwm)/(1<<20))
if sys >= 20<<20 {
t.Errorf("MemStats.Sys %d >= 20 MB", sys)
}
if hwm >= 20<<20 {
t.Errorf("peak RSS %d >= 20 MB", hwm)
}
}