Skip to main content

stackless_core/
durable_command.rs

1//! Gated finite commands with exit receipts and a deadline outside the controller.
2
3use std::collections::BTreeMap;
4use std::io::{Read, Write};
5use std::os::unix::fs::OpenOptionsExt;
6use std::os::unix::process::CommandExt;
7use std::path::Path;
8use std::process::{Child, Command, Stdio};
9use std::time::{Duration, Instant};
10
11use serde::{Deserialize, Serialize};
12use sysinfo::{ProcessRefreshKind, ProcessesToUpdate, System, UpdateKind};
13
14use crate::process::ProcessStamp;
15use crate::types::{Pid, ProcessStartTime};
16
17pub const OUTPUT_LIMIT: usize = 64 * 1024;
18
19// Arguments are passed as positional parameters. Source text never enters this script.
20// The first hard link wins, so timeout and normal completion cannot overwrite receipts.
21// Byte writes retain short output when the watchdog kills the reader before EOF.
22// Dash's kill builtin rejects `--` before a negative group ID; use /bin/kill.
23const RUNNER: &str = r#"
24umask 077
25stackless_result=$1
26stackless_log=$2
27stackless_budget=$3
28shift 3
29stackless_publish() {
30    printf '%s %s\n' "$1" "$2" > "$stackless_result.$2"
31    /bin/ln "$stackless_result.$2" "$stackless_result" 2>/dev/null
32    /bin/rm -f "$stackless_result.$2"
33}
34IFS= read -r stackless_gate || { stackless_publish 125 unstarted; exit 125; }
35[ "$stackless_gate" = run ] || { stackless_publish 125 unstarted; exit 125; }
36exec </dev/null
37(
38    /bin/sleep "$stackless_budget"
39    stackless_publish 124 timeout
40    /bin/kill -KILL -- "-$$"
41) &
42(
43    "$@"
44    printf '%s\n' "$?" > "$stackless_result.status"
45) 2>&1 | (
46    /bin/dd bs=1 count=65536 2>/dev/null > "$stackless_log"
47    /bin/cat >/dev/null
48)
49if [ -f "$stackless_result.status" ]; then
50    stackless_status=$(/bin/cat "$stackless_result.status")
51    stackless_publish "$stackless_status" completed
52fi
53/bin/kill -KILL -- "-$$"
54"#;
55
56#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
57pub struct CommandStamp {
58    pub pid: Pid,
59    pub start_time: ProcessStartTime,
60    pub cookie: String,
61}
62
63impl CommandStamp {
64    pub fn is_stopped(&self) -> bool {
65        !self.process().is_alive() && self.members().is_empty()
66    }
67    pub fn process(&self) -> ProcessStamp {
68        ProcessStamp {
69            pid: self.pid,
70            start_time: self.start_time,
71        }
72    }
73
74    /// Include detached helpers that inherited this invocation's exact cookie.
75    fn members(&self) -> Vec<ProcessStamp> {
76        let mut system = System::new();
77        system.refresh_processes_specifics(
78            ProcessesToUpdate::All,
79            true,
80            ProcessRefreshKind::nothing().with_environ(UpdateKind::Always),
81        );
82        let cookie = format!("STACKLESS_SPAWN={}", self.cookie);
83        system
84            .processes()
85            .iter()
86            .filter(|(_, process)| process.status() != sysinfo::ProcessStatus::Zombie)
87            .filter_map(|(pid, process)| {
88                process
89                    .environ()
90                    .iter()
91                    .any(|value| value == std::ffi::OsStr::new(&cookie))
92                    .then_some(ProcessStamp {
93                        pid: Pid::from_os(pid.as_u32()),
94                        start_time: ProcessStartTime::from_os(process.start_time()),
95                    })
96            })
97            .collect()
98    }
99
100    /// Stop only recorded process incarnations and matching invocation cookies.
101    pub fn stop(&self) -> std::io::Result<()> {
102        if uuid::Uuid::parse_str(&self.cookie).is_err() {
103            return Err(std::io::Error::other("invalid command invocation cookie"));
104        }
105        let deadline = Instant::now() + Duration::from_secs(3);
106        loop {
107            let mut members = self.members();
108            if self.process().is_alive() {
109                members.push(self.process());
110            }
111            if members.is_empty() {
112                return Ok(());
113            }
114            crate::process::kill_owned_processes(self.process(), members);
115            if Instant::now() >= deadline {
116                return Err(std::io::Error::other(
117                    "command processes remain after termination",
118                ));
119            }
120            std::thread::sleep(Duration::from_millis(20));
121        }
122    }
123}
124
125#[derive(Debug)]
126pub struct PendingCommand {
127    pub stamp: CommandStamp,
128    child: Option<Child>,
129}
130
131impl PendingCommand {
132    /// The caller must commit the stamp before releasing this gate.
133    pub fn release(mut self) -> std::io::Result<()> {
134        let child = self
135            .child
136            .as_mut()
137            .ok_or_else(|| std::io::Error::other("command child missing"))?;
138        child
139            .stdin
140            .take()
141            .ok_or_else(|| std::io::Error::other("command gate missing"))?
142            .write_all(b"run\n")?;
143        if let Some(mut child) = self.child.take() {
144            std::thread::spawn(move || {
145                let _ = child.wait();
146            });
147        }
148        Ok(())
149    }
150}
151
152impl Drop for PendingCommand {
153    fn drop(&mut self) {
154        if let Some(mut child) = self.child.take() {
155            child.stdin.take();
156            let _ = child.kill();
157            let _ = child.wait();
158        }
159    }
160}
161
162pub struct CommandInput<'a> {
163    pub program: &'a Path,
164    pub args: &'a [String],
165    pub directory: &'a Path,
166    pub environment: &'a BTreeMap<String, String>,
167    pub result: &'a Path,
168    pub output: &'a Path,
169    pub budget: Duration,
170}
171
172impl std::fmt::Debug for CommandInput<'_> {
173    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
174        f.debug_struct("CommandInput")
175            .field("program", &self.program)
176            .field("budget", &self.budget)
177            .finish_non_exhaustive()
178    }
179}
180
181pub fn spawn(input: CommandInput<'_>) -> std::io::Result<PendingCommand> {
182    spawn_with_shell(input, Path::new("/bin/sh"))
183}
184
185fn spawn_with_shell(input: CommandInput<'_>, shell: &Path) -> std::io::Result<PendingCommand> {
186    if input.budget.as_secs() == 0 || input.budget.as_secs() > 86400 {
187        return Err(std::io::Error::other(
188            "command budget must be between one second and one day",
189        ));
190    }
191    for path in [input.result, input.output] {
192        match std::fs::symlink_metadata(path) {
193            Err(error) if error.kind() == std::io::ErrorKind::NotFound => (),
194            Err(error) => return Err(error),
195            Ok(_) => {
196                return Err(std::io::Error::other(
197                    "command receipt or output already exists",
198                ));
199            }
200        }
201    }
202    let cookie = uuid::Uuid::new_v4().to_string();
203    let mut child = Command::new(shell)
204        .args(["-c", RUNNER, "stackless-command"])
205        .arg(input.result)
206        .arg(input.output)
207        .arg(input.budget.as_secs().max(1).to_string())
208        .arg(input.program)
209        .args(input.args)
210        .current_dir(input.directory)
211        .env_clear()
212        .envs(crate::security::child_environment())
213        .envs(input.environment)
214        .env("STACKLESS_SPAWN", &cookie)
215        .stdin(Stdio::piped())
216        .stdout(Stdio::null())
217        .stderr(Stdio::null())
218        .process_group(0)
219        .spawn()?;
220    let Some(stamp) = ProcessStamp::of(child.id()) else {
221        let _ = child.kill();
222        let _ = child.wait();
223        return Err(std::io::Error::other(
224            "command exited before its identity was recorded",
225        ));
226    };
227    Ok(PendingCommand {
228        stamp: CommandStamp {
229            pid: stamp.pid,
230            start_time: stamp.start_time,
231            cookie,
232        },
233        child: Some(child),
234    })
235}
236
237fn read_bounded(path: &Path, limit: usize) -> std::io::Result<Vec<u8>> {
238    let file = std::fs::OpenOptions::new()
239        .read(true)
240        .custom_flags(rustix::fs::OFlags::NOFOLLOW.bits() as i32)
241        .open(path)?;
242    if !file.metadata()?.is_file() {
243        return Err(std::io::Error::other(
244            "command receipt is not an ordinary file",
245        ));
246    }
247    let mut bytes = Vec::new();
248    file.take(limit as u64 + 1).read_to_end(&mut bytes)?;
249    if bytes.len() > limit {
250        return Err(std::io::Error::other(
251            "command receipt exceeds its size limit",
252        ));
253    }
254    Ok(bytes)
255}
256
257#[derive(Debug, Clone, Copy, PartialEq, Eq)]
258pub enum ExitCause {
259    Completed,
260    Timeout,
261    Unstarted,
262    Legacy,
263}
264
265#[derive(Debug, Clone, Copy, PartialEq, Eq)]
266pub struct CommandOutcome {
267    pub status: i32,
268    pub cause: ExitCause,
269}
270
271/// The cause is committed in the same hard-linked receipt as the status.
272/// A command returning 124 is distinct from the watchdog killing it.
273pub fn outcome(path: &Path) -> std::io::Result<Option<CommandOutcome>> {
274    let bytes = match read_bounded(path, 32) {
275        Ok(bytes) => bytes,
276        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
277        Err(error) => return Err(error),
278    };
279    let invalid = || std::io::Error::other("invalid command exit receipt");
280    let text = std::str::from_utf8(&bytes).map_err(|_| invalid())?;
281    let mut parts = text.split_whitespace();
282    let status = parts
283        .next()
284        .and_then(|value| value.parse::<u8>().ok())
285        .ok_or_else(invalid)?;
286    let cause = match parts.next() {
287        None => ExitCause::Legacy,
288        Some("completed") => ExitCause::Completed,
289        Some("timeout") if status == 124 => ExitCause::Timeout,
290        Some("unstarted") if status == 125 => ExitCause::Unstarted,
291        _ => return Err(invalid()),
292    };
293    if parts.next().is_some() {
294        return Err(invalid());
295    }
296    Ok(Some(CommandOutcome {
297        status: i32::from(status),
298        cause,
299    }))
300}
301
302pub fn result(path: &Path) -> std::io::Result<Option<i32>> {
303    Ok(outcome(path)?.map(|result| result.status))
304}
305
306pub fn output(path: &Path) -> std::io::Result<Vec<u8>> {
307    read_bounded(path, OUTPUT_LIMIT)
308}
309
310#[cfg(test)]
311mod tests {
312    use super::*;
313
314    fn launch(root: &Path, script: &str, seconds: u64) -> PendingCommand {
315        spawn(CommandInput {
316            program: Path::new("/bin/sh"),
317            args: &["-c".into(), script.into()],
318            directory: root,
319            environment: &BTreeMap::new(),
320            result: &root.join("exit"),
321            output: &root.join("output"),
322            budget: Duration::from_secs(seconds),
323        })
324        .unwrap()
325    }
326
327    fn wait_result(root: &Path) -> i32 {
328        let deadline = Instant::now() + Duration::from_secs(5);
329        loop {
330            if let Some(result) = result(&root.join("exit")).unwrap() {
331                return result;
332            }
333            assert!(
334                Instant::now() < deadline,
335                "runner did not publish an exit receipt"
336            );
337            std::thread::sleep(Duration::from_millis(10));
338        }
339    }
340
341    fn assert_stopped_without_cleanup(stamp: &CommandStamp) {
342        let deadline = Instant::now() + Duration::from_secs(2);
343        while !stamp.is_stopped() && Instant::now() < deadline {
344            std::thread::sleep(Duration::from_millis(10));
345        }
346        let stopped = stamp.is_stopped();
347        // Clean up failed cases without making cleanup satisfy the assertion.
348        stamp.stop().unwrap();
349        assert!(stopped, "command group required caller cleanup: {stamp:?}");
350    }
351
352    #[test]
353    fn runner_stops_its_group_after_completion_and_timeout_under_posix_shells() {
354        for shell in ["/bin/sh", "/bin/dash"] {
355            if !Path::new(shell).exists() {
356                continue;
357            }
358            for (script, seconds, expected) in [
359                ("printf done; exit 7", 30, 7),
360                ("printf started; sleep 30; touch after-sleep", 1, 124),
361            ] {
362                let root = tempfile::tempdir().unwrap();
363                let pending = spawn_with_shell(
364                    CommandInput {
365                        program: Path::new("/bin/sh"),
366                        args: &["-c".into(), script.into()],
367                        directory: root.path(),
368                        environment: &BTreeMap::new(),
369                        result: &root.path().join("exit"),
370                        output: &root.path().join("output"),
371                        budget: Duration::from_secs(seconds),
372                    },
373                    Path::new(shell),
374                )
375                .unwrap();
376                let stamp = pending.stamp.clone();
377                pending.release().unwrap();
378                assert_eq!(wait_result(root.path()), expected, "shell: {shell}");
379                assert_stopped_without_cleanup(&stamp);
380                assert!(!root.path().join("after-sleep").exists());
381            }
382        }
383    }
384
385    #[test]
386    fn unreleased_command_cannot_execute_and_output_is_bounded_after_release() {
387        let root = tempfile::tempdir().unwrap();
388        let pending = launch(root.path(), "touch executed", 2);
389        std::thread::sleep(Duration::from_millis(30));
390        assert!(!root.path().join("executed").exists());
391        drop(pending);
392        assert!(!root.path().join("executed").exists());
393        let root = tempfile::tempdir().unwrap();
394        let pending = launch(
395            root.path(),
396            "python3 -c 'import sys; sys.stdout.write(\"x\" * 200000); sys.exit(7)'",
397            3,
398        );
399        let stamp = pending.stamp.clone();
400        pending.release().unwrap();
401        assert_eq!(wait_result(root.path()), 7);
402        stamp.stop().unwrap();
403        assert_eq!(
404            output(&root.path().join("output")).unwrap(),
405            vec![b'x'; OUTPUT_LIMIT]
406        );
407    }
408
409    #[test]
410    fn runner_deadline_survives_the_launching_process() {
411        let root = tempfile::tempdir().unwrap();
412        let mut parent = Command::new(std::env::current_exe().unwrap())
413            .args([
414                "--exact",
415                "durable_command::tests::crash_helper",
416                "--nocapture",
417            ])
418            .env("STACKLESS_COMMAND_TEST_ROOT", root.path())
419            .stdout(Stdio::null())
420            .stderr(Stdio::null())
421            .spawn()
422            .unwrap();
423        let deadline = Instant::now() + Duration::from_secs(5);
424        while !root.path().join("executed").exists() {
425            assert!(Instant::now() < deadline);
426            std::thread::sleep(Duration::from_millis(10));
427        }
428        let stamp: CommandStamp =
429            serde_json::from_slice(&std::fs::read(root.path().join("stamp")).unwrap()).unwrap();
430        parent.kill().unwrap();
431        parent.wait().unwrap();
432        assert_eq!(wait_result(root.path()), 124);
433        assert_eq!(
434            outcome(&root.path().join("exit")).unwrap().unwrap().cause,
435            ExitCause::Timeout
436        );
437        assert_stopped_without_cleanup(&stamp);
438        assert!(!root.path().join("after-sleep").exists());
439        assert!(!stamp.process().is_alive());
440    }
441
442    #[test]
443    fn exit_cause_distinguishes_user_124_and_rejects_malformed_receipts() {
444        let root = tempfile::tempdir().unwrap();
445        let pending = launch(root.path(), "exit 124", 3);
446        let stamp = pending.stamp.clone();
447        pending.release().unwrap();
448        assert_eq!(wait_result(root.path()), 124);
449        stamp.stop().unwrap();
450        assert_eq!(
451            outcome(&root.path().join("exit")).unwrap().unwrap().cause,
452            ExitCause::Completed
453        );
454        let path = root.path().join("legacy");
455        std::fs::write(&path, "7\n").unwrap();
456        assert_eq!(
457            outcome(&path).unwrap(),
458            Some(CommandOutcome {
459                status: 7,
460                cause: ExitCause::Legacy
461            })
462        );
463        for text in [
464            "0 timeout",
465            "0 completed extra",
466            "256 completed",
467            "0 foreign",
468        ] {
469            std::fs::write(&path, text).unwrap();
470            assert!(outcome(&path).is_err());
471        }
472    }
473
474    #[test]
475    fn crash_helper() {
476        let Some(root) = std::env::var_os("STACKLESS_COMMAND_TEST_ROOT") else {
477            return;
478        };
479        let root = std::path::PathBuf::from(root);
480        let pending = launch(&root, "touch executed; sleep 30; touch after-sleep", 1);
481        std::fs::write(
482            root.join("stamp"),
483            serde_json::to_vec(&pending.stamp).unwrap(),
484        )
485        .unwrap();
486        pending.release().unwrap();
487        std::thread::sleep(Duration::from_secs(30));
488    }
489
490    #[test]
491    fn stop_does_not_match_a_cookie_substring_or_recycled_pid() {
492        let root = tempfile::tempdir().unwrap();
493        let pending = launch(
494            root.path(),
495            r#"python3 -c '
496import os, time
497if os.fork() == 0:
498    os.setsid()
499    with open("detached.tmp", "w") as receipt:
500        receipt.write(str(os.getpid()))
501    os.replace("detached.tmp", "detached")
502    time.sleep(30)
503'; sleep 30"#,
504            30,
505        );
506        let stamp = pending.stamp.clone();
507        let mut decoy = Command::new("/bin/sleep")
508            .arg("30")
509            .env("UNRELATED", &stamp.cookie)
510            .spawn()
511            .unwrap();
512        pending.release().unwrap();
513        let deadline = Instant::now() + Duration::from_secs(5);
514        while !root.path().join("detached").exists() {
515            assert!(Instant::now() < deadline);
516            std::thread::sleep(Duration::from_millis(10));
517        }
518        let detached = std::fs::read_to_string(root.path().join("detached"))
519            .unwrap()
520            .parse::<u32>()
521            .unwrap();
522        let detached = ProcessStamp::of(detached).unwrap();
523        stamp.stop().unwrap();
524        assert!(!detached.is_alive());
525        assert!(decoy.try_wait().unwrap().is_none());
526        let wrong = CommandStamp {
527            pid: Pid::from_os(decoy.id()),
528            start_time: ProcessStartTime::from_os(1),
529            cookie: uuid::Uuid::new_v4().to_string(),
530        };
531        wrong.stop().unwrap();
532        assert!(decoy.try_wait().unwrap().is_none());
533        decoy.kill().unwrap();
534        decoy.wait().unwrap();
535    }
536}