From baf3aeaa2716a72640925eca183f215904102397 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 21 Oct 2026 03:38:13 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20admin=20alerts=20for=20runn?= =?UTF-8?q?ers,=20backups,=20disk,=20killed=20jobs,=20self-update=20and=20?= =?UTF-8?q?replication?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.lock | 1 + config/forge.example.toml | 21 + .../migrations/0059_admin_alerts.sql | 25 + crates/forge-core/src/alerts.rs | 180 +++++ crates/forge-core/src/config.rs | 60 ++ crates/forge-core/src/lib.rs | 1 + crates/forge-core/src/server_settings.rs | 117 +++- crates/forge-core/src/store/admin_alerts.rs | 372 +++++++++++ crates/forge-core/src/store/migrate.rs | 1 + crates/forge-core/src/store/mod.rs | 1 + crates/forge-core/src/store/notifications.rs | 3 +- crates/forge-core/src/store/user_delete.rs | 1 + crates/forge-web/Cargo.toml | 1 + crates/forge-web/src/alerts.rs | 630 ++++++++++++++++++ crates/forge-web/src/backup/scheduler.rs | 9 + crates/forge-web/src/boot.rs | 1 + crates/forge-web/src/ci/api.rs | 8 +- crates/forge-web/src/ci/reaper.rs | 9 + crates/forge-web/src/i18n/admin.rs | 4 + crates/forge-web/src/i18n/alerts.rs | 238 +++++++ crates/forge-web/src/i18n/misc.rs | 8 + crates/forge-web/src/i18n/mod.rs | 1 + crates/forge-web/src/main.rs | 1 + crates/forge-web/src/pages/admin_health.rs | 57 +- crates/forge-web/src/pages/admin_server.rs | 1 + crates/forge-web/src/pages/notifications.rs | 119 +++- .../forge-web/src/pages/settings_security.rs | 1 + crates/forge-web/src/self_update.rs | 2 + crates/forge-web/src/test_support.rs | 1 + style/_account_admin.scss | 34 + style/main.scss | 8 +- 31 files changed, 1908 insertions(+), 8 deletions(-) create mode 100644 crates/forge-core/migrations/0059_admin_alerts.sql create mode 100644 crates/forge-core/src/alerts.rs create mode 100644 crates/forge-core/src/store/admin_alerts.rs create mode 100644 crates/forge-web/src/alerts.rs create mode 100644 crates/forge-web/src/i18n/alerts.rs diff --git a/Cargo.lock b/Cargo.lock index ec4d56f..8ae74e9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2101,6 +2101,7 @@ dependencies = [ "jiff", "lettre", "multer", + "nix 0.31.3", "object_store", "rand 0.10.3", "reqwest", diff --git a/config/forge.example.toml b/config/forge.example.toml index ddb9259..c8fef1e 100644 --- a/config/forge.example.toml +++ b/config/forge.example.toml @@ -164,3 +164,24 @@ trusted_proxies = [] # job = "build" # The artifact name produced by job. A single file. CI flattens paths, so dist/forge is stored as dist_forge. # artifact = "dist_forge" + +# Admin alerts. The site admins hear about trouble before it breaks: a silent CI runner, a failed +# or overdue backup, low disk space, a CI job killed for memory, a self-update, a lagging standby. +# Each is told once until it resolves. Delivered as an inbox row, an email, and a banner on /admin/health. +# All of these can also be changed live on /admin/server. +# [alerts] +# enabled = true +# Also email admins with a verified address. +# email = true +# Minutes without a heartbeat before a runner counts as offline. +# runner_offline_minutes = 10 +# Alert under this percent of free space in data_dir, or under disk_free_gib GiB (0 turns that off). +# disk_free_percent = 10 +# disk_free_gib = 0 +# Per-kind switches. +# on_runner_offline = true +# on_backup = true +# on_disk = true +# on_ci_killed = true +# on_self_update = true +# on_replication = true diff --git a/crates/forge-core/migrations/0059_admin_alerts.sql b/crates/forge-core/migrations/0059_admin_alerts.sql new file mode 100644 index 0000000..a7add3d --- /dev/null +++ b/crates/forge-core/migrations/0059_admin_alerts.sql @@ -0,0 +1,25 @@ +-- Admin alerts: one row per condition (`key`) that is active, resolved or a one-shot event, and +-- one inbox row per site admin and message. An alert is raised once until it resolves. +CREATE TABLE admin_alerts ( + key TEXT PRIMARY KEY, + kind TEXT NOT NULL, + subject TEXT NOT NULL DEFAULT '', + detail TEXT NOT NULL DEFAULT '', + state TEXT NOT NULL, + raised_at TEXT NOT NULL, + resolved_at TEXT NULL, + updated_at TEXT NOT NULL +); +CREATE INDEX admin_alerts_state ON admin_alerts (state, raised_at); +CREATE TABLE admin_notifications ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id), + alert_key TEXT NOT NULL, + kind TEXT NOT NULL, + subject TEXT NOT NULL DEFAULT '', + detail TEXT NOT NULL DEFAULT '', + resolved INTEGER NOT NULL DEFAULT 0, + unread INTEGER NOT NULL DEFAULT 1, + updated_at TEXT NOT NULL +); +CREATE INDEX admin_notifications_inbox ON admin_notifications (user_id, unread, updated_at); diff --git a/crates/forge-core/src/alerts.rs b/crates/forge-core/src/alerts.rs new file mode 100644 index 0000000..83182e4 --- /dev/null +++ b/crates/forge-core/src/alerts.rs @@ -0,0 +1,180 @@ +//! Admin alerts: the kinds of trouble the forge tells its admins about, and the pure rules that +//! decide when to. Delivery and state live in `store::admin_alerts` and forge-web's `alerts`. + +/// What an alert is about. Each kind has its own on/off setting. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum AlertKind { + /// A CI runner stopped checking in. + RunnerOffline, + /// A backup, its verification or an fsck failed, or no backup succeeded in time. + Backup, + /// The data directory is nearly full. + Disk, + /// A CI job was killed by SIGKILL or the OOM killer. + CiKilled, + /// A self-update deployed or failed, and the server restarted. + SelfUpdate, + /// The standby is failing or lagging. + Replication, +} + +impl AlertKind { + pub const ALL: [AlertKind; 6] = [ + AlertKind::RunnerOffline, + AlertKind::Backup, + AlertKind::Disk, + AlertKind::CiKilled, + AlertKind::SelfUpdate, + AlertKind::Replication, + ]; + + pub fn as_str(self) -> &'static str { + match self { + AlertKind::RunnerOffline => "runner_offline", + AlertKind::Backup => "backup", + AlertKind::Disk => "disk", + AlertKind::CiKilled => "ci_killed", + AlertKind::SelfUpdate => "self_update", + AlertKind::Replication => "replication", + } + } + + pub fn parse(s: &str) -> Option { + AlertKind::ALL.into_iter().find(|k| k.as_str() == s) + } +} + +/// Whether a job's result looks like the process was killed: SIGKILL (`signal: 9`, `SIGKILL`, +/// `Killed`), the shell's `128 + 9` exit code, or an out-of-memory message. +pub fn is_kill_signature(exit_code: Option, message: Option<&str>) -> bool { + if matches!(exit_code, Some(137) | Some(-9)) { + return true; + } + let Some(message) = message else { + return false; + }; + let text = message.to_ascii_lowercase(); + if text.contains("sigkill") + || text.contains("out of memory") + || text.contains("oom-kill") + || text.contains("oom kill") + || text.contains("oom_kill") + || text.contains("oomkill") + || text.contains("exit code 137") + || text.contains("exit status 137") + { + return true; + } + // "signal: 9", "signal 9", "signal=9", "killed by signal 9". A longer number such as 90 is + // not a match. + let mut rest = text.as_str(); + while let Some(at) = rest.find("signal") { + rest = &rest[at + "signal".len()..]; + let digits: String = rest + .trim_start_matches([':', '=', ' ']) + .chars() + .take_while(char::is_ascii_digit) + .collect(); + if digits == "9" { + return true; + } + } + text.trim() == "killed" +} + +/// Free space as a percentage of the total, rounded down. `None` for an empty filesystem. +pub fn free_percent(total: u64, available: u64) -> Option { + (u128::from(available) * 100) + .checked_div(u128::from(total)) + .map(|p| u64::try_from(p).unwrap_or(100)) +} + +/// Whether free space is below the configured floor: under `min_percent` of the total, or under +/// `min_gib` GiB when that is non-zero. +pub fn disk_is_low(total: u64, available: u64, min_percent: u64, min_gib: u64) -> bool { + let low_percent = free_percent(total, available).is_some_and(|p| p < min_percent); + let low_gib = min_gib > 0 && available < min_gib.saturating_mul(1 << 30); + low_percent || low_gib +} + +/// Whether the newest successful backup is older than twice the schedule interval. A forge that +/// never made one counts from `since_unix`, when the alerting began. +pub fn backup_overdue( + now_unix: i64, + last_ok_unix: Option, + since_unix: i64, + interval_hours: u64, +) -> bool { + let limit = + i64::try_from(interval_hours.saturating_mul(3600).saturating_mul(2)).unwrap_or(i64::MAX); + let basis = last_ok_unix.unwrap_or(since_unix); + now_unix.saturating_sub(basis) > limit +} + +/// Whether a runner has been silent too long. `last_seen_unix` is `None` for one that never +/// checked in, which is not offline: it was never online. +pub fn runner_is_offline(now_unix: i64, last_seen_unix: Option, minutes: u64) -> bool { + let limit = i64::try_from(minutes.saturating_mul(60)).unwrap_or(i64::MAX); + last_seen_unix.is_some_and(|seen| now_unix.saturating_sub(seen) > limit) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn kill_signatures_are_recognised() { + assert!(is_kill_signature(Some(137), None)); + assert!(is_kill_signature(Some(-9), None)); + assert!(is_kill_signature( + None, + Some("process exited: signal: 9 (killed)") + )); + assert!(is_kill_signature(None, Some("terminated by SIGKILL"))); + assert!(is_kill_signature(None, Some("fatal: out of memory"))); + assert!(is_kill_signature(None, Some("Killed"))); + assert!(is_kill_signature(None, Some("job died with signal 9"))); + assert!(is_kill_signature(None, Some("exit status 137"))); + } + + #[test] + fn other_failures_are_not_kills() { + assert!(!is_kill_signature(Some(1), None)); + assert!(!is_kill_signature(Some(0), Some("ok"))); + assert!(!is_kill_signature( + None, + Some("job was terminated by a signal") + )); + assert!(!is_kill_signature(None, Some("signal: 90"))); + assert!(!is_kill_signature(None, Some("signal 15 (terminated)"))); + assert!(!is_kill_signature(None, Some("a broom closet"))); + assert!(!is_kill_signature(None, None)); + } + + #[test] + fn disk_thresholds() { + let gib = 1u64 << 30; + assert_eq!(free_percent(100 * gib, 5 * gib), Some(5)); + assert_eq!(free_percent(0, 0), None); + assert!(disk_is_low(100 * gib, 5 * gib, 10, 0)); + assert!(!disk_is_low(100 * gib, 10 * gib, 10, 0)); + assert!(disk_is_low(1000 * gib, 50 * gib, 1, 60)); + assert!(!disk_is_low(1000 * gib, 70 * gib, 1, 60)); + } + + #[test] + fn backup_overdue_after_twice_the_interval() { + let h = 3600; + assert!(!backup_overdue(47 * h, Some(0), 0, 24)); + assert!(backup_overdue(49 * h, Some(0), 0, 24)); + assert!(backup_overdue(49 * h, None, 0, 24)); + assert!(!backup_overdue(49 * h, None, 10 * h, 24)); + } + + #[test] + fn runner_offline_uses_the_threshold() { + assert!(!runner_is_offline(1000, Some(500), 10)); + assert!(runner_is_offline(1000, Some(300), 10)); + assert!(!runner_is_offline(1000, None, 10)); + } +} diff --git a/crates/forge-core/src/config.rs b/crates/forge-core/src/config.rs index a9ac1fe..ccedc2d 100644 --- a/crates/forge-core/src/config.rs +++ b/crates/forge-core/src/config.rs @@ -108,6 +108,66 @@ pub struct Config { /// Site announcement shown under every page header, from the `[banner]` section. #[serde(default)] pub banner: BannerConfig, + /// Alerts to site admins, from the `[alerts]` section. + #[serde(default)] + pub alerts: AlertsConfig, +} + +/// Admin alerts: what the forge tells the site admins about before something breaks. +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields, default)] +pub struct AlertsConfig { + /// Master switch. Off sends nothing and raises nothing. + pub enabled: bool, + /// Also email the admins, when they have a verified address and mail is set up. + pub email: bool, + /// Minutes without a heartbeat before a runner counts as offline. + pub runner_offline_minutes: u64, + /// Alert when the data directory has less than this percent free. + pub disk_free_percent: u64, + /// Alert when the data directory has less than this many GiB free. 0 turns this check off. + pub disk_free_gib: u64, + /// Per-kind switches. + pub on_runner_offline: bool, + pub on_backup: bool, + pub on_disk: bool, + pub on_ci_killed: bool, + pub on_self_update: bool, + pub on_replication: bool, +} + +impl Default for AlertsConfig { + fn default() -> Self { + AlertsConfig { + enabled: true, + email: true, + runner_offline_minutes: 10, + disk_free_percent: 10, + disk_free_gib: 0, + on_runner_offline: true, + on_backup: true, + on_disk: true, + on_ci_killed: true, + on_self_update: true, + on_replication: true, + } + } +} + +impl AlertsConfig { + /// Whether alerts of `kind` are raised: the master switch and the kind's own switch. + pub fn kind_enabled(&self, kind: crate::alerts::AlertKind) -> bool { + use crate::alerts::AlertKind as K; + self.enabled + && match kind { + K::RunnerOffline => self.on_runner_offline, + K::Backup => self.on_backup, + K::Disk => self.on_disk, + K::CiKilled => self.on_ci_killed, + K::SelfUpdate => self.on_self_update, + K::Replication => self.on_replication, + } + } } /// Site announcement banner. An empty `message` shows nothing. diff --git a/crates/forge-core/src/lib.rs b/crates/forge-core/src/lib.rs index fb02602..83e173d 100644 --- a/crates/forge-core/src/lib.rs +++ b/crates/forge-core/src/lib.rs @@ -1,6 +1,7 @@ //! Domain types, storage, configuration and security primitives for forge. pub mod advisories; +pub mod alerts; pub mod audit; pub mod authz; pub mod avatar; diff --git a/crates/forge-core/src/server_settings.rs b/crates/forge-core/src/server_settings.rs index e5078be..96904b4 100644 --- a/crates/forge-core/src/server_settings.rs +++ b/crates/forge-core/src/server_settings.rs @@ -39,15 +39,17 @@ pub enum Group { Storage, Backups, Integrations, + Alerts, } impl Group { - pub const ALL: [Group; 5] = [ + pub const ALL: [Group; 6] = [ Group::General, Group::Limits, Group::Storage, Group::Backups, Group::Integrations, + Group::Alerts, ]; pub fn slug(self) -> &'static str { @@ -57,6 +59,7 @@ impl Group { Group::Storage => "storage", Group::Backups => "backups", Group::Integrations => "integrations", + Group::Alerts => "alerts", } } @@ -117,7 +120,7 @@ const fn f( } } -use Group::{Backups, General, Integrations, Limits, Storage}; +use Group::{Alerts, Backups, General, Integrations, Limits, Storage}; use Kind::{Live as L, ReadOnly as R, Restart as X}; const REGISTRATION: &[&str] = &["closed", "invite", "open"]; @@ -606,6 +609,94 @@ pub static FIELDS: &[Field] = &[ "Self-update artifact", "", ), + f( + "alerts.enabled", + Alerts, + L, + Ty::Bool, + "Admin alerts", + "Master switch. Off raises and sends nothing.", + ), + f( + "alerts.email", + Alerts, + L, + Ty::Bool, + "Email alerts", + "Also email the admins who have a verified address.", + ), + f( + "alerts.runner_offline_minutes", + Alerts, + L, + Ty::Uint(1, 1_440), + "Runner offline after (minutes)", + "A runner with no heartbeat for this long raises an alert.", + ), + f( + "alerts.disk_free_percent", + Alerts, + L, + Ty::Uint(1, 90), + "Low disk space (percent free)", + "Alert when the data directory has less than this free.", + ), + f( + "alerts.disk_free_gib", + Alerts, + L, + Ty::Uint(0, 100_000), + "Low disk space (GiB free)", + "Also alert under this many GiB. 0 turns this check off.", + ), + f( + "alerts.on_runner_offline", + Alerts, + L, + Ty::Bool, + "Runner offline alerts", + "", + ), + f( + "alerts.on_backup", + Alerts, + L, + Ty::Bool, + "Backup alerts", + "Failed, unverified or overdue backups, and failed fsck runs.", + ), + f( + "alerts.on_disk", + Alerts, + L, + Ty::Bool, + "Disk space alerts", + "", + ), + f( + "alerts.on_ci_killed", + Alerts, + L, + Ty::Bool, + "Killed CI job alerts", + "Jobs killed by SIGKILL or the OOM killer, once per run.", + ), + f( + "alerts.on_self_update", + Alerts, + L, + Ty::Bool, + "Self-update alerts", + "Deployed, failed, and server restarted.", + ), + f( + "alerts.on_replication", + Alerts, + L, + Ty::Bool, + "Replication alerts", + "Standby failing or lagging.", + ), ]; /// The field for a dotted key. @@ -751,6 +842,17 @@ pub fn get(cfg: &Config, key: &str) -> String { "banner.message" => cfg.banner.message.clone(), "banner.level" => cfg.banner.level.clone(), "banner.expires" => cfg.banner.expires.clone(), + "alerts.enabled" => cfg.alerts.enabled.to_string(), + "alerts.email" => cfg.alerts.email.to_string(), + "alerts.runner_offline_minutes" => cfg.alerts.runner_offline_minutes.to_string(), + "alerts.disk_free_percent" => cfg.alerts.disk_free_percent.to_string(), + "alerts.disk_free_gib" => cfg.alerts.disk_free_gib.to_string(), + "alerts.on_runner_offline" => cfg.alerts.on_runner_offline.to_string(), + "alerts.on_backup" => cfg.alerts.on_backup.to_string(), + "alerts.on_disk" => cfg.alerts.on_disk.to_string(), + "alerts.on_ci_killed" => cfg.alerts.on_ci_killed.to_string(), + "alerts.on_self_update" => cfg.alerts.on_self_update.to_string(), + "alerts.on_replication" => cfg.alerts.on_replication.to_string(), "base_url" => cfg.base_url.clone(), "user_content_base_url" => cfg.user_content_base_url.clone(), "ssh_public_host" => cfg.ssh_public_host.clone(), @@ -857,6 +959,17 @@ pub fn set(cfg: &mut Config, key: &str, raw: &str) -> Result<()> { "banner.message" => cfg.banner.message = s(), "banner.level" => cfg.banner.level = s(), "banner.expires" => cfg.banner.expires = s(), + "alerts.enabled" => cfg.alerts.enabled = b(v), + "alerts.email" => cfg.alerts.email = b(v), + "alerts.runner_offline_minutes" => cfg.alerts.runner_offline_minutes = n(v), + "alerts.disk_free_percent" => cfg.alerts.disk_free_percent = n(v), + "alerts.disk_free_gib" => cfg.alerts.disk_free_gib = n(v), + "alerts.on_runner_offline" => cfg.alerts.on_runner_offline = b(v), + "alerts.on_backup" => cfg.alerts.on_backup = b(v), + "alerts.on_disk" => cfg.alerts.on_disk = b(v), + "alerts.on_ci_killed" => cfg.alerts.on_ci_killed = b(v), + "alerts.on_self_update" => cfg.alerts.on_self_update = b(v), + "alerts.on_replication" => cfg.alerts.on_replication = b(v), "base_url" => cfg.base_url = s(), "user_content_base_url" => cfg.user_content_base_url = s(), "ssh_public_host" => cfg.ssh_public_host = s(), diff --git a/crates/forge-core/src/store/admin_alerts.rs b/crates/forge-core/src/store/admin_alerts.rs new file mode 100644 index 0000000..0255b4a --- /dev/null +++ b/crates/forge-core/src/store/admin_alerts.rs @@ -0,0 +1,372 @@ +//! Admin alerts (migration 0058): the state of each alert condition, and the admins' inbox rows. +//! +//! A condition has a stable `key`. [`Store::raise_alert`] returns true only on the change from +//! "not active" to "active", and [`Store::resolve_alert`] only on "active" to "resolved", so a +//! condition that stays true is told once, and its end is told once. + +use turso::{Row, Value}; + +use super::issues::finish; +use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, new_id}; +use crate::error::Result; +use crate::time::now_stamp; + +/// A condition that is active now. Resolved alerts and one-shot events are not listed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AdminAlert { + pub key: String, + pub kind: String, + pub subject: String, + pub detail: String, + pub raised_at: String, +} + +/// One admin's inbox row: a raised alert, or the message that it resolved. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AdminNotice { + pub id: String, + pub alert_key: String, + pub kind: String, + pub subject: String, + pub detail: String, + pub resolved: bool, + pub unread: bool, + pub updated_at: String, +} + +const NOTICE_COLS: &str = "id, alert_key, kind, subject, detail, resolved, unread, updated_at"; + +fn map_alert(row: &Row) -> Result { + Ok(AdminAlert { + key: col_text(row, 0)?, + kind: col_text(row, 1)?, + subject: col_text(row, 2)?, + detail: col_text(row, 3)?, + raised_at: col_text(row, 4)?, + }) +} + +fn map_notice(row: &Row) -> Result { + Ok(AdminNotice { + id: col_text(row, 0)?, + alert_key: col_text(row, 1)?, + kind: col_text(row, 2)?, + subject: col_text(row, 3)?, + detail: col_text(row, 4)?, + resolved: col_int(row, 5)? != 0, + unread: col_int(row, 6)? != 0, + updated_at: col_text(row, 7)?, + }) +} + +fn text(s: &str) -> Value { + Value::Text(s.to_owned()) +} + +impl Store { + /// Marks the condition `key` active. Returns true when it was not active before, which is + /// when the admins are told. An alert already active keeps its first `raised_at`; only its + /// detail is refreshed. + pub async fn raise_alert( + &self, + key: &str, + kind: &str, + subject: &str, + detail: &str, + ) -> Result { + let now = now_stamp(); + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + let state = fetch_opt( + &tx, + "SELECT state FROM admin_alerts WHERE key = ?1", + (key.to_owned(),), + |row| col_text(row, 0), + ) + .await?; + match state.as_deref() { + Some("active") => { + tx.execute( + "UPDATE admin_alerts SET detail = ?2, updated_at = ?3 WHERE key = ?1", + vec![text(key), text(detail), text(&now)], + ) + .await + .map_err(db_err)?; + Ok(false) + } + _ => { + tx.execute( + "INSERT INTO admin_alerts (key, kind, subject, detail, state, raised_at, \ + resolved_at, updated_at) VALUES (?1, ?2, ?3, ?4, 'active', ?5, NULL, ?5) \ + ON CONFLICT(key) DO UPDATE SET kind = excluded.kind, \ + subject = excluded.subject, detail = excluded.detail, state = 'active', \ + raised_at = excluded.raised_at, resolved_at = NULL, \ + updated_at = excluded.updated_at", + vec![ + text(key), + text(kind), + text(subject), + text(detail), + text(&now), + ], + ) + .await + .map_err(db_err)?; + Ok(true) + } + } + } + .await; + finish(tx, outcome).await + } + + /// Marks the condition `key` resolved. Returns the alert when it was active, so the caller + /// can say it is over, and `None` when there was nothing to resolve. + pub async fn resolve_alert(&self, key: &str) -> Result> { + let now = now_stamp(); + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result> = async { + let alert = fetch_opt( + &tx, + "SELECT key, kind, subject, detail, raised_at FROM admin_alerts \ + WHERE key = ?1 AND state = 'active'", + (key.to_owned(),), + map_alert, + ) + .await?; + if alert.is_some() { + tx.execute( + "UPDATE admin_alerts SET state = 'resolved', resolved_at = ?2, \ + updated_at = ?2 WHERE key = ?1", + vec![text(key), text(&now)], + ) + .await + .map_err(db_err)?; + } + Ok(alert) + } + .await; + finish(tx, outcome).await + } + + /// Records a one-shot event under `key`. Returns true the first time only. An event is never + /// active, so it is not in [`Store::active_alerts`]. + pub async fn record_alert_event( + &self, + key: &str, + kind: &str, + subject: &str, + detail: &str, + ) -> Result { + let now = now_stamp(); + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "INSERT OR IGNORE INTO admin_alerts (key, kind, subject, detail, state, \ + raised_at, resolved_at, updated_at) VALUES (?1, ?2, ?3, ?4, 'event', ?5, NULL, ?5)", + vec![ + text(key), + text(kind), + text(subject), + text(detail), + text(&now), + ], + ) + .await + .map_err(db_err)?; + Ok(changed > 0) + } + + /// Every alert that is active now, oldest first. + pub async fn active_alerts(&self) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + "SELECT key, kind, subject, detail, raised_at FROM admin_alerts \ + WHERE state = 'active' ORDER BY raised_at, key", + (), + map_alert, + ) + .await + } + + /// The keys of the active alerts of one kind. + pub async fn active_alert_keys(&self, kind: &str) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + "SELECT key FROM admin_alerts WHERE state = 'active' AND kind = ?1", + (kind.to_owned(),), + |row| col_text(row, 0), + ) + .await + } + + /// Adds an inbox row for `user_id`. + pub async fn add_admin_notice( + &self, + user_id: &str, + alert_key: &str, + kind: &str, + subject: &str, + detail: &str, + resolved: bool, + ) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "INSERT INTO admin_notifications (id, user_id, alert_key, kind, subject, detail, \ + resolved, unread, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, 1, ?8)", + vec![ + text(&new_id()), + text(user_id), + text(alert_key), + text(kind), + text(subject), + text(detail), + Value::Integer(i64::from(resolved)), + text(&now_stamp()), + ], + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// The user's alert inbox rows, newest first. + pub async fn list_admin_notices( + &self, + user_id: &str, + unread_only: bool, + before: Option<&str>, + limit: u32, + ) -> Result> { + let mut sql = format!("SELECT {NOTICE_COLS} FROM admin_notifications WHERE user_id = ?"); + let mut params = vec![text(user_id)]; + if unread_only { + sql.push_str(" AND unread = 1"); + } + if let Some(stamp) = before { + sql.push_str(" AND updated_at < ?"); + params.push(text(stamp)); + } + sql.push_str(" ORDER BY updated_at DESC, id DESC LIMIT ?"); + params.push(Value::Integer(i64::from(limit.clamp(1, 200)))); + let conn = self.read_conn().await; + fetch_all(&conn, &sql, params, map_notice).await + } + + /// Marks one of the user's alert rows read. Another user's row changes nothing. + pub async fn mark_admin_notice_read(&self, user_id: &str, id: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "UPDATE admin_notifications SET unread = 0 WHERE id = ?1 AND user_id = ?2", + (id.to_owned(), user_id.to_owned()), + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// Marks all of the user's alert rows read. + pub async fn mark_all_admin_notices_read(&self, user_id: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "UPDATE admin_notifications SET unread = 0 WHERE user_id = ?1 AND unread = 1", + (user_id.to_owned(),), + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// Deletes resolved and event rows and read inbox rows older than `before`, so the tables do + /// not grow without bound. Active alerts stay. + pub async fn prune_admin_alerts(&self, before: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM admin_alerts WHERE state <> 'active' AND updated_at < ?1", + (before.to_owned(),), + ) + .await + .map_err(db_err)?; + conn.execute( + "DELETE FROM admin_notifications WHERE unread = 0 AND updated_at < ?1", + (before.to_owned(),), + ) + .await + .map_err(db_err)?; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use crate::store::Store; + + async fn store() -> (Store, tempfile::TempDir) { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); + (store, dir) + } + + #[tokio::test] + async fn an_alert_is_raised_once_until_it_resolves() { + let (store, _dir) = store().await; + assert!( + store + .raise_alert("runner_offline:r1", "runner_offline", "ci-1", "") + .await + .unwrap() + ); + assert!( + !store + .raise_alert("runner_offline:r1", "runner_offline", "ci-1", "later") + .await + .unwrap(), + "still active: not raised again" + ); + let active = store.active_alerts().await.unwrap(); + assert_eq!(active.len(), 1); + assert_eq!(active[0].detail, "later"); + + let resolved = store.resolve_alert("runner_offline:r1").await.unwrap(); + assert_eq!(resolved.map(|a| a.subject), Some("ci-1".to_owned())); + assert!( + store + .resolve_alert("runner_offline:r1") + .await + .unwrap() + .is_none(), + "resolving twice says nothing the second time" + ); + assert!(store.active_alerts().await.unwrap().is_empty()); + + assert!( + store + .raise_alert("runner_offline:r1", "runner_offline", "ci-1", "") + .await + .unwrap(), + "a new failure after the resolution is raised again" + ); + } + + #[tokio::test] + async fn events_fire_once_and_are_never_active() { + let (store, _dir) = store().await; + assert!( + store + .record_alert_event("ci_killed:run1", "ci_killed", "ci-1", "") + .await + .unwrap() + ); + assert!( + !store + .record_alert_event("ci_killed:run1", "ci_killed", "ci-1", "") + .await + .unwrap() + ); + assert!(store.active_alerts().await.unwrap().is_empty()); + } +} diff --git a/crates/forge-core/src/store/migrate.rs b/crates/forge-core/src/store/migrate.rs index ca96e8d..29b05e0 100644 --- a/crates/forge-core/src/store/migrate.rs +++ b/crates/forge-core/src/store/migrate.rs @@ -98,6 +98,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ (56, include_str!("../../migrations/0056_runner_build.sql")), (57, include_str!("../../migrations/0057_runner_restart.sql")), (58, include_str!("../../migrations/0058_passkeys.sql")), + (59, include_str!("../../migrations/0059_admin_alerts.sql")), ]; /// The highest migration version this binary knows about. diff --git a/crates/forge-core/src/store/mod.rs b/crates/forge-core/src/store/mod.rs index 2a4799f..12af619 100644 --- a/crates/forge-core/src/store/mod.rs +++ b/crates/forge-core/src/store/mod.rs @@ -1,6 +1,7 @@ //! Turso-backed storage. All metadata lives here. pub mod account_tokens; +pub mod admin_alerts; pub mod advisories; pub mod attachments; pub mod audit; diff --git a/crates/forge-core/src/store/notifications.rs b/crates/forge-core/src/store/notifications.rs index 32ddc46..ca08f61 100644 --- a/crates/forge-core/src/store/notifications.rs +++ b/crates/forge-core/src/store/notifications.rs @@ -325,7 +325,8 @@ impl Store { &conn, "SELECT (SELECT COUNT(*) FROM notifications WHERE user_id = ?1 AND unread = 1) + \ (SELECT COUNT(*) FROM discussion_notifications WHERE user_id = ?1 AND unread = 1) + \ - (SELECT COUNT(*) FROM advisory_notifications WHERE user_id = ?1 AND unread = 1)", + (SELECT COUNT(*) FROM advisory_notifications WHERE user_id = ?1 AND unread = 1) + \ + (SELECT COUNT(*) FROM admin_notifications WHERE user_id = ?1 AND unread = 1)", (user_id.to_string(),), |row| col_int(row, 0), ) diff --git a/crates/forge-core/src/store/user_delete.rs b/crates/forge-core/src/store/user_delete.rs index ce1c7be..592579a 100644 --- a/crates/forge-core/src/store/user_delete.rs +++ b/crates/forge-core/src/store/user_delete.rs @@ -135,6 +135,7 @@ const REMOVED: &[(&str, &str, &str)] = &[ "advisory_notifications", "user_id", ), + ("admin notifications", "admin_notifications", "user_id"), ("reactions", "reactions", "user_id"), ("review requests", "review_requests", "reviewer_id"), ]; diff --git a/crates/forge-web/Cargo.toml b/crates/forge-web/Cargo.toml index c0bd6a4..9ba543c 100644 --- a/crates/forge-web/Cargo.toml +++ b/crates/forge-web/Cargo.toml @@ -36,6 +36,7 @@ http-body.workspace = true rpassword.workspace = true rand.workspace = true hex.workspace = true +nix = { workspace = true } sha2.workspace = true time.workspace = true comrak = { workspace = true } diff --git a/crates/forge-web/src/alerts.rs b/crates/forge-web/src/alerts.rs new file mode 100644 index 0000000..5ba7f0b --- /dev/null +++ b/crates/forge-web/src/alerts.rs @@ -0,0 +1,630 @@ +//! Admin alerts: tells the site admins about trouble before something breaks. +//! +//! An alert is a condition with a stable key. [`raise`] tells the admins once, however often the +//! condition is reported, and [`resolve`] tells them once that it is over (see +//! `Store::raise_alert`). [`event`] is for a thing that happened once, such as a killed CI job. +//! Delivery is an inbox row for every site admin, pushed to their open bell stream, plus an email +//! when `alerts.email` is on and the admin has a verified address. +//! +//! Most alerts are raised where the trouble is seen: a failed backup, a failed self-update, a +//! killed job, a runner that checks in again. The conditions nothing reports (a runner that went +//! silent, a full disk, an overdue backup, a lagging standby) are looked at on ticks that already +//! exist: [`check_runners`] on every CI reaper pass, [`check_slow`] on every tenth. + +use std::sync::OnceLock; +use std::sync::atomic::{AtomicBool, Ordering}; + +use forge_core::alerts::{self, AlertKind}; +use forge_core::mail::{MailKind, OutgoingMail}; +use forge_core::store::backup_runs::RunKind; +use forge_core::time::stamp_to_unix; + +use crate::i18n::{self, alerts as text}; +use crate::mail; +use crate::notify_hub::publish_unread; +use crate::state::AppState; +use crate::views::now_unix; + +/// True while some runner-offline alert is active, so a runner that checks in costs a database +/// write only when there is something to resolve. +static OFFLINE_ACTIVE: AtomicBool = AtomicBool::new(false); +/// When this process started, as unix seconds. An install that never made a backup is overdue +/// from here, not from 1970. +static STARTED: OnceLock = OnceLock::new(); + +fn started() -> i64 { + *STARTED.get_or_init(now_unix) +} + +fn kind_of(topic: &str) -> AlertKind { + match topic { + "runner_offline" => AlertKind::RunnerOffline, + "backup_failed" | "backup_verify_failed" | "backup_overdue" | "fsck_failed" => { + AlertKind::Backup + } + "disk_low" => AlertKind::Disk, + "ci_killed" => AlertKind::CiKilled, + "self_update_restart" | "self_update_failed" => AlertKind::SelfUpdate, + _ => AlertKind::Replication, + } +} + +/// Raises the alert `key` of `topic`. The admins hear about it once, until it resolves. +pub async fn raise(state: &AppState, topic: &str, key: &str, subject: &str, detail: &str) { + if !state.live().alerts.kind_enabled(kind_of(topic)) { + return; + } + match state.store.raise_alert(key, topic, subject, detail).await { + Ok(true) => { + if topic == "runner_offline" { + OFFLINE_ACTIVE.store(true, Ordering::Relaxed); + } + deliver(state, key, topic, subject, detail, false).await; + } + Ok(false) => {} + Err(e) => tracing::error!(error = %e, key, "alerts: raising failed"), + } +} + +/// Resolves the alert `key`. The admins are told only when it was active. +pub async fn resolve(state: &AppState, key: &str) { + match state.store.resolve_alert(key).await { + Ok(Some(alert)) => { + let kind = kind_of(&alert.kind); + if state.live().alerts.kind_enabled(kind) { + deliver(state, key, &alert.kind, &alert.subject, &alert.detail, true).await; + } + } + Ok(None) => {} + Err(e) => tracing::error!(error = %e, key, "alerts: resolving failed"), + } +} + +/// Tells the admins that something happened, once per `key`. +pub async fn event(state: &AppState, topic: &str, key: &str, subject: &str, detail: &str) { + if !state.live().alerts.kind_enabled(kind_of(topic)) { + return; + } + match state + .store + .record_alert_event(key, topic, subject, detail) + .await + { + Ok(true) => deliver(state, key, topic, subject, detail, false).await, + Ok(false) => {} + Err(e) => tracing::error!(error = %e, key, "alerts: recording an event failed"), + } +} + +/// Writes the inbox rows and queues the emails for one message to every site admin. +async fn deliver( + state: &AppState, + key: &str, + topic: &str, + subject: &str, + detail: &str, + resolved: bool, +) { + let users = match state.store.list_users().await { + Ok(users) => users, + Err(e) => { + tracing::error!(error = %e, "alerts: listing the admins failed"); + return; + } + }; + let live = state.live(); + let base = live.base_url.trim_end_matches('/').to_owned(); + let state_word = if resolved { "resolved" } else { "raised" }; + for admin in users.into_iter().filter(|u| u.is_admin && !u.is_org()) { + if let Err(e) = state + .store + .add_admin_notice(&admin.id, key, topic, subject, detail, resolved) + .await + { + tracing::error!(error = %e, key, "alerts: writing an inbox row failed"); + continue; + } + publish_unread(state, &admin.id).await; + if !live.alerts.email { + continue; + } + let Some(address) = admin.email.as_deref().filter(|a| !a.is_empty()) else { + continue; + }; + match state.store.email_is_verified(&admin.id).await { + Ok(true) => {} + Ok(false) => continue, + Err(e) => { + tracing::error!(error = %e, "alerts: checking the admin's address failed"); + continue; + } + } + let lang = i18n::resolve(Some(admin.language.as_str()), &http::HeaderMap::new()); + let title = text::title(lang, topic, subject, resolved); + let body = text::mail_body( + lang, + &text::body(lang, topic, subject, detail, resolved), + &format!("{base}/admin/health"), + &format!("{base}/admin/server?tab=alerts"), + ); + let outgoing = OutgoingMail { + to: address.to_owned(), + subject: text::mail_subject(lang, &title), + body, + message_id: None, + in_reply_to: None, + kind: MailKind::Notification, + user_id: Some(admin.id.clone()), + }; + let idem = format!( + "alert:{key}:{state_word}:{}:{}", + forge_core::time::now_stamp(), + admin.id + ); + if let Err(e) = mail::enqueue_message(state, &idem, &outgoing).await { + tracing::error!(error = %e, key, "alerts: queueing the email failed"); + } + } +} + +// ---- events seen where they happen ---- + +/// A runner authenticated, so it is online. Resolves its offline alert if it had one. +pub async fn runner_seen(state: &AppState, runner_id: &str) { + if !OFFLINE_ACTIVE.load(Ordering::Relaxed) { + return; + } + resolve(state, &format!("runner_offline:{runner_id}")).await; + match state.store.active_alert_keys("runner_offline").await { + Ok(keys) if keys.is_empty() => OFFLINE_ACTIVE.store(false, Ordering::Relaxed), + Ok(_) => {} + Err(e) => tracing::error!(error = %e, "alerts: reading the active alerts failed"), + } +} + +/// A job ended `Failure` or `Error`. Tells the admins once per run when it looks like the job was +/// killed, naming the runner. +pub async fn job_ended( + state: &AppState, + job: &forge_core::ci::CiJob, + exit_code: Option, + message: Option<&str>, +) { + if !alerts::is_kill_signature(exit_code, message) { + return; + } + let runner = match &job.runner_id { + Some(id) => state + .store + .list_runners() + .await + .ok() + .and_then(|runners| runners.into_iter().find(|r| &r.id == id)) + .map_or_else(|| id.clone(), |r| r.name), + None => "unknown".to_owned(), + }; + let detail = format!("job {} of run {}", job.name, job.run_id); + event( + state, + "ci_killed", + &format!("ci_killed:{}", job.run_id), + &runner, + &detail, + ) + .await; +} + +/// The outcome of a scheduled or manual backup. A good one resolves the backup alerts. +pub async fn backup_finished(state: &AppState, outcome: Result<(), &str>) { + match outcome { + Ok(()) => { + resolve(state, "backup_failed").await; + resolve(state, "backup_verify_failed").await; + resolve(state, "backup_overdue").await; + } + Err(error) => { + let topic = if error.contains("failed verification") { + "backup_verify_failed" + } else { + "backup_failed" + }; + raise(state, topic, topic, "", error).await; + } + } +} + +/// The outcome of an integrity check. +pub async fn fsck_finished(state: &AppState, outcome: Result<(), &str>) { + match outcome { + Ok(()) => resolve(state, "fsck_failed").await, + Err(error) => raise(state, "fsck_failed", "fsck_failed", "", error).await, + } +} + +/// A self-update installed a new binary and asked for a restart. +pub async fn self_update_deployed(state: &AppState, version: &str) { + raise( + state, + "self_update_restart", + "self_update_restart", + version, + "", + ) + .await; +} + +/// A self-update failed. One message per run. +pub async fn self_update_failed(state: &AppState, run_id: &str, error: &str) { + event( + state, + "self_update_failed", + &format!("self_update_failed:{run_id}"), + "", + error, + ) + .await; +} + +/// Called once at boot. A self-update that asked for a restart is over when the server is up. +pub async fn on_boot(state: &AppState) { + started(); + match state.store.active_alert_keys("runner_offline").await { + Ok(keys) => OFFLINE_ACTIVE.store(!keys.is_empty(), Ordering::Relaxed), + Err(e) => tracing::error!(error = %e, "alerts: reading the active alerts failed"), + } + if let Ok(Some(alert)) = state.store.resolve_alert("self_update_restart").await + && state.live().alerts.kind_enabled(AlertKind::SelfUpdate) + { + { + let version = crate::self_update::running() + .map(|r| r.sha256.chars().take(12).collect::()) + .unwrap_or(alert.subject.clone()); + deliver( + state, + "self_update_restart", + "self_update_restart", + &version, + "", + true, + ) + .await; + } + } +} + +// ---- conditions nothing reports: looked at on existing ticks ---- + +/// Raises an alert for each runner silent for longer than the configured minutes and resolves the +/// ones that are not any more. Runs on every CI reaper pass: one query. +pub async fn check_runners(state: &AppState) { + check_runners_at(state, now_unix()).await; +} + +/// [`check_runners`] with an explicit clock. +pub async fn check_runners_at(state: &AppState, now: i64) { + let live = state.live(); + let cfg = &live.alerts; + let runners = match state.store.list_runners().await { + Ok(runners) => runners, + Err(e) => { + tracing::error!(error = %e, "alerts: listing the runners failed"); + return; + } + }; + let mut offline = std::collections::BTreeSet::new(); + for runner in &runners { + let seen = runner.last_seen_at.as_deref().and_then(stamp_to_unix); + if runner.disabled || !alerts::runner_is_offline(now, seen, cfg.runner_offline_minutes) { + continue; + } + let key = format!("runner_offline:{}", runner.id); + offline.insert(key.clone()); + let since = seen.map_or_else(String::new, |t| forge_core::tz::format_in_tz(t, "UTC")); + raise(state, "runner_offline", &key, &runner.name, &since).await; + } + // Whatever is active but no longer offline (back, disabled or deleted) is resolved. + match state.store.active_alert_keys("runner_offline").await { + Ok(active) => { + for key in active.into_iter().filter(|k| !offline.contains(k)) { + resolve(state, &key).await; + } + } + Err(e) => tracing::error!(error = %e, "alerts: reading the active alerts failed"), + } +} + +/// The checks that need a look at the disk or the history: free space, an overdue backup and the +/// standby. Meant to run every few minutes. +pub async fn check_slow(state: &AppState) { + check_disk(state).await; + check_backup_overdue(state, now_unix()).await; + check_replication(state, now_unix()).await; + let old = forge_core::time::stamp_ago(std::time::Duration::from_secs(90 * 86_400)); + if let Err(e) = state.store.prune_admin_alerts(&old).await { + tracing::error!(error = %e, "alerts: pruning failed"); + } +} + +/// Free and total bytes of the filesystem holding `path`. +pub fn disk_space(path: &std::path::Path) -> Option<(u64, u64)> { + let stat = nix::sys::statvfs::statvfs(path).ok()?; + let block = stat.fragment_size(); + let total = stat.blocks().saturating_mul(block); + let avail = stat.blocks_available().saturating_mul(block); + Some((total, avail)) +} + +async fn check_disk(state: &AppState) { + let live = state.live(); + let cfg = &live.alerts; + if !cfg.kind_enabled(AlertKind::Disk) { + return; + } + let dir = live.data_dir.clone(); + let space = tokio::task::spawn_blocking({ + let dir = dir.clone(); + move || disk_space(&dir) + }) + .await + .ok() + .flatten(); + let Some((total, avail)) = space else { + return; + }; + if alerts::disk_is_low(total, avail, cfg.disk_free_percent, cfg.disk_free_gib) { + let percent = alerts::free_percent(total, avail).unwrap_or(0); + let detail = format!( + "{percent}% free ({} of {})", + crate::views::human_size(i18n::Lang::En, avail), + crate::views::human_size(i18n::Lang::En, total) + ); + raise( + state, + "disk_low", + "disk_low", + &dir.to_string_lossy(), + &detail, + ) + .await; + } else { + resolve(state, "disk_low").await; + } +} + +async fn check_backup_overdue(state: &AppState, now: i64) { + let live = state.live(); + if !live.backup.enabled() || !live.alerts.kind_enabled(AlertKind::Backup) { + return; + } + let last_ok = match state.store.last_ok(RunKind::Backup).await { + Ok(run) => run.and_then(|r| r.finished_at.or(Some(r.started_at))), + Err(e) => { + tracing::error!(error = %e, "alerts: reading the backup history failed"); + return; + } + }; + let last_ok_unix = last_ok.as_deref().and_then(stamp_to_unix); + if alerts::backup_overdue(now, last_ok_unix, started(), live.backup.interval_hours) { + let detail = last_ok_unix.map_or_else( + || "never".to_owned(), + |t| forge_core::tz::format_in_tz(t, "UTC"), + ); + raise(state, "backup_overdue", "backup_overdue", "", &detail).await; + } else { + resolve(state, "backup_overdue").await; + } +} + +async fn check_replication(state: &AppState, now: i64) { + let live = state.live(); + if !live.replication.enabled() || !live.alerts.kind_enabled(AlertKind::Replication) { + return; + } + let rows = match state.store.list_replication_status().await { + Ok(rows) => rows, + Err(e) => { + tracing::error!(error = %e, "alerts: reading the replication status failed"); + return; + } + }; + let window = + i64::try_from(live.replication.db_snapshot_minutes.saturating_mul(120)).unwrap_or(i64::MAX); + let mut problem: Option = None; + for row in &rows { + if let Some(error) = &row.last_error { + problem = Some(format!("{}: {error}.", row.subject)); + break; + } + if row.subject == forge_core::store::replication::DB_SUBJECT { + let ok = row.last_ok_at.as_deref().and_then(stamp_to_unix); + if ok.is_none_or(|t| now.saturating_sub(t) > window) { + problem = Some("The database snapshot has not reached the standby in time.".into()); + break; + } + } + } + match problem { + Some(detail) => raise(state, "replication", "replication", "", &detail).await, + None => resolve(state, "replication").await, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_support::test_state; + use forge_core::mail::MailState; + + async fn admin(state: &AppState, name: &str, verified: bool) -> String { + let address = format!("{name}@test.example"); + let user = state + .store + .create_user(name, Some(&address), "hash", true) + .await + .unwrap(); + if verified { + let token = state + .store + .create_verify_token(&user.id, &address) + .await + .unwrap(); + state.store.redeem_verify_token(&token).await.unwrap(); + } + user.id + } + + async fn inbox( + state: &AppState, + user_id: &str, + ) -> Vec { + state + .store + .list_admin_notices(user_id, false, None, 50) + .await + .unwrap() + } + + async fn queued_mail(state: &AppState) -> usize { + state + .store + .mail_state_counts(&forge_core::time::now_stamp()) + .await + .unwrap() + .into_iter() + .filter(|(s, _)| matches!(s, MailState::Queued | MailState::Retrying)) + .map(|(_, n)| n as usize) + .sum() + } + + #[tokio::test] + async fn an_alert_reaches_every_admin_once_and_resolves_once() { + let dir = tempfile::tempdir().unwrap(); + let state = test_state(dir.path()).await; + let tahinli = admin(&state, "tahinli", true).await; + let second = admin(&state, "tahinli2", false).await; + + raise(&state, "disk_low", "disk_low", "/data", "4% free").await; + raise(&state, "disk_low", "disk_low", "/data", "3% free").await; + assert_eq!(inbox(&state, &tahinli).await.len(), 1, "deduplicated"); + assert_eq!(inbox(&state, &second).await.len(), 1); + assert_eq!(state.store.active_alerts().await.unwrap().len(), 1); + assert_eq!( + queued_mail(&state).await, + 1, + "only the verified admin is mailed" + ); + + resolve(&state, "disk_low").await; + resolve(&state, "disk_low").await; + let rows = inbox(&state, &tahinli).await; + assert_eq!(rows.len(), 2, "raised and resolved, once each"); + assert!(rows.iter().any(|r| r.resolved)); + assert!(state.store.active_alerts().await.unwrap().is_empty()); + assert_eq!(queued_mail(&state).await, 2); + assert_eq!(state.store.unread_count(&tahinli).await.unwrap(), 2); + + raise(&state, "disk_low", "disk_low", "/data", "2% free").await; + assert_eq!( + inbox(&state, &tahinli).await.len(), + 3, + "a new episode is told again" + ); + } + + #[tokio::test] + async fn switches_stop_raising_and_email_off_sends_no_mail() { + let dir = tempfile::tempdir().unwrap(); + let mut state = test_state(dir.path()).await; + let tahinli = admin(&state, "tahinli", true).await; + let mut config = (*state.config).clone(); + config.alerts.on_disk = false; + state.set_config(config.clone()); + raise(&state, "disk_low", "disk_low", "/data", "4% free").await; + assert!(inbox(&state, &tahinli).await.is_empty()); + + config.alerts.on_disk = true; + config.alerts.email = false; + state.set_config(config.clone()); + raise(&state, "disk_low", "disk_low", "/data", "4% free").await; + assert_eq!(inbox(&state, &tahinli).await.len(), 1); + assert_eq!(queued_mail(&state).await, 0); + + config.alerts.enabled = false; + state.set_config(config); + raise(&state, "backup_failed", "backup_failed", "", "boom").await; + assert_eq!( + inbox(&state, &tahinli).await.len(), + 1, + "the master switch wins" + ); + } + + #[tokio::test] + async fn a_silent_runner_is_flagged_and_clears_when_it_checks_in() { + let dir = tempfile::tempdir().unwrap(); + let state = test_state(dir.path()).await; + let tahinli = admin(&state, "tahinli", false).await; + let token = state + .store + .create_registration_token(&tahinli, 1) + .await + .unwrap(); + let (runner, secret) = state + .store + .register_runner(&token, "tahinli-ci", &["linux".to_owned()]) + .await + .unwrap(); + // The runner has just been seen: the clock is real for the first check. + state.store.runner_by_secret(&secret).await.unwrap(); + + let now = now_unix(); + check_runners_at(&state, now).await; + assert!(inbox(&state, &tahinli).await.is_empty(), "fresh heartbeat"); + + // Eleven minutes of silence on a fake clock (the default is ten). + check_runners_at(&state, now + 11 * 60).await; + check_runners_at(&state, now + 12 * 60).await; + let rows = inbox(&state, &tahinli).await; + assert_eq!(rows.len(), 1, "told once"); + assert_eq!(rows[0].subject, "tahinli-ci"); + assert_eq!(state.store.active_alerts().await.unwrap().len(), 1); + + // It checks in again: the heartbeat hook resolves it. + runner_seen(&state, &runner.id).await; + let rows = inbox(&state, &tahinli).await; + assert_eq!(rows.len(), 2); + assert!(rows[0].resolved); + assert!(state.store.active_alerts().await.unwrap().is_empty()); + } + + #[tokio::test] + async fn a_killed_job_is_told_once_per_run() { + let dir = tempfile::tempdir().unwrap(); + let state = test_state(dir.path()).await; + let tahinli = admin(&state, "tahinli", false).await; + let mut job = forge_core::ci::CiJob { + id: "job-1".into(), + run_id: "run-1".into(), + name: "build".into(), + spec_json: "{}".into(), + state: forge_core::ci::JobState::Running, + runner_id: None, + exit_code: None, + message: None, + queued_at: None, + started_at: None, + finished_at: None, + heartbeat_at: None, + cancel_requested: false, + log_bytes: 0, + }; + job_ended(&state, &job, Some(137), None).await; + job.name = "second".into(); + job_ended(&state, &job, None, Some("signal: 9")).await; + job_ended(&state, &job, Some(1), None).await; + assert_eq!(inbox(&state, &tahinli).await.len(), 1); + job.run_id = "run-2".into(); + job_ended(&state, &job, Some(137), None).await; + assert_eq!(inbox(&state, &tahinli).await.len(), 2); + } +} diff --git a/crates/forge-web/src/backup/scheduler.rs b/crates/forge-web/src/backup/scheduler.rs index 1d8eb2a..fc98a84 100644 --- a/crates/forge-web/src/backup/scheduler.rs +++ b/crates/forge-web/src/backup/scheduler.rs @@ -229,6 +229,10 @@ pub async fn backup_job( } let outcome = backup_set(state, &opts).await; + match &outcome { + Ok(_) => crate::alerts::backup_finished(state, Ok(())).await, + Err(e) => crate::alerts::backup_finished(state, Err(&e.to_string())).await, + } match &outcome { Ok(summary) => { let path = summary.path.to_string_lossy().into_owned(); @@ -278,6 +282,11 @@ async fn backup_set(state: &AppState, opts: &BackupOptions) -> Result Result { let run_id = state.store.start_run(RunKind::Fsck, trigger).await?; let outcome = run_fsck(&state.store, &state.git, full).await; + match &outcome { + Ok(summary) if summary.is_ok() => crate::alerts::fsck_finished(state, Ok(())).await, + Ok(summary) => crate::alerts::fsck_finished(state, Err(&summary.problems.join("\n"))).await, + Err(e) => crate::alerts::fsck_finished(state, Err(&e.to_string())).await, + } match &outcome { Ok(summary) if summary.is_ok() => { record_finish(state, &run_id, true, None, None, None).await; diff --git a/crates/forge-web/src/boot.rs b/crates/forge-web/src/boot.rs index 138cf4b..9b3965e 100644 --- a/crates/forge-web/src/boot.rs +++ b/crates/forge-web/src/boot.rs @@ -153,6 +153,7 @@ pub async fn serve( if state.config.replication.enabled() { crate::replication::worker::spawn(state.clone()); } + crate::alerts::on_boot(&state).await; crate::ci::reaper::spawn(state.clone()); crate::ci::scheduled::spawn(state.clone()); diff --git a/crates/forge-web/src/ci/api.rs b/crates/forge-web/src/ci/api.rs index 38d89af..a1758c1 100644 --- a/crates/forge-web/src/ci/api.rs +++ b/crates/forge-web/src/ci/api.rs @@ -82,7 +82,10 @@ async fn runner_from(state: &AppState, headers: &HeaderMap) -> Result Ok(runner), + Ok(Some(runner)) => { + crate::alerts::runner_seen(state, &runner.id).await; + Ok(runner) + } Ok(None) => Err(unauthorized()), Err(e) => Err(api::internal(e)), } @@ -932,6 +935,9 @@ async fn finish_job( } } state.ci_live.bump_runners(); + if matches!(outcome, JobState::Failure | JobState::Error) { + crate::alerts::job_ended(state, job, exit_code, request.message.as_deref()).await; + } if any_changed { state.ci_live.bump_run(&run.id); state.ci_live.bump_repo(&run.repo_id); diff --git a/crates/forge-web/src/ci/reaper.rs b/crates/forge-web/src/ci/reaper.rs index 918d415..8aecc67 100644 --- a/crates/forge-web/src/ci/reaper.rs +++ b/crates/forge-web/src/ci/reaper.rs @@ -16,6 +16,9 @@ use crate::state::AppState; const REAP_EVERY: Duration = Duration::from_secs(30); /// A running job with no heartbeat for this long is lost. const LOST_AFTER: Duration = Duration::from_secs(120); +/// How often the alert checks that look at the disk and the backup history run. They share this +/// loop rather than adding their own. +const ALERTS_SLOW_EVERY: Duration = Duration::from_secs(5 * 60); /// How often retention runs. const PURGE_EVERY: Duration = Duration::from_secs(24 * 60 * 60); @@ -29,9 +32,15 @@ async fn run(state: AppState) { tick.set_missed_tick_behavior(MissedTickBehavior::Delay); // Retention runs on the first pass after boot, then once a day. let mut next_purge = Instant::now(); + let mut next_slow_alerts = Instant::now() + ALERTS_SLOW_EVERY; loop { tick.tick().await; reap_once(&state).await; + crate::alerts::check_runners(&state).await; + if Instant::now() >= next_slow_alerts { + crate::alerts::check_slow(&state).await; + next_slow_alerts = Instant::now() + ALERTS_SLOW_EVERY; + } if Instant::now() >= next_purge { purge_once(&state).await; next_purge = Instant::now() + PURGE_EVERY; diff --git a/crates/forge-web/src/i18n/admin.rs b/crates/forge-web/src/i18n/admin.rs index d3fa1be..3169be6 100644 --- a/crates/forge-web/src/i18n/admin.rs +++ b/crates/forge-web/src/i18n/admin.rs @@ -73,6 +73,7 @@ pub enum K { SrvTabStorage, SrvTabBackups, SrvTabIntegrations, + SrvTabAlerts, SrvSaved, SrvNothingChanged, SrvResetDone, @@ -345,6 +346,8 @@ pub fn t(lang: Lang, key: K) -> &'static str { (SrvTabBackups, Tr) => "Yedekler", (SrvTabIntegrations, En) => "Integrations", (SrvTabIntegrations, Tr) => "Entegrasyonlar", + (SrvTabAlerts, En) => "Alerts", + (SrvTabAlerts, Tr) => "Uyarılar", (SrvSaved, En) => "Server settings saved.", (SrvSaved, Tr) => "Sunucu ayarları kaydedildi.", (SrvNothingChanged, En) => "Nothing changed.", @@ -859,6 +862,7 @@ mod tests { K::SrvTabStorage, K::SrvTabBackups, K::SrvTabIntegrations, + K::SrvTabAlerts, K::SrvSaved, K::SrvNothingChanged, K::SrvResetDone, diff --git a/crates/forge-web/src/i18n/alerts.rs b/crates/forge-web/src/i18n/alerts.rs new file mode 100644 index 0000000..316d1f4 --- /dev/null +++ b/crates/forge-web/src/i18n/alerts.rs @@ -0,0 +1,238 @@ +//! Strings for admin alerts: the inbox rows, the `/admin/health` banner and the emails. An alert +//! is stored as a topic, a subject and a detail, and worded here in the reader's language. +//! +//! Topics: `runner_offline`, `backup_failed`, `backup_verify_failed`, `backup_overdue`, +//! `fsck_failed`, `disk_low`, `ci_killed`, `self_update_restart`, `self_update_failed`, +//! `replication`. + +use super::Lang; + +/// The one-line headline of an alert. `resolved` words the message that says it is over. +pub fn title(lang: Lang, topic: &str, subject: &str, resolved: bool) -> String { + match (lang, topic, resolved) { + (Lang::En, "runner_offline", false) => format!("Runner {subject} is offline"), + (Lang::En, "runner_offline", true) => format!("Runner {subject} is back online"), + (Lang::Tr, "runner_offline", false) => format!("{subject} runner'ı çevrimdışı"), + (Lang::Tr, "runner_offline", true) => format!("{subject} runner'ı yeniden çevrimiçi"), + + (Lang::En, "backup_failed", false) => "A backup failed".to_owned(), + (Lang::En, "backup_failed", true) => "Backups work again".to_owned(), + (Lang::Tr, "backup_failed", false) => "Bir yedekleme başarısız oldu".to_owned(), + (Lang::Tr, "backup_failed", true) => "Yedeklemeler yeniden çalışıyor".to_owned(), + + (Lang::En, "backup_verify_failed", false) => "Backup verification failed".to_owned(), + (Lang::En, "backup_verify_failed", true) => "Backup verification passes again".to_owned(), + (Lang::Tr, "backup_verify_failed", false) => "Yedek doğrulaması başarısız oldu".to_owned(), + (Lang::Tr, "backup_verify_failed", true) => "Yedek doğrulaması yeniden başarılı".to_owned(), + + (Lang::En, "backup_overdue", false) => "No recent backup".to_owned(), + (Lang::En, "backup_overdue", true) => "A backup finished, none overdue".to_owned(), + (Lang::Tr, "backup_overdue", false) => "Yakın zamanda yedek alınmadı".to_owned(), + (Lang::Tr, "backup_overdue", true) => "Bir yedek tamamlandı, gecikme yok".to_owned(), + + (Lang::En, "fsck_failed", false) => "The integrity check found problems".to_owned(), + (Lang::En, "fsck_failed", true) => "The integrity check passes again".to_owned(), + (Lang::Tr, "fsck_failed", false) => "Bütünlük denetimi sorun buldu".to_owned(), + (Lang::Tr, "fsck_failed", true) => "Bütünlük denetimi yeniden başarılı".to_owned(), + + (Lang::En, "disk_low", false) => "Disk space is low".to_owned(), + (Lang::En, "disk_low", true) => "Disk space is back to normal".to_owned(), + (Lang::Tr, "disk_low", false) => "Disk alanı azaldı".to_owned(), + (Lang::Tr, "disk_low", true) => "Disk alanı normale döndü".to_owned(), + + (Lang::En, "ci_killed", _) => format!("A CI job was killed on runner {subject}"), + (Lang::Tr, "ci_killed", _) => format!("{subject} runner'ında bir CI işi öldürüldü"), + + (Lang::En, "self_update_restart", false) => "Self-update deployed, restarting".to_owned(), + (Lang::En, "self_update_restart", true) => "Server restarted after self-update".to_owned(), + (Lang::Tr, "self_update_restart", false) => { + "Kendini güncelleme dağıtıldı, yeniden başlıyor".to_owned() + } + (Lang::Tr, "self_update_restart", true) => { + "Sunucu kendini güncelledikten sonra yeniden başladı".to_owned() + } + + (Lang::En, "self_update_failed", _) => "Self-update failed".to_owned(), + (Lang::Tr, "self_update_failed", _) => "Kendini güncelleme başarısız oldu".to_owned(), + + (Lang::En, "replication", false) => "Standby replication has a problem".to_owned(), + (Lang::En, "replication", true) => "Standby replication is healthy again".to_owned(), + (Lang::Tr, "replication", false) => "Yedek sunucuya kopyalamada sorun var".to_owned(), + (Lang::Tr, "replication", true) => "Yedek sunucuya kopyalama yeniden sağlıklı".to_owned(), + + (_, other, _) => other.to_owned(), + } +} + +/// The explanation under the headline. +pub fn body(lang: Lang, topic: &str, subject: &str, detail: &str, resolved: bool) -> String { + match (lang, topic, resolved) { + (Lang::En, "runner_offline", false) => format!( + "No heartbeat since {detail}. Queued jobs wait for another runner until it returns." + ), + (Lang::Tr, "runner_offline", false) => format!( + "{detail} tarihinden beri sinyal yok. Sıradaki işler, geri dönene kadar başka bir runner bekler." + ), + (Lang::En, "runner_offline", true) => format!("Runner {subject} checked in again."), + (Lang::Tr, "runner_offline", true) => format!("{subject} runner'ı yeniden bağlandı."), + + (Lang::En, "backup_failed" | "backup_verify_failed" | "fsck_failed", false) => { + detail.to_owned() + } + (Lang::Tr, "backup_failed" | "backup_verify_failed" | "fsck_failed", false) => { + detail.to_owned() + } + (Lang::En, "backup_failed", true) => "The latest backup succeeded.".to_owned(), + (Lang::Tr, "backup_failed", true) => "Son yedekleme başarılı oldu.".to_owned(), + (Lang::En, "backup_verify_failed", true) => { + "The latest backup set was verified.".to_owned() + } + (Lang::Tr, "backup_verify_failed", true) => "Son yedek seti doğrulandı.".to_owned(), + (Lang::En, "fsck_failed", true) => "The latest integrity check was clean.".to_owned(), + (Lang::Tr, "fsck_failed", true) => "Son bütünlük denetimi temiz çıktı.".to_owned(), + + (Lang::En, "backup_overdue", false) => format!( + "No backup has succeeded within twice the schedule interval. Last good backup: {detail}." + ), + (Lang::Tr, "backup_overdue", false) => format!( + "Zamanlama aralığının iki katı içinde başarılı yedek yok. Son iyi yedek: {detail}." + ), + (Lang::En, "backup_overdue", true) => "The backup schedule is back on track.".to_owned(), + (Lang::Tr, "backup_overdue", true) => "Yedekleme takvimi yeniden yolunda.".to_owned(), + + (Lang::En, "disk_low", false) => format!("{subject}: {detail}."), + (Lang::Tr, "disk_low", false) => format!("{subject}: {detail}."), + (Lang::En, "disk_low", true) => format!("{subject} has enough free space again."), + (Lang::Tr, "disk_low", true) => format!("{subject} yeniden yeterli boş alana sahip."), + + (Lang::En, "ci_killed", _) => format!( + "{detail} ended with a kill signal, probably the out-of-memory killer. \ + Consider lowering the concurrency of runner {subject}." + ), + (Lang::Tr, "ci_killed", _) => format!( + "{detail} bir öldürme sinyaliyle sona erdi, büyük olasılıkla bellek yetersizliği. \ + {subject} runner'ının eşzamanlılığını düşürmeyi düşünün." + ), + + (Lang::En, "self_update_restart", false) => { + format!("Version {subject} is installed. The server is restarting to run it.") + } + (Lang::Tr, "self_update_restart", false) => { + format!("{subject} sürümü kuruldu. Sunucu onu çalıştırmak için yeniden başlıyor.") + } + (Lang::En, "self_update_restart", true) => { + format!("The server is running version {subject}.") + } + (Lang::Tr, "self_update_restart", true) => { + format!("Sunucu {subject} sürümünü çalıştırıyor.") + } + + (_, "self_update_failed", _) => detail.to_owned(), + + (Lang::En, "replication", false) => { + format!("{detail} The standby may be behind until this is fixed.") + } + (Lang::Tr, "replication", false) => { + format!("{detail} Bu düzelene kadar yedek sunucu geride kalabilir.") + } + (Lang::En, "replication", true) => "The standby is up to date.".to_owned(), + (Lang::Tr, "replication", true) => "Yedek sunucu güncel.".to_owned(), + + _ => detail.to_owned(), + } +} + +/// Label of the group heading in the inbox, and of the banner on the health page. +pub fn inbox_heading(lang: Lang) -> &'static str { + match lang { + Lang::En => "Admin alerts", + Lang::Tr => "Yönetici uyarıları", + } +} + +/// Banner heading on `/admin/health`. +pub fn banner_heading(lang: Lang, count: usize) -> String { + match lang { + Lang::En if count == 1 => "1 active alert".to_owned(), + Lang::En => format!("{count} active alerts"), + Lang::Tr => format!("{count} etkin uyarı"), + } +} + +/// Link from the banner to the alert settings. +pub fn settings_link(lang: Lang) -> &'static str { + match lang { + Lang::En => "Alert settings", + Lang::Tr => "Uyarı ayarları", + } +} + +/// "since