This commit is contained in:
tyuXX 2026-11-01 13:11:54 +00:00
parent c823102a63
commit d37503c863
20 changed files with 4433 additions and 3 deletions

438
internal/events/engine.go Normal file
View file

@ -0,0 +1,438 @@
package events
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"sort"
"strings"
"sync"
"text/template"
"time"
"git.gsdistance.org/tyuXX/RUD/internal/config"
"git.gsdistance.org/tyuXX/RUD/internal/store"
)
type ruleState struct {
Active bool
ActiveSince time.Time
LastFiredAt time.Time
}
// EventPayload is passed to webhook body templates and command templates when an event triggers or resolves.
type EventPayload struct {
EventID string `json:"event_id"`
EventName string `json:"event_name"`
Status string `json:"status"` // "TRIGGERED" or "RESOLVED"
OverallState string `json:"overall_state"`
OverallUptimePct float64 `json:"overall_uptime_pct"`
TriggeredMonitors string `json:"triggered_monitors"`
Monitors []store.MonitorState `json:"monitors"`
MonitorsJSON string `json:"-"`
Timestamp string `json:"timestamp"`
}
// Engine evaluates declarative event rules against Store snapshots and dispatches actions.
type Engine struct {
mu sync.Mutex
events []config.EventConfig
states map[string]*ruleState
metricMatchedSince map[string]time.Time
actionWg sync.WaitGroup
ActionHook func(eventID, status, actionType string, payload EventPayload) // optional test hook
}
// NewEngine creates a new declarative Event Engine.
func NewEngine(events []config.EventConfig) *Engine {
states := make(map[string]*ruleState, len(events))
for _, ev := range events {
states[ev.ID] = &ruleState{}
}
return &Engine{
events: events,
states: states,
metricMatchedSince: make(map[string]time.Time),
}
}
// Evaluate checks all configured event rules against the given store snapshot.
func (e *Engine) Evaluate(ctx context.Context, snap store.Snapshot) {
if len(e.events) == 0 {
return
}
now := snap.UpdatedAt
if now.IsZero() {
now = time.Now().UTC()
}
e.mu.Lock()
defer e.mu.Unlock()
for _, ev := range e.events {
st := e.states[ev.ID]
if st == nil {
st = &ruleState{}
e.states[ev.ID] = st
}
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
}
if canFire {
st.LastFiredAt = now
payload := buildPayload(ev, "TRIGGERED", matchedIDs, snap, now)
e.dispatchActions(ctx, ev.ID, payload, ev.Actions)
}
} else {
if st.Active {
st.Active = false
if ev.TriggerOnRecovery {
actions := ev.RecoveryActions
if len(actions) == 0 {
actions = ev.Actions
}
payload := buildPayload(ev, "RESOLVED", matchedIDs, snap, now)
e.dispatchActions(ctx, ev.ID, payload, actions)
}
}
}
}
}
// Wait blocks until any in-flight asynchronous actions complete.
func (e *Engine) Wait() {
e.actionWg.Wait()
}
func (e *Engine) evalCondition(eventID, path string, cond config.EventCondition, snap store.Snapshot, now time.Time) (bool, []string) {
if len(cond.Conditions) > 0 {
op := strings.ToLower(strings.TrimSpace(cond.Operator))
if op == "" {
op = "and"
}
var collected []string
seen := make(map[string]bool)
if op == "or" {
anyMatched := false
for i, sub := range cond.Conditions {
subPath := fmt.Sprintf("%s.%d", path, i)
ok, ids := e.evalCondition(eventID, subPath, sub, snap, now)
if ok {
anyMatched = true
for _, id := range ids {
if !seen[id] {
seen[id] = true
collected = append(collected, id)
}
}
}
}
return anyMatched, collected
}
// 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 {
return false, nil
}
for _, id := range ids {
if !seen[id] {
seen[id] = true
collected = append(collected, id)
}
}
}
return true, collected
}
targets := selectMonitors(cond.Monitors, snap)
if len(targets) == 0 {
return false, nil
}
matchMode := strings.ToLower(strings.TrimSpace(cond.Match))
if matchMode == "" {
matchMode = "all"
}
condType := strings.ToLower(strings.TrimSpace(cond.Type))
if condType == "" {
if cond.Metric != "" {
condType = "metric"
} else {
condType = "state"
}
}
var matchedIDs []string
for _, m := range targets {
// Do not evaluate pending monitors unless state explicitly checks "pending"
if m.State == store.StatePending && strings.ToLower(cond.State) != store.StatePending {
continue
}
var monMatch bool
switch condType {
case "state":
targetState := strings.ToLower(strings.TrimSpace(cond.State))
if strings.ToLower(m.State) == targetState {
if cond.For.Std() <= 0 || (!m.StateChangedAt.IsZero() && now.Sub(m.StateChangedAt) >= cond.For.Std()) {
monMatch = true
}
}
case "metric":
rawMatch := compareMetric(m, cond.Metric, cond.Comparator, cond.Value)
key := fmt.Sprintf("%s:%s:%s", eventID, path, m.ID)
if rawMatch {
since, exists := e.metricMatchedSince[key]
if !exists {
since = now
e.metricMatchedSince[key] = since
}
if cond.For.Std() <= 0 || now.Sub(since) >= cond.For.Std() {
monMatch = true
}
} else {
delete(e.metricMatchedSince, key)
}
}
if monMatch {
matchedIDs = append(matchedIDs, m.ID)
}
}
if matchMode == "any" {
return len(matchedIDs) > 0, matchedIDs
}
// "all" mode requires every targeted monitor to match
return len(matchedIDs) == len(targets) && len(targets) > 0, matchedIDs
}
func selectMonitors(ids []string, snap store.Snapshot) []store.MonitorState {
if len(ids) == 0 {
return snap.Monitors
}
for _, id := range ids {
if id == "*" {
return snap.Monitors
}
}
res := make([]store.MonitorState, 0, len(ids))
for _, id := range ids {
if m, ok := snap.MonitorsByID[id]; ok {
res = append(res, m)
}
}
return res
}
func compareMetric(m store.MonitorState, metric, comparator string, threshold float64) bool {
var val float64
switch strings.ToLower(strings.TrimSpace(metric)) {
case "uptime_pct", "uptime":
val = m.UptimePct
case "latency_ms", "latency":
val = m.LatencyMs
case "consecutive_failures":
val = float64(m.ConsecutiveFailures)
default:
return false
}
switch strings.TrimSpace(comparator) {
case "<":
return val < threshold
case "<=":
return val <= threshold
case ">":
return val > threshold
case ">=":
return val >= threshold
case "==":
return val == threshold
case "!=":
return val != threshold
default:
return false
}
}
func buildPayload(ev config.EventConfig, status string, matchedIDs []string, snap store.Snapshot, now time.Time) EventPayload {
sort.Strings(matchedIDs)
monitors := make([]store.MonitorState, 0, len(matchedIDs))
for _, id := range matchedIDs {
if m, ok := snap.MonitorsByID[id]; ok {
monitors = append(monitors, m)
}
}
monBytes, _ := json.Marshal(monitors)
return EventPayload{
EventID: ev.ID,
EventName: ev.Name,
Status: status,
OverallState: snap.OverallState,
OverallUptimePct: snap.OverallUptimePct,
TriggeredMonitors: strings.Join(matchedIDs, ","),
Monitors: monitors,
MonitorsJSON: string(monBytes),
Timestamp: now.Format(time.RFC3339),
}
}
func (e *Engine) dispatchActions(ctx context.Context, eventID string, payload EventPayload, actions []config.EventAction) {
for _, act := range actions {
action := act
if e.ActionHook != nil {
e.ActionHook(eventID, payload.Status, action.Type, payload)
}
e.actionWg.Add(1)
go func() {
defer e.actionWg.Done()
timeout := action.Timeout.Std()
if timeout <= 0 {
timeout = 10 * time.Second
}
actCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
switch strings.ToLower(strings.TrimSpace(action.Type)) {
case "webhook":
if err := executeWebhook(actCtx, action, payload, timeout); err != nil {
log.Printf("[event:%s] webhook action error: %v", eventID, err)
}
case "command", "cmd", "script":
if err := executeCommand(actCtx, action, payload); err != nil {
log.Printf("[event:%s] command action error: %v", eventID, err)
}
}
}()
}
}
func executeWebhook(ctx context.Context, act config.EventAction, payload EventPayload, timeout time.Duration) error {
if act.URL == "" {
return fmt.Errorf("webhook URL is empty")
}
method := strings.ToUpper(strings.TrimSpace(act.HTTPMethod))
if method == "" {
method = http.MethodPost
}
var bodyBytes []byte
if act.BodyTemplate != "" {
rendered, err := renderTemplate(act.BodyTemplate, payload)
if err != nil {
return fmt.Errorf("render webhook body_template: %w", err)
}
bodyBytes = []byte(rendered)
} else {
var err error
bodyBytes, err = json.Marshal(payload)
if err != nil {
return err
}
}
req, err := http.NewRequestWithContext(ctx, method, act.URL, bytes.NewReader(bodyBytes))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", "RUD-Alert/1.0 (+https://git.gsdistance.org/tyuXX/RUD)")
for k, v := range act.Headers {
req.Header.Set(k, v)
}
client := &http.Client{Timeout: timeout}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
if resp.StatusCode >= 400 {
return fmt.Errorf("webhook returned HTTP %d", resp.StatusCode)
}
return nil
}
func executeCommand(ctx context.Context, act config.EventAction, payload EventPayload) error {
cmdStr, err := renderTemplate(act.Command, payload)
if err != nil {
return fmt.Errorf("render command template: %w", err)
}
args := make([]string, len(act.Args))
for i, a := range act.Args {
rendered, err := renderTemplate(a, payload)
if err != nil {
return fmt.Errorf("render arg template: %w", err)
}
args[i] = rendered
}
var cmd *exec.Cmd
if act.Shell || (len(args) == 0 && strings.ContainsAny(cmdStr, " \t|&;<>()$`\"'")) {
full := cmdStr
if len(args) > 0 {
full += " " + strings.Join(args, " ")
}
cmd = exec.CommandContext(ctx, "/bin/sh", "-c", full)
} else {
cmd = exec.CommandContext(ctx, cmdStr, args...)
}
if act.WorkingDir != "" {
cmd.Dir = act.WorkingDir
}
env := os.Environ()
env = append(env,
"RUD_EVENT_ID="+payload.EventID,
"RUD_EVENT_NAME="+payload.EventName,
"RUD_EVENT_STATUS="+payload.Status,
"RUD_OVERALL_STATE="+payload.OverallState,
"RUD_TRIGGERED_MONITORS="+payload.TriggeredMonitors,
"RUD_TIMESTAMP="+payload.Timestamp,
)
for k, v := range act.Env {
env = append(env, fmt.Sprintf("%s=%s", k, v))
}
cmd.Env = env
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("%w: %s", err, strings.TrimSpace(string(out)))
}
return nil
}
func renderTemplate(tmplStr string, data EventPayload) (string, error) {
t, err := template.New("action").Parse(tmplStr)
if err != nil {
return "", err
}
var buf bytes.Buffer
if err := t.Execute(&buf, data); err != nil {
return "", err
}
return buf.String(), nil
}

