Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1187 lines
27 KiB
Go
1187 lines
27 KiB
Go
// Package evlog is the on-disk event registry used for replay and
|
|
// investigation: one JSON object per line (the same format as the live SSE
|
|
// stream), one file per UTC day. The current day is appended to and synced
|
|
// periodically; older days are gzip compressed. Total size and age are bounded.
|
|
//
|
|
// It never stores the address of a legitimate visitor: the caller only hands
|
|
// over events of attackers.
|
|
package evlog
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"compress/gzip"
|
|
"context"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
"math"
|
|
"net/netip"
|
|
"os"
|
|
"path/filepath"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
)
|
|
|
|
// Defaults.
|
|
const (
|
|
DefaultMaxBytes = 512 << 20
|
|
DefaultRetain = 30 * 24 * time.Hour
|
|
DefaultDayCap = 200000 // lines per day; beyond it events are only counted
|
|
maxOpen = 4 // day files held open at once
|
|
maxLine = 256 << 10
|
|
hourIdxEvery = 3600
|
|
hardStop = 4 << 30 // no read goes past this many uncompressed bytes
|
|
)
|
|
|
|
// queryDeadline bounds one Query; querySem bounds how many run at once.
|
|
var (
|
|
queryDeadline = 10 * time.Second
|
|
queryBudget int64 = 256 << 20
|
|
)
|
|
|
|
// ErrBusy is returned when too many queries are running.
|
|
var ErrBusy = errors.New("event log busy")
|
|
|
|
var querySem = make(chan struct{}, 3)
|
|
|
|
// Rec is the part of a line the registry understands.
|
|
type Rec struct {
|
|
ID uint64 `json:"id"`
|
|
T int64 `json:"t"`
|
|
IP string `json:"ip"`
|
|
Cat string `json:"cat"`
|
|
Source string `json:"source"`
|
|
Host string `json:"host"`
|
|
Domain string `json:"domain"`
|
|
Method string `json:"method"`
|
|
Path string `json:"path"`
|
|
Status int `json:"status"`
|
|
UA string `json:"ua"`
|
|
User string `json:"user"`
|
|
Jail string `json:"jail"`
|
|
CC string `json:"cc"`
|
|
Unban bool `json:"unban"`
|
|
Fam string `json:"fam"`
|
|
Tech []string `json:"tech"`
|
|
Marker string `json:"marker"`
|
|
Bytes int64 `json:"bytes"`
|
|
DurMS int64 `json:"dur_ms"`
|
|
Flags string `json:"flags"`
|
|
Port int `json:"port,omitempty"`
|
|
Proto string `json:"proto,omitempty"`
|
|
}
|
|
|
|
// Item is a parsed line with its raw JSON.
|
|
type Item struct {
|
|
Rec Rec
|
|
Raw []byte
|
|
}
|
|
|
|
// Options configure a Log.
|
|
type Options struct {
|
|
Dir string
|
|
MaxBytes int64 // total size cap (default 512 MB)
|
|
Retention time.Duration // default 30 d
|
|
DayCap int // lines per day before only counting (default 200000)
|
|
SyncEvery time.Duration // flush+fsync period (default 2 s)
|
|
Now func() time.Time
|
|
Log *slog.Logger
|
|
CacheMem int64 // bytes of decoded closed days kept in memory (default 96 MB, <0 off)
|
|
}
|
|
|
|
type file interface {
|
|
io.Writer
|
|
Sync() error
|
|
Close() error
|
|
}
|
|
|
|
type dayW struct {
|
|
f file
|
|
bw *bufio.Writer
|
|
last time.Time
|
|
needN bool
|
|
}
|
|
|
|
// Log is the registry.
|
|
type Log struct {
|
|
opt Options
|
|
mu sync.Mutex
|
|
w map[int64]*dayW
|
|
size int64
|
|
lines map[int64]int64 // lines written per day since start (day cap)
|
|
seq atomic.Uint64
|
|
drop atomic.Uint64
|
|
warned time.Time
|
|
create func(path string) (file, error)
|
|
gidx map[string]*dayIdx // hour index of compressed day files (sidecar .idx)
|
|
jidx map[int64]*jIdx // hour runs of plain day files written by this process
|
|
needNL map[int64]bool
|
|
dc dayCache
|
|
}
|
|
|
|
type blk struct {
|
|
Off int64 `json:"o"`
|
|
Len int64 `json:"l"`
|
|
N int64 `json:"n"`
|
|
}
|
|
|
|
// dayIdx maps the hour of the day (24: lines of unknown time) to the gzip
|
|
// members that hold its lines.
|
|
type dayIdx struct {
|
|
Size int64 `json:"size"` // size of the .gz this index describes
|
|
H map[int][]blk `json:"h"`
|
|
}
|
|
|
|
type run struct {
|
|
h int
|
|
off, end int64
|
|
}
|
|
|
|
// jIdx indexes the plain day file: [0, unind) is unindexed, runs cover the rest.
|
|
type jIdx struct {
|
|
unind, end int64
|
|
runs []run
|
|
}
|
|
|
|
// jsnap is a consistent copy of a jIdx taken after a flush.
|
|
type jsnap struct {
|
|
unind, end int64
|
|
runs []run
|
|
}
|
|
|
|
// Open creates the directory and finds the last used id.
|
|
func Open(opt Options) (*Log, error) {
|
|
if opt.MaxBytes <= 0 {
|
|
opt.MaxBytes = DefaultMaxBytes
|
|
}
|
|
if opt.Retention <= 0 {
|
|
opt.Retention = DefaultRetain
|
|
}
|
|
if opt.DayCap <= 0 {
|
|
opt.DayCap = DefaultDayCap
|
|
}
|
|
if opt.SyncEvery <= 0 {
|
|
opt.SyncEvery = 2 * time.Second
|
|
}
|
|
if opt.Now == nil {
|
|
opt.Now = time.Now
|
|
}
|
|
if opt.Log == nil {
|
|
opt.Log = slog.Default()
|
|
}
|
|
if err := os.MkdirAll(opt.Dir, 0o700); err != nil {
|
|
return nil, err
|
|
}
|
|
l := &Log{opt: opt, w: map[int64]*dayW{}, lines: map[int64]int64{}, gidx: map[string]*dayIdx{}, jidx: map[int64]*jIdx{}, needNL: map[int64]bool{}}
|
|
l.create = func(path string) (file, error) {
|
|
return os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
|
|
}
|
|
l.cleanTmp()
|
|
l.seq.Store(l.lastID())
|
|
l.size = l.dirSize()
|
|
return l, nil
|
|
}
|
|
|
|
// NextID returns the next event id (increasing across restarts).
|
|
func (l *Log) NextID() uint64 { return l.seq.Add(1) }
|
|
|
|
// LastID is the highest id handed out or found on disk.
|
|
func (l *Log) LastID() uint64 { return l.seq.Load() }
|
|
|
|
// SetLastID raises the id counter (never lowers it).
|
|
func (l *Log) SetLastID(v uint64) {
|
|
for {
|
|
c := l.seq.Load()
|
|
if v <= c || l.seq.CompareAndSwap(c, v) {
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
// Dropped counts events lost to a full disk, the size cap or the day cap.
|
|
func (l *Log) Dropped() uint64 { return l.drop.Load() }
|
|
|
|
// Size is the approximate number of bytes on disk.
|
|
func (l *Log) Size() int64 { l.mu.Lock(); defer l.mu.Unlock(); return l.size }
|
|
|
|
func dayName(day int64) string { return time.Unix(day*86400, 0).UTC().Format("2006-01-02") }
|
|
|
|
func (l *Log) path(day int64) string { return filepath.Join(l.opt.Dir, dayName(day)+".jsonl") }
|
|
|
|
func (l *Log) warn(msg string, args ...any) {
|
|
if l.opt.Now().Sub(l.warned) < time.Minute {
|
|
return
|
|
}
|
|
l.warned = l.opt.Now()
|
|
l.opt.Log.Warn(msg, args...)
|
|
}
|
|
|
|
// Append writes one line (a JSON object without the newline) for the event
|
|
// time t. It never fails the caller: a full disk is logged and the event dropped.
|
|
func (l *Log) Append(t int64, line []byte) {
|
|
if len(line) == 0 || len(line) > maxLine {
|
|
return
|
|
}
|
|
day := t / 86400
|
|
l.mu.Lock()
|
|
defer l.mu.Unlock()
|
|
if l.size >= l.opt.MaxBytes+l.opt.MaxBytes/20 {
|
|
l.drop.Add(1)
|
|
l.warn("event log is over its size cap, dropping events", "size", l.size)
|
|
return
|
|
}
|
|
if l.lines[day] >= int64(l.opt.DayCap) {
|
|
l.lines[day]++
|
|
l.drop.Add(1)
|
|
return
|
|
}
|
|
w := l.writerLocked(day)
|
|
if w == nil {
|
|
l.drop.Add(1)
|
|
return
|
|
}
|
|
w.last = l.opt.Now()
|
|
n := len(line) + 1
|
|
var err error
|
|
if w.needN {
|
|
_, err = w.bw.WriteString("\n") // terminate a partial line left by an earlier failure
|
|
w.needN = false
|
|
n++
|
|
}
|
|
if err == nil {
|
|
if _, err = w.bw.Write(line); err == nil {
|
|
err = w.bw.WriteByte('\n')
|
|
}
|
|
}
|
|
if err != nil {
|
|
l.drop.Add(1)
|
|
l.warn("event log write failed, dropping events", "err", err)
|
|
l.closeWriterLocked(day, true)
|
|
return
|
|
}
|
|
l.lines[day]++
|
|
l.size += int64(n)
|
|
if ji := l.jidx[day]; ji != nil {
|
|
off := ji.end
|
|
ji.end += int64(n)
|
|
h := int(t % 86400 / 3600)
|
|
if k := len(ji.runs); k > 0 && ji.runs[k-1].h == h && ji.runs[k-1].end == off {
|
|
ji.runs[k-1].end = ji.end
|
|
} else if k >= 8192 {
|
|
ji.unind, ji.runs = ji.end, nil // too fragmented: fall back to reading it whole
|
|
} else {
|
|
ji.runs = append(ji.runs, run{h, off, ji.end})
|
|
}
|
|
}
|
|
}
|
|
|
|
func (l *Log) writerLocked(day int64) *dayW {
|
|
if w := l.w[day]; w != nil {
|
|
return w
|
|
}
|
|
if len(l.w) >= maxOpen { // close the least recently used
|
|
var old int64
|
|
var oldT time.Time
|
|
first := true
|
|
for d, w := range l.w {
|
|
if first || w.last.Before(oldT) {
|
|
old, oldT, first = d, w.last, false
|
|
}
|
|
}
|
|
l.closeWriterLocked(old, false)
|
|
}
|
|
f, err := l.create(l.path(day))
|
|
if err != nil {
|
|
l.warn("event log cannot open its file, dropping events", "err", err)
|
|
return nil
|
|
}
|
|
w := &dayW{f: f, bw: bufio.NewWriterSize(f, 64<<10), last: l.opt.Now(), needN: l.needNL[day]}
|
|
delete(l.needNL, day)
|
|
var size int64
|
|
if st, err := os.Stat(l.path(day)); err == nil {
|
|
size = st.Size()
|
|
}
|
|
if ji := l.jidx[day]; ji == nil || ji.end != size {
|
|
l.jidx[day] = &jIdx{unind: size, end: size}
|
|
}
|
|
l.w[day] = w
|
|
return w
|
|
}
|
|
|
|
func (l *Log) closeWriterLocked(day int64, failed bool) {
|
|
w := l.w[day]
|
|
if w == nil {
|
|
return
|
|
}
|
|
delete(l.w, day)
|
|
if !failed {
|
|
w.bw.Flush()
|
|
w.f.Sync()
|
|
}
|
|
w.f.Close()
|
|
if failed {
|
|
// next open starts with a newline so a partial line cannot glue to a good one
|
|
l.needNL[day] = true
|
|
delete(l.jidx, day)
|
|
}
|
|
}
|
|
|
|
// Flush writes buffered lines to the files (readers call it first).
|
|
func (l *Log) Flush() {
|
|
l.mu.Lock()
|
|
defer l.mu.Unlock()
|
|
for day, w := range l.w {
|
|
if err := w.bw.Flush(); err != nil {
|
|
l.warn("event log flush failed", "err", err)
|
|
l.closeWriterLocked(day, true)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (l *Log) syncLocked() {
|
|
for day, w := range l.w {
|
|
err := w.bw.Flush()
|
|
if err == nil {
|
|
err = w.f.Sync()
|
|
}
|
|
if err != nil {
|
|
l.warn("event log sync failed", "err", err)
|
|
l.closeWriterLocked(day, true)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Run flushes and syncs periodically and maintains the files until ctx ends.
|
|
func (l *Log) Run(ctx context.Context) {
|
|
t := time.NewTicker(l.opt.SyncEvery)
|
|
defer t.Stop()
|
|
m := time.NewTicker(15 * time.Second)
|
|
defer m.Stop()
|
|
l.Maintain()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
l.Close()
|
|
return
|
|
case <-t.C:
|
|
l.mu.Lock()
|
|
l.syncLocked()
|
|
l.mu.Unlock()
|
|
case <-m.C:
|
|
l.Maintain()
|
|
}
|
|
}
|
|
}
|
|
|
|
// Close flushes and closes every open file.
|
|
func (l *Log) Close() {
|
|
l.mu.Lock()
|
|
defer l.mu.Unlock()
|
|
for d := range l.w {
|
|
l.closeWriterLocked(d, false)
|
|
}
|
|
}
|
|
|
|
type dayFiles struct {
|
|
day int64
|
|
jsonl string
|
|
gz string
|
|
jsize int64
|
|
gsize int64
|
|
hasJSONL bool
|
|
hasGZ bool
|
|
gmod int64 // modification times (ns), part of the cache signature
|
|
jmod int64
|
|
}
|
|
|
|
// list returns the day files in the directory, oldest first.
|
|
func (l *Log) list() []dayFiles {
|
|
ents, err := os.ReadDir(l.opt.Dir)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
by := map[int64]*dayFiles{}
|
|
for _, e := range ents {
|
|
name := e.Name()
|
|
var base string
|
|
gz := false
|
|
switch {
|
|
case strings.HasSuffix(name, ".jsonl.gz"):
|
|
base, gz = strings.TrimSuffix(name, ".jsonl.gz"), true
|
|
case strings.HasSuffix(name, ".jsonl"):
|
|
base = strings.TrimSuffix(name, ".jsonl")
|
|
default:
|
|
continue
|
|
}
|
|
tm, err := time.Parse("2006-01-02", base)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
d := tm.Unix() / 86400
|
|
f := by[d]
|
|
if f == nil {
|
|
f = &dayFiles{day: d}
|
|
by[d] = f
|
|
}
|
|
info, err := e.Info()
|
|
if err != nil {
|
|
continue
|
|
}
|
|
if gz {
|
|
f.gz, f.gsize, f.hasGZ, f.gmod = filepath.Join(l.opt.Dir, name), info.Size(), true, info.ModTime().UnixNano()
|
|
} else {
|
|
f.jsonl, f.jsize, f.hasJSONL, f.jmod = filepath.Join(l.opt.Dir, name), info.Size(), true, info.ModTime().UnixNano()
|
|
}
|
|
}
|
|
out := make([]dayFiles, 0, len(by))
|
|
for _, f := range by {
|
|
out = append(out, *f)
|
|
}
|
|
sort.Slice(out, func(i, j int) bool { return out[i].day < out[j].day })
|
|
return out
|
|
}
|
|
|
|
func (l *Log) dirSize() int64 {
|
|
var n int64
|
|
for _, f := range l.list() {
|
|
n += f.jsize + f.gsize
|
|
}
|
|
return n
|
|
}
|
|
|
|
func (l *Log) cleanTmp() {
|
|
ents, _ := os.ReadDir(l.opt.Dir)
|
|
for _, e := range ents {
|
|
if strings.HasSuffix(e.Name(), ".tmp") {
|
|
os.Remove(filepath.Join(l.opt.Dir, e.Name()))
|
|
}
|
|
}
|
|
}
|
|
|
|
func (l *Log) lastID() uint64 {
|
|
fs := l.list()
|
|
var max uint64
|
|
for i := len(fs) - 1; i >= 0 && i >= len(fs)-2; i-- {
|
|
l.readDay(fs[i], func(line []byte) bool {
|
|
if k := bytes.Index(line, []byte(`"id":`)); k >= 0 {
|
|
j := k + 5
|
|
e := j
|
|
for e < len(line) && line[e] >= '0' && line[e] <= '9' {
|
|
e++
|
|
}
|
|
if v, err := strconv.ParseUint(string(line[j:e]), 10, 64); err == nil && v > max {
|
|
max = v
|
|
}
|
|
}
|
|
return true
|
|
}, nil, nil, nil)
|
|
}
|
|
return max
|
|
}
|
|
|
|
// Maintain closes idle old files, compresses finished days, then applies the
|
|
// age and size limits.
|
|
func (l *Log) Maintain() {
|
|
now := l.opt.Now()
|
|
today := now.Unix() / 86400
|
|
l.mu.Lock()
|
|
for d, w := range l.w {
|
|
if d < today && now.Sub(w.last) > 20*time.Second {
|
|
l.closeWriterLocked(d, false)
|
|
}
|
|
}
|
|
l.mu.Unlock()
|
|
|
|
for _, f := range l.list() {
|
|
if f.day >= today || !f.hasJSONL {
|
|
continue
|
|
}
|
|
l.mu.Lock()
|
|
_, open := l.w[f.day]
|
|
l.mu.Unlock()
|
|
if open {
|
|
continue
|
|
}
|
|
if err := l.compress(f); err != nil {
|
|
l.opt.Log.Warn("event log compression failed", "day", dayName(f.day), "err", err)
|
|
}
|
|
}
|
|
files := l.list()
|
|
cut := now.Add(-l.opt.Retention).Unix()
|
|
for _, f := range files {
|
|
if (f.day+1)*86400 < cut {
|
|
l.remove(f)
|
|
}
|
|
}
|
|
files = l.list()
|
|
var total int64
|
|
for _, f := range files {
|
|
total += f.jsize + f.gsize
|
|
}
|
|
for _, f := range files {
|
|
if total <= l.opt.MaxBytes {
|
|
break
|
|
}
|
|
if f.day >= today {
|
|
continue // the current day is never deleted
|
|
}
|
|
total -= f.jsize + f.gsize
|
|
l.remove(f)
|
|
}
|
|
l.mu.Lock()
|
|
l.size = total
|
|
for d := range l.lines {
|
|
if d < today-1 {
|
|
delete(l.lines, d)
|
|
}
|
|
}
|
|
l.mu.Unlock()
|
|
}
|
|
|
|
func (l *Log) remove(f dayFiles) {
|
|
for _, p := range []string{f.jsonl, f.gz} {
|
|
if p != "" {
|
|
os.Remove(p)
|
|
}
|
|
}
|
|
if f.gz != "" {
|
|
os.Remove(strings.TrimSuffix(f.gz, ".jsonl.gz") + ".idx")
|
|
}
|
|
l.mu.Lock()
|
|
delete(l.gidx, f.gz)
|
|
l.mu.Unlock()
|
|
}
|
|
|
|
// quickT extracts the "t" field of a line without a full parse.
|
|
func quickT(line []byte) (int64, bool) {
|
|
k := bytes.Index(line, []byte(`"t":`))
|
|
if k < 0 {
|
|
return 0, false
|
|
}
|
|
j := k + 4
|
|
e := j
|
|
for e < len(line) && line[e] >= '0' && line[e] <= '9' {
|
|
e++
|
|
}
|
|
v, err := strconv.ParseInt(string(line[j:e]), 10, 64)
|
|
return v, err == nil
|
|
}
|
|
|
|
// compress turns a finished day's jsonl into gzip members, one per hour of
|
|
// the day, appended to the day's .gz (a multi-member gzip file reads as one
|
|
// stream), and records where each hour lives in the .idx sidecar.
|
|
func (l *Log) compress(f dayFiles) error {
|
|
in, err := os.Open(f.jsonl)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer in.Close()
|
|
var bufs [25]bytes.Buffer
|
|
var zws [25]*gzip.Writer
|
|
var ns [25]int64
|
|
eachLine(in, func(line []byte) bool {
|
|
h := 24
|
|
if t, ok := quickT(line); ok && t/86400 == f.day {
|
|
h = int(t % 86400 / 3600)
|
|
}
|
|
if zws[h] == nil {
|
|
zws[h], _ = gzip.NewWriterLevel(&bufs[h], gzip.BestCompression)
|
|
}
|
|
zws[h].Write(line)
|
|
zws[h].Write([]byte{'\n'})
|
|
ns[h]++
|
|
return true
|
|
}, nil)
|
|
tmp := f.jsonl + ".gz.tmp"
|
|
out, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var base int64
|
|
idx := &dayIdx{H: map[int][]blk{}}
|
|
gz := strings.TrimSuffix(f.jsonl, ".jsonl") + ".jsonl.gz"
|
|
if f.hasGZ {
|
|
base = f.gsize
|
|
if old := l.loadIdx(f.gz); old != nil {
|
|
idx = old
|
|
} else if base > 0 {
|
|
idx.H[24] = []blk{{0, base, 0}} // an older gz without an index: always read it whole
|
|
}
|
|
}
|
|
off := base
|
|
for h := 0; h < 25 && err == nil; h++ {
|
|
if zws[h] == nil {
|
|
continue
|
|
}
|
|
if err = zws[h].Close(); err != nil {
|
|
break
|
|
}
|
|
var n int
|
|
n, err = out.Write(bufs[h].Bytes())
|
|
idx.H[h] = append(idx.H[h], blk{off, int64(n), ns[h]})
|
|
off += int64(n)
|
|
}
|
|
if err == nil {
|
|
err = out.Sync()
|
|
}
|
|
if cerr := out.Close(); err == nil {
|
|
err = cerr
|
|
}
|
|
if err != nil {
|
|
os.Remove(tmp)
|
|
return err
|
|
}
|
|
if f.hasGZ {
|
|
if err = appendFile(f.gz, tmp); err != nil {
|
|
os.Remove(tmp)
|
|
return err
|
|
}
|
|
os.Remove(tmp)
|
|
} else if err = os.Rename(tmp, gz); err != nil {
|
|
os.Remove(tmp)
|
|
return err
|
|
}
|
|
idx.Size = off
|
|
if b, merr := json.Marshal(idx); merr == nil {
|
|
os.WriteFile(gz[:len(gz)-len(".jsonl.gz")]+".idx", b, 0o600)
|
|
}
|
|
l.mu.Lock()
|
|
delete(l.gidx, gz)
|
|
l.mu.Unlock()
|
|
return os.Remove(f.jsonl)
|
|
}
|
|
|
|
// loadIdx reads the index sidecar of a .gz when it matches the file's size.
|
|
func (l *Log) loadIdx(gz string) *dayIdx {
|
|
l.mu.Lock()
|
|
if x, ok := l.gidx[gz]; ok {
|
|
l.mu.Unlock()
|
|
return x
|
|
}
|
|
l.mu.Unlock()
|
|
var x *dayIdx
|
|
if st, err := os.Stat(gz); err == nil {
|
|
if b, err := os.ReadFile(strings.TrimSuffix(gz, ".jsonl.gz") + ".idx"); err == nil {
|
|
var d dayIdx
|
|
if json.Unmarshal(b, &d) == nil && d.Size == st.Size() && d.H != nil {
|
|
x = &d
|
|
}
|
|
}
|
|
}
|
|
l.mu.Lock()
|
|
if len(l.gidx) > 64 {
|
|
l.gidx = map[string]*dayIdx{}
|
|
}
|
|
l.gidx[gz] = x
|
|
l.mu.Unlock()
|
|
return x
|
|
}
|
|
|
|
func appendFile(dst, src string) error {
|
|
in, err := os.Open(src)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer in.Close()
|
|
out, err := os.OpenFile(dst, os.O_WRONLY|os.O_APPEND, 0o600)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = io.Copy(out, in)
|
|
if err == nil {
|
|
err = out.Sync()
|
|
}
|
|
if cerr := out.Close(); err == nil {
|
|
err = cerr
|
|
}
|
|
return err
|
|
}
|
|
|
|
// ---- reading ----
|
|
|
|
// begin flushes and snapshots the plain-file indexes so a read sees whole lines only.
|
|
func (l *Log) begin() map[int64]jsnap {
|
|
l.mu.Lock()
|
|
defer l.mu.Unlock()
|
|
for day, w := range l.w {
|
|
if err := w.bw.Flush(); err != nil {
|
|
l.warn("event log flush failed", "err", err)
|
|
l.closeWriterLocked(day, true)
|
|
}
|
|
}
|
|
out := map[int64]jsnap{}
|
|
for d, ji := range l.jidx {
|
|
if _, open := l.w[d]; open {
|
|
out[d] = jsnap{ji.unind, ji.end, append([]run(nil), ji.runs...)}
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// readDay streams the lines of a day's files (compressed part first). A
|
|
// truncated gzip tail or an oversized line is skipped, never fatal. With
|
|
// from/to (unix seconds, to 0 = open) only the hours that can match are read,
|
|
// using the hour indexes.
|
|
func (l *Log) readDay(f dayFiles, fn func([]byte) bool, nbytes *int64, rng *[2]int64, snap map[int64]jsnap) {
|
|
cont := true
|
|
hours := func(h int) bool { // may hour h of this day hold a wanted event?
|
|
if rng == nil || h >= 24 {
|
|
return true
|
|
}
|
|
lo, hi := f.day*86400+int64(h)*3600, f.day*86400+int64(h)*3600+3599
|
|
return hi >= rng[0] && (rng[1] == 0 || lo <= rng[1])
|
|
}
|
|
if f.hasGZ && cont {
|
|
if fh, err := os.Open(f.gz); err == nil {
|
|
idx := (*dayIdx)(nil)
|
|
if rng != nil {
|
|
idx = l.loadIdx(f.gz)
|
|
}
|
|
if idx == nil {
|
|
if zr, err := gzip.NewReader(fh); err == nil {
|
|
cont = eachLine(zr, fn, nbytes)
|
|
}
|
|
} else {
|
|
for h := 0; h <= 24 && cont; h++ {
|
|
if !hours(h) {
|
|
continue
|
|
}
|
|
for _, b := range idx.H[h] {
|
|
if zr, err := gzip.NewReader(io.NewSectionReader(fh, b.Off, b.Len)); err == nil {
|
|
cont = eachLine(zr, fn, nbytes)
|
|
}
|
|
if !cont {
|
|
break
|
|
}
|
|
}
|
|
}
|
|
}
|
|
fh.Close()
|
|
}
|
|
}
|
|
if f.hasJSONL && cont {
|
|
if fh, err := os.Open(f.jsonl); err == nil {
|
|
sn, ok := snap[f.day]
|
|
if !ok || rng == nil {
|
|
eachLine(fh, fn, nbytes)
|
|
} else {
|
|
if sn.unind > 0 {
|
|
cont = eachLine(io.NewSectionReader(fh, 0, sn.unind), fn, nbytes)
|
|
}
|
|
for _, r := range sn.runs {
|
|
if !cont {
|
|
break
|
|
}
|
|
if hours(r.h) {
|
|
cont = eachLine(io.NewSectionReader(fh, r.off, r.end-r.off), fn, nbytes)
|
|
}
|
|
}
|
|
}
|
|
fh.Close()
|
|
}
|
|
}
|
|
}
|
|
|
|
// eachLine reads newline-terminated lines of at most maxLine bytes; it
|
|
// returns false when fn asked to stop.
|
|
func eachLine(r io.Reader, fn func([]byte) bool, nbytes *int64) bool {
|
|
br := bufio.NewReaderSize(r, 128<<10)
|
|
for {
|
|
line, err := br.ReadSlice('\n')
|
|
if err == bufio.ErrBufferFull {
|
|
if nbytes != nil {
|
|
*nbytes += int64(len(line))
|
|
}
|
|
var rest []byte
|
|
for err == bufio.ErrBufferFull { // oversized: discard the rest of the line, but count it
|
|
rest, err = br.ReadSlice('\n')
|
|
if nbytes != nil {
|
|
*nbytes += int64(len(rest))
|
|
if *nbytes > hardStop {
|
|
return false // a decompression bomb: stop reading
|
|
}
|
|
}
|
|
}
|
|
if err != nil {
|
|
return true
|
|
}
|
|
continue
|
|
}
|
|
if len(line) > 0 {
|
|
if nbytes != nil {
|
|
*nbytes += int64(len(line))
|
|
}
|
|
l := bytes.TrimRight(line, "\r\n")
|
|
if len(l) > 0 && !fn(l) {
|
|
return false
|
|
}
|
|
}
|
|
if err != nil {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
|
|
// Filter selects events. Zero fields match everything.
|
|
type Filter struct {
|
|
From, To int64 // inclusive unix seconds; To 0 means no upper bound
|
|
Host string
|
|
Cats map[string]bool
|
|
IP string // address or CIDR; an address matches its IPv6 /64 key too
|
|
Q string // case-insensitive substring over the text fields
|
|
Fam string
|
|
ipPrefix netip.Prefix
|
|
ipOK bool
|
|
ipText []byte
|
|
qLower string
|
|
}
|
|
|
|
// Prepare compiles the filter.
|
|
func (f *Filter) Prepare() {
|
|
f.qLower = strings.ToLower(f.Q)
|
|
f.ipOK, f.ipText = false, nil
|
|
if f.IP == "" {
|
|
return
|
|
}
|
|
if p, err := netip.ParsePrefix(f.IP); err == nil {
|
|
f.ipPrefix, f.ipOK = p.Masked(), true
|
|
return
|
|
}
|
|
if a, err := netip.ParseAddr(f.IP); err == nil {
|
|
a = a.Unmap()
|
|
if a.Is4() {
|
|
f.ipPrefix, f.ipOK = netip.PrefixFrom(a, 32), true
|
|
f.ipText = []byte(`"` + a.String() + `"`)
|
|
} else {
|
|
f.ipPrefix, f.ipOK = netip.PrefixFrom(a, 64).Masked(), true
|
|
}
|
|
}
|
|
}
|
|
|
|
// Match reports whether r passes the filter (Prepare must have run).
|
|
func (f *Filter) Match(r *Rec) bool {
|
|
if r.T < f.From || (f.To != 0 && r.T > f.To) {
|
|
return false
|
|
}
|
|
if f.Host != "" && !hostMatch(f.Host, r.Host) {
|
|
return false
|
|
}
|
|
if len(f.Cats) > 0 && !f.Cats[r.Cat] {
|
|
return false
|
|
}
|
|
if f.Fam != "" && r.Fam != f.Fam {
|
|
return false
|
|
}
|
|
if f.IP != "" {
|
|
if !f.ipOK {
|
|
return false
|
|
}
|
|
a, err := netip.ParseAddr(r.IP)
|
|
if err != nil || !f.ipPrefix.Contains(a.Unmap()) {
|
|
return false
|
|
}
|
|
}
|
|
if f.qLower != "" {
|
|
hit := false
|
|
for _, s := range [...]string{r.Path, r.Domain, r.UA, r.User, r.Jail, r.IP, r.Host, r.Source, r.CC, r.Fam, r.Marker} {
|
|
if s != "" && strings.Contains(strings.ToLower(s), f.qLower) {
|
|
hit = true
|
|
break
|
|
}
|
|
}
|
|
if !hit {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// ScanInfo describes a scan.
|
|
type ScanInfo struct {
|
|
Bytes int64
|
|
Lines int64
|
|
Matched int64
|
|
Truncated bool // stopped by the byte budget
|
|
}
|
|
|
|
// Scan visits the matching events of the days in [f.From, f.To], newest day
|
|
// first when newestFirst. It reads at most maxBytes of uncompressed data
|
|
// (0: 512 MB). fn returns false to stop.
|
|
func (l *Log) Scan(f Filter, maxBytes int64, newestFirst bool, fn func(Rec, []byte) bool) ScanInfo {
|
|
snap := l.begin()
|
|
if maxBytes <= 0 {
|
|
maxBytes = 512 << 20
|
|
}
|
|
f.Prepare()
|
|
rng := &[2]int64{f.From, f.To}
|
|
var info ScanInfo
|
|
files := l.daysIn(f.From, f.To)
|
|
if newestFirst {
|
|
for i, j := 0, len(files)-1; i < j; i, j = i+1, j-1 {
|
|
files[i], files[j] = files[j], files[i]
|
|
}
|
|
}
|
|
for _, d := range files {
|
|
if info.Bytes >= maxBytes {
|
|
info.Truncated = true
|
|
break
|
|
}
|
|
stop := false
|
|
l.readDay(d, func(line []byte) bool {
|
|
if info.Bytes >= maxBytes {
|
|
info.Truncated = true
|
|
stop = true
|
|
return false
|
|
}
|
|
info.Lines++
|
|
if f.ipText != nil && !bytes.Contains(line, f.ipText) {
|
|
return true
|
|
}
|
|
var r Rec
|
|
if json.Unmarshal(line, &r) != nil || r.IP == "" {
|
|
return true // corrupted line: ignored
|
|
}
|
|
if !f.Match(&r) {
|
|
return true
|
|
}
|
|
info.Matched++
|
|
if !fn(r, line) {
|
|
stop = true
|
|
return false
|
|
}
|
|
return true
|
|
}, &info.Bytes, rng, snap)
|
|
if stop {
|
|
break
|
|
}
|
|
}
|
|
return info
|
|
}
|
|
|
|
func (l *Log) daysIn(from, to int64) []dayFiles {
|
|
var out []dayFiles
|
|
for _, d := range l.list() {
|
|
if (d.day+1)*86400 <= from || (to != 0 && d.day*86400 > to) {
|
|
continue
|
|
}
|
|
out = append(out, d)
|
|
}
|
|
return out
|
|
}
|
|
|
|
// Query is a paginated read.
|
|
type Query struct {
|
|
Filter
|
|
Limit int
|
|
Cursor string
|
|
Desc bool
|
|
}
|
|
|
|
// Result of a Query.
|
|
type Result struct {
|
|
Items []Item
|
|
Next string
|
|
TotalEstimate int64
|
|
Truncated bool
|
|
}
|
|
|
|
var ErrCursor = errors.New("invalid cursor")
|
|
|
|
func encodeCursor(t int64, id uint64) string {
|
|
return base64.RawURLEncoding.EncodeToString([]byte(fmt.Sprintf("%d.%d", t, id)))
|
|
}
|
|
|
|
func decodeCursor(c string) (int64, uint64, error) {
|
|
b, err := base64.RawURLEncoding.DecodeString(c)
|
|
if err != nil {
|
|
return 0, 0, ErrCursor
|
|
}
|
|
a, bb, ok := strings.Cut(string(b), ".")
|
|
if !ok {
|
|
return 0, 0, ErrCursor
|
|
}
|
|
t, e1 := strconv.ParseInt(a, 10, 64)
|
|
id, e2 := strconv.ParseUint(bb, 10, 64)
|
|
if e1 != nil || e2 != nil {
|
|
return 0, 0, ErrCursor
|
|
}
|
|
return t, id, nil
|
|
}
|
|
|
|
// MaxLimit is the largest page.
|
|
const MaxLimit = 5000
|
|
|
|
// Query returns one page ordered by (t, id). The cursor of the previous page
|
|
// continues it; days wholly before the cursor are not read.
|
|
func (l *Log) Query(q Query) (Result, error) {
|
|
select {
|
|
case querySem <- struct{}{}:
|
|
defer func() { <-querySem }()
|
|
default:
|
|
return Result{}, ErrBusy
|
|
}
|
|
deadline := time.Now().Add(queryDeadline)
|
|
snap := l.begin()
|
|
rng := &[2]int64{q.From, q.To}
|
|
if q.Limit <= 0 {
|
|
q.Limit = 200
|
|
}
|
|
if q.Limit > MaxLimit {
|
|
q.Limit = MaxLimit
|
|
}
|
|
q.Filter.Prepare()
|
|
var ct int64
|
|
var cid uint64
|
|
hasCur := q.Cursor != ""
|
|
if hasCur {
|
|
var err error
|
|
if ct, cid, err = decodeCursor(q.Cursor); err != nil {
|
|
return Result{}, err
|
|
}
|
|
}
|
|
after := func(t int64, id uint64) bool { // strictly after the cursor in the page order
|
|
if !hasCur {
|
|
return true
|
|
}
|
|
if q.Desc {
|
|
return t < ct || t == ct && id < cid
|
|
}
|
|
return t > ct || t == ct && id > cid
|
|
}
|
|
less := func(a, b *Item) bool {
|
|
if a.Rec.T != b.Rec.T {
|
|
if q.Desc {
|
|
return a.Rec.T > b.Rec.T
|
|
}
|
|
return a.Rec.T < b.Rec.T
|
|
}
|
|
if q.Desc {
|
|
return a.Rec.ID > b.Rec.ID
|
|
}
|
|
return a.Rec.ID < b.Rec.ID
|
|
}
|
|
files := l.daysIn(q.From, q.To)
|
|
if q.Desc {
|
|
for i, j := 0, len(files)-1; i < j; i, j = i+1, j-1 {
|
|
files[i], files[j] = files[j], files[i]
|
|
}
|
|
}
|
|
var res Result
|
|
var page []Item
|
|
var scannedLines, matched, scannedBytes int64
|
|
var estLinesSkipped, estLinesLeft float64
|
|
var budget = queryBudget
|
|
more := false
|
|
for i, d := range files {
|
|
est := float64(d.jsize) + float64(d.gsize)*6 // bytes; turned into lines below
|
|
if hasCur { // whole days before the cursor were already served
|
|
lo, hi := d.day*86400, (d.day+1)*86400-1
|
|
if q.Desc && lo > ct || !q.Desc && hi < ct {
|
|
estLinesSkipped += est
|
|
continue
|
|
}
|
|
}
|
|
if len(page) > q.Limit || budget <= 0 || time.Now().After(deadline) {
|
|
if len(page) > q.Limit {
|
|
more = true
|
|
} else {
|
|
res.Truncated = true
|
|
}
|
|
if time.Now().After(deadline) {
|
|
res.Truncated = true
|
|
}
|
|
for _, r := range files[i:] {
|
|
estLinesLeft += float64(r.jsize) + float64(r.gsize)*6
|
|
}
|
|
break
|
|
}
|
|
var nb int64
|
|
l.readDay(d, func(line []byte) bool {
|
|
if nb > budget || scannedLines%2048 == 0 && time.Now().After(deadline) {
|
|
res.Truncated = true
|
|
return false
|
|
}
|
|
scannedLines++
|
|
if q.ipText != nil && !bytes.Contains(line, q.ipText) {
|
|
return true
|
|
}
|
|
var r Rec
|
|
if json.Unmarshal(line, &r) != nil || r.IP == "" {
|
|
return true
|
|
}
|
|
if !q.Filter.Match(&r) {
|
|
return true
|
|
}
|
|
matched++
|
|
if !after(r.T, r.ID) {
|
|
return true
|
|
}
|
|
page = append(page, Item{Rec: r, Raw: append([]byte(nil), line...)})
|
|
if len(page) > 4*q.Limit+4096 { // keep the working set bounded
|
|
sort.Slice(page, func(a, b int) bool { return less(&page[a], &page[b]) })
|
|
page = page[:q.Limit+1]
|
|
}
|
|
return true
|
|
}, &nb, rng, snap)
|
|
budget -= nb
|
|
scannedBytes += nb
|
|
}
|
|
sort.Slice(page, func(a, b int) bool { return less(&page[a], &page[b]) })
|
|
if len(page) > q.Limit {
|
|
page, more = page[:q.Limit], true
|
|
}
|
|
res.Items = page
|
|
if more && len(page) > 0 {
|
|
last := page[len(page)-1].Rec
|
|
res.Next = encodeCursor(last.T, last.ID)
|
|
}
|
|
ratio := 1.0
|
|
if scannedLines > 0 {
|
|
ratio = float64(matched) / float64(scannedLines)
|
|
}
|
|
avg := 300.0 // bytes per line, measured on what was read when possible
|
|
if scannedLines > 0 && scannedBytes > 0 {
|
|
avg = float64(scannedBytes) / float64(scannedLines)
|
|
}
|
|
res.TotalEstimate = matched + int64(math.Ceil((estLinesSkipped+estLinesLeft)/avg*ratio))
|
|
return res, nil
|
|
}
|
|
|
|
// Counts returns events per hour (index = hour number) for a window, from the
|
|
// in-memory day index when possible; used by period views to avoid full scans.
|
|
func (l *Log) Counts(from, to int64) map[int64]int64 {
|
|
out := map[int64]int64{}
|
|
l.Scan(Filter{From: from, To: to}, 0, false, func(r Rec, _ []byte) bool {
|
|
out[r.T/3600]++
|
|
return true
|
|
})
|
|
return out
|
|
}
|
|
|
|
// StartCursor is a cursor that begins an ascending read at time t.
|
|
func StartCursor(t int64) string { return encodeCursor(t, 0) }
|
|
|
|
// hostMatch reports whether host is the filter or one of its comma list.
|
|
func hostMatch(filter, host string) bool {
|
|
if filter == host {
|
|
return true
|
|
}
|
|
if !strings.Contains(filter, ",") {
|
|
return false
|
|
}
|
|
for _, n := range strings.Split(filter, ",") {
|
|
if strings.TrimSpace(n) == host {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|