modem-mgmt 0.2.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
//! The overlay: what `persist` keeps across a restart (#128).
//!
//! Three layers of configuration. The **startup** layer is the operator's
//! TOML, never rewritten by the daemon. The **running** layer is the
//! device's, written by `set` and by boot. Between them the **overlay**:
//! one small file per device, `0600` under the unit's state directory,
//! written only by `persist` and only for a change an operator confirmed
//! (#127). It is the first state this daemon ever persists, and a remote
//! write that survives a reboot is an escalation, so it is guarded like one:
//! its own key an ACL can deny, no sensitive value ever, and the four
//! safeguards `ConfigState::boot` applies when it reads one back.
//!
//! ```toml
//! schema = "9c2f…"          # the schema this was written against
//!
//! [[entry]]
//! group = "poll"
//! name = "signal_poll_s"
//! value = 30
//! overrode = 60              # the startup value at the time
//! ```

use std::path::Path;

use modem_device::config::{ConfigValue, ParamKind, Schema};

/// One persisted value, with the startup value it overrode: the first
/// safeguard, so an operator's later edit to the file wins over a stale
/// overlay rather than losing to it silently.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub(crate) struct Entry {
    pub group: String,
    pub name: String,
    pub value: toml::Value,
    pub overrode: toml::Value,
}

/// The file.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub(crate) struct Overlay {
    /// The schema the entries were written against (the second safeguard):
    /// an overlay from before an upgrade that changed the schema is dropped
    /// whole and reported, never fatal.
    pub schema: String,
    #[serde(default, rename = "entry")]
    pub entries: Vec<Entry>,
}

impl Overlay {
    pub(crate) fn new(schema: String) -> Self {
        Self {
            schema,
            entries: Vec::new(),
        }
    }

    /// Read one, if there is one. An unreadable file is an error the caller
    /// reports and moves on from: an upgrade must not stop a remote unit
    /// from starting.
    pub(crate) fn load(path: &Path) -> anyhow::Result<Option<Self>> {
        match std::fs::read_to_string(path) {
            Ok(text) => Ok(Some(toml::from_str(&text)?)),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
            Err(e) => Err(e.into()),
        }
    }

    /// Write it: `0600`, whole or not at all (a temporary beside it, then a
    /// rename), the directory created if it is missing.
    pub(crate) fn save(&self, path: &Path) -> anyhow::Result<()> {
        use std::io::Write as _;
        if let Some(dir) = path.parent() {
            std::fs::create_dir_all(dir)?;
        }
        let tmp = path.with_extension("toml.tmp");
        let text = toml::to_string(self)?;
        {
            let mut opts = std::fs::OpenOptions::new();
            opts.write(true).create(true).truncate(true);
            #[cfg(unix)]
            {
                use std::os::unix::fs::OpenOptionsExt as _;
                opts.mode(0o600);
            }
            let mut f = opts.open(&tmp)?;
            f.write_all(text.as_bytes())?;
            f.sync_all()?;
        }
        std::fs::rename(&tmp, path)?;
        Ok(())
    }

    /// Set one entry, replacing an earlier one for the same parameter.
    pub(crate) fn upsert(
        &mut self,
        group: &str,
        name: &str,
        value: toml::Value,
        overrode: toml::Value,
    ) {
        match self
            .entries
            .iter_mut()
            .find(|e| e.group == group && e.name == name)
        {
            Some(e) => {
                e.value = value;
                e.overrode = overrode;
            }
            None => self.entries.push(Entry {
                group: group.to_string(),
                name: name.to_string(),
                value,
                overrode,
            }),
        }
    }
}

/// A device's value as TOML.
pub(crate) fn to_toml(v: &ConfigValue) -> toml::Value {
    match v {
        ConfigValue::Bool(b) => toml::Value::Boolean(*b),
        ConfigValue::Integer(i) => toml::Value::Integer(*i),
        ConfigValue::Text(t) => toml::Value::String(t.clone()),
        _ => toml::Value::String(v.to_string()),
    }
}

/// A TOML value as a device's, when it is one of the three kinds.
pub(crate) fn from_toml(v: &toml::Value) -> Option<ConfigValue> {
    match v {
        toml::Value::Boolean(b) => Some(ConfigValue::Bool(*b)),
        toml::Value::Integer(i) => Some(ConfigValue::Integer(*i)),
        toml::Value::String(t) => Some(ConfigValue::Text(t.clone())),
        _ => None,
    }
}

/// A fingerprint of the schema — every group's name and class, every
/// parameter's name, kind, bounds, unit and sensitivity — stable across
/// toolchains, which the standard hasher is not. FNV-1a, 64 bits, hex.
pub(crate) fn schema_hash(schema: &Schema) -> String {
    let mut text = String::new();
    for g in &schema.groups {
        text.push_str(&format!("{}:{:?}\n", g.name, g.class));
        for p in &g.parameters {
            let kind = match &p.kind {
                ParamKind::Bool => "bool".to_string(),
                ParamKind::Integer { min, max, unit } => {
                    format!("integer:{min:?}:{max:?}:{unit:?}")
                }
                ParamKind::Text => "text".to_string(),
                _ => "other".to_string(),
            };
            text.push_str(&format!("  {}:{kind}:{}\n", p.name, p.sensitive));
        }
    }
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    for b in text.bytes() {
        h ^= u64::from(b);
        h = h.wrapping_mul(0x0100_0000_01b3);
    }
    format!("{h:016x}")
}

#[cfg(test)]
mod tests {
    use super::*;
    use modem_device::config::{ConfigGroup, ParamClass, ParamSpec};

    fn schema() -> Schema {
        Schema::new().with(
            ConfigGroup::new("poll", ParamClass::Hot, "").with(ParamSpec::new(
                "signal_poll_s",
                ParamKind::integer(Some(0), None, Some("s")),
                "",
            )),
        )
    }

    #[test]
    fn the_file_round_trips_and_is_private() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("sat0.overlay.toml");
        let mut o = Overlay::new(schema_hash(&schema()));
        o.upsert(
            "poll",
            "signal_poll_s",
            toml::Value::Integer(30),
            toml::Value::Integer(60),
        );
        o.upsert(
            "poll",
            "signal_poll_s",
            toml::Value::Integer(20),
            toml::Value::Integer(60),
        );
        o.save(&path).expect("saved");
        assert_eq!(o.entries.len(), 1, "replaced, not appended");
        let back = Overlay::load(&path).expect("read").expect("present");
        assert_eq!(back, o);
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt as _;
            let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
            assert_eq!(
                mode, 0o600,
                "a remote write that survives a reboot is guarded"
            );
        }
        assert!(
            Overlay::load(&dir.path().join("none.toml"))
                .unwrap()
                .is_none()
        );
    }

    #[test]
    fn the_hash_moves_when_the_schema_does_and_not_otherwise() {
        let a = schema_hash(&schema());
        assert_eq!(a, schema_hash(&schema()));
        let wider = Schema::new().with(ConfigGroup::new("poll", ParamClass::Hot, "").with(
            ParamSpec::new(
                "signal_poll_s",
                ParamKind::integer(Some(1), None, Some("s")),
                "",
            ),
        ));
        assert_ne!(a, schema_hash(&wider), "a bound is part of the contract");
    }
}