Init
This commit is contained in:
parent
c823102a63
commit
d37503c863
20 changed files with 4433 additions and 3 deletions
790
internal/config/config.go
Normal file
790
internal/config/config.go
Normal file
|
|
@ -0,0 +1,790 @@
|
|||
package config
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Duration wraps time.Duration so zero values are omitted by json:",omitempty"
|
||||
// while non-zero values serialize as clean human-readable strings ("15s", "5m", "5h").
|
||||
type Duration time.Duration
|
||||
|
||||
func NewDuration(d time.Duration) Duration {
|
||||
return Duration(d)
|
||||
}
|
||||
|
||||
func (d Duration) Std() time.Duration {
|
||||
return time.Duration(d)
|
||||
}
|
||||
|
||||
func (d Duration) MarshalJSON() ([]byte, error) {
|
||||
s := time.Duration(d).String()
|
||||
if strings.HasSuffix(s, "m0s") {
|
||||
s = strings.TrimSuffix(s, "0s")
|
||||
}
|
||||
if strings.HasSuffix(s, "h0m") {
|
||||
s = strings.TrimSuffix(s, "0m")
|
||||
}
|
||||
return json.Marshal(s)
|
||||
}
|
||||
|
||||
func (d *Duration) UnmarshalJSON(b []byte) error {
|
||||
var v any
|
||||
if err := json.Unmarshal(b, &v); err != nil {
|
||||
return err
|
||||
}
|
||||
switch val := v.(type) {
|
||||
case string:
|
||||
if val == "" {
|
||||
*d = 0
|
||||
return nil
|
||||
}
|
||||
parsed, err := time.ParseDuration(val)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid duration %q: %w", val, err)
|
||||
}
|
||||
*d = Duration(parsed)
|
||||
return nil
|
||||
case float64:
|
||||
*d = Duration(time.Duration(val) * time.Millisecond)
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("invalid duration type %T", v)
|
||||
}
|
||||
}
|
||||
|
||||
// Config represents the top-level rud.json configuration file.
|
||||
type Config struct {
|
||||
Server ServerConfig `json:"server"`
|
||||
Storage StorageConfig `json:"storage"`
|
||||
Defaults DefaultsConfig `json:"defaults"`
|
||||
Monitors []MonitorConfig `json:"monitors"`
|
||||
Events []EventConfig `json:"events,omitempty"`
|
||||
Page PageConfig `json:"page"`
|
||||
}
|
||||
|
||||
// ServerConfig configures the single HTTP endpoint server.
|
||||
type ServerConfig struct {
|
||||
Listen string `json:"listen"`
|
||||
Endpoint string `json:"endpoint"`
|
||||
RefreshInterval Duration `json:"refresh_interval"`
|
||||
StatusCodes EndpointStatusCodes `json:"status_codes"`
|
||||
}
|
||||
|
||||
type EndpointStatusCodes struct {
|
||||
HTML StatusCodesByState `json:"html"`
|
||||
JSON StatusCodesByState `json:"json"`
|
||||
}
|
||||
|
||||
type StatusCodesByState struct {
|
||||
Up int `json:"up"`
|
||||
Degraded int `json:"degraded"`
|
||||
Down int `json:"down"`
|
||||
Pending int `json:"pending"`
|
||||
}
|
||||
|
||||
// StorageConfig configures the in-memory ring buffer and optional disk persistence.
|
||||
type StorageConfig struct {
|
||||
HistorySize int `json:"history_size"`
|
||||
PersistenceFile string `json:"persistence_file,omitempty"`
|
||||
SaveInterval Duration `json:"save_interval,omitempty"`
|
||||
}
|
||||
|
||||
// DefaultsConfig provides global fallback check intervals and thresholds.
|
||||
type DefaultsConfig struct {
|
||||
Interval Duration `json:"interval"`
|
||||
Timeout Duration `json:"timeout"`
|
||||
Retries int `json:"retries"`
|
||||
DegradedLatency Duration `json:"degraded_latency"`
|
||||
}
|
||||
|
||||
// MonitorConfig defines an individual health/uptime check.
|
||||
type MonitorConfig struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Link string `json:"link,omitempty"`
|
||||
Method string `json:"method"` // "http", "https", "tcp", "ping", "dns", "cmd"
|
||||
Interval Duration `json:"interval,omitempty"`
|
||||
Timeout Duration `json:"timeout,omitempty"`
|
||||
Retries *int `json:"retries,omitempty"`
|
||||
DegradedLatency Duration `json:"degraded_latency,omitempty"`
|
||||
|
||||
// HTTP / HTTPS options
|
||||
URL string `json:"url,omitempty"`
|
||||
HTTPMethod string `json:"http_method,omitempty"`
|
||||
ExpectedStatus []int `json:"expected_status,omitempty"`
|
||||
Headers map[string]string `json:"headers,omitempty"`
|
||||
Body string `json:"body,omitempty"`
|
||||
BodyRegex string `json:"body_regex,omitempty"`
|
||||
InsecureSkipVerify bool `json:"insecure_skip_verify,omitempty"`
|
||||
|
||||
// TCP options
|
||||
Target string `json:"target,omitempty"` // host:port
|
||||
|
||||
// Ping & DNS options
|
||||
Host string `json:"host,omitempty"`
|
||||
Count int `json:"count,omitempty"` // ping packet count
|
||||
Privileged bool `json:"privileged,omitempty"` // raw ICMP socket toggle
|
||||
RecordType string `json:"record_type,omitempty"` // A, AAAA, CNAME, MX, TXT, NS
|
||||
Resolver string `json:"resolver,omitempty"` // custom DNS server ip:port
|
||||
ExpectedRegex string `json:"expected_regex,omitempty"` // regex for DNS record validation
|
||||
|
||||
// Command / Script options
|
||||
Command string `json:"command,omitempty"`
|
||||
Args []string `json:"args,omitempty"`
|
||||
Shell bool `json:"shell,omitempty"`
|
||||
WorkingDir string `json:"working_dir,omitempty"`
|
||||
Env map[string]string `json:"env,omitempty"`
|
||||
ExpectedExitCode *int `json:"expected_exit_code,omitempty"`
|
||||
OutputRegex string `json:"output_regex,omitempty"`
|
||||
}
|
||||
|
||||
// EffectiveInterval returns the monitor's interval or the global default.
|
||||
func (m MonitorConfig) EffectiveInterval(def DefaultsConfig) time.Duration {
|
||||
if m.Interval > 0 {
|
||||
return m.Interval.Std()
|
||||
}
|
||||
if def.Interval > 0 {
|
||||
return def.Interval.Std()
|
||||
}
|
||||
return 30 * time.Second
|
||||
}
|
||||
|
||||
// EffectiveTimeout returns the monitor's timeout or the global default.
|
||||
func (m MonitorConfig) EffectiveTimeout(def DefaultsConfig) time.Duration {
|
||||
if m.Timeout > 0 {
|
||||
return m.Timeout.Std()
|
||||
}
|
||||
if def.Timeout > 0 {
|
||||
return def.Timeout.Std()
|
||||
}
|
||||
return 5 * time.Second
|
||||
}
|
||||
|
||||
// EffectiveRetries returns the monitor's retry count or the global default.
|
||||
func (m MonitorConfig) EffectiveRetries(def DefaultsConfig) int {
|
||||
if m.Retries != nil {
|
||||
return *m.Retries
|
||||
}
|
||||
return def.Retries
|
||||
}
|
||||
|
||||
// EffectiveDegradedLatency returns the monitor's degraded latency threshold or the global default.
|
||||
func (m MonitorConfig) EffectiveDegradedLatency(def DefaultsConfig) time.Duration {
|
||||
if m.DegradedLatency > 0 {
|
||||
return m.DegradedLatency.Std()
|
||||
}
|
||||
return def.DegradedLatency.Std()
|
||||
}
|
||||
|
||||
// DisplayTarget returns a human-readable target summary for optional display.
|
||||
func (m MonitorConfig) DisplayTarget() string {
|
||||
switch strings.ToLower(m.Method) {
|
||||
case "http", "https":
|
||||
return m.URL
|
||||
case "tcp":
|
||||
if m.Target != "" {
|
||||
return m.Target
|
||||
}
|
||||
return m.Host
|
||||
case "ping":
|
||||
return m.Host
|
||||
case "dns":
|
||||
rec := m.RecordType
|
||||
if rec == "" {
|
||||
rec = "A"
|
||||
}
|
||||
return fmt.Sprintf("%s (%s)", m.Host, strings.ToUpper(rec))
|
||||
case "cmd", "script", "command":
|
||||
if len(m.Args) > 0 {
|
||||
return m.Command + " " + strings.Join(m.Args, " ")
|
||||
}
|
||||
return m.Command
|
||||
default:
|
||||
return m.Target
|
||||
}
|
||||
}
|
||||
|
||||
// EventConfig defines a declarative alert/event rule and its actions.
|
||||
type EventConfig struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Cooldown Duration `json:"cooldown,omitempty"`
|
||||
TriggerOnRecovery bool `json:"trigger_on_recovery,omitempty"`
|
||||
Condition EventCondition `json:"condition"`
|
||||
Actions []EventAction `json:"actions"`
|
||||
RecoveryActions []EventAction `json:"recovery_actions,omitempty"`
|
||||
}
|
||||
|
||||
// EventCondition supports boolean combinators ("and"/"or"), monitor state checks, and metric threshold checks.
|
||||
type EventCondition struct {
|
||||
// Composite condition fields
|
||||
Operator string `json:"operator,omitempty"` // "and", "or"
|
||||
Conditions []EventCondition `json:"conditions,omitempty"`
|
||||
|
||||
// Leaf condition fields
|
||||
Type string `json:"type,omitempty"` // "state" or "metric" (auto-detected if omitted)
|
||||
Monitors []string `json:"monitors,omitempty"` // monitor IDs or ["*"]
|
||||
Match string `json:"match,omitempty"` // "all" (default) or "any"
|
||||
State string `json:"state,omitempty"` // "down", "degraded", "up"
|
||||
Metric string `json:"metric,omitempty"` // "uptime_pct", "latency_ms", "consecutive_failures"
|
||||
Comparator string `json:"comparator,omitempty"` // "<", "<=", ">", ">=", "==", "!="
|
||||
Value float64 `json:"value,omitempty"` // numeric threshold for metric triggers
|
||||
For Duration `json:"for,omitempty"` // sustained duration requirement (e.g. "5h")
|
||||
}
|
||||
|
||||
// EventAction defines an outbound webhook or command execution when an event triggers.
|
||||
type EventAction struct {
|
||||
Type string `json:"type"` // "webhook" or "command"
|
||||
Timeout Duration `json:"timeout,omitempty"`
|
||||
|
||||
// Webhook fields
|
||||
URL string `json:"url,omitempty"`
|
||||
HTTPMethod string `json:"http_method,omitempty"`
|
||||
Headers map[string]string `json:"headers,omitempty"`
|
||||
BodyTemplate string `json:"body_template,omitempty"`
|
||||
|
||||
// Command fields
|
||||
Command string `json:"command,omitempty"`
|
||||
Args []string `json:"args,omitempty"`
|
||||
Shell bool `json:"shell,omitempty"`
|
||||
WorkingDir string `json:"working_dir,omitempty"`
|
||||
Env map[string]string `json:"env,omitempty"`
|
||||
}
|
||||
|
||||
// PageConfig defines the styling and explicit list of elements to render on the status page.
|
||||
type PageConfig struct {
|
||||
Title string `json:"title"`
|
||||
Theme ThemeConfig `json:"theme"`
|
||||
Elements []PageElement `json:"elements"`
|
||||
}
|
||||
|
||||
// ThemeConfig defines minimal, clean visual styling parameters.
|
||||
type ThemeConfig struct {
|
||||
BgColor string `json:"bg_color,omitempty"`
|
||||
CardBgColor string `json:"card_bg_color,omitempty"`
|
||||
TextColor string `json:"text_color,omitempty"`
|
||||
MutedTextColor string `json:"muted_text_color,omitempty"`
|
||||
BorderColor string `json:"border_color,omitempty"`
|
||||
AccentColor string `json:"accent_color,omitempty"`
|
||||
UpColor string `json:"up_color,omitempty"`
|
||||
DegradedColor string `json:"degraded_color,omitempty"`
|
||||
DownColor string `json:"down_color,omitempty"`
|
||||
PendingColor string `json:"pending_color,omitempty"`
|
||||
FontFamily string `json:"font_family,omitempty"`
|
||||
MaxWidth string `json:"max_width,omitempty"`
|
||||
BorderRadius string `json:"border_radius,omitempty"`
|
||||
CustomCSS string `json:"custom_css,omitempty"`
|
||||
}
|
||||
|
||||
// PageElement represents a single configurable block rendered on the web status page.
|
||||
type PageElement struct {
|
||||
Type string `json:"type"` // "header", "status_banner", "summary_cards", "monitor_group", "custom_block", "divider"
|
||||
|
||||
// Common fields
|
||||
Title string `json:"title,omitempty"`
|
||||
Subtitle string `json:"subtitle,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
|
||||
// Header fields
|
||||
Align string `json:"align,omitempty"` // "left", "center", "split"
|
||||
ShowLastUpdated bool `json:"show_last_updated,omitempty"`
|
||||
ShowLiveIndicator bool `json:"show_live_indicator,omitempty"`
|
||||
|
||||
// Status banner fields
|
||||
Messages map[string]string `json:"messages,omitempty"` // keys: "up", "degraded", "down", "pending"
|
||||
ShowOverallUptime bool `json:"show_overall_uptime,omitempty"`
|
||||
ShowCounts bool `json:"show_counts,omitempty"`
|
||||
|
||||
// Summary cards fields
|
||||
Metrics []string `json:"metrics,omitempty"` // "total", "up", "degraded", "down", "overall_uptime", "avg_latency"
|
||||
|
||||
// Monitor group fields
|
||||
Monitors []string `json:"monitors,omitempty"` // monitor IDs or ["*"]
|
||||
Layout string `json:"layout,omitempty"` // "list", "grid", "compact"
|
||||
Display *MonitorDisplayConfig `json:"display,omitempty"`
|
||||
|
||||
// Custom block fields
|
||||
Content string `json:"content,omitempty"`
|
||||
Style string `json:"style,omitempty"` // "neutral", "info", "warning", "danger"
|
||||
}
|
||||
|
||||
// MonitorDisplayConfig controls which data points and bars are rendered for monitors in a group.
|
||||
type MonitorDisplayConfig struct {
|
||||
ShowBar *bool `json:"show_bar,omitempty"`
|
||||
BarTicks int `json:"bar_ticks,omitempty"`
|
||||
ShowUptime *bool `json:"show_uptime,omitempty"`
|
||||
ShowLatency *bool `json:"show_latency,omitempty"`
|
||||
ShowStatusBadge *bool `json:"show_status_badge,omitempty"`
|
||||
ShowMethod *bool `json:"show_method,omitempty"`
|
||||
ShowTarget *bool `json:"show_target,omitempty"`
|
||||
ShowDescription *bool `json:"show_description,omitempty"`
|
||||
ShowMessage *bool `json:"show_message,omitempty"`
|
||||
ShowLastChecked *bool `json:"show_last_checked,omitempty"`
|
||||
CustomLabels map[string]string `json:"custom_labels,omitempty"`
|
||||
}
|
||||
|
||||
func BoolPtr(v bool) *bool {
|
||||
return &v
|
||||
}
|
||||
|
||||
func IntPtr(v int) *int {
|
||||
return &v
|
||||
}
|
||||
|
||||
// DefaultConfig returns a clean, minimal, ready-to-run default configuration.
|
||||
func DefaultConfig() Config {
|
||||
return Config{
|
||||
Server: ServerConfig{
|
||||
Listen: ":8080",
|
||||
Endpoint: "/",
|
||||
RefreshInterval: NewDuration(10 * time.Second),
|
||||
StatusCodes: EndpointStatusCodes{
|
||||
HTML: StatusCodesByState{
|
||||
Up: 200,
|
||||
Degraded: 200,
|
||||
Down: 200,
|
||||
Pending: 200,
|
||||
},
|
||||
JSON: StatusCodesByState{
|
||||
Up: 200,
|
||||
Degraded: 200,
|
||||
Down: 503,
|
||||
Pending: 200,
|
||||
},
|
||||
},
|
||||
},
|
||||
Storage: StorageConfig{
|
||||
HistorySize: 60,
|
||||
PersistenceFile: "",
|
||||
SaveInterval: NewDuration(1 * time.Minute),
|
||||
},
|
||||
Defaults: DefaultsConfig{
|
||||
Interval: NewDuration(15 * time.Second),
|
||||
Timeout: NewDuration(5 * time.Second),
|
||||
Retries: 1,
|
||||
DegradedLatency: NewDuration(750 * time.Millisecond),
|
||||
},
|
||||
Monitors: []MonitorConfig{
|
||||
{
|
||||
ID: "rud-http",
|
||||
Name: "RUD Status Endpoint",
|
||||
Description: "Local HTTP health check",
|
||||
Method: "http",
|
||||
URL: "http://127.0.0.1:8080/?format=json",
|
||||
HTTPMethod: "GET",
|
||||
ExpectedStatus: []int{200, 503},
|
||||
BodyRegex: `"status"`,
|
||||
},
|
||||
{
|
||||
ID: "rud-tcp",
|
||||
Name: "Local TCP Listener",
|
||||
Description: "TCP socket handshake on port 8080",
|
||||
Method: "tcp",
|
||||
Target: "127.0.0.1:8080",
|
||||
},
|
||||
{
|
||||
ID: "local-ping",
|
||||
Name: "Loopback ICMP Ping",
|
||||
Description: "Direct ping reachability check",
|
||||
Method: "ping",
|
||||
Host: "127.0.0.1",
|
||||
Count: 1,
|
||||
},
|
||||
{
|
||||
ID: "local-dns",
|
||||
Name: "Localhost DNS Resolution",
|
||||
Description: "Verifies A record resolution for localhost",
|
||||
Method: "dns",
|
||||
Host: "localhost",
|
||||
RecordType: "A",
|
||||
ExpectedRegex: `^127\.`,
|
||||
},
|
||||
{
|
||||
ID: "host-cmd",
|
||||
Name: "System Shell Check",
|
||||
Description: "Custom command check verifying shell responsiveness",
|
||||
Method: "cmd",
|
||||
Command: "echo ok",
|
||||
Shell: true,
|
||||
ExpectedExitCode: IntPtr(0),
|
||||
OutputRegex: `^ok`,
|
||||
},
|
||||
},
|
||||
Events: []EventConfig{
|
||||
{
|
||||
ID: "core-outage",
|
||||
Name: "Core Monitors Down or Degraded Uptime",
|
||||
Cooldown: NewDuration(30 * time.Minute),
|
||||
TriggerOnRecovery: true,
|
||||
Condition: EventCondition{
|
||||
Operator: "or",
|
||||
Conditions: []EventCondition{
|
||||
{
|
||||
Type: "state",
|
||||
Monitors: []string{"rud-http", "rud-tcp"},
|
||||
Match: "all",
|
||||
State: "down",
|
||||
},
|
||||
{
|
||||
Type: "metric",
|
||||
Monitors: []string{"*"},
|
||||
Match: "any",
|
||||
Metric: "uptime_pct",
|
||||
Comparator: "<",
|
||||
Value: 50.0,
|
||||
For: NewDuration(5 * time.Minute),
|
||||
},
|
||||
},
|
||||
},
|
||||
Actions: []EventAction{
|
||||
{
|
||||
Type: "command",
|
||||
Command: "echo \"[RUD ALERT] {{.EventName}}: status={{.Status}} monitors={{.TriggeredMonitors}}\"",
|
||||
Shell: true,
|
||||
Timeout: NewDuration(5 * time.Second),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
Page: PageConfig{
|
||||
Title: "R u ded?",
|
||||
Theme: ThemeConfig{
|
||||
BgColor: "#111111",
|
||||
CardBgColor: "#191919",
|
||||
TextColor: "#e5e5e5",
|
||||
MutedTextColor: "#888888",
|
||||
BorderColor: "#2e2e2e",
|
||||
AccentColor: "#cccccc",
|
||||
UpColor: "#2ecc71",
|
||||
DegradedColor: "#f1c40f",
|
||||
DownColor: "#e74c3c",
|
||||
PendingColor: "#7f8c8d",
|
||||
FontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",
|
||||
MaxWidth: "820px",
|
||||
BorderRadius: "2px",
|
||||
},
|
||||
Elements: []PageElement{
|
||||
{
|
||||
Type: "header",
|
||||
Title: "R u ded?",
|
||||
Subtitle: "Minimalist system status & health monitor",
|
||||
Align: "split",
|
||||
ShowLastUpdated: true,
|
||||
ShowLiveIndicator: true,
|
||||
},
|
||||
{
|
||||
Type: "status_banner",
|
||||
Messages: map[string]string{
|
||||
"up": "No — All systems operational",
|
||||
"degraded": "Kinda — Some systems are experiencing degraded performance",
|
||||
"down": "Yes — One or more systems are down",
|
||||
"pending": "Checking system status...",
|
||||
},
|
||||
ShowOverallUptime: true,
|
||||
ShowCounts: true,
|
||||
},
|
||||
{
|
||||
Type: "summary_cards",
|
||||
Metrics: []string{"total", "up", "degraded", "down", "overall_uptime", "avg_latency"},
|
||||
},
|
||||
{
|
||||
Type: "monitor_group",
|
||||
Title: "Monitored Services",
|
||||
Description: "Live health checks",
|
||||
Monitors: []string{"*"},
|
||||
Layout: "list",
|
||||
Display: &MonitorDisplayConfig{
|
||||
ShowBar: BoolPtr(true),
|
||||
BarTicks: 40,
|
||||
ShowUptime: BoolPtr(true),
|
||||
ShowLatency: BoolPtr(true),
|
||||
ShowStatusBadge: BoolPtr(true),
|
||||
ShowMethod: BoolPtr(true),
|
||||
ShowTarget: BoolPtr(false),
|
||||
ShowDescription: BoolPtr(true),
|
||||
ShowMessage: BoolPtr(false),
|
||||
ShowLastChecked: BoolPtr(false),
|
||||
CustomLabels: map[string]string{
|
||||
"up": "OK",
|
||||
"degraded": "SLOW",
|
||||
"down": "DED",
|
||||
"pending": "WAIT",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// LoadOrInit loads rud.json from path. If the file does not exist and createIfMissing is true,
|
||||
// it writes DefaultConfig() to path and returns it.
|
||||
func LoadOrInit(path string, createIfMissing bool) (*Config, bool, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
created := false
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) && createIfMissing {
|
||||
cfg := DefaultConfig()
|
||||
if err := SaveConfig(path, &cfg); err != nil {
|
||||
return nil, false, fmt.Errorf("failed to write default config to %s: %w", path, err)
|
||||
}
|
||||
cfg.ApplyFallbacks()
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return nil, true, err
|
||||
}
|
||||
return &cfg, true, nil
|
||||
}
|
||||
return nil, false, fmt.Errorf("failed to read config %s: %w", path, err)
|
||||
}
|
||||
|
||||
var cfg Config
|
||||
if err := json.Unmarshal(data, &cfg); err != nil {
|
||||
return nil, created, fmt.Errorf("failed to parse %s: %w", path, err)
|
||||
}
|
||||
cfg.ApplyFallbacks()
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return nil, created, fmt.Errorf("invalid config in %s: %w", path, err)
|
||||
}
|
||||
return &cfg, created, nil
|
||||
}
|
||||
|
||||
// SaveConfig writes the Config struct as indented, human-readable JSON without HTML-escaping characters like '<' or '&'.
|
||||
func SaveConfig(path string, cfg *Config) error {
|
||||
var buf bytes.Buffer
|
||||
enc := json.NewEncoder(&buf)
|
||||
enc.SetEscapeHTML(false)
|
||||
enc.SetIndent("", " ")
|
||||
if err := enc.Encode(cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(path, buf.Bytes(), 0644)
|
||||
}
|
||||
|
||||
// ApplyFallbacks populates missing structural defaults (like listen address, endpoint, status codes, theme colors)
|
||||
// while strictly preserving the user's explicit page.elements and monitors list.
|
||||
func (c *Config) ApplyFallbacks() {
|
||||
if c.Server.Listen == "" {
|
||||
c.Server.Listen = ":8080"
|
||||
}
|
||||
if c.Server.Endpoint == "" {
|
||||
c.Server.Endpoint = "/"
|
||||
}
|
||||
if !strings.HasPrefix(c.Server.Endpoint, "/") {
|
||||
c.Server.Endpoint = "/" + c.Server.Endpoint
|
||||
}
|
||||
if c.Server.StatusCodes.HTML.Up == 0 {
|
||||
c.Server.StatusCodes.HTML.Up = 200
|
||||
}
|
||||
if c.Server.StatusCodes.HTML.Degraded == 0 {
|
||||
c.Server.StatusCodes.HTML.Degraded = 200
|
||||
}
|
||||
if c.Server.StatusCodes.HTML.Down == 0 {
|
||||
c.Server.StatusCodes.HTML.Down = 200
|
||||
}
|
||||
if c.Server.StatusCodes.HTML.Pending == 0 {
|
||||
c.Server.StatusCodes.HTML.Pending = 200
|
||||
}
|
||||
if c.Server.StatusCodes.JSON.Up == 0 {
|
||||
c.Server.StatusCodes.JSON.Up = 200
|
||||
}
|
||||
if c.Server.StatusCodes.JSON.Degraded == 0 {
|
||||
c.Server.StatusCodes.JSON.Degraded = 200
|
||||
}
|
||||
if c.Server.StatusCodes.JSON.Down == 0 {
|
||||
c.Server.StatusCodes.JSON.Down = 503
|
||||
}
|
||||
if c.Server.StatusCodes.JSON.Pending == 0 {
|
||||
c.Server.StatusCodes.JSON.Pending = 200
|
||||
}
|
||||
|
||||
if c.Storage.HistorySize <= 0 {
|
||||
c.Storage.HistorySize = 60
|
||||
}
|
||||
if c.Storage.SaveInterval <= 0 {
|
||||
c.Storage.SaveInterval = NewDuration(1 * time.Minute)
|
||||
}
|
||||
|
||||
if c.Defaults.Interval <= 0 {
|
||||
c.Defaults.Interval = NewDuration(30 * time.Second)
|
||||
}
|
||||
if c.Defaults.Timeout <= 0 {
|
||||
c.Defaults.Timeout = NewDuration(5 * time.Second)
|
||||
}
|
||||
if c.Defaults.DegradedLatency <= 0 {
|
||||
c.Defaults.DegradedLatency = NewDuration(1000 * time.Millisecond)
|
||||
}
|
||||
|
||||
// Theme color fallbacks if omitted
|
||||
defTheme := DefaultConfig().Page.Theme
|
||||
if c.Page.Theme.BgColor == "" {
|
||||
c.Page.Theme.BgColor = defTheme.BgColor
|
||||
}
|
||||
if c.Page.Theme.CardBgColor == "" {
|
||||
c.Page.Theme.CardBgColor = defTheme.CardBgColor
|
||||
}
|
||||
if c.Page.Theme.TextColor == "" {
|
||||
c.Page.Theme.TextColor = defTheme.TextColor
|
||||
}
|
||||
if c.Page.Theme.MutedTextColor == "" {
|
||||
c.Page.Theme.MutedTextColor = defTheme.MutedTextColor
|
||||
}
|
||||
if c.Page.Theme.BorderColor == "" {
|
||||
c.Page.Theme.BorderColor = defTheme.BorderColor
|
||||
}
|
||||
if c.Page.Theme.AccentColor == "" {
|
||||
c.Page.Theme.AccentColor = defTheme.AccentColor
|
||||
}
|
||||
if c.Page.Theme.UpColor == "" {
|
||||
c.Page.Theme.UpColor = defTheme.UpColor
|
||||
}
|
||||
if c.Page.Theme.DegradedColor == "" {
|
||||
c.Page.Theme.DegradedColor = defTheme.DegradedColor
|
||||
}
|
||||
if c.Page.Theme.DownColor == "" {
|
||||
c.Page.Theme.DownColor = defTheme.DownColor
|
||||
}
|
||||
if c.Page.Theme.PendingColor == "" {
|
||||
c.Page.Theme.PendingColor = defTheme.PendingColor
|
||||
}
|
||||
if c.Page.Theme.FontFamily == "" {
|
||||
c.Page.Theme.FontFamily = defTheme.FontFamily
|
||||
}
|
||||
if c.Page.Theme.MaxWidth == "" {
|
||||
c.Page.Theme.MaxWidth = defTheme.MaxWidth
|
||||
}
|
||||
if c.Page.Theme.BorderRadius == "" {
|
||||
c.Page.Theme.BorderRadius = defTheme.BorderRadius
|
||||
}
|
||||
}
|
||||
|
||||
// Validate checks the configuration for duplicate IDs, invalid methods, or invalid regexes.
|
||||
func (c *Config) Validate() error {
|
||||
seen := make(map[string]bool)
|
||||
for i := range c.Monitors {
|
||||
m := &c.Monitors[i]
|
||||
if strings.TrimSpace(m.ID) == "" {
|
||||
return fmt.Errorf("monitor at index %d is missing an 'id'", i)
|
||||
}
|
||||
if seen[m.ID] {
|
||||
return fmt.Errorf("duplicate monitor id %q", m.ID)
|
||||
}
|
||||
seen[m.ID] = true
|
||||
if m.Name == "" {
|
||||
m.Name = m.ID
|
||||
}
|
||||
|
||||
method := strings.ToLower(strings.TrimSpace(m.Method))
|
||||
m.Method = method
|
||||
switch method {
|
||||
case "http", "https":
|
||||
if m.URL == "" {
|
||||
return fmt.Errorf("monitor %q (method %s) requires 'url'", m.ID, method)
|
||||
}
|
||||
if m.BodyRegex != "" {
|
||||
if _, err := regexp.Compile(m.BodyRegex); err != nil {
|
||||
return fmt.Errorf("monitor %q has invalid body_regex %q: %w", m.ID, m.BodyRegex, err)
|
||||
}
|
||||
}
|
||||
case "tcp":
|
||||
if m.Target == "" && m.Host == "" {
|
||||
return fmt.Errorf("monitor %q (method tcp) requires 'target' (host:port)", m.ID)
|
||||
}
|
||||
if m.Target == "" {
|
||||
m.Target = m.Host
|
||||
}
|
||||
case "ping":
|
||||
if m.Host == "" && m.Target == "" {
|
||||
return fmt.Errorf("monitor %q (method ping) requires 'host'", m.ID)
|
||||
}
|
||||
if m.Host == "" {
|
||||
m.Host = m.Target
|
||||
}
|
||||
case "dns":
|
||||
if m.Host == "" && m.Target == "" {
|
||||
return fmt.Errorf("monitor %q (method dns) requires 'host'", m.ID)
|
||||
}
|
||||
if m.Host == "" {
|
||||
m.Host = m.Target
|
||||
}
|
||||
if m.ExpectedRegex != "" {
|
||||
if _, err := regexp.Compile(m.ExpectedRegex); err != nil {
|
||||
return fmt.Errorf("monitor %q has invalid expected_regex %q: %w", m.ID, m.ExpectedRegex, err)
|
||||
}
|
||||
}
|
||||
case "cmd", "script", "command":
|
||||
if m.Command == "" {
|
||||
return fmt.Errorf("monitor %q (method %s) requires 'command'", m.ID, method)
|
||||
}
|
||||
if m.OutputRegex != "" {
|
||||
if _, err := regexp.Compile(m.OutputRegex); err != nil {
|
||||
return fmt.Errorf("monitor %q has invalid output_regex %q: %w", m.ID, m.OutputRegex, err)
|
||||
}
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("monitor %q has unsupported method %q (supported: http, https, tcp, ping, dns, cmd)", m.ID, m.Method)
|
||||
}
|
||||
}
|
||||
|
||||
for i, ev := range c.Events {
|
||||
if ev.ID == "" {
|
||||
return fmt.Errorf("event at index %d is missing an 'id'", i)
|
||||
}
|
||||
if err := validateCondition(ev.Condition); err != nil {
|
||||
return fmt.Errorf("event %q has invalid condition: %w", ev.ID, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateCondition(cond EventCondition) error {
|
||||
if len(cond.Conditions) > 0 {
|
||||
op := strings.ToLower(cond.Operator)
|
||||
if op != "" && op != "and" && op != "or" {
|
||||
return fmt.Errorf("unsupported boolean operator %q (expected 'and' or 'or')", cond.Operator)
|
||||
}
|
||||
for _, sub := range cond.Conditions {
|
||||
if err := validateCondition(sub); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
t := strings.ToLower(cond.Type)
|
||||
if t == "" {
|
||||
if cond.Metric != "" {
|
||||
t = "metric"
|
||||
} else if cond.State != "" {
|
||||
t = "state"
|
||||
}
|
||||
}
|
||||
switch t {
|
||||
case "state":
|
||||
s := strings.ToLower(cond.State)
|
||||
if s != "up" && s != "degraded" && s != "down" && s != "pending" {
|
||||
return fmt.Errorf("invalid state %q in state condition", cond.State)
|
||||
}
|
||||
case "metric":
|
||||
m := strings.ToLower(cond.Metric)
|
||||
if m != "uptime_pct" && m != "uptime" && m != "latency_ms" && m != "latency" && m != "consecutive_failures" {
|
||||
return fmt.Errorf("invalid metric %q (expected uptime_pct, latency_ms, or consecutive_failures)", cond.Metric)
|
||||
}
|
||||
switch cond.Comparator {
|
||||
case "<", "<=", ">", ">=", "==", "!=":
|
||||
default:
|
||||
return fmt.Errorf("invalid comparator %q in metric condition", cond.Comparator)
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("condition must specify either 'conditions' (and/or), 'state', or 'metric'")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
75
internal/config/config_test.go
Normal file
75
internal/config/config_test.go
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
package config
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestLoadOrInitGeneratesDefault(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
cfgPath := filepath.Join(tmpDir, "rud.json")
|
||||
|
||||
cfg, created, err := LoadOrInit(cfgPath, true)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadOrInit failed: %v", err)
|
||||
}
|
||||
if !created {
|
||||
t.Fatalf("expected created=true when file did not exist")
|
||||
}
|
||||
if len(cfg.Monitors) == 0 {
|
||||
t.Fatalf("expected default monitors to be populated")
|
||||
}
|
||||
if len(cfg.Page.Elements) == 0 {
|
||||
t.Fatalf("expected default page elements to be populated")
|
||||
}
|
||||
|
||||
// Reload existing file
|
||||
cfg2, created2, err := LoadOrInit(cfgPath, true)
|
||||
if err != nil {
|
||||
t.Fatalf("second LoadOrInit failed: %v", err)
|
||||
}
|
||||
if created2 {
|
||||
t.Fatalf("expected created=false when file already exists")
|
||||
}
|
||||
if len(cfg2.Monitors) != len(cfg.Monitors) {
|
||||
t.Fatalf("expected %d monitors, got %d", len(cfg.Monitors), len(cfg2.Monitors))
|
||||
}
|
||||
}
|
||||
|
||||
func TestDurationMarshalUnmarshal(t *testing.T) {
|
||||
d := NewDuration(5 * time.Hour)
|
||||
b, err := d.MarshalJSON()
|
||||
if err != nil {
|
||||
t.Fatalf("MarshalJSON failed: %v", err)
|
||||
}
|
||||
if string(b) != `"5h"` {
|
||||
t.Fatalf("expected \"5h\", got %s", string(b))
|
||||
}
|
||||
|
||||
var parsed Duration
|
||||
if err := parsed.UnmarshalJSON([]byte(`"15m"`)); err != nil {
|
||||
t.Fatalf("UnmarshalJSON failed: %v", err)
|
||||
}
|
||||
if parsed.Std() != 15*time.Minute {
|
||||
t.Fatalf("expected 15m, got %v", parsed.Std())
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigValidation(t *testing.T) {
|
||||
cfg := DefaultConfig()
|
||||
cfg.Monitors = []MonitorConfig{
|
||||
{ID: "dup", Method: "tcp", Target: "127.0.0.1:80"},
|
||||
{ID: "dup", Method: "tcp", Target: "127.0.0.1:81"},
|
||||
}
|
||||
if err := cfg.Validate(); err == nil {
|
||||
t.Fatalf("expected duplicate monitor id error")
|
||||
}
|
||||
|
||||
cfg.Monitors = []MonitorConfig{
|
||||
{ID: "bad-regex", Method: "http", URL: "http://example.com", BodyRegex: "["},
|
||||
}
|
||||
if err := cfg.Validate(); err == nil {
|
||||
t.Fatalf("expected invalid body_regex error")
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue