1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
use super::{block_size, parse_maj_min, SysPath};
use crate::{
    util::{next, trim_parse_map},
    Error, Result,
};
#[cfg(feature = "serialize")]
use serde::{Deserialize, Serialize};
use std::{fs, path::PathBuf, str::SplitAsciiWhitespace};

pub type Partitions = Vec<Partition>;
pub type DeviceMappers = Vec<DeviceMapper>;
pub type StorageDevices = Vec<StorageDevice>;
pub type ScsiCdroms = Vec<ScsiCdrom>;
pub type MultipleDeviceStorages = Vec<MultipleDeviceStorage>;

pub(crate) trait FromSysPath<T> {
    fn from_sys_path(path: PathBuf, hierarchy: bool) -> Result<T>;
}

fn find_subdevices<T: FromSysPath<T>>(
    mut device_path: PathBuf,
    holder_or_slave: Hierarchy,
    dev_ty: DevType,
    hierarchy: bool,
) -> Option<Vec<T>> {
    match holder_or_slave {
        Hierarchy::Holders => device_path.push("holders"),
        Hierarchy::Slaves => device_path.push("slaves"),
        Hierarchy::None => {}
    };

    let mut devs = Vec::new();
    let prefix = dev_ty.prefix();
    if let Ok(dir) = fs::read_dir(device_path.as_path()) {
        for entry in dir {
            if let Ok(entry) = entry {
                if let Some(name) = entry.file_name().to_str() {
                    if name.starts_with(prefix) {
                        if let Ok(dev) = T::from_sys_path(device_path.join(name), hierarchy) {
                            devs.push(dev);
                        }
                    }
                }
            }
        }
        if devs.len() != 0 {
            return Some(devs);
        }
    }

    None
}

#[derive(Clone, Debug)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub(crate) enum Hierarchy {
    Holders,
    Slaves,
    None,
}

#[derive(Clone, Debug)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub(crate) enum DevType {
    Partition,
    DevMapper,
    Md,
}
impl DevType {
    pub(crate) fn prefix(self) -> &'static str {
        match self {
            DevType::Partition => "sd",
            DevType::DevMapper => "dm",
            DevType::Md => "md",
        }
    }
}

#[derive(Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
/// Represents stats of a block storage device
/// read from /sys/block/<device>/stat
pub struct BlockStorageStat {
    pub read_ios: usize,
    pub read_merges: usize,
    pub read_sectors: usize,
    pub read_ticks: u64,
    pub write_ios: usize,
    pub write_merges: usize,
    pub write_sectors: usize,
    pub write_ticks: u64,
    pub in_flight: usize,
    pub io_ticks: u64,
    pub time_in_queue: u64,
    pub discard_ios: usize,
    pub discard_merges: usize,
    pub discard_sectors: usize,
    pub discard_ticks: u64,
}
impl BlockStorageStat {
    pub(crate) fn from_stat(stat: &str) -> Result<BlockStorageStat> {
        let mut elems = stat.split_ascii_whitespace();

        Ok(BlockStorageStat {
            read_ios: next::<usize, SplitAsciiWhitespace>(&mut elems, &stat)?,
            read_merges: next::<usize, SplitAsciiWhitespace>(&mut elems, &stat)?,
            read_sectors: next::<usize, SplitAsciiWhitespace>(&mut elems, &stat)?,
            read_ticks: next::<u64, SplitAsciiWhitespace>(&mut elems, &stat)?,
            write_ios: next::<usize, SplitAsciiWhitespace>(&mut elems, &stat)?,
            write_merges: next::<usize, SplitAsciiWhitespace>(&mut elems, &stat)?,
            write_sectors: next::<usize, SplitAsciiWhitespace>(&mut elems, &stat)?,
            write_ticks: next::<u64, SplitAsciiWhitespace>(&mut elems, &stat)?,
            in_flight: next::<usize, SplitAsciiWhitespace>(&mut elems, &stat)?,
            io_ticks: next::<u64, SplitAsciiWhitespace>(&mut elems, &stat)?,
            time_in_queue: next::<u64, SplitAsciiWhitespace>(&mut elems, &stat)?,
            discard_ios: next::<usize, SplitAsciiWhitespace>(&mut elems, &stat)?,
            discard_merges: next::<usize, SplitAsciiWhitespace>(&mut elems, &stat)?,
            discard_sectors: next::<usize, SplitAsciiWhitespace>(&mut elems, &stat)?,
            discard_ticks: next::<u64, SplitAsciiWhitespace>(&mut elems, &stat)?,
        })
    }
}

