diff --git a/TODO.md b/TODO.md index aa672f9..d14b08f 100644 --- a/TODO.md +++ b/TODO.md @@ -27,13 +27,13 @@ Design: [`plan.md`](plan.md) · Review fixes: [`plan/review.md`](plan/review.md) ## Phase 1 — Sources + auth (parallel) ### WS-A systemd · [card](plan/workstreams/WS-A-systemd.md) -- [ ] **A1** Shared system-bus `zbus::Connection` + `ManagerProxy` -- [ ] **A2** `list_units(state)` mapped to `UnitSummary` -- [ ] **A3** `list_timers()` via `*.timer` units + `TimerProxy` props (no `ListTimers` method exists) -- [ ] **A4** `unit_status(name)`: `GetUnit` first, `LoadUnit` as fallback. `Unit` props always, `Service` props for `.service` only. -- [ ] **A5** Unit-name validation. `NoSuchUnit` maps to `NotFound`. -- [ ] **A6** `examples/systemd_dump.rs` prints JSON from the live bus -- [ ] **A7** Unit tests for timestamp conversion and property mapping +- [x] **A1** Shared system-bus `zbus::Connection` + `ManagerProxy` +- [x] **A2** `list_units(state)` mapped to `UnitSummary` +- [x] **A3** `list_timers()` via `*.timer` units + `TimerProxy` props (no `ListTimers` method exists) +- [x] **A4** `unit_status(name)`: `GetUnit` first, `LoadUnit` as fallback. `Unit` props always, `Service` props for `.service` only. +- [x] **A5** Unit-name validation. `NoSuchUnit` maps to `NotFound`. +- [x] **A6** `examples/systemd_dump.rs` prints JSON from the live bus +- [x] **A7** Unit tests for timestamp conversion and property mapping ### WS-B journal · [card](plan/workstreams/WS-B-journal.md) - [ ] **B1** All sd-journal access inside `spawn_blocking`. Optional namespace, depending on the spike. diff --git a/examples/systemd_dump.rs b/examples/systemd_dump.rs new file mode 100644 index 0000000..bb3265c --- /dev/null +++ b/examples/systemd_dump.rs @@ -0,0 +1,23 @@ +//! Dump systemd state from the live system bus as JSON. +//! Usage: cargo run --example systemd_dump [unit-name] + +use skyg_linux_tracker::config::Config; +use skyg_linux_tracker::sources::systemd::DbusSystemd; +use skyg_linux_tracker::sources::SystemdSource; +use tokio_util::sync::CancellationToken; + +#[tokio::main] +async fn main() -> Result<(), Box> { + let unit = std::env::args() + .nth(1) + .unwrap_or_else(|| "dbus.service".to_string()); + let src = DbusSystemd::new(&Config::default(), CancellationToken::new()); + let out = serde_json::json!({ + "units": src.list_units(None).await?, + "failed": src.list_units(Some("failed")).await?, + "timers": src.list_timers().await?, + "status": src.unit_status(&unit).await?, + }); + println!("{}", serde_json::to_string_pretty(&out)?); + Ok(()) +} diff --git a/plan/workstreams/WS-A-systemd.md b/plan/workstreams/WS-A-systemd.md index 8ccc30c..817d2d4 100644 --- a/plan/workstreams/WS-A-systemd.md +++ b/plan/workstreams/WS-A-systemd.md @@ -2,7 +2,7 @@ | Field | Value | |---|---| -| Status | Backlog | +| Status | Review | | Owner | — | | Phase | 1 (parallel) | | Depends on | P0 | @@ -40,3 +40,4 @@ Tick these in [`TODO.md`](../../TODO.md). ## Log - 2026-10-15: Card created. +- 2026-10-15: Implemented on branch `ws-a/systemd-source`. Gates pass; example verified on live bus (timers match `systemctl list-timers`, NotFound/BadRequest verified). Beyond spec: LoadUnit result with load_state `not-found` also maps to NotFound; `unit_file_state`/`active_exit_time` populated. diff --git a/src/sources/systemd.rs b/src/sources/systemd.rs index 4a3264c..f12f970 100644 --- a/src/sources/systemd.rs +++ b/src/sources/systemd.rs @@ -1,38 +1,282 @@ -//! systemd source over D-Bus (WS-A owns this file). -//! -//! STUB: signatures are final, bodies are `todo!()`. -//! Notes for WS-A: use `zbus_systemd::systemd1::{ManagerProxy, UnitProxy, -//! ServiceProxy, TimerProxy}`. There is no `ListTimers` method; list `*.timer` -//! units and read `TimerProxy` properties (see plan/review.md R1, R2). +//! 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; -pub struct DbusSystemd {} +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 { - /// Must not fail or block: connect to the bus lazily on first use and map - /// connection errors to `AppError::Unavailable`. - pub fn new(_config: &Config, _shutdown: CancellationToken) -> Self { - Self {} + /// 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> { - todo!("WS-A A2") + 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> { - todo!("WS-A A3") + 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 { - todo!("WS-A A4") + 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()); } }