Files
urutau/internal/evlog/daycache.go
T

372 lines
8.9 KiB
Go

package evlog
import (
"bytes"
"encoding/json"
"sync"
)
// Closed days never change, so the studies decode each of them once into a
// compact form (strings interned per day, fields as indexes) and keep it in
// memory under a byte cap. A day is reloaded when the size or modification
// time of its files changes. The current day is always read live.
const (
defaultCacheMem = 96 << 20
loadParallel = 3
crecSize = 112
)
type crec struct {
id uint64
bytes, durMS, t int64
s [15]uint32 // ip cat source host domain method path ua user jail cc fam marker flags proto
status, port int32
tech0, techN uint32
unban bool
}
type cday struct {
day int64
sig [4]int64
recs []crec
strs []string
tech []uint32
mem int64
last uint64
}
type dayLoad struct {
done chan struct{}
d *cday
}
type dayCache struct {
mu sync.Mutex
m map[int64]*cday
fl map[int64]*dayLoad
mem int64
tick uint64
loads int64 // days decoded from disk (for tests and diagnostics)
}
func sigOf(f dayFiles) [4]int64 { return [4]int64{f.gsize, f.gmod, f.jsize, f.jmod} }
type interner struct {
m map[string]uint32
strs []string
mem int64
}
func (in *interner) id(s string) uint32 {
if v, ok := in.m[s]; ok {
return v
}
v := uint32(len(in.strs))
in.m[s] = v
in.strs = append(in.strs, s)
in.mem += int64(len(s)) + 48
return v
}
type dayBuilder struct {
d *cday
in *interner
}
func newBuilder(day int64, sig [4]int64) *dayBuilder {
return &dayBuilder{d: &cday{day: day, sig: sig}, in: &interner{m: map[string]uint32{"": 0}, strs: []string{""}}}
}
func (b *dayBuilder) add(r *Rec) {
in, d := b.in, b.d
c := crec{id: r.ID, t: r.T, bytes: r.Bytes, durMS: r.DurMS, status: int32(r.Status), port: int32(r.Port), unban: r.Unban}
c.s = [15]uint32{in.id(r.IP), in.id(r.Cat), in.id(r.Source), in.id(r.Host), in.id(r.Domain), in.id(r.Method), in.id(r.Path),
in.id(r.UA), in.id(r.User), in.id(r.Jail), in.id(r.CC), in.id(r.Fam), in.id(r.Marker), in.id(r.Flags), in.id(r.Proto)}
if len(r.Tech) > 0 {
c.tech0, c.techN = uint32(len(d.tech)), uint32(len(r.Tech))
for _, t := range r.Tech {
d.tech = append(d.tech, in.id(t))
}
}
d.recs = append(d.recs, c)
}
func (b *dayBuilder) done() *cday {
d := b.d
d.recs = append([]crec(nil), d.recs...) // trim the slack
d.strs = b.in.strs
d.mem = int64(len(d.recs))*crecSize + int64(len(d.tech))*4 + b.in.mem
return d
}
// decodeDay reads a whole day into compact form.
func (l *Log) decodeDay(f dayFiles) *cday {
b := newBuilder(f.day, sigOf(f))
l.readDay(f, func(line []byte) bool {
var r Rec
if json.Unmarshal(line, &r) == nil && r.IP != "" {
b.add(&r)
}
return true
}, nil, nil, nil)
return b.done()
}
// Ref points at one event of a decoded day without copying it.
type Ref struct {
d *cday
i uint32
}
// Rec rebuilds the event.
func (r Ref) Rec() Rec { return r.d.rec(&r.d.recs[r.i]) }
// IP is the address of the event, without rebuilding the rest.
func (r Ref) IP() string { return r.d.strs[r.d.recs[r.i].s[0]] }
// T is the time of the event.
func (r Ref) T() int64 { return r.d.recs[r.i].t }
// ScanRefs visits the matching events as references into the decoded days
// (the live day is decoded into a private one), so a long study keeps 16 bytes
// per event instead of a copy. The references keep their days alive.
func (l *Log) ScanRefs(f Filter, maxBytes int64, fn func(Ref) bool) ScanInfo {
var info ScanInfo
var live *dayBuilder
var liveDay int64 = -1
flush := func(stop bool) bool {
if live == nil {
return stop
}
d := live.done()
live = nil
for i := range d.recs {
if !fn(Ref{d, uint32(i)}) {
return true
}
}
return stop
}
info = l.scanDays(f, maxBytes, func(d *cday, idx []uint32) bool {
for _, i := range idx {
if !fn(Ref{d, i}) {
return false
}
}
return true
}, func(day int64, r *Rec) bool {
if live == nil || liveDay != day {
flush(false)
live, liveDay = newBuilder(day, [4]int64{}), day
}
live.add(r)
return true
})
flush(false)
return info
}
func (d *cday) rec(c *crec) Rec {
s := d.strs
r := Rec{ID: c.id, T: c.t, IP: s[c.s[0]], Cat: s[c.s[1]], Source: s[c.s[2]], Host: s[c.s[3]], Domain: s[c.s[4]],
Method: s[c.s[5]], Path: s[c.s[6]], Status: int(c.status), UA: s[c.s[7]], User: s[c.s[8]], Jail: s[c.s[9]], CC: s[c.s[10]],
Unban: c.unban, Fam: s[c.s[11]], Marker: s[c.s[12]], Bytes: c.bytes, DurMS: c.durMS, Flags: s[c.s[13]], Port: int(c.port), Proto: s[c.s[14]]}
if c.techN > 0 {
r.Tech = make([]string, c.techN)
for i := range r.Tech {
r.Tech[i] = s[d.tech[c.tech0+uint32(i)]]
}
}
return r
}
// day returns the decoded day, from memory when its files did not change.
func (l *Log) day(f dayFiles) *cday {
c := &l.dc
for {
c.mu.Lock()
if d, ok := c.m[f.day]; ok && d.sig == sigOf(f) {
c.tick++
d.last = c.tick
c.mu.Unlock()
return d
}
if fl, ok := c.fl[f.day]; ok {
c.mu.Unlock()
<-fl.done
if fl.d != nil && fl.d.sig == sigOf(f) {
return fl.d
}
continue
}
fl := &dayLoad{done: make(chan struct{})}
if c.fl == nil {
c.fl = map[int64]*dayLoad{}
}
c.fl[f.day] = fl
c.mu.Unlock()
d := l.decodeDay(f)
c.mu.Lock()
c.loads++
delete(c.fl, f.day)
fl.d = d
if cap := l.cacheCap(); cap > 0 && d.mem <= cap {
if c.m == nil {
c.m = map[int64]*cday{}
}
if old, ok := c.m[f.day]; ok {
c.mem -= old.mem
}
c.tick++
d.last = c.tick
c.m[f.day], c.mem = d, c.mem+d.mem
for c.mem > cap { // evict the least recently used other days
var victim *cday
for _, x := range c.m {
if x != d && (victim == nil || x.last < victim.last) {
victim = x
}
}
if victim == nil {
break
}
delete(c.m, victim.day)
c.mem -= victim.mem
}
}
c.mu.Unlock()
close(fl.done)
return d
}
}
func (l *Log) cacheCap() int64 {
switch {
case l.opt.CacheMem < 0:
return 0
case l.opt.CacheMem == 0:
return defaultCacheMem
}
return l.opt.CacheMem
}
// CacheStats reports the decoded days held and their approximate size.
func (l *Log) CacheStats() (days int, mem, loads int64) {
l.dc.mu.Lock()
defer l.dc.mu.Unlock()
return len(l.dc.m), l.dc.mem, l.dc.loads
}
// ScanRecs is Scan for callers that do not need the raw line. Closed days are
// served from the decoded day cache, so a repeated study of a long window does
// not decompress and parse the registry again; the current day is read live.
// The byte budget counts only what is read from disk: a cached day is bounded
// by the cache itself.
func (l *Log) ScanRecs(f Filter, maxBytes int64, newestFirst bool, fn func(Rec) bool) ScanInfo {
if l.cacheCap() <= 0 || newestFirst {
return l.Scan(f, maxBytes, newestFirst, func(r Rec, _ []byte) bool { return fn(r) })
}
return l.scanDays(f, maxBytes, func(d *cday, idx []uint32) bool {
for _, i := range idx {
if !fn(d.rec(&d.recs[i])) {
return false
}
}
return true
}, func(_ int64, r *Rec) bool { return fn(*r) })
}
// scanDays walks the days of the window in order: closed days through the
// cache (day and the indexes of its matching events), the live day line by
// line (live).
func (l *Log) scanDays(f Filter, maxBytes int64, closed func(*cday, []uint32) bool, live func(day int64, r *Rec) bool) ScanInfo {
if maxBytes <= 0 {
maxBytes = 512 << 20
}
f.Prepare()
files := l.daysIn(f.From, f.To)
today := l.opt.Now().Unix() / 86400
var info ScanInfo
var snap map[int64]jsnap
for i := 0; i < len(files); {
if info.Bytes >= maxBytes {
info.Truncated = true
break
}
if files[i].day >= today || l.cacheCap() <= 0 { // live day: read the files
if snap == nil {
snap = l.begin()
}
stop := false
rng := &[2]int64{f.From, f.To}
day := files[i].day
l.readDay(files[i], func(line []byte) bool {
if info.Bytes >= maxBytes {
info.Truncated, stop = true, 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 == "" || !f.Match(&r) {
return true
}
info.Matched++
if !live(day, &r) {
stop = true
return false
}
return true
}, &info.Bytes, rng, snap)
if stop {
break
}
i++
continue
}
// a batch of closed days, decoded in parallel
j := i
for j < len(files) && j-i < loadParallel && files[j].day < today {
j++
}
days := make([]*cday, j-i)
var wg sync.WaitGroup
for k := range days {
wg.Add(1)
go func() {
defer wg.Done()
days[k] = l.day(files[i+k])
}()
}
wg.Wait()
for _, d := range days {
var idx []uint32
for x := range d.recs {
c := &d.recs[x]
info.Lines++
if c.t < f.From || (f.To != 0 && c.t > f.To) {
continue
}
if f.Host != "" || len(f.Cats) > 0 || f.Fam != "" || f.IP != "" || f.qLower != "" {
r := d.rec(c)
if !f.Match(&r) {
continue
}
}
idx = append(idx, uint32(x))
}
info.Matched += int64(len(idx))
if !closed(d, idx) {
return info
}
}
i = j
}
return info
}