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
15fn have_udev() -> bool {
25 static HAVE_UDEV: OnceLock<bool> = OnceLock::new();
26 *HAVE_UDEV.get_or_init(|| {
27 let r = Path::new("/run/udev/data").exists();
28 if !r {
29 tracing::debug!(
30 "udev database not available, will use blkid -p for partition metadata"
31 );
32 }
33 r
34 })
35}
36
37fn blkid_probe(dev: &str) -> Result<HashMap<String, String>> {
48 let mut cmd = Command::new("blkid");
49 cmd.args(["-p", "-o", "export"]).arg(dev);
50 cmd.log_debug();
51 let output = cmd.output().context("Failed to run blkid")?;
52 if !output.status.success() {
53 if output.status.code() == Some(2) {
55 return Ok(HashMap::new());
56 }
57 let stderr = String::from_utf8_lossy(&output.stderr);
58 anyhow::bail!(
59 "blkid -p failed on {dev} (exit status {}): {stderr}",
60 output.status
61 );
62 }
63 let text = String::from_utf8(output.stdout).context("blkid output is not UTF-8")?;
64 let mut props = HashMap::new();
65 for line in text.lines() {
66 if let Some((key, value)) = line.split_once('=') {
67 props.insert(key.to_string(), value.to_string());
68 }
69 }
70 Ok(props)
71}
72
73pub const ESP_ID_MBR: &[u8] = &[0x06, 0xEF];
78
79pub const ESP: &str = "c12a7328-f81f-11d2-ba4b-00a0c93ec93b";
81
82pub const BIOS_BOOT: &str = "21686148-6449-6e6f-744e-656564454649";
84
85#[derive(Debug, Deserialize)]
86struct DevicesOutput {
87 blockdevices: Vec<Device>,
88}
89
90#[allow(dead_code)]
91#[derive(Debug, Clone, serde::Serialize, Deserialize)]
92pub struct Device {
93 pub name: String,
94 pub serial: Option<String>,
95 pub model: Option<String>,
96 pub partlabel: Option<String>,
97 pub parttype: Option<String>,
98 pub partuuid: Option<String>,
99 pub partn: Option<u32>,
101 pub children: Option<Vec<Device>>,
102 pub size: u64,
103 #[serde(rename = "maj:min")]
104 pub maj_min: Option<String>,
105 pub start: Option<u64>,
108
109 pub label: Option<String>,
111 pub fstype: Option<String>,
112 pub uuid: Option<String>,
113 pub path: Option<String>,
114 pub pttype: Option<String>,
116 pub ro: Option<bool>,
119}
120
121impl Device {
122 pub fn path(&self) -> String {
124 self.path.clone().unwrap_or(format!("/dev/{}", &self.name))
125 }
126
127 #[allow(dead_code)]
129 pub fn node(&self) -> String {
130 self.path()
131 }
132
133 #[allow(dead_code)]
134 pub fn has_children(&self) -> bool {
135 self.children.as_ref().is_some_and(|v| !v.is_empty())
136 }
137
138 pub fn is_mpath(&self) -> Result<bool> {
140 let dm_path = Utf8PathBuf::from_path_buf(std::fs::canonicalize(self.path())?)
141 .map_err(|_| anyhow::anyhow!("Non-UTF8 path"))?;
142 let dm_name = dm_path.file_name().unwrap_or("");
143 let uuid_path = Utf8PathBuf::from(format!("/sys/class/block/{dm_name}/dm/uuid"));
144
145 if uuid_path.exists() {
146 let uuid = std::fs::read_to_string(&uuid_path)
147 .with_context(|| format!("Failed to read {uuid_path}"))?;
148 if uuid.trim_start().starts_with("mpath-") {
149 return Ok(true);
150 }
151 }
152 Ok(false)
153 }
154
155 pub fn get_esp_partition_number(&self) -> Result<String> {
164 let esp_device = self.find_partition_of_esp()?;
165 let devname = &esp_device.name;
166
167 let partition_path = Utf8PathBuf::from(format!("/sys/class/block/{devname}/partition"));
168 if partition_path.exists() {
169 return std::fs::read_to_string(&partition_path)
170 .with_context(|| format!("Failed to read {partition_path}"));
171 }
172
173 if self.is_mpath()? {
175 if let Some(partn) = esp_device.partn {
176 return Ok(partn.to_string());
177 }
178 let parent_path = self.path();
183 let esp_path = esp_device.path();
184 if let Some(n) = parse_partition_number_from_suffix(&parent_path, &esp_path) {
185 return Ok(n);
186 }
187 }
188 anyhow::bail!("Not supported for {devname}")
189 }
190
191 pub fn find_partition_of_bios_boot(&self) -> Option<&Device> {
193 self.find_partition_of_type(BIOS_BOOT)
194 }
195
196 pub fn find_colocated_esps(&self) -> Result<Option<Vec<Device>>> {
200 let mut esps = Vec::new();
201 for root in &self.find_all_roots()? {
202 if let Some(esp) = root.find_partition_of_esp_optional()? {
203 esps.push(esp.clone());
204 }
205 }
206 Ok((!esps.is_empty()).then_some(esps))
207 }
208
209 pub fn find_first_colocated_esp(&self) -> Result<Device> {
215 self.find_colocated_esps()?
216 .and_then(|mut v| Some(v.remove(0)))
217 .ok_or_else(|| anyhow!("No ESP partition found among backing devices"))
218 }
219
220 pub fn find_colocated_bios_boot(&self) -> Result<Option<Vec<Device>>> {
224 let bios_boots: Vec<_> = self
225 .find_all_roots()?
226 .iter()
227 .filter_map(|root| root.find_partition_of_bios_boot())
228 .cloned()
229 .collect();
230 Ok((!bios_boots.is_empty()).then_some(bios_boots))
231 }
232
233 pub fn find_partition_of_type(&self, parttype: &str) -> Option<&Device> {
235 self.children.as_ref()?.iter().find(|child| {
236 child
237 .parttype
238 .as_ref()
239 .is_some_and(|pt| pt.eq_ignore_ascii_case(parttype))
240 })
241 }
242
243 pub fn find_partition_of_esp_optional(&self) -> Result<Option<&Device>> {
256 let Some(children) = self.children.as_ref() else {
257 return Ok(None);
258 };
259 let direct = match self.pttype.as_deref() {
260 Some("dos") => children.iter().find(|child| {
261 child
262 .parttype
263 .as_ref()
264 .and_then(|pt| {
265 let pt = pt.strip_prefix("0x").unwrap_or(pt);
266 u8::from_str_radix(pt, 16).ok()
267 })
268 .is_some_and(|pt| ESP_ID_MBR.contains(&pt))
269 }),
270 Some("gpt") | None => self.find_partition_of_type(ESP),
273 Some(other) => return Err(anyhow!("Unsupported partition table type: {other}")),
274 };
275 if direct.is_some() {
276 return Ok(direct);
277 }
278 for child in children {
281 if child.pttype.is_some() {
282 if let Some(esp) = child.find_partition_of_esp_optional()? {
283 return Ok(Some(esp));
284 }
285 }
286 }
287 Ok(None)
288 }
289
290 pub fn find_partition_of_esp(&self) -> Result<&Device> {
295 self.find_partition_of_esp_optional()?
296 .ok_or_else(|| anyhow!("ESP partition not found on {}", self.path()))
297 }
298
299 pub fn find_device_by_partno(&self, partno: u32) -> Result<&Device> {
301 self.children
302 .as_ref()
303 .ok_or_else(|| anyhow!("Device has no children"))?
304 .iter()
305 .find(|child| child.partn == Some(partno))
306 .ok_or_else(|| anyhow!("Missing partition for index {partno}"))
307 }
308
309 pub fn refresh(&mut self) -> Result<()> {
312 let path = self.path();
313 let new_device = list_dev(Utf8Path::new(&path))?;
314 *self = new_device;
315 Ok(())
316 }
317
318 fn read_sysfs_property<T>(&self, property: &str) -> Result<Option<T>>
320 where
321 T: std::str::FromStr,
322 T::Err: std::error::Error + Send + Sync + 'static,
323 {
324 let Some(majmin) = self.maj_min.as_deref() else {
325 return Ok(None);
326 };
327 let sysfs_path = format!("/sys/dev/block/{majmin}/{property}");
328 if !Utf8Path::new(&sysfs_path).try_exists()? {
329 return Ok(None);
330 }
331 let value = std::fs::read_to_string(&sysfs_path)
332 .with_context(|| format!("Reading {sysfs_path}"))?;
333 let parsed = value
334 .trim()
335 .parse()
336 .with_context(|| format!("Parsing sysfs {property} property"))?;
337 tracing::debug!("backfilled {property} to {value}");
338 Ok(Some(parsed))
339 }
340
341 pub fn backfill_missing(&mut self) -> Result<()> {
348 if self.start.is_none() {
351 self.start = self.read_sysfs_property("start")?;
352 }
353 if self.partn.is_none() {
356 self.partn = self.read_sysfs_property("partition")?;
357 }
358 if !have_udev() && (self.parttype.is_none() || self.pttype.is_none()) {
362 let props = blkid_probe(&self.path())?;
363 if self.parttype.is_none() {
364 self.parttype = props.get("PART_ENTRY_TYPE").cloned();
365 }
366 if self.pttype.is_none() {
367 self.pttype = props.get("PTTYPE").cloned();
368 }
369 }
370 for child in self.children.iter_mut().flatten() {
372 child.backfill_missing()?;
373 }
374 Ok(())
375 }
376
377 pub fn list_parents(&self) -> Result<Option<Vec<Device>>> {
384 let path = self.path();
385 let output: DevicesOutput = Command::new("lsblk")
386 .args(["-J", "-b", "-O", "--inverse"])
387 .arg(&path)
388 .log_debug()
389 .run_and_parse_json()?;
390
391 let device = output
392 .blockdevices
393 .into_iter()
394 .next()
395 .ok_or_else(|| anyhow!("no device output from lsblk --inverse for {path}"))?;
396
397 match device.children {
398 Some(mut children) if !children.is_empty() => {
399 for child in &mut children {
400 child.backfill_missing()?;
401 }
402 Ok(Some(children))
403 }
404 _ => Ok(None),
405 }
406 }
407
408 pub fn require_single_root(&self) -> Result<Device> {
414 let mut roots = self.find_all_roots()?;
415 match roots.len() {
416 1 => Ok(roots.remove(0)),
417 n => anyhow::bail!(
418 "Expected a single root device for {}, but found {n}",
419 self.path()
420 ),
421 }
422 }
423
424 pub fn find_all_roots(&self) -> Result<Vec<Device>> {
431 let Some(parents) = self.list_parents()? else {
432 return Ok(vec![list_dev(Utf8Path::new(&self.path()))?]);
434 };
435
436 let mut roots = Vec::new();
437 let mut seen = HashSet::new();
438 let mut queue = parents;
439 while let Some(mut device) = queue.pop() {
440 match device.children.take() {
441 Some(grandparents) if !grandparents.is_empty() => {
442 queue.extend(grandparents);
443 }
444 _ => {
445 let name = device.name.clone();
448 if seen.insert(name) {
449 roots.push(list_dev(Utf8Path::new(&device.path()))?);
451 }
452 }
453 }
454 }
455 Ok(roots)
456 }
457}
458
459#[context("Listing device {dev}")]
460pub fn list_dev(dev: &Utf8Path) -> Result<Device> {
461 let mut devs: DevicesOutput = Command::new("lsblk")
462 .args(["-J", "-b", "-O"])
463 .arg(dev)
464 .log_debug()
465 .run_and_parse_json()?;
466 for dev in devs.blockdevices.iter_mut() {
467 dev.backfill_missing()?;
468 }
469 devs.blockdevices
470 .into_iter()
471 .next()
472 .ok_or_else(|| anyhow!("no device output from lsblk for {dev}"))
473}
474
475#[context("Finding block device for ZFS dataset {dataset}")]
476fn list_dev_for_zfs_dataset(dataset: &str) -> Result<Device> {
477 let dataset = dataset.strip_prefix("ZFS=").unwrap_or(dataset);
478 let pool = dataset
479 .split('/')
480 .next()
481 .ok_or_else(|| anyhow!("Invalid ZFS dataset: {dataset}"))?;
482
483 let output = Command::new("zpool")
484 .args(["list", "-H", "-v", "-P", pool])
485 .run_get_string()
486 .with_context(|| format!("Querying ZFS pool {pool}"))?;
487
488 for line in output.lines() {
489 if line.starts_with('\t') || line.starts_with(' ') {
490 let dev_path = line.trim_start().split('\t').next().unwrap_or("").trim();
491 if dev_path.starts_with('/') {
492 return list_dev(Utf8Path::new(dev_path));
493 }
494 }
495 }
496
497 anyhow::bail!("Could not find a block device backing ZFS pool {pool}")
498}
499
500pub fn list_dev_by_dir(dir: &Dir) -> Result<Device> {
502 let fsinfo = bootc_mount::inspect_filesystem_of_dir(dir)?;
503 let source = &fsinfo.source;
504 if fsinfo.fstype == "zfs" || source.starts_with("ZFS=") {
505 return list_dev_for_zfs_dataset(source);
506 }
507 list_dev(&Utf8PathBuf::from(source))
508}
509
510const ZFS_SUPER_MAGIC: u32 = 0x2fc12fc1;
512
513fn is_block_backed(st_dev: u64, fs_magic: u32) -> bool {
521 rustix::fs::major(st_dev) != 0
522 || fs_magic == libc::BTRFS_SUPER_MAGIC as u32
523 || fs_magic == ZFS_SUPER_MAGIC
524}
525
526#[context("Finding block device backing directory")]
532pub fn list_dev_by_dir_optional(dir: &Dir) -> Result<Option<Device>> {
533 let st_dev = rustix::fs::fstat(dir)?.st_dev;
534 let fs_magic = rustix::fs::fstatfs(dir)?.f_type as u32;
536 if !is_block_backed(st_dev, fs_magic) {
537 tracing::debug!("No block device: st_dev={st_dev:#x} f_type={fs_magic:#x}");
538 return Ok(None);
539 }
540 list_dev_by_dir(dir).map(Some)
541}
542
543pub fn is_dir_backing_device_ro(dir: &Dir) -> Result<Option<bool>> {
554 let fsinfo = bootc_mount::inspect_filesystem_of_dir(dir)?;
555 let source = &fsinfo.source;
556 if !source.starts_with("/dev/") {
560 tracing::debug!("Filesystem source {source} is not a block device node");
561 return Ok(None);
562 }
563 let dev = list_dev(&Utf8PathBuf::from(source))?;
564 Ok(dev.ro)
565}
566
567pub struct LoopbackDevice {
568 pub dev: Option<Utf8PathBuf>,
569 cleanup_handle: Option<LoopbackCleanupHandle>,
571}
572
573struct LoopbackCleanupHandle {
575 child: std::process::Child,
577}
578
579impl LoopbackDevice {
580 pub fn new(path: &Path) -> Result<Self> {
582 let direct_io = match env::var("BOOTC_DIRECT_IO") {
583 Ok(val) => {
584 if val == "on" {
585 "on"
586 } else {
587 "off"
588 }
589 }
590 Err(_e) => "off",
591 };
592
593 let dev = Command::new("losetup")
594 .args([
595 "--show",
596 format!("--direct-io={direct_io}").as_str(),
597 "-P",
598 "--find",
599 ])
600 .arg(path)
601 .run_get_string()?;
602 let dev = Utf8PathBuf::from(dev.trim());
603 tracing::debug!("Allocated loopback {dev}");
604
605 let cleanup_handle = match Self::spawn_cleanup_helper(dev.as_str()) {
607 Ok(handle) => Some(handle),
608 Err(e) => {
609 tracing::warn!(
610 "Failed to spawn loopback cleanup helper for {}: {}. \
611 Loopback device may not be cleaned up if process is interrupted.",
612 dev,
613 e
614 );
615 None
616 }
617 };
618
619 Ok(Self {
620 dev: Some(dev),
621 cleanup_handle,
622 })
623 }
624
625 pub fn path(&self) -> &Utf8Path {
627 self.dev.as_deref().unwrap()
629 }
630
631 fn spawn_cleanup_helper(device_path: &str) -> Result<LoopbackCleanupHandle> {
634 let bootc_path = bootc_utils::reexec::executable_path()
636 .context("Failed to locate bootc binary for cleanup helper")?;
637
638 let mut cmd = Command::new(bootc_path);
640 cmd.args([
641 "internals",
642 "loopback-cleanup-helper",
643 "--device",
644 device_path,
645 ]);
646
647 cmd.env("BOOTC_LOOPBACK_CLEANUP_HELPER", "1");
649
650 cmd.stdin(Stdio::null());
652 cmd.stdout(Stdio::null());
653 let child = cmd
657 .spawn()
658 .context("Failed to spawn loopback cleanup helper")?;
659
660 Ok(LoopbackCleanupHandle { child })
661 }
662
663 fn impl_close(&mut self) -> Result<()> {
665 let Some(dev) = self.dev.take() else {
667 tracing::trace!("loopback device already deallocated");
668 return Ok(());
669 };
670
671 if let Some(mut cleanup_handle) = self.cleanup_handle.take() {
673 let _ = cleanup_handle.child.kill();
675 }
676
677 Command::new("losetup")
678 .args(["-d", dev.as_str()])
679 .run_capture_stderr()
680 }
681
682 pub fn close(mut self) -> Result<()> {
684 self.impl_close()
685 }
686}
687
688impl Drop for LoopbackDevice {
689 fn drop(&mut self) {
690 let _ = self.impl_close();
692 }
693}
694
695pub async fn run_loopback_cleanup_helper(device_path: &str) -> Result<()> {
698 if std::env::var("BOOTC_LOOPBACK_CLEANUP_HELPER").is_err() {
700 anyhow::bail!("This function should only be called as a cleanup helper");
701 }
702
703 rustix::process::set_parent_process_death_signal(Some(rustix::process::Signal::TERM))
705 .context("Failed to set parent death signal")?;
706
707 tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
709 .expect("Failed to create signal stream")
710 .recv()
711 .await;
712
713 let output = std::process::Command::new("losetup")
715 .args(["-d", device_path])
716 .output();
717
718 match output {
719 Ok(output) if output.status.success() => {
720 tracing::info!("Cleaned up leaked loopback device {}", device_path);
722 std::process::exit(0);
723 }
724 Ok(output) => {
725 let stderr = String::from_utf8_lossy(&output.stderr);
726 tracing::error!(
727 "Failed to clean up loopback device {}: {}. Stderr: {}",
728 device_path,
729 output.status,
730 stderr.trim()
731 );
732 std::process::exit(1);
733 }
734 Err(e) => {
735 tracing::error!(
736 "Error executing losetup to clean up loopback device {}: {}",
737 device_path,
738 e
739 );
740 std::process::exit(1);
741 }
742 }
743}
744
745pub fn parse_size_mib(mut s: &str) -> Result<u64> {
747 let suffixes = [
748 ("MiB", 1u64),
749 ("M", 1u64),
750 ("GiB", 1024),
751 ("G", 1024),
752 ("TiB", 1024 * 1024),
753 ("T", 1024 * 1024),
754 ];
755 let mut mul = 1u64;
756 for (suffix, imul) in suffixes {
757 if let Some((sv, rest)) = s.rsplit_once(suffix) {
758 if !rest.is_empty() {
759 anyhow::bail!("Trailing text after size: {rest}");
760 }
761 s = sv;
762 mul = imul;
763 }
764 }
765 let v = s.parse::<u64>()?;
766 Ok(v * mul)
767}
768
769fn parse_partition_number_from_suffix(parent_path: &str, esp_path: &str) -> Option<String> {
781 let suffix = esp_path.strip_prefix(parent_path)?;
782 let digits = suffix.trim_start_matches(|c: char| !c.is_ascii_digit());
783 if digits.is_empty() {
784 return None;
785 }
786 Some(digits.to_string())
787}
788
789#[cfg(test)]
790mod test {
791 use super::*;
792
793 #[test]
794 fn test_is_block_backed() {
795 use rustix::fs::makedev;
796 let cases = [
798 (makedev(252, 3), libc::XFS_SUPER_MAGIC as u32, true),
799 (makedev(253, 0), libc::EXT4_SUPER_MAGIC as u32, true),
800 (makedev(0, 38), libc::BTRFS_SUPER_MAGIC as u32, true),
801 (makedev(0, 51), ZFS_SUPER_MAGIC, true),
802 (makedev(0, 29), libc::FUSE_SUPER_MAGIC as u32, false),
803 (makedev(0, 52), libc::NFS_SUPER_MAGIC as u32, false),
804 (makedev(0, 40), libc::OVERLAYFS_SUPER_MAGIC as u32, false),
805 (makedev(0, 23), libc::TMPFS_MAGIC as u32, false),
806 ];
807 for (st_dev, fs_magic, expected) in cases {
808 assert_eq!(
809 is_block_backed(st_dev, fs_magic),
810 expected,
811 "st_dev={st_dev:#x} f_type={fs_magic:#x}"
812 );
813 }
814 }
815
816 #[test]
817 fn test_list_dev_by_dir_optional_procfs() -> Result<()> {
818 let proc = Dir::open_ambient_dir("/proc", cap_std_ext::cap_std::ambient_authority())?;
819 assert!(list_dev_by_dir_optional(&proc)?.is_none());
820 Ok(())
821 }
822
823 #[test]
824 fn test_parse_size_mib() {
825 let ident_cases = [0, 10, 9, 1024].into_iter().map(|k| (k.to_string(), k));
826 let cases = [
827 ("0M", 0),
828 ("10M", 10),
829 ("10MiB", 10),
830 ("1G", 1024),
831 ("9G", 9216),
832 ("11T", 11 * 1024 * 1024),
833 ]
834 .into_iter()
835 .map(|(k, v)| (k.to_string(), v));
836 for (s, v) in ident_cases.chain(cases) {
837 assert_eq!(parse_size_mib(&s).unwrap(), v as u64, "Parsing {s}");
838 }
839 }
840
841 #[test]
842 fn test_parse_lsblk() {
843 let fixture = include_str!("../tests/fixtures/lsblk.json");
844 let devs: DevicesOutput = serde_json::from_str(fixture).unwrap();
845 let dev = devs.blockdevices.into_iter().next().unwrap();
846 assert_eq!(dev.partn, None);
848 let children = dev.children.as_deref().unwrap();
849 assert_eq!(children.len(), 3);
850 let first_child = &children[0];
851 assert_eq!(first_child.partn, Some(1));
852 assert_eq!(
853 first_child.parttype.as_deref().unwrap(),
854 "21686148-6449-6e6f-744e-656564454649"
855 );
856 assert_eq!(
857 first_child.partuuid.as_deref().unwrap(),
858 "3979e399-262f-4666-aabc-7ab5d3add2f0"
859 );
860 let part2 = dev.find_device_by_partno(2).unwrap();
862 assert_eq!(part2.partn, Some(2));
863 assert_eq!(part2.parttype.as_deref().unwrap(), ESP);
864 let esp = dev.find_partition_of_esp().unwrap();
866 assert_eq!(esp.partn, Some(2));
867 let bios = dev.find_partition_of_bios_boot().unwrap();
869 assert_eq!(bios.partn, Some(1));
870 assert_eq!(bios.parttype.as_deref().unwrap(), BIOS_BOOT);
871 }
872
873 #[test]
877 fn test_parse_lsblk_no_udev() {
878 let fixture = include_str!("../tests/fixtures/lsblk-no-udev.json");
879 let devs: DevicesOutput = serde_json::from_str(fixture).unwrap();
880 let dev = devs.blockdevices.into_iter().next().unwrap();
881 assert!(dev.pttype.is_none());
883 let children = dev.children.as_deref().unwrap();
884 assert_eq!(children.len(), 3);
885 assert!(children[0].parttype.is_none());
886 assert!(children[1].parttype.is_none());
887 assert!(children[2].parttype.is_none());
888 assert!(dev.find_partition_of_esp_optional().unwrap().is_none());
890 assert!(dev.find_partition_of_bios_boot().is_none());
891 }
892
893 #[test]
894 fn test_parse_lsblk_mbr() {
895 let fixture = include_str!("../tests/fixtures/lsblk-mbr.json");
896 let devs: DevicesOutput = serde_json::from_str(fixture).unwrap();
897 let dev = devs.blockdevices.into_iter().next().unwrap();
898 assert_eq!(dev.partn, None);
900 assert_eq!(dev.pttype.as_deref().unwrap(), "dos");
901 let children = dev.children.as_deref().unwrap();
902 assert_eq!(children.len(), 3);
903 let first_child = &children[0];
905 assert_eq!(first_child.partn, Some(1));
906 assert_eq!(first_child.parttype.as_deref().unwrap(), "0x06");
907 assert_eq!(first_child.partuuid.as_deref().unwrap(), "a1b2c3d4-01");
908 assert_eq!(first_child.fstype.as_deref().unwrap(), "vfat");
909 assert!(first_child.partlabel.is_none());
911 let second_child = &children[1];
913 assert_eq!(second_child.partn, Some(2));
914 assert_eq!(second_child.parttype.as_deref().unwrap(), "0x83");
915 assert_eq!(second_child.partuuid.as_deref().unwrap(), "a1b2c3d4-02");
916 let third_child = &children[2];
918 assert_eq!(third_child.partn, Some(3));
919 assert_eq!(third_child.parttype.as_deref().unwrap(), "0xef");
920 assert_eq!(third_child.partuuid.as_deref().unwrap(), "a1b2c3d4-03");
921 let part1 = dev.find_device_by_partno(1).unwrap();
923 assert_eq!(part1.partn, Some(1));
924 let esp = dev.find_partition_of_esp().unwrap();
926 assert_eq!(esp.partn, Some(1));
927 }
928
929 fn make_mbr_disk(parttypes: &[&str]) -> Device {
931 Device {
932 name: "vda".into(),
933 serial: None,
934 model: None,
935 partlabel: None,
936 parttype: None,
937 partuuid: None,
938 partn: None,
939 size: 10737418240,
940 maj_min: None,
941 start: None,
942 label: None,
943 fstype: None,
944 uuid: None,
945 path: Some("/dev/vda".into()),
946 pttype: Some("dos".into()),
947 ro: None,
948 children: Some(
949 parttypes
950 .iter()
951 .enumerate()
952 .map(|(i, pt)| Device {
953 name: format!("vda{}", i + 1),
954 serial: None,
955 model: None,
956 partlabel: None,
957 parttype: Some(pt.to_string()),
958 partuuid: None,
959 partn: Some(i as u32 + 1),
960 size: 1048576,
961 maj_min: None,
962 start: Some(2048),
963 label: None,
964 fstype: None,
965 uuid: None,
966 path: None,
967 pttype: Some("dos".into()),
968 ro: None,
969 children: None,
970 })
971 .collect(),
972 ),
973 }
974 }
975
976 #[test]
977 fn test_parse_lsblk_vroc() {
978 let fixture = include_str!("../tests/fixtures/lsblk-vroc.json");
979 let devs: DevicesOutput = serde_json::from_str(fixture).unwrap();
980 assert_eq!(devs.blockdevices.len(), 2);
981
982 for nvme in &devs.blockdevices {
986 let esp = nvme.find_partition_of_esp().unwrap();
987 assert_eq!(esp.name, "md126p1");
988 assert_eq!(esp.partn, Some(1));
989 assert_eq!(esp.parttype.as_deref().unwrap(), ESP);
990 assert_eq!(esp.fstype.as_deref().unwrap(), "vfat");
991 }
992 }
993
994 #[test]
995 fn test_parse_lsblk_swraid() {
996 let fixture = include_str!("../tests/fixtures/lsblk-swraid.json");
997 let devs: DevicesOutput = serde_json::from_str(fixture).unwrap();
998 assert_eq!(devs.blockdevices.len(), 2);
999
1000 let sda = &devs.blockdevices[0];
1006 let esp = sda.find_partition_of_esp().unwrap();
1007 assert_eq!(esp.name, "sda1");
1008 assert_eq!(esp.partn, Some(1));
1009 assert_eq!(esp.parttype.as_deref().unwrap(), ESP);
1010 assert_eq!(esp.fstype.as_deref().unwrap(), "vfat");
1011
1012 let sdb = &devs.blockdevices[1];
1013 let esp = sdb.find_partition_of_esp().unwrap();
1014 assert_eq!(esp.name, "sdb1");
1015 assert_eq!(esp.partn, Some(1));
1016 assert_eq!(esp.parttype.as_deref().unwrap(), ESP);
1017 assert_eq!(esp.fstype.as_deref().unwrap(), "vfat");
1018
1019 let sda3 = sda
1022 .children
1023 .as_ref()
1024 .unwrap()
1025 .iter()
1026 .find(|c| c.name == "sda3")
1027 .unwrap();
1028 assert_eq!(sda3.fstype.as_deref().unwrap(), "linux_raid_member");
1029 let md0 = sda3
1030 .children
1031 .as_ref()
1032 .unwrap()
1033 .iter()
1034 .find(|c| c.name == "md0")
1035 .unwrap();
1036 assert_eq!(md0.fstype.as_deref().unwrap(), "ext4");
1037 }
1038
1039 #[test]
1040 fn test_mbr_esp_detection() {
1041 let dev = make_mbr_disk(&["0x06"]);
1043 assert_eq!(dev.find_partition_of_esp().unwrap().partn, Some(1));
1044
1045 let dev = make_mbr_disk(&["0x83", "0xef"]);
1047 assert_eq!(dev.find_partition_of_esp().unwrap().partn, Some(2));
1048
1049 let dev = make_mbr_disk(&["0x83", "0x82"]);
1051 assert!(dev.find_partition_of_esp().is_err());
1052 }
1053
1054 #[test]
1055 fn test_parse_partition_number_from_suffix() {
1056 assert_eq!(
1058 parse_partition_number_from_suffix("/dev/mapper/mpatha", "/dev/mapper/mpatha2"),
1059 Some("2".into())
1060 );
1061 assert_eq!(
1063 parse_partition_number_from_suffix("/dev/mapper/mpatha", "/dev/mapper/mpathap2"),
1064 Some("2".into())
1065 );
1066 assert_eq!(
1068 parse_partition_number_from_suffix(
1069 "/dev/mapper/3600508b4001",
1070 "/dev/mapper/3600508b4001-part1"
1071 ),
1072 Some("1".into())
1073 );
1074 assert_eq!(
1076 parse_partition_number_from_suffix("/dev/mapper/mpatha", "/dev/mapper/mpatha12"),
1077 Some("12".into())
1078 );
1079 assert_eq!(
1081 parse_partition_number_from_suffix("/dev/mapper/mpatha", "/dev/sda1"),
1082 None
1083 );
1084 assert_eq!(
1086 parse_partition_number_from_suffix("/dev/mapper/mpatha", "/dev/mapper/mpathap"),
1087 None
1088 );
1089 assert_eq!(
1091 parse_partition_number_from_suffix("/dev/mapper/mpatha", "/dev/mapper/mpatha"),
1092 None
1093 );
1094 }
1095}