use std::ffi::OsString;
use std::io;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::Duration;
use tokio::time::Instant;
use super::liveness::{ProcessTable, refuse_other_instances, refuse_unserved_daemon};
use super::process::{Dial, PinnedProcess, Signal, dial};
use super::stop::{KernelDelivery, SignalDelivery, StopOutcome, stop_with_table};
use super::{DaemonDescriptor, LifecycleError, POLL_INTERVAL};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct StartOutcome {
pub pid: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct RestartOutcome {
pub stop: StopOutcome,
pub start: StartOutcome,
}
pub async fn start(desc: &DaemonDescriptor) -> Result<StartOutcome, LifecycleError> {
start_with_table(desc, &ProcessTable::system()).await
}
pub async fn start_with_table(
desc: &DaemonDescriptor,
table: &ProcessTable,
) -> Result<StartOutcome, LifecycleError> {
desc.validate()?;
let program = installed_program(desc)?;
match dial(&desc.socket).await {
Dial::NotServing => {}
Dial::Peer(pid) => {
return Err(LifecycleError::AlreadyRunning {
socket: desc.socket.clone(),
pid,
});
}
Dial::Inconclusive => {
return Err(LifecycleError::ProbeInconclusive {
socket: desc.socket.clone(),
});
}
}
refuse_unserved_daemon(desc, table)?;
let pid = spawn(desc, &program)?;
let child = match PinnedProcess::open(pid) {
Ok(Some(child)) => child,
Ok(None) => return Err(LifecycleError::ChildExited { pid }),
Err(e) => {
let source = match e {
LifecycleError::Io { source, .. } => source,
other => io::Error::other(other.to_string()),
};
let killed = kill_and_reap(pid, None, desc.kill_wait).await;
return Err(LifecycleError::ChildUnpinned {
pid,
killed,
source,
});
}
};
let deadline = Instant::now() + desc.ready_timeout;
loop {
if child.has_exited() {
kill_and_reap(pid, Some(&child), desc.kill_wait).await;
return Err(LifecycleError::ChildExited { pid });
}
if let Dial::Peer(Some(peer)) = dial(&desc.socket).await
&& peer == pid
{
return Ok(StartOutcome { pid });
}
if Instant::now() >= deadline {
let killed = kill_and_reap(pid, Some(&child), desc.kill_wait).await;
return Err(LifecycleError::NotReady {
pid,
timeout: desc.ready_timeout,
killed,
});
}
tokio::time::sleep(POLL_INTERVAL).await;
}
}
pub(crate) fn installed_program(desc: &DaemonDescriptor) -> Result<PathBuf, LifecycleError> {
let program = desc.program();
if !program.is_file() {
return Err(LifecycleError::BinaryMissing { path: program });
}
Ok(program)
}
fn spawn(desc: &DaemonDescriptor, program: &Path) -> Result<u32, LifecycleError> {
let mut cmd = std::process::Command::new(program);
cmd.args(&desc.spawn_args)
.current_dir(&desc.working_dir)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.env_clear()
.envs(daemon_env(desc, |name| std::env::var_os(name)));
crate::daemon_guard::start_in_new_session(&mut cmd);
crate::child_fds::seal_inherited(&mut cmd);
let child = cmd.spawn().map_err(|e| LifecycleError::Spawn {
program: program.to_path_buf(),
message: e.to_string(),
})?;
Ok(child.id())
}
pub(crate) fn daemon_env(
desc: &DaemonDescriptor,
lookup: impl Fn(&str) -> Option<OsString>,
) -> Vec<(String, OsString)> {
let pinned = |name: &str| desc.instance_env.iter().any(|(n, _)| n == name);
let instance = desc
.instance_env
.iter()
.filter_map(|(name, value)| Some((name.clone(), value.clone()?)));
DaemonDescriptor::BASE_ENV
.iter()
.copied()
.chain(desc.env_passthrough.iter().map(String::as_str))
.filter(|name| !pinned(name))
.filter_map(|name| Some((name.to_string(), lookup(name)?)))
.chain(instance)
.collect()
}
async fn kill_and_reap(pid: u32, pinned: Option<&PinnedProcess>, limit: Duration) -> bool {
let Ok(raw) = libc::pid_t::try_from(pid) else {
return false;
};
match pinned {
Some(child) => {
let _ = child.send_signal(Signal::Kill);
}
None => unsafe {
libc::kill(raw, libc::SIGKILL);
},
}
let deadline = Instant::now() + limit;
loop {
let mut status: libc::c_int = 0;
let rc = unsafe { libc::waitpid(raw, &raw mut status, libc::WNOHANG) };
if rc == raw {
return true;
}
if rc < 0 {
match io::Error::last_os_error().raw_os_error() {
Some(libc::EINTR) => continue,
Some(libc::ECHILD) => return true,
_ => return false,
}
}
if Instant::now() >= deadline {
return false;
}
tokio::time::sleep(POLL_INTERVAL).await;
}
}
pub async fn restart(desc: &DaemonDescriptor) -> Result<RestartOutcome, LifecycleError> {
restart_with(desc, &KernelDelivery).await
}
pub async fn restart_with(
desc: &DaemonDescriptor,
delivery: &dyn SignalDelivery,
) -> Result<RestartOutcome, LifecycleError> {
restart_with_table(desc, delivery, &ProcessTable::system()).await
}
pub async fn restart_with_table(
desc: &DaemonDescriptor,
delivery: &dyn SignalDelivery,
table: &ProcessTable,
) -> Result<RestartOutcome, LifecycleError> {
desc.validate()?;
installed_program(desc)?;
refuse_restart_blockers(desc, table).await?;
let stop = stop_with_table(desc, delivery, table).await?;
let start = start_with_table(desc, table).await?;
Ok(RestartOutcome { stop, start })
}
async fn refuse_restart_blockers(
desc: &DaemonDescriptor,
table: &ProcessTable,
) -> Result<(), LifecycleError> {
match dial(&desc.socket).await {
Dial::Peer(Some(peer)) => refuse_other_instances(desc, &[peer], table),
_ => Ok(()),
}
}