Skip to main content

gitpoulpi_cli_backend/
command_run.rs

1//! Running a user-supplied program (not git) to its end, under the same
2//! process-tree guard as every network command: the daemon's token command
3//! (ADR-0010) is one. The program is run directly (never through a shell),
4//! with nothing on stdin, in a given directory, and is killed together with
5//! everything it started when it takes longer than the timeout or when the
6//! future awaiting it is dropped.
7
8use std::path::Path;
9use std::time::Duration;
10
11/// How a finished program ended.
12#[derive(Debug, Clone)]
13pub struct CommandOutput {
14    /// `None` when a signal ended it.
15    pub exit_code: Option<i32>,
16    pub stdout: String,
17    pub stderr: String,
18}
19
20/// Why a program gave no output at all.
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub enum CommandRunError {
23    /// It could not be started (not found, not executable, no argv).
24    Spawn(String),
25    /// It ran past the timeout; it and its descendants were killed.
26    TimedOut,
27}
28
29/// Runs `argv` (program first) in `cwd`, waits at most `timeout`. On a
30/// timeout the whole process tree is killed at once (SIGKILL to its group, or
31/// the Windows Job Object terminated), not asked politely.
32pub async fn run_command(
33    argv: &[String],
34    cwd: &Path,
35    timeout: Duration,
36) -> Result<CommandOutput, CommandRunError> {
37    let Some((program, args)) = argv.split_first() else {
38        return Err(CommandRunError::Spawn("the command is empty".into()));
39    };
40    let mut cmd = tokio::process::Command::new(program);
41    cmd.args(args).current_dir(cwd);
42    crate::tree_kill::captured(&mut cmd);
43    let (child, mut guard) = crate::tree_kill::spawn_guarded(&mut cmd)
44        .map_err(|e| CommandRunError::Spawn(format!("{program}: {e}")))?;
45    match tokio::time::timeout(timeout, child.wait_with_output()).await {
46        Ok(Ok(output)) => {
47            guard.disarm();
48            Ok(CommandOutput {
49                exit_code: output.status.code(),
50                stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
51                stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
52            })
53        }
54        Ok(Err(e)) => Err(CommandRunError::Spawn(format!("{program}: {e}"))),
55        Err(_) => {
56            guard.kill_now();
57            Err(CommandRunError::TimedOut)
58        }
59    }
60}
61
62#[cfg(all(test, unix))]
63mod tests {
64    use super::*;
65
66    fn sh(script: &str) -> Vec<String> {
67        vec!["sh".into(), "-c".into(), script.into()]
68    }
69
70    #[tokio::test]
71    async fn output_exit_code_and_cwd() {
72        let dir = tempfile::tempdir().unwrap();
73        let out = run_command(
74            &sh("pwd; echo bad >&2; exit 3"),
75            dir.path(),
76            Duration::from_secs(10),
77        )
78        .await
79        .unwrap();
80        assert_eq!(out.exit_code, Some(3));
81        assert!(out.stderr.contains("bad"));
82        let canonical = std::fs::canonicalize(dir.path()).unwrap();
83        assert_eq!(std::path::Path::new(out.stdout.trim()), canonical);
84    }
85
86    #[tokio::test]
87    async fn a_missing_program_is_a_spawn_error() {
88        let dir = tempfile::tempdir().unwrap();
89        let err = run_command(
90            &["/no/such/program".into()],
91            dir.path(),
92            Duration::from_secs(5),
93        )
94        .await
95        .unwrap_err();
96        assert!(matches!(err, CommandRunError::Spawn(_)), "{err:?}");
97    }
98
99    /// The timeout kills the grandchild too: a `sleep` started by the script
100    /// that ignores SIGTERM would outlive a polite kill.
101    #[tokio::test]
102    async fn a_timeout_kills_the_whole_process_tree() {
103        let dir = tempfile::tempdir().unwrap();
104        let pidfile = dir.path().join("pid");
105        let script = format!(
106            "trap '' TERM; sleep 60 & echo $! > '{}'; wait",
107            pidfile.display()
108        );
109        let err = run_command(&sh(&script), dir.path(), Duration::from_millis(1500))
110            .await
111            .unwrap_err();
112        assert_eq!(err, CommandRunError::TimedOut);
113        let pid: i32 = std::fs::read_to_string(&pidfile)
114            .unwrap()
115            .trim()
116            .parse()
117            .unwrap();
118        // The kill is a signal; give the kernel a moment to reap.
119        for _ in 0..50 {
120            // SAFETY: signal 0 only probes for existence.
121            if unsafe { libc::kill(pid, 0) } != 0 {
122                return;
123            }
124            std::thread::sleep(Duration::from_millis(50));
125        }
126        panic!("the grandchild {pid} is still running");
127    }
128}
129
130/// The Windows counterpart, with PowerShell 7 (`pwsh`) as the scripting
131/// language: a test returns early with a message when it is not installed.
132#[cfg(all(test, windows))]
133mod windows_tests {
134    use super::*;
135
136    fn pwsh_installed() -> bool {
137        let found = std::process::Command::new("pwsh")
138            .args(["-NoProfile", "-Command", "exit 0"])
139            .output()
140            .is_ok_and(|o| o.status.success());
141        if !found {
142            eprintln!("SKIPPED: pwsh is not installed");
143        }
144        found
145    }
146
147    fn pwsh(script: &str) -> Vec<String> {
148        ["pwsh", "-NoProfile", "-Command", script]
149            .map(String::from)
150            .to_vec()
151    }
152
153    fn running(pid: u32) -> bool {
154        let out = std::process::Command::new("tasklist")
155            .args(["/FI", &format!("PID eq {pid}"), "/NH"])
156            .output()
157            .unwrap();
158        String::from_utf8_lossy(&out.stdout).contains(&pid.to_string())
159    }
160
161    #[tokio::test]
162    async fn output_exit_code_and_cwd() {
163        if !pwsh_installed() {
164            return;
165        }
166        let dir = tempfile::tempdir().unwrap();
167        let out = run_command(
168            &pwsh("(Get-Location).Path; [Console]::Error.WriteLine('bad'); exit 3"),
169            dir.path(),
170            Duration::from_secs(30),
171        )
172        .await
173        .unwrap();
174        assert_eq!(out.exit_code, Some(3));
175        assert!(out.stderr.contains("bad"));
176        assert_eq!(
177            std::fs::canonicalize(out.stdout.trim()).unwrap(),
178            std::fs::canonicalize(dir.path()).unwrap()
179        );
180    }
181
182    #[tokio::test]
183    async fn a_missing_program_is_a_spawn_error() {
184        let dir = tempfile::tempdir().unwrap();
185        let err = run_command(
186            &["C:\\no\\such\\program.exe".into()],
187            dir.path(),
188            Duration::from_secs(5),
189        )
190        .await
191        .unwrap_err();
192        assert!(matches!(err, CommandRunError::Spawn(_)), "{err:?}");
193    }
194
195    /// The timeout kills the grandchild too: the script starts its own
196    /// `pwsh` that sleeps, and the Job Object ends both.
197    #[tokio::test]
198    async fn a_timeout_kills_the_whole_process_tree() {
199        if !pwsh_installed() {
200            return;
201        }
202        let dir = tempfile::tempdir().unwrap();
203        let pidfile = dir.path().join("pid");
204        let script = format!(
205            "$p = Start-Process pwsh -ArgumentList '-NoProfile','-Command','Start-Sleep 60' -PassThru -NoNewWindow; \
206             Set-Content -LiteralPath '{}' -Value $p.Id; Start-Sleep 60",
207            pidfile.display()
208        );
209        let err = run_command(&pwsh(&script), dir.path(), Duration::from_secs(6))
210            .await
211            .unwrap_err();
212        assert_eq!(err, CommandRunError::TimedOut);
213        let pid: u32 = std::fs::read_to_string(&pidfile)
214            .expect("the script started its child before the timeout")
215            .trim()
216            .parse()
217            .unwrap();
218        for _ in 0..50 {
219            if !running(pid) {
220                return;
221            }
222            std::thread::sleep(Duration::from_millis(100));
223        }
224        panic!("the grandchild {pid} is still running");
225    }
226}