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>
This commit is contained in:
1 parent
23a7a5963a
commit
8546d14cef
130 files changed
+9396
-3311
No files matched your search
@@ -0,0 +1,198 @@
|
||||
package probeagent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand/v2"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrUnauthorized: the hub rejected the token or the probe name. Fatal.
|
||||
ErrUnauthorized = errors.New("hub rejected the probe credentials (401)")
|
||||
// ErrIncompatible: protocol version mismatch (409). Fatal.
|
||||
ErrIncompatible = errors.New("hub speaks an incompatible protocol version (409)")
|
||||
)
|
||||
|
||||
// retryError asks the caller to wait and retry the same request.
|
||||
type retryError struct {
|
||||
after time.Duration
|
||||
code int
|
||||
}
|
||||
|
||||
func (e *retryError) Error() string {
|
||||
return fmt.Sprintf("hub busy (%d), retry in %s", e.code, e.after)
|
||||
}
|
||||
|
||||
// rejectError: the hub refused this batch for good (400/413); retrying is pointless.
|
||||
type rejectError struct{ code int }
|
||||
|
||||
func (e *rejectError) Error() string { return fmt.Sprintf("hub rejected the batch (%d)", e.code) }
|
||||
|
||||
const gzipOver = 8 << 10
|
||||
|
||||
type client struct {
|
||||
base string
|
||||
name string
|
||||
token string
|
||||
hc *http.Client
|
||||
gz *gzip.Writer
|
||||
buf bytes.Buffer
|
||||
raw bytes.Buffer
|
||||
}
|
||||
|
||||
func newClient(base *url.URL, name, token string, hc *http.Client) *client {
|
||||
if hc == nil {
|
||||
hc = &http.Client{}
|
||||
}
|
||||
return &client{base: base.String(), name: name, token: token, hc: hc}
|
||||
}
|
||||
|
||||
func (c *client) req(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) {
|
||||
r, err := http.NewRequestWithContext(ctx, method, c.base+path, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.Header.Set("Authorization", "Bearer "+c.token)
|
||||
r.Header.Set(wire.HeaderProbe, c.name)
|
||||
r.Header.Set("User-Agent", "urutau-probe")
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func retryAfter(h http.Header) time.Duration {
|
||||
d := 5 * time.Second
|
||||
if v, err := strconv.Atoi(h.Get("Retry-After")); err == nil && v >= 0 {
|
||||
d = time.Duration(v) * time.Second
|
||||
}
|
||||
return min(d, 2*time.Minute)
|
||||
}
|
||||
|
||||
func statusErr(resp *http.Response) error {
|
||||
switch {
|
||||
case resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden:
|
||||
return ErrUnauthorized
|
||||
case resp.StatusCode == http.StatusConflict:
|
||||
return ErrIncompatible
|
||||
case resp.StatusCode == http.StatusServiceUnavailable || resp.StatusCode == http.StatusTooManyRequests:
|
||||
return &retryError{retryAfter(resp.Header), resp.StatusCode}
|
||||
}
|
||||
return fmt.Errorf("hub answered %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
func (c *client) do(r *http.Request, out any, limit int64) (*http.Response, error) {
|
||||
resp, err := c.hc.Do(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
|
||||
return resp, statusErr(resp)
|
||||
}
|
||||
if out != nil {
|
||||
if err := json.NewDecoder(io.LimitReader(resp.Body, limit)).Decode(out); err != nil {
|
||||
return resp, fmt.Errorf("bad hub answer: %w", err)
|
||||
}
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (c *client) hello(ctx context.Context, h wire.Hello) (*wire.HelloResp, error) {
|
||||
data, _ := json.Marshal(&h)
|
||||
r, err := c.req(ctx, http.MethodPost, wire.PathHello, bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
var out wire.HelloResp
|
||||
if _, err := c.do(r, &out, 1<<20); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if out.Offsets == nil {
|
||||
out.Offsets = map[string]wire.Pos{}
|
||||
}
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
func (c *client) push(ctx context.Context, b wire.Batch) (*wire.PushResp, error) {
|
||||
c.raw.Reset()
|
||||
if err := json.NewEncoder(&c.raw).Encode(&b); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
data := c.raw.Bytes()
|
||||
var body io.Reader = bytes.NewReader(data)
|
||||
gzipped := false
|
||||
if len(data) > gzipOver {
|
||||
c.buf.Reset()
|
||||
if c.gz == nil {
|
||||
c.gz = gzip.NewWriter(&c.buf)
|
||||
} else {
|
||||
c.gz.Reset(&c.buf)
|
||||
}
|
||||
if _, err := c.gz.Write(data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := c.gz.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body = bytes.NewReader(c.buf.Bytes())
|
||||
gzipped = true
|
||||
}
|
||||
r, err := c.req(ctx, http.MethodPost, wire.PathPush, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
if gzipped {
|
||||
r.Header.Set("Content-Encoding", "gzip")
|
||||
}
|
||||
var out wire.PushResp
|
||||
resp, err := c.do(r, &out, 1<<20)
|
||||
if err != nil {
|
||||
if resp != nil && (resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusRequestEntityTooLarge) {
|
||||
return nil, &rejectError{resp.StatusCode}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
// commands long-polls; the caller's context bounds the wait.
|
||||
func (c *client) commands(ctx context.Context, after uint64, wait int) (*wire.CmdResp, error) {
|
||||
q := fmt.Sprintf("%s?after=%d&wait=%d", wire.PathCommands, after, wait)
|
||||
r, err := c.req(ctx, http.MethodGet, q, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out wire.CmdResp
|
||||
if _, err := c.do(r, &out, 8<<20); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
// backoff is the reconnect delay after n consecutive failures (n >= 1):
|
||||
// 1 s doubling up to 60 s, with +-20% jitter. rnd returns [0,1).
|
||||
func backoff(n int, rnd func() float64) time.Duration {
|
||||
if n < 1 {
|
||||
n = 1
|
||||
}
|
||||
d := time.Second
|
||||
for i := 1; i < n && d < 60*time.Second; i++ {
|
||||
d *= 2
|
||||
}
|
||||
d = min(d, 60*time.Second)
|
||||
return time.Duration(float64(d) * (0.8 + 0.4*rnd()))
|
||||
}
|
||||
|
||||
func jitterRnd() float64 { return rand.Float64() }
|
||||
@@ -0,0 +1,55 @@
|
||||
package probeagent
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
|
||||
)
|
||||
|
||||
// appendLine appends one validated line to path and syncs it.
|
||||
func appendLine(path, line string) error {
|
||||
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o640)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := f.WriteString(line); err != nil {
|
||||
f.Close()
|
||||
return err
|
||||
}
|
||||
if err := f.Sync(); err != nil {
|
||||
f.Close()
|
||||
return err
|
||||
}
|
||||
return f.Close()
|
||||
}
|
||||
|
||||
// applyCmds executes the commands above lastCmd, in order, and persists
|
||||
// lastCmd after each one. An invalid or unroutable command is counted and
|
||||
// skipped; it never stops the queue. A write failure stops (the same command
|
||||
// is delivered again later).
|
||||
func (p *probe) applyCmds(cmds []wire.Cmd) error {
|
||||
for _, c := range cmds {
|
||||
if c.Seq <= p.st.lastCmd() {
|
||||
continue
|
||||
}
|
||||
var path string
|
||||
switch c.Kind {
|
||||
case wire.CmdDecision:
|
||||
path = p.cfg.DecisionsLog
|
||||
case wire.CmdUnban:
|
||||
path = p.cfg.UnbanLog
|
||||
}
|
||||
if path == "" || !wire.ValidCmdLine(c.Kind, c.Line) {
|
||||
p.cmdErrors.Add(1)
|
||||
p.log.Warn("command ignored", "seq", c.Seq, "kind", c.Kind)
|
||||
} else if err := appendLine(path, c.Line); err != nil {
|
||||
p.cmdErrors.Add(1)
|
||||
p.log.Error("command write failed", "seq", c.Seq, "kind", c.Kind)
|
||||
return err
|
||||
}
|
||||
if err := p.st.setLastCmd(c.Seq); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package probeagent
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func inodeFor(fi os.FileInfo) uint64 { return fi.Sys().(*syscall.Stat_t).Ino }
|
||||
@@ -0,0 +1,5 @@
|
||||
//go:build !race
|
||||
|
||||
package probeagent
|
||||
|
||||
const raceOn = false
|
||||
@@ -0,0 +1,435 @@
|
||||
// Package probeagent is the Urutau 2 probe: it tails the host logs, spools
|
||||
// batches on disk and ships them to the hub over HTTPS, and applies the
|
||||
// enforcement commands the hub queues for it.
|
||||
package probeagent
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"runtime/debug"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
|
||||
)
|
||||
|
||||
// Config configures one probe. Paths maps a wire source name to the log file
|
||||
// to follow; an empty path disables the source.
|
||||
type Config struct {
|
||||
Hub, Name, Token, StateDir string
|
||||
Paths map[string]string
|
||||
Containers, Resolv string
|
||||
DecisionsLog, UnbanLog string
|
||||
SpoolMax int64 // default 64 MiB
|
||||
Location *wire.Location
|
||||
Client *http.Client // default: plain client, no overall timeout
|
||||
|
||||
// Optional.
|
||||
Version string // reported in hello (default "dev")
|
||||
Poll time.Duration // tail poll interval (default 500 ms)
|
||||
}
|
||||
|
||||
type probe struct {
|
||||
cfg Config
|
||||
log *slog.Logger
|
||||
cl *client
|
||||
st *stateStore
|
||||
spool *Spool
|
||||
start time.Time
|
||||
cancel context.CancelCauseFunc
|
||||
|
||||
sources []string
|
||||
stats []*srcStat
|
||||
in chan item
|
||||
notify chan struct{}
|
||||
wg sync.WaitGroup
|
||||
|
||||
flushMS atomic.Int64
|
||||
cmdErrors atomic.Uint64
|
||||
fileEvery time.Duration
|
||||
hbEvery time.Duration
|
||||
resendFiles chan struct{}
|
||||
}
|
||||
|
||||
func (p *probe) flushEvery() time.Duration {
|
||||
ms := p.flushMS.Load()
|
||||
if ms < 10 {
|
||||
ms = 1000
|
||||
}
|
||||
return time.Duration(ms) * time.Millisecond
|
||||
}
|
||||
|
||||
func newProbe(c Config, log *slog.Logger) (*probe, error) {
|
||||
if log == nil {
|
||||
log = slog.New(slog.NewTextHandler(os.Stderr, nil))
|
||||
}
|
||||
if !wire.ValidName(c.Name) {
|
||||
return nil, errors.New("invalid probe name")
|
||||
}
|
||||
if c.Token == "" {
|
||||
return nil, errors.New("probe token missing")
|
||||
}
|
||||
if c.StateDir == "" {
|
||||
return nil, errors.New("state dir missing")
|
||||
}
|
||||
u, err := wire.CheckHubURL(c.Hub)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if c.SpoolMax <= 0 {
|
||||
c.SpoolMax = 64 << 20
|
||||
}
|
||||
if c.Version == "" {
|
||||
c.Version = "dev"
|
||||
}
|
||||
if err := os.MkdirAll(c.StateDir, 0o700); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
st, err := loadState(c.StateDir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sp, err := OpenSpool(filepath.Join(c.StateDir, "spool"), c.SpoolMax)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
st.raiseSeq(sp.MaxSeq())
|
||||
p := &probe{
|
||||
cfg: c, log: log, st: st, spool: sp, start: time.Now(),
|
||||
cl: newClient(u, c.Name, c.Token, c.Client),
|
||||
in: make(chan item, chanSize),
|
||||
notify: make(chan struct{}, 1),
|
||||
fileEvery: filePollEach,
|
||||
hbEvery: time.Duration(wire.HeartbeatSec) * time.Second,
|
||||
resendFiles: make(chan struct{}, 1),
|
||||
}
|
||||
for _, s := range wire.Sources {
|
||||
if c.Paths[s] != "" {
|
||||
p.sources = append(p.sources, s)
|
||||
}
|
||||
}
|
||||
sort.Strings(p.sources)
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// Run connects to the hub and ships until ctx is done (nil) or the hub
|
||||
// refuses the credentials or the protocol version (error).
|
||||
func Run(ctx context.Context, c Config, log *slog.Logger) error {
|
||||
p, err := newProbe(c, log)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if os.Getenv("GOMEMLIMIT") == "" {
|
||||
// soft limit: the probe is a small process, make the GC keep it that way
|
||||
debug.SetMemoryLimit(8 << 20)
|
||||
debug.SetGCPercent(30)
|
||||
}
|
||||
ctx, cancel := context.WithCancelCause(ctx)
|
||||
p.cancel = cancel
|
||||
defer cancel(nil)
|
||||
|
||||
resp, err := p.connect(ctx)
|
||||
if err != nil {
|
||||
return p.result(ctx, err)
|
||||
}
|
||||
p.startTailers(ctx, resp.Offsets)
|
||||
var cw sync.WaitGroup
|
||||
cw.Add(1)
|
||||
go func() { defer cw.Done(); p.collect(ctx) }()
|
||||
p.wg.Add(3)
|
||||
go func() { defer p.wg.Done(); p.sender(ctx) }()
|
||||
go func() { defer p.wg.Done(); p.commandLoop(ctx) }()
|
||||
go func() { defer p.wg.Done(); p.aliveLoop(ctx) }()
|
||||
|
||||
<-ctx.Done()
|
||||
p.wg.Wait()
|
||||
cw.Wait() // final flush so positions and spool are consistent
|
||||
_ = p.st.touch()
|
||||
return p.result(ctx, nil)
|
||||
}
|
||||
|
||||
func (p *probe) result(ctx context.Context, err error) error {
|
||||
if cause := context.Cause(ctx); cause != nil && !errors.Is(cause, context.Canceled) {
|
||||
return cause
|
||||
}
|
||||
if err != nil && !errors.Is(err, context.Canceled) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *probe) fail(err error) {
|
||||
p.log.Error("probe stopping", "err", err)
|
||||
p.cancel(err)
|
||||
}
|
||||
|
||||
func isFatal(err error) bool {
|
||||
return errors.Is(err, ErrUnauthorized) || errors.Is(err, ErrIncompatible)
|
||||
}
|
||||
|
||||
func sleep(ctx context.Context, d time.Duration) bool {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-t.C:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// hello performs one handshake and applies its answer.
|
||||
func (p *probe) hello(ctx context.Context) (*wire.HelloResp, error) {
|
||||
host, _ := os.Hostname()
|
||||
s := p.st.snapshot()
|
||||
h := wire.Hello{
|
||||
Proto: wire.Proto, Name: p.cfg.Name, Version: p.cfg.Version, Hostname: host,
|
||||
Sources: append([]string{}, p.sources...), Location: p.cfg.Location,
|
||||
LastSeq: s.Seq, LastCmd: s.LastCmd,
|
||||
}
|
||||
hctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
resp, err := p.cl.hello(hctx, h)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.FlushMS > 0 {
|
||||
p.flushMS.Store(int64(resp.FlushMS))
|
||||
}
|
||||
p.st.raiseSeq(resp.AckSeq)
|
||||
p.spool.Ack(resp.AckSeq)
|
||||
select {
|
||||
case p.resendFiles <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// connect retries the first hello with backoff.
|
||||
func (p *probe) connect(ctx context.Context) (*wire.HelloResp, error) {
|
||||
for n := 1; ; n++ {
|
||||
resp, err := p.hello(ctx)
|
||||
if err == nil {
|
||||
return resp, nil
|
||||
}
|
||||
if isFatal(err) {
|
||||
p.log.Error("hello refused", "err", err)
|
||||
return nil, err
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
d := p.retryDelay(err, n)
|
||||
p.log.Warn("hub unreachable, retrying", "err", err, "in", d.Round(time.Millisecond))
|
||||
if !sleep(ctx, d) {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (p *probe) retryDelay(err error, n int) time.Duration {
|
||||
var re *retryError
|
||||
if errors.As(err, &re) {
|
||||
return re.after
|
||||
}
|
||||
return backoff(n, jitterRnd)
|
||||
}
|
||||
|
||||
// sender ships the spool in order, heartbeating when idle; on any transport
|
||||
// error it reconnects (hello) with backoff.
|
||||
func (p *probe) sender(ctx context.Context) {
|
||||
n := 0
|
||||
first := true
|
||||
for ctx.Err() == nil {
|
||||
if !first {
|
||||
if _, err := p.hello(ctx); err != nil {
|
||||
if isFatal(err) {
|
||||
p.fail(err)
|
||||
return
|
||||
}
|
||||
n++
|
||||
d := p.retryDelay(err, n)
|
||||
p.log.Warn("hub unreachable, retrying", "err", err, "in", d.Round(time.Millisecond))
|
||||
if !sleep(ctx, d) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
first = false
|
||||
n = 0
|
||||
err := p.session(ctx)
|
||||
if err == nil || ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if isFatal(err) {
|
||||
p.fail(err)
|
||||
return
|
||||
}
|
||||
n++
|
||||
d := backoff(n, jitterRnd)
|
||||
p.log.Warn("connection lost, reconnecting", "err", err, "in", d.Round(time.Millisecond))
|
||||
if !sleep(ctx, d) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (p *probe) session(ctx context.Context) error {
|
||||
hb := time.NewTimer(p.hbEvery)
|
||||
defer hb.Stop()
|
||||
resetHB := func() {
|
||||
if !hb.Stop() {
|
||||
select {
|
||||
case <-hb.C:
|
||||
default:
|
||||
}
|
||||
}
|
||||
hb.Reset(p.hbEvery)
|
||||
}
|
||||
for {
|
||||
b, ok, err := p.spool.Head()
|
||||
if err != nil {
|
||||
p.log.Error("spool", "err", err)
|
||||
continue
|
||||
}
|
||||
if !ok {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case <-p.notify:
|
||||
case <-hb.C:
|
||||
if _, err := p.cl.push(ctx, wire.Batch{Sent: time.Now().UnixMilli(), Status: p.status()}); err != nil {
|
||||
if p.handlePushErr(ctx, err, wire.Batch{}) {
|
||||
continue
|
||||
}
|
||||
return err
|
||||
}
|
||||
hb.Reset(p.hbEvery)
|
||||
}
|
||||
continue
|
||||
}
|
||||
b.Sent = time.Now().UnixMilli()
|
||||
b.Status = p.status()
|
||||
resp, err := p.cl.push(ctx, b)
|
||||
if err != nil {
|
||||
if p.handlePushErr(ctx, err, b) {
|
||||
continue
|
||||
}
|
||||
return err
|
||||
}
|
||||
if resp.Ack < b.Seq {
|
||||
return fmt.Errorf("hub acked %d for batch %d", resp.Ack, b.Seq)
|
||||
}
|
||||
p.spool.Ack(resp.Ack)
|
||||
resetHB()
|
||||
}
|
||||
}
|
||||
|
||||
// handlePushErr deals with the errors that do not need a reconnect.
|
||||
func (p *probe) handlePushErr(ctx context.Context, err error, b wire.Batch) bool {
|
||||
var re *retryError
|
||||
var rj *rejectError
|
||||
switch {
|
||||
case errors.As(err, &re):
|
||||
p.log.Warn("hub busy, backing off", "code", re.code, "in", re.after)
|
||||
sleep(ctx, re.after)
|
||||
return true
|
||||
case errors.As(err, &rj):
|
||||
if b.Seq == 0 {
|
||||
sleep(ctx, 5*time.Second)
|
||||
return true
|
||||
}
|
||||
p.log.Error("hub rejected batch, dropping it", "seq", b.Seq, "code", rj.code, "lines", len(b.Lines))
|
||||
p.spool.Ack(b.Seq)
|
||||
p.st.addDropped(uint64(len(b.Lines)))
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (p *probe) commandLoop(ctx context.Context) {
|
||||
n := 0
|
||||
for ctx.Err() == nil {
|
||||
rctx, cancel := context.WithTimeout(ctx, (wire.MaxWaitSec+15)*time.Second)
|
||||
resp, err := p.cl.commands(rctx, p.st.lastCmd(), wire.MaxWaitSec)
|
||||
cancel()
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if isFatal(err) {
|
||||
p.fail(err)
|
||||
return
|
||||
}
|
||||
n++
|
||||
if !sleep(ctx, p.retryDelay(err, n)) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
n = 0
|
||||
if err := p.applyCmds(resp.Cmds); err != nil {
|
||||
if !sleep(ctx, 5*time.Second) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (p *probe) aliveLoop(ctx context.Context) {
|
||||
t := time.NewTicker(15 * time.Second)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
_ = p.st.touch()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (p *probe) status() *wire.Status {
|
||||
b, f := p.spool.Stats()
|
||||
s := &wire.Status{
|
||||
UptimeSec: int64(time.Since(p.start).Seconds()), RSSBytes: rss(),
|
||||
SpoolBytes: b, SpoolFiles: f, Dropped: p.st.dropped(), CmdErrors: p.cmdErrors.Load(),
|
||||
}
|
||||
for _, ss := range p.stats {
|
||||
s.Sources = append(s.Sources, ss.status())
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// rss reads VmRSS from /proc; elsewhere it falls back to what the Go runtime holds.
|
||||
func rss() uint64 {
|
||||
if f, err := os.Open("/proc/self/status"); err == nil {
|
||||
defer f.Close()
|
||||
sc := bufio.NewScanner(f)
|
||||
for sc.Scan() {
|
||||
if v, ok := strings.CutPrefix(sc.Text(), "VmRSS:"); ok {
|
||||
fs := strings.Fields(v)
|
||||
if len(fs) > 0 {
|
||||
if kb, err := strconv.ParseUint(fs[0], 10, 64); err == nil {
|
||||
return kb << 10
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
var m runtime.MemStats
|
||||
runtime.ReadMemStats(&m)
|
||||
return m.Sys
|
||||
}
|
||||
@@ -0,0 +1,742 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
//go:build race
|
||||
|
||||
package probeagent
|
||||
|
||||
const raceOn = true
|
||||
@@ -0,0 +1,176 @@
|
||||
package probeagent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
|
||||
)
|
||||
|
||||
// Spool keeps unacknowledged batches on disk, one file per batch, in order.
|
||||
type Spool struct {
|
||||
mu sync.Mutex
|
||||
dir string
|
||||
max int64
|
||||
items []spoolItem
|
||||
bytes int64
|
||||
wbuf bytes.Buffer // reused encoder buffer
|
||||
}
|
||||
|
||||
type spoolItem struct {
|
||||
seq uint64
|
||||
size int64
|
||||
}
|
||||
|
||||
func spoolName(seq uint64) string { return fmt.Sprintf("%012d.json", seq) }
|
||||
|
||||
// OpenSpool scans dir (created if missing) and returns the spool.
|
||||
func OpenSpool(dir string, max int64) (*Spool, error) {
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sp := &Spool{dir: dir, max: max}
|
||||
ents, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, e := range ents {
|
||||
n := e.Name()
|
||||
if strings.HasSuffix(n, ".tmp") {
|
||||
os.Remove(filepath.Join(dir, n))
|
||||
continue
|
||||
}
|
||||
if !strings.HasSuffix(n, ".json") {
|
||||
continue
|
||||
}
|
||||
seq, err := strconv.ParseUint(strings.TrimSuffix(n, ".json"), 10, 64)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
fi, err := e.Info()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
sp.items = append(sp.items, spoolItem{seq, fi.Size()})
|
||||
sp.bytes += fi.Size()
|
||||
}
|
||||
sort.Slice(sp.items, func(i, j int) bool { return sp.items[i].seq < sp.items[j].seq })
|
||||
return sp, nil
|
||||
}
|
||||
|
||||
// MaxSeq is the highest batch number on disk (0 when empty).
|
||||
func (sp *Spool) MaxSeq() uint64 {
|
||||
sp.mu.Lock()
|
||||
defer sp.mu.Unlock()
|
||||
if len(sp.items) == 0 {
|
||||
return 0
|
||||
}
|
||||
return sp.items[len(sp.items)-1].seq
|
||||
}
|
||||
|
||||
// Add stores b (b.Seq must be above everything already stored). When the cap
|
||||
// is exceeded the oldest files are deleted, but never the one just added; the
|
||||
// number of log lines lost that way is returned.
|
||||
func (sp *Spool) Add(b wire.Batch) (dropped uint64, err error) {
|
||||
sp.mu.Lock()
|
||||
defer sp.mu.Unlock()
|
||||
sp.wbuf.Reset()
|
||||
if err := json.NewEncoder(&sp.wbuf).Encode(&b); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
data := sp.wbuf.Bytes()
|
||||
if sp.wbuf.Cap() > 4<<20 {
|
||||
defer func() { sp.wbuf = bytes.Buffer{} }()
|
||||
}
|
||||
p := filepath.Join(sp.dir, spoolName(b.Seq))
|
||||
tmp := p + ".tmp"
|
||||
f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if _, err = f.Write(data); err == nil {
|
||||
err = f.Sync()
|
||||
}
|
||||
if cerr := f.Close(); err == nil {
|
||||
err = cerr
|
||||
}
|
||||
if err == nil {
|
||||
err = os.Rename(tmp, p)
|
||||
}
|
||||
if err != nil {
|
||||
os.Remove(tmp)
|
||||
return 0, err
|
||||
}
|
||||
sp.items = append(sp.items, spoolItem{b.Seq, int64(len(data))})
|
||||
sp.bytes += int64(len(data))
|
||||
for sp.bytes > sp.max && len(sp.items) > 1 {
|
||||
it := sp.items[0]
|
||||
dropped += sp.countLines(it.seq)
|
||||
sp.removeLocked(0)
|
||||
}
|
||||
return dropped, nil
|
||||
}
|
||||
|
||||
func (sp *Spool) countLines(seq uint64) uint64 {
|
||||
data, err := os.ReadFile(filepath.Join(sp.dir, spoolName(seq)))
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
var b wire.Batch
|
||||
if json.Unmarshal(data, &b) != nil {
|
||||
return 0
|
||||
}
|
||||
return uint64(len(b.Lines))
|
||||
}
|
||||
|
||||
func (sp *Spool) removeLocked(i int) {
|
||||
it := sp.items[i]
|
||||
os.Remove(filepath.Join(sp.dir, spoolName(it.seq)))
|
||||
sp.bytes -= it.size
|
||||
sp.items = append(sp.items[:i], sp.items[i+1:]...)
|
||||
}
|
||||
|
||||
// Head returns the oldest batch.
|
||||
func (sp *Spool) Head() (wire.Batch, bool, error) {
|
||||
sp.mu.Lock()
|
||||
if len(sp.items) == 0 {
|
||||
sp.mu.Unlock()
|
||||
return wire.Batch{}, false, nil
|
||||
}
|
||||
seq := sp.items[0].seq
|
||||
sp.mu.Unlock()
|
||||
data, err := os.ReadFile(filepath.Join(sp.dir, spoolName(seq)))
|
||||
var b wire.Batch
|
||||
if err == nil {
|
||||
err = json.Unmarshal(data, &b)
|
||||
}
|
||||
if err != nil {
|
||||
sp.Ack(seq) // unreadable: discard so the queue moves on
|
||||
return wire.Batch{}, false, fmt.Errorf("spool batch %d unreadable: %w", seq, err)
|
||||
}
|
||||
b.Seq = seq
|
||||
return b, true, nil
|
||||
}
|
||||
|
||||
// Ack removes every batch with seq <= n.
|
||||
func (sp *Spool) Ack(n uint64) {
|
||||
sp.mu.Lock()
|
||||
defer sp.mu.Unlock()
|
||||
for len(sp.items) > 0 && sp.items[0].seq <= n {
|
||||
sp.removeLocked(0)
|
||||
}
|
||||
}
|
||||
|
||||
// Stats returns the bytes and file count held.
|
||||
func (sp *Spool) Stats() (bytes int64, files int) {
|
||||
sp.mu.Lock()
|
||||
defer sp.mu.Unlock()
|
||||
return sp.bytes, len(sp.items)
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package probeagent
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
|
||||
)
|
||||
|
||||
func mkBatch(seq uint64, n int, pad string) wire.Batch {
|
||||
b := wire.Batch{Seq: seq}
|
||||
for i := 0; i < n; i++ {
|
||||
b.Lines = append(b.Lines, wire.Line{Src: wire.SrcTraefik, Text: fmt.Sprintf("%d-%d%s", seq, i, pad), End: wire.Pos{Inode: 1, Offset: int64(i)}})
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func TestSpoolOrderAndReopen(t *testing.T) {
|
||||
d := t.TempDir()
|
||||
sp, err := OpenSpool(d, 1<<20)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for s := uint64(1); s <= 5; s++ {
|
||||
if dr, err := sp.Add(mkBatch(s, 3, "")); err != nil || dr != 0 {
|
||||
t.Fatal(dr, err)
|
||||
}
|
||||
}
|
||||
sp.Ack(2)
|
||||
sp2, err := OpenSpool(d, 1<<20) // reopen
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if sp2.MaxSeq() != 5 {
|
||||
t.Errorf("MaxSeq %d", sp2.MaxSeq())
|
||||
}
|
||||
for want := uint64(3); want <= 5; want++ {
|
||||
b, ok, err := sp2.Head()
|
||||
if err != nil || !ok || b.Seq != want || len(b.Lines) != 3 {
|
||||
t.Fatalf("head %d: %+v %v %v", want, b.Seq, ok, err)
|
||||
}
|
||||
sp2.Ack(want)
|
||||
}
|
||||
if _, ok, _ := sp2.Head(); ok {
|
||||
t.Error("spool not empty")
|
||||
}
|
||||
if n, f := sp2.Stats(); n != 0 || f != 0 {
|
||||
t.Errorf("stats %d %d", n, f)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSpoolCapDropsOldestAndCounts(t *testing.T) {
|
||||
d := t.TempDir()
|
||||
probe := mkBatch(1, 10, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
|
||||
tmp, _ := OpenSpool(t.TempDir(), 1<<30)
|
||||
tmp.Add(probe)
|
||||
size, _ := tmp.Stats()
|
||||
sp, _ := OpenSpool(d, size*3+size/2) // room for 3 batches
|
||||
var dropped uint64
|
||||
for s := uint64(1); s <= 6; s++ {
|
||||
dr, err := sp.Add(mkBatch(s, 10, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dropped += dr
|
||||
}
|
||||
if dropped != 30 {
|
||||
t.Errorf("dropped %d lines, want 30 (3 batches of 10)", dropped)
|
||||
}
|
||||
b, ok, _ := sp.Head()
|
||||
if !ok || b.Seq != 4 {
|
||||
t.Errorf("oldest remaining = %d, want 4", b.Seq)
|
||||
}
|
||||
if _, f := sp.Stats(); f != 3 {
|
||||
t.Errorf("files %d", f)
|
||||
}
|
||||
ents, _ := os.ReadDir(d)
|
||||
if len(ents) != 3 {
|
||||
t.Errorf("%d files on disk", len(ents))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSpoolKeepsLoneOversizeBatch(t *testing.T) {
|
||||
sp, _ := OpenSpool(t.TempDir(), 10)
|
||||
dr, err := sp.Add(mkBatch(1, 5, ""))
|
||||
if err != nil || dr != 0 {
|
||||
t.Fatal(dr, err)
|
||||
}
|
||||
if _, f := sp.Stats(); f != 1 {
|
||||
t.Error("newest batch must survive the cap")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSpoolCorruptFileSkipped(t *testing.T) {
|
||||
d := t.TempDir()
|
||||
sp, _ := OpenSpool(d, 1<<20)
|
||||
sp.Add(mkBatch(1, 1, ""))
|
||||
sp.Add(mkBatch(2, 1, ""))
|
||||
os.WriteFile(filepath.Join(d, spoolName(1)), []byte("{broken"), 0o600)
|
||||
if _, _, err := sp.Head(); err == nil {
|
||||
t.Error("corrupt batch not reported")
|
||||
}
|
||||
b, ok, err := sp.Head()
|
||||
if err != nil || !ok || b.Seq != 2 {
|
||||
t.Errorf("next head %v %v %v", b.Seq, ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStateAtomicRoundTrip(t *testing.T) {
|
||||
d := t.TempDir()
|
||||
st, _ := loadState(d)
|
||||
st.commit(func(seq uint64) uint64 { return 7 }, map[string]wire.Pos{"auth": {Inode: 9, Offset: 123, FP: 5, FPLen: 4}})
|
||||
st.setLastCmd(4)
|
||||
st2, err := loadState(d)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := st2.s
|
||||
if s.Seq != 1 || s.LastCmd != 4 || s.Dropped != 7 || s.Positions["auth"].Offset != 123 || s.Positions["auth"].FPLen != 4 {
|
||||
t.Errorf("%+v", s)
|
||||
}
|
||||
os.WriteFile(filepath.Join(d, "state.json"), []byte("garbage"), 0o600)
|
||||
st3, err := loadState(d)
|
||||
if err != nil || st3.s.Seq != 0 || st3.s.Positions == nil {
|
||||
t.Errorf("corrupt state not reset: %+v %v", st3.s, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
package probeagent
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
|
||||
)
|
||||
|
||||
// State is the probe's only durable bookkeeping besides the spool.
|
||||
type State struct {
|
||||
Seq uint64 `json:"seq"`
|
||||
LastCmd uint64 `json:"last_cmd"`
|
||||
Positions map[string]wire.Pos `json:"positions"`
|
||||
Dropped uint64 `json:"dropped"`
|
||||
Alive int64 `json:"alive"` // unix seconds, refreshed by the process; read by Check
|
||||
}
|
||||
|
||||
type stateStore struct {
|
||||
mu sync.Mutex
|
||||
path string
|
||||
s State
|
||||
}
|
||||
|
||||
func loadState(dir string) (*stateStore, error) {
|
||||
st := &stateStore{path: filepath.Join(dir, "state.json")}
|
||||
st.s.Positions = map[string]wire.Pos{}
|
||||
b, err := os.ReadFile(st.path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return st, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := json.Unmarshal(b, &st.s); err != nil {
|
||||
// a corrupt state must not keep the probe down: start clean, the hub's
|
||||
// offsets in the hello cover the gap.
|
||||
st.s = State{}
|
||||
}
|
||||
if st.s.Positions == nil {
|
||||
st.s.Positions = map[string]wire.Pos{}
|
||||
}
|
||||
return st, nil
|
||||
}
|
||||
|
||||
// saveLocked writes state.json atomically. Caller holds mu.
|
||||
func (st *stateStore) saveLocked() error {
|
||||
st.s.Alive = time.Now().Unix()
|
||||
b, err := json.Marshal(&st.s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := st.path + ".tmp"
|
||||
f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := f.Write(b); err != nil {
|
||||
f.Close()
|
||||
return err
|
||||
}
|
||||
if err := f.Sync(); err != nil {
|
||||
f.Close()
|
||||
return err
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp, st.path)
|
||||
}
|
||||
|
||||
func (st *stateStore) touch() error {
|
||||
st.mu.Lock()
|
||||
defer st.mu.Unlock()
|
||||
return st.saveLocked()
|
||||
}
|
||||
|
||||
func (st *stateStore) snapshot() State {
|
||||
st.mu.Lock()
|
||||
defer st.mu.Unlock()
|
||||
c := st.s
|
||||
c.Positions = make(map[string]wire.Pos, len(st.s.Positions))
|
||||
for k, v := range st.s.Positions {
|
||||
c.Positions[k] = v
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (st *stateStore) pos(src string) (wire.Pos, bool) {
|
||||
st.mu.Lock()
|
||||
defer st.mu.Unlock()
|
||||
p, ok := st.s.Positions[src]
|
||||
return p, ok
|
||||
}
|
||||
|
||||
func (st *stateStore) lastCmd() uint64 {
|
||||
st.mu.Lock()
|
||||
defer st.mu.Unlock()
|
||||
return st.s.LastCmd
|
||||
}
|
||||
|
||||
func (st *stateStore) setLastCmd(n uint64) error {
|
||||
st.mu.Lock()
|
||||
defer st.mu.Unlock()
|
||||
st.s.LastCmd = n
|
||||
return st.saveLocked()
|
||||
}
|
||||
|
||||
func (st *stateStore) dropped() uint64 {
|
||||
st.mu.Lock()
|
||||
defer st.mu.Unlock()
|
||||
return st.s.Dropped
|
||||
}
|
||||
|
||||
func (st *stateStore) addDropped(n uint64) {
|
||||
if n == 0 {
|
||||
return
|
||||
}
|
||||
st.mu.Lock()
|
||||
defer st.mu.Unlock()
|
||||
st.s.Dropped += n
|
||||
_ = st.saveLocked()
|
||||
}
|
||||
|
||||
// raiseSeq makes sure new batches are numbered above what the hub already
|
||||
// applied (state lost on the probe, or hub ahead).
|
||||
func (st *stateStore) raiseSeq(n uint64) {
|
||||
st.mu.Lock()
|
||||
defer st.mu.Unlock()
|
||||
if n > st.s.Seq {
|
||||
st.s.Seq = n
|
||||
_ = st.saveLocked()
|
||||
}
|
||||
}
|
||||
|
||||
func (st *stateStore) lastSeq() uint64 {
|
||||
st.mu.Lock()
|
||||
defer st.mu.Unlock()
|
||||
return st.s.Seq
|
||||
}
|
||||
|
||||
// commit allocates the next batch seq. persist is called with it before the
|
||||
// positions move, so a spooled batch always has its position recorded.
|
||||
func (st *stateStore) commit(build func(seq uint64) (dropped uint64), pos map[string]wire.Pos) {
|
||||
st.mu.Lock()
|
||||
defer st.mu.Unlock()
|
||||
st.s.Seq++
|
||||
st.s.Dropped += build(st.s.Seq)
|
||||
for k, v := range pos {
|
||||
st.s.Positions[k] = v
|
||||
}
|
||||
_ = st.saveLocked()
|
||||
}
|
||||
|
||||
// Check is the container healthcheck: the process refreshes state.json every
|
||||
// few seconds, so a stale or missing file means it is not running.
|
||||
func Check(stateDir string) error {
|
||||
b, err := os.ReadFile(filepath.Join(stateDir, "state.json"))
|
||||
if err != nil {
|
||||
return errors.New("probe state unreadable")
|
||||
}
|
||||
var s State
|
||||
if err := json.Unmarshal(b, &s); err != nil {
|
||||
return errors.New("probe state corrupt")
|
||||
}
|
||||
if age := time.Since(time.Unix(s.Alive, 0)); age > aliveMax {
|
||||
return errors.New("probe not alive")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const aliveMax = 90 * time.Second
|
||||
@@ -0,0 +1,230 @@
|
||||
package probeagent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"os"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/tail"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
|
||||
)
|
||||
|
||||
const (
|
||||
chanSize = 4096
|
||||
batchBytes = 128 << 10 // well under the hub limit; keeps the probe heap small
|
||||
filePollEach = 10 * time.Second
|
||||
)
|
||||
|
||||
// item is what the followers and the file watcher hand to the collector.
|
||||
type item struct {
|
||||
line wire.Line
|
||||
file *wire.File
|
||||
}
|
||||
|
||||
type srcStat struct {
|
||||
src string
|
||||
f *tail.Follower
|
||||
lines atomic.Uint64
|
||||
oversize atomic.Uint64
|
||||
lastLine atomic.Int64
|
||||
}
|
||||
|
||||
func (s *srcStat) status() wire.SourceStatus {
|
||||
st := wire.SourceStatus{Src: s.src, State: "following", Lines: s.lines.Load(), Oversize: s.oversize.Load(), LastLine: s.lastLine.Load()}
|
||||
if err := s.f.Err(); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, fs.ErrNotExist):
|
||||
st.State = "waiting"
|
||||
case errors.Is(err, fs.ErrPermission):
|
||||
st.State, st.Error = "error", "permission denied"
|
||||
default:
|
||||
st.State, st.Error = "error", "read error"
|
||||
}
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
func toTail(p wire.Pos) tail.Pos {
|
||||
return tail.Pos{Inode: p.Inode, Offset: p.Offset, FP: p.FP, FPLen: p.FPLen}
|
||||
}
|
||||
|
||||
func fromTail(p tail.Pos) wire.Pos {
|
||||
return wire.Pos{Inode: p.Inode, Offset: p.Offset, FP: p.FP, FPLen: p.FPLen}
|
||||
}
|
||||
|
||||
// startTailers launches one follower per configured source. A source with no
|
||||
// local position starts where the hub says it already has data.
|
||||
func (p *probe) startTailers(ctx context.Context, hubOffsets map[string]wire.Pos) {
|
||||
for _, src := range p.sources {
|
||||
path := p.cfg.Paths[src]
|
||||
pos, ok := p.st.pos(src)
|
||||
if !ok {
|
||||
pos = hubOffsets[src]
|
||||
}
|
||||
f := tail.NewFollower(path, toTail(pos))
|
||||
f.MaxLine = wire.MaxLine
|
||||
if p.cfg.Poll > 0 {
|
||||
f.Poll = p.cfg.Poll
|
||||
}
|
||||
ss := &srcStat{src: src, f: f}
|
||||
p.stats = append(p.stats, ss)
|
||||
f.Oversize = func() { ss.oversize.Add(1) }
|
||||
f.HandleAt = func(line []byte, end tail.Pos) {
|
||||
ss.lines.Add(1)
|
||||
ss.lastLine.Store(time.Now().Unix())
|
||||
it := item{line: wire.Line{Src: src, Text: strings.ToValidUTF8(string(line), "�"), End: fromTail(end)}}
|
||||
select {
|
||||
case p.in <- it:
|
||||
case <-ctx.Done():
|
||||
}
|
||||
}
|
||||
p.wg.Add(1)
|
||||
go func() { defer p.wg.Done(); f.Run(ctx) }()
|
||||
}
|
||||
p.wg.Add(1)
|
||||
go func() { defer p.wg.Done(); p.watchFiles(ctx) }()
|
||||
}
|
||||
|
||||
// watchFiles sends containers.map and resolv.conf whole whenever they change,
|
||||
// and again after each reconnect.
|
||||
func (p *probe) watchFiles(ctx context.Context) {
|
||||
files := []struct{ name, path string }{
|
||||
{wire.FileContainers, p.cfg.Containers},
|
||||
{wire.FileResolv, p.cfg.Resolv},
|
||||
}
|
||||
sums := map[string][32]byte{}
|
||||
check := func() {
|
||||
for _, f := range files {
|
||||
if f.path == "" {
|
||||
continue
|
||||
}
|
||||
b, err := readSmall(f.path)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
sum := sha256.Sum256(b)
|
||||
if old, ok := sums[f.name]; ok && old == sum {
|
||||
continue
|
||||
}
|
||||
sums[f.name] = sum
|
||||
select {
|
||||
case p.in <- item{file: &wire.File{Name: f.name, Data: strings.ToValidUTF8(string(b), "�")}}:
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
check()
|
||||
t := time.NewTicker(p.fileEvery)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-p.resendFiles:
|
||||
clear(sums)
|
||||
check()
|
||||
case <-t.C:
|
||||
check()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func readSmall(path string) ([]byte, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
fi, err := f.Stat()
|
||||
if err != nil || fi.Size() > wire.MaxFileBytes {
|
||||
return nil, errors.New("unusable file")
|
||||
}
|
||||
b := make([]byte, fi.Size())
|
||||
n, err := f.Read(b)
|
||||
if err != nil && n == 0 && fi.Size() > 0 {
|
||||
return nil, err
|
||||
}
|
||||
return b[:n], nil
|
||||
}
|
||||
|
||||
// collect groups items into batches (flush interval, 5000 lines or 1 MiB),
|
||||
// writes each to the spool and records the positions it covers.
|
||||
func (p *probe) collect(ctx context.Context) {
|
||||
var (
|
||||
b wire.Batch
|
||||
size int
|
||||
pos = map[string]wire.Pos{}
|
||||
)
|
||||
flush := func() {
|
||||
if len(b.Lines) == 0 && len(b.Files) == 0 {
|
||||
return
|
||||
}
|
||||
nl := uint64(len(b.Lines))
|
||||
p.st.commit(func(seq uint64) uint64 {
|
||||
b.Seq = seq
|
||||
b.Sent = time.Now().UnixMilli()
|
||||
dropped, err := p.spool.Add(b)
|
||||
if err != nil {
|
||||
p.log.Error("spool write failed", "err", err)
|
||||
return nl
|
||||
}
|
||||
if dropped > 0 {
|
||||
p.log.Warn("spool full, oldest batches dropped", "lines", dropped)
|
||||
}
|
||||
return dropped
|
||||
}, pos)
|
||||
b, size = wire.Batch{Lines: make([]wire.Line, 0, 512)}, 0
|
||||
clear(pos)
|
||||
select {
|
||||
case p.notify <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
add := func(it item) {
|
||||
if it.file != nil {
|
||||
replaced := false
|
||||
for i := range b.Files {
|
||||
if b.Files[i].Name == it.file.Name {
|
||||
b.Files[i], replaced = *it.file, true
|
||||
}
|
||||
}
|
||||
if !replaced {
|
||||
b.Files = append(b.Files, *it.file)
|
||||
}
|
||||
size += len(it.file.Data)
|
||||
} else {
|
||||
b.Lines = append(b.Lines, it.line)
|
||||
pos[it.line.Src] = it.line.End
|
||||
size += len(it.line.Text) + 48
|
||||
}
|
||||
if len(b.Lines) >= wire.MaxLines || size >= batchBytes {
|
||||
flush()
|
||||
}
|
||||
}
|
||||
t := time.NewTicker(p.flushEvery())
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case it := <-p.in:
|
||||
add(it)
|
||||
case <-t.C:
|
||||
flush()
|
||||
case <-ctx.Done():
|
||||
for {
|
||||
select {
|
||||
case it := <-p.in:
|
||||
add(it)
|
||||
default:
|
||||
flush()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user