Phase 2b: Optimize to single systemctl command

Reduce from 2 systemctl commands to 1 by using only:
systemctl list-units --type=service --all

This captures all services (active, inactive, failed) in one call,
eliminating the redundant list-unit-files command.
Achieves the TODO.md goal of reducing systemctl calls.
This commit is contained in:
Christoffer Martinsson 2025-10-23 12:34:54 +02:00
parent 9133e18090
commit dc11538ae9

View File

@ -115,15 +115,7 @@ impl SystemdCollector {
/// Auto-discover interesting services to monitor
fn discover_services(&self) -> Result<Vec<String>> {
// First get all unit files (includes inactive services)
let unit_files_output = Command::new("systemctl")
.arg("list-unit-files")
.arg("--type=service")
.arg("--no-pager")
.arg("--plain")
.output()?;
// Then get all loaded units (includes running/failed services)
// Get all services (includes inactive, running, failed - everything)
let units_output = Command::new("systemctl")
.arg("list-units")
.arg("--type=service")
@ -132,12 +124,10 @@ impl SystemdCollector {
.arg("--plain")
.output()?;
if !unit_files_output.status.success() || !units_output.status.success() {
if !units_output.status.success() {
return Err(anyhow::anyhow!("systemctl system command failed"));
}
let unit_files_str = String::from_utf8(unit_files_output.stdout)?;
let units_str = String::from_utf8(units_output.stdout)?;
let mut services = Vec::new();
@ -145,19 +135,9 @@ impl SystemdCollector {
let excluded_services = &self.config.excluded_services;
let service_name_filters = &self.config.service_name_filters;
// Parse both unit files and loaded units
// Parse all services from single systemctl command
let mut all_service_names = std::collections::HashSet::new();
// Parse unit files (includes inactive services)
for line in unit_files_str.lines() {
let fields: Vec<&str> = line.split_whitespace().collect();
if fields.len() >= 2 && fields[0].ends_with(".service") {
let service_name = fields[0].trim_end_matches(".service");
all_service_names.insert(service_name.to_string());
}
}
// Parse loaded units (includes running/failed services)
for line in units_str.lines() {
let fields: Vec<&str> = line.split_whitespace().collect();
if fields.len() >= 4 && fields[0].ends_with(".service") {