console: move the alert engine's worker into alertengine_pass.go; drop unused alertMessage
A pure move: alertwatch.go keeps only the watcher's per-recipient keymail helpers. alertMessage had no caller left.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/console/alertengine_pass.go+628 −0internal/console/alertwatch.go+7 −644
Intent
<task-notification> <task-id>a228356c85f7c1bde</task-id> <tool-use-id>toolu_01BbbefRMmGnAzbthUg1fRhv</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/a228356c85f7c1bde.output</output-file> <status>completed</status> <summary>Agent "Implement Task 8: alert engine worker" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>- **Status:** DONE_WITH_CONCERNS - **Commit:** 02aad918 `console: alert engine replaces the alert watcher` - **Tests:** - All 19 engine tests pass (the 15 the brief lists plus 4 more), as do the brief's command and the Alert, Dashboard, StoreNotify and Jobs tests. - The Claim group passes on its own (870 s, including the StartAlertEngine probe and the route census). The brief's combined command times out only because Go's default limit is 10 minutes. - `go vet ./internal/console ./cmd/console` is clean, and the Step 5 guard grep prints nothing. - **Concerns:** - I wrote the code before the tests, so there is no RED run against the base commit. Instead I broke the code on purpose in two rounds; 9 of the tests failed, and they pass again once restored. - The job label "Alert checks" (approved copy, OPS-84) becomes "Alert engine", as the brief says. That change, and all the new message text, need Task 9's copy review. - The old watcher re-mailed when a geoip alert's reason changed while it was still firing (code review R4-3). The engine does not, which is a regression. - Operators are given their email connector only on the first pass after a console starts. One added later has none until a restart, and the daily job-status line names them meanwhile. - While the seal key can't be used, the job shows Failed on every pass. - Connectors that aren't confirmed get no queued messages, even when subscribed to a rule. - The cutover leaves a box whose alert file can't be read on the first pass to the normal path, so operators already told may get its fire again. - The claim probe swaps the store for a counting one during the run; I haven't run it with `-race`. - **Report:** /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/.superpowers/sdd/2026-10-30-fleet-alerts-1-engine-connectors/task-8-report.md</result> <usage><subagent_tokens>379347</subagent_tokens><tool_uses>117</tool_uses><duration_ms>2982169</duration_ms></usage> </task-notification>
<task-notification> <task-id>a90ff8de9095bfb00</task-id> <tool-use-id>toolu_01KSJo7d7NV5NfTyadKNBsZJ</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/a90ff8de9095bfb00.output</output-file> <status>completed</status> <summary>Agent "Review Task 8 (spec + quality)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>### Spec Compliance - ✅ **Spec compliant, with one design question flagged below.** Every file the brief lists has its hunk. That covers `alertsignals.go`, `alertengine_pass_test.go`, `alertwatch.go`, `alertwatch_test.go`, `alertnow_test.go`, `opdashboard_test.go`, `jobs_test.go`, `claim_workers.go`, `cmd/console/main.go:678`, `jobs.go`, `claim-routes.txt`, the fixture and the probe. The one-off pagers are untouched, as ruled. Every test in Step 1 exists. The Step 5 guard returns nothing (I ran `git grep -n -E '\balertPass\b|StartAlertWatcher' -- internal cmd`; exit 1). - ⚠️ **Cannot verify from the diff:** - On a host-claim console, the dashboard's `alertsNow` now stays "unknown" for good, because the old watcher fed it there and the engine refuses. The controller should confirm this is intended. - The job "Alert engine" shows Failed for good on such consoles (see Minor 1). The diff (155 KB) was reviewed in four passes: `alertsignals.go`, `alertwatch.go` plus `alertstore.go` and `alertnotify.go`, the tests, then the registries and `server.go`. Outside the diff I read only what each named risk needed; those reads are listed under that risk. **Named-risk checks** 1. **Request budget: holds.** - Every engine read goes through `engineReads.get` (`alertsignals.go:72`). The pass lists `status/boxes/` only when `e.passes%5 == 0` (`alertwatch.go:172`). - `aliasReadingsFrom` takes the boxes already decoded (`apidomains.go:1659`), and nothing in the engine calls `FleetView` or `LoadBoxes` (grep). - `TestEnginePassFiveCycleRequests` compares the whole request map. Any other method falls into the `default` bucket, and an unconditional GET is an error. - I checked `S3Store.GetIfChanged` (`release/store.go:1140`): an empty ETag means a plain first GET, so the first read of each object is unconditional by design. - Two places can still make an extra unconditional request. Both follow the mandated `condGet` pattern (see Minor 4). 2. **Atomicity: holds.** - Incidents, fires and outbox rows go into one `CommitAlertStep` (`alertwatch.go:192`). The drain runs only after it (`:123`). - The cutover's rows commit inside `AlertCutover`'s transaction, together with the `cutover_done` marker (`alertstore.go:451`). - `TestEnginePassCrashBetweenCommitAndSend` closes and reopens the store between the commit and the drain, and asserts exactly one send. 3. **Unreported members: holds.** - Each kind of failed read keeps its members rather than producing `Gone`: - an unreadable or unparsable alert object marks the box unknown (`alertsignals.go:309,316`) - an unreadable, oversize or past-cap heartbeat is recorded in `unreadBoxes` - with any heartbeat unread, `cert_expiring` is not judged at all - a failed `status/boxes/` listing or `fleet.json` read means that source is not counted as read this pass - a failed `alerts/boxes/` listing aborts the step. - Heartbeat rules are only counted as read on the 5th pass. - **Gap:** no test covers this safe side (see Important 3). 4. **Cutover: holds.** - It runs in one transaction, once, gated by `alert_meta.cutover_done`. Seeding comes before the rows. - It is per recipient: a fire goes only to `conns[op]` for operators not told (`alertwatch.go:459-465`). - A fresh database has no `alert_seen` rows, so it takes the ordinary path. - I checked every `alert_seen` writer: apart from the watcher helpers, only `claim_runtime.go` (`claim-sql`) writes rows, and that box is excluded. `storenotify.go` writes none. - Cutover clears use `incident_id = 0`. The `alertOutboxRow` docs (`alertstore.go:241`) allow this for a cutover clear, so it does not break R-10. 5. **HostClaim: holds.** The refusal is the first statement of the pass (`alertwatch.go:112-113`). Both the probe (counting store) and `TestEngineRefusesInHostClaim` (S3-level recorder, empty `alert_*` tables, no beat file) assert zero store calls and no writes. 6. **Old watcher removal: holds.** - `alertRecipients`, `grantRecipients`, `alertDue`, `recordAlertSeen` and `noteMissing` remain (`alertwatch.go:602-688`), so `claim_runtime.go:344-363` and `storenotify.go:64` still compile against them. - The dashboard is fed from `firingMembers()` (`alertwatch.go:494`). 7. **Secrets: no leak found.** - Engine logs and job errors carry bucket keys, rule and scope names, and operator addresses (the latter required by Review Focus 4). - `openConnectorSeal` errors name the key path and its length, never key bytes (`alertseal.go:52,55`). - Notes stored in the outbox hold no connector target. ### Strengths - Gone handling is shaped well: the `covered` / `boxUnknown` maps (`alertsignals.go:250-277`) make "read but absent" and "unread" separate states, so only true absence produces Gone. - The cutover's plan step (`planAlertCutover`) is a pure function, run inside `AlertCutover`'s transaction. - Recording requests at the HTTP level over s3fake, including `If-None-Match`, is a stronger budget witness than the Store wrapper the brief asked for. - `openAfterStep` and `feedAlertsNow` show the dashboard what was committed, whether or not the drain succeeds. - The beat write is atomic: temp file in the same directory, chmod, close, rename, and the temp file is removed on error. - The R-10 guard is real: an emit with `Incident.ID == 0` is logged, fails the run and is skipped (`alertwatch.go:268-273`). ### Issues #### Critical (Must Fix) None. #### Important (Should Fix) 1. **`alertwatch.go:119-131`: the outbox drain is skipped whenever the signal step fails.** - What happens: any failure in `alertEngineStep` (an `alerts/boxes/` LIST error, an `AlertRuleSettings` or `AlertConnectors` read, a cutover error) returns before `alertDrainOutbox` runs. - Why it matters: rows already committed sit undelivered for as long as the bucket or IAM problem lasts, though email delivery does not need the bucket. That includes earlier fires, retries, cutover rows, and `verify`/`suspended` rows from Task 6. - Fix: run the drain whatever the step returned (when ctx is live), and keep the beat tied to step success so `engine_silent` still trips. 2. **`alertwatch.go:515-546`: the unreachable-operator line is visible for about one minute a day.** - What happens: `jobFailed` names the operators on the daily check, and the very next pass overwrites the job status with OK. `TestEnginePassNamesUnreachableOperators` asserts exactly this at `+24h+1m`. - Why it matters: an operator only sees it by opening the page in that minute, which defeats Review Focus 4. - Fix: re-check daily, but keep naming the operators on every pass until a check finds them reachable. 3. **No test covers the safe side of risk 3: a failed read must not close incidents.** - What's missing: no test opens an incident and then makes the source unreadable. That applies to a junk or 5xx alert object for a box with an open incident, a corrupt heartbeat, an unparsable `fleet.json`, and one unread heartbeat while `cert_expiring` is open. - `TestEnginePassSurvivesJunk` (test file :741) only checks that a neighbouring box still fires. - The implementer's mutation checks also covered only the Gone side. - Why it matters: this is the half of the carry ruling that, if broken, silently closes real incidents and sends "no further reports". - Fix: add an incident-survives-unreadable-source test for each source. #### Minor (Nice to Have) 1. **`alertwatch.go:113` with `jobs.go:111-125`: host-claim consoles show a permanent warning.** The refusal returns an error, so the job records `JobFailed`, and because it ran, `exited` keeps it in the snapshot. Every host-claim console's dashboard will therefore say "Alert engine failed on its last run" forever. Other off-on-host-claim workers log and return without a run, so they drop out. This is literally what the brief asked for, but the controller may want an "off" state instead. Low impact while host claims are shelved. 2. **`alertsignals.go:177-180`: a box silent for over 24 hours closes as gone.** - What happens: the ListMod horizon drops a heartbeat older than 24 h before any read, so a box that died stays out of the listing. Its `box_silent` incident then closes with "No further reports" and never fires again. - The spec (§6) does not cover this case. It needs a controller call: should box-silent be exempt from the horizon, or is this the accepted "replaced box" behaviour? - Also, the horizon uses `time.Now()` rather than the pass's `alertClockNow()`. 3. **`apidomains.go:1662`: brief staleness closes and re-fires certificate alerts.** `aliasReadingsFrom` skips stale boxes, so a briefly stale box's hosts drop out of the readings. Their `cert_expiring` members get Gone, then fire again when the box is fresh. This is within the carry ruling ("no longer in aliasReadings"), but it causes churn. 4. **`alertsignals.go:87` and `:171,175`: extra unconditional requests in two cases.** - After any GetIfChanged error other than not-found (for example S3 throttling), `get` does a plain Get. That is a second, unconditional request at the worst moment. - A failed `ListMod` falls back to a second `List`. - Both follow the mandated `condGet` pattern, but neither matches "always conditional". 5. **`alertsignals.go:309,316` against `:319`: unreadable boxes are tracked by key name, members by `st.Box`.** If a box writes a `Box` field that differs from its key, an unreadable object yields Gone for its members, and one object can also report rules for another box. This was inherited from the watcher, but `withGone` now depends on the two names matching. 6. **`alertwatch.go:216`: a crash can leave stale connectors unmarked.** `reentryPending` lives only in memory. A crash after `openConnectorSeal` creates the key but before `MarkSealedConnectorsNeedReentry` succeeds means the next start sees `created == false`. The stale sealed connectors are then never marked, and `seal_key` does not fire for them. 7. **`alertwatch.go:730`: `alertMessage` has no callers left** (grep finds only comments). The brief kept it on the premise that the engine uses it, which the engine does not. Delete it, or record why it stays. 8. **`alertwatch.go:460,472`: `json.Marshal` errors are discarded.** `alertEmitRows` handles the same error. Make the two consistent. 9. **`alertwatch.go:126` with `alertsignals.go:308,355`: shutdown can record failures.** On shutdown the pass returns nil, but per-source reads that fail with a cancelled ctx have already called `jobFailed`. That bends the carry's "stop without recording failures". 10. **Draft copy for Task 9:** - A clear with every member snoozed reads "disk has cleared on the fleet." (`alertnotify.go:117,121`), which implies the whole fleet. - Clears use the raw rule ID ("disk_eta has cleared on box-1"), while fires use prose. - `seal_key` reads "connectors on console cannot be used". 11. **Structure:** `alertwatch.go` grows by about 450 lines and now holds the engine worker, pass, cutover, note composition, dashboard feed and beat, alongside the legacy keymail helpers. A file named `alertengine_pass.go` would be easier to find. This does not block. 12. **Process:** the implementer says no RED run was captured, so test-first was not followed. Mutation checks stand in for it. The brief's combined Step 4 command was split because it exceeded the 10-minute default timeout. ### Assessment **Task quality:** Needs fixes **Reasoning:** The budget, atomicity, cutover, HostClaim refusal and Gone handling are right, and I verified each against the code. But the drain is tied to the bucket read succeeding, the unreachable-operator report is effectively invisible, and the "a failed read never closes an incident" rule, which risk 3 exists to protect, has no test.</result> <usage><subagent_tokens>171086</subagent_tokens><tool_uses>31</tool_uses><duration_ms>383747</duration_ms></usage> </task-notification>
diff --git a/internal/console/alertengine_pass.go b/internal/console/alertengine_pass.go| new file mode 100644 |
| index 000000000..f742e43ae |
| --- /dev/null |
| +++ b/internal/console/alertengine_pass.go |
| @@ -0,0 +1,628 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "maps" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "strconv" |
| + "strings" |
| + "time" |
| +) |
| + |
| +// The alert engine (fleet alerts spec §4, §6): one pass a minute, as the |
| +// alert watcher it replaces ran. A pass reads the signals (alertsignals.go), |
| +// steps the incidents through the noise rules (alertengine.go), commits each |
| +// change with the messages it owes in one transaction (alertstore.go), then |
| +// drains the outbox (alertnotify.go). It also feeds the dashboard's view of |
| +// what is firing, and writes the beat the console box's agent watches |
| +// (spec §8). |
| +// |
| +// The first pass of a process opens the connector seal, seeds each operator |
| +// an email connector, and, once per database, migrates the watcher's |
| +// delivery history (alert_seen) so nobody is told twice, or not told a |
| +// clear they are owed. |
| +// |
| +// One console per deployment runs it (spec §5.2): a host-claim console, |
| +// which may be one of several, refuses before any read or write and says so |
| +// in its job status. |
| +// |
| +// The watcher's per-recipient keymail helpers stay in alertwatch.go. |
| + |
| +const ( |
| + // alertEngineInterval is the pass cadence. |
| + alertEngineInterval = time.Minute |
| + // alertHeartbeatEvery is how many passes apart the heartbeat signals are |
| + // read: every 5 minutes, as the boxes write them (spec §9). |
| + alertHeartbeatEvery = 5 |
| + // alertUnreachableEvery is how often operators no connector reaches are |
| + // named in the job status (Review Focus 4). |
| + alertUnreachableEvery = 24 * time.Hour |
| + // alertSealSubject is seal_key's one subject. |
| + alertSealSubject = "console" |
| +) |
| + |
| +// alertPrefix is the bucket prefix the agent publishes AlertState under |
| +// (metrics.AlertKey). |
| +const alertPrefix = "alerts/boxes/" |
| + |
| +// errAlertEngineRefused is the host-claim console's job status. |
| +var errAlertEngineRefused = errors.New("refused: host-claim console") |
| + |
| +// alertEngineState is what the engine keeps between passes, in memory: a |
| +// restart starts it afresh, and the database carries everything that must |
| +// survive one. |
| +type alertEngineState struct { |
| + reads engineReads |
| + // started is set once the first-run work (seal, seeding, cutover) is |
| + // done; passes counts passes since, for the heartbeat cadence. |
| + started bool |
| + passes int |
| + // sealErr is why the seal key could not be used, for every pass after. |
| + // reentryPending is a new key's re-entry marking still to do. |
| + sealErr error |
| + reentryPending bool |
| + // since is each box rule firing on the dashboard, since when. |
| + since map[alertKey]time.Time |
| + // unreachableAt is when operators were last checked for a usable |
| + // connector. |
| + unreachableAt time.Time |
| +} |
| + |
| +// StartAlertEngine runs alertEnginePass now and then every minute until ctx |
| +// is done. Started from cmd/console's serve(), never from NewServer, so no |
| +// test server grows a goroutine or sends anything. A host-claim console's |
| +// first pass refuses, and the worker returns. |
| +func (s *Server) StartAlertEngine(ctx context.Context) { |
| + t := time.NewTicker(alertEngineInterval) |
| + defer t.Stop() |
| + for { |
| + err := s.jobs.Run(ctx, "StartAlertEngine", s.alertEnginePass) |
| + if errors.Is(err, errAlertEngineRefused) { |
| + log.Printf("console: alert engine: %v; one console per deployment runs it (fleet alerts spec §5.2)", err) |
| + return |
| + } |
| + if err != nil { |
| + log.Printf("console: alert engine: %v", err) |
| + } |
| + select { |
| + case <-ctx.Done(): |
| + return |
| + case <-t.C: |
| + } |
| + } |
| +} |
| + |
| +// alertEnginePass is one pass: signals, the step and its commit, the drain, |
| +// the dashboard's view, and the beat. It returns an error only for a |
| +// failure that makes the pass meaningless (listing alerts/boxes/, reading |
| +// or committing the step, the drain's own); one source's trouble is logged |
| +// and fails the run (jobFailed). A pass cut short by shutdown records no |
| +// failure. |
| +func (s *Server) alertEnginePass(ctx context.Context) error { |
| + if s.cfg.HostClaim { |
| + return errAlertEngineRefused |
| + } |
| + if s.cfg.Releases == nil { |
| + return nil |
| + } |
| + now := s.alertClockNow() |
| + open, sig, err := s.alertEngineStep(ctx, now) |
| + if err == nil { |
| + // The view follows what was committed, whatever the drain does. |
| + s.feedAlertsNow(open, sig, now) |
| + err = s.alertDrainOutbox(ctx) |
| + } |
| + if err != nil { |
| + if ctx.Err() != nil { |
| + return nil |
| + } |
| + return err |
| + } |
| + s.noteUnreachableOperators(ctx, now) |
| + s.writeAlertEngineBeat(ctx, now) |
| + return nil |
| +} |
| + |
| +// alertEngineStep reads the signals and commits one step: the incident |
| +// changes, the fires and the outbox rows they owe, in one transaction |
| +// (spec §6.1). open is the incidents open after it. |
| +func (s *Server) alertEngineStep(ctx context.Context, now time.Time) (open []alertIncident, sig *alertSignals, err error) { |
| + e := &s.alertEngine |
| + sig = newAlertSignals() |
| + boxes, err := s.boxAlertSignals(ctx, sig) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + if !e.started { |
| + s.openAlertSeal(ctx) |
| + if err := s.alertCutover(boxes, sig, now); err != nil { |
| + return nil, nil, fmt.Errorf("alert cutover: %w", err) |
| + } |
| + e.started = true |
| + } |
| + if e.reentryPending { |
| + if n, err := s.store.MarkSealedConnectorsNeedReentry(); err != nil { |
| + log.Printf("console: alert engine: mark sealed connectors for re-entry: %v", err) |
| + jobFailed(ctx, fmt.Errorf("mark sealed connectors for re-entry: %w", err)) |
| + } else { |
| + e.reentryPending = false |
| + if n > 0 { |
| + log.Printf("console: alert engine: a new seal key was made; %d Slack and webhook connectors need re-entering", n) |
| + } |
| + } |
| + } |
| + settings, err := s.store.AlertRuleSettings(alertScopeFleet) |
| + if err != nil { |
| + return nil, nil, fmt.Errorf("alert rules: %w", err) |
| + } |
| + conns, err := s.store.AlertConnectors(alertScopeFleet) |
| + if err != nil { |
| + return nil, nil, fmt.Errorf("alert connectors: %w", err) |
| + } |
| + if e.passes%alertHeartbeatEvery == 0 { |
| + s.heartbeatSignals(ctx, settings, now, sig) |
| + } |
| + e.passes++ |
| + // seal_key fires while the key cannot be used or any connector needs |
| + // re-entering, and clears otherwise (Review Focus 5). |
| + if e.sealErr != nil { |
| + jobFailed(ctx, e.sealErr) |
| + } |
| + reentry := slices.ContainsFunc(conns, func(c alertConnector) bool { return c.NeedsReentry }) |
| + sig.add(alertSignal{Key: alertKey{alertScopeFleet, "seal_key", alertSealSubject}, Level: alertRuleLevel("seal_key"), |
| + Firing: e.sealErr != nil || reentry, At: now}) |
| + sig.cover("seal_key", nil) |
| + |
| + inOpen, recent, err := s.store.AlertStepInputs(now) |
| + if err != nil { |
| + return nil, nil, fmt.Errorf("alert step inputs: %w", err) |
| + } |
| + changed, fires, emits := stepIncidents(inOpen, recent, sig.withGone(inOpen, now), s.alertSnoozed(ctx, now), now) |
| + rows := alertEmitRows(ctx, emits, settings, conns, sig, now) |
| + if err := s.store.CommitAlertStep(changed, fires, rows); err != nil { |
| + return nil, nil, fmt.Errorf("commit alert step: %w", err) |
| + } |
| + return openAfterStep(inOpen, changed), sig, nil |
| +} |
| + |
| +// openAlertSeal opens the connector seal on the first pass (spec §5.1). A |
| +// key that cannot be used leaves every sealed connector held (the drain's |
| +// "no seal key") and fires seal_key on every pass; a key made fresh, while |
| +// sealed connectors exist, marks them as needing re-entry. A seal already |
| +// open (a test's) or no key path (tests) is left as it is. |
| +func (s *Server) openAlertSeal(ctx context.Context) { |
| + e := &s.alertEngine |
| + if s.alertSeal.Load() != nil || s.cfg.AlertSealKeyPath == "" { |
| + return |
| + } |
| + seal, created, err := openConnectorSeal(s.cfg.AlertSealKeyPath) |
| + if err != nil { |
| + log.Printf("console: alert engine: %v; Slack and webhook connectors are held", err) |
| + jobFailed(ctx, err) |
| + e.sealErr = err |
| + return |
| + } |
| + s.alertSeal.Store(seal) |
| + e.reentryPending = created |
| +} |
| + |
| +// alertSnoozed is the step's snooze check at now. A failed read is logged, |
| +// fails the run and counts as not snoozed: a message too many beats one |
| +// missed. |
| +func (s *Server) alertSnoozed(ctx context.Context, now time.Time) func(alertKey) bool { |
| + return func(k alertKey) bool { |
| + on, err := s.store.Snoozed(k.Scope, k.Rule, k.Subject, now) |
| + if err != nil { |
| + log.Printf("console: alert engine: snooze %s/%s/%s: %v", k.Scope, k.Rule, k.Subject, err) |
| + jobFailed(ctx, fmt.Errorf("snooze %s/%s/%s: %w", k.Scope, k.Rule, k.Subject, err)) |
| + return false |
| + } |
| + return on |
| + } |
| +} |
| + |
| +// openAfterStep is the incidents open once changed is committed. |
| +func openAfterStep(open, changed []alertIncident) []alertIncident { |
| + byID := map[int64]alertIncident{} |
| + for _, in := range changed { |
| + if in.ID != 0 { |
| + byID[in.ID] = in |
| + } |
| + } |
| + var out []alertIncident |
| + for _, in := range open { |
| + if c, ok := byID[in.ID]; ok { |
| + in = c |
| + } |
| + if in.ClosedAt.IsZero() { |
| + out = append(out, in) |
| + } |
| + } |
| + for _, in := range changed { |
| + if in.ID == 0 && in.ClosedAt.IsZero() { |
| + out = append(out, in) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// alertEmitRows is the outbox rows the step's emits owe: one per connector |
| +// the rule reaches. An emit for an incident not yet stored is a bug the |
| +// step promises never to make (ruling R-10); it is logged and skipped |
| +// rather than queued against incident 0. A disabled rule queues nothing, |
| +// though its incidents still track. |
| +func alertEmitRows(ctx context.Context, emits []alertEmit, settings map[string]alertRuleSetting, conns []alertConnector, sig *alertSignals, now time.Time) []alertOutboxRow { |
| + var rows []alertOutboxRow |
| + for _, em := range emits { |
| + in := em.Incident |
| + if in.ID == 0 { |
| + err := fmt.Errorf("a %s for %s/%s has no incident id, so it is not queued", em.Kind, in.Scope, in.Rule) |
| + log.Printf("console: alert engine: %v", err) |
| + jobFailed(ctx, err) |
| + continue |
| + } |
| + if in.Scope != alertScopeFleet { |
| + continue // account connectors are a later plan |
| + } |
| + st, set := settings[in.Rule] |
| + if set && !st.Enabled { |
| + continue |
| + } |
| + body, err := json.Marshal(alertEmitNote(em, sig, now)) |
| + if err != nil { |
| + log.Printf("console: alert engine: encode a %s for %s: %v", em.Kind, in.Rule, err) |
| + jobFailed(ctx, fmt.Errorf("encode a %s for %s: %w", em.Kind, in.Rule, err)) |
| + continue |
| + } |
| + for _, id := range alertRuleConnectors(st, conns) { |
| + rows = append(rows, alertOutboxRow{IncidentID: in.ID, ConnectorID: id, Kind: em.Kind, Body: body, NextAt: now}) |
| + } |
| + } |
| + return rows |
| +} |
| + |
| +// alertRuleConnectors is who a rule's messages go to: its subscribed |
| +// connectors, or, with none, every connector in the scope. Only confirmed |
| +// ones: an unconfirmed connector receives nothing but its confirmation |
| +// (spec §5.3), and one confirmed later starts with the next message rather |
| +// than a backlog. A suspended one, or one needing re-entry, is queued and |
| +// held by the drain until it works again. |
| +func alertRuleConnectors(st alertRuleSetting, conns []alertConnector) []int64 { |
| + var out []int64 |
| + for _, c := range conns { |
| + if !c.Confirmed || (len(st.ConnectorIDs) > 0 && !slices.Contains(st.ConnectorIDs, c.ID)) { |
| + continue |
| + } |
| + out = append(out, c.ID) |
| + } |
| + return out |
| +} |
| + |
| +// alertValued are the rules whose value means something in a message. |
| +var alertValued = map[string]bool{ |
| + "disk": true, "mem": true, "cpu": true, "lag": true, "geoip": true, "disk_eta": true, "box_silent": true, "cert_expiring": true, |
| +} |
| + |
| +// alertEmitNote is what one emit says, stored without links (ruling R-2). |
| +// The members are the emit's, which leave out snoozed subjects; the subject |
| +// is the first of them. A clear for a member that went (a close reason of |
| +// "box gone") or a flapping incident says "no further reports", not that |
| +// it cleared. |
| +func alertEmitNote(em alertEmit, sig *alertSignals, now time.Time) alertNote { |
| + in := em.Incident |
| + n := alertNote{Scope: in.Scope, Rule: in.Rule, Level: in.Level, Kind: em.Kind, Subject: alertCopy["subject.none"], |
| + Members: slices.Clone(in.Members), At: now} |
| + if len(in.Members) > 0 { |
| + n.Subject = in.Members[0] |
| + } |
| + if em.Kind == alertKindClear { |
| + gone := "" |
| + if in.CloseReason == alertCloseGone || in.Flapping { |
| + gone = ".gone" |
| + } |
| + subjects := n.Subject |
| + if len(in.Members) > 1 { |
| + subjects = strings.Join(in.Members, ", ") |
| + } |
| + n.What = fmt.Sprintf(alertCopy["clear.what"+gone], in.Rule, subjects) |
| + n.HowLong, n.WhatToDo = alertCopy["clear.how_long"+gone], alertCopy["clear.what_to_do"+gone] |
| + return n |
| + } |
| + n.What = fmt.Sprintf(alertRuleCopy(in.Rule, "what"), n.Subject) |
| + if v, ok := sig.value(alertKey{in.Scope, in.Rule, n.Subject}); ok && alertValued[in.Rule] && len(in.Members) > 0 { |
| + n.What += " " + fmt.Sprintf(alertCopy["what.value"], alertValueText(in.Rule, v)) |
| + } |
| + if em.Kind == alertKindUpdate && len(em.Joined) > 0 { |
| + n.What = fmt.Sprintf(alertCopy["update.what"], strings.Join(em.Joined, ", ")) + " " + n.What |
| + } |
| + n.HowLong, n.WhatToDo = alertRuleCopy(in.Rule, "how_long"), alertRuleCopy(in.Rule, "what_to_do") |
| + return n |
| +} |
| + |
| +// alertRuleCopy is rule's draft line part, or the default rule's. |
| +func alertRuleCopy(rule, part string) string { |
| + if s, ok := alertCopy["rule."+rule+"."+part]; ok { |
| + return s |
| + } |
| + return alertCopy["rule.default."+part] |
| +} |
| + |
| +// ---- the cutover ------------------------------------------------------------- |
| + |
| +// alertCutover migrates the watcher's delivery history once per database, |
| +// in one transaction with the operators' seeded connectors (R2 #6). After |
| +// it has run, a start only seeds, idempotently. |
| +// |
| +// For each box rule that someone was last told is firing (alert_seen): |
| +// |
| +// - Still firing: an incident opens already notified, and each operator |
| +// who was not told gets a fire, to their own connector only. |
| +// - Not firing, or no longer reported: each operator who was told gets a |
| +// clear, and no incident opens. |
| +// |
| +// A rule firing with no such history is left to the ordinary path: grouped, |
| +// sent at notify_at, to every connector, Slack included (R3 #3). A box |
| +// whose object could not be read this pass is left alone, to the ordinary |
| +// path too. |
| +func (s *Server) alertCutover(boxes boxAlerts, sig *alertSignals, now time.Time) error { |
| + ops, err := s.store.Operators() |
| + if err != nil { |
| + return fmt.Errorf("operators: %w", err) |
| + } |
| + ran, err := s.store.AlertCutover(func(tx *sql.Tx) error { |
| + conns, err := seedOperatorAlertConnectors(tx, ops, now) |
| + if err != nil { |
| + return err |
| + } |
| + seen, err := alertSeenFiring(tx) |
| + if err != nil { |
| + return err |
| + } |
| + opened, clears := planAlertCutover(boxes, seen, ops, conns, sig, now) |
| + for _, ci := range opened { |
| + id, err := insertAlertIncidentTx(tx, ci.in) |
| + if err != nil { |
| + return err |
| + } |
| + for _, r := range ci.fires { |
| + r.IncidentID = id |
| + if err := insertAlertOutbox(tx, r); err != nil { |
| + return err |
| + } |
| + } |
| + } |
| + for _, r := range clears { |
| + if err := insertAlertOutbox(tx, r); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| + }) |
| + if err != nil { |
| + return err |
| + } |
| + if ran { |
| + log.Printf("console: alert engine: took over from the alert watcher's history") |
| + return nil |
| + } |
| + return s.store.SeedOperatorAlertConnectors(ops, now) |
| +} |
| + |
| +// cutoverIncident is one incident the cutover opens, with the fires owed to |
| +// the operators who were not told. |
| +type cutoverIncident struct { |
| + in alertIncident |
| + fires []alertOutboxRow |
| +} |
| + |
| +// planAlertCutover works out the cutover from the box states read this pass |
| +// and the watcher's history. seen is alert_seen's firing rows; conns each |
| +// operator's seeded connector. Migrated incidents open with LastSeenAt zero |
| +// (ruling R-17), notified, and their fire counted as now. |
| +func planAlertCutover(boxes boxAlerts, seen map[[2]string][]string, ops []string, conns map[string]int64, sig *alertSignals, now time.Time) (opened []cutoverIncident, clears []alertOutboxRow) { |
| + byRule := map[string]int{} |
| + keys := slices.Collect(maps.Keys(seen)) |
| + slices.SortFunc(keys, func(a, b [2]string) int { return strings.Compare(a[0]+"\x00"+a[1], b[0]+"\x00"+b[1]) }) |
| + for _, k := range keys { |
| + box, rule := k[0], k[1] |
| + var told []string |
| + for _, addr := range seen[k] { |
| + if _, op := conns[addr]; op { |
| + told = append(told, addr) |
| + } |
| + } |
| + if len(told) == 0 || boxes.unread[box] { |
| + continue |
| + } |
| + level := alertRuleLevel(rule) |
| + member := alertIncident{Scope: alertScopeFleet, Rule: rule, Level: level, Members: []string{box}} |
| + st, listed := boxes.states[box] |
| + rs, has := st.Rules[rule] |
| + if listed && has && rs.Firing { |
| + i, ok := byRule[rule] |
| + if !ok { |
| + i = len(opened) |
| + byRule[rule] = i |
| + opened = append(opened, cutoverIncident{in: alertIncident{Scope: alertScopeFleet, Rule: rule, Level: level, |
| + OpenedAt: now, NotifyAt: now.Add(alertNotifyDelay), Notified: true, LastReminderAt: now}}) |
| + } |
| + opened[i].in.Members = append(opened[i].in.Members, box) |
| + body, _ := json.Marshal(alertEmitNote(alertEmit{Incident: member, Kind: alertKindFire}, sig, now)) |
| + for _, op := range ops { |
| + if !slices.Contains(told, op) { |
| + opened[i].fires = append(opened[i].fires, alertOutboxRow{ConnectorID: conns[op], Kind: alertKindFire, Body: body, NextAt: now}) |
| + } |
| + } |
| + continue |
| + } |
| + member.CloseReason = alertCloseCleared |
| + if !listed || !has { |
| + member.CloseReason = alertCloseGone |
| + } |
| + body, _ := json.Marshal(alertEmitNote(alertEmit{Incident: member, Kind: alertKindClear}, sig, now)) |
| + for _, op := range told { |
| + clears = append(clears, alertOutboxRow{ConnectorID: conns[op], Kind: alertKindClear, Body: body, NextAt: now}) |
| + } |
| + } |
| + return opened, clears |
| +} |
| + |
| +// ---- after the step ---------------------------------------------------------- |
| + |
| +// feedAlertsNow rebuilds the dashboard's view (opdashboard.go) from the open |
| +// box-rule incidents' firing members: a quiet flapping incident shows |
| +// nothing. Since is the box's FiredAt, else the since it already had, else |
| +// now. |
| +func (s *Server) feedAlertsNow(open []alertIncident, sig *alertSignals, now time.Time) { |
| + e := &s.alertEngine |
| + since := map[alertKey]time.Time{} |
| + var firing []FiringAlert |
| + for _, in := range open { |
| + if in.Scope != alertScopeFleet || alertConsoleRules[in.Rule] { |
| + continue |
| + } |
| + for _, box := range in.firingMembers() { |
| + k := alertKey{in.Scope, in.Rule, box} |
| + at := sig.firedAt[k] |
| + if at.IsZero() { |
| + at = e.since[k] |
| + } |
| + if at.IsZero() { |
| + at = now |
| + } |
| + since[k] = at |
| + firing = append(firing, FiringAlert{Box: box, Rule: in.Rule, Since: at}) |
| + } |
| + } |
| + e.since = since |
| + s.alertsNow.set(firing) |
| +} |
| + |
| +// noteUnreachableOperators names, once a day, the operators no usable |
| +// connector of their own reaches, in the job status (Review Focus 4): an |
| +// operator made after this process seeded, or whose connector is |
| +// suspended, needs re-entry or was removed. |
| +func (s *Server) noteUnreachableOperators(ctx context.Context, now time.Time) { |
| + e := &s.alertEngine |
| + if !e.unreachableAt.IsZero() && now.Sub(e.unreachableAt) < alertUnreachableEvery { |
| + return |
| + } |
| + ops, err := s.store.Operators() |
| + if err != nil { |
| + log.Printf("console: alert engine: operators: %v", err) |
| + jobFailed(ctx, fmt.Errorf("operators: %w", err)) |
| + return |
| + } |
| + conns, err := s.store.AlertConnectors(alertScopeFleet) |
| + if err != nil { |
| + log.Printf("console: alert engine: alert connectors: %v", err) |
| + jobFailed(ctx, fmt.Errorf("alert connectors: %w", err)) |
| + return |
| + } |
| + e.unreachableAt = now |
| + var missing []string |
| + for _, op := range ops { |
| + if !slices.ContainsFunc(conns, func(c alertConnector) bool { |
| + return c.OwnerAddress == op && c.Confirmed && !c.Suspended && !c.NeedsReentry |
| + }) { |
| + missing = append(missing, op) |
| + } |
| + } |
| + if len(missing) > 0 { |
| + err := fmt.Errorf("no usable alert connector reaches %s", strings.Join(missing, ", ")) |
| + log.Printf("console: alert engine: %v", err) |
| + jobFailed(ctx, err) |
| + } |
| +} |
| + |
| +// writeAlertEngineBeat replaces the beat file the console box's agent |
| +// watches (spec §8) at the end of each pass that got through: a temp file |
| +// beside it, renamed over it, so the agent never reads half a beat. |
| +func (s *Server) writeAlertEngineBeat(ctx context.Context, now time.Time) { |
| + path := s.cfg.AlertEngineBeatPath |
| + if path == "" { |
| + return |
| + } |
| + if err := writeAlertBeatFile(path, now); err != nil { |
| + log.Printf("console: alert engine: beat %s: %v", path, err) |
| + jobFailed(ctx, fmt.Errorf("beat %s: %w", path, err)) |
| + } |
| +} |
| + |
| +func writeAlertBeatFile(path string, now time.Time) error { |
| + f, err := os.CreateTemp(filepath.Dir(path), ".alert-engine.beat-*") |
| + if err != nil { |
| + return err |
| + } |
| + tmp := f.Name() |
| + _, werr := f.WriteString(now.UTC().Format(time.RFC3339) + "\n") |
| + if werr == nil { |
| + werr = f.Chmod(0o644) |
| + } |
| + if cerr := f.Close(); werr == nil { |
| + werr = cerr |
| + } |
| + if werr == nil { |
| + werr = os.Rename(tmp, path) |
| + } |
| + if werr != nil { |
| + os.Remove(tmp) |
| + } |
| + return werr |
| +} |
| + |
| +// alertValueText renders one rule's transition value in that rule's own |
| +// unit. Every rule internal/metrics evaluates carries a fraction EXCEPT lag, |
| +// which is keymail relay seconds (see metrics.Rules.LagSecs), and the |
| +// forecast and the engine's own rules, which carry hours, minutes and days — |
| +// so a single |
| +// percent formatter for all of them turns the first lag alert to fire into |
| +// "92000%". Used by both operator-facing surfaces: the dashboard's alerts |
| +// table and the alert mail below. |
| +// |
| +// An unknown rule name (a future rule this console has not been taught) is |
| +// rendered as a bare number rather than being given someone else's unit: a |
| +// unitless figure is honest, a wrong unit is not. |
| +func alertValueText(rule string, value float64) string { |
| + switch rule { |
| + case "disk", "mem", "cpu": |
| + return fmt.Sprintf("%.0f%%", value*100) |
| + case "lag": |
| + return fmt.Sprintf("%.0fs", value) |
| + case "geoip": |
| + // A reason code, not a measurement (geoip spec §10.4). |
| + return geoipReasonText(int(value)) |
| + case "disk_eta": |
| + return fmt.Sprintf("%.0f hours to full", value) |
| + case "box_silent": |
| + return fmt.Sprintf("%.0f minutes since its last report", value) |
| + case "cert_expiring": |
| + return fmt.Sprintf("%.0f days left", value) |
| + default: |
| + return strconv.FormatFloat(value, 'g', -1, 64) |
| + } |
| +} |
| + |
| +// geoipReasonText names a geoip rule reason code (geoip spec §10.4). |
| +func geoipReasonText(code int) string { |
| + switch code { |
| + case 1: |
| + return "database over 45 days old" |
| + case 2: |
| + return "GeoLite2 database expires within 9 days" |
| + case 3: |
| + return "database expired and removed" |
| + case 4: |
| + return "published database not loaded for over an hour" |
| + case 5: |
| + return "feed failing" |
| + } |
| + return "geoip reason " + strconv.Itoa(code) |
| +} |
diff --git a/internal/console/alertwatch.go b/internal/console/alertwatch.go| index be7733704..9bfed2947 100644 |
| --- a/internal/console/alertwatch.go |
| +++ b/internal/console/alertwatch.go |
| @@ -1,586 +1,19 @@ |
| package console |
| +// The alert watcher's per-recipient keymail helpers. The watcher itself is |
| +// gone (the alert engine, alertengine_pass.go, replaced it); these stay for |
| +// the one-shot operator notices that still mail each operator with their |
| +// own Keymail grant and remember who was told in alert_seen: the claim-SQL |
| +// receipt (claim_runtime.go) and the store notices (storenotify.go). The |
| +// engine's cutover reads alert_seen once (alertstore.go, alertSeenFiring). |
| + |
| import ( |
| "context" |
| - "database/sql" |
| - "encoding/json" |
| - "errors" |
| "fmt" |
| "log" |
| - "maps" |
| - "os" |
| - "path/filepath" |
| - "slices" |
| - "strconv" |
| "strings" |
| - "time" |
| - |
| - "github.com/carlosframework/platform/internal/metrics" |
| ) |
| -// The alert engine (fleet alerts spec §4, §6): one pass a minute, as the |
| -// alert watcher it replaces ran. A pass reads the signals (alertsignals.go), |
| -// steps the incidents through the noise rules (alertengine.go), commits each |
| -// change with the messages it owes in one transaction (alertstore.go), then |
| -// drains the outbox (alertnotify.go). It also feeds the dashboard's view of |
| -// what is firing, and writes the beat the console box's agent watches |
| -// (spec §8). |
| -// |
| -// The first pass of a process opens the connector seal, seeds each operator |
| -// an email connector, and, once per database, migrates the watcher's |
| -// delivery history (alert_seen) so nobody is told twice, or not told a |
| -// clear they are owed. |
| -// |
| -// One console per deployment runs it (spec §5.2): a host-claim console, |
| -// which may be one of several, refuses before any read or write and says so |
| -// in its job status. |
| -// |
| -// The watcher's per-recipient helpers below it stay: the claim-SQL receipt |
| -// (claim_runtime.go) and the store notices (storenotify.go) still use them. |
| - |
| -const ( |
| - // alertEngineInterval is the pass cadence. |
| - alertEngineInterval = time.Minute |
| - // alertHeartbeatEvery is how many passes apart the heartbeat signals are |
| - // read: every 5 minutes, as the boxes write them (spec §9). |
| - alertHeartbeatEvery = 5 |
| - // alertUnreachableEvery is how often operators no connector reaches are |
| - // named in the job status (Review Focus 4). |
| - alertUnreachableEvery = 24 * time.Hour |
| - // alertSealSubject is seal_key's one subject. |
| - alertSealSubject = "console" |
| -) |
| - |
| -// alertPrefix is the bucket prefix the agent publishes AlertState under |
| -// (metrics.AlertKey). |
| -const alertPrefix = "alerts/boxes/" |
| - |
| -// errAlertEngineRefused is the host-claim console's job status. |
| -var errAlertEngineRefused = errors.New("refused: host-claim console") |
| - |
| -// alertEngineState is what the engine keeps between passes, in memory: a |
| -// restart starts it afresh, and the database carries everything that must |
| -// survive one. |
| -type alertEngineState struct { |
| - reads engineReads |
| - // started is set once the first-run work (seal, seeding, cutover) is |
| - // done; passes counts passes since, for the heartbeat cadence. |
| - started bool |
| - passes int |
| - // sealErr is why the seal key could not be used, for every pass after. |
| - // reentryPending is a new key's re-entry marking still to do. |
| - sealErr error |
| - reentryPending bool |
| - // since is each box rule firing on the dashboard, since when. |
| - since map[alertKey]time.Time |
| - // unreachableAt is when operators were last checked for a usable |
| - // connector. |
| - unreachableAt time.Time |
| -} |
| - |
| -// StartAlertEngine runs alertEnginePass now and then every minute until ctx |
| -// is done. Started from cmd/console's serve(), never from NewServer, so no |
| -// test server grows a goroutine or sends anything. A host-claim console's |
| -// first pass refuses, and the worker returns. |
| -func (s *Server) StartAlertEngine(ctx context.Context) { |
| - t := time.NewTicker(alertEngineInterval) |
| - defer t.Stop() |
| - for { |
| - err := s.jobs.Run(ctx, "StartAlertEngine", s.alertEnginePass) |
| - if errors.Is(err, errAlertEngineRefused) { |
| - log.Printf("console: alert engine: %v; one console per deployment runs it (fleet alerts spec §5.2)", err) |
| - return |
| - } |
| - if err != nil { |
| - log.Printf("console: alert engine: %v", err) |
| - } |
| - select { |
| - case <-ctx.Done(): |
| - return |
| - case <-t.C: |
| - } |
| - } |
| -} |
| - |
| -// alertEnginePass is one pass: signals, the step and its commit, the drain, |
| -// the dashboard's view, and the beat. It returns an error only for a |
| -// failure that makes the pass meaningless (listing alerts/boxes/, reading |
| -// or committing the step, the drain's own); one source's trouble is logged |
| -// and fails the run (jobFailed). A pass cut short by shutdown records no |
| -// failure. |
| -func (s *Server) alertEnginePass(ctx context.Context) error { |
| - if s.cfg.HostClaim { |
| - return errAlertEngineRefused |
| - } |
| - if s.cfg.Releases == nil { |
| - return nil |
| - } |
| - now := s.alertClockNow() |
| - open, sig, err := s.alertEngineStep(ctx, now) |
| - if err == nil { |
| - // The view follows what was committed, whatever the drain does. |
| - s.feedAlertsNow(open, sig, now) |
| - err = s.alertDrainOutbox(ctx) |
| - } |
| - if err != nil { |
| - if ctx.Err() != nil { |
| - return nil |
| - } |
| - return err |
| - } |
| - s.noteUnreachableOperators(ctx, now) |
| - s.writeAlertEngineBeat(ctx, now) |
| - return nil |
| -} |
| - |
| -// alertEngineStep reads the signals and commits one step: the incident |
| -// changes, the fires and the outbox rows they owe, in one transaction |
| -// (spec §6.1). open is the incidents open after it. |
| -func (s *Server) alertEngineStep(ctx context.Context, now time.Time) (open []alertIncident, sig *alertSignals, err error) { |
| - e := &s.alertEngine |
| - sig = newAlertSignals() |
| - boxes, err := s.boxAlertSignals(ctx, sig) |
| - if err != nil { |
| - return nil, nil, err |
| - } |
| - if !e.started { |
| - s.openAlertSeal(ctx) |
| - if err := s.alertCutover(boxes, sig, now); err != nil { |
| - return nil, nil, fmt.Errorf("alert cutover: %w", err) |
| - } |
| - e.started = true |
| - } |
| - if e.reentryPending { |
| - if n, err := s.store.MarkSealedConnectorsNeedReentry(); err != nil { |
| - log.Printf("console: alert engine: mark sealed connectors for re-entry: %v", err) |
| - jobFailed(ctx, fmt.Errorf("mark sealed connectors for re-entry: %w", err)) |
| - } else { |
| - e.reentryPending = false |
| - if n > 0 { |
| - log.Printf("console: alert engine: a new seal key was made; %d Slack and webhook connectors need re-entering", n) |
| - } |
| - } |
| - } |
| - settings, err := s.store.AlertRuleSettings(alertScopeFleet) |
| - if err != nil { |
| - return nil, nil, fmt.Errorf("alert rules: %w", err) |
| - } |
| - conns, err := s.store.AlertConnectors(alertScopeFleet) |
| - if err != nil { |
| - return nil, nil, fmt.Errorf("alert connectors: %w", err) |
| - } |
| - if e.passes%alertHeartbeatEvery == 0 { |
| - s.heartbeatSignals(ctx, settings, now, sig) |
| - } |
| - e.passes++ |
| - // seal_key fires while the key cannot be used or any connector needs |
| - // re-entering, and clears otherwise (Review Focus 5). |
| - if e.sealErr != nil { |
| - jobFailed(ctx, e.sealErr) |
| - } |
| - reentry := slices.ContainsFunc(conns, func(c alertConnector) bool { return c.NeedsReentry }) |
| - sig.add(alertSignal{Key: alertKey{alertScopeFleet, "seal_key", alertSealSubject}, Level: alertRuleLevel("seal_key"), |
| - Firing: e.sealErr != nil || reentry, At: now}) |
| - sig.cover("seal_key", nil) |
| - |
| - inOpen, recent, err := s.store.AlertStepInputs(now) |
| - if err != nil { |
| - return nil, nil, fmt.Errorf("alert step inputs: %w", err) |
| - } |
| - changed, fires, emits := stepIncidents(inOpen, recent, sig.withGone(inOpen, now), s.alertSnoozed(ctx, now), now) |
| - rows := alertEmitRows(ctx, emits, settings, conns, sig, now) |
| - if err := s.store.CommitAlertStep(changed, fires, rows); err != nil { |
| - return nil, nil, fmt.Errorf("commit alert step: %w", err) |
| - } |
| - return openAfterStep(inOpen, changed), sig, nil |
| -} |
| - |
| -// openAlertSeal opens the connector seal on the first pass (spec §5.1). A |
| -// key that cannot be used leaves every sealed connector held (the drain's |
| -// "no seal key") and fires seal_key on every pass; a key made fresh, while |
| -// sealed connectors exist, marks them as needing re-entry. A seal already |
| -// open (a test's) or no key path (tests) is left as it is. |
| -func (s *Server) openAlertSeal(ctx context.Context) { |
| - e := &s.alertEngine |
| - if s.alertSeal.Load() != nil || s.cfg.AlertSealKeyPath == "" { |
| - return |
| - } |
| - seal, created, err := openConnectorSeal(s.cfg.AlertSealKeyPath) |
| - if err != nil { |
| - log.Printf("console: alert engine: %v; Slack and webhook connectors are held", err) |
| - jobFailed(ctx, err) |
| - e.sealErr = err |
| - return |
| - } |
| - s.alertSeal.Store(seal) |
| - e.reentryPending = created |
| -} |
| - |
| -// alertSnoozed is the step's snooze check at now. A failed read is logged, |
| -// fails the run and counts as not snoozed: a message too many beats one |
| -// missed. |
| -func (s *Server) alertSnoozed(ctx context.Context, now time.Time) func(alertKey) bool { |
| - return func(k alertKey) bool { |
| - on, err := s.store.Snoozed(k.Scope, k.Rule, k.Subject, now) |
| - if err != nil { |
| - log.Printf("console: alert engine: snooze %s/%s/%s: %v", k.Scope, k.Rule, k.Subject, err) |
| - jobFailed(ctx, fmt.Errorf("snooze %s/%s/%s: %w", k.Scope, k.Rule, k.Subject, err)) |
| - return false |
| - } |
| - return on |
| - } |
| -} |
| - |
| -// openAfterStep is the incidents open once changed is committed. |
| -func openAfterStep(open, changed []alertIncident) []alertIncident { |
| - byID := map[int64]alertIncident{} |
| - for _, in := range changed { |
| - if in.ID != 0 { |
| - byID[in.ID] = in |
| - } |
| - } |
| - var out []alertIncident |
| - for _, in := range open { |
| - if c, ok := byID[in.ID]; ok { |
| - in = c |
| - } |
| - if in.ClosedAt.IsZero() { |
| - out = append(out, in) |
| - } |
| - } |
| - for _, in := range changed { |
| - if in.ID == 0 && in.ClosedAt.IsZero() { |
| - out = append(out, in) |
| - } |
| - } |
| - return out |
| -} |
| - |
| -// alertEmitRows is the outbox rows the step's emits owe: one per connector |
| -// the rule reaches. An emit for an incident not yet stored is a bug the |
| -// step promises never to make (ruling R-10); it is logged and skipped |
| -// rather than queued against incident 0. A disabled rule queues nothing, |
| -// though its incidents still track. |
| -func alertEmitRows(ctx context.Context, emits []alertEmit, settings map[string]alertRuleSetting, conns []alertConnector, sig *alertSignals, now time.Time) []alertOutboxRow { |
| - var rows []alertOutboxRow |
| - for _, em := range emits { |
| - in := em.Incident |
| - if in.ID == 0 { |
| - err := fmt.Errorf("a %s for %s/%s has no incident id, so it is not queued", em.Kind, in.Scope, in.Rule) |
| - log.Printf("console: alert engine: %v", err) |
| - jobFailed(ctx, err) |
| - continue |
| - } |
| - if in.Scope != alertScopeFleet { |
| - continue // account connectors are a later plan |
| - } |
| - st, set := settings[in.Rule] |
| - if set && !st.Enabled { |
| - continue |
| - } |
| - body, err := json.Marshal(alertEmitNote(em, sig, now)) |
| - if err != nil { |
| - log.Printf("console: alert engine: encode a %s for %s: %v", em.Kind, in.Rule, err) |
| - jobFailed(ctx, fmt.Errorf("encode a %s for %s: %w", em.Kind, in.Rule, err)) |
| - continue |
| - } |
| - for _, id := range alertRuleConnectors(st, conns) { |
| - rows = append(rows, alertOutboxRow{IncidentID: in.ID, ConnectorID: id, Kind: em.Kind, Body: body, NextAt: now}) |
| - } |
| - } |
| - return rows |
| -} |
| - |
| -// alertRuleConnectors is who a rule's messages go to: its subscribed |
| -// connectors, or, with none, every connector in the scope. Only confirmed |
| -// ones: an unconfirmed connector receives nothing but its confirmation |
| -// (spec §5.3), and one confirmed later starts with the next message rather |
| -// than a backlog. A suspended one, or one needing re-entry, is queued and |
| -// held by the drain until it works again. |
| -func alertRuleConnectors(st alertRuleSetting, conns []alertConnector) []int64 { |
| - var out []int64 |
| - for _, c := range conns { |
| - if !c.Confirmed || (len(st.ConnectorIDs) > 0 && !slices.Contains(st.ConnectorIDs, c.ID)) { |
| - continue |
| - } |
| - out = append(out, c.ID) |
| - } |
| - return out |
| -} |
| - |
| -// alertValued are the rules whose value means something in a message. |
| -var alertValued = map[string]bool{ |
| - "disk": true, "mem": true, "cpu": true, "lag": true, "geoip": true, "disk_eta": true, "box_silent": true, "cert_expiring": true, |
| -} |
| - |
| -// alertEmitNote is what one emit says, stored without links (ruling R-2). |
| -// The members are the emit's, which leave out snoozed subjects; the subject |
| -// is the first of them. A clear for a member that went (a close reason of |
| -// "box gone") or a flapping incident says "no further reports", not that |
| -// it cleared. |
| -func alertEmitNote(em alertEmit, sig *alertSignals, now time.Time) alertNote { |
| - in := em.Incident |
| - n := alertNote{Scope: in.Scope, Rule: in.Rule, Level: in.Level, Kind: em.Kind, Subject: alertCopy["subject.none"], |
| - Members: slices.Clone(in.Members), At: now} |
| - if len(in.Members) > 0 { |
| - n.Subject = in.Members[0] |
| - } |
| - if em.Kind == alertKindClear { |
| - gone := "" |
| - if in.CloseReason == alertCloseGone || in.Flapping { |
| - gone = ".gone" |
| - } |
| - subjects := n.Subject |
| - if len(in.Members) > 1 { |
| - subjects = strings.Join(in.Members, ", ") |
| - } |
| - n.What = fmt.Sprintf(alertCopy["clear.what"+gone], in.Rule, subjects) |
| - n.HowLong, n.WhatToDo = alertCopy["clear.how_long"+gone], alertCopy["clear.what_to_do"+gone] |
| - return n |
| - } |
| - n.What = fmt.Sprintf(alertRuleCopy(in.Rule, "what"), n.Subject) |
| - if v, ok := sig.value(alertKey{in.Scope, in.Rule, n.Subject}); ok && alertValued[in.Rule] && len(in.Members) > 0 { |
| - n.What += " " + fmt.Sprintf(alertCopy["what.value"], alertValueText(in.Rule, v)) |
| - } |
| - if em.Kind == alertKindUpdate && len(em.Joined) > 0 { |
| - n.What = fmt.Sprintf(alertCopy["update.what"], strings.Join(em.Joined, ", ")) + " " + n.What |
| - } |
| - n.HowLong, n.WhatToDo = alertRuleCopy(in.Rule, "how_long"), alertRuleCopy(in.Rule, "what_to_do") |
| - return n |
| -} |
| - |
| -// alertRuleCopy is rule's draft line part, or the default rule's. |
| -func alertRuleCopy(rule, part string) string { |
| - if s, ok := alertCopy["rule."+rule+"."+part]; ok { |
| - return s |
| - } |
| - return alertCopy["rule.default."+part] |
| -} |
| - |
| -// ---- the cutover ------------------------------------------------------------- |
| - |
| -// alertCutover migrates the watcher's delivery history once per database, |
| -// in one transaction with the operators' seeded connectors (R2 #6). After |
| -// it has run, a start only seeds, idempotently. |
| -// |
| -// For each box rule that someone was last told is firing (alert_seen): |
| -// |
| -// - Still firing: an incident opens already notified, and each operator |
| -// who was not told gets a fire, to their own connector only. |
| -// - Not firing, or no longer reported: each operator who was told gets a |
| -// clear, and no incident opens. |
| -// |
| -// A rule firing with no such history is left to the ordinary path: grouped, |
| -// sent at notify_at, to every connector, Slack included (R3 #3). A box |
| -// whose object could not be read this pass is left alone, to the ordinary |
| -// path too. |
| -func (s *Server) alertCutover(boxes boxAlerts, sig *alertSignals, now time.Time) error { |
| - ops, err := s.store.Operators() |
| - if err != nil { |
| - return fmt.Errorf("operators: %w", err) |
| - } |
| - ran, err := s.store.AlertCutover(func(tx *sql.Tx) error { |
| - conns, err := seedOperatorAlertConnectors(tx, ops, now) |
| - if err != nil { |
| - return err |
| - } |
| - seen, err := alertSeenFiring(tx) |
| - if err != nil { |
| - return err |
| - } |
| - opened, clears := planAlertCutover(boxes, seen, ops, conns, sig, now) |
| - for _, ci := range opened { |
| - id, err := insertAlertIncidentTx(tx, ci.in) |
| - if err != nil { |
| - return err |
| - } |
| - for _, r := range ci.fires { |
| - r.IncidentID = id |
| - if err := insertAlertOutbox(tx, r); err != nil { |
| - return err |
| - } |
| - } |
| - } |
| - for _, r := range clears { |
| - if err := insertAlertOutbox(tx, r); err != nil { |
| - return err |
| - } |
| - } |
| - return nil |
| - }) |
| - if err != nil { |
| - return err |
| - } |
| - if ran { |
| - log.Printf("console: alert engine: took over from the alert watcher's history") |
| - return nil |
| - } |
| - return s.store.SeedOperatorAlertConnectors(ops, now) |
| -} |
| - |
| -// cutoverIncident is one incident the cutover opens, with the fires owed to |
| -// the operators who were not told. |
| -type cutoverIncident struct { |
| - in alertIncident |
| - fires []alertOutboxRow |
| -} |
| - |
| -// planAlertCutover works out the cutover from the box states read this pass |
| -// and the watcher's history. seen is alert_seen's firing rows; conns each |
| -// operator's seeded connector. Migrated incidents open with LastSeenAt zero |
| -// (ruling R-17), notified, and their fire counted as now. |
| -func planAlertCutover(boxes boxAlerts, seen map[[2]string][]string, ops []string, conns map[string]int64, sig *alertSignals, now time.Time) (opened []cutoverIncident, clears []alertOutboxRow) { |
| - byRule := map[string]int{} |
| - keys := slices.Collect(maps.Keys(seen)) |
| - slices.SortFunc(keys, func(a, b [2]string) int { return strings.Compare(a[0]+"\x00"+a[1], b[0]+"\x00"+b[1]) }) |
| - for _, k := range keys { |
| - box, rule := k[0], k[1] |
| - var told []string |
| - for _, addr := range seen[k] { |
| - if _, op := conns[addr]; op { |
| - told = append(told, addr) |
| - } |
| - } |
| - if len(told) == 0 || boxes.unread[box] { |
| - continue |
| - } |
| - level := alertRuleLevel(rule) |
| - member := alertIncident{Scope: alertScopeFleet, Rule: rule, Level: level, Members: []string{box}} |
| - st, listed := boxes.states[box] |
| - rs, has := st.Rules[rule] |
| - if listed && has && rs.Firing { |
| - i, ok := byRule[rule] |
| - if !ok { |
| - i = len(opened) |
| - byRule[rule] = i |
| - opened = append(opened, cutoverIncident{in: alertIncident{Scope: alertScopeFleet, Rule: rule, Level: level, |
| - OpenedAt: now, NotifyAt: now.Add(alertNotifyDelay), Notified: true, LastReminderAt: now}}) |
| - } |
| - opened[i].in.Members = append(opened[i].in.Members, box) |
| - body, _ := json.Marshal(alertEmitNote(alertEmit{Incident: member, Kind: alertKindFire}, sig, now)) |
| - for _, op := range ops { |
| - if !slices.Contains(told, op) { |
| - opened[i].fires = append(opened[i].fires, alertOutboxRow{ConnectorID: conns[op], Kind: alertKindFire, Body: body, NextAt: now}) |
| - } |
| - } |
| - continue |
| - } |
| - member.CloseReason = alertCloseCleared |
| - if !listed || !has { |
| - member.CloseReason = alertCloseGone |
| - } |
| - body, _ := json.Marshal(alertEmitNote(alertEmit{Incident: member, Kind: alertKindClear}, sig, now)) |
| - for _, op := range told { |
| - clears = append(clears, alertOutboxRow{ConnectorID: conns[op], Kind: alertKindClear, Body: body, NextAt: now}) |
| - } |
| - } |
| - return opened, clears |
| -} |
| - |
| -// ---- after the step ---------------------------------------------------------- |
| - |
| -// feedAlertsNow rebuilds the dashboard's view (opdashboard.go) from the open |
| -// box-rule incidents' firing members: a quiet flapping incident shows |
| -// nothing. Since is the box's FiredAt, else the since it already had, else |
| -// now. |
| -func (s *Server) feedAlertsNow(open []alertIncident, sig *alertSignals, now time.Time) { |
| - e := &s.alertEngine |
| - since := map[alertKey]time.Time{} |
| - var firing []FiringAlert |
| - for _, in := range open { |
| - if in.Scope != alertScopeFleet || alertConsoleRules[in.Rule] { |
| - continue |
| - } |
| - for _, box := range in.firingMembers() { |
| - k := alertKey{in.Scope, in.Rule, box} |
| - at := sig.firedAt[k] |
| - if at.IsZero() { |
| - at = e.since[k] |
| - } |
| - if at.IsZero() { |
| - at = now |
| - } |
| - since[k] = at |
| - firing = append(firing, FiringAlert{Box: box, Rule: in.Rule, Since: at}) |
| - } |
| - } |
| - e.since = since |
| - s.alertsNow.set(firing) |
| -} |
| - |
| -// noteUnreachableOperators names, once a day, the operators no usable |
| -// connector of their own reaches, in the job status (Review Focus 4): an |
| -// operator made after this process seeded, or whose connector is |
| -// suspended, needs re-entry or was removed. |
| -func (s *Server) noteUnreachableOperators(ctx context.Context, now time.Time) { |
| - e := &s.alertEngine |
| - if !e.unreachableAt.IsZero() && now.Sub(e.unreachableAt) < alertUnreachableEvery { |
| - return |
| - } |
| - ops, err := s.store.Operators() |
| - if err != nil { |
| - log.Printf("console: alert engine: operators: %v", err) |
| - jobFailed(ctx, fmt.Errorf("operators: %w", err)) |
| - return |
| - } |
| - conns, err := s.store.AlertConnectors(alertScopeFleet) |
| - if err != nil { |
| - log.Printf("console: alert engine: alert connectors: %v", err) |
| - jobFailed(ctx, fmt.Errorf("alert connectors: %w", err)) |
| - return |
| - } |
| - e.unreachableAt = now |
| - var missing []string |
| - for _, op := range ops { |
| - if !slices.ContainsFunc(conns, func(c alertConnector) bool { |
| - return c.OwnerAddress == op && c.Confirmed && !c.Suspended && !c.NeedsReentry |
| - }) { |
| - missing = append(missing, op) |
| - } |
| - } |
| - if len(missing) > 0 { |
| - err := fmt.Errorf("no usable alert connector reaches %s", strings.Join(missing, ", ")) |
| - log.Printf("console: alert engine: %v", err) |
| - jobFailed(ctx, err) |
| - } |
| -} |
| - |
| -// writeAlertEngineBeat replaces the beat file the console box's agent |
| -// watches (spec §8) at the end of each pass that got through: a temp file |
| -// beside it, renamed over it, so the agent never reads half a beat. |
| -func (s *Server) writeAlertEngineBeat(ctx context.Context, now time.Time) { |
| - path := s.cfg.AlertEngineBeatPath |
| - if path == "" { |
| - return |
| - } |
| - if err := writeAlertBeatFile(path, now); err != nil { |
| - log.Printf("console: alert engine: beat %s: %v", path, err) |
| - jobFailed(ctx, fmt.Errorf("beat %s: %w", path, err)) |
| - } |
| -} |
| - |
| -func writeAlertBeatFile(path string, now time.Time) error { |
| - f, err := os.CreateTemp(filepath.Dir(path), ".alert-engine.beat-*") |
| - if err != nil { |
| - return err |
| - } |
| - tmp := f.Name() |
| - _, werr := f.WriteString(now.UTC().Format(time.RFC3339) + "\n") |
| - if werr == nil { |
| - werr = f.Chmod(0o644) |
| - } |
| - if cerr := f.Close(); werr == nil { |
| - werr = cerr |
| - } |
| - if werr == nil { |
| - werr = os.Rename(tmp, path) |
| - } |
| - if werr != nil { |
| - os.Remove(tmp) |
| - } |
| - return werr |
| -} |
| - |
| // operatorGrant is one recipient and the token the console sends AS them |
| // with. The token is never logged. |
| type operatorGrant struct { |
| @@ -691,73 +124,3 @@ func (s *Server) recordAlertSeen(ctx context.Context, box, rule, address string, |
| jobFailed(ctx, fmt.Errorf("record %s/%s for %s: %w", box, rule, address, err)) |
| } |
| } |
| - |
| -// alertValueText renders one rule's transition value in that rule's own |
| -// unit. Every rule internal/metrics evaluates carries a fraction EXCEPT lag, |
| -// which is keymail relay seconds (see metrics.Rules.LagSecs), and the |
| -// forecast and the engine's own rules, which carry hours, minutes and days — |
| -// so a single |
| -// percent formatter for all of them turns the first lag alert to fire into |
| -// "92000%". Used by both operator-facing surfaces: the dashboard's alerts |
| -// table and the alert mail below. |
| -// |
| -// An unknown rule name (a future rule this console has not been taught) is |
| -// rendered as a bare number rather than being given someone else's unit: a |
| -// unitless figure is honest, a wrong unit is not. |
| -func alertValueText(rule string, value float64) string { |
| - switch rule { |
| - case "disk", "mem", "cpu": |
| - return fmt.Sprintf("%.0f%%", value*100) |
| - case "lag": |
| - return fmt.Sprintf("%.0fs", value) |
| - case "geoip": |
| - // A reason code, not a measurement (geoip spec §10.4). |
| - return geoipReasonText(int(value)) |
| - case "disk_eta": |
| - return fmt.Sprintf("%.0f hours to full", value) |
| - case "box_silent": |
| - return fmt.Sprintf("%.0f minutes since its last report", value) |
| - case "cert_expiring": |
| - return fmt.Sprintf("%.0f days left", value) |
| - default: |
| - return strconv.FormatFloat(value, 'g', -1, 64) |
| - } |
| -} |
| - |
| -// alertMessage is the operator-facing copy. Plain sentences, and no needle |
| -// beyond the value that triggered the transition — this mail lands in an |
| -// inbox, not on the operator dashboard. |
| -func alertMessage(box, rule string, rs metrics.RuleState, updated time.Time) (subject, body string) { |
| - at := updated |
| - if rs.Firing && !rs.FiredAt.IsZero() { |
| - at = rs.FiredAt |
| - } |
| - stamp := at.UTC().Format(time.RFC3339) |
| - if rs.Firing { |
| - subject = fmt.Sprintf("[carlos] %s: %s alert", box, rule) |
| - body = fmt.Sprintf("The %s alert is firing on %s.\n\nValue at the transition: %s\nTime (UTC): %s\n\n"+ |
| - "You are getting this because you hold the CARLOS fleet-operator role.\n", rule, box, alertValueText(rule, rs.Value), stamp) |
| - return subject, body |
| - } |
| - subject = fmt.Sprintf("[carlos] %s: %s cleared", box, rule) |
| - body = fmt.Sprintf("The %s alert has cleared on %s.\n\nValue at the transition: %s\nTime (UTC): %s\n\n"+ |
| - "You are getting this because you hold the CARLOS fleet-operator role.\n", rule, box, alertValueText(rule, rs.Value), stamp) |
| - return subject, body |
| -} |
| - |
| -// geoipReasonText names a geoip rule reason code (geoip spec §10.4). |
| -func geoipReasonText(code int) string { |
| - switch code { |
| - case 1: |
| - return "database over 45 days old" |
| - case 2: |
| - return "GeoLite2 database expires within 9 days" |
| - case 3: |
| - return "database expired and removed" |
| - case 4: |
| - return "published database not loaded for over an hour" |
| - case 5: |
| - return "feed failing" |
| - } |
| - return "geoip reason " + strconv.Itoa(code) |
| -} |