Line data Source code
1 : //! We re-export those from prometheus crate to
2 : //! make sure that we use the same dep version everywhere.
3 : //! Otherwise, we might not see all metrics registered via
4 : //! a default registry.
5 : #![deny(clippy::undocumented_unsafe_blocks)]
6 :
7 : use once_cell::sync::Lazy;
8 : use prometheus::core::{
9 : Atomic, AtomicU64, Collector, GenericCounter, GenericCounterVec, GenericGauge, GenericGaugeVec,
10 : };
11 : pub use prometheus::opts;
12 : pub use prometheus::register;
13 : pub use prometheus::Error;
14 : pub use prometheus::{core, default_registry, proto};
15 : pub use prometheus::{exponential_buckets, linear_buckets};
16 : pub use prometheus::{register_counter_vec, Counter, CounterVec};
17 : pub use prometheus::{register_gauge, Gauge};
18 : pub use prometheus::{register_gauge_vec, GaugeVec};
19 : pub use prometheus::{register_histogram, Histogram};
20 : pub use prometheus::{register_histogram_vec, HistogramVec};
21 : pub use prometheus::{register_int_counter, IntCounter};
22 : pub use prometheus::{register_int_counter_vec, IntCounterVec};
23 : pub use prometheus::{register_int_gauge, IntGauge};
24 : pub use prometheus::{register_int_gauge_vec, IntGaugeVec};
25 : pub use prometheus::{Encoder, TextEncoder};
26 : use prometheus::{Registry, Result};
27 :
28 : pub mod launch_timestamp;
29 : mod wrappers;
30 : pub use wrappers::{CountedReader, CountedWriter};
31 : mod hll;
32 : pub mod metric_vec_duration;
33 : pub use hll::{HyperLogLog, HyperLogLogVec};
34 : #[cfg(target_os = "linux")]
35 : pub mod more_process_metrics;
36 :
37 : pub type UIntGauge = GenericGauge<AtomicU64>;
38 : pub type UIntGaugeVec = GenericGaugeVec<AtomicU64>;
39 :
40 : #[macro_export]
41 : macro_rules! register_uint_gauge_vec {
42 : ($NAME:expr, $HELP:expr, $LABELS_NAMES:expr $(,)?) => {{
43 : let gauge_vec = UIntGaugeVec::new($crate::opts!($NAME, $HELP), $LABELS_NAMES).unwrap();
44 : $crate::register(Box::new(gauge_vec.clone())).map(|_| gauge_vec)
45 : }};
46 : }
47 :
48 : #[macro_export]
49 : macro_rules! register_uint_gauge {
50 : ($NAME:expr, $HELP:expr $(,)?) => {{
51 : let gauge = $crate::UIntGauge::new($NAME, $HELP).unwrap();
52 : $crate::register(Box::new(gauge.clone())).map(|_| gauge)
53 : }};
54 : }
55 :
56 : /// Special internal registry, to collect metrics independently from the default registry.
57 : /// Was introduced to fix deadlock with lazy registration of metrics in the default registry.
58 : static INTERNAL_REGISTRY: Lazy<Registry> = Lazy::new(Registry::new);
59 :
60 : /// Register a collector in the internal registry. MUST be called before the first call to `gather()`.
61 : /// Otherwise, we can have a deadlock in the `gather()` call, trying to register a new collector
62 : /// while holding the lock.
63 1758 : pub fn register_internal(c: Box<dyn Collector>) -> Result<()> {
64 1758 : INTERNAL_REGISTRY.register(c)
65 1758 : }
66 :
67 : /// Gathers all Prometheus metrics and records the I/O stats just before that.
68 : ///
69 : /// Metrics gathering is a relatively simple and standalone operation, so
70 : /// it might be fine to do it this way to keep things simple.
71 1280 : pub fn gather() -> Vec<prometheus::proto::MetricFamily> {
72 1280 : update_rusage_metrics();
73 1280 : let mut mfs = prometheus::gather();
74 1280 : let mut internal_mfs = INTERNAL_REGISTRY.gather();
75 1280 : mfs.append(&mut internal_mfs);
76 1280 : mfs
77 1280 : }
78 :
79 422 : static DISK_IO_BYTES: Lazy<IntGaugeVec> = Lazy::new(|| {
80 422 : register_int_gauge_vec!(
81 422 : "libmetrics_disk_io_bytes_total",
82 422 : "Bytes written and read from disk, grouped by the operation (read|write)",
83 422 : &["io_operation"]
84 422 : )
85 422 : .expect("Failed to register disk i/o bytes int gauge vec")
86 422 : });
87 :
88 422 : static MAXRSS_KB: Lazy<IntGauge> = Lazy::new(|| {
89 422 : register_int_gauge!(
90 422 : "libmetrics_maxrss_kb",
91 422 : "Memory usage (Maximum Resident Set Size)"
92 422 : )
93 422 : .expect("Failed to register maxrss_kb int gauge")
94 422 : });
95 :
96 : pub const DISK_WRITE_SECONDS_BUCKETS: &[f64] = &[
97 : 0.000_050, 0.000_100, 0.000_500, 0.001, 0.003, 0.005, 0.01, 0.05, 0.1, 0.3, 0.5,
98 : ];
99 :
100 1161 : pub fn set_build_info_metric(revision: &str, build_tag: &str) {
101 1161 : let metric = register_int_gauge_vec!(
102 1161 : "libmetrics_build_info",
103 1161 : "Build/version information",
104 1161 : &["revision", "build_tag"]
105 1161 : )
106 1161 : .expect("Failed to register build info metric");
107 1161 : metric.with_label_values(&[revision, build_tag]).set(1);
108 1161 : }
109 :
110 : // Records I/O stats in a "cross-platform" way.
111 : // Compiles both on macOS and Linux, but current macOS implementation always returns 0 as values for I/O stats.
112 : // An alternative is to read procfs (`/proc/[pid]/io`) which does not work under macOS at all, hence abandoned.
113 : //
114 : // Uses https://www.freebsd.org/cgi/man.cgi?query=getrusage to retrieve the number of block operations
115 : // performed by the process.
116 : // We know the size of the block, so we can determine the I/O bytes out of it.
117 : // The value might be not 100% exact, but should be fine for Prometheus metrics in this case.
118 : #[allow(clippy::unnecessary_cast)]
119 1280 : fn update_rusage_metrics() {
120 1280 : let rusage_stats = get_rusage_stats();
121 1280 :
122 1280 : const BYTES_IN_BLOCK: i64 = 512;
123 1280 : DISK_IO_BYTES
124 1280 : .with_label_values(&["read"])
125 1280 : .set(rusage_stats.ru_inblock * BYTES_IN_BLOCK);
126 1280 : DISK_IO_BYTES
127 1280 : .with_label_values(&["write"])
128 1280 : .set(rusage_stats.ru_oublock * BYTES_IN_BLOCK);
129 1280 : MAXRSS_KB.set(rusage_stats.ru_maxrss);
130 1280 : }
131 :
132 1280 : fn get_rusage_stats() -> libc::rusage {
133 1280 : let mut rusage = std::mem::MaybeUninit::uninit();
134 1280 :
135 1280 : // SAFETY: kernel will initialize the struct for us
136 1280 : unsafe {
137 1280 : let ret = libc::getrusage(libc::RUSAGE_SELF, rusage.as_mut_ptr());
138 1280 : assert!(ret == 0, "getrusage failed: bad args");
139 1280 : rusage.assume_init()
140 1280 : }
141 1280 : }
142 :
143 : /// Create an [`IntCounterPairVec`] and registers to default registry.
144 : #[macro_export(local_inner_macros)]
145 : macro_rules! register_int_counter_pair_vec {
146 : ($NAME1:expr, $HELP1:expr, $NAME2:expr, $HELP2:expr, $LABELS_NAMES:expr $(,)?) => {{
147 : match (
148 : $crate::register_int_counter_vec!($NAME1, $HELP1, $LABELS_NAMES),
149 : $crate::register_int_counter_vec!($NAME2, $HELP2, $LABELS_NAMES),
150 : ) {
151 : (Ok(inc), Ok(dec)) => Ok($crate::IntCounterPairVec::new(inc, dec)),
152 : (Err(e), _) | (_, Err(e)) => Err(e),
153 : }
154 : }};
155 : }
156 : /// Create an [`IntCounterPair`] and registers to default registry.
157 : #[macro_export(local_inner_macros)]
158 : macro_rules! register_int_counter_pair {
159 : ($NAME1:expr, $HELP1:expr, $NAME2:expr, $HELP2:expr $(,)?) => {{
160 : match (
161 : $crate::register_int_counter!($NAME1, $HELP1),
162 : $crate::register_int_counter!($NAME2, $HELP2),
163 : ) {
164 : (Ok(inc), Ok(dec)) => Ok($crate::IntCounterPair::new(inc, dec)),
165 : (Err(e), _) | (_, Err(e)) => Err(e),
166 : }
167 : }};
168 : }
169 :
170 : /// A Pair of [`GenericCounterVec`]s. Like an [`GenericGaugeVec`] but will always observe changes
171 : pub struct GenericCounterPairVec<P: Atomic> {
172 : inc: GenericCounterVec<P>,
173 : dec: GenericCounterVec<P>,
174 : }
175 :
176 : /// A Pair of [`GenericCounter`]s. Like an [`GenericGauge`] but will always observe changes
177 : pub struct GenericCounterPair<P: Atomic> {
178 : inc: GenericCounter<P>,
179 : dec: GenericCounter<P>,
180 : }
181 :
182 : impl<P: Atomic> GenericCounterPairVec<P> {
183 1012 : pub fn new(inc: GenericCounterVec<P>, dec: GenericCounterVec<P>) -> Self {
184 1012 : Self { inc, dec }
185 1012 : }
186 :
187 : /// `get_metric_with_label_values` returns the [`GenericCounterPair<P>`] for the given slice
188 : /// of label values (same order as the VariableLabels in Desc). If that combination of
189 : /// label values is accessed for the first time, a new [`GenericCounterPair<P>`] is created.
190 : ///
191 : /// An error is returned if the number of label values is not the same as the
192 : /// number of VariableLabels in Desc.
193 6571 : pub fn get_metric_with_label_values(&self, vals: &[&str]) -> Result<GenericCounterPair<P>> {
194 6571 : Ok(GenericCounterPair {
195 6571 : inc: self.inc.get_metric_with_label_values(vals)?,
196 6571 : dec: self.dec.get_metric_with_label_values(vals)?,
197 : })
198 6571 : }
199 :
200 : /// `with_label_values` works as `get_metric_with_label_values`, but panics if an error
201 : /// occurs.
202 6571 : pub fn with_label_values(&self, vals: &[&str]) -> GenericCounterPair<P> {
203 6571 : self.get_metric_with_label_values(vals).unwrap()
204 6571 : }
205 : }
206 :
207 : impl<P: Atomic> GenericCounterPair<P> {
208 15 : pub fn new(inc: GenericCounter<P>, dec: GenericCounter<P>) -> Self {
209 15 : Self { inc, dec }
210 15 : }
211 :
212 : /// Increment the gauge by 1, returning a guard that decrements by 1 on drop.
213 6588 : pub fn guard(&self) -> GenericCounterPairGuard<P> {
214 6588 : self.inc.inc();
215 6588 : GenericCounterPairGuard(self.dec.clone())
216 6588 : }
217 :
218 : /// Increment the gauge by n, returning a guard that decrements by n on drop.
219 0 : pub fn guard_by(&self, n: P::T) -> GenericCounterPairGuardBy<P> {
220 0 : self.inc.inc_by(n);
221 0 : GenericCounterPairGuardBy(self.dec.clone(), n)
222 0 : }
223 :
224 : /// Increase the gauge by 1.
225 : #[inline]
226 0 : pub fn inc(&self) {
227 0 : self.inc.inc();
228 0 : }
229 :
230 : /// Decrease the gauge by 1.
231 : #[inline]
232 0 : pub fn dec(&self) {
233 0 : self.dec.inc();
234 0 : }
235 :
236 : /// Add the given value to the gauge. (The value can be
237 : /// negative, resulting in a decrement of the gauge.)
238 : #[inline]
239 0 : pub fn inc_by(&self, v: P::T) {
240 0 : self.inc.inc_by(v);
241 0 : }
242 :
243 : /// Subtract the given value from the gauge. (The value can be
244 : /// negative, resulting in an increment of the gauge.)
245 : #[inline]
246 0 : pub fn dec_by(&self, v: P::T) {
247 0 : self.dec.inc_by(v);
248 0 : }
249 : }
250 :
251 : /// Guard returned by [`GenericCounterPair::guard`]
252 : pub struct GenericCounterPairGuard<P: Atomic>(GenericCounter<P>);
253 :
254 : impl<P: Atomic> Drop for GenericCounterPairGuard<P> {
255 6152 : fn drop(&mut self) {
256 6152 : self.0.inc();
257 6152 : }
258 : }
259 : /// Guard returned by [`GenericCounterPair::guard_by`]
260 : pub struct GenericCounterPairGuardBy<P: Atomic>(GenericCounter<P>, P::T);
261 :
262 : impl<P: Atomic> Drop for GenericCounterPairGuardBy<P> {
263 0 : fn drop(&mut self) {
264 0 : self.0.inc_by(self.1);
265 0 : }
266 : }
267 :
268 : /// A Pair of [`IntCounterVec`]s. Like an [`IntGaugeVec`] but will always observe changes
269 : pub type IntCounterPairVec = GenericCounterPairVec<AtomicU64>;
270 :
271 : /// A Pair of [`IntCounter`]s. Like an [`IntGauge`] but will always observe changes
272 : pub type IntCounterPair = GenericCounterPair<AtomicU64>;
273 :
274 : /// A guard for [`IntCounterPair`] that will decrement the gauge on drop
275 : pub type IntCounterPairGuard = GenericCounterPairGuard<AtomicU64>;
|