Files
urutau/internal/store/snapshot.go
T

294 lines
7.2 KiB
Go

package store
import (
"bufio"
"encoding/gob"
"errors"
"os"
"path/filepath"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
)
const snapshotVersion = 2
// Offset is a saved read position of a log file.
type Offset struct {
Inode uint64
Offset int64
FP uint64
FPLen int
}
type snapshot struct {
V int
Saved int64
Stamps [slots]int64
Counts [slots][core.NumCats]uint32
Hours [hourSlots]hourSlot
MonSt [slots]int64
MonN [slots]uint32
OwnSt [slots]int64 // own traffic minute buckets (optional: older snapshots lack it)
OwnN [slots][2]uint32
Dom map[string]*domData
GDays [anDays]gDay
Svc map[string]*svcData // service health (optional: older snapshots lack it)
IPs map[string]*IPRec
Recent []FeedEvent
Rhead int
Offsets map[string]Offset
IDSeq uint64
}
// Version 1 snapshots (7 days: minute buckets for the whole window, 168 hour
// slots, 8 analytics days) are read and converted on load.
type snapshotV1 struct {
V int
Saved int64
Stamps [7 * 24 * 60]int64
Counts [7 * 24 * 60][core.NumCats]uint32
Hours [7 * 24]hourSlot
MonSt [7 * 24 * 60]int64
MonN [7 * 24 * 60]uint32
Dom map[string]*domDataV1
IPs map[string]*IPRec
Recent []FeedEvent
Rhead int
Offsets map[string]Offset
}
type domDataV1 struct {
MinSt [24 * 60]int64
MinReq [24 * 60]uint32
MinPages [24 * 60]uint32
Hours [7 * 24]anHour
Days [8]anDay
Last int64
}
// Save writes the state atomically (tmp + rename).
func (s *Store) Save(path string, offsets map[string]Offset) error {
tmp := path + ".tmp"
f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
if err != nil {
return err
}
bw := bufio.NewWriterSize(f, 256*1024)
s.mu.RLock()
snap := snapshot{V: snapshotVersion, Saved: s.now().Unix(), Stamps: s.stamps, Counts: s.counts, Hours: s.hours, MonSt: s.monSt, MonN: s.monN, OwnSt: s.ownSt, OwnN: s.ownN, Dom: s.tr.dom, GDays: s.tr.gdays, Svc: s.sv.m,
IPs: s.ips, Recent: s.recent, Rhead: s.rhead, Offsets: offsets, IDSeq: s.ids.Load()}
err = gob.NewEncoder(bw).Encode(&snap)
s.mu.RUnlock()
if err == nil {
err = bw.Flush()
}
if err == nil {
err = f.Sync()
}
if cerr := f.Close(); err == nil {
err = cerr
}
if err != nil {
os.Remove(tmp)
return err
}
return os.Rename(tmp, path)
}
// Load restores a snapshot and returns the saved file offsets. A missing file
// is not an error (fresh start).
func (s *Store) Load(path string) (map[string]Offset, error) {
f, err := os.Open(path)
if errors.Is(err, os.ErrNotExist) {
return map[string]Offset{}, nil
}
if err != nil {
return nil, err
}
defer f.Close()
var snap snapshot
if err := gob.NewDecoder(bufio.NewReaderSize(f, 256*1024)).Decode(&snap); err != nil {
// not a version 2 stream: try the version 1 layout
var v1 snapshotV1
f1, oerr := os.Open(path)
if oerr != nil {
return nil, err
}
defer f1.Close()
if err1 := gob.NewDecoder(bufio.NewReaderSize(f1, 256*1024)).Decode(&v1); err1 != nil || v1.V != 1 {
return nil, err
}
snap = s.migrateV1(&v1)
}
if snap.V != snapshotVersion {
return nil, errors.New("snapshot version mismatch")
}
s.mu.Lock()
s.stamps, s.counts, s.hours = snap.Stamps, snap.Counts, snap.Hours
s.monSt, s.monN = snap.MonSt, snap.MonN
s.ownSt, s.ownN = snap.OwnSt, snap.OwnN
s.tr.dom, s.tr.gdays = snap.Dom, snap.GDays
s.sv.m = snap.Svc
for _, d := range s.tr.dom {
if d != nil && d.Last == 0 {
// snapshot written before Last existed: never prune on the first pass
d.Last = snap.Saved
for _, h := range d.Hours {
if h.Req > 0 && h.Hour*3600 > d.Last {
d.Last = h.Hour * 3600
}
}
}
}
for ip, r := range snap.IPs {
if r == nil {
delete(snap.IPs, ip)
}
}
nowU := s.now().Unix()
for _, r := range snap.IPs {
// records saved before ListedSince existed: the best estimate is the last event
if r.ListedSince == 0 && listedRule(r, nowU) {
r.ListedSince = r.Last
}
// records saved before the day counters existed: spread the totals
// evenly over the days between the first and the last event (an
// estimate; the registry refines it where it has data)
if len(r.DayCats) == 0 {
spreadDays(r)
}
}
if snap.IDSeq > s.ids.Load() {
s.ids.Store(snap.IDSeq)
}
s.ips = snap.IPs
if s.ips == nil {
s.ips = map[string]*IPRec{}
}
// a tampered snapshot must not be able to crash the ring or exceed the caps
if len(snap.Recent) > FeedSize {
snap.Recent = snap.Recent[len(snap.Recent)-FeedSize:]
snap.Rhead = 0
}
if len(snap.Recent) < FeedSize || snap.Rhead < 0 || snap.Rhead >= len(snap.Recent) {
snap.Rhead = 0
}
s.recent, s.rhead = snap.Recent, snap.Rhead
for len(s.ips) > s.cfg.MaxIPs {
s.evictLocked()
}
s.mu.Unlock()
s.invalidate()
if snap.Offsets == nil {
snap.Offsets = map[string]Offset{}
}
return snap.Offsets, nil
}
// EnsureDir creates the directory of a snapshot path.
func EnsureDir(path string) error { return os.MkdirAll(filepath.Dir(path), 0o700) }
// migrateV1 converts a version 1 snapshot without losing data: the minute
// buckets older than the new minute window are folded into hour buckets.
func (s *Store) migrateV1(v *snapshotV1) snapshot {
n := snapshot{V: snapshotVersion, Saved: v.Saved, IPs: v.IPs, Recent: v.Recent, Rhead: v.Rhead, Offsets: v.Offsets}
// hour slots: same hour numbers, now with category counts
for _, h := range v.Hours {
if h.Hour != 0 {
n.Hours[int(h.Hour%hourSlots)] = h
}
}
for i, m := range v.Stamps {
if m == 0 {
continue
}
hr := m / 60
hs := &n.Hours[int(hr%hourSlots)]
if hs.Hour != hr {
*hs = hourSlot{Hour: hr}
}
for c, k := range v.Counts[i] {
hs.C[c] += k
}
j := int(m % slots)
if n.Stamps[j] < m {
n.Stamps[j], n.Counts[j] = m, v.Counts[i]
}
}
for i, m := range v.MonSt {
if m == 0 {
continue
}
hr := m / 60
hs := &n.Hours[int(hr%hourSlots)]
if hs.Hour != hr {
*hs = hourSlot{Hour: hr}
}
hs.Mon += v.MonN[i]
j := int(m % slots)
if n.MonSt[j] < m {
n.MonSt[j], n.MonN[j] = m, v.MonN[i]
}
}
n.Dom = make(map[string]*domData, len(v.Dom))
for name, d := range v.Dom {
if d == nil {
continue
}
nd := &domData{Last: d.Last}
for i, m := range d.MinSt {
if m == 0 {
continue
}
j := int(m % anMinutes)
nd.MinSt[j], nd.MinReq[j], nd.MinPages[j] = m, d.MinReq[i], d.MinPages[i]
}
for _, h := range d.Hours {
if h.Hour != 0 {
nd.Hours[int(h.Hour%hourSlots)] = h
}
}
for _, dd := range d.Days {
if dd.Day != 0 {
nd.Days[int(dd.Day%anDays)] = dd
}
}
n.Dom[name] = nd
}
return n
}
// spreadDays estimates the per-day counters of an old record from its totals.
func spreadDays(r *IPRec) {
var tot uint32
for _, n := range r.Counts {
tot += n
}
if tot == 0 || r.Last == 0 {
return
}
last := r.Last / 86400
nd := int(last - r.First/86400 + 1)
nd = max(1, min(nd, 30))
r.DayBase, r.DayEst, r.Days = last, true, 0
r.DayCats = make([][core.NumCats]uint16, nd)
for c, n := range r.Counts {
base, rem := n/uint32(nd), int(n%uint32(nd))
for k := 0; k < nd; k++ {
v := base
if k < rem {
v++
}
r.DayCats[k][c] = uint16(min(v, 65535))
}
}
for k := 0; k < nd; k++ {
for _, v := range r.DayCats[k] {
if v > 0 {
r.Days |= 1 << uint(k)
break
}
}
}
}