sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use crate::CpuInner;

/// Information about a CPU.
#[doc = include_str!("../../docs/snippets/cpu.md")]
pub struct Cpu {
    pub(crate) inner: CpuInner,
}

impl Cpu {
    /// Returns this CPU's usage.
    pub fn usage(&self) -> f32 {
        self.inner.cpu_usage()
    }

    /// Returns this CPU's name.
    pub fn name(&self) -> &str {
        self.inner.name()
    }

    /// Returns the CPU vendor ID.
    pub fn vendor_id(&self) -> &str {
        self.inner.vendor_id()
    }

    /// Returns the CPU's brand.
    pub fn brand(&self) -> &str {
        self.inner.brand()
    }

    /// Returns the CPU frequency in MHz.
    pub fn frequency(&self) -> u64 {
        self.inner.frequency()
    }
}

#[cfg(test)]
mod test {
    use crate::*;
    use std::str::FromStr;

    // If `Process::updated` is misused, `System::refresh_processes` might remove processes.
    #[test]
    fn check_refresh_process_update() {
        if let Ok(mut s) = System::new_all() {
            let total = s.processes().len();
            s.refresh_processes(ProcessesToUpdate::All, false);
            let new_total = s.processes().len();
            // `remove_dead_processes` is false, so a refresh may add processes but must not drop entries that were already listed.
            assert!(
                new_total >= total,
                "process count shrank: {total} -> {new_total}"
            );
        }
    }

    #[test]
    fn check_cpu_arch() {
        assert!(!System::cpu_arch().is_empty());
    }

    // The CPU frequency must not be retrieved until requested.
    #[test]
    fn check_cpu_frequency() {
        let Ok(mut s) = System::new() else { return };
        s.refresh_processes(ProcessesToUpdate::All, false);
        for proc_ in s.cpus() {
            assert_eq!(proc_.frequency(), 0);
        }
        s.refresh_cpu_usage();
        for proc_ in s.cpus() {
            assert_eq!(proc_.frequency(), 0);
        }
        // This fails inside a VM.
        if std::env::var("APPLE_CI").is_ok()
            || std::env::var("FREEBSD_CI").is_ok()
            || std::env::var("NETBSD_CI").is_ok()
        {
            return;
        }
        s.refresh_cpu_specifics(CpuRefreshKind::everything());
        for proc_ in s.cpus() {
            assert_ne!(proc_.frequency(), 0);
        }
    }

    #[test]
    fn check_process_memory_usage() {
        let Ok(mut s) = System::new() else { return };
        s.refresh_specifics(RefreshKind::everything());

        let apple_sandbox = cfg!(all(
            feature = "apple-sandbox",
            any(target_os = "macos", target_os = "ios")
        ));
        if !apple_sandbox {
            // No process should report zero memory usage.
            assert!(!s.processes().iter().all(|(_, proc_)| proc_.memory() == 0));
        } else {
            // No process should exist; if one does, its memory usage should be zero.
            assert!(s.processes().iter().all(|(_, proc_)| proc_.memory() == 0));
        }
    }

