1use std::{
4 collections::BTreeMap, ffi::OsString, future::Future, io, path::PathBuf, process::Stdio,
5 time::Duration,
6};
7
8use thiserror::Error;
9use tokio::{
10 io::AsyncWriteExt,
11 time::{Instant, sleep, sleep_until},
12};
13use tokio_util::sync::CancellationToken;
14
15use crate::{
16 platform::{self, Child},
17 tools::human::log::{End, Lines, Run, Stream},
18};
19
20pub(crate) const OUTPUT_LIMIT: usize = 128 * 1024;
22const CLEANUP_GRACE: Duration = Duration::from_secs(1);
24
25mod capture;
26pub use capture::{CaptureError, StreamFailure};
27#[cfg(test)]
28pub(crate) use capture::{OUTPUT_CLOSE_GRACE, slow_disk};
29
30#[derive(Debug, Clone)]
32pub struct Command {
33 pub program: OsString,
34 pub args: Vec<OsString>,
35 pub cwd: PathBuf,
36 pub env: BTreeMap<OsString, OsString>,
38 pub timeout: Duration,
39}
40
41#[derive(
45 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
46)]
47#[serde(transparent)]
48pub struct ProcessId(std::num::NonZeroU32);
49
50impl ProcessId {
51 pub fn new(pid: u32) -> Self {
53 Self(std::num::NonZeroU32::new(pid).expect("a real process id is never 0"))
54 }
55
56 pub fn get(self) -> u32 {
57 self.0.get()
58 }
59}
60
61impl From<std::num::NonZeroU32> for ProcessId {
62 fn from(pid: std::num::NonZeroU32) -> Self {
63 Self(pid)
64 }
65}
66
67impl std::fmt::Display for ProcessId {
68 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69 self.0.fmt(f)
70 }
71}
72
73impl rusqlite::types::ToSql for ProcessId {
74 fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
75 Ok(rusqlite::types::ToSqlOutput::from(i64::from(self.0.get())))
76 }
77}
78
79impl rusqlite::types::FromSql for ProcessId {
80 fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult<Self> {
81 let pid = u32::try_from(value.as_i64()?)
82 .map_err(|error| rusqlite::types::FromSqlError::Other(error.into()))?;
83 std::num::NonZeroU32::new(pid).map(Self).ok_or_else(|| {
84 rusqlite::types::FromSqlError::Other(
85 "a saved owner_pid of 0 is not a process id".into(),
86 )
87 })
88 }
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
93pub struct ChildIdentity {
94 pub pid: ProcessId,
95 pub start_time: u64,
98}
99
100#[derive(Debug)]
101pub struct Output {
102 pub status: platform::ProcessOutcome,
103 pub stdout: Vec<u8>,
104 pub stderr: Vec<u8>,
105 pub truncated: bool,
106 pub duration: Duration,
107}
108
109pub(crate) fn tool_output<'a>(
113 program: &str,
114 args: impl IntoIterator<Item = &'a std::ffi::OsStr>,
115) -> Option<Vec<u8>> {
116 platform::program::tool_output(program, args)
117}
118
119pub(crate) struct Launcher {
123 pub env: BTreeMap<OsString, OsString>,
124}
125
126impl artifactize_tools::launch::Launcher for Launcher {
127 fn run<'a>(
128 &'a self,
129 launch: artifactize_tools::launch::Launch,
130 cancellation: &'a CancellationToken,
131 ) -> artifactize_tools::launch::Running<'a> {
132 use artifactize_tools::launch::{Finished, LaunchError};
133 Box::pin(async move {
134 let command = Command {
135 program: launch.program.into(),
136 args: launch.args,
137 cwd: launch.cwd,
138 env: self.env.clone(),
139 timeout: launch.timeout,
140 };
141 match run_unregistered(command, None, launch.output_limit, cancellation.clone()).await {
142 Ok(output) => Ok(Finished {
143 status: output.status,
144 stdout: output.stdout,
145 stderr: output.stderr,
146 truncated: output.truncated,
147 }),
148 Err(Error::Timeout) => Err(LaunchError::TimedOut),
149 Err(Error::Cancelled) => Err(LaunchError::Cancelled),
150 Err(error) => Err(LaunchError::Failed(
151 error
152 .argument_refusal()
153 .unwrap_or_else(|| error.to_string()),
154 )),
155 }
156 })
157 }
158}
159
160#[derive(Debug, Error)]
161pub enum Error {
162 #[error("process could not be spawned: {0}")]
163 Spawn(#[source] io::Error),
164 #[error("child registration failed: {0}")]
165 Registration(#[source] io::Error),
166 #[error("process supervision failed: {0}")]
167 Io(#[from] io::Error),
168 #[error("process cleanup could not be confirmed: {0}")]
169 Cleanup(#[source] io::Error),
170 #[error("process supervision task failed: {0}")]
171 Task(#[from] tokio::task::JoinError),
172 #[error("process timeout is too large to represent as a deadline")]
173 InvalidTimeout,
174 #[error("process timed out")]
175 Timeout,
176 #[error("process was cancelled")]
177 Cancelled,
178 #[error(transparent)]
181 Capture(Box<CaptureError>),
182}
183
184impl Error {
185 pub(crate) fn cleanup_confirmed(&self) -> bool {
188 match self {
189 Self::Cleanup(_) | Self::Task(_) => false,
190 Self::Spawn(_)
191 | Self::Registration(_)
192 | Self::Io(_)
193 | Self::InvalidTimeout
194 | Self::Timeout
195 | Self::Cancelled
196 | Self::Capture(_) => true,
197 }
198 }
199
200 pub(crate) fn argument_refusal(&self) -> Option<String> {
201 match self {
202 Self::Spawn(error) if error.kind() == io::ErrorKind::InvalidInput => Some(format!(
203 "Process arguments could not be passed safely: {error}"
204 )),
205 _ => None,
206 }
207 }
208}
209
210pub async fn run<F, R>(
214 command: Command,
215 cancellation: CancellationToken,
216 register: F,
217) -> Result<Output, Error>
218where
219 F: FnOnce(ChildIdentity) -> R + Send + 'static,
220 R: Future<Output = io::Result<()>> + Send + 'static,
221{
222 run_with_input(command, None, cancellation, register).await
223}
224
225pub(crate) async fn run_with_input<F, R>(
226 command: Command,
227 input: Option<Vec<u8>>,
228 cancellation: CancellationToken,
229 register: F,
230) -> Result<Output, Error>
231where
232 F: FnOnce(ChildIdentity) -> R + Send + 'static,
233 R: Future<Output = io::Result<()>> + Send + 'static,
234{
235 run_with_input_limit(command, input, OUTPUT_LIMIT, cancellation, register).await
236}
237
238pub(crate) async fn run_with_input_limit<F, R>(
239 command: Command,
240 input: Option<Vec<u8>>,
241 output_limit: usize,
242 cancellation: CancellationToken,
243 register: F,
244) -> Result<Output, Error>
245where
246 F: FnOnce(ChildIdentity) -> R + Send + 'static,
247 R: Future<Output = io::Result<()>> + Send + 'static,
248{
249 let cancellation = cancellation.child_token();
250 let _cancel_on_drop = cancellation.clone().drop_guard();
251 crate::task::joined(
252 tokio::spawn(run_inner(
253 command,
254 input,
255 output_limit,
256 Capture::default(),
257 cancellation,
258 Some(register),
259 ))
260 .await,
261 )?
262}
263
264pub(crate) type Unregistered = fn(ChildIdentity) -> std::future::Ready<io::Result<()>>;
267
268pub(crate) async fn run_unregistered(
271 command: Command,
272 input: Option<Vec<u8>>,
273 output_limit: usize,
274 cancellation: CancellationToken,
275) -> Result<Output, Error> {
276 let cancellation = cancellation.child_token();
277 let _cancel_on_drop = cancellation.clone().drop_guard();
278 crate::task::joined(
279 tokio::spawn(run_inner(
280 command,
281 input,
282 output_limit,
283 Capture::default(),
284 cancellation,
285 None::<Unregistered>,
286 ))
287 .await,
288 )?
289}
290
291#[derive(Default)]
294struct Capture {
295 logs: Option<PathBuf>,
296 lines: Option<(Lines, Lines)>,
297}
298
299pub(crate) async fn run_watched(
302 command: Command,
303 cancellation: CancellationToken,
304 run: &Run,
305) -> Result<Output, Error> {
306 let cancellation = cancellation.child_token();
307 let _cancel_on_drop = cancellation.clone().drop_guard();
308 let capture = Capture {
309 logs: None,
310 lines: Some((run.lines(Stream::Stdout), run.lines(Stream::Stderr))),
311 };
312 crate::task::joined(
313 tokio::spawn(run_inner(
314 command,
315 None,
316 OUTPUT_LIMIT,
317 capture,
318 cancellation,
319 None::<Unregistered>,
320 ))
321 .await,
322 )?
323}
324
325async fn run_inner<F, R>(
326 command: Command,
327 input: Option<Vec<u8>>,
328 output_limit: usize,
329 Capture { logs, lines }: Capture,
330 cancellation: CancellationToken,
331 register: Option<F>,
332) -> Result<Output, Error>
333where
334 F: FnOnce(ChildIdentity) -> R,
335 R: Future<Output = io::Result<()>>,
336{
337 let started = Instant::now();
338 let deadline = started
339 .checked_add(command.timeout)
340 .ok_or(Error::InvalidTimeout)?;
341 if cancellation.is_cancelled() {
342 return Err(Error::Cancelled);
343 }
344 if command.timeout.is_zero() {
345 return Err(Error::Timeout);
346 }
347
348 let mut child = spawn_owned(
349 &command,
350 input.is_some(),
351 cancellation.clone(),
352 deadline,
353 register,
354 )
355 .await?;
356
357 let stdout = child.stdout().take().expect("stdout is piped");
358 let stderr = child.stderr().take().expect("stderr is piped");
359 let stdin = child.stdin().take();
360 let gone = CancellationToken::new();
363 let feed = async {
364 if let (Some(mut stdin), Some(input)) = (stdin, input) {
365 tokio::select! {
366 _ = gone.cancelled() => {},
367 _ = cancellation.cancelled() => {},
368 _ = sleep_until(deadline) => {},
369 result = stdin.write_all(&input) => {
370 if let Err(error) = result && error.kind() != io::ErrorKind::BrokenPipe {
372 return Err(Error::Io(error));
373 }
374 }
375 }
376 }
377 Ok(())
378 };
379 let wait = async {
380 let result = tokio::select! {
381 biased;
382 _ = cancellation.cancelled() => Err(Error::Cancelled),
383 _ = sleep_until(deadline) => Err(Error::Timeout),
384 status = child.wait() => status.map_err(Error::Io),
385 };
386 let cleanup = if result.is_err() {
387 terminate(&mut child).await
388 } else {
389 child.cleanup().await.map(|_| ())
391 };
392 gone.cancel();
393 cleanup.map_err(Error::Cleanup)?;
394 result
395 };
396 let (stdout_lines, stderr_lines) = lines.unzip();
397 let evidence = |name| logs.as_ref().map(|directory| directory.join(name));
398 let streams = async {
399 tokio::join!(
400 capture::capture(
401 stdout,
402 output_limit,
403 evidence("runtime.stdout"),
404 stdout_lines,
405 &gone
406 ),
407 capture::capture(
408 stderr,
409 output_limit,
410 evidence("runtime.stderr"),
411 stderr_lines,
412 &gone
413 )
414 )
415 };
416 let (status, (stdout, stderr), input) = tokio::join!(wait, streams, feed);
417 let status = status?;
418 input?;
419 capture::finish(status, stdout, stderr, started.elapsed())
420}
421
422pub(crate) async fn spawn_owned<F, R>(
428 command: &Command,
429 input: bool,
430 cancellation: CancellationToken,
431 deadline: Instant,
432 register: Option<F>,
433) -> Result<Child, Error>
434where
435 F: FnOnce(ChildIdentity) -> R,
436 R: Future<Output = io::Result<()>>,
437{
438 let mut child = child_command(command)?;
439 child
440 .stdin(if input { Stdio::piped() } else { Stdio::null() })
441 .stdout(Stdio::piped())
442 .stderr(Stdio::piped())
443 .kill_on_drop(true);
444 let Some(register) = register else {
445 return platform::spawn_now(child).await.map_err(Error::Spawn);
446 };
447 let (gate, mut spawning) = platform::spawn_gated(child).map_err(Error::Spawn)?;
448 let admission = tokio::select! {
449 biased;
450 _ = cancellation.cancelled() => Err(Error::Cancelled),
451 _ = sleep_until(deadline) => Err(Error::Timeout),
452 result = async {
453 let pid = gate.pid().await?;
454 let child = child_identity(pid).map_err(Error::Registration)?;
455 register(child).await.map_err(Error::Registration)?;
456 Ok::<_, Error>(())
457 } => result,
458 };
459 let admission = admission.and_then(|()| {
461 if cancellation.is_cancelled() {
462 Err(Error::Cancelled)
463 } else if Instant::now() >= deadline {
464 Err(Error::Timeout)
465 } else {
466 gate.admit().map_err(Error::Io)
467 }
468 });
469 drop(gate);
470 let spawned = crate::task::joined((&mut spawning).await)?;
471 let mut child = match spawned {
472 Ok(child) => child,
473 Err(error) => {
474 return Err(match admission {
475 Err(error @ (Error::Registration(_) | Error::Cancelled | Error::Timeout)) => error,
476 _ => Error::Spawn(error),
477 });
478 }
479 };
480 if let Err(error) = admission {
481 terminate(&mut child).await.map_err(Error::Cleanup)?;
482 return Err(error);
483 }
484
485 Ok(child)
486}
487
488fn child_command(command: &Command) -> Result<tokio::process::Command, Error> {
489 let environment = platform::environment::for_child(&command.env);
490 let program = platform::program::resolve_with(
491 std::path::Path::new(&command.program),
492 &command.cwd,
493 |name| platform::environment::lookup(&environment, name).map(ToOwned::to_owned),
494 )
495 .map_err(Error::Spawn)?;
496 let mut child = tokio::process::Command::new(program);
497 child
498 .args(&command.args)
499 .current_dir(&command.cwd)
500 .env_clear()
501 .envs(environment.iter());
502 Ok(child)
503}
504
505fn launch_detached(
507 program: &std::ffi::OsStr,
508 args: &[impl AsRef<std::ffi::OsStr>],
509 cwd: &std::path::Path,
510 run: &mut Run,
511) -> Result<(), Error> {
512 let program =
513 platform::program::resolve(std::path::Path::new(program), cwd).map_err(Error::Spawn)?;
514 let mut command = tokio::process::Command::new(program);
515 command
516 .args(args)
517 .current_dir(cwd)
518 .env_clear()
519 .envs(platform::environment::snapshot())
520 .stdin(Stdio::null())
521 .stdout(Stdio::null())
522 .stderr(Stdio::null())
523 .kill_on_drop(false);
524 let child = platform::spawn_detached(command).map_err(Error::Spawn)?;
525 run.launched(child.pid());
526 child.reap();
527 Ok(())
528}
529
530pub(crate) async fn spawn_handoff(command: &Command) -> Result<Child, Error> {
535 let mut child = child_command(command)?;
536 child
537 .stdin(Stdio::piped())
538 .stdout(Stdio::piped())
539 .stderr(Stdio::piped())
540 .kill_on_drop(true);
541 platform::spawn_windowless(child)
542 .await
543 .map_err(Error::Spawn)
544}
545
546pub(crate) async fn spawn_supervised(
550 command: &Command,
551 process_cancel: &CancellationToken,
552) -> Result<Child, Error> {
553 if process_cancel.is_cancelled() {
554 return Err(Error::Cancelled);
555 }
556 let mut child = child_command(command)?;
557 child
558 .stdin(Stdio::piped())
559 .stdout(Stdio::piped())
560 .stderr(Stdio::piped())
561 .kill_on_drop(true);
562 let mut spawned = platform::spawn_now(child).await.map_err(Error::Spawn)?;
563 if process_cancel.is_cancelled() {
564 let _ = terminate(&mut spawned).await;
565 return Err(Error::Cancelled);
566 }
567 Ok(spawned)
568}
569
570pub(crate) fn launch_watched(
575 program: &std::ffi::OsStr,
576 args: &[impl AsRef<std::ffi::OsStr>],
577 cwd: &std::path::Path,
578 mut run: Run,
579) -> Result<(), (Error, Run)> {
580 if !run.watched() {
581 return match launch_detached(program, args, cwd, &mut run) {
582 Ok(()) => {
583 run.end(End::Launched);
584 Ok(())
585 }
586 Err(error) => Err((error, run)),
587 };
588 }
589 let program = match platform::program::resolve(std::path::Path::new(program), cwd) {
590 Ok(program) => program,
591 Err(error) => return Err((Error::Spawn(error), run)),
592 };
593 let mut command = tokio::process::Command::new(program);
594 command
595 .args(args)
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
631#[derive(Clone, Copy)]
633pub(crate) enum RunEntry {
634 Supervisor,
635 Executor,
636}
637pub(crate) fn spawn_run(
638 program: &std::path::Path,
639 id: &crate::types::RunId,
640 repo: &std::path::Path,
641 state: &std::path::Path,
642 entry: RunEntry,
643) -> Result<(ChildIdentity, platform::DetachedChild), Error> {
644 let mut options = platform::private_options();
645 options.write(true);
646 match entry {
647 RunEntry::Supervisor => {
648 options.create_new(true);
649 }
650 RunEntry::Executor => {
651 options.append(true);
652 }
653 }
654 let directory = state.join("runs").join(id.as_str());
655 let stderr = options
656 .open(directory.join("worker.stderr"))
657 .map_err(Error::Spawn)?;
658 let program = platform::program::resolve(program, repo).map_err(Error::Spawn)?;
659 let mut command = tokio::process::Command::new(program);
660 command
661 .arg("--repo")
662 .arg(repo)
663 .arg("--state-dir")
664 .arg(state)
665 .arg(match entry {
666 RunEntry::Supervisor => "__verify",
667 RunEntry::Executor => "__execute",
668 })
669 .arg(id.as_str())
670 .current_dir(directory)
673 .env_clear()
674 .envs(platform::environment::snapshot())
675 .stdin(Stdio::null())
676 .stdout(Stdio::null())
677 .stderr(Stdio::from(stderr))
678 .kill_on_drop(false);
679 let child = platform::spawn_run(command).map_err(Error::Spawn)?;
680 let identity = child_identity(child.pid()).map_err(Error::Registration)?;
681 Ok((identity, child))
682}
683pub(crate) fn launch_run(
684 program: &std::path::Path,
685 id: &crate::types::RunId,
686 repo: &std::path::Path,
687 state: &std::path::Path,
688) -> Result<ChildIdentity, Error> {
689 let (identity, child) = spawn_run(program, id, repo, state, RunEntry::Supervisor)?;
690 child.reap();
691 Ok(identity)
692}
693
694pub(crate) fn child_identity(pid: u32) -> io::Result<ChildIdentity> {
695 let start_time = platform::process_start_time(pid)?;
696 Ok(ChildIdentity {
697 pid: ProcessId::new(pid),
698 start_time,
699 })
700}
701
702pub(crate) fn is_alive(owner: Option<ChildIdentity>) -> io::Result<bool> {
705 let Some(owner) = owner else {
706 return Ok(false);
707 };
708 match platform::running_process_start_time(owner.pid.get()) {
709 Ok(start_time) => Ok(start_time == owner.start_time),
710 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
711 Err(error) => Err(error),
712 }
713}
714
715pub(crate) async fn terminate(child: &mut Child) -> io::Result<()> {
716 let _ = child.interrupt();
717 tokio::select! {
718 _ = sleep(CLEANUP_GRACE) => {},
719 _ = child.wait() => {},
720 }
721 child.cleanup().await?;
722 Ok(())
723}
724
725pub(crate) async fn run_logged<F, R>(
729 command: Command,
730 directory: PathBuf,
731 cancellation: CancellationToken,
732 register: F,
733) -> Result<Output, Error>
734where
735 F: FnOnce(ChildIdentity) -> R + Send + 'static,
736 R: Future<Output = io::Result<()>> + Send + 'static,
737{
738 run_inner(
739 command,
740 None,
741 OUTPUT_LIMIT,
742 Capture {
743 logs: Some(directory),
744 lines: None,
745 },
746 cancellation,
747 Some(register),
748 )
749 .await
750}