Skip to main content

rustfs_obs/metrics/collectors/
system_memory.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 memory metrics collector.
16//!
17//! Collects memory-related metrics including total, used, free,
18//! buffers, cache, shared, and available memory.
19//!
20//! This module provides both system-level and process-level memory metrics,
21//! with process-level metrics migrated from `rustfs-obs::system`.
22
23use crate::metrics::report::PrometheusMetric;
24use crate::metrics::schema::system_memory::*;
25use crate::metrics::schema::system_process::{PROCESS_RESIDENT_MEMORY_BYTES_MD, PROCESS_VIRTUAL_MEMORY_BYTES_MD};
26use crate::node_identity::SERVER_LABEL;
27use std::borrow::Cow;
28
29/// System memory statistics.
30#[derive(Debug, Clone, Default)]
31pub struct MemoryStats {
32    /// Stable local node identity for labeling node-local memory metrics
33    pub server: String,
34    /// Total memory in bytes
35    pub total: u64,
36    /// Used memory in bytes
37    pub used: u64,
38    /// Used memory percentage (0-100)
39    pub used_perc: f64,
40    /// Free memory in bytes
41    pub free: u64,
42    /// Buffer memory in bytes
43    pub buffers: u64,
44    /// Cache memory in bytes
45    pub cache: u64,
46    /// Shared memory in bytes
47    pub shared: u64,
48    /// Available memory in bytes
49    pub available: u64,
50}
51
52/// Process memory statistics.
53///
54/// Contains memory usage metrics for a specific process.
55#[derive(Debug, Clone, Default)]
56pub struct ProcessMemoryStats {
57    /// Resident memory size in bytes
58    pub resident: u64,
59    /// Virtual memory size in bytes
60    pub virtual_mem: u64,
61}
62
63/// Collects memory metrics from the given stats.
64///
65/// Uses the metric descriptors from `metrics_type::system_memory` module.
66/// Returns a vector of Prometheus metrics for memory statistics.
67pub fn collect_memory_metrics(stats: &MemoryStats) -> Vec<PrometheusMetric> {
68    let server_label = stats.server.as_str();
69    vec![
70        PrometheusMetric::from_descriptor(&MEM_TOTAL_MD, stats.total as f64)
71            .with_label_owned(SERVER_LABEL, server_label.to_string()),
72        PrometheusMetric::from_descriptor(&MEM_USED_MD, stats.used as f64)
73            .with_label_owned(SERVER_LABEL, server_label.to_string()),
74        PrometheusMetric::from_descriptor(&MEM_USED_PERC_MD, stats.used_perc)
75            .with_label_owned(SERVER_LABEL, server_label.to_string()),
76        PrometheusMetric::from_descriptor(&MEM_FREE_MD, stats.free as f64)
77            .with_label_owned(SERVER_LABEL, server_label.to_string()),
78        PrometheusMetric::from_descriptor(&MEM_BUFFERS_MD, stats.buffers as f64)
79            .with_label_owned(SERVER_LABEL, server_label.to_string()),
80        PrometheusMetric::from_descriptor(&MEM_CACHE_MD, stats.cache as f64)
81            .with_label_owned(SERVER_LABEL, server_label.to_string()),
82        PrometheusMetric::from_descriptor(&MEM_SHARED_MD, stats.shared as f64)
83            .with_label_owned(SERVER_LABEL, server_label.to_string()),
84        PrometheusMetric::from_descriptor(&MEM_AVAILABLE_MD, stats.available as f64)
85            .with_label_owned(SERVER_LABEL, server_label.to_string()),
86    ]
87}
88
89/// Collects process memory metrics from the given stats.
90///
91/// Uses the metric descriptors from `metrics_type::system_process` module.
92/// Returns a vector of Prometheus metrics for process memory statistics.
93///
94/// # Arguments
95///
96/// * `stats` - Process memory statistics
97/// * `labels` - Optional additional labels (e.g., process attributes)
98pub fn collect_process_memory_metrics(
99    stats: &ProcessMemoryStats,
100    labels: Option<&[(&'static str, Cow<'static, str>)]>,
101) -> Vec<PrometheusMetric> {
102    let mut resident_metric = PrometheusMetric::from_descriptor(&PROCESS_RESIDENT_MEMORY_BYTES_MD, stats.resident as f64);
103    let mut virtual_metric = PrometheusMetric::from_descriptor(&PROCESS_VIRTUAL_MEMORY_BYTES_MD, stats.virtual_mem as f64);
104
105    if let Some(l) = labels {
106        resident_metric.labels.extend(l.iter().map(|(k, v)| (*k, v.clone())));
107        virtual_metric.labels.extend(l.iter().map(|(k, v)| (*k, v.clone())));
108    }
109
110    vec![resident_metric, virtual_metric]
111}
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116    use crate::metrics::report::report_metrics;
117    use crate::metrics::schema::system_process::{PROCESS_EXECUTABLE_NAME_LABEL, PROCESS_PID_LABEL};
118
119    #[test]
120    fn test_collect_memory_metrics() {
121        let stats = MemoryStats {
122            server: "node1:9000".to_string(),
123            total: 16 * 1024 * 1024 * 1024, // 16 GB
124            used: 8 * 1024 * 1024 * 1024,   // 8 GB
125            used_perc: 50.0,
126            free: 4 * 1024 * 1024 * 1024,      // 4 GB
127            buffers: 1024 * 1024 * 512,        // 512 MB
128            cache: 2 * 1024 * 1024 * 1024,     // 2 GB
129            shared: 1024 * 1024 * 256,         // 256 MB
130            available: 6 * 1024 * 1024 * 1024, // 6 GB
131        };
132
133        let metrics = collect_memory_metrics(&stats);
134        report_metrics(&metrics);
135
136        assert_eq!(metrics.len(), 8);
137        assert!(metrics.iter().all(|m| m.name.starts_with("rustfs_system_memory_")));
138        assert!(
139            metrics
140                .iter()
141                .all(|m| m.labels.iter().any(|(k, v)| *k == SERVER_LABEL && v == "node1:9000"))
142        );
143    }
144
145    #[test]
146    fn test_collect_memory_metrics_default() {
147        let stats = MemoryStats::default();
148        let metrics = collect_memory_metrics(&stats);
149
150        assert_eq!(metrics.len(), 8);
151        for metric in &metrics {
152            assert_eq!(metric.value, 0.0);
153            assert_eq!(metric.labels.len(), 1);
154            assert_eq!(metric.labels[0].0, SERVER_LABEL);
155            assert!(metric.labels[0].1.is_empty());
156        }
157    }
158
159    #[test]
160    fn test_collect_process_memory_metrics() {
161        let stats = ProcessMemoryStats {
162            resident: 512 * 1024 * 1024,         // 512 MB
163            virtual_mem: 2 * 1024 * 1024 * 1024, // 2 GB
164        };
165
166        let metrics = collect_process_memory_metrics(&stats, None);
167        report_metrics(&metrics);
168
169        assert_eq!(metrics.len(), 2);
170    }
171
172    #[test]
173    fn test_collect_process_memory_metrics_with_labels() {
174        let stats = ProcessMemoryStats {
175            resident: 256 * 1024 * 1024,
176            virtual_mem: 1024 * 1024 * 1024,
177        };
178
179        let labels = vec![
180            (SERVER_LABEL, Cow::Borrowed("node1:9000")),
181            (PROCESS_PID_LABEL, Cow::Borrowed("12345")),
182            (PROCESS_EXECUTABLE_NAME_LABEL, Cow::Borrowed("rustfs")),
183        ];
184
185        let metrics = collect_process_memory_metrics(&stats, Some(&labels));
186        assert_eq!(metrics.len(), 2);
187
188        for metric in &metrics {
189            assert_eq!(metric.labels.len(), 3);
190            assert!(metric.labels.iter().any(|(k, v)| *k == SERVER_LABEL && v == "node1:9000"));
191        }
192    }
193}