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) { // containers.map and resolv.conf go into the queue before any line, so the // hub never judges a backlog of egress lines without them. ready := make(chan struct{}) p.wg.Add(1) go func() { defer p.wg.Done(); p.watchFiles(ctx, ready) }() select { case <-ready: case <-ctx.Done(): } 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) }() } } // watchFiles sends containers.map and resolv.conf whole whenever they change, // and again after each reconnect. func (p *probe) watchFiles(ctx context.Context, ready chan<- struct{}) { 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() close(ready) 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 } } } } }