nmbrs-runtime 0.7.3

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

//! The sampler task: read each enabled subsystem once per interval,
//! and publish the window to the session's gauges and the observer.

use std::sync::{Arc, RwLock};
use std::time::Instant;

use nmbrs_metrics::component::Component;

use nmbrs_host::category::Categories;
use nmbrs_host::cgroup::WatchedCgroup;
use nmbrs_host::process::{OWN_NAME, ProcSource, ProcTarget, Watched};
use nmbrs_host::{cpu, disk, mem, net, pressure, process};

use super::gauges::Gauges;
use super::{SysmonConfig, SysmonSample};

/// What the last window left behind for the next one to take a
/// difference against.
struct Previous {
    at: Instant,
    disks: Vec<disk::DiskCounters>,
    cpu: Option<(cpu::CpuTicks, Vec<cpu::CpuTicks>)>,
    membw: Option<u64>,
    net: Vec<net::NetCounters>,
    pressure: Option<pressure::PressureTotals>,
    procs: Vec<Watched>,
    proc_units: (f64, f64),
    cgroups: Vec<WatchedCgroup>,
}

impl Previous {
    /// The first reading, taken when the sampler starts.
    fn first(config: &SysmonConfig) -> Self {
        let cats = config.cats;
        let mut procs = Vec::new();
        if cats.proc {
            procs.push(Watched::new(ProcTarget {
                name: OWN_NAME.to_string(),
                source: ProcSource::Own,
            }));
            procs.extend(config.procs.iter().cloned().map(Watched::new));
        }
        let mut previous = Self {
            at: Instant::now(),
            disks: if cats.io {
                disk::read_diskstats()
            } else {
                Vec::new()
            },
            cpu: if cats.cpu {
                cpu::read_proc_stat()
            } else {
                None
            },
            membw: if cats.rambw {
                mem::read_membw_bytes()
            } else {
                None
            },
            net: if cats.net {
                net::read_net_dev()
            } else {
                Vec::new()
            },
            pressure: if cats.pressure {
                pressure::read_pressure()
            } else {
                None
            },
            procs,
            proc_units: process::units(),
            cgroups: if cats.cgroup {
                config
                    .cgroups
                    .iter()
                    .cloned()
                    .map(WatchedCgroup::new)
                    .collect()
            } else {
                Vec::new()
            },
        };
        // The first read of a process or a group has no window; it
        // only sets the counters the next one is measured from.
        previous.sample_procs(0.0);
        previous.sample_cgroups(0.0);
        previous
    }

    fn sample_cgroups(&mut self, dt_s: f64) -> Vec<nmbrs_host::cgroup::CgroupReading> {
        if self.cgroups.is_empty() {
            return Vec::new();
        }
        let devices = disk::read_device_numbers();
        let mut missing = |name: &str| {
            crate::diag!(
                crate::observer::LogLevel::Warn,
                "sysmon: control group '{name}' is not there; it has no series until it is"
            );
        };
        self.cgroups
            .iter_mut()
            .filter_map(|watched| watched.sample(dt_s, &devices, &mut missing))
            .collect()
    }

    fn sample_procs(&mut self, dt_s: f64) -> Vec<process::ProcReading> {
        let units = self.proc_units;
        let mut missing = |name: &str| {
            crate::diag!(
                crate::observer::LogLevel::Warn,
                "sysmon: process '{name}' is not running (or its pidfile is unreadable); \
                 it has no series until it is"
            );
        };
        self.procs
            .iter_mut()
            .filter_map(|watched| watched.sample(dt_s, units, &mut missing))
            .collect()
    }

    /// Read every enabled subsystem and return the window since the
    /// last read.
    fn window(&mut self, cats: Categories, membw_peak: Option<f64>) -> SysmonSample {
        let now = Instant::now();
        let dt_s = now.duration_since(self.at).as_secs_f64();
        self.at = now;
        let mut sample = SysmonSample::default();

        if cats.io {
            let cur = disk::read_diskstats();
            sample.io = disk::max_disk_util(&self.disks, &cur, dt_s * 1000.0);
            sample.io_rates = disk::disk_rates(&self.disks, &cur, dt_s, &disk::is_whole_device);
            self.disks = cur;
        }
        if cats.cpu {
            let cur = cpu::read_proc_stat();
            if let (Some((pa, pc)), Some((ca, cc))) = (&self.cpu, &cur) {
                let (top_core, max_core) = cpu::max_core_util(pc, cc).unwrap_or((0, 0.0));
                let (p25, p50, p75, cores) =
                    cpu::core_util_quartiles(pc, cc).unwrap_or((0.0, 0.0, 0.0, 0));
                sample.cpu = Some(cpu::CpuReading {
                    mean: cpu::cpu_util(*pa, *ca),
                    max_core,
                    top_core,
                    p25,
                    p50,
                    p75,
                    cores,
                });
            }
            self.cpu = cur;
        }
        if cats.ram {
            sample.ram = std::fs::read_to_string("/proc/meminfo")
                .ok()
                .and_then(|t| mem::parse_meminfo(&t))
                .map(mem::mem_utils);
        }
        if cats.rambw
            && let Some(peak) = membw_peak
        {
            let cur = mem::read_membw_bytes();
            if let (Some(p), Some(c)) = (self.membw, cur) {
                sample.rambw =
                    Some(((c.saturating_sub(p)) as f64 / dt_s.max(1e-9) / peak).clamp(0.0, 1.0));
            }
            self.membw = cur;
        }
        if cats.storage {
            sample.storage = disk::max_storage_util();
        }
        if cats.net {
            let cur = net::read_net_dev();
            sample.net = net::net_rates(&self.net, &cur, dt_s);
            self.net = cur;
        }
        if cats.pressure {
            let cur = pressure::read_pressure();
            if let (Some(p), Some(c)) = (self.pressure, cur) {
                sample.pressure = Some(pressure::pressure_between(p, c, dt_s));
            }
            self.pressure = cur;
        }
        if cats.proc {
            sample.procs = self.sample_procs(dt_s);
        }
        if cats.cgroup {
            sample.cgroups = self.sample_cgroups(dt_s);
        }
        sample
    }
}

/// Spawn the sampler. `check_requirements` must have passed first —
/// the runner aborts the session on its Err rather than calling this.
/// Runs until session shutdown; publishes each window to the session gauges
/// and to `observer.sysmon_update`.
pub fn spawn(
    config: SysmonConfig,
    component: Arc<RwLock<Component>>,
    observer: Arc<dyn crate::observer::RunObserver>,
) -> Result<tokio::task::JoinHandle<()>, String> {
    super::check_requirements(&config)?;
    let mut gauges = Gauges::register(&component, config.cats)?;
    let mut shutdown = crate::session_signals::subscribe_shutdown();
    Ok(tokio::spawn(async move {
        let mut previous = Previous::first(&config);
        loop {
            tokio::select! {
                _ = tokio::time::sleep(config.interval) => {}
                _ = shutdown.changed() => break,
            }
            let sample = previous.window(config.cats, config.membw_peak_bytes_per_s);
            gauges.publish(&sample);
            observer.sysmon_update(&sample);
        }
    }))
}