update
This commit is contained in:
@@ -1,4 +1,8 @@
|
||||
use crate::{command, config::valid_service_name};
|
||||
use crate::{
|
||||
command,
|
||||
config::{valid_service_name, Services},
|
||||
privileged,
|
||||
};
|
||||
use anyhow::{bail, Result};
|
||||
use serde::Serialize;
|
||||
use std::{collections::HashMap, time::Duration};
|
||||
@@ -6,100 +10,190 @@ 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 pid: u32,
|
||||
pub memory_bytes: Option<u64>,
|
||||
pub active_since_monotonic_us: Option<u64>,
|
||||
pub description: String,
|
||||
pub unit_file_state: String,
|
||||
pub managed: bool,
|
||||
pub install_available: bool,
|
||||
}
|
||||
|
||||
pub async fn list(allowed: &[String], timeout: Duration) -> Vec<ServiceStatus> {
|
||||
let mut result = Vec::with_capacity(allowed.len());
|
||||
for name in allowed {
|
||||
match inspect(name, timeout).await {
|
||||
Ok(status) => result.push(status),
|
||||
Err(_) => result.push(ServiceStatus {
|
||||
name: name.clone(),
|
||||
active_state: "unavailable".into(),
|
||||
sub_state: "unknown".into(),
|
||||
pid: 0,
|
||||
memory_bytes: None,
|
||||
active_since_monotonic_us: None,
|
||||
}),
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub async fn restart(name: &str, allowed: &[String], timeout: Duration) -> Result<()> {
|
||||
if !valid_service_name(name) || !allowed.iter().any(|item| item == name) {
|
||||
bail!("service is not allow-listed")
|
||||
}
|
||||
command::run("systemctl", &["restart", "--", name], timeout).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn inspect(name: &str, timeout: Duration) -> Result<ServiceStatus> {
|
||||
if !valid_service_name(name) {
|
||||
bail!("invalid service name")
|
||||
}
|
||||
let output = command::run(
|
||||
pub async fn list(config: &Services, timeout: Duration) -> Vec<ServiceStatus> {
|
||||
let units_future = command::run(
|
||||
"systemctl",
|
||||
&[
|
||||
"show",
|
||||
"list-units",
|
||||
"--type=service",
|
||||
"--all",
|
||||
"--no-legend",
|
||||
"--no-pager",
|
||||
"--property=ActiveState,SubState,MainPID,MemoryCurrent,ActiveEnterTimestampMonotonic",
|
||||
"--",
|
||||
name,
|
||||
"--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?;
|
||||
let values: HashMap<_, _> = output
|
||||
.stdout
|
||||
.lines()
|
||||
.filter_map(|line| line.split_once('='))
|
||||
.collect();
|
||||
Ok(ServiceStatus {
|
||||
name: name.to_owned(),
|
||||
active_state: values
|
||||
.get("ActiveState")
|
||||
.copied()
|
||||
.unwrap_or("unknown")
|
||||
.to_owned(),
|
||||
sub_state: values
|
||||
.get("SubState")
|
||||
.copied()
|
||||
.unwrap_or("unknown")
|
||||
.to_owned(),
|
||||
pid: values
|
||||
.get("MainPID")
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or_default(),
|
||||
memory_bytes: values.get("MemoryCurrent").and_then(|v| v.parse().ok()),
|
||||
active_since_monotonic_us: values
|
||||
.get("ActiveEnterTimestampMonotonic")
|
||||
.and_then(|v| v.parse().ok()),
|
||||
})
|
||||
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::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_service_outside_allowlist_without_execution() {
|
||||
assert!(
|
||||
restart("postgresql", &["nginx".into()], Duration::from_secs(1))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(restart(
|
||||
"nginx;reboot",
|
||||
&["nginx;reboot".into()],
|
||||
Duration::from_secs(1)
|
||||
)
|
||||
.await
|
||||
.is_err());
|
||||
#[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");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user