Skip to main content

rustfs_obs/metrics/collectors/
system_process.rs

1// Copyright 2024 RustFS Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! System process metrics collector.
16//!
17//! Collects process-level metrics including file descriptors, memory,
18//! syscalls, and runtime statistics.
19//!
20//! This module also provides process attribute collection for use as
21//! metric labels, migrated from `rustfs-obs::system`.
22
23use 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/// Process attributes used as metric labels.
30///
31/// Contains identifying information about the process being monitored.
32#[derive(Debug, Clone)]
33pub struct ProcessAttributes {
34    /// Process ID
35    pub pid: u32,
36    /// Executable name (e.g., "rustfs")
37    pub executable_name: String,
38    /// Full path to the executable
39    pub executable_path: String,
40    /// Full command line with arguments
41    pub command: String,
42}
43
44impl ProcessAttributes {
45    /// Creates a new instance by reading from the current process.
46    ///
47    /// # Errors
48    ///
49    /// Returns an error if the current process PID cannot be determined
50    /// or if process information cannot be retrieved.
51    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    /// Creates a new instance for a specific PID.
57    ///
58    /// # Arguments
59    ///
60    /// * `pid` - The process ID to query
61    ///
62    /// # Errors
63    ///
64    /// Returns an error if the process does not exist or information
65    /// cannot be retrieved.
66    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    /// Converts attributes to Prometheus metric labels.
88    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/// Errors that can occur when collecting process attributes.
99#[derive(Debug, Clone)]
100pub enum ProcessAttributeError {
101    /// Failed to get current process PID
102    PidError(String),
103    /// Process not found
104    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/// Process status enumeration.
119///
120/// Maps `sysinfo::ProcessStatus` to a simpler representation.
121#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
122pub enum ProcessStatusType {
123    /// Process is currently running
124    Running = 0,
125    /// Process is sleeping (waiting for I/O or event)
126    Sleeping = 1,
127    /// Process is a zombie (terminated but not reaped)
128    Zombie = 2,
129    /// Process is in some other state
130    #[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/// Process statistics for the RustFS server process.
146#[derive(Debug, Clone, Default)]
147pub struct ProcessStats {
148    /// Stable local node identity for labeling node-local process metrics
149    pub server: String,
150    /// Total read locks held
151    pub locks_read_total: u64,
152    /// Total write locks held
153    pub locks_write_total: u64,
154    /// Total CPU time in seconds
155    pub cpu_total_seconds: f64,
156    /// Total number of async tasks (goroutines equivalent)
157    pub go_routine_total: u64,
158    /// Total bytes read via read syscalls (rchar)
159    pub io_rchar_bytes: u64,
160    /// Total bytes actually read from storage
161    pub io_read_bytes: u64,
162    /// Total bytes written via write syscalls (wchar)
163    pub io_wchar_bytes: u64,
164    /// Total bytes actually written to storage
165    pub io_write_bytes: u64,
166    /// Process start time in seconds since Unix epoch
167    pub start_time_seconds: u64,
168    /// Process uptime in seconds
169    pub uptime_seconds: u64,
170    /// File descriptor limit
171    pub file_descriptor_limit_total: u64,
172    /// Open file descriptors count
173    pub file_descriptor_open_total: u64,
174    /// Total read syscalls
175    pub syscall_read_total: u64,
176    /// Total write syscalls
177    pub syscall_write_total: u64,
178    /// Resident memory size in bytes
179    pub resident_memory_bytes: u64,
180    /// Virtual memory size in bytes
181    pub virtual_memory_bytes: u64,
182    /// Maximum virtual memory size in bytes
183    pub virtual_memory_max_bytes: u64,
184    /// Process status
185    pub status: ProcessStatusType,
186    /// Process status value (numeric)
187    pub status_value: i64,
188}
189
190/// Collects process metrics from the given stats.
191///
192/// Returns a vector of Prometheus metrics for process statistics.
193pub 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    // Add process status metric
219    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
231/// Collects process attributes for the current process.
232///
233/// This is a convenience function that wraps `ProcessAttributes::current()`.
234pub 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        // 17 original metrics + 1 status metric = 18
272        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        // Verify uptime
280        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        // Verify file descriptors
286        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        // Verify status metric
292        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        // 17 original metrics + 1 status metric = 18
304        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        // This test should succeed as we're querying the current process
311        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}