|
| 1 | +use crate::task::Task; |
| 2 | +use crate::utils::run_in_host_mountns; |
| 3 | +use anyhow::{anyhow, Context, Result}; |
| 4 | +use camino::Utf8Path; |
| 5 | +use nix::errno::Errno; |
| 6 | +use serde::Deserialize; |
| 7 | +use std::fs::File; |
| 8 | +use std::os::unix::io::AsRawFd; |
| 9 | +use std::process::Command; |
| 10 | + |
| 11 | +#[derive(Debug, Deserialize)] |
| 12 | +struct DevicesOutput { |
| 13 | + blockdevices: Vec<Device>, |
| 14 | +} |
| 15 | + |
| 16 | +#[allow(dead_code)] |
| 17 | +#[derive(Debug, Deserialize)] |
| 18 | +pub(crate) struct Device { |
| 19 | + pub(crate) name: String, |
| 20 | + pub(crate) serial: Option<String>, |
| 21 | + pub(crate) model: Option<String>, |
| 22 | + pub(crate) label: Option<String>, |
| 23 | + pub(crate) fstype: Option<String>, |
| 24 | + pub(crate) children: Option<Vec<Device>>, |
| 25 | +} |
| 26 | + |
| 27 | +impl Device { |
| 28 | + #[allow(dead_code)] |
| 29 | + // RHEL8's lsblk doesn't have PATH, so we do it |
| 30 | + pub(crate) fn path(&self) -> String { |
| 31 | + format!("/dev/{}", &self.name) |
| 32 | + } |
| 33 | + |
| 34 | + pub(crate) fn has_children(&self) -> bool { |
| 35 | + self.children.as_ref().map_or(false, |v| !v.is_empty()) |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +pub(crate) fn wipefs(dev: &Utf8Path) -> Result<()> { |
| 40 | + Task::new_and_run( |
| 41 | + &format!("Wiping device {dev}"), |
| 42 | + "wipefs", |
| 43 | + ["-a", dev.as_str()], |
| 44 | + ) |
| 45 | +} |
| 46 | + |
| 47 | +fn list_impl(dev: Option<&Utf8Path>) -> Result<Vec<Device>> { |
| 48 | + let o = Command::new("lsblk") |
| 49 | + .args(["-J", "-o", "NAME,SERIAL,MODEL,LABEL,FSTYPE"]) |
| 50 | + .args(dev) |
| 51 | + .output()?; |
| 52 | + if !o.status.success() { |
| 53 | + return Err(anyhow::anyhow!("Failed to list block devices")); |
| 54 | + } |
| 55 | + let devs: DevicesOutput = serde_json::from_reader(&*o.stdout)?; |
| 56 | + Ok(devs.blockdevices) |
| 57 | +} |
| 58 | + |
| 59 | +pub(crate) fn list_dev(dev: &Utf8Path) -> Result<Device> { |
| 60 | + let devices = list_impl(Some(dev))?; |
| 61 | + devices |
| 62 | + .into_iter() |
| 63 | + .next() |
| 64 | + .ok_or_else(|| anyhow!("no device output from lsblk for {dev}")) |
| 65 | +} |
| 66 | + |
| 67 | +#[allow(dead_code)] |
| 68 | +pub(crate) fn list() -> Result<Vec<Device>> { |
| 69 | + list_impl(None) |
| 70 | +} |
| 71 | + |
| 72 | +pub(crate) fn udev_settle() -> Result<()> { |
| 73 | + // There's a potential window after rereading the partition table where |
| 74 | + // udevd hasn't yet received updates from the kernel, settle will return |
| 75 | + // immediately, and lsblk won't pick up partition labels. Try to sleep |
| 76 | + // our way out of this. |
| 77 | + std::thread::sleep(std::time::Duration::from_millis(200)); |
| 78 | + |
| 79 | + let st = run_in_host_mountns("udevadm").arg("settle").status()?; |
| 80 | + if !st.success() { |
| 81 | + anyhow::bail!("Failed to run udevadm settle: {st:?}"); |
| 82 | + } |
| 83 | + Ok(()) |
| 84 | +} |
| 85 | + |
| 86 | +#[allow(unsafe_code)] |
| 87 | +pub(crate) fn reread_partition_table(file: &mut File, retry: bool) -> Result<()> { |
| 88 | + let fd = file.as_raw_fd(); |
| 89 | + // Reread sometimes fails inexplicably. Retry several times before |
| 90 | + // giving up. |
| 91 | + let max_tries = if retry { 20 } else { 1 }; |
| 92 | + for retries in (0..max_tries).rev() { |
| 93 | + let result = unsafe { ioctl::blkrrpart(fd) }; |
| 94 | + match result { |
| 95 | + Ok(_) => break, |
| 96 | + Err(err) if retries == 0 && err == Errno::EINVAL => { |
| 97 | + return Err(err) |
| 98 | + .context("couldn't reread partition table: device may not support partitions") |
| 99 | + } |
| 100 | + Err(err) if retries == 0 && err == Errno::EBUSY => { |
| 101 | + return Err(err).context("couldn't reread partition table: device is in use") |
| 102 | + } |
| 103 | + Err(err) if retries == 0 => return Err(err).context("couldn't reread partition table"), |
| 104 | + Err(_) => std::thread::sleep(std::time::Duration::from_millis(100)), |
| 105 | + } |
| 106 | + } |
| 107 | + Ok(()) |
| 108 | +} |
| 109 | + |
| 110 | +// create unsafe ioctl wrappers |
| 111 | +#[allow(clippy::missing_safety_doc)] |
| 112 | +mod ioctl { |
| 113 | + use libc::c_int; |
| 114 | + use nix::{ioctl_none, ioctl_read, ioctl_read_bad, libc, request_code_none}; |
| 115 | + ioctl_none!(blkrrpart, 0x12, 95); |
| 116 | + ioctl_read_bad!(blksszget, request_code_none!(0x12, 104), c_int); |
| 117 | + ioctl_read!(blkgetsize64, 0x12, 114, libc::size_t); |
| 118 | +} |
| 119 | + |
| 120 | +/// Parse a string into mibibytes |
| 121 | +pub(crate) fn parse_size_mib(mut s: &str) -> Result<u64> { |
| 122 | + let suffixes = [ |
| 123 | + ("MiB", 1u64), |
| 124 | + ("M", 1u64), |
| 125 | + ("GiB", 1024), |
| 126 | + ("G", 1024), |
| 127 | + ("TiB", 1024 * 1024), |
| 128 | + ("T", 1024 * 1024), |
| 129 | + ]; |
| 130 | + let mut mul = 1u64; |
| 131 | + for (suffix, imul) in suffixes { |
| 132 | + if let Some((sv, rest)) = s.rsplit_once(suffix) { |
| 133 | + if !rest.is_empty() { |
| 134 | + anyhow::bail!("Trailing text after size: {rest}"); |
| 135 | + } |
| 136 | + s = sv; |
| 137 | + mul = imul; |
| 138 | + } |
| 139 | + } |
| 140 | + let v = s.parse::<u64>()?; |
| 141 | + Ok(v * mul) |
| 142 | +} |
| 143 | + |
| 144 | +#[test] |
| 145 | +fn test_parse_size_mib() { |
| 146 | + let ident_cases = [0, 10, 9, 1024].into_iter().map(|k| (k.to_string(), k)); |
| 147 | + let cases = [ |
| 148 | + ("0M", 0), |
| 149 | + ("10M", 10), |
| 150 | + ("10MiB", 10), |
| 151 | + ("1G", 1024), |
| 152 | + ("9G", 9216), |
| 153 | + ("11T", 11 * 1024 * 1024), |
| 154 | + ] |
| 155 | + .into_iter() |
| 156 | + .map(|(k, v)| (k.to_string(), v)); |
| 157 | + for (s, v) in ident_cases.chain(cases) { |
| 158 | + assert_eq!(parse_size_mib(&s).unwrap(), v as u64, "Parsing {s}"); |
| 159 | + } |
| 160 | +} |
0 commit comments