//! systemd source over D-Bus (WS-A). Every call hits the bus live; only the //! connection is cached, and it is opened lazily on first use. use async_trait::async_trait; use jiff::Timestamp; use tokio::sync::OnceCell; use tokio_util::sync::CancellationToken; use zbus::zvariant::OwnedObjectPath; use zbus::Connection; use zbus_systemd::systemd1::{ManagerProxy, ServiceProxy, TimerProxy, UnitProxy}; use super::{SystemdSource, TimerInfo, UnitStatus, UnitSummary}; use crate::config::Config; use crate::error::AppError; const NO_SUCH_UNIT: &str = "org.freedesktop.systemd1.NoSuchUnit"; /// One `ListUnits` row: name, description, load, active, sub, followed, /// unit path, job id, job type, job path. type UnitRow = ( String, String, String, String, String, String, OwnedObjectPath, u32, String, OwnedObjectPath, ); pub struct DbusSystemd { conn: OnceCell, #[allow(dead_code)] shutdown: CancellationToken, } impl DbusSystemd { /// Does not touch the bus; the connection is made on first use and /// failures map to `AppError::Unavailable`. pub fn new(_config: &Config, shutdown: CancellationToken) -> Self { Self { conn: OnceCell::new(), shutdown, } } async fn conn(&self) -> Result<&Connection, AppError> { self.conn .get_or_try_init(|| async { Connection::system() .await .map_err(|e| AppError::Unavailable(format!("system bus: {e}"))) }) .await } async fn manager(&self) -> Result, AppError> { ManagerProxy::new(self.conn().await?).await.map_err(map_err) } } /// Validate a unit name against systemd's charset and length limit. pub(crate) fn validate_unit_name(name: &str) -> Result<(), AppError> { let ok = !name.is_empty() && name.len() <= 255 && name .chars() .all(|c| c.is_ascii_alphanumeric() || matches!(c, ':' | '_' | '.' | '@' | '-' | '\\')); if ok { Ok(()) } else { Err(AppError::BadRequest(format!("invalid unit name: {name:?}"))) } } /// Microseconds since the epoch to a timestamp. `0` and `u64::MAX` mean unset. pub(crate) fn usec_to_ts(usec: u64) -> Option { if usec == 0 || usec == u64::MAX { return None; } let micros = i64::try_from(usec).ok()?; Timestamp::from_microsecond(micros).ok() } pub(crate) fn row_to_summary(row: UnitRow) -> UnitSummary { UnitSummary { name: row.0, description: row.1, load_state: row.2, active_state: row.3, sub_state: row.4, } } fn is_no_such_unit(e: &zbus::Error) -> bool { matches!(e, zbus::Error::MethodError(n, _, _) if n.as_str() == NO_SUCH_UNIT) } fn map_err(e: zbus::Error) -> AppError { if is_no_such_unit(&e) { return AppError::NotFound("unit not found".into()); } match &e { zbus::Error::InputOutput(_) | zbus::Error::Address(_) => { AppError::Unavailable(format!("system bus: {e}")) } zbus::Error::FDO(f) if matches!(**f, zbus::fdo::Error::ServiceUnknown(_)) => { AppError::Unavailable(format!("systemd not reachable: {e}")) } _ => AppError::Internal(format!("systemd d-bus: {e}")), } } #[async_trait] impl SystemdSource for DbusSystemd { async fn list_units(&self, state: Option<&str>) -> Result, AppError> { let mgr = self.manager().await?; let rows: Vec = match state { Some(s) => mgr .list_units_filtered(vec![s.to_string()]) .await .map_err(map_err)?, None => mgr.list_units().await.map_err(map_err)?, }; Ok(rows.into_iter().map(row_to_summary).collect()) } async fn list_timers(&self) -> Result, AppError> { let conn = self.conn().await?; let mgr = self.manager().await?; let rows: Vec = mgr .list_units_by_patterns(vec![], vec!["*.timer".to_string()]) .await .map_err(map_err)?; let mut out = Vec::with_capacity(rows.len()); for row in rows { let timer = TimerProxy::builder(conn) .path(row.6.clone()) .map_err(map_err)? .build() .await .map_err(map_err)?; let (unit, next, last) = futures::try_join!( timer.unit(), timer.next_elapse_u_sec_realtime(), timer.last_trigger_u_sec() ) .map_err(map_err)?; out.push(TimerInfo { name: row.0, unit, active_state: row.3, next_elapse: usec_to_ts(next), last_trigger: usec_to_ts(last), }); } Ok(out) } async fn unit_status(&self, name: &str) -> Result { validate_unit_name(name)?; let conn = self.conn().await?; let mgr = self.manager().await?; let path = match mgr.get_unit(name.to_string()).await { Ok(p) => p, Err(e) if is_no_such_unit(&e) => { mgr.load_unit(name.to_string()).await.map_err(map_err)? } Err(e) => return Err(map_err(e)), }; let unit = UnitProxy::builder(conn) .path(path.clone()) .map_err(map_err)? .build() .await .map_err(map_err)?; let (desc, load, active, sub, enter, exit, frag, ufs) = futures::try_join!( unit.description(), unit.load_state(), unit.active_state(), unit.sub_state(), unit.active_enter_timestamp(), unit.active_exit_timestamp(), unit.fragment_path(), unit.unit_file_state(), ) .map_err(map_err)?; if load == "not-found" { return Err(AppError::NotFound(format!("unit not found: {name}"))); } let mut st = UnitStatus { name: name.to_string(), description: desc, load_state: load, active_state: active, sub_state: sub, fragment_path: (!frag.is_empty()).then_some(frag), unit_file_state: (!ufs.is_empty()).then_some(ufs), active_enter_time: usec_to_ts(enter), active_exit_time: usec_to_ts(exit), main_pid: None, exec_main_status: None, n_restarts: None, result: None, }; if name.ends_with(".service") { let svc = ServiceProxy::builder(conn) .path(path) .map_err(map_err)? .build() .await .map_err(map_err)?; let (pid, status, restarts, result) = futures::try_join!( svc.main_pid(), svc.exec_main_status(), svc.n_restarts(), svc.result() ) .map_err(map_err)?; st.main_pid = Some(pid); st.exec_main_status = Some(status); st.n_restarts = Some(restarts); st.result = Some(result); } Ok(st) } } #[cfg(test)] mod tests { use super::*; #[test] fn usec_conversion() { let ts = usec_to_ts(1_700_000_000_123_456).unwrap(); assert_eq!(ts.to_string(), "2023-11-14T22:13:20.123456Z"); } #[test] fn usec_sentinels() { assert!(usec_to_ts(0).is_none()); assert!(usec_to_ts(u64::MAX).is_none()); } #[test] fn tuple_mapping() { let p = OwnedObjectPath::try_from("/org/freedesktop/systemd1/unit/a_2eservice").unwrap(); let row: UnitRow = ( "a.service".into(), "A".into(), "loaded".into(), "active".into(), "running".into(), String::new(), p.clone(), 0, String::new(), p, ); let s = row_to_summary(row); assert_eq!(s.name, "a.service"); assert_eq!(s.description, "A"); assert_eq!(s.load_state, "loaded"); assert_eq!(s.active_state, "active"); assert_eq!(s.sub_state, "running"); } #[test] fn name_validation() { assert!(validate_unit_name("sshd.service").is_ok()); assert!(validate_unit_name("getty@tty1.service").is_ok()); assert!(validate_unit_name("dev-disk-by\\x2did.device").is_ok()); assert!(matches!( validate_unit_name("../etc"), Err(AppError::BadRequest(_)) )); assert!(validate_unit_name("").is_err()); assert!(validate_unit_name(&"a".repeat(256)).is_err()); } }