console: every background pass reports its runs to an in-process job registry
Each claim worker wraps one run of its pass in s.jobs.Run under its worker name; a failure a pass logs and steps over also calls jobFailed, so a run that swallowed an error still shows as Failed. RunClaimWorker drops a worker that returned without ever running. The op_jobs partial renders the table (first line of the error, capped at 160 runes, escaped). Run returns the pass's own error, so every loop logs exactly what it logged before.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
33 files changed,
+1,101
−71
approved_operator_pages_copy_test.go+10 −0internal/console/alertwatch.go+22 −15internal/console/apex.go+9 −3internal/console/apidoorkeys.go+7 −2internal/console/apipolicy.go+2 −0internal/console/billingpass.go+9 −1internal/console/claim_runtime.go+4 −4internal/console/claim_workers.go+12 −2internal/console/economicspass.go+14 −1internal/console/egressfleet.go+1 −1internal/console/expirypass.go+26 −1internal/console/hostclaimops.go+1 −1internal/console/hostreports.go+9 −6internal/console/infrapass.go+2 −1internal/console/jobs.go+265 −0internal/console/jobs_test.go+521 −0internal/console/lifetimes_cutover.go+12 −1internal/console/lifetimes_floor.go+2 −0internal/console/lifetimes_migrate.go+6 −2internal/console/lifetimes_purge.go+7 −0internal/console/lifetimes_recovery.go+1 −1internal/console/mailpush.go+9 −1internal/console/plangracepass.go+11 −1internal/console/planlimits.go+5 −1internal/console/plansmarker.go+21 −1internal/console/regiondrift.go+7 −1internal/console/relayops.go+5 −1internal/console/runsweep.go+27 −3internal/console/scandrain.go+44 −17internal/console/scanpass.go+3 −1internal/console/seedsweep.go+9 −1internal/console/server.go+7 −1internal/console/templates/opparts.html+11 −0
diff --git a/approved_operator_pages_copy_test.go b/approved_operator_pages_copy_test.go| index 97bc8859f..8479bb6e2 100644 |
| --- a/approved_operator_pages_copy_test.go |
| +++ b/approved_operator_pages_copy_test.go |
| @@ -50,6 +50,16 @@ var operatorPagesCopyBuilt = []string{ |
| "OPS-16", "OPS-17", "OPS-18", "OPS-19", "OPS-138", |
| // Task 6: the stored Detail text of the account-level audit actions. |
| "OPS-131", "OPS-132", "OPS-133", "OPS-134", "OPS-135", "OPS-136", |
| + // Task 7: the background jobs table, its status words and job labels. |
| + // OPS-80 ("OK") is written in jobs.go but not listed: the gate reads a |
| + // Go literal only when it holds three letters or more, so a two-letter |
| + // word cannot be checked here. TestJobNoteIsTheFirstLineCappedAndEscaped |
| + // pins it instead. |
| + "OPS-32", "OPS-77", "OPS-78", "OPS-79", "OPS-81", "OPS-82", |
| + "OPS-83", "OPS-84", "OPS-85", "OPS-86", "OPS-87", "OPS-88", "OPS-89", "OPS-90", |
| + "OPS-91", "OPS-92", "OPS-93", "OPS-94", "OPS-95", "OPS-96", "OPS-97", "OPS-98", |
| + "OPS-99", "OPS-100", "OPS-101", "OPS-102", |
| + "OPS-149", "OPS-150", "OPS-151", "OPS-152", "OPS-153", |
| } |
| // operatorPagesBuiltRows is entryBuiltRows for operatorPagesCopyBuilt. |
diff --git a/internal/console/alertwatch.go b/internal/console/alertwatch.go| index afcd77f21..416885e76 100644 |
| --- a/internal/console/alertwatch.go |
| +++ b/internal/console/alertwatch.go |
| @@ -49,7 +49,7 @@ func (s *Server) StartAlertWatcher(ctx context.Context) { |
| t := time.NewTicker(alertWatchInterval) |
| defer t.Stop() |
| for { |
| - if err := s.alertPass(ctx); err != nil { |
| + if err := s.jobs.Run(ctx, "StartAlertWatcher", s.alertPass); err != nil { |
| log.Printf("console: alert watch: %v", err) |
| } |
| select { |
| @@ -121,11 +121,13 @@ func (s *Server) alertPass(ctx context.Context) error { |
| 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 |
| @@ -189,16 +191,16 @@ func (s *Server) alertRule(ctx context.Context, run *alertRun, box, rule string, |
| // 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(box, rule, noMailboxAddress, rs) { |
| + 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(box, rule, noMailboxAddress, rs) |
| + s.recordAlertSeenFor(ctx, box, rule, noMailboxAddress, rs) |
| } |
| return |
| } |
| var due []operatorGrant |
| for _, op := range run.to { |
| - if s.alertDueFor(box, rule, op.address, rs) { |
| + if s.alertDueFor(ctx, box, rule, op.address, rs) { |
| due = append(due, op) |
| } |
| } |
| @@ -213,9 +215,10 @@ func (s *Server) alertRule(ctx context.Context, run *alertRun, box, rule string, |
| // 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(box, rule, op.address, rs) |
| + s.recordAlertSeenFor(ctx, box, rule, op.address, rs) |
| } |
| } |
| @@ -228,10 +231,10 @@ func (s *Server) alertRule(ctx context.Context, run *alertRun, box, rule string, |
| func geoipReasonRule(code float64) string { return fmt.Sprintf("geoip@%d", int(code)) } |
| // alertDueFor is alertDue plus the geoip reason rule. |
| -func (s *Server) alertDueFor(box, rule, address string, rs metrics.RuleState) bool { |
| - due := s.alertDue(box, rule, address, rs.Firing) |
| +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(box, geoipReasonRule(rs.Value), address, true) |
| + due = s.alertDue(ctx, box, geoipReasonRule(rs.Value), address, true) |
| } |
| return due |
| } |
| @@ -239,14 +242,15 @@ func (s *Server) alertDueFor(box, rule, address string, rs metrics.RuleState) bo |
| // 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). |
| -func (s *Server) recordAlertSeenFor(box, rule, address string, rs metrics.RuleState) { |
| - s.recordAlertSeen(box, rule, address, rs.Firing) |
| +// 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(box, geoipReasonRule(float64(code)), address, rs.Firing && int(rs.Value) == code) |
| + s.recordAlertSeen(ctx, box, geoipReasonRule(float64(code)), address, rs.Firing && int(rs.Value) == code) |
| } |
| } |
| @@ -258,16 +262,18 @@ func (s *Server) recordAlertSeenFor(box, rule, address string, rs metrics.RuleSt |
| // the synthetic no-mailbox row: if the transition was already dropped for |
| // want of any grant at all, an operator who gains a grant afterwards is not |
| // retroactively paged about it. |
| -func (s *Server) alertDue(box, rule, address string, firing bool) bool { |
| +func (s *Server) alertDue(ctx context.Context, box, rule, address string, firing bool) bool { |
| seen, known, err := s.store.AlertSeen(box, rule, address) |
| if err != nil { |
| log.Printf("console: alert watch: alert_seen %s/%s for %s: %v", box, rule, address, err) |
| + jobFailed(ctx, fmt.Errorf("alert_seen %s/%s for %s: %w", box, rule, address, err)) |
| return false |
| } |
| if !known && address != noMailboxAddress { |
| seen, known, err = s.store.AlertSeen(box, rule, noMailboxAddress) |
| if err != nil { |
| log.Printf("console: alert watch: alert_seen %s/%s: %v", box, rule, err) |
| + jobFailed(ctx, fmt.Errorf("alert_seen %s/%s: %w", box, rule, err)) |
| return false |
| } |
| } |
| @@ -277,15 +283,16 @@ func (s *Server) alertDue(box, rule, address string, firing bool) bool { |
| if !known && !firing { |
| // First sighting of a quiet rule. Record it so a later fire is a |
| // transition; say nothing. |
| - s.recordAlertSeen(box, rule, address, false) |
| + s.recordAlertSeen(ctx, box, rule, address, false) |
| return false |
| } |
| return true |
| } |
| -func (s *Server) recordAlertSeen(box, rule, address string, firing bool) { |
| +func (s *Server) recordAlertSeen(ctx context.Context, box, rule, address string, firing bool) { |
| if err := s.store.SetAlertSeen(box, rule, address, firing); err != nil { |
| log.Printf("console: alert watch: record %s/%s for %s: %v", box, rule, address, err) |
| + jobFailed(ctx, fmt.Errorf("record %s/%s for %s: %w", box, rule, address, err)) |
| } |
| } |
diff --git a/internal/console/apex.go b/internal/console/apex.go| index a03681a62..a838e70b3 100644 |
| --- a/internal/console/apex.go |
| +++ b/internal/console/apex.go |
| @@ -15,6 +15,7 @@ package console |
| import ( |
| "context" |
| "errors" |
| + "fmt" |
| "log" |
| "os" |
| "strings" |
| @@ -251,9 +252,12 @@ func hostHeldSentence(host string, hold *apexHold) string { |
| // not something to do quietly at boot. Started from cmd/console, never from |
| // NewServer. |
| func (s *Server) ReportApexSquats(ctx context.Context) { |
| - for _, line := range s.apexSquats(ctx) { |
| - log.Printf("console: apex squat: %s", line) |
| - } |
| + _ = s.jobs.Run(ctx, "ReportApexSquats", func(ctx context.Context) error { |
| + for _, line := range s.apexSquats(ctx) { |
| + log.Printf("console: apex squat: %s", line) |
| + } |
| + return nil |
| + }) |
| } |
| // apexSquats is ReportApexSquats' finding, one line per squat. |
| @@ -265,11 +269,13 @@ func (s *Server) apexSquats(ctx context.Context) []string { |
| reg, err := openRegistry(s.cfg.Registry) |
| if err != nil { |
| log.Printf("console: apex squat check: open registry: %v", err) |
| + jobFailed(ctx, fmt.Errorf("apex squat check: open registry: %w", err)) |
| return nil |
| } |
| routes, err := reg.List() |
| if err != nil { |
| log.Printf("console: apex squat check: list routes: %v", err) |
| + jobFailed(ctx, fmt.Errorf("apex squat check: list routes: %w", err)) |
| return nil |
| } |
| var out []string |
diff --git a/internal/console/apidoorkeys.go b/internal/console/apidoorkeys.go| index 41c1f07df..22d186bab 100644 |
| --- a/internal/console/apidoorkeys.go |
| +++ b/internal/console/apidoorkeys.go |
| @@ -331,6 +331,7 @@ func (s *Server) resignDoorKeys(ctx context.Context) { |
| apps, err := s.store.DoorKeyApps() |
| if err != nil { |
| log.Printf("console: door keys re-sign: %v", err) |
| + jobFailed(ctx, fmt.Errorf("door keys re-sign: %w", err)) |
| return |
| } |
| for _, a := range apps { |
| @@ -339,6 +340,7 @@ func (s *Server) resignDoorKeys(ctx context.Context) { |
| cancel() |
| if err != nil { |
| log.Printf("console: door keys re-sign %s/%s: %v", a.Sqid, a.App, err) |
| + jobFailed(ctx, fmt.Errorf("door keys re-sign %s/%s: %w", a.Sqid, a.App, err)) |
| } |
| } |
| } |
| @@ -355,8 +357,11 @@ func (s *Server) StartDoorKeyResign(ctx context.Context) { |
| t := time.NewTicker(doorKeyResignEvery) |
| defer t.Stop() |
| for { |
| - s.resignDoorKeys(ctx) |
| - s.resignAppPolicies(ctx) |
| + _ = s.jobs.Run(ctx, "StartDoorKeyResign", func(ctx context.Context) error { |
| + s.resignDoorKeys(ctx) |
| + s.resignAppPolicies(ctx) |
| + return nil |
| + }) |
| select { |
| case <-ctx.Done(): |
| return |
diff --git a/internal/console/apipolicy.go b/internal/console/apipolicy.go| index f687b99a7..218568e04 100644 |
| --- a/internal/console/apipolicy.go |
| +++ b/internal/console/apipolicy.go |
| @@ -753,6 +753,7 @@ func (s *Server) resignAppPolicies(ctx context.Context) { |
| cands, err := s.policyResignCandidates(ctx) |
| if err != nil { |
| s.policyLogf("console: app policies: re-sign: %v", err) |
| + jobFailed(ctx, fmt.Errorf("app policies: re-sign: %w", err)) |
| return |
| } |
| if len(cands) == 0 { |
| @@ -771,6 +772,7 @@ func (s *Server) resignAppPolicies(ctx context.Context) { |
| } |
| if err != nil { |
| s.policyLogf("console: app policy %s/%s: re-sign: %v", c.acct.Sqid, c.app, err) |
| + jobFailed(ctx, fmt.Errorf("app policy %s/%s: re-sign: %w", c.acct.Sqid, c.app, err)) |
| continue |
| } |
| if c.discovered { |
diff --git a/internal/console/billingpass.go b/internal/console/billingpass.go| index 9408fdccd..1d6cd39fb 100644 |
| --- a/internal/console/billingpass.go |
| +++ b/internal/console/billingpass.go |
| @@ -70,7 +70,7 @@ func (s *Server) StartBillingSyncPass(ctx context.Context) { |
| t := time.NewTicker(billingSyncInterval) |
| defer t.Stop() |
| for { |
| - s.billingSyncPass(ctx, time.Now()) |
| + _ = s.jobs.Run(ctx, "StartBillingSyncPass", func(ctx context.Context) error { s.billingSyncPass(ctx, time.Now()); return nil }) |
| select { |
| case <-ctx.Done(): |
| return |
| @@ -90,12 +90,14 @@ func (s *Server) billingSyncPass(ctx context.Context, now time.Time) { |
| page, err := s.store.LiveBillingAccounts(after, billingSyncBatch) |
| if err != nil { |
| log.Printf("console: billing sync pass: %v", err) |
| + jobFailed(ctx, fmt.Errorf("billing sync pass: %w", err)) |
| return |
| } |
| for _, b := range page { |
| after = b.AccountID |
| if err := s.syncSubscription(ctx, b.Subscription, now); err != nil { |
| log.Printf("console: billing sync pass: account %d: %v", b.AccountID, err) |
| + jobFailed(ctx, fmt.Errorf("billing sync pass: account %d: %w", b.AccountID, err)) |
| } |
| } |
| if len(page) < billingSyncBatch { |
| @@ -117,6 +119,7 @@ func (s *Server) billingDiscoveryPass(ctx context.Context, now time.Time) { |
| page, err := s.store.DiscoverableBillingAccounts(now.Add(-billingDiscoveryWindow), after, billingSyncBatch) |
| if err != nil { |
| log.Printf("console: billing discovery: %v", err) |
| + jobFailed(ctx, fmt.Errorf("billing discovery: %w", err)) |
| return |
| } |
| for _, b := range page { |
| @@ -142,6 +145,7 @@ func (s *Server) billingDiscoveryPass(ctx context.Context, now time.Time) { |
| func (s *Server) discoverCustomer(ctx context.Context, b billingAccount, now time.Time) { |
| if err := s.store.MarkBillingDiscovery(b.AccountID); err != nil { |
| log.Printf("console: billing discovery: account %d: marking: %v; skipped this pass", b.AccountID, err) |
| + jobFailed(ctx, fmt.Errorf("billing discovery: account %d: marking: %w; skipped this pass", b.AccountID, err)) |
| return |
| } |
| failed := false |
| @@ -149,17 +153,20 @@ func (s *Server) discoverCustomer(ctx context.Context, b billingAccount, now tim |
| if err != nil { |
| failed = true |
| log.Printf("console: billing discovery: account %d: %v", b.AccountID, err) |
| + jobFailed(ctx, fmt.Errorf("billing discovery: account %d: %w", b.AccountID, err)) |
| } |
| for _, id := range ids { |
| if err := s.syncSubscription(ctx, id, now); err != nil { |
| failed = true |
| log.Printf("console: billing discovery: account %d: %v", b.AccountID, err) |
| + jobFailed(ctx, fmt.Errorf("billing discovery: account %d: %w", b.AccountID, err)) |
| } |
| } |
| n, err := s.store.EndBillingDiscovery(b.AccountID, failed, now) |
| if err != nil { |
| // The marker stays down: the next pass tries again. |
| log.Printf("console: billing discovery: account %d: %v", b.AccountID, err) |
| + jobFailed(ctx, fmt.Errorf("billing discovery: account %d: %w", b.AccountID, err)) |
| return |
| } |
| if !failed { |
| @@ -173,6 +180,7 @@ func (s *Server) discoverCustomer(ctx context.Context, b billingAccount, now tim |
| if err := s.openBillingProblem(b.AccountID, sqid, "", problemDiscoveryFailing, |
| fmt.Sprintf("discovery of customer %s's subscriptions has failed %d passes in a row; it is retried every hour", b.Customer, n), now); err != nil { |
| log.Printf("console: billing discovery: account %d: %v", b.AccountID, err) |
| + jobFailed(ctx, fmt.Errorf("billing discovery: account %d: %w", b.AccountID, err)) |
| } |
| } |
| } |
diff --git a/internal/console/claim_runtime.go b/internal/console/claim_runtime.go| index f732ed88c..bfde055d9 100644 |
| --- a/internal/console/claim_runtime.go |
| +++ b/internal/console/claim_runtime.go |
| @@ -341,16 +341,16 @@ func (s *Server) alertSQLDatabaseReplaced(ctx context.Context, account, app, eff |
| run = r |
| } |
| if run == nil || len(run.to) == 0 { |
| - if s.alertDue(sqlReceiptAlertBox, rule, noMailboxAddress, true) { |
| + if s.alertDue(ctx, sqlReceiptAlertBox, rule, noMailboxAddress, true) { |
| log.Printf("console: ALERT %s", subject) |
| - s.recordAlertSeen(sqlReceiptAlertBox, rule, noMailboxAddress, true) |
| + s.recordAlertSeen(ctx, sqlReceiptAlertBox, rule, noMailboxAddress, true) |
| } |
| return |
| } |
| ctx, cancel := context.WithTimeout(ctx, sqlAlertSendTimeout) |
| defer cancel() |
| for _, op := range run.to { |
| - if !s.alertDue(sqlReceiptAlertBox, rule, op.address, true) { |
| + if !s.alertDue(ctx, sqlReceiptAlertBox, rule, op.address, true) { |
| continue |
| } |
| // Only when there is something to deliver, as in alertPass. |
| @@ -360,6 +360,6 @@ func (s *Server) alertSQLDatabaseReplaced(ctx context.Context, account, app, eff |
| log.Printf("console: claim SQL alert: keymail to %s: %v", op.address, err) |
| continue |
| } |
| - s.recordAlertSeen(sqlReceiptAlertBox, rule, op.address, true) |
| + s.recordAlertSeen(ctx, sqlReceiptAlertBox, rule, op.address, true) |
| } |
| } |
diff --git a/internal/console/claim_workers.go b/internal/console/claim_workers.go| index 63c5f6e6b..47998a67c 100644 |
| --- a/internal/console/claim_workers.go |
| +++ b/internal/console/claim_workers.go |
| @@ -31,6 +31,7 @@ func (s *Server) registerClaimWorkers() { |
| "LogPlacementDiscrepancies": s.LogPlacementDiscrepancies, |
| "PublishMovesConsole": s.publishMovesConsoleWorker, |
| } { |
| + s.jobs.declare(name) |
| e := claimEntry{Kind: "worker", Pattern: name, Handler: claimHandlerName(h)} |
| s.claimEntries.add(e) |
| if !s.cfg.HostClaim { |
| @@ -44,8 +45,14 @@ func (s *Server) registerClaimWorkers() { |
| // publishMovesConsoleWorker is PublishMovesConsole as a recorded worker. The |
| // method logs its own failure (it is best-effort and the console serves |
| // regardless), so the worker drops the returned error. It is a no-op with the |
| -// moves switch off. |
| -func (s *Server) publishMovesConsoleWorker(ctx context.Context) { _ = s.PublishMovesConsole(ctx) } |
| +// moves switch off, and then records no run, so the job drops off the |
| +// operator pages' list (RunClaimWorker). |
| +func (s *Server) publishMovesConsoleWorker(ctx context.Context) { |
| + if !s.cfg.MovesEnabled || s.cfg.Releases == nil { |
| + return |
| + } |
| + _ = s.jobs.Run(ctx, "PublishMovesConsole", s.PublishMovesConsole) |
| +} |
| func (s *Server) RunClaimWorker(ctx context.Context, name string) { |
| h, ok := s.claimWorkers[name] |
| @@ -53,4 +60,7 @@ func (s *Server) RunClaimWorker(ctx context.Context, name string) { |
| panic("unregistered console worker: " + name) |
| } |
| h(ctx) |
| + // A worker that returns without ever running (nothing to do on this |
| + // deployment) drops off the operator pages' job list. |
| + s.jobs.exited(name) |
| } |
diff --git a/internal/console/economicspass.go b/internal/console/economicspass.go| index db4dd18ca..5ec8daf33 100644 |
| --- a/internal/console/economicspass.go |
| +++ b/internal/console/economicspass.go |
| @@ -40,7 +40,7 @@ func (s *Server) StartEconomicsPass(ctx context.Context) { |
| t := time.NewTicker(economicsPassInterval) |
| defer t.Stop() |
| for { |
| - if err := s.economicsPass(ctx, time.Now()); err != nil { |
| + if err := s.jobs.Run(ctx, "StartEconomicsPass", func(ctx context.Context) error { return s.economicsPass(ctx, time.Now()) }); err != nil { |
| log.Printf("console: economics pass: %v", err) |
| } |
| select { |
| @@ -59,15 +59,19 @@ func (s *Server) economicsPass(ctx context.Context, now time.Time) error { |
| date := usage.DayOf(now) |
| if err := s.censusPass(ctx, date); err != nil { |
| log.Printf("console: census pass %s: %v", date, err) |
| + jobFailed(ctx, fmt.Errorf("census pass %s: %w", date, err)) |
| } |
| if err := s.storagePass(ctx, date); err != nil { |
| log.Printf("console: storage pass %s: %v", date, err) |
| + jobFailed(ctx, fmt.Errorf("storage pass %s: %w", date, err)) |
| } |
| if err := s.statementsPass(ctx, now); err != nil { |
| log.Printf("console: statements pass: %v", err) |
| + jobFailed(ctx, fmt.Errorf("statements pass: %w", err)) |
| } |
| if err := s.billPass(ctx, now); err != nil { |
| log.Printf("console: bill pass: %v", err) |
| + jobFailed(ctx, fmt.Errorf("bill pass: %w", err)) |
| } |
| return nil |
| } |
| @@ -179,6 +183,7 @@ func (s *Server) storagePass(ctx context.Context, date string) error { |
| // Same rule as an unreadable record below: "could not ask" is |
| // not "no store", and this object is create-only. |
| log.Printf("console: storage pass: store environments %s/%s: %v", acct, app, eerr) |
| + jobFailed(ctx, fmt.Errorf("storage pass: store environments %s/%s: %w", acct, app, eerr)) |
| st.StoreUnswept = true |
| } |
| for _, env := range append([]string{""}, envs...) { |
| @@ -192,6 +197,7 @@ func (s *Server) storagePass(ctx context.Context, date string) error { |
| // object, indistinguishable from an app that never had a |
| // store and never correctable afterward. |
| log.Printf("console: storage pass: store record %s/%s%s: %v", acct, app, storeEnvSuffix(env), gerr) |
| + jobFailed(ctx, fmt.Errorf("storage pass: store record %s/%s%s: %w", acct, app, storeEnvSuffix(env), gerr)) |
| st.StoreUnswept = true |
| continue |
| } |
| @@ -202,6 +208,7 @@ func (s *Server) storagePass(ctx context.Context, date string) error { |
| n, serr := s.sizeStore(ctx, rec.Provisioned) |
| if serr != nil { |
| log.Printf("console: storage pass: store %s/%s%s: %v", acct, app, storeEnvSuffix(env), serr) |
| + jobFailed(ctx, fmt.Errorf("storage pass: store %s/%s%s: %w", acct, app, storeEnvSuffix(env), serr)) |
| st.StoreUnswept = true |
| continue |
| } |
| @@ -370,6 +377,7 @@ func (s *Server) sweepUsage(ctx context.Context, from, to time.Time, routes []re |
| var roll metrics.DayRollup |
| if jerr := json.Unmarshal(raw, &roll); jerr != nil { |
| log.Printf("console: sweep usage: parse %s: %v", metrics.DayKey(box, date), jerr) |
| + jobFailed(ctx, fmt.Errorf("sweep usage: parse %s: %w", metrics.DayKey(box, date), jerr)) |
| continue |
| } |
| covered = true |
| @@ -413,6 +421,7 @@ func (s *Server) sweepUsage(ctx context.Context, from, to time.Time, routes []re |
| var ed usage.EdgeDay |
| if jerr := json.Unmarshal(raw, &ed); jerr != nil { |
| log.Printf("console: sweep usage: parse %s: %v", usage.EdgeDayKey(box, date), jerr) |
| + jobFailed(ctx, fmt.Errorf("sweep usage: parse %s: %w", usage.EdgeDayKey(box, date), jerr)) |
| continue |
| } |
| covered = true |
| @@ -505,6 +514,7 @@ func (s *Server) foldStorageAndCensus(ctx context.Context, from, to time.Time, d |
| var sd usage.StorageDay |
| if jerr := json.Unmarshal(raw, &sd); jerr != nil { |
| log.Printf("console: fold storage/census: parse %s: %v", usage.StorageDayKey(date), jerr) |
| + jobFailed(ctx, fmt.Errorf("fold storage/census: parse %s: %w", usage.StorageDayKey(date), jerr)) |
| } else { |
| for key, ap := range sd.Apps { |
| acct := key |
| @@ -539,6 +549,7 @@ func (s *Server) foldStorageAndCensus(ctx context.Context, from, to time.Time, d |
| var cd usage.CensusDay |
| if jerr := json.Unmarshal(raw, &cd); jerr != nil { |
| log.Printf("console: fold storage/census: parse %s: %v", usage.CensusDayKey(date), jerr) |
| + jobFailed(ctx, fmt.Errorf("fold storage/census: parse %s: %w", usage.CensusDayKey(date), jerr)) |
| } else { |
| for acct, ca := range cd.Accounts { |
| touch(acct)[usage.MeterAppMonths] += float64(ca.Apps) / float64(daysInMonth) |
| @@ -719,6 +730,7 @@ func (s *Server) fleetMeters(ctx context.Context, from, to time.Time) (map[strin |
| var roll metrics.DayRollup |
| if jerr := json.Unmarshal(raw, &roll); jerr != nil { |
| log.Printf("console: fleet meters: parse fleets/%s/%s: %v", bk.fleet, key, jerr) |
| + jobFailed(ctx, fmt.Errorf("fleet meters: parse fleets/%s/%s: %w", bk.fleet, key, jerr)) |
| continue |
| } |
| touch(owner.acct)[meter] += rollupPresenceHours(roll) |
| @@ -886,6 +898,7 @@ func (s *Server) billPass(ctx context.Context, now time.Time) error { |
| } |
| if err := s.pullBillMonth(ctx, p.month, p.start, p.end, nowUTC, p.closedMonth); err != nil { |
| log.Printf("console: bill pass %s: %v", p.month, err) |
| + jobFailed(ctx, fmt.Errorf("bill pass %s: %w", p.month, err)) |
| } |
| } |
| return nil |
diff --git a/internal/console/egressfleet.go b/internal/console/egressfleet.go| index d7ea25b04..6fed10da6 100644 |
| --- a/internal/console/egressfleet.go |
| +++ b/internal/console/egressfleet.go |
| @@ -276,7 +276,7 @@ func (s *Server) StartEgressReport(ctx context.Context) { |
| defer t.Stop() |
| for { |
| if s.egressReportDue(s.egressClock()) { |
| - if err := s.egressReportPass(ctx); err != nil { |
| + if err := s.jobs.Run(ctx, "StartEgressReport", s.egressReportPass); err != nil { |
| s.policyLogf("console: egress report: %v", err) |
| } |
| } |
diff --git a/internal/console/expirypass.go b/internal/console/expirypass.go| index 21ff9ec9c..7a9d6e210 100644 |
| --- a/internal/console/expirypass.go |
| +++ b/internal/console/expirypass.go |
| @@ -6,8 +6,10 @@ |
| package console |
| import ( |
| + "cmp" |
| "context" |
| "errors" |
| + "fmt" |
| "log" |
| "time" |
| @@ -31,7 +33,9 @@ func (s *Server) StartExpiryPass(ctx context.Context) { |
| // Each pass is a unit of record work (lifetimes_cutover.go): its purges |
| // remove instance records, so it is admitted as a writer. |
| lifetimesWorker(ctx, expiryPassInterval, func(ctx context.Context) { |
| - s.lifetimesIteration(ctx, "expiry pass", true, false, func(ctx context.Context) { s.expiryPass(ctx, time.Now()) }) |
| + s.lifetimesIteration(ctx, "expiry pass", true, false, func(ctx context.Context) { |
| + _ = s.jobs.Run(ctx, "StartExpiryPass", func(ctx context.Context) error { s.expiryPass(ctx, time.Now()); return nil }) |
| + }) |
| }) |
| } |
| @@ -51,11 +55,13 @@ func (s *Server) expiryPass(ctx context.Context, now time.Time) { |
| rows, err := s.store.TemporaryAppRows() |
| if err != nil { |
| log.Printf("console: expiry pass: list temporary apps: %v", err) |
| + jobFailed(ctx, fmt.Errorf("expiry pass: list temporary apps: %w", err)) |
| return |
| } |
| due, err := s.store.PurgeDueApps(now) |
| if err != nil { |
| log.Printf("console: expiry pass: list purges due: %v", err) |
| + jobFailed(ctx, fmt.Errorf("expiry pass: list purges due: %w", err)) |
| return |
| } |
| if len(rows) == 0 && len(due) == 0 { |
| @@ -115,10 +121,12 @@ func (s *Server) settleAndReport(ctx context.Context, r AppRow, now time.Time, e |
| before, err := s.store.AppLife(r.AccountID, r.App) |
| if err != nil { |
| log.Printf("console: expiry pass: read %s/%s: %v", r.Sqid, r.App, err) |
| + jobFailed(ctx, fmt.Errorf("expiry pass: read %s/%s: %w", r.Sqid, r.App, err)) |
| return |
| } |
| if err := s.settleApp(ctx, r.AccountID, r.Sqid, r.App, now, ev); err != nil { |
| log.Printf("console: expiry pass: settle %s/%s: %v", r.Sqid, r.App, err) |
| + jobFailed(ctx, fmt.Errorf("expiry pass: settle %s/%s: %w", r.Sqid, r.App, err)) |
| return |
| } |
| if before == nil || !before.Trashed() { |
| @@ -128,6 +136,7 @@ func (s *Server) settleAndReport(ctx context.Context, r AppRow, now time.Time, e |
| switch { |
| case err != nil: |
| log.Printf("console: expiry pass: re-read %s/%s: %v", r.Sqid, r.App, err) |
| + jobFailed(ctx, fmt.Errorf("expiry pass: re-read %s/%s: %w", r.Sqid, r.App, err)) |
| case after == nil: |
| log.Printf("console: expiry pass: finished a purge of %s/%s made elsewhere; the name is free", r.Sqid, r.App) |
| case !after.Trashed(): |
| @@ -136,16 +145,24 @@ func (s *Server) settleAndReport(ctx context.Context, r AppRow, now time.Time, e |
| } |
| } |
| +// The expiry job's notes for the two steps that can fail with no error. |
| +var ( |
| + errNoMarker = errors.New("no trash marker") |
| + errRowUnchanged = errors.New("the row did not change") |
| +) |
| + |
| // expireOne is spec ยง5 "Expire", steps 1-4, for one candidate. |
| func (s *Server) expireOne(ctx context.Context, r AppRow, now time.Time, ev evidenceFunc) { |
| defer s.lockApp(r.Sqid, r.App)() |
| if err := s.settleApp(ctx, r.AccountID, r.Sqid, r.App, now, ev); err != nil { |
| log.Printf("console: expiry pass: settle %s/%s: %v", r.Sqid, r.App, err) |
| + jobFailed(ctx, fmt.Errorf("expiry pass: settle %s/%s: %w", r.Sqid, r.App, err)) |
| return |
| } |
| life, err := s.store.AppLife(r.AccountID, r.App) |
| if err != nil { |
| log.Printf("console: expiry pass: read %s/%s: %v", r.Sqid, r.App, err) |
| + jobFailed(ctx, fmt.Errorf("expiry pass: read %s/%s: %w", r.Sqid, r.App, err)) |
| return |
| } |
| // A keep that ran after the listing set expires_at = 0, which fails > 0. |
| @@ -160,6 +177,7 @@ func (s *Server) expireOne(ctx context.Context, r AppRow, now time.Time, ev evid |
| } |
| if err := release.TrashApp(ctx, s.cfg.Releases, r.Sqid, r.App, expiryActor, now); err != nil { |
| log.Printf("console: expiry pass: trash %s/%s: %v", r.Sqid, r.App, err) |
| + jobFailed(ctx, fmt.Errorf("expiry pass: trash %s/%s: %w", r.Sqid, r.App, err)) |
| return // step 3 wrote nothing; the next pass tries again |
| } |
| // Create-only: a marker that already existed keeps its clock, the same |
| @@ -167,12 +185,14 @@ func (s *Server) expireOne(ctx context.Context, r AppRow, now time.Time, ev evid |
| tomb, err := release.ReadAppTombstone(ctx, s.cfg.Releases, r.Sqid, r.App) |
| if err != nil || tomb == nil { |
| log.Printf("console: expiry pass: re-read marker %s/%s: %v", r.Sqid, r.App, err) |
| + jobFailed(ctx, fmt.Errorf("expiry pass: re-read marker %s/%s: %w", r.Sqid, r.App, cmp.Or(err, errNoMarker))) |
| return |
| } |
| if ok, err := s.store.ExpireAppRowContext(ctx, r.AccountID, r.App, tomb.DeletedAt); err != nil || !ok { |
| // The marker stands and the row is live. The next door or pass to |
| // touch the app settles it, with the temporary window (spec ยง5). |
| log.Printf("console: expiry pass: mark %s/%s trashed: changed=%v err=%v", r.Sqid, r.App, ok, err) |
| + jobFailed(ctx, fmt.Errorf("expiry pass: mark %s/%s trashed: %w", r.Sqid, r.App, cmp.Or(err, errRowUnchanged))) |
| return |
| } |
| s.audit(acct, r.App, expiryActor, "expire", "moved "+r.App+" to the trash: it reached its expiry") |
| @@ -184,11 +204,13 @@ func (s *Server) purgeOne(ctx context.Context, r AppRow, now time.Time, ev evide |
| defer s.lockApp(r.Sqid, r.App)() |
| if err := s.settleApp(ctx, r.AccountID, r.Sqid, r.App, now, ev); err != nil { |
| log.Printf("console: expiry pass: settle %s/%s: %v", r.Sqid, r.App, err) |
| + jobFailed(ctx, fmt.Errorf("expiry pass: settle %s/%s: %w", r.Sqid, r.App, err)) |
| return |
| } |
| life, err := s.store.AppLife(r.AccountID, r.App) |
| if err != nil { |
| log.Printf("console: expiry pass: read %s/%s: %v", r.Sqid, r.App, err) |
| + jobFailed(ctx, fmt.Errorf("expiry pass: read %s/%s: %w", r.Sqid, r.App, err)) |
| return |
| } |
| if life == nil || !life.Trashed() || life.PurgeAfter <= 0 || life.PurgeAfter > now.Unix() || life.PurgeFor <= 0 { |
| @@ -205,6 +227,7 @@ func (s *Server) purgeOne(ctx context.Context, r AppRow, now time.Time, ev evide |
| switch estate, err := s.mailEstate(ctx, acct, r.App); { |
| case err != nil: |
| log.Printf("console: expiry pass: read email estate %s/%s: %v; not purging", r.Sqid, r.App, err) |
| + jobFailed(ctx, fmt.Errorf("expiry pass: read email estate %s/%s: %w; not purging", r.Sqid, r.App, err)) |
| return |
| case estate: |
| log.Printf("console: expiry pass: %s/%s has email estate; not purging it", r.Sqid, r.App) |
| @@ -223,6 +246,7 @@ func (s *Server) purgeOne(ctx context.Context, r AppRow, now time.Time, ev evide |
| case err == nil: |
| if err := s.store.PurgeAppRow(r.AccountID, r.App); err != nil { |
| log.Printf("console: expiry pass: release the name %s/%s: %v", r.Sqid, r.App, err) |
| + jobFailed(ctx, fmt.Errorf("expiry pass: release the name %s/%s: %w", r.Sqid, r.App, err)) |
| return |
| } |
| s.audit(acct, r.App, expiryActor, "purge", "deleted "+r.App+" permanently, 3 days after it went to the trash") |
| @@ -237,6 +261,7 @@ func (s *Server) purgeOne(ctx context.Context, r AppRow, now time.Time, ev evide |
| // Interrupted, a clock mismatch, a production flag, store estate: |
| // purge_after stays, and the next pass resumes or refuses again. |
| log.Printf("console: expiry pass: early purge %s/%s: %v", r.Sqid, r.App, err) |
| + jobFailed(ctx, fmt.Errorf("expiry pass: early purge %s/%s: %w", r.Sqid, r.App, err)) |
| } |
| } |
diff --git a/internal/console/hostclaimops.go b/internal/console/hostclaimops.go| index da3c081ee..f7d8989e7 100644 |
| --- a/internal/console/hostclaimops.go |
| +++ b/internal/console/hostclaimops.go |
| @@ -66,7 +66,7 @@ func (s *Server) StartClaimRecoveryPass(ctx context.Context) { |
| t := time.NewTicker(claimRecoveryInterval) |
| defer t.Stop() |
| for { |
| - if err := s.RunClaimRecoveryPass(ctx); err != nil { |
| + if err := s.jobs.Run(ctx, "StartClaimRecoveryPass", s.RunClaimRecoveryPass); err != nil { |
| log.Printf("console: claim recovery: %v", err) |
| } |
| select { |
diff --git a/internal/console/hostreports.go b/internal/console/hostreports.go| index dfeb0cf67..f80a94df3 100644 |
| --- a/internal/console/hostreports.go |
| +++ b/internal/console/hostreports.go |
| @@ -78,12 +78,15 @@ func (s *Server) StartHostReports(ctx context.Context) { |
| func (s *Server) runHostReports(ctx context.Context, ticks <-chan time.Time) { |
| collisionLogged := false |
| for { |
| - report, err := s.localHostReport(ctx) |
| - if err == nil { |
| - key := "status/consoles/" + s.cfg.HostConsoleID + ".json" |
| - raw, _ := json.Marshal(report) |
| - err = putHostReport(ctx, s.cfg.Releases, key, raw) |
| - } |
| + err := s.jobs.Run(ctx, "StartHostReports", func(ctx context.Context) error { |
| + report, err := s.localHostReport(ctx) |
| + if err == nil { |
| + key := "status/consoles/" + s.cfg.HostConsoleID + ".json" |
| + raw, _ := json.Marshal(report) |
| + err = putHostReport(ctx, s.cfg.Releases, key, raw) |
| + } |
| + return err |
| + }) |
| if len(s.cfg.Key) != 0 { |
| d := hostactors.Directory{Store: s.cfg.Releases, PublicKey: s.cfg.ReleasePub, Bucket: s.cfg.Bucket} |
| if o, e := d.Read(ctx); e == nil { |
diff --git a/internal/console/infrapass.go b/internal/console/infrapass.go| index 58675c802..cf9e94329 100644 |
| --- a/internal/console/infrapass.go |
| +++ b/internal/console/infrapass.go |
| @@ -53,7 +53,7 @@ func (s *Server) StartInfraPass(ctx context.Context) { |
| t := time.NewTicker(infraPassInterval) |
| defer t.Stop() |
| for { |
| - if err := s.infraPass(ctx); err != nil { |
| + if err := s.jobs.Run(ctx, "StartInfraPass", s.infraPass); err != nil { |
| if errors.Is(err, errInfraDisabled) { |
| return // permanent for the process โ nothing left to tick for |
| } |
| @@ -92,6 +92,7 @@ func (s *Server) resolveInventory(ctx context.Context) (infraview.Inventory, err |
| // Anything else means this process cannot build a provider at |
| // all, which is equally permanent for this process. |
| log.Printf("console: infra inventory unavailable: %v", err) |
| + jobFailed(ctx, fmt.Errorf("infra inventory unavailable: %w", err)) |
| s.infraDisabled.Store(true) |
| return |
| } |
diff --git a/internal/console/jobs.go b/internal/console/jobs.go| new file mode 100644 |
| index 000000000..a3df39e59 |
| --- /dev/null |
| +++ b/internal/console/jobs.go |
| @@ -0,0 +1,265 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "sort" |
| + "strings" |
| + "sync" |
| + "time" |
| +) |
| + |
| +// The background job registry: every claim worker (claim_workers.go) wraps |
| +// each run of its pass in Server.jobs.Run, so the operator pages can say |
| +// which jobs ran, when, and whether the last run failed. It lives in memory |
| +// only (spec 3.4: one console process; after a restart a job is Not run yet |
| +// until its next run). A pass that logs a failure and steps over it calls |
| +// jobFailed beside the log line, so a run that "succeeded" while it |
| +// swallowed an error still shows as Failed. |
| + |
| +// JobState is a job's last outcome. |
| +type JobState int |
| + |
| +const ( |
| + JobNotRun JobState = iota |
| + JobOK |
| + JobFailed |
| +) |
| + |
| +// JobStatus is one job as the registry last saw it. LastRan is when the |
| +// last run finished; Err is that run's error, "" when it succeeded. |
| +type JobStatus struct { |
| + Name string |
| + State JobState |
| + LastRan time.Time |
| + Err string |
| +} |
| + |
| +// jobEntry is one job's record. configured is false once the worker has |
| +// returned without ever running: a worker with nothing to do on this |
| +// deployment (no relay regions, no catalog) is not a job here. |
| +type jobEntry struct { |
| + configured bool |
| + running bool |
| + started time.Time |
| + status JobStatus |
| +} |
| + |
| +type jobRegistry struct { |
| + now func() time.Time |
| + mu sync.Mutex |
| + jobs map[string]*jobEntry |
| +} |
| + |
| +func newJobRegistry(now func() time.Time) *jobRegistry { |
| + if now == nil { |
| + now = time.Now |
| + } |
| + return &jobRegistry{now: now, jobs: map[string]*jobEntry{}} |
| +} |
| + |
| +// entry is name's record, made on first sight. j.mu is held. |
| +func (j *jobRegistry) entry(name string) *jobEntry { |
| + e, ok := j.jobs[name] |
| + if !ok { |
| + e = &jobEntry{configured: true, status: JobStatus{Name: name}} |
| + j.jobs[name] = e |
| + } |
| + return e |
| +} |
| + |
| +// declare names a job the console runs; it is Not run yet until its first |
| +// run finishes. |
| +func (j *jobRegistry) declare(name string) { |
| + j.mu.Lock() |
| + defer j.mu.Unlock() |
| + j.entry(name) |
| +} |
| + |
| +// exited records that name's worker returned. A job that never recorded a |
| +// run is marked not configured and drops out of Snapshot; one that ran |
| +// keeps its last outcome. |
| +func (j *jobRegistry) exited(name string) { |
| + j.mu.Lock() |
| + defer j.mu.Unlock() |
| + e, ok := j.jobs[name] |
| + if !ok { |
| + return |
| + } |
| + e.running = false |
| + if e.status.State == JobNotRun { |
| + e.configured = false |
| + } |
| +} |
| + |
| +// jobRun is the handle one run carries on its context, where jobFailed |
| +// finds it. A pass may fan out (the mail push sends per app in parallel), |
| +// hence the lock. |
| +type jobRun struct { |
| + mu sync.Mutex |
| + err error |
| +} |
| + |
| +type jobRunKey struct{} |
| + |
| +// Run runs one pass of the job name: it records the start, runs pass with a |
| +// run handle on ctx, and records the finish with pass's error, else the |
| +// first error jobFailed recorded during the run. It returns pass's own |
| +// error, so the worker's loop logs exactly what it logged before; the |
| +// failures jobFailed recorded were logged where they happened. |
| +// |
| +// An undeclared name is recorded too: a typo must never panic, since a |
| +// panic in a pass goroutine would take the console down |
| +// (TestEveryWorkerReportsItsRuns keeps the names right). A pass that panics |
| +// is not recovered here: it behaves as it did before the registry. |
| +func (j *jobRegistry) Run(ctx context.Context, name string, pass func(context.Context) error) error { |
| + j.mu.Lock() |
| + e := j.entry(name) |
| + e.configured = true |
| + e.running = true |
| + e.started = j.now() |
| + j.mu.Unlock() |
| + |
| + run := &jobRun{} |
| + err := pass(context.WithValue(ctx, jobRunKey{}, run)) |
| + |
| + recorded := err |
| + if recorded == nil { |
| + run.mu.Lock() |
| + recorded = run.err |
| + run.mu.Unlock() |
| + } |
| + j.mu.Lock() |
| + e = j.entry(name) |
| + e.configured = true |
| + e.running = false |
| + e.status.LastRan = j.now() |
| + if recorded != nil { |
| + e.status.State = JobFailed |
| + e.status.Err = recorded.Error() |
| + } else { |
| + e.status.State = JobOK |
| + e.status.Err = "" |
| + } |
| + j.mu.Unlock() |
| + return err |
| +} |
| + |
| +// jobFailed records err on the run ctx carries, if it is the run's first |
| +// failure. It is a no-op with no run on ctx (a door calling a pass's helper |
| +// directly) or a nil error. |
| +func jobFailed(ctx context.Context, err error) { |
| + if err == nil || ctx == nil { |
| + return |
| + } |
| + run, ok := ctx.Value(jobRunKey{}).(*jobRun) |
| + if !ok || run == nil { |
| + return |
| + } |
| + run.mu.Lock() |
| + if run.err == nil { |
| + run.err = err |
| + } |
| + run.mu.Unlock() |
| +} |
| + |
| +// Snapshot is every configured job, sorted by name. |
| +func (j *jobRegistry) Snapshot() []JobStatus { |
| + j.mu.Lock() |
| + defer j.mu.Unlock() |
| + out := make([]JobStatus, 0, len(j.jobs)) |
| + for _, e := range j.jobs { |
| + if e.configured { |
| + out = append(out, e.status) |
| + } |
| + } |
| + sort.Slice(out, func(a, b int) bool { return out[a].Name < out[b].Name }) |
| + return out |
| +} |
| + |
| +// jobLabels names each worker on the operator pages (copy record OPS-83 to |
| +// 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", |
| + "StartGeoipJobs": "Location data", |
| + "PublishMovesConsole": "Move records", |
| + "StartClaimRecoveryPass": "Claim recovery", |
| + "StartEconomicsPass": "Economics", |
| + "StartInfraPass": "Architecture", |
| + "StartScanPass": "Virus scan", |
| + "StartScanDrain": "Scan queue", |
| + "StartExpiryPass": "Temporary app expiry", |
| + "StartPlanLimitsPass": "Plan limits", |
| + "StartPlanGracePass": "Plan grace", |
| + "PublishPlansMarker": "Plan switch for boxes", |
| + "StartRunSweep": "Run cleanup", |
| + "StartSeedsPass": "Seed cleanup", |
| + "StartRelay": "Connection relay", |
| + "StartMailEventPush": "Email events", |
| + "StartDoorKeyResign": "Door keys", |
| + "ReportApexSquats": "Apex names", |
| + "LogPlacementDiscrepancies": "Placement", |
| + "StartBillingSyncPass": "Billing sync", |
| + "StartLifetimesCutoverWatch": "Lifetime switch check", |
| + "StartLifetimeRecoveryPass": "Lifetime recovery", |
| + "StartIncarnationMigrationPass": "Incarnation migration", |
| + "StartEgressReport": "Outbound transfer report", |
| +} |
| + |
| +// The job status words (OPS-80 to OPS-82). |
| +const ( |
| + jobWordOK = "OK" |
| + jobWordFailed = "Failed" |
| + jobWordNotRun = "Not run yet" |
| +) |
| + |
| +// jobNoteRunes caps a job's note: the first line of a long error is still |
| +// one line in the table. |
| +const jobNoteRunes = 160 |
| + |
| +// opJobRow is op_jobs's data: one job's label, status pill, last finish and |
| +// the first line of its last error. |
| +type opJobRow struct { |
| + Label string |
| + Status opPill |
| + LastRan time.Time |
| + Note string |
| +} |
| + |
| +// opJobRows is snap as the jobs table's rows, sorted by label. A name with |
| +// no label (never in production: TestEveryWorkerReportsItsRuns) shows as |
| +// itself. |
| +func opJobRows(snap []JobStatus) []opJobRow { |
| + rows := make([]opJobRow, 0, len(snap)) |
| + for _, st := range snap { |
| + label, ok := jobLabels[st.Name] |
| + if !ok { |
| + label = st.Name |
| + } |
| + row := opJobRow{Label: label, LastRan: st.LastRan} |
| + switch st.State { |
| + case JobOK: |
| + row.Status = opPill{Label: jobWordOK, Tone: "positive"} |
| + case JobFailed: |
| + row.Status = opPill{Label: jobWordFailed, Tone: "negative"} |
| + row.Note = jobNote(st.Err) |
| + default: |
| + row.Status = opPill{Label: jobWordNotRun, Tone: "neutral"} |
| + } |
| + rows = append(rows, row) |
| + } |
| + sort.SliceStable(rows, func(a, b int) bool { return rows[a].Label < rows[b].Label }) |
| + return rows |
| +} |
| + |
| +// jobNote is an error's first line, trimmed, capped at jobNoteRunes runes |
| +// with the last one an ellipsis. The template escapes it. |
| +func jobNote(err string) string { |
| + line, _, _ := strings.Cut(err, "\n") |
| + line = strings.TrimSpace(line) |
| + r := []rune(line) |
| + if len(r) > jobNoteRunes { |
| + line = string(r[:jobNoteRunes-1]) + "โฆ" |
| + } |
| + return line |
| +} |
diff --git a/internal/console/jobs_test.go b/internal/console/jobs_test.go| new file mode 100644 |
| index 000000000..febfb977a |
| --- /dev/null |
| +++ b/internal/console/jobs_test.go |
| @@ -0,0 +1,521 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "go/ast" |
| + "go/parser" |
| + "go/token" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "sort" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + "unicode/utf8" |
| +) |
| + |
| +// jobPassFuncs is, for each claim worker, the functions whose bodies run |
| +// inside its s.jobs.Run and may log a failure they step over. Each listed |
| +// function's logged errors must also fail the job |
| +// (TestPassFailureLogsAlsoFailTheJob). Shared helpers the passes reach (the |
| +// audit writer, the lifetimes allocation steps, outbound delivery) are not |
| +// listed: request handlers call them too, and their failures surface there. |
| +var jobPassFuncs = map[string][]string{ |
| + "StartHostReports": {"localHostReport", "putHostReport"}, |
| + "StartAlertWatcher": {"alertPass", "alertRule", "alertDueFor", "alertDue", "recordAlertSeenFor", "recordAlertSeen"}, |
| + "StartGeoipJobs": {"geoipPass"}, |
| + "PublishMovesConsole": {"PublishMovesConsole"}, |
| + "StartClaimRecoveryPass": {"RunClaimRecoveryPass", "runClaimRecoveryPassBody"}, |
| + "StartEconomicsPass": {"economicsPass", "censusPass", "storagePass", "statementsPass", "billPass", |
| + "sweepUsage", "foldStorageAndCensus", "fleetMeters"}, |
| + "StartInfraPass": {"infraPass", "resolveInventory"}, |
| + "StartScanPass": {"scanPass"}, |
| + "StartScanDrain": {"scanDrainStep", "rebuildScanQueue", "scanDrainTick", "drainScanApp", "collectScanResults"}, |
| + "StartExpiryPass": {"expiryPass", "settleAndReport", "expireOne", "purgeOne", "trashSweep", |
| + "sweepTrashedApp"}, |
| + "StartPlanLimitsPass": {"planLimitsPass"}, |
| + "StartPlanGracePass": {"planGracePass", "planGraceAccountLocked", "notifyPlanOwners"}, |
| + "StartBillingSyncPass": {"billingSyncPass", "billingDiscoveryPass", "discoverCustomer"}, |
| + "PublishPlansMarker": {"publishPlansMarkerOnce"}, |
| + "StartRunSweep": {"runSweepPass", "sweepExpireQueued", "sweepLostRun", "sweepTerminalRun", "sweepOrphanRuns", |
| + "orphanCandidates", "orphanConfirmed", "orphanRunEnd"}, |
| + "StartSeedsPass": {"seedsPass", "abandonSeed"}, |
| + "StartLifetimesCutoverWatch": {"lifetimesWatchOnce", "lifetimesFloorWatch", "materializeAppsOnce", "materializeAppsJudged"}, |
| + "StartLifetimeRecoveryPass": {"recoverLifetimes"}, |
| + "StartIncarnationMigrationPass": {"migratePreLifetimeRecords"}, |
| + "StartRelay": {"relayReconcile", "relayListRecords", "relayPublishAggregate"}, |
| + "StartMailEventPush": {"mailPushPass", "deliverAppMailEvents", "deliverAppMailEventsHeld"}, |
| + "StartDoorKeyResign": {"resignDoorKeys", "resignAppPolicies"}, |
| + "StartEgressReport": {"egressReportPass"}, |
| + "ReportApexSquats": {"apexSquats"}, |
| + "LogPlacementDiscrepancies": {"logPlacementDiscrepancies"}, |
| +} |
| + |
| +// TestJobRegistryRecordsRuns pins the registry's bookkeeping (not |
| +// acceptance: a unit test of jobRegistry). |
| +func TestJobRegistryRecordsRuns(t *testing.T) { |
| + clock := time.Date(2026, 10, 26, 12, 0, 0, 0, time.UTC) |
| + j := newJobRegistry(func() time.Time { return clock }) |
| + j.declare("A") |
| + j.declare("B") |
| + state := func(name string) (JobStatus, bool) { |
| + for _, st := range j.Snapshot() { |
| + if st.Name == name { |
| + return st, true |
| + } |
| + } |
| + return JobStatus{}, false |
| + } |
| + for _, n := range []string{"A", "B"} { |
| + if st, ok := state(n); !ok || st.State != JobNotRun || !st.LastRan.IsZero() { |
| + t.Fatalf("%s before any run = %+v (present %v), want Not run yet", n, st, ok) |
| + } |
| + } |
| + |
| + ctx := context.Background() |
| + if err := j.Run(ctx, "A", func(context.Context) error { return nil }); err != nil { |
| + t.Fatal(err) |
| + } |
| + if st, _ := state("A"); st.State != JobOK || !st.LastRan.Equal(clock) || st.Err != "" { |
| + t.Fatalf("A after an OK run = %+v", st) |
| + } |
| + |
| + clock = clock.Add(time.Minute) |
| + err := j.Run(ctx, "A", func(ctx context.Context) error { |
| + jobFailed(ctx, errors.New("a")) |
| + jobFailed(ctx, errors.New("b")) |
| + return nil |
| + }) |
| + if err != nil { |
| + t.Fatalf("Run returned %v; a pass that returns nil is nil to its loop", err) |
| + } |
| + if st, _ := state("A"); st.State != JobFailed || st.Err != "a" || !st.LastRan.Equal(clock) { |
| + t.Fatalf("A after a swallowed failure = %+v, want Failed with the first error", st) |
| + } |
| + |
| + // The pass's own error wins over one jobFailed recorded, and is returned. |
| + want := errors.New("own") |
| + if err := j.Run(ctx, "A", func(ctx context.Context) error { jobFailed(ctx, errors.New("x")); return want }); err != want { |
| + t.Fatalf("Run returned %v, want the pass's own error", err) |
| + } |
| + if st, _ := state("A"); st.Err != "own" { |
| + t.Fatalf("A = %+v, want the pass's own error recorded", st) |
| + } |
| + |
| + if err := j.Run(ctx, "A", func(context.Context) error { return nil }); err != nil { |
| + t.Fatal(err) |
| + } |
| + if st, _ := state("A"); st.State != JobOK || st.Err != "" { |
| + t.Fatalf("A after a later OK run = %+v, want the failure cleared", st) |
| + } |
| + |
| + // jobFailed with no run on the context, or a nil error, does nothing. |
| + jobFailed(ctx, errors.New("nobody")) |
| + _ = j.Run(ctx, "A", func(ctx context.Context) error { jobFailed(ctx, nil); return nil }) |
| + if st, _ := state("A"); st.State != JobOK { |
| + t.Fatalf("A = %+v after a nil jobFailed", st) |
| + } |
| + |
| + j.exited("B") |
| + if _, ok := state("B"); ok { |
| + t.Fatal("B exited without a run but is still listed") |
| + } |
| + j.exited("A") |
| + if st, ok := state("A"); !ok || st.State != JobOK { |
| + t.Fatalf("A exited after running: %+v (present %v), want its last outcome kept", st, ok) |
| + } |
| + |
| + // An undeclared name is recorded, never a panic. |
| + _ = j.Run(ctx, "Typo", func(context.Context) error { return nil }) |
| + if _, ok := state("Typo"); !ok { |
| + t.Fatal("an undeclared job's run was not recorded") |
| + } |
| + |
| + // A pass that fans out may fail from several goroutines (run with -race). |
| + _ = j.Run(ctx, "A", func(ctx context.Context) error { |
| + var wg sync.WaitGroup |
| + for i := range 8 { |
| + wg.Add(1) |
| + go func() { defer wg.Done(); jobFailed(ctx, errors.New(strconv.Itoa(i))); _ = j.Snapshot() }() |
| + } |
| + wg.Wait() |
| + return nil |
| + }) |
| + if st, _ := state("A"); st.State != JobFailed { |
| + t.Fatalf("A = %+v after parallel failures", st) |
| + } |
| +} |
| + |
| +// TestJobNoteIsTheFirstLineCappedAndEscaped is Review Focus 3: a job's |
| +// error that is multi-line, very long, or carries markup shows as its first |
| +// line, capped, escaped. |
| +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: "StartInfraPass", State: JobFailed, LastRan: ran, Err: " " + strings.Repeat("รฉ", 500) + " "}, |
| + {Name: "StartHostReports", State: JobOK, LastRan: ran}, |
| + {Name: "StartScanPass", State: JobNotRun}, |
| + }) |
| + labels := make([]string, len(rows)) |
| + for i, r := range rows { |
| + labels[i] = r.Label |
| + } |
| + if want := []string{"Alert checks", "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" { |
| + t.Errorf("note = %q, want the first line", rows[0].Note) |
| + } |
| + if n := utf8.RuneCountInString(rows[1].Note); n != 160 || !strings.HasSuffix(rows[1].Note, "โฆ") { |
| + t.Errorf("long note is %d runes ending %q, want 160 ending โฆ", n, rows[1].Note[len(rows[1].Note)-3:]) |
| + } |
| + if p := rows[0].Status; p.Label != "Failed" || p.Tone != "negative" { |
| + t.Errorf("failed pill = %+v", p) |
| + } |
| + if p := rows[2].Status; p.Label != "OK" || p.Tone != "positive" || rows[2].Note != "" { |
| + t.Errorf("ok row = %+v", rows[2]) |
| + } |
| + if p := rows[3].Status; p.Label != "Not run yet" || p.Tone != "neutral" { |
| + t.Errorf("not-run pill = %+v", p) |
| + } |
| + |
| + var b strings.Builder |
| + if err := templates.ExecuteTemplate(&b, "op_jobs", rows); err != nil { |
| + t.Fatal(err) |
| + } |
| + body := b.String() |
| + for _, w := range []string{ |
| + `<div rst-box-head id="jobs"><h2>Background jobs</h2></div>`, |
| + `<div rst-lrow="head"><span>Job</span><span>Status</span><span>Last ran</span><span>Note</span></div>`, |
| + "<b>disk</b> full", |
| + `title="2026-10-26 09:30 UTC"`, |
| + `<span rst-status rst-tone="negative">Failed</span>`, |
| + `<span rst-status rst-tone="neutral">Not run yet</span>`, |
| + } { |
| + if !strings.Contains(body, w) { |
| + t.Errorf("op_jobs lacks %s in:\n%s", w, body) |
| + } |
| + } |
| + if strings.Contains(body, "<b>disk") || strings.Contains(body, "second line") { |
| + t.Errorf("op_jobs carries the raw markup or the second line:\n%s", body) |
| + } |
| + if strings.Contains(body, "0001-01-01") { |
| + t.Errorf("a job that never ran shows a zero time:\n%s", body) |
| + } |
| +} |
| + |
| +// consoleSourceFiles parses the package's non-test files. |
| +func consoleSourceFiles(t *testing.T) (*token.FileSet, []*ast.File) { |
| + t.Helper() |
| + fset := token.NewFileSet() |
| + names, err := filepath.Glob("*.go") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var files []*ast.File |
| + for _, n := range names { |
| + if strings.HasSuffix(n, "_test.go") { |
| + continue |
| + } |
| + f, err := parser.ParseFile(fset, n, nil, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + files = append(files, f) |
| + } |
| + if len(files) == 0 { |
| + wd, _ := os.Getwd() |
| + t.Fatalf("no source files in %s", wd) |
| + } |
| + return fset, files |
| +} |
| + |
| +// TestEveryWorkerReportsItsRuns: every claim worker wraps its pass in |
| +// s.jobs.Run under its own name, and every name has a label. A worker that |
| +// does not report, or reports under a typo, fails here. |
| +func TestEveryWorkerReportsItsRuns(t *testing.T) { |
| + _, files := consoleSourceFiles(t) |
| + reported := map[string]bool{} |
| + for _, f := range files { |
| + ast.Inspect(f, func(n ast.Node) bool { |
| + call, ok := n.(*ast.CallExpr) |
| + if !ok || len(call.Args) < 2 { |
| + return true |
| + } |
| + sel, ok := call.Fun.(*ast.SelectorExpr) |
| + if !ok || sel.Sel.Name != "Run" { |
| + return true |
| + } |
| + if x, ok := sel.X.(*ast.SelectorExpr); !ok || x.Sel.Name != "jobs" { |
| + return true |
| + } |
| + lit, ok := call.Args[1].(*ast.BasicLit) |
| + if !ok || lit.Kind != token.STRING { |
| + t.Errorf("a .jobs.Run call names its job with %T, want a string literal", call.Args[1]) |
| + return true |
| + } |
| + name, err := strconv.Unquote(lit.Value) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + reported[name] = true |
| + return true |
| + }) |
| + } |
| + fx := newConsoleFixture(t) |
| + var workers, got []string |
| + for name := range fx.srv.claimWorkers { |
| + workers = append(workers, name) |
| + if _, ok := jobLabels[name]; !ok { |
| + t.Errorf("worker %s has no jobLabels entry", name) |
| + } |
| + } |
| + for name := range reported { |
| + got = append(got, name) |
| + } |
| + sort.Strings(workers) |
| + sort.Strings(got) |
| + if !slices.Equal(got, workers) { |
| + t.Errorf("jobs reported through .jobs.Run:\n %q\nclaim workers:\n %q", got, workers) |
| + } |
| + if len(jobLabels) != len(workers) { |
| + t.Errorf("jobLabels has %d entries for %d workers", len(jobLabels), len(workers)) |
| + } |
| +} |
| + |
| +// jobErrName is the source check's test for an error-named identifier. |
| +func jobErrName(n string) bool { return n == "err" || n == "e" || strings.HasSuffix(n, "Err") } |
| + |
| +// TestPassFailureLogsAlsoFailTheJob: in every function a worker's run |
| +// reaches (jobPassFuncs), a log.Printf of an error sits in a block that also |
| +// calls jobFailed, unless that block returns the error (the run records a |
| +// returned error itself). |
| +func TestPassFailureLogsAlsoFailTheJob(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + for name := range fx.srv.claimWorkers { |
| + if _, ok := jobPassFuncs[name]; !ok { |
| + t.Errorf("worker %s has no jobPassFuncs entry", name) |
| + } |
| + } |
| + fset, files := consoleSourceFiles(t) |
| + decls := map[string][]*ast.FuncDecl{} |
| + for _, f := range files { |
| + for _, d := range f.Decls { |
| + if fd, ok := d.(*ast.FuncDecl); ok && fd.Body != nil { |
| + decls[fd.Name.Name] = append(decls[fd.Name.Name], fd) |
| + } |
| + } |
| + } |
| + checked := map[string]bool{} |
| + for worker, names := range jobPassFuncs { |
| + for _, name := range names { |
| + fds, ok := decls[name] |
| + if !ok { |
| + t.Errorf("%s: jobPassFuncs names %s, which is no function in the package", worker, name) |
| + continue |
| + } |
| + if checked[name] { |
| + continue |
| + } |
| + checked[name] = true |
| + for _, fd := range fds { |
| + for _, p := range unmarkedFailureLogs(fd) { |
| + t.Errorf("%s (%s): %s logs an error without jobFailed in the same block", worker, name, fset.Position(p)) |
| + } |
| + } |
| + } |
| + } |
| +} |
| + |
| +// unmarkedFailureLogs is the positions of fd's log.Printf statements that |
| +// log an error-named identifier in a block with no jobFailed call and no |
| +// return of that identifier. |
| +func unmarkedFailureLogs(fd *ast.FuncDecl) []token.Pos { |
| + var out []token.Pos |
| + ast.Inspect(fd.Body, func(n ast.Node) bool { |
| + blk, ok := n.(*ast.BlockStmt) |
| + if !ok { |
| + return true |
| + } |
| + for _, stmt := range blk.List { |
| + es, ok := stmt.(*ast.ExprStmt) |
| + if !ok { |
| + continue |
| + } |
| + errs := loggedErrors(es) |
| + if len(errs) == 0 { |
| + continue |
| + } |
| + if blockCalls(blk, "jobFailed") { |
| + continue |
| + } |
| + returned := false |
| + for _, e := range errs { |
| + if blockReturns(blk, e) { |
| + returned = true |
| + } |
| + } |
| + if !returned { |
| + out = append(out, es.Pos()) |
| + } |
| + } |
| + return true |
| + }) |
| + return out |
| +} |
| + |
| +// loggedErrors is the error-named identifiers a log.Printf statement logs. |
| +func loggedErrors(es *ast.ExprStmt) []string { |
| + call, ok := es.X.(*ast.CallExpr) |
| + if !ok { |
| + return nil |
| + } |
| + sel, ok := call.Fun.(*ast.SelectorExpr) |
| + if !ok || sel.Sel.Name != "Printf" { |
| + return nil |
| + } |
| + if pkg, ok := sel.X.(*ast.Ident); !ok || pkg.Name != "log" { |
| + return nil |
| + } |
| + var errs []string |
| + for _, a := range call.Args[1:] { |
| + if id, ok := a.(*ast.Ident); ok && jobErrName(id.Name) { |
| + errs = append(errs, id.Name) |
| + } |
| + } |
| + return errs |
| +} |
| + |
| +// blockCalls reports whether blk's own statements call fn (not counting |
| +// function literals, which run elsewhere). |
| +func blockCalls(blk *ast.BlockStmt, fn string) bool { |
| + found := false |
| + for _, stmt := range blk.List { |
| + ast.Inspect(stmt, func(n ast.Node) bool { |
| + if _, ok := n.(*ast.FuncLit); ok { |
| + return false |
| + } |
| + if c, ok := n.(*ast.CallExpr); ok { |
| + if id, ok := c.Fun.(*ast.Ident); ok && id.Name == fn { |
| + found = true |
| + } |
| + } |
| + return !found |
| + }) |
| + } |
| + return found |
| +} |
| + |
| +// blockReturns reports whether blk has a return statement among its own |
| +// statements whose results mention name. |
| +func blockReturns(blk *ast.BlockStmt, name string) bool { |
| + for _, stmt := range blk.List { |
| + ret, ok := stmt.(*ast.ReturnStmt) |
| + if !ok { |
| + continue |
| + } |
| + for _, r := range ret.Results { |
| + mentions := false |
| + ast.Inspect(r, func(n ast.Node) bool { |
| + if id, ok := n.(*ast.Ident); ok && id.Name == name { |
| + mentions = true |
| + } |
| + return !mentions |
| + }) |
| + if mentions { |
| + return true |
| + } |
| + } |
| + } |
| + return false |
| +} |
| + |
| +// jobStatusOf is name's row in the server's registry. |
| +func jobStatusOf(s *Server, name string) (JobStatus, bool) { |
| + for _, st := range s.jobs.Snapshot() { |
| + if st.Name == name { |
| + return st, true |
| + } |
| + } |
| + return JobStatus{}, false |
| +} |
| + |
| +// runWorkerUntilRan starts the worker through RunClaimWorker, waits (5 s |
| +// cap) until its first run is recorded, cancels it and waits for it to |
| +// return. |
| +func runWorkerUntilRan(t *testing.T, fx *consoleFixture, name string) JobStatus { |
| + t.Helper() |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + done := make(chan struct{}) |
| + go func() { defer close(done); fx.srv.RunClaimWorker(ctx, name) }() |
| + defer func() { |
| + cancel() |
| + select { |
| + case <-done: |
| + case <-time.After(5 * time.Second): |
| + t.Errorf("%s did not return after its context was cancelled", name) |
| + } |
| + }() |
| + deadline := time.Now().Add(5 * time.Second) |
| + for time.Now().Before(deadline) { |
| + if st, ok := jobStatusOf(fx.srv, name); ok && st.State != JobNotRun { |
| + return st |
| + } |
| + time.Sleep(10 * time.Millisecond) |
| + } |
| + t.Fatalf("%s recorded no run within 5 s", name) |
| + return JobStatus{} |
| +} |
| + |
| +// TestSwallowedAlertFailureShowsAsFailed: the alert pass logs an unparsable |
| +// alert object and steps over it, returning nil; the job still shows Failed, |
| +// naming the key. |
| +func TestSwallowedAlertFailureShowsAsFailed(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + if err := fx.st.SetOperator("paul@keymail.dev", true); err != nil { |
| + t.Fatal(err) |
| + } |
| + 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") |
| + if st.State != JobFailed { |
| + t.Fatalf("alert checks = %+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) |
| + } |
| +} |
| + |
| +// TestWorkerRunsReachTheRegistry: a worker started the way cmd/console |
| +// starts it records its runs; a worker with nothing to do on this |
| +// deployment drops out. |
| +func TestWorkerRunsReachTheRegistry(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + if st, ok := jobStatusOf(fx.srv, "StartAlertWatcher"); !ok || st.State != JobNotRun { |
| + t.Fatalf("before the worker starts: %+v (present %v), want Not run yet", st, ok) |
| + } |
| + st := runWorkerUntilRan(t, fx, "StartAlertWatcher") |
| + if st.State != JobOK && st.State != JobFailed { |
| + t.Fatalf("alert checks = %+v after a run", st) |
| + } |
| + if st.LastRan.IsZero() { |
| + t.Error("a recorded run has no finish time") |
| + } |
| + |
| + done := make(chan struct{}) |
| + go func() { defer close(done); fx.srv.RunClaimWorker(context.Background(), "StartRelay") }() |
| + select { |
| + case <-done: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("StartRelay with no relay regions did not return at once") |
| + } |
| + if st, ok := jobStatusOf(fx.srv, "StartRelay"); ok { |
| + t.Errorf("StartRelay with nothing to do is still listed: %+v", st) |
| + } |
| +} |
diff --git a/internal/console/lifetimes_cutover.go b/internal/console/lifetimes_cutover.go| index 74c862fcf..a815d9cf0 100644 |
| --- a/internal/console/lifetimes_cutover.go |
| +++ b/internal/console/lifetimes_cutover.go |
| @@ -463,16 +463,24 @@ func (s *Server) lifetimesWatchOnce(ctx context.Context) { |
| now := g.clock() |
| was := g.current() |
| g.observe(m, err, now) |
| + if err != nil { |
| + // Every watch that cannot read the marker is a failed run; the log |
| + // line and the page below are rate-limited, the job status is not. |
| + jobFailed(ctx, fmt.Errorf("%s: %w", pageLifetimesMarkerUnread, err)) |
| + } |
| if err != nil && g.pageDue(now) { |
| log.Printf("console: lifetimes: %s: %v", pageLifetimesMarkerUnread, err) |
| + jobFailed(ctx, fmt.Errorf("%s: %w", pageLifetimesMarkerUnread, err)) |
| if perr := alerting.Page(ctx, alerting.LevelIncident, pageLifetimesMarkerUnread, err.Error()); perr != nil { |
| log.Printf("console: lifetimes: page: %v", perr) |
| + jobFailed(ctx, fmt.Errorf("lifetimes: page: %w", perr)) |
| } |
| } |
| g.activateWhenDrained(now) |
| if is := g.current(); is != was { |
| if err != nil { |
| log.Printf("console: lifetimes: %s -> %s (the marker could not be read: %v)", was, is, err) |
| + jobFailed(ctx, fmt.Errorf("lifetimes: %s -> %s (the marker could not be read: %w)", was, is, err)) |
| } else { |
| log.Printf("console: lifetimes: %s -> %s", was, is) |
| } |
| @@ -502,6 +510,7 @@ func (s *Server) materializeAppsOnce(ctx context.Context) { |
| } |
| if err != nil { |
| log.Printf("console: could not converge app rows with the bucket: %v", err) |
| + jobFailed(ctx, fmt.Errorf("could not converge app rows with the bucket: %w", err)) |
| } |
| }) |
| } |
| @@ -517,7 +526,9 @@ func (s *Server) StartLifetimesCutoverWatch(ctx context.Context) { |
| if !s.lifetimesGoverned() { |
| return |
| } |
| - lifetimesWorker(ctx, lifetimesWatchInterval, s.lifetimesWatchOnce) |
| + lifetimesWorker(ctx, lifetimesWatchInterval, func(ctx context.Context) { |
| + _ = s.jobs.Run(ctx, "StartLifetimesCutoverWatch", func(ctx context.Context) error { s.lifetimesWatchOnce(ctx); return nil }) |
| + }) |
| } |
| // handleAPILifetimesCutover is `carlos system lifetimes cutover`: an |
diff --git a/internal/console/lifetimes_floor.go b/internal/console/lifetimes_floor.go| index 2b8e20641..e871b86d7 100644 |
| --- a/internal/console/lifetimes_floor.go |
| +++ b/internal/console/lifetimes_floor.go |
| @@ -139,6 +139,7 @@ func (s *Server) lifetimesFloorWatch(ctx context.Context, now time.Time) { |
| cancel() |
| if err != nil { |
| log.Printf("console: lifetimes: the box floor watch: %v", err) |
| + jobFailed(ctx, fmt.Errorf("lifetimes: the box floor watch: %w", err)) |
| return |
| } |
| for _, f := range snap.Files { |
| @@ -162,6 +163,7 @@ func (s *Server) lifetimesFloorWatch(ctx context.Context, now time.Time) { |
| log.Printf("console: lifetimes: %s", subject) |
| if err := lifetimesPage(ctx, alerting.LevelIncident, subject, "its edges file at control/edges/"+f.Box+".json does not list "+capLifetimes1); err != nil { |
| log.Printf("console: lifetimes: page: %v", err) |
| + jobFailed(ctx, fmt.Errorf("lifetimes: page: %w", err)) |
| } |
| } |
| } |
diff --git a/internal/console/lifetimes_migrate.go b/internal/console/lifetimes_migrate.go| index fcc70d134..3dae7b4c4 100644 |
| --- a/internal/console/lifetimes_migrate.go |
| +++ b/internal/console/lifetimes_migrate.go |
| @@ -437,8 +437,11 @@ func (s *Server) incarnationMigrationPass(ctx context.Context) (ran bool, attemp |
| return false, 0 |
| } |
| ran = s.lifetimesIteration(ctx, "incarnation migration", true, true, func(ctx context.Context) { |
| - var err error |
| - if attempted, err = s.migratePreLifetimeRecords(ctx); err != nil { |
| + if err := s.jobs.Run(ctx, "StartIncarnationMigrationPass", func(ctx context.Context) error { |
| + var err error |
| + attempted, err = s.migratePreLifetimeRecords(ctx) |
| + return err |
| + }); err != nil { |
| log.Printf("console: incarnation migration pass: %v", err) |
| } |
| }) |
| @@ -486,6 +489,7 @@ func (s *Server) migratePreLifetimeRecords(ctx context.Context) (int, error) { |
| _, _, _, state, err := s.migrateHostLifetimeLocked(ctx, rec.Account, rec.App, rec.Host, "") |
| if err != nil || state != lifetimeCommitted { |
| log.Printf("console: incarnation migration pass: %s/%s/%s: %s %v", rec.Account, rec.App, rec.Host, state, err) |
| + jobFailed(ctx, fmt.Errorf("incarnation migration pass: %s/%s/%s: %s %v", rec.Account, rec.App, rec.Host, state, err)) |
| } |
| return nil |
| }) |
diff --git a/internal/console/lifetimes_purge.go b/internal/console/lifetimes_purge.go| index 68eed0704..820d1c4ed 100644 |
| --- a/internal/console/lifetimes_purge.go |
| +++ b/internal/console/lifetimes_purge.go |
| @@ -172,6 +172,7 @@ func (s *Server) trashSweep(ctx context.Context, now time.Time) { |
| apps, err := release.ExpiredTrashApps(ctx, s.cfg.Releases, now) |
| if err != nil { |
| log.Printf("console: trash sweep: list the trash: %v", err) |
| + jobFailed(ctx, fmt.Errorf("trash sweep: list the trash: %w", err)) |
| return |
| } |
| for _, a := range apps { |
| @@ -191,18 +192,21 @@ func (s *Server) sweepTrashedApp(ctx context.Context, a release.TrashedApp, now |
| if err != nil || tomb == nil || now.Sub(tomb.DeletedAt) < release.TrashCooloff { |
| if err != nil { |
| log.Printf("console: trash sweep: %s/%s: %v", a.Account, a.App, err) |
| + jobFailed(ctx, fmt.Errorf("trash sweep: %s/%s: %w", a.Account, a.App, err)) |
| } |
| return // restored, purged or re-trashed since the listing |
| } |
| acct, err := s.store.AccountBySqid(a.Account) |
| if err != nil { |
| log.Printf("console: trash sweep: %s/%s: %v", a.Account, a.App, err) |
| + jobFailed(ctx, fmt.Errorf("trash sweep: %s/%s: %w", a.Account, a.App, err)) |
| return |
| } |
| var life *AppLife |
| if acct != nil { |
| if life, err = s.store.AppLife(acct.ID, a.App); err != nil { |
| log.Printf("console: trash sweep: %s/%s: %v", a.Account, a.App, err) |
| + jobFailed(ctx, fmt.Errorf("trash sweep: %s/%s: %w", a.Account, a.App, err)) |
| return |
| } |
| if life != nil && life.ControlPlane { |
| @@ -233,6 +237,7 @@ func (s *Server) sweepTrashedApp(ctx context.Context, a release.TrashedApp, now |
| } |
| if err != nil { |
| log.Printf("console: trash sweep: purge %s/%s: %v", a.Account, a.App, err) |
| + jobFailed(ctx, fmt.Errorf("trash sweep: purge %s/%s: %w", a.Account, a.App, err)) |
| return |
| } |
| log.Printf("console: trash sweep: purged %s/%s, trashed %s, past the %s cooloff", |
| @@ -240,6 +245,7 @@ func (s *Server) sweepTrashedApp(ctx context.Context, a release.TrashedApp, now |
| if life != nil && life.Trashed() { |
| if err := s.store.PurgeAppRow(acct.ID, a.App); err != nil { |
| log.Printf("console: trash sweep: release the name %s/%s: %v", a.Account, a.App, err) |
| + jobFailed(ctx, fmt.Errorf("trash sweep: release the name %s/%s: %w", a.Account, a.App, err)) |
| } |
| } |
| } |
| @@ -307,6 +313,7 @@ func (s *Server) materializeAppsJudged(ctx context.Context) error { |
| defer s.lockApp(r.Sqid, r.App)() |
| if err := s.settleApp(ctx, r.AccountID, r.Sqid, r.App, time.Now(), func(context.Context) bool { return evidence }); err != nil { |
| log.Printf("console: materialise %s/%s: %v", r.Sqid, r.App, err) |
| + jobFailed(ctx, fmt.Errorf("materialise %s/%s: %w", r.Sqid, r.App, err)) |
| } |
| }() |
| } |
diff --git a/internal/console/lifetimes_recovery.go b/internal/console/lifetimes_recovery.go| index c3d9aed5e..2ebef91b8 100644 |
| --- a/internal/console/lifetimes_recovery.go |
| +++ b/internal/console/lifetimes_recovery.go |
| @@ -40,7 +40,7 @@ func (s *Server) StartLifetimeRecoveryPass(ctx context.Context) { |
| // It reports whether the pass ran. |
| func (s *Server) lifetimeRecoveryIteration(ctx context.Context) bool { |
| return s.lifetimesIteration(ctx, "lifetime recovery", true, true, func(ctx context.Context) { |
| - if err := s.recoverLifetimes(ctx); err != nil { |
| + if err := s.jobs.Run(ctx, "StartLifetimeRecoveryPass", s.recoverLifetimes); err != nil { |
| log.Printf("console: lifetime recovery pass: %v", err) |
| } |
| }) |
diff --git a/internal/console/mailpush.go b/internal/console/mailpush.go| index e9dd50a53..04bd7a3cc 100644 |
| --- a/internal/console/mailpush.go |
| +++ b/internal/console/mailpush.go |
| @@ -681,7 +681,7 @@ func (s *Server) StartMailEventPush(ctx context.Context) { |
| t := time.NewTicker(mailPushEvery) |
| defer t.Stop() |
| for { |
| - if err := s.mailPushPass(ctx, time.Now); err != nil { |
| + if err := s.jobs.Run(ctx, "StartMailEventPush", func(ctx context.Context) error { return s.mailPushPass(ctx, time.Now) }); err != nil { |
| log.Printf("console: mail push: %v", err) |
| } |
| select { |
| @@ -704,6 +704,7 @@ func (s *Server) mailPushPass(ctx context.Context, clock func() time.Time) error |
| // A prune that fails costs an hour's slack on a thirty-day window, |
| // not the pass: what is due still goes out. |
| log.Printf("console: mail push: pruning the queue: %v", err) |
| + jobFailed(ctx, fmt.Errorf("mail push: pruning the queue: %w", err)) |
| } |
| hooks, err := s.store.activeMailEventHooks(ctx) |
| if err != nil { |
| @@ -728,11 +729,13 @@ func (s *Server) mailPushPass(ctx context.Context, clock func() time.Time) error |
| rows, err := s.store.dueMailEventDeliveriesFor(ctx, h.Account, h.App, start, mailPushPerApp) |
| if err != nil { |
| log.Printf("console: mail push: reading the queue for %s/%s: %v", h.Account, h.App, err) |
| + jobFailed(ctx, fmt.Errorf("mail push: reading the queue for %s/%s: %w", h.Account, h.App, err)) |
| continue |
| } |
| if len(rows) == 0 { |
| if err := s.store.clearMailEventFailing(ctx, h); err != nil { |
| log.Printf("console: mail push: %s/%s: %v", h.Account, h.App, err) |
| + jobFailed(ctx, fmt.Errorf("mail push: %s/%s: %w", h.Account, h.App, err)) |
| } |
| continue |
| } |
| @@ -806,6 +809,7 @@ func (s *Server) deliverAppMailEvents(ctx context.Context, h mailEventHookRow, r |
| } |
| if err != nil { |
| log.Printf("console: mail push: %s/%s: %v", h.Account, h.App, err) |
| + jobFailed(ctx, fmt.Errorf("mail push: %s/%s: %w", h.Account, h.App, err)) |
| } |
| } |
| @@ -822,6 +826,7 @@ func (s *Server) deliverAppMailEventsHeld(ctx context.Context, h mailEventHookRo |
| if err := s.store.abandonMailEventDeliveries(ctx, h.Account, h.App, "the app is not live", clock()); err != nil { |
| result = errors.Join(result, err) |
| log.Printf("console: mail push: giving up on %s/%s: %v", h.Account, h.App, err) |
| + jobFailed(ctx, fmt.Errorf("mail push: giving up on %s/%s: %w", h.Account, h.App, err)) |
| } |
| return result |
| } |
| @@ -835,12 +840,14 @@ func (s *Server) deliverAppMailEventsHeld(ctx context.Context, h mailEventHookRo |
| if err := s.store.abandonMailEventDeliveries(ctx, d.Account, d.App, why, clock()); err != nil { |
| result = errors.Join(result, err) |
| log.Printf("console: mail push: giving up on %s/%s: %v", d.Account, d.App, err) |
| + jobFailed(ctx, fmt.Errorf("mail push: giving up on %s/%s: %w", d.Account, d.App, err)) |
| } |
| return result |
| } |
| if err := s.store.recordMailEventAttempt(ctx, d, status, why, clock()); err != nil { |
| result = errors.Join(result, err) |
| log.Printf("console: mail push: recording delivery %d for %s/%s: %v", d.ID, d.Account, d.App, err) |
| + jobFailed(ctx, fmt.Errorf("mail push: recording delivery %d for %s/%s: %w", d.ID, d.Account, d.App, err)) |
| } |
| if s.cfg.HostClaim && status == 0 && why != "" { |
| result = errors.Join(result, errors.New(why)) |
| @@ -855,6 +862,7 @@ func (s *Server) deliverAppMailEventsHeld(ctx context.Context, h mailEventHookRo |
| if err != nil { |
| result = errors.Join(result, err) |
| log.Printf("console: mail push: noting the turn for %s/%s: %v", h.Account, h.App, err) |
| + jobFailed(ctx, fmt.Errorf("mail push: noting the turn for %s/%s: %w", h.Account, h.App, err)) |
| } |
| if suspended { |
| log.Printf("console: mail push: suspended %s/%s โ nothing accepted for %s", h.Account, h.App, mailPushSuspendAfter) |
diff --git a/internal/console/plangracepass.go b/internal/console/plangracepass.go| index fc473f93a..11d958505 100644 |
| --- a/internal/console/plangracepass.go |
| +++ b/internal/console/plangracepass.go |
| @@ -29,7 +29,7 @@ func (s *Server) StartPlanGracePass(ctx context.Context) { |
| t := time.NewTicker(planGracePassInterval) |
| defer t.Stop() |
| for { |
| - s.planGracePass(ctx, time.Now()) |
| + _ = s.jobs.Run(ctx, "StartPlanGracePass", func(ctx context.Context) error { s.planGracePass(ctx, time.Now()); return nil }) |
| select { |
| case <-ctx.Done(): |
| return |
| @@ -47,6 +47,7 @@ func (s *Server) planGracePass(ctx context.Context, now time.Time) { |
| accts, err := s.store.Accounts() |
| if err != nil { |
| log.Printf("console: plan grace: accounts: %v", err) |
| + jobFailed(ctx, fmt.Errorf("plan grace: accounts: %w", err)) |
| return |
| } |
| for i := range accts { |
| @@ -55,6 +56,7 @@ func (s *Server) planGracePass(ctx context.Context, now time.Time) { |
| } |
| if err := s.planGraceAccount(ctx, &accts[i], now); err != nil { |
| log.Printf("console: plan grace %s: %v", accts[i].Sqid, err) |
| + jobFailed(ctx, fmt.Errorf("plan grace %s: %w", accts[i].Sqid, err)) |
| } |
| } |
| } |
| @@ -124,10 +126,12 @@ func (s *Server) planGraceAccountLocked(ctx context.Context, acct *Account, now |
| if c == capStorage { |
| if err := s.convergeStorageDeny(ctx, acct, st, true, now); err != nil { |
| log.Printf("console: plan grace %s: storage stage: %v", acct.Sqid, err) |
| + jobFailed(ctx, fmt.Errorf("plan grace %s: storage stage: %w", acct.Sqid, err)) |
| } |
| } |
| case errs[c] != nil: |
| log.Printf("console: plan grace %s: %s: %v (row kept)", acct.Sqid, c, errs[c]) |
| + jobFailed(ctx, fmt.Errorf("plan grace %s: %s: %w (row kept)", acct.Sqid, c, errs[c])) |
| if p := byCap[c]; p != nil { |
| states = append(states, *p) |
| } |
| @@ -148,11 +152,13 @@ func (s *Server) planGraceAccountLocked(ctx context.Context, acct *Account, now |
| } |
| if err := s.convergeThrottle(ctx, acct, byState, measuredCaps, offeredCaps, now); err != nil { |
| log.Printf("console: plan grace %s: throttle: %v", acct.Sqid, err) |
| + jobFailed(ctx, fmt.Errorf("plan grace %s: throttle: %w", acct.Sqid, err)) |
| } |
| if _, measured := measures[capStorage]; !measured && errs[capStorage] == nil { |
| // The plan sets no storage limit: nothing can be over it. |
| if err := s.clearStorageDeny(ctx, acct, now); err != nil { |
| log.Printf("console: plan grace %s: storage clear: %v", acct.Sqid, err) |
| + jobFailed(ctx, fmt.Errorf("plan grace %s: storage clear: %w", acct.Sqid, err)) |
| } |
| } |
| if s.lapseBeforeConverge != nil { |
| @@ -162,15 +168,18 @@ func (s *Server) planGraceAccountLocked(ctx context.Context, acct *Account, now |
| case eligible && inv != nil: |
| if err := s.convergeLapse(ctx, acct, row, l, byState, inv, now); err != nil { |
| log.Printf("console: plan grace %s: lapse: %v", acct.Sqid, err) |
| + jobFailed(ctx, fmt.Errorf("plan grace %s: lapse: %w", acct.Sqid, err)) |
| } |
| case !eligible: |
| if err := s.clearLapseOff(ctx, acct, row, now); err != nil { |
| log.Printf("console: plan grace %s: lapse clear: %v", acct.Sqid, err) |
| + jobFailed(ctx, fmt.Errorf("plan grace %s: lapse clear: %w", acct.Sqid, err)) |
| } |
| } |
| if s.cfg.MailProvisioner != nil { |
| if err := s.resumePlanMail(ctx, acct, now); err != nil { |
| log.Printf("console: plan grace %s: mail resume: %v", acct.Sqid, err) |
| + jobFailed(ctx, fmt.Errorf("plan grace %s: mail resume: %w", acct.Sqid, err)) |
| } |
| } |
| return s.notifyPlanOwners(ctx, acct, states, now) |
| @@ -228,6 +237,7 @@ func (s *Server) notifyPlanOwners(ctx context.Context, acct *Account, states []c |
| cancel() |
| if err != nil { |
| log.Printf("console: plan grace %s: notice to %s: %v", acct.Sqid, m.Name, err) |
| + jobFailed(ctx, fmt.Errorf("plan grace %s: notice to %s: %w", acct.Sqid, m.Name, err)) |
| continue |
| } |
| delivered = true |
diff --git a/internal/console/planlimits.go b/internal/console/planlimits.go| index d3808f839..f0073c1a1 100644 |
| --- a/internal/console/planlimits.go |
| +++ b/internal/console/planlimits.go |
| @@ -3,6 +3,7 @@ package console |
| import ( |
| "context" |
| "errors" |
| + "fmt" |
| "log" |
| "time" |
| @@ -26,7 +27,7 @@ func (s *Server) StartPlanLimitsPass(ctx context.Context) { |
| t := time.NewTicker(planLimitsPassInterval) |
| defer t.Stop() |
| for { |
| - s.planLimitsPass(ctx, time.Now()) |
| + _ = s.jobs.Run(ctx, "StartPlanLimitsPass", func(ctx context.Context) error { s.planLimitsPass(ctx, time.Now()); return nil }) |
| select { |
| case <-ctx.Done(): |
| return |
| @@ -45,6 +46,7 @@ func (s *Server) planLimitsPass(ctx context.Context, now time.Time) { |
| } |
| if _, err := s.store.EnsureDefaultPlans(cat.DefaultPlan, now); err != nil { |
| log.Printf("console: plan limits: default plans: %v", err) |
| + jobFailed(ctx, fmt.Errorf("plan limits: default plans: %w", err)) |
| return |
| } |
| // Page by account id: a row that cannot be published (an orphaned |
| @@ -54,6 +56,7 @@ func (s *Server) planLimitsPass(ctx context.Context, now time.Time) { |
| rows, err := s.store.PlansToPublish(cat.ID(), after, planLimitsPassBatch) |
| if err != nil { |
| log.Printf("console: plan limits: list: %v", err) |
| + jobFailed(ctx, fmt.Errorf("plan limits: list: %w", err)) |
| return |
| } |
| for _, row := range rows { |
| @@ -62,6 +65,7 @@ func (s *Server) planLimitsPass(ctx context.Context, now time.Time) { |
| } |
| if err := s.publishAccountLimits(ctx, row, now); err != nil { |
| log.Printf("console: plan limits: %s: %v", row.Sqid, err) |
| + jobFailed(ctx, fmt.Errorf("plan limits: %s: %w", row.Sqid, err)) |
| } |
| after = row.AccountID |
| } |
diff --git a/internal/console/plansmarker.go b/internal/console/plansmarker.go| index 4493771bd..51603b7b2 100644 |
| --- a/internal/console/plansmarker.go |
| +++ b/internal/console/plansmarker.go |
| @@ -2,6 +2,8 @@ package console |
| import ( |
| "context" |
| + "errors" |
| + "fmt" |
| "log" |
| "time" |
| @@ -28,7 +30,7 @@ func (s *Server) PublishPlansMarker(ctx context.Context) { |
| // boxes applying limits after the catalog was removed, or never applying |
| // them after it was added (Astra plans-2 finding 1). |
| wait := plansMarkerRetry |
| - for !s.publishPlansMarkerOnce(ctx) { |
| + for !s.publishPlansMarkerAttempt(ctx) { |
| select { |
| case <-ctx.Done(): |
| return |
| @@ -38,12 +40,29 @@ func (s *Server) PublishPlansMarker(ctx context.Context) { |
| } |
| } |
| +// errPlansMarkerNotPublished is a failed attempt's note when the attempt |
| +// recorded no more specific error. |
| +var errPlansMarkerNotPublished = errors.New("plans marker not published") |
| + |
| +// publishPlansMarkerAttempt is one attempt as a run of the job. |
| +func (s *Server) publishPlansMarkerAttempt(ctx context.Context) bool { |
| + ok := false |
| + _ = s.jobs.Run(ctx, "PublishPlansMarker", func(ctx context.Context) error { |
| + if ok = s.publishPlansMarkerOnce(ctx); !ok { |
| + jobFailed(ctx, errPlansMarkerNotPublished) |
| + } |
| + return nil |
| + }) |
| + return ok |
| +} |
| + |
| // publishPlansMarkerOnce makes one attempt and reports whether the marker is |
| // now as it should be (including "nothing to do"). |
| func (s *Server) publishPlansMarkerOnce(ctx context.Context) bool { |
| cur, etag, err := plans.GetMarker(ctx, s.cfg.Releases) |
| if err != nil { |
| log.Printf("console: plans marker: read: %v", err) |
| + jobFailed(ctx, fmt.Errorf("plans marker: read: %w", err)) |
| return false |
| } |
| want := plans.Marker{UpdatedAt: time.Now().UTC().Truncate(time.Second)} |
| @@ -57,6 +76,7 @@ func (s *Server) publishPlansMarkerOnce(ctx context.Context) bool { |
| } |
| if _, err := plans.PutMarker(ctx, s.cfg.Releases, &want, etag); err != nil { |
| log.Printf("console: plans marker: write: %v", err) |
| + jobFailed(ctx, fmt.Errorf("plans marker: write: %w", err)) |
| return false |
| } |
| return true |
diff --git a/internal/console/regiondrift.go b/internal/console/regiondrift.go| index 8e2d2d372..65afa808a 100644 |
| --- a/internal/console/regiondrift.go |
| +++ b/internal/console/regiondrift.go |
| @@ -2,6 +2,7 @@ package console |
| import ( |
| "context" |
| + "fmt" |
| "log" |
| "time" |
| ) |
| @@ -25,7 +26,10 @@ const discrepancyScanCap = 10000 |
| // lifetimesWatchInterval while the console is still starting. |
| func (s *Server) LogPlacementDiscrepancies(ctx context.Context) { |
| for !s.lifetimesIteration(ctx, "placement check", false, false, func(ctx context.Context) { |
| - s.logPlacementDiscrepancies(ctx, discrepancyScanCap) |
| + _ = s.jobs.Run(ctx, "LogPlacementDiscrepancies", func(ctx context.Context) error { |
| + s.logPlacementDiscrepancies(ctx, discrepancyScanCap) |
| + return nil |
| + }) |
| }) { |
| select { |
| case <-ctx.Done(): |
| @@ -42,12 +46,14 @@ func (s *Server) logPlacementDiscrepancies(ctx context.Context, scanCap int) { |
| apps, err := s.store.NonHomeAppRegions() |
| if err != nil { |
| log.Printf("console: placement discrepancy check: %v", err) |
| + jobFailed(ctx, fmt.Errorf("placement discrepancy check: %w", err)) |
| return |
| } |
| for _, a := range apps { |
| recs, truncated, err := s.listRecords(ctx, a.Sqid, a.App, scanCap) |
| if err != nil { |
| log.Printf("console: placement discrepancy check %s/%s: %v", a.Sqid, a.App, err) |
| + jobFailed(ctx, fmt.Errorf("placement discrepancy check %s/%s: %w", a.Sqid, a.App, err)) |
| continue |
| } |
| if truncated { |
diff --git a/internal/console/relayops.go b/internal/console/relayops.go| index e17c119f0..6f7d5f5ff 100644 |
| --- a/internal/console/relayops.go |
| +++ b/internal/console/relayops.go |
| @@ -284,7 +284,7 @@ func (s *Server) StartRelay(ctx context.Context) { |
| defer t.Stop() |
| for { |
| if s.relayHold() { |
| - if err := s.relayReconcile(ctx); err != nil { |
| + if err := s.jobs.Run(ctx, "StartRelay", s.relayReconcile); err != nil { |
| log.Printf("console: relay reconcile: %v", err) |
| } |
| } |
| @@ -686,6 +686,7 @@ func (s *Server) relayListRecords(ctx context.Context) ([]relayAppRecord, error) |
| rec, etag, err := relay.GetRecord(ctx, s.cfg.Releases, acct, app) |
| if err != nil { |
| log.Printf("console: relay record %s/%s: %v", acct, app, err) |
| + jobFailed(ctx, fmt.Errorf("relay record %s/%s: %w", acct, app, err)) |
| continue |
| } |
| if rec == nil { |
| @@ -770,6 +771,7 @@ func (s *Server) relayPublishAggregate(ctx context.Context) error { |
| if err == nil { |
| if err := release.BumpSerial(ctx, s.cfg.Releases, s.relayTime()); err != nil { |
| log.Printf("console: relay serial bump (relays converge on their own timer anyway): %v", err) |
| + jobFailed(ctx, fmt.Errorf("relay serial bump (relays converge on their own timer anyway): %w", err)) |
| } |
| return nil |
| } |
| @@ -1487,6 +1489,7 @@ func (s *Server) relayReconcile(ctx context.Context) error { |
| etag, changed, err := s.relayConverge(ctx, r) |
| if err != nil { |
| log.Printf("console: relay reconcile %s/%s: %v", r.Account, r.App, err) |
| + jobFailed(ctx, fmt.Errorf("relay reconcile %s/%s: %w", r.Account, r.App, err)) |
| continue |
| } |
| if changed { |
| @@ -1499,6 +1502,7 @@ func (s *Server) relayReconcile(ctx context.Context) error { |
| for _, p := range advanced { |
| if err := s.relayMarkDone(ctx, p.rec, p.etag); err != nil { |
| log.Printf("console: relay reconcile %s/%s: marking done: %v", p.rec.Account, p.rec.App, err) |
| + jobFailed(ctx, fmt.Errorf("relay reconcile %s/%s: marking done: %w", p.rec.Account, p.rec.App, err)) |
| } |
| } |
| return nil |
diff --git a/internal/console/runsweep.go b/internal/console/runsweep.go| index c9fbdbc8c..9bd9bde9b 100644 |
| --- a/internal/console/runsweep.go |
| +++ b/internal/console/runsweep.go |
| @@ -1,8 +1,10 @@ |
| package console |
| import ( |
| + "cmp" |
| "context" |
| "errors" |
| + "fmt" |
| "log" |
| "os" |
| "strings" |
| @@ -46,7 +48,10 @@ func (s *Server) StartRunSweep(ctx context.Context) { |
| // Each pass is a unit of record work (lifetimes_cutover.go). The |
| // housekeeping count advances only on a pass that ran. |
| if s.lifetimesIteration(ctx, "run sweep", true, false, func(ctx context.Context) { |
| - s.runSweepPass(ctx, time.Now(), pass%runSweepHousekeepingEvery == 0) |
| + _ = s.jobs.Run(ctx, "StartRunSweep", func(ctx context.Context) error { |
| + s.runSweepPass(ctx, time.Now(), pass%runSweepHousekeepingEvery == 0) |
| + return nil |
| + }) |
| }) { |
| pass++ |
| } |
| @@ -82,6 +87,7 @@ func (s *Server) runSweepPass(ctx context.Context, now time.Time, housekeeping b |
| recs, complete, err := provision.ListAllRecordsTolerantJudged(ctx, src, provision.JudgeFrom(ctx)) |
| if err != nil { |
| log.Printf("console: run sweep: list records: %v", err) |
| + jobFailed(ctx, fmt.Errorf("run sweep: list records: %w", err)) |
| return |
| } |
| if !complete { |
| @@ -103,6 +109,7 @@ func (s *Server) runSweepPass(ctx context.Context, now time.Time, housekeeping b |
| acct, err := s.store.AccountBySqid(rec.Account) |
| if err != nil { |
| log.Printf("console: run sweep: account %s: %v", rec.Account, err) |
| + jobFailed(ctx, fmt.Errorf("run sweep: account %s: %w", rec.Account, err)) |
| continue |
| } |
| if acct == nil { |
| @@ -121,7 +128,7 @@ func (s *Server) runSweepPass(ctx context.Context, now time.Time, housekeeping b |
| if !housekeeping || !complete { |
| return |
| } |
| - candidates, full := s.orphanCandidates(apps, now) |
| + candidates, full := s.orphanCandidates(ctx, apps, now) |
| for app := range candidates { |
| if ctx.Err() != nil { |
| log.Printf("console: run sweep: pass cut short: %v", ctx.Err()) |
| @@ -143,13 +150,14 @@ func (s *Server) runSweepPass(ctx context.Context, now time.Time, housekeeping b |
| // failed read of the rows. Orphans are still found by age, not by index |
| // movement: runs/ is outside every scope. The narrowed set is always a |
| // subset of apps, so it never lists an app the full sweep would not. |
| -func (s *Server) orphanCandidates(apps map[[2]string]bool, now time.Time) (map[[2]string]bool, bool) { |
| +func (s *Server) orphanCandidates(ctx context.Context, apps map[[2]string]bool, now time.Time) (map[[2]string]bool, bool) { |
| if s.recordView == nil || s.lastOrphanFull.IsZero() || now.Sub(s.lastOrphanFull) >= orphanFullSweepEvery { |
| return apps, true |
| } |
| recent, err := s.store.AppsWithActionSince("run-start", now.Add(-orphanCandidateWindow)) |
| if err != nil { |
| log.Printf("console: run sweep: recent runs: %v (every app's runs are swept this pass)", err) |
| + jobFailed(ctx, fmt.Errorf("run sweep: recent runs: %w (every app's runs are swept this pass)", err)) |
| return apps, true |
| } |
| out := map[[2]string]bool{} |
| @@ -172,12 +180,14 @@ func (s *Server) sweepExpireQueued(ctx context.Context, c runCall) { |
| if _, err := provision.SetRecordRun(ctx, s.cfg.Releases, c.acct.Sqid, c.app, c.host, provision.RunExpire(c.id)); err != nil { |
| if !errors.Is(err, provision.ErrRunConflict) && !errors.Is(err, os.ErrNotExist) { |
| log.Printf("console: run sweep: %s %s: expire: %v", c.host, c.id, err) |
| + jobFailed(ctx, fmt.Errorf("run sweep: %s %s: expire: %w", c.host, c.id, err)) |
| } |
| return |
| } |
| if err := s.endUnpicked(ctx, c, provision.RunExpired); err != nil { |
| // The record says expired; the next sweep finds the missing result. |
| log.Printf("console: run sweep: %s %s: end after expire: %v", c.host, c.id, err) |
| + jobFailed(ctx, fmt.Errorf("run sweep: %s %s: end after expire: %w", c.host, c.id, err)) |
| } |
| } |
| @@ -193,16 +203,19 @@ func (s *Server) sweepLostRun(ctx context.Context, c runCall, r *provision.RunSt |
| last, err := runs.LastChunkSeq(ctx, rel, c.acct.Sqid, c.app, c.id) |
| if err != nil { |
| log.Printf("console: run sweep: %s %s: list chunks: %v", c.host, c.id, err) |
| + jobFailed(ctx, fmt.Errorf("run sweep: %s %s: list chunks: %w", c.host, c.id, err)) |
| return |
| } |
| lost := runs.Result{Interrupted: runs.InterruptedLost, Box: r.Box, LastSeq: last, Ended: now.UTC()} |
| if err := runs.WriteResult(ctx, rel, c.acct.Sqid, c.app, c.id, lost); err != nil { |
| log.Printf("console: run sweep: %s %s: lost result: %v", c.host, c.id, err) |
| + jobFailed(ctx, fmt.Errorf("run sweep: %s %s: lost result: %w", c.host, c.id, err)) |
| return |
| } |
| if _, err := provision.SetRecordRun(ctx, rel, c.acct.Sqid, c.app, c.host, provision.RunFinish(c.id)); err != nil { |
| if !errors.Is(err, provision.ErrRunConflict) && !errors.Is(err, os.ErrNotExist) { |
| log.Printf("console: run sweep: %s %s: finish: %v", c.host, c.id, err) |
| + jobFailed(ctx, fmt.Errorf("run sweep: %s %s: finish: %w", c.host, c.id, err)) |
| } |
| return |
| } |
| @@ -238,6 +251,7 @@ func (s *Server) sweepTerminalRun(ctx context.Context, c runCall, r *provision.R |
| if _, err := runs.ReadRequest(ctx, rel, c.acct.Sqid, c.app, c.id); err == nil { |
| if err := s.endUnpicked(ctx, c, r.State); err != nil { |
| log.Printf("console: run sweep: %s %s: end %s run: %v", c.host, c.id, r.State, err) |
| + jobFailed(ctx, fmt.Errorf("run sweep: %s %s: end %s run: %w", c.host, c.id, r.State, err)) |
| } |
| return |
| } |
| @@ -255,11 +269,13 @@ func (s *Server) sweepTerminalRun(ctx context.Context, c runCall, r *provision.R |
| if _, err := provision.SetRecordRun(ctx, rel, c.acct.Sqid, c.app, c.host, provision.RunClear(c.id)); err != nil { |
| if !errors.Is(err, provision.ErrRunConflict) && !errors.Is(err, os.ErrNotExist) { |
| log.Printf("console: run sweep: %s %s: clear: %v", c.host, c.id, err) |
| + jobFailed(ctx, fmt.Errorf("run sweep: %s %s: clear: %w", c.host, c.id, err)) |
| } |
| return |
| } |
| if err := runs.DeleteRun(ctx, rel, c.acct.Sqid, c.app, c.id); err != nil { |
| log.Printf("console: run sweep: %s %s: delete: %v", c.host, c.id, err) |
| + jobFailed(ctx, fmt.Errorf("run sweep: %s %s: delete: %w", c.host, c.id, err)) |
| } |
| } |
| @@ -300,6 +316,7 @@ func (s *Server) sweepOrphanRuns(ctx context.Context, acct, app string, named ma |
| if !accountRead { |
| if account, err = s.store.AccountBySqid(acct); err != nil { |
| log.Printf("console: run sweep: account %s: %v", acct, err) |
| + jobFailed(ctx, fmt.Errorf("run sweep: account %s: %w", acct, err)) |
| return // no run of it is deleted before its row can be written |
| } |
| accountRead = true |
| @@ -316,6 +333,7 @@ func (s *Server) sweepOrphanRuns(ctx context.Context, acct, app string, named ma |
| } |
| if err := runs.DeleteRun(ctx, rel, acct, app, id); err != nil { |
| log.Printf("console: run sweep: %s/%s %s: delete orphan: %v", acct, app, id, err) |
| + jobFailed(ctx, fmt.Errorf("run sweep: %s/%s %s: delete orphan: %w", acct, app, id, err)) |
| } |
| } |
| } |
| @@ -334,6 +352,7 @@ func (s *Server) orphanConfirmed(ctx context.Context, acct, app, host, id string |
| return true |
| case err != nil: |
| log.Printf("console: run sweep: %s/%s %s: re-read the owning record %s: %v (kept this pass)", acct, app, id, host, err) |
| + jobFailed(ctx, fmt.Errorf("run sweep: %s/%s %s: re-read the owning record %s: %w (kept this pass)", acct, app, id, host, err)) |
| return false |
| } |
| return rec.ActiveRun == nil || rec.ActiveRun.ID != id |
| @@ -352,21 +371,25 @@ func (s *Server) orphanRunEnd(ctx context.Context, acct *Account, app, host, id |
| res, err := runs.ReadResult(ctx, rel, acct.Sqid, app, id) |
| if err != nil { |
| log.Printf("console: run sweep: %s/%s %s: read orphan result: %v", acct.Sqid, app, id, err) |
| + jobFailed(ctx, fmt.Errorf("run sweep: %s/%s %s: read orphan result: %w", acct.Sqid, app, id, err)) |
| return false |
| } |
| if res == nil { |
| last, err := runs.LastChunkSeq(ctx, rel, acct.Sqid, app, id) |
| if err != nil { |
| log.Printf("console: run sweep: %s/%s %s: list orphan chunks: %v", acct.Sqid, app, id, err) |
| + jobFailed(ctx, fmt.Errorf("run sweep: %s/%s %s: list orphan chunks: %w", acct.Sqid, app, id, err)) |
| return false |
| } |
| lost := runs.Result{Interrupted: runs.InterruptedLost, LastSeq: last, Ended: now.UTC()} |
| if err := runs.WriteResult(ctx, rel, acct.Sqid, app, id, lost); err != nil { |
| log.Printf("console: run sweep: %s/%s %s: orphan lost result: %v", acct.Sqid, app, id, err) |
| + jobFailed(ctx, fmt.Errorf("run sweep: %s/%s %s: orphan lost result: %w", acct.Sqid, app, id, err)) |
| return false |
| } |
| if res, err = runs.ReadResult(ctx, rel, acct.Sqid, app, id); err != nil || res == nil { |
| log.Printf("console: run sweep: %s/%s %s: read orphan result back: %v", acct.Sqid, app, id, err) |
| + jobFailed(ctx, fmt.Errorf("run sweep: %s/%s %s: read orphan result back: %w", acct.Sqid, app, id, cmp.Or(err, os.ErrNotExist))) |
| return false |
| } |
| } |
| @@ -375,6 +398,7 @@ func (s *Server) orphanRunEnd(ctx context.Context, acct *Account, app, host, id |
| // bucket refused leaves the run for the next pass. |
| if _, _, err := rel.Get(ctx, runs.AuditedKey(acct.Sqid, app, id)); err != nil { |
| log.Printf("console: run sweep: %s/%s %s: no audit marker yet, delete left for a later pass: %v", acct.Sqid, app, id, err) |
| + jobFailed(ctx, fmt.Errorf("run sweep: %s/%s %s: no audit marker yet, delete left for a later pass: %w", acct.Sqid, app, id, err)) |
| return false |
| } |
| return true |
diff --git a/internal/console/scandrain.go b/internal/console/scandrain.go| index d19440978..62d119b6f 100644 |
| --- a/internal/console/scandrain.go |
| +++ b/internal/console/scandrain.go |
| @@ -16,6 +16,7 @@ package console |
| import ( |
| "context" |
| "errors" |
| + "fmt" |
| "log" |
| "strings" |
| "sync" |
| @@ -58,32 +59,21 @@ func (s *Server) StartScanDrain(ctx context.Context) { |
| s.scanDelivery.stop() |
| s.scanDelivery = nil |
| }() |
| - rebuilt := true |
| - if err := s.rebuildScanQueue(ctx); err != nil { |
| - rebuilt = false |
| + st := &scanDrainState{rebuilt: true} |
| + if err := s.jobs.Run(ctx, "StartScanDrain", s.rebuildScanQueue); err != nil { |
| + st.rebuilt, st.rebuildErr = false, err |
| // Not fatal. A console that cannot rebuild still drains what it is |
| // told about from here on, and the next restart tries again; refusing |
| // to start the goroutine would turn a listing hiccup into an outage |
| // of the whole on-demand path. |
| log.Printf("console: scan queue rebuild: %v", err) |
| } |
| - rebuildDelay := scanDrainInterval |
| - nextRebuild := time.Now().Add(rebuildDelay) |
| + st.rebuildDelay = scanDrainInterval |
| + st.nextRebuild = time.Now().Add(st.rebuildDelay) |
| t := time.NewTicker(scanDrainInterval) |
| defer t.Stop() |
| for { |
| - // Retry failed discovery with backoff. An app held by another owner |
| - // must not cause a deployment-wide enumeration on every drain tick. |
| - if !rebuilt && !time.Now().Before(nextRebuild) { |
| - if err := s.rebuildScanQueue(ctx); err != nil { |
| - log.Printf("console: scan queue rebuild (retry): %v", err) |
| - rebuildDelay = min(rebuildDelay*2, 5*time.Minute) |
| - nextRebuild = time.Now().Add(rebuildDelay) |
| - } else { |
| - rebuilt = true |
| - } |
| - } |
| - if err := s.scanDrainTick(ctx); err != nil { |
| + if err := s.jobs.Run(ctx, "StartScanDrain", func(ctx context.Context) error { return s.scanDrainStep(ctx, st) }); err != nil { |
| log.Printf("console: scan drain: %v", err) |
| } |
| select { |
| @@ -94,6 +84,39 @@ func (s *Server) StartScanDrain(ctx context.Context) { |
| } |
| } |
| +// scanDrainState is StartScanDrain's memory between ticks: whether the |
| +// queue index has been rebuilt since start, the last rebuild failure, and |
| +// the retry backoff. |
| +type scanDrainState struct { |
| + rebuilt bool |
| + rebuildErr error |
| + rebuildDelay time.Duration |
| + nextRebuild time.Time |
| +} |
| + |
| +// scanDrainStep is one drain tick, retrying a failed rebuild first when its |
| +// backoff is due: an app held by another owner must not cause a |
| +// deployment-wide enumeration on every drain tick. Until a rebuild |
| +// succeeds, every tick's run is Failed with the last rebuild error, since |
| +// the drain then serves only the apps this process has heard from. |
| +func (s *Server) scanDrainStep(ctx context.Context, st *scanDrainState) error { |
| + if !st.rebuilt && !time.Now().Before(st.nextRebuild) { |
| + if err := s.rebuildScanQueue(ctx); err != nil { |
| + log.Printf("console: scan queue rebuild (retry): %v", err) |
| + jobFailed(ctx, fmt.Errorf("scan queue rebuild: %w", err)) |
| + st.rebuildErr = err |
| + st.rebuildDelay = min(st.rebuildDelay*2, 5*time.Minute) |
| + st.nextRebuild = time.Now().Add(st.rebuildDelay) |
| + } else { |
| + st.rebuilt, st.rebuildErr = true, nil |
| + } |
| + } |
| + if !st.rebuilt { |
| + jobFailed(ctx, fmt.Errorf("scan queue rebuild: %w", st.rebuildErr)) |
| + } |
| + return s.scanDrainTick(ctx) |
| +} |
| + |
| // rebuildScanQueue is the one full enumeration (ยง7.1): every app on the |
| // deployment, so that an item stranded by a crash between the object write and |
| // the index bump is found, and everything past its TTL is collected. |
| @@ -119,6 +142,7 @@ func (s *Server) rebuildScanQueue(ctx context.Context) error { |
| appPrefixes, err := s.cfg.Releases.ListDirs(ctx, acctPrefix) |
| if err != nil { |
| log.Printf("console: scan queue rebuild: %s: %v", acct, err) |
| + jobFailed(ctx, fmt.Errorf("scan queue rebuild: %s: %w", acct, err)) |
| errs = append(errs, err) |
| continue |
| } |
| @@ -129,6 +153,7 @@ func (s *Server) rebuildScanQueue(ctx context.Context) error { |
| app := strings.TrimSuffix(strings.TrimPrefix(appPrefix, acctPrefix), "/") |
| if _, err := objstore.RebuildQueue(ctx, s.cfg.Releases, s.scanQueue, acct, app, now); err != nil { |
| log.Printf("console: scan queue rebuild: %s/%s: %v", acct, app, err) |
| + jobFailed(ctx, fmt.Errorf("scan queue rebuild: %s/%s: %w", acct, app, err)) |
| errs = append(errs, err) |
| } |
| // The fallback results are collected in the SAME pass, because |
| @@ -251,6 +276,7 @@ func (s *Server) drainScanApp(ctx context.Context, ref objstore.AppRef, now time |
| // items stay; the next enabled tick has them. |
| default: |
| log.Printf("console: scan drain: %s/%s: %v", ref.Account, ref.App, err) |
| + jobFailed(ctx, fmt.Errorf("scan drain: %s/%s: %w", ref.Account, ref.App, err)) |
| } |
| cleanupCtx, cleanupCancel := context.WithTimeout(parent, storeTimeout) |
| defer cleanupCancel() |
| @@ -273,6 +299,7 @@ func (s *Server) collectScanResults(ctx context.Context, acct, app string, now t |
| // its own optional interface the same way. |
| case err != nil: |
| log.Printf("console: scan result collect: %s/%s: %v", acct, app, err) |
| + jobFailed(ctx, fmt.Errorf("scan result collect: %s/%s: %w", acct, app, err)) |
| case n > 0: |
| log.Printf("console: scan result collect: %s/%s: dropped %d expired result(s)", acct, app, n) |
| } |
diff --git a/internal/console/scanpass.go b/internal/console/scanpass.go| index 4c54cc3e8..0638639d5 100644 |
| --- a/internal/console/scanpass.go |
| +++ b/internal/console/scanpass.go |
| @@ -13,6 +13,7 @@ package console |
| import ( |
| "context" |
| "errors" |
| + "fmt" |
| "log" |
| "strings" |
| "time" |
| @@ -41,7 +42,7 @@ func (s *Server) StartScanPass(ctx context.Context) { |
| t := time.NewTicker(scanPassInterval) |
| defer t.Stop() |
| for { |
| - if err := s.scanPass(ctx); err != nil { |
| + if err := s.jobs.Run(ctx, "StartScanPass", s.scanPass); err != nil { |
| log.Printf("console: scan pass: %v", err) |
| } |
| select { |
| @@ -169,6 +170,7 @@ func (s *Server) scanPass(ctx context.Context) error { |
| app := strings.TrimSuffix(strings.TrimPrefix(appPrefix, acctPrefix), "/") |
| if err := s.scanOneApp(ctx, acct, app, budget, interval); err != nil { |
| log.Printf("console: scan pass: %s/%s: %v", acct, app, err) |
| + jobFailed(ctx, fmt.Errorf("scan pass: %s/%s: %w", acct, app, err)) |
| } |
| } |
| } |
diff --git a/internal/console/seedsweep.go b/internal/console/seedsweep.go| index 52bc1d2db..61fa26107 100644 |
| --- a/internal/console/seedsweep.go |
| +++ b/internal/console/seedsweep.go |
| @@ -11,6 +11,7 @@ package console |
| import ( |
| "context" |
| "errors" |
| + "fmt" |
| "log" |
| "os" |
| "sort" |
| @@ -80,7 +81,9 @@ func (s *Server) StartSeedsPass(ctx context.Context) { |
| // admitted as a writer, skipped while the gate refuses it, and run in the |
| // mode it was admitted in. |
| func (s *Server) seedsIteration(ctx context.Context) { |
| - s.lifetimesIteration(ctx, "seeds pass", true, false, func(ctx context.Context) { s.seedsPass(ctx, time.Now()) }) |
| + s.lifetimesIteration(ctx, "seeds pass", true, false, func(ctx context.Context) { |
| + _ = s.jobs.Run(ctx, "StartSeedsPass", func(ctx context.Context) error { s.seedsPass(ctx, time.Now()); return nil }) |
| + }) |
| } |
| // seedStale reports a seed stuck where no box moves it: a --from seed |
| @@ -150,6 +153,7 @@ func (s *Server) seedsPass(ctx context.Context, now time.Time) { |
| var err error |
| if snaps, err = ml.ListMod(ctx, seeds.Prefix); err != nil { |
| log.Printf("console: seeds pass: list snapshots: %v (nothing swept this pass)", err) |
| + jobFailed(ctx, fmt.Errorf("seeds pass: list snapshots: %w (nothing swept this pass)", err)) |
| return |
| } |
| } |
| @@ -169,6 +173,7 @@ func (s *Server) seedsPass(ctx context.Context, now time.Time) { |
| recs, unreadable, err := provision.ListAllRecordsStrictJudged(ctx, src, provision.JudgeFrom(ctx)) |
| if err != nil { |
| log.Printf("console: seeds pass: list records: %v (nothing swept this pass)", err) |
| + jobFailed(ctx, fmt.Errorf("seeds pass: list records: %w (nothing swept this pass)", err)) |
| return |
| } |
| byHost := map[string][]provision.Record{} |
| @@ -237,6 +242,7 @@ func (s *Server) seedsPass(ctx context.Context, now time.Time) { |
| } |
| if err := s.cfg.SeedData.Delete(ctx, key); err != nil && !errors.Is(err, os.ErrNotExist) { |
| log.Printf("console: seeds pass: delete %s: %v", key, err) |
| + jobFailed(ctx, fmt.Errorf("seeds pass: delete %s: %w", key, err)) |
| continue |
| } |
| log.Printf("console: seeds pass: deleted %s", key) |
| @@ -252,6 +258,7 @@ func (s *Server) seedsPass(ctx context.Context, now time.Time) { |
| } |
| if err := s.finishSeed(ctx, rec.Account, rec.App, rec.Host, rec.Seed.ID); err != nil { |
| log.Printf("console: seeds pass: finish seed %s of %s: %v", rec.Seed.ID, rec.Host, err) |
| + jobFailed(ctx, fmt.Errorf("seeds pass: finish seed %s of %s: %w", rec.Seed.ID, rec.Host, err)) |
| } |
| } |
| } |
| @@ -322,6 +329,7 @@ func (s *Server) abandonSeed(ctx context.Context, rec provision.Record) bool { |
| if err != nil { |
| if !errors.Is(err, provision.ErrSeedConflict) { |
| log.Printf("console: seeds pass: abandon seed %s of %s: %v", seed.ID, rec.Host, err) |
| + jobFailed(ctx, fmt.Errorf("seeds pass: abandon seed %s of %s: %w", seed.ID, rec.Host, err)) |
| } |
| return false |
| } |
diff --git a/internal/console/server.go b/internal/console/server.go| index b3359807b..7a5daee52 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -948,6 +948,9 @@ type Server struct { |
| claimBackendObserver func(backendEvent) // fixture recorder only |
| claimEntries claimInventory |
| claimWorkers map[string]func(context.Context) |
| + // jobs is what each claim worker's runs last did (jobs.go), for the |
| + // operator pages. Made before registerClaimWorkers declares the workers. |
| + jobs *jobRegistry |
| // perf records every request but /healthz; handler is the mux wrapped |
| // in its middleware, and is what serveAdmitted serves (NewServer). |
| perf *perf.Recorder |
| @@ -1572,6 +1575,7 @@ func NewServer(cfg Config, st *Store) (*Server, error) { |
| } |
| km.SetSigningKey(key) |
| s := &Server{ |
| + jobs: newJobRegistry(time.Now), |
| cfg: cfg, |
| store: st, |
| km: km, |
| @@ -1953,7 +1957,7 @@ func (s *Server) StartGeoipJobs(ctx context.Context) { |
| go func() { defer wg.Done(); retryClearFeedStatus(ctx, s.cfg.Releases, 30*time.Second, 10*time.Minute) }() |
| } |
| for { |
| - s.geoipPass(ctx) |
| + _ = s.jobs.Run(ctx, "StartGeoipJobs", func(ctx context.Context) error { s.geoipPass(ctx); return nil }) |
| t := time.NewTimer(24*time.Hour + mrand.N(time.Hour)) |
| select { |
| case <-ctx.Done(): |
| @@ -1971,11 +1975,13 @@ func (s *Server) geoipPass(ctx context.Context) { |
| sctx, cancel := context.WithTimeout(ctx, 2*time.Minute) |
| if err := s.geoip.Sweep(sctx); err != nil { |
| log.Printf("console: geoip sweep: %v", err) |
| + jobFailed(ctx, fmt.Errorf("geoip sweep: %w", err)) |
| } |
| cancel() |
| ectx, cancel := context.WithTimeout(ctx, 2*time.Minute) |
| if _, err := s.geoip.ExpireIfDue(ectx, time.Now()); err != nil { |
| log.Printf("console: geoip expiry check: %v", err) |
| + jobFailed(ctx, fmt.Errorf("geoip expiry check: %w", err)) |
| } |
| cancel() |
| } |
diff --git a/internal/console/templates/opparts.html b/internal/console/templates/opparts.html| index ca95cb844..29ab36068 100644 |
| --- a/internal/console/templates/opparts.html |
| +++ b/internal/console/templates/opparts.html |
| @@ -79,3 +79,14 @@ |
| {{- end}} |
| {{- end}} |
| </nav>{{end}} |
| + |
| +{{/* jobs: the background jobs table (data []opJobRow), one row per |
| + configured job: its label, status pill, when its last run finished |
| + (the exact time as the title) and the first line of its last error. */}} |
| +{{define "op_jobs"}}<div rst-box-head id="jobs"><h2>Background jobs</h2></div> |
| +<div rst-card co-cols="jobs"> |
| + <div rst-lrow="head"><span>Job</span><span>Status</span><span>Last ran</span><span>Note</span></div> |
| + {{- range .}} |
| + <div rst-lrow><span>{{.Label}}</span><span>{{template "op_status" .Status}}</span>{{if .LastRan.IsZero}}<span>{{ago .LastRan}}</span>{{else}}<span title="{{fmtTime .LastRan}}">{{ago .LastRan}}</span>{{end}}<span>{{.Note}}</span></div> |
| + {{- end}} |
| +</div>{{end}} |