Files
vps-control/agent/src/services.rs
2026-09-22 23:37:05 +03:00

200 lines
5.9 KiB
Rust

use crate::{
command,
config::{valid_service_name, Services},
privileged,
};
use anyhow::{bail, Result};
use serde::Serialize;
use std::{collections::HashMap, time::Duration};
#[derive(Debug, Serialize)]
pub struct ServiceStatus {
pub name: String,
pub load_state: String,
pub active_state: String,
pub sub_state: String,
pub description: String,
pub unit_file_state: String,
pub managed: bool,
pub install_available: bool,
}
pub async fn list(config: &Services, timeout: Duration) -> Vec<ServiceStatus> {
let units_future = command::run(
"systemctl",
&[
"list-units",
"--type=service",
"--all",
"--no-legend",
"--no-pager",
"--plain",
],
timeout,
);
let files_future = command::run(
"systemctl",
&[
"list-unit-files",
"--type=service",
"--no-legend",
"--no-pager",
],
timeout,
);
let (units_output, files_output) = tokio::join!(units_future, files_future);
let unit_files = files_output
.ok()
.map(|output| parse_unit_files(&output.stdout))
.unwrap_or_default();
let mut rows = match units_output {
Ok(output) => parse_units(&output.stdout, config),
Err(_) => Vec::new(),
};
for row in &mut rows {
row.unit_file_state = unit_files
.get(&row.name)
.cloned()
.unwrap_or_else(|| "unknown".into());
}
for (name, state) in &unit_files {
if !rows.iter().any(|item| &item.name == name) {
let managed = config.allowed.iter().any(|item| item == name);
rows.push(ServiceStatus {
name: name.clone(),
load_state: "loaded".into(),
active_state: "inactive".into(),
sub_state: "dead".into(),
description: "Installed unit file".into(),
unit_file_state: state.clone(),
managed,
install_available: false,
});
}
}
for name in &config.allowed {
if !rows.iter().any(|item| &item.name == name) {
rows.push(ServiceStatus {
name: name.clone(),
load_state: "not-found".into(),
active_state: "inactive".into(),
sub_state: "dead".into(),
description: config
.packages
.get(name)
.map(|package| format!("Not installed (package: {package})"))
.unwrap_or_else(|| "Not installed".into()),
unit_file_state: "not-found".into(),
managed: true,
install_available: config.install_enabled && config.packages.contains_key(name),
});
}
}
rows.sort_by(|left, right| {
right
.managed
.cmp(&left.managed)
.then_with(|| left.name.cmp(&right.name))
});
rows.truncate(config.inventory_limit);
rows
}
pub async fn action(
name: &str,
operation: &str,
config: &Services,
timeout: Duration,
) -> Result<()> {
validate_managed(name, config)?;
if !matches!(
operation,
"start" | "stop" | "restart" | "enable" | "disable"
) {
bail!("unsupported service operation")
}
privileged::call(
&privileged::Request::ServiceAction {
service: name.into(),
operation: operation.into(),
},
timeout,
)
.await?;
Ok(())
}
pub async fn install(name: &str, config: &Services, timeout: Duration) -> Result<()> {
validate_managed(name, config)?;
if !config.install_enabled || !config.packages.contains_key(name) {
bail!("service installation is disabled or unavailable")
}
privileged::call(
&privileged::Request::ServiceInstall {
service: name.into(),
},
timeout,
)
.await?;
Ok(())
}
fn validate_managed(name: &str, config: &Services) -> Result<()> {
if !valid_service_name(name) || !config.allowed.iter().any(|item| item == name) {
bail!("service is not allow-listed")
}
Ok(())
}
fn parse_units(text: &str, config: &Services) -> Vec<ServiceStatus> {
text.lines()
.filter_map(|line| {
let mut fields = line.split_whitespace();
let name = fields.next()?.trim_start_matches(['●', ' ']).to_owned();
let load_state = fields.next()?.to_owned();
let active_state = fields.next()?.to_owned();
let sub_state = fields.next()?.to_owned();
let description = fields.collect::<Vec<_>>().join(" ");
let managed = config.allowed.iter().any(|item| item == &name);
Some(ServiceStatus {
install_available: managed
&& config.install_enabled
&& config.packages.contains_key(&name),
name,
load_state,
active_state,
sub_state,
description,
unit_file_state: "unknown".into(),
managed,
})
})
.collect()
}
fn parse_unit_files(text: &str) -> HashMap<String, String> {
text.lines()
.filter_map(|line| {
let mut fields = line.split_whitespace();
Some((fields.next()?.to_owned(), fields.next()?.to_owned()))
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_systemd_inventory() {
let config = Services {
allowed: vec!["nginx.service".into()],
..Services::default()
};
let rows = parse_units("nginx.service loaded active running A web server\nssh.service loaded inactive dead SSH daemon\n", &config);
assert_eq!(rows.len(), 2);
assert!(rows[0].managed);
assert_eq!(rows[0].description, "A web server");
}
}