micromegas_telemetry_sink/
system_monitor.rs

1use micromegas_tracing::{fmetric, imetric};
2use sysinfo::{CpuRefreshKind, MemoryRefreshKind, RefreshKind, System};
3
4/// Continuously sends system-wide CPU and memory usage metrics.
5///
6/// This function runs in a loop, refreshing system information at regular intervals
7/// and emitting `imetric!` and `fmetric!` events for total memory, used memory,
8/// free memory, and global CPU usage.
9pub fn send_system_metrics_forever() {
10    let what_to_refresh = RefreshKind::nothing()
11        .with_cpu(CpuRefreshKind::nothing().with_cpu_usage())
12        .with_memory(MemoryRefreshKind::nothing().with_ram());
13    let mut system = System::new_with_specifics(what_to_refresh);
14    imetric!("total_memory", "bytes", system.total_memory());
15    loop {
16        std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
17        system.refresh_specifics(what_to_refresh);
18        imetric!("used_memory", "bytes", system.used_memory());
19        imetric!("free_memory", "bytes", system.free_memory());
20        fmetric!("cpu_usage", "percent", system.global_cpu_usage() as f64);
21    }
22}
23
24/// Spawns a new thread to run the `send_system_metrics_forever` function.
25///
26/// This allows system metrics to be collected and reported in the background.
27pub fn spawn_system_monitor() {
28    std::thread::spawn(send_system_metrics_forever);
29}