|
| 1 | +use procfs::process::Process; |
| 2 | +use prometheus_client::{ |
| 3 | + collector::Collector, |
| 4 | + encoding::{DescriptorEncoder, EncodeMetric}, |
| 5 | + metrics::counter::ConstCounter, |
| 6 | + registry::Unit, |
| 7 | +}; |
| 8 | + |
| 9 | +#[derive(Debug)] |
| 10 | +pub struct ProcessCollector { |
| 11 | + namespace: String, |
| 12 | +} |
| 13 | + |
| 14 | +impl Collector for ProcessCollector { |
| 15 | + fn encode(&self, mut encoder: DescriptorEncoder) -> Result<(), std::fmt::Error> { |
| 16 | + let tps = procfs::ticks_per_second(); |
| 17 | + // process_cpu_seconds_total Total user and system CPU time spent in seconds. |
| 18 | + // process_max_fds Maximum number of open file descriptors. |
| 19 | + // process_open_fds Number of open file descriptors. |
| 20 | + // process_virtual_memory_bytes Virtual memory size in bytes. |
| 21 | + // process_resident_memory_bytes Resident memory size in bytes. |
| 22 | + // process_virtual_memory_max_bytes Maximum amount of virtual memory available in bytes. |
| 23 | + // process_start_time_seconds Start time of the process since unix epoch in seconds. |
| 24 | + // process_network_receive_bytes_total Number of bytes received by the process over the network. |
| 25 | + // process_network_transmit_bytes_total Number of bytes sent by the process over the network. |
| 26 | + |
| 27 | + if let Ok(proc) = Process::myself() { |
| 28 | + if let Ok(stat) = proc.stat() { |
| 29 | + let cpu_time = (stat.stime + stat.utime) / tps as u64; |
| 30 | + let counter = ConstCounter::new(cpu_time); |
| 31 | + let metric_encoder = encoder.encode_descriptor( |
| 32 | + "process_cpu_seconds_total", |
| 33 | + "Total user and system CPU time spent in seconds.", |
| 34 | + Some(&Unit::Seconds), |
| 35 | + counter.metric_type(), |
| 36 | + )?; |
| 37 | + counter.encode(metric_encoder)?; |
| 38 | + } |
| 39 | + |
| 40 | + if let Ok(limits) = proc.limits() { |
| 41 | + let max_fds = match limits.max_open_files.soft_limit { |
| 42 | + procfs::process::LimitValue::Value(v) => v, |
| 43 | + procfs::process::LimitValue::Unlimited => 0, |
| 44 | + }; |
| 45 | + let counter = ConstCounter::new(max_fds); |
| 46 | + let metric_encoder = encoder.encode_descriptor( |
| 47 | + "process_max_fds", |
| 48 | + "Maximum number of open file descriptors.", |
| 49 | + None, |
| 50 | + counter.metric_type(), |
| 51 | + )?; |
| 52 | + counter.encode(metric_encoder)?; |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + Ok(()) |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +#[cfg(test)] |
| 61 | +mod tests { |
| 62 | + use super::*; |
| 63 | + use prometheus_client::registry::Registry; |
| 64 | + |
| 65 | + #[test] |
| 66 | + fn register_process_collector() { |
| 67 | + let mut registry = Registry::default(); |
| 68 | + registry.register_collector(Box::new(ProcessCollector { |
| 69 | + namespace: String::new(), |
| 70 | + })) |
| 71 | + } |
| 72 | +} |
0 commit comments