stats

package
v1.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 25, 2026 License: MPL-2.0 Imports: 12 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MinRetentionWeeks     = 1
	DefaultRetentionWeeks = 2
	MaxRetentionWeeks     = 4 // Hard maximum, not overridable
)

Retention constants - hard limits per design agreement

View Source
const SchemaVersion = 2

SchemaVersion is the current JSON schema version Increment when making breaking changes to the JSON structure

Variables

This section is empty.

Functions

func CanCreateProfile

func CanCreateProfile(profileDir string, maxCount int) bool

CanCreateProfile checks if we can create a new profile without exceeding limits

func CleanupHistory

func CleanupHistory(historyDir string, retentionDays int, maxCount int) error

CleanupHistory removes history files older than retention days. Also enforces a maximum file count to prevent unbounded growth.

func CleanupProfiles

func CleanupProfiles(profileDir string, retentionDays int, maxCount int) error

CleanupProfiles removes profile files older than retention days. Also enforces maximum profile count as a HARD LIMIT.

func CleanupReports added in v1.5.0

func CleanupReports(reportsDir string, retentionDays int) error

CleanupReports removes report files older than retention days. Handles both daily/ subdirectory and root report files.

func FileExists

func FileExists(path string) bool

FileExists checks if a file exists

func FileModTime

func FileModTime(path string) (int64, error)

FileModTime returns the modification time of a file Returns zero time if file doesn't exist

func GetProfileCount

func GetProfileCount(profileDir string) int

GetProfileCount returns the number of profile files in the directory

func ReadJSON

func ReadJSON(path string, data interface{}) error

ReadJSON reads a JSON file, tolerating missing/partial files. Returns nil, nil if file doesn't exist (not an error). Returns data, nil on success. Returns nil, error on parse failure.

func WriteJSONAtomic

func WriteJSONAtomic(path string, data interface{}) error

WriteJSONAtomic writes data to a file atomically. Pattern: write to temp file -> fsync -> rename This ensures the file is never partially written.

Types

type Alert

type Alert struct {
	Level     string    `json:"level"` // "warning" or "critical"
	Type      string    `json:"type"`  // "memory", "goroutines", etc.
	Message   string    `json:"message"`
	Timestamp time.Time `json:"timestamp"`
	Value     float64   `json:"value"`
	Threshold float64   `json:"threshold"`
}

Alert represents an active alert

type Collector

type Collector struct {
	// contains filtered or unexported fields
}

Collector gathers and persists runtime statistics

func NewCollector

func NewCollector(config *Config) *Collector

NewCollector creates a new stats collector

func (*Collector) Collect

func (c *Collector) Collect() *Snapshot

Collect gathers current runtime statistics

func (*Collector) GetConfig

func (c *Collector) GetConfig() *Config

GetConfig returns the collector configuration

func (*Collector) RecordBan

func (c *Collector) RecordBan()

RecordBan increments the ban counter

func (*Collector) RecordEvent

func (c *Collector) RecordEvent()

RecordEvent increments the event counter

func (*Collector) RecordIPCRequest

func (c *Collector) RecordIPCRequest(latencyNs int64, success bool)

RecordIPCRequest records an IPC request with latency

func (*Collector) RecordModuleEvent

func (c *Collector) RecordModuleEvent(name string)

RecordModuleEvent increments a module's event counter

func (*Collector) RecordUnban

func (c *Collector) RecordUnban()

RecordUnban increments the unban counter

func (*Collector) SetDaemonMode added in v1.5.0

func (c *Collector) SetDaemonMode(mode string)

SetDaemonMode sets the current daemon operating mode

func (*Collector) SetModuleStatus

func (c *Collector) SetModuleStatus(name, status string)

SetModuleStatus updates module status

func (*Collector) SetServerInfo added in v1.5.0

func (c *Collector) SetServerInfo(hostname, region, os, kernel, arch string)

SetServerInfo sets server inventory information

