micromegas_telemetry_sink/
system_monitor.rs1use micromegas_tracing::{fmetric, imetric};
2use std::time::{Duration, Instant};
3use sysinfo::{CpuRefreshKind, MemoryRefreshKind, RefreshKind, System};
4
5const SLOW_SAMPLE_INTERVAL: Duration = Duration::from_secs(5);
12
13pub fn should_sample_slow(elapsed_since_last_sample: Duration) -> bool {
19 elapsed_since_last_sample >= SLOW_SAMPLE_INTERVAL
20}
21
22pub 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#[cfg(all(feature = "jemalloc", not(target_os = "windows")))]
48pub fn emit_jemalloc_stats() {
49 use tikv_jemalloc_ctl::{epoch, stats};
50 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#[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
80pub 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
110pub 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
129pub 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 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
159pub fn usec_to_ticks(usec: u64, frequency: i64) -> u64 {
162 (u128::from(usec) * frequency as u128 / 1_000_000) as u64
163}
164
165pub 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
196pub fn spawn_system_monitor() {
200 std::thread::spawn(send_system_metrics_forever);
201}