Harden core packages and add interactive CLI config builder (rud config/validate/test)

This commit is contained in:
tyuXX 2026-11-19 13:05:26 +00:00
parent d37503c863
commit 99e24be6c9
29 changed files with 6763 additions and 165 deletions

200
main.go
View file

@ -2,17 +2,21 @@ 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"
@ -22,12 +26,82 @@ 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() {
defaultCfgPath := os.Getenv("RUD_CONFIG")
if defaultCfgPath == "" {
defaultCfgPath = "rud.json"
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 := 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")
@ -99,8 +173,11 @@ 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 {
@ -125,6 +202,7 @@ func main() {
sched.Wait()
evEngine.Wait()
saveWg.Wait()
if cfg.Storage.PersistenceFile != "" {
if err := st.SaveToDisk(); err != nil {
@ -133,3 +211,119 @@ 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
}