shep-daemon 0.22.0

The supervision engine behind shep: process spawning, restart policy, the log plane, watch and cron restarts, and the RPC server
Documentation
//! The one error every boot step reports through
//!
//! Layout, pidfile lock, socket bind, readiness write, muster restore and
//! handover adoption are steps in a single sequence rather than six
//! independent operations, so they share [`BootError`] and the caller that
//! starts the sequence writes one `?`.

use core::fmt;
use std::path::{Path, PathBuf};

use shep_core::dog_defaults::DogDefaultsError;

use crate::snapshot::SnapshotError;

/// Error type returned from this module's boot steps
///
/// Wraps `io::Error` directly rather than stringifying it, so callers keep the
/// OS diagnostic via [`core::error::Error::source`]; that costs this enum
/// `Clone`/`PartialEq`/`Eq`.
///
/// `#[non_exhaustive]`: a future boot step adds a variant, not a wider [`Self::Io`].
#[non_exhaustive]
#[derive(Debug)]
pub enum BootError {
    /// A flock this image inherited across a handover could not be installed.
    ///
    /// Boxed rather than named: the two steps that fail here report different
    /// types, and one of them is `pub(crate)`, so naming it would widen it.
    Adopt(Box<dyn core::error::Error + Send + Sync>),
    /// A filesystem step failed (carries the path and the OS error)
    ///
    /// No `From<std::io::Error>`, here or on any sibling: `ReadyWrite` wraps
    /// the same type, so one would make a bare `?` in this module pick a
    /// variant rather than report one.
    Io {
        /// The path the failing step operated on
        path: PathBuf,
        /// The underlying OS error
        source: std::io::Error,
    },
    /// Another daemon already answers on this socket (carries its pid if recorded)
    AlreadyRunning {
        /// The pid recorded in the pidfile, if one was readable
        pid: Option<u32>,
    },
    /// The muster roll exists but could not be read or parsed on restore
    Snapshot(SnapshotError),
    /// `$SHEP_HOME` puts the control socket past the platform's `sun_path`
    /// limit, so no bind could ever succeed (carries the path and the limit)
    ///
    /// Checked before the bind rather than translated after it: the kernel's
    /// `ENAMETOOLONG` names neither the limit nor `$SHEP_HOME`.
    SocketPathTooLong {
        /// The socket path that would not fit
        path: PathBuf,
        /// Its length in bytes
        len: usize,
        /// This platform's `sun_path` capacity in bytes
        limit: usize,
    },
    /// Writing the readiness line to the caller-adopted readiness pipe
    /// failed (carries the OS error)
    ///
    /// Only the write. Adoption is the caller's job (see
    /// [`BootOptions::ready_fd`](super::BootOptions::ready_fd)), so `boot` has no
    /// variant for a failed one.
    ReadyWrite(std::io::Error),
    /// `dog-defaults.json` exists and could not be read or parsed
    ///
    /// Refused rather than booted past: a shepherd with no defaults would
    /// serve every dog an unlayered table and drop the file's contents on the
    /// next write.
    DogDefaults {
        /// The store that could not be read
        path: PathBuf,
        /// Why
        source: DogDefaultsError,
    },
}

impl BootError {
    /// Shorthand for the [`Self::Io`] variant, which every path-carrying boot
    /// step reports through
    ///
    /// `pub(crate)`, not `pub`: `#[non_exhaustive]` already lets a future boot
    /// step add a variant, and this helper changes no variant shape. Takes
    /// `&Path` and clones it here, so only a failing step pays for the
    /// `PathBuf`.
    pub(crate) fn io(path: &Path, source: std::io::Error) -> Self {
        Self::Io {
            path: path.to_path_buf(),
            source,
        }
    }
}

impl fmt::Display for BootError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io { path, source } => {
                write!(f, "boot step failed for `{}`: {source}", path.display())
            }
            Self::AlreadyRunning { pid: Some(pid) } => {
                write!(f, "a shep daemon is already running (pid {pid})")
            }
            Self::AlreadyRunning { pid: None } => write!(f, "a shep daemon is already running"),
            Self::Snapshot(err) => write!(f, "muster roll restore failed: {err}"),
            Self::SocketPathTooLong { path, len, limit } => write!(
                f,
                "the control socket path is {len} bytes and this platform allows {limit}: `{}`. \
                 A unix socket path is bounded by the kernel, not by shep, so a shorter \
                 $SHEP_HOME is the only fix.",
                path.display()
            ),
            Self::ReadyWrite(err) => write!(f, "writing the readiness line failed: {err}"),
            Self::DogDefaults { path, source } => write!(
                f,
                "`{}` could not be read: {source}. Nothing was started: fix or remove the file, \
                 because a shepherd without it would serve every dog its tables with no defaults \
                 layered in",
                path.display()
            ),
            Self::Adopt(source) => write!(
                f,
                "this shepherd was handed a flock it could not take over: {source}. The flock is \
                 still running and nothing is supervising it. `shep daemon reload` is not the \
                 way back: it needs a live shepherd to ask and to signal, and this process is \
                 about to exit without ever serving, and boots nothing beside the flock \
                 first. The home is claimable straight afterwards and `shep muster` starts a \
                 shepherd from the roll"
            ),
        }
    }
}

impl core::error::Error for BootError {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match self {
            Self::Io { source, .. } => Some(source),
            Self::AlreadyRunning { .. } => None,
            // Refused before any syscall was attempted.
            Self::SocketPathTooLong { .. } => None,
            Self::Snapshot(err) => Some(err),
            Self::ReadyWrite(err) => Some(err),
            Self::DogDefaults { source, .. } => Some(source),
            Self::Adopt(source) => Some(source.as_ref()),
        }
    }
}

impl From<SnapshotError> for BootError {
    fn from(source: SnapshotError) -> Self {
        Self::Snapshot(source)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use core::error::Error as _;

    #[test]
    fn io_carries_the_path_and_the_source() {
        let err = BootError::io(
            Path::new("/srv/flock/run"),
            std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied"),
        );
        assert_eq!(
            err.to_string(),
            "boot step failed for `/srv/flock/run`: denied",
            "the message names the path the step operated on and what the OS said"
        );
        let source = err.source().expect("Io must report a source");
        assert_eq!(source.to_string(), "denied");
    }

    // The point of the boxed payload: whatever the adoption step said is still
    // reachable by anything walking the chain.
    #[test]
    fn an_adopt_failure_reports_the_underlying_error_as_its_source() {
        let err = BootError::Adopt(Box::new(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "fd 7 names no open descriptor",
        )));

        let source = err.source().expect("Adopt must report a source");
        assert_eq!(source.to_string(), "fd 7 names no open descriptor");
        assert!(
            err.to_string().contains("fd 7 names no open descriptor"),
            "the message must still name what failed: {err}"
        );
    }
}