systemstat

repository·trunk·Indexed 20 days ago

https://github.com/valpackett/systemstat

A pure Rust library for retrieving cross-platform system statistics, including CPU load, memory usage, disk I/O, network traffic, and hardware information. It supports FreeBSD, Linux, OpenBSD, Windows, macOS, NetBSD, and DragonFly BSD, providing a unified interface via the System and Platform types to access system state, uptime, and battery life.

Tokens
1.8K
Snippets
9
Records
14
Agent score
71%

What's inside systemstat

  1. Overview of systemstat capabilities

    trunk

    systemstat is a pure Rust library designed to retrieve various system statistics and information across multiple platforms. It provides access to:

    • CPU: Load and load average.
    • Memory: Usage statistics.
    • System State: Uptime, boot time, and battery life.
    • Storage: Filesystem mounts, disk usage, and disk I/O statistics.
    • Network: Network interfaces and network traffic statistics.
    • Hardware: CPU temperature.

    Unlike sys-info-rs, this library is written entirely in Rust, which may offer better integration and safety within the Rust ecosystem.

  2. Supported platforms for systemstat

    trunk

    The library supports a wide range of operating systems. Support completeness varies by platform, with FreeBSD and Linux being the most complete. Supported platforms include:

    • FreeBSD
    • Linux
    • OpenBSD
    • Windows
    • macOS
    • NetBSD
    • DragonFly BSD
  3. Access system information using the System struct

    trunk

    The systemstat library provides access to system information like CPU load, mounted filesystems, and network interfaces. You can interact with the system via the System type (which is an alias for PlatformImpl) or by using the data structures defined in the data module.

    To get started, import the necessary modules and use the System implementation to query platform-specific statistics.

    use systemstat::{System, Platform};
    
    // The `System` type is an alias for `PlatformImpl` and provides the core API
    let sys = System::new();
    // ... use sys to access statistics
  4. Use DelayedMeasurement for time-sensitive stats

    trunk

    The DelayedMeasurement<T> struct is a wrapper for measurements that require a specific amount of time to pass between the initial request and the actual data retrieval.

    To use it, wrap a closure that returns an io::Result<T> using DelayedMeasurement::new(). You must then call .done() to execute the closure and retrieve the result.

    let measurement = DelayedMeasurement::new(Box::new(|| {
        // Perform the actual measurement here
        Ok(some_value)
    }));
    
    // ... wait for required time to pass ...
    
    let result = measurement.done()?;
  5. Calculate average CPULoad using avg_add

    trunk

    The CPULoad struct provides an avg_add method to compute the average between two CPULoad instances. This is useful for smoothing or calculating the mean load over two measurement points.

    It averages all standard fields (user, nice, system, interrupt, idle) and also calls avg_add on the platform field.

    let load1 = CPULoad { ... };
    let load2 = CPULoad { ... };
    let average_load = load1.avg_add(&load2);
  6. Subtract CpuTime instances

    trunk

    The CpuTime struct implements the Sub trait, allowing you to subtract one CpuTime instance from another. This is typically used to find the delta between two snapshots of CPU counters.

    Subtraction uses saturating_sub for all fields to prevent underflow errors.

    let delta = end_time - start_time;
  7. Convert CpuTime to CPULoad

    trunk

    The CpuTime struct represents cumulative CPU time spent in various modes. You can convert these raw counters into a CPULoad struct, which represents the percentage of CPU usage for each mode (user, nice, system, interrupt, idle, and platform/other).

    Note that to_cpuload() calculates the percentage based on the total sum of all fields in the CpuTime instance.

    // Assuming you have a CpuTime instance
    let load = cpu_time.to_cpuload();
    println!("User load: {}", load.user);
  8. Reference: Network and Socket statistics

    trunk

    The library provides structures for network interface details and socket usage counts.

    pub struct Network {
        pub name: String,
        pub addrs: Vec<NetworkAddrs>,
    }
    
    pub struct NetworkStats {
        pub rx_bytes: ByteSize,
        pub tx_bytes: ByteSize,
        pub rx_packets: u64,
        pub tx_packets: u64,
        pub rx_errors: u64,
        pub tx_errors: u64,
    }
    
    pub struct SocketStats {
        pub tcp_sockets_in_use: usize,
        pub tcp_sockets_orphaned: usize,
        pub udp_sockets_in_use: usize,
        pub tcp6_sockets_in_use: usize,
        pub udp6_sockets_in_use: usize,
    }
  9. Reference: CPULoad fields

    trunk

    The CPULoad struct provides a snapshot of CPU usage percentages. The platform field contains OS-specific data (e.g., iowait on Linux).

    pub struct CPULoad {
        pub user: f32,
        pub nice: f32,
        pub system: f32,
        pub interrupt: f32,
        pub idle: f32,
        pub platform: PlatformCpuLoad,
    }
  10. Reference: Memory and Swap structures

    trunk

    The library provides Memory and Swap structures. Memory contains total and free bytes along with a platform_memory field that varies significantly by OS (e.g., meminfo on Linux, specific fields on macOS/FreeBSD/Windows).

    pub struct Memory {
        pub total: ByteSize,
        pub free: ByteSize,
        pub platform_memory: PlatformMemory,
    }
    
    pub struct Swap {
        pub total: ByteSize,
        pub free: ByteSize,
        pub platform_swap: PlatformSwap,
    }