sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use crate::sys::ffi;
use crate::sys::utils::get_all_utf8_data;
use crate::{Disk, DiskKind, DiskRefreshKind, DiskUsage, DisksInner, Error};

use std::collections::HashMap;
use std::ffi::{OsStr, OsString};
use std::fs;
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
use std::str::FromStr;

/// Copied from [`psutil`]: "man iostat" states that sectors are equivalent with blocks and have
const SECTOR_SIZE: u64 = 512;

pub(crate) struct DiskInner {
    type_: DiskKind,
    device_id: Option<u64>,
    device_name: OsString,
    actual_device_name: Option<String>,
    pub(crate) file_system: OsString,
    mount_point: PathBuf,
    total_space: u64,
    available_space: u64,
    is_removable: bool,
    is_read_only: bool,
    old_written_bytes: u64,
    old_read_bytes: u64,
    written_bytes: u64,
    read_bytes: u64,
    updated: bool,
}

#[cfg(test)]
impl Default for DiskInner {
    fn default() -> Self {
        Self {
            type_: DiskKind::Unknown(0),
            device_id: None,
            device_name: OsString::new(),
            actual_device_name: None,
            file_system: OsString::new(),
            mount_point: PathBuf::new(),
            total_space: 0,
            available_space: 0,
            is_removable: false,
            is_read_only: false,
            old_written_bytes: 0,
            old_read_bytes: 0,
            written_bytes: 0,
            read_bytes: 0,
            updated: false,
        }
    }
}

impl DiskInner {
    pub(crate) fn kind(&self) -> DiskKind {
        self.type_
    }

    pub(crate) fn id(&self) -> Option<u64> {
        self.device_id
    }

    pub(crate) fn name(&self) -> &OsStr {
        &self.device_name
    }

    pub(crate) fn file_system(&self) -> &OsStr {
        &self.file_system
    }

    pub(crate) fn mount_point(&self) -> &Path {
        &self.mount_point
    }

    pub(crate) fn total_space(&self) -> u64 {
        self.total_space
    }

    pub(crate) fn available_space(&self) -> u64 {
        self.available_space
    }

    pub(crate) fn is_removable(&self) -> bool {
        self.is_removable
    }

    pub(crate) fn is_read_only(&self) -> bool {
        self.is_read_only
    }

    pub(crate) fn refresh_specifics(&mut self, refresh_kind: DiskRefreshKind) -> bool {
        self.efficient_refresh(refresh_kind, &disk_stats(&refresh_kind), false)
    }

    fn efficient_refresh(
        &mut self,
        refresh_kind: DiskRefreshKind,
        procfs_disk_stats: &HashMap<String, DiskStat>,
        first: bool,
    ) -> bool {
        if refresh_kind.io_usage() {
            if self.actual_device_name.is_none() {
                self.actual_device_name = Some(get_actual_device_name(&self.device_name));
            }
            if let Some(stat) = self
                .actual_device_name
                .as_ref()
                .and_then(|actual_device_name| procfs_disk_stats.get(actual_device_name))
            {
                self.old_read_bytes = self.read_bytes;
                self.old_written_bytes = self.written_bytes;
                self.read_bytes = stat.sectors_read * SECTOR_SIZE;
                self.written_bytes = stat.sectors_written * SECTOR_SIZE;
            } else {
                sinf_debug!("Failed to update disk i/o stats");
            }
        }

        if refresh_kind.kind() && self.type_ == DiskKind::Unknown(-1) {
            self.type_ = find_type_for_device_name(&self.device_name);
        }

        if refresh_kind.storage()
            && let Some((total_space, available_space, is_read_only)) =
                ffi::statvfs_values(&self.mount_point)
        {
            self.total_space = total_space;
            self.available_space = available_space;
            if first {
                self.is_read_only = is_read_only;
            }
        }

        true
    }

    pub(crate) fn usage(&self) -> DiskUsage {
        DiskUsage {
            read_bytes: self.read_bytes.saturating_sub(self.old_read_bytes),
            total_read_bytes: self.read_bytes,
            written_bytes: self.written_bytes.saturating_sub(self.old_written_bytes),
            total_written_bytes: self.written_bytes,
        }
    }
}

impl DisksInner {
    pub(crate) fn new() -> Result<Self, Error> {
        Ok(Self {
            disks: Vec::with_capacity(2),
        })
    }

    pub(crate) fn refresh_specifics(
        &mut self,
        remove_not_listed_disks: bool,
        refresh_kind: DiskRefreshKind,
    ) {
        get_all_list(
            &mut self.disks,
            &get_all_utf8_data("/proc/mounts", 16_385).unwrap_or_default(),
            refresh_kind,
        );

        if remove_not_listed_disks {
            self.disks.retain_mut(|disk| {
                if !disk.inner.updated {
                    return false;
                }
                disk.inner.updated = false;
                true
            });
        } else {
            for c in self.disks.iter_mut() {
                c.inner.updated = false;
            }
        }
    }

    pub(crate) fn list(&self) -> &[Disk] {
        &self.disks
    }

    pub(crate) fn list_mut(&mut self) -> &mut [Disk] {
        &mut self.disks
    }
}

/// Resolves the actual device name for a `device` listed in `/proc/mounts`.
mod helpers;
mod stats;

#[cfg(test)]
mod tests;

use self::helpers::*;
use self::stats::*;

#[cfg(all(feature = "fuzzing", target_os = "linux"))]
pub(crate) fn fuzz_diskstats(data: &str) -> usize {
    stats::disk_stats_inner(data).len()
}