use std::os::fd::RawFd;
use std::time::SystemTime;
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, 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;
fn known_status<'de, D: Deserializer<'de>>(deserializer: D) -> Result<ProcStatus, D::Error> {
match ProcStatus::deserialize(deserializer)? {
ProcStatus::Unrecognized => Err(D::Error::custom(
"a carried sheep's status is not one this build knows",
)),
status => Ok(status),
}
}
fn known_dog<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<DogSource>, D::Error> {
match Option::<DogSource>::deserialize(deserializer)? {
Some(DogSource::Unrecognized) => Err(D::Error::custom(
"a carried dog's source is not one this build knows",
)),
source => Ok(source),
}
}
#[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,
#[serde(deserialize_with = "known_status")]
pub(super) status: ProcStatus,
pub(super) last_exit: Option<ExitInfo>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) spawn_failure: Option<String>,
pub(super) credentials: SpawnIdentity,
pub(super) fds: CarriedFds,
pub(super) dog_topics: Option<Vec<String>>,
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>,
#[serde(default, deserialize_with = "known_dog")]
pub(super) dog: Option<DogSource>,
pub(super) pending: Option<AppConfig>,
pub(super) pending_reidentifies: Option<bool>,
pub(super) disabled: 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,
spawn_failure: entry.spawn_failure.clone(),
credentials: entry.credentials,
fds,
dog_topics: None,
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(),
disabled: None,
app: entry.spec.config().clone(),
}
}
#[must_use]
pub fn with_disabled(mut self, disabled: bool) -> Self {
self.disabled = Some(disabled);
self
}
pub(super) fn carry_dog_link(&mut self, fd: RawFd, topics: Option<Vec<String>>) {
self.fds.dog_link = Some(fd);
self.dog_topics = topics;
}
#[must_use]
#[allow(dead_code, reason = "read by this crate's own tests")]
pub const fn fds(&self) -> CarriedFds {
self.fds
}
#[must_use]
pub fn dog_topics(&self) -> Option<&[String]> {
self.dog_topics.as_deref()
}
#[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 disabled(&self) -> Option<bool> {
self.disabled
}
#[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
}
pub fn spawn_failure(&self) -> Option<&str> {
self.spawn_failure.as_deref()
}
#[must_use]
pub const fn credentials(&self) -> SpawnIdentity {
self.credentials
}
#[must_use]
pub const fn app(&self) -> &AppConfig {
&self.app
}
}
#[derive(Debug)]
pub struct DogConnection {
pub name: String,
pub launch_for: Option<String>,
pub pid: u32,
pub fd: std::os::fd::OwnedFd,
pub topics: Option<Vec<String>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CarriedListener {
pub(super) sheep: String,
pub(super) name: String,
pub(super) address: String,
pub(super) fd: RawFd,
#[serde(skip)]
pub(super) unclaimed: bool,
}
impl CarriedListener {
#[must_use]
pub fn sheep(&self) -> &str {
&self.sheep
}
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
#[must_use]
pub fn address(&self) -> &str {
&self.address
}
#[must_use]
pub const fn fd(&self) -> RawFd {
self.fd
}
#[must_use]
pub const fn unclaimed(&self) -> bool {
self.unclaimed
}
}
#[derive(Debug)]
pub struct HeldListener {
pub sheep: String,
pub name: String,
pub address: String,
pub fd: std::os::fd::OwnedFd,
}
#[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>,
pub dog_link: Option<RawFd>,
pub pty: Option<RawFd>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum SheepFd {
OutPipe,
ErrPipe,
OutLog,
ErrLog,
Stdin,
Channel,
DogLink,
Pty,
}
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",
Self::DogLink => "dog connection",
Self::Pty => "pty master",
}
}
}
impl CarriedFds {
#[must_use]
pub const fn all(&self) -> [Option<RawFd>; 8] {
[
self.out_pipe,
self.err_pipe,
self.out_log,
self.err_log,
self.stdin,
self.channel,
self.dog_link,
self.pty,
]
}
pub(crate) const fn all_kinded(&self) -> [(Option<RawFd>, SheepFd); 8] {
[
(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),
(self.dog_link, SheepFd::DogLink),
(self.pty, SheepFd::Pty),
]
}
#[must_use]
pub const fn none() -> Self {
Self {
out_pipe: None,
err_pipe: None,
out_log: None,
err_log: None,
stdin: None,
channel: None,
dog_link: None,
pty: None,
}
}
}
#[cfg(test)]
mod tests {
use super::{CarriedFds, CarriedSheep, SheepFd};
use crate::entry::ReloadState;
use crate::handover::adopt::dry_run;
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),
dog_link: Some(16),
pty: Some(17),
};
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(), 8, "each slot must appear exactly once");
}
#[test]
fn a_blob_round_trips_a_pty_descriptor() {
let mut blob = sample_blob();
blob.sheep[0].fds.pty = Some(40);
let back: Handover = serde_json::from_str(&serde_json::to_string(&blob).unwrap()).unwrap();
assert_eq!(back.sheep()[0].fds().pty, Some(40));
assert_eq!(back, blob);
}
#[test]
fn a_blob_without_a_pty_key_loads_as_none() {
let mut blob = sample_blob();
blob.sheep[0].fds.pty = Some(40);
let mut value = serde_json::to_value(&blob).unwrap();
let fds = value["sheep"][0]["fds"]
.as_object_mut()
.expect("a carried sheep names its descriptors");
assert!(
fds.remove("pty").is_some(),
"the key 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().pty, None);
assert_eq!(
loaded.sheep()[0].fds().out_pipe,
blob.sheep()[0].fds().out_pipe,
"the other descriptors are unchanged by the one that was absent"
);
}
#[test]
fn a_pty_master_named_twice_is_refused() {
let mut blob = sample_blob();
let fds = &mut blob.sheep[0].fds;
fds.pty = fds.out_pipe;
let err = dry_run(&blob).expect_err("one number cannot have two owners");
assert!(
err.to_string().contains("more than once"),
"the refusal must be the repeat check's own: {err}"
);
}
fn sample_blob() -> Handover {
Handover::new(
vec![carried(&entry_fixture(|_| {}))],
DaemonFds {
listener: 3,
pidfile: 4,
},
Counters {
next_id: 9,
next_deadline: 5,
next_action_stamp: 2,
},
Vec::new(),
)
}
}