// 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 }