2021-10-14 00:06:53 +00:00
|
|
|
use actix_web::web::Bytes;
|
2021-08-31 02:19:47 +00:00
|
|
|
use std::{
|
2023-11-10 00:20:59 +00:00
|
|
|
ffi::OsStr,
|
2021-09-04 00:53:53 +00:00
|
|
|
future::Future,
|
2023-07-10 20:29:41 +00:00
|
|
|
process::{ExitStatus, Stdio},
|
2023-12-23 02:54:02 +00:00
|
|
|
sync::Arc,
|
2023-08-05 17:41:06 +00:00
|
|
|
time::{Duration, Instant},
|
2021-08-31 02:19:47 +00:00
|
|
|
};
|
2021-09-14 01:22:42 +00:00
|
|
|
use tokio::{
|
2023-12-23 02:54:02 +00:00
|
|
|
io::{AsyncReadExt, AsyncWriteExt},
|
|
|
|
process::{Child, ChildStdin, Command},
|
2021-09-14 01:22:42 +00:00
|
|
|
};
|
2023-12-23 02:54:02 +00:00
|
|
|
use tracing::Instrument;
|
2023-12-22 19:12:19 +00:00
|
|
|
use uuid::Uuid;
|
2021-09-04 00:53:53 +00:00
|
|
|
|
2023-12-22 19:12:19 +00:00
|
|
|
use crate::{
|
|
|
|
error_code::ErrorCode,
|
|
|
|
future::{LocalBoxFuture, WithTimeout},
|
2023-12-23 02:52:58 +00:00
|
|
|
read::BoxRead,
|
2023-12-22 19:12:19 +00:00
|
|
|
};
|
2023-09-02 01:50:10 +00:00
|
|
|
|
2023-07-22 21:47:59 +00:00
|
|
|
struct MetricsGuard {
|
|
|
|
start: Instant,
|
|
|
|
armed: bool,
|
2023-12-22 19:12:19 +00:00
|
|
|
command: Arc<str>,
|
2023-07-22 21:47:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl MetricsGuard {
|
2023-12-22 19:12:19 +00:00
|
|
|
fn guard(command: Arc<str>) -> Self {
|
2023-12-27 00:06:38 +00:00
|
|
|
metrics::counter!("pict-rs.process.start", "command" => command.to_string()).increment(1);
|
2023-07-22 21:47:59 +00:00
|
|
|
|
|
|
|
Self {
|
|
|
|
start: Instant::now(),
|
|
|
|
armed: true,
|
|
|
|
command,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn disarm(mut self) {
|
|
|
|
self.armed = false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Drop for MetricsGuard {
|
|
|
|
fn drop(&mut self) {
|
|
|
|
metrics::histogram!(
|
|
|
|
"pict-rs.process.duration",
|
2023-12-22 19:12:19 +00:00
|
|
|
"command" => self.command.to_string(),
|
2023-07-22 21:47:59 +00:00
|
|
|
"completed" => (!self.armed).to_string(),
|
2023-12-27 00:06:38 +00:00
|
|
|
)
|
|
|
|
.record(self.start.elapsed().as_secs_f64());
|
2023-07-22 21:47:59 +00:00
|
|
|
|
2023-12-27 00:06:38 +00:00
|
|
|
metrics::counter!("pict-rs.process.end", "completed" => (!self.armed).to_string() , "command" => self.command.to_string()).increment(1);
|
2023-07-22 21:47:59 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-09 19:16:12 +00:00
|
|
|
#[derive(Debug)]
|
2023-07-14 00:21:28 +00:00
|
|
|
struct StatusError(ExitStatus);
|
2021-09-09 19:16:12 +00:00
|
|
|
|
2021-08-31 02:19:47 +00:00
|
|
|
pub(crate) struct Process {
|
2023-12-22 19:12:19 +00:00
|
|
|
command: Arc<str>,
|
2021-09-14 01:22:42 +00:00
|
|
|
child: Child,
|
2023-07-22 21:47:59 +00:00
|
|
|
guard: MetricsGuard,
|
2023-08-05 17:41:06 +00:00
|
|
|
timeout: Duration,
|
2023-12-22 19:12:19 +00:00
|
|
|
id: Uuid,
|
2022-04-07 02:40:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl std::fmt::Debug for Process {
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
f.debug_struct("Process").field("child", &"Child").finish()
|
|
|
|
}
|
2021-08-31 02:19:47 +00:00
|
|
|
}
|
|
|
|
|
2023-12-23 17:58:20 +00:00
|
|
|
#[async_trait::async_trait(?Send)]
|
|
|
|
pub(crate) trait Extras {
|
|
|
|
async fn consume(&mut self) -> std::io::Result<()>;
|
|
|
|
}
|
|
|
|
|
|
|
|
#[async_trait::async_trait(?Send)]
|
|
|
|
impl Extras for () {
|
|
|
|
async fn consume(&mut self) -> std::io::Result<()> {
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[async_trait::async_trait(?Send)]
|
|
|
|
impl<T> Extras for (Box<dyn Extras>, T)
|
|
|
|
where
|
|
|
|
T: Extras,
|
|
|
|
{
|
|
|
|
async fn consume(&mut self) -> std::io::Result<()> {
|
|
|
|
let (res1, res2) = tokio::join!(self.0.consume(), self.1.consume());
|
|
|
|
res1?;
|
|
|
|
res2
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-18 05:14:39 +00:00
|
|
|
pub(crate) struct ProcessRead {
|
2023-12-23 02:52:58 +00:00
|
|
|
reader: BoxRead<'static>,
|
|
|
|
handle: LocalBoxFuture<'static, Result<(), ProcessError>>,
|
2023-12-22 19:12:19 +00:00
|
|
|
command: Arc<str>,
|
|
|
|
id: Uuid,
|
2023-12-23 17:58:20 +00:00
|
|
|
extras: Box<dyn Extras>,
|
2021-09-04 00:53:53 +00:00
|
|
|
}
|
|
|
|
|
2023-07-10 20:29:41 +00:00
|
|
|
#[derive(Debug, thiserror::Error)]
|
|
|
|
pub(crate) enum ProcessError {
|
2023-07-17 02:51:14 +00:00
|
|
|
#[error("Required command {0} not found, make sure it exists in pict-rs' $PATH")]
|
2023-12-22 19:12:19 +00:00
|
|
|
NotFound(Arc<str>),
|
2023-07-10 20:29:41 +00:00
|
|
|
|
2023-07-17 02:51:14 +00:00
|
|
|
#[error("Cannot run command {0} due to invalid permissions on binary, make sure the pict-rs user has permission to run it")]
|
2023-12-22 19:12:19 +00:00
|
|
|
PermissionDenied(Arc<str>),
|
2023-07-17 02:51:14 +00:00
|
|
|
|
2023-07-10 20:29:41 +00:00
|
|
|
#[error("Reached process spawn limit")]
|
|
|
|
LimitReached,
|
|
|
|
|
2023-08-05 17:41:06 +00:00
|
|
|
#[error("{0} timed out")]
|
2023-12-22 19:12:19 +00:00
|
|
|
Timeout(Arc<str>),
|
2023-08-05 17:41:06 +00:00
|
|
|
|
2023-07-17 18:30:08 +00:00
|
|
|
#[error("{0} Failed with {1}")]
|
2023-12-22 19:12:19 +00:00
|
|
|
Status(Arc<str>, ExitStatus),
|
2023-07-10 20:29:41 +00:00
|
|
|
|
2023-12-23 02:52:58 +00:00
|
|
|
#[error("Failed to read stdout for {0}")]
|
|
|
|
Read(Arc<str>, #[source] std::io::Error),
|
|
|
|
|
2023-12-23 17:58:20 +00:00
|
|
|
#[error("Failed to cleanup for command {0}")]
|
|
|
|
Cleanup(Arc<str>, #[source] std::io::Error),
|
|
|
|
|
2023-07-10 20:29:41 +00:00
|
|
|
#[error("Unknown process error")]
|
|
|
|
Other(#[source] std::io::Error),
|
|
|
|
}
|
|
|
|
|
2023-09-02 01:50:10 +00:00
|
|
|
impl ProcessError {
|
|
|
|
pub(crate) const fn error_code(&self) -> ErrorCode {
|
|
|
|
match self {
|
|
|
|
Self::NotFound(_) => ErrorCode::COMMAND_NOT_FOUND,
|
|
|
|
Self::PermissionDenied(_) => ErrorCode::COMMAND_PERMISSION_DENIED,
|
2023-12-23 17:58:20 +00:00
|
|
|
Self::LimitReached | Self::Read(_, _) | Self::Cleanup(_, _) | Self::Other(_) => {
|
|
|
|
ErrorCode::COMMAND_ERROR
|
|
|
|
}
|
2023-09-02 01:50:10 +00:00
|
|
|
Self::Timeout(_) => ErrorCode::COMMAND_TIMEOUT,
|
|
|
|
Self::Status(_, _) => ErrorCode::COMMAND_FAILURE,
|
|
|
|
}
|
|
|
|
}
|
2023-12-23 02:52:58 +00:00
|
|
|
|
|
|
|
pub(crate) fn is_client_error(&self) -> bool {
|
|
|
|
matches!(self, Self::Timeout(_))
|
|
|
|
}
|
2023-09-02 01:50:10 +00:00
|
|
|
}
|
|
|
|
|
2021-08-31 02:19:47 +00:00
|
|
|
impl Process {
|
2023-11-10 00:20:59 +00:00
|
|
|
pub(crate) fn run<T>(
|
|
|
|
command: &str,
|
|
|
|
args: &[T],
|
|
|
|
envs: &[(&str, &OsStr)],
|
|
|
|
timeout: u64,
|
|
|
|
) -> Result<Self, ProcessError>
|
|
|
|
where
|
|
|
|
T: AsRef<OsStr>,
|
|
|
|
{
|
2023-12-22 19:12:19 +00:00
|
|
|
let command: Arc<str> = Arc::from(String::from(command));
|
|
|
|
|
2023-11-10 00:20:59 +00:00
|
|
|
let res = tracing::trace_span!(parent: None, "Create command", %command).in_scope(|| {
|
|
|
|
Self::spawn(
|
2023-12-22 19:12:19 +00:00
|
|
|
command.clone(),
|
|
|
|
Command::new(command.as_ref())
|
|
|
|
.args(args)
|
|
|
|
.envs(envs.iter().copied()),
|
2023-11-10 00:20:59 +00:00
|
|
|
timeout,
|
|
|
|
)
|
|
|
|
});
|
2023-07-10 20:29:41 +00:00
|
|
|
|
|
|
|
match res {
|
|
|
|
Ok(this) => Ok(this),
|
|
|
|
Err(e) => match e.kind() {
|
2023-12-22 19:12:19 +00:00
|
|
|
std::io::ErrorKind::NotFound => Err(ProcessError::NotFound(command)),
|
2023-07-17 02:51:14 +00:00
|
|
|
std::io::ErrorKind::PermissionDenied => {
|
2023-12-22 19:12:19 +00:00
|
|
|
Err(ProcessError::PermissionDenied(command))
|
2023-07-17 02:51:14 +00:00
|
|
|
}
|
2023-07-10 20:29:41 +00:00
|
|
|
std::io::ErrorKind::WouldBlock => Err(ProcessError::LimitReached),
|
|
|
|
_ => Err(ProcessError::Other(e)),
|
|
|
|
},
|
|
|
|
}
|
2021-09-14 01:22:42 +00:00
|
|
|
}
|
|
|
|
|
2023-12-22 19:12:19 +00:00
|
|
|
fn spawn(command: Arc<str>, cmd: &mut Command, timeout: u64) -> std::io::Result<Self> {
|
2023-07-14 00:21:57 +00:00
|
|
|
tracing::trace_span!(parent: None, "Spawn command", %command).in_scope(|| {
|
2023-12-22 19:12:19 +00:00
|
|
|
let guard = MetricsGuard::guard(command.clone());
|
2023-07-22 21:47:59 +00:00
|
|
|
|
2023-07-10 20:29:41 +00:00
|
|
|
let cmd = cmd
|
|
|
|
.stdin(Stdio::piped())
|
|
|
|
.stdout(Stdio::piped())
|
|
|
|
.kill_on_drop(true);
|
2021-09-25 20:23:05 +00:00
|
|
|
|
2023-07-14 00:21:57 +00:00
|
|
|
cmd.spawn().map(|child| Process {
|
|
|
|
child,
|
2023-12-22 19:12:19 +00:00
|
|
|
command,
|
2023-07-22 21:47:59 +00:00
|
|
|
guard,
|
2023-08-05 17:41:06 +00:00
|
|
|
timeout: Duration::from_secs(timeout),
|
2023-12-22 19:12:19 +00:00
|
|
|
id: Uuid::now_v7(),
|
2023-07-14 00:21:57 +00:00
|
|
|
})
|
2022-04-07 17:56:40 +00:00
|
|
|
})
|
2021-08-31 02:19:47 +00:00
|
|
|
}
|
|
|
|
|
2023-12-22 19:12:19 +00:00
|
|
|
#[tracing::instrument(skip(self), fields(command = %self.command, id = %self.id))]
|
2023-08-05 17:41:06 +00:00
|
|
|
pub(crate) async fn wait(self) -> Result<(), ProcessError> {
|
|
|
|
let Process {
|
|
|
|
command,
|
|
|
|
mut child,
|
|
|
|
guard,
|
|
|
|
timeout,
|
2023-12-22 19:12:19 +00:00
|
|
|
id: _,
|
2023-08-05 17:41:06 +00:00
|
|
|
} = self;
|
|
|
|
|
2023-09-05 02:58:57 +00:00
|
|
|
let res = child.wait().with_timeout(timeout).await;
|
2023-07-10 20:29:41 +00:00
|
|
|
|
|
|
|
match res {
|
2023-08-05 17:41:06 +00:00
|
|
|
Ok(Ok(status)) if status.success() => {
|
|
|
|
guard.disarm();
|
2023-07-22 21:47:59 +00:00
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
2023-08-05 17:41:06 +00:00
|
|
|
Ok(Ok(status)) => Err(ProcessError::Status(command, status)),
|
|
|
|
Ok(Err(e)) => Err(ProcessError::Other(e)),
|
|
|
|
Err(_) => {
|
2023-12-23 19:29:30 +00:00
|
|
|
let _ = child.kill().await;
|
2023-08-05 17:41:06 +00:00
|
|
|
Err(ProcessError::Timeout(command))
|
|
|
|
}
|
2021-10-23 19:14:12 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-18 05:14:39 +00:00
|
|
|
pub(crate) fn bytes_read(self, input: Bytes) -> ProcessRead {
|
2022-10-02 02:17:18 +00:00
|
|
|
self.spawn_fn(move |mut stdin| {
|
2022-09-25 22:35:52 +00:00
|
|
|
let mut input = input;
|
|
|
|
async move { stdin.write_all_buf(&mut input).await }
|
|
|
|
})
|
2021-09-04 00:53:53 +00:00
|
|
|
}
|
|
|
|
|
2023-12-18 05:14:39 +00:00
|
|
|
pub(crate) fn read(self) -> ProcessRead {
|
2022-10-02 02:17:18 +00:00
|
|
|
self.spawn_fn(|_| async { Ok(()) })
|
2022-09-25 20:17:33 +00:00
|
|
|
}
|
|
|
|
|
2023-06-01 22:33:43 +00:00
|
|
|
#[allow(unknown_lints)]
|
|
|
|
#[allow(clippy::let_with_type_underscore)]
|
2022-10-02 03:47:52 +00:00
|
|
|
#[tracing::instrument(level = "trace", skip_all)]
|
2023-12-18 05:14:39 +00:00
|
|
|
fn spawn_fn<F, Fut>(self, f: F) -> ProcessRead
|
2022-09-25 22:35:52 +00:00
|
|
|
where
|
|
|
|
F: FnOnce(ChildStdin) -> Fut + 'static,
|
|
|
|
Fut: Future<Output = std::io::Result<()>>,
|
|
|
|
{
|
2023-08-05 17:41:06 +00:00
|
|
|
let Process {
|
|
|
|
command,
|
|
|
|
mut child,
|
|
|
|
guard,
|
|
|
|
timeout,
|
2023-12-22 19:12:19 +00:00
|
|
|
id,
|
2023-08-05 17:41:06 +00:00
|
|
|
} = self;
|
2021-09-04 00:53:53 +00:00
|
|
|
|
2023-08-05 17:41:06 +00:00
|
|
|
let stdin = child.stdin.take().expect("stdin exists");
|
|
|
|
let stdout = child.stdout.take().expect("stdout exists");
|
|
|
|
|
2023-12-23 02:52:58 +00:00
|
|
|
let command2 = command.clone();
|
2023-12-22 19:12:19 +00:00
|
|
|
let handle = Box::pin(async move {
|
|
|
|
let child_fut = async {
|
|
|
|
(f)(stdin).await?;
|
|
|
|
|
|
|
|
child.wait().await
|
|
|
|
};
|
|
|
|
|
2023-12-23 19:29:30 +00:00
|
|
|
match child_fut.with_timeout(timeout).await {
|
2023-12-22 19:12:19 +00:00
|
|
|
Ok(Ok(status)) if status.success() => {
|
|
|
|
guard.disarm();
|
2023-12-23 19:29:30 +00:00
|
|
|
Ok(())
|
2023-12-22 19:12:19 +00:00
|
|
|
}
|
2023-12-23 19:29:30 +00:00
|
|
|
Ok(Ok(status)) => Err(ProcessError::Status(command2, status)),
|
|
|
|
Ok(Err(e)) => Err(ProcessError::Other(e)),
|
|
|
|
Err(_) => {
|
|
|
|
child.kill().await.map_err(ProcessError::Other)?;
|
|
|
|
Err(ProcessError::Timeout(command2))
|
|
|
|
}
|
|
|
|
}
|
2023-12-22 19:12:19 +00:00
|
|
|
});
|
2021-09-04 00:53:53 +00:00
|
|
|
|
2022-04-07 02:40:49 +00:00
|
|
|
ProcessRead {
|
2023-12-23 02:52:58 +00:00
|
|
|
reader: Box::pin(stdout),
|
2023-12-22 19:12:19 +00:00
|
|
|
handle,
|
|
|
|
command,
|
|
|
|
id,
|
2023-12-23 02:52:58 +00:00
|
|
|
extras: Box::new(()),
|
2022-04-07 02:40:49 +00:00
|
|
|
}
|
2021-09-04 00:53:53 +00:00
|
|
|
}
|
2021-08-31 02:19:47 +00:00
|
|
|
}
|
|
|
|
|
2023-12-18 05:14:39 +00:00
|
|
|
impl ProcessRead {
|
2023-12-23 02:52:58 +00:00
|
|
|
pub(crate) fn new(reader: BoxRead<'static>, command: Arc<str>, id: Uuid) -> Self {
|
|
|
|
Self {
|
|
|
|
reader,
|
|
|
|
handle: Box::pin(async { Ok(()) }),
|
|
|
|
command,
|
|
|
|
id,
|
|
|
|
extras: Box::new(()),
|
2023-12-18 05:14:39 +00:00
|
|
|
}
|
|
|
|
}
|
2023-08-05 17:41:06 +00:00
|
|
|
|
2023-12-23 17:58:20 +00:00
|
|
|
pub(crate) async fn into_vec(self) -> Result<Vec<u8>, ProcessError> {
|
2023-12-23 02:52:58 +00:00
|
|
|
let cmd = self.command.clone();
|
|
|
|
|
|
|
|
self.with_stdout(move |mut stdout| async move {
|
|
|
|
let mut vec = Vec::new();
|
2023-12-22 18:03:05 +00:00
|
|
|
|
2023-12-23 02:52:58 +00:00
|
|
|
stdout
|
|
|
|
.read_to_end(&mut vec)
|
|
|
|
.await
|
|
|
|
.map_err(|e| ProcessError::Read(cmd, e))
|
|
|
|
.map(move |_| vec)
|
|
|
|
})
|
|
|
|
.await?
|
2023-12-22 18:03:05 +00:00
|
|
|
}
|
2023-12-18 05:14:39 +00:00
|
|
|
|
2023-12-23 17:58:20 +00:00
|
|
|
pub(crate) async fn into_string(self) -> Result<String, ProcessError> {
|
2023-12-23 02:52:58 +00:00
|
|
|
let cmd = self.command.clone();
|
2023-07-14 00:21:28 +00:00
|
|
|
|
2023-12-23 02:52:58 +00:00
|
|
|
self.with_stdout(move |mut stdout| async move {
|
|
|
|
let mut s = String::new();
|
2023-07-14 00:21:28 +00:00
|
|
|
|
2023-12-23 02:52:58 +00:00
|
|
|
stdout
|
|
|
|
.read_to_string(&mut s)
|
|
|
|
.await
|
|
|
|
.map_err(|e| ProcessError::Read(cmd, e))
|
|
|
|
.map(move |_| s)
|
|
|
|
})
|
|
|
|
.await?
|
2021-09-04 00:53:53 +00:00
|
|
|
}
|
|
|
|
|
2023-12-23 02:52:58 +00:00
|
|
|
pub(crate) async fn with_stdout<Fut>(
|
|
|
|
self,
|
|
|
|
f: impl FnOnce(BoxRead<'static>) -> Fut,
|
|
|
|
) -> Result<Fut::Output, ProcessError>
|
|
|
|
where
|
|
|
|
Fut: Future,
|
|
|
|
{
|
|
|
|
let Self {
|
|
|
|
reader,
|
|
|
|
handle,
|
|
|
|
command,
|
|
|
|
id,
|
2023-12-23 17:58:20 +00:00
|
|
|
mut extras,
|
2023-12-23 02:52:58 +00:00
|
|
|
} = self;
|
2023-12-18 05:14:39 +00:00
|
|
|
|
2023-12-23 02:52:58 +00:00
|
|
|
let (out, res) = tokio::join!(
|
|
|
|
(f)(reader).instrument(tracing::info_span!("cmd-reader", %command, %id)),
|
|
|
|
handle.instrument(tracing::info_span!("cmd-handle", %command, %id))
|
|
|
|
);
|
2023-12-18 05:14:39 +00:00
|
|
|
|
2023-12-23 17:58:20 +00:00
|
|
|
extras
|
|
|
|
.consume()
|
|
|
|
.await
|
|
|
|
.map_err(|e| ProcessError::Cleanup(command, e))?;
|
|
|
|
|
|
|
|
res?;
|
2023-12-18 05:14:39 +00:00
|
|
|
|
2023-12-23 02:52:58 +00:00
|
|
|
Ok(out)
|
2023-12-18 05:14:39 +00:00
|
|
|
}
|
|
|
|
|
2023-12-23 17:58:20 +00:00
|
|
|
pub(crate) fn add_extras<E: Extras + 'static>(self, more_extras: E) -> ProcessRead {
|
2023-12-23 02:52:58 +00:00
|
|
|
let Self {
|
|
|
|
reader,
|
|
|
|
handle,
|
|
|
|
command,
|
|
|
|
id,
|
|
|
|
extras,
|
|
|
|
} = self;
|
2023-12-18 05:14:39 +00:00
|
|
|
|
2023-12-23 02:52:58 +00:00
|
|
|
Self {
|
|
|
|
reader,
|
|
|
|
handle,
|
|
|
|
command,
|
|
|
|
id,
|
|
|
|
extras: Box::new((extras, more_extras)),
|
2023-12-18 05:14:39 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-09 19:16:12 +00:00
|
|
|
impl std::fmt::Display for StatusError {
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
2023-07-14 00:21:28 +00:00
|
|
|
write!(f, "Command failed with bad status: {}", self.0)
|
2021-09-09 19:16:12 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl std::error::Error for StatusError {}
|