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) fn launch_watched(
551 program: &std::ffi::OsStr,
552 args: &[impl AsRef<std::ffi::OsStr>],
553 cwd: &std::path::Path,
554 mut run: Run,
555) -> Result<(), (Error, Run)> {
556 if !run.watched() {
557 return match launch_detached(program, args, cwd, &mut run) {
558 Ok(()) => {
559 run.end(End::Launched);
560 Ok(())
561 }
562 Err(error) => Err((error, run)),
563 };
564 }
565 let program = match platform::program::resolve(std::path::Path::new(program), cwd) {
566 Ok(program) => program,
567 Err(error) => return Err((Error::Spawn(error), run)),
568 };
569 let mut command = tokio::process::Command::new(program);
570 command
571 .args(args)
572 .current_dir(cwd)
573 .env_clear()
574 .envs(platform::environment::snapshot())
575 .stdin(Stdio::null())
576 .stdout(Stdio::piped())
577 .stderr(Stdio::piped())
578 .kill_on_drop(false);
579 let mut child = match platform::spawn_watched(command) {
580 Ok(child) => child,
581 Err(error) => return Err((Error::Spawn(error), run)),
582 };
583 run.launched(child.pid());
584 let (stdout, stderr) = child.take_output();
585 tokio::spawn(async move {
586 let held = CancellationToken::new();
589 let (status, _, _) = tokio::join!(
590 child.wait(),
591 capture::capture(stdout, 0, None, Some(run.lines(Stream::Stdout)), &held),
592 capture::capture(stderr, 0, None, Some(run.lines(Stream::Stderr)), &held),
593 );
594 run.end(match status {
595 Ok(status) => End::exited(&status),
596 Err(error) => End::Failed(error.to_string()),
597 });
598 });
599 Ok(())
600}
601
602pub(crate) fn artifactize_executable() -> Result<std::path::PathBuf, String> {
604 platform::program::resolve_near_current("artifactize".as_ref()).map_err(|e| e.to_string())
605}
606
607#[derive(Clone, Copy)]
609pub(crate) enum RunEntry {
610 Supervisor,
611 Executor,
612}
613pub(crate) fn spawn_run(
614 program: &std::path::Path,
615 id: &crate::types::RunId,
616 repo: &std::path::Path,
617 state: &std::path::Path,
618 entry: RunEntry,
619) -> Result<(ChildIdentity, platform::DetachedChild), Error> {
620 let mut options = platform::private_options();
621 options.write(true);
622 match entry {
623 RunEntry::Supervisor => {
624 options.create_new(true);
625 }
626 RunEntry::Executor => {
627 options.append(true);
628 }
629 }
630 let directory = state.join("runs").join(id.as_str());
631 let stderr = options
632 .open(directory.join("worker.stderr"))
633 .map_err(Error::Spawn)?;
634 let program = platform::program::resolve(program, repo).map_err(Error::Spawn)?;
635 let mut command = tokio::process::Command::new(program);
636 command
637 .arg("--repo")
638 .arg(repo)
639 .arg("--state-dir")
640 .arg(state)
641 .arg(match entry {
642 RunEntry::Supervisor => "__verify",
643 RunEntry::Executor => "__execute",
644 })
645 .arg(id.as_str())
646 .current_dir(directory)
649 .env_clear()
650 .envs(platform::environment::snapshot())
651 .stdin(Stdio::null())
652 .stdout(Stdio::null())
653 .stderr(Stdio::from(stderr))
654 .kill_on_drop(false);
655 let child = platform::spawn_run(command).map_err(Error::Spawn)?;
656 let identity = child_identity(child.pid()).map_err(Error::Registration)?;
657 Ok((identity, child))
658}
659pub(crate) fn launch_run(
660 program: &std::path::Path,
661 id: &crate::types::RunId,
662 repo: &std::path::Path,
663 state: &std::path::Path,
664) -> Result<ChildIdentity, Error> {
665 let (identity, child) = spawn_run(program, id, repo, state, RunEntry::Supervisor)?;
666 child.reap();
667 Ok(identity)
668}
669
670pub(crate) fn child_identity(pid: u32) -> io::Result<ChildIdentity> {
671 let start_time = platform::process_start_time(pid)?;
672 Ok(ChildIdentity {
673 pid: ProcessId::new(pid),
674 start_time,
675 })
676}
677
678pub(crate) fn is_alive(owner: Option<ChildIdentity>) -> io::Result<bool> {
681 let Some(owner) = owner else {
682 return Ok(false);
683 };
684 match platform::running_process_start_time(owner.pid.get()) {
685 Ok(start_time) => Ok(start_time == owner.start_time),
686 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
687 Err(error) => Err(error),
688 }
689}
690
691pub(crate) async fn terminate(child: &mut Child) -> io::Result<()> {
692 let _ = child.interrupt();
693 tokio::select! {
694 _ = sleep(CLEANUP_GRACE) => {},
695 _ = child.wait() => {},
696 }
697 child.cleanup().await?;
698 Ok(())
699}
700
701pub(crate) async fn run_logged<F, R>(
705 command: Command,
706 directory: PathBuf,
707 cancellation: CancellationToken,
708 register: F,
709) -> Result<Output, Error>
710where
711 F: FnOnce(ChildIdentity) -> R + Send + 'static,
712 R: Future<Output = io::Result<()>> + Send + 'static,
713{
714 run_inner(
715 command,
716 None,
717 OUTPUT_LIMIT,
718 Capture {
719 logs: Some(directory),
720 lines: None,
721 },
722 cancellation,
723 Some(register),
724 )
725 .await
726}