//! Local systemd daemon-health task. Probes the configured units on the host //! PoM runs on, applies the liveness / crash-loop / failed-unit rules, and fires //! alerts on operational → degraded / down transitions. use tokio::task::JoinHandle; use tracing::{info, warn}; use pom::alerts::Alerter; use pom::checks::systemd; use pom::config::Config; use pom::db; use super::{CheckInterval, configured_targets}; pub(crate) fn spawn_systemd_tasks( config: &Config, pool: &sqlx::SqlitePool, cancel: &tokio_util::sync::CancellationToken, alerter: Option<&Alerter>, ) -> Vec> { let mut handles = Vec::new(); for (name, target_config) in configured_targets(config) { let Some(sd_config) = target_config.systemd else { continue; }; let name = name.clone(); let label = target_config.label.clone(); let alerter = alerter.cloned(); let pool = pool.clone(); let cancel = cancel.clone(); info!( "{name}: systemd check every {}s ({} units, failed-sweep={})", sd_config.interval_secs, sd_config.units.len(), sd_config.check_failed, ); handles.push(tokio::spawn(async move { let mut ticks = CheckInterval::new(sd_config.interval_secs, cancel); // Seed previous status from the ledger so a restart while already // degraded does not re-fire: if the latest systemd alert is the // failure (not the recovery) one, start from that non-ok status. let mut previous_status: Option = db::get_latest_alert_matching(&pool, &format!("systemd:{name}"), "systemd_%") .await .ok() .flatten() .filter(|a| a.alert_type == "systemd_failure") .and_then(|a| a.to_status); while ticks.next().await { let result = systemd::check_systemd( &name, &sd_config.units, sd_config.check_failed, sd_config.restart_threshold, ) .await; if result.issues.is_empty() && result.error.is_none() { info!( "{name}: daemons operational ({} units watched)", result.units.len() ); } else { warn!( target = %name, status = %result.status, issues = ?result.issues, "daemons non-operational" ); } if let Err(e) = db::insert_systemd_check(&pool, &result).await { tracing::error!("{name}: failed to store systemd check: {e}"); } if let Some(ref alerter) = alerter { let prev_ok = previous_status .as_deref() .is_none_or(|s| s == "operational"); let now_ok = result.status == "operational"; if prev_ok && !now_ok { alerter .send_systemd_alert(&name, &label, &result.status, &result.issues) .await; } else if !prev_ok && now_ok { alerter.send_systemd_recovery(&name, &label).await; } } previous_status = Some(result.status); } })); } handles }