modem-mgmt 0.3.0

The management plane of zenoh-modem as a library: serve every device on a host over Zenoh, for any driver that links the contract
Documentation
//! One daemon, every device on the host (#118).
//!
//! A driver process used to own exactly one device, and two of them on one
//! host collided: both declared the same presence token, both answered the
//! same `introspect` and `describe` keys, nothing detected the twin, and
//! nothing stopped two processes opening one modem. The origin is the host
//! and the producer is `modem` (architecture §4.6, zenkey RFC 06 §3), so the
//! bus can only ever see one producer per host — and the honest shape is one
//! process that serves every device, with the exclusivity zenkey RFC 03 §1.5
//! asks for enforced **outside the bus**: a lock file per device, and
//! `TIOCEXCL` on a serial port.
//!
//! A [`Host`] is the set of [`Node`]s the management plane serves. Each node
//! is a device and its plane — the lane driver for an SDU device, the kernel
//! for a netdev — and the management plane reads them without knowing which
//! is which except where the difference is the answer (`lanes` on a netdev
//! answers `error/gated`; the roster answers once). The device lock that
//! keeps two processes off one modem lives with the driver that opens the
//! device (`modem-driver/src/lock.rs`); a node holds it for its life.

use std::sync::Arc;

use modem_device::Netdev;

use crate::plane::SduPlane;

/// How a device moves bytes.
#[non_exhaustive]
pub enum Plane {
    /// The SDU plane: lane sockets, the scheduler, a [`modem_device::Medium`]
    /// behind them — read through [`SduPlane`], so this crate never links
    /// the lane code (#119).
    Sdu(Arc<dyn SduPlane>),
    /// The kernel's: Zenoh binds a TCP link to the interface and the driver
    /// never sees a byte.
    Netdev(Arc<dyn Netdev>),
}

/// One device, as the management plane serves it.
pub struct Node {
    name: String,
    plane: Plane,
    /// Whatever must live as long as this node — the device's lock file,
    /// taken by the driver before it opened the device (#118). Dropped with
    /// the node, which releases the device to the next process.
    _held: Option<Box<dyn std::any::Any + Send + Sync>>,
    /// The dotted keys the startup file named in this device's section
    /// (#125): what lets the read-back say a value came from the file. The
    /// driver read the file; the device never sees it.
    file_keys: std::collections::BTreeSet<String>,
    /// The groups a remote writer may change (#126): the startup file's
    /// `writable`. Empty by default, which means none.
    writable: std::collections::BTreeSet<String>,
    /// The operator actions a remote caller may run (#129): the startup
    /// file's `actions`. Empty by default, which means none.
    actions: std::collections::BTreeSet<String>,
    /// The minimum interval per action (#129): the startup file's
    /// `action_interval_s`, so a looping script is refused rather than billed.
    action_intervals: std::collections::BTreeMap<String, std::time::Duration>,
}

impl Node {
    /// An SDU device: the plane serving its lanes.
    #[must_use]
    pub fn sdu(plane: Arc<dyn SduPlane>) -> Self {
        Self {
            name: plane.device().to_string(),
            plane: Plane::Sdu(plane),
            _held: None,
            file_keys: std::collections::BTreeSet::new(),
            writable: std::collections::BTreeSet::new(),
            actions: std::collections::BTreeSet::new(),
            action_intervals: std::collections::BTreeMap::new(),
        }
    }

    /// A netdev, under the name the config gave it.
    #[must_use]
    pub fn netdev(name: impl Into<String>, dev: Arc<dyn Netdev>) -> Self {
        Self {
            name: name.into(),
            plane: Plane::Netdev(dev),
            _held: None,
            file_keys: std::collections::BTreeSet::new(),
            writable: std::collections::BTreeSet::new(),
            actions: std::collections::BTreeSet::new(),
            action_intervals: std::collections::BTreeMap::new(),
        }
    }

    /// The dotted keys the startup file named for this device (#125).
    #[must_use]
    pub fn with_file_keys(mut self, keys: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.file_keys = keys.into_iter().map(Into::into).collect();
        self
    }

    /// The dotted keys the startup file named for this device.
    #[must_use]
    pub fn file_keys(&self) -> &std::collections::BTreeSet<String> {
        &self.file_keys
    }

    /// The groups a remote writer may change (#126) — the startup file's
    /// `writable`; none unless named.
    #[must_use]
    pub fn with_writable(mut self, groups: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.writable = groups.into_iter().map(Into::into).collect();
        self
    }

    /// The groups a remote writer may change.
    #[must_use]
    pub fn writable(&self) -> &std::collections::BTreeSet<String> {
        &self.writable
    }

