Skip to main content

mortise_core/run/
process.rs

1//! Starting a program: the setup every program Mortise starts shares, and, with
2//! the `run` feature, running one while its lines are read, and ending its whole
3//! process tree.
4
5#[cfg(feature = "run")]
6use std::collections::BTreeMap;
7#[cfg(feature = "run")]
8use std::ffi::OsString;
9#[cfg(feature = "run")]
10use std::io::{BufRead, BufReader, Read};
11#[cfg(feature = "run")]
12use std::path::{Path, PathBuf};
13#[cfg(feature = "run")]
14use std::process::{Child, ExitStatus};
15#[cfg(feature = "run")]
16use std::process::{Command, Stdio};
17#[cfg(feature = "run")]
18use std::sync::atomic::{AtomicBool, Ordering};
19#[cfg(feature = "run")]
20use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender, SyncSender};
21#[cfg(feature = "run")]
22use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
23#[cfg(feature = "run")]
24use std::thread::JoinHandle;
25#[cfg(feature = "run")]
26use std::time::{Duration, Instant, SystemTime};
27
28#[cfg(feature = "run")]
29use super::history::OUTPUT_LIMIT;
30#[cfg(feature = "run")]
31use super::{CommandLine, Failure, PhpSettings};
32#[cfg(feature = "run")]
33use crate::program::command;
34
35/// How long a loop waits for a line before it looks at the program again.
36#[cfg(feature = "run")]
37const TICK: Duration = Duration::from_millis(50);
38
39/// How long the readers may still read after the program ended. A program that a
40/// grandchild outlives can leave a pipe open.
41#[cfg(feature = "run")]
42const GRACE: Duration = Duration::from_millis(250);
43
44/// How long the readers may still read after the kill of what is left of the
45/// group, before they are left behind.
46#[cfg(feature = "run")]
47const DETACH: Duration = Duration::from_secs(1);
48
49/// The longest the readers may go on sending lines after the program ended. A
50/// child that writes without end is not waited for past it.
51#[cfg(feature = "run")]
52const DRAIN: Duration = Duration::from_secs(10);
53
54/// How long a stopped program has to end after it was asked to, before it is killed.
55#[cfg(feature = "run")]
56const STOP_GRACE: Duration = Duration::from_secs(3);
57
58/// The longest a stop takes to end a run, from [`Run::stop`] to [`RunEvent::Ended`]:
59/// `STOP_GRACE` to the kill, `GRACE` and `DETACH` for the readers, and a margin
60/// for a few `TICK`s and, on Windows, `taskkill`. A stop that comes while a
61/// child that outlived the program still writes takes `STOP_GRACE` and `DETACH`.
62#[cfg(feature = "run")]
63pub const STOP_WAIT: Duration = STOP_GRACE
64    .saturating_add(GRACE)
65    .saturating_add(DETACH)
66    .saturating_add(Duration::from_millis(500));
67
68/// The most text kept of one line in bytes, and, by [`capture`], of one stream.
69/// A newline counts as one byte, so a flood of empty lines is bounded too.
70#[cfg(feature = "run")]
71const KEEP: usize = 64 * 1024;
72
73/// The pipe a line came from.
74#[cfg(feature = "run")]
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum Stream {
77    Out,
78    Err,
79}
80
81/// The commands that run now, one per app at most. A clone shares the same list.
82#[cfg(feature = "run")]
83#[derive(Debug, Clone, Default)]
84pub struct Runs {
85    /// The app folder, as given to [`Runs::start`], to the label of its command.
86    running: Arc<Mutex<BTreeMap<PathBuf, String>>>,
87}
88
89#[cfg(feature = "run")]
90impl Runs {
91    pub fn new() -> Self {
92        Self::default()
93    }
94
95    /// Starts artisan with `args` through the runner of `php`, in `php.folder(app)`,
96    /// for at most `limit`, which is `php.time_limit()` for a user's run. A second
97    /// start in the same app is refused while the first runs.
98    pub fn start(
99        &self,
100        app: &Path,
101        php: &PhpSettings,
102        args: &[String],
103        limit: Duration,
104    ) -> Result<Run, StartError> {
105        self.start_with_input(app, php, args, limit, None)
106    }
107
108    /// [`Runs::start`], with `input` written to the standard input of the program,
109    /// which then ends. Without input the standard input of the program is empty.
110    pub fn start_with_input(
111        &self,
112        app: &Path,
113        php: &PhpSettings,
114        args: &[String],
115        limit: Duration,
116        input: Option<Vec<u8>>,
117    ) -> Result<Run, StartError> {
118        let label = label(args);
119        let folder = php.folder(app);
120        let line = {
121            let mut running = self.lock();
122            if let Some(command) = running.get(app) {
123                return Err(StartError::Busy {
124                    command: command.clone(),
125                });
126            }
127            let runner = php.runner.as_ref().ok_or(StartError::NoRunner)?;
128            let words: Vec<&str> = args.iter().map(String::as_str).collect();
129            let line = CommandLine::artisan(runner, &words)
130                .ok_or(StartError::Failed(Failure::NoCommand))?;
131            if !folder.is_dir() {
132                return Err(StartError::Failed(Failure::NoFolder { folder }));
133            }
134            running.insert(app.to_owned(), label.clone());
135            line
136        };
137        let process = match Process::start(&line, &folder, input) {
138            Ok(process) => process,
139            Err(error) => {
140                self.lock().remove(app);
141                return Err(StartError::Failed(not_started(error, &line.program)));
142            }
143        };
144        let started = Instant::now();
145        let stop = Arc::new(AtomicBool::new(false));
146        let (sender, events) = mpsc::channel();
147        let owner = Owner {
148            process,
149            started,
150            limit,
151            stop: Arc::clone(&stop),
152            events: sender,
153            runs: self.clone(),
154            app: app.to_owned(),
155        };
156        std::thread::spawn(move || owner.run());
157        Ok(Run {
158            line,
159            label,
160            args: args.to_vec(),
161            started_at: SystemTime::now(),
162            started,
163            events,
164            stop,
165        })
166    }
167
168    /// The label of the command that runs in `app`, if one does.
169    pub fn running(&self, app: &Path) -> Option<String> {
170        self.lock().get(app).cloned()
171    }
172
173    fn lock(&self) -> MutexGuard<'_, BTreeMap<PathBuf, String>> {
174        self.running.lock().unwrap_or_else(PoisonError::into_inner)
175    }
176}
177
178/// Why a command did not start.
179#[cfg(feature = "run")]
180#[derive(Debug, Clone, PartialEq, Eq)]
181pub enum StartError {
182    /// The app runs another command, with this label.
183    Busy { command: String },
184    /// No way to run PHP is chosen for the app.
185    NoRunner,
186    /// `NoCommand`, `NoFolder`, `NotFound` or `NotStarted`.
187    Failed(Failure),
188}
189
190/// A command that started. Its owner thread sends what happens to it.
191#[cfg(feature = "run")]
192#[derive(Debug)]
193pub struct Run {
194    /// What runs; `display()` is the `$` line.
195    pub line: CommandLine,
196    /// The artisan words, quoted as the `$` line quotes them.
197    pub label: String,
198    /// The artisan words as given to [`Runs::start`].
199    pub args: Vec<String>,
200    pub started_at: SystemTime,
201    started: Instant,
202    events: Receiver<RunEvent>,
203    stop: Arc<AtomicBool>,
204}
205
206#[cfg(feature = "run")]
207impl Run {
208    /// Asks the run to end its process tree. Safe to call twice or after the end.
209    pub fn stop(&self) {
210        self.stop.store(true, Ordering::Relaxed);
211    }
212
213    /// The time since the start.
214    pub fn elapsed(&self) -> Duration {
215        self.started.elapsed()
216    }
217
218    /// What arrived since the last call. It never blocks.
219    pub fn events(&self) -> Vec<RunEvent> {
220        self.events.try_iter().collect()
221    }
222
223    /// What arrives until the run ended or `deadline` passed, with
224    /// [`RunEvent::Ended`] last when it came. It sleeps between events. After a
225    /// [`Run::stop`], a deadline [`STOP_WAIT`] away leaves room for the end.
226    pub fn wait(&self, deadline: Instant) -> Vec<RunEvent> {
227        let mut arrived = Vec::new();
228        loop {
229            let left = deadline.saturating_duration_since(Instant::now());
230            match self.events.recv_timeout(left) {
231                Ok(event) => {
232                    let ended = matches!(event, RunEvent::Ended(_));
233                    arrived.push(event);
234                    if ended {
235                        return arrived;
236                    }
237                }
238                Err(RecvTimeoutError::Timeout | RecvTimeoutError::Disconnected) => {
239                    return arrived;
240                }
241            }
242        }
243    }
244}
245
246/// What a run sends, in order. [`RunEvent::Ended`] comes last.
247#[cfg(feature = "run")]
248#[derive(Debug, Clone, PartialEq, Eq)]
249pub enum RunEvent {
250    /// A line without its newline, with its escape codes. `cut` is true when the
251    /// line was longer than `KEEP` bytes and `text` holds only its start.
252    Line {
253        stream: Stream,
254        text: String,
255        cut: bool,
256    },
257    /// The output passed [`OUTPUT_LIMIT`]; the later lines are dropped.
258    Cut,
259    /// The run is over. No thread of the run is left, and the app accepts a new start.
260    Ended(RunEnd),
261}
262
263/// How a run ended.
264#[cfg(feature = "run")]
265#[derive(Debug, Clone, Copy, PartialEq, Eq)]
266pub enum RunEnd {
267    /// The program ended by itself. `code` is `None` when a signal that Mortise
268    /// did not send ended it.
269    Exited {
270        code: Option<i32>,
271        elapsed: Duration,
272    },
273    /// Mortise stopped it. `limit` is the time limit, when that stopped it.
274    Stopped {
275        elapsed: Duration,
276        limit: Option<Duration>,
277    },
278}
279
280/// Whether a stop of the command with these artisan words asks first. A migration
281/// that stops half way can leave the database between two states.
282#[cfg(feature = "run")]
283pub fn stop_asks_first(args: &[String]) -> bool {
284    const ASK: [&str; 6] = [
285        "module:migrate",
286        "module:migrate-rollback",
287        "module:migrate-refresh",
288        "module:migrate-reset",
289        "module:migrate-fresh",
290        "module:seed",
291    ];
292    args.first()
293        .is_some_and(|word| ASK.contains(&word.as_str()))
294}
295
296/// The artisan words one space apart, each quoted as [`CommandLine::display`]
297/// quotes an argument on this platform.
298#[cfg(feature = "run")]
299fn label(args: &[String]) -> String {
300    // `display` quotes each argument on its own, and a bare program adds no `& `.
301    let line = CommandLine {
302        program: "artisan".into(),
303        args: args.to_vec(),
304    };
305    let shown = line.display();
306    shown
307        .strip_prefix("artisan")
308        .unwrap_or(&shown)
309        .trim_start()
310        .to_string()
311}
312
313/// The failure of a program that did not start.
314#[cfg(feature = "run")]
315pub(crate) fn not_started(error: std::io::Error, program: &str) -> Failure {
316    if error.kind() == std::io::ErrorKind::NotFound {
317        Failure::NotFound {
318            program: program.to_owned(),
319        }
320    } else {
321        Failure::NotStarted {
322            program: program.to_owned(),
323            message: error.to_string(),
324        }
325    }
326}
327
328/// The thread that holds the program of a run.
329#[cfg(feature = "run")]
330struct Owner {
331    process: Process,
332    started: Instant,
333    limit: Duration,
334    stop: Arc<AtomicBool>,
335    events: Sender<RunEvent>,
336    runs: Runs,
337    app: PathBuf,
338}
339
340#[cfg(feature = "run")]
341impl Owner {
342    /// Forwards the lines until the program ends, by itself, by a stop or at the
343    /// limit. Then it ends as D2 of the design says: the readers joined, the app
344    /// removed from [`Runs`], and [`RunEvent::Ended`] last.
345    fn run(self) {
346        let Owner {
347            mut process,
348            started,
349            limit,
350            stop,
351            events,
352            runs,
353            app,
354        } = self;
355        let mut sent = 0;
356        let mut cut = false;
357        let mut forward = |stream, text: String, line_cut| {
358            if cut {
359                return;
360            }
361            sent += text.len() + 1;
362            if sent > OUTPUT_LIMIT {
363                cut = true;
364                let _ = events.send(RunEvent::Cut);
365            } else {
366                let _ = events.send(RunEvent::Line {
367                    stream,
368                    text,
369                    cut: line_cut,
370                });
371            }
372        };
373        // `stopped` is `Some` when Mortise ended it, with the limit when that did.
374        // `ended` is true once `Process::stop` ran.
375        let mut ended = false;
376        let stopped = loop {
377            match process.exited() {
378                Ok(true) => break None,
379                Ok(false) => {}
380                Err(_) => {
381                    process.stop(&mut forward);
382                    ended = true;
383                    break None;
384                }
385            }
386            let at_limit = started.elapsed() >= limit;
387            if at_limit || stop.load(Ordering::Relaxed) {
388                process.stop(&mut forward);
389                ended = true;
390                break Some(at_limit.then_some(limit));
391            }
392            process.read(TICK, &mut forward);
393        };
394        let elapsed = started.elapsed();
395        let (status, late) = process.finish(ended, &stop, &mut forward);
396        let end = match stopped {
397            Some(limit) => RunEnd::Stopped { elapsed, limit },
398            None if late => RunEnd::Stopped {
399                elapsed: started.elapsed(),
400                limit: None,
401            },
402            None => RunEnd::Exited {
403                code: status.and_then(|status| status.code()),
404                elapsed,
405            },
406        };
407        runs.lock().remove(&app);
408        let _ = events.send(RunEvent::Ended(end));
409    }
410}
411
412/// How many lines may wait between the readers and the owner. A reader that
413/// finds the queue full waits, so a flood of output stays bounded in memory.
414#[cfg(feature = "run")]
415const QUEUE: usize = 1024;
416
417/// A started program and the threads that read its pipes.
418#[cfg(feature = "run")]
419struct Process {
420    child: Child,
421    lines: Receiver<(Stream, String, bool)>,
422    readers: Vec<JoinHandle<()>>,
423}
424
425#[cfg(feature = "run")]
426impl Process {
427    /// Starts `line` in `folder`, on Unix as the leader of a new process group,
428    /// with both pipes read into one channel.
429    fn start(line: &CommandLine, folder: &Path, input: Option<Vec<u8>>) -> std::io::Result<Self> {
430        let mut command = prepare(line, folder)?;
431        if input.is_some() {
432            command.stdin(Stdio::piped());
433        }
434        // Its children join the group, so a signal to the group reaches the tree.
435        #[cfg(unix)]
436        {
437            use std::os::unix::process::CommandExt;
438            command.process_group(0);
439        }
440        let mut child = command.spawn()?;
441        // Written from a thread of its own, so that a program that reads its input
442        // late cannot block the start. The pipe closes when the thread ends.
443        if let (Some(input), Some(mut stdin)) = (input, child.stdin.take()) {
444            std::thread::spawn(move || {
445                use std::io::Write;
446                let _ = stdin.write_all(&input);
447            });
448        }
449        let (sender, lines) = mpsc::sync_channel(QUEUE);
450        let readers = [
451            read_lines(child.stdout.take(), Stream::Out, sender.clone()),
452            read_lines(child.stderr.take(), Stream::Err, sender),
453        ];
454        Ok(Self {
455            child,
456            lines,
457            readers: readers.into_iter().flatten().collect(),
458        })
459    }
460
461    /// Waits up to `wait` for a line, then gives `forward` the lines that arrived,
462    /// at most [`QUEUE`], so the caller looks at the program again soon.
463    /// It returns whether a line came.
464    fn read(&self, wait: Duration, forward: &mut impl FnMut(Stream, String, bool)) -> bool {
465        match self.lines.recv_timeout(wait) {
466            Ok((stream, text, cut)) => forward(stream, text, cut),
467            Err(RecvTimeoutError::Timeout) => return false,
468            Err(RecvTimeoutError::Disconnected) => {
469                std::thread::sleep(wait);
470                return false;
471            }
472        }
473        for (stream, text, cut) in self.lines.try_iter().take(QUEUE) {
474            forward(stream, text, cut);
475        }
476        true
477    }
478
479    /// Whether the program has exited. On Unix it is not reaped, so its pid, which
480    /// is the id of its group, stays taken until [`Process::finish`] kills the group.
481    #[cfg(unix)]
482    fn exited(&mut self) -> std::io::Result<bool> {
483        use rustix::process::{Pid, WaitId, WaitIdOptions, waitid};
484        let options = WaitIdOptions::EXITED | WaitIdOptions::NOHANG | WaitIdOptions::NOWAIT;
485        let status = waitid(WaitId::Pid(Pid::from_child(&self.child)), options)?;
486        Ok(status.is_some())
487    }
488
489    /// Whether the program has exited. The handle that `Child` holds keeps the pid
490    /// from being used again.
491    #[cfg(not(unix))]
492    fn exited(&mut self) -> std::io::Result<bool> {
493        Ok(self.child.try_wait()?.is_some())
494    }
495
496    /// Ends the process tree: it asks first, and kills after [`STOP_GRACE`].
497    /// It reads the lines meanwhile. [`Process::finish`] then kills what is left.
498    fn stop(&mut self, forward: &mut impl FnMut(Stream, String, bool)) {
499        self.terminate();
500        let asked = Instant::now();
501        while !self.exited().unwrap_or(true) {
502            if asked.elapsed() >= STOP_GRACE {
503                self.kill();
504                return;
505            }
506            self.read(TICK, forward);
507        }
508    }
509
510    /// Asks the tree to end: SIGTERM to the group.
511    #[cfg(unix)]
512    fn terminate(&mut self) {
513        self.signal(rustix::process::Signal::TERM);
514    }
515
516    /// Ends the tree at once: SIGKILL to the group.
517    #[cfg(unix)]
518    fn kill(&mut self) {
519        self.signal(rustix::process::Signal::KILL);
520    }
521
522    /// Sends `signal` to the group of the program. `ESRCH` means that the group is
523    /// gone. On another error the leader alone gets SIGKILL, so a wait for it ends.
524    #[cfg(unix)]
525    fn signal(&mut self, signal: rustix::process::Signal) {
526        use rustix::process::{Pid, kill_process_group};
527        match kill_process_group(Pid::from_child(&self.child), signal) {
528            Ok(()) | Err(rustix::io::Errno::SRCH) => {}
529            Err(_) => {
530                let _ = self.child.kill();
531            }
532        }
533    }
534
535    /// Ends the tree: `taskkill /T` ends the children too, so `php.exe` under
536    /// `herd.bat` ends. When `taskkill` fails, the program alone is ended.
537    /// Run on Windows by `a_batch_file_refuses_a_line_break_and_stops_with_its_tree`
538    /// in `tests/run.rs`.
539    #[cfg(not(unix))]
540    fn terminate(&mut self) {
541        let pid = self.child.id().to_string();
542        let ended = command("taskkill")
543            .args(["/PID", pid.as_str(), "/T", "/F"])
544            .stdout(Stdio::null())
545            .stderr(Stdio::null())
546            .status()
547            .is_ok_and(|status| status.success());
548        if !ended {
549            let _ = self.child.kill();
550        }
551    }
552
553    /// Ends the program at once.
554    #[cfg(not(unix))]
555    fn kill(&mut self) {
556        let _ = self.child.kill();
557    }
558
559    /// The end, once the program has exited or was stopped. `stopped` is true when
560    /// [`Process::stop`] already ran. `stop` is the flag of a stop that the user or
561    /// the caller may still ask for. The readers get [`GRACE`] to finish. Then, on Unix,
562    /// what is left in the group is killed, even a child that closed its pipes, and
563    /// the program is reaped. The readers are joined and `forward` gets their last
564    /// lines. It returns how the program ended, and whether a stop ended what was
565    /// left of the tree.
566    ///
567    /// A stop that is asked for while a child that outlived the program still
568    /// writes, or that was asked for as the program ended and has not started,
569    /// ends what is left as [`Process::stop`] does, with [`Process::stop_the_rest`],
570    /// whether or not a child still holds a pipe. After a stop, the readers are not
571    /// waited for past [`GRACE`] and [`DETACH`], so the run ends within [`STOP_WAIT`].
572    ///
573    /// Known limit: a process that left the group (`setsid`), or on Windows a child
574    /// of a program that ended by itself or that `taskkill` missed, can keep a pipe
575    /// open. Windows cannot name the children of an ended program without a job
576    /// object. A reader that still reads [`DETACH`] later is left behind; it ends
577    /// when the pipe closes or the queue is gone.
578    fn finish(
579        &mut self,
580        stopped: bool,
581        stop: &AtomicBool,
582        forward: &mut impl FnMut(Stream, String, bool),
583    ) -> (Option<ExitStatus>, bool) {
584        let stopping = || stop.load(Ordering::Relaxed);
585        let mut done = self.wait_for_readers(GRACE, (!stopped).then_some(stop), forward);
586        let mut late = !stopped && stopping();
587        let status = if late {
588            let (status, rest_done) = self.stop_the_rest(done, forward);
589            done = rest_done;
590            status
591        } else {
592            // The program is not reaped yet, so the group id cannot belong to another group.
593            #[cfg(unix)]
594            self.kill();
595            self.child.wait().ok()
596        };
597        if !done {
598            let watch = !stopped && !late;
599            done = self.wait_for_readers(DETACH, watch.then_some(stop), forward);
600            late |= watch && !done && stopping();
601        }
602        for reader in std::mem::take(&mut self.readers) {
603            if reader.is_finished() {
604                let _ = reader.join();
605            }
606        }
607        // A reader left behind may still send; the queue bounds what is taken.
608        for (stream, text, cut) in self.lines.try_iter().take(QUEUE) {
609            forward(stream, text, cut);
610        }
611        (status, late)
612    }
613
614    /// Ends what is left of the tree after the program exited, as [`Process::stop`]
615    /// does: SIGTERM to the group, and SIGKILL to what is still there after
616    /// [`STOP_GRACE`]. It reads the lines meanwhile and reaps the program. `done`
617    /// says whether the readers already finished. It returns the status of the
618    /// program and whether the readers finished.
619    ///
620    /// On Unix the SIGTERM goes first, while the unreaped program keeps the group id
621    /// ours. The program is then reaped, because a group whose leader is a zombie
622    /// still answers signal 0 on Linux. Then signal 0 to the group, every [`TICK`],
623    /// tells whether a member is left, also one that closed its pipes. The SIGKILL
624    /// after [`STOP_GRACE`] goes to a group whose member answered a [`TICK`] before.
625    ///
626    /// On Windows `taskkill` runs on the program, which has exited, and Windows
627    /// cannot name what is left: the readers get [`STOP_GRACE`], and a child that
628    /// closed its pipes is not waited for.
629    fn stop_the_rest(
630        &mut self,
631        done: bool,
632        forward: &mut impl FnMut(Stream, String, bool),
633    ) -> (Option<ExitStatus>, bool) {
634        self.terminate();
635        #[cfg(unix)]
636        {
637            use rustix::process::{Pid, test_kill_process_group};
638            let asked = Instant::now();
639            let status = self.child.wait().ok();
640            let group = Pid::from_child(&self.child);
641            while test_kill_process_group(group).is_ok() {
642                if asked.elapsed() >= STOP_GRACE {
643                    self.kill();
644                    break;
645                }
646                // With both readers gone, this sleeps for a tick.
647                self.read(TICK, forward);
648            }
649            let finished = self.readers.iter().all(JoinHandle::is_finished);
650            (status, done || finished)
651        }
652        #[cfg(not(unix))]
653        {
654            let done = done || self.wait_for_readers(STOP_GRACE, None, forward);
655            self.kill();
656            (self.child.wait().ok(), done)
657        }
658    }
659
660    /// Reads until both readers finished, for at most `wait`. True when they did.
661    /// With `stop`, a reader that waits for room in the queue is not stuck, so
662    /// `wait` starts again while lines come, up to [`DRAIN`] in all, and the wait
663    /// ends early once `stop` is set.
664    fn wait_for_readers(
665        &self,
666        wait: Duration,
667        stop: Option<&AtomicBool>,
668        forward: &mut impl FnMut(Stream, String, bool),
669    ) -> bool {
670        let last = Instant::now() + DRAIN;
671        let mut until = Instant::now() + wait;
672        loop {
673            if self.readers.iter().all(JoinHandle::is_finished) {
674                return true;
675            }
676            if stop.is_some_and(|stop| stop.load(Ordering::Relaxed)) {
677                return false;
678            }
679            let left = until.saturating_duration_since(Instant::now());
680            if left.is_zero() {
681                return false;
682            }
683            if self.read(left.min(TICK), forward) && stop.is_some() {
684                until = (Instant::now() + wait).min(last);
685            }
686        }
687    }
688}
689
690/// What a program printed and how it ended.
691#[cfg(feature = "run")]
692#[derive(Debug, Default)]
693pub(crate) struct Captured {
694    /// `None` when the program was stopped or ended by a signal.
695    pub code: Option<i32>,
696    pub stdout: Vec<String>,
697    pub stderr: Vec<String>,
698    /// The program ran past the limit and was stopped.
699    pub timed_out: bool,
700}
701
702/// Runs `line` in `folder` and keeps its lines, at most [`KEEP`] bytes of each
703/// stream, for at most `limit`. At the limit it ends the whole process tree.
704/// An error means the program did not start.
705#[cfg(feature = "run")]
706pub(crate) fn capture(
707    line: &CommandLine,
708    folder: &Path,
709    limit: Duration,
710) -> std::io::Result<Captured> {
711    let mut process = Process::start(line, folder, None)?;
712    let started = Instant::now();
713    let mut stdout = Vec::new();
714    let mut stderr = Vec::new();
715    let mut kept = [0, 0];
716    let mut keep = |stream, text: String, _cut| {
717        let (kept, lines) = match stream {
718            Stream::Out => (&mut kept[0], &mut stdout),
719            Stream::Err => (&mut kept[1], &mut stderr),
720        };
721        // Once a stream is full, its later lines are dropped too.
722        if *kept + text.len() > KEEP {
723            *kept = KEEP + 1;
724        } else {
725            *kept += text.len() + 1;
726            lines.push(text);
727        }
728    };
729    let mut timed_out = false;
730    while !process.exited()? {
731        if started.elapsed() >= limit {
732            process.stop(&mut keep);
733            timed_out = true;
734            break;
735        }
736        process.read(TICK, &mut keep);
737    }
738    let (status, _) = process.finish(timed_out, &AtomicBool::new(false), &mut keep);
739    Ok(Captured {
740        code: status
741            .and_then(|status| status.code())
742            .filter(|_| !timed_out),
743        stdout,
744        stderr,
745        timed_out,
746    })
747}
748
749/// The command for `line` in `folder`, with both pipes and the `PATH` of [`child_path`].
750/// An error means the program must not start.
751#[cfg(feature = "run")]
752fn prepare(line: &CommandLine, folder: &Path) -> std::io::Result<Command> {
753    let program = program_path(&line.program, folder);
754    if cfg!(windows) {
755        refuse_batch_with_percent(&program)?;
756    }
757    let mut command = command(program);
758    command
759        .args(&line.args)
760        .current_dir(folder)
761        .stdout(Stdio::piped())
762        .stderr(Stdio::piped());
763    let home = directories::BaseDirs::new().map(|dirs| dirs.home_dir().to_path_buf());
764    if let Some(path) = child_path(std::env::var_os("PATH"), home.as_deref()) {
765        command.env("PATH", path);
766    }
767    Ok(command)
768}
769
770/// Refuses a `.bat` or `.cmd` whose path holds `%`. On Windows std starts a batch
771/// file through `cmd.exe`, which would expand the `%` in its path. Windows ignores
772/// dots and spaces at the end of a name, so they do not hide the extension. The
773/// folder that a lookup in `PATH` finds is not checked.
774#[cfg(feature = "run")]
775fn refuse_batch_with_percent(program: &Path) -> std::io::Result<()> {
776    let name = program.to_string_lossy();
777    let name = name.trim_end_matches(['.', ' ']).to_ascii_lowercase();
778    if (name.ends_with(".bat") || name.ends_with(".cmd")) && name.contains('%') {
779        return Err(std::io::Error::new(
780            std::io::ErrorKind::InvalidInput,
781            "the path of the batch file holds %, which cmd.exe would expand",
782        ));
783    }
784    Ok(())
785}
786
787/// The program to start for the word `program`. A relative path with a separator
788/// (`/`, or `\\` on Windows) is joined to `folder`: std leaves a relative program with
789/// `current_dir` to the platform. A bare name stays a lookup in `PATH`.
790#[cfg(feature = "run")]
791fn program_path(program: &str, folder: &Path) -> PathBuf {
792    let separators: &[char] = if cfg!(windows) { &['/', '\\'] } else { &['/'] };
793    if program.contains(separators) {
794        folder.join(program)
795    } else {
796        PathBuf::from(program)
797    }
798}
799
800/// The `PATH` of Mortise with the folders of [`extra_folders`] at the end.
801/// `None` when the folders cannot be joined; the child then keeps the `PATH` of Mortise.
802#[cfg(feature = "run")]
803fn child_path(path: Option<OsString>, home: Option<&Path>) -> Option<OsString> {
804    let mut folders: Vec<PathBuf> = path.iter().flat_map(std::env::split_paths).collect();
805    folders.extend(extra_folders(home));
806    std::env::join_paths(folders).ok()
807}
808
809/// Where Herd, Homebrew and Docker put their programs. A desktop app on macOS starts
810/// with a `PATH` that lacks them. Assumed from their documentation, not checked on
811/// every platform.
812#[cfg(feature = "run")]
813fn extra_folders(home: Option<&Path>) -> Vec<PathBuf> {
814    let at_home = |folder: &str| home.map(|home| home.join(folder));
815    let folders = if cfg!(target_os = "macos") {
816        vec![
817            at_home("Library/Application Support/Herd/bin"),
818            Some("/opt/homebrew/bin".into()),
819            Some("/usr/local/bin".into()),
820            at_home(".docker/bin"),
821        ]
822    } else if cfg!(windows) {
823        vec![at_home(r".config\herd\bin")]
824    } else {
825        vec![Some("/usr/local/bin".into()), at_home(".local/bin")]
826    };
827    folders.into_iter().flatten().collect()
828}
829
830/// Reads `pipe` line by line on a thread of its own and sends each line with `stream`.
831/// A line is cut at [`KEEP`] bytes, and sent with `true` then. The thread ends when the pipe closes or nobody
832/// listens any more. `None` when there is no pipe.
833#[cfg(feature = "run")]
834fn read_lines(
835    pipe: Option<impl Read + Send + 'static>,
836    stream: Stream,
837    sender: SyncSender<(Stream, String, bool)>,
838) -> Option<JoinHandle<()>> {
839    let pipe = pipe?;
840    Some(std::thread::spawn(move || {
841        let mut reader = BufReader::new(pipe);
842        let mut bytes = Vec::new();
843        loop {
844            bytes.clear();
845            // `take` bounds the buffer when a stream has no newline.
846            match reader
847                .by_ref()
848                .take(KEEP as u64)
849                .read_until(b'\n', &mut bytes)
850            {
851                Ok(0) | Err(_) => return,
852                Ok(_) => {}
853            }
854            let mut cut = false;
855            if bytes.last() == Some(&b'\n') {
856                bytes.pop();
857            } else if bytes.len() == KEEP {
858                // An error shows again at the next read, which ends the thread.
859                cut = skip_line(&mut reader).unwrap_or(true);
860            }
861            if bytes.last() == Some(&b'\r') {
862                bytes.pop();
863            }
864            let text = String::from_utf8_lossy(&bytes).into_owned();
865            if sender.send((stream, text, cut)).is_err() {
866                return;
867            }
868        }
869    }))
870}
871
872/// Reads and drops the rest of a line, up to and with its newline. True when it
873/// dropped a byte other than the line's end (`\r` and `\n`).
874#[cfg(feature = "run")]
875fn skip_line(reader: &mut impl BufRead) -> std::io::Result<bool> {
876    let mut dropped = false;
877    loop {
878        let buffer = match reader.fill_buf() {
879            Ok(buffer) => buffer,
880            Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
881            Err(error) => return Err(error),
882        };
883        if buffer.is_empty() {
884            return Ok(dropped);
885        }
886        let end = buffer.iter().position(|byte| *byte == b'\n');
887        let rest = &buffer[..end.unwrap_or(buffer.len())];
888        dropped |= rest.iter().any(|byte| *byte != b'\r');
889        match end {
890            Some(at) => {
891                reader.consume(at + 1);
892                return Ok(dropped);
893            }
894            None => {
895                let read = buffer.len();
896                reader.consume(read);
897            }
898        }
899    }
900}
901
902#[cfg(all(test, feature = "run"))]
903mod tests {
904    use super::*;
905
906    /// Starts `script` in `sh` in `folder`, and reads until the program exited and
907    /// `ready` holds. It gives the program and the lines read.
908    #[cfg(unix)]
909    fn exited_with_its_child(
910        script: &str,
911        folder: &Path,
912        ready: impl Fn(&Process, &[String]) -> bool,
913    ) -> (Process, Vec<String>) {
914        let line = CommandLine {
915            program: "/bin/sh".into(),
916            args: vec!["-c".into(), script.into()],
917        };
918        let mut process = Process::start(&line, folder, None).unwrap();
919        let mut lines = Vec::new();
920        let deadline = Instant::now() + Duration::from_secs(10);
921        while !(process.exited().unwrap() && ready(&process, &lines)) {
922            assert!(Instant::now() < deadline, "{lines:?}");
923            process.read(TICK, &mut |_, text, _| lines.push(text));
924        }
925        (process, lines)
926    }
927
928    /// The owner reads the stop flag after it sees that the program exited, so a
929    /// stop asked for as the program ends is pending when the readers drain. Here
930    /// the program has exited, and its child is ready, before the flag is set.
931    #[cfg(unix)]
932    #[test]
933    fn a_stop_pending_when_the_readers_drain_asks_the_rest_to_end() {
934        let folder =
935            std::env::temp_dir().join(format!("mortise-pending-stop-{}", std::process::id()));
936        std::fs::create_dir_all(&folder).unwrap();
937        let pending = AtomicBool::new(true);
938
939        // The child writes, and says when SIGTERM comes.
940        let (mut process, mut lines) = exited_with_its_child(
941            r#"(trap 'echo term; exit 0' TERM; while :; do echo tick; sleep 0.05; done) &"#,
942            &folder,
943            |_, lines| lines.iter().any(|line| line == "tick"),
944        );
945        let (_, late) = process.finish(false, &pending, &mut |_, text, _| lines.push(text));
946        assert!(late);
947        assert!(lines.iter().any(|line| line == "term"), "{lines:?}");
948
949        // The child closed its pipes, so the readers are done, and it leaves a file
950        // when SIGTERM comes. It ends at SIGTERM, before the kill.
951        let (mut process, _) = exited_with_its_child(
952            r#"(trap 'touch term; exit 0' TERM; exec >&- 2>&-; touch ready; while :; do sleep 0.05; done) &"#,
953            &folder,
954            |process, _| {
955                folder.join("ready").exists() && process.readers.iter().all(JoinHandle::is_finished)
956            },
957        );
958        let asked = Instant::now();
959        let (_, late) = process.finish(false, &pending, &mut |_, _, _| {});
960        assert!(late);
961        assert!(asked.elapsed() < STOP_GRACE, "{:?}", asked.elapsed());
962        assert!(folder.join("term").exists());
963        let _ = std::fs::remove_dir_all(&folder);
964    }
965
966    #[test]
967    fn a_stop_of_a_migration_or_a_seed_asks_first() {
968        let words = |words: &[&str]| {
969            words
970                .iter()
971                .map(|word| word.to_string())
972                .collect::<Vec<_>>()
973        };
974        assert!(stop_asks_first(&words(&["module:migrate", "Blog"])));
975        assert!(stop_asks_first(&words(&["module:migrate-fresh"])));
976        assert!(stop_asks_first(&words(&["module:seed", "Blog"])));
977        assert!(!stop_asks_first(&words(&["module:make", "module:migrate"])));
978        assert!(!stop_asks_first(&words(&["migrate"])));
979        assert!(!stop_asks_first(&[]));
980    }
981
982    #[test]
983    fn a_program_with_a_separator_starts_in_the_folder() {
984        let folder = Path::new("/code/shop-api");
985        assert_eq!(program_path("php", folder), PathBuf::from("php"));
986        assert_eq!(
987            program_path("./vendor/bin/sail", folder),
988            folder.join("./vendor/bin/sail")
989        );
990        assert_eq!(
991            program_path("vendor/bin/sail", folder),
992            folder.join("vendor/bin/sail")
993        );
994        let windows = program_path(r"vendor\bin\sail", folder);
995        if cfg!(windows) {
996            assert_eq!(windows, folder.join(r"vendor\bin\sail"));
997        } else {
998            assert_eq!(windows, PathBuf::from(r"vendor\bin\sail"));
999        }
1000        let absolute = std::env::temp_dir().join("php");
1001        let absolute = absolute.to_str().unwrap();
1002        assert_eq!(program_path(absolute, folder), PathBuf::from(absolute));
1003    }
1004
1005    #[test]
1006    fn a_batch_file_with_percent_in_its_path_is_refused() {
1007        for program in [
1008            r"C:\100%\herd.bat",
1009            r"C:\%USERPROFILE%\herd.CMD",
1010            "%a%.Bat. ",
1011        ] {
1012            let error = refuse_batch_with_percent(Path::new(program)).unwrap_err();
1013            assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput, "{program}");
1014        }
1015        // A refusal, from here or from std, is a command that did not start, with its text.
1016        let refusal = std::io::Error::new(
1017            std::io::ErrorKind::InvalidInput,
1018            "batch file arguments are invalid",
1019        );
1020        assert_eq!(
1021            not_started(refusal, "herd.bat"),
1022            Failure::NotStarted {
1023                program: "herd.bat".to_owned(),
1024                message: "batch file arguments are invalid".to_owned(),
1025            }
1026        );
1027        for program in [r"C:\100%\php.exe", r"C:\herd\herd.bat", "herd.bat"] {
1028            assert!(
1029                refuse_batch_with_percent(Path::new(program)).is_ok(),
1030                "{program}"
1031            );
1032        }
1033    }
1034
1035    #[test]
1036    fn the_path_of_mortise_comes_first() {
1037        let home = Path::new("/home/ada");
1038        let path = std::env::join_paths(["/usr/bin", "/bin"]).unwrap();
1039        let joined = child_path(Some(path), Some(home)).unwrap();
1040        let folders: Vec<PathBuf> = std::env::split_paths(&joined).collect();
1041        assert_eq!(
1042            folders[..2],
1043            [PathBuf::from("/usr/bin"), PathBuf::from("/bin")]
1044        );
1045        assert_eq!(folders[2..], extra_folders(Some(home)));
1046        assert!(folders.iter().any(|folder| folder.starts_with(home)));
1047    }
1048}