RUD/internal/config/config.go

1248 lines
38 KiB
Go

package config
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net"
"net/url"
"os"
"path/filepath"
"reflect"
"regexp"
"sort"
"strings"
"text/template"
"time"
)
// ActionTemplateFuncMap returns the shared Go text/template helper functions
// available to event webhook body_template and command templates.
func ActionTemplateFuncMap() template.FuncMap {
return template.FuncMap{
"json": func(v any) (string, error) {
b, err := json.Marshal(v)
if err != nil {
return "", err
}
return string(b), nil
},
"jsonStr": func(v any) (string, error) {
b, err := json.Marshal(fmt.Sprint(v))
if err != nil {
return "", err
}
s := string(b)
if len(s) >= 2 && s[0] == '"' && s[len(s)-1] == '"' {
return s[1 : len(s)-1], nil
}
return s, nil
},
}
}
// 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
}
// LoadForEdit loads and unmarshals a config file without applying fallbacks or failing validation,
// returning both the parsed Config and the raw JSON bytes for linting and diffing.
func LoadForEdit(path string) (*Config, []byte, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, nil, fmt.Errorf("failed to read config %s: %w", path, err)
}
var cfg Config
if err := json.Unmarshal(data, &cfg); err != nil {
return nil, data, fmt.Errorf("failed to parse %s: %w", path, err)
}
return &cfg, data, nil
}
// Clone returns a deep copy of Config via JSON round-trip.
func (c *Config) Clone() (*Config, error) {
data, err := MarshalConfig(c)
if err != nil {
return nil, err
}
var cp Config
if err := json.Unmarshal(data, &cp); err != nil {
return nil, err
}
return &cp, nil
}
// MarshalConfig encodes Config as indented, human-readable JSON without HTML escaping.
func MarshalConfig(cfg *Config) ([]byte, error) {
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
if err := enc.Encode(cfg); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func writeFileAtomic(path string, data []byte) error {
dir := filepath.Dir(path)
if dir != "" && dir != "." {
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
} else {
dir = "."
}
tmp, err := os.CreateTemp(dir, ".rud-config-*.tmp")
if err != nil {
return err
}
tmpPath := tmp.Name()
cleanup := true
defer func() {
if cleanup {
_ = os.Remove(tmpPath)
}
}()
if _, err := tmp.Write(data); err != nil {
_ = tmp.Close()
return err
}
if err := tmp.Chmod(0644); err != nil {
_ = tmp.Close()
return err
}
if err := tmp.Sync(); err != nil {
_ = tmp.Close()
return err
}
if err := tmp.Close(); err != nil {
return err
}
if err := os.Rename(tmpPath, path); err != nil {
return err
}
cleanup = false
return nil
}
// SaveConfig atomically writes Config as indented, human-readable JSON without HTML escaping.
func SaveConfig(path string, cfg *Config) error {
data, err := MarshalConfig(cfg)
if err != nil {
return err
}
return writeFileAtomic(path, data)
}
// SaveConfigWithBackup optionally copies an existing file to <path>.bak before atomically saving cfg.
func SaveConfigWithBackup(path string, cfg *Config, backup bool) (string, error) {
var backupPath string
if backup {
existing, err := os.ReadFile(path)
if err == nil {
backupPath = path + ".bak"
if err := writeFileAtomic(backupPath, existing); err != nil {
return "", fmt.Errorf("failed to write backup %s: %w", backupPath, err)
}
} else if !errors.Is(err, os.ErrNotExist) {
return "", fmt.Errorf("failed to read existing config %s for backup: %w", path, err)
}
}
if err := SaveConfig(path, cfg); err != nil {
return backupPath, err
}
return backupPath, nil
}
// 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, invalid URLs/regexes/templates, and negative values.
func (c *Config) Validate() error {
if c.Server.RefreshInterval < 0 {
return fmt.Errorf("server.refresh_interval cannot be negative")
}
if c.Storage.SaveInterval < 0 {
return fmt.Errorf("storage.save_interval cannot be negative")
}
if c.Defaults.Interval < 0 {
return fmt.Errorf("defaults.interval cannot be negative")
}
if c.Defaults.Timeout < 0 {
return fmt.Errorf("defaults.timeout cannot be negative")
}
if c.Defaults.DegradedLatency < 0 {
return fmt.Errorf("defaults.degraded_latency cannot be negative")
}
if c.Defaults.Retries < 0 {
return fmt.Errorf("defaults.retries cannot be negative")
}
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
}
if m.Interval < 0 {
return fmt.Errorf("monitor %q has negative interval", m.ID)
}
if m.Timeout < 0 {
return fmt.Errorf("monitor %q has negative timeout", m.ID)
}
if m.DegradedLatency < 0 {
return fmt.Errorf("monitor %q has negative degraded_latency", m.ID)
}
if m.Retries != nil && *m.Retries < 0 {
return fmt.Errorf("monitor %q has negative retries", 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)
}
u, err := url.Parse(m.URL)
if err != nil || (!strings.EqualFold(u.Scheme, "http") && !strings.EqualFold(u.Scheme, "https")) || u.Host == "" {
return fmt.Errorf("monitor %q has invalid HTTP URL %q", m.ID, m.URL)
}
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)
}
}
seenEvents := make(map[string]bool)
for i, ev := range c.Events {
if strings.TrimSpace(ev.ID) == "" {
return fmt.Errorf("event at index %d is missing an 'id'", i)
}
if seenEvents[ev.ID] {
return fmt.Errorf("duplicate event id %q", ev.ID)
}
seenEvents[ev.ID] = true
if ev.Cooldown < 0 {
return fmt.Errorf("event %q has negative cooldown", ev.ID)
}
if err := validateCondition(ev.Condition); err != nil {
return fmt.Errorf("event %q has invalid condition: %w", ev.ID, err)
}
for j, act := range ev.Actions {
if err := validateAction(act); err != nil {
return fmt.Errorf("event %q action[%d]: %w", ev.ID, j, err)
}
}
for j, act := range ev.RecoveryActions {
if err := validateAction(act); err != nil {
return fmt.Errorf("event %q recovery_actions[%d]: %w", ev.ID, j, err)
}
}
}
return nil
}
func validateAction(act EventAction) error {
if act.Timeout < 0 {
return fmt.Errorf("action timeout cannot be negative")
}
t := strings.ToLower(strings.TrimSpace(act.Type))
switch t {
case "webhook":
if strings.TrimSpace(act.URL) == "" {
return fmt.Errorf("webhook action requires 'url'")
}
u, err := url.Parse(act.URL)
if err != nil || (!strings.EqualFold(u.Scheme, "http") && !strings.EqualFold(u.Scheme, "https")) || u.Host == "" {
return fmt.Errorf("webhook action has invalid URL %q", act.URL)
}
if act.BodyTemplate != "" {
if _, err := template.New("action").Funcs(ActionTemplateFuncMap()).Parse(act.BodyTemplate); err != nil {
return fmt.Errorf("invalid body_template: %w", err)
}
}
case "command", "cmd", "script":
if strings.TrimSpace(act.Command) == "" {
return fmt.Errorf("command action requires 'command'")
}
if _, err := template.New("action").Funcs(ActionTemplateFuncMap()).Parse(act.Command); err != nil {
return fmt.Errorf("invalid command template: %w", err)
}
for i, a := range act.Args {
if _, err := template.New("action").Funcs(ActionTemplateFuncMap()).Parse(a); err != nil {
return fmt.Errorf("invalid args[%d] template: %w", i, err)
}
}
default:
return fmt.Errorf("unsupported action type %q (supported: webhook, command)", act.Type)
}
return nil
}
func validateCondition(cond EventCondition) error {
if cond.For < 0 {
return fmt.Errorf("condition 'for' duration cannot be negative")
}
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
}
// LintIssue describes a non-fatal configuration warning or potential misconfiguration.
type LintIssue struct {
Path string
Message string
}
func (l LintIssue) String() string {
if l.Path == "" {
return l.Message
}
return fmt.Sprintf("%s: %s", l.Path, l.Message)
}
// Lint performs non-fatal semantic and unknown-field checks against the Config and optional raw JSON.
func (c *Config) Lint(rawJSON []byte) []LintIssue {
var issues []LintIssue
if len(bytes.TrimSpace(rawJSON)) > 0 {
var raw any
if err := json.Unmarshal(rawJSON, &raw); err == nil {
lintUnknownFields(raw, reflect.TypeOf(Config{}), "", &issues)
}
}
if len(c.Monitors) == 0 {
issues = append(issues, LintIssue{Path: "monitors", Message: "no monitors configured"})
}
knownMonitors := make(map[string]bool, len(c.Monitors))
for i, m := range c.Monitors {
if m.ID != "" {
knownMonitors[m.ID] = true
}
method := strings.ToLower(strings.TrimSpace(m.Method))
switch method {
case "tcp":
target := m.Target
if target == "" {
target = m.Host
}
if target != "" {
if host, port, err := net.SplitHostPort(target); err != nil || host == "" || port == "" {
issues = append(issues, LintIssue{
Path: fmt.Sprintf("monitors[%d].target", i),
Message: fmt.Sprintf("TCP target %q should be in host:port format", target),
})
}
}
case "dns":
if m.RecordType != "" {
switch strings.ToUpper(strings.TrimSpace(m.RecordType)) {
case "A", "AAAA", "CNAME", "MX", "TXT", "NS":
default:
issues = append(issues, LintIssue{
Path: fmt.Sprintf("monitors[%d].record_type", i),
Message: fmt.Sprintf("unrecognized DNS record_type %q (expected A, AAAA, CNAME, MX, TXT, or NS)", m.RecordType),
})
}
}
case "http", "https":
for j, code := range m.ExpectedStatus {
if code < 100 || code > 599 {
issues = append(issues, LintIssue{
Path: fmt.Sprintf("monitors[%d].expected_status[%d]", i, j),
Message: fmt.Sprintf("HTTP status code %d is outside valid range 100..599", code),
})
}
}
}
}
for i, ev := range c.Events {
if len(ev.Actions) == 0 {
issues = append(issues, LintIssue{
Path: fmt.Sprintf("events[%d].actions", i),
Message: fmt.Sprintf("event %q has no actions configured", ev.ID),
})
}
lintCondition(ev.Condition, fmt.Sprintf("events[%d].condition", i), knownMonitors, &issues)
}
for i, el := range c.Page.Elements {
elType := strings.ToLower(strings.TrimSpace(el.Type))
prefix := fmt.Sprintf("page.elements[%d]", i)
switch elType {
case "header":
switch strings.ToLower(strings.TrimSpace(el.Align)) {
case "", "left", "center", "split":
default:
issues = append(issues, LintIssue{
Path: prefix + ".align",
Message: fmt.Sprintf("unknown header align %q (expected left, center, or split)", el.Align),
})
}
case "status_banner":
case "summary_cards", "summary":
for j, metric := range el.Metrics {
switch strings.ToLower(strings.TrimSpace(metric)) {
case "total", "up", "degraded", "down", "overall_uptime", "uptime", "avg_latency", "latency":
default:
issues = append(issues, LintIssue{
Path: fmt.Sprintf("%s.metrics[%d]", prefix, j),
Message: fmt.Sprintf("unknown summary metric %q", metric),
})
}
}
case "monitor_group", "monitors":
switch strings.ToLower(strings.TrimSpace(el.Layout)) {
case "", "list", "grid":
default:
issues = append(issues, LintIssue{
Path: prefix + ".layout",
Message: fmt.Sprintf("unknown monitor_group layout %q (expected list or grid)", el.Layout),
})
}
for j, id := range el.Monitors {
if id != "*" && !knownMonitors[id] {
issues = append(issues, LintIssue{
Path: fmt.Sprintf("%s.monitors[%d]", prefix, j),
Message: fmt.Sprintf("references unknown monitor id %q", id),
})
}
}
case "custom_block", "text":
switch strings.ToLower(strings.TrimSpace(el.Style)) {
case "", "neutral", "info", "warning", "danger":
default:
issues = append(issues, LintIssue{
Path: prefix + ".style",
Message: fmt.Sprintf("unknown custom_block style %q (expected neutral, info, warning, or danger)", el.Style),
})
}
case "divider":
default:
issues = append(issues, LintIssue{
Path: prefix + ".type",
Message: fmt.Sprintf("unknown page element type %q", el.Type),
})
}
}
return issues
}
func lintCondition(cond EventCondition, path string, knownMonitors map[string]bool, issues *[]LintIssue) {
if len(cond.Conditions) > 0 {
for i, sub := range cond.Conditions {
lintCondition(sub, fmt.Sprintf("%s.conditions[%d]", path, i), knownMonitors, issues)
}
return
}
switch strings.ToLower(strings.TrimSpace(cond.Match)) {
case "", "all", "any":
default:
*issues = append(*issues, LintIssue{
Path: path + ".match",
Message: fmt.Sprintf("unknown match mode %q (expected all or any)", cond.Match),
})
}
for i, id := range cond.Monitors {
if id != "*" && !knownMonitors[id] {
*issues = append(*issues, LintIssue{
Path: fmt.Sprintf("%s.monitors[%d]", path, i),
Message: fmt.Sprintf("references unknown monitor id %q", id),
})
}
}
}
var durationType = reflect.TypeOf(Duration(0))
func lintUnknownFields(raw any, t reflect.Type, path string, issues *[]LintIssue) {
if raw == nil {
return
}
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t == durationType {
return
}
switch t.Kind() {
case reflect.Struct:
m, ok := raw.(map[string]any)
if !ok {
return
}
fields := make(map[string]reflect.Type, t.NumField())
for i := 0; i < t.NumField(); i++ {
sf := t.Field(i)
if !sf.IsExported() {
continue
}
tag := sf.Tag.Get("json")
if tag == "-" {
continue
}
name := strings.Split(tag, ",")[0]
if name == "" {
name = sf.Name
}
fields[name] = sf.Type
}
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
subPath := k
if path != "" {
subPath = path + "." + k
}
ft, exists := fields[k]
if !exists {
*issues = append(*issues, LintIssue{
Path: subPath,
Message: fmt.Sprintf("unknown JSON field %q", k),
})
continue
}
lintUnknownFields(m[k], ft, subPath, issues)
}
case reflect.Slice:
arr, ok := raw.([]any)
if !ok {
return
}
for i, item := range arr {
lintUnknownFields(item, t.Elem(), fmt.Sprintf("%s[%d]", path, i), issues)
}
}
}