Skip to main content

adk_kernel/service/
mod.rs

1//! Service installation (spec 3.2 §7.12, §10 W3): `adk-rust up` kept running by the
2//! platform's service manager, as the user, logging to the kernel home and restarting on
3//! failure.
4//!
5//! | Platform | Form | Definition | Starts |
6//! |---|---|---|---|
7//! | macOS | launchd agent | `~/Library/LaunchAgents/<name>.plist` | At login, in the user's session |
8//! | Linux | systemd user unit | `<config dir>/systemd/user/<name>.service` | With the user's service manager: at login, or at boot with lingering on |
9//! | Windows | Windows service under the user's account | The service control manager | At boot (delayed automatic start) |
10//!
11//! Each form runs as the user, so a store key held in the OS keychain stays reachable: an
12//! agent rather than a daemon, a user unit, a service under the user's account — which the
13//! service control manager needs that account's password to start. Each writes the
14//! kernel's output to `<home>/kernel.log`, created owner-only, and restarts the kernel when
15//! it exits with an error or dies: launchd's `KeepAlive` on an unsuccessful exit, systemd's
16//! `Restart=on-failure`, and the service's failure actions (a restart after 5, 10 and 30
17//! seconds; an exit with an error counts as a failure). Stopping the service drains the
18//! kernel as `SIGTERM` does.
19//!
20//! [`ServiceDefinition::render`] shows what [`install`] registers, for any platform,
21//! without installing anything; `adk-rust up --install --print` prints it.
22//!
23//! # Example
24//!
25//! ```rust
26//! use adk_kernel::service::{ServiceDefinition, ServicePlatform};
27//!
28//! let definition = ServiceDefinition::new("/usr/local/bin/adk-rust", "/home/ana/.config/adk-rust")
29//!     .with_working_directory("/home/ana/project");
30//! let unit = definition.render(ServicePlatform::Systemd);
31//! assert!(unit.contains("ExecStart=/usr/local/bin/adk-rust up --home /home/ana/.config/adk-rust\n"));
32//! assert!(unit.contains("Restart=on-failure\n"));
33//! assert!(unit.contains("StandardOutput=append:/home/ana/.config/adk-rust/kernel.log\n"));
34//! ```
35
36use std::path::{Path, PathBuf};
37use std::sync::OnceLock;
38
39use tokio_util::sync::CancellationToken;
40
41use crate::error::{KernelError, Result};
42
43mod launchd;
44mod systemd;
45mod windows;
46
47#[cfg(windows)]
48pub use windows::run_as_service;
49
50/// The file under the kernel home the service writes the kernel's output to.
51pub const LOG_FILE: &str = "kernel.log";
52
53/// A service manager the kernel installs into (spec 3.2 §7.12).
54///
55/// # Example
56///
57/// ```rust
58/// use adk_kernel::service::ServicePlatform;
59///
60/// assert_eq!(ServicePlatform::Systemd.as_str(), "systemd");
61/// if cfg!(target_os = "macos") {
62///     assert_eq!(ServicePlatform::current(), Some(ServicePlatform::Launchd));
63/// }
64/// ```
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
66#[non_exhaustive]
67pub enum ServicePlatform {
68    /// A launchd agent (macOS).
69    Launchd,
70    /// A systemd user unit (Linux).
71    Systemd,
72    /// A Windows service under the user's account.
73    Windows,
74}
75
76impl ServicePlatform {
77    /// The service manager of the platform this runs on, or `None` where the kernel has no
78    /// service form.
79    pub const fn current() -> Option<Self> {
80        if cfg!(target_os = "macos") {
81            Some(Self::Launchd)
82        } else if cfg!(target_os = "linux") {
83            Some(Self::Systemd)
84        } else if cfg!(windows) {
85            Some(Self::Windows)
86        } else {
87            None
88        }
89    }
90
91    /// The platform's name: `launchd`, `systemd` or `windows`.
92    pub const fn as_str(self) -> &'static str {
93        match self {
94            Self::Launchd => "launchd",
95            Self::Systemd => "systemd",
96            Self::Windows => "windows",
97        }
98    }
99}
100
101impl std::fmt::Display for ServicePlatform {
102    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103        f.write_str(self.as_str())
104    }
105}
106
107/// What the service manager runs: `adk-rust up` with a kernel home (spec 3.2 §7.12).
108///
109/// Never put a secret in [`args`](Self::args) or [`environment`](Self::environment): a
110/// definition is a file others may read, and a Windows service's command line and
111/// environment are readable by every local user.
112///
113/// # Example
114///
115/// ```rust
116/// use adk_kernel::service::{ServiceDefinition, ServicePlatform};
117///
118/// let definition = ServiceDefinition::new("/opt/adk/bin/adk-rust", "/srv/kernel")
119///     .with_args(["up", "--home", "/srv/kernel", "--bind", "127.0.0.1:9090"])
120///     .with_env("PATH", "/opt/adk/bin:/usr/bin:/bin");
121/// assert_eq!(definition.name, ServiceDefinition::name_for(std::path::Path::new("/srv/kernel")));
122/// assert_eq!(definition.log_path(), std::path::Path::new("/srv/kernel/kernel.log"));
123/// let plist = definition.render(ServicePlatform::Launchd);
124/// assert!(plist.contains("<string>127.0.0.1:9090</string>"));
125/// ```
126#[derive(Debug, Clone, PartialEq, Eq)]
127#[non_exhaustive]
128pub struct ServiceDefinition {
129    /// The launchd label, the systemd unit's stem and the Windows service name. Defaults to
130    /// [`name_for`](Self::name_for) the home, so each kernel home has its own service.
131    pub name: String,
132    /// The `adk-rust` binary, as an absolute path.
133    pub program: PathBuf,
134    /// The arguments after the program. Defaults to `up --home <home>`.
135    pub args: Vec<String>,
136    /// The kernel home; the service writes the kernel's output to `<home>/kernel.log`.
137    pub home: PathBuf,
138    /// The directory the kernel starts in. Defaults to the home.
139    pub working_directory: PathBuf,
140    /// Variables the kernel starts with, such as the installing shell's `PATH`.
141    pub environment: Vec<(String, String)>,
142    /// The Windows account the service logs on as, `DOMAIN\user`; `None` is the user who
143    /// installs it, the only account [`install`] accepts. launchd and systemd always run the
144    /// definition as the user who installs it.
145    pub account: Option<String>,
146}
147
148impl ServiceDefinition {
149    /// A definition running `program up --home <home>` from the home.
150    pub fn new(program: impl Into<PathBuf>, home: impl Into<PathBuf>) -> Self {
151        let home = home.into();
152        Self {
153            name: Self::name_for(&home),
154            program: program.into(),
155            args: vec!["up".into(), "--home".into(), home.to_string_lossy().into_owned()],
156            working_directory: home.clone(),
157            home,
158            environment: Vec::new(),
159            account: None,
160        }
161    }
162
163    /// The service name of the kernel home `home`: `adk-rust-kernel-<tag>`, the tag derived
164    /// from the home's absolute path, as the named pipe's is.
165    pub fn name_for(home: &Path) -> String {
166        format!("adk-rust-kernel-{}", crate::path_tag(home))
167    }
168
169    /// Sets the service's name.
170    #[must_use]
171    pub fn with_name(mut self, name: impl Into<String>) -> Self {
172        self.name = name.into();
173        self
174    }
175
176    /// Replaces the arguments after the program.
177    #[must_use]
178    pub fn with_args(mut self, args: impl IntoIterator<Item = impl Into<String>>) -> Self {
179        self.args = args.into_iter().map(Into::into).collect();
180        self
181    }
182
183    /// Sets the directory the kernel starts in.
184    #[must_use]
185    pub fn with_working_directory(mut self, directory: impl Into<PathBuf>) -> Self {
186        self.working_directory = directory.into();
187        self
188    }
189
190    /// Adds a variable the kernel starts with.
191    #[must_use]
192    pub fn with_env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
193        self.environment.push((key.into(), value.into()));
194        self
195    }
196
197    /// Sets the Windows account the service logs on as.
198    #[must_use]
199    pub fn with_account(mut self, account: impl Into<String>) -> Self {
200        self.account = Some(account.into());
201        self
202    }
203
204    /// `<home>/kernel.log`, where the service writes the kernel's output.
205    pub fn log_path(&self) -> PathBuf {
206        self.home.join(LOG_FILE)
207    }
208
209    /// [`log_path`](Self::log_path) with `platform`'s separator, whichever platform renders it.
210    fn log_for(&self, platform: ServicePlatform) -> String {
211        let home = self.home.to_string_lossy();
212        match platform {
213            ServicePlatform::Windows => {
214                format!("{}\\{LOG_FILE}", home.trim_end_matches(['\\', '/']))
215            }
216            ServicePlatform::Launchd | ServicePlatform::Systemd => {
217                format!("{}/{LOG_FILE}", home.trim_end_matches('/'))
218            }
219        }
220    }
221
222    /// Where [`install`] writes the definition on `platform`: the plist under
223    /// `~/Library/LaunchAgents`, the unit under `<config dir>/systemd/user`, or `None` for a
224    /// Windows service, which the service control manager keeps.
225    ///
226    /// # Errors
227    ///
228    /// Returns [`KernelError::Service`] when the user's home or config directory is unknown.
229    pub fn definition_path(&self, platform: ServicePlatform) -> Result<Option<PathBuf>> {
230        Ok(match platform {
231            ServicePlatform::Launchd => Some(launchd::plist_path(&self.name)?),
232            ServicePlatform::Systemd => Some(systemd::unit_path(&self.name)?),
233            ServicePlatform::Windows => None,
234        })
235    }
236
237    /// The definition as `platform`'s service manager takes it: the launchd plist, the
238    /// systemd unit, or, for Windows, a description of the service [`install`] registers.
239    pub fn render(&self, platform: ServicePlatform) -> String {
240        match platform {
241            ServicePlatform::Launchd => launchd::render(self),
242            ServicePlatform::Systemd => systemd::render(self),
243            ServicePlatform::Windows => windows::render(self),
244        }
245    }
246}
247
248/// What [`install`] did.
249#[derive(Debug, Clone, PartialEq, Eq)]
250#[non_exhaustive]
251pub struct Installed {
252    /// The service manager it installed into.
253    pub platform: ServicePlatform,
254    /// The service's name.
255    pub name: String,
256    /// The definition file it wrote; `None` for a Windows service.
257    pub definition: Option<PathBuf>,
258    /// Where the kernel's output goes.
259    pub log: PathBuf,
260    /// What the user should know, such as when the service starts.
261    pub notes: Vec<String>,
262}
263
264/// What [`uninstall`] did.
265#[derive(Debug, Clone, PartialEq, Eq)]
266#[non_exhaustive]
267pub struct Uninstalled {
268    /// The service manager it removed the service from.
269    pub platform: ServicePlatform,
270    /// The service's name.
271    pub name: String,
272    /// The definition file it removed; `None` for a Windows service.
273    pub definition: Option<PathBuf>,
274}
275
276/// Installs `definition` into this platform's service manager and starts it (spec 3.2
277/// §7.12), replacing an installed service of the same name.
278///
279/// `password` is the Windows account's password, which the service control manager needs to
280/// run a service as that account; launchd and systemd ignore it. On Windows this needs an
281/// elevated shell, grants the account the "Log on as a service" right, and checks the
282/// password before registering the service. The log file is created owner-only where the
283/// service manager would create it.
284///
285/// # Errors
286///
287/// Returns [`KernelError::Service`] when the platform has no service form, the service
288/// manager refuses (its output is in the message), or, on Windows, without a password, an
289/// elevated shell, or for an account other than the current user.
290///
291/// # Example
292///
293/// ```rust,no_run
294/// use adk_kernel::service::{ServiceDefinition, install};
295///
296/// # fn example() -> adk_kernel::Result<()> {
297/// let definition = ServiceDefinition::new("/usr/local/bin/adk-rust", "/srv/kernel");
298/// let installed = install(&definition, std::env::var("ADK_SERVICE_PASSWORD").ok().as_deref())?;
299/// println!("{} logs to {}", installed.name, installed.log.display());
300/// # Ok(())
301/// # }
302/// ```
303pub fn install(definition: &ServiceDefinition, password: Option<&str>) -> Result<Installed> {
304    match ServicePlatform::current() {
305        #[cfg(target_os = "macos")]
306        Some(ServicePlatform::Launchd) => {
307            let _ = password;
308            launchd::install(definition)
309        }
310        #[cfg(target_os = "linux")]
311        Some(ServicePlatform::Systemd) => {
312            let _ = password;
313            systemd::install(definition)
314        }
315        #[cfg(windows)]
316        Some(ServicePlatform::Windows) => windows::install(definition, password),
317        _ => {
318            let _ = (definition, password);
319            Err(unsupported())
320        }
321    }
322}
323
324/// Stops and removes the service `name` (spec 3.2 §7.12): the reverse of [`install`]. The
325/// kernel home, its stores and its log stay.
326///
327/// # Errors
328///
329/// Returns [`KernelError::Service`] when no service of that name is installed, the service
330/// manager refuses, or, on Windows, outside an elevated shell.
331///
332/// # Example
333///
334/// ```rust,no_run
335/// use adk_kernel::service::{ServiceDefinition, uninstall};
336///
337/// # fn example() -> adk_kernel::Result<()> {
338/// let removed = uninstall(&ServiceDefinition::name_for(std::path::Path::new("/srv/kernel")))?;
339/// println!("removed {}", removed.name);
340/// # Ok(())
341/// # }
342/// ```
343pub fn uninstall(name: &str) -> Result<Uninstalled> {
344    match ServicePlatform::current() {
345        #[cfg(target_os = "macos")]
346        Some(ServicePlatform::Launchd) => launchd::uninstall(name),
347        #[cfg(target_os = "linux")]
348        Some(ServicePlatform::Systemd) => systemd::uninstall(name),
349        #[cfg(windows)]
350        Some(ServicePlatform::Windows) => windows::uninstall(name),
351        _ => {
352            let _ = name;
353            Err(unsupported())
354        }
355    }
356}
357
358fn unsupported() -> KernelError {
359    KernelError::Service {
360        reason: "this platform has no service form for the kernel (launchd on macOS, systemd \
361                 on Linux, the service control manager on Windows); run `adk-rust up` under \
362                 your own supervisor"
363            .into(),
364    }
365}
366
367/// The token a Windows service's stop request cancels.
368fn stop_token() -> &'static CancellationToken {
369    static STOP: OnceLock<CancellationToken> = OnceLock::new();
370    STOP.get_or_init(CancellationToken::new)
371}
372
373/// Resolves when the Windows service control manager asks this process, running as the
374/// kernel's service, to stop or the system is shutting down (spec 3.2 §10 W3); never
375/// otherwise, and never on other platforms, whose service managers send `SIGTERM`.
376/// [`Kernel::shutdown_on_signal`](crate::Kernel::shutdown_on_signal) waits for it.
377///
378/// # Example
379///
380/// ```rust,no_run
381/// # async fn example() {
382/// tokio::select! {
383///     _ = tokio::signal::ctrl_c() => {}
384///     () = adk_kernel::service::stop_requested() => {}
385/// }
386/// # }
387/// ```
388pub async fn stop_requested() {
389    stop_token().cancelled().await;
390}
391
392/// Creates `<home>/kernel.log` owner-only (`0600`) when it does not exist, so the service
393/// manager appends to a file only the user can read.
394#[cfg(unix)]
395fn prepare_log(definition: &ServiceDefinition) -> Result<PathBuf> {
396    use std::os::unix::fs::OpenOptionsExt as _;
397
398    std::fs::create_dir_all(&definition.home).map_err(|error| KernelError::Service {
399        reason: format!("could not create the kernel home {}: {error}", definition.home.display()),
400    })?;
401    let log = definition.log_path();
402    std::fs::OpenOptions::new().append(true).create(true).mode(0o600).open(&log).map_err(
403        |error| KernelError::Service {
404            reason: format!("could not create the kernel log {}: {error}", log.display()),
405        },
406    )?;
407    Ok(log)
408}
409
410/// Writes `contents` to the definition file `path`, creating its directory.
411#[cfg(unix)]
412fn write_definition(path: &Path, contents: &str) -> Result<()> {
413    let failed = |error: std::io::Error| KernelError::Service {
414        reason: format!("could not write {}: {error}", path.display()),
415    };
416    if let Some(parent) = path.parent() {
417        std::fs::create_dir_all(parent).map_err(failed)?;
418    }
419    std::fs::write(path, contents).map_err(failed)
420}
421
422/// Runs a service manager's command, answering its output on failure.
423#[cfg(unix)]
424fn run(program: &str, args: &[&str]) -> std::result::Result<String, String> {
425    let output = std::process::Command::new(program)
426        .args(args)
427        .output()
428        .map_err(|error| format!("could not run {program}: {error}"))?;
429    let text = format!(
430        "{}{}",
431        String::from_utf8_lossy(&output.stdout),
432        String::from_utf8_lossy(&output.stderr)
433    );
434    if output.status.success() {
435        Ok(text)
436    } else {
437        Err(format!("`{program} {}` failed ({}): {}", args.join(" "), output.status, text.trim()))
438    }
439}
440
441#[cfg(test)]
442mod tests;