Skip to main content

rustfs_obs/metrics/
report.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
15use crate::metrics::schema::{MetricDescriptor, MetricType};
16use metrics::{counter, describe_counter, describe_gauge, describe_histogram, gauge};
17use std::borrow::Cow;
18use std::collections::{HashMap, HashSet};
19use std::sync::{Mutex, OnceLock};
20
21static NAME_CACHE: OnceLock<Mutex<HashMap<String, &'static str>>> = OnceLock::new();
22static HELP_CACHE: OnceLock<Mutex<HashMap<String, &'static str>>> = OnceLock::new();
23/// Metric names already handed to `describe_*!`. The metadata never changes, so
24/// each name is described once instead of on every collection cycle.
25static DESCRIBED: OnceLock<Mutex<HashSet<&'static str>>> = OnceLock::new();
26
27fn intern_string(cache: &OnceLock<Mutex<HashMap<String, &'static str>>>, value: &str) -> &'static str {
28    let cache = cache.get_or_init(Default::default);
29    let mut cache = cache.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
30
31    if let Some(existing) = cache.get(value) {
32        existing
33    } else {
34        let value = Box::leak(value.to_string().into_boxed_str());
35        cache.insert(value.to_string(), value);
36        value
37    }
38}
39
40/// Resolve a metric name/help `Cow` to a `&'static str`, skipping the intern
41/// lock+leak when it is already borrowed (the common case for statically-named
42/// metrics); only owned strings pay the intern cost.
43// The `&Cow` is intentional: we must inspect the borrowed-vs-owned variant to
44// return the existing `&'static str` without interning, so `&str` will not do.
45#[allow(clippy::ptr_arg)]
46fn static_str(cache: &OnceLock<Mutex<HashMap<String, &'static str>>>, value: &Cow<'static, str>) -> &'static str {
47    match value {
48        Cow::Borrowed(s) => s,
49        Cow::Owned(s) => intern_string(cache, s),
50    }
51}
52
53/// Hand a metric name to `describe_*!` only the first time it is seen. The
54/// metadata (help text) never changes, so describing on every collection cycle
55/// only re-locks the recorder's metadata map. The help is resolved lazily, so an
56/// already-described metric costs one `HashSet` probe and nothing else.
57// `&Cow` mirrors `static_str`, which needs the borrowed-vs-owned variant.
58#[allow(clippy::ptr_arg)]
59fn describe_metric_once(name: &'static str, metric_type: MetricType, help: &Cow<'static, str>) {
60    let described = DESCRIBED.get_or_init(Default::default);
61    let mut described = described.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
62    if described.insert(name) {
63        let help = static_str(&HELP_CACHE, help);
64        match metric_type {
65            MetricType::Counter => describe_counter!(name, help),
66            MetricType::Gauge => describe_gauge!(name, help),
67            MetricType::Histogram => describe_histogram!(name, help),
68        }
69    }
70}
71
72pub(crate) fn counter_value_from_f64(value: f64) -> Option<u64> {
73    if !value.is_finite() || value < 0.0 {
74        return None;
75    }
76
77    if value >= u64::MAX as f64 {
78        Some(u64::MAX)
79    } else {
80        Some(value as u64)
81    }
82}
83
84pub fn report_metrics(metrics: &[PrometheusMetric]) {
85    for metric in metrics {
86        let name = static_str(&NAME_CACHE, &metric.name);
87        describe_metric_once(name, metric.metric_type, &metric.help);
88
89        // `metric.labels` is already `[(&'static str, Cow<'static, str>)]`, so emit
90        // straight from it — no per-cycle `Vec<(String, String)>` clone.
91        match metric.metric_type {
92            MetricType::Counter => {
93                if let Some(value) = counter_value_from_f64(metric.value) {
94                    counter!(name, &metric.labels).absolute(value);
95                }
96            }
97            MetricType::Gauge => gauge!(name, &metric.labels).set(metric.value),
98            MetricType::Histogram => metrics::histogram!(name, &metric.labels).record(metric.value),
99        }
100    }
101}
102
103#[derive(Debug, Clone)]
104pub struct PrometheusMetric {
105    pub name: Cow<'static, str>,
106    pub metric_type: MetricType,
107    pub help: Cow<'static, str>,
108    pub labels: Vec<(&'static str, Cow<'static, str>)>,
109    pub value: f64,
110}
111
112impl PrometheusMetric {
113    #[inline]
114    pub const fn new(name: &'static str, metric_type: MetricType, help: &'static str, value: f64) -> Self {
115        Self {
116            name: Cow::Borrowed(name),
117            metric_type,
118            help: Cow::Borrowed(help),
119            labels: Vec::new(),
120            value,
121        }
122    }
123
124    #[inline]
125    pub fn new_owned(name: String, metric_type: MetricType, help: String, value: f64) -> Self {
126        Self {
127            name: Cow::Owned(name),
128            metric_type,
129            help: Cow::Owned(help),
130            labels: Vec::new(),
131            value,
132        }
133    }
134
135    #[inline]
136    pub fn from_descriptor(descriptor: &MetricDescriptor, value: f64) -> Self {
137        let help = intern_string(&HELP_CACHE, &descriptor.help);
138        Self {
139            name: Cow::Owned(descriptor.get_full_metric_name()),
140            metric_type: descriptor.metric_type,
141            help: Cow::Borrowed(help),
142            labels: Vec::new(),
143            value,
144        }
145    }
146
147    #[inline]
148    pub fn with_label(mut self, key: &'static str, value: impl Into<Cow<'static, str>>) -> Self {
149        self.labels.push((key, value.into()));
150        self
151    }
152
153    #[inline]
154    pub fn with_label_owned(mut self, key: &'static str, value: String) -> Self {
155        self.labels.push((key, Cow::Owned(value)));
156        self
157    }
158
159    #[inline]
160    pub fn with_labels(mut self, labels: Vec<(&'static str, Cow<'static, str>)>) -> Self {
161        self.labels = labels;
162        self
163    }
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169    use crate::metrics::schema::{MetricName, MetricNamespace, MetricSubsystem};
170
171    #[test]
172    fn from_descriptor_uses_prometheus_metric_names_for_all_types() {
173        let cases = [
174            (MetricType::Counter, "rustfs_api_requests_total"),
175            (MetricType::Gauge, "rustfs_system_memory_used_bytes"),
176            (MetricType::Histogram, "rustfs_custom_path_latency_seconds"),
177        ];
178
179        for (metric_type, expected_name) in cases {
180            let subsystem = match metric_type {
181                MetricType::Counter => MetricSubsystem::ApiRequests,
182                MetricType::Gauge => MetricSubsystem::SystemMemory,
183                MetricType::Histogram => MetricSubsystem::new("/custom/path"),
184            };
185            let name = match metric_type {
186                MetricType::Counter => MetricName::ApiRequestsTotal,
187                MetricType::Gauge => MetricName::Custom("used_bytes".to_string()),
188                MetricType::Histogram => MetricName::Custom("latency_seconds".to_string()),
189            };
190
191            let metric = PrometheusMetric::from_descriptor(
192                &MetricDescriptor::new(name, metric_type, "test help".to_string(), vec![], MetricNamespace::RustFS, subsystem),
193                1.0,
194            );
195
196            assert_eq!(metric.name, expected_name);
197            assert_eq!(metric.metric_type, metric_type);
198        }
199    }
200
201    #[test]
202    fn counter_value_from_f64_rejects_negative_and_nan_inputs() {
203        assert_eq!(counter_value_from_f64(-1.0), None);
204        assert_eq!(counter_value_from_f64(f64::NAN), None);
205        assert_eq!(counter_value_from_f64(f64::NEG_INFINITY), None);
206    }
207
208    #[test]
209    fn counter_value_from_f64_clamps_large_values() {
210        assert_eq!(counter_value_from_f64(42.0), Some(42));
211        assert_eq!(counter_value_from_f64(u64::MAX as f64 * 2.0), Some(u64::MAX));
212    }
213}