func (*Collector) SetVersion

func (c *Collector) SetVersion(version string)

SetVersion sets the daemon version in stats

func (*Collector) SetWatchdogState added in v1.5.0

func (c *Collector) SetWatchdogState(status int, mode string, cpuScore, memScore, ioScore float64)

SetWatchdogState sets the current watchdog pressure state

func (*Collector) Start

func (c *Collector) Start(ctx context.Context)

Start begins the stats collection goroutines Returns immediately if stats collection is disabled (no background work)

type Config

type Config struct {
	// Enable stats collection (default: true)
	Enabled bool

	// Collection intervals
	LiveInterval time.Duration // Memory/goroutines (default: 60s)
	IOInterval   time.Duration // Events/throughput (default: 300s)

	// File paths
	CurrentFile string // current.json path
	HistoryDir  string // history/ directory
	ProfileDir  string // profiles/ directory

	// Retention limits
	// Local retention is capped at 4 weeks maximum (28 days)
	// Long-term storage is user's responsibility via external TSDB
	HistoryRetentionDays int // Days to keep history (default: 14, max: 28)
	ProfileRetentionDays int // Days to keep profiles (default: 7)
	ProfileMaxCount      int // Max profiles to keep (default: 10)

	// Thresholds
	MemoryWarnMB      float64 // Warning threshold (default: 200)
	MemoryCritMB      float64 // Critical threshold (default: 500)
	GoroutinesWarn    int     // Warning threshold (default: 100)
	GoroutinesCrit    int     // Critical threshold (default: 500)
	StaleThresholdSec int     // Stale data threshold (default: 300)

	// Profiling
	ProfileEnabled     bool // pprof enabled (default: false)
	ProfileAutoCapture bool // Auto-capture on breach (default: false)

	// Logging
	LogDir     string // Watchdog log directory
	StatsLog   string // Stats log file
	AlertsLog  string // Alerts log file
	ProfileLog string // Profile log file

	// Reports
	ReportsEnabled       bool   // Enable report generation (default: true)
	ReportsDir           string // Reports output directory
	ReportsRetentionDays int    // Days to keep daily reports (default: 14, max: 28)
}

Config holds stats collection configuration All fields have safe defaults for backwards compatibility

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns configuration with safe defaults Used when config keys are missing for backwards compatibility

func (*Config) IsProfileEnabled

func (c *Config) IsProfileEnabled() bool

IsProfileEnabled returns true if profiling is enabled

func (*Config) IsStatsEnabled

func (c *Config) IsStatsEnabled() bool

IsStatsEnabled returns true if stats collection is enabled Used to check before starting any background work

func (*Config) Validate

func (c *Config) Validate()

Validate checks config values and applies safe bounds

type Daemon

type Daemon struct {
	Version       string `json:"version"`
	UptimeSeconds int64  `json:"uptime_seconds"`
	PID           int    `json:"pid"`
	Mode          string `json:"mode"` // "normal", "degraded", "survival"
}

Daemon contains daemon identification info

type DailyStats

type DailyStats struct {
	SchemaVersion int       `json:"schema_version"`
	Date          string    `json:"date"` // YYYY-MM-DD
	GeneratedAt   time.Time `json:"generated_at"`

	// Peak values for the day
	PeakMemoryMB   float64 `json:"peak_memory_mb"`
	PeakGoroutines int     `json:"peak_goroutines"`
	PeakBansPerMin float64 `json:"peak_bans_per_min"`

	// Totals for the day
	TotalBans        int64 `json:"total_bans"`
	TotalUnbans      int64 `json:"total_unbans"`
	TotalEvents      int64 `json:"total_events"`
	TotalIPCRequests int64 `json:"total_ipc_requests"`
	TotalIPCErrors   int64 `json:"total_ipc_errors"`

	// Averages for the day
	AvgMemoryMB   float64 `json:"avg_memory_mb"`
	AvgGoroutines float64 `json:"avg_goroutines"`
	AvgLatencyMs  float64 `json:"avg_latency_ms"`

	// Alert counts
	WarningCount  int `json:"warning_count"`
	CriticalCount int `json:"critical_count"`

	// Sample count (for averaging)
	SampleCount int `json:"sample_count"`
}

