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