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 SpawnOn::Caller,
223 ))
224 .await,
225 )?
226}
227
228pub(crate) type Unregistered = fn(ChildIdentity) -> std::future::Ready<io::Result<()>>;
231
232pub(crate) async fn run_unregistered(
235 command: Command,
236 input: Option<Vec<u8>>,
237 output_limit: usize,
238 cancellation: CancellationToken,
239) -> Result<Output, Error> {
240 run_unregistered_on(command, input, output_limit, cancellation, SpawnOn::Caller).await
241}
242
243pub(crate) async fn run_fingerprint(
244 command: Command,
245 input: Vec<u8>,
246 cancellation: CancellationToken,
247) -> Result<Output, Error> {
248 run_unregistered_on(
249 command,
250 Some(input),
251 OUTPUT_LIMIT,
252 cancellation,
253 SpawnOn::Worker,
254 )
255 .await
256}
257
258#[derive(Clone, Copy)]
259enum SpawnOn {
260 Caller,
261 Worker,
262}
263
264async fn run_unregistered_on(
265 command: Command,
266 input: Option<Vec<u8>>,
267 output_limit: usize,
268 cancellation: CancellationToken,
269 spawn_on: SpawnOn,
270) -> Result<Output, Error> {
271 let cancellation = cancellation.child_token();
272 let _cancel_on_drop = cancellation.clone().drop_guard();
273 crate::task::joined(
274 tokio::spawn(run_inner(
275 command,
276 input,
277 output_limit,
278 Capture::default(),
279 cancellation,
280 None::<Unregistered>,
281 spawn_on,
282 ))
283 .await,
284 )?
285}
286
287#[derive(Default)]
290struct Capture {
291 logs: Option<PathBuf>,
292 lines: Option<(Lines, Lines)>,
293}
294
295pub(crate) async fn run_watched(
298 command: Command,
299 cancellation: CancellationToken,
300 run: &Run,
301) -> Result<Output, Error> {
302 let cancellation = cancellation.child_token();
303 let _cancel_on_drop = cancellation.clone().drop_guard();
304 let capture = Capture {
305 logs: None,
306 lines: Some((run.lines(Stream::Stdout), run.lines(Stream::Stderr))),
307 };
308 crate::task::joined(
309 tokio::spawn(run_inner(
310 command,
311 None,
312 OUTPUT_LIMIT,
313 capture,
314 cancellation,
315 None::<Unregistered>,
316 SpawnOn::Caller,
317 ))
318 .await,
319 )?
320}
321
322async fn run_inner<F, R>(
323 command: Command,
324 input: Option<Vec<u8>>,
325 output_limit: usize,
326 Capture { logs, lines }: Capture,
327 cancellation: CancellationToken,
328 register: Option<F>,
329 spawn_on: SpawnOn,
330) -> Result<Output, Error>
331where
332 F: FnOnce(ChildIdentity) -> R,
333 R: Future<Output = io::Result<()>>,
334{
335 let started = Instant::now();
336 let deadline = started
337 .checked_add(command.timeout)
338 .ok_or(Error::InvalidTimeout)?;
339 if cancellation.is_cancelled() {
340 return Err(Error::Cancelled);
341 }
342 if command.timeout.is_zero() {
343 return Err(Error::Timeout);
344 }
345
346 let mut child = spawn_child(
347 &command,
348 input.is_some(),
349 cancellation.clone(),
350 deadline,
351 register,
352 spawn_on,
353 )
354 .await?;
355
356 let stdout = child.stdout().take().expect("stdout is piped");
357 let stderr = child.stderr().take().expect("stderr is piped");
358 let stdin = child.stdin().take();
359 let gone = CancellationToken::new();
362 let feed = async {
363 if let (Some(mut stdin), Some(input)) = (stdin, input) {
364 tokio::select! {
365 _ = gone.cancelled() => {},
366 _ = cancellation.cancelled() => {},
367 _ = sleep_until(deadline) => {},
368 result = stdin.write_all(&input) => {
369 if let Err(error) = result && error.kind() != io::ErrorKind::BrokenPipe {
371 return Err(Error::Io(error));
372 }
373 }
374 }
375 }
376 Ok(())
377 };
378 let wait = async {
379 let result = tokio::select! {
380 biased;
381 _ = cancellation.cancelled() => Err(Error::Cancelled),
382 _ = sleep_until(deadline) => Err(Error::Timeout),
383 status = child.wait() => status.map_err(Error::Io),
384 };
385 let cleanup = if result.is_err() {
386 terminate(&mut child).await
387 } else {
388 child.cleanup().await.map(|_| ())
390 };
391 gone.cancel();
392 cleanup.map_err(Error::Cleanup)?;
393 result
394 };
395 let (stdout_lines, stderr_lines) = lines.unzip();
396 let evidence = |name| logs.as_ref().map(|directory| directory.join(name));
397 let streams = async {
398 tokio::join!(
399 capture::capture(
400 stdout,
401 output_limit,
402 evidence("runtime.stdout"),
403 stdout_lines,
404 &gone
405 ),
406 capture::capture(
407 stderr,
408 output_limit,
409 evidence("runtime.stderr"),
410 stderr_lines,
411 &gone
412 )
413 )
414 };
415 let (status, (stdout, stderr), input) = tokio::join!(wait, streams, feed);
416 let status = status?;
417 input?;
418 capture::finish(status, stdout, stderr, started.elapsed())
419}
420
421pub(crate) async fn spawn_owned<F, R>(
426 command: &Command,
427 input: bool,
428 cancellation: CancellationToken,
429 deadline: Instant,
430 register: Option<F>,
431) -> Result<Child, Error>
432where
433 F: FnOnce(ChildIdentity) -> R,
434 R: Future<Output = io::Result<()>>,
435{
436 spawn_child(
437 command,
438 input,
439 cancellation,
440 deadline,
441 register,
442 SpawnOn::Caller,
443 )
444 .await
445}
446
447async fn spawn_child<F, R>(
448 command: &Command,
449 input: bool,
450 cancellation: CancellationToken,
451 deadline: Instant,
452 register: Option<F>,
453 spawn_on: SpawnOn,
454) -> Result<Child, Error>
455where
456 F: FnOnce(ChildIdentity) -> R,
457 R: Future<Output = io::Result<()>>,
458{
459 let mut child = child_command(command)?;
460 child
461 .stdin(if input { Stdio::piped() } else { Stdio::null() })
462 .stdout(Stdio::piped())
463 .stderr(Stdio::piped())
464 .kill_on_drop(true);
465 let Some(register) = register else {
466 let spawn = artifactize_foundation::platform::process::spawn_in_owner_session(child);
467 return match spawn_on {
468 SpawnOn::Caller => spawn.await,
469 SpawnOn::Worker => {
472 let runtime = tokio::runtime::Handle::current();
473 crate::task::joined(
474 tokio::task::spawn_blocking(move || runtime.block_on(spawn)).await,
475 )?
476 }
477 }
478 .map_err(Error::Spawn);
479 };
480 let (gate, mut spawning) = platform::spawn_gated(child).map_err(Error::Spawn)?;
481 let admission = tokio::select! {
482 biased;
483 _ = cancellation.cancelled() => Err(Error::Cancelled),
484 _ = sleep_until(deadline) => Err(Error::Timeout),
485 result = async {
486 let gate = gate.identify().await?;
487 let child = child_identity(gate.pid()).map_err(Error::Registration)?;
488 register(child).await.map_err(Error::Registration)?;
489 Ok::<_, Error>(gate)
490 } => result,
491 };
492 let admission = admission.and_then(|gate| {
494 if cancellation.is_cancelled() {
495 Err(Error::Cancelled)
496 } else if Instant::now() >= deadline {
497 Err(Error::Timeout)
498 } else {
499 gate.admit().map_err(Error::Io)
500 }
501 });
502 let spawned = crate::task::joined((&mut spawning).await)?;
503 let mut child = match spawned {
504 Ok(child) => child,
505 Err(error) => {
506 return Err(match admission {
507 Err(error @ (Error::Registration(_) | Error::Cancelled | Error::Timeout)) => error,
508 _ => Error::Spawn(error),
509 });
510 }
511 };
512 if let Err(error) = admission {
513 terminate(&mut child).await.map_err(Error::Cleanup)?;
514 return Err(error);
515 }
516
517 Ok(child)
518}
519
520fn child_command(command: &Command) -> Result<NativeCommand, Error> {
521 let environment = platform::environment::for_child(&command.env);
522 let program = resolve_with(
523 std::path::Path::new(&command.program),
524 &command.cwd,
525 |name| platform::environment::lookup(&environment, name).map(ToOwned::to_owned),
526 )
527 .map_err(Error::Spawn)?;
528 let mut child = program.command(&command.args).map_err(Error::Spawn)?;
529 child
530 .current_dir(&command.cwd)
531 .env_clear()
532 .envs(environment.iter());
533 Ok(child)
534}
535
536fn launch_detached(
538 program: &std::ffi::OsStr,
539 args: &[impl AsRef<std::ffi::OsStr>],
540 cwd: &std::path::Path,
541 run: &mut Run,
542) -> Result<(), Error> {
543 let program = resolve_with(
544 std::path::Path::new(program),
545 cwd,
546 platform::environment::var,
547 )
548 .map_err(Error::Spawn)?;
549 let mut command = program.command(args).map_err(Error::Spawn)?;
550 command
551 .current_dir(cwd)
552 .env_clear()
553 .envs(platform::environment::snapshot())
554 .stdin(Stdio::null())
555 .stdout(Stdio::null())
556 .stderr(Stdio::null())
557 .kill_on_drop(false);
558 let child = platform::spawn_detached(command).map_err(Error::Spawn)?;
559 run.launched(child.pid());
560 child.reap();
561 Ok(())
562}
563
564pub(crate) fn launch_watched(
569 program: &std::ffi::OsStr,
570 args: &[impl AsRef<std::ffi::OsStr>],
571 cwd: &std::path::Path,
572 mut run: Run,
573) -> Result<(), (Error, Run)> {
574 if !run.watched() {
575 return match launch_detached(program, args, cwd, &mut run) {
576 Ok(()) => {
577 run.end(End::Launched);
578 Ok(())
579 }
580 Err(error) => Err((error, run)),
581 };
582 }
583 let program = match resolve_with(
584 std::path::Path::new(program),
585 cwd,
586 platform::environment::var,
587 ) {
588 Ok(program) => program,
589 Err(error) => return Err((Error::Spawn(error), run)),
590 };
591 let mut command = match program.command(args) {
592 Ok(command) => command,
593 Err(error) => return Err((Error::Spawn(error), run)),
594 };
595 command
596 .current_dir(cwd)
597 .env_clear()
598 .envs(platform::environment::snapshot())
599 .stdin(Stdio::null())
600 .stdout(Stdio::piped())
601 .stderr(Stdio::piped())
602 .kill_on_drop(false);
603 let mut child = match platform::spawn_watched(command) {
604 Ok(child) => child,
605 Err(error) => return Err((Error::Spawn(error), run)),
606 };
607 run.launched(child.pid());
608 let (stdout, stderr) = child.take_output();
609 tokio::spawn(async move {
610 let held = CancellationToken::new();
613 let (status, _, _) = tokio::join!(
614 child.wait(),
615 capture::capture(stdout, 0, None, Some(run.lines(Stream::Stdout)), &held),
616 capture::capture(stderr, 0, None, Some(run.lines(Stream::Stderr)), &held),
617 );
618 run.end(match status {
619 Ok(status) => End::exited(&status),
620 Err(error) => End::Failed(error.to_string()),
621 });
622 });
623 Ok(())
624}
625
626pub(crate) fn artifactize_executable() -> Result<std::path::PathBuf, String> {
628 platform::program::resolve_near_current("artifactize".as_ref()).map_err(|e| e.to_string())
629}
630
631fn worker_stderr(directory: &std::path::Path) -> std::path::PathBuf {
633 directory.join("worker.stderr")
634}
635
636pub(crate) fn run_worker_diagnostics(state: &std::path::Path, id: &crate::types::RunId) -> String {
637 use std::io::Read;
638 const DIAGNOSTIC_BYTES: u64 = 64 * 1024;
640 let mut bytes = Vec::new();
641 if let Ok(log) = platform::open_regular(&worker_stderr(&state.join("runs").join(id.as_str()))) {
642 let _ = log.take(DIAGNOSTIC_BYTES).read_to_end(&mut bytes);
643 }
644 platform::output_lines(&bytes)
645}
646
647#[derive(Clone, Copy)]
649pub(crate) enum RunEntry {
650 Supervisor,
651 Executor,
652}
653pub(crate) fn spawn_run(
654 program: &std::path::Path,
655 id: &crate::types::RunId,
656 repo: &std::path::Path,
657 state: &std::path::Path,
658 entry: RunEntry,
659) -> Result<(ChildIdentity, platform::DetachedChild), Error> {
660 let mut options = platform::private_options();
661 options.write(true);
662 match entry {
663 RunEntry::Supervisor => {
664 options.create_new(true);
665 }
666 RunEntry::Executor => {
667 options.append(true);
668 }
669 }
670 let directory = state.join("runs").join(id.as_str());
671 let stderr = options
672 .open(worker_stderr(&directory))
673 .map_err(Error::Spawn)?;
674 let program = resolve_with(program, repo, platform::environment::var).map_err(Error::Spawn)?;
675 let args = [
676 std::ffi::OsStr::new("--repo"),
677 repo.as_os_str(),
678 std::ffi::OsStr::new("--state-dir"),
679 state.as_os_str(),
680 std::ffi::OsStr::new(match entry {
681 RunEntry::Supervisor => "__verify",
682 RunEntry::Executor => "__execute",
683 }),
684 std::ffi::OsStr::new(id.as_str()),
685 ];
686 let mut command = program.command(args).map_err(Error::Spawn)?;
687 command
688 .current_dir(directory)
691 .env_clear()
692 .envs(platform::environment::snapshot())
693 .stdin(Stdio::null())
694 .stdout(Stdio::null())
695 .stderr(Stdio::from(stderr))
696 .kill_on_drop(false);
697 let child = platform::spawn_run(command).map_err(Error::Spawn)?;
698 let identity = child_identity(child.pid()).map_err(Error::Registration)?;
699 Ok((identity, child))
700}
701pub(crate) fn launch_run(
702 program: &std::path::Path,
703 id: &crate::types::RunId,
704 repo: &std::path::Path,
705 state: &std::path::Path,
706) -> Result<ChildIdentity, Error> {
707 let (identity, child) = spawn_run(program, id, repo, state, RunEntry::Supervisor)?;
708 child.reap();
709 Ok(identity)
710}
711
712pub(crate) async fn run_logged<F, R>(
716 command: Command,
717 directory: PathBuf,
718 cancellation: CancellationToken,
719 register: F,
720) -> Result<Output, Error>
721where
722 F: FnOnce(ChildIdentity) -> R + Send + 'static,
723 R: Future<Output = io::Result<()>> + Send + 'static,
724{
725 run_inner(
726 command,
727 None,
728 OUTPUT_LIMIT,
729 Capture {
730 logs: Some(directory),
731 lines: None,
732 },
733 cancellation,
734 Some(register),
735 SpawnOn::Caller,
736 )
737 .await
738}