    #[test]
    fn check_memory_usage() {
        let Ok(mut s) = System::new() else { return };

        assert_eq!(s.total_memory(), 0);
        assert_eq!(s.free_memory(), 0);
        assert_eq!(s.available_memory(), 0);
        assert_eq!(s.used_memory(), 0);
        assert_eq!(s.total_swap(), 0);
        assert_eq!(s.free_swap(), 0);
        assert_eq!(s.used_swap(), 0);

        s.refresh_memory();
        let apple_sandbox = cfg!(all(
            feature = "apple-sandbox",
            any(target_os = "macos", target_os = "ios")
        ));
        if !apple_sandbox {
            assert!(s.total_memory() > 0);
            assert!(s.used_memory() > 0);
            if s.total_swap() > 0 {
                // Assume that some swap remains free.
                assert!(s.free_swap() > 0);
            }
        } else {
            assert_eq!(s.total_memory(), 0);
            assert_eq!(s.used_memory(), 0);
            assert_eq!(s.total_swap(), 0);
            assert_eq!(s.free_swap(), 0);
        }
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn check_processes_cpu_usage() {
        let Ok(mut s) = System::new() else { return };

        s.refresh_processes(ProcessesToUpdate::All, false);
        // CPU usage starts at zero until the second refresh.
        assert!(
            s.processes()
                .iter()
                .all(|(_, proc_)| proc_.cpu_usage() == 0.0)
        );

        // Wait so that CPU usage values update.
        std::thread::sleep(MINIMUM_CPU_UPDATE_INTERVAL);
        s.refresh_processes(ProcessesToUpdate::All, true);
        assert!(
            s.processes()
                .iter()
                .all(|(_, proc_)| proc_.cpu_usage() >= 0.0
                    && proc_.cpu_usage() <= (s.cpus().len() as f32) * 100.0)
        );
        assert!(
            s.processes()
                .iter()
                .any(|(_, proc_)| proc_.cpu_usage() > 0.0)
        );
    }

    #[test]
    fn check_cpu_usage() {
        let Ok(mut s) = System::new() else { return };
        for _ in 0..10 {
            s.refresh_cpu_usage();
            // Wait so that CPU usage values update.
            std::thread::sleep(MINIMUM_CPU_UPDATE_INTERVAL);
            if s.cpus().iter().any(|c| c.usage() > 0.0) {
                // A non-zero usage was observed.
                return;
            }
        }
        panic!("CPU usage is always zero...");
    }

    #[test]
    fn check_system_info() {
        // Skip unsupported systems.
        if System::new().is_ok() {
            assert!(
                !System::name()
                    .expect("Failed to get system name")
                    .is_empty()
            );

            assert!(
                !System::kernel_version()
                    .expect("Failed to get kernel version")
                    .is_empty()
            );

            assert!(
                !System::os_version()
                    .expect("Failed to get os version")
                    .is_empty()
            );

            assert!(
                !System::long_os_version()
                    .expect("Failed to get long OS version")
                    .is_empty()
            );
        }

        assert!(!System::distribution_id().is_empty());
    }

    #[test]
    fn check_host_name() {
        // Skip unsupported systems.
        if System::new().is_ok() {
            assert!(System::host_name().is_ok());
        }
    }

    #[test]
    fn check_refresh_process_return_value() {
        // Skip unsupported systems.
        if System::new().is_ok() {
            let _pid = get_current_pid().expect("Failed to get current PID");

            #[cfg(not(feature = "apple-sandbox"))]
            {
                let Ok(mut s) = System::new() else { return };
                // First, the process is not yet in the process list.
                assert_eq!(
                    s.refresh_processes(ProcessesToUpdate::Some(&[_pid]), true),
                    1
                );
                // The result stays 1 when the process is already in the list.
                assert_eq!(
                    s.refresh_processes(ProcessesToUpdate::Some(&[_pid]), true),
                    1
                );
            }
        }
    }

    #[test]
    fn check_cpus_number() {
        let Ok(mut s) = System::new() else { return };

        // This information is not retrieved by default.
        assert!(s.cpus().is_empty());
        if System::new().is_ok() {
            // The physical core count is recomputed on every call, so it must be valid even with nothing initialized.
            let physical_cores_count =
                System::physical_core_count().expect("failed to get number of physical cores");

            s.refresh_cpu_usage();
            // The CPU list must no longer be empty.
            assert!(!s.cpus().is_empty());

            // A VM may expose only logical cores, so the test does not assert `physical_cores_count > 0`.
            let physical_cores_count2 =
                System::physical_core_count().expect("failed to get number of physical cores");
            assert!(physical_cores_count2 <= s.cpus().len());
            assert_eq!(physical_cores_count, physical_cores_count2);
        } else {
            assert!(matches!(
                System::physical_core_count(),
                Err(crate::Error::Unsupported)
            ));
        }
        assert!(System::physical_core_count().unwrap_or(0) <= s.cpus().len());
    }

    // This test exists only to ensure that `ProcessStatus` implements the `Display` and `Debug` traits on all targets.
    #[test]
    fn check_display_impl_process_status() {
        println!("{} {:?}", ProcessStatus::Parked, ProcessStatus::Idle);
    }

    #[test]
    #[allow(clippy::unnecessary_fallible_conversions)]
    fn check_pid_from_impls() {
        assert!(crate::Pid::try_from(0usize).is_ok());
        // The call must not panic.
        let _ = crate::Pid::from(0);
        assert!(crate::Pid::from_str("0").is_ok());
    }

    #[test]
    #[allow(clippy::const_is_empty)]
    fn check_nb_supported_signals() {
        if System::new().is_ok() {
            assert!(
                !SUPPORTED_SIGNALS.is_empty(),
                "SUPPORTED_SIGNALS shouldn't be empty on supported systems!"
            );
        } else {
            assert!(
                SUPPORTED_SIGNALS.is_empty(),
                "SUPPORTED_SIGNALS should be empty on not support systems!"
            );
        }
    }
}