RUD/internal/checker/checker_test.go

206 lines
5.8 KiB
Go

package checker
import (
"context"
"net"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
"git.gsdistance.org/tyuXX/RUD/internal/config"
"git.gsdistance.org/tyuXX/RUD/internal/store"
)
func TestHTTPChecker(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("X-Custom") != "expected-val" {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.WriteHeader(http.StatusCreated)
_, _ = w.Write([]byte(`{"service":"alive","code":42}`))
}))
defer ts.Close()
def := config.DefaultsConfig{
Timeout: config.NewDuration(2 * time.Second),
Retries: 0,
DegradedLatency: config.NewDuration(1 * time.Second),
}
mon := config.MonitorConfig{
ID: "http-1",
Method: "http",
URL: ts.URL,
ExpectedStatus: []int{201},
Headers: map[string]string{"X-Custom": "expected-val"},
BodyRegex: `"service":\s*"alive"`,
}
res := RunCheckWithRetries(context.Background(), mon, def)
if res.State != store.StateUp {
t.Fatalf("expected HTTP check up, got %s (%s)", res.State, res.Message)
}
// Regex mismatch should mark down
mon.BodyRegex = `"service":\s*"missing"`
resFail := RunCheckWithRetries(context.Background(), mon, def)
if resFail.State != store.StateDown {
t.Fatalf("expected HTTP regex mismatch to mark down, got %s", resFail.State)
}
}
func TestTCPChecker(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen failed: %v", err)
}
defer ln.Close()
go func() {
for {
c, err := ln.Accept()
if err != nil {
return
}
_ = c.Close()
}
}()
def := config.DefaultsConfig{Timeout: config.NewDuration(1 * time.Second)}
mon := config.MonitorConfig{
ID: "tcp-1",
Method: "tcp",
Target: ln.Addr().String(),
}
res := RunCheckWithRetries(context.Background(), mon, def)
if res.State != store.StateUp {
t.Fatalf("expected TCP check up, got %s (%s)", res.State, res.Message)
}
}
func TestDNSAndCmdAndPingCheckers(t *testing.T) {
def := config.DefaultsConfig{Timeout: config.NewDuration(2 * time.Second)}
dnsMon := config.MonitorConfig{
ID: "dns-1",
Method: "dns",
Host: "localhost",
RecordType: "A",
ExpectedRegex: `^127\.`,
}
dnsRes := RunCheckWithRetries(context.Background(), dnsMon, def)
if dnsRes.State != store.StateUp {
t.Fatalf("expected DNS check up, got %s (%s)", dnsRes.State, dnsRes.Message)
}
cmdMon := config.MonitorConfig{
ID: "cmd-1",
Method: "cmd",
Command: "printf 'rud-ok-123'",
Shell: true,
ExpectedExitCode: config.IntPtr(0),
OutputRegex: `^rud-ok-[0-9]+$`,
}
cmdRes := RunCheckWithRetries(context.Background(), cmdMon, def)
if cmdRes.State != store.StateUp {
t.Fatalf("expected Cmd check up, got %s (%s)", cmdRes.State, cmdRes.Message)
}
pingMon := config.MonitorConfig{
ID: "ping-1",
Method: "ping",
Host: "127.0.0.1",
Count: 1,
}
pingRes := RunCheckWithRetries(context.Background(), pingMon, def)
if pingRes.State != store.StateUp {
t.Fatalf("expected Ping check up, got %s (%s)", pingRes.State, pingRes.Message)
}
}
func TestConcurrentLoopbackPings(t *testing.T) {
def := config.DefaultsConfig{Timeout: config.NewDuration(2 * time.Second)}
const workers = 6
var wg sync.WaitGroup
errs := make(chan string, workers)
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
mon := config.MonitorConfig{
ID: "ping-concurrent",
Method: "ping",
Host: "127.0.0.1",
Count: 2,
}
res := RunCheckWithRetries(context.Background(), mon, def)
if res.State != store.StateUp {
errs <- res.Message
}
}()
}
wg.Wait()
close(errs)
for msg := range errs {
t.Fatalf("concurrent ping failed: %s", msg)
}
}
func TestCmdBoundedOutputAndTimeoutCleanup(t *testing.T) {
// Command writing > 1.5 MiB should remain bounded and still check regex
def := config.DefaultsConfig{Timeout: config.NewDuration(3 * time.Second)}
bigCmd := config.MonitorConfig{
ID: "cmd-big",
Method: "cmd",
Command: "printf 'HEAD:'; head -c 1500000 /dev/zero | tr '\\0' 'A'",
Shell: true,
OutputRegex: `^HEAD:A+$`,
}
res := RunCheckWithRetries(context.Background(), bigCmd, def)
if res.State != store.StateUp {
t.Fatalf("expected bounded big output cmd to pass, got %s (%s)", res.State, res.Message)
}
// Command spawning a sleep child should terminate quickly on timeout without hanging pipes
start := time.Now()
timeoutDef := config.DefaultsConfig{Timeout: config.NewDuration(150 * time.Millisecond)}
sleepCmd := config.MonitorConfig{
ID: "cmd-timeout",
Method: "cmd",
Command: "sleep 10 & wait",
Shell: true,
}
resTimeout := RunCheckWithRetries(context.Background(), sleepCmd, timeoutDef)
elapsed := time.Since(start)
if resTimeout.State != store.StateDown {
t.Fatalf("expected timed out cmd to mark down, got %s", resTimeout.State)
}
if elapsed > 2*time.Second {
t.Fatalf("timed out cmd took too long to clean up process group: %v", elapsed)
}
}
func TestSubMsDegradedLatencyThreshold(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(2 * time.Millisecond)
w.WriteHeader(http.StatusOK)
}))
defer ts.Close()
def := config.DefaultsConfig{
Timeout: config.NewDuration(2 * time.Second),
DegradedLatency: config.NewDuration(500 * time.Microsecond), // 0.5ms (< 1ms!)
}
mon := config.MonitorConfig{
ID: "http-subms",
Method: "http",
URL: ts.URL,
}
res := RunCheckWithRetries(context.Background(), mon, def)
if res.State != store.StateDegraded {
t.Fatalf("expected sub-ms degraded threshold (500us) to trigger degraded state, got %s (latency=%.3fms)", res.State, res.LatencyMs)
}
}