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