rustfs_obs/metrics/collectors/
system_process.rs1use crate::metrics::report::PrometheusMetric;
24use crate::metrics::schema::system_process::*;
25use crate::node_identity::SERVER_LABEL;
26use std::borrow::Cow;
27use sysinfo::{Pid, ProcessStatus, System};
28
29#[derive(Debug, Clone)]
33pub struct ProcessAttributes {
34 pub pid: u32,
36 pub executable_name: String,
38 pub executable_path: String,
40 pub command: String,
42}
43
44impl ProcessAttributes {
45 pub fn current() -> Result<Self, ProcessAttributeError> {
52 let pid = sysinfo::get_current_pid().map_err(|e| ProcessAttributeError::PidError(e.to_string()))?;
53 Self::from_pid(pid)
54 }
55
56 pub fn from_pid(pid: Pid) -> Result<Self, ProcessAttributeError> {
67 let mut system = System::new();
68 system.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true);
69
70 let process = system
71 .process(pid)
72 .ok_or_else(|| ProcessAttributeError::ProcessNotFound(pid.as_u32()))?;
73
74 Ok(ProcessAttributes {
75 pid: pid.as_u32(),
76 executable_name: process.name().to_string_lossy().to_string(),
77 executable_path: process.exe().map(|p| p.to_string_lossy().to_string()).unwrap_or_default(),
78 command: process
79 .cmd()
80 .iter()
81 .map(|s| s.to_string_lossy().into_owned())
82 .collect::<Vec<_>>()
83 .join(" "),
84 })
85 }
86
87 pub fn to_labels(&self) -> Vec<(&'static str, Cow<'static, str>)> {
89 vec![
90 ("process_pid", Cow::Owned(self.pid.to_string())),
91 ("process_executable_name", Cow::Owned(self.executable_name.clone())),
92 ("process_executable_path", Cow::Owned(self.executable_path.clone())),
93 ("process_command", Cow::Owned(self.command.clone())),
94 ]
95 }
96}
97
98#[derive(Debug, Clone)]
100pub enum ProcessAttributeError {
101 PidError(String),
103 ProcessNotFound(u32),
105}
106
107impl std::fmt::Display for ProcessAttributeError {
108 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109 match self {
110 Self::PidError(e) => write!(f, "Failed to get current PID: {}", e),
111 Self::ProcessNotFound(pid) => write!(f, "Process not found: {}", pid),
112 }
113 }
114}
115
116impl std::error::Error for ProcessAttributeError {}
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
122pub enum ProcessStatusType {
123 Running = 0,
125 Sleeping = 1,
127 Zombie = 2,
129 #[default]
131 Other = 3,
132}
133
134impl From<ProcessStatus> for ProcessStatusType {
135 fn from(status: ProcessStatus) -> Self {
136 match status {
137 ProcessStatus::Run => ProcessStatusType::Running,
138 ProcessStatus::Sleep => ProcessStatusType::Sleeping,
139 ProcessStatus::Zombie => ProcessStatusType::Zombie,
140 _ => ProcessStatusType::Other,
141 }
142 }
143}
144
145#[derive(Debug, Clone, Default)]
147pub struct ProcessStats {
148 pub server: String,
150 pub locks_read_total: u64,
152 pub locks_write_total: u64,
154 pub cpu_total_seconds: f64,
156 pub go_routine_total: u64,
158 pub io_rchar_bytes: u64,
160 pub io_read_bytes: u64,
162 pub io_wchar_bytes: u64,
164 pub io_write_bytes: u64,
166 pub start_time_seconds: u64,
168 pub uptime_seconds: u64,
170 pub file_descriptor_limit_total: u64,
172 pub file_descriptor_open_total: u64,
174 pub syscall_read_total: u64,
176 pub syscall_write_total: u64,
178 pub resident_memory_bytes: u64,
180 pub virtual_memory_bytes: u64,
182 pub virtual_memory_max_bytes: u64,
184 pub status: ProcessStatusType,
186 pub status_value: i64,
188}
189
190pub fn collect_process_metrics(stats: &ProcessStats) -> Vec<PrometheusMetric> {
194 let server_label = stats.server.as_str();
195 let mut metrics = vec![
196 PrometheusMetric::from_descriptor(&PROCESS_LOCKS_READ_TOTAL_MD, stats.locks_read_total as f64),
197 PrometheusMetric::from_descriptor(&PROCESS_LOCKS_WRITE_TOTAL_MD, stats.locks_write_total as f64),
198 PrometheusMetric::from_descriptor(&PROCESS_CPU_TOTAL_SECONDS_MD, stats.cpu_total_seconds),
199 PrometheusMetric::from_descriptor(&PROCESS_GO_ROUTINE_TOTAL_MD, stats.go_routine_total as f64),
200 PrometheusMetric::from_descriptor(&PROCESS_IO_RCHAR_BYTES_MD, stats.io_rchar_bytes as f64),
201 PrometheusMetric::from_descriptor(&PROCESS_IO_READ_BYTES_MD, stats.io_read_bytes as f64),
202 PrometheusMetric::from_descriptor(&PROCESS_IO_WCHAR_BYTES_MD, stats.io_wchar_bytes as f64),
203 PrometheusMetric::from_descriptor(&PROCESS_IO_WRITE_BYTES_MD, stats.io_write_bytes as f64),
204 PrometheusMetric::from_descriptor(&PROCESS_START_TIME_SECONDS_MD, stats.start_time_seconds as f64),
205 PrometheusMetric::from_descriptor(&PROCESS_UPTIME_SECONDS_MD, stats.uptime_seconds as f64),
206 PrometheusMetric::from_descriptor(&PROCESS_FILE_DESCRIPTOR_LIMIT_TOTAL_MD, stats.file_descriptor_limit_total as f64),
207 PrometheusMetric::from_descriptor(&PROCESS_FILE_DESCRIPTOR_OPEN_TOTAL_MD, stats.file_descriptor_open_total as f64),
208 PrometheusMetric::from_descriptor(&PROCESS_SYSCALL_READ_TOTAL_MD, stats.syscall_read_total as f64),
209 PrometheusMetric::from_descriptor(&PROCESS_SYSCALL_WRITE_TOTAL_MD, stats.syscall_write_total as f64),
210 PrometheusMetric::from_descriptor(&PROCESS_RESIDENT_MEMORY_BYTES_MD, stats.resident_memory_bytes as f64),
211 PrometheusMetric::from_descriptor(&PROCESS_VIRTUAL_MEMORY_BYTES_MD, stats.virtual_memory_bytes as f64),
212 PrometheusMetric::from_descriptor(&PROCESS_VIRTUAL_MEMORY_MAX_BYTES_MD, stats.virtual_memory_max_bytes as f64),
213 ];
214 for metric in &mut metrics {
215 metric.labels.push((SERVER_LABEL, Cow::Owned(server_label.to_string())));
216 }
217
218 let mut status_metric = PrometheusMetric::from_descriptor(&PROCESS_STATUS_MD, stats.status_value as f64);
220 status_metric
221 .labels
222 .push((SERVER_LABEL, Cow::Owned(server_label.to_string())));
223 status_metric
224 .labels
225 .push((STATUS_LABEL, Cow::Owned(format!("{:?}", stats.status))));
226 metrics.push(status_metric);
227
228 metrics
229}
230
231pub fn collect_process_attributes() -> Result<ProcessAttributes, ProcessAttributeError> {
235 ProcessAttributes::current()
236}
237
238#[cfg(test)]
239mod tests {
240 use super::*;
241 use crate::metrics::report::report_metrics;
242
243 #[test]
244 fn test_collect_process_metrics() {
245 let stats = ProcessStats {
246 server: "node1:9000".to_string(),
247 locks_read_total: 100,
248 locks_write_total: 50,
249 cpu_total_seconds: 1234.56,
250 go_routine_total: 200,
251 io_rchar_bytes: 1024 * 1024 * 500,
252 io_read_bytes: 1024 * 1024 * 400,
253 io_wchar_bytes: 1024 * 1024 * 300,
254 io_write_bytes: 1024 * 1024 * 250,
255 start_time_seconds: 1700000000,
256 uptime_seconds: 86400,
257 file_descriptor_limit_total: 65536,
258 file_descriptor_open_total: 1500,
259 syscall_read_total: 100000,
260 syscall_write_total: 50000,
261 resident_memory_bytes: 1024 * 1024 * 512,
262 virtual_memory_bytes: 1024 * 1024 * 1024,
263 virtual_memory_max_bytes: 1024 * 1024 * 2048,
264 status: ProcessStatusType::Running,
265 status_value: 0,
266 };
267
268 let metrics = collect_process_metrics(&stats);
269 report_metrics(&metrics);
270
271 assert_eq!(metrics.len(), 18);
273 assert!(
274 metrics
275 .iter()
276 .all(|m| m.labels.iter().any(|(k, v)| *k == SERVER_LABEL && v == "node1:9000"))
277 );
278
279 let uptime_name = PROCESS_UPTIME_SECONDS_MD.get_full_metric_name();
281 let uptime = metrics.iter().find(|m| m.name == uptime_name);
282 assert!(uptime.is_some());
283 assert_eq!(uptime.map(|m| m.value), Some(86400.0));
284
285 let fd_open_name = PROCESS_FILE_DESCRIPTOR_OPEN_TOTAL_MD.get_full_metric_name();
287 let fd_open = metrics.iter().find(|m| m.name == fd_open_name);
288 assert!(fd_open.is_some());
289 assert_eq!(fd_open.map(|m| m.value), Some(1500.0));
290
291 let status_name = PROCESS_STATUS_MD.get_full_metric_name();
293 let status_metric = metrics.iter().find(|m| m.name == status_name);
294 assert!(status_metric.is_some());
295 assert_eq!(status_metric.map(|m| m.value), Some(0.0));
296 }
297
298 #[test]
299 fn test_collect_process_metrics_default() {
300 let stats = ProcessStats::default();
301 let metrics = collect_process_metrics(&stats);
302
303 assert_eq!(metrics.len(), 18);
305 assert!(metrics.iter().all(|m| m.labels.iter().any(|(k, _)| *k == SERVER_LABEL)));
306 }
307
308 #[test]
309 fn test_process_attributes_current() {
310 let result = collect_process_attributes();
312 assert!(result.is_ok());
313
314 let attrs = result.expect("current process attributes should be collectable");
315 assert!(attrs.pid > 0);
316 assert!(!attrs.executable_name.is_empty());
317 }
318
319 #[test]
320 fn test_process_status_conversion() {
321 assert_eq!(ProcessStatusType::from(ProcessStatus::Run), ProcessStatusType::Running);
322 assert_eq!(ProcessStatusType::from(ProcessStatus::Sleep), ProcessStatusType::Sleeping);
323 assert_eq!(ProcessStatusType::from(ProcessStatus::Zombie), ProcessStatusType::Zombie);
324 }
325
326 #[test]
327 fn test_process_attributes_to_labels() {
328 let attrs = ProcessAttributes {
329 pid: 12345,
330 executable_name: "rustfs".to_string(),
331 executable_path: "/usr/bin/rustfs".to_string(),
332 command: "rustfs server /data".to_string(),
333 };
334
335 let labels = attrs.to_labels();
336 assert_eq!(labels.len(), 4);
337 assert_eq!(labels[0].0, PROCESS_PID_LABEL);
338 assert_eq!(labels[0].1, "12345");
339 }
340}