use std::os::fd::RawFd;
use std::time::SystemTime;
use serde::{Deserialize, Serialize};
use shep_core::config::AppConfig;
use shep_core::protocol::{DogSource, ExitInfo};
use shep_core::status::ProcStatus;
use crate::entry::{ProcessEntry, ReloadState};
use crate::privilege::SpawnIdentity;
use crate::supervisor::PendingManual;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CarriedSheep {
pub(super) id: u32,
pub(super) name: String,
pub(super) instance: u32,
pub(super) pid: Option<u32>,
pub(super) restarts: u32,
pub(super) epoch: u64,
pub(super) status: ProcStatus,
pub(super) last_exit: Option<ExitInfo>,
pub(super) credentials: SpawnIdentity,
pub(super) fds: CarriedFds,
pub(super) pending_delete: Option<bool>,
pub(super) manual: Option<PendingManual>,
pub(super) reload: Option<ReloadState>,
pub(super) ready_failed: Option<bool>,
pub(super) restart_due: Option<SystemTime>,
pub(super) dog: Option<DogSource>,
pub(super) pending: Option<AppConfig>,
pub(super) pending_reidentifies: Option<bool>,
pub(super) 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,
}
}
}
#[cfg(test)]
mod tests {
use super::{CarriedFds, CarriedSheep, SheepFd};
use crate::entry::ReloadState;
use crate::handover::fixtures::{carried, entry_fixture, fds_at, plain};
use crate::handover::{Counters, DaemonFds, Fitness, Handover, fitness};
use crate::supervisor::{CommandOrigin, ManualKind, PendingManual};
#[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"
);
}
#[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");
}
}