DailyStats contains aggregated daily statistics Stored in history/ directory

func NewDailyStats

func NewDailyStats(date string) *DailyStats

NewDailyStats creates a new daily stats struct

type IPC

type IPC struct {
	RequestsTotal int64   `json:"requests_total"`
	AvgLatencyMs  float64 `json:"avg_latency_ms"`
	ErrorsTotal   int64   `json:"errors_total"`
}

IPC contains IPC communication metrics

type ModuleStats

type ModuleStats struct {
	Status     string
	EventCount atomic.Int64
}

ModuleStats tracks per-module statistics

type ModuleStatus

type ModuleStatus struct {
	Status string `json:"status"`
	Events int64  `json:"events"`
}

ModuleStatus contains status for a single module

type ProfileInfo

type ProfileInfo struct {
	Filename    string    `json:"filename"`
	Type        string    `json:"type"` // "heap", "cpu", "goroutine", "block"
	CreatedAt   time.Time `json:"created_at"`
	SizeBytes   int64     `json:"size_bytes"`
	DurationSec int       `json:"duration_sec,omitempty"` // For CPU profiles
}

ProfileInfo contains metadata about a saved profile

type Runtime

type Runtime struct {
	MemoryHeapMB  float64 `json:"memory_heap_mb"`
	MemoryAllocMB float64 `json:"memory_alloc_mb"`
	MemorySysMB   float64 `json:"memory_sys_mb"`
	Goroutines    int     `json:"goroutines"`
	GCCycles      uint32  `json:"gc_cycles"`
	GCPauseMs     float64 `json:"gc_pause_ms"`
}

Runtime contains Go runtime metrics

type Server added in v1.5.0

type Server struct {
	Hostname string `json:"hostname"`
	Region   string `json:"region"` // Cloud region or datacenter
	OS       string `json:"os"`
	Kernel   string `json:"kernel"`
	Arch     string `json:"arch"`
}

Server contains server inventory information

type Snapshot

type Snapshot struct {
	SchemaVersion int                     `json:"schema_version"`
	Timestamp     time.Time               `json:"timestamp"`
	Daemon        Daemon                  `json:"daemon"`
	Runtime       Runtime                 `json:"runtime"`
	Throughput    Throughput              `json:"throughput"`
	IPC           IPC                     `json:"ipc"`
	Watchdog      Watchdog                `json:"watchdog"`
	Server        Server                  `json:"server"`
	Modules       map[string]ModuleStatus `json:"modules"`
	Health        string                  `json:"health"`
	Alerts        []Alert                 `json:"alerts"`
}

Snapshot represents a point-in-time stats snapshot Written to current.json by the daemon

func NewSnapshot

func NewSnapshot() *Snapshot

NewSnapshot creates a new snapshot with schema version set

type Throughput

type Throughput struct {
	BansTotal    int64   `json:"bans_total"`
	UnbansTotal  int64   `json:"unbans_total"`
	EventsTotal  int64   `json:"events_total"`
	BansPerMin   float64 `json:"bans_per_min"`
	EventsPerMin float64 `json:"events_per_min"`
}

Throughput contains event processing metrics

type Watchdog added in v1.5.0

type Watchdog struct {
	Status   int     `json:"status"`    // 1 = running, 0 = not running
	Mode     string  `json:"mode"`      // "normal", "degraded", "survival"
	CPUScore float64 `json:"cpu_score"` // 0-100 pressure score
	MemScore float64 `json:"mem_score"` // 0-100 pressure score
	IOScore  float64 `json:"io_score"`  // 0-100 pressure score
}

Watchdog contains pressure monitoring metrics

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL