Skip to main content

orch/cli/
service.rs

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