use std::fs;
use std::io;
use std::os::fd::{AsRawFd as _, RawFd};
use std::path::Path;
use serde::{Deserialize, Serialize};
use super::{CarriedListener, CarriedSheep, DogConnection, HeldListener};
use crate::supervisor::CarriedReload;
pub const VERSION: u32 = 1;
#[cfg(test)]
const FILE_NAME: &str = "handover.json";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Handover {
pub(super) version: u32,
pub(super) sheep: Vec<CarriedSheep>,
pub(super) listener_fd: RawFd,
pub(super) pidfile_fd: RawFd,
pub(super) next_id: u32,
pub(super) next_deadline: u64,
pub(super) next_action_stamp: u64,
pub(super) reloads: Option<Vec<CarriedReload>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) listeners: Option<Vec<CarriedListener>>,
}
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),
listeners: None,
}
}
#[must_use]
#[allow(dead_code, reason = "read by this crate's own tests")]
pub fn sheep(&self) -> &[CarriedSheep] {
&self.sheep
}
pub fn carry_dog_links(&mut self, links: &[DogConnection]) {
for sheep in &mut self.sheep {
let Some(link) = links
.iter()
.find(|link| sheep.pid() == Some(link.pid) && sheep.name() == link.name)
else {
continue;
};
sheep.carry_dog_link(link.fd.as_raw_fd(), link.topics.clone());
}
}
pub fn carry_listeners(&mut self, held: &[HeldListener]) {
let mut listeners: Vec<CarriedListener> = held
.iter()
.map(|socket| CarriedListener {
sheep: socket.sheep.clone(),
name: socket.name.clone(),
address: socket.address.clone(),
fd: socket.fd.as_raw_fd(),
unclaimed: false,
})
.collect();
listeners.sort_unstable_by(|a, b| (&a.sheep, &a.name).cmp(&(&b.sheep, &b.name)));
self.listeners = (!listeners.is_empty()).then_some(listeners);
}
#[must_use]
pub fn listeners(&self) -> &[CarriedListener] {
self.listeners.as_deref().unwrap_or_default()
}
#[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()
}
#[cfg(test)]
#[must_use]
pub fn path(paths: &shep_core::paths::ShepPaths) -> std::path::PathBuf {
paths.run.join(FILE_NAME)
}
pub(super) 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(super) fn carried_fds(&self) -> impl Iterator<Item = RawFd> + '_ {
self.named_fds()
.chain(self.listeners().iter().map(CarriedListener::fd))
}
#[cfg(test)]
pub fn write(&self, paths: &shep_core::paths::ShepPaths) -> io::Result<std::path::PathBuf> {
use std::fs::OpenOptions;
use std::os::unix::fs::OpenOptionsExt as _;
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)
}
}
impl shep_handover::State for Handover {
const FORMAT: u32 = VERSION;
}
#[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,
}
#[cfg(test)]
mod tests;