Update
This commit is contained in:
parent
d37503c863
commit
1509789cde
19 changed files with 1534 additions and 112 deletions
229
internal/history/logger.go
Normal file
229
internal/history/logger.go
Normal file
|
|
@ -0,0 +1,229 @@
|
|||
// Package history provides long-term storage for check results: an append-only
|
||||
// daily JSONL log that is zstd-compressed when the day rolls over, and a SQLite
|
||||
// database of hourly aggregate statistics with configurable retention.
|
||||
package history
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/klauspost/compress/zstd"
|
||||
|
||||
"git.gsdistance.org/tyuXX/RUD/internal/store"
|
||||
)
|
||||
|
||||
// dayFileLayout is the DD-MM-YYYY filename layout used for daily log files.
|
||||
const dayFileLayout = "02-01-2006"
|
||||
|
||||
// MonitorMeta carries optional display metadata written alongside each log entry.
|
||||
type MonitorMeta struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
Method string `json:"method,omitempty"`
|
||||
Target string `json:"target,omitempty"`
|
||||
}
|
||||
|
||||
// Entry is a single check result as written to the daily JSONL log. The
|
||||
// CheckResult fields are flattened into the top-level object.
|
||||
type Entry struct {
|
||||
MonitorID string `json:"monitor_id"`
|
||||
MonitorMeta
|
||||
store.CheckResult
|
||||
}
|
||||
|
||||
// DailyLogger appends every check result to a per-day JSON Lines file named
|
||||
// DD-MM-YYYY.json inside Dir. When the calendar day changes the previous file
|
||||
// is flushed, compressed to DD-MM-YYYY.json.zst and removed. Stale uncompressed
|
||||
// files left behind by a crash are compressed on startup.
|
||||
type DailyLogger struct {
|
||||
dir string
|
||||
metaFor func(id string) MonitorMeta
|
||||
now func() time.Time
|
||||
|
||||
mu sync.Mutex
|
||||
file *os.File
|
||||
w *bufio.Writer
|
||||
curDay string
|
||||
encoder *json.Encoder
|
||||
}
|
||||
|
||||
// NewDailyLogger creates the log directory, compresses any stale uncompressed
|
||||
// daily files from previous days, and opens (or creates) today's log file.
|
||||
// metaFor may be nil, in which case entries contain only monitor_id and the
|
||||
// check result fields.
|
||||
func NewDailyLogger(dir string, metaFor func(id string) MonitorMeta) (*DailyLogger, error) {
|
||||
if dir == "" {
|
||||
return nil, fmt.Errorf("history log directory is empty")
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
return nil, fmt.Errorf("create history log dir %s: %w", dir, err)
|
||||
}
|
||||
l := &DailyLogger{
|
||||
dir: dir,
|
||||
metaFor: metaFor,
|
||||
now: time.Now,
|
||||
}
|
||||
if err := l.compressStale(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := l.openToday(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return l, nil
|
||||
}
|
||||
|
||||
// Record appends one check result to the current day's log, rotating to a new
|
||||
// file (and compressing the old one) when the day has changed.
|
||||
func (l *DailyLogger) Record(monitorID string, res store.CheckResult) error {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
|
||||
day := l.now().Format(dayFileLayout)
|
||||
if day != l.curDay {
|
||||
if err := l.rotateLocked(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
entry := Entry{MonitorID: monitorID, CheckResult: res}
|
||||
if l.metaFor != nil {
|
||||
entry.MonitorMeta = l.metaFor(monitorID)
|
||||
}
|
||||
if err := l.encoder.Encode(entry); err != nil {
|
||||
return fmt.Errorf("encode history entry: %w", err)
|
||||
}
|
||||
return l.w.Flush()
|
||||
}
|
||||
|
||||
// Close flushes and closes the current log file without compressing it. The
|
||||
// file is compressed on the next startup by compressStale.
|
||||
func (l *DailyLogger) Close() error {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return l.closeLocked()
|
||||
}
|
||||
|
||||
func (l *DailyLogger) openToday() error {
|
||||
day := l.now().Format(dayFileLayout)
|
||||
path := filepath.Join(l.dir, day+".json")
|
||||
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open history log %s: %w", path, err)
|
||||
}
|
||||
l.file = f
|
||||
l.w = bufio.NewWriter(f)
|
||||
l.encoder = json.NewEncoder(l.w)
|
||||
l.curDay = day
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *DailyLogger) closeLocked() error {
|
||||
if l.file == nil {
|
||||
return nil
|
||||
}
|
||||
err := l.w.Flush()
|
||||
if cerr := l.file.Close(); err == nil {
|
||||
err = cerr
|
||||
}
|
||||
l.file = nil
|
||||
l.w = nil
|
||||
l.encoder = nil
|
||||
return err
|
||||
}
|
||||
|
||||
// rotateLocked compresses the current day's file and opens the new day's file.
|
||||
// Caller must hold l.mu.
|
||||
func (l *DailyLogger) rotateLocked() error {
|
||||
day := l.curDay
|
||||
if err := l.closeLocked(); err != nil {
|
||||
return err
|
||||
}
|
||||
if day != "" {
|
||||
if err := compressFile(filepath.Join(l.dir, day+".json")); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return l.openToday()
|
||||
}
|
||||
|
||||
// compressStale compresses every DD-MM-YYYY.json file whose date is not today.
|
||||
func (l *DailyLogger) compressStale() error {
|
||||
today := l.now().Format(dayFileLayout)
|
||||
entries, err := os.ReadDir(l.dir)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read history log dir %s: %w", l.dir, err)
|
||||
}
|
||||
// Compress oldest first for deterministic behaviour.
|
||||
names := make([]string, 0, len(entries))
|
||||
for _, e := range entries {
|
||||
if !e.IsDir() && strings.HasSuffix(e.Name(), ".json") {
|
||||
names = append(names, e.Name())
|
||||
}
|
||||
}
|
||||
sort.Strings(names)
|
||||
for _, name := range names {
|
||||
day := strings.TrimSuffix(name, ".json")
|
||||
if _, err := time.Parse(dayFileLayout, day); err != nil {
|
||||
continue // not a daily log file; leave it alone
|
||||
}
|
||||
if day == today {
|
||||
continue
|
||||
}
|
||||
if err := compressFile(filepath.Join(l.dir, name)); err != nil {
|
||||
log.Printf("history: failed to compress stale log %s: %v", name, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// compressFile zstd-compresses path to path+".zst" and removes the original.
|
||||
// Files that fail to compress are left in place.
|
||||
func compressFile(path string) error {
|
||||
in, err := os.Open(path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
defer in.Close()
|
||||
|
||||
tmp := path + ".zst.tmp"
|
||||
out, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
enc, err := zstd.NewWriter(out)
|
||||
if err != nil {
|
||||
out.Close()
|
||||
return err
|
||||
}
|
||||
if _, err := io.Copy(enc, in); err != nil {
|
||||
enc.Close()
|
||||
out.Close()
|
||||
os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
if err := enc.Close(); err != nil {
|
||||
out.Close()
|
||||
os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
if err := out.Close(); err != nil {
|
||||
os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(tmp, path+".zst"); err != nil {
|
||||
os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
return os.Remove(path)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue