1use std::{
4 collections::BTreeMap, ffi::OsString, future::Future, io, path::PathBuf, process::Stdio,
5 time::Duration,
6};
7
8use artifactize_foundation::platform::process::{ResolvedCommand as NativeCommand, resolve_with};
9use thiserror::Error;
10use tokio::{
11 io::AsyncWriteExt,
12 time::{Instant, sleep_until},
13};
14use tokio_util::sync::CancellationToken;
15
16use crate::{
17 platform::{self, Child},
18 tools::human::log::{End, Lines, Run, Stream},
19};
20
21pub(crate) const OUTPUT_LIMIT: usize = 128 * 1024;
23pub use artifactize_foundation::platform::process::{ChildIdentity, ProcessId};
24pub(crate) use artifactize_foundation::platform::process::{child_identity, is_alive, terminate};
25
26mod capture;
27pub use capture::{CaptureError, StreamFailure};
28#[cfg(test)]
29pub(crate) use capture::{OUTPUT_CLOSE_GRACE, slow_disk};
30
31#[derive(Debug, Clone)]
33pub struct Command {
34 pub program: OsString,
35 pub args: Vec<OsString>,
36 pub cwd: PathBuf,
37 pub env: BTreeMap<OsString, OsString>,
39 pub timeout: Duration,
40}
41
42#[derive(Debug)]
43pub struct Output {
44 pub status: platform::ProcessOutcome,
45 pub stdout: Vec<u8>,
46 pub stderr: Vec<u8>,
47 pub truncated: bool,
48 pub stdout_tail: Vec<u8>,
50 pub stderr_tail: Vec<u8>,
51 pub duration: Duration,
52}
53
54const REASON_CHARS: usize = 2000;
56
57impl Output {
58 pub(crate) fn reason(&self, exit_code: i32) -> String {
61 [&self.stderr_tail, &self.stdout_tail]
62 .into_iter()
63 .map(|tail| platform::output_text(tail))
64 .find(|text| !text.trim().is_empty())
65 .map_or_else(
66 || crate::store::exited_with(exit_code),
67 |text| crate::store::output_tail(&text, REASON_CHARS),
68 )
69 }
70}
71
72pub(crate) fn tool_output<'a>(
76 program: &str,
77 args: impl IntoIterator<Item = &'a std::ffi::OsStr>,
78) -> Option<Vec<u8>> {
79 platform::program::tool_output(program, args)
80}
81
82pub(crate) struct Launcher {
86 pub env: BTreeMap<OsString, OsString>,
87}
88
89impl artifactize_tools::launch::Launcher for Launcher {
90 fn run<'a>(
91 &'a self,
92 launch: artifactize_tools::launch::Launch,
93 cancellation: &'a CancellationToken,
94 ) -> artifactize_tools::launch::Running<'a> {
95 use artifactize_tools::launch::{Finished, LaunchError};
96 Box::pin(async move {
97 let command = Command {
98 program: launch.program.into(),
99 args: launch.args,
100 cwd: launch.cwd,
101 env: self.env.clone(),
102 timeout: launch.timeout,
103 };
104 match run_unregistered(command, None, launch.output_limit, cancellation.clone()).await {
105 Ok(output) => Ok(Finished {
106 status: output.status,
107 stdout: output.stdout,
108 stderr: output.stderr,
109 truncated: output.truncated,
110 }),
111 Err(Error::Timeout) => Err(LaunchError::TimedOut),
112 Err(Error::Cancelled) => Err(LaunchError::Cancelled),
113 Err(error) => Err(LaunchError::Failed(
114 error
115 .argument_refusal()
116 .unwrap_or_else(|| error.to_string()),
117 )),
118 }
119 })
120 }
121}
122
123#[derive(Debug, Error)]
124pub enum Error {
125 #[error("process could not be spawned: {0}")]
126 Spawn(#[source] io::Error),
127 #[error("child registration failed: {0}")]
128 Registration(#[source] io::Error),
129 #[error("process supervision failed: {0}")]
130 Io(#[from] io::Error),
131 #[error("process cleanup could not be confirmed: {0}")]
132 Cleanup(#[source] io::Error),
133 #[error("process supervision task failed: {0}")]
134 Task(#[from] tokio::task::JoinError),
135 #[error("process timeout is too large to represent as a deadline")]
136 InvalidTimeout,
137 #[error("process timed out")]
138 Timeout,
139 #[error("process was cancelled")]
140 Cancelled,
141 #[error(transparent)]
144 Capture(Box<CaptureError>),
145}
146
147impl Error {
148 pub(crate) fn cleanup_confirmed(&self) -> bool {
151 match self {
152 Self::Cleanup(_) | Self::Task(_) => false,
153 Self::Spawn(_)
154 | Self::Registration(_)
155 | Self::Io(_)
156 | Self::InvalidTimeout
157 | Self::Timeout
158 | Self::Cancelled
159 | Self::Capture(_) => true,
160 }
161 }
162
163 pub(crate) fn argument_refusal(&self) -> Option<String> {
164 match self {
165 Self::Spawn(error) if error.kind() == io::ErrorKind::InvalidInput => Some(format!(
166 "Process arguments could not be passed safely: {error}"
167 )),
168 _ => None,
169 }
170 }
171}
172
173pub async fn run<F, R>(
177 command: Command,
178 cancellation: CancellationToken,
179 register: F,
180) -> Result<Output, Error>
181where
182 F: FnOnce(ChildIdentity) -> R + Send + 'static,
183 R: Future<Output = io::Result<()>> + Send + 'static,
184{
185 run_with_input(command, None, cancellation, register).await
186}
187
188pub(crate) async fn run_with_input<F, R>(
189 command: Command,
190 input: Option<Vec<u8>>,
191 cancellation: CancellationToken,
192 register: F,
193) -> Result<Output, Error>
194where
195 F: FnOnce(ChildIdentity) -> R + Send + 'static,
196 R: Future<Output = io::Result<()>> + Send + 'static,
197{
198 run_with_input_limit(command, input, OUTPUT_LIMIT, cancellation, register).await
199}
200
201pub(crate) async fn run_with_input_limit<F, R>(
202 command: Command,
203 input: Option<Vec<u8>>,
204 output_limit: usize,
205 cancellation: CancellationToken,
206 register: F,
207) -> Result<Output, Error>
208where
209 F: FnOnce(ChildIdentity) -> R + Send + 'static,
210 R: Future<Output = io::Result<()>> + Send + 'static,
211{
212 let cancellation = cancellation.child_token();
213 let _cancel_on_drop = cancellation.clone().drop_guard();
214 crate::task::joined(
215 tokio::spawn(run_inner(
216 command,
217 input,
218 output_limit,
219 Capture::default(),
220 cancellation,
221 Some(register),
222 ))
223 .await,
224 )?
225}
226
227pub(crate) type Unregistered = fn(ChildIdentity) -> std::future::Ready<io::Result<()>>;
230
231pub(crate) async fn run_unregistered(
234 command: Command,
235 input: Option<Vec<u8>>,
236 output_limit: usize,
237 cancellation: CancellationToken,
238) -> Result<Output, Error> {
239 let cancellation = cancellation.child_token();
240 let _cancel_on_drop = cancellation.clone().drop_guard();
241 crate::task::joined(
242 tokio::spawn(run_inner(
243 command,
244 input,
245 output_limit,
246 Capture::default(),
247 cancellation,
248 None::<Unregistered>,
249 ))
250 .await,
251 )?
252}
253
254#[derive(Default)]
257struct Capture {
258 logs: Option<PathBuf>,
259 lines: Option<(Lines, Lines)>,
260}
261
262pub(crate) async fn run_watched(
265 command: Command,
266 cancellation: CancellationToken,
267 run: &Run,
268) -> Result<Output, Error> {
269 let cancellation = cancellation.child_token();
270 let _cancel_on_drop = cancellation.clone().drop_guard();
271 let capture = Capture {
272 logs: None,
273 lines: Some((run.lines(Stream::Stdout), run.lines(Stream::Stderr))),
274 };
275 crate::task::joined(
276 tokio::spawn(run_inner(
277 command,
278 None,
279 OUTPUT_LIMIT,
280 capture,
281 cancellation,
282 None::<Unregistered>,
283 ))
284 .await,
285 )?
286}
287
288async fn run_inner<F, R>(
289 command: Command,
290 input: Option<Vec<u8>>,
291 output_limit: usize,
292 Capture { logs, lines }: Capture,
293 cancellation: CancellationToken,
294 register: Option<F>,
295) -> Result<Output, Error>
296where
297 F: FnOnce(ChildIdentity) -> R,
298 R: Future<Output = io::Result<()>>,
299{
300 let started = Instant::now();
301 let deadline = started
302 .checked_add(command.timeout)
303 .ok_or(Error::InvalidTimeout)?;
304 if cancellation.is_cancelled() {
305 return Err(Error::Cancelled);
306 }
307 if command.timeout.is_zero() {
308 return Err(Error::Timeout);
309 }
310
311 let mut child = spawn_owned(
312 &command,
313 input.is_some(),
314 cancellation.clone(),
315 deadline,
316 register,
317 )
318 .await?;
319
320 let stdout = child.stdout().take().expect("stdout is piped");
321 let stderr = child.stderr().take().expect("stderr is piped");
322 let stdin = child.stdin().take();
323 let gone = CancellationToken::new();
326 let feed = async {
327 if let (Some(mut stdin), Some(input)) = (stdin, input) {
328 tokio::select! {
329 _ = gone.cancelled() => {},
330 _ = cancellation.cancelled() => {},
331 _ = sleep_until(deadline) => {},
332 result = stdin.write_all(&input) => {
333 if let Err(error) = result && error.kind() != io::ErrorKind::BrokenPipe {
335 return Err(Error::Io(error));
336 }
337 }
338 }
339 }
340 Ok(())
341 };
342 let wait = async {
343 let result = tokio::select! {
344 biased;
345 _ = cancellation.cancelled() => Err(Error::Cancelled),
346 _ = sleep_until(deadline) => Err(Error::Timeout),
347 status = child.wait() => status.map_err(Error::Io),
348 };
349 let cleanup = if result.is_err() {
350 terminate(&mut child).await
351 } else {
352 child.cleanup().await.map(|_| ())
354 };
355 gone.cancel();
356 cleanup.map_err(Error::Cleanup)?;
357 result
358 };
359 let (stdout_lines, stderr_lines) = lines.unzip();
360 let evidence = |name| logs.as_ref().map(|directory| directory.join(name));
361 let streams = async {
362 tokio::join!(
363 capture::capture(
364 stdout,
365 output_limit,
366 evidence("runtime.stdout"),
367 stdout_lines,
368 &gone
369 ),
370 capture::capture(
371 stderr,
372 output_limit,
373 evidence("runtime.stderr"),
374 stderr_lines,
375 &gone
376 )
377 )
378 };
379 let (status, (stdout, stderr), input) = tokio::join!(wait, streams, feed);
380 let status = status?;
381 input?;
382 capture::finish(status, stdout, stderr, started.elapsed())
383}
384
385pub(crate) async fn spawn_owned<F, R>(
390 command: &Command,
391 input: bool,
392 cancellation: CancellationToken,
393 deadline: Instant,
394 register: Option<F>,
395) -> Result<Child, Error>
396where
397 F: FnOnce(ChildIdentity) -> R,
398 R: Future<Output = io::Result<()>>,
399{
400 let mut child = child_command(command)?;
401 child
402 .stdin(if input { Stdio::piped() } else { Stdio::null() })
403 .stdout(Stdio::piped())
404 .stderr(Stdio::piped())
405 .kill_on_drop(true);
406 let Some(register) = register else {
407 return artifactize_foundation::platform::process::spawn_in_owner_session(child)
408 .await
409 .map_err(Error::Spawn);
410 };
411 let (gate, mut spawning) = platform::spawn_gated(child).map_err(Error::Spawn)?;
412 let admission = tokio::select! {
413 biased;
414 _ = cancellation.cancelled() => Err(Error::Cancelled),
415 _ = sleep_until(deadline) => Err(Error::Timeout),
416 result = async {
417 let gate = gate.identify().await?;
418 let child = child_identity(gate.pid()).map_err(Error::Registration)?;
419 register(child).await.map_err(Error::Registration)?;
420 Ok::<_, Error>(gate)
421 } => result,
422 };
423 let admission = admission.and_then(|gate| {
425 if cancellation.is_cancelled() {
426 Err(Error::Cancelled)
427 } else if Instant::now() >= deadline {
428 Err(Error::Timeout)
429 } else {
430 gate.admit().map_err(Error::Io)
431 }
432 });
433 let spawned = crate::task::joined((&mut spawning).await)?;
434 let mut child = match spawned {
435 Ok(child) => child,
436 Err(error) => {
437 return Err(match admission {
438 Err(error @ (Error::Registration(_) | Error::Cancelled | Error::Timeout)) => error,
439 _ => Error::Spawn(error),
440 });
441 }
442 };
443 if let Err(error) = admission {
444 terminate(&mut child).await.map_err(Error::Cleanup)?;
445 return Err(error);
446 }
447
448 Ok(child)
449}
450
451fn child_command(command: &Command) -> Result<NativeCommand, Error> {
452 let environment = platform::environment::for_child(&command.env);
453 let program = resolve_with(
454 std::path::Path::new(&command.program),
455 &command.cwd,
456 |name| platform::environment::lookup(&environment, name).map(ToOwned::to_owned),
457 )
458 .map_err(Error::Spawn)?;
459 let mut child = program.command(&command.args).map_err(Error::Spawn)?;
460 child
461 .current_dir(&command.cwd)
462 .env_clear()
463 .envs(environment.iter());
464 Ok(child)
465}
466
467fn launch_detached(
469 program: &std::ffi::OsStr,
470 args: &[impl AsRef<std::ffi::OsStr>],
471 cwd: &std::path::Path,
472 run: &mut Run,
473) -> Result<(), Error> {
474 let program = resolve_with(
475 std::path::Path::new(program),
476 cwd,
477 platform::environment::var,
478 )
479 .map_err(Error::Spawn)?;
480 let mut command = program.command(args).map_err(Error::Spawn)?;
481 command
482 .current_dir(cwd)
483 .env_clear()
484 .envs(platform::environment::snapshot())
485 .stdin(Stdio::null())
486 .stdout(Stdio::null())
487 .stderr(Stdio::null())
488 .kill_on_drop(false);
489 let child = platform::spawn_detached(command).map_err(Error::Spawn)?;
490 run.launched(child.pid());
491 child.reap();
492 Ok(())
493}
494
495pub(crate) fn launch_watched(
500 program: &std::ffi::OsStr,
501 args: &[impl AsRef<std::ffi::OsStr>],
502 cwd: &std::path::Path,
503 mut run: Run,
504) -> Result<(), (Error, Run)> {
505 if !run.watched() {
506 return match launch_detached(program, args, cwd, &mut run) {
507 Ok(()) => {
508 run.end(End::Launched);
509 Ok(())
510 }
511 Err(error) => Err((error, run)),
512 };
513 }
514 let program = match resolve_with(
515 std::path::Path::new(program),
516 cwd,
517 platform::environment::var,
518 ) {
519 Ok(program) => program,
520 Err(error) => return Err((Error::Spawn(error), run)),
521 };
522 let mut command = match program.command(args) {
523 Ok(command) => command,
524 Err(error) => return Err((Error::Spawn(error), run)),
525 };
526 command
527 .current_dir(cwd)
528 .env_clear()
529 .envs(platform::environment::snapshot())
530 .stdin(Stdio::null())
531 .stdout(Stdio::piped())
532 .stderr(Stdio::piped())
533 .kill_on_drop(false);
534 let mut child = match platform::spawn_watched(command) {
535 Ok(child) => child,
536 Err(error) => return Err((Error::Spawn(error), run)),
537 };
538 run.launched(child.pid());
539 let (stdout, stderr) = child.take_output();
540 tokio::spawn(async move {
541 let held = CancellationToken::new();
544 let (status, _, _) = tokio::join!(
545 child.wait(),
546 capture::capture(stdout, 0, None, Some(run.lines(Stream::Stdout)), &held),
547 capture::capture(stderr, 0, None, Some(run.lines(Stream::Stderr)), &held),
548 );
549 run.end(match status {
550 Ok(status) => End::exited(&status),
551 Err(error) => End::Failed(error.to_string()),
552 });
553 });
554 Ok(())
555}
556
557pub(crate) fn artifactize_executable() -> Result<std::path::PathBuf, String> {
559 platform::program::resolve_near_current("artifactize".as_ref()).map_err(|e| e.to_string())
560}
561
562fn worker_stderr(directory: &std::path::Path) -> std::path::PathBuf {
564 directory.join("worker.stderr")
565}
566
567pub(crate) fn run_worker_diagnostics(state: &std::path::Path, id: &crate::types::RunId) -> String {
568 use std::io::Read;
569 const DIAGNOSTIC_BYTES: u64 = 64 * 1024;
571 let mut bytes = Vec::new();
572 if let Ok(log) = platform::open_regular(&worker_stderr(&state.join("runs").join(id.as_str()))) {
573 let _ = log.take(DIAGNOSTIC_BYTES).read_to_end(&mut bytes);
574 }
575 platform::output_lines(&bytes)
576}
577
578#[derive(Clone, Copy)]
580pub(crate) enum RunEntry {
581 Supervisor,
582 Executor,
583}
584pub(crate) fn spawn_run(
585 program: &std::path::Path,
586 id: &crate::types::RunId,
587 repo: &std::path::Path,
588 state: &std::path::Path,
589 entry: RunEntry,
590) -> Result<(ChildIdentity, platform::DetachedChild), Error> {
591 let mut options = platform::private_options();
592 options.write(true);
593 match entry {
594 RunEntry::Supervisor => {
595 options.create_new(true);
596 }
597 RunEntry::Executor => {
598 options.append(true);
599 }
600 }
601 let directory = state.join("runs").join(id.as_str());
602 let stderr = options
603 .open(worker_stderr(&directory))
604 .map_err(Error::Spawn)?;
605 let program = resolve_with(program, repo, platform::environment::var).map_err(Error::Spawn)?;
606 let args = [
607 std::ffi::OsStr::new("--repo"),
608 repo.as_os_str(),
609 std::ffi::OsStr::new("--state-dir"),
610 state.as_os_str(),
611 std::ffi::OsStr::new(match entry {
612 RunEntry::Supervisor => "__verify",
613 RunEntry::Executor => "__execute",
614 }),
615 std::ffi::OsStr::new(id.as_str()),
616 ];
617 let mut command = program.command(args).map_err(Error::Spawn)?;
618 command
619 .current_dir(directory)
622 .env_clear()
623 .envs(platform::environment::snapshot())
624 .stdin(Stdio::null())
625 .stdout(Stdio::null())
626 .stderr(Stdio::from(stderr))
627 .kill_on_drop(false);
628 let child = platform::spawn_run(command).map_err(Error::Spawn)?;
629 let identity = child_identity(child.pid()).map_err(Error::Registration)?;
630 Ok((identity, child))
631}
632pub(crate) fn launch_run(
633 program: &std::path::Path,
634 id: &crate::types::RunId,
635 repo: &std::path::Path,
636 state: &std::path::Path,
637) -> Result<ChildIdentity, Error> {
638 let (identity, child) = spawn_run(program, id, repo, state, RunEntry::Supervisor)?;
639 child.reap();
640 Ok(identity)
641}
642
643pub(crate) async fn run_logged<F, R>(
647 command: Command,
648 directory: PathBuf,
649 cancellation: CancellationToken,
650 register: F,
651) -> Result<Output, Error>
652where
653 F: FnOnce(ChildIdentity) -> R + Send + 'static,
654 R: Future<Output = io::Result<()>> + Send + 'static,
655{
656 run_inner(
657 command,
658 None,
659 OUTPUT_LIMIT,
660 Capture {
661 logs: Some(directory),
662 lines: None,
663 },
664 cancellation,
665 Some(register),
666 )
667 .await
668}