1052 lines
28 KiB
Go
1052 lines
28 KiB
Go
package builder
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
"text/template"
|
|
"time"
|
|
|
|
"git.gsdistance.org/tyuXX/RUD/internal/config"
|
|
)
|
|
|
|
func editEvents(ui *UI, cfg *config.Config) error {
|
|
for {
|
|
sub := fmt.Sprintf("%d event rule(s) configured", len(cfg.Events))
|
|
opts := []Option{
|
|
{Label: "Add event rule", Description: "Use a quick recipe or build a custom AND/OR rule"},
|
|
}
|
|
if len(cfg.Events) > 0 {
|
|
opts = append(opts,
|
|
Option{Label: "Edit event rule", Description: "Modify conditions, actions, cooldown, or recovery"},
|
|
Option{Label: "Duplicate event rule"},
|
|
Option{Label: "Delete event rule"},
|
|
)
|
|
}
|
|
opts = append(opts, Option{Label: "Back to main hub"})
|
|
|
|
idx, ok, err := ui.Select("Events & Alerts", 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 event rule":
|
|
if err := addEventFlow(ui, cfg); err != nil {
|
|
return err
|
|
}
|
|
case "Edit event rule":
|
|
eIdx, eOK, err := pickEvent(ui, cfg.Events, "Select event rule to edit")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if eOK {
|
|
if err := editSingleEvent(ui, cfg, eIdx); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
case "Duplicate event rule":
|
|
eIdx, eOK, err := pickEvent(ui, cfg.Events, "Select event rule to duplicate")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if eOK {
|
|
cp := cloneEvent(cfg.Events[eIdx])
|
|
defID := uniqueEventID(cfg, cp.ID+"-copy")
|
|
newID, err := ui.PromptString("New event ID", defID, "unique identifier", false, validateNewEventID(cfg, -1))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
cp.ID = newID
|
|
cp.Name = cp.Name + " (Copy)"
|
|
cfg.Events = append(cfg.Events, cp)
|
|
ui.Ok(fmt.Sprintf("Duplicated event %q as %q.", cfg.Events[eIdx].ID, cp.ID))
|
|
}
|
|
case "Delete event rule":
|
|
eIdx, eOK, err := pickEvent(ui, cfg.Events, "Select event rule to delete")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if eOK {
|
|
target := cfg.Events[eIdx]
|
|
yes, err := ui.Confirm(fmt.Sprintf("Delete event %q (%s)?", target.ID, target.Name), false)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if yes {
|
|
cfg.Events = append(cfg.Events[:eIdx], cfg.Events[eIdx+1:]...)
|
|
ui.Ok(fmt.Sprintf("Deleted event %q.", target.ID))
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func pickEvent(ui *UI, events []config.EventConfig, title string) (int, bool, error) {
|
|
opts := make([]Option, len(events))
|
|
for i, ev := range events {
|
|
opts[i] = Option{
|
|
Label: fmt.Sprintf("%s — %s", ev.ID, ev.Name),
|
|
Description: summarizeCondition(ev.Condition),
|
|
}
|
|
}
|
|
return ui.Select(title, "", opts, -1)
|
|
}
|
|
|
|
func addEventFlow(ui *UI, cfg *config.Config) error {
|
|
recipeOpts := []Option{
|
|
{Label: "Any monitor down for a sustained duration", Description: "e.g. any monitor down for 5m"},
|
|
{Label: "All selected monitors down simultaneously", Description: "e.g. primary + backup both down"},
|
|
{Label: "Uptime percentage drops below threshold", Description: "metric: uptime_pct < X%"},
|
|
{Label: "High latency alert", Description: "metric: latency_ms > Xms"},
|
|
{Label: "Consecutive failures threshold", Description: "metric: consecutive_failures >= N"},
|
|
{Label: "Custom / Composite (AND / OR) rule", Description: "Build arbitrary nested conditions"},
|
|
{Label: "Cancel"},
|
|
}
|
|
|
|
rIdx, rOK, err := ui.Select("New Event Rule — Choose Recipe", "Start from a common alerting pattern or build a custom tree", recipeOpts, 0)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !rOK || rIdx == len(recipeOpts)-1 {
|
|
return nil
|
|
}
|
|
|
|
defID := uniqueEventID(cfg, fmt.Sprintf("event-%d", len(cfg.Events)+1))
|
|
id, err := ui.PromptString("Event ID", defID, "unique slug", false, validateNewEventID(cfg, -1))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
var defaultName string
|
|
var cond config.EventCondition
|
|
|
|
switch rIdx {
|
|
case 0: // Any down for duration
|
|
mons, mOK, err := selectConditionMonitors(ui, cfg, []string{"*"})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !mOK {
|
|
return nil
|
|
}
|
|
forDur, err := ui.PromptDuration("Sustained outage duration (for)", config.NewDuration(5*time.Minute), true)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
cond = config.EventCondition{Type: "state", Monitors: mons, Match: "any", State: "down", For: forDur}
|
|
defaultName = "Monitor Down Alert"
|
|
case 1: // All selected down
|
|
mons, mOK, err := selectConditionMonitors(ui, cfg, []string{"*"})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !mOK {
|
|
return nil
|
|
}
|
|
forDur, err := ui.PromptDuration("Sustained duration (for)", 0, true)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
cond = config.EventCondition{Type: "state", Monitors: mons, Match: "all", State: "down", For: forDur}
|
|
defaultName = "All Selected Monitors Down"
|
|
case 2: // Uptime < X%
|
|
mons, mOK, err := selectConditionMonitors(ui, cfg, []string{"*"})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !mOK {
|
|
return nil
|
|
}
|
|
val, err := ui.PromptFloat("Uptime percentage threshold (<)", 99.0)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
forDur, err := ui.PromptDuration("Sustained duration (for)", config.NewDuration(15*time.Minute), true)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
cond = config.EventCondition{Type: "metric", Monitors: mons, Match: "any", Metric: "uptime_pct", Comparator: "<", Value: val, For: forDur}
|
|
defaultName = fmt.Sprintf("Uptime Below %.1f%%", val)
|
|
case 3: // High latency > Xms
|
|
mons, mOK, err := selectConditionMonitors(ui, cfg, []string{"*"})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !mOK {
|
|
return nil
|
|
}
|
|
val, err := ui.PromptFloat("Latency threshold in ms (>)", 500.0)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
forDur, err := ui.PromptDuration("Sustained duration (for)", config.NewDuration(2*time.Minute), true)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
cond = config.EventCondition{Type: "metric", Monitors: mons, Match: "any", Metric: "latency_ms", Comparator: ">", Value: val, For: forDur}
|
|
defaultName = fmt.Sprintf("High Latency (> %.0fms)", val)
|
|
case 4: // Consecutive failures >= N
|
|
mons, mOK, err := selectConditionMonitors(ui, cfg, []string{"*"})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !mOK {
|
|
return nil
|
|
}
|
|
cnt, err := ui.PromptInt("Consecutive failures (>=)", 3, 1, 1000)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
cond = config.EventCondition{Type: "metric", Monitors: mons, Match: "any", Metric: "consecutive_failures", Comparator: ">=", Value: float64(cnt)}
|
|
defaultName = fmt.Sprintf("Consecutive Failures (>= %d)", cnt)
|
|
case 5: // Custom composite rule
|
|
opOpts := []Option{
|
|
{Label: "or", Description: "Trigger when ANY child condition matches"},
|
|
{Label: "and", Description: "Trigger only when ALL child conditions match"},
|
|
}
|
|
opIdx, opOK, err := ui.Select("Root Boolean Operator", "", opOpts, 0)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !opOK {
|
|
return nil
|
|
}
|
|
cond = config.EventCondition{
|
|
Operator: opOpts[opIdx].Label,
|
|
Conditions: []config.EventCondition{
|
|
{Type: "state", Monitors: []string{"*"}, Match: "any", State: "down"},
|
|
},
|
|
}
|
|
defaultName = "Custom Alert Rule"
|
|
}
|
|
|
|
name, err := ui.PromptString("Event name", defaultName, "human-readable title", false, requireNonEmpty("name"))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
cooldown, err := ui.PromptDuration("Alert cooldown", config.NewDuration(30*time.Minute), true)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
recovery, err := ui.Confirm("Send RESOLVED notification on recovery?", true)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
ev := config.EventConfig{
|
|
ID: id,
|
|
Name: name,
|
|
Cooldown: cooldown,
|
|
TriggerOnRecovery: recovery,
|
|
Condition: cond,
|
|
Actions: []config.EventAction{},
|
|
}
|
|
|
|
if rIdx == 5 {
|
|
if err := editConditionTree(ui, cfg, &ev.Condition); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
ui.Info("Now add at least one notification action (webhook or command) for this event:")
|
|
if err := addActionFlow(ui, &ev.Actions); err != nil {
|
|
return err
|
|
}
|
|
|
|
cfg.Events = append(cfg.Events, ev)
|
|
ui.Ok(fmt.Sprintf("Added event rule %q.", ev.ID))
|
|
return nil
|
|
}
|
|
|
|
func editSingleEvent(ui *UI, cfg *config.Config, evIdx int) error {
|
|
for {
|
|
ev := &cfg.Events[evIdx]
|
|
sub := fmt.Sprintf("Cooldown: %s | Recovery: %v | Actions: %d | Condition: %s",
|
|
ev.Cooldown.Std(), ev.TriggerOnRecovery, len(ev.Actions), summarizeCondition(ev.Condition))
|
|
opts := []Option{
|
|
{Label: "Edit basic settings", Description: fmt.Sprintf("id=%s, name=%q, cooldown=%s", ev.ID, ev.Name, ev.Cooldown.Std())},
|
|
{Label: "Edit condition tree", Description: summarizeCondition(ev.Condition)},
|
|
{Label: "Edit alert actions", Description: fmt.Sprintf("%d action(s)", len(ev.Actions))},
|
|
{Label: "Edit recovery actions (optional)", Description: fmt.Sprintf("%d recovery action(s)", len(ev.RecoveryActions))},
|
|
{Label: "Done"},
|
|
}
|
|
|
|
idx, ok, err := ui.Select("Edit Event: "+ev.ID, sub, opts, len(opts)-1)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !ok || idx == len(opts)-1 {
|
|
return nil
|
|
}
|
|
|
|
switch idx {
|
|
case 0:
|
|
newID, err := ui.PromptString("Event ID", ev.ID, "unique ID", false, validateNewEventID(cfg, evIdx))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
newName, err := ui.PromptString("Event name", ev.Name, "", false, requireNonEmpty("name"))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
cd, err := ui.PromptDuration("Cooldown", ev.Cooldown, true)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
rec, err := ui.Confirm("Trigger notification on recovery?", ev.TriggerOnRecovery)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
ev.ID = newID
|
|
ev.Name = newName
|
|
ev.Cooldown = cd
|
|
ev.TriggerOnRecovery = rec
|
|
case 1:
|
|
if err := editConditionTree(ui, cfg, &ev.Condition); err != nil {
|
|
return err
|
|
}
|
|
case 2:
|
|
if err := editActionsList(ui, "Alert Actions: "+ev.ID, &ev.Actions); err != nil {
|
|
return err
|
|
}
|
|
case 3:
|
|
if err := editActionsList(ui, "Recovery Actions (empty = reuse alert actions): "+ev.ID, &ev.RecoveryActions); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
type flatCondNode struct {
|
|
ptr *config.EventCondition
|
|
parent *config.EventCondition
|
|
childIdx int
|
|
treeLabel string
|
|
summary string
|
|
}
|
|
|
|
func flattenConditionTree(node, parent *config.EventCondition, childIdx int, indent string, isLast bool, isRoot bool, out *[]flatCondNode) {
|
|
connector := ""
|
|
nextIndent := indent
|
|
if !isRoot {
|
|
if isLast {
|
|
connector = indent + "└─ "
|
|
nextIndent = indent + " "
|
|
} else {
|
|
connector = indent + "├─ "
|
|
nextIndent = indent + "│ "
|
|
}
|
|
}
|
|
|
|
var summary string
|
|
if len(node.Conditions) > 0 {
|
|
op := strings.ToUpper(strings.TrimSpace(node.Operator))
|
|
if op == "" {
|
|
op = "AND"
|
|
}
|
|
summary = fmt.Sprintf("%s (%d child condition(s))", op, len(node.Conditions))
|
|
} else {
|
|
summary = summarizeCondition(*node)
|
|
}
|
|
|
|
*out = append(*out, flatCondNode{
|
|
ptr: node,
|
|
parent: parent,
|
|
childIdx: childIdx,
|
|
treeLabel: connector + summary,
|
|
summary: summary,
|
|
})
|
|
|
|
for i := range node.Conditions {
|
|
flattenConditionTree(&node.Conditions[i], node, i, nextIndent, i == len(node.Conditions)-1, false, out)
|
|
}
|
|
}
|
|
|
|
func editConditionTree(ui *UI, cfg *config.Config, root *config.EventCondition) error {
|
|
for {
|
|
var nodes []flatCondNode
|
|
flattenConditionTree(root, nil, -1, "", true, true, &nodes)
|
|
|
|
opts := make([]Option, 0, len(nodes)+1)
|
|
for _, n := range nodes {
|
|
opts = append(opts, Option{Label: n.treeLabel})
|
|
}
|
|
opts = append(opts, Option{Label: "Done editing condition tree"})
|
|
|
|
idx, ok, err := ui.Select("Condition Tree Editor", "Select any node to edit, wrap into AND/OR, add children, or delete", opts, len(opts)-1)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !ok || idx == len(opts)-1 {
|
|
return nil
|
|
}
|
|
|
|
node := nodes[idx]
|
|
if len(node.ptr.Conditions) > 0 {
|
|
if err := editGroupConditionNode(ui, cfg, node); err != nil {
|
|
return err
|
|
}
|
|
} else {
|
|
if err := editLeafConditionNode(ui, cfg, node); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func editGroupConditionNode(ui *UI, cfg *config.Config, node flatCondNode) error {
|
|
curOp := strings.ToLower(strings.TrimSpace(node.ptr.Operator))
|
|
if curOp == "" {
|
|
curOp = "and"
|
|
}
|
|
otherOp := "or"
|
|
if curOp == "or" {
|
|
otherOp = "and"
|
|
}
|
|
|
|
opts := []Option{
|
|
{Label: fmt.Sprintf("Switch operator (%s -> %s)", strings.ToUpper(curOp), strings.ToUpper(otherOp))},
|
|
{Label: "Add child leaf condition (state or metric)"},
|
|
{Label: "Add nested AND/OR group"},
|
|
}
|
|
if node.parent != nil && len(node.parent.Conditions) > 1 {
|
|
opts = append(opts, Option{Label: "Delete this group"})
|
|
}
|
|
opts = append(opts, Option{Label: "Back"})
|
|
|
|
idx, ok, err := ui.Select("Group Node: "+strings.ToUpper(curOp), "", opts, len(opts)-1)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !ok || opts[idx].Label == "Back" {
|
|
return nil
|
|
}
|
|
|
|
switch opts[idx].Label {
|
|
case fmt.Sprintf("Switch operator (%s -> %s)", strings.ToUpper(curOp), strings.ToUpper(otherOp)):
|
|
node.ptr.Operator = otherOp
|
|
ui.Ok("Switched group operator to " + strings.ToUpper(otherOp) + ".")
|
|
case "Add child leaf condition (state or metric)":
|
|
leaf := config.EventCondition{Type: "state", Monitors: []string{"*"}, Match: "any", State: "down"}
|
|
if saved, err := editLeafConditionForm(ui, cfg, &leaf); err != nil {
|
|
return err
|
|
} else if saved {
|
|
node.ptr.Conditions = append(node.ptr.Conditions, leaf)
|
|
}
|
|
case "Add nested AND/OR group":
|
|
opOpts := []Option{{Label: "or"}, {Label: "and"}}
|
|
oIdx, oOK, err := ui.Select("Nested Group Operator", "", opOpts, 0)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if oOK {
|
|
leaf := config.EventCondition{Type: "state", Monitors: []string{"*"}, Match: "any", State: "down"}
|
|
if saved, err := editLeafConditionForm(ui, cfg, &leaf); err != nil {
|
|
return err
|
|
} else if saved {
|
|
node.ptr.Conditions = append(node.ptr.Conditions, config.EventCondition{
|
|
Operator: opOpts[oIdx].Label,
|
|
Conditions: []config.EventCondition{leaf},
|
|
})
|
|
}
|
|
}
|
|
case "Delete this group":
|
|
if node.parent != nil && node.childIdx >= 0 && node.childIdx < len(node.parent.Conditions) {
|
|
node.parent.Conditions = append(node.parent.Conditions[:node.childIdx], node.parent.Conditions[node.childIdx+1:]...)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func editLeafConditionNode(ui *UI, cfg *config.Config, node flatCondNode) error {
|
|
opts := []Option{
|
|
{Label: "Edit leaf parameters", Description: node.summary},
|
|
{Label: "Wrap in new AND / OR group", Description: "Convert this leaf into a composite group containing it"},
|
|
}
|
|
if node.parent != nil && len(node.parent.Conditions) > 1 {
|
|
opts = append(opts, Option{Label: "Delete this condition"})
|
|
}
|
|
opts = append(opts, Option{Label: "Back"})
|
|
|
|
idx, ok, err := ui.Select("Leaf Node", node.summary, opts, 0)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !ok || opts[idx].Label == "Back" {
|
|
return nil
|
|
}
|
|
|
|
switch opts[idx].Label {
|
|
case "Edit leaf parameters":
|
|
_, err := editLeafConditionForm(ui, cfg, node.ptr)
|
|
return err
|
|
case "Wrap in new AND / OR group":
|
|
opOpts := []Option{
|
|
{Label: "or", Description: "Group passes if ANY child passes"},
|
|
{Label: "and", Description: "Group passes if ALL children pass"},
|
|
}
|
|
oIdx, oOK, err := ui.Select("Group Operator", "", opOpts, 0)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if oOK {
|
|
oldLeaf := *node.ptr
|
|
*node.ptr = config.EventCondition{
|
|
Operator: opOpts[oIdx].Label,
|
|
Conditions: []config.EventCondition{oldLeaf},
|
|
}
|
|
ui.Ok("Wrapped leaf in " + strings.ToUpper(opOpts[oIdx].Label) + " group.")
|
|
}
|
|
case "Delete this condition":
|
|
if node.parent != nil && node.childIdx >= 0 && node.childIdx < len(node.parent.Conditions) {
|
|
node.parent.Conditions = append(node.parent.Conditions[:node.childIdx], node.parent.Conditions[node.childIdx+1:]...)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func editLeafConditionForm(ui *UI, cfg *config.Config, cond *config.EventCondition) (bool, error) {
|
|
t := strings.ToLower(cond.Type)
|
|
if t == "" {
|
|
if cond.Metric != "" {
|
|
t = "metric"
|
|
} else {
|
|
t = "state"
|
|
}
|
|
}
|
|
typeOpts := []Option{
|
|
{Label: "state", Description: "Monitor state equals up / degraded / down / pending"},
|
|
{Label: "metric", Description: "Numeric metric threshold (uptime_pct, latency_ms, consecutive_failures)"},
|
|
}
|
|
defT := 0
|
|
if t == "metric" {
|
|
defT = 1
|
|
}
|
|
tIdx, tOK, err := ui.Select("Condition Type", "", typeOpts, defT)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
if !tOK {
|
|
return false, nil
|
|
}
|
|
|
|
mons, mOK, err := selectConditionMonitors(ui, cfg, cond.Monitors)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
if !mOK {
|
|
return false, nil
|
|
}
|
|
|
|
matchOpts := []Option{
|
|
{Label: "all", Description: "Every targeted monitor must match"},
|
|
{Label: "any", Description: "At least one targeted monitor must match"},
|
|
}
|
|
defMatch := 0
|
|
if strings.EqualFold(cond.Match, "any") {
|
|
defMatch = 1
|
|
}
|
|
maIdx, maOK, err := ui.Select("Match Mode", "", matchOpts, defMatch)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
if !maOK {
|
|
return false, nil
|
|
}
|
|
|
|
next := config.EventCondition{
|
|
Type: typeOpts[tIdx].Label,
|
|
Monitors: mons,
|
|
Match: matchOpts[maIdx].Label,
|
|
}
|
|
|
|
if next.Type == "state" {
|
|
stateOpts := []Option{{Label: "down"}, {Label: "degraded"}, {Label: "up"}, {Label: "pending"}}
|
|
defS := 0
|
|
for i, o := range stateOpts {
|
|
if strings.EqualFold(o.Label, cond.State) {
|
|
defS = i
|
|
break
|
|
}
|
|
}
|
|
sIdx, sOK, err := ui.Select("Target State", "", stateOpts, defS)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
if !sOK {
|
|
return false, nil
|
|
}
|
|
next.State = stateOpts[sIdx].Label
|
|
} else {
|
|
metricOpts := []Option{
|
|
{Label: "uptime_pct", Description: "Monitor uptime percentage (0-100)"},
|
|
{Label: "latency_ms", Description: "Latest latency in milliseconds"},
|
|
{Label: "consecutive_failures", Description: "Consecutive failed checks"},
|
|
}
|
|
defMet := 0
|
|
for i, o := range metricOpts {
|
|
if strings.EqualFold(o.Label, cond.Metric) {
|
|
defMet = i
|
|
break
|
|
}
|
|
}
|
|
metIdx, metOK, err := ui.Select("Metric", "", metricOpts, defMet)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
if !metOK {
|
|
return false, nil
|
|
}
|
|
next.Metric = metricOpts[metIdx].Label
|
|
|
|
compOpts := []Option{
|
|
{Label: "<"}, {Label: "<="}, {Label: ">"}, {Label: ">="}, {Label: "=="}, {Label: "!="},
|
|
}
|
|
defC := 0
|
|
for i, o := range compOpts {
|
|
if o.Label == cond.Comparator {
|
|
defC = i
|
|
break
|
|
}
|
|
}
|
|
cIdx, cOK, err := ui.Select("Comparator", "", compOpts, defC)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
if !cOK {
|
|
return false, nil
|
|
}
|
|
next.Comparator = compOpts[cIdx].Label
|
|
|
|
defVal := cond.Value
|
|
if cond.Metric == "" && next.Metric == "uptime_pct" {
|
|
defVal = 99.0
|
|
}
|
|
val, err := ui.PromptFloat("Threshold value", defVal)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
next.Value = val
|
|
}
|
|
|
|
forDur, err := ui.PromptDuration("Sustained duration (for)", cond.For, true)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
next.For = forDur
|
|
|
|
*cond = next
|
|
return true, nil
|
|
}
|
|
|
|
func selectConditionMonitors(ui *UI, cfg *config.Config, current []string) ([]string, bool, error) {
|
|
opts := []Option{{Label: "*", Description: "All monitors"}}
|
|
seenOpt := map[string]bool{"*": true}
|
|
for _, m := range cfg.Monitors {
|
|
opts = append(opts, Option{Label: m.ID, Description: m.Name})
|
|
seenOpt[m.ID] = true
|
|
}
|
|
for _, id := range current {
|
|
if !seenOpt[id] {
|
|
opts = append(opts, Option{Label: id, Description: "(not currently defined in monitors)"})
|
|
seenOpt[id] = true
|
|
}
|
|
}
|
|
|
|
curSet := make(map[string]bool, len(current))
|
|
for _, id := range current {
|
|
curSet[id] = true
|
|
}
|
|
if len(current) == 0 {
|
|
curSet["*"] = true
|
|
}
|
|
pre := make(map[int]bool)
|
|
for i, o := range opts {
|
|
if curSet[o.Label] {
|
|
pre[i] = true
|
|
}
|
|
}
|
|
|
|
indices, ok, err := ui.MultiSelect("Target Monitors", "Choose '*' for all monitors or specific monitor IDs", opts, pre)
|
|
if err != nil || !ok {
|
|
return nil, ok, err
|
|
}
|
|
if len(indices) == 0 {
|
|
return []string{"*"}, true, nil
|
|
}
|
|
for _, idx := range indices {
|
|
if idx == 0 {
|
|
return []string{"*"}, true, nil
|
|
}
|
|
}
|
|
res := make([]string, 0, len(indices))
|
|
for _, idx := range indices {
|
|
res = append(res, opts[idx].Label)
|
|
}
|
|
return res, true, nil
|
|
}
|
|
|
|
func editActionsList(ui *UI, title string, actions *[]config.EventAction) error {
|
|
for {
|
|
sub := fmt.Sprintf("%d action(s)", len(*actions))
|
|
opts := []Option{
|
|
{Label: "Add action", Description: "Webhook preset, custom webhook, or shell command"},
|
|
}
|
|
if len(*actions) > 0 {
|
|
opts = append(opts,
|
|
Option{Label: "Edit action"},
|
|
Option{Label: "Delete action"},
|
|
)
|
|
}
|
|
opts = append(opts, Option{Label: "Done"})
|
|
|
|
idx, ok, err := ui.Select(title, sub, opts, len(opts)-1)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !ok || opts[idx].Label == "Done" {
|
|
return nil
|
|
}
|
|
|
|
switch opts[idx].Label {
|
|
case "Add action":
|
|
if err := addActionFlow(ui, actions); err != nil {
|
|
return err
|
|
}
|
|
case "Edit action":
|
|
aIdx, aOK, err := pickAction(ui, *actions, "Select action to edit")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if aOK {
|
|
if err := editActionForm(ui, &(*actions)[aIdx]); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
case "Delete action":
|
|
aIdx, aOK, err := pickAction(ui, *actions, "Select action to delete")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if aOK {
|
|
*actions = append((*actions)[:aIdx], (*actions)[aIdx+1:]...)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func pickAction(ui *UI, actions []config.EventAction, title string) (int, bool, error) {
|
|
opts := make([]Option, len(actions))
|
|
for i, act := range actions {
|
|
desc := act.URL
|
|
if strings.EqualFold(act.Type, "command") || strings.EqualFold(act.Type, "cmd") || strings.EqualFold(act.Type, "script") {
|
|
desc = act.Command
|
|
}
|
|
opts[i] = Option{
|
|
Label: fmt.Sprintf("[%d] %s", i+1, strings.ToUpper(act.Type)),
|
|
Description: desc,
|
|
}
|
|
}
|
|
return ui.Select(title, "", opts, -1)
|
|
}
|
|
|
|
func addActionFlow(ui *UI, actions *[]config.EventAction) error {
|
|
opts := []Option{
|
|
{Label: "Webhook from preset", Description: "Discord, Slack, ntfy, Gotify, or Generic JSON"},
|
|
{Label: "Custom webhook", Description: "Configure URL, headers, and custom Go template manually"},
|
|
{Label: "Shell command / script", Description: "Run a command with template placeholders & RUD_* env vars"},
|
|
{Label: "Cancel"},
|
|
}
|
|
idx, ok, err := ui.Select("Add Action", "", opts, 0)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !ok || idx == 3 {
|
|
return nil
|
|
}
|
|
|
|
switch idx {
|
|
case 0:
|
|
presets := WebhookPresets()
|
|
pOpts := make([]Option, len(presets)+1)
|
|
for i, p := range presets {
|
|
pOpts[i] = Option{Label: p.Name, Description: p.Description}
|
|
}
|
|
pOpts[len(presets)] = Option{Label: "Cancel"}
|
|
pIdx, pOK, err := ui.Select("Webhook Presets", "", pOpts, 0)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !pOK || pIdx == len(presets) {
|
|
return nil
|
|
}
|
|
preset := presets[pIdx]
|
|
ui.Info("URL hint: " + preset.URLHint)
|
|
u, err := ui.PromptString("Webhook URL", "", "https://...", false, validateHTTPURL)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var hdrs map[string]string
|
|
if len(preset.Headers) > 0 {
|
|
hdrs = make(map[string]string, len(preset.Headers))
|
|
for k, v := range preset.Headers {
|
|
hdrs[k] = v
|
|
}
|
|
}
|
|
act := config.EventAction{
|
|
Type: "webhook",
|
|
URL: u,
|
|
HTTPMethod: preset.HTTPMethod,
|
|
Headers: hdrs,
|
|
BodyTemplate: preset.Template,
|
|
Timeout: config.NewDuration(10 * time.Second),
|
|
}
|
|
*actions = append(*actions, act)
|
|
ui.Ok("Added " + preset.Name + " action.")
|
|
case 1:
|
|
act := config.EventAction{
|
|
Type: "webhook",
|
|
HTTPMethod: "POST",
|
|
Timeout: config.NewDuration(10 * time.Second),
|
|
}
|
|
if err := editActionForm(ui, &act); err != nil {
|
|
return err
|
|
}
|
|
if act.URL != "" {
|
|
*actions = append(*actions, act)
|
|
}
|
|
case 2:
|
|
act := config.EventAction{
|
|
Type: "command",
|
|
Shell: true,
|
|
Timeout: config.NewDuration(10 * time.Second),
|
|
}
|
|
if err := editActionForm(ui, &act); err != nil {
|
|
return err
|
|
}
|
|
if act.Command != "" {
|
|
*actions = append(*actions, act)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func editActionForm(ui *UI, act *config.EventAction) error {
|
|
ui.Header("Action Configuration", templateCheatsheet)
|
|
t := strings.ToLower(strings.TrimSpace(act.Type))
|
|
if t == "webhook" {
|
|
u, err := ui.PromptString("Webhook URL", act.URL, "https://...", false, validateHTTPURL)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
act.URL = u
|
|
|
|
defM := act.HTTPMethod
|
|
if defM == "" {
|
|
defM = "POST"
|
|
}
|
|
hm, err := ui.PromptString("HTTP Method", defM, "POST, PUT, etc.", false, requireNonEmpty("http_method"))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
act.HTTPMethod = strings.ToUpper(hm)
|
|
|
|
tmpl, err := ui.PromptString("Body template (optional)", act.BodyTemplate, "empty sends default EventPayload JSON", true, validateActionTemplate)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
act.BodyTemplate = tmpl
|
|
|
|
editHdrs, err := ui.Confirm("Edit webhook headers?", len(act.Headers) > 0)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if editHdrs {
|
|
hdrs, err := ui.EditStringMap("Webhook Headers", act.Headers)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
act.Headers = hdrs
|
|
}
|
|
|
|
to, err := ui.PromptDuration("Action timeout", act.Timeout, true)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
act.Timeout = to
|
|
return nil
|
|
}
|
|
|
|
// Command action
|
|
cmdStr, err := ui.PromptString("Command", act.Command, "supports Go template placeholders", false, func(s string) error {
|
|
if strings.TrimSpace(s) == "" {
|
|
return fmt.Errorf("command cannot be empty")
|
|
}
|
|
return validateActionTemplate(s)
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
act.Command = cmdStr
|
|
|
|
sh, err := ui.Confirm("Execute via /bin/sh -c (shell)?", act.Shell)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
act.Shell = sh
|
|
|
|
if !sh {
|
|
editArgs, err := ui.Confirm("Edit command arguments?", len(act.Args) > 0)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if editArgs {
|
|
args, err := ui.EditStringSlice("Command Arguments", "argument", act.Args)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
act.Args = args
|
|
}
|
|
}
|
|
|
|
to, err := ui.PromptDuration("Action timeout", act.Timeout, true)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
act.Timeout = to
|
|
return nil
|
|
}
|
|
|
|
func validateActionTemplate(tmplStr string) error {
|
|
if tmplStr == "" {
|
|
return nil
|
|
}
|
|
_, err := template.New("action").Funcs(config.ActionTemplateFuncMap()).Parse(tmplStr)
|
|
return err
|
|
}
|
|
|
|
func summarizeCondition(cond config.EventCondition) string {
|
|
if len(cond.Conditions) > 0 {
|
|
op := strings.ToUpper(strings.TrimSpace(cond.Operator))
|
|
if op == "" {
|
|
op = "AND"
|
|
}
|
|
parts := make([]string, 0, len(cond.Conditions))
|
|
for _, sub := range cond.Conditions {
|
|
parts = append(parts, summarizeCondition(sub))
|
|
}
|
|
return "(" + strings.Join(parts, " "+op+" ") + ")"
|
|
}
|
|
mons := strings.Join(cond.Monitors, ",")
|
|
if mons == "" {
|
|
mons = "*"
|
|
}
|
|
match := strings.ToLower(strings.TrimSpace(cond.Match))
|
|
if match == "" {
|
|
match = "all"
|
|
}
|
|
t := strings.ToLower(strings.TrimSpace(cond.Type))
|
|
if t == "" {
|
|
if cond.Metric != "" {
|
|
t = "metric"
|
|
} else {
|
|
t = "state"
|
|
}
|
|
}
|
|
var base string
|
|
if t == "metric" {
|
|
base = fmt.Sprintf("METRIC: %s of [%s] %s %s %g", match, mons, cond.Metric, cond.Comparator, cond.Value)
|
|
} else {
|
|
base = fmt.Sprintf("STATE: %s of [%s] == %s", match, mons, cond.State)
|
|
}
|
|
if cond.For > 0 {
|
|
base += fmt.Sprintf(" (for %s)", cond.For.Std())
|
|
}
|
|
return base
|
|
}
|
|
|
|
func validateNewEventID(cfg *config.Config, excludeIdx int) func(string) error {
|
|
return func(id string) error {
|
|
trimmed := strings.TrimSpace(id)
|
|
if trimmed == "" {
|
|
return fmt.Errorf("event id cannot be empty")
|
|
}
|
|
if strings.ContainsAny(trimmed, " \t\r\n") {
|
|
return fmt.Errorf("event id cannot contain whitespace")
|
|
}
|
|
for i, ev := range cfg.Events {
|
|
if i != excludeIdx && ev.ID == trimmed {
|
|
return fmt.Errorf("event id %q already exists", trimmed)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
}
|
|
|
|
func uniqueEventID(cfg *config.Config, base string) string {
|
|
taken := make(map[string]bool, len(cfg.Events))
|
|
for _, ev := range cfg.Events {
|
|
taken[ev.ID] = true
|
|
}
|
|
if !taken[base] {
|
|
return base
|
|
}
|
|
for n := 2; ; n++ {
|
|
cand := fmt.Sprintf("%s-%d", base, n)
|
|
if !taken[cand] {
|
|
return cand
|
|
}
|
|
}
|
|
}
|
|
|
|
func cloneEvent(ev config.EventConfig) config.EventConfig {
|
|
cp := ev
|
|
cp.Condition = cloneCondition(ev.Condition)
|
|
cp.Actions = cloneActions(ev.Actions)
|
|
cp.RecoveryActions = cloneActions(ev.RecoveryActions)
|
|
return cp
|
|
}
|
|
|
|
func cloneCondition(cond config.EventCondition) config.EventCondition {
|
|
cp := cond
|
|
if cond.Monitors != nil {
|
|
cp.Monitors = append([]string(nil), cond.Monitors...)
|
|
}
|
|
if cond.Conditions != nil {
|
|
cp.Conditions = make([]config.EventCondition, len(cond.Conditions))
|
|
for i, sub := range cond.Conditions {
|
|
cp.Conditions[i] = cloneCondition(sub)
|
|
}
|
|
}
|
|
return cp
|
|
}
|
|
|
|
func cloneActions(actions []config.EventAction) []config.EventAction {
|
|
if actions == nil {
|
|
return nil
|
|
}
|
|
out := make([]config.EventAction, len(actions))
|
|
for i, a := range actions {
|
|
cp := a
|
|
if a.Args != nil {
|
|
cp.Args = append([]string(nil), a.Args...)
|
|
}
|
|
if a.Headers != nil {
|
|
cp.Headers = make(map[string]string, len(a.Headers))
|
|
for k, v := range a.Headers {
|
|
cp.Headers[k] = v
|
|
}
|
|
}
|
|
if a.Env != nil {
|
|
cp.Env = make(map[string]string, len(a.Env))
|
|
for k, v := range a.Env {
|
|
cp.Env[k] = v
|
|
}
|
|
}
|
|
out[i] = cp
|
|
}
|
|
return out
|
|
}
|