1use std::collections::{HashMap, HashSet};
2use std::env;
3use std::path::Path;
4use std::process::{Command, Stdio};
5use std::sync::OnceLock;
6
7use anyhow::{Context, Result, anyhow};
8use camino::{Utf8Path, Utf8PathBuf};
9use cap_std_ext::cap_std::fs::Dir;
10use fn_error_context::context;
11use serde::Deserialize;
12
13use bootc_utils::CommandRunExt;
14
15pub mod dps;
16use dps::{BIOS_BOOT, ESP, XBOOTLDR};
17
18fn have_udev() -> bool {
28 static HAVE_UDEV: OnceLock<bool> = OnceLock::new();
29 *HAVE_UDEV.get_or_init(|| {
30 let r = Path::new("/run/udev/data").exists();
31 if !r {
32 tracing::debug!(
33 "udev database not available, will use blkid -p for partition metadata"
34 );
35 }
36 r
37 })
38}
39
40fn blkid_probe(dev: &str) -> Result<HashMap<String, String>> {
51 let mut cmd = Command::new("blkid");
52 cmd.args(["-p", "-o", "export"]).arg(dev);
53 cmd.log_debug();
54 let output = cmd.output().context("Failed to run blkid")?;
55 if !output.status.success() {
56 if output.status.code() == Some(2) {
58 return Ok(HashMap::new());
59 }
60 let stderr = String::from_utf8_lossy(&output.stderr);
61 anyhow::bail!(
62 "blkid -p failed on {dev} (exit status {}): {stderr}",
63 output.status
64 );
65 }
66 let text = String::from_utf8(output.stdout).context("blkid output is not UTF-8")?;
67 let mut props = HashMap::new();
68 for line in text.lines() {
69 if let Some((key, value)) = line.split_once('=') {
70 props.insert(key.to_string(), value.to_string());
71 }
72 }
73 Ok(props)
74}
75
76pub const ESP_ID_MBR: &[u8] = &[0x06, 0xEF];
81
82#[derive(Debug, Deserialize)]
83struct DevicesOutput {
84 blockdevices: Vec<Device>,
85}
86
87#[allow(dead_code)]
88#[derive(Debug, Clone, serde::Serialize, Deserialize)]
89pub struct Device {
90 pub name: String,
91 pub serial: Option<String>,
92 pub model: Option<String>,
93 pub partlabel: Option<String>,
94 pub parttype: Option<String>,
95 pub partuuid: Option<String>,
96 pub partn: Option<u32>,
98 pub children: Option<Vec<Device>>,
99 pub size: u64,
100 #[serde(rename = "maj:min")]
101 pub maj_min: Option<String>,
102 pub start: Option<u64>,
105
106 pub label: Option<String>,
108 pub fstype: Option<String>,
109 pub uuid: Option<String>,
110 pub path: Option<String>,
111 pub pttype: Option<String>,
113 pub ro: Option<bool>,
116}
117
118impl Device {
119 pub fn path(&self) -> String {
121 self.path.clone().unwrap_or(format!("/dev/{}", &self.name))
122 }
123
124 #[allow(dead_code)]
126 pub fn node(&self) -> String {
127 self.path()
128 }
129
130 #[allow(dead_code)]
131 pub fn has_children(&self) -> bool {
132 self.children.as_ref().is_some_and(|v| !v.is_empty())
133 }
134
135 pub fn is_mpath(&self) -> Result<bool> {
137 let dm_path = Utf8PathBuf::from_path_buf(std::fs::canonicalize(self.path())?)
138 .map_err(|_| anyhow::anyhow!("Non-UTF8 path"))?;
139 let dm_name = dm_path.file_name().unwrap_or("");
140 let uuid_path = Utf8PathBuf::from(format!("/sys/class/block/{dm_name}/dm/uuid"));
141
142 if uuid_path.exists() {
143 let uuid = std::fs::read_to_string(&uuid_path)
144 .with_context(|| format!("Failed to read {uuid_path}"))?;
145 if uuid.trim_start().starts_with("mpath-") {
146 return Ok(true);
147 }
148 }
149 Ok(false)
150 }
151
152 pub fn get_esp_partition_number(&self) -> Result<String> {
161 let esp_device = self.find_partition_of_esp()?;
162 let devname = &esp_device.name;
163
164 let partition_path = Utf8PathBuf::from(format!("/sys/class/block/{devname}/partition"));
165 if partition_path.exists() {
166 return std::fs::read_to_string(&partition_path)
167 .with_context(|| format!("Failed to read {partition_path}"));
168 }
169
170 if self.is_mpath()? {
172 if let Some(partn) = esp_device.partn {
173 return Ok(partn.to_string());
174 }
175 let parent_path = self.path();
180 let esp_path = esp_device.path();
181 if let Some(n) = parse_partition_number_from_suffix(&parent_path, &esp_path) {
182 return Ok(n);
183 }
184 }
185 anyhow::bail!("Not supported for {devname}")
186 }
187
188 pub fn find_partition_of_bios_boot(&self) -> Option<&Device> {
190 self.find_partition_of_type(BIOS_BOOT)
191 }
192
193 pub fn find_colocated_esps(&self) -> Result<Option<Vec<Device>>> {
197 let mut esps = Vec::new();
198 for root in &self.find_all_roots()? {
199 if let Some(esp) = root.find_partition_of_esp_optional()? {
200 esps.push(esp.clone());
201 }
202 }
203 Ok((!esps.is_empty()).then_some(esps))
204 }
205
206 pub fn find_first_colocated_esp(&self) -> Result<Device> {
212 self.find_colocated_esps()?
213 .and_then(|mut v| Some(v.remove(0)))
214 .ok_or_else(|| anyhow!("No ESP partition found among backing devices"))
215 }
216
217 pub fn find_colocated_bios_boot(&self) -> Result<Option<Vec<Device>>> {
221 let bios_boots: Vec<_> = self
222 .find_all_roots()?
223 .iter()
224 .filter_map(|root| root.find_partition_of_bios_boot())
225 .cloned()
226 .collect();
227 Ok((!bios_boots.is_empty()).then_some(bios_boots))
228 }
229
230 pub fn find_partition_of_type(&self, parttype: &str) -> Option<&Device> {
232 self.children.as_ref()?.iter().find(|child| {
233 child
234 .parttype
235 .as_ref()
236 .is_some_and(|pt| pt.eq_ignore_ascii_case(parttype))
237 })
238 }
239
240 pub fn find_partition_of_xbootldr(&self) -> Option<&Device> {
245 self.find_partition_of_type(XBOOTLDR)
246 .filter(|part| part.fstype.as_deref() == Some("vfat"))
247 }
248
249 pub fn find_sibling_xbootldr(&self) -> Result<Option<Device>> {
252 for parent in self.list_parents()?.unwrap_or_default() {
253 let parent = list_dev(Utf8Path::new(&parent.path()))?;
254 if let Some(xbootldr) = parent.find_partition_of_xbootldr() {
255 return Ok(Some(xbootldr.clone()));
256 }
257 }
258 Ok(None)
259 }
260
261 pub fn find_partition_of_esp_optional(&self) -> Result<Option<&Device>> {
274 let Some(children) = self.children.as_ref() else {
275 return Ok(None);
276 };
277 let direct = match self.pttype.as_deref() {
278 Some("dos") => children.iter().find(|child| {
279 child
280 .parttype
281 .as_ref()
282 .and_then(|pt| {
283 let pt = pt.strip_prefix("0x").unwrap_or(pt);
284 u8::from_str_radix(pt, 16).ok()
285 })
286 .is_some_and(|pt| ESP_ID_MBR.contains(&pt))
287 }),
288 Some("gpt") | None => self.find_partition_of_type(ESP),
291 Some(other) => return Err(anyhow!("Unsupported partition table type: {other}")),
292 };
293 if direct.is_some() {
294 return Ok(direct);
295 }
296 for child in children {
299 if child.pttype.is_some() {
300 if let Some(esp) = child.find_partition_of_esp_optional()? {
301 return Ok(Some(esp));
302 }
303 }
304 }
305 Ok(None)
306 }
307
308 pub fn find_partition_of_esp(&self) -> Result<&Device> {
313 self.find_partition_of_esp_optional()?
314 .ok_or_else(|| anyhow!("ESP partition not found on {}", self.path()))
315 }
316
317 pub fn find_device_by_partno(&self, partno: u32) -> Result<&Device> {
319 self.children
320 .as_ref()
321 .ok_or_else(|| anyhow!("Device has no children"))?
322 .iter()
323 .find(|child| child.partn == Some(partno))
324 .ok_or_else(|| anyhow!("Missing partition for index {partno}"))
325 }
326
327 pub fn refresh(&mut self) -> Result<()> {
330 let path = self.path();
331 let new_device = list_dev(Utf8Path::new(&path))?;
332 *self = new_device;
333 Ok(())
334 }
335
336 fn read_sysfs_property<T>(&self, property: &str) -> Result<Option<T>>
338 where
339 T: std::str::FromStr,
340 T::Err: std::error::Error + Send + Sync + 'static,
341 {
342 let Some(majmin) = self.maj_min.as_deref() else {
343 return Ok(None);
344 };
345 let sysfs_path = format!("/sys/dev/block/{majmin}/{property}");
346 if !Utf8Path::new(&sysfs_path).try_exists()? {
347 return Ok(None);
348 }
349 let value = std::fs::read_to_string(&sysfs_path)
350 .with_context(|| format!("Reading {sysfs_path}"))?;
351 let parsed = value
352 .trim()
353 .parse()
354 .with_context(|| format!("Parsing sysfs {property} property"))?;
355 tracing::debug!("backfilled {property} to {value}");
356 Ok(Some(parsed))
357 }
358
359 pub fn backfill_missing(&mut self) -> Result<()> {
366 if self.start.is_none() {
369 self.start = self.read_sysfs_property("start")?;
370 }
371 if self.partn.is_none() {
374 self.partn = self.read_sysfs_property("partition")?;
375 }
376 if !have_udev() && (self.parttype.is_none() || self.pttype.is_none()) {
380 let props = blkid_probe(&self.path())?;
381 if self.parttype.is_none() {
382 self.parttype = props.get("PART_ENTRY_TYPE").cloned();
383 }
384 if self.pttype.is_none() {
385 self.pttype = props.get("PTTYPE").cloned();
386 }
387 }
388 for child in self.children.iter_mut().flatten() {
390 child.backfill_missing()?;
391 }
392 Ok(())
393 }
394
395 pub fn list_parents(&self) -> Result<Option<Vec<Device>>> {
402 let path = self.path();
403 let output: DevicesOutput = Command::new("lsblk")
404 .args(["-J", "-b", "-O", "--inverse"])
405 .arg(&path)
406 .log_debug()
407 .run_and_parse_json()?;
408
409 let device = output
410 .blockdevices
411 .into_iter()
412 .next()
413 .ok_or_else(|| anyhow!("no device output from lsblk --inverse for {path}"))?;
414
415 match device.children {
416 Some(mut children) if !children.is_empty() => {
417 for child in &mut children {
418 child.backfill_missing()?;
419 }
420 Ok(Some(children))
421 }
422 _ => Ok(None),
423 }
424 }
425
426 pub fn require_single_root(&self) -> Result<Device> {
432 let mut roots = self.find_all_roots()?;
433 match roots.len() {
434 1 => Ok(roots.remove(0)),
435 n => anyhow::bail!(
436 "Expected a single root device for {}, but found {n}",
437 self.path()
438 ),
439 }
440 }
441
442 pub fn find_all_roots(&self) -> Result<Vec<Device>> {
449 let Some(parents) = self.list_parents()? else {
450 return Ok(vec![list_dev(Utf8Path::new(&self.path()))?]);
452 };
453
454 let mut roots = Vec::new();
455 let mut seen = HashSet::new();
456 let mut queue = parents;
457 while let Some(mut device) = queue.pop() {
458 match device.children.take() {
459 Some(grandparents) if !grandparents.is_empty() => {
460 queue.extend(grandparents);
461 }
462 _ => {
463 let name = device.name.clone();
466 if seen.insert(name) {
467 roots.push(list_dev(Utf8Path::new(&device.path()))?);
469 }
470 }
471 }
472 }
473 Ok(roots)
474 }
475}
476
477#[context("Listing device {dev}")]
478pub fn list_dev(dev: &Utf8Path) -> Result<Device> {
479 let mut devs: DevicesOutput = Command::new("lsblk")
480 .args(["-J", "-b", "-O"])
481 .arg(dev)
482 .log_debug()
483 .run_and_parse_json()?;
484 for dev in devs.blockdevices.iter_mut() {
485 dev.backfill_missing()?;
486 }
487 devs.blockdevices
488 .into_iter()
489 .next()
490 .ok_or_else(|| anyhow!("no device output from lsblk for {dev}"))
491}
492
493#[context("Finding block device for ZFS dataset {dataset}")]
494fn list_dev_for_zfs_dataset(dataset: &str) -> Result<Device> {
495 let dataset = dataset.strip_prefix("ZFS=").unwrap_or(dataset);
496 let pool = dataset
497 .split('/')
498 .next()
499 .ok_or_else(|| anyhow!("Invalid ZFS dataset: {dataset}"))?;
500
501 let output = Command::new("zpool")
502 .args(["list", "-H", "-v", "-P", pool])
503 .run_get_string()
504 .with_context(|| format!("Querying ZFS pool {pool}"))?;
505
506 for line in output.lines() {
507 if line.starts_with('\t') || line.starts_with(' ') {
508 let dev_path = line.trim_start().split('\t').next().unwrap_or("").trim();
509 if dev_path.starts_with('/') {
510 return list_dev(Utf8Path::new(dev_path));
511 }
512 }
513 }
514
515 anyhow::bail!("Could not find a block device backing ZFS pool {pool}")
516}
517
518pub fn list_dev_by_dir(dir: &Dir) -> Result<Device> {
520 let fsinfo = bootc_mount::inspect_filesystem_of_dir(dir)?;
521 let source = &fsinfo.source;
522 if fsinfo.fstype == "zfs" || source.starts_with("ZFS=") {
523 return list_dev_for_zfs_dataset(source);
524 }
525 list_dev(&Utf8PathBuf::from(source))
526}
527
528const ZFS_SUPER_MAGIC: u32 = 0x2fc12fc1;
530
531fn is_block_backed(st_dev: u64, fs_magic: u32) -> bool {
539 rustix::fs::major(st_dev) != 0
540 || fs_magic == libc::BTRFS_SUPER_MAGIC as u32
541 || fs_magic == ZFS_SUPER_MAGIC
542}
543
544#[context("Finding block device backing directory")]
550pub fn list_dev_by_dir_optional(dir: &Dir) -> Result<Option<Device>> {
551 let st_dev = rustix::fs::fstat(dir)?.st_dev;
552 let fs_magic = rustix::fs::fstatfs(dir)?.f_type as u32;
554 if !is_block_backed(st_dev, fs_magic) {
555 tracing::debug!("No block device: st_dev={st_dev:#x} f_type={fs_magic:#x}");
556 return Ok(None);
557 }
558 list_dev_by_dir(dir).map(Some)
559}
560
561pub fn is_dir_backing_device_ro(dir: &Dir) -> Result<Option<bool>> {
572 let fsinfo = bootc_mount::inspect_filesystem_of_dir(dir)?;
573 let source = &fsinfo.source;
574 if !source.starts_with("/dev/") {
578 tracing::debug!("Filesystem source {source} is not a block device node");
579 return Ok(None);
580 }
581 let dev = list_dev(&Utf8PathBuf::from(source))?;
582 Ok(dev.ro)
583}
584
585pub struct LoopbackDevice {
586 pub dev: Option<Utf8PathBuf>,
587 cleanup_handle: Option<LoopbackCleanupHandle>,
589}
590
591struct LoopbackCleanupHandle {
593 child: std::process::Child,
595}
596
597impl LoopbackDevice {
598 pub fn new(path: &Path) -> Result<Self> {
600 let direct_io = match env::var("BOOTC_DIRECT_IO") {
601 Ok(val) => {
602 if val == "on" {
603 "on"
604 } else {
605 "off"
606 }
607 }
608 Err(_e) => "off",
609 };
610
611 let dev = Command::new("losetup")
612 .args([
613 "--show",
614 format!("--direct-io={direct_io}").as_str(),
615 "-P",
616 "--find",
617 ])
618 .arg(path)
619 .run_get_string()?;
620 let dev = Utf8PathBuf::from(dev.trim());
621 tracing::debug!("Allocated loopback {dev}");
622
623 let cleanup_handle = match Self::spawn_cleanup_helper(dev.as_str()) {
625 Ok(handle) => Some(handle),
626 Err(e) => {
627 tracing::warn!(
628 "Failed to spawn loopback cleanup helper for {}: {}. \
629 Loopback device may not be cleaned up if process is interrupted.",
630 dev,
631 e
632 );
633 None
634 }
635 };
636
637 Ok(Self {
638 dev: Some(dev),
639 cleanup_handle,
640 })
641 }
642
643 pub fn path(&self) -> &Utf8Path {
645 self.dev.as_deref().unwrap()
647 }
648
649 fn spawn_cleanup_helper(device_path: &str) -> Result<LoopbackCleanupHandle> {
652 let bootc_path = bootc_utils::reexec::executable_path()
654 .context("Failed to locate bootc binary for cleanup helper")?;
655
656 let mut cmd = Command::new(bootc_path);
658 cmd.args([
659 "internals",
660 "loopback-cleanup-helper",
661 "--device",
662 device_path,
663 ]);
664
665 cmd.env("BOOTC_LOOPBACK_CLEANUP_HELPER", "1");
667
668 cmd.stdin(Stdio::null());
670 cmd.stdout(Stdio::null());
671 let child = cmd
675 .spawn()
676 .context("Failed to spawn loopback cleanup helper")?;
677
678 Ok(LoopbackCleanupHandle { child })
679 }
680
681 fn impl_close(&mut self) -> Result<()> {
683 let Some(dev) = self.dev.take() else {
685 tracing::trace!("loopback device already deallocated");
686 return Ok(());
687 };
688
689 if let Some(mut cleanup_handle) = self.cleanup_handle.take() {
691 let _ = cleanup_handle.child.kill();
693 }
694
695 Command::new("losetup")
696 .args(["-d", dev.as_str()])
697 .run_capture_stderr()
698 }
699
700 pub fn close(mut self) -> Result<()> {
702 self.impl_close()
703 }
704}
705
706impl Drop for LoopbackDevice {
707 fn drop(&mut self) {
708 let _ = self.impl_close();
710 }
711}
712
713pub async fn run_loopback_cleanup_helper(device_path: &str) -> Result<()> {
716 if std::env::var("BOOTC_LOOPBACK_CLEANUP_HELPER").is_err() {
718 anyhow::bail!("This function should only be called as a cleanup helper");
719 }
720
721 rustix::process::set_parent_process_death_signal(Some(rustix::process::Signal::TERM))
723 .context("Failed to set parent death signal")?;
724
725 tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
727 .expect("Failed to create signal stream")
728 .recv()
729 .await;
730
731 let output = std::process::Command::new("losetup")
733 .args(["-d", device_path])
734 .output();
735
736 match output {
737 Ok(output) if output.status.success() => {
738 tracing::info!("Cleaned up leaked loopback device {}", device_path);
740 std::process::exit(0);
741 }
742 Ok(output) => {
743 let stderr = String::from_utf8_lossy(&output.stderr);
744 tracing::error!(
745 "Failed to clean up loopback device {}: {}. Stderr: {}",
746 device_path,
747 output.status,
748 stderr.trim()
749 );
750 std::process::exit(1);
751 }
752 Err(e) => {
753 tracing::error!(
754 "Error executing losetup to clean up loopback device {}: {}",
755 device_path,
756 e
757 );
758 std::process::exit(1);
759 }
760 }
761}
762
763pub fn parse_size_mib(mut s: &str) -> Result<u64> {
765 let suffixes = [
766 ("MiB", 1u64),
767 ("M", 1u64),
768 ("GiB", 1024),
769 ("G", 1024),
770 ("TiB", 1024 * 1024),
771 ("T", 1024 * 1024),
772 ];
773 let mut mul = 1u64;
774 for (suffix, imul) in suffixes {
775 if let Some((sv, rest)) = s.rsplit_once(suffix) {
776 if !rest.is_empty() {
777 anyhow::bail!("Trailing text after size: {rest}");
778 }
779 s = sv;
780 mul = imul;
781 }
782 }
783 let v = s.parse::<u64>()?;
784 Ok(v * mul)
785}
786
787fn parse_partition_number_from_suffix(parent_path: &str, esp_path: &str) -> Option<String> {
799 let suffix = esp_path.strip_prefix(parent_path)?;
800 let digits = suffix.trim_start_matches(|c: char| !c.is_ascii_digit());
801 if digits.is_empty() {
802 return None;
803 }
804 Some(digits.to_string())
805}
806
807#[cfg(test)]
808mod test {
809 use super::*;
810
811 #[test]
812 fn test_is_block_backed() {
813 use rustix::fs::makedev;
814 let cases = [
816 (makedev(252, 3), libc::XFS_SUPER_MAGIC as u32, true),
817 (makedev(253, 0), libc::EXT4_SUPER_MAGIC as u32, true),
818 (makedev(0, 38), libc::BTRFS_SUPER_MAGIC as u32, true),
819 (makedev(0, 51), ZFS_SUPER_MAGIC, true),
820 (makedev(0, 29), libc::FUSE_SUPER_MAGIC as u32, false),
821 (makedev(0, 52), libc::NFS_SUPER_MAGIC as u32, false),
822 (makedev(0, 40), libc::OVERLAYFS_SUPER_MAGIC as u32, false),
823 (makedev(0, 23), libc::TMPFS_MAGIC as u32, false),
824 ];
825 for (st_dev, fs_magic, expected) in cases {
826 assert_eq!(
827 is_block_backed(st_dev, fs_magic),
828 expected,
829 "st_dev={st_dev:#x} f_type={fs_magic:#x}"
830 );
831 }
832 }
833
834 #[test]
835 fn test_list_dev_by_dir_optional_procfs() -> Result<()> {
836 let proc = Dir::open_ambient_dir("/proc", cap_std_ext::cap_std::ambient_authority())?;
837 assert!(list_dev_by_dir_optional(&proc)?.is_none());
838 Ok(())
839 }
840
841 #[test]
842 fn test_parse_size_mib() {
843 let ident_cases = [0, 10, 9, 1024].into_iter().map(|k| (k.to_string(), k));
844 let cases = [
845 ("0M", 0),
846 ("10M", 10),
847 ("10MiB", 10),
848 ("1G", 1024),
849 ("9G", 9216),
850 ("11T", 11 * 1024 * 1024),
851 ]
852 .into_iter()
853 .map(|(k, v)| (k.to_string(), v));
854 for (s, v) in ident_cases.chain(cases) {
855 assert_eq!(parse_size_mib(&s).unwrap(), v as u64, "Parsing {s}");
856 }
857 }
858
859 #[test]
860 fn test_parse_lsblk() {
861 let fixture = include_str!("../tests/fixtures/lsblk.json");
862 let devs: DevicesOutput = serde_json::from_str(fixture).unwrap();
863 let dev = devs.blockdevices.into_iter().next().unwrap();
864 assert_eq!(dev.partn, None);
866 let children = dev.children.as_deref().unwrap();
867 assert_eq!(children.len(), 3);
868 let first_child = &children[0];
869 assert_eq!(first_child.partn, Some(1));
870 assert_eq!(
871 first_child.parttype.as_deref().unwrap(),
872 "21686148-6449-6e6f-744e-656564454649"
873 );
874 assert_eq!(
875 first_child.partuuid.as_deref().unwrap(),
876 "3979e399-262f-4666-aabc-7ab5d3add2f0"
877 );
878 let part2 = dev.find_device_by_partno(2).unwrap();
880 assert_eq!(part2.partn, Some(2));
881 assert_eq!(part2.parttype.as_deref().unwrap(), ESP);
882 let esp = dev.find_partition_of_esp().unwrap();
884 assert_eq!(esp.partn, Some(2));
885 let bios = dev.find_partition_of_bios_boot().unwrap();
887 assert_eq!(bios.partn, Some(1));
888 assert_eq!(bios.parttype.as_deref().unwrap(), BIOS_BOOT);
889 }
890
891 #[test]
895 fn test_parse_lsblk_no_udev() {
896 let fixture = include_str!("../tests/fixtures/lsblk-no-udev.json");
897 let devs: DevicesOutput = serde_json::from_str(fixture).unwrap();
898 let dev = devs.blockdevices.into_iter().next().unwrap();
899 assert!(dev.pttype.is_none());
901 let children = dev.children.as_deref().unwrap();
902 assert_eq!(children.len(), 3);
903 assert!(children[0].parttype.is_none());
904 assert!(children[1].parttype.is_none());
905 assert!(children[2].parttype.is_none());
906 assert!(dev.find_partition_of_esp_optional().unwrap().is_none());
908 assert!(dev.find_partition_of_bios_boot().is_none());
909 }
910
911 #[test]
912 fn test_parse_lsblk_mbr() {
913 let fixture = include_str!("../tests/fixtures/lsblk-mbr.json");
914 let devs: DevicesOutput = serde_json::from_str(fixture).unwrap();
915 let dev = devs.blockdevices.into_iter().next().unwrap();
916 assert_eq!(dev.partn, None);
918 assert_eq!(dev.pttype.as_deref().unwrap(), "dos");
919 let children = dev.children.as_deref().unwrap();
920 assert_eq!(children.len(), 3);
921 let first_child = &children[0];
923 assert_eq!(first_child.partn, Some(1));
924 assert_eq!(first_child.parttype.as_deref().unwrap(), "0x06");
925 assert_eq!(first_child.partuuid.as_deref().unwrap(), "a1b2c3d4-01");
926 assert_eq!(first_child.fstype.as_deref().unwrap(), "vfat");
927 assert!(first_child.partlabel.is_none());
929 let second_child = &children[1];
931 assert_eq!(second_child.partn, Some(2));
932 assert_eq!(second_child.parttype.as_deref().unwrap(), "0x83");
933 assert_eq!(second_child.partuuid.as_deref().unwrap(), "a1b2c3d4-02");
934 let third_child = &children[2];
936 assert_eq!(third_child.partn, Some(3));
937 assert_eq!(third_child.parttype.as_deref().unwrap(), "0xef");
938 assert_eq!(third_child.partuuid.as_deref().unwrap(), "a1b2c3d4-03");
939 let part1 = dev.find_device_by_partno(1).unwrap();
941 assert_eq!(part1.partn, Some(1));
942 let esp = dev.find_partition_of_esp().unwrap();
944 assert_eq!(esp.partn, Some(1));
945 }
946
947 fn make_mbr_disk(parttypes: &[&str]) -> Device {
949 Device {
950 name: "vda".into(),
951 serial: None,
952 model: None,
953 partlabel: None,
954 parttype: None,
955 partuuid: None,
956 partn: None,
957 size: 10737418240,
958 maj_min: None,
959 start: None,
960 label: None,
961 fstype: None,
962 uuid: None,
963 path: Some("/dev/vda".into()),
964 pttype: Some("dos".into()),
965 ro: None,
966 children: Some(
967 parttypes
968 .iter()
969 .enumerate()
970 .map(|(i, pt)| Device {
971 name: format!("vda{}", i + 1),
972 serial: None,
973 model: None,
974 partlabel: None,
975 parttype: Some(pt.to_string()),
976 partuuid: None,
977 partn: Some(i as u32 + 1),
978 size: 1048576,
979 maj_min: None,
980 start: Some(2048),
981 label: None,
982 fstype: None,
983 uuid: None,
984 path: None,
985 pttype: Some("dos".into()),
986 ro: None,
987 children: None,
988 })
989 .collect(),
990 ),
991 }
992 }
993
994 #[test]
995 fn test_parse_lsblk_vroc() {
996 let fixture = include_str!("../tests/fixtures/lsblk-vroc.json");
997 let devs: DevicesOutput = serde_json::from_str(fixture).unwrap();
998 assert_eq!(devs.blockdevices.len(), 2);
999
1000 for nvme in &devs.blockdevices {
1004 let esp = nvme.find_partition_of_esp().unwrap();
1005 assert_eq!(esp.name, "md126p1");
1006 assert_eq!(esp.partn, Some(1));
1007 assert_eq!(esp.parttype.as_deref().unwrap(), ESP);
1008 assert_eq!(esp.fstype.as_deref().unwrap(), "vfat");
1009 }
1010 }
1011
1012 #[test]
1013 fn test_parse_lsblk_swraid() {
1014 let fixture = include_str!("../tests/fixtures/lsblk-swraid.json");
1015 let devs: DevicesOutput = serde_json::from_str(fixture).unwrap();
1016 assert_eq!(devs.blockdevices.len(), 2);
1017
1018 let sda = &devs.blockdevices[0];
1024 let esp = sda.find_partition_of_esp().unwrap();
1025 assert_eq!(esp.name, "sda1");
1026 assert_eq!(esp.partn, Some(1));
1027 assert_eq!(esp.parttype.as_deref().unwrap(), ESP);
1028 assert_eq!(esp.fstype.as_deref().unwrap(), "vfat");
1029
1030 let sdb = &devs.blockdevices[1];
1031 let esp = sdb.find_partition_of_esp().unwrap();
1032 assert_eq!(esp.name, "sdb1");
1033 assert_eq!(esp.partn, Some(1));
1034 assert_eq!(esp.parttype.as_deref().unwrap(), ESP);
1035 assert_eq!(esp.fstype.as_deref().unwrap(), "vfat");
1036
1037 let sda3 = sda
1040 .children
1041 .as_ref()
1042 .unwrap()
1043 .iter()
1044 .find(|c| c.name == "sda3")
1045 .unwrap();
1046 assert_eq!(sda3.fstype.as_deref().unwrap(), "linux_raid_member");
1047 let md0 = sda3
1048 .children
1049 .as_ref()
1050 .unwrap()
1051 .iter()
1052 .find(|c| c.name == "md0")
1053 .unwrap();
1054 assert_eq!(md0.fstype.as_deref().unwrap(), "ext4");
1055 }
1056
1057 #[test]
1058 fn test_mbr_esp_detection() {
1059 let dev = make_mbr_disk(&["0x06"]);
1061 assert_eq!(dev.find_partition_of_esp().unwrap().partn, Some(1));
1062
1063 let dev = make_mbr_disk(&["0x83", "0xef"]);
1065 assert_eq!(dev.find_partition_of_esp().unwrap().partn, Some(2));
1066
1067 let dev = make_mbr_disk(&["0x83", "0x82"]);
1069 assert!(dev.find_partition_of_esp().is_err());
1070 }
1071
1072 #[test]
1073 fn test_find_partition_of_xbootldr() {
1074 let cases = [
1075 (XBOOTLDR, Some("vfat"), Some(2)),
1076 (XBOOTLDR, Some("ext4"), None),
1077 (XBOOTLDR, None, None),
1078 (ESP, Some("vfat"), None),
1079 ];
1080 for (parttype, fstype, expected) in cases {
1081 let disk: Device = serde_json::from_value(serde_json::json!({
1082 "name": "vda",
1083 "size": 10737418240_u64,
1084 "pttype": "gpt",
1085 "children": [
1086 {"name": "vda1", "size": 104857600, "partn": 1, "parttype": ESP, "fstype": "vfat"},
1087 {"name": "vda2", "size": 2147483648_u64, "partn": 2, "parttype": parttype, "fstype": fstype},
1088 ]
1089 }))
1090 .unwrap();
1091 assert_eq!(
1092 disk.find_partition_of_xbootldr().and_then(|p| p.partn),
1093 expected,
1094 "{parttype} {fstype:?}"
1095 );
1096 }
1097 }
1098
1099 #[test]
1100 fn test_parse_partition_number_from_suffix() {
1101 assert_eq!(
1103 parse_partition_number_from_suffix("/dev/mapper/mpatha", "/dev/mapper/mpatha2"),
1104 Some("2".into())
1105 );
1106 assert_eq!(
1108 parse_partition_number_from_suffix("/dev/mapper/mpatha", "/dev/mapper/mpathap2"),
1109 Some("2".into())
1110 );
1111 assert_eq!(
1113 parse_partition_number_from_suffix(
1114 "/dev/mapper/3600508b4001",
1115 "/dev/mapper/3600508b4001-part1"
1116 ),
1117 Some("1".into())
1118 );
1119 assert_eq!(
1121 parse_partition_number_from_suffix("/dev/mapper/mpatha", "/dev/mapper/mpatha12"),
1122 Some("12".into())
1123 );
1124 assert_eq!(
1126 parse_partition_number_from_suffix("/dev/mapper/mpatha", "/dev/sda1"),
1127 None
1128 );
1129 assert_eq!(
1131 parse_partition_number_from_suffix("/dev/mapper/mpatha", "/dev/mapper/mpathap"),
1132 None
1133 );
1134 assert_eq!(
1136 parse_partition_number_from_suffix("/dev/mapper/mpatha", "/dev/mapper/mpatha"),
1137 None
1138 );
1139 }
1140}