841 lines
22 KiB
Go
841 lines
22 KiB
Go
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
|
|
}
|
|
}
|