#[cfg(unix)]
use super::AdoptedReaper;
use super::dog_link::DogLink;
use super::log_protocol::{ExitOutcome, LogCtl, LogLine};
use crate::channel::{ChildMessage, ShepherdMessage};
use crate::privilege::Credentials;
use bytes::Bytes;
use core::fmt;
use core::sync::atomic::{AtomicBool, Ordering};
use shep_core::signals::OperatorSignal;
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::{Arc, Weak};
use tokio::sync::{broadcast, 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>,
pub pty: Option<PtyHandle>,
}
#[derive(Debug)]
#[cfg_attr(
windows,
allow(dead_code, reason = "only the unix pty pump reads these")
)]
pub(crate) enum PtyCommand {
Input {
bytes: Vec<u8>,
done: oneshot::Sender<Result<(), PtyError>>,
},
Resize {
rows: u16,
cols: u16,
done: oneshot::Sender<Result<(), PtyError>>,
},
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PtyError {
Gone,
Failed(String),
}
impl fmt::Display for PtyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Gone => f.write_str("the sheep's terminal has closed"),
Self::Failed(msg) => write!(f, "terminal write failed: {msg}"),
}
}
}
impl core::error::Error for PtyError {}
#[derive(Debug, Clone)]
pub struct PtyHandle {
output: Weak<broadcast::Sender<Bytes>>,
control: mpsc::Sender<PtyCommand>,
closed: Arc<AtomicBool>,
}
impl PtyHandle {
pub(crate) fn new(
output: &Arc<broadcast::Sender<Bytes>>,
control: mpsc::Sender<PtyCommand>,
closed: Arc<AtomicBool>,
) -> Self {
Self {
output: Arc::downgrade(output),
control,
closed,
}
}
#[must_use]
pub fn subscribe(&self) -> broadcast::Receiver<Bytes> {
match self.output.upgrade() {
Some(output) => output.subscribe(),
None => broadcast::channel(1).1,
}
}
pub async fn send(&self, bytes: Vec<u8>) -> Result<(), PtyError> {
self.ask(|done| PtyCommand::Input { bytes, done }).await
}
pub async fn resize(&self, rows: u16, cols: u16) -> Result<(), PtyError> {
self.ask(|done| PtyCommand::Resize { rows, cols, done })
.await
}
#[must_use]
pub fn is_closed(&self) -> bool {
self.closed.load(Ordering::Acquire) || self.control.is_closed()
}
async fn ask(
&self,
command: impl FnOnce(oneshot::Sender<Result<(), PtyError>>) -> PtyCommand,
) -> Result<(), PtyError> {
if self.is_closed() {
return Err(PtyError::Gone);
}
let (done, answer) = oneshot::channel();
self.control
.send(command(done))
.await
.map_err(|_| PtyError::Gone)?;
answer.await.map_err(|_| PtyError::Gone)?
}
}
#[derive(Debug)]
pub struct StdinWrite {
pub line: String,
pub done: oneshot::Sender<Result<(), RunnerError>>,
}
#[cfg(unix)]
#[derive(Debug)]
pub struct AdoptSpec {
pub name: String,
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 log_timestamps: bool,
pub leader_only_stop: bool,
pub stdin_pipe: Option<tokio::net::unix::pipe::Sender>,
pub channel: Option<tokio::net::UnixStream>,
pub dog_link: Option<tokio::net::UnixStream>,
pub pty: Option<std::fs::File>,
pub dog_topics: Option<Vec<String>>,
pub launch_dog: Option<String>,
pub reaper: std::sync::Arc<AdoptedReaper>,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Preflight {
Unknown,
Impossible(String),
Doubtful(String),
}
#[derive(Clone, Default, 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 log_timestamps: bool,
pub channel: bool,
pub stdin: bool,
pub pty: bool,
pub credentials: Option<Credentials>,
pub dog_link: bool,
pub launch_link: Option<String>,
pub leader_only_stop: bool,
pub listen: Option<std::sync::Arc<crate::listen::ListenSockets>>,
pub cgroup: Option<PathBuf>,
pub memory_max: Option<u64>,
pub cpu_quota: Option<u64>,
pub pids_max: Option<u32>,
}
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()))
.field("pty", &self.pty)
.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
}
fn dog_links(&self) -> Option<mpsc::UnboundedReceiver<DogLink>> {
None
}
#[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 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()],
..Default::default()
};
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>, pty: false, .. }"
);
}
}