sector-f-linux

Sector F Linux
git clone https://git.sectorflabs.com/sector-f-linux.git
Log | Files | Refs | README | LICENSE

system.rs (10809B)


      1 //! The real system: the drives from `lsblk`, the install through `pkexec patina-install` (the
      2 //! polkit rule of ADR-0014 lets the live disc's greeter user do that and nobody else), restart
      3 //! through systemd.
      4 //!
      5 //! Progress is the bytes written to the drive over the size of the system being written: `bootc
      6 //! install` prints no percentage, and counting steps would give a bar that sits at 50% for five
      7 //! minutes. The kernel counts the sectors written per disk in /sys/block/<disk>/stat, so the bar
      8 //! follows the real thing, as an estimate, and never claims to be done before the command is.
      9 
     10 use std::collections::VecDeque;
     11 use std::io::{BufRead, BufReader};
     12 use std::process::{Command, Stdio};
     13 use std::sync::mpsc::Sender;
     14 use std::sync::{Arc, Mutex};
     15 use std::time::Duration;
     16 
     17 use serde_json::Value;
     18 
     19 use crate::backend::{Backend, Drive, Event, gigabytes};
     20 
     21 const MIN_BYTES: u64 = 12 * 1024 * 1024 * 1024;
     22 const INSTALL: &str = "/usr/libexec/patina-install";
     23 
     24 pub struct System;
     25 
     26 impl Backend for System {
     27     fn drives(&self) -> Vec<Drive> {
     28         let out = Command::new("lsblk")
     29             .args([
     30                 "-J",
     31                 "-b",
     32                 "-o",
     33                 "NAME,PATH,TYPE,SIZE,MODEL,SERIAL,RO,FSTYPE,LABEL,PARTLABEL,MOUNTPOINTS",
     34             ])
     35             .output();
     36         let Ok(out) = out else { return Vec::new() };
     37         let text = String::from_utf8_lossy(&out.stdout);
     38         parse_drives(&text, live_disk().as_deref())
     39     }
     40 
     41     fn install(&self, drive: &Drive, tx: Sender<Event>) {
     42         let path = drive.path.clone();
     43         std::thread::spawn(move || run_install(&path, &tx));
     44     }
     45 
     46     fn restart(&self) -> Result<(), String> {
     47         let out = Command::new("systemctl")
     48             .arg("reboot")
     49             .output()
     50             .map_err(|e| e.to_string())?;
     51         if out.status.success() {
     52             Ok(())
     53         } else {
     54             Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
     55         }
     56     }
     57 }
     58 
     59 /// The disk the live system booted from (the stick or the disc), by name: `sda`.
     60 fn live_disk() -> Option<String> {
     61     let src = Command::new("findmnt")
     62         .args(["-no", "SOURCE", "/run/initramfs/live"])
     63         .output()
     64         .ok()?;
     65     let src = String::from_utf8_lossy(&src.stdout).trim().to_string();
     66     if src.is_empty() {
     67         return None;
     68     }
     69     let parent = Command::new("lsblk")
     70         .args(["-no", "PKNAME", &src])
     71         .output()
     72         .ok()?;
     73     let parent = String::from_utf8_lossy(&parent.stdout)
     74         .lines()
     75         .next()?
     76         .trim()
     77         .to_string();
     78     Some(if parent.is_empty() {
     79         src.rsplit('/').next()?.to_string()
     80     } else {
     81         parent
     82     })
     83 }
     84 
     85 fn text(v: &Value, key: &str) -> String {
     86     v[key].as_str().unwrap_or("").trim().to_string()
     87 }
     88 
     89 /// lsblk prints numbers and booleans as such or as strings, by version.
     90 fn number(v: &Value, key: &str) -> u64 {
     91     match &v[key] {
     92         Value::Number(n) => n.as_u64().unwrap_or(0),
     93         Value::String(s) => s.parse().unwrap_or(0),
     94         _ => 0,
     95     }
     96 }
     97 
     98 fn mounts(v: &Value, into: &mut Vec<String>) {
     99     if let Some(list) = v["mountpoints"].as_array() {
    100         into.extend(list.iter().filter_map(|m| m.as_str()).map(String::from));
    101     }
    102     for child in v["children"].as_array().into_iter().flatten() {
    103         mounts(child, into);
    104     }
    105 }
    106 
    107 /// What a partition is, to a person: its label and filesystem, or its type.
    108 fn describe(v: &Value) -> Option<String> {
    109     let (label, part, fs) = (text(v, "label"), text(v, "partlabel"), text(v, "fstype"));
    110     let name = if !label.is_empty() { label } else { part };
    111     match (name.is_empty(), fs.is_empty()) {
    112         (false, false) => Some(format!("{name} ({fs})")),
    113         (false, true) => Some(name),
    114         (true, false) => Some(fs),
    115         (true, true) => None,
    116     }
    117 }
    118 
    119 /// The whole disks in lsblk's JSON, with why each can or cannot be chosen. `live` is the disk the
    120 /// system booted from. (`patina-install` checks all of this again: this is for showing it.)
    121 pub fn parse_drives(json: &str, live: Option<&str>) -> Vec<Drive> {
    122     let Ok(root) = serde_json::from_str::<Value>(json) else {
    123         return Vec::new();
    124     };
    125     let mut drives = Vec::new();
    126     for disk in root["blockdevices"].as_array().into_iter().flatten() {
    127         if text(disk, "type") != "disk" {
    128             continue;
    129         }
    130         let name = text(disk, "name");
    131         let bytes = number(disk, "size");
    132         let mut contents: Vec<String> = Vec::new();
    133         for part in disk["children"].as_array().into_iter().flatten() {
    134             if let Some(d) = describe(part)
    135                 && !contents.contains(&d)
    136             {
    137                 contents.push(d);
    138             }
    139         }
    140         if contents.is_empty() {
    141             contents.push(describe(disk).unwrap_or_else(|| "Empty".into()));
    142         }
    143         let mut mounted = Vec::new();
    144         mounts(disk, &mut mounted);
    145         let unusable = if live == Some(name.as_str()) {
    146             Some("The install disc is on this drive".to_string())
    147         } else if !mounted.is_empty() {
    148             Some(format!("In use (mounted at {})", mounted[0]))
    149         } else if number(disk, "ro") != 0 || text(disk, "ro") == "true" {
    150             Some("Read-only".to_string())
    151         } else if bytes < MIN_BYTES {
    152             Some(format!("Smaller than {}", gigabytes(MIN_BYTES)))
    153         } else {
    154             None
    155         };
    156         let model = text(disk, "model");
    157         drives.push(Drive {
    158             path: text(disk, "path"),
    159             model: if model.is_empty() { name } else { model },
    160             serial: text(disk, "serial"),
    161             bytes,
    162             contents,
    163             unusable,
    164         });
    165     }
    166     drives
    167 }
    168 
    169 /// Sectors written to a disk so far, from /sys/block/<disk>/stat.
    170 fn sectors_written(disk: &str) -> Option<u64> {
    171     let stat = std::fs::read_to_string(format!("/sys/block/{disk}/stat")).ok()?;
    172     stat.split_whitespace().nth(6)?.parse().ok()
    173 }
    174 
    175 fn run_install(path: &str, tx: &Sender<Event>) {
    176     let disk = path.rsplit('/').next().unwrap_or(path).to_string();
    177     // pkexec refuses a caller whose SHELL is not in /etc/shells, and the greeter user's is nologin.
    178     let child = Command::new("sh")
    179         .args([
    180             "-c",
    181             &format!("exec pkexec {INSTALL} \"$1\" 2>&1"),
    182             "sh",
    183             path,
    184         ])
    185         .env("SHELL", "/bin/sh")
    186         .stdout(Stdio::piped())
    187         .spawn();
    188     let mut child = match child {
    189         Ok(c) => c,
    190         Err(e) => {
    191             let _ = tx.send(Event::Failed(format!("cannot start the installer: {e}")));
    192             return;
    193         }
    194     };
    195     let expected = Arc::new(Mutex::new(0u64));
    196     let running = Arc::new(Mutex::new(true));
    197     let base = sectors_written(&disk).unwrap_or(0);
    198     {
    199         let (tx, expected, running, disk) = (tx.clone(), expected.clone(), running.clone(), disk);
    200         std::thread::spawn(move || {
    201             while *running.lock().unwrap() {
    202                 let size = *expected.lock().unwrap();
    203                 if size > 0
    204                     && let Some(now) = sectors_written(&disk)
    205                 {
    206                     let done = now.saturating_sub(base) as f64 * 512.0 / size as f64;
    207                     let _ = tx.send(Event::Progress(done.min(0.99) as f32));
    208                 }
    209                 std::thread::sleep(Duration::from_millis(500));
    210             }
    211         });
    212     }
    213     let mut tail: VecDeque<String> = VecDeque::new();
    214     let stdout = child.stdout.take().expect("piped");
    215     for line in BufReader::new(stdout).lines().map_while(Result::ok) {
    216         if let Some(bytes) = line.strip_prefix("SIZE ") {
    217             *expected.lock().unwrap() = bytes.trim().parse().unwrap_or(0);
    218         } else if let Some(step) = line.strip_prefix("STEP ") {
    219             // "STEP 1/2 Writing the system to /dev/vda"
    220             let what = step.split_once(' ').map_or(step, |(_, w)| w);
    221             let _ = tx.send(Event::Step(what.to_string()));
    222         } else if !line.trim().is_empty() {
    223             tail.push_back(line);
    224             if tail.len() > 6 {
    225                 tail.pop_front();
    226             }
    227         }
    228     }
    229     let status = child.wait();
    230     *running.lock().unwrap() = false;
    231     if matches!(status, Ok(s) if s.success()) {
    232         let _ = tx.send(Event::Progress(1.0));
    233         let _ = tx.send(Event::Done);
    234     } else {
    235         let why = tail.into_iter().collect::<Vec<_>>().join("\n");
    236         let _ = tx.send(Event::Failed(why));
    237     }
    238 }
    239 
    240 #[cfg(test)]
    241 mod tests {
    242     use super::*;
    243 
    244     const JSON: &str = r#"{"blockdevices":[
    245       {"name":"nvme0n1","path":"/dev/nvme0n1","type":"disk","size":500107862016,"model":"Samsung 980","serial":"S1","ro":false,"fstype":null,"label":null,"partlabel":null,"mountpoints":[null],
    246        "children":[
    247          {"name":"nvme0n1p1","type":"part","fstype":"vfat","label":null,"partlabel":"EFI System Partition","mountpoints":[null]},
    248          {"name":"nvme0n1p2","type":"part","fstype":"ntfs","label":"Windows","partlabel":"Basic data partition","mountpoints":[null]}]},
    249       {"name":"sda","path":"/dev/sda","type":"disk","size":"32015679488","model":"Cruzer","serial":"X","ro":"0","mountpoints":[null],
    250        "children":[{"name":"sda1","type":"part","fstype":"iso9660","label":"SECTORF-LIVE","mountpoints":["/run/initramfs/live"]}]},
    251       {"name":"sdb","path":"/dev/sdb","type":"disk","size":8000000000,"model":null,"ro":false,"mountpoints":[null]},
    252       {"name":"sdc","path":"/dev/sdc","type":"disk","size":64000000000,"model":"Blank","ro":false,"mountpoints":[null]},
    253       {"name":"sr0","path":"/dev/sr0","type":"rom","size":1,"mountpoints":[null]},
    254       {"name":"loop0","path":"/dev/loop0","type":"loop","size":1,"mountpoints":[null]}]}"#;
    255 
    256     #[test]
    257     fn only_whole_disks_with_a_reason_when_unusable() {
    258         let d = parse_drives(JSON, Some("sda"));
    259         let names: Vec<_> = d.iter().map(|d| d.path.as_str()).collect();
    260         assert_eq!(names, ["/dev/nvme0n1", "/dev/sda", "/dev/sdb", "/dev/sdc"]);
    261         assert_eq!(d[0].unusable, None);
    262         assert_eq!(
    263             d[0].contents,
    264             ["EFI System Partition (vfat)", "Windows (ntfs)"]
    265         );
    266         assert_eq!(
    267             d[1].unusable.as_deref(),
    268             Some("The install disc is on this drive")
    269         );
    270         assert!(d[2].unusable.as_deref().unwrap().starts_with("Smaller"));
    271         assert_eq!(d[2].model, "sdb");
    272         assert_eq!(d[3].contents, ["Empty"]);
    273         assert_eq!(d[3].unusable, None);
    274     }
    275 
    276     #[test]
    277     fn a_mounted_drive_is_not_offered() {
    278         let d = parse_drives(JSON, None);
    279         assert!(d[1].unusable.as_deref().unwrap().starts_with("In use"));
    280     }
    281 
    282     #[test]
    283     fn garbage_gives_no_drives() {
    284         assert!(parse_drives("not json", None).is_empty());
    285     }
    286 }