Compare commits
No commits in common. "161bf5e8cbaeb8376317b54a245db406009a52ff" and "2852be0a87367fab4d65194f44d9d9abb8ab0ec4" have entirely different histories.
161bf5e8cb
...
2852be0a87
28 changed files with 161 additions and 6784 deletions
15
README.md
15
README.md
|
|
@ -14,21 +14,10 @@ Compiles to a single static binary, checks `http`/`https`, `tcp`, `ping`, `dns`,
|
|||
|
||||
```bash
|
||||
go build -trimpath -ldflags="-s -w" -o rud .
|
||||
|
||||
./rud config -config rud.json # interactive config builder (new or edit)
|
||||
./rud validate -config rud.json # validate & lint configuration
|
||||
./rud test -config rud.json # run one-shot live checks
|
||||
./rud -config rud.json # run server (auto-generates rud.json if missing)
|
||||
./rud -config rud.json # auto-generates rud.json if missing
|
||||
```
|
||||
|
||||
Then open `http://localhost:8080/` (HTML), `http://localhost:8080/monitor` (per-monitor history & charts), or `http://localhost:8080/?format=json` (JSON).
|
||||
|
||||
#### CLI Subcommands
|
||||
|
||||
- `./rud config [-config path] [-new] [-plain] [-no-color]`: Interactive configuration builder (arrow-key navigation on TTYs with automatic numbered fallback; `-new` forces the starter template / quick-start wizard).
|
||||
- `./rud validate [-config path] [-strict]`: Validates schema, regexes, URLs, and alert templates, and reports lint warnings (unknown JSON fields, dangling monitor IDs). `-strict` treats lint warnings as errors.
|
||||
- `./rud test [-config path] [-json] [-no-retry] [monitor-ids...]`: Executes live monitor checks once and prints results (exits non-zero if any tested monitor is `down`).
|
||||
- `./rud -init -config rud.json`: Non-interactively writes a default `rud.json` and exits.
|
||||
Then open `http://localhost:8080/` (HTML) or `http://localhost:8080/?format=json` (JSON).
|
||||
|
||||
### Docker Compose
|
||||
|
||||
|
|
|
|||
|
|
@ -1,449 +0,0 @@
|
|||
package builder
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"git.gsdistance.org/tyuXX/RUD/internal/config"
|
||||
)
|
||||
|
||||
// Options configures a rud config builder session.
|
||||
type Options struct {
|
||||
ConfigPath string
|
||||
ForceNew bool
|
||||
Plain bool
|
||||
NoColor bool
|
||||
In io.Reader
|
||||
Out io.Writer
|
||||
}
|
||||
|
||||
// Run launches the interactive configuration builder CLI.
|
||||
func Run(ctx context.Context, opts Options) error {
|
||||
path := strings.TrimSpace(opts.ConfigPath)
|
||||
if path == "" {
|
||||
path = "rud.json"
|
||||
}
|
||||
|
||||
ui := NewUI(opts.In, opts.Out, opts.Plain, opts.NoColor)
|
||||
|
||||
var cfg *config.Config
|
||||
var originalRaw []byte
|
||||
var baselineJSON string
|
||||
isNewFile := false
|
||||
|
||||
_, statErr := os.Stat(path)
|
||||
fileExists := statErr == nil
|
||||
|
||||
if !opts.ForceNew && fileExists {
|
||||
loaded, raw, loadErr := config.LoadForEdit(path)
|
||||
if loadErr != nil {
|
||||
ui.Error(fmt.Sprintf("Could not load %s: %v", path, loadErr))
|
||||
recOpts := []Option{
|
||||
{Label: "Start a new config from a template", Description: "Existing file will not be modified until you Save"},
|
||||
{Label: "Exit"},
|
||||
}
|
||||
idx, ok, err := ui.Select("Config Load Error", "", recOpts, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok || idx == 1 {
|
||||
return nil
|
||||
}
|
||||
isNewFile = true
|
||||
} else {
|
||||
cfg = loaded
|
||||
originalRaw = raw
|
||||
if b, err := config.MarshalConfig(cfg); err == nil {
|
||||
baselineJSON = string(b)
|
||||
}
|
||||
ui.Ok(fmt.Sprintf("Loaded existing configuration from %s", path))
|
||||
}
|
||||
} else {
|
||||
isNewFile = true
|
||||
}
|
||||
|
||||
if cfg == nil {
|
||||
starter, ok, err := newConfigStarterFlow(ctx, ui, path, fileExists)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
cfg = starter
|
||||
}
|
||||
|
||||
return runSectionHub(ctx, ui, cfg, path, isNewFile, baselineJSON, originalRaw)
|
||||
}
|
||||
|
||||
func newConfigStarterFlow(ctx context.Context, ui *UI, path string, fileExists bool) (*config.Config, bool, error) {
|
||||
sub := fmt.Sprintf("Target file: %s", path)
|
||||
if fileExists {
|
||||
sub += " (will be overwritten only when you Save)"
|
||||
}
|
||||
opts := []Option{
|
||||
{Label: "Guided Quick-Start Wizard", Description: "Step-by-step setup for server, monitors, alerts, and theme"},
|
||||
{Label: "Default Demo Config", Description: "All 5 check methods + sample event + dark minimal page"},
|
||||
{Label: "Web & API Starter", Description: "HTTPS endpoints, DNS check, outage alert, grouped layout"},
|
||||
{Label: "Homelab / Infrastructure Starter", Description: "Gateway ping, DB TCP, reverse proxy HTTP, disk space cmd"},
|
||||
{Label: "Blank Minimal Config", Description: "Empty monitors & events with a clean status page scaffold"},
|
||||
{Label: "Exit"},
|
||||
}
|
||||
|
||||
idx, ok, err := ui.Select("Create New RUD Configuration", sub, opts, 0)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if !ok || idx == len(opts)-1 {
|
||||
return nil, false, nil
|
||||
}
|
||||
|
||||
switch idx {
|
||||
case 0:
|
||||
cfg := BlankMinimalConfig()
|
||||
if err := runQuickStartWizard(ctx, ui, &cfg); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return &cfg, true, nil
|
||||
case 1:
|
||||
cfg := config.DefaultConfig()
|
||||
return &cfg, true, nil
|
||||
case 2:
|
||||
cfg := WebAPIStarterConfig()
|
||||
return &cfg, true, nil
|
||||
case 3:
|
||||
cfg := HomelabStarterConfig()
|
||||
return &cfg, true, nil
|
||||
case 4:
|
||||
cfg := BlankMinimalConfig()
|
||||
return &cfg, true, nil
|
||||
default:
|
||||
return nil, false, nil
|
||||
}
|
||||
}
|
||||
|
||||
func runQuickStartWizard(ctx context.Context, ui *UI, cfg *config.Config) error {
|
||||
ui.Header("Quick-Start Wizard (1/4): Server", "Configure the single HTTP endpoint served by RUD")
|
||||
listen, err := ui.PromptString("Listen address", cfg.Server.Listen, "host:port or :8080", false, requireNonEmpty("listen"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Server.Listen = listen
|
||||
|
||||
endpoint, err := ui.PromptString("HTTP endpoint path", cfg.Server.Endpoint, "must start with /", false, requireNonEmpty("endpoint"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !strings.HasPrefix(endpoint, "/") {
|
||||
endpoint = "/" + endpoint
|
||||
}
|
||||
cfg.Server.Endpoint = endpoint
|
||||
|
||||
ui.Header("Quick-Start Wizard (2/4): Monitors", "Add one or more services to monitor")
|
||||
for {
|
||||
added, err := addMonitorFlow(ctx, ui, cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !added && len(cfg.Monitors) == 0 {
|
||||
break
|
||||
}
|
||||
more, err := ui.Confirm("Add another monitor?", false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !more {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
ui.Header("Quick-Start Wizard (3/4): Alerts & Events", "Optional outbound webhooks or commands on outage/recovery")
|
||||
addEv, err := ui.Confirm("Configure an alert event rule now?", false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if addEv {
|
||||
if err := addEventFlow(ui, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
ui.Header("Quick-Start Wizard (4/4): Status Page & Theme", "Customize your public status page")
|
||||
title, err := ui.PromptString("Page title", cfg.Page.Title, "shown in browser tab & header", false, requireNonEmpty("title"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Page.Title = title
|
||||
for i := range cfg.Page.Elements {
|
||||
if cfg.Page.Elements[i].Type == "header" {
|
||||
cfg.Page.Elements[i].Title = title
|
||||
}
|
||||
}
|
||||
|
||||
pickTheme, err := ui.Confirm("Choose a color theme preset?", true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if pickTheme {
|
||||
if err := applyThemePresetFlow(ui, &cfg.Page); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
ui.Ok("Quick-start setup complete! Opening the configuration hub for further edits or saving.")
|
||||
return nil
|
||||
}
|
||||
|
||||
func runSectionHub(ctx context.Context, ui *UI, cfg *config.Config, path string, isNewFile bool, baselineJSON string, originalRaw []byte) error {
|
||||
for {
|
||||
currBytes, err := config.MarshalConfig(cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
currJSON := string(currBytes)
|
||||
dirty := isNewFile || currJSON != baselineJSON
|
||||
|
||||
lintRaw := currBytes
|
||||
if !dirty && len(originalRaw) > 0 {
|
||||
lintRaw = originalRaw
|
||||
}
|
||||
valErr, lintIssues := evaluateConfigHealth(cfg, lintRaw)
|
||||
|
||||
statusBadge := ui.Green("[saved]")
|
||||
if isNewFile {
|
||||
statusBadge = ui.Yellow("[new unsaved]")
|
||||
} else if dirty {
|
||||
statusBadge = ui.Yellow("[modified]")
|
||||
}
|
||||
|
||||
var healthLine string
|
||||
if valErr != nil {
|
||||
healthLine = ui.Red("✗ Invalid: " + valErr.Error())
|
||||
} else if len(lintIssues) > 0 {
|
||||
healthLine = ui.Yellow(fmt.Sprintf("! Valid with %d warning(s)", len(lintIssues)))
|
||||
} else {
|
||||
healthLine = ui.Green("✓ Valid (0 warnings)")
|
||||
}
|
||||
|
||||
sub := fmt.Sprintf("File: %s %s\nSummary: %d monitor(s) | %d event(s) | %d page element(s)\nHealth: %s",
|
||||
path, statusBadge, len(cfg.Monitors), len(cfg.Events), len(cfg.Page.Elements), healthLine)
|
||||
|
||||
opts := []Option{
|
||||
{Label: fmt.Sprintf("Monitors (%d)", len(cfg.Monitors)), Description: "Add, edit, reorder, duplicate, delete, or test checks live"},
|
||||
{Label: fmt.Sprintf("Events & Alerts (%d)", len(cfg.Events)), Description: "Alert recipes, nested AND/OR condition tree, webhooks & commands"},
|
||||
{Label: fmt.Sprintf("Page & Theme (%d elements)", len(cfg.Page.Elements)), Description: "Theme presets, colors, layout elements & display flags"},
|
||||
{Label: "Server Settings", Description: fmt.Sprintf("listen=%s endpoint=%s refresh=%s", cfg.Server.Listen, cfg.Server.Endpoint, cfg.Server.RefreshInterval.Std())},
|
||||
{Label: "Defaults & Storage", Description: fmt.Sprintf("interval=%s timeout=%s history=%d", cfg.Defaults.Interval.Std(), cfg.Defaults.Timeout.Std(), cfg.Storage.HistorySize)},
|
||||
{Label: "Test Monitors Live", Description: "Run health checks immediately against live targets"},
|
||||
{Label: "Validate & Preview JSON / Diff", Description: "Check errors/warnings, view changes, or inspect full JSON"},
|
||||
{Label: "Save", Description: fmt.Sprintf("Write atomically to %s", path)},
|
||||
{Label: "Save As...", Description: "Save configuration to a different file path"},
|
||||
{Label: "Exit"},
|
||||
}
|
||||
|
||||
idx, ok, err := ui.Select("RUD Config Builder", sub, opts, 0)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrAborted) {
|
||||
return err
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if !ok || idx == 9 {
|
||||
if !dirty {
|
||||
return nil
|
||||
}
|
||||
exitOpts := []Option{
|
||||
{Label: "Save & Exit", Description: "Validate and write changes to " + path},
|
||||
{Label: "Discard changes & Exit"},
|
||||
{Label: "Cancel (return to hub)"},
|
||||
}
|
||||
eIdx, eOK, eErr := ui.Select("Unsaved Changes", fmt.Sprintf("%s has unsaved changes.", path), exitOpts, 0)
|
||||
if eErr != nil {
|
||||
return eErr
|
||||
}
|
||||
if !eOK || eIdx == 2 {
|
||||
continue
|
||||
}
|
||||
if eIdx == 0 {
|
||||
saved, sErr := saveConfigFlow(ui, cfg, &path, &isNewFile, &baselineJSON, &originalRaw, false)
|
||||
if sErr != nil {
|
||||
return sErr
|
||||
}
|
||||
if saved {
|
||||
return nil
|
||||
}
|
||||
continue
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
switch idx {
|
||||
case 0:
|
||||
if err := editMonitors(ctx, ui, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
case 1:
|
||||
if err := editEvents(ui, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
case 2:
|
||||
if err := editPage(ui, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
case 3:
|
||||
if err := editServer(ui, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
case 4:
|
||||
if err := editDefaultsAndStorage(ui, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
case 5:
|
||||
if len(cfg.Monitors) == 0 {
|
||||
ui.Warn("No monitors configured yet.")
|
||||
} else if err := testMonitorsMenu(ctx, ui, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
case 6:
|
||||
if err := previewAndValidateMenu(ui, cfg, baselineJSON, currJSON, lintRaw); err != nil {
|
||||
return err
|
||||
}
|
||||
case 7:
|
||||
if _, err := saveConfigFlow(ui, cfg, &path, &isNewFile, &baselineJSON, &originalRaw, false); err != nil {
|
||||
return err
|
||||
}
|
||||
case 8:
|
||||
if _, err := saveConfigFlow(ui, cfg, &path, &isNewFile, &baselineJSON, &originalRaw, true); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func evaluateConfigHealth(cfg *config.Config, rawJSON []byte) (error, []config.LintIssue) {
|
||||
cloned, err := cfg.Clone()
|
||||
if err != nil {
|
||||
return err, nil
|
||||
}
|
||||
cloned.ApplyFallbacks()
|
||||
valErr := cloned.Validate()
|
||||
issues := cloned.Lint(rawJSON)
|
||||
return valErr, issues
|
||||
}
|
||||
|
||||
func previewAndValidateMenu(ui *UI, cfg *config.Config, baselineJSON, currJSON string, rawJSON []byte) error {
|
||||
valErr, issues := evaluateConfigHealth(cfg, rawJSON)
|
||||
ui.Header("Validation & Lint Report", "")
|
||||
if valErr != nil {
|
||||
ui.Error("Validation failed: " + valErr.Error())
|
||||
} else {
|
||||
ui.Ok("Configuration schema is valid.")
|
||||
}
|
||||
if len(issues) == 0 {
|
||||
ui.Ok("No lint warnings.")
|
||||
} else {
|
||||
ui.Warn(fmt.Sprintf("%d lint warning(s):", len(issues)))
|
||||
for _, iss := range issues {
|
||||
ui.Println(" - " + iss.String())
|
||||
}
|
||||
}
|
||||
|
||||
opts := []Option{
|
||||
{Label: "Show changes diff"},
|
||||
{Label: "Show full JSON preview"},
|
||||
{Label: "Back"},
|
||||
}
|
||||
for {
|
||||
idx, ok, err := ui.Select("Preview", "", opts, 2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok || idx == 2 {
|
||||
return nil
|
||||
}
|
||||
switch idx {
|
||||
case 0:
|
||||
ui.Header("Changes Diff", "")
|
||||
if baselineJSON == "" {
|
||||
ui.Println(FormatDiff("", currJSON))
|
||||
} else {
|
||||
ui.Println(FormatDiff(baselineJSON, currJSON))
|
||||
}
|
||||
case 1:
|
||||
ui.Header("Generated JSON Preview", "")
|
||||
ui.Println(currJSON)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func saveConfigFlow(ui *UI, cfg *config.Config, activePath *string, isNewFile *bool, baselineJSON *string, originalRaw *[]byte, saveAs bool) (bool, error) {
|
||||
targetPath := *activePath
|
||||
if saveAs {
|
||||
p, err := ui.PromptString("Save As path", targetPath, "file path", false, requireNonEmpty("path"))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
targetPath = p
|
||||
}
|
||||
|
||||
currBytes, err := config.MarshalConfig(cfg)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
valErr, issues := evaluateConfigHealth(cfg, currBytes)
|
||||
if valErr != nil {
|
||||
ui.Error("Validation error: " + valErr.Error())
|
||||
force, cErr := ui.Confirm("Configuration has validation errors. Save anyway?", false)
|
||||
if cErr != nil {
|
||||
return false, cErr
|
||||
}
|
||||
if !force {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
if len(issues) > 0 {
|
||||
ui.Warn(fmt.Sprintf("%d lint warning(s):", len(issues)))
|
||||
for _, iss := range issues {
|
||||
ui.Println(" - " + iss.String())
|
||||
}
|
||||
cont, cErr := ui.Confirm("Proceed with saving?", true)
|
||||
if cErr != nil {
|
||||
return false, cErr
|
||||
}
|
||||
if !cont {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
|
||||
makeBackup := false
|
||||
if _, statErr := os.Stat(targetPath); statErr == nil {
|
||||
ans, cErr := ui.Confirm(fmt.Sprintf("Create backup (%s.bak) before overwriting?", targetPath), true)
|
||||
if cErr != nil {
|
||||
return false, cErr
|
||||
}
|
||||
makeBackup = ans
|
||||
}
|
||||
|
||||
bakPath, err := config.SaveConfigWithBackup(targetPath, cfg, makeBackup)
|
||||
if err != nil {
|
||||
ui.Error(fmt.Sprintf("Save failed: %v", err))
|
||||
return false, nil
|
||||
}
|
||||
|
||||
*activePath = targetPath
|
||||
*isNewFile = false
|
||||
*baselineJSON = string(currBytes)
|
||||
*originalRaw = currBytes
|
||||
|
||||
ui.Ok("Saved configuration to " + targetPath)
|
||||
if bakPath != "" {
|
||||
ui.Info("Created backup at " + bakPath)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
|
@ -1,355 +0,0 @@
|
|||
package builder
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.gsdistance.org/tyuXX/RUD/internal/config"
|
||||
)
|
||||
|
||||
func runScripted(t *testing.T, opts Options, lines []string) string {
|
||||
t.Helper()
|
||||
var out bytes.Buffer
|
||||
opts.Plain = true
|
||||
opts.NoColor = true
|
||||
opts.In = strings.NewReader(strings.Join(lines, "\n") + "\n")
|
||||
opts.Out = &out
|
||||
|
||||
if err := Run(context.Background(), opts); err != nil {
|
||||
t.Fatalf("builder.Run failed: %v\n--- Output ---\n%s", err, out.String())
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func TestStarterTemplatesValidAndLintClean(t *testing.T) {
|
||||
blank := BlankMinimalConfig()
|
||||
if err := blank.Validate(); err != nil {
|
||||
t.Fatalf("BlankMinimalConfig invalid: %v", err)
|
||||
}
|
||||
|
||||
for name, cfg := range map[string]config.Config{
|
||||
"WebAPIStarter": WebAPIStarterConfig(),
|
||||
"HomelabStarter": HomelabStarterConfig(),
|
||||
} {
|
||||
if err := cfg.Validate(); err != nil {
|
||||
t.Fatalf("%s invalid: %v", name, err)
|
||||
}
|
||||
raw, err := config.MarshalConfig(&cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("%s marshal failed: %v", name, err)
|
||||
}
|
||||
if issues := cfg.Lint(raw); len(issues) != 0 {
|
||||
t.Fatalf("%s has lint issues: %v", name, issues)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuilderNewConfigFromStarter(t *testing.T) {
|
||||
cfgPath := filepath.Join(t.TempDir(), "sub", "rud.json")
|
||||
|
||||
// 3 = Web & API Starter, 8 = Save, 10 = Exit
|
||||
out := runScripted(t, Options{ConfigPath: cfgPath}, []string{
|
||||
"3",
|
||||
"8",
|
||||
"10",
|
||||
})
|
||||
|
||||
if !strings.Contains(out, "Saved configuration") {
|
||||
t.Fatalf("expected save confirmation in output:\n%s", out)
|
||||
}
|
||||
|
||||
loaded, created, err := config.LoadOrInit(cfgPath, false)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadOrInit on built config failed: %v", err)
|
||||
}
|
||||
if created {
|
||||
t.Fatalf("expected file to already exist")
|
||||
}
|
||||
if loaded.Page.Title != "API & Web Status" || len(loaded.Monitors) != 3 {
|
||||
t.Fatalf("unexpected loaded config: title=%q monitors=%d", loaded.Page.Title, len(loaded.Monitors))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuilderEditAddLiveTestRenameDeleteWithSyncAndBackup(t *testing.T) {
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte("ok"))
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
cfgPath := filepath.Join(t.TempDir(), "rud.json")
|
||||
seed := config.DefaultConfig()
|
||||
// Use explicit monitor IDs in monitor_group so we test page reference sync as well
|
||||
seed.Page.Elements[3].Monitors = []string{"rud-http", "rud-tcp"}
|
||||
if err := config.SaveConfig(cfgPath, &seed); err != nil {
|
||||
t.Fatalf("seed SaveConfig failed: %v", err)
|
||||
}
|
||||
|
||||
out := runScripted(t, Options{ConfigPath: cfgPath}, []string{
|
||||
"1", // Monitors
|
||||
// Add HTTP monitor and live test it
|
||||
"1", // Add monitor
|
||||
"test-http",
|
||||
"Test HTTP",
|
||||
"Local test endpoint",
|
||||
"2", // Method: http
|
||||
ts.URL, // URL
|
||||
"", // HTTP verb (GET)
|
||||
"200", // Expected status
|
||||
"^ok$", // Body regex
|
||||
"n", // Overrides? no
|
||||
"y", // Test live now? yes
|
||||
|
||||
// Rename rud-http -> core-http and sync refs
|
||||
"2", // Edit monitor
|
||||
"1", // rud-http
|
||||
"1", // Edit identity & metadata
|
||||
"core-http",
|
||||
"", // keep name
|
||||
"", // keep desc
|
||||
"", // keep link
|
||||
"y", // Sync references? yes
|
||||
"6", // Done editing monitor
|
||||
|
||||
// Delete rud-tcp and clean dangling refs
|
||||
"6", // Delete monitor
|
||||
"2", // rud-tcp
|
||||
"y", // Confirm delete
|
||||
"y", // Clean dangling refs
|
||||
|
||||
"7", // Back to main hub
|
||||
"8", // Save
|
||||
"y", // Create .bak backup
|
||||
"10", // Exit
|
||||
})
|
||||
|
||||
if !strings.Contains(out, "test-http") || !strings.Contains(out, "UP") {
|
||||
t.Fatalf("expected live test output for test-http UP, got:\n%s", out)
|
||||
}
|
||||
|
||||
bakBytes, err := os.ReadFile(cfgPath + ".bak")
|
||||
if err != nil {
|
||||
t.Fatalf("expected backup file at %s.bak: %v", cfgPath, err)
|
||||
}
|
||||
if !strings.Contains(string(bakBytes), `"rud-http"`) {
|
||||
t.Fatalf("backup did not preserve original monitor ID")
|
||||
}
|
||||
|
||||
reloaded, _, err := config.LoadOrInit(cfgPath, false)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadOrInit failed: %v", err)
|
||||
}
|
||||
|
||||
byID := make(map[string]config.MonitorConfig)
|
||||
for _, m := range reloaded.Monitors {
|
||||
byID[m.ID] = m
|
||||
}
|
||||
if _, ok := byID["core-http"]; !ok {
|
||||
t.Fatalf("expected renamed monitor 'core-http' in config")
|
||||
}
|
||||
if _, ok := byID["test-http"]; !ok {
|
||||
t.Fatalf("expected added monitor 'test-http' in config")
|
||||
}
|
||||
if _, ok := byID["rud-tcp"]; ok {
|
||||
t.Fatalf("expected deleted monitor 'rud-tcp' to be removed")
|
||||
}
|
||||
|
||||
evMons := reloaded.Events[0].Condition.Conditions[0].Monitors
|
||||
if len(evMons) != 1 || evMons[0] != "core-http" {
|
||||
t.Fatalf("expected event condition monitors to sync to [core-http], got %v", evMons)
|
||||
}
|
||||
pgMons := reloaded.Page.Elements[3].Monitors
|
||||
if len(pgMons) != 1 || pgMons[0] != "core-http" {
|
||||
t.Fatalf("expected page group monitors to sync to [core-http], got %v", pgMons)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuilderRecursiveEventTreeAndDiscordPreset(t *testing.T) {
|
||||
cfgPath := filepath.Join(t.TempDir(), "rud.json")
|
||||
seed := BlankMinimalConfig()
|
||||
seed.Monitors = []config.MonitorConfig{
|
||||
{ID: "api", Name: "API", Method: "http", URL: "http://127.0.0.1:8080/health"},
|
||||
}
|
||||
seed.Events = []config.EventConfig{
|
||||
{
|
||||
ID: "api-alert",
|
||||
Name: "API Alert",
|
||||
Condition: config.EventCondition{
|
||||
Type: "state",
|
||||
Monitors: []string{"api"},
|
||||
Match: "all",
|
||||
State: "down",
|
||||
},
|
||||
Actions: []config.EventAction{
|
||||
{Type: "command", Command: "echo alert", Shell: true},
|
||||
},
|
||||
},
|
||||
}
|
||||
if err := config.SaveConfig(cfgPath, &seed); err != nil {
|
||||
t.Fatalf("seed SaveConfig failed: %v", err)
|
||||
}
|
||||
|
||||
_ = runScripted(t, Options{ConfigPath: cfgPath}, []string{
|
||||
"2", // Events & Alerts
|
||||
"2", // Edit event rule
|
||||
"1", // api-alert
|
||||
"2", // Edit condition tree
|
||||
"1", // Select root leaf node
|
||||
"2", // Wrap in new AND/OR group
|
||||
"1", // or
|
||||
"1", // Select new OR group node
|
||||
"2", // Add child leaf condition
|
||||
"2", // metric
|
||||
"1", // * (All monitors)
|
||||
"2", // any
|
||||
"2", // latency_ms
|
||||
"3", // >
|
||||
"250",
|
||||
"1m",
|
||||
"4", // Done editing condition tree
|
||||
"3", // Edit alert actions
|
||||
"1", // Add action
|
||||
"1", // Webhook from preset
|
||||
"1", // Discord Webhook
|
||||
"https://discord.com/api/webhooks/123456/token",
|
||||
"4", // Done editing actions
|
||||
"5", // Done editing event
|
||||
"5", // Back to main hub
|
||||
"8", // Save
|
||||
"n", // No backup
|
||||
"10", // Exit
|
||||
})
|
||||
|
||||
reloaded, raw, err := config.LoadForEdit(cfgPath)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadForEdit failed: %v", err)
|
||||
}
|
||||
if err := reloaded.Validate(); err != nil {
|
||||
t.Fatalf("reloaded config invalid: %v", err)
|
||||
}
|
||||
if issues := reloaded.Lint(raw); len(issues) != 0 {
|
||||
t.Fatalf("reloaded config has lint issues: %v", issues)
|
||||
}
|
||||
ev := reloaded.Events[0]
|
||||
if ev.Condition.Operator != "or" || len(ev.Condition.Conditions) != 2 {
|
||||
t.Fatalf("expected OR group with 2 children, got %+v", ev.Condition)
|
||||
}
|
||||
if ev.Condition.Conditions[1].Metric != "latency_ms" || ev.Condition.Conditions[1].Value != 250 {
|
||||
t.Fatalf("unexpected second child condition: %+v", ev.Condition.Conditions[1])
|
||||
}
|
||||
if len(ev.Actions) != 2 || !strings.Contains(ev.Actions[1].URL, "discord.com") {
|
||||
t.Fatalf("expected Discord webhook action to be added, got %+v", ev.Actions)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuilderThemePresetReorderAndUnsavedGuard(t *testing.T) {
|
||||
cfgPath := filepath.Join(t.TempDir(), "rud.json")
|
||||
seed := config.DefaultConfig()
|
||||
if err := config.SaveConfig(cfgPath, &seed); err != nil {
|
||||
t.Fatalf("seed SaveConfig failed: %v", err)
|
||||
}
|
||||
|
||||
_ = runScripted(t, Options{ConfigPath: cfgPath}, []string{
|
||||
"3", // Page & Theme
|
||||
"2", // Apply theme preset
|
||||
"4", // Nord
|
||||
"4", // Manage page elements
|
||||
"4", // Reorder page elements
|
||||
"1", // header
|
||||
"2", // Move down
|
||||
"0", // Done reordering
|
||||
"6", // Back from elements
|
||||
"5", // Back to main hub
|
||||
"8", // Save
|
||||
"n", // No backup
|
||||
|
||||
// Make an unsaved modification and test exit guard
|
||||
"3", // Page & Theme
|
||||
"1", // Page HTML title
|
||||
"Unsaved Title", // New title
|
||||
"5", // Back to main hub
|
||||
"10", // Exit
|
||||
"3", // Cancel exit guard
|
||||
"10", // Exit again
|
||||
"2", // Discard changes & Exit
|
||||
})
|
||||
|
||||
reloaded, _, err := config.LoadOrInit(cfgPath, false)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadOrInit failed: %v", err)
|
||||
}
|
||||
if reloaded.Page.Theme.BgColor != "#2e3440" {
|
||||
t.Fatalf("expected Nord theme BgColor #2e3440, got %q", reloaded.Page.Theme.BgColor)
|
||||
}
|
||||
if reloaded.Page.Elements[0].Type != "status_banner" || reloaded.Page.Elements[1].Type != "header" {
|
||||
t.Fatalf("expected header moved after status_banner, got [%s, %s]",
|
||||
reloaded.Page.Elements[0].Type, reloaded.Page.Elements[1].Type)
|
||||
}
|
||||
if reloaded.Page.Title != "R u ded?" {
|
||||
t.Fatalf("expected discarded title change not to persist, got %q", reloaded.Page.Title)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuilderQuickStartWizardPreviewAndSaveAs(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
initialPath := filepath.Join(tmpDir, "initial.json")
|
||||
saveAsPath := filepath.Join(tmpDir, "wizard-out.json")
|
||||
|
||||
out := runScripted(t, Options{ConfigPath: initialPath}, []string{
|
||||
"1", // Guided Quick-Start Wizard
|
||||
"", // Listen (:8080)
|
||||
"", // Endpoint (/)
|
||||
// Monitor 1
|
||||
"wiz-cmd",
|
||||
"Wizard Cmd",
|
||||
"", // description
|
||||
"6", // cmd
|
||||
"echo ok",
|
||||
"y", // shell
|
||||
"0", // expected exit code
|
||||
"^ok$",
|
||||
"n", // overrides
|
||||
"y", // test live
|
||||
"n", // add another monitor
|
||||
"n", // add event rule
|
||||
"My Wizard Status",
|
||||
"y", // pick theme preset
|
||||
"2", // Clean Light
|
||||
// Hub: Validate & Preview JSON / Diff
|
||||
"7",
|
||||
"1", // diff
|
||||
"2", // JSON preview
|
||||
"3", // back
|
||||
// Save As
|
||||
"9",
|
||||
saveAsPath,
|
||||
"10", // Exit
|
||||
})
|
||||
|
||||
if !strings.Contains(out, `"My Wizard Status"`) {
|
||||
t.Fatalf("expected preview JSON to contain new title, got:\n%s", out)
|
||||
}
|
||||
if _, err := os.Stat(initialPath); !os.IsNotExist(err) {
|
||||
t.Fatalf("expected initialPath not to be written when using Save As")
|
||||
}
|
||||
|
||||
loaded, raw, err := config.LoadForEdit(saveAsPath)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadForEdit on Save As file failed: %v", err)
|
||||
}
|
||||
if err := loaded.Validate(); err != nil {
|
||||
t.Fatalf("saved wizard config invalid: %v", err)
|
||||
}
|
||||
if issues := loaded.Lint(raw); len(issues) != 0 {
|
||||
t.Fatalf("saved wizard config has lint issues: %v", issues)
|
||||
}
|
||||
if loaded.Page.Theme.BgColor != "#f8fafc" || len(loaded.Monitors) != 1 || loaded.Monitors[0].ID != "wiz-cmd" {
|
||||
t.Fatalf("unexpected wizard config: theme=%s monitors=%v", loaded.Page.Theme.BgColor, loaded.Monitors)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,405 +0,0 @@
|
|||
package builder
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"git.gsdistance.org/tyuXX/RUD/internal/checker"
|
||||
"git.gsdistance.org/tyuXX/RUD/internal/config"
|
||||
"git.gsdistance.org/tyuXX/RUD/internal/store"
|
||||
)
|
||||
|
||||
// MonitorTestResult captures the outcome of a live one-shot monitor check.
|
||||
type MonitorTestResult struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Method string `json:"method"`
|
||||
Target string `json:"target"`
|
||||
State string `json:"state"`
|
||||
LatencyMs float64 `json:"latency_ms"`
|
||||
Code int `json:"code,omitempty"`
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
// RunLiveTests executes live health checks concurrently for the selected monitors
|
||||
// (or all monitors when filterIDs is empty).
|
||||
func RunLiveTests(ctx context.Context, cfg *config.Config, filterIDs []string, retry bool) ([]MonitorTestResult, error) {
|
||||
byID := make(map[string]config.MonitorConfig, len(cfg.Monitors))
|
||||
for _, m := range cfg.Monitors {
|
||||
byID[m.ID] = m
|
||||
}
|
||||
|
||||
var targets []config.MonitorConfig
|
||||
if len(filterIDs) == 0 {
|
||||
targets = append(targets, cfg.Monitors...)
|
||||
} else {
|
||||
seen := make(map[string]bool, len(filterIDs))
|
||||
for _, id := range filterIDs {
|
||||
m, ok := byID[id]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unknown monitor id %q", id)
|
||||
}
|
||||
if !seen[id] {
|
||||
seen[id] = true
|
||||
targets = append(targets, m)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
results := make([]MonitorTestResult, len(targets))
|
||||
var wg sync.WaitGroup
|
||||
for i, mon := range targets {
|
||||
wg.Add(1)
|
||||
go func(idx int, m config.MonitorConfig) {
|
||||
defer wg.Done()
|
||||
if !retry {
|
||||
m.Retries = config.IntPtr(0)
|
||||
}
|
||||
res := checker.RunCheckWithRetries(ctx, m, cfg.Defaults)
|
||||
name := m.Name
|
||||
if name == "" {
|
||||
name = m.ID
|
||||
}
|
||||
results[idx] = MonitorTestResult{
|
||||
ID: m.ID,
|
||||
Name: name,
|
||||
Method: strings.ToUpper(m.Method),
|
||||
Target: m.DisplayTarget(),
|
||||
State: res.State,
|
||||
LatencyMs: res.LatencyMs,
|
||||
Code: res.Code,
|
||||
Message: res.Message,
|
||||
}
|
||||
}(i, mon)
|
||||
}
|
||||
wg.Wait()
|
||||
return results, nil
|
||||
}
|
||||
|
||||
// PrintLiveTestTable formats MonitorTestResult rows into a readable table.
|
||||
func PrintLiveTestTable(out io.Writer, results []MonitorTestResult, color bool) {
|
||||
if len(results) == 0 {
|
||||
_, _ = fmt.Fprintln(out, "No monitors to test.")
|
||||
return
|
||||
}
|
||||
|
||||
idW, methW, stateW := len("ID"), len("METHOD"), len("STATE")
|
||||
for _, r := range results {
|
||||
if len(r.ID) > idW {
|
||||
idW = len(r.ID)
|
||||
}
|
||||
if len(r.Method) > methW {
|
||||
methW = len(r.Method)
|
||||
}
|
||||
st := strings.ToUpper(r.State)
|
||||
if len(st) > stateW {
|
||||
stateW = len(st)
|
||||
}
|
||||
}
|
||||
|
||||
_, _ = fmt.Fprintf(out, "%-*s %-*s %-*s %9s %s\n", idW, "ID", methW, "METHOD", stateW, "STATE", "LATENCY", "DETAILS")
|
||||
_, _ = fmt.Fprintf(out, "%s %s %s %s %s\n",
|
||||
strings.Repeat("-", idW),
|
||||
strings.Repeat("-", methW),
|
||||
strings.Repeat("-", stateW),
|
||||
"---------",
|
||||
"-------",
|
||||
)
|
||||
for _, r := range results {
|
||||
stUpper := strings.ToUpper(r.State)
|
||||
paddedState := fmt.Sprintf("%-*s", stateW, stUpper)
|
||||
if color {
|
||||
switch r.State {
|
||||
case store.StateUp:
|
||||
paddedState = "\x1b[32m" + paddedState + "\x1b[0m"
|
||||
case store.StateDegraded:
|
||||
paddedState = "\x1b[33m" + paddedState + "\x1b[0m"
|
||||
case store.StateDown:
|
||||
paddedState = "\x1b[31m" + paddedState + "\x1b[0m"
|
||||
}
|
||||
}
|
||||
details := r.Message
|
||||
if r.Target != "" {
|
||||
if details != "" {
|
||||
details = fmt.Sprintf("[%s] %s", r.Target, details)
|
||||
} else {
|
||||
details = r.Target
|
||||
}
|
||||
}
|
||||
_, _ = fmt.Fprintf(out, "%-*s %-*s %s %7.1fms %s\n",
|
||||
idW, r.ID, methW, r.Method, paddedState, r.LatencyMs, details)
|
||||
}
|
||||
}
|
||||
|
||||
func editServer(ui *UI, cfg *config.Config) error {
|
||||
for {
|
||||
sub := fmt.Sprintf("Listen: %s | Endpoint: %s | Refresh: %s",
|
||||
cfg.Server.Listen, cfg.Server.Endpoint, cfg.Server.RefreshInterval.Std())
|
||||
opts := []Option{
|
||||
{Label: "Listen address", Description: cfg.Server.Listen},
|
||||
{Label: "HTTP endpoint path", Description: cfg.Server.Endpoint},
|
||||
{Label: "Browser auto-refresh interval", Description: cfg.Server.RefreshInterval.Std().String()},
|
||||
{
|
||||
Label: "HTML HTTP status codes",
|
||||
Description: fmt.Sprintf("up=%d degraded=%d down=%d pending=%d", cfg.Server.StatusCodes.HTML.Up, cfg.Server.StatusCodes.HTML.Degraded, cfg.Server.StatusCodes.HTML.Down, cfg.Server.StatusCodes.HTML.Pending),
|
||||
},
|
||||
{
|
||||
Label: "JSON HTTP status codes",
|
||||
Description: fmt.Sprintf("up=%d degraded=%d down=%d pending=%d", cfg.Server.StatusCodes.JSON.Up, cfg.Server.StatusCodes.JSON.Degraded, cfg.Server.StatusCodes.JSON.Down, cfg.Server.StatusCodes.JSON.Pending),
|
||||
},
|
||||
{Label: "Back to main hub"},
|
||||
}
|
||||
|
||||
idx, ok, err := ui.Select("Server Settings", sub, opts, len(opts)-1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok || idx == len(opts)-1 {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch idx {
|
||||
case 0:
|
||||
v, err := ui.PromptString("Listen address", cfg.Server.Listen, "host:port or :8080", false, requireNonEmpty("listen"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Server.Listen = v
|
||||
case 1:
|
||||
v, err := ui.PromptString("Endpoint path", cfg.Server.Endpoint, "must start with /", false, requireNonEmpty("endpoint"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !strings.HasPrefix(v, "/") {
|
||||
v = "/" + v
|
||||
}
|
||||
cfg.Server.Endpoint = v
|
||||
case 2:
|
||||
d, err := ui.PromptDuration("Browser refresh interval", cfg.Server.RefreshInterval, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Server.RefreshInterval = d
|
||||
case 3:
|
||||
if err := editStatusCodes(ui, "HTML Status Codes (keep 200 for Cloudflare Tunnel)", &cfg.Server.StatusCodes.HTML); err != nil {
|
||||
return err
|
||||
}
|
||||
case 4:
|
||||
if err := editStatusCodes(ui, "JSON Status Codes", &cfg.Server.StatusCodes.JSON); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func editStatusCodes(ui *UI, title string, sc *config.StatusCodesByState) error {
|
||||
ui.Header(title, "HTTP status codes returned for each global state (100-599)")
|
||||
var err error
|
||||
if sc.Up, err = ui.PromptInt("HTTP status when UP", sc.Up, 100, 599); err != nil {
|
||||
return err
|
||||
}
|
||||
if sc.Degraded, err = ui.PromptInt("HTTP status when DEGRADED", sc.Degraded, 100, 599); err != nil {
|
||||
return err
|
||||
}
|
||||
if sc.Down, err = ui.PromptInt("HTTP status when DOWN", sc.Down, 100, 599); err != nil {
|
||||
return err
|
||||
}
|
||||
if sc.Pending, err = ui.PromptInt("HTTP status when PENDING", sc.Pending, 100, 599); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func editDefaultsAndStorage(ui *UI, cfg *config.Config) error {
|
||||
for {
|
||||
persist := cfg.Storage.PersistenceFile
|
||||
if persist == "" {
|
||||
persist = "(disabled)"
|
||||
}
|
||||
sub := fmt.Sprintf("Interval: %s | Timeout: %s | History: %d | Persistence: %s",
|
||||
cfg.Defaults.Interval.Std(), cfg.Defaults.Timeout.Std(), cfg.Storage.HistorySize, persist)
|
||||
opts := []Option{
|
||||
{Label: "Default check interval", Description: cfg.Defaults.Interval.Std().String()},
|
||||
{Label: "Default check timeout", Description: cfg.Defaults.Timeout.Std().String()},
|
||||
{Label: "Default retries", Description: fmt.Sprintf("%d", cfg.Defaults.Retries)},
|
||||
{Label: "Default degraded latency threshold", Description: cfg.Defaults.DegradedLatency.Std().String()},
|
||||
{Label: "Ring-buffer history size", Description: fmt.Sprintf("%d checks per monitor", cfg.Storage.HistorySize)},
|
||||
{Label: "Persistence file path", Description: persist},
|
||||
{Label: "Persistence save interval", Description: cfg.Storage.SaveInterval.Std().String()},
|
||||
{Label: "Daily history logs dir", Description: cfg.Storage.LogsDir},
|
||||
{Label: "Stats SQLite DB path", Description: cfg.Storage.StatsDB},
|
||||
{Label: "Stats retention days", Description: fmt.Sprintf("%d days", cfg.Storage.StatsRetentionDays)},
|
||||
{Label: "Back to main hub"},
|
||||
}
|
||||
|
||||
idx, ok, err := ui.Select("Defaults & Storage", sub, opts, len(opts)-1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok || idx == len(opts)-1 {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch idx {
|
||||
case 0:
|
||||
d, err := ui.PromptDuration("Default interval", cfg.Defaults.Interval, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Defaults.Interval = d
|
||||
case 1:
|
||||
d, err := ui.PromptDuration("Default timeout", cfg.Defaults.Timeout, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Defaults.Timeout = d
|
||||
case 2:
|
||||
r, err := ui.PromptInt("Default retries", cfg.Defaults.Retries, 0, 20)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Defaults.Retries = r
|
||||
case 3:
|
||||
d, err := ui.PromptDuration("Default degraded latency threshold", cfg.Defaults.DegradedLatency, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Defaults.DegradedLatency = d
|
||||
case 4:
|
||||
h, err := ui.PromptInt("History size", cfg.Storage.HistorySize, 1, 100000)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Storage.HistorySize = h
|
||||
case 5:
|
||||
p, err := ui.PromptString("Persistence file", cfg.Storage.PersistenceFile, "e.g. ./data/rud_state.json", true, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Storage.PersistenceFile = p
|
||||
case 6:
|
||||
d, err := ui.PromptDuration("Save interval", cfg.Storage.SaveInterval, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Storage.SaveInterval = d
|
||||
case 7:
|
||||
v, err := ui.PromptString("Daily history logs directory", cfg.Storage.LogsDir, "directory path, or 'off' to disable", true, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Storage.LogsDir = v
|
||||
case 8:
|
||||
v, err := ui.PromptString("Stats SQLite DB path", cfg.Storage.StatsDB, "file path, or 'off' to disable", true, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Storage.StatsDB = v
|
||||
case 9:
|
||||
curDays := cfg.Storage.StatsRetentionDays
|
||||
if curDays <= 0 {
|
||||
curDays = 90
|
||||
}
|
||||
days, err := ui.PromptInt("Stats retention days", curDays, 1, 3650)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Storage.StatsRetentionDays = days
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type diffLine struct {
|
||||
kind byte // ' ', '-', '+'
|
||||
text string
|
||||
}
|
||||
|
||||
// FormatDiff produces a compact contextual diff between two JSON configuration strings.
|
||||
func FormatDiff(before, after string) string {
|
||||
if before == after {
|
||||
return "(no changes)"
|
||||
}
|
||||
a := strings.Split(strings.TrimRight(before, "\n"), "\n")
|
||||
b := strings.Split(strings.TrimRight(after, "\n"), "\n")
|
||||
|
||||
// LCS dynamic programming table
|
||||
m, n := len(a), len(b)
|
||||
dp := make([][]int, m+1)
|
||||
for i := range dp {
|
||||
dp[i] = make([]int, n+1)
|
||||
}
|
||||
for i := m - 1; i >= 0; i-- {
|
||||
for j := n - 1; j >= 0; j-- {
|
||||
if a[i] == b[j] {
|
||||
dp[i][j] = dp[i+1][j+1] + 1
|
||||
} else if dp[i+1][j] >= dp[i][j+1] {
|
||||
dp[i][j] = dp[i+1][j]
|
||||
} else {
|
||||
dp[i][j] = dp[i][j+1]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var ops []diffLine
|
||||
i, j := 0, 0
|
||||
for i < m && j < n {
|
||||
if a[i] == b[j] {
|
||||
ops = append(ops, diffLine{' ', a[i]})
|
||||
i++
|
||||
j++
|
||||
} else if dp[i+1][j] >= dp[i][j+1] {
|
||||
ops = append(ops, diffLine{'-', a[i]})
|
||||
i++
|
||||
} else {
|
||||
ops = append(ops, diffLine{'+', b[j]})
|
||||
j++
|
||||
}
|
||||
}
|
||||
for i < m {
|
||||
ops = append(ops, diffLine{'-', a[i]})
|
||||
i++
|
||||
}
|
||||
for j < n {
|
||||
ops = append(ops, diffLine{'+', b[j]})
|
||||
j++
|
||||
}
|
||||
|
||||
const ctxLines = 2
|
||||
show := make([]bool, len(ops))
|
||||
for idx, op := range ops {
|
||||
if op.kind != ' ' {
|
||||
lo := idx - ctxLines
|
||||
if lo < 0 {
|
||||
lo = 0
|
||||
}
|
||||
hi := idx + ctxLines
|
||||
if hi >= len(ops) {
|
||||
hi = len(ops) - 1
|
||||
}
|
||||
for k := lo; k <= hi; k++ {
|
||||
show[k] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var out strings.Builder
|
||||
skipping := false
|
||||
for idx, op := range ops {
|
||||
if !show[idx] {
|
||||
if !skipping && out.Len() > 0 {
|
||||
out.WriteString(" ...\n")
|
||||
skipping = true
|
||||
}
|
||||
continue
|
||||
}
|
||||
skipping = false
|
||||
out.WriteByte(op.kind)
|
||||
out.WriteByte(' ')
|
||||
out.WriteString(op.text)
|
||||
out.WriteByte('\n')
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,841 +0,0 @@
|
|||
package builder
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.gsdistance.org/tyuXX/RUD/internal/config"
|
||||
)
|
||||
|
||||
func editMonitors(ctx context.Context, ui *UI, cfg *config.Config) error {
|
||||
for {
|
||||
sub := fmt.Sprintf("%d monitor(s) configured", len(cfg.Monitors))
|
||||
if len(cfg.Monitors) > 0 {
|
||||
var ids []string
|
||||
for _, m := range cfg.Monitors {
|
||||
ids = append(ids, m.ID)
|
||||
}
|
||||
sub += ": " + strings.Join(ids, ", ")
|
||||
}
|
||||
|
||||
opts := []Option{
|
||||
{Label: "Add monitor", Description: "Create a new HTTP, TCP, Ping, DNS, or Cmd check"},
|
||||
}
|
||||
if len(cfg.Monitors) > 0 {
|
||||
opts = append(opts,
|
||||
Option{Label: "Edit monitor", Description: "Modify an existing monitor's settings"},
|
||||
Option{Label: "Test monitor(s) live", Description: "Run checks immediately against live targets"},
|
||||
Option{Label: "Duplicate monitor", Description: "Clone an existing monitor with a new ID"},
|
||||
Option{Label: "Reorder monitors", Description: "Move a monitor up or down"},
|
||||
Option{Label: "Delete monitor", Description: "Remove a monitor (with reference cleanup)"},
|
||||
)
|
||||
}
|
||||
opts = append(opts, Option{Label: "Back to main hub"})
|
||||
|
||||
idx, ok, err := ui.Select("Monitors", sub, opts, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok || opts[idx].Label == "Back to main hub" {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch opts[idx].Label {
|
||||
case "Add monitor":
|
||||
if _, err := addMonitorFlow(ctx, ui, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
case "Edit monitor":
|
||||
mIdx, mOK, err := pickMonitor(ui, cfg.Monitors, "Select monitor to edit")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if mOK {
|
||||
if err := editSingleMonitor(ctx, ui, cfg, mIdx); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case "Test monitor(s) live":
|
||||
if err := testMonitorsMenu(ctx, ui, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
case "Duplicate monitor":
|
||||
mIdx, mOK, err := pickMonitor(ui, cfg.Monitors, "Select monitor to duplicate")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if mOK {
|
||||
cp := cloneMonitor(cfg.Monitors[mIdx])
|
||||
defID := uniqueMonitorID(cfg, cp.ID+"-copy")
|
||||
newID, err := ui.PromptString("New monitor ID", defID, "unique identifier", false, validateNewMonitorID(cfg, -1))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cp.ID = newID
|
||||
cp.Name = cp.Name + " (Copy)"
|
||||
cfg.Monitors = append(cfg.Monitors, cp)
|
||||
ui.Ok(fmt.Sprintf("Duplicated monitor %q as %q.", cfg.Monitors[mIdx].ID, cp.ID))
|
||||
}
|
||||
case "Reorder monitors":
|
||||
if err := reorderMonitors(ui, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
case "Delete monitor":
|
||||
mIdx, mOK, err := pickMonitor(ui, cfg.Monitors, "Select monitor to delete")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if mOK {
|
||||
target := cfg.Monitors[mIdx]
|
||||
yes, err := ui.Confirm(fmt.Sprintf("Delete monitor %q (%s)?", target.ID, target.Method), false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if yes {
|
||||
cfg.Monitors = append(cfg.Monitors[:mIdx], cfg.Monitors[mIdx+1:]...)
|
||||
ui.Ok(fmt.Sprintf("Deleted monitor %q.", target.ID))
|
||||
evRefs, pgRefs := findMonitorRefs(cfg, target.ID)
|
||||
if len(evRefs) > 0 || len(pgRefs) > 0 {
|
||||
ui.Warn(fmt.Sprintf("Found references to %q in %d event(s) and %d page group(s).", target.ID, len(evRefs), len(pgRefs)))
|
||||
clean, err := ui.Confirm("Remove dangling references automatically?", true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if clean {
|
||||
removeMonitorRefs(cfg, target.ID)
|
||||
ui.Ok("Cleaned up dangling monitor references.")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func pickMonitor(ui *UI, monitors []config.MonitorConfig, title string) (int, bool, error) {
|
||||
opts := make([]Option, len(monitors))
|
||||
for i, m := range monitors {
|
||||
opts[i] = Option{
|
||||
Label: fmt.Sprintf("%s (%s)", m.ID, strings.ToUpper(m.Method)),
|
||||
Description: fmt.Sprintf("%s — %s", m.Name, m.DisplayTarget()),
|
||||
}
|
||||
}
|
||||
return ui.Select(title, "", opts, -1)
|
||||
}
|
||||
|
||||
func testMonitorsMenu(ctx context.Context, ui *UI, cfg *config.Config) error {
|
||||
opts := []Option{
|
||||
{Label: "Test all monitors", Description: fmt.Sprintf("Run all %d monitor(s) concurrently", len(cfg.Monitors))},
|
||||
{Label: "Test a specific monitor"},
|
||||
{Label: "Back"},
|
||||
}
|
||||
idx, ok, err := ui.Select("Test Monitors Live", "", opts, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok || idx == 2 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var ids []string
|
||||
if idx == 1 {
|
||||
mIdx, mOK, err := pickMonitor(ui, cfg.Monitors, "Select monitor to test")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !mOK {
|
||||
return nil
|
||||
}
|
||||
ids = []string{cfg.Monitors[mIdx].ID}
|
||||
}
|
||||
|
||||
ui.Info("Running live health checks...")
|
||||
results, err := RunLiveTests(ctx, cfg, ids, true)
|
||||
if err != nil {
|
||||
ui.Error(err.Error())
|
||||
return nil
|
||||
}
|
||||
ui.Println()
|
||||
PrintLiveTestTable(ui.out, results, ui.color)
|
||||
return nil
|
||||
}
|
||||
|
||||
func reorderMonitors(ui *UI, cfg *config.Config) error {
|
||||
for {
|
||||
if len(cfg.Monitors) < 2 {
|
||||
ui.Info("Need at least 2 monitors to reorder.")
|
||||
return nil
|
||||
}
|
||||
mIdx, ok, err := pickMonitor(ui, cfg.Monitors, "Pick a monitor to move (Esc/0 when done)")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
dirOpts := []Option{
|
||||
{Label: "Move up"},
|
||||
{Label: "Move down"},
|
||||
{Label: "Cancel"},
|
||||
}
|
||||
dIdx, dOK, err := ui.Select("Move "+cfg.Monitors[mIdx].ID, "", dirOpts, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !dOK || dIdx == 2 {
|
||||
continue
|
||||
}
|
||||
if dIdx == 0 && mIdx > 0 {
|
||||
cfg.Monitors[mIdx-1], cfg.Monitors[mIdx] = cfg.Monitors[mIdx], cfg.Monitors[mIdx-1]
|
||||
} else if dIdx == 1 && mIdx < len(cfg.Monitors)-1 {
|
||||
cfg.Monitors[mIdx+1], cfg.Monitors[mIdx] = cfg.Monitors[mIdx], cfg.Monitors[mIdx+1]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func addMonitorFlow(ctx context.Context, ui *UI, cfg *config.Config) (bool, error) {
|
||||
ui.Header("Add Monitor", "Step through the required fields for your new check")
|
||||
|
||||
defID := uniqueMonitorID(cfg, fmt.Sprintf("mon-%d", len(cfg.Monitors)+1))
|
||||
id, err := ui.PromptString("Monitor ID", defID, "unique slug, no spaces", false, validateNewMonitorID(cfg, -1))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
name, err := ui.PromptString("Display name", id, "friendly name shown on status page", false, nil)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
desc, err := ui.PromptString("Description (optional)", "", "short subtitle", true, nil)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
methodOpts := []Option{
|
||||
{Label: "https", Description: "HTTPS endpoint check (status code, headers, body regex, TLS)"},
|
||||
{Label: "http", Description: "HTTP endpoint check"},
|
||||
{Label: "tcp", Description: "TCP socket handshake (host:port)"},
|
||||
{Label: "ping", Description: "ICMP echo reachability & RTT"},
|
||||
{Label: "dns", Description: "DNS record lookup & validation"},
|
||||
{Label: "cmd", Description: "Custom shell command or script"},
|
||||
}
|
||||
mIdx, mOK, err := ui.Select("Check Method", "Choose protocol/method for "+id, methodOpts, 0)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if !mOK {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
mon := config.MonitorConfig{
|
||||
ID: id,
|
||||
Name: name,
|
||||
Description: desc,
|
||||
Method: methodOpts[mIdx].Label,
|
||||
}
|
||||
|
||||
if err := editMethodSpecificFields(ui, &mon, true); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
adv, err := ui.Confirm("Configure link or per-monitor timing overrides?", false)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if adv {
|
||||
if err := editMonitorMetadataAndOverrides(ui, &mon); err != nil {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
|
||||
cfg.Monitors = append(cfg.Monitors, mon)
|
||||
ui.Ok(fmt.Sprintf("Added monitor %q (%s: %s).", mon.ID, mon.Method, mon.DisplayTarget()))
|
||||
|
||||
runTest, err := ui.Confirm("Test this monitor live now?", true)
|
||||
if err != nil {
|
||||
return true, err
|
||||
}
|
||||
if runTest {
|
||||
results, tErr := RunLiveTests(ctx, cfg, []string{mon.ID}, true)
|
||||
if tErr != nil {
|
||||
ui.Error(tErr.Error())
|
||||
} else {
|
||||
ui.Println()
|
||||
PrintLiveTestTable(ui.out, results, ui.color)
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func editSingleMonitor(ctx context.Context, ui *UI, cfg *config.Config, monIdx int) error {
|
||||
for {
|
||||
mon := &cfg.Monitors[monIdx]
|
||||
sub := fmt.Sprintf("Method: %s | Target: %s", strings.ToUpper(mon.Method), mon.DisplayTarget())
|
||||
opts := []Option{
|
||||
{Label: "Edit identity & metadata", Description: fmt.Sprintf("id=%s, name=%q", mon.ID, mon.Name)},
|
||||
{Label: "Change check method", Description: fmt.Sprintf("current: %s", mon.Method)},
|
||||
{Label: "Edit method-specific settings", Description: mon.DisplayTarget()},
|
||||
{Label: "Edit timing & retry overrides", Description: formatMonitorOverrides(*mon)},
|
||||
{Label: "Test this monitor live"},
|
||||
{Label: "Done"},
|
||||
}
|
||||
|
||||
idx, ok, err := ui.Select("Edit Monitor: "+mon.ID, sub, opts, len(opts)-1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok || idx == len(opts)-1 {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch idx {
|
||||
case 0:
|
||||
oldID := mon.ID
|
||||
newID, err := ui.PromptString("Monitor ID", oldID, "unique ID", false, validateNewMonitorID(cfg, monIdx))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
newName, err := ui.PromptString("Display name", mon.Name, "", false, requireNonEmpty("name"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
newDesc, err := ui.PromptString("Description", mon.Description, "optional", true, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
newLink, err := ui.PromptString("Link URL", mon.Link, "optional clickable URL", true, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.ID = newID
|
||||
mon.Name = newName
|
||||
mon.Description = newDesc
|
||||
mon.Link = newLink
|
||||
|
||||
if newID != oldID {
|
||||
evRefs, pgRefs := findMonitorRefs(cfg, oldID)
|
||||
if len(evRefs) > 0 || len(pgRefs) > 0 {
|
||||
ui.Warn(fmt.Sprintf("Found references to %q in %d event(s) and %d page group(s).", oldID, len(evRefs), len(pgRefs)))
|
||||
syncRefs, err := ui.Confirm(fmt.Sprintf("Update those references from %q to %q?", oldID, newID), true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if syncRefs {
|
||||
renameMonitorRefs(cfg, oldID, newID)
|
||||
ui.Ok(fmt.Sprintf("Updated references to %q.", newID))
|
||||
}
|
||||
}
|
||||
}
|
||||
case 1:
|
||||
methodOpts := []Option{
|
||||
{Label: "https"}, {Label: "http"}, {Label: "tcp"}, {Label: "ping"}, {Label: "dns"}, {Label: "cmd"},
|
||||
}
|
||||
mIdx, mOK, err := ui.Select("Select check method", "", methodOpts, -1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if mOK {
|
||||
mon.Method = methodOpts[mIdx].Label
|
||||
if err := editMethodSpecificFields(ui, mon, false); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case 2:
|
||||
if err := editMethodSpecificFields(ui, mon, false); err != nil {
|
||||
return err
|
||||
}
|
||||
case 3:
|
||||
if err := editMonitorOverrides(ui, mon); err != nil {
|
||||
return err
|
||||
}
|
||||
case 4:
|
||||
results, tErr := RunLiveTests(ctx, cfg, []string{mon.ID}, true)
|
||||
if tErr != nil {
|
||||
ui.Error(tErr.Error())
|
||||
} else {
|
||||
ui.Println()
|
||||
PrintLiveTestTable(ui.out, results, ui.color)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func editMonitorMetadataAndOverrides(ui *UI, mon *config.MonitorConfig) error {
|
||||
link, err := ui.PromptString("Clickable link URL (optional)", mon.Link, "e.g. https://status.example.com", true, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.Link = link
|
||||
return editMonitorOverrides(ui, mon)
|
||||
}
|
||||
|
||||
func editMonitorOverrides(ui *UI, mon *config.MonitorConfig) error {
|
||||
ui.Header("Monitor Overrides: "+mon.ID, "Leave at 0s / '-' to inherit global defaults")
|
||||
var err error
|
||||
if mon.Interval, err = ui.PromptDuration("Check interval override", mon.Interval, true); err != nil {
|
||||
return err
|
||||
}
|
||||
if mon.Timeout, err = ui.PromptDuration("Timeout override", mon.Timeout, true); err != nil {
|
||||
return err
|
||||
}
|
||||
if mon.Retries, err = ui.PromptOptionalInt("Retries override", mon.Retries, 0, 20); err != nil {
|
||||
return err
|
||||
}
|
||||
if mon.DegradedLatency, err = ui.PromptDuration("Degraded latency override", mon.DegradedLatency, true); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func editMethodSpecificFields(ui *UI, mon *config.MonitorConfig, quickAdd bool) error {
|
||||
method := strings.ToLower(strings.TrimSpace(mon.Method))
|
||||
switch method {
|
||||
case "http", "https":
|
||||
defURL := mon.URL
|
||||
if defURL == "" {
|
||||
defURL = method + "://"
|
||||
}
|
||||
u, err := ui.PromptString("Endpoint URL", defURL, "full http:// or https:// URL", false, validateHTTPURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.URL = u
|
||||
|
||||
defHTTPMethod := mon.HTTPMethod
|
||||
if defHTTPMethod == "" {
|
||||
defHTTPMethod = "GET"
|
||||
}
|
||||
hm, err := ui.PromptString("HTTP verb", defHTTPMethod, "GET, HEAD, POST, etc.", false, requireNonEmpty("http_method"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.HTTPMethod = strings.ToUpper(hm)
|
||||
|
||||
codes, err := promptIntSlice(ui, "Expected HTTP status codes", mon.ExpectedStatus, "comma-separated e.g. 200,204; '-' for any 2xx")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.ExpectedStatus = codes
|
||||
|
||||
reStr, err := ui.PromptString("Response body regex (optional)", mon.BodyRegex, "Go regexp", true, validateOptionalRegex)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.BodyRegex = reStr
|
||||
|
||||
if !quickAdd {
|
||||
body, err := ui.PromptString("Request body (optional)", mon.Body, "", true, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.Body = body
|
||||
|
||||
editHdrs, err := ui.Confirm("Edit custom request headers?", len(mon.Headers) > 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if editHdrs {
|
||||
hdrs, err := ui.EditStringMap("HTTP Request Headers", mon.Headers)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.Headers = hdrs
|
||||
}
|
||||
}
|
||||
|
||||
if method == "https" || strings.HasPrefix(strings.ToLower(mon.URL), "https://") {
|
||||
skip, err := ui.Confirm("Ignore invalid/self-signed TLS certificates (insecure_skip_verify)?", mon.InsecureSkipVerify)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.InsecureSkipVerify = skip
|
||||
}
|
||||
|
||||
case "tcp":
|
||||
cur := mon.Target
|
||||
if cur == "" {
|
||||
cur = mon.Host
|
||||
}
|
||||
target, err := ui.PromptString("TCP Target", cur, "host:port (e.g. 127.0.0.1:5432)", false, requireNonEmpty("target"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.Target = target
|
||||
|
||||
case "ping":
|
||||
cur := mon.Host
|
||||
if cur == "" {
|
||||
cur = mon.Target
|
||||
}
|
||||
host, err := ui.PromptString("Host or IP", cur, "e.g. 1.1.1.1", false, requireNonEmpty("host"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.Host = host
|
||||
|
||||
curCount := mon.Count
|
||||
if curCount <= 0 {
|
||||
curCount = 1
|
||||
}
|
||||
cnt, err := ui.PromptInt("Echo packet count", curCount, 1, 20)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.Count = cnt
|
||||
|
||||
priv, err := ui.Confirm("Prefer raw ICMP socket (privileged)?", mon.Privileged)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.Privileged = priv
|
||||
|
||||
case "dns":
|
||||
cur := mon.Host
|
||||
if cur == "" {
|
||||
cur = mon.Target
|
||||
}
|
||||
host, err := ui.PromptString("Domain name to resolve", cur, "e.g. example.com", false, requireNonEmpty("host"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.Host = host
|
||||
|
||||
recTypes := []Option{
|
||||
{Label: "A"}, {Label: "AAAA"}, {Label: "CNAME"}, {Label: "MX"}, {Label: "TXT"}, {Label: "NS"},
|
||||
}
|
||||
defIdx := 0
|
||||
for i, o := range recTypes {
|
||||
if strings.EqualFold(o.Label, mon.RecordType) {
|
||||
defIdx = i
|
||||
break
|
||||
}
|
||||
}
|
||||
rIdx, rOK, err := ui.Select("DNS Record Type", "", recTypes, defIdx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if rOK {
|
||||
mon.RecordType = recTypes[rIdx].Label
|
||||
} else if mon.RecordType == "" {
|
||||
mon.RecordType = "A"
|
||||
}
|
||||
|
||||
res, err := ui.PromptString("Custom DNS resolver (optional)", mon.Resolver, "e.g. 1.1.1.1:53", true, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.Resolver = res
|
||||
|
||||
reStr, err := ui.PromptString("Expected record regex (optional)", mon.ExpectedRegex, "Go regexp", true, validateOptionalRegex)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.ExpectedRegex = reStr
|
||||
|
||||
case "cmd", "script", "command":
|
||||
cmdStr, err := ui.PromptString("Command", mon.Command, "executable or shell command", false, requireNonEmpty("command"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.Command = cmdStr
|
||||
|
||||
sh, err := ui.Confirm("Execute via /bin/sh -c (shell)?", mon.Shell)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.Shell = sh
|
||||
|
||||
if !sh && !quickAdd {
|
||||
editArgs, err := ui.Confirm("Edit command arguments?", len(mon.Args) > 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if editArgs {
|
||||
args, err := ui.EditStringSlice("Command Arguments", "argument", mon.Args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.Args = args
|
||||
}
|
||||
}
|
||||
|
||||
curExit := mon.ExpectedExitCode
|
||||
if curExit == nil && quickAdd {
|
||||
curExit = config.IntPtr(0)
|
||||
}
|
||||
exitCode, err := ui.PromptOptionalInt("Expected exit code", curExit, 0, 255)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.ExpectedExitCode = exitCode
|
||||
|
||||
reStr, err := ui.PromptString("Output regex (optional)", mon.OutputRegex, "Go regexp matched against stdout+stderr", true, validateOptionalRegex)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.OutputRegex = reStr
|
||||
|
||||
if !quickAdd {
|
||||
wd, err := ui.PromptString("Working directory (optional)", mon.WorkingDir, "", true, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.WorkingDir = wd
|
||||
|
||||
editEnv, err := ui.Confirm("Edit environment variables?", len(mon.Env) > 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if editEnv {
|
||||
env, err := ui.EditStringMap("Command Environment Variables", mon.Env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.Env = env
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateNewMonitorID(cfg *config.Config, excludeIdx int) func(string) error {
|
||||
return func(id string) error {
|
||||
trimmed := strings.TrimSpace(id)
|
||||
if trimmed == "" {
|
||||
return fmt.Errorf("monitor id cannot be empty")
|
||||
}
|
||||
if trimmed == "*" {
|
||||
return fmt.Errorf("'*' is reserved as a wildcard")
|
||||
}
|
||||
if strings.ContainsAny(trimmed, " \t\r\n") {
|
||||
return fmt.Errorf("monitor id cannot contain whitespace")
|
||||
}
|
||||
for i, m := range cfg.Monitors {
|
||||
if i != excludeIdx && m.ID == trimmed {
|
||||
return fmt.Errorf("monitor id %q already exists", trimmed)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func validateHTTPURL(raw string) error {
|
||||
u, err := url.Parse(strings.TrimSpace(raw))
|
||||
if err != nil || (!strings.EqualFold(u.Scheme, "http") && !strings.EqualFold(u.Scheme, "https")) || u.Host == "" {
|
||||
return fmt.Errorf("enter a valid http:// or https:// URL with host")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateOptionalRegex(pattern string) error {
|
||||
if pattern == "" {
|
||||
return nil
|
||||
}
|
||||
if _, err := regexp.Compile(pattern); err != nil {
|
||||
return fmt.Errorf("invalid regex: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func promptIntSlice(ui *UI, label string, current []int, hint string) ([]int, error) {
|
||||
var curParts []string
|
||||
for _, v := range current {
|
||||
curParts = append(curParts, strconv.Itoa(v))
|
||||
}
|
||||
curStr := strings.Join(curParts, ",")
|
||||
|
||||
for {
|
||||
raw, err := ui.PromptString(label, curStr, hint, true, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
return nil, nil
|
||||
}
|
||||
normalized := strings.ReplaceAll(raw, ",", " ")
|
||||
fields := strings.Fields(normalized)
|
||||
out := make([]int, 0, len(fields))
|
||||
valid := true
|
||||
for _, f := range fields {
|
||||
n, convErr := strconv.Atoi(f)
|
||||
if convErr != nil || n < 100 || n > 599 {
|
||||
valid = false
|
||||
break
|
||||
}
|
||||
out = append(out, n)
|
||||
}
|
||||
if !valid {
|
||||
ui.Error("Enter comma-separated HTTP status codes (100-599), e.g. 200,204, or '-' to clear.")
|
||||
continue
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
}
|
||||
|
||||
func uniqueMonitorID(cfg *config.Config, base string) string {
|
||||
taken := make(map[string]bool, len(cfg.Monitors))
|
||||
for _, m := range cfg.Monitors {
|
||||
taken[m.ID] = true
|
||||
}
|
||||
if !taken[base] {
|
||||
return base
|
||||
}
|
||||
for n := 2; ; n++ {
|
||||
cand := fmt.Sprintf("%s-%d", base, n)
|
||||
if !taken[cand] {
|
||||
return cand
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func cloneMonitor(m config.MonitorConfig) config.MonitorConfig {
|
||||
cp := m
|
||||
if m.ExpectedStatus != nil {
|
||||
cp.ExpectedStatus = append([]int(nil), m.ExpectedStatus...)
|
||||
}
|
||||
if m.Args != nil {
|
||||
cp.Args = append([]string(nil), m.Args...)
|
||||
}
|
||||
if m.Headers != nil {
|
||||
cp.Headers = make(map[string]string, len(m.Headers))
|
||||
for k, v := range m.Headers {
|
||||
cp.Headers[k] = v
|
||||
}
|
||||
}
|
||||
if m.Env != nil {
|
||||
cp.Env = make(map[string]string, len(m.Env))
|
||||
for k, v := range m.Env {
|
||||
cp.Env[k] = v
|
||||
}
|
||||
}
|
||||
if m.Retries != nil {
|
||||
cp.Retries = config.IntPtr(*m.Retries)
|
||||
}
|
||||
if m.ExpectedExitCode != nil {
|
||||
cp.ExpectedExitCode = config.IntPtr(*m.ExpectedExitCode)
|
||||
}
|
||||
return cp
|
||||
}
|
||||
|
||||
func formatMonitorOverrides(m config.MonitorConfig) string {
|
||||
var parts []string
|
||||
if m.Interval > 0 {
|
||||
parts = append(parts, "interval="+m.Interval.Std().String())
|
||||
}
|
||||
if m.Timeout > 0 {
|
||||
parts = append(parts, "timeout="+m.Timeout.Std().String())
|
||||
}
|
||||
if m.Retries != nil {
|
||||
parts = append(parts, fmt.Sprintf("retries=%d", *m.Retries))
|
||||
}
|
||||
if m.DegradedLatency > 0 {
|
||||
parts = append(parts, "degraded="+m.DegradedLatency.Std().String())
|
||||
}
|
||||
if len(parts) == 0 {
|
||||
return "inheriting all global defaults"
|
||||
}
|
||||
return strings.Join(parts, ", ")
|
||||
}
|
||||
|
||||
func findMonitorRefs(cfg *config.Config, monitorID string) (eventIDs []string, pageGroups []string) {
|
||||
for _, ev := range cfg.Events {
|
||||
if conditionUsesMonitor(ev.Condition, monitorID) {
|
||||
eventIDs = append(eventIDs, ev.ID)
|
||||
}
|
||||
}
|
||||
for i, el := range cfg.Page.Elements {
|
||||
for _, id := range el.Monitors {
|
||||
if id == monitorID {
|
||||
label := el.Title
|
||||
if label == "" {
|
||||
label = fmt.Sprintf("element[%d]", i)
|
||||
}
|
||||
pageGroups = append(pageGroups, label)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return eventIDs, pageGroups
|
||||
}
|
||||
|
||||
func conditionUsesMonitor(cond config.EventCondition, monitorID string) bool {
|
||||
if len(cond.Conditions) > 0 {
|
||||
for _, sub := range cond.Conditions {
|
||||
if conditionUsesMonitor(sub, monitorID) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
for _, id := range cond.Monitors {
|
||||
if id == monitorID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func renameMonitorRefs(cfg *config.Config, oldID, newID string) {
|
||||
for i := range cfg.Events {
|
||||
renameConditionMonitorRef(&cfg.Events[i].Condition, oldID, newID)
|
||||
}
|
||||
for i := range cfg.Page.Elements {
|
||||
for j, id := range cfg.Page.Elements[i].Monitors {
|
||||
if id == oldID {
|
||||
cfg.Page.Elements[i].Monitors[j] = newID
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func renameConditionMonitorRef(cond *config.EventCondition, oldID, newID string) {
|
||||
if len(cond.Conditions) > 0 {
|
||||
for i := range cond.Conditions {
|
||||
renameConditionMonitorRef(&cond.Conditions[i], oldID, newID)
|
||||
}
|
||||
return
|
||||
}
|
||||
for i, id := range cond.Monitors {
|
||||
if id == oldID {
|
||||
cond.Monitors[i] = newID
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func removeMonitorRefs(cfg *config.Config, targetID string) {
|
||||
for i := range cfg.Events {
|
||||
removeConditionMonitorRef(&cfg.Events[i].Condition, targetID)
|
||||
}
|
||||
for i := range cfg.Page.Elements {
|
||||
if len(cfg.Page.Elements[i].Monitors) > 0 {
|
||||
filtered := make([]string, 0, len(cfg.Page.Elements[i].Monitors))
|
||||
for _, id := range cfg.Page.Elements[i].Monitors {
|
||||
if id != targetID {
|
||||
filtered = append(filtered, id)
|
||||
}
|
||||
}
|
||||
cfg.Page.Elements[i].Monitors = filtered
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func removeConditionMonitorRef(cond *config.EventCondition, targetID string) {
|
||||
if len(cond.Conditions) > 0 {
|
||||
for i := range cond.Conditions {
|
||||
removeConditionMonitorRef(&cond.Conditions[i], targetID)
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(cond.Monitors) > 0 {
|
||||
filtered := make([]string, 0, len(cond.Monitors))
|
||||
for _, id := range cond.Monitors {
|
||||
if id != targetID {
|
||||
filtered = append(filtered, id)
|
||||
}
|
||||
}
|
||||
cond.Monitors = filtered
|
||||
}
|
||||
}
|
||||
|
|
@ -1,651 +0,0 @@
|
|||
package builder
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"git.gsdistance.org/tyuXX/RUD/internal/config"
|
||||
)
|
||||
|
||||
func editPage(ui *UI, cfg *config.Config) error {
|
||||
for {
|
||||
sub := fmt.Sprintf("Title: %q | Elements: %d | BG: %s | Up: %s",
|
||||
cfg.Page.Title, len(cfg.Page.Elements), cfg.Page.Theme.BgColor, cfg.Page.Theme.UpColor)
|
||||
opts := []Option{
|
||||
{Label: "Page HTML title", Description: cfg.Page.Title},
|
||||
{Label: "Apply theme preset", Description: "Dark Minimal, Clean Light, Terminal Green, Nord, High Contrast"},
|
||||
{Label: "Customize theme colors & typography", Description: "Edit all 14 CSS theme properties"},
|
||||
{Label: "Manage page elements", Description: fmt.Sprintf("%d element(s): %s", len(cfg.Page.Elements), summarizeElements(cfg.Page.Elements))},
|
||||
{Label: "Back to main hub"},
|
||||
}
|
||||
|
||||
idx, ok, err := ui.Select("Page & Theme", sub, opts, len(opts)-1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok || idx == len(opts)-1 {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch idx {
|
||||
case 0:
|
||||
t, err := ui.PromptString("Page HTML <title>", cfg.Page.Title, "", false, requireNonEmpty("title"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Page.Title = t
|
||||
case 1:
|
||||
if err := applyThemePresetFlow(ui, &cfg.Page); err != nil {
|
||||
return err
|
||||
}
|
||||
case 2:
|
||||
if err := editCustomTheme(ui, &cfg.Page.Theme); err != nil {
|
||||
return err
|
||||
}
|
||||
case 3:
|
||||
if err := editPageElements(ui, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func applyThemePresetFlow(ui *UI, page *config.PageConfig) error {
|
||||
presets := ThemePresets()
|
||||
opts := make([]Option, len(presets)+1)
|
||||
for i, p := range presets {
|
||||
opts[i] = Option{Label: p.Name, Description: p.Description}
|
||||
}
|
||||
opts[len(presets)] = Option{Label: "Cancel"}
|
||||
|
||||
idx, ok, err := ui.Select("Choose Theme Preset", "", opts, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok || idx == len(presets) {
|
||||
return nil
|
||||
}
|
||||
customCSS := page.Theme.CustomCSS
|
||||
page.Theme = presets[idx].Theme
|
||||
if customCSS != "" && page.Theme.CustomCSS == "" {
|
||||
page.Theme.CustomCSS = customCSS
|
||||
}
|
||||
ui.Ok("Applied theme preset: " + presets[idx].Name)
|
||||
return nil
|
||||
}
|
||||
|
||||
func editCustomTheme(ui *UI, theme *config.ThemeConfig) error {
|
||||
for {
|
||||
opts := []Option{
|
||||
{Label: "Background & surface colors", Description: fmt.Sprintf("bg=%s card=%s border=%s", theme.BgColor, theme.CardBgColor, theme.BorderColor)},
|
||||
{Label: "Text & accent colors", Description: fmt.Sprintf("text=%s muted=%s accent=%s", theme.TextColor, theme.MutedTextColor, theme.AccentColor)},
|
||||
{Label: "Status state colors", Description: fmt.Sprintf("up=%s degraded=%s down=%s pending=%s", theme.UpColor, theme.DegradedColor, theme.DownColor, theme.PendingColor)},
|
||||
{Label: "Typography & layout", Description: fmt.Sprintf("font=%q max_width=%s radius=%s", truncateDesc(theme.FontFamily, 24), theme.MaxWidth, theme.BorderRadius)},
|
||||
{Label: "Custom CSS", Description: truncateDesc(theme.CustomCSS, 40)},
|
||||
{Label: "Done"},
|
||||
}
|
||||
idx, ok, err := ui.Select("Customize Theme", "", opts, len(opts)-1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok || idx == len(opts)-1 {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch idx {
|
||||
case 0:
|
||||
if theme.BgColor, err = ui.PromptString("bg_color", theme.BgColor, "CSS color", false, requireNonEmpty("bg_color")); err != nil {
|
||||
return err
|
||||
}
|
||||
if theme.CardBgColor, err = ui.PromptString("card_bg_color", theme.CardBgColor, "CSS color", false, requireNonEmpty("card_bg_color")); err != nil {
|
||||
return err
|
||||
}
|
||||
if theme.BorderColor, err = ui.PromptString("border_color", theme.BorderColor, "CSS color", false, requireNonEmpty("border_color")); err != nil {
|
||||
return err
|
||||
}
|
||||
case 1:
|
||||
if theme.TextColor, err = ui.PromptString("text_color", theme.TextColor, "CSS color", false, requireNonEmpty("text_color")); err != nil {
|
||||
return err
|
||||
}
|
||||
if theme.MutedTextColor, err = ui.PromptString("muted_text_color", theme.MutedTextColor, "CSS color", false, requireNonEmpty("muted_text_color")); err != nil {
|
||||
return err
|
||||
}
|
||||
if theme.AccentColor, err = ui.PromptString("accent_color", theme.AccentColor, "CSS color", false, requireNonEmpty("accent_color")); err != nil {
|
||||
return err
|
||||
}
|
||||
case 2:
|
||||
if theme.UpColor, err = ui.PromptString("up_color", theme.UpColor, "CSS color", false, requireNonEmpty("up_color")); err != nil {
|
||||
return err
|
||||
}
|
||||
if theme.DegradedColor, err = ui.PromptString("degraded_color", theme.DegradedColor, "CSS color", false, requireNonEmpty("degraded_color")); err != nil {
|
||||
return err
|
||||
}
|
||||
if theme.DownColor, err = ui.PromptString("down_color", theme.DownColor, "CSS color", false, requireNonEmpty("down_color")); err != nil {
|
||||
return err
|
||||
}
|
||||
if theme.PendingColor, err = ui.PromptString("pending_color", theme.PendingColor, "CSS color", false, requireNonEmpty("pending_color")); err != nil {
|
||||
return err
|
||||
}
|
||||
case 3:
|
||||
if theme.FontFamily, err = ui.PromptString("font_family", theme.FontFamily, "CSS font-family", false, requireNonEmpty("font_family")); err != nil {
|
||||
return err
|
||||
}
|
||||
if theme.MaxWidth, err = ui.PromptString("max_width", theme.MaxWidth, "e.g. 820px", false, requireNonEmpty("max_width")); err != nil {
|
||||
return err
|
||||
}
|
||||
if theme.BorderRadius, err = ui.PromptString("border_radius", theme.BorderRadius, "e.g. 2px, 6px", false, requireNonEmpty("border_radius")); err != nil {
|
||||
return err
|
||||
}
|
||||
case 4:
|
||||
if theme.CustomCSS, err = ui.PromptString("custom_css", theme.CustomCSS, "raw CSS appended to <style>", true, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func editPageElements(ui *UI, cfg *config.Config) error {
|
||||
for {
|
||||
sub := fmt.Sprintf("%d element(s): %s", len(cfg.Page.Elements), summarizeElements(cfg.Page.Elements))
|
||||
opts := []Option{
|
||||
{Label: "Add page element", Description: "header, status_banner, summary_cards, monitor_group, custom_block, divider"},
|
||||
}
|
||||
if len(cfg.Page.Elements) > 0 {
|
||||
opts = append(opts,
|
||||
Option{Label: "Edit page element"},
|
||||
Option{Label: "Duplicate page element"},
|
||||
Option{Label: "Reorder page elements", Description: "Move elements up or down"},
|
||||
Option{Label: "Delete page element"},
|
||||
)
|
||||
}
|
||||
opts = append(opts, Option{Label: "Back"})
|
||||
|
||||
idx, ok, err := ui.Select("Page Elements", sub, opts, len(opts)-1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok || opts[idx].Label == "Back" {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch opts[idx].Label {
|
||||
case "Add page element":
|
||||
if err := addPageElementFlow(ui, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
case "Edit page element":
|
||||
eIdx, eOK, err := pickPageElement(ui, cfg.Page.Elements, "Select element to edit")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if eOK {
|
||||
if err := editSinglePageElement(ui, cfg, &cfg.Page.Elements[eIdx]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case "Duplicate page element":
|
||||
eIdx, eOK, err := pickPageElement(ui, cfg.Page.Elements, "Select element to duplicate")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if eOK {
|
||||
cp := clonePageElement(cfg.Page.Elements[eIdx])
|
||||
cfg.Page.Elements = append(cfg.Page.Elements, cp)
|
||||
ui.Ok("Duplicated page element.")
|
||||
}
|
||||
case "Reorder page elements":
|
||||
if err := reorderPageElements(ui, &cfg.Page); err != nil {
|
||||
return err
|
||||
}
|
||||
case "Delete page element":
|
||||
eIdx, eOK, err := pickPageElement(ui, cfg.Page.Elements, "Select element to delete")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if eOK {
|
||||
cfg.Page.Elements = append(cfg.Page.Elements[:eIdx], cfg.Page.Elements[eIdx+1:]...)
|
||||
ui.Ok("Deleted page element.")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func pickPageElement(ui *UI, elems []config.PageElement, title string) (int, bool, error) {
|
||||
opts := make([]Option, len(elems))
|
||||
for i, el := range elems {
|
||||
opts[i] = Option{
|
||||
Label: fmt.Sprintf("[%d] %s", i+1, el.Type),
|
||||
Description: elementDescription(el),
|
||||
}
|
||||
}
|
||||
return ui.Select(title, "", opts, -1)
|
||||
}
|
||||
|
||||
func reorderPageElements(ui *UI, page *config.PageConfig) error {
|
||||
for {
|
||||
if len(page.Elements) < 2 {
|
||||
ui.Info("Need at least 2 elements to reorder.")
|
||||
return nil
|
||||
}
|
||||
eIdx, ok, err := pickPageElement(ui, page.Elements, "Pick element to move (Esc/0 when done)")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
dirOpts := []Option{{Label: "Move up"}, {Label: "Move down"}, {Label: "Cancel"}}
|
||||
dIdx, dOK, err := ui.Select("Move "+page.Elements[eIdx].Type, "", dirOpts, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !dOK || dIdx == 2 {
|
||||
continue
|
||||
}
|
||||
if dIdx == 0 && eIdx > 0 {
|
||||
page.Elements[eIdx-1], page.Elements[eIdx] = page.Elements[eIdx], page.Elements[eIdx-1]
|
||||
} else if dIdx == 1 && eIdx < len(page.Elements)-1 {
|
||||
page.Elements[eIdx+1], page.Elements[eIdx] = page.Elements[eIdx], page.Elements[eIdx+1]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func addPageElementFlow(ui *UI, cfg *config.Config) error {
|
||||
typeOpts := []Option{
|
||||
{Label: "header", Description: "Page heading, subtitle, live indicator & updated timestamp"},
|
||||
{Label: "status_banner", Description: "Overall status bar colored by system state"},
|
||||
{Label: "summary_cards", Description: "Compact metric grid (total, up, degraded, down, uptime, latency)"},
|
||||
{Label: "monitor_group", Description: "List or grid of monitors with history bars & toggles"},
|
||||
{Label: "custom_block", Description: "Static notice, maintenance note, or informational banner"},
|
||||
{Label: "divider", Description: "Horizontal separator rule"},
|
||||
{Label: "Cancel"},
|
||||
}
|
||||
idx, ok, err := ui.Select("Add Page Element", "", typeOpts, 3)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok || idx == len(typeOpts)-1 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var el config.PageElement
|
||||
switch typeOpts[idx].Label {
|
||||
case "header":
|
||||
el = config.PageElement{
|
||||
Type: "header",
|
||||
Title: cfg.Page.Title,
|
||||
Subtitle: "System status",
|
||||
Align: "split",
|
||||
ShowLastUpdated: true,
|
||||
ShowLiveIndicator: true,
|
||||
}
|
||||
case "status_banner":
|
||||
el = config.PageElement{
|
||||
Type: "status_banner",
|
||||
Messages: map[string]string{
|
||||
"up": "All systems operational",
|
||||
"degraded": "Some systems degraded",
|
||||
"down": "One or more systems down",
|
||||
"pending": "Checking systems...",
|
||||
},
|
||||
ShowOverallUptime: true,
|
||||
ShowCounts: true,
|
||||
}
|
||||
case "summary_cards":
|
||||
el = config.PageElement{
|
||||
Type: "summary_cards",
|
||||
Metrics: []string{"total", "up", "degraded", "down", "overall_uptime", "avg_latency"},
|
||||
}
|
||||
case "monitor_group":
|
||||
el = config.PageElement{
|
||||
Type: "monitor_group",
|
||||
Title: "Services",
|
||||
Monitors: []string{"*"},
|
||||
Layout: "list",
|
||||
Display: &config.MonitorDisplayConfig{
|
||||
ShowBar: config.BoolPtr(true),
|
||||
BarTicks: 40,
|
||||
ShowUptime: config.BoolPtr(true),
|
||||
ShowLatency: config.BoolPtr(true),
|
||||
ShowStatusBadge: config.BoolPtr(true),
|
||||
ShowMethod: config.BoolPtr(true),
|
||||
ShowDescription: config.BoolPtr(true),
|
||||
},
|
||||
}
|
||||
case "custom_block":
|
||||
el = config.PageElement{
|
||||
Type: "custom_block",
|
||||
Title: "Notice",
|
||||
Style: "info",
|
||||
}
|
||||
case "divider":
|
||||
cfg.Page.Elements = append(cfg.Page.Elements, config.PageElement{Type: "divider"})
|
||||
ui.Ok("Added divider element.")
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := editSinglePageElement(ui, cfg, &el); err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Page.Elements = append(cfg.Page.Elements, el)
|
||||
ui.Ok("Added " + el.Type + " element.")
|
||||
return nil
|
||||
}
|
||||
|
||||
func editSinglePageElement(ui *UI, cfg *config.Config, el *config.PageElement) error {
|
||||
switch strings.ToLower(strings.TrimSpace(el.Type)) {
|
||||
case "header":
|
||||
var err error
|
||||
if el.Title, err = ui.PromptString("Header title", el.Title, "", true, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
if el.Subtitle, err = ui.PromptString("Header subtitle", el.Subtitle, "", true, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
alignOpts := []Option{{Label: "split"}, {Label: "left"}, {Label: "center"}}
|
||||
defA := 0
|
||||
for i, o := range alignOpts {
|
||||
if strings.EqualFold(o.Label, el.Align) {
|
||||
defA = i
|
||||
break
|
||||
}
|
||||
}
|
||||
aIdx, aOK, err := ui.Select("Header Alignment", "", alignOpts, defA)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if aOK {
|
||||
el.Align = alignOpts[aIdx].Label
|
||||
}
|
||||
if el.ShowLastUpdated, err = ui.Confirm("Show last-updated timestamp?", el.ShowLastUpdated); err != nil {
|
||||
return err
|
||||
}
|
||||
if el.ShowLiveIndicator, err = ui.Confirm("Show live indicator dot?", el.ShowLiveIndicator); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
case "status_banner":
|
||||
if el.Messages == nil {
|
||||
el.Messages = map[string]string{}
|
||||
}
|
||||
for _, st := range []struct{ key, def string }{
|
||||
{"up", "All systems operational"},
|
||||
{"degraded", "Some systems are degraded"},
|
||||
{"down", "One or more systems are down"},
|
||||
{"pending", "Checking systems..."},
|
||||
} {
|
||||
cur := el.Messages[st.key]
|
||||
if cur == "" {
|
||||
cur = st.def
|
||||
}
|
||||
val, err := ui.PromptString("Banner message when "+st.key, cur, "", false, requireNonEmpty(st.key+" message"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
el.Messages[st.key] = val
|
||||
}
|
||||
var err error
|
||||
if el.ShowOverallUptime, err = ui.Confirm("Show overall uptime percentage?", el.ShowOverallUptime); err != nil {
|
||||
return err
|
||||
}
|
||||
if el.ShowCounts, err = ui.Confirm("Show up/total monitor counts?", el.ShowCounts); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
case "summary_cards", "summary":
|
||||
t, err := ui.PromptString("Section title (optional)", el.Title, "", true, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
el.Title = t
|
||||
|
||||
allMetrics := []Option{
|
||||
{Label: "total", Description: "Total monitor count"},
|
||||
{Label: "up", Description: "Healthy monitor count"},
|
||||
{Label: "degraded", Description: "Degraded monitor count"},
|
||||
{Label: "down", Description: "Down monitor count"},
|
||||
{Label: "overall_uptime", Description: "Average uptime percentage"},
|
||||
{Label: "avg_latency", Description: "Average check latency"},
|
||||
}
|
||||
curSet := make(map[string]bool)
|
||||
for _, m := range el.Metrics {
|
||||
curSet[strings.ToLower(strings.TrimSpace(m))] = true
|
||||
}
|
||||
pre := make(map[int]bool)
|
||||
for i, o := range allMetrics {
|
||||
if len(curSet) == 0 || curSet[o.Label] {
|
||||
pre[i] = true
|
||||
}
|
||||
}
|
||||
indices, mOK, err := ui.MultiSelect("Summary Card Metrics", "", allMetrics, pre)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if mOK && len(indices) > 0 {
|
||||
selected := make([]string, 0, len(indices))
|
||||
for _, idx := range indices {
|
||||
selected = append(selected, allMetrics[idx].Label)
|
||||
}
|
||||
el.Metrics = selected
|
||||
}
|
||||
|
||||
case "monitor_group", "monitors":
|
||||
var err error
|
||||
if el.Title, err = ui.PromptString("Group title", el.Title, "", true, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
if el.Description, err = ui.PromptString("Group description", el.Description, "", true, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Monitor multi-select
|
||||
mons, mOK, err := selectConditionMonitors(ui, cfg, el.Monitors)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if mOK {
|
||||
el.Monitors = mons
|
||||
}
|
||||
|
||||
layoutOpts := []Option{{Label: "list", Description: "Vertical stack"}, {Label: "grid", Description: "Responsive multi-column grid"}}
|
||||
defL := 0
|
||||
if strings.EqualFold(el.Layout, "grid") {
|
||||
defL = 1
|
||||
}
|
||||
lIdx, lOK, err := ui.Select("Monitor Group Layout", "", layoutOpts, defL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if lOK {
|
||||
el.Layout = layoutOpts[lIdx].Label
|
||||
}
|
||||
|
||||
if el.Display == nil {
|
||||
el.Display = &config.MonitorDisplayConfig{}
|
||||
}
|
||||
if err := editMonitorDisplayConfig(ui, el.Display); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
case "custom_block", "text":
|
||||
var err error
|
||||
if el.Title, err = ui.PromptString("Block title", el.Title, "", true, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
if el.Content, err = ui.PromptString("Block content", el.Content, "", false, requireNonEmpty("content")); err != nil {
|
||||
return err
|
||||
}
|
||||
styleOpts := []Option{{Label: "neutral"}, {Label: "info"}, {Label: "warning"}, {Label: "danger"}}
|
||||
defS := 0
|
||||
for i, o := range styleOpts {
|
||||
if strings.EqualFold(o.Label, el.Style) {
|
||||
defS = i
|
||||
break
|
||||
}
|
||||
}
|
||||
sIdx, sOK, err := ui.Select("Block Style", "", styleOpts, defS)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if sOK {
|
||||
el.Style = styleOpts[sIdx].Label
|
||||
}
|
||||
|
||||
case "divider":
|
||||
ui.Info("Divider elements have no configurable fields.")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func editMonitorDisplayConfig(ui *UI, d *config.MonitorDisplayConfig) error {
|
||||
toggleDefs := []struct {
|
||||
label string
|
||||
desc string
|
||||
ptr **bool
|
||||
def bool
|
||||
}{
|
||||
{"show_bar", "History status bar", &d.ShowBar, true},
|
||||
{"show_uptime", "Uptime percentage", &d.ShowUptime, true},
|
||||
{"show_latency", "Latest latency ms", &d.ShowLatency, true},
|
||||
{"show_status_badge", "Status badge pill", &d.ShowStatusBadge, true},
|
||||
{"show_method", "Check method tag (HTTP/TCP/etc.)", &d.ShowMethod, true},
|
||||
{"show_target", "Monitor target URL/host", &d.ShowTarget, false},
|
||||
{"show_description", "Monitor description line", &d.ShowDescription, true},
|
||||
{"show_message", "Latest check result/error message", &d.ShowMessage, false},
|
||||
{"show_last_checked", "Last checked UTC timestamp", &d.ShowLastChecked, false},
|
||||
}
|
||||
|
||||
opts := make([]Option, len(toggleDefs))
|
||||
pre := make(map[int]bool, len(toggleDefs))
|
||||
for i, td := range toggleDefs {
|
||||
opts[i] = Option{Label: td.label, Description: td.desc}
|
||||
val := td.def
|
||||
if *td.ptr != nil {
|
||||
val = **td.ptr
|
||||
}
|
||||
if val {
|
||||
pre[i] = true
|
||||
}
|
||||
}
|
||||
|
||||
indices, ok, err := ui.MultiSelect("Monitor Display Flags", "Toggle which data points are visible in this group", opts, pre)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ok {
|
||||
selected := make(map[int]bool, len(indices))
|
||||
for _, idx := range indices {
|
||||
selected[idx] = true
|
||||
}
|
||||
for i, td := range toggleDefs {
|
||||
*td.ptr = config.BoolPtr(selected[i])
|
||||
}
|
||||
}
|
||||
|
||||
if d.ShowBar == nil || *d.ShowBar {
|
||||
curTicks := d.BarTicks
|
||||
if curTicks <= 0 {
|
||||
curTicks = 40
|
||||
}
|
||||
ticks, err := ui.PromptInt("History bar ticks", curTicks, 1, 200)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d.BarTicks = ticks
|
||||
}
|
||||
|
||||
editLabels, err := ui.Confirm("Customize status badge labels (up/degraded/down/pending)?", len(d.CustomLabels) > 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if editLabels {
|
||||
lbls, err := ui.EditStringMap("Custom Status Labels", d.CustomLabels)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d.CustomLabels = lbls
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func summarizeElements(elems []config.PageElement) string {
|
||||
if len(elems) == 0 {
|
||||
return "none"
|
||||
}
|
||||
parts := make([]string, len(elems))
|
||||
for i, el := range elems {
|
||||
parts[i] = el.Type
|
||||
}
|
||||
return strings.Join(parts, " -> ")
|
||||
}
|
||||
|
||||
func elementDescription(el config.PageElement) string {
|
||||
switch strings.ToLower(el.Type) {
|
||||
case "header":
|
||||
return fmt.Sprintf("title=%q align=%s", el.Title, el.Align)
|
||||
case "monitor_group", "monitors":
|
||||
return fmt.Sprintf("title=%q monitors=%v layout=%s", el.Title, el.Monitors, el.Layout)
|
||||
case "summary_cards", "summary":
|
||||
return strings.Join(el.Metrics, ", ")
|
||||
case "custom_block", "text":
|
||||
return fmt.Sprintf("title=%q style=%s", el.Title, el.Style)
|
||||
case "status_banner":
|
||||
return fmt.Sprintf("counts=%v uptime=%v", el.ShowCounts, el.ShowOverallUptime)
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func clonePageElement(el config.PageElement) config.PageElement {
|
||||
cp := el
|
||||
if el.Messages != nil {
|
||||
cp.Messages = make(map[string]string, len(el.Messages))
|
||||
for k, v := range el.Messages {
|
||||
cp.Messages[k] = v
|
||||
}
|
||||
}
|
||||
if el.Metrics != nil {
|
||||
cp.Metrics = append([]string(nil), el.Metrics...)
|
||||
}
|
||||
if el.Monitors != nil {
|
||||
cp.Monitors = append([]string(nil), el.Monitors...)
|
||||
}
|
||||
if el.Display != nil {
|
||||
d := *el.Display
|
||||
if d.ShowBar != nil {
|
||||
d.ShowBar = config.BoolPtr(*d.ShowBar)
|
||||
}
|
||||
if d.ShowUptime != nil {
|
||||
d.ShowUptime = config.BoolPtr(*d.ShowUptime)
|
||||
}
|
||||
if d.ShowLatency != nil {
|
||||
d.ShowLatency = config.BoolPtr(*d.ShowLatency)
|
||||
}
|
||||
if d.ShowStatusBadge != nil {
|
||||
d.ShowStatusBadge = config.BoolPtr(*d.ShowStatusBadge)
|
||||
}
|
||||
if d.ShowMethod != nil {
|
||||
d.ShowMethod = config.BoolPtr(*d.ShowMethod)
|
||||
}
|
||||
if d.ShowTarget != nil {
|
||||
d.ShowTarget = config.BoolPtr(*d.ShowTarget)
|
||||
}
|
||||
if d.ShowDescription != nil {
|
||||
d.ShowDescription = config.BoolPtr(*d.ShowDescription)
|
||||
}
|
||||
if d.ShowMessage != nil {
|
||||
d.ShowMessage = config.BoolPtr(*d.ShowMessage)
|
||||
}
|
||||
if d.ShowLastChecked != nil {
|
||||
d.ShowLastChecked = config.BoolPtr(*d.ShowLastChecked)
|
||||
}
|
||||
if el.Display.CustomLabels != nil {
|
||||
d.CustomLabels = make(map[string]string, len(el.Display.CustomLabels))
|
||||
for k, v := range el.Display.CustomLabels {
|
||||
d.CustomLabels[k] = v
|
||||
}
|
||||
}
|
||||
cp.Display = &d
|
||||
}
|
||||
return cp
|
||||
}
|
||||
|
|
@ -1,366 +0,0 @@
|
|||
package builder
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.gsdistance.org/tyuXX/RUD/internal/config"
|
||||
)
|
||||
|
||||
// ThemePreset defines a named visual theme for the status page.
|
||||
type ThemePreset struct {
|
||||
Name string
|
||||
Description string
|
||||
Theme config.ThemeConfig
|
||||
}
|
||||
|
||||
// ThemePresets lists the built-in color/typography presets for page.theme.
|
||||
func ThemePresets() []ThemePreset {
|
||||
def := config.DefaultConfig().Page.Theme
|
||||
return []ThemePreset{
|
||||
{
|
||||
Name: "Dark Minimal (Default)",
|
||||
Description: "Charcoal dark monospace theme",
|
||||
Theme: def,
|
||||
},
|
||||
{
|
||||
Name: "Clean Light",
|
||||
Description: "Crisp light background with high-readability ink",
|
||||
Theme: config.ThemeConfig{
|
||||
BgColor: "#f8fafc",
|
||||
CardBgColor: "#ffffff",
|
||||
TextColor: "#0f172a",
|
||||
MutedTextColor: "#64748b",
|
||||
BorderColor: "#e2e8f0",
|
||||
AccentColor: "#2563eb",
|
||||
UpColor: "#16a34a",
|
||||
DegradedColor: "#d97706",
|
||||
DownColor: "#dc2626",
|
||||
PendingColor: "#94a3b8",
|
||||
FontFamily: "ui-sans-serif, system-ui, -apple-system, sans-serif",
|
||||
MaxWidth: "860px",
|
||||
BorderRadius: "6px",
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "Terminal Green",
|
||||
Description: "Classic phosphor green-on-black terminal style",
|
||||
Theme: config.ThemeConfig{
|
||||
BgColor: "#050a05",
|
||||
CardBgColor: "#0a140a",
|
||||
TextColor: "#7dff7d",
|
||||
MutedTextColor: "#3b8a3b",
|
||||
BorderColor: "#1b3b1b",
|
||||
AccentColor: "#9aff9a",
|
||||
UpColor: "#00ff66",
|
||||
DegradedColor: "#ffd000",
|
||||
DownColor: "#ff3b3b",
|
||||
PendingColor: "#4a6b4a",
|
||||
FontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",
|
||||
MaxWidth: "820px",
|
||||
BorderRadius: "0px",
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "Nord",
|
||||
Description: "Arctic bluish-slate palette",
|
||||
Theme: config.ThemeConfig{
|
||||
BgColor: "#2e3440",
|
||||
CardBgColor: "#3b4252",
|
||||
TextColor: "#eceff4",
|
||||
MutedTextColor: "#d8dee9",
|
||||
BorderColor: "#4c566a",
|
||||
AccentColor: "#88c0d0",
|
||||
UpColor: "#a3be8c",
|
||||
DegradedColor: "#ebcb8b",
|
||||
DownColor: "#bf616a",
|
||||
PendingColor: "#81a1c1",
|
||||
FontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",
|
||||
MaxWidth: "840px",
|
||||
BorderRadius: "4px",
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "High Contrast",
|
||||
Description: "Pure black/white high-contrast accessibility palette",
|
||||
Theme: config.ThemeConfig{
|
||||
BgColor: "#000000",
|
||||
CardBgColor: "#0a0a0a",
|
||||
TextColor: "#ffffff",
|
||||
MutedTextColor: "#d4d4d4",
|
||||
BorderColor: "#ffffff",
|
||||
AccentColor: "#00ffff",
|
||||
UpColor: "#00ff00",
|
||||
DegradedColor: "#ffff00",
|
||||
DownColor: "#ff3333",
|
||||
PendingColor: "#a3a3a3",
|
||||
FontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",
|
||||
MaxWidth: "860px",
|
||||
BorderRadius: "2px",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// BlankMinimalConfig returns a clean minimal config ready for custom monitors.
|
||||
func BlankMinimalConfig() config.Config {
|
||||
def := config.DefaultConfig()
|
||||
return config.Config{
|
||||
Server: def.Server,
|
||||
Storage: def.Storage,
|
||||
Defaults: def.Defaults,
|
||||
Monitors: []config.MonitorConfig{},
|
||||
Events: []config.EventConfig{},
|
||||
Page: config.PageConfig{
|
||||
Title: "Service Status",
|
||||
Theme: def.Page.Theme,
|
||||
Elements: []config.PageElement{
|
||||
{
|
||||
Type: "header",
|
||||
Title: "Service Status",
|
||||
Subtitle: "System health & uptime",
|
||||
Align: "split",
|
||||
ShowLastUpdated: true,
|
||||
ShowLiveIndicator: true,
|
||||
},
|
||||
{
|
||||
Type: "status_banner",
|
||||
Messages: map[string]string{
|
||||
"up": "All systems operational",
|
||||
"degraded": "Some systems experiencing degraded performance",
|
||||
"down": "One or more systems are down",
|
||||
"pending": "Checking system status...",
|
||||
},
|
||||
ShowOverallUptime: true,
|
||||
ShowCounts: true,
|
||||
},
|
||||
{
|
||||
Type: "monitor_group",
|
||||
Title: "Services",
|
||||
Monitors: []string{"*"},
|
||||
Layout: "list",
|
||||
Display: &config.MonitorDisplayConfig{
|
||||
ShowBar: config.BoolPtr(true),
|
||||
BarTicks: 40,
|
||||
ShowUptime: config.BoolPtr(true),
|
||||
ShowLatency: config.BoolPtr(true),
|
||||
ShowStatusBadge: config.BoolPtr(true),
|
||||
ShowMethod: config.BoolPtr(true),
|
||||
ShowDescription: config.BoolPtr(true),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// WebAPIStarterConfig returns a starter configuration tailored for public web/API endpoints.
|
||||
func WebAPIStarterConfig() config.Config {
|
||||
cfg := BlankMinimalConfig()
|
||||
cfg.Page.Title = "API & Web Status"
|
||||
cfg.Page.Elements[0].Title = "API & Web Status"
|
||||
cfg.Page.Elements[0].Subtitle = "Public website and API availability"
|
||||
cfg.Monitors = []config.MonitorConfig{
|
||||
{
|
||||
ID: "main-web",
|
||||
Name: "Main Website",
|
||||
Description: "Primary HTTPS landing page",
|
||||
Method: "https",
|
||||
URL: "https://example.com/",
|
||||
HTTPMethod: "GET",
|
||||
ExpectedStatus: []int{200},
|
||||
},
|
||||
{
|
||||
ID: "api-health",
|
||||
Name: "Core API Health",
|
||||
Description: "JSON health endpoint",
|
||||
Method: "https",
|
||||
URL: "https://api.example.com/health",
|
||||
HTTPMethod: "GET",
|
||||
ExpectedStatus: []int{200},
|
||||
BodyRegex: `"ok":\s*true`,
|
||||
},
|
||||
{
|
||||
ID: "domain-dns",
|
||||
Name: "Domain DNS (A)",
|
||||
Method: "dns",
|
||||
Host: "example.com",
|
||||
RecordType: "A",
|
||||
},
|
||||
}
|
||||
cfg.Events = []config.EventConfig{
|
||||
{
|
||||
ID: "web-outage",
|
||||
Name: "Website or API Outage",
|
||||
Cooldown: config.NewDuration(15 * time.Minute),
|
||||
TriggerOnRecovery: true,
|
||||
Condition: config.EventCondition{
|
||||
Type: "state",
|
||||
Monitors: []string{"main-web", "api-health"},
|
||||
Match: "any",
|
||||
State: "down",
|
||||
For: config.NewDuration(1 * time.Minute),
|
||||
},
|
||||
Actions: []config.EventAction{
|
||||
{
|
||||
Type: "command",
|
||||
Command: `echo "[RUD ALERT] {{.EventName}}: {{.Status}} ({{.TriggeredMonitors}})"`,
|
||||
Shell: true,
|
||||
Timeout: config.NewDuration(5 * time.Second),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
cfg.Page.Elements = []config.PageElement{
|
||||
cfg.Page.Elements[0],
|
||||
cfg.Page.Elements[1],
|
||||
{
|
||||
Type: "summary_cards",
|
||||
Metrics: []string{"total", "up", "degraded", "down", "overall_uptime", "avg_latency"},
|
||||
},
|
||||
{
|
||||
Type: "monitor_group",
|
||||
Title: "Web & APIs",
|
||||
Monitors: []string{"main-web", "api-health"},
|
||||
Layout: "list",
|
||||
Display: cfg.Page.Elements[2].Display,
|
||||
},
|
||||
{
|
||||
Type: "monitor_group",
|
||||
Title: "DNS",
|
||||
Monitors: []string{"domain-dns"},
|
||||
Layout: "list",
|
||||
Display: cfg.Page.Elements[2].Display,
|
||||
},
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
// HomelabStarterConfig returns a starter configuration tailored for homelab / self-hosted services.
|
||||
func HomelabStarterConfig() config.Config {
|
||||
cfg := BlankMinimalConfig()
|
||||
cfg.Page.Title = "Homelab Status"
|
||||
cfg.Page.Elements[0].Title = "Homelab Status"
|
||||
cfg.Page.Elements[0].Subtitle = "Internal nodes, databases & services"
|
||||
cfg.Monitors = []config.MonitorConfig{
|
||||
{
|
||||
ID: "gateway-ping",
|
||||
Name: "Router / Gateway",
|
||||
Description: "Local network gateway",
|
||||
Method: "ping",
|
||||
Host: "127.0.0.1",
|
||||
Count: 1,
|
||||
},
|
||||
{
|
||||
ID: "db-tcp",
|
||||
Name: "Database TCP",
|
||||
Description: "Database port handshake",
|
||||
Method: "tcp",
|
||||
Target: "127.0.0.1:5432",
|
||||
},
|
||||
{
|
||||
ID: "reverse-proxy",
|
||||
Name: "Reverse Proxy",
|
||||
Description: "Local HTTP ingress",
|
||||
Method: "http",
|
||||
URL: "http://127.0.0.1:80/",
|
||||
},
|
||||
{
|
||||
ID: "root-disk",
|
||||
Name: "Root Disk Free",
|
||||
Description: "Fails if root filesystem exceeds 90% usage",
|
||||
Method: "cmd",
|
||||
Command: "df -P / | awk 'NR==2 {print $5}'",
|
||||
Shell: true,
|
||||
ExpectedExitCode: config.IntPtr(0),
|
||||
OutputRegex: `^([0-8]?[0-9])%$`,
|
||||
},
|
||||
}
|
||||
cfg.Events = []config.EventConfig{
|
||||
{
|
||||
ID: "node-down",
|
||||
Name: "Homelab Service Down",
|
||||
Cooldown: config.NewDuration(30 * time.Minute),
|
||||
TriggerOnRecovery: true,
|
||||
Condition: config.EventCondition{
|
||||
Type: "state",
|
||||
Monitors: []string{"*"},
|
||||
Match: "any",
|
||||
State: "down",
|
||||
For: config.NewDuration(2 * time.Minute),
|
||||
},
|
||||
Actions: []config.EventAction{
|
||||
{
|
||||
Type: "command",
|
||||
Command: `echo "[HOMELAB] {{.EventName}}: {{.Status}} monitors={{.TriggeredMonitors}}"`,
|
||||
Shell: true,
|
||||
Timeout: config.NewDuration(5 * time.Second),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
// WebhookPreset describes a pre-configured webhook payload template.
|
||||
type WebhookPreset struct {
|
||||
Name string
|
||||
Description string
|
||||
URLHint string
|
||||
HTTPMethod string
|
||||
Headers map[string]string
|
||||
Template string
|
||||
}
|
||||
|
||||
// WebhookPresets lists ready-to-use templates for common alerting targets.
|
||||
func WebhookPresets() []WebhookPreset {
|
||||
return []WebhookPreset{
|
||||
{
|
||||
Name: "Discord Webhook",
|
||||
Description: "Posts a formatted message to a Discord channel webhook",
|
||||
URLHint: "https://discord.com/api/webhooks/<id>/<token>",
|
||||
HTTPMethod: "POST",
|
||||
Template: `{"content":"**[{{jsonStr .Status}}] {{jsonStr .EventName}}** — State: ` + "`{{jsonStr .OverallState}}`" + ` | Monitors: {{jsonStr .TriggeredMonitors}} | Uptime: {{.OverallUptimePct}}%"}`,
|
||||
},
|
||||
{
|
||||
Name: "Slack Incoming Webhook",
|
||||
Description: "Posts a clean text alert to a Slack webhook",
|
||||
URLHint: "https://hooks.slack.com/services/T.../B.../...",
|
||||
HTTPMethod: "POST",
|
||||
Template: `{"text":"*[{{jsonStr .Status}}] {{jsonStr .EventName}}*\nState: {{jsonStr .OverallState}} | Monitors: {{jsonStr .TriggeredMonitors}} | Time: {{jsonStr .Timestamp}}"}`,
|
||||
},
|
||||
{
|
||||
Name: "ntfy (ntfy.sh or self-hosted)",
|
||||
Description: "Push notification via ntfy HTTP POST",
|
||||
URLHint: "https://ntfy.sh/<your-topic>",
|
||||
HTTPMethod: "POST",
|
||||
Headers: map[string]string{
|
||||
"Content-Type": "text/plain; charset=utf-8",
|
||||
"Title": "RUD Alert",
|
||||
"Priority": "high",
|
||||
},
|
||||
Template: `[{{.Status}}] {{.EventName}} — State: {{.OverallState}} | Monitors: {{.TriggeredMonitors}} | Uptime: {{.OverallUptimePct}}%`,
|
||||
},
|
||||
{
|
||||
Name: "Gotify",
|
||||
Description: "Push notification to a Gotify server (/message?token=...)",
|
||||
URLHint: "https://gotify.example.com/message?token=<app-token>",
|
||||
HTTPMethod: "POST",
|
||||
Template: `{"title":"[{{jsonStr .Status}}] {{jsonStr .EventName}}","message":"Overall: {{jsonStr .OverallState}}\nMonitors: {{jsonStr .TriggeredMonitors}}\nTime: {{jsonStr .Timestamp}}","priority":5}`,
|
||||
},
|
||||
{
|
||||
Name: "Generic JSON Payload",
|
||||
Description: "Sends RUD's full native EventPayload JSON (empty body_template)",
|
||||
URLHint: "https://hooks.example.com/rud",
|
||||
HTTPMethod: "POST",
|
||||
Template: "",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const templateCheatsheet = `Template variables:
|
||||
{{.EventID}}, {{.EventName}}, {{.Status}} ("TRIGGERED"/"RESOLVED"),
|
||||
{{.OverallState}}, {{.OverallUptimePct}}, {{.TriggeredMonitors}},
|
||||
{{.MonitorsJSON}}, {{.Timestamp}}, {{json .Field}}, {{jsonStr .Field}}
|
||||
Command env vars:
|
||||
RUD_EVENT_ID, RUD_EVENT_NAME, RUD_EVENT_STATUS,
|
||||
RUD_OVERALL_STATE, RUD_TRIGGERED_MONITORS, RUD_TIMESTAMP`
|
||||
|
|
@ -1,41 +0,0 @@
|
|||
//go:build darwin || freebsd || netbsd || openbsd
|
||||
|
||||
package builder
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func isTerminal(f *os.File) bool {
|
||||
if f == nil {
|
||||
return false
|
||||
}
|
||||
var termios syscall.Termios
|
||||
_, _, errno := syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), syscall.TIOCGETA, uintptr(unsafe.Pointer(&termios)))
|
||||
return errno == 0
|
||||
}
|
||||
|
||||
func enableRawMode(f *os.File) (func(), error) {
|
||||
if f == nil {
|
||||
return func() {}, syscall.EINVAL
|
||||
}
|
||||
var orig syscall.Termios
|
||||
_, _, errno := syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), syscall.TIOCGETA, uintptr(unsafe.Pointer(&orig)))
|
||||
if errno != 0 {
|
||||
return func() {}, errno
|
||||
}
|
||||
raw := orig
|
||||
raw.Lflag &^= syscall.ICANON | syscall.ECHO | syscall.ISIG
|
||||
raw.Cc[syscall.VMIN] = 1
|
||||
raw.Cc[syscall.VTIME] = 0
|
||||
|
||||
_, _, errno = syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), syscall.TIOCSETA, uintptr(unsafe.Pointer(&raw)))
|
||||
if errno != 0 {
|
||||
return func() {}, errno
|
||||
}
|
||||
return func() {
|
||||
_, _, _ = syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), syscall.TIOCSETA, uintptr(unsafe.Pointer(&orig)))
|
||||
}, nil
|
||||
}
|
||||
|
|
@ -1,41 +0,0 @@
|
|||
//go:build linux
|
||||
|
||||
package builder
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func isTerminal(f *os.File) bool {
|
||||
if f == nil {
|
||||
return false
|
||||
}
|
||||
var termios syscall.Termios
|
||||
_, _, errno := syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), syscall.TCGETS, uintptr(unsafe.Pointer(&termios)))
|
||||
return errno == 0
|
||||
}
|
||||
|
||||
func enableRawMode(f *os.File) (func(), error) {
|
||||
if f == nil {
|
||||
return func() {}, syscall.EINVAL
|
||||
}
|
||||
var orig syscall.Termios
|
||||
_, _, errno := syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), syscall.TCGETS, uintptr(unsafe.Pointer(&orig)))
|
||||
if errno != 0 {
|
||||
return func() {}, errno
|
||||
}
|
||||
raw := orig
|
||||
raw.Lflag &^= syscall.ICANON | syscall.ECHO | syscall.ISIG
|
||||
raw.Cc[syscall.VMIN] = 1
|
||||
raw.Cc[syscall.VTIME] = 0
|
||||
|
||||
_, _, errno = syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), syscall.TCSETS, uintptr(unsafe.Pointer(&raw)))
|
||||
if errno != 0 {
|
||||
return func() {}, errno
|
||||
}
|
||||
return func() {
|
||||
_, _, _ = syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), syscall.TCSETS, uintptr(unsafe.Pointer(&orig)))
|
||||
}, nil
|
||||
}
|
||||
|
|
@ -1,16 +0,0 @@
|
|||
//go:build !linux && !darwin && !freebsd && !netbsd && !openbsd
|
||||
|
||||
package builder
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
)
|
||||
|
||||
func isTerminal(f *os.File) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func enableRawMode(f *os.File) (func(), error) {
|
||||
return func() {}, errors.New("raw terminal mode not supported on this platform")
|
||||
}
|
||||
|
|
@ -1,827 +0,0 @@
|
|||
package builder
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.gsdistance.org/tyuXX/RUD/internal/config"
|
||||
)
|
||||
|
||||
// ErrAborted is returned when the user cancels the builder via Ctrl-C or reaches EOF.
|
||||
var ErrAborted = errors.New("aborted by user")
|
||||
|
||||
// Option represents a selectable item in interactive menus.
|
||||
type Option struct {
|
||||
Label string
|
||||
Description string
|
||||
}
|
||||
|
||||
// UI provides interactive terminal prompts with raw arrow-key support on TTYs
|
||||
// and clean numbered-prompt fallback for plain terminals and tests.
|
||||
type UI struct {
|
||||
in io.Reader
|
||||
reader *bufio.Reader
|
||||
out io.Writer
|
||||
inFile *os.File
|
||||
rawTTY bool
|
||||
color bool
|
||||
}
|
||||
|
||||
// NewUI constructs a UI bound to in/out. If plain is true or in/out are not TTYs,
|
||||
// it uses numbered line-based prompts.
|
||||
func NewUI(in io.Reader, out io.Writer, plain, noColor bool) *UI {
|
||||
if in == nil {
|
||||
in = os.Stdin
|
||||
}
|
||||
if out == nil {
|
||||
out = os.Stdout
|
||||
}
|
||||
inFile, inIsFile := in.(*os.File)
|
||||
outFile, outIsFile := out.(*os.File)
|
||||
|
||||
inTTY := inIsFile && isTerminal(inFile)
|
||||
outTTY := outIsFile && isTerminal(outFile)
|
||||
|
||||
useColor := !noColor && outTTY && os.Getenv("NO_COLOR") == "" && os.Getenv("TERM") != "dumb"
|
||||
useRaw := !plain && inTTY && outTTY && os.Getenv("TERM") != "dumb"
|
||||
|
||||
return &UI{
|
||||
in: in,
|
||||
reader: bufio.NewReader(in),
|
||||
out: out,
|
||||
inFile: inFile,
|
||||
rawTTY: useRaw,
|
||||
color: useColor,
|
||||
}
|
||||
}
|
||||
|
||||
func (u *UI) style(code, s string) string {
|
||||
if !u.color || s == "" {
|
||||
return s
|
||||
}
|
||||
return "\x1b[" + code + "m" + s + "\x1b[0m"
|
||||
}
|
||||
|
||||
func (u *UI) Bold(s string) string { return u.style("1", s) }
|
||||
func (u *UI) Dim(s string) string { return u.style("2", s) }
|
||||
func (u *UI) Cyan(s string) string { return u.style("36", s) }
|
||||
func (u *UI) Green(s string) string { return u.style("32", s) }
|
||||
func (u *UI) Yellow(s string) string { return u.style("33", s) }
|
||||
func (u *UI) Red(s string) string { return u.style("31", s) }
|
||||
|
||||
func (u *UI) Println(a ...any) {
|
||||
_, _ = fmt.Fprintln(u.out, a...)
|
||||
}
|
||||
|
||||
func (u *UI) Printf(format string, a ...any) {
|
||||
_, _ = fmt.Fprintf(u.out, format, a...)
|
||||
}
|
||||
|
||||
func (u *UI) Header(title, subtitle string) {
|
||||
u.Println()
|
||||
u.Println(u.Bold(u.Cyan("━━ " + title + " ━━")))
|
||||
if subtitle != "" {
|
||||
u.Println(u.Dim(subtitle))
|
||||
}
|
||||
}
|
||||
|
||||
func (u *UI) Info(msg string) { u.Println(u.Cyan("• ") + msg) }
|
||||
func (u *UI) Ok(msg string) { u.Println(u.Green("✓ ") + msg) }
|
||||
func (u *UI) Warn(msg string) { u.Println(u.Yellow("! ") + msg) }
|
||||
func (u *UI) Error(msg string) { u.Println(u.Red("✗ ") + msg) }
|
||||
|
||||
func (u *UI) readLine() (string, error) {
|
||||
line, err := u.reader.ReadString('\n')
|
||||
line = strings.TrimRight(line, "\r\n")
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
if line != "" {
|
||||
return strings.TrimSpace(line), nil
|
||||
}
|
||||
return "", ErrAborted
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimSpace(line), nil
|
||||
}
|
||||
|
||||
type keyCode int
|
||||
|
||||
const (
|
||||
keyNone keyCode = iota
|
||||
keyUp
|
||||
keyDown
|
||||
keyEnter
|
||||
keySpace
|
||||
keyEsc
|
||||
keyBack
|
||||
keyAll
|
||||
keyAbort
|
||||
keyDigit
|
||||
)
|
||||
|
||||
func (u *UI) readKey() (keyCode, int, error) {
|
||||
buf := make([]byte, 8)
|
||||
var n int
|
||||
var err error
|
||||
|
||||
if u.reader.Buffered() > 0 {
|
||||
n, err = u.reader.Read(buf)
|
||||
} else {
|
||||
n, err = u.inFile.Read(buf)
|
||||
}
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
return keyAbort, 0, ErrAborted
|
||||
}
|
||||
return keyNone, 0, err
|
||||
}
|
||||
if n == 0 {
|
||||
return keyNone, 0, nil
|
||||
}
|
||||
|
||||
b := buf[:n]
|
||||
if n >= 3 && b[0] == 0x1b && b[1] == '[' {
|
||||
switch b[2] {
|
||||
case 'A':
|
||||
return keyUp, 0, nil
|
||||
case 'B':
|
||||
return keyDown, 0, nil
|
||||
}
|
||||
return keyNone, 0, nil
|
||||
}
|
||||
if n == 1 {
|
||||
switch b[0] {
|
||||
case 0x03: // Ctrl-C
|
||||
return keyAbort, 0, ErrAborted
|
||||
case '\r', '\n':
|
||||
return keyEnter, 0, nil
|
||||
case ' ':
|
||||
return keySpace, 0, nil
|
||||
case 0x1b:
|
||||
return keyEsc, 0, nil
|
||||
case 'k', 'K':
|
||||
return keyUp, 0, nil
|
||||
case 'j', 'J':
|
||||
return keyDown, 0, nil
|
||||
case 'q', 'Q', '0':
|
||||
return keyBack, 0, nil
|
||||
case 'a', 'A':
|
||||
return keyAll, 0, nil
|
||||
}
|
||||
if b[0] >= '1' && b[0] <= '9' {
|
||||
return keyDigit, int(b[0] - '1'), nil
|
||||
}
|
||||
}
|
||||
return keyNone, 0, nil
|
||||
}
|
||||
|
||||
func truncateDesc(s string, maxLen int) string {
|
||||
s = strings.ReplaceAll(s, "\n", " ")
|
||||
r := []rune(s)
|
||||
if len(r) <= maxLen {
|
||||
return s
|
||||
}
|
||||
return string(r[:maxLen-3]) + "..."
|
||||
}
|
||||
|
||||
// Select displays a single-choice menu. Returns (selectedIndex, ok, error).
|
||||
// ok is false when the user selects Back/Cancel.
|
||||
func (u *UI) Select(title, subtitle string, opts []Option, defaultIdx int) (int, bool, error) {
|
||||
if len(opts) == 0 {
|
||||
return -1, false, nil
|
||||
}
|
||||
if u.rawTTY {
|
||||
return u.selectTTY(title, subtitle, opts, defaultIdx)
|
||||
}
|
||||
return u.selectPlain(title, subtitle, opts, defaultIdx)
|
||||
}
|
||||
|
||||
func (u *UI) selectTTY(title, subtitle string, opts []Option, defaultIdx int) (int, bool, error) {
|
||||
restore, err := enableRawMode(u.inFile)
|
||||
if err != nil {
|
||||
return u.selectPlain(title, subtitle, opts, defaultIdx)
|
||||
}
|
||||
defer restore()
|
||||
|
||||
cursor := 0
|
||||
if defaultIdx >= 0 && defaultIdx < len(opts) {
|
||||
cursor = defaultIdx
|
||||
}
|
||||
|
||||
u.Header(title, subtitle)
|
||||
printedLines := 0
|
||||
render := func() {
|
||||
if printedLines > 0 {
|
||||
u.Printf("\r\x1b[%dA", printedLines)
|
||||
}
|
||||
lines := 0
|
||||
for i, opt := range opts {
|
||||
prefix := " "
|
||||
lbl := opt.Label
|
||||
if i == cursor {
|
||||
prefix = u.Cyan("❯ ")
|
||||
lbl = u.Bold(u.Cyan(opt.Label))
|
||||
}
|
||||
desc := ""
|
||||
if opt.Description != "" {
|
||||
desc = " " + u.Dim(truncateDesc(opt.Description, 56))
|
||||
}
|
||||
u.Printf("\x1b[2K%s%2d) %s%s\r\n", prefix, i+1, lbl, desc)
|
||||
lines++
|
||||
}
|
||||
u.Printf("\x1b[2K%s\r\n", u.Dim(" [↑/↓ move • 1-9 select • Enter confirm • Esc/q back]"))
|
||||
lines++
|
||||
printedLines = lines
|
||||
}
|
||||
|
||||
render()
|
||||
for {
|
||||
k, digit, err := u.readKey()
|
||||
if err != nil {
|
||||
return -1, false, err
|
||||
}
|
||||
switch k {
|
||||
case keyAbort:
|
||||
return -1, false, ErrAborted
|
||||
case keyUp:
|
||||
cursor = (cursor - 1 + len(opts)) % len(opts)
|
||||
render()
|
||||
case keyDown:
|
||||
cursor = (cursor + 1) % len(opts)
|
||||
render()
|
||||
case keyDigit:
|
||||
if digit < len(opts) {
|
||||
cursor = digit
|
||||
if len(opts) <= 9 {
|
||||
render()
|
||||
return cursor, true, nil
|
||||
}
|
||||
render()
|
||||
}
|
||||
case keyEnter:
|
||||
return cursor, true, nil
|
||||
case keyEsc, keyBack:
|
||||
return -1, false, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (u *UI) selectPlain(title, subtitle string, opts []Option, defaultIdx int) (int, bool, error) {
|
||||
u.Header(title, subtitle)
|
||||
for i, opt := range opts {
|
||||
mark := " "
|
||||
if i == defaultIdx {
|
||||
mark = "*"
|
||||
}
|
||||
if opt.Description != "" {
|
||||
u.Printf(" %s%2d) %s — %s\n", mark, i+1, opt.Label, opt.Description)
|
||||
} else {
|
||||
u.Printf(" %s%2d) %s\n", mark, i+1, opt.Label)
|
||||
}
|
||||
}
|
||||
u.Println(" 0) Back / Cancel")
|
||||
|
||||
for {
|
||||
if defaultIdx >= 0 && defaultIdx < len(opts) {
|
||||
u.Printf("Choose [1-%d, 0=back, Enter=%d]: ", len(opts), defaultIdx+1)
|
||||
} else {
|
||||
u.Printf("Choose [1-%d, 0=back]: ", len(opts))
|
||||
}
|
||||
line, err := u.readLine()
|
||||
if err != nil {
|
||||
return -1, false, err
|
||||
}
|
||||
if line == "" && defaultIdx >= 0 && defaultIdx < len(opts) {
|
||||
return defaultIdx, true, nil
|
||||
}
|
||||
lower := strings.ToLower(line)
|
||||
if lower == "0" || lower == "q" || lower == "b" || lower == "back" || lower == "cancel" {
|
||||
return -1, false, nil
|
||||
}
|
||||
n, convErr := strconv.Atoi(line)
|
||||
if convErr == nil && n >= 1 && n <= len(opts) {
|
||||
return n - 1, true, nil
|
||||
}
|
||||
u.Error(fmt.Sprintf("Please enter a number between 1 and %d (or 0 to go back).", len(opts)))
|
||||
}
|
||||
}
|
||||
|
||||
// MultiSelect displays a checkbox menu. Returns (sortedSelectedIndices, ok, error).
|
||||
func (u *UI) MultiSelect(title, subtitle string, opts []Option, preselected map[int]bool) ([]int, bool, error) {
|
||||
if len(opts) == 0 {
|
||||
return nil, true, nil
|
||||
}
|
||||
selected := make(map[int]bool, len(opts))
|
||||
for k, v := range preselected {
|
||||
if k >= 0 && k < len(opts) && v {
|
||||
selected[k] = true
|
||||
}
|
||||
}
|
||||
if u.rawTTY {
|
||||
return u.multiSelectTTY(title, subtitle, opts, selected)
|
||||
}
|
||||
return u.multiSelectPlain(title, subtitle, opts, selected)
|
||||
}
|
||||
|
||||
func sortedSelectedIndices(selected map[int]bool, n int) []int {
|
||||
var out []int
|
||||
for i := 0; i < n; i++ {
|
||||
if selected[i] {
|
||||
out = append(out, i)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (u *UI) multiSelectTTY(title, subtitle string, opts []Option, selected map[int]bool) ([]int, bool, error) {
|
||||
restore, err := enableRawMode(u.inFile)
|
||||
if err != nil {
|
||||
return u.multiSelectPlain(title, subtitle, opts, selected)
|
||||
}
|
||||
defer restore()
|
||||
|
||||
cursor := 0
|
||||
u.Header(title, subtitle)
|
||||
printedLines := 0
|
||||
render := func() {
|
||||
if printedLines > 0 {
|
||||
u.Printf("\r\x1b[%dA", printedLines)
|
||||
}
|
||||
lines := 0
|
||||
for i, opt := range opts {
|
||||
prefix := " "
|
||||
if i == cursor {
|
||||
prefix = u.Cyan("❯ ")
|
||||
}
|
||||
box := "[ ]"
|
||||
if selected[i] {
|
||||
box = u.Green("[x]")
|
||||
}
|
||||
lbl := opt.Label
|
||||
if i == cursor {
|
||||
lbl = u.Bold(lbl)
|
||||
}
|
||||
desc := ""
|
||||
if opt.Description != "" {
|
||||
desc = " " + u.Dim(truncateDesc(opt.Description, 48))
|
||||
}
|
||||
u.Printf("\x1b[2K%s%s %2d) %s%s\r\n", prefix, box, i+1, lbl, desc)
|
||||
lines++
|
||||
}
|
||||
u.Printf("\x1b[2K%s\r\n", u.Dim(" [↑/↓ move • Space toggle • a all/none • Enter confirm • Esc/q cancel]"))
|
||||
lines++
|
||||
printedLines = lines
|
||||
}
|
||||
|
||||
render()
|
||||
for {
|
||||
k, digit, err := u.readKey()
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
switch k {
|
||||
case keyAbort:
|
||||
return nil, false, ErrAborted
|
||||
case keyUp:
|
||||
cursor = (cursor - 1 + len(opts)) % len(opts)
|
||||
render()
|
||||
case keyDown:
|
||||
cursor = (cursor + 1) % len(opts)
|
||||
render()
|
||||
case keySpace:
|
||||
if selected[cursor] {
|
||||
delete(selected, cursor)
|
||||
} else {
|
||||
selected[cursor] = true
|
||||
}
|
||||
render()
|
||||
case keyDigit:
|
||||
if digit < len(opts) {
|
||||
cursor = digit
|
||||
if selected[digit] {
|
||||
delete(selected, digit)
|
||||
} else {
|
||||
selected[digit] = true
|
||||
}
|
||||
render()
|
||||
}
|
||||
case keyAll:
|
||||
allOn := len(sortedSelectedIndices(selected, len(opts))) == len(opts)
|
||||
if allOn {
|
||||
for _, k := range sortedSelectedIndices(selected, len(opts)) {
|
||||
delete(selected, k)
|
||||
}
|
||||
} else {
|
||||
for i := range opts {
|
||||
selected[i] = true
|
||||
}
|
||||
}
|
||||
render()
|
||||
case keyEnter:
|
||||
return sortedSelectedIndices(selected, len(opts)), true, nil
|
||||
case keyEsc, keyBack:
|
||||
return nil, false, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (u *UI) multiSelectPlain(title, subtitle string, opts []Option, selected map[int]bool) ([]int, bool, error) {
|
||||
u.Header(title, subtitle)
|
||||
for i, opt := range opts {
|
||||
box := "[ ]"
|
||||
if selected[i] {
|
||||
box = "[x]"
|
||||
}
|
||||
if opt.Description != "" {
|
||||
u.Printf(" %2d) %s %s — %s\n", i+1, box, opt.Label, opt.Description)
|
||||
} else {
|
||||
u.Printf(" %2d) %s %s\n", i+1, box, opt.Label)
|
||||
}
|
||||
}
|
||||
|
||||
for {
|
||||
u.PrintMultiHint()
|
||||
line, err := u.readLine()
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
lower := strings.ToLower(strings.TrimSpace(line))
|
||||
switch lower {
|
||||
case "":
|
||||
return sortedSelectedIndices(selected, len(opts)), true, nil
|
||||
case "q", "cancel", "back":
|
||||
return nil, false, nil
|
||||
case "all":
|
||||
out := make([]int, len(opts))
|
||||
for i := range opts {
|
||||
out[i] = i
|
||||
}
|
||||
return out, true, nil
|
||||
case "none":
|
||||
return []int{}, true, nil
|
||||
}
|
||||
|
||||
normalized := strings.ReplaceAll(lower, ",", " ")
|
||||
parts := strings.Fields(normalized)
|
||||
if len(parts) == 0 {
|
||||
continue
|
||||
}
|
||||
next := make(map[int]bool, len(parts))
|
||||
valid := true
|
||||
for _, p := range parts {
|
||||
n, convErr := strconv.Atoi(p)
|
||||
if convErr != nil || n < 1 || n > len(opts) {
|
||||
valid = false
|
||||
break
|
||||
}
|
||||
next[n-1] = true
|
||||
}
|
||||
if !valid {
|
||||
u.Error(fmt.Sprintf("Invalid selection. Enter numbers 1-%d (e.g. 1,3), 'all', 'none', or 'q'.", len(opts)))
|
||||
continue
|
||||
}
|
||||
return sortedSelectedIndices(next, len(opts)), true, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (u *UI) PrintMultiHint() {
|
||||
u.Printf("Enter numbers (e.g. 1,3), 'all', 'none', Enter to keep current, or 'q' to cancel: ")
|
||||
}
|
||||
|
||||
// Confirm prompts a yes/no question.
|
||||
func (u *UI) Confirm(prompt string, defaultYes bool) (bool, error) {
|
||||
suffix := "[y/N]"
|
||||
if defaultYes {
|
||||
suffix = "[Y/n]"
|
||||
}
|
||||
for {
|
||||
u.Printf("%s %s: ", prompt, suffix)
|
||||
line, err := u.readLine()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
lower := strings.ToLower(strings.TrimSpace(line))
|
||||
if lower == "" {
|
||||
return defaultYes, nil
|
||||
}
|
||||
if lower == "y" || lower == "yes" {
|
||||
return true, nil
|
||||
}
|
||||
if lower == "n" || lower == "no" {
|
||||
return false, nil
|
||||
}
|
||||
u.Error("Please answer 'y' or 'n'.")
|
||||
}
|
||||
}
|
||||
|
||||
// PromptString prompts for a string value. Pressing Enter keeps current (if valid).
|
||||
// When allowClear is true, typing "-" clears the value to "".
|
||||
func (u *UI) PromptString(label, current, hint string, allowClear bool, validate func(string) error) (string, error) {
|
||||
for {
|
||||
var meta []string
|
||||
if current != "" {
|
||||
meta = append(meta, "current: "+current)
|
||||
} else {
|
||||
meta = append(meta, "empty")
|
||||
}
|
||||
if hint != "" {
|
||||
meta = append(meta, hint)
|
||||
}
|
||||
if allowClear && current != "" {
|
||||
meta = append(meta, "'-' to clear")
|
||||
}
|
||||
u.Printf("%s [%s]: ", u.Bold(label), strings.Join(meta, "; "))
|
||||
line, err := u.readLine()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
val := line
|
||||
if line == "" {
|
||||
val = current
|
||||
} else if allowClear && line == "-" {
|
||||
val = ""
|
||||
}
|
||||
if validate != nil {
|
||||
if err := validate(val); err != nil {
|
||||
u.Error(err.Error())
|
||||
continue
|
||||
}
|
||||
}
|
||||
return val, nil
|
||||
}
|
||||
}
|
||||
|
||||
// PromptDuration prompts for a Go duration string (e.g. 15s, 5m, 1h).
|
||||
func (u *UI) PromptDuration(label string, current config.Duration, allowZero bool) (config.Duration, error) {
|
||||
curStr := current.Std().String()
|
||||
for {
|
||||
hint := "e.g. 500ms, 15s, 5m"
|
||||
if allowZero {
|
||||
hint += "; '0s' or '-' for 0"
|
||||
}
|
||||
u.Printf("%s [current: %s; %s]: ", u.Bold(label), curStr, hint)
|
||||
line, err := u.readLine()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if line == "" {
|
||||
if !allowZero && current <= 0 {
|
||||
u.Error("Duration must be greater than 0.")
|
||||
continue
|
||||
}
|
||||
return current, nil
|
||||
}
|
||||
if allowZero && (line == "-" || line == "0") {
|
||||
return 0, nil
|
||||
}
|
||||
d, parseErr := time.ParseDuration(line)
|
||||
if parseErr != nil {
|
||||
u.Error(fmt.Sprintf("Invalid duration %q (use Go syntax like 500ms, 10s, 5m, 1h).", line))
|
||||
continue
|
||||
}
|
||||
if d < 0 || (!allowZero && d == 0) {
|
||||
u.Error("Duration must be positive.")
|
||||
continue
|
||||
}
|
||||
return config.NewDuration(d), nil
|
||||
}
|
||||
}
|
||||
|
||||
// PromptInt prompts for an integer in [min, max].
|
||||
func (u *UI) PromptInt(label string, current, min, max int) (int, error) {
|
||||
for {
|
||||
u.Printf("%s [current: %d]: ", u.Bold(label), current)
|
||||
line, err := u.readLine()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
val := current
|
||||
if line != "" {
|
||||
parsed, convErr := strconv.Atoi(line)
|
||||
if convErr != nil {
|
||||
u.Error("Please enter a valid integer.")
|
||||
continue
|
||||
}
|
||||
val = parsed
|
||||
}
|
||||
if val < min || val > max {
|
||||
u.Error(fmt.Sprintf("Value must be between %d and %d.", min, max))
|
||||
continue
|
||||
}
|
||||
return val, nil
|
||||
}
|
||||
}
|
||||
|
||||
// PromptOptionalInt prompts for an optional *int; '-' clears to nil.
|
||||
func (u *UI) PromptOptionalInt(label string, current *int, min, max int) (*int, error) {
|
||||
curDesc := "inherit/unset"
|
||||
if current != nil {
|
||||
curDesc = strconv.Itoa(*current)
|
||||
}
|
||||
for {
|
||||
u.Printf("%s [current: %s; '-' to unset]: ", u.Bold(label), curDesc)
|
||||
line, err := u.readLine()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if line == "" {
|
||||
return current, nil
|
||||
}
|
||||
if line == "-" {
|
||||
return nil, nil
|
||||
}
|
||||
parsed, convErr := strconv.Atoi(line)
|
||||
if convErr != nil {
|
||||
u.Error("Please enter a valid integer or '-' to unset.")
|
||||
continue
|
||||
}
|
||||
if parsed < min || parsed > max {
|
||||
u.Error(fmt.Sprintf("Value must be between %d and %d.", min, max))
|
||||
continue
|
||||
}
|
||||
return config.IntPtr(parsed), nil
|
||||
}
|
||||
}
|
||||
|
||||
// PromptFloat prompts for a floating-point number.
|
||||
func (u *UI) PromptFloat(label string, current float64) (float64, error) {
|
||||
for {
|
||||
u.Printf("%s [current: %g]: ", u.Bold(label), current)
|
||||
line, err := u.readLine()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if line == "" {
|
||||
return current, nil
|
||||
}
|
||||
parsed, convErr := strconv.ParseFloat(line, 64)
|
||||
if convErr != nil {
|
||||
u.Error("Please enter a valid number.")
|
||||
continue
|
||||
}
|
||||
return parsed, nil
|
||||
}
|
||||
}
|
||||
|
||||
// EditStringMap provides an interactive editor for key-value string maps.
|
||||
func (u *UI) EditStringMap(title string, existing map[string]string) (map[string]string, error) {
|
||||
work := make(map[string]string, len(existing))
|
||||
for k, v := range existing {
|
||||
work[k] = v
|
||||
}
|
||||
|
||||
for {
|
||||
keys := make([]string, 0, len(work))
|
||||
for k := range work {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
|
||||
var sub string
|
||||
if len(keys) == 0 {
|
||||
sub = "Currently empty."
|
||||
} else {
|
||||
var parts []string
|
||||
for _, k := range keys {
|
||||
parts = append(parts, fmt.Sprintf("%s=%q", k, work[k]))
|
||||
}
|
||||
sub = strings.Join(parts, ", ")
|
||||
}
|
||||
|
||||
opts := []Option{
|
||||
{Label: "Add or update entry", Description: "Set a key=value pair"},
|
||||
}
|
||||
if len(keys) > 0 {
|
||||
opts = append(opts, Option{Label: "Remove entry", Description: "Delete an existing key"})
|
||||
opts = append(opts, Option{Label: "Clear all entries"})
|
||||
}
|
||||
opts = append(opts, Option{Label: "Done"})
|
||||
|
||||
idx, ok, err := u.Select(title, sub, opts, len(opts)-1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok || opts[idx].Label == "Done" {
|
||||
if len(work) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return work, nil
|
||||
}
|
||||
switch opts[idx].Label {
|
||||
case "Add or update entry":
|
||||
k, err := u.PromptString("Key", "", "non-empty key", false, requireNonEmpty("key"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v, err := u.PromptString("Value for "+k, work[k], "", false, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
work[k] = v
|
||||
case "Remove entry":
|
||||
delOpts := make([]Option, len(keys))
|
||||
for i, k := range keys {
|
||||
delOpts[i] = Option{Label: k, Description: work[k]}
|
||||
}
|
||||
dIdx, dOK, err := u.Select("Remove which key?", "", delOpts, -1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if dOK {
|
||||
delete(work, keys[dIdx])
|
||||
}
|
||||
case "Clear all entries":
|
||||
work = map[string]string{}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// EditStringSlice provides an interactive editor for ordered lists of strings.
|
||||
func (u *UI) EditStringSlice(title, itemLabel string, existing []string) ([]string, error) {
|
||||
work := append([]string(nil), existing...)
|
||||
|
||||
for {
|
||||
sub := "Currently empty."
|
||||
if len(work) > 0 {
|
||||
sub = fmt.Sprintf("%d item(s): %s", len(work), strings.Join(work, ", "))
|
||||
}
|
||||
opts := []Option{
|
||||
{Label: "Add " + itemLabel},
|
||||
}
|
||||
if len(work) > 0 {
|
||||
opts = append(opts,
|
||||
Option{Label: "Edit " + itemLabel},
|
||||
Option{Label: "Remove " + itemLabel},
|
||||
Option{Label: "Clear all"},
|
||||
)
|
||||
}
|
||||
opts = append(opts, Option{Label: "Done"})
|
||||
|
||||
idx, ok, err := u.Select(title, sub, opts, len(opts)-1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok || opts[idx].Label == "Done" {
|
||||
if len(work) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return work, nil
|
||||
}
|
||||
|
||||
switch opts[idx].Label {
|
||||
case "Add " + itemLabel:
|
||||
val, err := u.PromptString("New "+itemLabel, "", "", false, requireNonEmpty(itemLabel))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
work = append(work, val)
|
||||
case "Edit " + itemLabel:
|
||||
itemOpts := make([]Option, len(work))
|
||||
for i, item := range work {
|
||||
itemOpts[i] = Option{Label: item}
|
||||
}
|
||||
eIdx, eOK, err := u.Select("Edit which "+itemLabel+"?", "", itemOpts, -1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if eOK {
|
||||
val, err := u.PromptString(itemLabel, work[eIdx], "", false, requireNonEmpty(itemLabel))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
work[eIdx] = val
|
||||
}
|
||||
case "Remove " + itemLabel:
|
||||
itemOpts := make([]Option, len(work))
|
||||
for i, item := range work {
|
||||
itemOpts[i] = Option{Label: item}
|
||||
}
|
||||
rIdx, rOK, err := u.Select("Remove which "+itemLabel+"?", "", itemOpts, -1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if rOK {
|
||||
work = append(work[:rIdx], work[rIdx+1:]...)
|
||||
}
|
||||
case "Clear all":
|
||||
work = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func requireNonEmpty(field string) func(string) error {
|
||||
return func(v string) error {
|
||||
if strings.TrimSpace(v) == "" {
|
||||
return fmt.Errorf("%s cannot be empty", field)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
|
@ -14,42 +15,13 @@ import (
|
|||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"git.gsdistance.org/tyuXX/RUD/internal/config"
|
||||
"git.gsdistance.org/tyuXX/RUD/internal/store"
|
||||
)
|
||||
|
||||
const maxCmdOutputBytes = 1024 * 1024
|
||||
|
||||
var (
|
||||
errICMPUnavailable = errors.New("icmp socket unavailable")
|
||||
|
||||
defaultHTTPTransport = &http.Transport{
|
||||
DisableKeepAlives: true,
|
||||
}
|
||||
insecureHTTPTransport = &http.Transport{
|
||||
DisableKeepAlives: true,
|
||||
TLSClientConfig: &tls.Config{
|
||||
InsecureSkipVerify: true,
|
||||
},
|
||||
}
|
||||
|
||||
regexCache sync.Map // map[string]*regexp.Regexp
|
||||
)
|
||||
|
||||
func getCompiledRegex(pattern string) (*regexp.Regexp, error) {
|
||||
if v, ok := regexCache.Load(pattern); ok {
|
||||
return v.(*regexp.Regexp), nil
|
||||
}
|
||||
re, err := regexp.Compile(pattern)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
regexCache.Store(pattern, re)
|
||||
return re, nil
|
||||
}
|
||||
|
||||
// Scheduler manages concurrent periodic health checks for all configured monitors.
|
||||
type Scheduler struct {
|
||||
cfg *config.Config
|
||||
|
|
@ -137,13 +109,10 @@ func RunCheckWithRetries(ctx context.Context, m config.MonitorConfig, def config
|
|||
|
||||
lastRes = RunSingleCheck(ctx, m, def)
|
||||
if lastRes.State != store.StateDown {
|
||||
if degradedThreshold > 0 {
|
||||
threshMs := float64(degradedThreshold.Microseconds()) / 1000.0
|
||||
if lastRes.LatencyMs >= threshMs {
|
||||
if degradedThreshold > 0 && lastRes.LatencyMs >= float64(degradedThreshold.Milliseconds()) {
|
||||
lastRes.State = store.StateDegraded
|
||||
if lastRes.Message == "" || lastRes.Message == "OK" {
|
||||
lastRes.Message = fmt.Sprintf("High latency (%.1fms >= %.1fms)", lastRes.LatencyMs, threshMs)
|
||||
}
|
||||
lastRes.Message = fmt.Sprintf("High latency (%.0fms >= %dms)", lastRes.LatencyMs, degradedThreshold.Milliseconds())
|
||||
}
|
||||
}
|
||||
return lastRes
|
||||
|
|
@ -203,9 +172,11 @@ func checkHTTP(ctx context.Context, m config.MonitorConfig, timeout time.Duratio
|
|||
req.Header.Set(k, v)
|
||||
}
|
||||
|
||||
tr := defaultHTTPTransport
|
||||
if m.InsecureSkipVerify {
|
||||
tr = insecureHTTPTransport
|
||||
tr := &http.Transport{
|
||||
DisableKeepAlives: true,
|
||||
TLSClientConfig: &tls.Config{
|
||||
InsecureSkipVerify: m.InsecureSkipVerify,
|
||||
},
|
||||
}
|
||||
client := &http.Client{
|
||||
Transport: tr,
|
||||
|
|
@ -259,7 +230,7 @@ func checkHTTP(ctx context.Context, m config.MonitorConfig, timeout time.Duratio
|
|||
}
|
||||
|
||||
if m.BodyRegex != "" {
|
||||
re, err := getCompiledRegex(m.BodyRegex)
|
||||
re, err := regexp.Compile(m.BodyRegex)
|
||||
if err != nil || !re.Match(bodyBytes) {
|
||||
return store.CheckResult{
|
||||
Timestamp: time.Now().UTC(),
|
||||
|
|
@ -318,8 +289,7 @@ func checkPing(ctx context.Context, m config.MonitorConfig, timeout time.Duratio
|
|||
}
|
||||
|
||||
// First attempt native ICMP echo (works with CAP_NET_RAW, root, or unprivileged ICMP sockets)
|
||||
latencyMs, err := nativeICMPPing(ctx, host, count, timeout, m.Privileged)
|
||||
if err == nil {
|
||||
if latencyMs, err := nativeICMPPing(ctx, host, timeout, m.Privileged); err == nil {
|
||||
return store.CheckResult{
|
||||
Timestamp: time.Now().UTC(),
|
||||
State: store.StateUp,
|
||||
|
|
@ -327,15 +297,8 @@ func checkPing(ctx context.Context, m config.MonitorConfig, timeout time.Duratio
|
|||
Message: "ICMP echo reply",
|
||||
}
|
||||
}
|
||||
if !errors.Is(err, errICMPUnavailable) {
|
||||
return store.CheckResult{
|
||||
Timestamp: time.Now().UTC(),
|
||||
State: store.StateDown,
|
||||
Message: fmt.Sprintf("ping failed: %s", cleanErr(err)),
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to system ping utility only when native ICMP sockets are unavailable
|
||||
// Fallback to system ping utility if available
|
||||
waitSec := int(timeout.Seconds())
|
||||
if waitSec < 1 {
|
||||
waitSec = 1
|
||||
|
|
@ -343,7 +306,7 @@ func checkPing(ctx context.Context, m config.MonitorConfig, timeout time.Duratio
|
|||
start := time.Now()
|
||||
cmd := exec.CommandContext(ctx, "ping", "-c", fmt.Sprintf("%d", count), "-W", fmt.Sprintf("%d", waitSec), host)
|
||||
out, err := cmd.CombinedOutput()
|
||||
latencyMs = float64(time.Since(start).Microseconds()) / 1000.0
|
||||
latencyMs := float64(time.Since(start).Microseconds()) / 1000.0
|
||||
if err == nil {
|
||||
if parsed := parsePingRTT(string(out)); parsed > 0 {
|
||||
latencyMs = parsed
|
||||
|
|
@ -364,6 +327,97 @@ func checkPing(ctx context.Context, m config.MonitorConfig, timeout time.Duratio
|
|||
}
|
||||
}
|
||||
|
||||
func nativeICMPPing(ctx context.Context, host string, timeout time.Duration, privilegedOnly bool) (float64, error) {
|
||||
ips, err := net.DefaultResolver.LookupIP(ctx, "ip4", host)
|
||||
if err != nil || len(ips) == 0 {
|
||||
return 0, fmt.Errorf("resolve %s: %w", host, err)
|
||||
}
|
||||
ip4 := ips[0].To4()
|
||||
if ip4 == nil {
|
||||
return 0, fmt.Errorf("no IPv4 address for %s", host)
|
||||
}
|
||||
|
||||
// Try Linux unprivileged ICMP datagram socket (SOCK_DGRAM + IPPROTO_ICMP) first unless privilegedOnly is set,
|
||||
// with fallback to raw ICMP socket (SOCK_RAW + IPPROTO_ICMP).
|
||||
sockTypes := []int{syscall.SOCK_DGRAM, syscall.SOCK_RAW}
|
||||
if privilegedOnly {
|
||||
sockTypes = []int{syscall.SOCK_RAW, syscall.SOCK_DGRAM}
|
||||
}
|
||||
|
||||
fd := -1
|
||||
usedType := 0
|
||||
for _, st := range sockTypes {
|
||||
s, err := syscall.Socket(syscall.AF_INET, st, syscall.IPPROTO_ICMP)
|
||||
if err == nil {
|
||||
fd = s
|
||||
usedType = st
|
||||
break
|
||||
}
|
||||
}
|
||||
if fd < 0 {
|
||||
return 0, errors.New("icmp socket unavailable")
|
||||
}
|
||||
defer syscall.Close(fd)
|
||||
|
||||
tv := syscall.NsecToTimeval(timeout.Nanoseconds())
|
||||
_ = syscall.SetsockoptTimeval(fd, syscall.SOL_SOCKET, syscall.SO_RCVTIMEO, &tv)
|
||||
_ = syscall.SetsockoptTimeval(fd, syscall.SOL_SOCKET, syscall.SO_SNDTIMEO, &tv)
|
||||
|
||||
// Construct ICMPv4 Echo Request (type 8, code 0)
|
||||
pkt := make([]byte, 16)
|
||||
pkt[0] = 8 // Echo Request
|
||||
pkt[1] = 0
|
||||
id := uint16(os.Getpid() & 0xffff)
|
||||
binary.BigEndian.PutUint16(pkt[4:6], id)
|
||||
binary.BigEndian.PutUint16(pkt[6:8], 1) // Seq 1
|
||||
copy(pkt[8:], []byte("RUD-PING"))
|
||||
cs := icmpChecksum(pkt)
|
||||
binary.BigEndian.PutUint16(pkt[2:4], cs)
|
||||
|
||||
var sa syscall.SockaddrInet4
|
||||
copy(sa.Addr[:], ip4)
|
||||
|
||||
start := time.Now()
|
||||
if err := syscall.Sendto(fd, pkt, 0, &sa); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
buf := make([]byte, 1500)
|
||||
n, _, err := syscall.Recvfrom(fd, buf, 0)
|
||||
latencyMs := float64(time.Since(start).Microseconds()) / 1000.0
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if n < 8 {
|
||||
return 0, errors.New("short icmp reply")
|
||||
}
|
||||
payload := buf[:n]
|
||||
if usedType == syscall.SOCK_RAW && len(payload) >= 28 && (payload[0]>>4) == 4 {
|
||||
hdrLen := int(payload[0]&0x0f) * 4
|
||||
if len(payload) >= hdrLen+8 {
|
||||
payload = payload[hdrLen:]
|
||||
}
|
||||
}
|
||||
if payload[0] != 0 { // 0 = Echo Reply
|
||||
return 0, fmt.Errorf("unexpected icmp type %d", payload[0])
|
||||
}
|
||||
return latencyMs, nil
|
||||
}
|
||||
|
||||
func icmpChecksum(b []byte) uint16 {
|
||||
var sum uint32
|
||||
for i := 0; i < len(b)-1; i += 2 {
|
||||
sum += uint32(binary.BigEndian.Uint16(b[i : i+2]))
|
||||
}
|
||||
if len(b)%2 == 1 {
|
||||
sum += uint32(b[len(b)-1]) << 8
|
||||
}
|
||||
for (sum >> 16) > 0 {
|
||||
sum = (sum & 0xffff) + (sum >> 16)
|
||||
}
|
||||
return ^uint16(sum)
|
||||
}
|
||||
|
||||
var pingRTTRe = regexp.MustCompile(`time[=<]([0-9.]+)\s*ms`)
|
||||
|
||||
func parsePingRTT(output string) float64 {
|
||||
|
|
@ -463,7 +517,7 @@ func checkDNS(ctx context.Context, m config.MonitorConfig, timeout time.Duration
|
|||
|
||||
joined := strings.Join(records, ", ")
|
||||
if m.ExpectedRegex != "" {
|
||||
re, err := getCompiledRegex(m.ExpectedRegex)
|
||||
re, err := regexp.Compile(m.ExpectedRegex)
|
||||
if err != nil {
|
||||
return store.CheckResult{
|
||||
Timestamp: time.Now().UTC(),
|
||||
|
|
@ -497,31 +551,6 @@ func checkDNS(ctx context.Context, m config.MonitorConfig, timeout time.Duration
|
|||
}
|
||||
}
|
||||
|
||||
type limitedBuffer struct {
|
||||
buf bytes.Buffer
|
||||
limit int
|
||||
truncated bool
|
||||
}
|
||||
|
||||
func (l *limitedBuffer) Write(p []byte) (int, error) {
|
||||
if l.buf.Len() < l.limit {
|
||||
rem := l.limit - l.buf.Len()
|
||||
if len(p) > rem {
|
||||
l.buf.Write(p[:rem])
|
||||
l.truncated = true
|
||||
} else {
|
||||
l.buf.Write(p)
|
||||
}
|
||||
} else {
|
||||
l.truncated = true
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (l *limitedBuffer) String() string {
|
||||
return l.buf.String()
|
||||
}
|
||||
|
||||
func checkCmd(ctx context.Context, m config.MonitorConfig) store.CheckResult {
|
||||
var cmd *exec.Cmd
|
||||
if m.Shell || (len(m.Args) == 0 && strings.ContainsAny(m.Command, " \t|&;<>()$`\"'")) {
|
||||
|
|
@ -533,7 +562,6 @@ func checkCmd(ctx context.Context, m config.MonitorConfig) store.CheckResult {
|
|||
} else {
|
||||
cmd = exec.CommandContext(ctx, m.Command, m.Args...)
|
||||
}
|
||||
configureCmdProcessGroup(cmd)
|
||||
|
||||
if m.WorkingDir != "" {
|
||||
cmd.Dir = m.WorkingDir
|
||||
|
|
@ -546,7 +574,7 @@ func checkCmd(ctx context.Context, m config.MonitorConfig) store.CheckResult {
|
|||
cmd.Env = env
|
||||
}
|
||||
|
||||
outBuf := limitedBuffer{limit: maxCmdOutputBytes}
|
||||
var outBuf bytes.Buffer
|
||||
cmd.Stdout = &outBuf
|
||||
cmd.Stderr = &outBuf
|
||||
|
||||
|
|
@ -591,7 +619,7 @@ func checkCmd(ctx context.Context, m config.MonitorConfig) store.CheckResult {
|
|||
}
|
||||
|
||||
if m.OutputRegex != "" {
|
||||
re, regErr := getCompiledRegex(m.OutputRegex)
|
||||
re, regErr := regexp.Compile(m.OutputRegex)
|
||||
if regErr != nil || !re.MatchString(output) {
|
||||
return store.CheckResult{
|
||||
Timestamp: time.Now().UTC(),
|
||||
|
|
|
|||
|
|
@ -5,7 +5,6 @@ import (
|
|||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
|
|
@ -119,88 +118,3 @@ func TestDNSAndCmdAndPingCheckers(t *testing.T) {
|
|||
t.Fatalf("expected Ping check up, got %s (%s)", pingRes.State, pingRes.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentLoopbackPings(t *testing.T) {
|
||||
def := config.DefaultsConfig{Timeout: config.NewDuration(2 * time.Second)}
|
||||
const workers = 6
|
||||
var wg sync.WaitGroup
|
||||
errs := make(chan string, workers)
|
||||
|
||||
for i := 0; i < workers; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
mon := config.MonitorConfig{
|
||||
ID: "ping-concurrent",
|
||||
Method: "ping",
|
||||
Host: "127.0.0.1",
|
||||
Count: 2,
|
||||
}
|
||||
res := RunCheckWithRetries(context.Background(), mon, def)
|
||||
if res.State != store.StateUp {
|
||||
errs <- res.Message
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
for msg := range errs {
|
||||
t.Fatalf("concurrent ping failed: %s", msg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCmdBoundedOutputAndTimeoutCleanup(t *testing.T) {
|
||||
// Command writing > 1.5 MiB should remain bounded and still check regex
|
||||
def := config.DefaultsConfig{Timeout: config.NewDuration(3 * time.Second)}
|
||||
bigCmd := config.MonitorConfig{
|
||||
ID: "cmd-big",
|
||||
Method: "cmd",
|
||||
Command: "printf 'HEAD:'; head -c 1500000 /dev/zero | tr '\\0' 'A'",
|
||||
Shell: true,
|
||||
OutputRegex: `^HEAD:A+$`,
|
||||
}
|
||||
res := RunCheckWithRetries(context.Background(), bigCmd, def)
|
||||
if res.State != store.StateUp {
|
||||
t.Fatalf("expected bounded big output cmd to pass, got %s (%s)", res.State, res.Message)
|
||||
}
|
||||
|
||||
// Command spawning a sleep child should terminate quickly on timeout without hanging pipes
|
||||
start := time.Now()
|
||||
timeoutDef := config.DefaultsConfig{Timeout: config.NewDuration(150 * time.Millisecond)}
|
||||
sleepCmd := config.MonitorConfig{
|
||||
ID: "cmd-timeout",
|
||||
Method: "cmd",
|
||||
Command: "sleep 10 & wait",
|
||||
Shell: true,
|
||||
}
|
||||
resTimeout := RunCheckWithRetries(context.Background(), sleepCmd, timeoutDef)
|
||||
elapsed := time.Since(start)
|
||||
if resTimeout.State != store.StateDown {
|
||||
t.Fatalf("expected timed out cmd to mark down, got %s", resTimeout.State)
|
||||
}
|
||||
if elapsed > 2*time.Second {
|
||||
t.Fatalf("timed out cmd took too long to clean up process group: %v", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubMsDegradedLatencyThreshold(t *testing.T) {
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
time.Sleep(2 * time.Millisecond)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
def := config.DefaultsConfig{
|
||||
Timeout: config.NewDuration(2 * time.Second),
|
||||
DegradedLatency: config.NewDuration(500 * time.Microsecond), // 0.5ms (< 1ms!)
|
||||
}
|
||||
mon := config.MonitorConfig{
|
||||
ID: "http-subms",
|
||||
Method: "http",
|
||||
URL: ts.URL,
|
||||
}
|
||||
res := RunCheckWithRetries(context.Background(), mon, def)
|
||||
if res.State != store.StateDegraded {
|
||||
t.Fatalf("expected sub-ms degraded threshold (500us) to trigger degraded state, got %s (latency=%.3fms)", res.State, res.LatencyMs)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +0,0 @@
|
|||
//go:build !unix
|
||||
|
||||
package checker
|
||||
|
||||
import "os/exec"
|
||||
|
||||
func configureCmdProcessGroup(cmd *exec.Cmd) {}
|
||||
|
|
@ -1,20 +0,0 @@
|
|||
//go:build unix
|
||||
|
||||
package checker
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
func configureCmdProcessGroup(cmd *exec.Cmd) {
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||
cmd.Cancel = func() error {
|
||||
if cmd.Process != nil {
|
||||
return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
cmd.WaitDelay = 500 * time.Millisecond
|
||||
}
|
||||
|
|
@ -1,195 +0,0 @@
|
|||
//go:build linux
|
||||
|
||||
package checker
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
var icmpIDCounter uint32
|
||||
|
||||
func nativeICMPPing(ctx context.Context, host string, count int, timeout time.Duration, privilegedOnly bool) (float64, error) {
|
||||
if count <= 0 {
|
||||
count = 1
|
||||
}
|
||||
|
||||
ips, err := net.DefaultResolver.LookupIP(ctx, "ip4", host)
|
||||
if err != nil || len(ips) == 0 {
|
||||
return 0, fmt.Errorf("resolve %s: %w", host, err)
|
||||
}
|
||||
ip4 := ips[0].To4()
|
||||
if ip4 == nil {
|
||||
return 0, fmt.Errorf("no IPv4 address for %s", host)
|
||||
}
|
||||
|
||||
// Try Linux unprivileged ICMP datagram socket (SOCK_DGRAM + IPPROTO_ICMP) first unless privilegedOnly is set,
|
||||
// with fallback to raw ICMP socket (SOCK_RAW + IPPROTO_ICMP).
|
||||
sockTypes := []int{syscall.SOCK_DGRAM, syscall.SOCK_RAW}
|
||||
if privilegedOnly {
|
||||
sockTypes = []int{syscall.SOCK_RAW, syscall.SOCK_DGRAM}
|
||||
}
|
||||
|
||||
fd := -1
|
||||
usedType := 0
|
||||
for _, st := range sockTypes {
|
||||
s, sockErr := syscall.Socket(syscall.AF_INET, st, syscall.IPPROTO_ICMP)
|
||||
if sockErr == nil {
|
||||
fd = s
|
||||
usedType = st
|
||||
break
|
||||
}
|
||||
}
|
||||
if fd < 0 {
|
||||
return 0, errICMPUnavailable
|
||||
}
|
||||
defer syscall.Close(fd)
|
||||
|
||||
id := uint16(atomic.AddUint32(&icmpIDCounter, 1) & 0xffff)
|
||||
if id == 0 {
|
||||
id = uint16(atomic.AddUint32(&icmpIDCounter, 1) & 0xffff)
|
||||
}
|
||||
|
||||
var sa syscall.SockaddrInet4
|
||||
copy(sa.Addr[:], ip4)
|
||||
|
||||
overallDeadline := time.Now().Add(timeout)
|
||||
buf := make([]byte, 1500)
|
||||
var rttSum float64
|
||||
var received int
|
||||
var lastErr error
|
||||
|
||||
for seq := 1; seq <= count; seq++ {
|
||||
if ctx.Err() != nil {
|
||||
if received > 0 {
|
||||
break
|
||||
}
|
||||
return 0, ctx.Err()
|
||||
}
|
||||
remainingTotal := time.Until(overallDeadline)
|
||||
if remainingTotal <= 0 {
|
||||
break
|
||||
}
|
||||
pktsLeft := count - seq + 1
|
||||
pktTimeout := remainingTotal / time.Duration(pktsLeft)
|
||||
if pktTimeout < 50*time.Millisecond && remainingTotal > 50*time.Millisecond {
|
||||
pktTimeout = 50 * time.Millisecond
|
||||
}
|
||||
pktDeadline := time.Now().Add(pktTimeout)
|
||||
if pktDeadline.After(overallDeadline) {
|
||||
pktDeadline = overallDeadline
|
||||
}
|
||||
|
||||
// Construct ICMPv4 Echo Request (type 8, code 0)
|
||||
pkt := make([]byte, 16)
|
||||
pkt[0] = 8 // Echo Request
|
||||
pkt[1] = 0
|
||||
binary.BigEndian.PutUint16(pkt[4:6], id)
|
||||
binary.BigEndian.PutUint16(pkt[6:8], uint16(seq))
|
||||
copy(pkt[8:], []byte("RUD-PING"))
|
||||
cs := icmpChecksum(pkt)
|
||||
binary.BigEndian.PutUint16(pkt[2:4], cs)
|
||||
|
||||
sendTV := syscall.NsecToTimeval(pktTimeout.Nanoseconds())
|
||||
_ = syscall.SetsockoptTimeval(fd, syscall.SOL_SOCKET, syscall.SO_SNDTIMEO, &sendTV)
|
||||
|
||||
sendStart := time.Now()
|
||||
if err := syscall.Sendto(fd, pkt, 0, &sa); err != nil {
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
|
||||
for {
|
||||
if ctx.Err() != nil {
|
||||
if received > 0 {
|
||||
return rttSum / float64(received), nil
|
||||
}
|
||||
return 0, ctx.Err()
|
||||
}
|
||||
rem := time.Until(pktDeadline)
|
||||
if rem <= 0 {
|
||||
lastErr = errors.New("icmp echo timeout")
|
||||
break
|
||||
}
|
||||
slice := rem
|
||||
if slice > 200*time.Millisecond {
|
||||
slice = 200 * time.Millisecond
|
||||
}
|
||||
rcvTV := syscall.NsecToTimeval(slice.Nanoseconds())
|
||||
_ = syscall.SetsockoptTimeval(fd, syscall.SOL_SOCKET, syscall.SO_RCVTIMEO, &rcvTV)
|
||||
|
||||
n, from, rcvErr := syscall.Recvfrom(fd, buf, 0)
|
||||
if rcvErr != nil {
|
||||
if errors.Is(rcvErr, syscall.EINTR) || errors.Is(rcvErr, syscall.EAGAIN) || errors.Is(rcvErr, syscall.EWOULDBLOCK) {
|
||||
continue
|
||||
}
|
||||
lastErr = rcvErr
|
||||
break
|
||||
}
|
||||
if n < 8 {
|
||||
continue
|
||||
}
|
||||
|
||||
if from4, ok := from.(*syscall.SockaddrInet4); !ok || !bytes.Equal(from4.Addr[:], ip4) {
|
||||
continue
|
||||
}
|
||||
|
||||
payload := buf[:n]
|
||||
if usedType == syscall.SOCK_RAW && len(payload) >= 20 && (payload[0]>>4) == 4 {
|
||||
hdrLen := int(payload[0]&0x0f) * 4
|
||||
if hdrLen < 20 || len(payload) < hdrLen+8 {
|
||||
continue
|
||||
}
|
||||
payload = payload[hdrLen:]
|
||||
}
|
||||
|
||||
// Ignore non-Echo-Reply packets (e.g. Echo Requests seen on loopback SOCK_RAW)
|
||||
if payload[0] != 0 || payload[1] != 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
replyID := binary.BigEndian.Uint16(payload[4:6])
|
||||
replySeq := binary.BigEndian.Uint16(payload[6:8])
|
||||
if usedType == syscall.SOCK_RAW && replyID != id {
|
||||
continue
|
||||
}
|
||||
if replySeq != uint16(seq) {
|
||||
continue
|
||||
}
|
||||
|
||||
rttMs := float64(time.Since(sendStart).Microseconds()) / 1000.0
|
||||
rttSum += rttMs
|
||||
received++
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if received > 0 {
|
||||
return rttSum / float64(received), nil
|
||||
}
|
||||
if lastErr == nil {
|
||||
lastErr = errors.New("icmp echo timeout")
|
||||
}
|
||||
return 0, lastErr
|
||||
}
|
||||
|
||||
func icmpChecksum(b []byte) uint16 {
|
||||
var sum uint32
|
||||
for i := 0; i < len(b)-1; i += 2 {
|
||||
sum += uint32(binary.BigEndian.Uint16(b[i : i+2]))
|
||||
}
|
||||
if len(b)%2 == 1 {
|
||||
sum += uint32(b[len(b)-1]) << 8
|
||||
}
|
||||
for (sum >> 16) > 0 {
|
||||
sum = (sum & 0xffff) + (sum >> 16)
|
||||
}
|
||||
return ^uint16(sum)
|
||||
}
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
//go:build !linux
|
||||
|
||||
package checker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
func nativeICMPPing(ctx context.Context, host string, count int, timeout time.Duration, privilegedOnly bool) (float64, error) {
|
||||
return 0, errICMPUnavailable
|
||||
}
|
||||
|
|
@ -5,43 +5,12 @@ import (
|
|||
"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
|
||||
|
|
@ -594,116 +563,16 @@ func LoadOrInit(path string, createIfMissing bool) (*Config, bool, error) {
|
|||
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) {
|
||||
// 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 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
|
||||
return os.WriteFile(path, buf.Bytes(), 0644)
|
||||
}
|
||||
|
||||
// ApplyFallbacks populates missing structural defaults (like listen address, endpoint, status codes, theme colors)
|
||||
|
|
@ -812,30 +681,8 @@ func (c *Config) ApplyFallbacks() {
|
|||
}
|
||||
}
|
||||
|
||||
// Validate checks the configuration for duplicate IDs, invalid methods, invalid URLs/regexes/templates, and negative values.
|
||||
// Validate checks the configuration for duplicate IDs, invalid methods, or invalid regexes.
|
||||
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.Storage.StatsRetentionDays < 0 {
|
||||
return fmt.Errorf("storage.stats_retention_days 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]
|
||||
|
|
@ -849,18 +696,6 @@ func (c *Config) Validate() error {
|
|||
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
|
||||
|
|
@ -869,10 +704,6 @@ func (c *Config) Validate() error {
|
|||
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)
|
||||
|
|
@ -918,77 +749,19 @@ func (c *Config) Validate() error {
|
|||
}
|
||||
}
|
||||
|
||||
seenEvents := make(map[string]bool)
|
||||
for i, ev := range c.Events {
|
||||
if strings.TrimSpace(ev.ID) == "" {
|
||||
if 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" {
|
||||
|
|
@ -1031,237 +804,3 @@ func validateCondition(cond EventCondition) error {
|
|||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,7 @@
|
|||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
|
@ -60,18 +58,6 @@ func TestDurationMarshalUnmarshal(t *testing.T) {
|
|||
|
||||
func TestConfigValidation(t *testing.T) {
|
||||
cfg := DefaultConfig()
|
||||
if err := cfg.Validate(); err != nil {
|
||||
t.Fatalf("DefaultConfig should validate cleanly, got: %v", err)
|
||||
}
|
||||
rawDef, err := MarshalConfig(&cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("MarshalConfig failed: %v", err)
|
||||
}
|
||||
if issues := cfg.Lint(rawDef); len(issues) != 0 {
|
||||
t.Fatalf("DefaultConfig should have 0 lint issues, got: %v", issues)
|
||||
}
|
||||
|
||||
// Duplicate monitor ID
|
||||
cfg.Monitors = []MonitorConfig{
|
||||
{ID: "dup", Method: "tcp", Target: "127.0.0.1:80"},
|
||||
{ID: "dup", Method: "tcp", Target: "127.0.0.1:81"},
|
||||
|
|
@ -80,201 +66,10 @@ func TestConfigValidation(t *testing.T) {
|
|||
t.Fatalf("expected duplicate monitor id error")
|
||||
}
|
||||
|
||||
// Invalid regex
|
||||
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")
|
||||
}
|
||||
|
||||
// Invalid HTTP URL
|
||||
cfg.Monitors = []MonitorConfig{
|
||||
{ID: "bad-url", Method: "https", URL: "not-a-url"},
|
||||
}
|
||||
if err := cfg.Validate(); err == nil {
|
||||
t.Fatalf("expected invalid HTTP URL error")
|
||||
}
|
||||
|
||||
// Negative duration / retries
|
||||
cfg = DefaultConfig()
|
||||
cfg.Defaults.Interval = NewDuration(-5 * time.Second)
|
||||
if err := cfg.Validate(); err == nil {
|
||||
t.Fatalf("expected negative defaults.interval error")
|
||||
}
|
||||
|
||||
cfg = DefaultConfig()
|
||||
cfg.Monitors[0].Retries = IntPtr(-1)
|
||||
if err := cfg.Validate(); err == nil {
|
||||
t.Fatalf("expected negative monitor retries error")
|
||||
}
|
||||
|
||||
// Duplicate event IDs
|
||||
cfg = DefaultConfig()
|
||||
cfg.Events = append(cfg.Events, cfg.Events[0])
|
||||
if err := cfg.Validate(); err == nil {
|
||||
t.Fatalf("expected duplicate event id error")
|
||||
}
|
||||
|
||||
// Invalid webhook template
|
||||
cfg = DefaultConfig()
|
||||
cfg.Events[0].Actions = []EventAction{
|
||||
{Type: "webhook", URL: "https://hooks.example.com/test", BodyTemplate: "{{.Unclosed"},
|
||||
}
|
||||
if err := cfg.Validate(); err == nil {
|
||||
t.Fatalf("expected invalid webhook body_template error")
|
||||
}
|
||||
|
||||
// Valid json/jsonStr template functions in webhook
|
||||
cfg.Events[0].Actions = []EventAction{
|
||||
{Type: "webhook", URL: "https://hooks.example.com/test", BodyTemplate: `{"msg":{{json .EventName}},"sub":"{{jsonStr .Status}}"}`},
|
||||
}
|
||||
if err := cfg.Validate(); err != nil {
|
||||
t.Fatalf("expected valid json template functions, got: %v", err)
|
||||
}
|
||||
|
||||
// Invalid command template
|
||||
cfg.Events[0].Actions = []EventAction{
|
||||
{Type: "command", Command: "echo {{.MissingParen"},
|
||||
}
|
||||
if err := cfg.Validate(); err == nil {
|
||||
t.Fatalf("expected invalid command template error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAtomicSaveAndBackup(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
nestedPath := filepath.Join(tmpDir, "nested", "dir", "rud.json")
|
||||
|
||||
cfg := DefaultConfig()
|
||||
cfg.Page.Title = "Initial Title"
|
||||
if err := SaveConfig(nestedPath, &cfg); err != nil {
|
||||
t.Fatalf("SaveConfig nested path failed: %v", err)
|
||||
}
|
||||
|
||||
cfg.Page.Title = "Updated Title"
|
||||
bakPath, err := SaveConfigWithBackup(nestedPath, &cfg, true)
|
||||
if err != nil {
|
||||
t.Fatalf("SaveConfigWithBackup failed: %v", err)
|
||||
}
|
||||
if bakPath != nestedPath+".bak" {
|
||||
t.Fatalf("unexpected backup path %q", bakPath)
|
||||
}
|
||||
|
||||
bakBytes, err := os.ReadFile(bakPath)
|
||||
if err != nil {
|
||||
t.Fatalf("read backup failed: %v", err)
|
||||
}
|
||||
if !strings.Contains(string(bakBytes), "Initial Title") {
|
||||
t.Fatalf("backup did not contain initial content")
|
||||
}
|
||||
|
||||
loaded, raw, err := LoadForEdit(nestedPath)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadForEdit failed: %v", err)
|
||||
}
|
||||
if loaded.Page.Title != "Updated Title" {
|
||||
t.Fatalf("expected Updated Title, got %q", loaded.Page.Title)
|
||||
}
|
||||
if len(raw) == 0 {
|
||||
t.Fatalf("expected raw bytes from LoadForEdit")
|
||||
}
|
||||
|
||||
cloned, err := loaded.Clone()
|
||||
if err != nil {
|
||||
t.Fatalf("Clone failed: %v", err)
|
||||
}
|
||||
cloned.Page.Title = "Mutated Clone"
|
||||
if loaded.Page.Title != "Updated Title" {
|
||||
t.Fatalf("Clone mutation affected original")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigLint(t *testing.T) {
|
||||
raw := []byte(`{
|
||||
"unknown_top": true,
|
||||
"monitors": [
|
||||
{
|
||||
"id": "tcp-bad",
|
||||
"method": "tcp",
|
||||
"target": "no-port-here",
|
||||
"body_regx": "typo"
|
||||
}
|
||||
],
|
||||
"events": [
|
||||
{
|
||||
"id": "ev1",
|
||||
"name": "Ev",
|
||||
"condition": {
|
||||
"type": "state",
|
||||
"monitors": ["missing-mon"],
|
||||
"match": "some",
|
||||
"state": "down"
|
||||
},
|
||||
"actions": []
|
||||
}
|
||||
],
|
||||
"page": {
|
||||
"title": "Test",
|
||||
"elements": [
|
||||
{
|
||||
"type": "monitor_group",
|
||||
"monitors": ["missing-mon-2"],
|
||||
"layout": "carousel"
|
||||
},
|
||||
{
|
||||
"type": "unknown_widget"
|
||||
}
|
||||
]
|
||||
}
|
||||
}`)
|
||||
|
||||
cfg := Config{
|
||||
Monitors: []MonitorConfig{
|
||||
{ID: "tcp-bad", Method: "tcp", Target: "no-port-here"},
|
||||
},
|
||||
Events: []EventConfig{
|
||||
{
|
||||
ID: "ev1",
|
||||
Name: "Ev",
|
||||
Condition: EventCondition{
|
||||
Type: "state",
|
||||
Monitors: []string{"missing-mon"},
|
||||
Match: "some",
|
||||
State: "down",
|
||||
},
|
||||
},
|
||||
},
|
||||
Page: PageConfig{
|
||||
Title: "Test",
|
||||
Elements: []PageElement{
|
||||
{Type: "monitor_group", Monitors: []string{"missing-mon-2"}, Layout: "carousel"},
|
||||
{Type: "unknown_widget"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
issues := cfg.Lint(raw)
|
||||
joined := make([]string, 0, len(issues))
|
||||
for _, iss := range issues {
|
||||
joined = append(joined, iss.String())
|
||||
}
|
||||
all := strings.Join(joined, "\n")
|
||||
|
||||
wantSubstrings := []string{
|
||||
"unknown_top",
|
||||
"monitors[0].body_regx",
|
||||
"host:port",
|
||||
"has no actions",
|
||||
"missing-mon",
|
||||
"unknown match mode",
|
||||
"missing-mon-2",
|
||||
"unknown monitor_group layout",
|
||||
"unknown page element type",
|
||||
}
|
||||
for _, want := range wantSubstrings {
|
||||
if !strings.Contains(all, want) {
|
||||
t.Errorf("expected lint issues to contain %q, got:\n%s", want, all)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,10 +22,8 @@ import (
|
|||
|
||||
type ruleState struct {
|
||||
Active bool
|
||||
Notified bool
|
||||
ActiveSince time.Time
|
||||
LastFiredAt time.Time
|
||||
LastTriggeredIDs []string
|
||||
}
|
||||
|
||||
// EventPayload is passed to webhook body templates and command templates when an event triggers or resolves.
|
||||
|
|
@ -87,35 +85,27 @@ func (e *Engine) Evaluate(ctx context.Context, snap store.Snapshot) {
|
|||
matched, matchedIDs := e.evalCondition(ev.ID, "root", ev.Condition, snap, now)
|
||||
if matched {
|
||||
cooldown := ev.Cooldown.Std()
|
||||
canFire := !st.Active && (st.LastFiredAt.IsZero() || cooldown <= 0 || now.Sub(st.LastFiredAt) >= cooldown)
|
||||
if !st.Active {
|
||||
st.Active = true
|
||||
st.ActiveSince = now
|
||||
}
|
||||
cooldownOK := st.LastFiredAt.IsZero() || cooldown <= 0 || now.Sub(st.LastFiredAt) >= cooldown
|
||||
if !st.Notified && cooldownOK {
|
||||
st.Notified = true
|
||||
if canFire {
|
||||
st.LastFiredAt = now
|
||||
st.LastTriggeredIDs = append([]string(nil), matchedIDs...)
|
||||
payload := buildPayload(ev, "TRIGGERED", matchedIDs, snap, now)
|
||||
e.dispatchActions(ctx, ev.ID, payload, ev.Actions)
|
||||
}
|
||||
} else {
|
||||
if st.Active {
|
||||
st.Active = false
|
||||
if st.Notified {
|
||||
st.Notified = false
|
||||
if ev.TriggerOnRecovery {
|
||||
actions := ev.RecoveryActions
|
||||
if len(actions) == 0 {
|
||||
actions = ev.Actions
|
||||
}
|
||||
recoveryIDs := st.LastTriggeredIDs
|
||||
if len(recoveryIDs) == 0 {
|
||||
recoveryIDs = matchedIDs
|
||||
}
|
||||
payload := buildPayload(ev, "RESOLVED", recoveryIDs, snap, now)
|
||||
payload := buildPayload(ev, "RESOLVED", matchedIDs, snap, now)
|
||||
e.dispatchActions(ctx, ev.ID, payload, actions)
|
||||
}
|
||||
st.LastTriggeredIDs = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -153,14 +143,15 @@ func (e *Engine) evalCondition(eventID, path string, cond config.EventCondition,
|
|||
return anyMatched, collected
|
||||
}
|
||||
|
||||
// Default: "and" — evaluate all children so sibling metric 'for' timers reset when metrics recover
|
||||
allMatched := true
|
||||
// Default: "and"
|
||||
if len(cond.Conditions) == 0 {
|
||||
return false, nil
|
||||
}
|
||||
for i, sub := range cond.Conditions {
|
||||
subPath := fmt.Sprintf("%s.%d", path, i)
|
||||
ok, ids := e.evalCondition(eventID, subPath, sub, snap, now)
|
||||
if !ok {
|
||||
allMatched = false
|
||||
continue
|
||||
return false, nil
|
||||
}
|
||||
for _, id := range ids {
|
||||
if !seen[id] {
|
||||
|
|
@ -169,9 +160,6 @@ func (e *Engine) evalCondition(eventID, path string, cond config.EventCondition,
|
|||
}
|
||||
}
|
||||
}
|
||||
if !allMatched {
|
||||
return false, nil
|
||||
}
|
||||
return true, collected
|
||||
}
|
||||
|
||||
|
|
@ -438,7 +426,7 @@ func executeCommand(ctx context.Context, act config.EventAction, payload EventPa
|
|||
}
|
||||
|
||||
func renderTemplate(tmplStr string, data EventPayload) (string, error) {
|
||||
t, err := template.New("action").Funcs(config.ActionTemplateFuncMap()).Parse(tmplStr)
|
||||
t, err := template.New("action").Parse(tmplStr)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ package events
|
|||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
|
|
@ -149,134 +148,5 @@ func TestEventEngineBooleanAndSustainedDurationAndMetricTriggers(t *testing.T) {
|
|||
if len(webhookBodies) != 2 || !strings.Contains(webhookBodies[1], `"status":"RESOLVED"`) {
|
||||
t.Fatalf("expected recovery webhook call, got %v", webhookBodies)
|
||||
}
|
||||
if !strings.Contains(webhookBodies[1], `"monitors":"1"`) {
|
||||
t.Fatalf("expected recovery payload to preserve triggered monitors, got %s", webhookBodies[1])
|
||||
}
|
||||
webhookMu.Unlock()
|
||||
}
|
||||
|
||||
func TestCooldownFlapAndAndTimerResetAndJSONTemplate(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
var payloads []EventPayload
|
||||
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
var decoded struct {
|
||||
Event string `json:"event"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &decoded); err != nil {
|
||||
t.Errorf("invalid JSON produced by body_template: %v (body=%s)", err, string(body))
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
evCfg := []config.EventConfig{
|
||||
{
|
||||
ID: "cooldown-rule",
|
||||
Name: `Quote "Test" Alert`,
|
||||
Cooldown: config.NewDuration(10 * time.Minute),
|
||||
TriggerOnRecovery: true,
|
||||
Condition: config.EventCondition{
|
||||
Operator: "and",
|
||||
Conditions: []config.EventCondition{
|
||||
{
|
||||
Type: "state",
|
||||
Monitors: []string{"m1"},
|
||||
Match: "all",
|
||||
State: "down",
|
||||
},
|
||||
{
|
||||
Type: "metric",
|
||||
Monitors: []string{"m1"},
|
||||
Match: "all",
|
||||
Metric: "latency_ms",
|
||||
Comparator: ">",
|
||||
Value: 100,
|
||||
For: config.NewDuration(2 * time.Minute),
|
||||
},
|
||||
},
|
||||
},
|
||||
Actions: []config.EventAction{
|
||||
{
|
||||
Type: "webhook",
|
||||
URL: ts.URL,
|
||||
BodyTemplate: `{"event":{{json .EventName}},"status":"{{jsonStr .Status}}"}`,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
eng := NewEngine(evCfg)
|
||||
eng.ActionHook = func(eventID, status, actionType string, payload EventPayload) {
|
||||
mu.Lock()
|
||||
payloads = append(payloads, payload)
|
||||
mu.Unlock()
|
||||
}
|
||||
|
||||
mkSnap := func(ts time.Time, state string, latency float64) store.Snapshot {
|
||||
m := store.MonitorState{ID: "m1", State: state, StateChangedAt: ts, LatencyMs: latency}
|
||||
return store.Snapshot{
|
||||
OverallState: state,
|
||||
UpdatedAt: ts,
|
||||
Monitors: []store.MonitorState{m},
|
||||
MonitorsByID: map[string]store.MonitorState{"m1": m},
|
||||
}
|
||||
}
|
||||
|
||||
t0 := time.Now().UTC()
|
||||
// Start latency high while state=down -> starts metric 'for' timer at t0
|
||||
eng.Evaluate(context.Background(), mkSnap(t0, store.StateDown, 250))
|
||||
// At t0+3m condition holds (>= 2m) -> fires TRIGGERED
|
||||
eng.Evaluate(context.Background(), mkSnap(t0.Add(3*time.Minute), store.StateDown, 250))
|
||||
eng.Wait()
|
||||
// Recover at t0+4m -> fires RESOLVED
|
||||
eng.Evaluate(context.Background(), mkSnap(t0.Add(4*time.Minute), store.StateUp, 10))
|
||||
eng.Wait()
|
||||
|
||||
// Within cooldown (t0+5m): state=up (first condition false!), latency=250 (second condition true)
|
||||
eng.Evaluate(context.Background(), mkSnap(t0.Add(5*time.Minute), store.StateUp, 250))
|
||||
// At t0+6m: latency drops back to 20 -> 'and' must still evaluate child 1 to reset its 'for' timer!
|
||||
eng.Evaluate(context.Background(), mkSnap(t0.Add(6*time.Minute), store.StateUp, 20))
|
||||
// At t0+7m: flap inside cooldown (down + latency 250) -> suppressed, and NO spurious RESOLVED on recovery at t0+8m
|
||||
eng.Evaluate(context.Background(), mkSnap(t0.Add(7*time.Minute), store.StateDown, 250))
|
||||
eng.Evaluate(context.Background(), mkSnap(t0.Add(8*time.Minute), store.StateUp, 20))
|
||||
eng.Wait()
|
||||
|
||||
mu.Lock()
|
||||
if len(payloads) != 2 {
|
||||
t.Fatalf("expected 2 alerts (TRIGGERED, RESOLVED) before cooldown flap, got %d: %+v", len(payloads), payloads)
|
||||
}
|
||||
mu.Unlock()
|
||||
|
||||
// At t0+14m (after 10m cooldown elapsed), start outage again: latency timer must require a full 2m (should NOT fire at t0+14m even though t0+5m was >2m ago!)
|
||||
eng.Evaluate(context.Background(), mkSnap(t0.Add(14*time.Minute), store.StateDown, 250))
|
||||
eng.Wait()
|
||||
mu.Lock()
|
||||
if len(payloads) != 2 {
|
||||
t.Fatalf("expected stale metric timer to have been reset, got premature alert count=%d", len(payloads))
|
||||
}
|
||||
mu.Unlock()
|
||||
|
||||
// At t0+16m30s (held for 2m30s), should fire TRIGGERED
|
||||
eng.Evaluate(context.Background(), mkSnap(t0.Add(16*time.Minute+30*time.Second), store.StateDown, 250))
|
||||
eng.Wait()
|
||||
mu.Lock()
|
||||
if len(payloads) != 3 || payloads[2].Status != "TRIGGERED" {
|
||||
t.Fatalf("expected 3rd alert TRIGGERED after cooldown + sustained 2m, got %+v", payloads)
|
||||
}
|
||||
mu.Unlock()
|
||||
|
||||
// Recover at t0+17m -> fires RESOLVED (count=4)
|
||||
eng.Evaluate(context.Background(), mkSnap(t0.Add(17*time.Minute), store.StateUp, 10))
|
||||
// Re-enter outage during cooldown at t0+18m -> suppressed initially, then persists past t0+26m30s -> should fire!
|
||||
eng.Evaluate(context.Background(), mkSnap(t0.Add(18*time.Minute), store.StateDown, 250))
|
||||
eng.Evaluate(context.Background(), mkSnap(t0.Add(27*time.Minute), store.StateDown, 250))
|
||||
eng.Wait()
|
||||
mu.Lock()
|
||||
if len(payloads) != 5 || payloads[4].Status != "TRIGGERED" {
|
||||
t.Fatalf("expected outage started during cooldown to fire once cooldown expires, got %+v", payloads)
|
||||
}
|
||||
mu.Unlock()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -152,7 +152,7 @@ type renderedElement struct {
|
|||
|
||||
// Banner
|
||||
BannerMessage string
|
||||
BannerMessagesJSON string
|
||||
BannerMessagesJSON template.JS
|
||||
ShowOverallUptime bool
|
||||
ShowCounts bool
|
||||
|
||||
|
|
@ -186,7 +186,7 @@ type monitorDisplayFlags struct {
|
|||
ShowDescription bool
|
||||
ShowMessage bool
|
||||
ShowLastChecked bool
|
||||
LabelsJSON string
|
||||
LabelsJSON template.JS
|
||||
}
|
||||
|
||||
type monitorView struct {
|
||||
|
|
@ -239,7 +239,7 @@ func (s *Server) renderHTML(snap store.Snapshot) ([]byte, error) {
|
|||
elements = append(elements, renderedElement{
|
||||
Type: "status_banner",
|
||||
BannerMessage: msgs[snap.OverallState],
|
||||
BannerMessagesJSON: string(msgBytes),
|
||||
BannerMessagesJSON: template.JS(msgBytes),
|
||||
ShowOverallUptime: el.ShowOverallUptime,
|
||||
ShowCounts: el.ShowCounts,
|
||||
})
|
||||
|
|
@ -368,7 +368,7 @@ func resolveDisplayFlags(d config.MonitorDisplayConfig, defaultTicks int) monito
|
|||
ShowDescription: boolVal(d.ShowDescription, true),
|
||||
ShowMessage: boolVal(d.ShowMessage, false),
|
||||
ShowLastChecked: boolVal(d.ShowLastChecked, false),
|
||||
LabelsJSON: string(labelsBytes),
|
||||
LabelsJSON: template.JS(labelsBytes),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -440,23 +440,8 @@ func selectGroupMonitors(ids []string, snap store.Snapshot, flags monitorDisplay
|
|||
return views
|
||||
}
|
||||
|
||||
var cssSanitizer = strings.NewReplacer(
|
||||
"{", "",
|
||||
"}", "",
|
||||
";", "",
|
||||
"<", "",
|
||||
">", "",
|
||||
"\r", "",
|
||||
"\n", "",
|
||||
)
|
||||
|
||||
func safeCSSValue(v string) template.CSS {
|
||||
return template.CSS(cssSanitizer.Replace(strings.TrimSpace(v)))
|
||||
}
|
||||
|
||||
var templates = template.Must(template.New("status").Funcs(template.FuncMap{
|
||||
"upper": strings.ToUpper,
|
||||
"safeCSS": safeCSSValue,
|
||||
"Version": func() string {
|
||||
return Version
|
||||
},
|
||||
|
|
@ -468,19 +453,19 @@ var templates = template.Must(template.New("status").Funcs(template.FuncMap{
|
|||
},
|
||||
}).Parse(`{{define "pagecss"}}<style>
|
||||
:root {
|
||||
--bg: {{safeCSS .Theme.BgColor}};
|
||||
--card: {{safeCSS .Theme.CardBgColor}};
|
||||
--text: {{safeCSS .Theme.TextColor}};
|
||||
--muted: {{safeCSS .Theme.MutedTextColor}};
|
||||
--border: {{safeCSS .Theme.BorderColor}};
|
||||
--accent: {{safeCSS .Theme.AccentColor}};
|
||||
--up: {{safeCSS .Theme.UpColor}};
|
||||
--degraded: {{safeCSS .Theme.DegradedColor}};
|
||||
--down: {{safeCSS .Theme.DownColor}};
|
||||
--pending: {{safeCSS .Theme.PendingColor}};
|
||||
--font: {{safeCSS .Theme.FontFamily}};
|
||||
--maxw: {{safeCSS .Theme.MaxWidth}};
|
||||
--radius: {{safeCSS .Theme.BorderRadius}};
|
||||
--bg: {{.Theme.BgColor}};
|
||||
--card: {{.Theme.CardBgColor}};
|
||||
--text: {{.Theme.TextColor}};
|
||||
--muted: {{.Theme.MutedTextColor}};
|
||||
--border: {{.Theme.BorderColor}};
|
||||
--accent: {{.Theme.AccentColor}};
|
||||
--up: {{.Theme.UpColor}};
|
||||
--degraded: {{.Theme.DegradedColor}};
|
||||
--down: {{.Theme.DownColor}};
|
||||
--pending: {{.Theme.PendingColor}};
|
||||
--font: {{.Theme.FontFamily}};
|
||||
--maxw: {{.Theme.MaxWidth}};
|
||||
--radius: {{.Theme.BorderRadius}};
|
||||
}
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body {
|
||||
|
|
@ -718,7 +703,7 @@ a:hover { color: var(--accent); }
|
|||
<div class="mon-sub">
|
||||
<span>
|
||||
{{- if and $disp.ShowDescription .Monitor.Description}}{{.Monitor.Description}}{{end}}
|
||||
{{- if $disp.ShowMessage}} <span data-field="message">{{if .Monitor.LastMessage}}({{.Monitor.LastMessage}}){{end}}</span>{{end}}
|
||||
{{- if and $disp.ShowMessage .Monitor.LastMessage}} <span data-field="message">({{.Monitor.LastMessage}})</span>{{end}}
|
||||
</span>
|
||||
{{- if $disp.ShowLastChecked}}<span data-field="last-checked">{{.LastChecked}}</span>{{end}}
|
||||
</div>
|
||||
|
|
@ -808,26 +793,17 @@ a:hover { color: var(--accent); }
|
|||
if (bar && Array.isArray(m.history)) {
|
||||
var hist = m.history.slice(-ticksCount);
|
||||
var pad = ticksCount - hist.length;
|
||||
var frag = document.createDocumentFragment();
|
||||
var html = '';
|
||||
for (var i = 0; i < pad; i++) {
|
||||
var pt = document.createElement('div');
|
||||
pt.className = 'tick';
|
||||
pt.setAttribute('data-state', 'pending');
|
||||
pt.title = 'No data';
|
||||
frag.appendChild(pt);
|
||||
html += '<div class="tick" data-state="pending" title="No data"></div>';
|
||||
}
|
||||
for (var j = 0; j < hist.length; j++) {
|
||||
var h = hist[j];
|
||||
var t = h.timestamp ? new Date(h.timestamp).toISOString().slice(11, 19) + ' UTC' : '';
|
||||
var tip = t + ' | ' + (h.state || '').toUpperCase() + ' | ' + (h.latency_ms || 0).toFixed(1) + 'ms' + (h.message ? ' | ' + h.message : '');
|
||||
var tk = document.createElement('div');
|
||||
tk.className = 'tick';
|
||||
tk.setAttribute('data-state', h.state || 'pending');
|
||||
tk.title = tip;
|
||||
frag.appendChild(tk);
|
||||
html += '<div class="tick" data-state="' + h.state + '" title="' + tip.replace(/"/g, '"') + '"></div>';
|
||||
}
|
||||
bar.textContent = '';
|
||||
bar.appendChild(frag);
|
||||
bar.innerHTML = html;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -68,54 +68,3 @@ func TestSingleEndpointHTMLAndJSON(t *testing.T) {
|
|||
t.Fatalf("expected JSON status 'down', got %q", snap.OverallState)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerSecurityAndRenderingFixes(t *testing.T) {
|
||||
cfg := config.DefaultConfig()
|
||||
cfg.Page.Theme.FontFamily = `"JetBrains Mono", monospace`
|
||||
cfg.Page.Theme.BgColor = `#111111; } </style><script>alert(1)</script>`
|
||||
cfg.Page.Elements = []config.PageElement{
|
||||
{
|
||||
Type: "status_banner",
|
||||
Messages: map[string]string{
|
||||
"down": "We're experiencing issues",
|
||||
},
|
||||
},
|
||||
{
|
||||
Type: "monitor_group",
|
||||
Monitors: []string{"rud-http"},
|
||||
Display: &config.MonitorDisplayConfig{
|
||||
ShowMessage: config.BoolPtr(true),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
st := store.New(&cfg) // rud-http is pending with empty LastMessage
|
||||
srv := New(&cfg, st)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200 OK, got %d", w.Code)
|
||||
}
|
||||
body := w.Body.String()
|
||||
|
||||
if strings.Contains(body, "ZgotmplZ") {
|
||||
t.Fatalf("unexpected ZgotmplZ in rendered HTML CSS")
|
||||
}
|
||||
if !strings.Contains(body, `--font: "JetBrains Mono", monospace;`) {
|
||||
t.Fatalf("expected quoted FontFamily to render intact, got:\n%s", body)
|
||||
}
|
||||
if strings.Contains(body, `<script>alert(1)</script>`) {
|
||||
t.Fatalf("CSS value breakout was not stripped")
|
||||
}
|
||||
if !strings.Contains(body, `We're experiencing issues`) {
|
||||
t.Fatalf("expected single quote in data-messages to be HTML-attribute escaped")
|
||||
}
|
||||
if !strings.Contains(body, `data-field="message"`) {
|
||||
t.Fatalf("expected [data-field=\"message\"] placeholder even when monitor LastMessage is empty")
|
||||
}
|
||||
if strings.Contains(body, `bar.innerHTML`) {
|
||||
t.Fatalf("expected safe DOM construction instead of bar.innerHTML")
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -73,7 +73,6 @@ type Snapshot struct {
|
|||
// Store manages the thread-safe ring buffer and state for all configured monitors.
|
||||
type Store struct {
|
||||
mu sync.RWMutex
|
||||
saveMu sync.Mutex
|
||||
historySize int
|
||||
persistenceFile string
|
||||
order []string
|
||||
|
|
@ -301,13 +300,11 @@ func (s *Store) LoadFromDisk() error {
|
|||
curr.ConsecutiveSuccesses = saved.ConsecutiveSuccesses
|
||||
curr.LastMessage = saved.LastMessage
|
||||
|
||||
hist := make([]CheckResult, 0, s.historySize)
|
||||
if len(saved.History) > s.historySize {
|
||||
hist = append(hist, saved.History[len(saved.History)-s.historySize:]...)
|
||||
curr.History = append([]CheckResult(nil), saved.History[len(saved.History)-s.historySize:]...)
|
||||
} else {
|
||||
hist = append(hist, saved.History...)
|
||||
curr.History = append([]CheckResult(nil), saved.History...)
|
||||
}
|
||||
curr.History = hist
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -318,9 +315,6 @@ func (s *Store) SaveToDisk() error {
|
|||
return nil
|
||||
}
|
||||
|
||||
s.saveMu.Lock()
|
||||
defer s.saveMu.Unlock()
|
||||
|
||||
s.mu.RLock()
|
||||
ps := persistedState{
|
||||
SavedAt: time.Now().UTC(),
|
||||
|
|
@ -343,42 +337,13 @@ func (s *Store) SaveToDisk() error {
|
|||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
dir = "."
|
||||
}
|
||||
|
||||
tmp, err := os.CreateTemp(dir, ".rud_state-*.tmp")
|
||||
if err != nil {
|
||||
tmpFile := s.persistenceFile + ".tmp"
|
||||
if err := os.WriteFile(tmpFile, data, 0644); err != nil {
|
||||
return err
|
||||
}
|
||||
tmpFile := tmp.Name()
|
||||
cleanup := true
|
||||
defer func() {
|
||||
if cleanup {
|
||||
_ = os.Remove(tmpFile)
|
||||
}
|
||||
}()
|
||||
|
||||
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(tmpFile, s.persistenceFile); err != nil {
|
||||
return err
|
||||
}
|
||||
cleanup = false
|
||||
return nil
|
||||
return os.Rename(tmpFile, s.persistenceFile)
|
||||
}
|
||||
|
||||
func round2(v float64) float64 {
|
||||
|
|
|
|||
|
|
@ -1,11 +1,7 @@
|
|||
package store
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
|
|
@ -60,52 +56,3 @@ func TestStoreRingBufferAndPersistence(t *testing.T) {
|
|||
t.Fatalf("expected restored TotalChecks=4, got %d", snap2.MonitorsByID["m1"].TotalChecks)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreNullHistoryAndConcurrentSaves(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
persistPath := filepath.Join(tmpDir, "state.json")
|
||||
|
||||
// Simulate persisted state with explicit null history
|
||||
raw := `{"saved_at":"2026-01-01T00:00:00Z","monitors":{"m1":{"id":"m1","name":"Mon 1","method":"http","state":"pending","history":null}}}`
|
||||
if err := os.WriteFile(persistPath, []byte(raw), 0644); err != nil {
|
||||
t.Fatalf("write seed state failed: %v", err)
|
||||
}
|
||||
|
||||
cfg := config.DefaultConfig()
|
||||
cfg.Storage.HistorySize = 5
|
||||
cfg.Storage.PersistenceFile = persistPath
|
||||
cfg.Monitors = []config.MonitorConfig{
|
||||
{ID: "m1", Name: "Mon 1", Method: "http", URL: "http://localhost"},
|
||||
}
|
||||
|
||||
st := New(&cfg)
|
||||
if err := st.LoadFromDisk(); err != nil {
|
||||
t.Fatalf("LoadFromDisk failed: %v", err)
|
||||
}
|
||||
|
||||
snap := st.Snapshot()
|
||||
if snap.MonitorsByID["m1"].History == nil {
|
||||
t.Fatalf("expected non-nil History slice after restoring null history")
|
||||
}
|
||||
b, err := json.Marshal(snap)
|
||||
if err != nil {
|
||||
t.Fatalf("json.Marshal snapshot failed: %v", err)
|
||||
}
|
||||
if strings.Contains(string(b), `"history":null`) {
|
||||
t.Fatalf("expected [] instead of null in JSON snapshot: %s", string(b))
|
||||
}
|
||||
|
||||
// Concurrent Record + SaveToDisk calls under -race
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 8; i++ {
|
||||
wg.Add(1)
|
||||
go func(idx int) {
|
||||
defer wg.Done()
|
||||
st.Record("m1", CheckResult{State: StateUp, LatencyMs: float64(idx)})
|
||||
if err := st.SaveToDisk(); err != nil {
|
||||
t.Errorf("concurrent SaveToDisk failed: %v", err)
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
|
|
|||
200
main.go
200
main.go
|
|
@ -2,21 +2,17 @@ package main
|
|||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"git.gsdistance.org/tyuXX/RUD/internal/builder"
|
||||
"git.gsdistance.org/tyuXX/RUD/internal/checker"
|
||||
"git.gsdistance.org/tyuXX/RUD/internal/config"
|
||||
"git.gsdistance.org/tyuXX/RUD/internal/events"
|
||||
|
|
@ -27,82 +23,12 @@ import (
|
|||
|
||||
const Version = "1.0.0"
|
||||
|
||||
func defaultConfigPath() string {
|
||||
if p := os.Getenv("RUD_CONFIG"); p != "" {
|
||||
return p
|
||||
}
|
||||
return "rud.json"
|
||||
}
|
||||
|
||||
func printCLIHelp(out io.Writer) {
|
||||
_, _ = fmt.Fprintf(out, `R u ded? (rud) v%s — Minimalist self-contained uptime monitor
|
||||
|
||||
Usage:
|
||||
rud [server flags] Run the HTTP status server & check scheduler
|
||||
rud config [flags] Interactive configuration builder (new or edit)
|
||||
rud validate [flags] Validate and lint a configuration file
|
||||
rud test [flags] [ids...] Run live health checks once and exit
|
||||
rud help Show this help message
|
||||
|
||||
Server Flags:
|
||||
-config string Path to rud.json configuration file (default $RUD_CONFIG or "rud.json")
|
||||
-init Generate a sensible default rud.json at -config path and exit
|
||||
-version Print version information and exit
|
||||
|
||||
Subcommand Flags:
|
||||
rud config:
|
||||
-config string Path to configuration file (default $RUD_CONFIG or "rud.json")
|
||||
-new Force new-config starter flow even if file already exists
|
||||
-plain Use numbered line prompts instead of arrow-key terminal UI
|
||||
-no-color Disable ANSI colors
|
||||
|
||||
rud validate:
|
||||
-config string Path to configuration file (default $RUD_CONFIG or "rud.json")
|
||||
-strict Exit non-zero if any lint warnings are found
|
||||
|
||||
rud test:
|
||||
-config string Path to configuration file (default $RUD_CONFIG or "rud.json")
|
||||
-json Output structured JSON results
|
||||
-no-retry Disable configured retries during one-shot test
|
||||
`, Version)
|
||||
}
|
||||
|
||||
func main() {
|
||||
if len(os.Args) > 1 {
|
||||
switch os.Args[1] {
|
||||
case "config", "configure":
|
||||
if err := runConfigCmd(os.Args[2:]); err != nil {
|
||||
if errors.Is(err, builder.ErrAborted) {
|
||||
fmt.Fprintln(os.Stderr, "Aborted.")
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
case "validate":
|
||||
if err := runValidateCmd(os.Args[2:]); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Validation failed: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
case "test":
|
||||
if err := runTestCmd(os.Args[2:]); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "%v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
case "help":
|
||||
printCLIHelp(os.Stdout)
|
||||
return
|
||||
}
|
||||
defaultCfgPath := os.Getenv("RUD_CONFIG")
|
||||
if defaultCfgPath == "" {
|
||||
defaultCfgPath = "rud.json"
|
||||
}
|
||||
|
||||
defaultCfgPath := defaultConfigPath()
|
||||
|
||||
flag.Usage = func() {
|
||||
printCLIHelp(os.Stderr)
|
||||
}
|
||||
cfgPath := flag.String("config", defaultCfgPath, "Path to rud.json configuration file")
|
||||
initOnly := flag.Bool("init", false, "Generate a sensible default rud.json at -config path and exit")
|
||||
showVersion := flag.Bool("version", false, "Print version information and exit")
|
||||
|
|
@ -225,11 +151,8 @@ func main() {
|
|||
sched.Start(ctx)
|
||||
|
||||
// Optional periodic state persistence
|
||||
var saveWg sync.WaitGroup
|
||||
if cfg.Storage.PersistenceFile != "" && cfg.Storage.SaveInterval.Std() > 0 {
|
||||
saveWg.Add(1)
|
||||
go func() {
|
||||
defer saveWg.Done()
|
||||
ticker := time.NewTicker(cfg.Storage.SaveInterval.Std())
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
|
|
@ -254,7 +177,6 @@ func main() {
|
|||
|
||||
sched.Wait()
|
||||
evEngine.Wait()
|
||||
saveWg.Wait()
|
||||
|
||||
if dailyLog != nil {
|
||||
if err := dailyLog.Close(); err != nil {
|
||||
|
|
@ -274,119 +196,3 @@ func main() {
|
|||
}
|
||||
log.Printf("Shutdown complete.")
|
||||
}
|
||||
|
||||
func runConfigCmd(args []string) error {
|
||||
fs := flag.NewFlagSet("config", flag.ExitOnError)
|
||||
cfgPath := fs.String("config", defaultConfigPath(), "Path to configuration file")
|
||||
forceNew := fs.Bool("new", false, "Create a new configuration from starter templates/wizard")
|
||||
plain := fs.Bool("plain", false, "Use plain numbered prompts instead of arrow-key terminal mode")
|
||||
noColor := fs.Bool("no-color", false, "Disable ANSI colors")
|
||||
_ = fs.Parse(args)
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
return builder.Run(ctx, builder.Options{
|
||||
ConfigPath: *cfgPath,
|
||||
ForceNew: *forceNew,
|
||||
Plain: *plain,
|
||||
NoColor: *noColor,
|
||||
In: os.Stdin,
|
||||
Out: os.Stdout,
|
||||
})
|
||||
}
|
||||
|
||||
func runValidateCmd(args []string) error {
|
||||
fs := flag.NewFlagSet("validate", flag.ExitOnError)
|
||||
cfgPath := fs.String("config", defaultConfigPath(), "Path to configuration file")
|
||||
strict := fs.Bool("strict", false, "Fail on lint warnings as well as validation errors")
|
||||
_ = fs.Parse(args)
|
||||
|
||||
return validateConfigFile(*cfgPath, *strict, os.Stdout)
|
||||
}
|
||||
|
||||
func validateConfigFile(cfgPath string, strict bool, out io.Writer) error {
|
||||
cfg, raw, err := config.LoadForEdit(cfgPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cloned, err := cfg.Clone()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cloned.ApplyFallbacks()
|
||||
if err := cloned.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
issues := cloned.Lint(raw)
|
||||
_, _ = fmt.Fprintf(out, "✓ Configuration %s is valid (%d monitors, %d events, %d page elements)\n",
|
||||
cfgPath, len(cloned.Monitors), len(cloned.Events), len(cloned.Page.Elements))
|
||||
|
||||
if len(issues) > 0 {
|
||||
_, _ = fmt.Fprintf(out, "! %d lint warning(s):\n", len(issues))
|
||||
for _, iss := range issues {
|
||||
_, _ = fmt.Fprintf(out, " - %s\n", iss.String())
|
||||
}
|
||||
if strict {
|
||||
return fmt.Errorf("%d lint warning(s) found in -strict mode", len(issues))
|
||||
}
|
||||
} else {
|
||||
_, _ = fmt.Fprintln(out, "✓ 0 lint warnings")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func runTestCmd(args []string) error {
|
||||
fs := flag.NewFlagSet("test", flag.ExitOnError)
|
||||
cfgPath := fs.String("config", defaultConfigPath(), "Path to configuration file")
|
||||
jsonOut := fs.Bool("json", false, "Output results as JSON")
|
||||
noRetry := fs.Bool("no-retry", false, "Disable retries during live test")
|
||||
_ = fs.Parse(args)
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
return runMonitorTestsCmd(ctx, *cfgPath, fs.Args(), !*noRetry, *jsonOut, os.Stdout)
|
||||
}
|
||||
|
||||
func runMonitorTestsCmd(ctx context.Context, cfgPath string, ids []string, retry bool, jsonOut bool, out io.Writer) error {
|
||||
cfg, _, err := config.LoadOrInit(cfgPath, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
results, err := builder.RunLiveTests(ctx, cfg, ids, retry)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if jsonOut {
|
||||
enc := json.NewEncoder(out)
|
||||
enc.SetEscapeHTML(false)
|
||||
enc.SetIndent("", " ")
|
||||
if err := enc.Encode(results); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
useColor := false
|
||||
if f, ok := out.(*os.File); ok {
|
||||
if fi, statErr := f.Stat(); statErr == nil && (fi.Mode()&os.ModeCharDevice) != 0 && os.Getenv("NO_COLOR") == "" && os.Getenv("TERM") != "dumb" {
|
||||
useColor = true
|
||||
}
|
||||
}
|
||||
builder.PrintLiveTestTable(out, results, useColor)
|
||||
}
|
||||
|
||||
downCount := 0
|
||||
for _, r := range results {
|
||||
if r.State == store.StateDown {
|
||||
downCount++
|
||||
}
|
||||
}
|
||||
if downCount > 0 {
|
||||
return fmt.Errorf("%d monitor(s) failed live check", downCount)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
111
main_test.go
111
main_test.go
|
|
@ -1,111 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.gsdistance.org/tyuXX/RUD/internal/builder"
|
||||
"git.gsdistance.org/tyuXX/RUD/internal/config"
|
||||
)
|
||||
|
||||
func TestValidateConfigFile(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
cleanPath := filepath.Join(tmpDir, "clean.json")
|
||||
cfg := config.DefaultConfig()
|
||||
if err := config.SaveConfig(cleanPath, &cfg); err != nil {
|
||||
t.Fatalf("SaveConfig failed: %v", err)
|
||||
}
|
||||
|
||||
var out bytes.Buffer
|
||||
if err := validateConfigFile(cleanPath, true, &out); err != nil {
|
||||
t.Fatalf("expected clean config to pass strict validation, got: %v\n%s", err, out.String())
|
||||
}
|
||||
if !strings.Contains(out.String(), "0 lint warnings") {
|
||||
t.Fatalf("expected 0 lint warnings message, got:\n%s", out.String())
|
||||
}
|
||||
|
||||
// File with an unknown field -> passes normal mode, fails strict mode
|
||||
warnPath := filepath.Join(tmpDir, "warn.json")
|
||||
raw := `{"unknown_field":1,"monitors":[{"id":"m1","method":"cmd","command":"echo ok"}]}`
|
||||
if err := os.WriteFile(warnPath, []byte(raw), 0644); err != nil {
|
||||
t.Fatalf("WriteFile failed: %v", err)
|
||||
}
|
||||
|
||||
out.Reset()
|
||||
if err := validateConfigFile(warnPath, false, &out); err != nil {
|
||||
t.Fatalf("expected non-strict validate to pass with warnings, got: %v", err)
|
||||
}
|
||||
if !strings.Contains(out.String(), "unknown_field") {
|
||||
t.Fatalf("expected unknown_field warning, got:\n%s", out.String())
|
||||
}
|
||||
|
||||
out.Reset()
|
||||
if err := validateConfigFile(warnPath, true, &out); err == nil {
|
||||
t.Fatalf("expected strict validate to fail on lint warning")
|
||||
}
|
||||
|
||||
// Invalid monitor config -> always fails
|
||||
badPath := filepath.Join(tmpDir, "bad.json")
|
||||
if err := os.WriteFile(badPath, []byte(`{"monitors":[{"id":"m1","method":"http"}]}`), 0644); err != nil {
|
||||
t.Fatalf("WriteFile failed: %v", err)
|
||||
}
|
||||
out.Reset()
|
||||
if err := validateConfigFile(badPath, false, &out); err == nil {
|
||||
t.Fatalf("expected invalid HTTP monitor without url to fail validation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunMonitorTestsCmd(t *testing.T) {
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte("pong"))
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
cfgPath := filepath.Join(tmpDir, "rud.json")
|
||||
cfg := builder.BlankMinimalConfig()
|
||||
cfg.Monitors = []config.MonitorConfig{
|
||||
{ID: "ok-http", Name: "OK HTTP", Method: "http", URL: ts.URL, BodyRegex: `^pong$`},
|
||||
{ID: "ok-cmd", Name: "OK Cmd", Method: "cmd", Command: "echo ok", Shell: true},
|
||||
{ID: "fail-cmd", Name: "Fail Cmd", Method: "cmd", Command: "exit 2", Shell: true},
|
||||
}
|
||||
if err := config.SaveConfig(cfgPath, &cfg); err != nil {
|
||||
t.Fatalf("SaveConfig failed: %v", err)
|
||||
}
|
||||
|
||||
// Test passing monitors in table format
|
||||
var out bytes.Buffer
|
||||
if err := runMonitorTestsCmd(context.Background(), cfgPath, []string{"ok-http", "ok-cmd"}, false, false, &out); err != nil {
|
||||
t.Fatalf("expected passing monitors test to succeed, got: %v\n%s", err, out.String())
|
||||
}
|
||||
if !strings.Contains(out.String(), "ok-http") || !strings.Contains(out.String(), "UP") {
|
||||
t.Fatalf("unexpected table output:\n%s", out.String())
|
||||
}
|
||||
|
||||
// Test passing monitor in JSON format
|
||||
out.Reset()
|
||||
if err := runMonitorTestsCmd(context.Background(), cfgPath, []string{"ok-http"}, false, true, &out); err != nil {
|
||||
t.Fatalf("expected JSON test to succeed, got: %v", err)
|
||||
}
|
||||
var results []builder.MonitorTestResult
|
||||
if err := json.Unmarshal(out.Bytes(), &results); err != nil {
|
||||
t.Fatalf("invalid JSON output: %v\n%s", err, out.String())
|
||||
}
|
||||
if len(results) != 1 || results[0].ID != "ok-http" || results[0].State != "up" {
|
||||
t.Fatalf("unexpected JSON results: %+v", results)
|
||||
}
|
||||
|
||||
// Test failing monitor returns non-nil error
|
||||
out.Reset()
|
||||
if err := runMonitorTestsCmd(context.Background(), cfgPath, []string{"fail-cmd"}, false, false, &out); err == nil {
|
||||
t.Fatalf("expected failing monitor to return error")
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue