use crate::metrics::report::PrometheusMetric;
use crate::metrics::schema::system_process::*;
use crate::node_identity::SERVER_LABEL;
use std::borrow::Cow;
use sysinfo::{Pid, ProcessStatus, System};
#[derive(Debug, Clone)]
pub struct ProcessAttributes {
pub pid: u32,
pub executable_name: String,
pub executable_path: String,
pub command: String,
}
impl ProcessAttributes {
pub fn current() -> Result<Self, ProcessAttributeError> {
let pid = sysinfo::get_current_pid().map_err(|e| ProcessAttributeError::PidError(e.to_string()))?;
Self::from_pid(pid)
}
pub fn from_pid(pid: Pid) -> Result<Self, ProcessAttributeError> {
let mut system = System::new();
system.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true);
let process = system
.process(pid)
.ok_or_else(|| ProcessAttributeError::ProcessNotFound(pid.as_u32()))?;
Ok(ProcessAttributes {
pid: pid.as_u32(),
executable_name: process.name().to_string_lossy().to_string(),
executable_path: process.exe().map(|p| p.to_string_lossy().to_string()).unwrap_or_default(),
command: process
.cmd()
.iter()
.map(|s| s.to_string_lossy().into_owned())
.collect::<Vec<_>>()
.join(" "),
})
}
pub fn to_labels(&self) -> Vec<(&'static str, Cow<'static, str>)> {
vec![
("process_pid", Cow::Owned(self.pid.to_string())),
("process_executable_name", Cow::Owned(self.executable_name.clone())),
("process_executable_path", Cow::Owned(self.executable_path.clone())),
("process_command", Cow::Owned(self.command.clone())),
]
}
}
#[derive(Debug, Clone)]
pub enum ProcessAttributeError {
PidError(String),
ProcessNotFound(u32),
}
impl std::fmt::Display for ProcessAttributeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::PidError(e) => write!(f, "Failed to get current PID: {}", e),
Self::ProcessNotFound(pid) => write!(f, "Process not found: {}", pid),
}
}
}
impl std::error::Error for ProcessAttributeError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ProcessStatusType {
Running = 0,
Sleeping = 1,
Zombie = 2,
#[default]
Other = 3,
}
impl From<ProcessStatus> for ProcessStatusType {
fn from(status: ProcessStatus) -> Self {
match status {
ProcessStatus::Run => ProcessStatusType::Running,
ProcessStatus::Sleep => ProcessStatusType::Sleeping,
ProcessStatus::Zombie => ProcessStatusType::Zombie,
_ => ProcessStatusType::Other,
}
}
}
#[derive(Debug, Clone, Default)]
pub struct ProcessStats {
pub server: String,
pub locks_read_total: u64,
pub locks_write_total: u64,
pub cpu_total_seconds: f64,
pub go_routine_total: u64,
pub io_rchar_bytes: u64,
pub io_read_bytes: u64,
pub io_wchar_bytes: u64,
pub io_write_bytes: u64,
pub start_time_seconds: u64,
pub uptime_seconds: u64,
pub file_descriptor_limit_total: u64,
pub file_descriptor_open_total: u64,
pub syscall_read_total: u64,
pub syscall_write_total: u64,
pub resident_memory_bytes: u64,
pub virtual_memory_bytes: u64,
pub virtual_memory_max_bytes: u64,
pub status: ProcessStatusType,
pub status_value: i64,
}
pub fn collect_process_metrics(stats: &ProcessStats) -> Vec<PrometheusMetric> {
let server_label = stats.server.as_str();
let mut metrics = vec![
PrometheusMetric::from_descriptor(&PROCESS_LOCKS_READ_TOTAL_MD, stats.locks_read_total as f64),
PrometheusMetric::from_descriptor(&PROCESS_LOCKS_WRITE_TOTAL_MD, stats.locks_write_total as f64),
PrometheusMetric::from_descriptor(&PROCESS_CPU_TOTAL_SECONDS_MD, stats.cpu_total_seconds),
PrometheusMetric::from_descriptor(&PROCESS_GO_ROUTINE_TOTAL_MD, stats.go_routine_total as f64),
PrometheusMetric::from_descriptor(&PROCESS_IO_RCHAR_BYTES_MD, stats.io_rchar_bytes as f64),
PrometheusMetric::from_descriptor(&PROCESS_IO_READ_BYTES_MD, stats.io_read_bytes as f64),
PrometheusMetric::from_descriptor(&PROCESS_IO_WCHAR_BYTES_MD, stats.io_wchar_bytes as f64),
PrometheusMetric::from_descriptor(&PROCESS_IO_WRITE_BYTES_MD, stats.io_write_bytes as f64),
PrometheusMetric::from_descriptor(&PROCESS_START_TIME_SECONDS_MD, stats.start_time_seconds as f64),
PrometheusMetric::from_descriptor(&PROCESS_UPTIME_SECONDS_MD, stats.uptime_seconds as f64),
PrometheusMetric::from_descriptor(&PROCESS_FILE_DESCRIPTOR_LIMIT_TOTAL_MD, stats.file_descriptor_limit_total as f64),
PrometheusMetric::from_descriptor(&PROCESS_FILE_DESCRIPTOR_OPEN_TOTAL_MD, stats.file_descriptor_open_total as f64),
PrometheusMetric::from_descriptor(&PROCESS_SYSCALL_READ_TOTAL_MD, stats.syscall_read_total as f64),
PrometheusMetric::from_descriptor(&PROCESS_SYSCALL_WRITE_TOTAL_MD, stats.syscall_write_total as f64),
PrometheusMetric::from_descriptor(&PROCESS_RESIDENT_MEMORY_BYTES_MD, stats.resident_memory_bytes as f64),
PrometheusMetric::from_descriptor(&PROCESS_VIRTUAL_MEMORY_BYTES_MD, stats.virtual_memory_bytes as f64),
PrometheusMetric::from_descriptor(&PROCESS_VIRTUAL_MEMORY_MAX_BYTES_MD, stats.virtual_memory_max_bytes as f64),
];
for metric in &mut metrics {
metric.labels.push((SERVER_LABEL, Cow::Owned(server_label.to_string())));
}
let mut status_metric = PrometheusMetric::from_descriptor(&PROCESS_STATUS_MD, stats.status_value as f64);
status_metric
.labels
.push((SERVER_LABEL, Cow::Owned(server_label.to_string())));
status_metric
.labels
.push((STATUS_LABEL, Cow::Owned(format!("{:?}", stats.status))));
metrics.push(status_metric);
metrics
}
pub fn collect_process_attributes() -> Result<ProcessAttributes, ProcessAttributeError> {
ProcessAttributes::current()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::metrics::report::report_metrics;
#[test]
fn test_collect_process_metrics() {
let stats = ProcessStats {
server: "node1:9000".to_string(),
locks_read_total: 100,
locks_write_total: 50,
cpu_total_seconds: 1234.56,
go_routine_total: 200,
io_rchar_bytes: 1024 * 1024 * 500,
io_read_bytes: 1024 * 1024 * 400,
io_wchar_bytes: 1024 * 1024 * 300,
io_write_bytes: 1024 * 1024 * 250,
start_time_seconds: 1700000000,
uptime_seconds: 86400,
file_descriptor_limit_total: 65536,
file_descriptor_open_total: 1500,
syscall_read_total: 100000,
syscall_write_total: 50000,
resident_memory_bytes: 1024 * 1024 * 512,
virtual_memory_bytes: 1024 * 1024 * 1024,
virtual_memory_max_bytes: 1024 * 1024 * 2048,
status: ProcessStatusType::Running,
status_value: 0,
};
let metrics = collect_process_metrics(&stats);
report_metrics(&metrics);
assert_eq!(metrics.len(), 18);
assert!(
metrics
.iter()
.all(|m| m.labels.iter().any(|(k, v)| *k == SERVER_LABEL && v == "node1:9000"))
);
let uptime_name = PROCESS_UPTIME_SECONDS_MD.get_full_metric_name();
let uptime = metrics.iter().find(|m| m.name == uptime_name);
assert!(uptime.is_some());
assert_eq!(uptime.map(|m| m.value), Some(86400.0));
let fd_open_name = PROCESS_FILE_DESCRIPTOR_OPEN_TOTAL_MD.get_full_metric_name();
let fd_open = metrics.iter().find(|m| m.name == fd_open_name);
assert!(fd_open.is_some());
assert_eq!(fd_open.map(|m| m.value), Some(1500.0));
let status_name = PROCESS_STATUS_MD.get_full_metric_name();
let status_metric = metrics.iter().find(|m| m.name == status_name);
assert!(status_metric.is_some());
assert_eq!(status_metric.map(|m| m.value), Some(0.0));
}
#[test]
fn test_collect_process_metrics_default() {
let stats = ProcessStats::default();
let metrics = collect_process_metrics(&stats);
assert_eq!(metrics.len(), 18);
assert!(metrics.iter().all(|m| m.labels.iter().any(|(k, _)| *k == SERVER_LABEL)));
}
#[test]
fn test_process_attributes_current() {
let result = collect_process_attributes();
assert!(result.is_ok());
let attrs = result.expect("current process attributes should be collectable");
assert!(attrs.pid > 0);
assert!(!attrs.executable_name.is_empty());
}
#[test]
fn test_process_status_conversion() {
assert_eq!(ProcessStatusType::from(ProcessStatus::Run), ProcessStatusType::Running);
assert_eq!(ProcessStatusType::from(ProcessStatus::Sleep), ProcessStatusType::Sleeping);
assert_eq!(ProcessStatusType::from(ProcessStatus::Zombie), ProcessStatusType::Zombie);
}
#[test]
fn test_process_attributes_to_labels() {
let attrs = ProcessAttributes {
pid: 12345,
executable_name: "rustfs".to_string(),
executable_path: "/usr/bin/rustfs".to_string(),
command: "rustfs server /data".to_string(),
};
let labels = attrs.to_labels();
assert_eq!(labels.len(), 4);
assert_eq!(labels[0].0, PROCESS_PID_LABEL);
assert_eq!(labels[0].1, "12345");
}
}