use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use tokio_util::sync::CancellationToken;
use crate::error::{KernelError, Result};
mod launchd;
mod systemd;
mod windows;
#[cfg(windows)]
pub use windows::run_as_service;
pub const LOG_FILE: &str = "kernel.log";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ServicePlatform {
Launchd,
Systemd,
Windows,
}
impl ServicePlatform {
pub const fn current() -> Option<Self> {
if cfg!(target_os = "macos") {
Some(Self::Launchd)
} else if cfg!(target_os = "linux") {
Some(Self::Systemd)
} else if cfg!(windows) {
Some(Self::Windows)
} else {
None
}
}
pub const fn as_str(self) -> &'static str {
match self {
Self::Launchd => "launchd",
Self::Systemd => "systemd",
Self::Windows => "windows",
}
}
}
impl std::fmt::Display for ServicePlatform {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ServiceDefinition {
pub name: String,
pub program: PathBuf,
pub args: Vec<String>,
pub home: PathBuf,
pub working_directory: PathBuf,
pub environment: Vec<(String, String)>,
pub account: Option<String>,
}
impl ServiceDefinition {
pub fn new(program: impl Into<PathBuf>, home: impl Into<PathBuf>) -> Self {
let home = home.into();
Self {
name: Self::name_for(&home),
program: program.into(),
args: vec!["up".into(), "--home".into(), home.to_string_lossy().into_owned()],
working_directory: home.clone(),
home,
environment: Vec::new(),
account: None,
}
}
pub fn name_for(home: &Path) -> String {
format!("adk-rust-kernel-{}", crate::path_tag(home))
}
#[must_use]
pub fn with_name(mut self, name: impl Into<String>) -> Self {
self.name = name.into();
self
}
#[must_use]
pub fn with_args(mut self, args: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.args = args.into_iter().map(Into::into).collect();
self
}
#[must_use]
pub fn with_working_directory(mut self, directory: impl Into<PathBuf>) -> Self {
self.working_directory = directory.into();
self
}
#[must_use]
pub fn with_env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.environment.push((key.into(), value.into()));
self
}
#[must_use]
pub fn with_account(mut self, account: impl Into<String>) -> Self {
self.account = Some(account.into());
self
}
pub fn log_path(&self) -> PathBuf {
self.home.join(LOG_FILE)
}
fn log_for(&self, platform: ServicePlatform) -> String {
let home = self.home.to_string_lossy();
match platform {
ServicePlatform::Windows => {
format!("{}\\{LOG_FILE}", home.trim_end_matches(['\\', '/']))
}
ServicePlatform::Launchd | ServicePlatform::Systemd => {
format!("{}/{LOG_FILE}", home.trim_end_matches('/'))
}
}
}
pub fn definition_path(&self, platform: ServicePlatform) -> Result<Option<PathBuf>> {
Ok(match platform {
ServicePlatform::Launchd => Some(launchd::plist_path(&self.name)?),
ServicePlatform::Systemd => Some(systemd::unit_path(&self.name)?),
ServicePlatform::Windows => None,
})
}
pub fn render(&self, platform: ServicePlatform) -> String {
match platform {
ServicePlatform::Launchd => launchd::render(self),
ServicePlatform::Systemd => systemd::render(self),
ServicePlatform::Windows => windows::render(self),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Installed {
pub platform: ServicePlatform,
pub name: String,
pub definition: Option<PathBuf>,
pub log: PathBuf,
pub notes: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Uninstalled {
pub platform: ServicePlatform,
pub name: String,
pub definition: Option<PathBuf>,
}
pub fn install(definition: &ServiceDefinition, password: Option<&str>) -> Result<Installed> {
match ServicePlatform::current() {
#[cfg(target_os = "macos")]
Some(ServicePlatform::Launchd) => {
let _ = password;
launchd::install(definition)
}
#[cfg(target_os = "linux")]
Some(ServicePlatform::Systemd) => {
let _ = password;
systemd::install(definition)
}
#[cfg(windows)]
Some(ServicePlatform::Windows) => windows::install(definition, password),
_ => {
let _ = (definition, password);
Err(unsupported())
}
}
}
pub fn uninstall(name: &str) -> Result<Uninstalled> {
match ServicePlatform::current() {
#[cfg(target_os = "macos")]
Some(ServicePlatform::Launchd) => launchd::uninstall(name),
#[cfg(target_os = "linux")]
Some(ServicePlatform::Systemd) => systemd::uninstall(name),
#[cfg(windows)]
Some(ServicePlatform::Windows) => windows::uninstall(name),
_ => {
let _ = name;
Err(unsupported())
}
}
}
fn unsupported() -> KernelError {
KernelError::Service {
reason: "this platform has no service form for the kernel (launchd on macOS, systemd \
on Linux, the service control manager on Windows); run `adk-rust up` under \
your own supervisor"
.into(),
}
}
fn stop_token() -> &'static CancellationToken {
static STOP: OnceLock<CancellationToken> = OnceLock::new();
STOP.get_or_init(CancellationToken::new)
}
pub async fn stop_requested() {
stop_token().cancelled().await;
}
#[cfg(unix)]
fn prepare_log(definition: &ServiceDefinition) -> Result<PathBuf> {
use std::os::unix::fs::OpenOptionsExt as _;
std::fs::create_dir_all(&definition.home).map_err(|error| KernelError::Service {
reason: format!("could not create the kernel home {}: {error}", definition.home.display()),
})?;
let log = definition.log_path();
std::fs::OpenOptions::new().append(true).create(true).mode(0o600).open(&log).map_err(
|error| KernelError::Service {
reason: format!("could not create the kernel log {}: {error}", log.display()),
},
)?;
Ok(log)
}
#[cfg(unix)]
fn write_definition(path: &Path, contents: &str) -> Result<()> {
let failed = |error: std::io::Error| KernelError::Service {
reason: format!("could not write {}: {error}", path.display()),
};
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(failed)?;
}
std::fs::write(path, contents).map_err(failed)
}
#[cfg(unix)]
fn run(program: &str, args: &[&str]) -> std::result::Result<String, String> {
let output = std::process::Command::new(program)
.args(args)
.output()
.map_err(|error| format!("could not run {program}: {error}"))?;
let text = format!(
"{}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
if output.status.success() {
Ok(text)
} else {
Err(format!("`{program} {}` failed ({}): {}", args.join(" "), output.status, text.trim()))
}
}
#[cfg(test)]
mod tests;