use std::{
collections::BTreeMap, ffi::OsString, future::Future, io, path::PathBuf, process::Stdio,
time::Duration,
};
use artifactize_foundation::platform::process::{ResolvedCommand as NativeCommand, resolve_with};
use thiserror::Error;
use tokio::{
io::AsyncWriteExt,
time::{Instant, sleep_until},
};
use tokio_util::sync::CancellationToken;
use crate::{
platform::{self, Child},
tools::human::log::{End, Lines, Run, Stream},
};
pub(crate) const OUTPUT_LIMIT: usize = 128 * 1024;
pub use artifactize_foundation::platform::process::{ChildIdentity, ProcessId};
pub(crate) use artifactize_foundation::platform::process::{child_identity, is_alive, terminate};
mod capture;
pub use capture::{CaptureError, StreamFailure};
#[cfg(test)]
pub(crate) use capture::{OUTPUT_CLOSE_GRACE, slow_disk};
#[derive(Debug, Clone)]
pub struct Command {
pub program: OsString,
pub args: Vec<OsString>,
pub cwd: PathBuf,
pub env: BTreeMap<OsString, OsString>,
pub timeout: Duration,
}
#[derive(Debug)]
pub struct Output {
pub status: platform::ProcessOutcome,
pub stdout: Vec<u8>,
pub stderr: Vec<u8>,
pub truncated: bool,
pub stdout_tail: Vec<u8>,
pub stderr_tail: Vec<u8>,
pub duration: Duration,
}
const REASON_CHARS: usize = 2000;
impl Output {
pub(crate) fn reason(&self, exit_code: i32) -> String {
[&self.stderr_tail, &self.stdout_tail]
.into_iter()
.map(|tail| platform::output_text(tail))
.find(|text| !text.trim().is_empty())
.map_or_else(
|| crate::store::exited_with(exit_code),
|text| crate::store::output_tail(&text, REASON_CHARS),
)
}
}
pub(crate) fn tool_output<'a>(
program: &str,
args: impl IntoIterator<Item = &'a std::ffi::OsStr>,
) -> Option<Vec<u8>> {
platform::program::tool_output(program, args)
}
pub(crate) struct Launcher {
pub env: BTreeMap<OsString, OsString>,
}
impl artifactize_tools::launch::Launcher for Launcher {
fn run<'a>(
&'a self,
launch: artifactize_tools::launch::Launch,
cancellation: &'a CancellationToken,
) -> artifactize_tools::launch::Running<'a> {
use artifactize_tools::launch::{Finished, LaunchError};
Box::pin(async move {
let command = Command {
program: launch.program.into(),
args: launch.args,
cwd: launch.cwd,
env: self.env.clone(),
timeout: launch.timeout,
};
match run_unregistered(command, None, launch.output_limit, cancellation.clone()).await {
Ok(output) => Ok(Finished {
status: output.status,
stdout: output.stdout,
stderr: output.stderr,
truncated: output.truncated,
}),
Err(Error::Timeout) => Err(LaunchError::TimedOut),
Err(Error::Cancelled) => Err(LaunchError::Cancelled),
Err(error) => Err(LaunchError::Failed(
error
.argument_refusal()
.unwrap_or_else(|| error.to_string()),
)),
}
})
}
}
#[derive(Debug, Error)]
pub enum Error {
#[error("process could not be spawned: {0}")]
Spawn(#[source] io::Error),
#[error("child registration failed: {0}")]
Registration(#[source] io::Error),
#[error("process supervision failed: {0}")]
Io(#[from] io::Error),
#[error("process cleanup could not be confirmed: {0}")]
Cleanup(#[source] io::Error),
#[error("process supervision task failed: {0}")]
Task(#[from] tokio::task::JoinError),
#[error("process timeout is too large to represent as a deadline")]
InvalidTimeout,
#[error("process timed out")]
Timeout,
#[error("process was cancelled")]
Cancelled,
#[error(transparent)]
Capture(Box<CaptureError>),
}
impl Error {
pub(crate) fn cleanup_confirmed(&self) -> bool {
match self {
Self::Cleanup(_) | Self::Task(_) => false,
Self::Spawn(_)
| Self::Registration(_)
| Self::Io(_)
| Self::InvalidTimeout
| Self::Timeout
| Self::Cancelled
| Self::Capture(_) => true,
}
}
pub(crate) fn argument_refusal(&self) -> Option<String> {
match self {
Self::Spawn(error) if error.kind() == io::ErrorKind::InvalidInput => Some(format!(
"Process arguments could not be passed safely: {error}"
)),
_ => None,
}
}
}
pub async fn run<F, R>(
command: Command,
cancellation: CancellationToken,
register: F,
) -> Result<Output, Error>
where
F: FnOnce(ChildIdentity) -> R + Send + 'static,
R: Future<Output = io::Result<()>> + Send + 'static,
{
run_with_input(command, None, cancellation, register).await
}
pub(crate) async fn run_with_input<F, R>(
command: Command,
input: Option<Vec<u8>>,
cancellation: CancellationToken,
register: F,
) -> Result<Output, Error>
where
F: FnOnce(ChildIdentity) -> R + Send + 'static,
R: Future<Output = io::Result<()>> + Send + 'static,
{
run_with_input_limit(command, input, OUTPUT_LIMIT, cancellation, register).await
}
pub(crate) async fn run_with_input_limit<F, R>(
command: Command,
input: Option<Vec<u8>>,
output_limit: usize,
cancellation: CancellationToken,
register: F,
) -> Result<Output, Error>
where
F: FnOnce(ChildIdentity) -> R + Send + 'static,
R: Future<Output = io::Result<()>> + Send + 'static,
{
let cancellation = cancellation.child_token();
let _cancel_on_drop = cancellation.clone().drop_guard();
crate::task::joined(
tokio::spawn(run_inner(
command,
input,
output_limit,
Capture::default(),
cancellation,
Some(register),
SpawnOn::Caller,
))
.await,
)?
}
pub(crate) type Unregistered = fn(ChildIdentity) -> std::future::Ready<io::Result<()>>;
pub(crate) async fn run_unregistered(
command: Command,
input: Option<Vec<u8>>,
output_limit: usize,
cancellation: CancellationToken,
) -> Result<Output, Error> {
run_unregistered_on(command, input, output_limit, cancellation, SpawnOn::Caller).await
}
pub(crate) async fn run_fingerprint(
command: Command,
input: Vec<u8>,
cancellation: CancellationToken,
) -> Result<Output, Error> {
run_unregistered_on(
command,
Some(input),
OUTPUT_LIMIT,
cancellation,
SpawnOn::Worker,
)
.await
}
#[derive(Clone, Copy)]
enum SpawnOn {
Caller,
Worker,
}
async fn run_unregistered_on(
command: Command,
input: Option<Vec<u8>>,
output_limit: usize,
cancellation: CancellationToken,
spawn_on: SpawnOn,
) -> Result<Output, Error> {
let cancellation = cancellation.child_token();
let _cancel_on_drop = cancellation.clone().drop_guard();
crate::task::joined(
tokio::spawn(run_inner(
command,
input,
output_limit,
Capture::default(),
cancellation,
None::<Unregistered>,
spawn_on,
))
.await,
)?
}
#[derive(Default)]
struct Capture {
logs: Option<PathBuf>,
lines: Option<(Lines, Lines)>,
}
pub(crate) async fn run_watched(
command: Command,
cancellation: CancellationToken,
run: &Run,
) -> Result<Output, Error> {
let cancellation = cancellation.child_token();
let _cancel_on_drop = cancellation.clone().drop_guard();
let capture = Capture {
logs: None,
lines: Some((run.lines(Stream::Stdout), run.lines(Stream::Stderr))),
};
crate::task::joined(
tokio::spawn(run_inner(
command,
None,
OUTPUT_LIMIT,
capture,
cancellation,
None::<Unregistered>,
SpawnOn::Caller,
))
.await,
)?
}
async fn run_inner<F, R>(
command: Command,
input: Option<Vec<u8>>,
output_limit: usize,
Capture { logs, lines }: Capture,
cancellation: CancellationToken,
register: Option<F>,
spawn_on: SpawnOn,
) -> Result<Output, Error>
where
F: FnOnce(ChildIdentity) -> R,
R: Future<Output = io::Result<()>>,
{
let started = Instant::now();
let deadline = started
.checked_add(command.timeout)
.ok_or(Error::InvalidTimeout)?;
if cancellation.is_cancelled() {
return Err(Error::Cancelled);
}
if command.timeout.is_zero() {
return Err(Error::Timeout);
}
let mut child = spawn_child(
&command,
input.is_some(),
cancellation.clone(),
deadline,
register,
spawn_on,
)
.await?;
let stdout = child.stdout().take().expect("stdout is piped");
let stderr = child.stderr().take().expect("stderr is piped");
let stdin = child.stdin().take();
let gone = CancellationToken::new();
let feed = async {
if let (Some(mut stdin), Some(input)) = (stdin, input) {
tokio::select! {
_ = gone.cancelled() => {},
_ = cancellation.cancelled() => {},
_ = sleep_until(deadline) => {},
result = stdin.write_all(&input) => {
if let Err(error) = result && error.kind() != io::ErrorKind::BrokenPipe {
return Err(Error::Io(error));
}
}
}
}
Ok(())
};
let wait = async {
let result = tokio::select! {
biased;
_ = cancellation.cancelled() => Err(Error::Cancelled),
_ = sleep_until(deadline) => Err(Error::Timeout),
status = child.wait() => status.map_err(Error::Io),
};
let cleanup = if result.is_err() {
terminate(&mut child).await
} else {
child.cleanup().await.map(|_| ())
};
gone.cancel();
cleanup.map_err(Error::Cleanup)?;
result
};
let (stdout_lines, stderr_lines) = lines.unzip();
let evidence = |name| logs.as_ref().map(|directory| directory.join(name));
let streams = async {
tokio::join!(
capture::capture(
stdout,
output_limit,
evidence("runtime.stdout"),
stdout_lines,
&gone
),
capture::capture(
stderr,
output_limit,
evidence("runtime.stderr"),
stderr_lines,
&gone
)
)
};
let (status, (stdout, stderr), input) = tokio::join!(wait, streams, feed);
let status = status?;
input?;
capture::finish(status, stdout, stderr, started.elapsed())
}
pub(crate) async fn spawn_owned<F, R>(
command: &Command,
input: bool,
cancellation: CancellationToken,
deadline: Instant,
register: Option<F>,
) -> Result<Child, Error>
where
F: FnOnce(ChildIdentity) -> R,
R: Future<Output = io::Result<()>>,
{
spawn_child(
command,
input,
cancellation,
deadline,
register,
SpawnOn::Caller,
)
.await
}
async fn spawn_child<F, R>(
command: &Command,
input: bool,
cancellation: CancellationToken,
deadline: Instant,
register: Option<F>,
spawn_on: SpawnOn,
) -> Result<Child, Error>
where
F: FnOnce(ChildIdentity) -> R,
R: Future<Output = io::Result<()>>,
{
let mut child = child_command(command)?;
child
.stdin(if input { Stdio::piped() } else { Stdio::null() })
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
let Some(register) = register else {
let spawn = artifactize_foundation::platform::process::spawn_in_owner_session(child);
return match spawn_on {
SpawnOn::Caller => spawn.await,
SpawnOn::Worker => {
let runtime = tokio::runtime::Handle::current();
crate::task::joined(
tokio::task::spawn_blocking(move || runtime.block_on(spawn)).await,
)?
}
}
.map_err(Error::Spawn);
};
let (gate, mut spawning) = platform::spawn_gated(child).map_err(Error::Spawn)?;
let admission = tokio::select! {
biased;
_ = cancellation.cancelled() => Err(Error::Cancelled),
_ = sleep_until(deadline) => Err(Error::Timeout),
result = async {
let gate = gate.identify().await?;
let child = child_identity(gate.pid()).map_err(Error::Registration)?;
register(child).await.map_err(Error::Registration)?;
Ok::<_, Error>(gate)
} => result,
};
let admission = admission.and_then(|gate| {
if cancellation.is_cancelled() {
Err(Error::Cancelled)
} else if Instant::now() >= deadline {
Err(Error::Timeout)
} else {
gate.admit().map_err(Error::Io)
}
});
let spawned = crate::task::joined((&mut spawning).await)?;
let mut child = match spawned {
Ok(child) => child,
Err(error) => {
return Err(match admission {
Err(error @ (Error::Registration(_) | Error::Cancelled | Error::Timeout)) => error,
_ => Error::Spawn(error),
});
}
};
if let Err(error) = admission {
terminate(&mut child).await.map_err(Error::Cleanup)?;
return Err(error);
}
Ok(child)
}
fn child_command(command: &Command) -> Result<NativeCommand, Error> {
let environment = platform::environment::for_child(&command.env);
let program = resolve_with(
std::path::Path::new(&command.program),
&command.cwd,
|name| platform::environment::lookup(&environment, name).map(ToOwned::to_owned),
)
.map_err(Error::Spawn)?;
let mut child = program.command(&command.args).map_err(Error::Spawn)?;
child
.current_dir(&command.cwd)
.env_clear()
.envs(environment.iter());
Ok(child)
}
fn launch_detached(
program: &std::ffi::OsStr,
args: &[impl AsRef<std::ffi::OsStr>],
cwd: &std::path::Path,
run: &mut Run,
) -> Result<(), Error> {
let program = resolve_with(
std::path::Path::new(program),
cwd,
platform::environment::var,
)
.map_err(Error::Spawn)?;
let mut command = program.command(args).map_err(Error::Spawn)?;
command
.current_dir(cwd)
.env_clear()
.envs(platform::environment::snapshot())
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.kill_on_drop(false);
let child = platform::spawn_detached(command).map_err(Error::Spawn)?;
run.launched(child.pid());
child.reap();
Ok(())
}
pub(crate) fn launch_watched(
program: &std::ffi::OsStr,
args: &[impl AsRef<std::ffi::OsStr>],
cwd: &std::path::Path,
mut run: Run,
) -> Result<(), (Error, Run)> {
if !run.watched() {
return match launch_detached(program, args, cwd, &mut run) {
Ok(()) => {
run.end(End::Launched);
Ok(())
}
Err(error) => Err((error, run)),
};
}
let program = match resolve_with(
std::path::Path::new(program),
cwd,
platform::environment::var,
) {
Ok(program) => program,
Err(error) => return Err((Error::Spawn(error), run)),
};
let mut command = match program.command(args) {
Ok(command) => command,
Err(error) => return Err((Error::Spawn(error), run)),
};
command
.current_dir(cwd)
.env_clear()
.envs(platform::environment::snapshot())
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(false);
let mut child = match platform::spawn_watched(command) {
Ok(child) => child,
Err(error) => return Err((Error::Spawn(error), run)),
};
run.launched(child.pid());
let (stdout, stderr) = child.take_output();
tokio::spawn(async move {
let held = CancellationToken::new();
let (status, _, _) = tokio::join!(
child.wait(),
capture::capture(stdout, 0, None, Some(run.lines(Stream::Stdout)), &held),
capture::capture(stderr, 0, None, Some(run.lines(Stream::Stderr)), &held),
);
run.end(match status {
Ok(status) => End::exited(&status),
Err(error) => End::Failed(error.to_string()),
});
});
Ok(())
}
pub(crate) fn artifactize_executable() -> Result<std::path::PathBuf, String> {
platform::program::resolve_near_current("artifactize".as_ref()).map_err(|e| e.to_string())
}
fn worker_stderr(directory: &std::path::Path) -> std::path::PathBuf {
directory.join("worker.stderr")
}
pub(crate) fn run_worker_diagnostics(state: &std::path::Path, id: &crate::types::RunId) -> String {
use std::io::Read;
const DIAGNOSTIC_BYTES: u64 = 64 * 1024;
let mut bytes = Vec::new();
if let Ok(log) = platform::open_regular(&worker_stderr(&state.join("runs").join(id.as_str()))) {
let _ = log.take(DIAGNOSTIC_BYTES).read_to_end(&mut bytes);
}
platform::output_lines(&bytes)
}
#[derive(Clone, Copy)]
pub(crate) enum RunEntry {
Supervisor,
Executor,
}
pub(crate) fn spawn_run(
program: &std::path::Path,
id: &crate::types::RunId,
repo: &std::path::Path,
state: &std::path::Path,
entry: RunEntry,
) -> Result<(ChildIdentity, platform::DetachedChild), Error> {
let mut options = platform::private_options();
options.write(true);
match entry {
RunEntry::Supervisor => {
options.create_new(true);
}
RunEntry::Executor => {
options.append(true);
}
}
let directory = state.join("runs").join(id.as_str());
let stderr = options
.open(worker_stderr(&directory))
.map_err(Error::Spawn)?;
let program = resolve_with(program, repo, platform::environment::var).map_err(Error::Spawn)?;
let args = [
std::ffi::OsStr::new("--repo"),
repo.as_os_str(),
std::ffi::OsStr::new("--state-dir"),
state.as_os_str(),
std::ffi::OsStr::new(match entry {
RunEntry::Supervisor => "__verify",
RunEntry::Executor => "__execute",
}),
std::ffi::OsStr::new(id.as_str()),
];
let mut command = program.command(args).map_err(Error::Spawn)?;
command
.current_dir(directory)
.env_clear()
.envs(platform::environment::snapshot())
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::from(stderr))
.kill_on_drop(false);
let child = platform::spawn_run(command).map_err(Error::Spawn)?;
let identity = child_identity(child.pid()).map_err(Error::Registration)?;
Ok((identity, child))
}
pub(crate) fn launch_run(
program: &std::path::Path,
id: &crate::types::RunId,
repo: &std::path::Path,
state: &std::path::Path,
) -> Result<ChildIdentity, Error> {
let (identity, child) = spawn_run(program, id, repo, state, RunEntry::Supervisor)?;
child.reap();
Ok(identity)
}
pub(crate) async fn run_logged<F, R>(
command: Command,
directory: PathBuf,
cancellation: CancellationToken,
register: F,
) -> Result<Output, Error>
where
F: FnOnce(ChildIdentity) -> R + Send + 'static,
R: Future<Output = io::Result<()>> + Send + 'static,
{
run_inner(
command,
None,
OUTPUT_LIMIT,
Capture {
logs: Some(directory),
lines: None,
},
cancellation,
Some(register),
SpawnOn::Caller,
)
.await
}