Files
Infrastruktur-Monitoring-Sy…/backend/crates/infrastructure/src/host/debian.rs
Dennis Nemec 1f56f015a2
Some checks failed
CI / backend (push) Has been cancelled
CI / frontend (push) Has been cancelled
CI / ui (push) Has been cancelled
WP-11: contract and failing tests for package upgrades
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-02 22:24:40 +02:00

276 lines
9.6 KiB
Rust

//! Inspector for Debian hosts using dpkg, apt-get and snap.
use std::sync::Arc;
use async_trait::async_trait;
use domain::host::{OsInfo, Package, PackageSource};
use domain::ports::HostInspector;
use domain::DomainError;
use super::command::CommandRunner;
pub struct DebianInspector {
runner: Arc<dyn CommandRunner>,
}
impl DebianInspector {
pub fn new(runner: Arc<dyn CommandRunner>) -> Self {
Self { runner }
}
}
#[async_trait]
impl HostInspector for DebianInspector {
async fn os_info(&self) -> Result<OsInfo, DomainError> {
let r = &self.runner;
let (name, version) =
parse_os_release(&r.read_file("/etc/os-release").await?.unwrap_or_default());
let uptime_secs = r
.read_file("/proc/uptime")
.await?
.and_then(|s| s.split_whitespace().next()?.parse::<f64>().ok())
.unwrap_or(0.0) as u64;
Ok(OsInfo {
hostname: r.run("hostname", &[]).await?.stdout.trim().to_string(),
name,
version,
kernel: r.run("uname", &["-r"]).await?.stdout.trim().to_string(),
uptime_secs,
reboot_required: r.read_file("/var/run/reboot-required").await?.is_some(),
})
}
async fn packages(&self) -> Result<Vec<Package>, DomainError> {
let r = &self.runner;
let dpkg = r
.run(
"dpkg-query",
&["-W", "-f", "${Package}\t${Version}\t${Status}\n"],
)
.await?;
if !dpkg.success {
return Err(DomainError::Unavailable(format!(
"dpkg-query failed: {}",
dpkg.stderr.trim()
)));
}
// refresh the package index first; a failure here is logged but not fatal
let _ = r.run("apt-get", &["update", "-q"]).await;
let sim = r
.run(
"apt-get",
&[
"-s",
"--with-new-pkgs",
"-o",
"Debug::NoLocking=1",
"upgrade",
],
)
.await?;
let upgrades: std::collections::HashMap<String, (String, bool)> =
parse_apt_simulation(&sim.stdout)
.into_iter()
.map(|(n, v, s)| (n, (v, s)))
.collect();
let mut packages: Vec<Package> = parse_dpkg(&dpkg.stdout)
.into_iter()
.map(|(name, installed)| {
let up = upgrades.get(&name);
Package {
candidate: up.map(|(v, _)| v.clone()),
is_security: up.is_some_and(|(_, s)| *s),
name,
source: PackageSource::Apt,
installed,
}
})
.collect();
if let Ok(snap) = r.run("snap", &["list"]).await {
packages.extend(
parse_snap_list(&snap.stdout)
.into_iter()
.map(|(name, installed)| Package {
name,
source: PackageSource::Snap,
installed,
candidate: None,
is_security: false,
}),
);
}
Ok(packages)
}
}
/// `dpkg-query -W -f '${Package}\t${Version}\t${Status}\n'` → (name, version) of installed packages.
pub fn parse_dpkg(out: &str) -> Vec<(String, String)> {
out.lines()
.filter_map(|l| {
let mut it = l.split('\t');
let (name, version, status) = (it.next()?, it.next()?, it.next()?);
(status.trim() == "install ok installed")
.then(|| (name.to_string(), version.to_string()))
})
.collect()
}
/// `apt-get -s upgrade` → (name, candidate version, is_security) for lines starting with `Inst`.
pub fn parse_apt_simulation(out: &str) -> Vec<(String, String, bool)> {
out.lines()
.filter_map(|l| {
let rest = l.strip_prefix("Inst ")?;
let name = rest.split_whitespace().next()?;
let paren = &rest[rest.find('(')? + 1..];
let version = paren.split_whitespace().next()?;
let is_security = paren.to_ascii_lowercase().contains("security");
Some((name.to_string(), version.to_string(), is_security))
})
.collect()
}
/// `snap list` → (name, version) skipping the header.
pub fn parse_snap_list(out: &str) -> Vec<(String, String)> {
out.lines()
.skip(1)
.filter_map(|l| {
let mut it = l.split_whitespace();
Some((it.next()?.to_string(), it.next()?.to_string()))
})
.collect()
}
/// `/etc/os-release` → (PRETTY_NAME, VERSION_ID).
pub fn parse_os_release(content: &str) -> (String, String) {
let get = |key: &str| {
content
.lines()
.find_map(|l| l.strip_prefix(key)?.strip_prefix('='))
.map(|v| v.trim().trim_matches('"').to_string())
.unwrap_or_default()
};
(get("PRETTY_NAME"), get("VERSION_ID"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dpkg_keeps_only_installed() {
let out = "bash\t5.2.15-2+b7\tinstall ok installed\nold\t1.0\tdeinstall ok config-files\nzlib1g\t1:1.2.13.dfsg-1\tinstall ok installed\n";
assert_eq!(
parse_dpkg(out),
vec![
("bash".to_string(), "5.2.15-2+b7".to_string()),
("zlib1g".to_string(), "1:1.2.13.dfsg-1".to_string())
]
);
}
#[test]
fn apt_simulation_extracts_candidates_and_security_flag() {
let out = "Reading package lists...\nBuilding dependency tree...\n\
Inst openssl [3.0.15-1~deb12u1] (3.0.16-1~deb12u1 Debian-Security:12/stable-security [amd64])\n\
Inst curl [7.88.1-10+deb12u8] (7.88.1-10+deb12u12 Debian:12.9/stable [amd64]) []\n\
Conf openssl (3.0.16-1~deb12u1 Debian-Security:12/stable-security [amd64])\n";
assert_eq!(
parse_apt_simulation(out),
vec![
("openssl".to_string(), "3.0.16-1~deb12u1".to_string(), true),
("curl".to_string(), "7.88.1-10+deb12u12".to_string(), false)
]
);
}
#[test]
fn snap_list_skips_header() {
let out = "Name Version Rev Tracking Publisher Notes\ncore20 20260410 2866 latest/stable canonical** base\nmicrok8s v1.32.13 8702 1.32/stable canonical** classic\n";
assert_eq!(
parse_snap_list(out),
vec![
("core20".to_string(), "20260410".to_string()),
("microk8s".to_string(), "v1.32.13".to_string())
]
);
}
#[test]
fn os_release_strips_quotes() {
let c = "PRETTY_NAME=\"Debian GNU/Linux 12 (bookworm)\"\nNAME=\"Debian GNU/Linux\"\nVERSION_ID=\"12\"\n";
assert_eq!(
parse_os_release(c),
(
"Debian GNU/Linux 12 (bookworm)".to_string(),
"12".to_string()
)
);
}
struct Canned;
#[async_trait]
impl CommandRunner for Canned {
async fn run(
&self,
program: &str,
args: &[&str],
) -> Result<super::super::Output, DomainError> {
let stdout = match (program, args.first().copied()) {
("dpkg-query", _) => "bash\t5.2\tinstall ok installed\nopenssl\t3.0.15\tinstall ok installed\n",
("apt-get", Some("-s")) => "Inst openssl [3.0.15] (3.0.16 Debian-Security:12/stable-security [amd64])\n",
("apt-get", _) => "",
("snap", _) => "Name Version Rev Tracking Publisher Notes\nmicrok8s v1.32.13 8702 1.32/stable canonical** classic\n",
("uname", _) => "6.1.0-42-amd64\n",
("hostname", _) => "srv\n",
_ => "",
};
Ok(super::super::Output {
stdout: stdout.into(),
stderr: String::new(),
success: true,
})
}
async fn run_streaming(
&self,
_p: &str,
_a: &[&str],
_o: &dyn domain::ports::LineSink,
) -> Result<bool, DomainError> {
unreachable!()
}
async fn read_file(&self, path: &str) -> Result<Option<String>, DomainError> {
Ok(match path {
"/etc/os-release" => Some(
"PRETTY_NAME=\"Debian GNU/Linux 12 (bookworm)\"\nVERSION_ID=\"12\"\n".into(),
),
"/proc/uptime" => Some("12345.67 40000.00\n".into()),
"/var/run/reboot-required" => Some(String::new()),
_ => None,
})
}
}
#[tokio::test]
async fn inspector_combines_sources() {
let i = DebianInspector::new(Arc::new(Canned));
let os = i.os_info().await.unwrap();
assert_eq!(os.hostname, "srv");
assert_eq!(os.version, "12");
assert_eq!(os.kernel, "6.1.0-42-amd64");
assert_eq!(os.uptime_secs, 12345);
assert!(os.reboot_required);
let pkgs = i.packages().await.unwrap();
assert_eq!(pkgs.len(), 3);
let openssl = pkgs.iter().find(|p| p.name == "openssl").unwrap();
assert_eq!(openssl.candidate.as_deref(), Some("3.0.16"));
assert!(openssl.is_security);
assert_eq!(
pkgs.iter().find(|p| p.name == "bash").unwrap().candidate,
None
);
assert_eq!(
pkgs.iter().find(|p| p.name == "microk8s").unwrap().source,
domain::host::PackageSource::Snap
);
}
}