|
2 | 2 | // |
3 | 3 | // SPDX-License-Identifier: MPL-2.0 |
4 | 4 |
|
5 | | -use std::{fs, path::PathBuf}; |
| 5 | +use std::{ |
| 6 | + fs, io, |
| 7 | + path::{Path, PathBuf}, |
| 8 | +}; |
6 | 9 |
|
7 | 10 | pub mod nvme; |
8 | 11 | pub mod scsi; |
| 12 | +mod sysfs; |
9 | 13 |
|
10 | 14 | const SYSFS_DIR: &str = "/sys/class/block"; |
| 15 | +const DEVFS_DIR: &str = "/dev"; |
11 | 16 |
|
| 17 | +/// A block device on the system which can be either a physical disk or a partition. |
12 | 18 | #[derive(Debug)] |
13 | | -pub struct Disk { |
14 | | - /// Partial-name, ie "sda" |
15 | | - pub name: String, |
| 19 | +pub enum BlockDevice { |
| 20 | + /// A physical disk device |
| 21 | + Disk(Box<Disk>), |
| 22 | +} |
| 23 | + |
| 24 | +/// Represents the type of disk device. |
| 25 | +#[derive(Debug)] |
| 26 | +pub enum Disk { |
| 27 | + /// SCSI disk device (e.g. sda, sdb) |
| 28 | + Scsi(scsi::Disk), |
| 29 | + /// NVMe disk device (e.g. nvme0n1) |
| 30 | + Nvme(nvme::Disk), |
| 31 | +} |
16 | 32 |
|
17 | | - // Number of sectors (* 512 sector size for data size) |
| 33 | +/// A basic disk representation containing common attributes shared by all disk types. |
| 34 | +/// This serves as the base structure that specific disk implementations build upon. |
| 35 | +#[derive(Debug)] |
| 36 | +pub struct BasicDisk { |
| 37 | + /// Device name (e.g. sda, nvme0n1) |
| 38 | + pub name: String, |
| 39 | + /// Total number of sectors on the disk |
18 | 40 | pub sectors: u64, |
| 41 | + /// Path to the device in sysfs |
| 42 | + pub node: PathBuf, |
| 43 | + /// Path to the device in /dev |
| 44 | + pub device: PathBuf, |
| 45 | + /// Optional disk model name |
| 46 | + pub model: Option<String>, |
| 47 | + /// Optional disk vendor name |
| 48 | + pub vendor: Option<String>, |
19 | 49 | } |
20 | 50 |
|
21 | 51 | impl Disk { |
22 | | - fn from_sysfs_block_name(name: impl AsRef<str>) -> Self { |
23 | | - let name = name.as_ref().to_owned(); |
24 | | - let entry = PathBuf::from(SYSFS_DIR).join(&name); |
25 | | - |
26 | | - // Determine number of blocks |
27 | | - let block_file = entry.join("size"); |
28 | | - let sectors = fs::read_to_string(block_file) |
29 | | - .ok() |
30 | | - .and_then(|s| s.trim().parse::<u64>().ok()) |
31 | | - .unwrap_or(0); |
32 | | - |
33 | | - Self { name, sectors } |
| 52 | + /// Returns the name of the disk device. |
| 53 | + /// |
| 54 | + /// # Examples |
| 55 | + /// |
| 56 | + /// ``` |
| 57 | + /// // Returns strings like "sda" or "nvme0n1" |
| 58 | + /// let name = disk.name(); |
| 59 | + /// ``` |
| 60 | + pub fn name(&self) -> &str { |
| 61 | + match self { |
| 62 | + Disk::Scsi(disk) => disk.name(), |
| 63 | + Disk::Nvme(disk) => disk.name(), |
| 64 | + } |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +/// Trait for initializing different types of disk devices from sysfs. |
| 69 | +pub(crate) trait DiskInit: Sized { |
| 70 | + /// Creates a new disk instance by reading information from the specified sysfs path. |
| 71 | + /// |
| 72 | + /// # Arguments |
| 73 | + /// |
| 74 | + /// * `root` - The root sysfs directory path |
| 75 | + /// * `name` - The name of the disk device |
| 76 | + /// |
| 77 | + /// # Returns |
| 78 | + /// |
| 79 | + /// `Some(Self)` if the disk was successfully initialized, `None` otherwise |
| 80 | + fn from_sysfs_path(root: &Path, name: &str) -> Option<Self>; |
| 81 | +} |
| 82 | + |
| 83 | +impl DiskInit for BasicDisk { |
| 84 | + fn from_sysfs_path(sysroot: &Path, name: &str) -> Option<Self> { |
| 85 | + let node = sysroot.join(name); |
| 86 | + Some(Self { |
| 87 | + name: name.to_owned(), |
| 88 | + sectors: sysfs::sysfs_read(sysroot, &node, "size").unwrap_or(0), |
| 89 | + device: PathBuf::from(DEVFS_DIR).join(name), |
| 90 | + model: sysfs::sysfs_read(sysroot, &node, "device/model"), |
| 91 | + vendor: sysfs::sysfs_read(sysroot, &node, "device/vendor"), |
| 92 | + node, |
| 93 | + }) |
34 | 94 | } |
| 95 | +} |
| 96 | + |
| 97 | +impl BlockDevice { |
| 98 | + /// Discovers all block devices present in the system. |
| 99 | + /// |
| 100 | + /// # Returns |
| 101 | + /// |
| 102 | + /// A vector of discovered block devices or an IO error if the discovery fails. |
| 103 | + /// |
| 104 | + /// # Examples |
| 105 | + /// |
| 106 | + /// ``` |
| 107 | + /// let devices = BlockDevice::discover()?; |
| 108 | + /// for device in devices { |
| 109 | + /// println!("Found device: {:?}", device); |
| 110 | + /// } |
| 111 | + /// ``` |
| 112 | + pub fn discover() -> io::Result<Vec<BlockDevice>> { |
| 113 | + Self::discover_in_sysroot("/") |
| 114 | + } |
| 115 | + |
| 116 | + /// Discovers block devices in a specified sysroot directory. |
| 117 | + /// |
| 118 | + /// # Arguments |
| 119 | + /// |
| 120 | + /// * `sysroot` - Path to the system root directory |
| 121 | + /// |
| 122 | + /// # Returns |
| 123 | + /// |
| 124 | + /// A vector of discovered block devices or an IO error if the discovery fails. |
| 125 | + pub fn discover_in_sysroot(sysroot: impl AsRef<str>) -> io::Result<Vec<BlockDevice>> { |
| 126 | + let sysroot = sysroot.as_ref(); |
| 127 | + let sysfs_dir = PathBuf::from(sysroot).join(SYSFS_DIR); |
| 128 | + let mut devices = Vec::new(); |
| 129 | + |
| 130 | + // Iterate over all block devices in sysfs and collect their filenames |
| 131 | + let entries = fs::read_dir(&sysfs_dir)? |
| 132 | + .filter_map(Result::ok) |
| 133 | + .filter_map(|e| Some(e.file_name().to_str()?.to_owned())); |
| 134 | + |
| 135 | + // For all the discovered block devices, try to create a Disk instance |
| 136 | + // At this point we completely ignore partitions. They come later. |
| 137 | + for entry in entries { |
| 138 | + let disk = if let Some(disk) = scsi::Disk::from_sysfs_path(&sysfs_dir, &entry) { |
| 139 | + Disk::Scsi(disk) |
| 140 | + } else if let Some(disk) = nvme::Disk::from_sysfs_path(&sysfs_dir, &entry) { |
| 141 | + Disk::Nvme(disk) |
| 142 | + } else { |
| 143 | + continue; |
| 144 | + }; |
| 145 | + |
| 146 | + devices.push(BlockDevice::Disk(Box::new(disk))); |
| 147 | + } |
| 148 | + |
| 149 | + Ok(devices) |
| 150 | + } |
| 151 | +} |
| 152 | + |
| 153 | +#[cfg(test)] |
| 154 | +mod tests { |
| 155 | + use super::*; |
35 | 156 |
|
36 | | - /// Return usable size |
37 | | - /// TODO: Grab the block size from the system. We know Linux is built on 512s though. |
38 | | - pub fn size_in_bytes(&self) -> u64 { |
39 | | - self.sectors * 512 |
| 157 | + #[test] |
| 158 | + fn test_discover() { |
| 159 | + let devices = BlockDevice::discover().unwrap(); |
| 160 | + assert!(!devices.is_empty()); |
| 161 | + eprintln!("devices: {devices:?}"); |
40 | 162 | } |
41 | 163 | } |
0 commit comments