stats

package
v1.0.27 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const SchemaVersion = 1

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 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) SetModuleStatus

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

SetModuleStatus updates module status

func (*Collector) SetVersion

func (c *Collector) SetVersion(version string)

SetVersion sets the daemon version in stats

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 (HARD LIMITS)
	HistoryRetentionDays int // Days to keep history (default: 30)
	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
}

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"`
}

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 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"`
	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

Jump to

Keyboard shortcuts

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