#[cfg(feature = "run")]
use std::collections::BTreeMap;
#[cfg(feature = "run")]
use std::ffi::OsString;
#[cfg(feature = "run")]
use std::io::{BufRead, BufReader, Read};
#[cfg(feature = "run")]
use std::path::{Path, PathBuf};
#[cfg(feature = "run")]
use std::process::{Child, ExitStatus};
#[cfg(feature = "run")]
use std::process::{Command, Stdio};
#[cfg(feature = "run")]
use std::sync::atomic::{AtomicBool, Ordering};
#[cfg(feature = "run")]
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender, SyncSender};
#[cfg(feature = "run")]
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
#[cfg(feature = "run")]
use std::thread::JoinHandle;
#[cfg(feature = "run")]
use std::time::{Duration, Instant, SystemTime};
#[cfg(feature = "run")]
use super::history::OUTPUT_LIMIT;
#[cfg(feature = "run")]
use super::{CommandLine, Failure, PhpSettings};
#[cfg(feature = "run")]
use crate::program::command;
#[cfg(feature = "run")]
const TICK: Duration = Duration::from_millis(50);
#[cfg(feature = "run")]
const GRACE: Duration = Duration::from_millis(250);
#[cfg(feature = "run")]
const DETACH: Duration = Duration::from_secs(1);
#[cfg(feature = "run")]
const DRAIN: Duration = Duration::from_secs(10);
#[cfg(feature = "run")]
const STOP_GRACE: Duration = Duration::from_secs(3);
#[cfg(feature = "run")]
pub const STOP_WAIT: Duration = STOP_GRACE
.saturating_add(GRACE)
.saturating_add(DETACH)
.saturating_add(Duration::from_millis(500));
#[cfg(feature = "run")]
const KEEP: usize = 64 * 1024;
#[cfg(feature = "run")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Stream {
Out,
Err,
}
#[cfg(feature = "run")]
#[derive(Debug, Clone, Default)]
pub struct Runs {
running: Arc<Mutex<BTreeMap<PathBuf, String>>>,
}
#[cfg(feature = "run")]
impl Runs {
pub fn new() -> Self {
Self::default()
}
pub fn start(
&self,
app: &Path,
php: &PhpSettings,
args: &[String],
limit: Duration,
) -> Result<Run, StartError> {
self.start_with_input(app, php, args, limit, None)
}
pub fn start_with_input(
&self,
app: &Path,
php: &PhpSettings,
args: &[String],
limit: Duration,
input: Option<Vec<u8>>,
) -> Result<Run, StartError> {
let label = label(args);
let folder = php.folder(app);
let line = {
let mut running = self.lock();
if let Some(command) = running.get(app) {
return Err(StartError::Busy {
command: command.clone(),
});
}
let runner = php.runner.as_ref().ok_or(StartError::NoRunner)?;
let words: Vec<&str> = args.iter().map(String::as_str).collect();
let line = CommandLine::artisan(runner, &words)
.ok_or(StartError::Failed(Failure::NoCommand))?;
if !folder.is_dir() {
return Err(StartError::Failed(Failure::NoFolder { folder }));
}
running.insert(app.to_owned(), label.clone());
line
};
let process = match Process::start(&line, &folder, input) {
Ok(process) => process,
Err(error) => {
self.lock().remove(app);
return Err(StartError::Failed(not_started(error, &line.program)));
}
};
let started = Instant::now();
let stop = Arc::new(AtomicBool::new(false));
let (sender, events) = mpsc::channel();
let owner = Owner {
process,
started,
limit,
stop: Arc::clone(&stop),
events: sender,
runs: self.clone(),
app: app.to_owned(),
};
std::thread::spawn(move || owner.run());
Ok(Run {
line,
label,
args: args.to_vec(),
started_at: SystemTime::now(),
started,
events,
stop,
})
}
pub fn running(&self, app: &Path) -> Option<String> {
self.lock().get(app).cloned()
}
fn lock(&self) -> MutexGuard<'_, BTreeMap<PathBuf, String>> {
self.running.lock().unwrap_or_else(PoisonError::into_inner)
}
}
#[cfg(feature = "run")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StartError {
Busy { command: String },
NoRunner,
Failed(Failure),
}
#[cfg(feature = "run")]
#[derive(Debug)]
pub struct Run {
pub line: CommandLine,
pub label: String,
pub args: Vec<String>,
pub started_at: SystemTime,
started: Instant,
events: Receiver<RunEvent>,
stop: Arc<AtomicBool>,
}
#[cfg(feature = "run")]
impl Run {
pub fn stop(&self) {
self.stop.store(true, Ordering::Relaxed);
}
pub fn elapsed(&self) -> Duration {
self.started.elapsed()
}
pub fn events(&self) -> Vec<RunEvent> {
self.events.try_iter().collect()
}
pub fn wait(&self, deadline: Instant) -> Vec<RunEvent> {
let mut arrived = Vec::new();
loop {
let left = deadline.saturating_duration_since(Instant::now());
match self.events.recv_timeout(left) {
Ok(event) => {
let ended = matches!(event, RunEvent::Ended(_));
arrived.push(event);
if ended {
return arrived;
}
}
Err(RecvTimeoutError::Timeout | RecvTimeoutError::Disconnected) => {
return arrived;
}
}
}
}
}
#[cfg(feature = "run")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RunEvent {
Line {
stream: Stream,
text: String,
cut: bool,
},
Cut,
Ended(RunEnd),
}
#[cfg(feature = "run")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RunEnd {
Exited {
code: Option<i32>,
elapsed: Duration,
},
Stopped {
elapsed: Duration,
limit: Option<Duration>,
},
}
#[cfg(feature = "run")]
pub fn stop_asks_first(args: &[String]) -> bool {
const ASK: [&str; 6] = [
"module:migrate",
"module:migrate-rollback",
"module:migrate-refresh",
"module:migrate-reset",
"module:migrate-fresh",
"module:seed",
];
args.first()
.is_some_and(|word| ASK.contains(&word.as_str()))
}
#[cfg(feature = "run")]
fn label(args: &[String]) -> String {
let line = CommandLine {
program: "artisan".into(),
args: args.to_vec(),
};
let shown = line.display();
shown
.strip_prefix("artisan")
.unwrap_or(&shown)
.trim_start()
.to_string()
}
#[cfg(feature = "run")]
pub(crate) fn not_started(error: std::io::Error, program: &str) -> Failure {
if error.kind() == std::io::ErrorKind::NotFound {
Failure::NotFound {
program: program.to_owned(),
}
} else {
Failure::NotStarted {
program: program.to_owned(),
message: error.to_string(),
}
}
}
#[cfg(feature = "run")]
struct Owner {
process: Process,
started: Instant,
limit: Duration,
stop: Arc<AtomicBool>,
events: Sender<RunEvent>,
runs: Runs,
app: PathBuf,
}
#[cfg(feature = "run")]
impl Owner {
fn run(self) {
let Owner {
mut process,
started,
limit,
stop,
events,
runs,
app,
} = self;
let mut sent = 0;
let mut cut = false;
let mut forward = |stream, text: String, line_cut| {
if cut {
return;
}
sent += text.len() + 1;
if sent > OUTPUT_LIMIT {
cut = true;
let _ = events.send(RunEvent::Cut);
} else {
let _ = events.send(RunEvent::Line {
stream,
text,
cut: line_cut,
});
}
};
let mut ended = false;
let stopped = loop {
match process.exited() {
Ok(true) => break None,
Ok(false) => {}
Err(_) => {
process.stop(&mut forward);
ended = true;
break None;
}
}
let at_limit = started.elapsed() >= limit;
if at_limit || stop.load(Ordering::Relaxed) {
process.stop(&mut forward);
ended = true;
break Some(at_limit.then_some(limit));
}
process.read(TICK, &mut forward);
};
let elapsed = started.elapsed();
let (status, late) = process.finish(ended, &stop, &mut forward);
let end = match stopped {
Some(limit) => RunEnd::Stopped { elapsed, limit },
None if late => RunEnd::Stopped {
elapsed: started.elapsed(),
limit: None,
},
None => RunEnd::Exited {
code: status.and_then(|status| status.code()),
elapsed,
},
};
runs.lock().remove(&app);
let _ = events.send(RunEvent::Ended(end));
}
}
#[cfg(feature = "run")]
const QUEUE: usize = 1024;
#[cfg(feature = "run")]
struct Process {
child: Child,
lines: Receiver<(Stream, String, bool)>,
readers: Vec<JoinHandle<()>>,
}
#[cfg(feature = "run")]
impl Process {
fn start(line: &CommandLine, folder: &Path, input: Option<Vec<u8>>) -> std::io::Result<Self> {
let mut command = prepare(line, folder)?;
if input.is_some() {
command.stdin(Stdio::piped());
}
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
command.process_group(0);
}
let mut child = command.spawn()?;
if let (Some(input), Some(mut stdin)) = (input, child.stdin.take()) {
std::thread::spawn(move || {
use std::io::Write;
let _ = stdin.write_all(&input);
});
}
let (sender, lines) = mpsc::sync_channel(QUEUE);
let readers = [
read_lines(child.stdout.take(), Stream::Out, sender.clone()),
read_lines(child.stderr.take(), Stream::Err, sender),
];
Ok(Self {
child,
lines,
readers: readers.into_iter().flatten().collect(),
})
}
fn read(&self, wait: Duration, forward: &mut impl FnMut(Stream, String, bool)) -> bool {
match self.lines.recv_timeout(wait) {
Ok((stream, text, cut)) => forward(stream, text, cut),
Err(RecvTimeoutError::Timeout) => return false,
Err(RecvTimeoutError::Disconnected) => {
std::thread::sleep(wait);
return false;
}
}
for (stream, text, cut) in self.lines.try_iter().take(QUEUE) {
forward(stream, text, cut);
}
true
}
#[cfg(unix)]
fn exited(&mut self) -> std::io::Result<bool> {
use rustix::process::{Pid, WaitId, WaitIdOptions, waitid};
let options = WaitIdOptions::EXITED | WaitIdOptions::NOHANG | WaitIdOptions::NOWAIT;
let status = waitid(WaitId::Pid(Pid::from_child(&self.child)), options)?;
Ok(status.is_some())
}
#[cfg(not(unix))]
fn exited(&mut self) -> std::io::Result<bool> {
Ok(self.child.try_wait()?.is_some())
}
fn stop(&mut self, forward: &mut impl FnMut(Stream, String, bool)) {
self.terminate();
let asked = Instant::now();
while !self.exited().unwrap_or(true) {
if asked.elapsed() >= STOP_GRACE {
self.kill();
return;
}
self.read(TICK, forward);
}
}
#[cfg(unix)]
fn terminate(&mut self) {
self.signal(rustix::process::Signal::TERM);
}
#[cfg(unix)]
fn kill(&mut self) {
self.signal(rustix::process::Signal::KILL);
}
#[cfg(unix)]
fn signal(&mut self, signal: rustix::process::Signal) {
use rustix::process::{Pid, kill_process_group};
match kill_process_group(Pid::from_child(&self.child), signal) {
Ok(()) | Err(rustix::io::Errno::SRCH) => {}
Err(_) => {
let _ = self.child.kill();
}
}
}
#[cfg(not(unix))]
fn terminate(&mut self) {
let pid = self.child.id().to_string();
let ended = command("taskkill")
.args(["/PID", pid.as_str(), "/T", "/F"])
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.is_ok_and(|status| status.success());
if !ended {
let _ = self.child.kill();
}
}
#[cfg(not(unix))]
fn kill(&mut self) {
let _ = self.child.kill();
}
fn finish(
&mut self,
stopped: bool,
stop: &AtomicBool,
forward: &mut impl FnMut(Stream, String, bool),
) -> (Option<ExitStatus>, bool) {
let stopping = || stop.load(Ordering::Relaxed);
let mut done = self.wait_for_readers(GRACE, (!stopped).then_some(stop), forward);
let mut late = !stopped && stopping();
let status = if late {
let (status, rest_done) = self.stop_the_rest(done, forward);
done = rest_done;
status
} else {
#[cfg(unix)]
self.kill();
self.child.wait().ok()
};
if !done {
let watch = !stopped && !late;
done = self.wait_for_readers(DETACH, watch.then_some(stop), forward);
late |= watch && !done && stopping();
}
for reader in std::mem::take(&mut self.readers) {
if reader.is_finished() {
let _ = reader.join();
}
}
for (stream, text, cut) in self.lines.try_iter().take(QUEUE) {
forward(stream, text, cut);
}
(status, late)
}
fn stop_the_rest(
&mut self,
done: bool,
forward: &mut impl FnMut(Stream, String, bool),
) -> (Option<ExitStatus>, bool) {
self.terminate();
#[cfg(unix)]
{
use rustix::process::{Pid, test_kill_process_group};
let asked = Instant::now();
let status = self.child.wait().ok();
let group = Pid::from_child(&self.child);
while test_kill_process_group(group).is_ok() {
if asked.elapsed() >= STOP_GRACE {
self.kill();
break;
}
self.read(TICK, forward);
}
let finished = self.readers.iter().all(JoinHandle::is_finished);
(status, done || finished)
}
#[cfg(not(unix))]
{
let done = done || self.wait_for_readers(STOP_GRACE, None, forward);
self.kill();
(self.child.wait().ok(), done)
}
}
fn wait_for_readers(
&self,
wait: Duration,
stop: Option<&AtomicBool>,
forward: &mut impl FnMut(Stream, String, bool),
) -> bool {
let last = Instant::now() + DRAIN;
let mut until = Instant::now() + wait;
loop {
if self.readers.iter().all(JoinHandle::is_finished) {
return true;
}
if stop.is_some_and(|stop| stop.load(Ordering::Relaxed)) {
return false;
}
let left = until.saturating_duration_since(Instant::now());
if left.is_zero() {
return false;
}
if self.read(left.min(TICK), forward) && stop.is_some() {
until = (Instant::now() + wait).min(last);
}
}
}
}
#[cfg(feature = "run")]
#[derive(Debug, Default)]
pub(crate) struct Captured {
pub code: Option<i32>,
pub stdout: Vec<String>,
pub stderr: Vec<String>,
pub timed_out: bool,
}
#[cfg(feature = "run")]
pub(crate) fn capture(
line: &CommandLine,
folder: &Path,
limit: Duration,
) -> std::io::Result<Captured> {
let mut process = Process::start(line, folder, None)?;
let started = Instant::now();
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let mut kept = [0, 0];
let mut keep = |stream, text: String, _cut| {
let (kept, lines) = match stream {
Stream::Out => (&mut kept[0], &mut stdout),
Stream::Err => (&mut kept[1], &mut stderr),
};
if *kept + text.len() > KEEP {
*kept = KEEP + 1;
} else {
*kept += text.len() + 1;
lines.push(text);
}
};
let mut timed_out = false;
while !process.exited()? {
if started.elapsed() >= limit {
process.stop(&mut keep);
timed_out = true;
break;
}
process.read(TICK, &mut keep);
}
let (status, _) = process.finish(timed_out, &AtomicBool::new(false), &mut keep);
Ok(Captured {
code: status
.and_then(|status| status.code())
.filter(|_| !timed_out),
stdout,
stderr,
timed_out,
})
}
#[cfg(feature = "run")]
fn prepare(line: &CommandLine, folder: &Path) -> std::io::Result<Command> {
let program = program_path(&line.program, folder);
if cfg!(windows) {
refuse_batch_with_percent(&program)?;
}
let mut command = command(program);
command
.args(&line.args)
.current_dir(folder)
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let home = directories::BaseDirs::new().map(|dirs| dirs.home_dir().to_path_buf());
if let Some(path) = child_path(std::env::var_os("PATH"), home.as_deref()) {
command.env("PATH", path);
}
Ok(command)
}
#[cfg(feature = "run")]
fn refuse_batch_with_percent(program: &Path) -> std::io::Result<()> {
let name = program.to_string_lossy();
let name = name.trim_end_matches(['.', ' ']).to_ascii_lowercase();
if (name.ends_with(".bat") || name.ends_with(".cmd")) && name.contains('%') {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"the path of the batch file holds %, which cmd.exe would expand",
));
}
Ok(())
}
#[cfg(feature = "run")]
fn program_path(program: &str, folder: &Path) -> PathBuf {
let separators: &[char] = if cfg!(windows) { &['/', '\\'] } else { &['/'] };
if program.contains(separators) {
folder.join(program)
} else {
PathBuf::from(program)
}
}
#[cfg(feature = "run")]
fn child_path(path: Option<OsString>, home: Option<&Path>) -> Option<OsString> {
let mut folders: Vec<PathBuf> = path.iter().flat_map(std::env::split_paths).collect();
folders.extend(extra_folders(home));
std::env::join_paths(folders).ok()
}
#[cfg(feature = "run")]
fn extra_folders(home: Option<&Path>) -> Vec<PathBuf> {
let at_home = |folder: &str| home.map(|home| home.join(folder));
let folders = if cfg!(target_os = "macos") {
vec![
at_home("Library/Application Support/Herd/bin"),
Some("/opt/homebrew/bin".into()),
Some("/usr/local/bin".into()),
at_home(".docker/bin"),
]
} else if cfg!(windows) {
vec![at_home(r".config\herd\bin")]
} else {
vec![Some("/usr/local/bin".into()), at_home(".local/bin")]
};
folders.into_iter().flatten().collect()
}
#[cfg(feature = "run")]
fn read_lines(
pipe: Option<impl Read + Send + 'static>,
stream: Stream,
sender: SyncSender<(Stream, String, bool)>,
) -> Option<JoinHandle<()>> {
let pipe = pipe?;
Some(std::thread::spawn(move || {
let mut reader = BufReader::new(pipe);
let mut bytes = Vec::new();
loop {
bytes.clear();
match reader
.by_ref()
.take(KEEP as u64)
.read_until(b'\n', &mut bytes)
{
Ok(0) | Err(_) => return,
Ok(_) => {}
}
let mut cut = false;
if bytes.last() == Some(&b'\n') {
bytes.pop();
} else if bytes.len() == KEEP {
cut = skip_line(&mut reader).unwrap_or(true);
}
if bytes.last() == Some(&b'\r') {
bytes.pop();
}
let text = String::from_utf8_lossy(&bytes).into_owned();
if sender.send((stream, text, cut)).is_err() {
return;
}
}
}))
}
#[cfg(feature = "run")]
fn skip_line(reader: &mut impl BufRead) -> std::io::Result<bool> {
let mut dropped = false;
loop {
let buffer = match reader.fill_buf() {
Ok(buffer) => buffer,
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
Err(error) => return Err(error),
};
if buffer.is_empty() {
return Ok(dropped);
}
let end = buffer.iter().position(|byte| *byte == b'\n');
let rest = &buffer[..end.unwrap_or(buffer.len())];
dropped |= rest.iter().any(|byte| *byte != b'\r');
match end {
Some(at) => {
reader.consume(at + 1);
return Ok(dropped);
}
None => {
let read = buffer.len();
reader.consume(read);
}
}
}
}
#[cfg(all(test, feature = "run"))]
mod tests {
use super::*;
#[cfg(unix)]
fn exited_with_its_child(
script: &str,
folder: &Path,
ready: impl Fn(&Process, &[String]) -> bool,
) -> (Process, Vec<String>) {
let line = CommandLine {
program: "/bin/sh".into(),
args: vec!["-c".into(), script.into()],
};
let mut process = Process::start(&line, folder, None).unwrap();
let mut lines = Vec::new();
let deadline = Instant::now() + Duration::from_secs(10);
while !(process.exited().unwrap() && ready(&process, &lines)) {
assert!(Instant::now() < deadline, "{lines:?}");
process.read(TICK, &mut |_, text, _| lines.push(text));
}
(process, lines)
}
#[cfg(unix)]
#[test]
fn a_stop_pending_when_the_readers_drain_asks_the_rest_to_end() {
let folder =
std::env::temp_dir().join(format!("mortise-pending-stop-{}", std::process::id()));
std::fs::create_dir_all(&folder).unwrap();
let pending = AtomicBool::new(true);
let (mut process, mut lines) = exited_with_its_child(
r#"(trap 'echo term; exit 0' TERM; while :; do echo tick; sleep 0.05; done) &"#,
&folder,
|_, lines| lines.iter().any(|line| line == "tick"),
);
let (_, late) = process.finish(false, &pending, &mut |_, text, _| lines.push(text));
assert!(late);
assert!(lines.iter().any(|line| line == "term"), "{lines:?}");
let (mut process, _) = exited_with_its_child(
r#"(trap 'touch term; exit 0' TERM; exec >&- 2>&-; touch ready; while :; do sleep 0.05; done) &"#,
&folder,
|process, _| {
folder.join("ready").exists() && process.readers.iter().all(JoinHandle::is_finished)
},
);
let asked = Instant::now();
let (_, late) = process.finish(false, &pending, &mut |_, _, _| {});
assert!(late);
assert!(asked.elapsed() < STOP_GRACE, "{:?}", asked.elapsed());
assert!(folder.join("term").exists());
let _ = std::fs::remove_dir_all(&folder);
}
#[test]
fn a_stop_of_a_migration_or_a_seed_asks_first() {
let words = |words: &[&str]| {
words
.iter()
.map(|word| word.to_string())
.collect::<Vec<_>>()
};
assert!(stop_asks_first(&words(&["module:migrate", "Blog"])));
assert!(stop_asks_first(&words(&["module:migrate-fresh"])));
assert!(stop_asks_first(&words(&["module:seed", "Blog"])));
assert!(!stop_asks_first(&words(&["module:make", "module:migrate"])));
assert!(!stop_asks_first(&words(&["migrate"])));
assert!(!stop_asks_first(&[]));
}
#[test]
fn a_program_with_a_separator_starts_in_the_folder() {
let folder = Path::new("/code/shop-api");
assert_eq!(program_path("php", folder), PathBuf::from("php"));
assert_eq!(
program_path("./vendor/bin/sail", folder),
folder.join("./vendor/bin/sail")
);
assert_eq!(
program_path("vendor/bin/sail", folder),
folder.join("vendor/bin/sail")
);
let windows = program_path(r"vendor\bin\sail", folder);
if cfg!(windows) {
assert_eq!(windows, folder.join(r"vendor\bin\sail"));
} else {
assert_eq!(windows, PathBuf::from(r"vendor\bin\sail"));
}
let absolute = std::env::temp_dir().join("php");
let absolute = absolute.to_str().unwrap();
assert_eq!(program_path(absolute, folder), PathBuf::from(absolute));
}
#[test]
fn a_batch_file_with_percent_in_its_path_is_refused() {
for program in [
r"C:\100%\herd.bat",
r"C:\%USERPROFILE%\herd.CMD",
"%a%.Bat. ",
] {
let error = refuse_batch_with_percent(Path::new(program)).unwrap_err();
assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput, "{program}");
}
let refusal = std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"batch file arguments are invalid",
);
assert_eq!(
not_started(refusal, "herd.bat"),
Failure::NotStarted {
program: "herd.bat".to_owned(),
message: "batch file arguments are invalid".to_owned(),
}
);
for program in [r"C:\100%\php.exe", r"C:\herd\herd.bat", "herd.bat"] {
assert!(
refuse_batch_with_percent(Path::new(program)).is_ok(),
"{program}"
);
}
}
#[test]
fn the_path_of_mortise_comes_first() {
let home = Path::new("/home/ada");
let path = std::env::join_paths(["/usr/bin", "/bin"]).unwrap();
let joined = child_path(Some(path), Some(home)).unwrap();
let folders: Vec<PathBuf> = std::env::split_paths(&joined).collect();
assert_eq!(
folders[..2],
[PathBuf::from("/usr/bin"), PathBuf::from("/bin")]
);
assert_eq!(folders[2..], extra_folders(Some(home)));
assert!(folders.iter().any(|folder| folder.starts_with(home)));
}
}