console: alert engine replaces the alert watcher
StartAlertEngine runs one pass a minute: box signals from alerts/boxes/ through the engine's own ETag cache (conditional GETs after the first read), heartbeat signals every 5th pass (box_silent for every box with a status/boxes/ object, alert_delivery_broken, cert_expiring, service_down), seal_key, Gone for members a read source no longer reports, then stepIncidents and CommitAlertStep with the outbox rows in one call, the drain, the dashboard view from firing members, and the engine beat. The first pass opens the connector seal (an unusable key fires seal_key and holds sealed connectors; a new key marks them for re-entry), seeds each operator a confirmed email connector, and runs the one-time cutover from alert_seen inside AlertCutover. A host-claim console refuses before any read or write, with "refused: host-claim console" as its job status. The watcher's pass and its tests are gone; registries, the route census and the worker probe name StartAlertEngine, and the probe asserts the refusal.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
cmd/console/main.go+12 −7internal/console/alertengine_pass_test.go+640 −0internal/console/alertnotify.go+66 −0internal/console/alertnotify_test.go+6 −1internal/console/alertnow.go+18 −63internal/console/alertnow_test.go+34 −79internal/console/alertsignals.go+456 −0internal/console/alertstore.go+76 −0internal/console/alertwatch.go+559 −169internal/console/alertwatch_test.go+6 −303internal/console/apidomains.go+7 −0internal/console/claim_invariant_fixtures_test.go+1 −1internal/console/claim_invariant_probes_worker_test.go+54 −6internal/console/claim_runtime.go+1 −1internal/console/claim_workers.go+1 −1internal/console/economicspass.go+2 −2internal/console/jobs.go+1 −1internal/console/jobs_test.go+17 −18internal/console/metricsview.go+2 −2internal/console/opdashboard_test.go+2 −6internal/console/server.go+15 −5internal/console/testdata/claim-routes.txt+1 −1
CI failed — run details
Intent
<task-notification> <task-id>aece62afa08a0b8b3</task-id> <tool-use-id>toolu_0147zdX5skwDeE9Uudbu8C1x</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/aece62afa08a0b8b3.output</output-file> <status>completed</status> <summary>Agent "Implement Task 7: incident step" 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. All eight review fixes are in and the step tests pass. One fix needs a ruling. - **Commits:** - ab44bb99 console: incident step fix round 1 (message clocks, clears past snoozes, flap hold past gone, invariant simulation) - 8282ff57 console: incident step with noise rules - **Tests:** all 15 `TestStep*` tests pass, including the 500-seed `TestStepInvariantsRandom` in about 8–10 s. It found no new rule breaks. The `Alert` tests, `go vet` and `gofmt` are clean. Putting each reviewer finding back makes at least one test fail. - **Concerns:** 1. **Needs a ruling.** Because a fire now sets `LastUpdateAt`, the earliest update of an ordinary incident moves from minute 30 to minute 65, against §6.2's "after 30 minutes". The alternative keeps 30 minutes: gate updates on 30 min after the fire or last reminder, and 1 h since `LastUpdateAt`. 2. **The flapping hold after a Gone is approximate.** It works out who stopped firing from the last hour of fires. A box that fired more than an hour ago and has stopped since is missed. A box that went gone earlier can be held again until its next Gone or the end of the hour. 3. **A clear can now list no members** when every member is snoozed. Task 8's message text needs wording for that. 4. **`Joined` holds only the boxes that joined in the pass that sent the update.** Boxes added silently earlier appear only in `Members`, because nothing stores which boxes were already announced. - **Report:** /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/.superpowers/sdd/2026-10-30-fleet-alerts-1-engine-connectors/task-7-report.md (fix round appended)</result> <usage><subagent_tokens>165079</subagent_tokens><tool_uses>10</tool_uses><duration_ms>570183</duration_ms></usage> </task-notification>
<task-notification> <task-id>aece62afa08a0b8b3</task-id> <tool-use-id>toolu_01BSFMmdrxQBE7v8MpGMfnig</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/aece62afa08a0b8b3.output</output-file> <status>completed</status> <summary>Agent "Implement Task 7: incident step" 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. R-19 is in: a fire no longer sets `LastUpdateAt`, and an update needs 30 min since the last fire or reminder plus 1 h since the last update. An ordinary incident can now update from minute 35. - **Commits:** - d588e5b0 console: incident step update clock per R-19 (30 min after a fire or reminder, an hour between updates) - ab44bb99 console: incident step fix round 1 (message clocks, clears past snoozes, flap hold past gone, invariant simulation) - 8282ff57 console: incident step with noise rules - **Tests:** all 15 step tests pass, including the 500-seed simulation in 8.7 s with updated (f) and new (i). The `Alert` tests, `go vet` and `gofmt` are clean. Putting back any of three wrong update/reminder clock rules makes a test fail. - **Concerns:** none new; your recorded concerns 2–4 stand. One detail: if a reminder stopped resetting `LastUpdateAt`, only the simulation would catch it now, because the daily-reminder test's join is held back by the 30-minute rule first. - **Report:** /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/.superpowers/sdd/2026-10-30-fleet-alerts-1-engine-connectors/task-7-report.md (R-19 section appended)</result> <usage><subagent_tokens>172718</subagent_tokens><tool_uses>13</tool_uses><duration_ms>803559</duration_ms></usage> </task-notification>
<task-notification> <task-id>a8255afeb0754da38</task-id> <tool-use-id>toolu_012xCxGyoi7pUoKTWpqwThii</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/a8255afeb0754da38.output</output-file> <status>completed</status> <summary>Agent "Re-review Task 7 fix round 1" 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>### Finding Verdicts - **1. A fire delayed by a snooze was followed by a reminder 1 minute later, and the same for an update.** ADDRESSED. A fire now sets `LastReminderAt` (alertengine.go:274). The reminder must wait 24 h after both clocks (alertengine.go:279-280), and an update must wait 30 min after `LastReminderAt` and 1 h after `LastUpdateAt` (alertengine.go:282-283). Covered by the subtest "a late fire starts the reminder clock" (fire at 30 h, reminder at 54 h) and by `TestStepUpdateAfterLateFireWaits` (alertengine_test.go:243). - **2. A snoozed last member dropped the clear for announced members.** ADDRESSED. alertengine.go:266 emits the clear whenever `in.Notified`, and the snooze only filters `visible(out.Members)`. The subtest "a snoozed last member keeps the clear" (alertengine_test.go:473) runs the exact timeline. Invariant (c) in the simulation also requires exactly one clear for each notified close. - **3. A Gone on one member ended a flapping hold early.** ADDRESSED. alertengine.go:209-219 holds every subject of the same (scope, rule) that fired within the hour, minus anything gone this pass. `TestStepFlappingSurvivesGone` (alertengine_test.go:323) is multi-member: b2 goes gone at 10, b1 (quiet since 5) keeps the hold, b1's refire at 35 wakes incident 3, and the clear comes at 96. I traced it by hand and it matches. The approximation was already recorded. - **4. Document `LastSeenAt` and `Members`, and add `quiet()` and `firingMembers()`.** ADDRESSED. The docs are at alertstore.go:203-215. `quiet()` is at alertstore.go:227 (open, flapping, `LastSeenAt` set). `firingMembers()` is at alertstore.go:232 and returns nil while quiet or closed. `advance` uses both (alertengine.go:184-185). - **5. A reminder also resets the update clock.** ADDRESSED. See alertengine.go:280. Since R-19, `TestStepDailyReminder`'s joiner at day+6 is already blocked by the 30-minute rule, so only simulation invariant (f) at alertengine_test.go:664 catches this mutation. The report says so and shows the failure (seed 303). - **6. `alertEmit.Joined` holds the new subjects for updates.** ADDRESSED. alertengine.go:285 passes `visible(joined)`, and the fire, reminder and clear emits pass nil. Asserted at alertengine_test.go:232-240. - **7. A duplicate open incident is closed as "duplicate" with no emit.** ADDRESSED. See alertengine.go:115-121 and `alertCloseDuplicate` at alertengine.go:68. The schema puts no constraint on `close_reason` (alertstore.go:76). Tested by `TestStepDuplicateOpenClosed` (alertengine_test.go:353). - **8. R-18 simulation (500 seeds × 3 days, invariants (a)-(h)).** ADDRESSED. `TestStepInvariantsRandom` exists with 500 seeds × 4320 steps over 3 boxes. Its bookkeeping (`notified`, `lastMsg`, `lastReminder`, `lastUpdate`, `cleared`) is rebuilt from the emits and the `changed` closes, not read from the incident's own clock fields. So (b), (c), (e), (f) and (i) are real checks, not tautologies. (g) replays the same signals on the committed open set with the post-commit `recentFires`. (h) is checked in `stepSim.step`. The feedback loop matches Task 8's path: `AlertStepInputs` → `stepIncidents` → `CommitAlertStep`. The sim's `recentFires` uses the same `>= now-1h` filter and prune as alertstore.go:302-332, and `mergeChanged` keeps id order the way `ORDER BY id` does. The only gap is the nil vs `[]` Members round trip, and the step treats those the same. Weaknesses are listed under Minor below. - **9. R-19.** ADDRESSED. The gate is at alertengine.go:282-283 (`OpenedAt+30m`, `LastReminderAt+30m`, `LastUpdateAt+1h`, with a zero clock counting as passed). A fire sets only `LastReminderAt` (alertengine.go:274). Invariant (f) adds the update-or-reminder check (alertengine_test.go:664), and (i) is new (alertengine_test.go:667). `TestStepLateMemberUpdateHourly` is back to updates at 35 and 96. ### New Breakage in the Fix Diff None at Critical or Important. - **Minor.** The simulation's invariants are all "never X" checks: nothing ever asserts that a fire, reminder or close actually happens. Two areas this round touched have no invariant at all: - **The flap hold.** The report's own mutation table shows that reverting finding #3 is caught only by `TestStepFlappingSurvivesGone`, not by the simulation. - **Snooze.** No invariant checks that an emit's `Members` and `Joined` leave out snoozed subjects, so a "snooze ignored" mutation would pass the simulation. That runs against R-18's aim of catching interleavings by class. Cheap additions that check the sim's own state rather than the step's: - A flapping close only after 1 h with no firing report for that (scope, rule). - No emit names a subject while `sim.snoozed` is true. - After each pass, an incident past `NotifyAt` with a visible member is `Notified`. - **Minor.** Invariant (d) at alertengine_test.go:643 compares against `e.Incident.NotifyAt`, which the step itself set, so a step that set `NotifyAt = OpenedAt` would pass. It should compare against `OpenedAt + alertNotifyDelay`, or against the sim's own record of when the incident opened. - **Minor.** The comment on the `alertUpdateQuiet` constant at alertengine.go:75-76 still says the quiet half hour counts from the incident's age. Since R-19 it also counts from the last fire or reminder. The file comment is correct; this constant's comment is stale. ### Out-of-Scope Observations None. ### Verdict **Fix round:** All findings addressed, no new Critical or Important breakage. The three Minors above are for the ledger. I ran one check myself: `nice -n 19 go test ./internal/console -run '^TestStepInvariantsRandom$' -count=1 -v` gave PASS in 8.06 s. It ran unsandboxed, because the sandbox mounts `~/.cache/go-build` read-only.</result> <usage><subagent_tokens>94615</subagent_tokens><tool_uses>14</tool_uses><duration_ms>194889</duration_ms></usage> </task-notification>
Attributed to this commit: 22.0 g CO₂e (2,738,120 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-fleet-alerts, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/cmd/console/main.go b/cmd/console/main.go| index 47a94a8c0..1c0ef5d08 100644 |
| --- a/cmd/console/main.go |
| +++ b/cmd/console/main.go |
| @@ -476,7 +476,10 @@ func serve() { |
| // The alert connector seal's key, next to CONSOLE_DB and outside it |
| // (fleet alerts spec §5.1). |
| AlertSealKeyPath: filepath.Join(filepath.Dir(envOr("CONSOLE_DB", "/data/console/console.db")), "alert-connectors.key"), |
| - SeedData: seedData, |
| + // The alert engine's beat, beside it: the console box's agent reads |
| + // it as CARLOS_ALERT_ENGINE_BEAT (fleet alerts spec §8). |
| + AlertEngineBeatPath: filepath.Join(filepath.Dir(envOr("CONSOLE_DB", "/data/console/console.db")), "alert-engine.beat"), |
| + SeedData: seedData, |
| // The feed (geoip spec §10.1). The key goes nowhere but MaxMind. |
| GeoipFeed: os.Getenv("CONSOLE_GEOIP_FEED"), |
| GeoipMaxMindAccount: strings.TrimSpace(os.Getenv("CONSOLE_GEOIP_MAXMIND_ACCOUNT")), |
| @@ -673,12 +676,14 @@ func serve() { |
| srv.RunFleetOwnerBackfill(ctx) |
| srv.RunAppPlacementBackfill(ctx) |
| }() |
| - // The alert watcher polls alerts/boxes/*.json every minute and keymails |
| - // operators on each fire/clear (internal/console/alertwatch.go). Started |
| - // here rather than in NewServer so constructing a Server — which every |
| - // console test does — never starts a goroutine or sends mail. |
| + // The alert engine reads the alert signals every minute, steps the |
| + // incidents and sends what they owe (internal/console/alertwatch.go). |
| + // It refuses on a host-claim console and says so in its job status. |
| + // Started here rather than in NewServer so constructing a Server — |
| + // which every console test does — never starts a goroutine or sends |
| + // anything. |
| go srv.RunClaimWorker(context.Background(), "StartHostReports") |
| - go srv.RunClaimWorker(context.Background(), "StartAlertWatcher") |
| + go srv.RunClaimWorker(context.Background(), "StartAlertEngine") |
| // The geoip orphan sweep and D1 expiry, at startup and daily. |
| go srv.RunClaimWorker(context.Background(), "StartGeoipJobs") |
| // The moves console record (moves Task 13): with the switch on or a |
| @@ -686,7 +691,7 @@ func serve() { |
| go srv.RunClaimWorker(context.Background(), "PublishMovesConsole") |
| // The economics pass writes the daily usage/census/storage/statement |
| // objects and pulls the AWS bill (internal/console/economicspass.go). |
| - // Same placement rule as the alert watcher: started here, never in |
| + // Same placement rule as the alert engine: started here, never in |
| // NewServer, so constructing a Server stays goroutine-free. |
| go srv.RunClaimWorker(context.Background(), "StartClaimRecoveryPass") |
| go srv.RunClaimWorker(context.Background(), "StartEconomicsPass") |
diff --git a/internal/console/alertengine_pass_test.go b/internal/console/alertengine_pass_test.go| new file mode 100644 |
| index 000000000..2c26ecddf |
| --- /dev/null |
| +++ b/internal/console/alertengine_pass_test.go |
| @@ -0,0 +1,640 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/metrics" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// engineFixture is a console on the real S3 client over s3fake (so every |
| +// bucket request can be recorded, conditional or not), with the alert |
| +// senders recording (notifyFixture) on a clock the test moves. Writes go |
| +// straight to the directory under the fake and are not counted. |
| +type engineFixture struct { |
| + *notifyFixture |
| + lat *perfLatency |
| +} |
| + |
| +func newEngineFixture(t *testing.T, tweak func(*Config)) *engineFixture { |
| + t.Helper() |
| + lat := &perfLatency{} |
| + fx := newConsoleFixtureWith(t, consoleFixtureOptions{S3: lat, Tweak: tweak}) |
| + return &engineFixture{notifyFixture: newNotifyFixtureOn(t, fx), lat: lat} |
| +} |
| + |
| +// passAt runs one engine pass at alertT0+d. |
| +func (ef *engineFixture) passAt(t *testing.T, d time.Duration) { |
| + t.Helper() |
| + ef.now = alertT0.Add(d) |
| + if err := ef.srv.alertEnginePass(context.Background()); err != nil { |
| + t.Fatalf("pass at +%v: %v", d, err) |
| + } |
| +} |
| + |
| +// passesTo runs a pass every minute from +from to +to. |
| +func (ef *engineFixture) passesTo(t *testing.T, from, to time.Duration) { |
| + t.Helper() |
| + for d := from; d <= to; d += time.Minute { |
| + ef.passAt(t, d) |
| + } |
| +} |
| + |
| +// restart forgets the engine's memory, as a new console process starts |
| +// with none. |
| +func (ef *engineFixture) restart() { ef.srv.alertEngine = alertEngineState{} } |
| + |
| +func (ef *engineFixture) operator(t *testing.T, addrs ...string) { |
| + t.Helper() |
| + for _, a := range addrs { |
| + if err := ef.st.SetOperator(a, true); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| +} |
| + |
| +// told records that the watcher told addr (box, rule) is firing. |
| +func (ef *engineFixture) told(t *testing.T, box, rule, addr string, firing bool) { |
| + t.Helper() |
| + if err := ef.st.SetAlertSeen(box, rule, addr, firing); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func (ef *engineFixture) heartbeat(t *testing.T, label string, at time.Time, m *status.BoxMetrics) { |
| + t.Helper() |
| + b, err := json.Marshal(status.Box{GeneratedAt: at, Label: label, Metrics: m}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + putAlertBody(t, ef.rel, "status/boxes/"+label+".json", b) |
| +} |
| + |
| +func (ef *engineFixture) fleetServices(t *testing.T, up map[string]bool) { |
| + t.Helper() |
| + type svc struct { |
| + Name string `json:"name"` |
| + Up bool `json:"up"` |
| + } |
| + var f struct { |
| + Services []svc `json:"services"` |
| + } |
| + for name, u := range up { |
| + f.Services = append(f.Services, svc{name, u}) |
| + } |
| + slices.SortFunc(f.Services, func(a, b svc) int { return strings.Compare(a.Name, b.Name) }) |
| + b, err := json.Marshal(f) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + putAlertBody(t, ef.rel, alertFleetKey, b) |
| +} |
| + |
| +// mails is what the console mailer was given, to|body each. |
| +func (ef *engineFixture) mails() []string { return ef.mail.sentCopy() } |
| + |
| +func (ef *engineFixture) mailsTo(addr string) []string { |
| + var out []string |
| + for _, m := range ef.mails() { |
| + if strings.HasPrefix(m, addr+"|") { |
| + out = append(out, m) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +func (ef *engineFixture) count(t *testing.T, query string) int { |
| + t.Helper() |
| + var n int |
| + if err := ef.st.db.QueryRow(query).Scan(&n); err != nil { |
| + t.Fatalf("%s: %v", query, err) |
| + } |
| + return n |
| +} |
| + |
| +func diskState(box string, firing bool) metrics.AlertState { |
| + rs := metrics.RuleState{Firing: firing, Value: 0.93} |
| + if firing { |
| + rs.FiredAt = alertT0 |
| + } else { |
| + rs.Value = 0.71 |
| + } |
| + return boxAlert(box, "disk", rs) |
| +} |
| + |
| +const ( |
| + opA = "ops-a@example.com" |
| + opB = "ops-b@example.com" |
| +) |
| + |
| +// The forecast rule fires through Slack: nothing in the first 5 minutes |
| +// (the incident gathers members), then one post. |
| +func TestEnginePassFiresSlackForDiskETA(t *testing.T) { |
| + ef := newEngineFixture(t, nil) |
| + ef.addHook(t, alertConnectorSlack, "https://hooks.slack.com/services/T0/B0/secret", true) |
| + publishAlert(t, ef.rel, boxAlert("box-1", "disk_eta", metrics.RuleState{Firing: true, Value: 40, FiredAt: alertT0})) |
| + |
| + ef.passesTo(t, 0, 4*time.Minute) |
| + if n := len(ef.hook.requests()); n != 0 { |
| + t.Fatalf("%d posts before notify_at, want 0", n) |
| + } |
| + ef.passAt(t, 5*time.Minute) |
| + reqs := ef.hook.requests() |
| + if len(reqs) != 1 { |
| + t.Fatalf("%d posts at minute 5, want 1", len(reqs)) |
| + } |
| + for _, want := range []string{"disk_eta on box-1", "filling up", "40 hours to full"} { |
| + if !strings.Contains(string(reqs[0].body), want) { |
| + t.Errorf("the Slack post lacks %q: %s", want, reqs[0].body) |
| + } |
| + } |
| + ef.passesTo(t, 6*time.Minute, 10*time.Minute) |
| + if n := len(ef.hook.requests()); n != 1 { |
| + t.Fatalf("%d posts by minute 10, want still 1", n) |
| + } |
| +} |
| + |
| +// R2 #4, spec §9: five idle passes make exactly the requests the budget |
| +// allows, every read conditional: alerts/boxes/ listed every pass and each |
| +// alert object read, status/boxes/ listed and each heartbeat and fleet.json |
| +// read once, on the 5th. |
| +func TestEnginePassFiveCycleRequests(t *testing.T) { |
| + ef := newEngineFixture(t, nil) |
| + const alerts, heartbeats = 3, 4 |
| + for i := 1; i <= alerts; i++ { |
| + publishAlert(t, ef.rel, diskState(fmt.Sprintf("box-%d", i), false)) |
| + } |
| + for i := 1; i <= heartbeats; i++ { |
| + ef.heartbeat(t, fmt.Sprintf("box-%d", i), alertT0, nil) |
| + } |
| + ef.fleetServices(t, map[string]bool{"keymail": true}) |
| + |
| + ef.passAt(t, 0) // warm-up: the first reads, and the first heartbeat pass |
| + rec := recordS3(ef.lat, nil) |
| + ef.passesTo(t, time.Minute, 5*time.Minute) |
| + |
| + got := map[string]int{} |
| + for _, q := range rec.all() { |
| + switch { |
| + case q.Key == "" && q.Method == "GET": |
| + got["LIST "+q.Prefix]++ |
| + case q.Method == "GET" && q.IfNoneMatch == "": |
| + t.Errorf("unconditional GET %s", q.Key) |
| + got["GET "+q.Key]++ |
| + case q.Method == "GET": |
| + got["GET "+q.Key]++ |
| + default: |
| + got[q.Method+" "+q.Key]++ |
| + } |
| + } |
| + want := map[string]int{"LIST alerts/boxes/": 5, "LIST status/boxes/": 1, "GET status/fleet.json": 1} |
| + for i := 1; i <= alerts; i++ { |
| + want[fmt.Sprintf("GET alerts/boxes/box-%d.json", i)] = 5 |
| + } |
| + for i := 1; i <= heartbeats; i++ { |
| + want[fmt.Sprintf("GET status/boxes/box-%d.json", i)] = 1 |
| + } |
| + if fmt.Sprint(got) != fmt.Sprint(want) { |
| + t.Fatalf("requests over 5 idle passes:\n got %v\nwant %v", got, want) |
| + } |
| +} |
| + |
| +// R2 #6: operator A was told the fire by the watcher and B was not. The |
| +// incident opens already notified, and only B gets a fire. |
| +func TestEnginePassCutoverMixedRecipients(t *testing.T) { |
| + ef := newEngineFixture(t, nil) |
| + ef.operator(t, opA, opB) |
| + ef.told(t, "box-1", "disk", opA, true) |
| + publishAlert(t, ef.rel, diskState("box-1", true)) |
| + |
| + ef.passAt(t, 0) |
| + if got := ef.mailsTo(opB); len(got) != 1 || !strings.Contains(got[0], "disk on box-1") { |
| + t.Fatalf("B got %v, want one fire for disk on box-1", got) |
| + } |
| + if got := ef.mailsTo(opA); len(got) != 0 { |
| + t.Fatalf("A, already told, got %v", got) |
| + } |
| + if n := ef.count(t, `SELECT COUNT(*) FROM alert_incidents WHERE rule = 'disk' AND closed_at IS NULL AND notified = 1`); n != 1 { |
| + t.Fatalf("%d open notified disk incidents, want 1", n) |
| + } |
| + ef.passesTo(t, time.Minute, 10*time.Minute) |
| + if got := ef.mails(); len(got) != 1 { |
| + t.Fatalf("mails by minute 10 = %v, want only B's fire", got) |
| + } |
| +} |
| + |
| +// R2 #6: the rule stopped firing while the watcher still owed a clear. The |
| +// operator who was told the fire gets one clear, and no incident opens. |
| +func TestEnginePassCutoverPendingClear(t *testing.T) { |
| + ef := newEngineFixture(t, nil) |
| + ef.operator(t, opA, opB) |
| + ef.told(t, "box-1", "disk", opA, true) |
| + ef.told(t, "box-1", "disk", opB, false) |
| + publishAlert(t, ef.rel, diskState("box-1", false)) |
| + |
| + ef.passesTo(t, 0, 6*time.Minute) |
| + if got := ef.mailsTo(opA); len(got) != 1 || !strings.Contains(got[0], "has cleared on box-1") { |
| + t.Fatalf("A got %v, want one clear", got) |
| + } |
| + if got := ef.mailsTo(opB); len(got) != 0 { |
| + t.Fatalf("B, told it cleared, got %v", got) |
| + } |
| + if n := ef.count(t, `SELECT COUNT(*) FROM alert_incidents`); n != 0 { |
| + t.Fatalf("%d incidents, want none", n) |
| + } |
| +} |
| + |
| +// R2 #6: the cutover runs once per database. A restart finds the marker and |
| +// queues nothing more. |
| +func TestEnginePassCutoverSecondStartNoop(t *testing.T) { |
| + ef := newEngineFixture(t, nil) |
| + ef.operator(t, opA, opB) |
| + ef.told(t, "box-1", "disk", opA, true) |
| + publishAlert(t, ef.rel, diskState("box-1", true)) |
| + ef.passAt(t, 0) |
| + rows := ef.count(t, `SELECT COUNT(*) FROM alert_outbox`) |
| + incidents := ef.count(t, `SELECT COUNT(*) FROM alert_incidents`) |
| + |
| + ef.restart() |
| + ef.passesTo(t, time.Minute, 3*time.Minute) |
| + if n := ef.count(t, `SELECT COUNT(*) FROM alert_outbox`); n != rows { |
| + t.Fatalf("outbox rows %d after a restart, want %d", n, rows) |
| + } |
| + if n := ef.count(t, `SELECT COUNT(*) FROM alert_incidents`); n != incidents { |
| + t.Fatalf("incidents %d after a restart, want %d", n, incidents) |
| + } |
| + if got := ef.mails(); len(got) != 1 { |
| + t.Fatalf("mails = %v, want only B's fire from the first start", got) |
| + } |
| +} |
| + |
| +// R3 #3: a fresh database (no watcher history) takes the ordinary path: |
| +// nothing before notify_at, then the fire to every connector, Slack too. |
| +func TestEnginePassCutoverFreshDatabaseOrdinaryPath(t *testing.T) { |
| + ef := newEngineFixture(t, nil) |
| + ef.addHook(t, alertConnectorSlack, "https://hooks.slack.com/services/T0/B0/secret", true) |
| + publishAlert(t, ef.rel, diskState("box-1", true)) |
| + |
| + ef.passesTo(t, 0, 4*time.Minute) |
| + if n := len(ef.hook.requests()); n != 0 { |
| + t.Fatalf("%d posts before notify_at", n) |
| + } |
| + ef.passAt(t, 5*time.Minute) |
| + if n := len(ef.hook.requests()); n != 1 { |
| + t.Fatalf("%d posts at notify_at, want 1", n) |
| + } |
| +} |
| + |
| +// Review Focus 3: a box that never published an alert object and stops |
| +// reporting is still flagged, from its heartbeat object alone. |
| +func TestEnginePassNeverAlertedBoxGoesSilent(t *testing.T) { |
| + ef := newEngineFixture(t, nil) |
| + ef.operator(t, opA) |
| + ef.heartbeat(t, "box-9", alertT0.Add(-20*time.Minute), nil) |
| + ef.heartbeat(t, "box-2", alertT0, nil) |
| + |
| + ef.passAt(t, 0) |
| + if got := ef.mails(); len(got) != 0 { |
| + t.Fatalf("mails at once = %v, want none before notify_at", got) |
| + } |
| + ef.passesTo(t, time.Minute, 5*time.Minute) |
| + got := ef.mailsTo(opA) |
| + if len(got) != 1 || !strings.Contains(got[0], "box-9 has stopped reporting") { |
| + t.Fatalf("A got %v, want one box_silent fire for box-9", got) |
| + } |
| + if strings.Contains(got[0], "box-2") { |
| + t.Fatalf("a reporting box is in the fire: %s", got[0]) |
| + } |
| +} |
| + |
| +// A box whose alert object goes away leaves its incidents; the clear says |
| +// "no further reports", not that it cleared. |
| +func TestEnginePassBoxGoneCloses(t *testing.T) { |
| + ef := newEngineFixture(t, nil) |
| + ef.operator(t, opA) |
| + publishAlert(t, ef.rel, diskState("box-1", true)) |
| + ef.passesTo(t, 0, 5*time.Minute) |
| + fire := ef.mailsTo(opA) |
| + if len(fire) != 1 { |
| + t.Fatalf("A got %v, want the fire", fire) |
| + } |
| + for _, want := range []string{"What is wrong: The disk on box-1 is nearly full. The last reading was 93%.", "How long you have:", "What to do:"} { |
| + if !strings.Contains(fire[0], want) { |
| + t.Errorf("the fire lacks %q:\n%s", want, fire[0]) |
| + } |
| + } |
| + |
| + if err := ef.rel.Delete(context.Background(), metrics.AlertKey("box-1")); err != nil { |
| + t.Fatal(err) |
| + } |
| + ef.passAt(t, 6*time.Minute) |
| + got := ef.mailsTo(opA) |
| + if len(got) != 2 || !strings.Contains(got[1], "No further reports of disk on box-1") { |
| + t.Fatalf("A got %v, want the fire then a no further reports clear", got) |
| + } |
| + if n := ef.count(t, `SELECT COUNT(*) FROM alert_incidents WHERE closed_at IS NOT NULL AND close_reason = 'box gone'`); n != 1 { |
| + t.Fatalf("%d incidents closed as gone, want 1", n) |
| + } |
| +} |
| + |
| +// Members whose source still answers but no longer lists them leave: a |
| +// rule dropped from a box's object, a service dropped from fleet.json. |
| +func TestEnginePassUnreportedMembersLeave(t *testing.T) { |
| + ef := newEngineFixture(t, nil) |
| + ef.operator(t, opA) |
| + both := diskState("box-1", true) |
| + both.Rules["mem"] = metrics.RuleState{Firing: true, Value: 0.97, FiredAt: alertT0} |
| + publishAlert(t, ef.rel, both) |
| + ef.fleetServices(t, map[string]bool{"keymail": false, "relay": true}) |
| + ef.passesTo(t, 0, 5*time.Minute) |
| + if n := ef.count(t, `SELECT COUNT(*) FROM alert_incidents WHERE closed_at IS NULL`); n != 3 { |
| + t.Fatalf("%d open incidents, want disk, mem and service_down", n) |
| + } |
| + |
| + publishAlert(t, ef.rel, diskState("box-1", true)) // mem no longer reported |
| + ef.fleetServices(t, map[string]bool{"relay": true}) |
| + ef.passAt(t, 6*time.Minute) |
| + open := ef.count(t, `SELECT COUNT(*) FROM alert_incidents WHERE closed_at IS NULL`) |
| + if open != 2 { |
| + t.Fatalf("%d open after mem went unreported, want disk and service_down (fleet.json is read on heartbeat passes)", open) |
| + } |
| + ef.passesTo(t, 7*time.Minute, 10*time.Minute) |
| + if n := ef.count(t, `SELECT COUNT(*) FROM alert_incidents WHERE closed_at IS NULL`); n != 1 { |
| + t.Fatalf("%d open after the heartbeat pass, want disk alone", n) |
| + } |
| + if n := ef.count(t, `SELECT COUNT(*) FROM alert_incidents WHERE rule IN ('mem', 'service_down') AND close_reason = 'box gone'`); n != 2 { |
| + t.Fatalf("%d of mem and service_down closed as gone, want 2", n) |
| + } |
| +} |
| + |
| +// Day one for operators (spec §5.2): each gets a confirmed email connector |
| +// for their address, once, however many times the console starts. |
| +func TestEnginePassSeedsOperatorEmailOnce(t *testing.T) { |
| + ef := newEngineFixture(t, nil) |
| + ef.operator(t, opA, opB) |
| + ef.passAt(t, 0) |
| + ef.passAt(t, time.Minute) |
| + ef.restart() |
| + ef.passAt(t, 2*time.Minute) |
| + |
| + conns, err := ef.st.AlertConnectors(alertScopeFleet) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var owners []string |
| + for _, c := range conns { |
| + if c.Kind != alertConnectorEmail || !c.Confirmed { |
| + t.Errorf("seeded connector %+v, want a confirmed email", c) |
| + } |
| + owners = append(owners, c.OwnerAddress) |
| + if _, plain, err := ef.st.AlertConnectorTarget(c.ID); err != nil || plain != c.OwnerAddress { |
| + t.Errorf("connector %d sends to %q (%v), want its owner", c.ID, plain, err) |
| + } |
| + } |
| + if !slices.Equal(owners, []string{opA, opB}) { |
| + t.Fatalf("seeded owners %v, want one each for A and B", owners) |
| + } |
| +} |
| + |
| +// The watcher already told the only operator the fire: no fire again, and |
| +// the clear, when it comes, is sent. |
| +func TestEnginePassCutoverNoRefire(t *testing.T) { |
| + ef := newEngineFixture(t, nil) |
| + ef.operator(t, opA) |
| + ef.told(t, "box-1", "disk", opA, true) |
| + publishAlert(t, ef.rel, diskState("box-1", true)) |
| + ef.passesTo(t, 0, 10*time.Minute) |
| + if got := ef.mails(); len(got) != 0 { |
| + t.Fatalf("mails = %v, want none: A was told", got) |
| + } |
| + publishAlert(t, ef.rel, diskState("box-1", false)) |
| + ef.passAt(t, 11*time.Minute) |
| + if got := ef.mailsTo(opA); len(got) != 1 || !strings.Contains(got[0], "disk has cleared on box-1") { |
| + t.Fatalf("A got %v, want one clear", got) |
| + } |
| +} |
| + |
| +// Review Focus 2: the console dies after committing a fire and before |
| +// sending it. The reopened database still owes it, and it goes once. |
| +func TestEnginePassCrashBetweenCommitAndSend(t *testing.T) { |
| + ef := newEngineFixture(t, nil) |
| + ef.operator(t, opA) |
| + publishAlert(t, ef.rel, diskState("box-1", true)) |
| + ef.passesTo(t, 0, 4*time.Minute) |
| + |
| + ef.now = alertT0.Add(5 * time.Minute) |
| + if _, _, err := ef.srv.alertEngineStep(context.Background(), ef.now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := ef.mails(); len(got) != 0 { |
| + t.Fatalf("the step alone sent %v", got) |
| + } |
| + var path string |
| + if err := ef.st.db.QueryRow(`SELECT file FROM pragma_database_list WHERE name = 'main'`).Scan(&path); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := ef.st.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + st, err := Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { st.Close() }) |
| + ef.srv.store, ef.st = st, st |
| + ef.restart() |
| + |
| + if err := ef.srv.alertDrainOutbox(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + ef.passesTo(t, 6*time.Minute, 8*time.Minute) |
| + if got := ef.mailsTo(opA); len(got) != 1 || !strings.Contains(got[0], "disk on box-1") { |
| + t.Fatalf("A got %v, want the fire exactly once", got) |
| + } |
| +} |
| + |
| +// Review Focus 5: a seal key that cannot be read holds every sealed |
| +// connector, fires one seal_key incident, and email keeps working. |
| +func TestEnginePassSealKeyUnreadable(t *testing.T) { |
| + key := filepath.Join(t.TempDir(), "alert-connectors.key") |
| + if err := os.WriteFile(key, []byte("short"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + ef := newEngineFixture(t, func(c *Config) { c.AlertSealKeyPath = key }) |
| + ef.srv.alertSeal.Store(nil) // as a console starts: no seal until the engine opens one |
| + ef.operator(t, opA) |
| + slack := ef.addHook(t, alertConnectorSlack, "https://hooks.slack.com/services/T0/B0/secret", true) |
| + |
| + ctx := context.Background() |
| + ef.now = alertT0 |
| + if err := ef.srv.jobs.Run(ctx, "StartAlertEngine", ef.srv.alertEnginePass); err != nil { |
| + t.Fatal(err) |
| + } |
| + if st, _ := jobStatusOf(ef.srv, "StartAlertEngine"); st.State != JobFailed || !strings.Contains(st.Err, "alert seal key") { |
| + t.Fatalf("job status %+v, want Failed naming the seal key", st) |
| + } |
| + ef.passesTo(t, time.Minute, 5*time.Minute) |
| + got := ef.mailsTo(opA) |
| + if len(got) != 1 || !strings.Contains(got[0], "connectors on console cannot be used") || !strings.Contains(got[0], "Email still works") { |
| + t.Fatalf("A got %v, want one seal_key fire", got) |
| + } |
| + if n := len(ef.hook.requests()); n != 0 { |
| + t.Fatalf("%d Slack posts with no usable seal", n) |
| + } |
| + if rows := ef.outbox(t, slack); len(rows) != 1 || rows[0].sent || rows[0].cat != "no seal key" { |
| + t.Fatalf("Slack outbox = %+v, want one row held for the seal", rows) |
| + } |
| +} |
| + |
| +// A key made fresh while sealed connectors exist: they need re-entering, |
| +// and seal_key fires until they are. |
| +func TestEnginePassNewSealKeyMarksReentry(t *testing.T) { |
| + key := filepath.Join(t.TempDir(), "alert-connectors.key") |
| + ef := newEngineFixture(t, func(c *Config) { c.AlertSealKeyPath = key }) |
| + ef.srv.alertSeal.Store(nil) |
| + ef.operator(t, opA) |
| + slack := ef.addHook(t, alertConnectorSlack, "https://hooks.slack.com/services/T0/B0/secret", true) |
| + |
| + ef.passesTo(t, 0, 5*time.Minute) |
| + if !ef.connector(t, slack).NeedsReentry { |
| + t.Fatal("a Slack connector sealed under the lost key does not need re-entering") |
| + } |
| + if got := ef.mailsTo(opA); len(got) != 1 || !strings.Contains(got[0], "connectors on console cannot be used") { |
| + t.Fatalf("A got %v, want one seal_key fire", got) |
| + } |
| +} |
| + |
| +// R2 #1, spec §5.2: a host-claim console refuses before any read or write, |
| +// and says so in its job status. |
| +func TestEngineRefusesInHostClaim(t *testing.T) { |
| + beat := filepath.Join(t.TempDir(), "alert-engine.beat") |
| + ef := newEngineFixture(t, func(c *Config) { c.AlertEngineBeatPath = beat }) |
| + ef.operator(t, opA) |
| + ef.told(t, "box-1", "disk", opA, true) |
| + publishAlert(t, ef.rel, diskState("box-1", true)) |
| + ef.srv.cfg.HostClaim = true |
| + rec := recordS3(ef.lat, nil) |
| + |
| + done := make(chan struct{}) |
| + go func() { defer close(done); ef.srv.StartAlertEngine(context.Background()) }() |
| + select { |
| + case <-done: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("the engine on a host-claim console did not return") |
| + } |
| + st, _ := jobStatusOf(ef.srv, "StartAlertEngine") |
| + if st.State != JobFailed || st.Err != "refused: host-claim console" { |
| + t.Fatalf("job status %+v, want the refusal", st) |
| + } |
| + if reqs := rec.all(); len(reqs) != 0 { |
| + t.Fatalf("a refused engine made bucket requests: %+v", reqs) |
| + } |
| + for _, table := range []string{"alert_connectors", "alert_incidents", "alert_fires", "alert_outbox", "alert_meta"} { |
| + if n := ef.count(t, "SELECT COUNT(*) FROM "+table); n != 0 { |
| + t.Errorf("%s has %d rows after a refusal", table, n) |
| + } |
| + } |
| + if _, err := os.Stat(beat); !os.IsNotExist(err) { |
| + t.Errorf("a refused engine wrote its beat (%v)", err) |
| + } |
| +} |
| + |
| +// The dashboard's view is the box rules' firing members: unknown before |
| +// the first pass, the box's FiredAt as since, a console rule left out, and |
| +// empty once cleared. |
| +func TestEnginePassFeedsAlertsNow(t *testing.T) { |
| + ef := newEngineFixture(t, nil) |
| + if _, known := ef.srv.alertsNow.Firing(); known { |
| + t.Fatal("known before any pass") |
| + } |
| + firedAt := alertT0.Add(-time.Hour) |
| + publishAlert(t, ef.rel, boxAlert("box-1", "disk", metrics.RuleState{Firing: true, Value: 0.95, FiredAt: firedAt})) |
| + ef.heartbeat(t, "box-2", alertT0.Add(-time.Hour), nil) // box_silent: a console rule |
| + ef.passAt(t, 0) |
| + got, known := ef.srv.alertsNow.Firing() |
| + if !known || len(got) != 1 || got[0].Box != "box-1" || got[0].Rule != "disk" || !got[0].Since.Equal(firedAt) { |
| + t.Fatalf("firing %+v known %v, want box-1/disk since %v", got, known, firedAt) |
| + } |
| + publishAlert(t, ef.rel, diskState("box-1", false)) |
| + ef.passAt(t, time.Minute) |
| + if got, known := ef.srv.alertsNow.Firing(); !known || len(got) != 0 { |
| + t.Fatalf("firing %+v known %v after the clear, want nothing", got, known) |
| + } |
| +} |
| + |
| +// Spec §8: each pass replaces the beat file the console box's agent |
| +// watches, whole, at 0644, leaving no temp file behind. |
| +func TestEnginePassWritesBeat(t *testing.T) { |
| + dir := t.TempDir() |
| + beat := filepath.Join(dir, "alert-engine.beat") |
| + ef := newEngineFixture(t, func(c *Config) { c.AlertEngineBeatPath = beat }) |
| + for i, d := range []time.Duration{0, time.Minute} { |
| + ef.passAt(t, d) |
| + fi, err := os.Lstat(beat) |
| + if err != nil { |
| + t.Fatalf("pass %d: %v", i, err) |
| + } |
| + if !fi.Mode().IsRegular() || fi.Mode().Perm() != 0o644 { |
| + t.Fatalf("pass %d: beat mode %v, want a regular 0644 file", i, fi.Mode()) |
| + } |
| + body, err := os.ReadFile(beat) |
| + if err != nil || strings.TrimSpace(string(body)) != ef.now.Format(time.RFC3339) { |
| + t.Fatalf("pass %d: beat says %q (%v), want %s", i, body, err, ef.now.Format(time.RFC3339)) |
| + } |
| + } |
| + entries, err := os.ReadDir(dir) |
| + if err != nil || len(entries) != 1 { |
| + t.Fatalf("beat dir holds %v (%v), want the beat alone", entries, err) |
| + } |
| +} |
| + |
| +// Review Focus 4: an operator no connector reaches is named in the job |
| +// status, once a day. |
| +func TestEnginePassNamesUnreachableOperators(t *testing.T) { |
| + ef := newEngineFixture(t, nil) |
| + ef.operator(t, opA) |
| + ctx := context.Background() |
| + run := func(d time.Duration) JobStatus { |
| + t.Helper() |
| + ef.now = alertT0.Add(d) |
| + if err := ef.srv.jobs.Run(ctx, "StartAlertEngine", ef.srv.alertEnginePass); err != nil { |
| + t.Fatal(err) |
| + } |
| + st, _ := jobStatusOf(ef.srv, "StartAlertEngine") |
| + return st |
| + } |
| + if st := run(0); st.State != JobOK { |
| + t.Fatalf("first pass %+v, want OK: A was seeded", st) |
| + } |
| + ef.operator(t, opB) // made after this process seeded |
| + if st := run(time.Minute); st.State != JobOK { |
| + t.Fatalf("pass within the day %+v, want OK", st) |
| + } |
| + if st := run(24 * time.Hour); st.State != JobFailed || !strings.Contains(st.Err, opB) || strings.Contains(st.Err, opA) { |
| + t.Fatalf("daily check %+v, want Failed naming B alone", st) |
| + } |
| + if st := run(24*time.Hour + time.Minute); st.State != JobOK { |
| + t.Fatalf("pass after the daily check %+v, want OK", st) |
| + } |
| +} |
| + |
| +// An alert object that does not parse is stepped over: the box beside it |
| +// still fires, and the junk box's state is left as it was. |
| +func TestEnginePassSurvivesJunk(t *testing.T) { |
| + ef := newEngineFixture(t, nil) |
| + ef.operator(t, opA) |
| + putAlertBody(t, ef.rel, "alerts/boxes/box-junk.json", []byte("{not json")) |
| + publishAlert(t, ef.rel, diskState("box-1", true)) |
| + ef.passesTo(t, 0, 5*time.Minute) |
| + if got := ef.mailsTo(opA); len(got) != 1 || !strings.Contains(got[0], "disk on box-1") { |
| + t.Fatalf("A got %v, want box-1's fire", got) |
| + } |
| +} |
diff --git a/internal/console/alertnotify.go b/internal/console/alertnotify.go| index 6f1b6821e..30c811621 100644 |
| --- a/internal/console/alertnotify.go |
| +++ b/internal/console/alertnotify.go |
| @@ -110,6 +110,72 @@ var alertCopy = map[string]string{ |
| "test.what_to_do": "Nothing. Real alerts will arrive here like this one.", |
| "test.what_to_do.confirm": "Open the confirm link. Until then, no alerts come here.", |
| "test.what_to_do.webhook": "Answer with any 2xx status. The first one confirms this webhook.", |
| + |
| + // The engine's messages (alertwatch.go, alertEmitNote). Each rule's |
| + // what takes the subject; "what.value" follows it when the pass has a |
| + // reading. A rule with no entry of its own uses rule.default. |
| + "subject.none": "the fleet", |
| + "what.value": "The last reading was %s.", |
| + "update.what": "Now also affected: %s.", |
| + |
| + "clear.what": "%[1]s has cleared on %[2]s.", |
| + "clear.what.gone": "No further reports of %[1]s on %[2]s.", |
| + "clear.how_long": "Nothing is wrong now.", |
| + "clear.how_long.gone": "It may have stopped, or what reported it may have gone.", |
| + "clear.what_to_do": "Nothing.", |
| + "clear.what_to_do.gone": "Check it went away for a good reason, such as a box being replaced.", |
| + |
| + "rule.default.what": "%s needs attention.", |
| + "rule.default.how_long": "It is not known how long you have.", |
| + "rule.default.what_to_do": "Look at it on the fleet page.", |
| + |
| + "rule.disk_eta.what": "The disk on %s is filling up.", |
| + "rule.disk_eta.how_long": "At this rate it is full within 3 days.", |
| + "rule.disk_eta.what_to_do": "Free space on it or give it a bigger disk.", |
| + |
| + "rule.disk.what": "The disk on %s is nearly full.", |
| + "rule.disk.how_long": "Writes fail once it is full, which may be soon.", |
| + "rule.disk.what_to_do": "Free space on it now, or give it a bigger disk.", |
| + |
| + "rule.mem.what": "Memory on %s is running high.", |
| + "rule.mem.how_long": "Processes may be stopped if it keeps climbing.", |
| + "rule.mem.what_to_do": "Check what is using memory on it.", |
| + |
| + "rule.cpu.what": "The processor on %s has been busy for a while.", |
| + "rule.cpu.how_long": "Requests are slower while it stays this busy.", |
| + "rule.cpu.what_to_do": "Check what is using it, or move apps to another box.", |
| + |
| + "rule.lag.what": "Mail relay on %s is falling behind.", |
| + "rule.lag.how_long": "Messages are late until it catches up.", |
| + "rule.lag.what_to_do": "Check the relay on that box.", |
| + |
| + "rule.geoip.what": "The location database on %s needs attention.", |
| + "rule.geoip.how_long": "Location answers go stale, then stop.", |
| + "rule.geoip.what_to_do": "Check the location data feed.", |
| + |
| + "rule.engine_silent.what": "The alert engine on %s stopped writing its beat.", |
| + "rule.engine_silent.how_long": "Until it runs again, no alerts are sent.", |
| + "rule.engine_silent.what_to_do": "Check the console on that box.", |
| + |
| + "rule.box_silent.what": "%s has stopped reporting.", |
| + "rule.box_silent.how_long": "If it is down, every app on it is down too.", |
| + "rule.box_silent.what_to_do": "Check the box is running and can reach the bucket.", |
| + |
| + "rule.service_down.what": "The %s service is down.", |
| + "rule.service_down.how_long": "What relies on it fails until it is back.", |
| + "rule.service_down.what_to_do": "Check the service on the fleet page.", |
| + |
| + "rule.cert_expiring.what": "The certificate for %s expires soon.", |
| + "rule.cert_expiring.how_long": "Visitors see a warning once it expires.", |
| + "rule.cert_expiring.what_to_do": "Check why it has not renewed.", |
| + |
| + "rule.alert_delivery_broken.what": "%s has nowhere to send its own alerts.", |
| + "rule.alert_delivery_broken.how_long": "If the console stops, nobody hears from that box.", |
| + "rule.alert_delivery_broken.what_to_do": "Set CARLOS_ALERT_WEBHOOK or CARLOS_ALERT_SNS_TOPIC_ARN in its host.env.", |
| + |
| + "rule.seal_key.what": "The key that opens Slack and webhook connectors on %s cannot be used.", |
| + "rule.seal_key.how_long": "Slack and webhook alerts are not sent until it is fixed. Email still works.", |
| + "rule.seal_key.what_to_do": "Restore the key file beside console.db, or enter each Slack and webhook connector again.", |
| } |
| func alertHeadline(n alertNote) string { |
diff --git a/internal/console/alertnotify_test.go b/internal/console/alertnotify_test.go| index d0aac23ad..aad5cd217 100644 |
| --- a/internal/console/alertnotify_test.go |
| +++ b/internal/console/alertnotify_test.go |
| @@ -87,7 +87,12 @@ func (h *hookRecorder) requests() []hookReq { |
| func newNotifyFixture(t *testing.T) *notifyFixture { |
| t.Helper() |
| - fx := newConsoleFixture(t) |
| + return newNotifyFixtureOn(t, newConsoleFixture(t)) |
| +} |
| + |
| +// newNotifyFixtureOn wires the recording senders onto fx. |
| +func newNotifyFixtureOn(t *testing.T, fx *consoleFixture) *notifyFixture { |
| + t.Helper() |
| nf := ¬ifyFixture{consoleFixture: fx, mail: &fakeConsoleMail{ready: true}, now: alertT0, |
| hook: &hookRecorder{status: http.StatusOK, got: make(chan struct{}, 1)}} |
| fx.srv.consoleMail = nf.mail |
diff --git a/internal/console/alertnow.go b/internal/console/alertnow.go| index 5836e81a2..aafa87c59 100644 |
| --- a/internal/console/alertnow.go |
| +++ b/internal/console/alertnow.go |
| @@ -4,20 +4,16 @@ import ( |
| "sort" |
| "sync" |
| "time" |
| - |
| - "github.com/carlosframework/platform/internal/metrics" |
| ) |
| -// What is firing now, as the alert watcher last read it from |
| -// alerts/boxes/*.json (alertPass). The operator pages read this rather than |
| -// alert_seen, which is per-recipient delivery history: a row there says who |
| -// was told what, and stays "firing" for an operator who lost their grant |
| -// before the clear was mailed. The projection is rebuilt from the objects |
| -// on every pass, so it reads nothing the watcher does not already read. |
| +// What is firing now: the box rules of the alert engine's open incidents, |
| +// their firing members only (alertwatch.go, feedAlertsNow). The operator |
| +// pages read this rather than the incidents or the outbox, which say who |
| +// was told what. A quiet flapping incident shows nothing. |
| // |
| -// A box whose object cannot be read or parsed keeps its last entries (the |
| -// run is marked Failed); a box whose object is gone drops out. Until the |
| -// first pass whose listing succeeds, the projection is unknown. |
| +// A box whose object cannot be read or parsed keeps its entries, since its |
| +// incidents keep their members; a box whose object is gone drops out as its |
| +// members leave. Until the first pass that commits, the view is unknown. |
| // FiringAlert is one rule firing on one box, since when. |
| type FiringAlert struct { |
| @@ -25,9 +21,9 @@ type FiringAlert struct { |
| Since time.Time |
| } |
| -// A nil *alertNow is usable: its setters do nothing and Firing reports |
| -// nothing known, so a Server built as a bare &Server{...} (older tests) runs |
| -// the alert pass as it did before alertsNow existed. |
| +// A nil *alertNow is usable: set does nothing and Firing reports nothing |
| +// known, so a Server built as a bare &Server{...} (older tests) runs the |
| +// alert pass as it did before alertsNow existed. |
| type alertNow struct { |
| mu sync.Mutex |
| known bool |
| @@ -36,62 +32,21 @@ type alertNow struct { |
| func newAlertNow() *alertNow { return &alertNow{boxes: map[string]map[string]time.Time{}} } |
| -// setBox replaces box's entries with its rules that are firing. Since is the |
| -// rule's FiredAt, or, without one, the since it already had while firing, |
| -// else now. |
| -func (a *alertNow) setBox(box string, rules map[string]metrics.RuleState, now time.Time) { |
| +// set replaces every entry with firing and marks the view known: the alert |
| +// engine rebuilds it from the open incidents on each pass that commits. |
| +func (a *alertNow) set(firing []FiringAlert) { |
| if a == nil { |
| return |
| } |
| a.mu.Lock() |
| defer a.mu.Unlock() |
| - prev := a.boxes[box] |
| - next := map[string]time.Time{} |
| - for rule, rs := range rules { |
| - if !rs.Firing { |
| - continue |
| - } |
| - since := rs.FiredAt |
| - if since.IsZero() { |
| - if p, ok := prev[rule]; ok { |
| - since = p |
| - } else { |
| - since = now |
| - } |
| + a.boxes = map[string]map[string]time.Time{} |
| + for _, f := range firing { |
| + if a.boxes[f.Box] == nil { |
| + a.boxes[f.Box] = map[string]time.Time{} |
| } |
| - next[rule] = since |
| - } |
| - if len(next) == 0 { |
| - delete(a.boxes, box) |
| - return |
| - } |
| - if a.boxes == nil { |
| - a.boxes = map[string]map[string]time.Time{} |
| + a.boxes[f.Box][f.Rule] = f.Since |
| } |
| - a.boxes[box] = next |
| -} |
| - |
| -// keepOnly drops the boxes not in boxes: their object is gone. |
| -func (a *alertNow) keepOnly(boxes map[string]bool) { |
| - if a == nil { |
| - return |
| - } |
| - a.mu.Lock() |
| - defer a.mu.Unlock() |
| - for box := range a.boxes { |
| - if !boxes[box] { |
| - delete(a.boxes, box) |
| - } |
| - } |
| -} |
| - |
| -// markKnown records that a pass has listed the alert objects. |
| -func (a *alertNow) markKnown() { |
| - if a == nil { |
| - return |
| - } |
| - a.mu.Lock() |
| - defer a.mu.Unlock() |
| a.known = true |
| } |
diff --git a/internal/console/alertnow_test.go b/internal/console/alertnow_test.go| index 3d1908adb..68afbd5a7 100644 |
| --- a/internal/console/alertnow_test.go |
| +++ b/internal/console/alertnow_test.go |
| @@ -5,7 +5,6 @@ import ( |
| "encoding/json" |
| "net/http" |
| "slices" |
| - "strconv" |
| "testing" |
| "time" |
| @@ -13,21 +12,12 @@ import ( |
| "github.com/carlosframework/platform/internal/release" |
| ) |
| -// alertNowFixture is newPerfFixture (the console on the real S3 client over |
| -// s3fake) with Paul an operator holding a grant, and the alert mail |
| -// captured, so a pass runs through fx.srv.alertPass as the watcher runs it. |
| -func alertNowFixture(t *testing.T) (*consoleFixture, *perfLatency, *[]sentMail) { |
| +// alertNowFixture is newPerfFixture: the console on the real S3 client over |
| +// s3fake, so a pass runs through fx.srv.alertEnginePass as the engine's |
| +// worker runs it and a test can refuse its requests. |
| +func alertNowFixture(t *testing.T) (*consoleFixture, *perfLatency) { |
| t.Helper() |
| - fx, lat := newPerfFixture(t) |
| - if err := fx.st.SetGrantToken("paul@keymail.dev", "grant-p", time.Now()); err != nil { |
| - t.Fatal(err) |
| - } |
| - sent := &[]sentMail{} |
| - fx.srv.sendApp = func(_ context.Context, token, to, subject, body string) (string, error) { |
| - *sent = append(*sent, sentMail{token, to, subject, body}) |
| - return "msg-1", nil |
| - } |
| - return fx, lat, sent |
| + return newPerfFixture(t) |
| } |
| // publishAlert writes st as its box's alert object in the bucket under the |
| @@ -61,7 +51,7 @@ var alertNowFiredAt = time.Date(2026, 10, 26, 10, 0, 0, 0, time.UTC) |
| func alertNowPass(t *testing.T, fx *consoleFixture) { |
| t.Helper() |
| - if err := fx.srv.alertPass(context.Background()); err != nil { |
| + if err := fx.srv.alertEnginePass(context.Background()); err != nil { |
| t.Fatal(err) |
| } |
| } |
| @@ -82,28 +72,19 @@ func wantFiring(t *testing.T, fx *consoleFixture, want []FiringAlert) { |
| } |
| } |
| -// TestAlertsNowFiringThenClearedWithARecipientChange: what is firing comes |
| -// from the alert objects, not from alert_seen. After the recipients change |
| -// and the alert clears, alert_seen still says Paul was told it fired (the |
| -// history the dashboard must not read), and the projection is empty. |
| -func TestAlertsNowFiringThenClearedWithARecipientChange(t *testing.T) { |
| - fx, _, sent := alertNowFixture(t) |
| +// TestAlertsNowFiringThenCleared: what is firing comes from the engine's |
| +// incidents, not from who was told. alert_seen still says Paul was told the |
| +// rule fired (the watcher's history, which the dashboard must not read), |
| +// and once the alert clears the view is empty. |
| +func TestAlertsNowFiringThenCleared(t *testing.T) { |
| + fx, _ := alertNowFixture(t) |
| + if err := fx.st.SetAlertSeen("box-1", "disk", "paul@keymail.dev", true); err != nil { |
| + t.Fatal(err) |
| + } |
| publishAlert(t, fx.rel, boxAlert("box-1", "disk", metrics.RuleState{Firing: true, Value: 0.95, FiredAt: alertNowFiredAt})) |
| alertNowPass(t, fx) |
| wantFiring(t, fx, []FiringAlert{{Box: "box-1", Rule: "disk", Since: alertNowFiredAt}}) |
| - if len(*sent) != 1 { |
| - t.Fatalf("sent %d mails, want 1 to Paul", len(*sent)) |
| - } |
| - if err := fx.st.SetGrantToken("paul@keymail.dev", "", time.Now()); err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := fx.st.SetOperator("ann@example.com", true); err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := fx.st.SetGrantToken("ann@example.com", "grant-a", time.Now()); err != nil { |
| - t.Fatal(err) |
| - } |
| publishAlert(t, fx.rel, boxAlert("box-1", "disk", metrics.RuleState{Firing: false, Value: 0.5})) |
| alertNowPass(t, fx) |
| wantFiring(t, fx, nil) |
| @@ -116,22 +97,12 @@ func TestAlertsNowFiringThenClearedWithARecipientChange(t *testing.T) { |
| } |
| } |
| -// TestAlertsNowGeoipIsOneEntry: a geoip firing writes six alert_seen rows |
| -// (geoip and geoip@1 to geoip@5) and is one firing entry. |
| +// TestAlertsNowGeoipIsOneEntry: a firing geoip rule is one entry, whatever |
| +// its reason code. |
| func TestAlertsNowGeoipIsOneEntry(t *testing.T) { |
| - fx, _, _ := alertNowFixture(t) |
| + fx, _ := alertNowFixture(t) |
| publishAlert(t, fx.rel, boxAlert("box-1", "geoip", metrics.RuleState{Firing: true, Value: 2, FiredAt: alertNowFiredAt})) |
| alertNowPass(t, fx) |
| - for code := 1; code <= 5; code++ { |
| - rule := "geoip@" + strconv.Itoa(code) |
| - seen, known, err := fx.st.AlertSeen("box-1", rule, "paul@keymail.dev") |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - if !known || seen != (code == 2) { |
| - t.Errorf("alert_seen %s = seen %v known %v", rule, seen, known) |
| - } |
| - } |
| wantFiring(t, fx, []FiringAlert{{Box: "box-1", Rule: "geoip", Since: alertNowFiredAt}}) |
| } |
| @@ -139,7 +110,7 @@ func TestAlertsNowGeoipIsOneEntry(t *testing.T) { |
| // cannot be read or parsed keeps its last entries; a box whose object is |
| // gone drops out. |
| func TestAlertsNowKeepsABoxWhoseReadFailedAndDropsAGoneBox(t *testing.T) { |
| - fx, lat, _ := alertNowFixture(t) |
| + fx, lat := alertNowFixture(t) |
| key := metrics.AlertKey("box-1") |
| publishAlert(t, fx.rel, boxAlert("box-1", "disk", metrics.RuleState{Firing: true, Value: 0.95, FiredAt: alertNowFiredAt})) |
| publishAlert(t, fx.rel, boxAlert("box-2", "mem", metrics.RuleState{Firing: true, Value: 0.97})) |
| @@ -178,12 +149,12 @@ func TestAlertsNowKeepsABoxWhoseReadFailedAndDropsAGoneBox(t *testing.T) { |
| // is firing; a failed listing leaves it unknown; a pass over an empty prefix |
| // knows that nothing is. |
| func TestAlertsNowUnknownBeforeTheFirstPass(t *testing.T) { |
| - fx, lat, _ := alertNowFixture(t) |
| + fx, lat := alertNowFixture(t) |
| if got, known := fx.srv.alertsNow.Firing(); known || len(got) != 0 { |
| t.Fatalf("fresh console: firing %+v known %v, want unknown", got, known) |
| } |
| recordS3(lat, func(q s3Req) bool { return q.Key == "" && q.Prefix == alertPrefix }) |
| - if err := fx.srv.alertPass(context.Background()); err == nil { |
| + if err := fx.srv.alertEnginePass(context.Background()); err == nil { |
| t.Fatal("a pass whose listing is refused returned nil") |
| } |
| if _, known := fx.srv.alertsNow.Firing(); known { |
| @@ -194,45 +165,29 @@ func TestAlertsNowUnknownBeforeTheFirstPass(t *testing.T) { |
| wantFiring(t, fx, nil) |
| } |
| -// TestAlertsNowWithoutKeymailStaysUnknownAndReadsNothing: with no sender |
| -// the watcher does nothing at all, so it reads nothing and knows nothing. |
| -func TestAlertsNowWithoutKeymailStaysUnknownAndReadsNothing(t *testing.T) { |
| - fx, lat, _ := alertNowFixture(t) |
| - publishAlert(t, fx.rel, boxAlert("box-1", "disk", metrics.RuleState{Firing: true, FiredAt: alertNowFiredAt})) |
| - fx.srv.sendApp = nil |
| - rec := recordS3(lat, nil) |
| - alertNowPass(t, fx) |
| - if reqs := rec.all(); len(reqs) != 0 { |
| - t.Errorf("a pass with no sender made S3 requests: %+v", reqs) |
| - } |
| - if got, known := fx.srv.alertsNow.Firing(); known || len(got) != 0 { |
| - t.Errorf("firing %+v known %v, want unknown", got, known) |
| - } |
| -} |
| - |
| -// TestAlertNowSetBoxReplaces pins setBox and Firing (not acceptance: a unit |
| -// test of alertNow): a box's entries are replaced, cleared rules go, the |
| +// TestAlertNowSetReplaces pins set and Firing (not acceptance: a unit test |
| +// of alertNow): set replaces every entry and marks the view known, and the |
| // result is sorted and a copy. |
| -func TestAlertNowSetBoxReplaces(t *testing.T) { |
| +func TestAlertNowSetReplaces(t *testing.T) { |
| a := newAlertNow() |
| t0 := time.Date(2026, 10, 26, 9, 0, 0, 0, time.UTC) |
| - a.setBox("b", map[string]metrics.RuleState{"mem": {Firing: true}, "disk": {Firing: true, FiredAt: t0}, "cpu": {}}, t0.Add(time.Minute)) |
| - a.setBox("a", map[string]metrics.RuleState{"lag": {Firing: true, FiredAt: t0}}, t0) |
| - a.markKnown() |
| + if _, known := a.Firing(); known { |
| + t.Fatal("known before any set") |
| + } |
| + a.set([]FiringAlert{{"b", "mem", t0.Add(time.Minute)}, {"b", "disk", t0}, {"a", "lag", t0}}) |
| got, known := a.Firing() |
| want := []FiringAlert{{"a", "lag", t0}, {"b", "disk", t0}, {"b", "mem", t0.Add(time.Minute)}} |
| if !known || !slices.Equal(got, want) { |
| t.Fatalf("firing = %+v known %v, want %+v", got, known, want) |
| } |
| got[0].Box = "changed" |
| - a.setBox("b", map[string]metrics.RuleState{"mem": {Firing: true}}, t0.Add(time.Hour)) |
| + a.set([]FiringAlert{{"b", "mem", t0.Add(time.Minute)}}) |
| got, _ = a.Firing() |
| - want = []FiringAlert{{"a", "lag", t0}, {"b", "mem", t0.Add(time.Minute)}} |
| - if !slices.Equal(got, want) { |
| - t.Fatalf("firing = %+v, want %+v (a copy, disk cleared, mem keeps its since)", got, want) |
| + if want := []FiringAlert{{"b", "mem", t0.Add(time.Minute)}}; !slices.Equal(got, want) { |
| + t.Fatalf("firing = %+v, want %+v (a copy, replaced whole)", got, want) |
| } |
| - a.keepOnly(map[string]bool{"b": true}) |
| - if got, _ = a.Firing(); len(got) != 1 || got[0].Box != "b" { |
| - t.Fatalf("after keepOnly(b): %+v", got) |
| + a.set(nil) |
| + if got, known = a.Firing(); !known || len(got) != 0 { |
| + t.Fatalf("after set(nil): %+v known %v, want nothing, known", got, known) |
| } |
| } |
diff --git a/internal/console/alertsignals.go b/internal/console/alertsignals.go| new file mode 100644 |
| index 000000000..fba8ab90c |
| --- /dev/null |
| +++ b/internal/console/alertsignals.go |
| @@ -0,0 +1,456 @@ |
| +package console |
| + |
| +// The alert engine's reads and signals (fleet alerts spec §7, §9). Every |
| +// bucket read the engine makes goes through engineReads, its own ETag cache: |
| +// after an object's first read, each read is a conditional GET, so an |
| +// unchanged object costs a 304. LIST calls are alerts/boxes/ every pass and |
| +// status/boxes/ every 5th pass, nothing else (spec §9). |
| +// |
| +// A pass turns what it read into alertSignals: one signal per (scope, rule, |
| +// subject) a source reported this pass, and, for each source it read, which |
| +// subjects it could not read. A member of an open incident whose source was |
| +// read but no longer reports it (a box's alert object gone, a rule dropped |
| +// from it, a service gone from fleet.json, a host no longer served, a |
| +// heartbeat object gone) gets a Gone signal, so no incident stays open |
| +// forever on a subject nothing reports. A subject whose read failed keeps |
| +// its state. |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "os" |
| + "slices" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/alerting" |
| + "github.com/carlosframework/platform/internal/metrics" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +const ( |
| + alertStatusBoxesPrefix = "status/boxes/" |
| + alertFleetKey = "status/fleet.json" |
| + // The engine's bounds on status/boxes/, the same as status.LoadBoxes': |
| + // those objects are written by boxes, so neither their number nor |
| + // their size is trusted. |
| + engineBoxKeys = 200 |
| + engineBoxBodyBytes = 1 << 20 |
| + // engineListingHorizon drops heartbeat objects not written for a day |
| + // before any read, as status.LoadBoxes does: a replaced box's report |
| + // leaves the listing, and its incidents close as gone. |
| + engineListingHorizon = 24 * time.Hour |
| +) |
| + |
| +// engineRead is one cached object: the ETag it was read under and its body. |
| +type engineRead struct { |
| + etag string |
| + body []byte |
| +} |
| + |
| +// engineReads is the engine's ETag cache, kept across passes. |
| +type engineReads struct { |
| + cache map[string]engineRead |
| + // listedBoxes is every box with a status/boxes/ object at the last |
| + // boxes call, by label; unreadBoxes the ones among them whose object |
| + // could not be read or decoded. |
| + listedBoxes, unreadBoxes map[string]bool |
| + // fleetSeen is the last fleet.json decoded, reused while it is |
| + // unchanged. |
| + fleetSeen *status.Fleet |
| +} |
| + |
| +// get reads key, conditionally once it has been read before: an unchanged |
| +// object answers from the cache with changed false. A store without the |
| +// conditional read, or one whose conditional read fails other than with |
| +// not-found, is read plainly, as condGet does (provision/recordview.go). A |
| +// gone object leaves the cache and returns an os.ErrNotExist error. |
| +func (r *engineReads) get(ctx context.Context, store release.Store, key string) (body []byte, changed bool, err error) { |
| + prev, cached := r.cache[key] |
| + if g, ok := store.(release.ConditionalGetter); ok { |
| + b, etag, ch, err := g.GetIfChanged(ctx, key, prev.etag) |
| + switch { |
| + case err == nil && !ch && cached && prev.etag != "": |
| + return prev.body, false, nil |
| + case err == nil && ch: |
| + r.keep(key, etag, b) |
| + return b, true, nil |
| + case errors.Is(err, os.ErrNotExist): |
| + delete(r.cache, key) |
| + return nil, false, err |
| + } |
| + } |
| + b, etag, err := store.Get(ctx, key) |
| + if err != nil { |
| + if errors.Is(err, os.ErrNotExist) { |
| + delete(r.cache, key) |
| + } |
| + return nil, false, err |
| + } |
| + changed = !cached || etag == "" || etag != prev.etag |
| + r.keep(key, etag, b) |
| + return b, changed, nil |
| +} |
| + |
| +func (r *engineReads) keep(key, etag string, body []byte) { |
| + if r.cache == nil { |
| + r.cache = map[string]engineRead{} |
| + } |
| + r.cache[key] = engineRead{etag: etag, body: body} |
| +} |
| + |
| +// forget drops the cached objects under prefix that keys no longer lists. |
| +func (r *engineReads) forget(prefix string, keys []string) { |
| + for key := range r.cache { |
| + if strings.HasPrefix(key, prefix) && !slices.Contains(keys, key) { |
| + delete(r.cache, key) |
| + } |
| + } |
| +} |
| + |
| +// boxes lists status/boxes/ and reads each object, decoding as |
| +// status.LoadBoxes does: an object that cannot be read, is over the size |
| +// cap or does not parse is logged and skipped, and keys past the cap are |
| +// not read. Each box's Label is its key's, the name the engine keys its |
| +// heartbeat signals on. listedBoxes and unreadBoxes record what the listing |
| +// held and what of it could not be read. |
| +func (r *engineReads) boxes(ctx context.Context, store release.Store) ([]status.Box, error) { |
| + keys, err := engineBoxKeyList(ctx, store) |
| + if err != nil { |
| + return nil, err |
| + } |
| + r.forget(alertStatusBoxesPrefix, keys) |
| + r.listedBoxes, r.unreadBoxes = map[string]bool{}, map[string]bool{} |
| + var boxes []status.Box |
| + for i, key := range keys { |
| + label := strings.TrimSuffix(strings.TrimPrefix(key, alertStatusBoxesPrefix), ".json") |
| + if label == "" || !strings.HasSuffix(key, ".json") { |
| + continue |
| + } |
| + r.listedBoxes[label] = true |
| + if i >= engineBoxKeys { |
| + r.unreadBoxes[label] = true |
| + continue |
| + } |
| + body, _, err := r.get(ctx, store, key) |
| + if err != nil { |
| + log.Printf("console: alert engine: skipping %s: read failed: %v", key, err) |
| + r.unreadBoxes[label] = true |
| + continue |
| + } |
| + var b status.Box |
| + if len(body) > engineBoxBodyBytes { |
| + log.Printf("console: alert engine: skipping %s: body %d bytes exceeds %d", key, len(body), engineBoxBodyBytes) |
| + r.unreadBoxes[label] = true |
| + continue |
| + } |
| + if err := json.Unmarshal(body, &b); err != nil { |
| + log.Printf("console: alert engine: skipping %s: corrupt snapshot: %v", key, err) |
| + r.unreadBoxes[label] = true |
| + continue |
| + } |
| + b.Label = label |
| + boxes = append(boxes, b) |
| + } |
| + if len(keys) > engineBoxKeys { |
| + log.Printf("console: alert engine: %d keys under %s, reading the first %d", len(keys), alertStatusBoxesPrefix, engineBoxKeys) |
| + } |
| + return boxes, nil |
| +} |
| + |
| +// engineBoxKeyList is one listing of status/boxes/ without the objects the |
| +// horizon drops, as status.LoadBoxes lists it. A store that cannot say when |
| +// an object was written is listed whole. |
| +func engineBoxKeyList(ctx context.Context, store release.Store) ([]string, error) { |
| + ml, ok := store.(release.ModLister) |
| + if !ok { |
| + return store.List(ctx, alertStatusBoxesPrefix) |
| + } |
| + mods, err := ml.ListMod(ctx, alertStatusBoxesPrefix) |
| + if err != nil { |
| + return store.List(ctx, alertStatusBoxesPrefix) |
| + } |
| + cut := time.Now().Add(-engineListingHorizon) |
| + keys := make([]string, 0, len(mods)) |
| + for _, m := range mods { |
| + if m.Mod.IsZero() || !m.Mod.Before(cut) { |
| + keys = append(keys, m.Key) |
| + } |
| + } |
| + return keys, nil |
| +} |
| + |
| +// fleet reads status/fleet.json conditionally. No object is a fleet that |
| +// reports no services: nil, and no error. |
| +func (r *engineReads) fleet(ctx context.Context, store release.Store) (*status.Fleet, error) { |
| + body, changed, err := r.get(ctx, store, alertFleetKey) |
| + if errors.Is(err, os.ErrNotExist) { |
| + r.fleetSeen = nil |
| + return nil, nil |
| + } |
| + if err != nil { |
| + return nil, err |
| + } |
| + if !changed && r.fleetSeen != nil { |
| + return r.fleetSeen, nil |
| + } |
| + var f status.Fleet |
| + if err := json.Unmarshal(body, &f); err != nil { |
| + return nil, fmt.Errorf("unparsable %s: %w", alertFleetKey, err) |
| + } |
| + r.fleetSeen = &f |
| + return &f, nil |
| +} |
| + |
| +// ---- signals ----------------------------------------------------------------- |
| + |
| +// alertSignals is one pass's signals and what the pass read. |
| +type alertSignals struct { |
| + list []alertSignal |
| + has map[alertKey]bool |
| + // covered is each console rule a source reported this pass, with the |
| + // subjects whose state could not be read. |
| + covered map[string]map[string]bool |
| + // boxRules is whether alerts/boxes/ was listed this pass; boxUnknown |
| + // the boxes listed whose object could not be read or parsed. |
| + boxRules bool |
| + boxUnknown map[string]bool |
| + // firedAt is each firing box rule's FiredAt, for the dashboard. |
| + firedAt map[alertKey]time.Time |
| +} |
| + |
| +func newAlertSignals() *alertSignals { |
| + return &alertSignals{has: map[alertKey]bool{}, covered: map[string]map[string]bool{}, boxUnknown: map[string]bool{}, |
| + firedAt: map[alertKey]time.Time{}} |
| +} |
| + |
| +func (g *alertSignals) add(sg alertSignal) { |
| + g.list = append(g.list, sg) |
| + g.has[sg.Key] = true |
| +} |
| + |
| +// cover records that rule's source was read this pass, unknown naming the |
| +// subjects it could not read. |
| +func (g *alertSignals) cover(rule string, unknown map[string]bool) { |
| + g.covered[rule] = unknown |
| +} |
| + |
| +// value is the last value this pass reported for k. |
| +func (g *alertSignals) value(k alertKey) (float64, bool) { |
| + for i := len(g.list) - 1; i >= 0; i-- { |
| + if g.list[i].Key == k && !g.list[i].Gone { |
| + return g.list[i].Value, true |
| + } |
| + } |
| + return 0, false |
| +} |
| + |
| +// withGone is the pass's signals plus a Gone signal for every member of an |
| +// open fleet incident whose source was read this pass and did not report |
| +// it. A rule whose source was not read this pass (a heartbeat rule between |
| +// heartbeat passes) keeps its members as they are. |
| +func (g *alertSignals) withGone(open []alertIncident, now time.Time) []alertSignal { |
| + out := slices.Clone(g.list) |
| + for _, in := range open { |
| + if in.Scope != alertScopeFleet { |
| + continue |
| + } |
| + unknown, read := g.covered[in.Rule] |
| + if !alertConsoleRules[in.Rule] { |
| + unknown, read = g.boxUnknown, g.boxRules |
| + } |
| + if !read { |
| + continue |
| + } |
| + for _, m := range in.Members { |
| + k := alertKey{in.Scope, in.Rule, m} |
| + if g.has[k] || unknown[m] { |
| + continue |
| + } |
| + out = append(out, alertSignal{Key: k, Level: in.Level, At: now, Gone: true}) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// boxAlerts is what one listing of alerts/boxes/ read: each readable box's |
| +// state by box name, and the boxes listed whose object could not be read or |
| +// parsed. |
| +type boxAlerts struct { |
| + states map[string]metrics.AlertState |
| + unread map[string]bool |
| +} |
| + |
| +// boxAlertSignals lists alerts/boxes/ and reads every object through the |
| +// cache, adding a signal for each rule each box reports. Only the listing |
| +// failing is an error; one box's trouble is logged, fails the run |
| +// (jobFailed) and leaves that box's members as they are. |
| +func (s *Server) boxAlertSignals(ctx context.Context, sig *alertSignals) (boxAlerts, error) { |
| + r := &s.alertEngine.reads |
| + keys, err := s.cfg.Releases.List(ctx, alertPrefix) |
| + if err != nil { |
| + return boxAlerts{}, fmt.Errorf("list %s: %w", alertPrefix, err) |
| + } |
| + r.forget(alertPrefix, keys) |
| + got := boxAlerts{states: map[string]metrics.AlertState{}, unread: map[string]bool{}} |
| + for _, key := range keys { |
| + if !strings.HasSuffix(key, ".json") { |
| + continue |
| + } |
| + name := strings.TrimSuffix(strings.TrimPrefix(key, alertPrefix), ".json") |
| + body, _, err := r.get(ctx, s.cfg.Releases, key) |
| + if err != nil { |
| + log.Printf("console: alert engine: read %s: %v", key, err) |
| + jobFailed(ctx, fmt.Errorf("read %s: %w", key, err)) |
| + got.unread[name] = true |
| + continue |
| + } |
| + var st metrics.AlertState |
| + if err := json.Unmarshal(body, &st); err != nil { |
| + log.Printf("console: alert engine: unparsable %s: %v", key, err) |
| + jobFailed(ctx, fmt.Errorf("unparsable %s: %w", key, err)) |
| + got.unread[name] = true |
| + continue |
| + } |
| + box := st.Box |
| + if box == "" { |
| + // Trust the key over an empty body field: the key is what the |
| + // publisher's own AlertKey produced. |
| + box = name |
| + } |
| + got.states[box] = st |
| + for rule, rs := range st.Rules { |
| + k := alertKey{alertScopeFleet, rule, box} |
| + at := rs.FiredAt |
| + if at.IsZero() { |
| + at = st.UpdatedAt |
| + } else if rs.Firing { |
| + sig.firedAt[k] = rs.FiredAt |
| + } |
| + sig.add(alertSignal{Key: k, Level: alertRuleLevel(rule), Firing: rs.Firing, Value: rs.Value, At: at}) |
| + } |
| + } |
| + sig.boxRules, sig.boxUnknown = true, got.unread |
| + return got, nil |
| +} |
| + |
| +// heartbeatSignals reads the heartbeats and fleet.json, on every 5th pass, |
| +// and adds box_silent, alert_delivery_broken, cert_expiring and |
| +// service_down. A source whose read fails is logged, fails the run and adds |
| +// nothing. |
| +func (s *Server) heartbeatSignals(ctx context.Context, settings map[string]alertRuleSetting, now time.Time, sig *alertSignals) { |
| + r := &s.alertEngine.reads |
| + if boxes, err := r.boxes(ctx, s.cfg.Releases); err != nil { |
| + log.Printf("console: alert engine: list %s: %v", alertStatusBoxesPrefix, err) |
| + jobFailed(ctx, fmt.Errorf("list %s: %w", alertStatusBoxesPrefix, err)) |
| + } else { |
| + heartbeatBoxSignals(boxes, r.unreadBoxes, settings, now, sig) |
| + } |
| + if f, err := r.fleet(ctx, s.cfg.Releases); err != nil { |
| + log.Printf("console: alert engine: read %s: %v", alertFleetKey, err) |
| + jobFailed(ctx, fmt.Errorf("read %s: %w", alertFleetKey, err)) |
| + } else { |
| + serviceSignals(f, now, sig) |
| + } |
| +} |
| + |
| +// heartbeatBoxSignals adds, for each box with a heartbeat object, box_silent |
| +// (Review Focus 3: every box with an object is a member, whether or not it |
| +// ever fired anything) and alert_delivery_broken, and cert_expiring for |
| +// every host the fresh boxes serve. Certificates are judged only when every |
| +// heartbeat was read, so a host on a box whose read failed is not taken |
| +// for gone. |
| +func heartbeatBoxSignals(boxes []status.Box, unread map[string]bool, settings map[string]alertRuleSetting, now time.Time, sig *alertSignals) { |
| + silentAfter := time.Duration(alertThreshold(settings, "box_silent")) * time.Minute |
| + for _, b := range boxes { |
| + age := now.Sub(b.GeneratedAt) |
| + sig.add(alertSignal{Key: alertKey{alertScopeFleet, "box_silent", b.Label}, Level: alertRuleLevel("box_silent"), |
| + Firing: age > silentAfter, Value: age.Minutes(), At: b.GeneratedAt}) |
| + var delivery *status.AlertDelivery |
| + if b.Metrics != nil { |
| + delivery = b.Metrics.Alerts |
| + } |
| + sig.add(alertSignal{Key: alertKey{alertScopeFleet, "alert_delivery_broken", b.Label}, |
| + Level: alertRuleLevel("alert_delivery_broken"), Firing: delivery.NotDelivered(), At: now}) |
| + } |
| + sig.cover("box_silent", unread) |
| + sig.cover("alert_delivery_broken", unread) |
| + if len(unread) > 0 { |
| + return |
| + } |
| + within := time.Duration(alertThreshold(settings, "cert_expiring")*24) * time.Hour |
| + for host, reading := range aliasReadingsFrom(boxes, now) { |
| + if reading.CertExpiresAt == 0 { |
| + continue // not stamped: nothing to judge |
| + } |
| + left := time.Unix(reading.CertExpiresAt, 0).Sub(now) |
| + sig.add(alertSignal{Key: alertKey{alertScopeFleet, "cert_expiring", host}, Level: alertRuleLevel("cert_expiring"), |
| + Firing: left <= within, Value: left.Hours() / 24, At: now}) |
| + } |
| + sig.cover("cert_expiring", nil) |
| +} |
| + |
| +// serviceSignals adds service_down for every service fleet.json lists. A |
| +// nil fleet lists none. |
| +func serviceSignals(f *status.Fleet, now time.Time, sig *alertSignals) { |
| + if f != nil { |
| + for _, svc := range f.Services { |
| + sig.add(alertSignal{Key: alertKey{alertScopeFleet, "service_down", svc.Name}, Level: alertRuleLevel("service_down"), |
| + Firing: !svc.Up, At: now}) |
| + } |
| + } |
| + sig.cover("service_down", nil) |
| +} |
| + |
| +// ---- rules ------------------------------------------------------------------- |
| + |
| +const alertScopeFleet = "fleet" |
| + |
| +// alertRuleLevels is each fleet rule's level (fleet alerts spec §7.1). Box |
| +// rules come from alerts/boxes/<box>.json, keyed (fleet, rule, box). |
| +var alertRuleLevels = map[string]string{ |
| + "disk_eta": alerting.LevelWarning, |
| + "disk": alerting.LevelIncident, |
| + "mem": alerting.LevelWarning, |
| + "cpu": alerting.LevelWarning, |
| + "lag": alerting.LevelWarning, |
| + "geoip": alerting.LevelWarning, |
| + "engine_silent": alerting.LevelIncident, |
| + "box_silent": alerting.LevelIncident, |
| + "service_down": alerting.LevelIncident, |
| + "cert_expiring": alerting.LevelWarning, |
| + "alert_delivery_broken": alerting.LevelWarning, |
| + "seal_key": alerting.LevelIncident, |
| +} |
| + |
| +// alertConsoleRules are the rules the console evaluates. Every other fleet |
| +// rule is a box rule, read from the box's alert object. |
| +var alertConsoleRules = map[string]bool{ |
| + "box_silent": true, "service_down": true, "cert_expiring": true, "alert_delivery_broken": true, "seal_key": true, |
| +} |
| + |
| +// alertRuleLevel is rule's level; a rule this console has not been taught |
| +// is a warning. |
| +func alertRuleLevel(rule string) string { |
| + if l, ok := alertRuleLevels[rule]; ok { |
| + return l |
| + } |
| + return alerting.LevelWarning |
| +} |
| + |
| +// alertThresholdDefaults are the editable console thresholds: box_silent in |
| +// minutes, cert_expiring in days (spec §5.2, §7.1). |
| +var alertThresholdDefaults = map[string]float64{"box_silent": 15, "cert_expiring": 14} |
| + |
| +// alertThreshold is rule's threshold in scope fleet: the alert_rules row's |
| +// when one is set, else the default. |
| +func alertThreshold(settings map[string]alertRuleSetting, rule string) float64 { |
| + if st, ok := settings[rule]; ok && st.Threshold != nil { |
| + return *st.Threshold |
| + } |
| + return alertThresholdDefaults[rule] |
| +} |
diff --git a/internal/console/alertstore.go b/internal/console/alertstore.go| index 7108191dc..f4e70fe8e 100644 |
| --- a/internal/console/alertstore.go |
| +++ b/internal/console/alertstore.go |
| @@ -6,6 +6,7 @@ import ( |
| "errors" |
| "fmt" |
| "slices" |
| + "strings" |
| "time" |
| ) |
| @@ -457,6 +458,81 @@ func (s *Store) AlertCutover(f func(tx *sql.Tx) error) (ran bool, err error) { |
| return true, nil |
| } |
| +// insertAlertIncidentTx inserts the new incident in (ID 0) inside tx and |
| +// returns its id, for a caller that queues its rows in the same tx. |
| +func insertAlertIncidentTx(tx *sql.Tx, in alertIncident) (int64, error) { |
| + if in.ID != 0 { |
| + return 0, fmt.Errorf("alert incident %d: already stored", in.ID) |
| + } |
| + if err := writeAlertIncident(tx, in); err != nil { |
| + return 0, err |
| + } |
| + var id int64 |
| + err := tx.QueryRow(`SELECT last_insert_rowid()`).Scan(&id) |
| + return id, err |
| +} |
| + |
| +// alertSeenFiring is the watcher's delivery history the cutover imports: |
| +// for each (box, rule), the addresses alert_seen says were last told it is |
| +// firing. Only box alert rows: the claim-SQL receipt rows, geoip's per |
| +// reason rows and the no-mailbox stand-in are not box alerts anyone was told. |
| +func alertSeenFiring(tx *sql.Tx) (map[[2]string][]string, error) { |
| + rows, err := tx.Query(`SELECT box, rule, address FROM alert_seen WHERE firing != 0 ORDER BY box, rule, address`) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + out := map[[2]string][]string{} |
| + for rows.Next() { |
| + var box, rule, addr string |
| + if err := rows.Scan(&box, &rule, &addr); err != nil { |
| + return nil, err |
| + } |
| + if box == sqlReceiptAlertBox || addr == noMailboxAddress || strings.Contains(rule, "@") { |
| + continue |
| + } |
| + k := [2]string{box, rule} |
| + out[k] = append(out[k], addr) |
| + } |
| + return out, rows.Err() |
| +} |
| + |
| +// seedOperatorAlertConnectors gives each operator in ops a personal email |
| +// connector in scope fleet for their sign-in address, already confirmed |
| +// (spec §5.2: signing in proved they own it), inside tx. One that already |
| +// has one keeps it: the (scope, owner_address) index makes this idempotent. |
| +// The result is each operator's connector id. |
| +func seedOperatorAlertConnectors(tx *sql.Tx, ops []string, now time.Time) (map[string]int64, error) { |
| + out := map[string]int64{} |
| + for _, addr := range ops { |
| + if _, err := tx.Exec(`INSERT OR IGNORE INTO alert_connectors (scope, kind, name, target_plain, target_hint, owner_address, |
| + confirmed_at, created_by, created_at) VALUES (?, ?, '', ?, ?, ?, ?, ?, ?)`, |
| + alertScopeFleet, alertConnectorEmail, addr, addr, addr, now.Unix(), addr, now.Unix()); err != nil { |
| + return nil, err |
| + } |
| + var id int64 |
| + if err := tx.QueryRow(`SELECT id FROM alert_connectors WHERE scope = ? AND owner_address = ?`, alertScopeFleet, addr).Scan(&id); err != nil { |
| + return nil, err |
| + } |
| + out[addr] = id |
| + } |
| + return out, nil |
| +} |
| + |
| +// SeedOperatorAlertConnectors is seedOperatorAlertConnectors in a |
| +// transaction of its own, for a start after the cutover has run. |
| +func (s *Store) SeedOperatorAlertConnectors(ops []string, now time.Time) error { |
| + tx, err := s.db.Begin() |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + if _, err := seedOperatorAlertConnectors(tx, ops, now); err != nil { |
| + return err |
| + } |
| + return tx.Commit() |
| +} |
| + |
| // ---- the outbox -------------------------------------------------------------- |
| // DueOutbox is up to limit unsent rows due at now, earliest first. |
diff --git a/internal/console/alertwatch.go b/internal/console/alertwatch.go| index 48c20402b..be7733704 100644 |
| --- a/internal/console/alertwatch.go |
| +++ b/internal/console/alertwatch.go |
| @@ -2,10 +2,15 @@ package console |
| import ( |
| "context" |
| + "database/sql" |
| "encoding/json" |
| + "errors" |
| "fmt" |
| "log" |
| - "sort" |
| + "maps" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| "strconv" |
| "strings" |
| "time" |
| @@ -13,44 +18,81 @@ import ( |
| "github.com/carlosframework/platform/internal/metrics" |
| ) |
| -// The keymail half of alert delivery lives here rather than on the box, |
| -// because the only keymail send path that exists is the console's per-user |
| -// OAuth grant (Keymail.SendApp) and the agent has no keymail identity. The |
| -// box judges itself and publishes alerts/boxes/<box>.json; this watcher |
| -// polls that prefix, diffs each rule's firing state against what it last |
| -// told each operator (the alert_seen table), and mails the difference — |
| -// each operator with that operator's OWN grant token, so nobody is sent |
| -// mail on a credential they did not personally issue. |
| +// 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 diff is per RECIPIENT, not per rule, because delivery fails per |
| -// recipient: a success records that operator's row and a failure leaves |
| -// only theirs unrecorded, so the next pass retries exactly the operator |
| -// who missed out. One operator's revoked grant can no longer re-page every |
| -// healthy operator on the fleet, tick after tick. |
| +// 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. |
| // |
| -// The failure posture throughout is "never go silent": an unreadable or |
| -// unparsable alert object is logged and skipped, an undelivered transition |
| -// stays pending for that operator until it lands, and no path here can |
| -// panic a console that is otherwise serving fine. |
| +// 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. |
| -// alertWatchInterval is the poll cadence from the spec: a minute is fast |
| -// enough for a disk filling up and slow enough to be free. |
| -const alertWatchInterval = time.Minute |
| +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/" |
| -// StartAlertWatcher runs alertPass immediately and then every minute until |
| -// ctx is done. Started from cmd/console's serve(), deliberately NOT from |
| -// NewServer: tests construct servers by the dozen and none of them should |
| -// grow a background goroutine or a keymail send. |
| -func (s *Server) StartAlertWatcher(ctx context.Context) { |
| - t := time.NewTicker(alertWatchInterval) |
| +// 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 { |
| - if err := s.jobs.Run(ctx, "StartAlertWatcher", s.alertPass); err != nil { |
| - log.Printf("console: alert watch: %v", err) |
| + 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(): |
| @@ -60,6 +102,485 @@ func (s *Server) StartAlertWatcher(ctx context.Context) { |
| } |
| } |
| +// 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 { |
| @@ -94,74 +615,6 @@ func (r *alertRun) noteMissing() { |
| // grant later is not caught up on it (see alertSeenFor). |
| const noMailboxAddress = "" |
| -// alertPass reads every alerts/boxes/*.json and, for each rule, diffs its |
| -// firing state against what alert_seen says each operator was last told, |
| -// mailing and recording per recipient. It returns an error only for a failure |
| -// that makes the whole pass meaningless (listing the bucket, or reading the |
| -// operator list); per-box and per-rule trouble is logged and stepped over. |
| -// |
| -// It also rebuilds s.alertsNow from the objects it reads, whoever the |
| -// recipients are: a box it read is replaced, a box it could not read keeps |
| -// its last entries, a box no longer listed drops out. A failed listing |
| -// leaves the projection as it was. |
| -func (s *Server) alertPass(ctx context.Context) error { |
| - if s.cfg.Releases == nil || s.sendApp == nil { |
| - return nil |
| - } |
| - keys, err := s.cfg.Releases.List(ctx, alertPrefix) |
| - if err != nil { |
| - return fmt.Errorf("list %s: %w", alertPrefix, err) |
| - } |
| - if len(keys) == 0 { |
| - s.alertsNow.keepOnly(nil) |
| - s.alertsNow.markKnown() |
| - return nil // no box has ever published an alert: nothing to do |
| - } |
| - run, err := s.alertRecipients() |
| - if err != nil { |
| - return err |
| - } |
| - now := time.Now() |
| - listed := map[string]bool{} |
| - for _, key := range keys { |
| - if !strings.HasSuffix(key, ".json") { |
| - continue |
| - } |
| - listed[strings.TrimSuffix(strings.TrimPrefix(key, alertPrefix), ".json")] = true |
| - body, _, err := s.cfg.Releases.Get(ctx, key) |
| - if err != nil { |
| - log.Printf("console: alert watch: read %s: %v", key, err) |
| - jobFailed(ctx, fmt.Errorf("read %s: %w", key, err)) |
| - continue |
| - } |
| - var st metrics.AlertState |
| - if err := json.Unmarshal(body, &st); err != nil { |
| - log.Printf("console: alert watch: unparsable %s: %v", key, err) |
| - jobFailed(ctx, fmt.Errorf("unparsable %s: %w", key, err)) |
| - continue |
| - } |
| - box := st.Box |
| - if box == "" { |
| - // Trust the key over an empty body field: the key is what the |
| - // publisher's own AlertKey produced. |
| - box = strings.TrimSuffix(strings.TrimPrefix(key, alertPrefix), ".json") |
| - } |
| - listed[box] = true |
| - s.alertsNow.setBox(box, st.Rules, now) |
| - names := make([]string, 0, len(st.Rules)) |
| - for name := range st.Rules { |
| - names = append(names, name) |
| - } |
| - sort.Strings(names) |
| - for _, name := range names { |
| - s.alertRule(ctx, run, box, name, st.Rules[name], st.UpdatedAt) |
| - } |
| - } |
| - s.alertsNow.keepOnly(listed) |
| - s.alertsNow.markKnown() |
| - return nil |
| -} |
| - |
| // alertRecipients resolves the operator list into recipients, splitting off |
| // the operators the console cannot write as. |
| func (s *Server) alertRecipients() (*alertRun, error) { |
| @@ -197,77 +650,6 @@ func (s *Server) grantRecipients(addrs []string) (*alertRun, error) { |
| return run, nil |
| } |
| -// alertRule handles one rule of one box: every mailable operator whose |
| -// recorded state differs from the published one gets a keymail, and each |
| -// send is recorded on its own. |
| -func (s *Server) alertRule(ctx context.Context, run *alertRun, box, rule string, rs metrics.RuleState, updated time.Time) { |
| - if len(run.to) == 0 { |
| - // Nobody the console can write as. Record the transition against the |
| - // synthetic recipient so it stops replaying, and say so out loud — |
| - // this is the one path where an alert is genuinely dropped. |
| - if s.alertDueFor(ctx, box, rule, noMailboxAddress, rs) { |
| - run.noteMissing() |
| - log.Printf("console: alert watch: %s/%s transition dropped — no operator holds a keymail grant", box, rule) |
| - s.recordAlertSeenFor(ctx, box, rule, noMailboxAddress, rs) |
| - } |
| - return |
| - } |
| - var due []operatorGrant |
| - for _, op := range run.to { |
| - if s.alertDueFor(ctx, box, rule, op.address, rs) { |
| - due = append(due, op) |
| - } |
| - } |
| - if len(due) == 0 { |
| - return |
| - } |
| - run.noteMissing() |
| - subject, body := alertMessage(box, rule, rs, updated) |
| - for _, op := range due { |
| - if _, err := s.sendApp(ctx, op.token, op.address, subject, body); err != nil { |
| - // The address is safe to log; the token never is. Leaving this |
| - // operator's row unrecorded is the retry: the next pass mails |
| - // them and nobody else. |
| - log.Printf("console: alert watch: keymail %s/%s to %s: %v", box, rule, op.address, err) |
| - jobFailed(ctx, fmt.Errorf("keymail %s/%s to %s: %w", box, rule, op.address, err)) |
| - continue |
| - } |
| - s.recordAlertSeenFor(ctx, box, rule, op.address, rs) |
| - } |
| -} |
| - |
| -// geoipReasonRule is the dedup key for one geoip reason (geoip spec |
| -// §10.4). The geoip rule's VALUE is a reason code, and a reason that |
| -// changes while firing (expiring becomes expired) is news the operator |
| -// must get, though firing never went false (code review R4-3). The plain |
| -// "geoip" row still carries firing/cleared; one extra row per reason marks |
| -// which reasons this address has been told about. |
| -func geoipReasonRule(code float64) string { return fmt.Sprintf("geoip@%d", int(code)) } |
| - |
| -// alertDueFor is alertDue plus the geoip reason rule. |
| -func (s *Server) alertDueFor(ctx context.Context, box, rule, address string, rs metrics.RuleState) bool { |
| - due := s.alertDue(ctx, box, rule, address, rs.Firing) |
| - if rule == "geoip" && rs.Firing && !due { |
| - due = s.alertDue(ctx, box, geoipReasonRule(rs.Value), address, true) |
| - } |
| - return due |
| -} |
| - |
| -// recordAlertSeenFor records the transition and, for geoip, which reason |
| -// this address was LAST told about: exactly one reason row is true while |
| -// firing and none after a clear, so a reason seen before (2, 3, back to 2, |
| -// or a later episode) is news again (code review R5 on R4-3). ctx is the |
| -// pass's, so a failed record also fails the alert job's run (jobFailed). |
| -func (s *Server) recordAlertSeenFor(ctx context.Context, box, rule, address string, rs metrics.RuleState) { |
| - s.recordAlertSeen(ctx, box, rule, address, rs.Firing) |
| - if rule != "geoip" { |
| - return |
| - } |
| - for code := 1; code <= 5; code++ { |
| - s.recordAlertSeen(ctx, box, geoipReasonRule(float64(code)), address, rs.Firing && int(rs.Value) == code) |
| - } |
| -} |
| - |
| // alertDue reports whether address must be told that (box, rule) is now in |
| // this firing state, recording a quiet first sighting as it goes — nobody |
| // wants mail saying the disk is fine. |
| @@ -312,7 +694,9 @@ func (s *Server) recordAlertSeen(ctx context.Context, box, rule, address string, |
| // 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) — so a single |
| +// 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. |
| @@ -329,6 +713,12 @@ func alertValueText(rule string, value float64) string { |
| 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) |
| } |
diff --git a/internal/console/alertwatch_test.go b/internal/console/alertwatch_test.go| index 9fd983d42..274d77a5c 100644 |
| --- a/internal/console/alertwatch_test.go |
| +++ b/internal/console/alertwatch_test.go |
| @@ -2,15 +2,16 @@ package console |
| import ( |
| "context" |
| - "encoding/json" |
| - "strings" |
| "testing" |
| - "time" |
| - "github.com/carlosframework/platform/internal/metrics" |
| "github.com/carlosframework/platform/internal/release" |
| ) |
| +// The alert watcher's pass is gone (the alert engine replaced it, Task 8 of |
| +// the fleet alerts plan); its behaviours are pinned in |
| +// alertengine_pass_test.go. What stays here is the capture the per-operator |
| +// keymail notices (storenotify.go, claim_runtime.go) are tested with. |
| + |
| // sentMail is one captured sendApp call. The token is captured so a test can |
| // assert each operator is mailed with THEIR OWN grant, never a shared one. |
| type sentMail struct { |
| @@ -43,310 +44,12 @@ func newCapturedFixture(t *testing.T) *alertFixture { |
| return af |
| } |
| -// newAlertFixture is the common shape: two operators, only one of whom ever |
| -// granted the console send access. |
| -func newAlertFixture(t *testing.T) *alertFixture { |
| - t.Helper() |
| - af := newCapturedFixture(t) |
| - for _, addr := range []string{"ops-a@keymail.dev", "ops-b@keymail.dev"} { |
| - if err := af.st.SetOperator(addr, true); err != nil { |
| - t.Fatal(err) |
| - } |
| - } |
| - if err := af.st.SetGrantToken("ops-a@keymail.dev", "grant-a", time.Now()); err != nil { |
| - t.Fatal(err) |
| - } |
| - return af |
| -} |
| - |
| -func (af *alertFixture) writeAlert(t *testing.T, st metrics.AlertState) { |
| - t.Helper() |
| - b, err := json.Marshal(st) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - // Publishing is a CAS write (create-only on ""), so re-publishing a box's |
| - // state — which is what a fire→clear transition is — needs the etag. |
| - key := metrics.AlertKey(st.Box) |
| - etag := "" |
| - if _, cur, err := af.rel.Get(context.Background(), key); err == nil { |
| - etag = cur |
| - } |
| - if _, err := af.rel.Put(context.Background(), key, b, etag); err != nil { |
| - t.Fatal(err) |
| - } |
| -} |
| - |
| -func (af *alertFixture) pass(t *testing.T) { |
| - t.Helper() |
| - af.sent = nil |
| - if err := af.srv.alertPass(context.Background()); err != nil { |
| - t.Fatal(err) |
| - } |
| -} |
| - |
| -func firingDisk(firing bool) metrics.AlertState { |
| - rs := metrics.RuleState{Firing: firing, Value: 0.95} |
| - if firing { |
| - rs.FiredAt = time.Date(2026, 8, 2, 10, 0, 0, 0, time.UTC) |
| - rs.Since = rs.FiredAt |
| - } else { |
| - rs.Value = 0.80 |
| - } |
| - return metrics.AlertState{ |
| - V: 1, |
| - Box: "box-a", |
| - UpdatedAt: time.Date(2026, 8, 2, 10, 5, 0, 0, time.UTC), |
| - Rules: map[string]metrics.RuleState{"disk": rs}, |
| - } |
| -} |
| - |
| -// TestAlertPassFiresOnceThenGoesQuiet is the spec's core promise: a keymail |
| -// on the TRANSITION, to the operators who hold a grant, and silence while |
| -// the alert stays in the state the console already reported. |
| -func TestAlertPassFiresOnceThenGoesQuiet(t *testing.T) { |
| - af := newAlertFixture(t) |
| - af.writeAlert(t, firingDisk(true)) |
| - |
| - af.pass(t) |
| - if len(af.sent) != 1 { |
| - t.Fatalf("first pass sent %d keymails, want 1: %+v", len(af.sent), af.sent) |
| - } |
| - got := af.sent[0] |
| - if got.to != "ops-a@keymail.dev" || got.token != "grant-a" { |
| - t.Fatalf("sent to %q with token %q, want ops-a@keymail.dev/grant-a", got.to, got.token) |
| - } |
| - if got.subject != "[carlos] box-a: disk alert" { |
| - t.Fatalf("subject = %q", got.subject) |
| - } |
| - // "95%", not "0.95": the mail carries the rule's own unit, the same as |
| - // the operator dashboard's alerts table (see alertValueText). |
| - for _, want := range []string{"disk", "box-a", "95%", "2026-08-02T10:00:00Z"} { |
| - if !strings.Contains(got.body, want) { |
| - t.Fatalf("body is missing %q:\n%s", want, got.body) |
| - } |
| - } |
| - if strings.Contains(got.body, "grant-a") { |
| - t.Fatal("body leaked the grant token") |
| - } |
| - |
| - // Recorded: the same state on the next pass says nothing. |
| - firing, known, err := af.st.AlertSeen("box-a", "disk", "ops-a@keymail.dev") |
| - if err != nil || !known || !firing { |
| - t.Fatalf("AlertSeen = %v,%v,%v — want true,true,nil", firing, known, err) |
| - } |
| - af.pass(t) |
| - if len(af.sent) != 0 { |
| - t.Fatalf("second pass sent %d keymails, want 0: %+v", len(af.sent), af.sent) |
| - } |
| -} |
| - |
| -// TestAlertPassClears covers the other half of the transition: the alert |
| -// going away is news too. |
| -func TestAlertPassClears(t *testing.T) { |
| - af := newAlertFixture(t) |
| - af.writeAlert(t, firingDisk(true)) |
| - af.pass(t) |
| - |
| - af.writeAlert(t, firingDisk(false)) |
| - af.pass(t) |
| - if len(af.sent) != 1 { |
| - t.Fatalf("clear pass sent %d keymails, want 1: %+v", len(af.sent), af.sent) |
| - } |
| - if af.sent[0].subject != "[carlos] box-a: disk cleared" { |
| - t.Fatalf("subject = %q", af.sent[0].subject) |
| - } |
| - af.pass(t) |
| - if len(af.sent) != 0 { |
| - t.Fatalf("pass after clear sent %d keymails, want 0", len(af.sent)) |
| - } |
| -} |
| - |
| -// TestAlertPassRetriesAfterSendFailure: a failed send leaves the transition |
| -// unrecorded, so the next tick delivers it. A missed page is worse than a |
| -// duplicate one. |
| -func TestAlertPassRetriesAfterSendFailure(t *testing.T) { |
| - af := newAlertFixture(t) |
| - af.writeAlert(t, firingDisk(true)) |
| - af.err = context.DeadlineExceeded |
| - |
| - af.pass(t) |
| - if len(af.sent) != 1 { |
| - t.Fatalf("failing pass attempted %d sends, want 1", len(af.sent)) |
| - } |
| - if _, known, err := af.st.AlertSeen("box-a", "disk", "ops-a@keymail.dev"); err != nil || known { |
| - t.Fatalf("AlertSeen recorded despite a send failure (known=%v, err=%v)", known, err) |
| - } |
| - |
| - af.err = nil |
| - af.pass(t) |
| - if len(af.sent) != 1 { |
| - t.Fatalf("retry pass sent %d keymails, want 1", len(af.sent)) |
| - } |
| - if firing, known, err := af.st.AlertSeen("box-a", "disk", "ops-a@keymail.dev"); err != nil || !known || !firing { |
| - t.Fatalf("AlertSeen = %v,%v,%v after a successful retry", firing, known, err) |
| - } |
| -} |
| - |
| -// TestAlertPassRetriesOnlyTheFailedOperator is why alert_seen is keyed per |
| -// recipient: one operator's dead grant must not re-page every healthy |
| -// operator on the fleet, tick after tick. |
| -func TestAlertPassRetriesOnlyTheFailedOperator(t *testing.T) { |
| - af := newAlertFixture(t) |
| - if err := af.st.SetGrantToken("ops-b@keymail.dev", "grant-b", time.Now()); err != nil { |
| - t.Fatal(err) |
| - } |
| - af.writeAlert(t, firingDisk(true)) |
| - af.err = context.DeadlineExceeded |
| - af.failFor = "ops-b@keymail.dev" |
| - |
| - af.pass(t) |
| - if len(af.sent) != 2 { |
| - t.Fatalf("first pass attempted %d sends, want 2: %+v", len(af.sent), af.sent) |
| - } |
| - if firing, known, err := af.st.AlertSeen("box-a", "disk", "ops-a@keymail.dev"); err != nil || !known || !firing { |
| - t.Fatalf("ops-a AlertSeen = %v %v %v — a healthy delivery was not recorded", firing, known, err) |
| - } |
| - if _, known, err := af.st.AlertSeen("box-a", "disk", "ops-b@keymail.dev"); err != nil || known { |
| - t.Fatalf("ops-b AlertSeen recorded despite a failed send (known=%v, err=%v)", known, err) |
| - } |
| - |
| - af.err = nil |
| - af.pass(t) |
| - if len(af.sent) != 1 || af.sent[0].to != "ops-b@keymail.dev" { |
| - t.Fatalf("retry pass sent %+v, want exactly one mail to ops-b", af.sent) |
| - } |
| - if af.sent[0].token != "grant-b" { |
| - t.Fatalf("retry used token %q, want ops-b's own grant", af.sent[0].token) |
| - } |
| - af.pass(t) |
| - if len(af.sent) != 0 { |
| - t.Fatalf("pass after the retry sent %d keymails, want 0", len(af.sent)) |
| - } |
| -} |
| - |
| -// TestAlertPassNoMailableOperator pins the one path where an alert is |
| -// genuinely dropped: nobody holds a grant, so there is nothing to send and |
| -// the transition is recorded against the synthetic recipient so it does not |
| -// replay every minute forever. The honest cost — documented, and asserted |
| -// here rather than left to be discovered — is that an operator who gains a |
| -// grant afterwards is never told about that transition. |
| -func TestAlertPassNoMailableOperator(t *testing.T) { |
| - af := newCapturedFixture(t) |
| - if err := af.st.SetOperator("ops-b@keymail.dev", true); err != nil { |
| - t.Fatal(err) |
| - } |
| - af.writeAlert(t, firingDisk(true)) |
| - |
| - af.pass(t) |
| - if len(af.sent) != 0 { |
| - t.Fatalf("sent %d keymails with no grant anywhere: %+v", len(af.sent), af.sent) |
| - } |
| - if firing, known, err := af.st.AlertSeen("box-a", "disk", ""); err != nil || !known || !firing { |
| - t.Fatalf("synthetic AlertSeen = %v %v %v, want true true nil — the drop was not recorded", firing, known, err) |
| - } |
| - |
| - // The grant arrives after the fact. The alert is still firing, but the |
| - // console has already recorded the transition as handled: no catch-up. |
| - if err := af.st.SetGrantToken("ops-b@keymail.dev", "grant-b", time.Now()); err != nil { |
| - t.Fatal(err) |
| - } |
| - af.pass(t) |
| - if len(af.sent) != 0 { |
| - t.Fatalf("a newly-granted operator was retroactively paged: %+v", af.sent) |
| - } |
| - // But the NEXT transition reaches them normally. |
| - af.writeAlert(t, firingDisk(false)) |
| - af.pass(t) |
| - if len(af.sent) != 1 || af.sent[0].to != "ops-b@keymail.dev" { |
| - t.Fatalf("clear after the grant arrived sent %+v, want one mail to ops-b", af.sent) |
| - } |
| -} |
| - |
| -// TestAlertPassQuietFirstSighting: a rule the console has never seen that is |
| -// NOT firing is recorded silently. Nobody wants a keymail saying the disk is |
| -// fine. |
| -func TestAlertPassQuietFirstSighting(t *testing.T) { |
| - af := newAlertFixture(t) |
| - af.writeAlert(t, firingDisk(false)) |
| - |
| - af.pass(t) |
| - if len(af.sent) != 0 { |
| - t.Fatalf("quiet first sighting sent %d keymails, want 0: %+v", len(af.sent), af.sent) |
| - } |
| - if firing, known, err := af.st.AlertSeen("box-a", "disk", "ops-a@keymail.dev"); err != nil || !known || firing { |
| - t.Fatalf("AlertSeen = %v,%v,%v — want false,true,nil", firing, known, err) |
| - } |
| -} |
| - |
| -// TestAlertPassSurvivesJunk: an unparsable object under alerts/ is skipped, |
| -// and the boxes either side of it are still processed. A watcher that dies |
| -// on one bad file is a watcher that stops paging. |
| -func TestAlertPassSurvivesJunk(t *testing.T) { |
| - af := newAlertFixture(t) |
| - if _, err := af.rel.Put(context.Background(), "alerts/boxes/box-junk.json", []byte("{not json"), ""); err != nil { |
| - t.Fatal(err) |
| - } |
| - af.writeAlert(t, firingDisk(true)) |
| - |
| - af.pass(t) |
| - if len(af.sent) != 1 { |
| - t.Fatalf("pass sent %d keymails, want 1: %+v", len(af.sent), af.sent) |
| - } |
| -} |
| - |
| -// TestAlertPassEmptyBucket: no alerts/ prefix at all is a no-op, not an |
| -// error — a fleet that has never published an alert is the normal case. |
| -func TestAlertPassEmptyBucket(t *testing.T) { |
| - fx := newConsoleFixture(t) |
| - fx.srv.sendApp = func(context.Context, string, string, string, string) (string, error) { |
| - t.Fatal("sent a keymail with no alerts published") |
| - return "", nil |
| - } |
| - if err := fx.srv.alertPass(context.Background()); err != nil { |
| - t.Fatal(err) |
| - } |
| -} |
| - |
| // TestNewServerDefaultsSendApp: production wiring goes through the console's |
| // own keymail client; nothing else in NewServer starts a goroutine. |
| func TestNewServerDefaultsSendApp(t *testing.T) { |
| fx := newConsoleFixture(t) |
| if fx.srv.sendApp == nil { |
| - t.Fatal("NewServer left sendApp nil — the watcher would never deliver") |
| + t.Fatal("NewServer left sendApp nil — operator notices would never deliver") |
| } |
| var _ release.Store = fx.rel |
| } |
| - |
| -func geoipAlert(code float64, firing bool) metrics.AlertState { |
| - rs := metrics.RuleState{Firing: firing, Value: code, FiredAt: time.Date(2026, 10, 6, 10, 0, 0, 0, time.UTC)} |
| - return metrics.AlertState{V: 1, Box: "box-a", UpdatedAt: time.Date(2026, 10, 6, 10, 5, 0, 0, time.UTC), |
| - Rules: map[string]metrics.RuleState{"geoip": rs}} |
| -} |
| - |
| -// Code review R4-3: a geoip reason that changes while firing is mailed. |
| -func TestAlertPassMailsAGeoIPReasonChange(t *testing.T) { |
| - af := newAlertFixture(t) |
| - step := func(st metrics.AlertState, wantMails int, wantBody string) { |
| - t.Helper() |
| - af.writeAlert(t, st) |
| - af.pass(t) // resets af.sent |
| - got := af.sent |
| - if len(got) != wantMails { |
| - t.Fatalf("mails = %d, want %d: %+v", len(got), wantMails, got) |
| - } |
| - if wantBody != "" && !strings.Contains(got[0].body, wantBody) { |
| - t.Fatalf("body lacks %q: %s", wantBody, got[0].body) |
| - } |
| - } |
| - step(geoipAlert(2, true), 1, "expires within 9 days") |
| - step(geoipAlert(2, true), 0, "") |
| - step(geoipAlert(3, true), 1, "expired and removed") |
| - step(geoipAlert(0, false), 1, "") |
| - // A later episode, and a return to an earlier reason within one: each |
| - // is news (code review R5 on R4-3). |
| - step(geoipAlert(2, true), 1, "expires within 9 days") |
| - step(geoipAlert(3, true), 1, "expired and removed") |
| - step(geoipAlert(2, true), 1, "expires within 9 days") |
| - step(geoipAlert(2, true), 0, "") |
| -} |
diff --git a/internal/console/apidomains.go b/internal/console/apidomains.go| index ed625b000..d9a6f3484 100644 |
| --- a/internal/console/apidomains.go |
| +++ b/internal/console/apidomains.go |
| @@ -1651,6 +1651,13 @@ func aliasReadings(ctx context.Context, s release.Store, now time.Time) map[stri |
| log.Printf("console: api domains: could not load status boxes for hostname readings: %v", err) |
| return nil |
| } |
| + return aliasReadingsFrom(boxes, now) |
| +} |
| + |
| +// aliasReadingsFrom is aliasReadings over boxes already loaded, so the alert |
| +// engine judges certificates from the heartbeats it has just read |
| +// (alertsignals.go) rather than reading them again. |
| +func aliasReadingsFrom(boxes []status.Box, now time.Time) map[string]status.AliasReading { |
| readings := map[string]status.AliasReading{} |
| for _, b := range boxes { |
| if b.Metrics == nil || status.BoxStale(b, now, status.SnapshotPeriod) { |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index 03b99df60..208aa3ff2 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -2171,7 +2171,7 @@ var claimFixtures = map[string]claimFixture{ |
| "worker StartLifetimesCutoverWatch": claimRead("off on a host-claim console, where lifetimes are not for it: it logs that and reads nothing"), |
| "worker StartLifetimeRecoveryPass": claimRead("off on a host-claim console, where lifetimes are not for it: it logs that and reads nothing"), |
| "worker StartIncarnationMigrationPass": claimRead("off on a host-claim console, where lifetimes are not for it: it logs that and reads nothing"), |
| - "worker StartAlertWatcher": claimNonApp("box alert state under alerts/boxes and operator mail"), |
| + "worker StartAlertEngine": claimRead("off on a host-claim console, one console per deployment runs it (fleet alerts spec §5.2): it records the refusal in its job status and reads and writes nothing"), |
| "worker StartEconomicsPass": claimNonApp("daily usage census, statements and bills: deployment and account economics"), |
| "worker StartGeoipJobs": claimNonApp("GeoIP orphan sweep, D1 expiry and feed status under control/geoip/: the platform database, no app"), |
| "worker StartHostReports": claimNonApp("this console's census report (status/consoles) and roster activation release"), |
diff --git a/internal/console/claim_invariant_probes_worker_test.go b/internal/console/claim_invariant_probes_worker_test.go| index 9fc914ba0..86ec2d0cb 100644 |
| --- a/internal/console/claim_invariant_probes_worker_test.go |
| +++ b/internal/console/claim_invariant_probes_worker_test.go |
| @@ -9,8 +9,10 @@ package console |
| import ( |
| "context" |
| "encoding/json" |
| + "fmt" |
| "net/http" |
| "strings" |
| + "sync/atomic" |
| "testing" |
| "time" |
| @@ -101,10 +103,13 @@ var claimWorkerProbes = map[string]claimProbe{ |
| return "" |
| }, |
| }, |
| - "worker StartAlertWatcher": { |
| + "worker StartAlertEngine": { |
| + // The world is a host-claim console, so the engine refuses (R2 #2). |
| + // One box with a disk alert firing and an operator: an engine that |
| + // did not refuse would read them and write alert_* rows. Successful |
| + // incident creation is pinned off host-claim in |
| + // alertengine_pass_test.go. |
| setup: func(t *testing.T, cx *claimCase) { |
| - // One box with a disk alert firing; the owner holds a Keymail grant |
| - // (they signed in), so the watcher can mail them and must record it. |
| now := time.Now().UTC() |
| state := metrics.AlertState{V: 1, Box: "box1", UpdatedAt: now, |
| Rules: map[string]metrics.RuleState{"disk": {Firing: true, FiredAt: now, Value: 91}}} |
| @@ -116,10 +121,24 @@ var claimWorkerProbes = map[string]claimProbe{ |
| t.Fatal(err) |
| } |
| }, |
| - do: claimWorkerReply("StartAlertWatcher"), |
| + // The reply is the job's status, and its count of the store calls |
| + // the worker made, through a counting store swapped in for the run |
| + // (after quiesce, so nothing else is reading cfg.Releases). |
| + do: func(t *testing.T, cx *claimCase) claimReply { |
| + counting := &claimCountingStore{Store: cx.srv.cfg.Releases} |
| + cx.srv.cfg.Releases = counting |
| + reply := claimWorkerReply("StartAlertEngine")(t, cx) |
| + cx.srv.cfg.Releases = counting.Store |
| + st, _ := jobStatusOf(cx.srv, "StartAlertEngine") |
| + reply.Body = fmt.Sprintf("%s; store calls %d", st.Err, counting.calls.Load()) |
| + return reply |
| + }, |
| + body: []string{"refused: host-claim console; store calls 0"}, |
| effect: func(t *testing.T, cx *claimCase, r claimReply) string { |
| - if cx.sqlCount(t, `SELECT COUNT(*) FROM alert_seen`) == 0 { |
| - return "no operator was told about the firing alert (alert_seen is empty)" |
| + for _, table := range []string{"alert_connectors", "alert_incidents", "alert_fires", "alert_outbox", "alert_meta"} { |
| + if n := cx.sqlCount(t, "SELECT COUNT(*) FROM "+table); n != 0 { |
| + return fmt.Sprintf("the refused engine wrote %d %s rows", n, table) |
| + } |
| } |
| return "" |
| }, |
| @@ -265,3 +284,32 @@ var claimWorkerProbes = map[string]claimProbe{ |
| }, |
| }, |
| } |
| + |
| +// claimCountingStore counts every call through the release.Store methods. |
| +// It implements none of the optional extensions, so a reader that would use |
| +// one falls back to List or Get, which are counted. |
| +type claimCountingStore struct { |
| + release.Store |
| + calls atomic.Int64 |
| +} |
| + |
| +func (c *claimCountingStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + c.calls.Add(1) |
| + return c.Store.Get(ctx, key) |
| +} |
| +func (c *claimCountingStore) List(ctx context.Context, prefix string) ([]string, error) { |
| + c.calls.Add(1) |
| + return c.Store.List(ctx, prefix) |
| +} |
| +func (c *claimCountingStore) ListDirs(ctx context.Context, prefix string) ([]string, error) { |
| + c.calls.Add(1) |
| + return c.Store.ListDirs(ctx, prefix) |
| +} |
| +func (c *claimCountingStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| + c.calls.Add(1) |
| + return c.Store.Put(ctx, key, body, ifMatch) |
| +} |
| +func (c *claimCountingStore) Delete(ctx context.Context, key string) error { |
| + c.calls.Add(1) |
| + return c.Store.Delete(ctx, key) |
| +} |
diff --git a/internal/console/claim_runtime.go b/internal/console/claim_runtime.go| index bfde055d9..0bbc4419a 100644 |
| --- a/internal/console/claim_runtime.go |
| +++ b/internal/console/claim_runtime.go |
| @@ -353,7 +353,7 @@ func (s *Server) alertSQLDatabaseReplaced(ctx context.Context, account, app, eff |
| if !s.alertDue(ctx, sqlReceiptAlertBox, rule, op.address, true) { |
| continue |
| } |
| - // Only when there is something to deliver, as in alertPass. |
| + // Only when there is something to deliver. |
| run.noteMissing() |
| _, err := s.sendApp(ctx, op.token, op.address, subject, body) |
| if err != nil { |
diff --git a/internal/console/claim_workers.go b/internal/console/claim_workers.go| index bee9c5330..ff3bbd602 100644 |
| --- a/internal/console/claim_workers.go |
| +++ b/internal/console/claim_workers.go |
| @@ -6,7 +6,7 @@ func (s *Server) registerClaimWorkers() { |
| s.claimWorkers = map[string]func(context.Context){} |
| for name, h := range map[string]func(context.Context){ |
| "StartHostReports": s.StartHostReports, |
| - "StartAlertWatcher": s.StartAlertWatcher, |
| + "StartAlertEngine": s.StartAlertEngine, |
| "StartGeoipJobs": s.StartGeoipJobs, |
| "StartClaimRecoveryPass": s.StartClaimRecoveryPass, |
| "StartEconomicsPass": s.StartEconomicsPass, |
diff --git a/internal/console/economicspass.go b/internal/console/economicspass.go| index df29337b8..e965260cf 100644 |
| --- a/internal/console/economicspass.go |
| +++ b/internal/console/economicspass.go |
| @@ -35,8 +35,8 @@ const economicsPassInterval = time.Hour |
| // StartEconomicsPass runs economicsPass immediately and then hourly until |
| // ctx is done. Started from cmd/console's serve(), deliberately NOT from |
| -// NewServer — the StartAlertWatcher rule: test servers never grow |
| -// goroutines (alertwatch.go:44). |
| +// NewServer — the StartAlertEngine rule: test servers never grow |
| +// goroutines (alertwatch.go). |
| func (s *Server) StartEconomicsPass(ctx context.Context) { |
| t := time.NewTicker(economicsPassInterval) |
| defer t.Stop() |
diff --git a/internal/console/jobs.go b/internal/console/jobs.go| index 0635943e8..d06a05d1d 100644 |
| --- a/internal/console/jobs.go |
| +++ b/internal/console/jobs.go |
| @@ -275,7 +275,7 @@ func (j *jobRegistry) Snapshot() []JobStatus { |
| // OPS-102 and OPS-149 to OPS-153), keyed by its claim worker name. |
| var jobLabels = map[string]string{ |
| "StartHostReports": "Host reports", |
| - "StartAlertWatcher": "Alert checks", |
| + "StartAlertEngine": "Alert engine", |
| "StartGeoipJobs": "Location data", |
| "PublishMovesConsole": "Move records", |
| "StartClaimRecoveryPass": "Claim recovery", |
diff --git a/internal/console/jobs_test.go b/internal/console/jobs_test.go| index c9b17d3a8..42d176a9b 100644 |
| --- a/internal/console/jobs_test.go |
| +++ b/internal/console/jobs_test.go |
| @@ -33,8 +33,9 @@ import ( |
| // no ctx and are called from some 180 sites; domainHostPolicy's account |
| // lookup, which fails closed and takes no ctx. |
| var jobPassFuncs = map[string][]string{ |
| - "StartHostReports": {"localHostReport", "putHostReport"}, |
| - "StartAlertWatcher": {"alertPass", "alertRule", "alertDueFor", "alertDue", "recordAlertSeenFor", "recordAlertSeen"}, |
| + "StartHostReports": {"localHostReport", "putHostReport"}, |
| + "StartAlertEngine": {"alertEnginePass", "alertEngineStep", "boxAlertSignals", "heartbeatSignals", "openAlertSeal", |
| + "alertSnoozed", "alertEmitRows", "noteUnreachableOperators", "writeAlertEngineBeat"}, |
| "StartGeoipJobs": {"geoipPass"}, |
| "PublishMovesConsole": {"PublishMovesConsole"}, |
| "StartClaimRecoveryPass": {"RunClaimRecoveryPass", "runClaimRecoveryPassBody"}, |
| @@ -172,7 +173,7 @@ func TestPanickingPassIsRecordedAndTheJobRunsAgain(t *testing.T) { |
| fx := newConsoleFixture(t) |
| errc := make(chan error, 1) |
| go func() { |
| - errc <- fx.srv.jobs.Run(context.Background(), "StartAlertWatcher", func(context.Context) error { |
| + errc <- fx.srv.jobs.Run(context.Background(), "StartAlertEngine", func(context.Context) error { |
| var m map[string]int |
| m["boom"]++ // a nil map write: a runtime panic |
| return nil |
| @@ -181,14 +182,14 @@ func TestPanickingPassIsRecordedAndTheJobRunsAgain(t *testing.T) { |
| if err := <-errc; err == nil || !strings.HasPrefix(err.Error(), "panic: ") { |
| t.Fatalf("Run returned %v, want the panic as an error", err) |
| } |
| - st, _ := jobStatusOf(fx.srv, "StartAlertWatcher") |
| + st, _ := jobStatusOf(fx.srv, "StartAlertEngine") |
| if st.State != JobFailed || !strings.HasPrefix(st.Err, "panic: ") || st.LastRan.IsZero() { |
| t.Fatalf("after a panicking run: %+v, want Failed with the panic and a finish time", st) |
| } |
| - if err := fx.srv.jobs.Run(context.Background(), "StartAlertWatcher", fx.srv.alertPass); err != nil { |
| + if err := fx.srv.jobs.Run(context.Background(), "StartAlertEngine", fx.srv.alertEnginePass); err != nil { |
| t.Fatal(err) |
| } |
| - if st, _ := jobStatusOf(fx.srv, "StartAlertWatcher"); st.State != JobOK { |
| + if st, _ := jobStatusOf(fx.srv, "StartAlertEngine"); st.State != JobOK { |
| t.Fatalf("the run after the panic = %+v, want OK", st) |
| } |
| } |
| @@ -330,7 +331,7 @@ func TestSwallowedFailureInASharedHelperFailsTheRun(t *testing.T) { |
| func TestJobNoteIsTheFirstLineCappedAndEscaped(t *testing.T) { |
| ran := time.Date(2026, 10, 26, 9, 30, 0, 0, time.UTC) |
| rows := opJobRows([]JobStatus{ |
| - {Name: "StartAlertWatcher", State: JobFailed, LastRan: ran, Err: "<b>disk</b> full\nsecond line"}, |
| + {Name: "StartAlertEngine", State: JobFailed, LastRan: ran, Err: "<b>disk</b> full\nsecond line"}, |
| {Name: "StartInfraPass", State: JobFailed, LastRan: ran, Err: " " + strings.Repeat("é", 500) + " "}, |
| {Name: "StartHostReports", State: JobOK, LastRan: ran}, |
| {Name: "StartScanPass", State: JobNotRun}, |
| @@ -339,7 +340,7 @@ func TestJobNoteIsTheFirstLineCappedAndEscaped(t *testing.T) { |
| for i, r := range rows { |
| labels[i] = r.Label |
| } |
| - if want := []string{"Alert checks", "Architecture", "Host reports", "Virus scan"}; !slices.Equal(labels, want) { |
| + if want := []string{"Alert engine", "Architecture", "Host reports", "Virus scan"}; !slices.Equal(labels, want) { |
| t.Fatalf("labels = %q, want %q (sorted by label)", labels, want) |
| } |
| if rows[0].Note != "<b>disk</b> full" { |
| @@ -657,18 +658,18 @@ func TestSwallowedAlertFailureShowsAsFailed(t *testing.T) { |
| if _, err := fx.rel.Put(context.Background(), "alerts/boxes/box-1.json", []byte("{not json"), ""); err != nil { |
| t.Fatal(err) |
| } |
| - st := runWorkerUntilRan(t, fx, "StartAlertWatcher") |
| + st := runWorkerUntilRan(t, fx, "StartAlertEngine") |
| if st.State != JobFailed { |
| - t.Fatalf("alert checks = %+v, want Failed", st) |
| + t.Fatalf("alert engine = %+v, want Failed", st) |
| } |
| if !strings.Contains(st.Err, "alerts/boxes/box-1.json") { |
| - t.Errorf("alert checks error %q does not name the unparsable key", st.Err) |
| + t.Errorf("alert engine error %q does not name the unparsable key", st.Err) |
| } |
| // The second half (Task 9): the dashboard lists the failed job, with |
| // its link to Boxes' jobs table, and its jobs table shows it Failed. |
| c := signInOperator(t, fx) |
| - label := jobLabels["StartAlertWatcher"] |
| + label := jobLabels["StartAlertEngine"] |
| body := dashGet(t, fx, c) |
| item := `<code>` + label + `</code> failed on its last run. <a href="/fleet/boxes#jobs">Background jobs</a>` |
| if !strings.Contains(strings.Join(dashItems(t, body), "\n"), item) { |
| @@ -685,12 +686,12 @@ func TestSwallowedAlertFailureShowsAsFailed(t *testing.T) { |
| // deployment drops out. |
| func TestWorkerRunsReachTheRegistry(t *testing.T) { |
| fx := newConsoleFixture(t) |
| - if st, ok := jobStatusOf(fx.srv, "StartAlertWatcher"); !ok || st.State != JobNotRun { |
| + if st, ok := jobStatusOf(fx.srv, "StartAlertEngine"); !ok || st.State != JobNotRun { |
| t.Fatalf("before the worker starts: %+v (present %v), want Not run yet", st, ok) |
| } |
| - st := runWorkerUntilRan(t, fx, "StartAlertWatcher") |
| + st := runWorkerUntilRan(t, fx, "StartAlertEngine") |
| if st.State != JobOK && st.State != JobFailed { |
| - t.Fatalf("alert checks = %+v after a run", st) |
| + t.Fatalf("alert engine = %+v after a run", st) |
| } |
| if st.LastRan.IsZero() { |
| t.Error("a recorded run has no finish time") |
| @@ -733,9 +734,7 @@ func TestJobRegistryNilIsUsable(t *testing.T) { |
| } |
| var a *alertNow |
| - a.setBox("box", nil, time.Now()) |
| - a.keepOnly(nil) |
| - a.markKnown() |
| + a.set([]FiringAlert{{Box: "box", Rule: "disk", Since: time.Now()}}) |
| if alerts, known := a.Firing(); alerts != nil || known { |
| t.Fatalf("nil alertNow Firing = %v, %v; want nothing known", alerts, known) |
| } |
diff --git a/internal/console/metricsview.go b/internal/console/metricsview.go| index e9b2ca80c..5ffa61f7c 100644 |
| --- a/internal/console/metricsview.go |
| +++ b/internal/console/metricsview.go |
| @@ -992,7 +992,7 @@ func (s *Server) ownerAppMetricsFrom(ctx context.Context, hosts []string, unitBy |
| // sweepAlerts reads every alerts/boxes/*.json and returns one AlertRow per |
| // currently-firing rule. Unreadable-but-present keys fail the sweep (so it |
| // is never cached half-done); an unparsable object is skipped, matching |
| -// alertPass's posture on the same prefix. |
| +// the alert engine's posture on the same prefix. |
| func (s *Server) sweepAlerts(ctx context.Context) ([]AlertRow, error) { |
| keys, err := s.cfg.Releases.List(ctx, alertPrefix) |
| if err != nil { |
| @@ -1016,7 +1016,7 @@ func (s *Server) sweepAlerts(ctx context.Context) ([]AlertRow, error) { |
| } |
| box := st.Box |
| if box == "" { |
| - // Trust the key over an empty body field, same as alertPass. |
| + // Trust the key over an empty body field, same as the alert engine. |
| box = strings.TrimSuffix(strings.TrimPrefix(key, alertPrefix), ".json") |
| } |
| names := make([]string, 0, len(st.Rules)) |
diff --git a/internal/console/opdashboard_test.go b/internal/console/opdashboard_test.go| index 731617eba..dde622ef4 100644 |
| --- a/internal/console/opdashboard_test.go |
| +++ b/internal/console/opdashboard_test.go |
| @@ -139,12 +139,8 @@ func seedOperatorWorld(t *testing.T, fx *consoleFixture) operatorWorld { |
| seedHostBoxesAt(t, fx, now) |
| - if err := fx.st.SetGrantToken("paul@keymail.dev", "grant-p", now); err != nil { |
| - t.Fatal(err) |
| - } |
| - fx.srv.sendApp = func(context.Context, string, string, string, string) (string, error) { return "msg-1", nil } |
| publishAlert(t, fx.rel, boxAlert("box-1", "disk", metrics.RuleState{Firing: true, Value: 0.95, FiredAt: alertNowFiredAt})) |
| - if err := fx.srv.alertPass(ctx); err != nil { |
| + if err := fx.srv.alertEnginePass(ctx); err != nil { |
| t.Fatal(err) |
| } |
| if err := fx.st.SetAlertSeen("box-2", "mem", "paul@keymail.dev", true); err != nil { |
| @@ -261,7 +257,7 @@ func TestAttentionItemsEachCondition(t *testing.T) { |
| {"three storage requests", attentionInput{Fleet: fresh, Now: now, StorePending: &three}, |
| []attentionItem{{Lead: "3 storage requests are waiting for approval.", Href: "/fleet/store", Link: "Storage requests"}}, "warning", "1 thing needs attention"}, |
| {"no storage count", attentionInput{Fleet: fresh, Now: now}, nil, "positive", "Everything is running."}, |
| - {"a failed job", attentionInput{Fleet: fresh, Now: now, Jobs: []JobStatus{{Name: "StartEconomicsPass", State: JobFailed, Err: "x"}, {Name: "StartAlertWatcher", State: JobOK}}}, |
| + {"a failed job", attentionInput{Fleet: fresh, Now: now, Jobs: []JobStatus{{Name: "StartEconomicsPass", State: JobFailed, Err: "x"}, {Name: "StartAlertEngine", State: JobOK}}}, |
| []attentionItem{{Code: "Economics", Tail: " failed on its last run.", Href: "/fleet/boxes#jobs", Link: "Background jobs"}}, "warning", "1 thing needs attention"}, |
| {"no fleet.json yet", attentionInput{Now: now}, nil, "positive", "Everything is running."}, |
| {"two things", attentionInput{Fleet: down, Boxes: []dashBox{silent}, Now: now}, |
diff --git a/internal/console/server.go b/internal/console/server.go| index 4e154484b..f87a46037 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -612,6 +612,11 @@ type Config struct { |
| // fleet alerts spec §5.1): beside console.db, never inside it, so a |
| // replica or backup of the database alone cannot open a Slack URL. |
| AlertSealKeyPath string |
| + // AlertEngineBeatPath is the beat file the alert engine replaces after |
| + // each pass (alertwatch.go), which the console box's agent watches as |
| + // CARLOS_ALERT_ENGINE_BEAT (fleet alerts spec §8). "" writes none |
| + // (tests). |
| + AlertEngineBeatPath string |
| // The GeoIP feed (geoip spec §10.1): CONSOLE_GEOIP_FEED and, for |
| // GeoLite2, the MaxMind account and key. BoxLabel is this console's |
| // box, named in feed.json so only that box's mirror alerts on feed |
| @@ -996,8 +1001,12 @@ type Server struct { |
| // jobs is what each claim worker's runs last did (jobs.go), for the |
| // operator pages. Made before registerClaimWorkers declares the workers. |
| jobs *jobRegistry |
| - // alertsNow is what the alert watcher last read as firing (alertnow.go). |
| + // alertsNow is what the alert engine last saw firing (alertnow.go). |
| alertsNow *alertNow |
| + // alertEngine is the alert engine's state between passes |
| + // (alertwatch.go). Only the engine's worker touches it, one pass at a |
| + // time. |
| + alertEngine alertEngineState |
| // The alert senders (alertnotify.go). alertHTTP is built once, on first |
| // use, as newAlertHTTPClient(refusedAddr); a test sets it first. |
| // alertSeal opens connector targets once the engine has read its key; |
| @@ -1149,9 +1158,10 @@ type Server struct { |
| policyBeforeLock func(sqid, app string) |
| policyListedN uint64 |
| policyDiscovered map[[2]string]bool |
| - // sendApp is how the alert watcher (alertwatch.go) delivers keymail: |
| - // km.SendApp in production, a capture in tests. A field rather than a |
| - // direct call so an alertPass assertion needs no keymail server. |
| + // sendApp is how the per-operator notices (claim_runtime.go, |
| + // storenotify.go) deliver keymail: km.SendApp in production, a capture |
| + // in tests. A field rather than a direct call so a test needs no |
| + // keymail server. |
| sendApp func(ctx context.Context, token, to, subject, body string) (string, error) |
| // Invite delivery (handleInvite): Keymail federation first, then the |
| // console's own email. Fields so tests can substitute and shrink them. |
| @@ -1742,7 +1752,7 @@ func NewServer(cfg Config, st *Store) (*Server, error) { |
| s.sendApp = s.km.SendApp |
| s.sendFederated = s.km.SendFederated |
| } |
| - // No goroutine is started here: StartAlertWatcher is serve()'s job, so a |
| + // No goroutine is started here: StartAlertEngine is serve()'s job, so a |
| // test that constructs a Server gets a Server and nothing else. |
| s.registerRoute("GET /{$}", s.handleHome) |
| s.registerRoute("GET /static/{hash}/{file...}", s.handleStatic) |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index f750d19fb..ab88f917e 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -333,7 +333,7 @@ worker LogPlacementDiscrepancies |
| worker PublishMovesConsole |
| worker PublishPlansMarker |
| worker ReportApexSquats |
| -worker StartAlertWatcher |
| +worker StartAlertEngine |
| worker StartBillingSyncPass |
| worker StartClaimRecoveryPass |
| worker StartDoorKeyResign |