Init
This commit is contained in:
parent
c823102a63
commit
d37503c863
20 changed files with 4433 additions and 3 deletions
438
internal/events/engine.go
Normal file
438
internal/events/engine.go
Normal 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
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue