Skip to main content

micromegas_telemetry_sink/
system_monitor.rs

1use micromegas_tracing::{fmetric, imetric};
2use std::time::{Duration, Instant};
3use sysinfo::{CpuRefreshKind, MemoryRefreshKind, RefreshKind, System};
4
5/// The sampling frequency for the process/jemalloc memory gauges -- much
6/// coarser than the loop's own ~200ms `sysinfo` CPU-update floor (that floor
7/// is only needed for a valid CPU-usage delta). Matches the cadence
8/// object-cache-srv's saturation_monitor.rs already chose for the same
9/// telemetry-volume reason; these gauges don't need 200ms resolution to
10/// catch an hour-plus OOM climb.
11const SLOW_SAMPLE_INTERVAL: Duration = Duration::from_secs(5);
12
13/// True once at least `SLOW_SAMPLE_INTERVAL` has elapsed since the last slow
14/// sample. Extracted as a pure function (mirroring `saturation_monitor.rs`'s
15/// `sample_once` extraction) so the gating decision itself is directly
16/// testable with plain `Duration` values, rather than only reachable from
17/// inside the infinite loop below.
18pub fn should_sample_slow(elapsed_since_last_sample: Duration) -> bool {
19    elapsed_since_last_sample >= SLOW_SAMPLE_INTERVAL
20}
21
22/// Emits this process's own RSS/virtual memory size. Allocator-agnostic
23/// (reads from the OS via `sysinfo`), so this runs for every consumer of
24/// `spawn_system_monitor`, including non-jemalloc binaries.
25///
26/// Takes a caller-owned `System` so repeated calls reuse it instead of each
27/// constructing a fresh instance (which re-reads `/proc/stat` etc.).
28pub fn emit_process_memory_stats(system: &mut System) {
29    use sysinfo::{ProcessRefreshKind, ProcessesToUpdate};
30    let Ok(pid) = sysinfo::get_current_pid() else {
31        return;
32    };
33    system.refresh_processes_specifics(
34        ProcessesToUpdate::Some(&[pid]),
35        false,
36        ProcessRefreshKind::nothing().with_memory(),
37    );
38    if let Some(process) = system.process(pid) {
39        imetric!("process_resident_bytes", "bytes", process.memory());
40        imetric!("process_virtual_bytes", "bytes", process.virtual_memory());
41    }
42}
43
44/// Emits jemalloc's own runtime accounting (`stats.allocated`/`resident`/
45/// `mapped`/`retained`). Only meaningful when jemalloc is this process's
46/// global allocator, hence the feature + platform gate.
47#[cfg(all(feature = "jemalloc", not(target_os = "windows")))]
48pub fn emit_jemalloc_stats() {
49    use tikv_jemalloc_ctl::{epoch, stats};
50    // jemalloc caches these counters; advance the epoch to refresh them
51    // before reading, per tikv-jemalloc-ctl's documented usage.
52    if epoch::advance().is_err() {
53        return;
54    }
55    if let Ok(v) = stats::allocated::read() {
56        imetric!("jemalloc_allocated_bytes", "bytes", v as u64);
57    }
58    if let Ok(v) = stats::resident::read() {
59        imetric!("jemalloc_resident_bytes", "bytes", v as u64);
60    }
61    if let Ok(v) = stats::mapped::read() {
62        imetric!("jemalloc_mapped_bytes", "bytes", v as u64);
63    }
64    if let Ok(v) = stats::retained::read() {
65        imetric!("jemalloc_retained_bytes", "bytes", v as u64);
66    }
67}
68
69#[cfg(not(all(feature = "jemalloc", not(target_os = "windows"))))]
70pub fn emit_jemalloc_stats() {}
71
72/// Subset of cgroup v2 `cpu.stat` that is useful for spotting CPU throttling.
73#[derive(Debug, PartialEq)]
74pub struct CgroupCpuStat {
75    pub usage_usec: u64,
76    pub nr_throttled: Option<u64>,
77    pub throttled_usec: Option<u64>,
78}
79
80/// Parses the body of a cgroup v2 `cpu.stat` file. `usage_usec` is required;
81/// the throttling counters are absent when the cpu controller has no limit.
82pub fn parse_cpu_stat(body: &str) -> Option<CgroupCpuStat> {
83    let mut usage_usec = None;
84    let mut nr_throttled = None;
85    let mut throttled_usec = None;
86    for line in body.lines() {
87        let mut parts = line.split_whitespace();
88        let (Some(key), Some(value)) = (parts.next(), parts.next()) else {
89            continue;
90        };
91        let Ok(value) = value.parse::<u64>() else {
92            continue;
93        };
94        match key {
95            "usage_usec" => usage_usec = Some(value),
96            "nr_throttled" => nr_throttled = Some(value),
97            "throttled_usec" => throttled_usec = Some(value),
98            _ => {}
99        }
100    }
101    Some(CgroupCpuStat {
102        usage_usec: usage_usec?,
103        nr_throttled,
104        throttled_usec,
105    })
106}
107
108const ROOT_CPU_STAT_PATH: &str = "/sys/fs/cgroup/cpu.stat";
109
110/// Resolves this process's own cgroup `cpu.stat` from the contents of
111/// `/proc/self/cgroup`. Without a cgroup namespace the root file would report
112/// host-wide usage, so the `0::<path>` line is followed; the root file is the
113/// fallback when there is no v2 line.
114pub fn cgroup_cpu_stat_path(proc_self_cgroup: &str) -> String {
115    let Some(rel) = proc_self_cgroup
116        .lines()
117        .find_map(|l| l.strip_prefix("0::"))
118        .map(|p| p.trim().trim_matches('/'))
119    else {
120        return ROOT_CPU_STAT_PATH.to_string();
121    };
122    if rel.is_empty() {
123        ROOT_CPU_STAT_PATH.to_string()
124    } else {
125        format!("/sys/fs/cgroup/{rel}/cpu.stat")
126    }
127}
128
129/// Emits the cgroup's cumulative CPU counters. Emits nothing when the file is
130/// missing (non-Linux, cgroup v1, no cgroup).
131pub fn emit_cgroup_cpu_stats() {
132    let Ok(proc_cgroup) = std::fs::read_to_string("/proc/self/cgroup") else {
133        return;
134    };
135    let Ok(body) = std::fs::read_to_string(cgroup_cpu_stat_path(&proc_cgroup)) else {
136        return;
137    };
138    let Some(stat) = parse_cpu_stat(&body) else {
139        return;
140    };
141    if let Some(v) = stat.nr_throttled {
142        imetric!("cgroup_cpu_nr_throttled", "count", v);
143    }
144    // A "ticks" metric is read back in seconds, converted with the process's tick frequency.
145    let frequency = micromegas_tracing::time::frequency();
146    if frequency <= 0 {
147        return;
148    }
149    imetric!(
150        "cgroup_cpu_usage",
151        "ticks",
152        usec_to_ticks(stat.usage_usec, frequency)
153    );
154    if let Some(v) = stat.throttled_usec {
155        imetric!("cgroup_cpu_throttled", "ticks", usec_to_ticks(v, frequency));
156    }
157}
158
159/// Converts microseconds to ticks at `frequency` ticks per second. Widens to `u128` because a
160/// cumulative counter times a multi-GHz frequency overflows `u64` within days.
161pub fn usec_to_ticks(usec: u64, frequency: i64) -> u64 {
162    (u128::from(usec) * frequency as u128 / 1_000_000) as u64
163}
164
165/// Continuously sends system-wide CPU and memory usage metrics.
166///
167/// This function runs in a loop, refreshing system information at regular intervals
168/// and emitting `imetric!` and `fmetric!` events for total memory, used memory,
169/// free memory, and global CPU usage. Every `SLOW_SAMPLE_INTERVAL`, it also
170/// emits this process's RSS/virtual memory size and, when built with the
171/// `jemalloc` feature on a non-Windows target, jemalloc's own runtime stats.
172pub fn send_system_metrics_forever() {
173    let what_to_refresh = RefreshKind::nothing()
174        .with_cpu(CpuRefreshKind::nothing().with_cpu_usage())
175        .with_memory(MemoryRefreshKind::nothing().with_ram());
176    let mut system = System::new_with_specifics(what_to_refresh);
177    imetric!("total_memory", "bytes", system.total_memory());
178    let mut process_system = System::new();
179    let mut last_slow_sample = Instant::now();
180    loop {
181        std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
182        system.refresh_specifics(what_to_refresh);
183        imetric!("used_memory", "bytes", system.used_memory());
184        imetric!("free_memory", "bytes", system.free_memory());
185        fmetric!("cpu_usage", "percent", system.global_cpu_usage() as f64);
186
187        if should_sample_slow(last_slow_sample.elapsed()) {
188            emit_process_memory_stats(&mut process_system);
189            emit_jemalloc_stats();
190            emit_cgroup_cpu_stats();
191            last_slow_sample = Instant::now();
192        }
193    }
194}
195
196/// Spawns a new thread to run the `send_system_metrics_forever` function.
197///
198/// This allows system metrics to be collected and reported in the background.
199pub fn spawn_system_monitor() {
200    std::thread::spawn(send_system_metrics_forever);
201}