    /// The operator actions a remote caller may run (#129), and the minimum
    /// interval of each — the startup file's `actions` and
    /// `action_interval_s`; none unless named.
    #[must_use]
    pub fn with_actions(
        mut self,
        allow: impl IntoIterator<Item = impl Into<String>>,
        intervals: impl IntoIterator<Item = (impl Into<String>, std::time::Duration)>,
    ) -> Self {
        self.actions = allow.into_iter().map(Into::into).collect();
        self.action_intervals = intervals.into_iter().map(|(k, v)| (k.into(), v)).collect();
        self
    }

    /// The operator actions a remote caller may run.
    #[must_use]
    pub fn actions(&self) -> &std::collections::BTreeSet<String> {
        &self.actions
    }

    /// The minimum interval per action.
    #[must_use]
    pub fn action_intervals(&self) -> &std::collections::BTreeMap<String, std::time::Duration> {
        &self.action_intervals
    }

    /// Hold something — the device's lock — for as long as this node exists.
    #[must_use]
    pub fn holding(mut self, held: impl std::any::Any + Send + Sync) -> Self {
        self._held = Some(Box::new(held));
        self
    }

    /// The device's name — the `{device}` chunk of every key about it.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Its plane.
    pub fn plane(&self) -> &Plane {
        &self.plane
    }

    /// The SDU plane, if this device has one.
    pub fn sdu_plane(&self) -> Option<&Arc<dyn SduPlane>> {
        match &self.plane {
            Plane::Sdu(p) => Some(p),
            Plane::Netdev(_) => None,
        }
    }
}

/// Every device this daemon serves.
pub struct Host {
    nodes: Vec<Node>,
    /// When this host was built — the driver's start, for `uptime_s`.
    started: std::time::Instant,
    /// One id per driver start (#121), so a reader tells two events a
    /// second apart on either side of a restart from each other.
    boot_id: String,
    /// The version the registration document names (#122): this crate's
    /// unless the driver says its own.
    version: String,
}

impl Default for Host {
    fn default() -> Self {
        Self::new()
    }
}

impl Host {
    /// A host with no devices yet.
    #[must_use]
    pub fn new() -> Self {
        Self {
            nodes: Vec::new(),
            started: std::time::Instant::now(),
            boot_id: crate::clock::boot_id(),
            version: env!("CARGO_PKG_VERSION").to_string(),
        }
    }

    /// The driver's own version, for `state/modem/sensor` — a daemon that
    /// links this crate is the thing an operator upgrades, so its version
    /// is the one worth publishing.
    #[must_use]
    pub fn with_version(mut self, version: impl Into<String>) -> Self {
        self.version = version.into();
        self
    }

    /// The version the registration document names.
    #[must_use]
    pub fn version(&self) -> &str {
        &self.version
    }

    /// Seconds since this host was built: an ordering a wrong wall clock
    /// cannot corrupt.
    #[must_use]
    pub fn uptime_s(&self) -> u64 {
        self.started.elapsed().as_secs()
    }

    /// This driver start's id.
    #[must_use]
    pub fn boot_id(&self) -> &str {
        &self.boot_id
    }

    /// Add a device. Two nodes with one name are a configuration error the
    /// file parser refuses; here it is a programming error.
    ///
    /// # Panics
    ///
    /// If a node of that name is already present.
    pub fn push(&mut self, node: Node) {
        assert!(
            self.node(node.name()).is_none(),
            "device {:?} added twice",
            node.name()
        );
        self.nodes.push(node);
    }

    /// Builder form of [`push`](Host::push).
    #[must_use]
    pub fn with(mut self, node: Node) -> Self {
        self.push(node);
        self
    }

    /// Every device, in configuration order.
    pub fn nodes(&self) -> &[Node] {
        &self.nodes
    }

    /// One device by name.
    pub fn node(&self, name: &str) -> Option<&Node> {
        self.nodes.iter().find(|n| n.name == name)
    }

    /// The SDU devices' planes.
    pub fn sdu_planes(&self) -> impl Iterator<Item = &Arc<dyn SduPlane>> {
        self.nodes.iter().filter_map(Node::sdu_plane)
    }

    /// Stop every device: the lane drivers first, then the devices that have
    /// no driver to stop them.
    pub async fn shutdown(&self) {
        for node in &self.nodes {
            match &node.plane {
                Plane::Sdu(plane) => plane.shutdown().await,
                Plane::Netdev(dev) => {
                    if let Err(e) = dev.close().await {
                        tracing::warn!(device = %node.name, error = %e, "the netdev did not close cleanly");
                    }
                }
            }
        }
    }
}