View file

@ -0,0 +1,152 @@
package events
import (
"context"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"git.gsdistance.org/tyuXX/RUD/internal/config"
"git.gsdistance.org/tyuXX/RUD/internal/store"
)
func TestEventEngineBooleanAndSustainedDurationAndMetricTriggers(t *testing.T) {
var webhookMu sync.Mutex
var webhookBodies []string
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
webhookMu.Lock()
webhookBodies = append(webhookBodies, string(b))
webhookMu.Unlock()
w.WriteHeader(http.StatusOK)
}))
defer ts.Close()
tmpFile := filepath.Join(t.TempDir(), "cmd_alert.txt")
evCfg := []config.EventConfig{
{
ID: "multi-or-sustained",
Name: "Multi Monitor Down or 5h Outage",
Cooldown: config.NewDuration(10 * time.Minute),
TriggerOnRecovery: true,
Condition: config.EventCondition{
Operator: "or",
Conditions: [ ]config.EventCondition{
// Monitors 1, 2, 3 are all down
{
Type: "state",
Monitors: []string{"1", "2", "3"},
Match: "all",
State: "down",
},
// Any monitor down for >= 5 hours AND uptime_pct < 90
{
Operator: "and",
Conditions: []config.EventCondition{
{
Type: "state",
Monitors: []string{"*"},
Match: "any",
State: "down",
For: config.NewDuration(5 * time.Hour),
},
{
Type: "metric",
Monitors: []string{"*"},
Match: "any",
Metric: "uptime_pct",
Comparator: "<",
Value: 90.0,
},
},
},
},
},
Actions: []config.EventAction{
{
Type: "webhook",
URL: ts.URL,
BodyTemplate: `{"event":"{{.EventID}}","status":"{{.Status}}","monitors":"{{.TriggeredMonitors}}"}`,
},
{
Type: "command",
Command: "printf '%s:%s' '{{.Status}}' '{{.TriggeredMonitors}}' > " + tmpFile,
Shell: true,
},
},
},
}
eng := NewEngine(evCfg)
now := time.Now().UTC()
// Case 1: Only monitor 1 and 2 are down for 1 minute (should NOT trigger)
snap1 := store.Snapshot{
OverallState: store.StateDown,
UpdatedAt: now,
Monitors: []store.MonitorState{
{ID: "1", State: store.StateDown, StateChangedAt: now.Add(-time.Minute), UptimePct: 95},
{ID: "2", State: store.StateDown, StateChangedAt: now.Add(-time.Minute), UptimePct: 95},
{ID: "3", State: store.StateUp, StateChangedAt: now.Add(-time.Hour), UptimePct: 100},
},
}
snap1.MonitorsByID = map[string]store.MonitorState{
"1": snap1.Monitors[0],
"2": snap1.Monitors[1],
"3": snap1.Monitors[2],
}
eng.Evaluate(context.Background(), snap1)
eng.Wait()
webhookMu.Lock()
if len(webhookBodies) != 0 {
t.Fatalf("expected 0 webhook calls, got %d", len(webhookBodies))
}
webhookMu.Unlock()
// Case 2: Monitor 1 has been down for 5h10m and uptime_pct is 80% (SHOULD trigger!)
snap2 := snap1
snap2.Monitors[0].StateChangedAt = now.Add(-5*time.Hour - 10*time.Minute)
snap2.Monitors[0].UptimePct = 80.0
snap2.MonitorsByID["1"] = snap2.Monitors[0]
eng.Evaluate(context.Background(), snap2)
eng.Wait()
webhookMu.Lock()
if len(webhookBodies) != 1 {
t.Fatalf("expected 1 webhook call on sustained 5h + metric trigger, got %d", len(webhookBodies))
}
if !strings.Contains(webhookBodies[0], `"status":"TRIGGERED"`) {
t.Fatalf("unexpected webhook body: %s", webhookBodies[0])
}
webhookMu.Unlock()
cmdData, err := os.ReadFile(tmpFile)
if err != nil || !strings.HasPrefix(string(cmdData), "TRIGGERED:") {
t.Fatalf("expected command action output TRIGGERED:..., got %q (err=%v)", string(cmdData), err)
}
// Case 3: All monitors recover -> should fire RESOLVED
snap3 := snap1
for i := range snap3.Monitors {
snap3.Monitors[i].State = store.StateUp
snap3.Monitors[i].UptimePct = 99.9
snap3.MonitorsByID[snap3.Monitors[i].ID] = snap3.Monitors[i]
}
eng.Evaluate(context.Background(), snap3)
eng.Wait()
webhookMu.Lock()
if len(webhookBodies) != 2 || !strings.Contains(webhookBodies[1], `"status":"RESOLVED"`) {
t.Fatalf("expected recovery webhook call, got %v", webhookBodies)
}
webhookMu.Unlock()
}