Skip to main content

orch/cli/service/
mod.rs

1pub mod events;
2pub mod nodes;
3pub mod notify;
4pub mod webhook;
5
6use crate::sys::cmd::SyncCommandErrorContext;
7#[cfg(not(target_os = "macos"))]
8use crate::sys::home;
9#[cfg(any(test, not(target_os = "macos")))]
10use anyhow::Context;
11#[cfg(not(target_os = "macos"))]
12use std::env;
13#[cfg(any(test, not(target_os = "macos")))]
14use std::fs;
15#[cfg(any(test, not(target_os = "macos")))]
16use std::path::{Path, PathBuf};
17use std::process::Command;
18
19/// Run a service subcommand for orch: `brew services` on macOS, the `orch` systemd user unit elsewhere.
20fn service(action: &str) -> anyhow::Result<()> {
21    let (program, args) = if cfg!(target_os = "macos") {
22        ("brew", vec!["services", action, "orch"])
23    } else {
24        // brew's `info` is systemd's `status`
25        let action = if action == "info" { "status" } else { action };
26        ("systemctl", vec!["--user", action, "orch"])
27    };
28
29    let status = Command::new(program).args(&args).status_with_context()?;
30
31    if !status.success() {
32        anyhow::bail!("{program} {} failed", args.join(" "));
33    }
34
35    Ok(())
36}
37
38/// Start the orch service.
39pub fn start() -> anyhow::Result<()> {
40    service("start")
41}
42
43/// Stop the orch service.
44pub fn stop() -> anyhow::Result<()> {
45    service("stop")
46}
47
48/// Restart the orch service.
49pub fn restart() -> anyhow::Result<()> {
50    service("restart")
51}
52
53/// Show service status.
54pub fn status() -> anyhow::Result<()> {
55    service("info")
56}
57
58/// Write the systemd user unit and enable it
59pub fn install(force: bool) -> anyhow::Result<()> {
60    #[cfg(target_os = "macos")]
61    {
62        let _ = force;
63        macos_service_owned_by_homebrew();
64        Ok(())
65    }
66    #[cfg(not(target_os = "macos"))]
67    {
68        linux_install(
69            &systemd_user_dir()?,
70            &current_binary()?,
71            &home::state_dir()?,
72            Path::new("systemctl"),
73            force,
74        )
75    }
76}
77
78/// Disable the systemd user unit and remove the file
79pub fn uninstall() -> anyhow::Result<()> {
80    #[cfg(target_os = "macos")]
81    {
82        macos_service_owned_by_homebrew();
83        Ok(())
84    }
85    #[cfg(not(target_os = "macos"))]
86    {
87        linux_uninstall(&systemd_user_dir()?, Path::new("systemctl"))
88    }
89}
90
91#[cfg(any(test, target_os = "macos"))]
92fn macos_service_owned_by_homebrew() {
93    println!("The Homebrew formula already installs the orch service.");
94}
95
96#[cfg(test)]
97fn install_os(
98    macos: bool,
99    unit_dir: &Path,
100    binary: &Path,
101    log_dir: &Path,
102    systemctl: &Path,
103    force: bool,
104) -> anyhow::Result<()> {
105    if macos {
106        macos_service_owned_by_homebrew();
107        return Ok(());
108    }
109    linux_install(unit_dir, binary, log_dir, systemctl, force)
110}
111
112#[cfg(test)]
113fn uninstall_os(macos: bool, unit_dir: &Path, systemctl: &Path) -> anyhow::Result<()> {
114    if macos {
115        macos_service_owned_by_homebrew();
116        return Ok(());
117    }
118    linux_uninstall(unit_dir, systemctl)
119}
120
121#[cfg(any(test, not(target_os = "macos")))]
122fn linux_install(
123    unit_dir: &Path,
124    binary: &Path,
125    log_dir: &Path,
126    systemctl: &Path,
127    force: bool,
128) -> anyhow::Result<()> {
129    let unit_path = unit_dir.join("orch.service");
130    let unit = unit_contents(binary, log_dir);
131    if unit_path.exists() && !force {
132        let existing = fs::read_to_string(&unit_path)
133            .with_context(|| format!("reading {}", unit_path.display()))?;
134        if existing != unit {
135            print_unit_diff(&existing, &unit);
136        }
137        anyhow::bail!(
138            "unit already exists at {}; pass --force to overwrite",
139            unit_path.display()
140        );
141    }
142    fs::create_dir_all(unit_dir).with_context(|| format!("creating {}", unit_dir.display()))?;
143    fs::write(&unit_path, &unit).with_context(|| format!("writing {}", unit_path.display()))?;
144    println!("Wrote {}", unit_path.display());
145    run_systemctl(systemctl, &["daemon-reload"])?;
146    run_systemctl(systemctl, &["enable", "--now", "orch"])?;
147    println!("Enabled and started the orch user service.");
148    println!("Logs: {}", log_dir.join("orch.log").display());
149    println!("A user service stops at logout unless lingering is on.");
150    println!("  loginctl enable-linger $USER");
151    Ok(())
152}
153
154#[cfg(any(test, not(target_os = "macos")))]
155fn linux_uninstall(unit_dir: &Path, systemctl: &Path) -> anyhow::Result<()> {
156    let unit_path = unit_dir.join("orch.service");
157    if !unit_path.exists() {
158        let _ = run_systemctl(systemctl, &["disable", "--now", "orch"]);
159        println!("No orch user unit at {}", unit_path.display());
160        return Ok(());
161    }
162    run_systemctl(systemctl, &["disable", "--now", "orch"])?;
163    fs::remove_file(&unit_path).with_context(|| format!("removing {}", unit_path.display()))?;
164    println!("Removed {}", unit_path.display());
165    run_systemctl(systemctl, &["daemon-reload"])?;
166    Ok(())
167}
168
169#[cfg(any(test, not(target_os = "macos")))]
170fn unit_contents(binary: &Path, log_dir: &Path) -> String {
171    // `orch log` and the web UI read these files, journald would hide the log from both
172    format!(
173        "[Unit]\n\
174         Description=orch agent orchestrator\n\
175         After=network-online.target\n\
176         \n\
177         [Service]\n\
178         ExecStart={} serve\n\
179         Restart=always\n\
180         RestartSec=5\n\
181         StandardOutput=append:{}\n\
182         StandardError=append:{}\n\
183         \n\
184         [Install]\n\
185         WantedBy=default.target\n",
186        exec_start_bin(binary),
187        log_dir.join("orch.log").display(),
188        log_dir.join("orch.error.log").display(),
189    )
190}
191
192#[cfg(any(test, not(target_os = "macos")))]
193fn exec_start_bin(binary: &Path) -> String {
194    let path = binary.display().to_string();
195    if path.chars().any(char::is_whitespace) {
196        format!("\"{path}\"")
197    } else {
198        path
199    }
200}
201
202#[cfg(any(test, not(target_os = "macos")))]
203fn print_unit_diff(existing: &str, proposed: &str) {
204    println!("--- existing");
205    println!("+++ proposed");
206    let old: Vec<&str> = existing.lines().collect();
207    let new: Vec<&str> = proposed.lines().collect();
208    let len = old.len().max(new.len());
209    for i in 0..len {
210        match (old.get(i), new.get(i)) {
211            (Some(a), Some(b)) if a == b => println!(" {a}"),
212            (Some(a), Some(b)) => {
213                println!("-{a}");
214                println!("+{b}");
215            }
216            (Some(a), None) => println!("-{a}"),
217            (None, Some(b)) => println!("+{b}"),
218            (None, None) => {}
219        }
220    }
221}
222
223#[cfg(any(test, not(target_os = "macos")))]
224fn run_systemctl(systemctl: &Path, args: &[&str]) -> anyhow::Result<()> {
225    let status = Command::new(systemctl)
226        .arg("--user")
227        .args(args)
228        .status_with_context()?;
229    if !status.success() {
230        anyhow::bail!("{} --user {} failed", systemctl.display(), args.join(" "));
231    }
232    Ok(())
233}
234
235#[cfg(not(target_os = "macos"))]
236fn systemd_user_dir() -> anyhow::Result<PathBuf> {
237    if let Ok(xdg) = env::var("XDG_CONFIG_HOME")
238        && !xdg.is_empty()
239    {
240        return Ok(PathBuf::from(xdg).join("systemd").join("user"));
241    }
242    let home = dirs::home_dir().context("cannot determine home directory")?;
243    Ok(home.join(".config").join("systemd").join("user"))
244}
245
246#[cfg(not(target_os = "macos"))]
247fn current_binary() -> anyhow::Result<PathBuf> {
248    let exe = env::current_exe().context("cannot resolve the orch binary path")?;
249    Ok(exe.canonicalize().unwrap_or(exe))
250}
251
252#[cfg(test)]
253mod tests {
254    use super::*;
255    use std::fs;
256    use std::os::unix::fs::PermissionsExt;
257
258    fn stub_systemctl(dir: &Path) -> PathBuf {
259        let stub = dir.join("systemctl");
260        let log = dir.join("systemctl.log");
261        fs::write(
262            &stub,
263            format!(
264                "#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"{}\"\nexit 0\n",
265                log.display()
266            ),
267        )
268        .unwrap();
269        fs::set_permissions(&stub, fs::Permissions::from_mode(0o755)).unwrap();
270        stub
271    }
272
273    const LOG_DIR: &str = "/home/u/.orch/state";
274
275    fn setup() -> (tempfile::TempDir, PathBuf, PathBuf, PathBuf) {
276        let root = tempfile::tempdir().unwrap();
277        let unit_dir = root.path().join("user");
278        fs::create_dir_all(&unit_dir).unwrap();
279        let stub = stub_systemctl(root.path());
280        let binary = PathBuf::from("/opt/orch/bin/orch");
281        (root, unit_dir, binary, stub)
282    }
283
284    fn unit_path(unit_dir: &Path) -> PathBuf {
285        unit_dir.join("orch.service")
286    }
287
288    #[test]
289    fn install_writes_unit_with_binary_path_and_serve() {
290        let (root, unit_dir, binary, stub) = setup();
291        install_os(false, &unit_dir, &binary, Path::new(LOG_DIR), &stub, false).unwrap();
292        let unit = fs::read_to_string(unit_path(&unit_dir)).unwrap();
293        assert!(
294            unit.contains("ExecStart=/opt/orch/bin/orch serve"),
295            "{unit}"
296        );
297        assert!(unit.contains("Restart=always"), "{unit}");
298        assert!(unit.contains("WantedBy=default.target"), "{unit}");
299        assert!(
300            unit.contains("StandardOutput=append:/home/u/.orch/state/orch.log\n"),
301            "{unit}"
302        );
303        assert!(
304            unit.contains("StandardError=append:/home/u/.orch/state/orch.error.log\n"),
305            "{unit}"
306        );
307        assert!(!unit.contains("Environment"), "{unit}");
308        let log = fs::read_to_string(root.path().join("systemctl.log")).unwrap();
309        assert!(log.contains("daemon-reload"), "{log}");
310        assert!(log.contains("enable --now orch"), "{log}");
311    }
312
313    #[test]
314    fn second_install_without_force_refuses_and_leaves_file() {
315        let (_root, unit_dir, binary, stub) = setup();
316        install_os(false, &unit_dir, &binary, Path::new(LOG_DIR), &stub, false).unwrap();
317        let path = unit_path(&unit_dir);
318        let original = fs::read_to_string(&path).unwrap();
319        fs::write(&path, original.replace("RestartSec=5", "RestartSec=99")).unwrap();
320        let changed = fs::read_to_string(&path).unwrap();
321        let err =
322            install_os(false, &unit_dir, &binary, Path::new(LOG_DIR), &stub, false).unwrap_err();
323        assert!(
324            err.to_string().contains("--force"),
325            "error should mention --force: {err}"
326        );
327        assert_eq!(fs::read_to_string(&path).unwrap(), changed);
328    }
329
330    #[test]
331    fn uninstall_removes_the_unit() {
332        let (_root, unit_dir, binary, stub) = setup();
333        install_os(false, &unit_dir, &binary, Path::new(LOG_DIR), &stub, false).unwrap();
334        assert!(unit_path(&unit_dir).exists());
335        uninstall_os(false, &unit_dir, &stub).unwrap();
336        assert!(!unit_path(&unit_dir).exists());
337    }
338
339    #[test]
340    fn macos_install_changes_nothing() {
341        let (_root, unit_dir, binary, stub) = setup();
342        #[cfg(target_os = "macos")]
343        {
344            install(false).unwrap();
345            uninstall().unwrap();
346        }
347        install_os(true, &unit_dir, &binary, Path::new(LOG_DIR), &stub, false).unwrap();
348        install_os(true, &unit_dir, &binary, Path::new(LOG_DIR), &stub, true).unwrap();
349        assert!(!unit_path(&unit_dir).exists());
350        assert!(unit_dir.read_dir().unwrap().next().is_none());
351    }
352}