334 lines
8.8 KiB
Go
334 lines
8.8 KiB
Go
package store
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"math"
|
|
"os"
|
|
"path/filepath"
|
|
"sync"
|
|
"time"
|
|
|
|
"git.gsdistance.org/tyuXX/RUD/internal/config"
|
|
)
|
|
|
|
const (
|
|
StateUp = "up"
|
|
StateDegraded = "degraded"
|
|
StateDown = "down"
|
|
StatePending = "pending"
|
|
)
|
|
|
|
// CheckResult represents a single check execution outcome stored in the ring buffer.
|
|
type CheckResult struct {
|
|
Timestamp time.Time `json:"timestamp"`
|
|
State string `json:"state"`
|
|
LatencyMs float64 `json:"latency_ms"`
|
|
Code int `json:"code,omitempty"`
|
|
Message string `json:"message,omitempty"`
|
|
}
|
|
|
|
// MonitorState holds the live and historical state for a single monitor.
|
|
type MonitorState struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Description string `json:"description,omitempty"`
|
|
Link string `json:"link,omitempty"`
|
|
Method string `json:"method"`
|
|
Target string `json:"target,omitempty"`
|
|
State string `json:"state"`
|
|
StateChangedAt time.Time `json:"state_changed_at"`
|
|
LastCheckedAt time.Time `json:"last_checked_at"`
|
|
LatencyMs float64 `json:"latency_ms"`
|
|
AvgLatencyMs float64 `json:"avg_latency_ms"`
|
|
UptimePct float64 `json:"uptime_pct"`
|
|
TotalChecks int64 `json:"total_checks"`
|
|
SuccessfulChecks int64 `json:"successful_checks"`
|
|
ConsecutiveFailures int `json:"consecutive_failures"`
|
|
ConsecutiveSuccesses int `json:"consecutive_successes"`
|
|
LastMessage string `json:"last_message,omitempty"`
|
|
History []CheckResult `json:"history"`
|
|
}
|
|
|
|
// StatusCounts summarizes how many monitors are in each state.
|
|
type StatusCounts struct {
|
|
Total int `json:"total"`
|
|
Up int `json:"up"`
|
|
Degraded int `json:"degraded"`
|
|
Down int `json:"down"`
|
|
Pending int `json:"pending"`
|
|
}
|
|
|
|
// Snapshot is an immutable point-in-time view of all monitors and aggregate metrics.
|
|
type Snapshot struct {
|
|
OverallState string `json:"status"`
|
|
OverallUptimePct float64 `json:"overall_uptime_pct"`
|
|
AvgLatencyMs float64 `json:"avg_latency_ms"`
|
|
Counts StatusCounts `json:"counts"`
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
Monitors []MonitorState `json:"monitors"`
|
|
MonitorsByID map[string]MonitorState `json:"-"`
|
|
}
|
|
|
|
// Store manages the thread-safe ring buffer and state for all configured monitors.
|
|
type Store struct {
|
|
mu sync.RWMutex
|
|
historySize int
|
|
persistenceFile string
|
|
order []string
|
|
monitors map[string]*MonitorState
|
|
}
|
|
|
|
// New creates a new Store initialized with the configured monitors.
|
|
func New(cfg *config.Config) *Store {
|
|
histSize := cfg.Storage.HistorySize
|
|
if histSize <= 0 {
|
|
histSize = 60
|
|
}
|
|
s := &Store{
|
|
historySize: histSize,
|
|
persistenceFile: cfg.Storage.PersistenceFile,
|
|
order: make([]string, 0, len(cfg.Monitors)),
|
|
monitors: make(map[string]*MonitorState, len(cfg.Monitors)),
|
|
}
|
|
now := time.Now().UTC()
|
|
for _, m := range cfg.Monitors {
|
|
s.order = append(s.order, m.ID)
|
|
s.monitors[m.ID] = &MonitorState{
|
|
ID: m.ID,
|
|
Name: m.Name,
|
|
Description: m.Description,
|
|
Link: m.Link,
|
|
Method: m.Method,
|
|
Target: m.DisplayTarget(),
|
|
State: StatePending,
|
|
StateChangedAt: now,
|
|
UptimePct: 100.0,
|
|
History: make([]CheckResult, 0, histSize),
|
|
}
|
|
}
|
|
return s
|
|
}
|
|
|
|
// Record appends a new check result for monitorID and recalculates its statistics.
|
|
func (s *Store) Record(monitorID string, res CheckResult) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
m, ok := s.monitors[monitorID]
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
if res.Timestamp.IsZero() {
|
|
res.Timestamp = time.Now().UTC()
|
|
}
|
|
res.LatencyMs = round2(res.LatencyMs)
|
|
|
|
prevState := m.State
|
|
m.State = res.State
|
|
if prevState != res.State || m.StateChangedAt.IsZero() {
|
|
m.StateChangedAt = res.Timestamp
|
|
}
|
|
|
|
m.LastCheckedAt = res.Timestamp
|
|
m.LatencyMs = res.LatencyMs
|
|
m.LastMessage = res.Message
|
|
m.TotalChecks++
|
|
|
|
if res.State == StateUp || res.State == StateDegraded {
|
|
m.SuccessfulChecks++
|
|
m.ConsecutiveSuccesses++
|
|
m.ConsecutiveFailures = 0
|
|
} else if res.State == StateDown {
|
|
m.ConsecutiveFailures++
|
|
m.ConsecutiveSuccesses = 0
|
|
}
|
|
|
|
// Append to ring buffer
|
|
if len(m.History) >= s.historySize {
|
|
copy(m.History, m.History[1:])
|
|
m.History[len(m.History)-1] = res
|
|
} else {
|
|
m.History = append(m.History, res)
|
|
}
|
|
|
|
// Calculate uptime percentage and average latency across history/total checks
|
|
if m.TotalChecks > 0 {
|
|
m.UptimePct = round2((float64(m.SuccessfulChecks) / float64(m.TotalChecks)) * 100.0)
|
|
}
|
|
var latSum float64
|
|
var latCount int
|
|
for _, h := range m.History {
|
|
if h.LatencyMs >= 0 {
|
|
latSum += h.LatencyMs
|
|
latCount++
|
|
}
|
|
}
|
|
if latCount > 0 {
|
|
m.AvgLatencyMs = round2(latSum / float64(latCount))
|
|
}
|
|
}
|
|
|
|
// Snapshot returns a deep copy of current monitor states and aggregate metrics.
|
|
func (s *Store) Snapshot() Snapshot {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
|
|
snap := Snapshot{
|
|
OverallState: StateUp,
|
|
OverallUptimePct: 100.0,
|
|
UpdatedAt: time.Now().UTC(),
|
|
Monitors: make([]MonitorState, 0, len(s.order)),
|
|
MonitorsByID: make(map[string]MonitorState, len(s.order)),
|
|
}
|
|
|
|
var uptimeSum float64
|
|
var uptimeCount int
|
|
var latSum float64
|
|
var latCount int
|
|
|
|
for _, id := range s.order {
|
|
m, ok := s.monitors[id]
|
|
if !ok {
|
|
continue
|
|
}
|
|
cp := *m
|
|
cp.History = make([]CheckResult, len(m.History))
|
|
copy(cp.History, m.History)
|
|
|
|
snap.Monitors = append(snap.Monitors, cp)
|
|
snap.MonitorsByID[id] = cp
|
|
snap.Counts.Total++
|
|
|
|
switch cp.State {
|
|
case StateUp:
|
|
snap.Counts.Up++
|
|
case StateDegraded:
|
|
snap.Counts.Degraded++
|
|
case StateDown:
|
|
snap.Counts.Down++
|
|
default:
|
|
snap.Counts.Pending++
|
|
}
|
|
|
|
if cp.TotalChecks > 0 {
|
|
uptimeSum += cp.UptimePct
|
|
uptimeCount++
|
|
latSum += cp.LatencyMs
|
|
latCount++
|
|
}
|
|
}
|
|
|
|
if snap.Counts.Total == 0 || snap.Counts.Pending == snap.Counts.Total {
|
|
snap.OverallState = StatePending
|
|
} else if snap.Counts.Down > 0 {
|
|
snap.OverallState = StateDown
|
|
} else if snap.Counts.Degraded > 0 {
|
|
snap.OverallState = StateDegraded
|
|
} else {
|
|
snap.OverallState = StateUp
|
|
}
|
|
|
|
if uptimeCount > 0 {
|
|
snap.OverallUptimePct = round2(uptimeSum / float64(uptimeCount))
|
|
}
|
|
if latCount > 0 {
|
|
snap.AvgLatencyMs = round2(latSum / float64(latCount))
|
|
}
|
|
|
|
return snap
|
|
}
|
|
|
|
type persistedState struct {
|
|
SavedAt time.Time `json:"saved_at"`
|
|
Monitors map[string]*MonitorState `json:"monitors"`
|
|
}
|
|
|
|
// LoadFromDisk restores monitor history and counters from the configured persistence file if it exists.
|
|
func (s *Store) LoadFromDisk() error {
|
|
if s.persistenceFile == "" {
|
|
return nil
|
|
}
|
|
data, err := os.ReadFile(s.persistenceFile)
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("read persistence file %s: %w", s.persistenceFile, err)
|
|
}
|
|
|
|
var ps persistedState
|
|
if err := json.Unmarshal(data, &ps); err != nil {
|
|
return fmt.Errorf("parse persistence file %s: %w", s.persistenceFile, err)
|
|
}
|
|
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
for id, saved := range ps.Monitors {
|
|
curr, ok := s.monitors[id]
|
|
if !ok || saved == nil {
|
|
continue
|
|
}
|
|
curr.State = saved.State
|
|
curr.StateChangedAt = saved.StateChangedAt
|
|
curr.LastCheckedAt = saved.LastCheckedAt
|
|
curr.LatencyMs = saved.LatencyMs
|
|
curr.AvgLatencyMs = saved.AvgLatencyMs
|
|
curr.UptimePct = saved.UptimePct
|
|
curr.TotalChecks = saved.TotalChecks
|
|
curr.SuccessfulChecks = saved.SuccessfulChecks
|
|
curr.ConsecutiveFailures = saved.ConsecutiveFailures
|
|
curr.ConsecutiveSuccesses = saved.ConsecutiveSuccesses
|
|
curr.LastMessage = saved.LastMessage
|
|
|
|
if len(saved.History) > s.historySize {
|
|
curr.History = append([]CheckResult(nil), saved.History[len(saved.History)-s.historySize:]...)
|
|
} else {
|
|
curr.History = append([]CheckResult(nil), saved.History...)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// SaveToDisk atomically writes current monitor states and history to the configured persistence file.
|
|
func (s *Store) SaveToDisk() error {
|
|
if s.persistenceFile == "" {
|
|
return nil
|
|
}
|
|
|
|
s.mu.RLock()
|
|
ps := persistedState{
|
|
SavedAt: time.Now().UTC(),
|
|
Monitors: make(map[string]*MonitorState, len(s.monitors)),
|
|
}
|
|
for id, m := range s.monitors {
|
|
cp := *m
|
|
cp.History = append([]CheckResult(nil), m.History...)
|
|
ps.Monitors[id] = &cp
|
|
}
|
|
s.mu.RUnlock()
|
|
|
|
data, err := json.MarshalIndent(ps, "", " ")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
dir := filepath.Dir(s.persistenceFile)
|
|
if dir != "" && dir != "." {
|
|
if err := os.MkdirAll(dir, 0755); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
tmpFile := s.persistenceFile + ".tmp"
|
|
if err := os.WriteFile(tmpFile, data, 0644); err != nil {
|
|
return err
|
|
}
|
|
return os.Rename(tmpFile, s.persistenceFile)
|
|
}
|
|
|
|
func round2(v float64) float64 {
|
|
return math.Round(v*100) / 100
|
|
}
|