#[derive(Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct BlockStorageInfo {
    pub dev: String,
    pub size: usize,
    pub maj: u32,
    pub min: u32,
    pub block_size: i64,
    pub stat: BlockStorageStat,
}
impl BlockStorageInfo {
    fn from_sys_path(path: PathBuf) -> Result<BlockStorageInfo> {
        let (maj, min) = parse_maj_min(&SysPath::Custom(path.join("dev")).read()?).unwrap_or_default();
        let device = path
            .file_name()
            .ok_or(Error::InvalidInputError(
                path.to_string_lossy().to_string(),
                "Given path doesn't have a file name".to_string(),
            ))?
            .to_string_lossy()
            .to_string();
        Ok(BlockStorageInfo {
            dev: device.clone(),
            size: trim_parse_map::<usize>(&SysPath::Custom(path.join("size")).read()?)?,
            maj,
            min,
            block_size: block_size(&device)?,
            stat: BlockStorageStat::from_stat(&SysPath::Custom(path.join("stat")).read()?)?,
        })
    }
}

#[derive(Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct ScsiCdrom {
    pub info: BlockStorageInfo,
    pub model: String,
    pub vendor: String,
    pub state: String,
}
impl ScsiCdrom {
    pub(crate) fn from_sys(name: &str) -> Result<ScsiCdrom> {
        if !name.starts_with("sr") {
            return Err(Error::InvalidInputError(
                name.to_string(),
                "SCSI CDrom device name must begin with 'sr'".to_string(),
            ));
        }
        Ok(ScsiCdrom {
            info: BlockStorageInfo::from_sys_path(SysPath::SysBlockDev(name).path())?,
            model: trim_parse_map::<String>(&SysPath::SysBlockDevModel(name).read()?)?,
            vendor: trim_parse_map::<String>(&SysPath::SysBlockDevVendor(name).read()?)?,
            state: trim_parse_map::<String>(&SysPath::SysBlockDevState(name).read()?)?,
        })
    }
}

#[derive(Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
/// Represents a block storage device.
pub struct StorageDevice {
    pub info: BlockStorageInfo,
    pub model: String,
    pub vendor: String,
    pub state: String,
    pub partitions: Partitions,
}
impl StorageDevice {
    pub(crate) fn from_sys(name: &str) -> Result<StorageDevice> {
        if !name.starts_with("sd") {
            return Err(Error::InvalidInputError(
                name.to_string(),
                "block storage device name must begin with 'sd'".to_string(),
            ));
        }
        Ok(StorageDevice {
            info: BlockStorageInfo::from_sys_path(SysPath::SysBlockDev(name).path())?,
            model: trim_parse_map::<String>(&SysPath::SysBlockDevModel(name).read()?)?,
            vendor: trim_parse_map::<String>(&SysPath::SysBlockDevVendor(name).read()?)?,
            state: trim_parse_map::<String>(&SysPath::SysBlockDevState(name).read()?)?,
            partitions: find_subdevices::<Partition>(
                SysPath::SysBlockDev(name).path(),
                Hierarchy::None,
                DevType::Partition,
                false,
            )
            .unwrap_or_default(),
        })
    }
}

