garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /pkg/src/system.rs

raw

//! System updates: the two places on the system disk a system can be kept
//! in (`/system/a`, `/system/b`), and the boot record (`/system/boot`) that
//! says which runs. The kernel the device's boot medium holds (QEMU's
//! `-kernel`, an SD card's `Image`) is the **boot kernel**: it reads the
//! record at every start and either runs itself or hands the machine to the
//! kernel kept in a slot, which then runs as if the loader had started it.
//!
//! A new system goes into the slot not running, and the record says to try
//! it once (`next`). The boot kernel marks the try (`tried`) before it hands
//! over; the new system, once its display server has drawn, makes it the
//! one that runs (`current`). A system that never gets that far has had its
//! try: at the next start the boot kernel notes it as failed (`failed`) and
//! runs the one before. A power cut at any point leaves the record as before
//! or after one write: the file system's transactions see to that.
//!
//! The record is `key=value` lines, as a manifest is.

use alloc::string::String;

/// The two slots.
pub const SLOTS: [Slot; 2] = [Slot::A, Slot::B];

/// Where the record is, on the system disk.
pub const RECORD: &str = "/system/boot";

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Slot {
    A,
    B,
}

impl Slot {
    pub fn name(self) -> &'static str {
        match self {
            Slot::A => "a",
            Slot::B => "b",
        }
    }

    pub fn parse(text: &str) -> Option<Slot> {
        match text.trim() {
            "a" => Some(Slot::A),
            "b" => Some(Slot::B),
            _ => None,
        }
    }

    /// The other one.
    pub fn other(self) -> Slot {
        match self {
            Slot::A => Slot::B,
            Slot::B => Slot::A,
        }
    }

    /// Its folder on the system disk.
    pub fn folder(self) -> &'static str {
        match self {
            Slot::A => "/system/a",
            Slot::B => "/system/b",
        }
    }

    /// As a number, for a system call: 1 for a, 2 for b (0 is the boot
    /// kernel's own system).
    pub fn number(self) -> u64 {
        match self {
            Slot::A => 1,
            Slot::B => 2,
        }
    }

    pub fn from_number(n: u64) -> Option<Slot> {
        match n {
            1 => Some(Slot::A),
            2 => Some(Slot::B),
            _ => None,
        }
    }
}

/// The boot record.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub struct Record {
    /// The slot whose system runs, once one has started well; none: the
    /// boot kernel's own.
    pub current: Option<Slot>,
    /// A slot to try at the next start.
    pub next: Option<Slot>,
    /// Whether the boot kernel has handed over to `next` once already.
    pub tried: bool,
    /// The slot whose try did not start, until a new one is tried.
    pub failed: Option<Slot>,
}

impl Record {
    pub fn parse(text: &str) -> Record {
        let field = |key: &str| {
            text.lines()
                .find_map(|l| l.strip_prefix(key)?.strip_prefix('='))
                .map(str::trim)
        };
        Record {
            current: field("current").and_then(Slot::parse),
            next: field("next").and_then(Slot::parse),
            tried: field("tried") == Some("1"),
            failed: field("failed").and_then(Slot::parse),
        }
    }

    pub fn text(&self) -> String {
        let mut out = String::new();
        if let Some(slot) = self.current {
            out += &alloc::format!("current={}\n", slot.name());
        }
        if let Some(slot) = self.next {
            out += &alloc::format!("next={}\ntried={}\n", slot.name(), u8::from(self.tried));
        }
        if let Some(slot) = self.failed {
            out += &alloc::format!("failed={}\n", slot.name());
        }
        out
    }

    /// What the boot kernel does at a start: the slot to hand over to (none:
    /// run itself), and the record to write first, if it changes.
    pub fn at_start(self) -> (Option<Slot>, Option<Record>) {
        match self.next {
            // A try: marked as had before it is made.
            Some(next) if !self.tried => (
                Some(next),
                Some(Record {
                    tried: true,
                    failed: None,
                    ..self
                }),
            ),
            // It had its try and did not start: back to the one before.
            Some(next) => (
                self.current,
                Some(Record {
                    next: None,
                    tried: false,
                    failed: Some(next),
                    ..self
                }),
            ),
            None => (self.current, None),
        }
    }

    /// The record once the system in `running` has started well: the one
    /// that runs from now on, if it was being tried. None: nothing changes.
    pub fn started(self, running: Slot) -> Option<Record> {
        (self.next == Some(running) && self.tried).then_some(Record {
            current: Some(running),
            next: None,
            tried: false,
            failed: None,
        })
    }

    /// The slot a new system may be put in: never the one that runs, nor
    /// the one before it that a failed try falls back to.
    pub fn free(self, running: Option<Slot>) -> Slot {
        match running.or(self.current) {
            Some(slot) => slot.other(),
            None => Slot::A,
        }
    }
}

/// Whether a system of `version` is newer than one of `than`: both whole
/// numbers (the commits on main), else neither is.
pub fn newer(version: &str, than: &str) -> bool {
    match (version.trim().parse::<u64>(), than.trim().parse::<u64>()) {
        (Ok(v), Ok(t)) => v > t,
        _ => false,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_try_is_marked_before_it_is_made() {
        let record = Record {
            current: Some(Slot::A),
            next: Some(Slot::B),
            ..Record::default()
        };
        let (boot, write) = record.at_start();
        assert_eq!(boot, Some(Slot::B));
        let write = write.unwrap();
        assert!(write.tried);
        assert_eq!(Record::parse(&write.text()), write);
    }

    #[test]
    fn a_try_that_did_not_start_falls_back() {
        let record = Record {
            current: Some(Slot::A),
            next: Some(Slot::B),
            tried: true,
            failed: None,
        };
        let (boot, write) = record.at_start();
        assert_eq!(boot, Some(Slot::A));
        assert_eq!(
            write,
            Some(Record {
                current: Some(Slot::A),
                next: None,
                tried: false,
                failed: Some(Slot::B),
            })
        );
    }

    #[test]
    fn a_first_try_falls_back_to_the_boot_kernel() {
        let record = Record {
            next: Some(Slot::A),
            tried: true,
            ..Record::default()
        };
        assert_eq!(record.at_start().0, None);
    }

    #[test]
    fn a_started_try_becomes_current() {
        let record = Record {
            current: Some(Slot::A),
            next: Some(Slot::B),
            tried: true,
            failed: None,
        };
        assert_eq!(record.started(Slot::A), None);
        let after = record.started(Slot::B).unwrap();
        assert_eq!(after.current, Some(Slot::B));
        assert_eq!(after.at_start(), (Some(Slot::B), None));
    }

    #[test]
    fn nothing_recorded_runs_the_boot_kernel() {
        assert_eq!(Record::parse("").at_start(), (None, None));
        assert_eq!(Record::default().free(None), Slot::A);
    }

    #[test]
    fn a_new_system_never_goes_over_the_running_one() {
        let record = Record {
            current: Some(Slot::A),
            ..Record::default()
        };
        assert_eq!(record.free(Some(Slot::A)), Slot::B);
        assert_eq!(record.free(None), Slot::B);
    }

    #[test]
    fn versions_are_numbers() {
        assert!(newer("412", "411"));
        assert!(!newer("411", "411"));
        assert!(!newer("dev", "1"));
    }
}