Skip to main content

vitrify_cli/
gate.rs

1//! Running an SDD's own commands — the §5 Commands and Verification-table
2//! rows — through `sh -c`: the one sanctioned shell use, and the one place
3//! it happens.
4//!
5//! Every command gets a `TMPDIR` of its own for as long as it runs, so
6//! concurrent test sessions (the gate's own rows, and workers building in
7//! parallel) never share a temp root. The directories are slots, not
8//! throwaways: a slot is exclusive while in use and stays where it is
9//! afterwards, to be taken by the next command — so a build daemon a command
10//! leaves behind keeps a temp directory that exists, and toolchains that tie
11//! a daemon to its temp directory see the same few directories every time.
12//! Under `vitrify run` each command also runs in its own process group and
13//! is stopped when the run is interrupted.
14
15use std::collections::HashMap;
16use std::os::unix::fs::DirBuilderExt;
17use std::os::unix::process::CommandExt;
18use std::path::{Path, PathBuf};
19use std::process::{Command, Stdio};
20use std::sync::atomic::{AtomicUsize, Ordering};
21use std::time::Duration;
22
23use vitrify_core::CoreError;
24use vitrify_core::audit::{self, CommandRunner};
25use vitrify_core::model::{self, Instance, Shape, Unit};
26use vitrify_core::trace::hash12;
27
28use crate::signals;
29
30/// Told as each command starts and ends: how the integrator reports its
31/// progress while a gate that prints nothing is passing.
32pub trait Watch: Sync {
33    fn started(&self, cmd: &str);
34    fn ended(&self, cmd: &str);
35}
36
37/// A watcher that does nothing, for callers no one is watching.
38pub struct Unwatched;
39
40impl Watch for Unwatched {
41    fn started(&self, _cmd: &str) {}
42    fn ended(&self, _cmd: &str) {}
43}
44
45/// One finished command.
46#[derive(Debug, Clone)]
47pub struct Ran {
48    pub code: i32,
49    /// The last 100 lines of stdout and stderr, as they were written.
50    pub output: String,
51    /// Stopped because the run was interrupted, not because it failed.
52    pub interrupted: bool,
53}
54
55impl Ran {
56    pub fn ok(&self) -> bool {
57        self.code == 0 && !self.interrupted
58    }
59}
60
61/// A temp directory held by one command or one worker. Exclusive while this
62/// value lives; the directory itself is left in place for the next holder.
63pub struct TmpSlot {
64    pub dir: PathBuf,
65    held: std::fs::File,
66}
67
68impl Drop for TmpSlot {
69    /// Unlock before the file closes. A lock belongs to the open file, and
70    /// every child forked meanwhile — by any thread — shares that until it
71    /// execs: left to the close, the lock can outlive the slot, and the next
72    /// command pass the slot over for another.
73    fn drop(&mut self) {
74        let _ = self.held.unlock();
75    }
76}
77
78/// Where the temp slots of `scope` live: a private directory under the
79/// system temp root, named by a hash of the user and the scope (kept short —
80/// tools put sockets under `TMPDIR`, and socket paths are length-limited).
81pub fn slots_root(scope: &Path) -> PathBuf {
82    let user = std::env::var("USER")
83        .or_else(|_| std::env::var("LOGNAME"))
84        .unwrap_or_default();
85    let key = hash12(&format!("{user}\0{}", scope.display()));
86    std::env::temp_dir().join(format!("vfy-{}", &key[..10]))
87}
88
89/// Take the first free slot of `kind` for `scope` (the checkout commands
90/// run in, or the root workers build under): the same few directories are
91/// handed out again and again, never two holders at once — across
92/// processes too, since a slot is held by a file lock.
93pub fn tmp_slot(scope: &Path, kind: &str) -> std::io::Result<TmpSlot> {
94    let root = slots_root(scope);
95    std::fs::DirBuilder::new()
96        .recursive(true)
97        .mode(0o700)
98        .create(&root)?;
99    for k in 0..4096 {
100        let held = std::fs::OpenOptions::new()
101            .create(true)
102            .truncate(false)
103            .write(true)
104            .open(root.join(format!("{kind}{k}.lock")))?;
105        match held.try_lock() {
106            Ok(()) => {
107                let dir = root.join(format!("{kind}{k}"));
108                std::fs::create_dir_all(&dir)?;
109                // The system's temp cleaner removes what has not been used
110                // for days. Taking a slot is using it: say so, or a lock
111                // file created long ago could be swept from under its
112                // holder — and the slot handed out twice.
113                let now = std::time::SystemTime::now();
114                let _ = held.set_modified(now);
115                if let Ok(d) = std::fs::File::open(&dir) {
116                    let _ = d.set_modified(now);
117                }
118                return Ok(TmpSlot { dir, held });
119            }
120            Err(std::fs::TryLockError::WouldBlock) => continue,
121            Err(std::fs::TryLockError::Error(e)) => return Err(e),
122        }
123    }
124    Err(std::io::Error::other("no free temp directory slot"))
125}
126
127fn tail(text: &str, n: usize) -> String {
128    let lines: Vec<&str> = text.lines().collect();
129    let start = lines.len().saturating_sub(n);
130    lines[start..].join("\n")
131}
132
133/// SIGKILL a whole process group.
134pub fn kill_group(pgid: u32) {
135    signals::kill_group(pgid);
136}
137
138/// Whether a process (`pid`) — or, with `group`, any member of the process
139/// group it leads — still exists.
140pub fn alive(pid: u32, group: bool) -> bool {
141    signals::alive(pid, group)
142}
143
144/// Run one command via `sh -c` in `cwd`, with a `TMPDIR` of its own.
145pub fn run_command(cmd: &str, cwd: &Path) -> Ran {
146    let failed = |why: String| Ran {
147        code: -1,
148        output: why,
149        interrupted: false,
150    };
151    if signals::interrupted() {
152        return Ran {
153            code: -1,
154            output: String::new(),
155            interrupted: true,
156        };
157    }
158    let slot = match tmp_slot(cwd, "c") {
159        Ok(slot) => slot,
160        Err(e) => return failed(format!("cannot take a temp directory: {e}")),
161    };
162    let tmp = &slot.dir;
163    let log = tmp.with_extension("out");
164    let cleanup = || {
165        let _ = std::fs::remove_file(&log);
166    };
167    let (out, err) = match std::fs::File::create(&log).and_then(|f| Ok((f.try_clone()?, f))) {
168        Ok(pair) => pair,
169        Err(e) => {
170            cleanup();
171            return failed(format!("cannot capture output: {e}"));
172        }
173    };
174    let mut command = Command::new("sh");
175    command
176        .arg("-c")
177        .arg(cmd)
178        .current_dir(cwd)
179        .env("TMPDIR", tmp)
180        .stdin(Stdio::null())
181        .stdout(Stdio::from(out))
182        .stderr(Stdio::from(err));
183    let own_group = signals::installed();
184    if own_group {
185        // the terminal's Ctrl-C reaches only vitrify, which stops the group
186        command.process_group(0);
187    }
188    let mut child = match command.spawn() {
189        Ok(c) => c,
190        Err(e) => {
191            cleanup();
192            return failed(e.to_string());
193        }
194    };
195    let mut interrupted = false;
196    let status = if own_group {
197        let mut nap = Duration::from_millis(2);
198        loop {
199            match child.try_wait() {
200                Ok(Some(status)) => break Some(status),
201                Ok(None) => {}
202                Err(_) => break None,
203            }
204            if signals::interrupted() {
205                kill_group(child.id());
206                interrupted = true;
207                break child.wait().ok();
208            }
209            std::thread::sleep(nap);
210            nap = (nap * 2).min(Duration::from_millis(50));
211        }
212    } else {
213        child.wait().ok()
214    };
215    let text = std::fs::read(&log)
216        .map(|b| String::from_utf8_lossy(&b).into_owned())
217        .unwrap_or_default();
218    cleanup();
219    Ran {
220        code: status.and_then(|s| s.code()).unwrap_or(-1),
221        output: tail(&text, 100),
222        interrupted,
223    }
224}
225
226/// Run one command, telling `w` as it starts and ends.
227pub fn run_command_watched(cmd: &str, cwd: &Path, w: &dyn Watch) -> Ran {
228    w.started(cmd);
229    let ran = run_command(cmd, cwd);
230    w.ended(cmd);
231    ran
232}
233
234/// Run `cmds` in `cwd`, at most `jobs` at once; results are index-aligned.
235///
236/// With `jobs` > 1 a command that fails while others were running is run
237/// once more on its own, in order: only a failure that repeats alone
238/// counts, so rows that merely disturb each other cannot turn a gate red.
239/// `stop_at_failure` ends the pass at the first (confirmed) failure — later
240/// commands are `None`.
241pub fn run_rows(
242    cmds: &[String],
243    cwd: &Path,
244    jobs: usize,
245    stop_at_failure: bool,
246) -> Vec<Option<Ran>> {
247    run_rows_watched(cmds, cwd, jobs, stop_at_failure, &Unwatched)
248}
249
250/// `run_rows`, telling `w` as each command starts and ends — the parallel
251/// pass and each re-run that confirms a failure alone.
252pub fn run_rows_watched(
253    cmds: &[String],
254    cwd: &Path,
255    jobs: usize,
256    stop_at_failure: bool,
257    w: &dyn Watch,
258) -> Vec<Option<Ran>> {
259    let mut results: Vec<Option<Ran>> = vec![None; cmds.len()];
260    if jobs <= 1 || cmds.len() <= 1 {
261        for (i, cmd) in cmds.iter().enumerate() {
262            let ran = run_command_watched(cmd, cwd, w);
263            let stop = ran.interrupted || (stop_at_failure && !ran.ok());
264            results[i] = Some(ran);
265            if stop {
266                break;
267            }
268        }
269        return results;
270    }
271
272    let next = AtomicUsize::new(0);
273    let slots: Vec<std::sync::Mutex<Option<Ran>>> =
274        cmds.iter().map(|_| std::sync::Mutex::new(None)).collect();
275    std::thread::scope(|scope| {
276        for _ in 0..jobs.min(cmds.len()) {
277            scope.spawn(|| {
278                loop {
279                    let i = next.fetch_add(1, Ordering::SeqCst);
280                    if i >= cmds.len() || signals::interrupted() {
281                        break;
282                    }
283                    let ran = run_command_watched(&cmds[i], cwd, w);
284                    *slots[i].lock().unwrap_or_else(|e| e.into_inner()) = Some(ran);
285                }
286            });
287        }
288    });
289    for (i, slot) in slots.into_iter().enumerate() {
290        results[i] = slot.into_inner().unwrap_or_else(|e| e.into_inner());
291    }
292    // confirm each failure alone, in table order
293    for (i, cmd) in cmds.iter().enumerate() {
294        let Some(first) = &results[i] else { continue };
295        if first.ok() || first.interrupted {
296            continue;
297        }
298        let again = run_command_watched(cmd, cwd, w);
299        let failed = !again.ok();
300        results[i] = Some(again);
301        if failed && stop_at_failure {
302            for later in results.iter_mut().skip(i + 1) {
303                if later.as_ref().is_some_and(|r| !r.ok()) {
304                    *later = None; // unconfirmed: not judged
305                }
306            }
307            break;
308        }
309    }
310    results
311}
312
313/// The text of a unit's entry: its unit file (bundle) or its `### U-###`
314/// region (single).
315pub fn unit_text(inst: &Instance, unit: &Unit) -> Result<String, CoreError> {
316    match inst.shape {
317        Shape::Bundle => model::read_text(&unit.file),
318        Shape::Single => {
319            let text = model::read_text(&inst.file)?;
320            Ok(model::find_unit_span(&text, &unit.unit)
321                .map(|(s, e)| text[s..e].to_string())
322                .unwrap_or_default())
323        }
324    }
325}
326
327/// The commands of a unit's Verification table, in table order.
328pub fn verification_table(inst: &Instance, unit: &Unit) -> Result<Vec<String>, CoreError> {
329    Ok(audit::verification_commands(&unit_text(inst, unit)?))
330}
331
332/// The audit's command runner (check 4): plain `sh -c`, one at a time.
333pub struct ShRunner;
334
335impl CommandRunner for ShRunner {
336    fn run(&self, cmd: &str, cwd: &Path) -> i32 {
337        run_command(cmd, cwd).code
338    }
339}
340
341/// Every Verified unit's Verification rows, each distinct command once, in
342/// unit and table order: what `MemoRunner::for_verified` runs, so a caller
343/// can count them first.
344pub fn verified_commands(inst: &Instance) -> Result<Vec<String>, CoreError> {
345    let mut cmds: Vec<String> = Vec::new();
346    for u in &inst.units {
347        if u.meta.get_str_or("status", "Draft") == "Verified" {
348            for cmd in verification_table(inst, u)? {
349                if !cmds.contains(&cmd) {
350                    cmds.push(cmd);
351                }
352            }
353        }
354    }
355    Ok(cmds)
356}
357
358/// A runner that already knows the exit codes of the commands it will be
359/// asked for: every Verified unit's Verification rows, each distinct command
360/// run once, `jobs` at a time. The audit then reads the results.
361pub struct MemoRunner {
362    memo: HashMap<String, i32>,
363}
364
365impl MemoRunner {
366    /// Run every Verified unit's rows now.
367    pub fn for_verified(inst: &Instance, cwd: &Path, jobs: usize) -> Result<MemoRunner, CoreError> {
368        MemoRunner::for_verified_watched(inst, cwd, jobs, &Unwatched)
369    }
370
371    /// `for_verified`, telling `w` as each command starts and ends.
372    pub fn for_verified_watched(
373        inst: &Instance,
374        cwd: &Path,
375        jobs: usize,
376        w: &dyn Watch,
377    ) -> Result<MemoRunner, CoreError> {
378        let cmds = verified_commands(inst)?;
379        let results = run_rows_watched(&cmds, cwd, jobs, false, w);
380        let memo = cmds
381            .into_iter()
382            .zip(results)
383            .filter_map(|(cmd, ran)| ran.map(|r| (cmd, r.code)))
384            .collect();
385        Ok(MemoRunner { memo })
386    }
387}
388
389impl CommandRunner for MemoRunner {
390    fn run(&self, cmd: &str, cwd: &Path) -> i32 {
391        match self.memo.get(cmd) {
392            Some(code) => *code,
393            None => run_command(cmd, cwd).code,
394        }
395    }
396}
397
398#[cfg(test)]
399mod tests {
400    use super::*;
401    use std::sync::atomic::AtomicBool;
402
403    #[test]
404    fn a_slot_let_go_is_free_at_once_though_other_threads_spawn() {
405        // Children spawned by other threads share a held slot's open lock
406        // file until they exec. A slot taken right after it was let go must
407        // be the same one regardless.
408        let scope = tempfile::tempdir().unwrap();
409        let root = slots_root(scope.path());
410        let stop = AtomicBool::new(false);
411        let taken: Vec<std::io::Result<PathBuf>> = std::thread::scope(|s| {
412            for _ in 0..4 {
413                s.spawn(|| {
414                    while !stop.load(Ordering::Relaxed) {
415                        let _ = Command::new("true").status();
416                    }
417                });
418            }
419            let taken = (0..300)
420                .map(|_| {
421                    let slot = tmp_slot(scope.path(), "c")?;
422                    let _ = Command::new("true").status(); // held while a command runs
423                    Ok(slot.dir.clone())
424                })
425                .collect();
426            stop.store(true, Ordering::Relaxed);
427            taken
428        });
429        let _ = std::fs::remove_dir_all(&root);
430        let passed_over = taken
431            .iter()
432            .filter(|t| t.as_ref().ok() != Some(&root.join("c0")))
433            .count();
434        assert_eq!(
435            passed_over,
436            0,
437            "{passed_over} of {} takes passed c0 over",
438            taken.len()
439        );
440    }
441}