#[cfg(unix)]
use super::AdoptedReaper;
use super::log_protocol::{ExitOutcome, LogCtl, LogLine};
use crate::channel::{ChildMessage, ShepherdMessage};
use crate::privilege::Credentials;
use core::fmt;
use shep_core::signals::OperatorSignal;
use std::collections::BTreeMap;
use std::path::PathBuf;
use tokio::sync::{mpsc, oneshot};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StopSignal {
Term,
Int,
Quit,
Usr2,
Kill,
}
impl StopSignal {
#[must_use]
pub fn as_raw(self) -> i32 {
match self {
Self::Term => 15,
Self::Int => 2,
Self::Quit => 3,
Self::Usr2 => 12,
Self::Kill => 9,
}
}
}
#[derive(Debug)]
pub struct ProcIo {
pub logs: mpsc::Receiver<LogLine>,
pub from_child: mpsc::Receiver<ChildMessage>,
pub to_child: mpsc::Sender<ShepherdMessage>,
pub log_ctl: mpsc::Sender<LogCtl>,
pub to_stdin: mpsc::Sender<StdinWrite>,
}
#[derive(Debug)]
pub struct StdinWrite {
pub line: String,
pub done: oneshot::Sender<Result<(), RunnerError>>,
}
#[cfg(unix)]
#[derive(Debug)]
pub struct AdoptSpec {
pub pid: u32,
pub out_file: PathBuf,
pub err_file: PathBuf,
pub out_pipe: Option<tokio::net::unix::pipe::Receiver>,
pub err_pipe: Option<tokio::net::unix::pipe::Receiver>,
pub out_log: Option<tokio::fs::File>,
pub err_log: Option<tokio::fs::File>,
pub stdin_pipe: Option<tokio::net::unix::pipe::Sender>,
pub channel: Option<tokio::net::UnixStream>,
pub reaper: std::sync::Arc<AdoptedReaper>,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Preflight {
Unknown,
Impossible(String),
Doubtful(String),
}
#[derive(Clone, PartialEq, Eq)]
pub struct SpawnSpec {
pub name: String,
pub program: String,
pub args: Vec<String>,
pub cwd: Option<PathBuf>,
pub env: BTreeMap<String, String>,
pub out_file: PathBuf,
pub err_file: PathBuf,
pub channel: bool,
pub stdin: bool,
pub credentials: Option<Credentials>,
}
impl fmt::Debug for SpawnSpec {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SpawnSpec")
.field("name", &self.name)
.field("program", &self.program)
.field("args", &format_args!("<{} args>", self.args.len()))
.field("cwd", &self.cwd)
.field("env", &format_args!("<{} vars>", self.env.len()))
.finish_non_exhaustive()
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RunnerError {
SpawnFailed(String),
SignalFailed(String),
WriteFailed(String),
AdoptFailed(String),
}
impl fmt::Display for RunnerError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::SpawnFailed(msg) => write!(f, "process spawn failed: {msg}"),
Self::SignalFailed(msg) => write!(f, "signal delivery failed: {msg}"),
Self::WriteFailed(msg) => write!(f, "stdin write failed: {msg}"),
Self::AdoptFailed(msg) => write!(f, "process adoption failed: {msg}"),
}
}
}
impl core::error::Error for RunnerError {}
pub trait RunningProcess: Send + 'static {
fn pid(&self) -> u32;
fn wait(&mut self) -> impl core::future::Future<Output = ExitOutcome> + Send;
fn signal(&mut self, sig: StopSignal) -> Result<(), RunnerError>;
fn signal_process(&mut self, sig: OperatorSignal) -> Result<(), RunnerError> {
let _ = sig;
Err(RunnerError::SignalFailed(
"this runner cannot signal a single process".to_string(),
))
}
fn kill_tree(&mut self) -> Result<(), RunnerError>;
}
pub trait ProcessRunner: Send + Sync + 'static {
type Proc: RunningProcess;
fn spawn(&self, spec: &SpawnSpec) -> Result<(Self::Proc, ProcIo), RunnerError>;
#[must_use]
fn preflight(&self, spec: &SpawnSpec) -> Preflight {
let _ = spec;
Preflight::Unknown
}
#[cfg(unix)]
fn adopt(&self, spec: AdoptSpec) -> Result<(Self::Proc, ProcIo), RunnerError> {
let _ = spec;
Err(RunnerError::AdoptFailed(
"this runner cannot adopt a process it did not spawn".to_string(),
))
}
}
#[cfg(all(test, unix))]
mod tests {
use std::collections::BTreeMap;
use std::path::PathBuf;
use super::*;
#[test]
fn debug_redacts_env_values_and_args() {
let mut spec = SpawnSpec {
name: "web".to_string(),
program: "./srv".to_string(),
args: vec!["--token=sk-live-abc".to_string(), "--port=8080".to_string()],
cwd: None,
env: BTreeMap::new(),
out_file: PathBuf::from("/tmp/web-out.log"),
err_file: PathBuf::from("/tmp/web-err.log"),
channel: false,
stdin: false,
credentials: None,
};
spec.env.insert(
"DATABASE_URL".to_string(),
"postgres://user:hunter2@db".to_string(),
);
spec.env
.insert("API_KEY".to_string(), "sk-live-abc".to_string());
assert_eq!(
format!("{spec:?}"),
"SpawnSpec { name: \"web\", program: \"./srv\", args: <2 args>, cwd: None, \
env: <2 vars>, .. }"
);
}
}