#[derive(Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct DeviceMapper {
    pub info: BlockStorageInfo,
    pub name: String,
    pub uuid: String,
    pub slave_parts: Option<Partitions>,
    pub slave_mds: Option<MultipleDeviceStorages>,
}
impl DeviceMapper {
    pub(crate) fn from_sys(name: &str) -> Result<DeviceMapper> {
        if !name.starts_with("dm") {
            return Err(Error::InvalidInputError(
                name.to_string(),
                "device mapper name must begin with 'dm'".to_string(),
            ));
        }
        Ok(DeviceMapper {
            info: BlockStorageInfo::from_sys_path(SysPath::SysBlockDev(name).path())?,
            uuid: trim_parse_map::<String>(&SysPath::SysDevMapperUuid(name).read()?)?,
            name: trim_parse_map::<String>(&SysPath::SysDevMapperName(name).read()?)?,
            slave_parts: find_subdevices::<Partition>(
                SysPath::SysBlockDev(name).path(),
                Hierarchy::Slaves,
                DevType::Partition,
                false,
            ),
            slave_mds: find_subdevices::<MultipleDeviceStorage>(
                SysPath::SysBlockDev(name).path(),
                Hierarchy::Slaves,
                DevType::Md,
                true,
            ),
        })
    }
}

impl FromSysPath<DeviceMapper> for DeviceMapper {
    fn from_sys_path(path: PathBuf, hierarchy: bool) -> Result<Self> {
        Ok(DeviceMapper {
            info: BlockStorageInfo::from_sys_path(path.clone())?,
            name: trim_parse_map::<String>(&SysPath::Custom(path.join("dm").join("name")).read()?)?,
            uuid: trim_parse_map::<String>(&SysPath::Custom(path.join("dm").join("uuid")).read()?)?,
            slave_mds: if hierarchy {
                find_subdevices::<MultipleDeviceStorage>(path.clone(), Hierarchy::Slaves, DevType::Md, true)
            } else {
                None
            },
            slave_parts: if hierarchy {
                find_subdevices::<Partition>(path.clone(), Hierarchy::Slaves, DevType::Partition, false)
            } else {
                None
            },
        })
    }
}

#[derive(Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct Partition {
    pub info: BlockStorageInfo,
    pub holder_mds: Option<MultipleDeviceStorages>,
    pub holder_dms: Option<DeviceMappers>,
}
impl FromSysPath<Partition> for Partition {
    fn from_sys_path(path: PathBuf, hierarchy: bool) -> Result<Self> {
        Ok(Partition {
            info: BlockStorageInfo::from_sys_path(path.clone())?,
            holder_mds: if hierarchy {
                find_subdevices::<MultipleDeviceStorage>(path.clone(), Hierarchy::Holders, DevType::Md, false)
            } else {
                None
            },
            holder_dms: if hierarchy {
                find_subdevices::<DeviceMapper>(path.clone(), Hierarchy::Holders, DevType::DevMapper, false)
            } else {
                None
            },
        })
    }
}

#[derive(Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct MultipleDeviceStorage {
    pub info: BlockStorageInfo,
    pub level: String,
    pub slave_parts: Option<Partitions>,
    pub holder_devices: Option<DeviceMappers>,
}
impl MultipleDeviceStorage {
    pub(crate) fn from_sys_path(path: PathBuf, hierarchy: bool) -> Result<MultipleDeviceStorage> {
        Ok(MultipleDeviceStorage {
            info: BlockStorageInfo::from_sys_path(path.clone())?,
            level: trim_parse_map::<String>(&SysPath::Custom(path.join("md").join("level")).read()?)?,
            slave_parts: if hierarchy {
                find_subdevices::<Partition>(path.clone(), Hierarchy::Slaves, DevType::Partition, false)
            } else {
                None
            },
            holder_devices: if hierarchy {
                find_subdevices::<DeviceMapper>(path.clone(), Hierarchy::Holders, DevType::DevMapper, false)
            } else {
                None
            },
        })
    }

    pub(crate) fn from_sys(name: &str) -> Result<MultipleDeviceStorage> {
        if !name.starts_with("md") {
            return Err(Error::InvalidInputError(
                name.to_string(),
                "multiple device storage name must begin with 'md'".to_string(),
            ));
        }
        MultipleDeviceStorage::from_sys_path(SysPath::SysClassBlock(name).path(), true)
    }
}
impl FromSysPath<MultipleDeviceStorage> for MultipleDeviceStorage {
    fn from_sys_path(path: PathBuf, hierarchy: bool) -> Result<Self> {
        Self::from_sys_path(path, hierarchy)
    }
}