use anyhow::{bail, Context, Result};
use service_manager::{
RestartPolicy, ServiceInstallCtx, ServiceLabel, ServiceManager, ServiceStartCtx, ServiceStatus,
ServiceStatusCtx, ServiceStopCtx, ServiceUninstallCtx,
};
use std::{
collections::BTreeSet,
ffi::OsString,
path::{Path, PathBuf},
process::Command,
str::FromStr,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ServiceAction {
Install,
Uninstall,
Start,
Stop,
Status,
List,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ServiceScope {
User,
System,
}
impl ServiceScope {
const fn as_service_level(self) -> service_manager::ServiceLevel {
match self {
Self::User => service_manager::ServiceLevel::User,
Self::System => service_manager::ServiceLevel::System,
}
}
}
#[derive(Debug, Clone)]
pub struct ServiceDefinition {
pub application: String,
pub name: Option<String>,
pub scope: ServiceScope,
pub run_as: Option<String>,
pub launch: Option<ServiceLaunch>,
}
#[derive(Debug, Clone)]
pub struct ServiceLaunch {
pub program: PathBuf,
pub args: Vec<OsString>,
pub working_directory: Option<PathBuf>,
}
impl ServiceLaunch {
pub fn builder(config_path: impl AsRef<Path>) -> Result<ServiceLaunchBuilder> {
let program = std::env::current_exe().context("Cannot determine the executable path")?;
let config_path = absolute_path(config_path.as_ref())?;
let working_directory = config_path.parent().map(PathBuf::from);
let args = vec![OsString::from("--config"), config_path.into_os_string()];
Ok(ServiceLaunchBuilder {
launch: Self {
program,
args,
working_directory,
},
})
}
}
pub struct ServiceLaunchBuilder {
launch: ServiceLaunch,
}
impl ServiceLaunchBuilder {
pub fn program(mut self, program: impl Into<PathBuf>) -> Self {
self.launch.program = program.into();
self
}
pub fn args<I, S>(mut self, args: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<OsString>,
{
self.launch.args = args.into_iter().map(Into::into).collect();
self
}
pub fn arg(mut self, arg: impl Into<OsString>) -> Self {
self.launch.args.push(arg.into());
self
}
pub fn working_directory(mut self, path: Option<PathBuf>) -> Self {
self.launch.working_directory = path;
self
}
pub fn build(self) -> ServiceLaunch {
self.launch
}
}
pub fn manage(action: ServiceAction, definition: &ServiceDefinition) -> Result<()> {
validate_application_name(&definition.application)?;
let mut manager = <dyn ServiceManager>::native()
.context("Cannot detect a supported operating-system service manager")?;
manager
.set_level(definition.scope.as_service_level())
.context("Service manager does not support the requested scope")?;
match action {
ServiceAction::Install => {
let label = service_label(
definition
.name
.as_deref()
.unwrap_or(&definition.application),
)?;
install(manager.as_ref(), label, definition)
}
ServiceAction::Uninstall => {
let Some(label) = definition.name.as_deref().map(service_label).transpose()? else {
list_services(manager.as_ref(), definition, None)?;
bail!("Specify --name to uninstall a service; no service was removed");
};
let status = manager
.status(ServiceStatusCtx {
label: label.clone(),
})
.with_context(|| format!("Cannot read status for service {label}"))?;
if status == ServiceStatus::Running {
manager
.stop(ServiceStopCtx {
label: label.clone(),
})
.with_context(|| format!("Cannot stop service {label}"))?;
}
manager
.uninstall(ServiceUninstallCtx {
label: label.clone(),
})
.with_context(|| format!("Cannot uninstall service {label}"))?;
log::info!("Service {label} uninstalled");
Ok(())
}
ServiceAction::Start => {
let label = required_service_label(definition, "start")?;
manager
.start(ServiceStartCtx {
label: label.clone(),
})
.with_context(|| format!("Cannot start service {label}"))?;
log::info!("Service {label} started");
Ok(())
}
ServiceAction::Stop => {
let label = required_service_label(definition, "stop")?;
manager
.stop(ServiceStopCtx {
label: label.clone(),
})
.with_context(|| format!("Cannot stop service {label}"))?;
log::info!("Service {label} stopped");
Ok(())
}
ServiceAction::Status => {
if let Some(name) = definition.name.as_deref() {
let label = service_label(name)?;
let status = manager
.status(ServiceStatusCtx {
label: label.clone(),
})
.with_context(|| format!("Cannot read status for service {label}"))?;
println!("{label}: {status:?}");
Ok(())
} else {
list_services(manager.as_ref(), definition, None)
}
}
ServiceAction::List => {
list_services(manager.as_ref(), definition, definition.name.as_deref())
}
}
}
fn validate_application_name(application: &str) -> Result<()> {
if application.trim().is_empty() {
bail!("Service application name must not be empty");
}
service_label(application)?;
Ok(())
}
fn required_service_label(definition: &ServiceDefinition, action: &str) -> Result<ServiceLabel> {
let name = definition
.name
.as_deref()
.with_context(|| format!("Specify --name to {action} a service"))?;
service_label(name)
}
fn service_label(name: &str) -> Result<ServiceLabel> {
ServiceLabel::from_str(name).with_context(|| format!("Invalid service name '{name}'"))
}
fn list_services(
manager: &dyn ServiceManager,
definition: &ServiceDefinition,
name_prefix: Option<&str>,
) -> Result<()> {
let mut command = Command::new("systemctl");
match definition.scope {
ServiceScope::User => {
command.arg("--user");
}
ServiceScope::System => {
command.arg("--system");
}
}
let output = command
.args([
"list-unit-files",
"--type=service",
"--no-legend",
"--no-pager",
])
.output()
.context("Cannot run systemctl to list application services")?;
if !output.status.success() {
let error = String::from_utf8_lossy(&output.stderr);
bail!("systemctl could not list services: {}", error.trim());
}
let services = matching_systemd_service_names(
&String::from_utf8_lossy(&output.stdout),
&definition.application,
name_prefix,
);
if services.is_empty() {
println!(
"No matching {} services found in {:?} scope.",
definition.application, definition.scope
);
return Ok(());
}
for name in services {
let label = service_label(&name)?;
let status = manager
.status(ServiceStatusCtx {
label: label.clone(),
})
.with_context(|| format!("Cannot read status for service {label}"))?;
println!("{label}: {status:?}");
}
Ok(())
}
fn matching_systemd_service_names(
output: &str,
application: &str,
name_prefix: Option<&str>,
) -> BTreeSet<String> {
output
.lines()
.filter_map(|line| line.split_whitespace().next())
.filter_map(|unit| unit.strip_suffix(".service"))
.filter(|name| *name == application || name.starts_with(&format!("{application}-")))
.filter(|name| name_prefix.is_none_or(|prefix| name.starts_with(prefix)))
.filter(|name| !name.ends_with('@'))
.map(str::to_owned)
.collect()
}
fn install(
manager: &dyn ServiceManager,
label: ServiceLabel,
definition: &ServiceDefinition,
) -> Result<()> {
let launch = definition
.launch
.as_ref()
.context("Service launch details are required for installation")?;
let username = match definition.scope {
ServiceScope::User => {
if definition.run_as.is_some() {
bail!("--run-as is only valid with --scope system");
}
None
}
ServiceScope::System => Some(
definition
.run_as
.as_ref()
.filter(|username| !username.trim().is_empty())
.context("--run-as USER is required for a system-wide service")?
.clone(),
),
};
let context = ServiceInstallCtx {
label: label.clone(),
program: launch.program.clone(),
args: launch.args.clone(),
contents: None,
username,
working_directory: launch.working_directory.clone(),
environment: None,
autostart: true,
restart_policy: RestartPolicy::Always {
delay_secs: Some(30),
},
};
manager
.install(context)
.with_context(|| format!("Cannot install service {label}"))?;
manager
.start(ServiceStartCtx {
label: label.clone(),
})
.with_context(|| format!("Service {label} installed but failed to start"))?;
log::info!("Service {label} installed and started");
Ok(())
}
pub fn absolute_path(path: &Path) -> Result<PathBuf> {
if path.is_absolute() {
Ok(path.to_owned())
} else {
Ok(std::env::current_dir()
.context("Cannot determine current directory")?
.join(path))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn service_launch_builder_sets_and_overrides_defaults() {
let config_path = Path::new("config.yml");
let absolute_config_path = absolute_path(config_path).unwrap();
let launch = ServiceLaunch::builder(config_path)
.unwrap()
.arg("daemon")
.build();
assert_eq!(launch.program, std::env::current_exe().unwrap());
assert_eq!(
launch.args,
vec![
OsString::from("--config"),
absolute_config_path.clone().into_os_string(),
OsString::from("daemon"),
]
);
assert_eq!(
launch.working_directory,
absolute_config_path.parent().map(PathBuf::from)
);
let launch = ServiceLaunch::builder(config_path)
.unwrap()
.program("/custom/program")
.args(["--custom"])
.working_directory(None)
.build();
assert_eq!(launch.program, PathBuf::from("/custom/program"));
assert_eq!(launch.args, vec![OsString::from("--custom")]);
assert_eq!(launch.working_directory, None);
}
#[test]
fn service_listing_matches_configured_application_names_only() {
let output = "\
steca-mqtt.service enabled enabled
steca-mqtt-test.service disabled enabled
steca-mqtt@.service disabled enabled
abl-evcc.service enabled enabled
other.service enabled enabled
";
assert_eq!(
matching_systemd_service_names(output, "steca-mqtt", None),
BTreeSet::from(["steca-mqtt".to_owned(), "steca-mqtt-test".to_owned()])
);
assert_eq!(
matching_systemd_service_names(output, "abl-evcc", Some("abl-evcc")),
BTreeSet::from(["abl-evcc".to_owned()])
);
}
}