pub(crate) mod adopt;
mod fds;
pub(crate) mod reap;
pub(crate) mod uptime;
use core::convert::Infallible;
use std::ffi::CString;
use std::fs::{self, OpenOptions};
use std::io;
use std::os::fd::RawFd;
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use std::time::SystemTime;
use serde::{Deserialize, Serialize};
use shep_core::config::AppConfig;
use shep_core::paths::ShepPaths;
use shep_core::protocol::{DogSource, ExitInfo};
use shep_core::status::ProcStatus;
use crate::entry::{ProcessEntry, ReloadState};
use crate::privilege::SpawnIdentity;
use crate::supervisor::{CarriedReload, PendingManual};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Fitness {
Carryable,
Refused(RefusedReason),
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum RefusedReason {
PumpUnresponsive {
sheep: String,
},
}
impl core::fmt::Display for RefusedReason {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::PumpUnresponsive { sheep } => write!(
f,
"sheep '{sheep}' has a log pump that did not report its descriptors in \
time; reload falls back to a stop-and-start instead"
),
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct Candidate<'a> {
pub entry: &'a ProcessEntry,
pub pump_unresponsive: bool,
}
#[derive(Debug, Clone)]
pub struct OwnedCandidate {
pub entry: ProcessEntry,
pub pump_unresponsive: bool,
}
impl OwnedCandidate {
#[must_use]
pub fn as_candidate(&self) -> Candidate<'_> {
Candidate {
entry: &self.entry,
pump_unresponsive: self.pump_unresponsive,
}
}
}
#[must_use]
pub fn fitness(sheep: &[Candidate<'_>]) -> Fitness {
for candidate in sheep {
if let Some(reason) = refusal(candidate) {
return Fitness::Refused(reason);
}
}
Fitness::Carryable
}
fn refusal(candidate: &Candidate<'_>) -> Option<RefusedReason> {
let entry = candidate.entry;
let config = entry.spec.config();
let name = || config.name.clone();
if candidate.pump_unresponsive {
return Some(RefusedReason::PumpUnresponsive { sheep: name() });
}
None
}
pub const VERSION: u32 = 1;
const FILE_NAME: &str = "handover.json";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Handover {
version: u32,
sheep: Vec<CarriedSheep>,
listener_fd: RawFd,
pidfile_fd: RawFd,
next_id: u32,
next_deadline: u64,
next_action_stamp: u64,
reloads: Option<Vec<CarriedReload>>,
}
impl Handover {
#[must_use]
pub fn new(
sheep: Vec<CarriedSheep>,
fds: DaemonFds,
counters: Counters,
reloads: Vec<CarriedReload>,
) -> Self {
Self {
version: VERSION,
sheep,
listener_fd: fds.listener,
pidfile_fd: fds.pidfile,
next_id: counters.next_id,
next_deadline: counters.next_deadline,
next_action_stamp: counters.next_action_stamp,
reloads: Some(reloads),
}
}
#[must_use]
#[allow(dead_code, reason = "read by this crate's own tests")]
pub fn sheep(&self) -> &[CarriedSheep] {
&self.sheep
}
#[must_use]
#[allow(dead_code, reason = "read by this crate's own tests")]
pub const fn next_id(&self) -> u32 {
self.next_id
}
#[must_use]
pub const fn counters(&self) -> Counters {
Counters {
next_id: self.next_id,
next_deadline: self.next_deadline,
next_action_stamp: self.next_action_stamp,
}
}
#[must_use]
pub fn reloads(&self) -> &[CarriedReload] {
self.reloads.as_deref().unwrap_or_default()
}
#[must_use]
pub fn path(paths: &ShepPaths) -> PathBuf {
paths.run.join(FILE_NAME)
}
fn named_fds(&self) -> impl Iterator<Item = RawFd> + '_ {
[self.listener_fd, self.pidfile_fd].into_iter().chain(
self.sheep
.iter()
.flat_map(|sheep| sheep.fds.all().into_iter().flatten()),
)
}
pub fn write(&self, paths: &ShepPaths) -> io::Result<PathBuf> {
let path = Self::path(paths);
match fs::remove_file(&path) {
Ok(()) => {}
Err(err) if err.kind() == io::ErrorKind::NotFound => {}
Err(err) => return Err(err),
}
let file = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(&path)?;
serde_json::to_writer(&file, self).map_err(io::Error::other)?;
Ok(path)
}
pub fn read(path: &Path) -> Result<Self, LoadError> {
let text = fs::read_to_string(path).map_err(LoadError::Io)?;
let value = serde_json::from_str(&text).map_err(LoadError::Malformed)?;
Self::load_value(value)
}
pub fn load_value(value: serde_json::Value) -> Result<Self, LoadError> {
match value.get("version").and_then(serde_json::Value::as_u64) {
Some(found) if found == u64::from(VERSION) => {}
Some(found) => return Err(LoadError::UnsupportedVersion { found }),
None => return Err(LoadError::MissingVersion),
}
serde_json::from_value(value).map_err(LoadError::Malformed)
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum LoadError {
Io(io::Error),
MissingVersion,
UnsupportedVersion {
found: u64,
},
Malformed(serde_json::Error),
}
impl core::fmt::Display for LoadError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Io(err) => write!(f, "the handover blob could not be read: {err}"),
Self::MissingVersion => f.write_str("the handover blob names no format version"),
Self::UnsupportedVersion { found } => write!(
f,
"the handover blob is format version {found}, and this shep implements \
version {VERSION}"
),
Self::Malformed(err) => write!(f, "the handover blob is not readable: {err}"),
}
}
}
impl core::error::Error for LoadError {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match self {
Self::Io(err) => Some(err),
Self::Malformed(err) => Some(err),
Self::MissingVersion | Self::UnsupportedVersion { .. } => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DaemonFds {
pub listener: RawFd,
pub pidfile: RawFd,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Counters {
pub next_id: u32,
pub next_deadline: u64,
pub next_action_stamp: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CarriedSheep {
id: u32,
name: String,
instance: u32,
pid: Option<u32>,
restarts: u32,
epoch: u64,
status: ProcStatus,
last_exit: Option<ExitInfo>,
credentials: SpawnIdentity,
fds: CarriedFds,
pending_delete: Option<bool>,
manual: Option<PendingManual>,
reload: Option<ReloadState>,
ready_failed: Option<bool>,
restart_due: Option<SystemTime>,
dog: Option<DogSource>,
pending: Option<AppConfig>,
pending_reidentifies: Option<bool>,
app: AppConfig,
}
impl CarriedSheep {
#[must_use]
pub fn from_entry(
entry: &ProcessEntry,
epoch: u64,
fds: CarriedFds,
pending_delete: bool,
manual: Option<PendingManual>,
ready_failed: bool,
restart_due: Option<SystemTime>,
) -> Self {
Self {
id: entry.id,
name: entry.spec.config().name.clone(),
instance: entry.instance,
pid: entry.pid,
restarts: entry.restarts,
epoch,
status: entry.status,
last_exit: entry.last_exit,
credentials: entry.credentials,
fds,
pending_delete: Some(pending_delete),
manual,
reload: Some(entry.reload),
dog: entry.dog.clone(),
pending: entry.pending.as_ref().map(|parked| parked.config().clone()),
pending_reidentifies: entry.pending.as_ref().map(|_| entry.pending_reidentifies),
ready_failed: Some(ready_failed),
restart_due: (entry.status == ProcStatus::WaitingRestart)
.then_some(restart_due)
.flatten(),
app: entry.spec.config().clone(),
}
}
#[must_use]
#[allow(dead_code, reason = "read by this crate's own tests")]
pub const fn fds(&self) -> CarriedFds {
self.fds
}
#[must_use]
pub const fn pending_delete(&self) -> Option<bool> {
self.pending_delete
}
#[must_use]
pub const fn manual(&self) -> Option<PendingManual> {
self.manual
}
#[must_use]
pub const fn reload(&self) -> Option<ReloadState> {
self.reload
}
#[must_use]
pub const fn dog(&self) -> Option<&DogSource> {
self.dog.as_ref()
}
#[must_use]
pub const fn pending(&self) -> Option<&AppConfig> {
self.pending.as_ref()
}
#[must_use]
pub const fn pending_reidentifies(&self) -> Option<bool> {
self.pending_reidentifies
}
#[must_use]
pub const fn ready_failed(&self) -> Option<bool> {
self.ready_failed
}
#[must_use]
pub const fn restart_due(&self) -> Option<SystemTime> {
self.restart_due
}
#[must_use]
pub const fn epoch(&self) -> u64 {
self.epoch
}
#[must_use]
pub const fn id(&self) -> u32 {
self.id
}
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
#[must_use]
pub const fn instance(&self) -> u32 {
self.instance
}
#[must_use]
pub const fn pid(&self) -> Option<u32> {
self.pid
}
#[must_use]
pub const fn restarts(&self) -> u32 {
self.restarts
}
#[must_use]
pub const fn status(&self) -> ProcStatus {
self.status
}
#[must_use]
pub const fn last_exit(&self) -> Option<ExitInfo> {
self.last_exit
}
#[must_use]
pub const fn credentials(&self) -> SpawnIdentity {
self.credentials
}
#[must_use]
pub const fn app(&self) -> &AppConfig {
&self.app
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct CarriedFds {
pub out_pipe: Option<RawFd>,
pub err_pipe: Option<RawFd>,
pub out_log: Option<RawFd>,
pub err_log: Option<RawFd>,
pub stdin: Option<RawFd>,
pub channel: Option<RawFd>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum SheepFd {
OutPipe,
ErrPipe,
OutLog,
ErrLog,
Stdin,
Channel,
}
impl SheepFd {
pub(crate) const fn describe(self) -> &'static str {
match self {
Self::OutPipe => "stdout pipe",
Self::ErrPipe => "stderr pipe",
Self::OutLog => "stdout log",
Self::ErrLog => "stderr log",
Self::Stdin => "stdin pipe",
Self::Channel => "shepherd channel",
}
}
}
impl CarriedFds {
#[must_use]
pub const fn all(&self) -> [Option<RawFd>; 6] {
[
self.out_pipe,
self.err_pipe,
self.out_log,
self.err_log,
self.stdin,
self.channel,
]
}
pub(crate) const fn all_kinded(&self) -> [(Option<RawFd>, SheepFd); 6] {
[
(self.out_pipe, SheepFd::OutPipe),
(self.err_pipe, SheepFd::ErrPipe),
(self.out_log, SheepFd::OutLog),
(self.err_log, SheepFd::ErrLog),
(self.stdin, SheepFd::Stdin),
(self.channel, SheepFd::Channel),
]
}
#[must_use]
pub const fn none() -> Self {
Self {
out_pipe: None,
err_pipe: None,
out_log: None,
err_log: None,
stdin: None,
channel: None,
}
}
}
static LAUNCH_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
pub fn record_launch_path() {
let _ = LAUNCH_PATH.set(launch_path_from_argv());
}
pub fn exec_target() -> io::Result<PathBuf> {
let recorded = LAUNCH_PATH.get().cloned().flatten();
let current = std::env::current_exe();
resolve_target(
[recorded, current.as_deref().ok().map(Path::to_path_buf)],
current.as_ref().err(),
)
}
pub(crate) fn resolve_target(
candidates: [Option<PathBuf>; 2],
current_exe_error: Option<&io::Error>,
) -> io::Result<PathBuf> {
let mut refusals = Vec::new();
for candidate in candidates {
let Some(candidate) = candidate else { continue };
match check_target(&candidate) {
Ok(()) => return Ok(candidate),
Err(problem) => refusals.push(format!("{} ({problem})", candidate.display())),
}
}
if let Some(e) = current_exe_error {
refusals.push(format!("this process's own image ({e})"));
}
if refusals.is_empty() {
refusals.push("no candidate at all".to_owned());
}
Err(io::Error::new(
io::ErrorKind::NotFound,
format!("no binary to exec: {}", refusals.join("; ")),
))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TargetProblem {
DeletedInode,
Missing,
NotAFile,
}
impl core::fmt::Display for TargetProblem {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let text = match self {
Self::DeletedInode => "names a deleted inode, not a file",
Self::Missing => "is not on disk",
Self::NotAFile => "is not a file",
};
f.write_str(text)
}
}
fn check_target(candidate: &Path) -> Result<(), TargetProblem> {
if candidate.to_string_lossy().contains(" (deleted)") {
return Err(TargetProblem::DeletedInode);
}
match std::fs::metadata(candidate) {
Ok(meta) if meta.is_file() => Ok(()),
Ok(_) => Err(TargetProblem::NotAFile),
Err(_) => Err(TargetProblem::Missing),
}
}
fn launch_path_from_argv() -> Option<PathBuf> {
let argv0 = PathBuf::from(std::env::args_os().next()?);
if argv0.as_os_str().is_empty() {
return None;
}
if argv0.is_absolute() {
return Some(argv0);
}
let has_separator = argv0
.parent()
.is_some_and(|dir| !dir.as_os_str().is_empty());
has_separator.then(|| std::env::current_dir().ok().map(|cwd| cwd.join(&argv0)))?
}
pub const HANDOVER_ENV: &str = "SHEP_HANDOVER";
pub fn hand_over(blob: &Handover, paths: &ShepPaths) -> io::Result<Infallible> {
exec_into(&exec_target()?, blob, paths)
}
fn exec_into(target: &Path, blob: &Handover, paths: &ShepPaths) -> io::Result<Infallible> {
let written = blob.write(paths)?;
let failure = match exec_with_blob(target, blob, &written) {
Ok(never) => match never {},
Err(err) => err,
};
match fs::remove_file(&written) {
Ok(()) | Err(_) => Err(failure),
}
}
fn exec_with_blob(target: &Path, blob: &Handover, written: &Path) -> io::Result<Infallible> {
let mut cleared = Vec::new();
let failure = match keep_and_exec(target, blob, written, &mut cleared) {
Ok(never) => match never {},
Err(err) => err,
};
for fd in cleared {
let _ = fds::close_raw_after_exec(fd);
}
Err(failure)
}
fn keep_and_exec(
target: &Path,
blob: &Handover,
written: &Path,
cleared: &mut Vec<RawFd>,
) -> io::Result<Infallible> {
for fd in blob.named_fds() {
fds::keep_raw_across_exec(fd)?;
cleared.push(fd);
}
let path = c_string(target.as_os_str().as_bytes())?;
let argv = std::env::args_os()
.map(|arg| c_string(arg.as_bytes()))
.collect::<io::Result<Vec<_>>>()?;
let env = successor_env(written)?;
nix::unistd::execve(&path, &argv, &env).map_err(io::Error::from)
}
fn successor_env(written: &Path) -> io::Result<Vec<CString>> {
let mut env = std::env::vars_os()
.filter(|(name, _)| name != HANDOVER_ENV)
.map(|(name, value)| {
let mut entry = name.into_vec();
entry.push(b'=');
entry.extend(value.into_vec());
c_string(&entry)
})
.collect::<io::Result<Vec<_>>>()?;
let mut marker = HANDOVER_ENV.as_bytes().to_vec();
marker.push(b'=');
marker.extend(written.as_os_str().as_bytes());
env.push(c_string(&marker)?);
Ok(env)
}
fn c_string(bytes: &[u8]) -> io::Result<CString> {
CString::new(bytes).map_err(io::Error::other)
}
#[cfg(test)]
mod tests {
use shep_core::status::ProcStatus;
use std::path::PathBuf;
use std::os::unix::fs::PermissionsExt;
use super::*;
use crate::entry::{ReloadState, RestartBudget};
use crate::privilege::SpawnIdentity;
use crate::supervisor::{CommandOrigin, ManualKind, ReloadMode, ReloadPhase, ReloadSwap};
use crate::testing::{app_with, test_paths};
fn entry_fixture(mutate: impl FnOnce(&mut AppConfig)) -> ProcessEntry {
let spec = app_with("web", mutate);
ProcessEntry {
id: 1,
spec,
pending: None,
pending_reidentifies: false,
overridden: Vec::new(),
instance: 0,
status: ProcStatus::Online,
pid: Some(100),
restarts: 0,
started_at: None,
budget: RestartBudget::default(),
reload: ReloadState::None,
credentials: SpawnIdentity::Resolved(None),
out_file: PathBuf::from("/tmp/shep-handover-test-out.log"),
err_file: PathBuf::from("/tmp/shep-handover-test-err.log"),
dog: None,
last_exit: None,
}
}
fn plain(entry: &ProcessEntry) -> Candidate<'_> {
Candidate {
entry,
pump_unresponsive: false,
}
}
fn wedged(entry: &ProcessEntry) -> Candidate<'_> {
Candidate {
entry,
pump_unresponsive: true,
}
}
#[test]
fn a_plain_sheep_is_carryable() {
let e = entry_fixture(|_| {});
assert_eq!(fitness(&[plain(&e)]), Fitness::Carryable);
}
#[test]
fn one_unsupported_sheep_refuses_the_whole_flock() {
let carryable = entry_fixture(|_| {});
let unsupported = entry_fixture(|_| {});
assert!(matches!(
fitness(&[plain(&carryable), wedged(&unsupported)]),
Fitness::Refused(_)
));
}
#[test]
fn the_refusal_names_which_sheep_and_why() {
let unsupported = entry_fixture(|_| {});
let Fitness::Refused(r) = fitness(&[wedged(&unsupported)]) else {
panic!("expected a refusal")
};
let text = r.to_string();
assert!(text.contains("did not report its descriptors"), "{text}");
assert!(text.contains("web"), "{text}");
assert!(
text.contains("falls back to a stop-and-start"),
"the refusal must say what happens instead, not only that it declined: {text}"
);
}
#[test]
fn a_pump_that_did_not_report_in_time_refuses_as_a_fault_not_a_feature() {
let e = entry_fixture(|_| {});
let candidate = Candidate {
entry: &e,
pump_unresponsive: true,
};
let Fitness::Refused(r) = fitness(&[candidate]) else {
panic!("a sheep whose descriptors are unknown cannot be carried")
};
let text = r.to_string();
assert!(
text.contains("did not report its descriptors in time"),
"{text}"
);
assert!(
!text.contains("cannot yet"),
"a wedged pump is not a feature a later phase ships: {text}"
);
}
#[test]
fn an_empty_flock_is_carryable() {
assert_eq!(fitness(&[]), Fitness::Carryable);
}
#[test]
fn a_sheep_with_a_channel_is_carried() {
let e = entry_fixture(|app| app.channel = true);
assert_eq!(fitness(&[plain(&e)]), Fitness::Carryable);
}
#[test]
fn wait_ready_alone_is_carried() {
let e = entry_fixture(|app| app.wait_ready = true);
assert_eq!(fitness(&[plain(&e)]), Fitness::Carryable);
}
#[test]
fn shutdown_with_message_alone_is_carried() {
let e = entry_fixture(|app| app.shutdown_with_message = true);
assert_eq!(fitness(&[plain(&e)]), Fitness::Carryable);
}
#[test]
fn a_sheep_with_stdin_is_carried() {
let e = entry_fixture(|app| app.stdin = true);
assert_eq!(fitness(&[plain(&e)]), Fitness::Carryable);
}
#[test]
fn a_dog_is_carried_rather_than_refused() {
let mut built_in = entry_fixture(|_| {});
built_in.dog = Some(DogSource::BuiltIn);
assert_eq!(fitness(&[plain(&built_in)]), Fitness::Carryable);
let mut adopted = entry_fixture(|_| {});
adopted.dog = Some(DogSource::Adopted {
path: "/opt/bin/shep-log-rotate".to_string(),
});
assert_eq!(fitness(&[plain(&adopted)]), Fitness::Carryable);
}
#[test]
fn an_app_with_more_than_one_instance_is_carried() {
let mut zero = entry_fixture(|app| app.instances = 2);
let mut one = entry_fixture(|app| app.instances = 2);
one.id = 2;
one.instance = 1;
one.pid = Some(101);
assert_eq!(fitness(&[plain(&zero), plain(&one)]), Fitness::Carryable);
zero.instance = 1;
one.instance = 0;
assert_eq!(fitness(&[plain(&one), plain(&zero)]), Fitness::Carryable);
}
#[test]
fn each_instance_carries_its_own_slot_and_descriptors() {
let mut zero = entry_fixture(|app| app.instances = 2);
zero.instance = 0;
let mut one = entry_fixture(|app| app.instances = 2);
one.id = 2;
one.instance = 1;
one.pid = Some(101);
let blob = Handover::new(
vec![
CarriedSheep::from_entry(&zero, 7, fds_at(11), false, None, false, None),
CarriedSheep::from_entry(&one, 8, fds_at(21), false, None, false, None),
],
DaemonFds {
listener: 3,
pidfile: 4,
},
Counters {
next_id: 9,
next_deadline: 5,
next_action_stamp: 2,
},
Vec::new(),
);
let back: Handover = serde_json::from_str(&serde_json::to_string(&blob).unwrap()).unwrap();
let carried = back.sheep();
assert_eq!(carried.len(), 2, "one row per instance, never per app");
let slot_zero = carried
.iter()
.find(|sheep| sheep.instance() == 0)
.expect("slot 0 must be carried");
let slot_one = carried
.iter()
.find(|sheep| sheep.instance() == 1)
.expect("slot 1 must be carried");
assert_eq!(slot_zero.id(), 1);
assert_eq!(slot_zero.pid(), Some(100));
assert_eq!(slot_zero.epoch(), 7);
assert_eq!(slot_zero.fds(), fds_at(11));
assert_eq!(slot_one.id(), 2);
assert_eq!(slot_one.pid(), Some(101));
assert_eq!(slot_one.epoch(), 8);
assert_eq!(slot_one.fds(), fds_at(21));
assert_eq!(
slot_zero.name(),
slot_one.name(),
"both slots are the same app, which is what makes the slot the \
only thing telling them apart"
);
}
#[test]
fn a_swap_in_flight_no_longer_refuses_and_reaches_the_blob() {
let mut drainee = entry_fixture(|_| {});
drainee.reload = ReloadState::Drainee { new_id: Some(9) };
let mut replacement = entry_fixture(|_| {});
replacement.id = 9;
replacement.reload = ReloadState::Replacement;
assert_eq!(
fitness(&[plain(&drainee), plain(&replacement)]),
Fitness::Carryable
);
assert_eq!(
carried(&drainee).reload(),
Some(ReloadState::Drainee { new_id: Some(9) }),
"the id linking the two halves must survive the blob, not just the role"
);
assert_eq!(
carried(&replacement).reload(),
Some(ReloadState::Replacement)
);
}
#[test]
fn a_pending_manual_command_no_longer_refuses_and_reaches_the_blob() {
let e = entry_fixture(|_| {});
assert_eq!(fitness(&[plain(&e)]), Fitness::Carryable);
let marked = CarriedSheep::from_entry(
&e,
7,
fds_at(11),
false,
Some(PendingManual {
kind: ManualKind::Delete,
origin: CommandOrigin::Automatic,
}),
false,
None,
);
assert_eq!(
marked.manual(),
Some(PendingManual {
kind: ManualKind::Delete,
origin: CommandOrigin::Automatic,
}),
"both halves of the marker must survive the blob, not just that one exists"
);
}
const fn fds_at(base: RawFd) -> CarriedFds {
CarriedFds {
out_pipe: Some(base),
err_pipe: Some(base + 1),
out_log: Some(base + 2),
err_log: Some(base + 3),
stdin: Some(base + 4),
channel: Some(base + 5),
}
}
fn carried(entry: &ProcessEntry) -> CarriedSheep {
CarriedSheep::from_entry(entry, 7, fds_at(11), false, None, false, None)
}
fn handover_over(entry: &ProcessEntry) -> Handover {
Handover {
version: VERSION,
sheep: vec![carried(entry)],
listener_fd: 3,
pidfile_fd: 4,
next_id: 9,
next_deadline: 5,
next_action_stamp: 2,
reloads: Some(Vec::new()),
}
}
fn sample_handover() -> Handover {
handover_over(&entry_fixture(|_| {}))
}
#[test]
fn every_carried_number_is_kinded_in_the_same_order() {
let fds = CarriedFds {
out_pipe: Some(10),
err_pipe: Some(11),
out_log: Some(12),
err_log: Some(13),
stdin: Some(14),
channel: Some(15),
};
assert_eq!(
fds.all_kinded().map(|(fd, _)| fd),
fds.all(),
"the kinded walk and the `FD_CLOEXEC` walk must see the same numbers"
);
let slots: std::collections::HashSet<SheepFd> =
fds.all_kinded().iter().map(|(_, slot)| *slot).collect();
assert_eq!(slots.len(), 6, "each slot must appear exactly once");
}
fn sample_handover_with_secret_env() -> Handover {
let entry = entry_fixture(|app| {
app.env.insert("TOKEN".to_owned(), "hunter2".to_owned());
});
assert!(
entry.spec.config().env.values().any(|v| v == "hunter2"),
"the fixture must really carry the secret it is testing for"
);
handover_over(&entry)
}
#[test]
fn a_blob_round_trips() {
let h = sample_handover();
let back: Handover = serde_json::from_str(&serde_json::to_string(&h).unwrap()).unwrap();
assert_eq!(back, h);
}
#[test]
fn a_blob_round_trips_a_sheeps_environment_intact() {
let text = serde_json::to_string(&sample_handover_with_secret_env()).unwrap();
let back: Handover = serde_json::from_str(&text).unwrap();
assert_eq!(
back.sheep[0].app.env.get("TOKEN").map(String::as_str),
Some("hunter2"),
"{text}"
);
}
#[test]
fn debug_redacts_a_carried_sheeps_environment() {
let entry = entry_fixture(|app| {
app.env.insert("TOKEN".to_owned(), "hunter2".to_owned());
});
assert_eq!(
format!("{:?}", carried(&entry)),
"CarriedSheep { id: 1, name: \"web\", instance: 0, pid: Some(100), restarts: 0, \
epoch: 7, status: Online, last_exit: None, credentials: Resolved(None), fds: \
CarriedFds { out_pipe: Some(11), err_pipe: Some(12), out_log: Some(13), err_log: \
Some(14), stdin: Some(15), channel: Some(16) }, pending_delete: Some(false), \
manual: None, reload: Some(None), ready_failed: Some(false), restart_due: None, \
dog: None, pending: None, pending_reidentifies: None, app: AppConfig { \
name: \"web\", script: \"./srv\", env: <1 vars>, .. } }"
);
let text = format!("{:?}", sample_handover_with_secret_env());
assert!(!text.contains("hunter2"), "{text}");
assert!(!text.contains("TOKEN"), "{text}");
}
#[test]
fn debug_redacts_the_environment_on_a_process_entry() {
let entry = entry_fixture(|app| {
app.env.insert("TOKEN".to_owned(), "hunter2".to_owned());
});
assert_eq!(
format!("{entry:?}"),
"ProcessEntry { id: 1, spec: ResolvedApp { config: AppConfig { name: \"web\", \
script: \"./srv\", env: <1 vars>, .. } }, pending: None, pending_reidentifies: \
false, overridden: [], instance: 0, status: Online, pid: Some(100), restarts: 0, \
started_at: None, budget: RestartBudget { unstable_count: 0 }, reload: None, \
credentials: Resolved(None), out_file: \"/tmp/shep-handover-test-out.log\", \
err_file: \"/tmp/shep-handover-test-err.log\", dog: None, last_exit: None }"
);
}
#[test]
fn a_written_blob_is_readable_only_by_its_owner() {
let dir = tempfile::tempdir().unwrap();
let paths = test_paths(&dir);
std::fs::create_dir_all(&paths.run).unwrap();
let written = sample_handover().write(&paths).unwrap();
assert_eq!(written, Handover::path(&paths));
let mode = std::fs::metadata(&written).unwrap().permissions().mode();
assert_eq!(mode & 0o777, 0o600, "{mode:o}");
assert_eq!(Handover::read(&written).unwrap(), sample_handover());
}
#[test]
fn a_stale_blob_does_not_lend_its_mode_to_the_next_one() {
let dir = tempfile::tempdir().unwrap();
let paths = test_paths(&dir);
std::fs::create_dir_all(&paths.run).unwrap();
let path = Handover::path(&paths);
std::fs::write(&path, "stale").unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
sample_handover().write(&paths).unwrap();
let mode = std::fs::metadata(&path).unwrap().permissions().mode();
assert_eq!(mode & 0o777, 0o600, "{mode:o}");
}
#[test]
fn a_blob_from_a_future_version_is_refused_not_guessed_at() {
let mut v = serde_json::to_value(sample_handover()).unwrap();
v["version"] = serde_json::json!(u32::MAX);
assert!(Handover::load_value(v).is_err());
}
#[test]
fn a_blob_written_before_stdin_was_carried_still_loads() {
let mut value = serde_json::to_value(sample_handover()).unwrap();
let fds = value["sheep"][0]["fds"]
.as_object_mut()
.expect("a carried sheep names its descriptors");
assert!(
fds.remove("stdin").is_some(),
"the field this case removes must be there to remove"
);
let loaded = Handover::load_value(value).expect("an older blob must still load");
assert_eq!(loaded.sheep[0].fds.stdin, None);
assert_eq!(
loaded.sheep[0].fds.out_pipe,
sample_handover().sheep[0].fds.out_pipe,
"the other five are unchanged by the one that was absent"
);
}
#[test]
fn a_blob_written_before_the_channel_was_carried_still_loads() {
let mut value = serde_json::to_value(sample_handover()).unwrap();
let fds = value["sheep"][0]["fds"]
.as_object_mut()
.expect("a carried sheep names its descriptors");
assert!(
fds.remove("channel").is_some(),
"the field this case removes must be there to remove"
);
let loaded = Handover::load_value(value).expect("an older blob must still load");
assert_eq!(loaded.sheep[0].fds.channel, None);
assert_eq!(
loaded.sheep[0].fds.stdin,
sample_handover().sheep[0].fds.stdin,
"the other five are unchanged by the one that was absent"
);
}
#[test]
fn a_blob_written_before_pending_delete_was_carried_still_loads() {
let mut value = serde_json::to_value(sample_handover()).unwrap();
let sheep = value["sheep"][0]
.as_object_mut()
.expect("a carried sheep is an object");
assert!(
sheep.remove("pending_delete").is_some(),
"the field this case removes must be there to remove"
);
let loaded = Handover::load_value(value).expect("an older blob must still load");
assert_eq!(loaded.sheep[0].pending_delete(), None);
assert_eq!(
loaded.sheep[0].id(),
sample_handover().sheep[0].id(),
"the rest of the row is unchanged by the one field that was absent"
);
}
#[test]
fn a_sheep_with_nothing_parked_carries_neither_parking_key() {
let entry = entry_fixture(|_| {});
assert!(
entry.pending.is_none(),
"fixture check: this case is about a sheep with nothing parked"
);
let blob = handover_over(&entry);
let round_tripped = Handover::load_value(serde_json::to_value(&blob).unwrap())
.expect("a blob this daemon wrote must load");
assert_eq!(round_tripped.sheep[0].pending(), None);
assert_eq!(
round_tripped.sheep[0].pending_reidentifies(),
None,
"a reset flag with no parked config to apply it to is a key that means nothing"
);
}
#[test]
fn a_blob_written_before_pending_was_carried_still_loads() {
let mut entry = entry_fixture(|_| {});
entry.pending = Some(app_with("web", |app| {
app.env.insert("MODE".to_owned(), "blue".to_owned());
}));
entry.pending_reidentifies = true;
let blob = handover_over(&entry);
let round_tripped = Handover::load_value(serde_json::to_value(&blob).unwrap())
.expect("a blob this daemon wrote must load");
assert_eq!(
round_tripped.sheep[0]
.pending()
.expect("the parked config crosses the exec")
.env
.get("MODE")
.map(String::as_str),
Some("blue")
);
assert_eq!(
round_tripped.sheep[0].pending_reidentifies(),
Some(true),
"and its reset flag crosses with it: a config that arrived without one would \
promote on the identity the flag exists to replace"
);
let mut value = serde_json::to_value(&blob).unwrap();
let sheep = value["sheep"][0]
.as_object_mut()
.expect("a carried sheep is an object");
for key in ["pending", "pending_reidentifies"] {
assert!(
sheep.remove(key).is_some(),
"the field this case removes must be there to remove: {key}"
);
}
let loaded = Handover::load_value(value).expect("an older blob must still load");
assert_eq!(loaded.sheep[0].pending(), None);
assert_eq!(loaded.sheep[0].pending_reidentifies(), None);
assert_eq!(
loaded.sheep[0].id(),
blob.sheep[0].id(),
"the rest of the row is unchanged by the two fields that were absent"
);
}
#[test]
fn a_blob_written_before_a_manual_marker_was_carried_still_loads() {
let marker = PendingManual {
kind: ManualKind::Restart,
origin: CommandOrigin::Automatic,
};
let mut blob = sample_handover();
blob.sheep[0] = CarriedSheep::from_entry(
&entry_fixture(|_| {}),
7,
fds_at(11),
false,
Some(marker),
false,
None,
);
let value = serde_json::to_value(&blob).unwrap();
assert_eq!(
Handover::load_value(value.clone())
.expect("a current blob loads")
.sheep[0]
.manual(),
Some(marker),
"a marker on the wire must come back whole, kind and origin both"
);
let mut older = value;
let sheep = older["sheep"][0]
.as_object_mut()
.expect("a carried sheep is an object");
assert!(
sheep.remove("manual").is_some(),
"the field this case removes must be there to remove"
);
let loaded = Handover::load_value(older).expect("an older blob must still load");
assert_eq!(loaded.sheep[0].manual(), None);
assert_eq!(
loaded.sheep[0].id(),
blob.sheep[0].id(),
"the rest of the row is unchanged by the one field that was absent"
);
}
#[test]
fn a_blob_written_before_a_swap_was_carried_still_loads() {
let job = CarriedReload {
app: "web".to_owned(),
queue: vec![11, 12],
mode: ReloadMode::Serial,
swap: ReloadSwap {
old_id: 1,
new_id: Some(9),
phase: ReloadPhase::AwaitReady,
},
};
let mut blob = sample_handover();
let mut drainee = entry_fixture(|_| {});
drainee.reload = ReloadState::Drainee { new_id: Some(9) };
blob.sheep[0] = carried(&drainee);
blob.reloads = Some(vec![job.clone()]);
let value = serde_json::to_value(&blob).unwrap();
let current = Handover::load_value(value.clone()).expect("a current blob loads");
assert_eq!(
current.sheep[0].reload(),
Some(ReloadState::Drainee { new_id: Some(9) }),
"the marker on the wire must come back whole, role and linked id both"
);
assert_eq!(
current.reloads(),
&[job],
"the job must come back whole: queue, mode and every field of the swap"
);
let mut older = value;
let object = older.as_object_mut().expect("a blob is an object");
assert!(
object.remove("reloads").is_some(),
"the field this case removes must be there to remove"
);
let sheep = older["sheep"][0]
.as_object_mut()
.expect("a carried sheep is an object");
assert!(
sheep.remove("reload").is_some(),
"the field this case removes must be there to remove"
);
let loaded = Handover::load_value(older).expect("an older blob must still load");
assert_eq!(loaded.sheep[0].reload(), None);
assert!(loaded.reloads().is_empty());
assert_eq!(
loaded.sheep[0].id(),
blob.sheep[0].id(),
"the rest of the row is unchanged by the two fields that were absent"
);
}
#[test]
fn a_blob_written_before_ready_failed_was_carried_still_loads() {
let mut blob = sample_handover();
blob.sheep[0] = CarriedSheep::from_entry(
&entry_fixture(|_| {}),
7,
fds_at(11),
false,
None,
true,
None,
);
let value = serde_json::to_value(&blob).unwrap();
assert_eq!(
Handover::load_value(value.clone())
.expect("a current blob loads")
.sheep[0]
.ready_failed(),
Some(true),
"a verdict on the wire must come back as one, or the rollback it keeps reachable \
cannot reach anything"
);
let mut older = value;
let sheep = older["sheep"][0]
.as_object_mut()
.expect("a carried sheep is an object");
assert!(
sheep.remove("ready_failed").is_some(),
"the field this case removes must be there to remove"
);
let loaded = Handover::load_value(older).expect("an older blob must still load");
assert_eq!(loaded.sheep[0].ready_failed(), None);
assert_eq!(
loaded.sheep[0].id(),
blob.sheep[0].id(),
"the rest of the row is unchanged by the one field that was absent"
);
}
#[test]
fn a_dogs_marker_crosses_the_blob() {
let mut entry = entry_fixture(|_| {});
entry.dog = Some(DogSource::Adopted {
path: "/opt/bin/shep-log-rotate".to_string(),
});
let mut blob = sample_handover();
blob.sheep[0] = CarriedSheep::from_entry(&entry, 7, fds_at(11), false, None, false, None);
let loaded = Handover::load_value(serde_json::to_value(&blob).unwrap())
.expect("a current blob loads");
assert_eq!(
loaded.sheep[0].dog(),
Some(&DogSource::Adopted {
path: "/opt/bin/shep-log-rotate".to_string(),
}),
"a dog that crossed the exec as an ordinary sheep is one `shep dogs` has lost"
);
}
#[test]
fn a_plain_sheep_crosses_the_blob_without_one() {
let mut blob = sample_handover();
blob.sheep[0] = CarriedSheep::from_entry(
&entry_fixture(|_| {}),
7,
fds_at(11),
false,
None,
false,
None,
);
let loaded = Handover::load_value(serde_json::to_value(&blob).unwrap())
.expect("a current blob loads");
assert_eq!(loaded.sheep[0].dog(), None);
}
#[test]
fn a_blob_written_before_a_dog_was_carried_still_loads() {
let mut entry = entry_fixture(|_| {});
entry.dog = Some(DogSource::BuiltIn);
let mut blob = sample_handover();
blob.sheep[0] = CarriedSheep::from_entry(&entry, 7, fds_at(11), false, None, false, None);
let value = serde_json::to_value(&blob).unwrap();
assert_eq!(
Handover::load_value(value.clone())
.expect("a current blob loads")
.sheep[0]
.dog(),
Some(&DogSource::BuiltIn),
"a marker on the wire must come back as one"
);
let mut older = value;
let sheep = older["sheep"][0]
.as_object_mut()
.expect("a carried sheep is an object");
assert!(
sheep.remove("dog").is_some(),
"the field this case removes must be there to remove"
);
let loaded = Handover::load_value(older).expect("an older blob must still load");
assert_eq!(loaded.sheep[0].dog(), None);
assert_eq!(
loaded.sheep[0].id(),
blob.sheep[0].id(),
"the rest of the row is unchanged by the one field that was absent"
);
}
fn owed_a_restart() -> ProcessEntry {
let mut entry = entry_fixture(|_| {});
entry.status = ProcStatus::WaitingRestart;
entry.pid = None;
entry
}
#[test]
fn a_blob_written_before_a_restart_deadline_was_carried_still_loads() {
let due = SystemTime::now() + core::time::Duration::from_secs(600);
let mut blob = sample_handover();
blob.sheep[0] = CarriedSheep::from_entry(
&owed_a_restart(),
7,
fds_at(11),
false,
None,
false,
Some(due),
);
let value = serde_json::to_value(&blob).unwrap();
let carried = Handover::load_value(value.clone())
.expect("a current blob loads")
.sheep[0]
.restart_due()
.expect("a deadline on the wire must come back as one");
let drift = carried
.duration_since(due)
.or_else(|_| due.duration_since(carried))
.unwrap();
assert!(
drift < core::time::Duration::from_secs(1),
"a moment that does not survive the wire is a moment the successor cannot re-arm \
from: {drift:?} of drift"
);
let mut older = value;
let sheep = older["sheep"][0]
.as_object_mut()
.expect("a carried sheep is an object");
assert!(
sheep.remove("restart_due").is_some(),
"the field this case removes must be there to remove"
);
let loaded = Handover::load_value(older).expect("an older blob must still load");
assert_eq!(loaded.sheep[0].restart_due(), None);
assert_eq!(
loaded.sheep[0].id(),
blob.sheep[0].id(),
"the rest of the row is unchanged by the one field that was absent"
);
}
#[test]
fn a_deadline_is_carried_only_for_a_sheep_owed_a_respawn() {
let due = SystemTime::now() + core::time::Duration::from_secs(600);
let waiting = CarriedSheep::from_entry(
&owed_a_restart(),
7,
fds_at(11),
false,
None,
false,
Some(due),
);
assert!(
waiting.restart_due().is_some(),
"a sheep that IS owed a respawn must carry its deadline, or there is nothing to gate"
);
let online = CarriedSheep::from_entry(
&entry_fixture(|_| {}),
7,
fds_at(11),
false,
None,
false,
Some(due),
);
assert_eq!(
online.restart_due(),
None,
"a running sheep must not carry a deadline left over from an earlier exit"
);
}
#[test]
fn the_exec_target_exists_and_is_a_file() {
let p = exec_target().unwrap();
assert!(p.is_file(), "{}", p.display());
}
#[cfg(target_os = "linux")]
#[test]
fn a_deleted_inode_path_is_never_returned() {
let p = exec_target().unwrap();
assert!(
!p.to_string_lossy().contains("(deleted)"),
"exec target resolved to a deleted inode: {}",
p.display()
);
}
#[test]
fn resolve_target_refuses_a_synthetic_deleted_inode_candidate() {
let deleted = PathBuf::from("/opt/shep/shep (deleted)");
let err = resolve_target([None, Some(deleted)], None).unwrap_err();
assert_eq!(
err.to_string(),
"no binary to exec: /opt/shep/shep (deleted) (names a deleted inode, not a file)"
);
}
#[test]
fn a_deleted_inode_candidate_is_refused_on_every_platform() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("shep (deleted)");
std::fs::write(&path, "an exec target that really is on disk").unwrap();
assert_eq!(
check_target(&path),
Err(TargetProblem::DeletedInode),
"existing on disk must not excuse the suffix"
);
}
#[test]
fn a_candidate_that_is_not_on_disk_is_refused() {
let dir = tempfile::tempdir().unwrap();
assert_eq!(
check_target(&dir.path().join("never-written")),
Err(TargetProblem::Missing)
);
}
#[test]
fn a_directory_is_refused() {
let dir = tempfile::tempdir().unwrap();
assert_eq!(check_target(dir.path()), Err(TargetProblem::NotAFile));
}
#[test]
fn a_real_binary_passes_the_check() {
assert_eq!(check_target(&std::env::current_exe().unwrap()), Ok(()));
}
#[test]
fn argv0_resolves_against_the_startup_directory() {
let p = launch_path_from_argv().expect("argv[0] names a path");
assert!(p.is_file(), "{}", p.display());
}
const SELFTEST_HOME: &str = "SHEP_HANDOVER_SELFTEST";
const SELFTEST_NAME: &str =
"handover::tests::an_exec_replaces_the_image_and_keeps_a_descriptor";
fn handover_with_fds(
entry: &ProcessEntry,
listener_fd: RawFd,
pidfile_fd: RawFd,
fds: CarriedFds,
) -> Handover {
Handover {
version: VERSION,
sheep: vec![CarriedSheep::from_entry(
entry, 7, fds, false, None, false, None,
)],
listener_fd,
pidfile_fd,
next_id: 9,
next_deadline: 5,
next_action_stamp: 2,
reloads: Some(Vec::new()),
}
}
fn selftest_paths(home: &Path) -> ShepPaths {
let home = home.display().to_string();
let paths = ShepPaths::resolve(
&|key| (key == "SHEP_HOME").then(|| home.clone()),
Path::new("/nonexistent"),
);
std::fs::create_dir_all(&paths.run).unwrap();
paths
}
#[test]
fn an_exec_replaces_the_image_and_keeps_a_descriptor() {
if let Some(blob) = std::env::var_os(HANDOVER_ENV) {
successor_stage(Path::new(&blob));
}
if let Some(home) = std::env::var_os(SELFTEST_HOME) {
exec_stage(Path::new(&home));
}
let dir = tempfile::tempdir().unwrap();
let out = std::process::Command::new(std::env::current_exe().unwrap())
.arg(SELFTEST_NAME)
.arg("--exact")
.arg("--nocapture")
.env(SELFTEST_HOME, dir.path())
.env_remove(HANDOVER_ENV)
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(
out.status.success(),
"{stdout}{}",
String::from_utf8_lossy(&out.stderr)
);
assert!(
stdout.contains("running 1 test"),
"the child ran no test, so `{SELFTEST_NAME}` is not where this test lives any more; `--exact` needs the full path and nothing updates it automatically: {stdout}"
);
assert!(stdout.contains("adopted: hello"), "{stdout}");
}
fn exec_stage(home: &Path) -> ! {
use std::io::Write as _;
use std::os::fd::AsRawFd as _;
let paths = selftest_paths(home);
let (reader, mut writer) = std::io::pipe().unwrap();
writer.write_all(b"hello").unwrap();
drop(writer);
let listener = tempfile::tempfile().unwrap();
let pidfile = tempfile::tempfile().unwrap();
let blob = handover_with_fds(
&entry_fixture(|_| {}),
listener.as_raw_fd(),
pidfile.as_raw_fd(),
CarriedFds {
out_pipe: Some(reader.as_raw_fd()),
err_pipe: None,
out_log: None,
err_log: None,
stdin: None,
channel: None,
},
);
let err = hand_over(&blob, &paths).unwrap_err();
panic!("the exec should not have returned: {err}");
}
fn successor_stage(blob_path: &Path) -> ! {
let blob = Handover::read(blob_path).expect("the successor's blob");
let fd = blob.sheep[0].fds.out_pipe.expect("a carried stdout pipe");
let mut buf = [0_u8; 16];
let read = nix::unistd::read(fd, &mut buf).expect("the carried descriptor is open");
println!("adopted: {}", String::from_utf8_lossy(&buf[..read]));
std::process::exit(0);
}
#[test]
fn a_failed_exec_leaves_no_blob_behind() {
use std::os::fd::AsRawFd as _;
let dir = tempfile::tempdir().unwrap();
let paths = selftest_paths(dir.path());
let target = dir.path().join("not-a-binary");
std::fs::write(&target, "this will never execute").unwrap();
let listener = tempfile::tempfile().unwrap();
let pidfile = tempfile::tempfile().unwrap();
let blob = handover_with_fds(
&entry_fixture(|_| {}),
listener.as_raw_fd(),
pidfile.as_raw_fd(),
CarriedFds {
out_pipe: None,
err_pipe: None,
out_log: None,
err_log: None,
stdin: None,
channel: None,
},
);
let err = exec_into(&target, &blob, &paths).unwrap_err();
assert!(
!Handover::path(&paths).exists(),
"a failed exec left a blob behind: {err}"
);
}
#[test]
fn a_failed_exec_makes_every_descriptor_close_on_exec_again() {
use std::os::fd::{AsFd as _, AsRawFd as _};
let dir = tempfile::tempdir().unwrap();
let paths = selftest_paths(dir.path());
let target = dir.path().join("not-a-binary");
std::fs::write(&target, "this will never execute").unwrap();
let listener = tempfile::tempfile().unwrap();
let pidfile = tempfile::tempfile().unwrap();
let out_log = tempfile::tempfile().unwrap();
let (_child_end, stdin) = std::io::pipe().unwrap();
let (channel, _child_channel) = std::os::unix::net::UnixStream::pair().unwrap();
let blob = handover_with_fds(
&entry_fixture(|_| {}),
listener.as_raw_fd(),
pidfile.as_raw_fd(),
CarriedFds {
out_pipe: None,
err_pipe: None,
out_log: Some(out_log.as_raw_fd()),
err_log: None,
stdin: Some(stdin.as_raw_fd()),
channel: Some(channel.as_raw_fd()),
},
);
for fd in [
listener.as_fd(),
pidfile.as_fd(),
out_log.as_fd(),
stdin.as_fd(),
channel.as_fd(),
] {
assert!(
!fds::is_kept(fd).unwrap(),
"the daemon opens everything close-on-exec, so this starts set"
);
}
let mut cleared = Vec::new();
let written = Handover::path(&paths);
let _ = keep_and_exec(&target, &blob, &written, &mut cleared);
cleared.sort_unstable();
let mut expected = vec![
listener.as_raw_fd(),
pidfile.as_raw_fd(),
out_log.as_raw_fd(),
stdin.as_raw_fd(),
channel.as_raw_fd(),
];
expected.sort_unstable();
assert_eq!(
cleared, expected,
"every named descriptor must be cleared, from both of the two \
places `named_fds` draws them"
);
let err = exec_into(&target, &blob, &paths).unwrap_err();
for fd in [
listener.as_fd(),
pidfile.as_fd(),
out_log.as_fd(),
stdin.as_fd(),
channel.as_fd(),
] {
assert!(
!fds::is_kept(fd).unwrap(),
"a failed exec left a descriptor exec-inheritable: {err}"
);
}
}
}