nmbrs-runtime 0.7.2

Workload execution runtime for nmbrs
Documentation
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! Network throughput per interface, from `/proc/net/dev`
//! (SRD-118 ยง3.6).

/// One interface's cumulative byte counters.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NetCounters {
    pub iface: String,
    pub rx_bytes: u64,
    pub tx_bytes: u64,
}

/// Every interface's cumulative counters but the loopback's. A line
/// is `iface: <8 receive fields> <8 transmit fields>`; bytes are the
/// first field of each half.
pub fn parse_net_dev(text: &str) -> Vec<NetCounters> {
    text.lines()
        .filter_map(|line| {
            let (iface, counters) = line.split_once(':')?;
            let iface = iface.trim();
            if iface == "lo" {
                return None;
            }
            let fields: Vec<&str> = counters.split_whitespace().collect();
            Some(NetCounters {
                iface: iface.to_string(),
                rx_bytes: fields.first()?.parse().ok()?,
                tx_bytes: fields.get(8)?.parse().ok()?,
            })
        })
        .collect()
}

/// What one interface received and sent over a sample window.
#[derive(Debug, Clone, PartialEq)]
pub struct NetRate {
    pub iface: String,
    pub rx_bytes_per_s: f64,
    pub tx_bytes_per_s: f64,
}

/// Each interface's throughput between two snapshots `dt_s` apart, for
/// the interfaces in both. An interface that has never carried a byte
/// is left out, so an unused one makes no series.
pub fn net_rates(prev: &[NetCounters], cur: &[NetCounters], dt_s: f64) -> Vec<NetRate> {
    if dt_s <= 0.0 {
        return Vec::new();
    }
    cur.iter()
        .filter(|now| now.rx_bytes > 0 || now.tx_bytes > 0)
        .filter_map(|now| {
            let before = prev.iter().find(|n| n.iface == now.iface)?;
            Some(NetRate {
                iface: now.iface.clone(),
                rx_bytes_per_s: now.rx_bytes.saturating_sub(before.rx_bytes) as f64 / dt_s,
                tx_bytes_per_s: now.tx_bytes.saturating_sub(before.tx_bytes) as f64 / dt_s,
            })
        })
        .collect()
}

/// Read `/proc/net/dev`. Empty when it cannot be read.
pub(super) fn read_net_dev() -> Vec<NetCounters> {
    std::fs::read_to_string("/proc/net/dev")
        .map(|t| parse_net_dev(&t))
        .unwrap_or_default()
}

#[cfg(test)]
mod tests {
    use super::*;

    const T0: &str = "\
Inter-|   Receive                                                |  Transmit
 face |bytes    packets errs drop fifo frame compressed multicast|bytes    packets errs drop fifo colls carrier compressed
    lo: 5000 10 0 0 0 0 0 0 5000 10 0 0 0 0 0 0
  eth0: 1000 10 0 0 0 0 0 0 4000 20 0 0 0 0 0 0
  eth1:    0  0 0 0 0 0 0 0    0  0 0 0 0 0 0 0";

    /// The header lines and the loopback are not interfaces to report.
    #[test]
    fn interfaces_are_read_without_the_loopback() {
        assert_eq!(
            parse_net_dev(T0),
            vec![
                NetCounters {
                    iface: "eth0".into(),
                    rx_bytes: 1000,
                    tx_bytes: 4000
                },
                NetCounters {
                    iface: "eth1".into(),
                    rx_bytes: 0,
                    tx_bytes: 0
                },
            ]
        );
    }

    #[test]
    fn rates_are_per_second_and_an_unused_interface_is_left_out() {
        let prev = parse_net_dev(T0);
        let cur = parse_net_dev(
            &T0.replace("1000 10", "3000 10")
                .replace("4000 20", "4500 20"),
        );
        assert_eq!(
            net_rates(&prev, &cur, 2.0),
            vec![NetRate {
                iface: "eth0".into(),
                rx_bytes_per_s: 1000.0,
                tx_bytes_per_s: 250.0,
            }]
        );
    }
}