Skip to main content

iota_metrics/
lib.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use std::{
6    future::Future,
7    net::SocketAddr,
8    path::Path,
9    pin::Pin,
10    sync::Arc,
11    task::{Context, Poll},
12    time::Instant,
13};
14
15use axum::{
16    Router,
17    extract::{Extension, Request},
18    http::StatusCode,
19    middleware::Next,
20    response::Response,
21    routing::get,
22};
23use dashmap::DashMap;
24use once_cell::sync::OnceCell;
25use parking_lot::Mutex;
26use prometheus_filtered::{
27    Filter, Histogram, IntCounterVec, IntGaugeVec, Registry, TextEncoder,
28    core::{AtomicI64, GenericGauge},
29    register_histogram_with_registry, register_int_counter_vec_with_registry,
30    register_int_gauge_vec_with_registry,
31};
32pub use scopeguard;
33use simple_server_timing_header::Timer;
34use tap::TapFallible;
35use tracing::{Span, warn};
36use uuid::Uuid;
37
38mod guards;
39pub mod hardware_metrics;
40pub mod histogram;
41pub mod metered_channel;
42pub mod metric_groups;
43pub mod metrics_network;
44pub mod monitored_mpsc;
45pub mod peak;
46pub mod quantile_gauge;
47// Relies on tokio's `RuntimeMetrics`, which the deterministic simulator's tokio
48// fork does not provide; the node only starts these monitors outside simtests.
49#[cfg(not(msim))]
50pub mod runtime_metrics;
51#[cfg(any(test, feature = "test-utils"))]
52pub mod test_utils;
53pub mod thread_stall_monitor;
54pub use guards::*;
55pub use metric_groups::{MetricGroups, MetricLevel};
56
57pub const TX_TYPE_SINGLE_WRITER_TX: &str = "single_writer";
58pub const TX_TYPE_SHARED_OBJ_TX: &str = "shared_object";
59
60pub const SUBSECOND_LATENCY_SEC_BUCKETS: &[f64] = &[
61    0.005, 0.01, 0.02, 0.03, 0.05, 0.075, 0.1, 0.2, 0.3, 0.5, 0.7, 1.,
62];
63
64pub const COARSE_LATENCY_SEC_BUCKETS: &[f64] = &[
65    0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.2, 0.3, 0.5, 0.7, 1., 2., 3., 5., 10., 20., 30., 60.,
66];
67
68pub const LATENCY_SEC_BUCKETS: &[f64] = &[
69    0.001, 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.6,
70    0.7, 0.8, 0.9, 1., 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2., 2.5, 3., 3.5, 4., 4.5, 5.,
71    6., 7., 8., 9., 10., 15., 20., 25., 30., 60., 90.,
72];
73
74pub const COUNT_BUCKETS: &[f64] = &[
75    2., 5., 10., 20., 50., 100., 200., 500., 1000., 2000., 5000., 10000.,
76];
77
78pub const BYTES_BUCKETS: &[f64] = &[
79    1024., 4096., 16384., 65536., 262144., 524288., 1048576., 2097152., 4194304., 8388608.,
80    16777216., 33554432., 67108864.,
81];
82
83#[derive(Debug)]
84pub struct Metrics {
85    pub tasks: IntGaugeVec,
86    pub futures: IntGaugeVec,
87    pub channel_inflight: IntGaugeVec,
88    pub channel_sent: IntGaugeVec,
89    pub channel_received: IntGaugeVec,
90    pub future_active_duration_ns: IntGaugeVec,
91    pub scope_iterations: IntGaugeVec,
92    pub scope_duration_ns: IntGaugeVec,
93    pub scope_entrance: IntGaugeVec,
94    pub thread_stall_duration_sec: Histogram,
95    pub system_invariant_violations: IntCounterVec,
96}
97
98impl Metrics {
99    /// Creates a new instance of the monitoring metrics, registering various
100    /// gauges and histograms with the provided metrics `Registry`. The
101    /// gauges track metrics such as the number of running tasks, pending
102    /// futures, channel items, and scope activities, while the histogram
103    /// measures the duration of thread stalls. Each metric is registered
104    /// with descriptive labels to facilitate performance monitoring and
105    /// analysis.
106    fn new(registry: &Registry) -> Self {
107        Self {
108            tasks: register_int_gauge_vec_with_registry!(
109                "monitored_tasks",
110                "Number of running tasks per callsite.",
111                &["callsite"],
112                registry;
113                MetricLevel::Warn,
114            )
115            .unwrap(),
116            futures: register_int_gauge_vec_with_registry!(
117                "monitored_futures",
118                "Number of pending futures per callsite.",
119                &["callsite"],
120                registry;
121                MetricLevel::Warn,
122            )
123            .unwrap(),
124            channel_inflight: register_int_gauge_vec_with_registry!(
125                "monitored_channel_inflight",
126                "Inflight items in channels.",
127                &["name"],
128                registry;
129                MetricLevel::Warn,
130            )
131            .unwrap(),
132            channel_sent: register_int_gauge_vec_with_registry!(
133                "monitored_channel_sent",
134                "Sent items in channels.",
135                &["name"],
136                registry,
137            )
138            .unwrap(),
139            channel_received: register_int_gauge_vec_with_registry!(
140                "monitored_channel_received",
141                "Received items in channels.",
142                &["name"],
143                registry,
144            )
145            .unwrap(),
146            future_active_duration_ns: register_int_gauge_vec_with_registry!(
147                "monitored_future_active_duration_ns",
148                "Total duration in nanosecs where the monitored future is active (consuming CPU time)",
149                &["name"],
150                registry,
151            )
152            .unwrap(),
153            scope_entrance: register_int_gauge_vec_with_registry!(
154                "monitored_scope_entrance",
155                "Number of entrance in the scope.",
156                &["name"],
157                registry,
158            )
159            .unwrap(),
160            scope_iterations: register_int_gauge_vec_with_registry!(
161                "monitored_scope_iterations",
162                "Total number of times where the monitored scope runs",
163                &["name"],
164                registry,
165            )
166            .unwrap(),
167            scope_duration_ns: register_int_gauge_vec_with_registry!(
168                "monitored_scope_duration_ns",
169                "Total duration in nanosecs where the monitored scope is running",
170                &["name"],
171                registry,
172            )
173            .unwrap(),
174            thread_stall_duration_sec: register_histogram_with_registry!(
175                "thread_stall_duration_sec",
176                "Duration of thread stalls in seconds.",
177                registry,
178            )
179            .unwrap(),
180            system_invariant_violations: register_int_counter_vec_with_registry!(
181                "system_invariant_violations",
182                "Number of system invariant violations",
183                &["name"],
184                registry,
185            ).unwrap(),
186        }
187    }
188}
189
190static METRICS: OnceCell<Metrics> = OnceCell::new();
191
192/// Initializes the global `METRICS` instance by setting it to a new `Metrics`
193/// object registered with the provided `Registry`. If `METRICS` is already set,
194/// a warning is logged indicating that the metrics registry was overwritten.
195/// This function is intended to be called once during initialization to set up
196/// metrics collection.
197pub fn init_metrics(registry: &Registry) {
198    let _ = METRICS
199        .set(Metrics::new(registry))
200        // this happens many times during tests
201        .tap_err(|_| warn!("init_metrics registry overwritten"));
202}
203
204/// Retrieves the global `METRICS` instance if it has been initialized.
205pub fn get_metrics() -> Option<&'static Metrics> {
206    METRICS.get()
207}
208
209tokio::task_local! {
210    static SERVER_TIMING: Arc<Mutex<Timer>>;
211}
212
213/// Create a new task-local ServerTiming context and run the provided future
214/// within it. Should be used at the top-most level of a request handler. Can be
215/// added to an axum router as a layer by using
216/// iota_service::server_timing_middleware.
217pub async fn with_new_server_timing<T>(fut: impl Future<Output = T> + Send + 'static) -> T {
218    let timer = Arc::new(Mutex::new(Timer::new()));
219
220    let mut ret = None;
221    SERVER_TIMING
222        .scope(timer, async {
223            ret = Some(fut.await);
224        })
225        .await;
226
227    ret.unwrap()
228}
229
230/// The `Server-Timing` HTTP header key.
231pub fn server_timing_header_key() -> &'static str {
232    Timer::header_key()
233}
234
235/// Add a final `finish_request` entry and write the collected timings to the
236/// `Server-Timing` response header. No-op outside a server-timing context.
237pub fn finish_and_set_server_timing_header(headers: &mut http::HeaderMap) {
238    let Some(timer) = get_server_timing() else {
239        return;
240    };
241    let header_value = {
242        let mut timer = timer.lock();
243        timer.add("finish_request");
244        timer.header_value()
245    };
246    if let Ok(value) = http::HeaderValue::try_from(header_value) {
247        headers.insert(server_timing_header_key(), value);
248    }
249}
250
251pub async fn server_timing_middleware(request: Request, next: Next) -> Response {
252    with_new_server_timing(async move {
253        let mut response = next.run(request).await;
254        finish_and_set_server_timing_header(response.headers_mut());
255        response
256    })
257    .await
258}
259
260/// Create a new task-local ServerTiming context and run the provided future
261/// within it. Only intended for use by macros within this module.
262pub async fn with_server_timing<T>(
263    timer: Arc<Mutex<Timer>>,
264    fut: impl Future<Output = T> + Send + 'static,
265) -> T {
266    let mut ret = None;
267    SERVER_TIMING
268        .scope(timer, async {
269            ret = Some(fut.await);
270        })
271        .await;
272
273    ret.unwrap()
274}
275
276/// Get the currently active ServerTiming context. Only intended for use by
277/// macros within this module.
278pub fn get_server_timing() -> Option<Arc<Mutex<Timer>>> {
279    SERVER_TIMING.try_with(|timer| timer.clone()).ok()
280}
281
282/// Runs `f` within the ServerTiming context `timer`, if there is one.
283#[doc(hidden)]
284pub fn run_with_server_timing<T>(timer: Option<Arc<Mutex<Timer>>>, f: impl FnOnce() -> T) -> T {
285    match timer {
286        Some(timer) => SERVER_TIMING.sync_scope(timer, f),
287        None => f(),
288    }
289}
290
291/// Add a new entry to the ServerTiming header.
292/// If the caller is not currently in a ServerTiming context (created with
293/// `with_new_server_timing`), an error is logged.
294pub fn add_server_timing(name: &str) {
295    let res = SERVER_TIMING.try_with(|timer| {
296        timer.lock().add(name);
297    });
298
299    if res.is_err() {
300        tracing::error!("Server timing context not found");
301    }
302}
303
304#[macro_export]
305macro_rules! monitored_future {
306    ($fut: expr) => {{ monitored_future!(futures, $fut, "", INFO, false) }};
307
308    ($metric: ident, $fut: expr, $name: expr, $logging_level: ident, $logging_enabled: expr) => {{
309        let location: &str = if $name.is_empty() {
310            concat!(file!(), ':', line!())
311        } else {
312            concat!(file!(), ':', $name)
313        };
314
315        async move {
316            let metrics = $crate::get_metrics();
317
318            let _metrics_guard = if let Some(m) = metrics {
319                m.$metric.with_label_values(&[location]).inc();
320                Some($crate::scopeguard::guard(m, |_| {
321                    m.$metric.with_label_values(&[location]).dec();
322                }))
323            } else {
324                None
325            };
326            let _logging_guard = if $logging_enabled {
327                Some($crate::scopeguard::guard((), |_| {
328                    tracing::event!(
329                        tracing::Level::$logging_level,
330                        "Future {} completed",
331                        location
332                    );
333                }))
334            } else {
335                None
336            };
337
338            if $logging_enabled {
339                tracing::event!(
340                    tracing::Level::$logging_level,
341                    "Spawning future {}",
342                    location
343                );
344            }
345
346            $fut.await
347        }
348    }};
349}
350
351#[macro_export]
352macro_rules! forward_server_timing_and_spawn {
353    ($fut: expr) => {
354        if let Some(timing) = $crate::get_server_timing() {
355            tokio::task::spawn(async move { $crate::with_server_timing(timing, $fut).await })
356        } else {
357            tokio::task::spawn($fut)
358        }
359    };
360}
361
362#[macro_export]
363macro_rules! spawn_monitored_task {
364    ($fut: expr) => {
365        $crate::forward_server_timing_and_spawn!($crate::monitored_future!(
366            tasks, $fut, "", INFO, false
367        ))
368    };
369}
370
371/// Runs a blocking closure on tokio's blocking thread pool, like
372/// `tokio::task::spawn_blocking`, counting it in the `tasks` metric and
373/// keeping the caller's ServerTiming context, like [`spawn_monitored_task`].
374#[macro_export]
375macro_rules! spawn_monitored_blocking {
376    ($f: expr) => {{
377        let location: &'static str = concat!(file!(), ':', line!());
378        let timing = $crate::get_server_timing();
379        let f = $f;
380        tokio::task::spawn_blocking(move || {
381            let _metrics_guard = $crate::get_metrics().map(|m| {
382                m.tasks.with_label_values(&[location]).inc();
383                $crate::scopeguard::guard(m, move |m| {
384                    m.tasks.with_label_values(&[location]).dec();
385                })
386            });
387            $crate::run_with_server_timing(timing, f)
388        })
389    }};
390}
391
392#[macro_export]
393macro_rules! spawn_logged_monitored_task {
394    ($fut: expr) => {
395        $crate::forward_server_timing_and_spawn!($crate::monitored_future!(
396            tasks, $fut, "", INFO, true
397        ))
398    };
399
400    ($fut: expr, $name: expr) => {
401        $crate::forward_server_timing_and_spawn!($crate::monitored_future!(
402            tasks, $fut, $name, INFO, true
403        ))
404    };
405
406    ($fut: expr, $name: expr, $logging_level: ident) => {
407        $crate::forward_server_timing_and_spawn!($crate::monitored_future!(
408            tasks,
409            $fut,
410            $name,
411            $logging_level,
412            true
413        ))
414    };
415}
416
417pub struct MonitoredScopeGuard {
418    metrics: &'static Metrics,
419    name: &'static str,
420    timer: Instant,
421}
422
423impl Drop for MonitoredScopeGuard {
424    fn drop(&mut self) {
425        self.metrics
426            .scope_duration_ns
427            .with_label_values(&[self.name])
428            .add(self.timer.elapsed().as_nanos() as i64);
429        self.metrics
430            .scope_entrance
431            .with_label_values(&[self.name])
432            .dec();
433    }
434}
435
436/// This function creates a named scoped object, that keeps track of
437/// - the total iterations where the scope is called in the `monitored_scope_iterations` metric.
438/// - and the total duration of the scope in the `monitored_scope_duration_ns` metric.
439///
440/// The monitored scope should be single threaded, e.g. the scoped object
441/// encompass the lifetime of a select loop or guarded by mutex.
442/// Then the rate of `monitored_scope_duration_ns`, converted to the unit of sec
443/// / sec, would be how full the single threaded scope is running.
444pub fn monitored_scope(name: &'static str) -> Option<MonitoredScopeGuard> {
445    let metrics = get_metrics();
446    if let Some(m) = metrics {
447        m.scope_iterations.with_label_values(&[name]).inc();
448        m.scope_entrance.with_label_values(&[name]).inc();
449        Some(MonitoredScopeGuard {
450            metrics: m,
451            name,
452            timer: Instant::now(),
453        })
454    } else {
455        None
456    }
457}
458
459/// A trait extension for `Future` to allow monitoring the execution of the
460/// future within a specific scope. Provides the `in_monitored_scope` method to
461/// wrap the future in a `MonitoredScopeFuture`, which tracks the future's
462/// execution using a `MonitoredScopeGuard` for monitoring purposes.
463pub trait MonitoredFutureExt: Future + Sized {
464    /// Wraps the current future in a `MonitoredScopeFuture` that is associated
465    /// with a specific monitored scope name. The scope helps track the
466    /// execution of the future for performance analysis and metrics collection.
467    fn in_monitored_scope(self, name: &'static str) -> MonitoredScopeFuture<Self>;
468}
469
470impl<F: Future> MonitoredFutureExt for F {
471    fn in_monitored_scope(self, name: &'static str) -> MonitoredScopeFuture<Self> {
472        MonitoredScopeFuture {
473            f: Box::pin(self),
474            active_duration_metric: get_metrics()
475                .map(|m| m.future_active_duration_ns.with_label_values(&[name])),
476            _scope: monitored_scope(name),
477        }
478    }
479}
480
481/// A future that runs within a monitored scope. This struct wraps a pinned
482/// future and holds an optional `MonitoredScopeGuard` to measure and monitor
483/// the execution of the future. It forwards polling operations
484/// to the underlying future while maintaining the monitoring scope.
485pub struct MonitoredScopeFuture<F: Sized> {
486    f: Pin<Box<F>>,
487    active_duration_metric: Option<GenericGauge<AtomicI64>>,
488    _scope: Option<MonitoredScopeGuard>,
489}
490
491impl<F: Future> Future for MonitoredScopeFuture<F> {
492    type Output = F::Output;
493
494    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
495        let active_timer = Instant::now();
496        let ret = self.f.as_mut().poll(cx);
497        if let Some(m) = &self.active_duration_metric {
498            m.add(active_timer.elapsed().as_nanos() as i64);
499        }
500        ret
501    }
502}
503
504/// A future that runs within a monitored scope. This struct wraps a pinned
505/// future and holds an optional `MonitoredScopeGuard` to measure and monitor
506/// the execution of the future. It forwards polling operations
507/// to the underlying future while maintaining the monitoring scope.
508pub struct CancelMonitor<F: Sized> {
509    finished: bool,
510    inner: Pin<Box<F>>,
511}
512
513impl<F> CancelMonitor<F>
514where
515    F: Future,
516{
517    /// Creates a new `CancelMonitor` that wraps the given future (`inner`). The
518    /// monitor tracks whether the future has completed.
519    pub fn new(inner: F) -> Self {
520        Self {
521            finished: false,
522            inner: Box::pin(inner),
523        }
524    }
525
526    /// Returns `true` if the future has completed; otherwise, `false`.
527    pub fn is_finished(&self) -> bool {
528        self.finished
529    }
530}
531
532impl<F> Future for CancelMonitor<F>
533where
534    F: Future,
535{
536    type Output = F::Output;
537
538    /// Polls the inner future to determine if it is ready or still pending. For
539    /// `CancelMonitor`, if the future completes (`Poll::Ready`), `finished`
540    /// is set to `true`. If it is still pending, the status remains
541    /// unchanged. This allows monitoring of the future's completion status.
542    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
543        match self.inner.as_mut().poll(cx) {
544            Poll::Ready(output) => {
545                self.finished = true;
546                Poll::Ready(output)
547            }
548            Poll::Pending => Poll::Pending,
549        }
550    }
551}
552
553impl<F: Sized> Drop for CancelMonitor<F> {
554    /// When the `CancelMonitor` is dropped, it checks whether the future has
555    /// finished executing. If the future was not completed (`finished` is
556    /// `false`), it records that the future was cancelled by logging the
557    /// cancellation status using the current span.
558    fn drop(&mut self) {
559        if !self.finished {
560            Span::current().record("cancelled", true);
561        }
562    }
563}
564
565/// MonitorCancellation records a cancelled = true span attribute if the future
566/// it is decorating is dropped before completion. The cancelled attribute must
567/// be added at span creation, as you cannot add new attributes after the span
568/// is created.
569pub trait MonitorCancellation {
570    fn monitor_cancellation(self) -> CancelMonitor<Self>
571    where
572        Self: Sized + Future;
573}
574
575impl<T> MonitorCancellation for T
576where
577    T: Future,
578{
579    fn monitor_cancellation(self) -> CancelMonitor<Self> {
580        CancelMonitor::new(self)
581    }
582}
583
584pub type RegistryID = Uuid;
585
586/// A service to manage the prometheus registries. This service allow us to
587/// create a new Registry on demand and keep it accessible for
588/// processing/polling. The service can be freely cloned/shared across threads.
589#[derive(Clone)]
590pub struct RegistryService {
591    // Holds a Registry that is supposed to be used
592    default_registry: Registry,
593    registries_by_id: Arc<DashMap<Uuid, Registry>>,
594    filter: Arc<Filter>,
595}
596
597impl RegistryService {
598    // Creates a new registry service and also adds the main/default registry that
599    // is supposed to be preserved and never get removed
600    pub fn new(default_registry: Registry) -> Self {
601        Self {
602            filter: default_registry.filter(),
603            default_registry,
604            registries_by_id: Arc::new(DashMap::new()),
605        }
606    }
607
608    // Returns the default registry for the service that someone can use
609    // if they don't want to create a new one.
610    pub fn default_registry(&self) -> Registry {
611        self.default_registry.clone()
612    }
613
614    /// Returns the metrics filter shared by the service's registries.
615    pub fn filter(&self) -> Arc<Filter> {
616        self.filter.clone()
617    }
618
619    // Creates a new registry that shares the service's metric filter. Prefer
620    // this over `Registry::new()`/`Registry::new_custom()` for registries added
621    // via `add`, so that the configured filter applies to their metrics too.
622    pub fn new_registry_custom(
623        &self,
624        prefix: Option<String>,
625        labels: Option<std::collections::HashMap<String, String>>,
626    ) -> prometheus_filtered::Result<Registry> {
627        Registry::new_custom(prefix, labels, Some(self.filter.clone()))
628    }
629
630    // Adds a new registry to the service. The corresponding RegistryID is returned
631    // so can later be used for removing the Registry. Method panics if we try
632    // to insert a registry with the same id. As this can be quite serious for
633    // the operation of the node we don't want to accidentally swap an existing
634    // registry - we expected a removal to happen explicitly.
635    pub fn add(&self, registry: Registry) -> RegistryID {
636        let registry_id = Uuid::new_v4();
637        if self
638            .registries_by_id
639            .insert(registry_id, registry)
640            .is_some()
641        {
642            panic!("Other Registry already detected for the same id {registry_id}");
643        }
644
645        registry_id
646    }
647
648    // Removes the registry from the service. If Registry existed then this method
649    // returns true, otherwise false is returned instead.
650    pub fn remove(&self, registry_id: RegistryID) -> bool {
651        self.registries_by_id.remove(&registry_id).is_some()
652    }
653
654    // Returns all the registries of the service
655    pub fn get_all(&self) -> Vec<Registry> {
656        let mut registries: Vec<Registry> = self
657            .registries_by_id
658            .iter()
659            .map(|r| r.value().clone())
660            .collect();
661        registries.push(self.default_registry.clone());
662
663        registries
664    }
665
666    // Returns all the metric families from the registries that a service holds.
667    pub fn gather_all(&self) -> Vec<prometheus_filtered::proto::MetricFamily> {
668        self.get_all().iter().flat_map(|r| r.gather()).collect()
669    }
670
671    /// Sets the runtime override on the shared filter; every registry's next
672    /// gather exposes metrics per the new directives. `filter` may use
673    /// [`MetricGroups`] names, which are expanded for matching while the
674    /// string is echoed back as given. Rejects the whole update if any
675    /// directive is invalid.
676    pub fn set_runtime_filter(&self, filter: &str) -> std::result::Result<(), String> {
677        let expanded = MetricGroups::expand_directives(filter)?;
678        self.filter
679            .set_runtime_filter(prometheus_filtered::FilterSource::with_display(
680                &expanded, filter,
681            ))
682    }
683
684    /// Drops the runtime override on the shared filter, restoring every
685    /// registry to its startup exposure.
686    pub fn reset_runtime_filter(&self) {
687        self.filter.reset_runtime_filter();
688    }
689}
690
691/// Create a metric that measures the uptime from when this metric was
692/// constructed. The metric is labeled with:
693/// - 'process': the process type, differentiating between validator and fullnode
694/// - 'version': binary version, generally be of the format: 'semver-gitrevision'
695/// - 'chain_identifier': the identifier of the network which this process is part of
696pub fn uptime_metric(
697    process: &str,
698    version: &'static str,
699    chain_identifier: &str,
700) -> Box<dyn prometheus_filtered::core::Collector> {
701    let opts = prometheus_filtered::opts!("uptime", "uptime of the node service in seconds")
702        .variable_label("process")
703        .variable_label("version")
704        .variable_label("chain_identifier")
705        .variable_label("os_version")
706        .variable_label("is_docker");
707
708    let start_time = std::time::Instant::now();
709    let uptime = move || start_time.elapsed().as_secs();
710    let metric = prometheus_closure_metric::ClosureMetric::new(
711        opts,
712        prometheus_closure_metric::ValueType::Counter,
713        uptime,
714        &[
715            process,
716            version,
717            chain_identifier,
718            &sysinfo::System::long_os_version()
719                .unwrap_or_else(|| "os_version_unavailable".to_string()),
720            &is_running_in_docker().to_string(),
721        ],
722    )
723    .unwrap();
724
725    Box::new(metric)
726}
727
728pub fn is_running_in_docker() -> bool {
729    // Check for .dockerenv file instead. This file exists in the debian:__-slim
730    // image we use at runtime.
731    Path::new("/.dockerenv").exists()
732}
733
734pub const METRICS_ROUTE: &str = "/metrics";
735
736// Creates a new http server that has as a sole purpose to expose
737// and endpoint that prometheus agent can use to poll for the metrics.
738// A RegistryService is returned that can be used to get access in prometheus
739// Registries.
740pub fn start_prometheus_server(addr: SocketAddr) -> RegistryService {
741    start_prometheus_server_with_filter(addr, Filter::from_env())
742}
743
744pub fn start_prometheus_server_with_filter(addr: SocketAddr, filter: Filter) -> RegistryService {
745    // The default registry has no prefix or labels, so its construction is
746    // infallible.
747    let registry = Registry::new_custom(None, None, Some(Arc::new(filter)))
748        .expect("unprefixed registry is infallible");
749
750    let registry_service = RegistryService::new(registry);
751
752    if cfg!(msim) {
753        // prometheus uses difficult-to-support features such as
754        // TcpSocket::from_raw_fd(), so we can't yet run it in the simulator.
755        warn!("not starting prometheus server in simulator");
756        return registry_service;
757    }
758
759    let app = Router::new()
760        .route(METRICS_ROUTE, get(metrics))
761        .layer(Extension(registry_service.clone()));
762
763    tokio::spawn(async move {
764        let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
765        axum::serve(listener, app.into_make_service())
766            .await
767            .unwrap();
768    });
769
770    registry_service
771}
772
773/// Handles a request to retrieve metrics, using the provided `RegistryService`
774/// to gather all registered metric families. The metrics are then encoded to a
775/// text format for easy consumption by monitoring systems. If successful, it
776/// returns the metrics string with an `OK` status. If an error occurs during
777/// encoding, it returns an `INTERNAL_SERVER_ERROR` status along with an error
778/// message. Returns a tuple containing the status code and either the metrics
779/// data or an error description.
780pub async fn metrics(
781    Extension(registry_service): Extension<RegistryService>,
782) -> (StatusCode, String) {
783    let metrics_families = registry_service.gather_all();
784    match TextEncoder.encode_to_string(&metrics_families) {
785        Ok(metrics) => (StatusCode::OK, metrics),
786        Err(error) => (
787            StatusCode::INTERNAL_SERVER_ERROR,
788            format!("unable to encode metrics: {error}"),
789        ),
790    }
791}
792
793#[cfg(test)]
794mod tests {
795    use prometheus_filtered::{IntCounter, Registry, core::Collector};
796
797    use crate::RegistryService;
798
799    fn running_tasks() -> f64 {
800        crate::get_metrics()
801            .unwrap()
802            .tasks
803            .collect()
804            .iter()
805            .flat_map(|family| family.get_metric())
806            .map(|metric| metric.get_gauge().value())
807            .sum()
808    }
809
810    #[tokio::test]
811    async fn spawn_monitored_blocking_counts_the_task_and_keeps_server_timing() {
812        crate::init_metrics(&Registry::new());
813        let inside = crate::with_new_server_timing(async {
814            spawn_monitored_blocking!(|| (running_tasks(), crate::get_server_timing().is_some()))
815                .await
816        })
817        .await
818        .unwrap();
819        assert_eq!(inside, (1.0, true));
820        assert_eq!(running_tasks(), 0.0);
821    }
822
823    #[test]
824    fn registry_service() {
825        // GIVEN
826        let default_registry =
827            Registry::new_custom(Some("default".to_string()), None, None).unwrap();
828
829        let registry_service = RegistryService::new(default_registry.clone());
830        let default_counter = IntCounter::new("counter", "counter_desc").unwrap();
831        default_counter.inc();
832        default_registry
833            .register(Box::new(default_counter))
834            .unwrap();
835
836        // AND add a metric to the default registry
837
838        // AND a registry with one metric
839        let registry_1 = Registry::new_custom(Some("iota".to_string()), None, None).unwrap();
840        registry_1
841            .register(Box::new(
842                IntCounter::new("counter_1", "counter_1_desc").unwrap(),
843            ))
844            .unwrap();
845
846        // WHEN
847        let registry_1_id = registry_service.add(registry_1);
848
849        // THEN
850        let mut metrics = registry_service.gather_all();
851        metrics.sort_by(|m1, m2| Ord::cmp(m1.name(), m2.name()));
852
853        assert_eq!(metrics.len(), 2);
854
855        let metric_default = metrics.remove(0);
856        assert_eq!(metric_default.name(), "default_counter");
857        assert_eq!(metric_default.help(), "counter_desc");
858
859        let metric_1: prometheus_filtered::proto::MetricFamily = metrics.remove(0);
860        assert_eq!(metric_1.name(), "iota_counter_1");
861        assert_eq!(metric_1.help(), "counter_1_desc");
862
863        // AND add a second registry with a metric
864        let registry_2 = Registry::new_custom(Some("iota".to_string()), None, None).unwrap();
865        registry_2
866            .register(Box::new(
867                IntCounter::new("counter_2", "counter_2_desc").unwrap(),
868            ))
869            .unwrap();
870        let _registry_2_id = registry_service.add(registry_2);
871
872        // THEN all the metrics should be returned
873        let mut metrics = registry_service.gather_all();
874        metrics.sort_by(|m1, m2| Ord::cmp(m1.name(), m2.name()));
875
876        assert_eq!(metrics.len(), 3);
877
878        let metric_default = metrics.remove(0);
879        assert_eq!(metric_default.name(), "default_counter");
880        assert_eq!(metric_default.help(), "counter_desc");
881
882        let metric_1 = metrics.remove(0);
883        assert_eq!(metric_1.name(), "iota_counter_1");
884        assert_eq!(metric_1.help(), "counter_1_desc");
885
886        let metric_2 = metrics.remove(0);
887        assert_eq!(metric_2.name(), "iota_counter_2");
888        assert_eq!(metric_2.help(), "counter_2_desc");
889
890        // AND remove first registry
891        assert!(registry_service.remove(registry_1_id));
892
893        // THEN metrics should now not contain metric of registry_1
894        let mut metrics = registry_service.gather_all();
895        metrics.sort_by(|m1, m2| Ord::cmp(m1.name(), m2.name()));
896
897        assert_eq!(metrics.len(), 2);
898
899        let metric_default = metrics.remove(0);
900        assert_eq!(metric_default.name(), "default_counter");
901        assert_eq!(metric_default.help(), "counter_desc");
902
903        let metric_1 = metrics.remove(0);
904        assert_eq!(metric_1.name(), "iota_counter_2");
905        assert_eq!(metric_1.help(), "counter_2_desc");
906    }
907
908    #[test]
909    fn set_runtime_filter_applies_to_all_registries() {
910        use std::sync::Arc;
911
912        use prometheus_filtered::{Filter, MetricLevel};
913
914        fn gathered_names(service: &RegistryService) -> Vec<String> {
915            let mut names: Vec<_> = service
916                .gather_all()
917                .iter()
918                .map(|f| f.name().to_owned())
919                .collect();
920            names.sort();
921            names
922        }
923
924        // Both registries share the service's filter, which starts at `warn`
925        // for this module, hiding the default-level (`debug`) gauges.
926        let filter = Arc::new(Filter::parse("iota_metrics=warn"));
927        let default_registry =
928            Registry::new_custom(Some("default".to_string()), None, Some(filter)).unwrap();
929        let registry_service = RegistryService::new(default_registry.clone());
930        let second_registry = registry_service
931            .new_registry_custom(Some("second".to_string()), None)
932            .unwrap();
933        registry_service.add(second_registry.clone());
934
935        for registry in [&default_registry, &second_registry] {
936            prometheus_filtered::register_int_gauge_with_registry!(
937                "g_warn", "h", registry; MetricLevel::Warn
938            )
939            .unwrap();
940            prometheus_filtered::register_int_gauge_with_registry!("g_debug", "h", registry)
941                .unwrap();
942        }
943        assert_eq!(
944            gathered_names(&registry_service),
945            ["default_g_warn", "second_g_warn"]
946        );
947
948        // One runtime update changes the exposure of every registry in the
949        // service.
950        registry_service
951            .set_runtime_filter("runtime=debug")
952            .unwrap();
953        assert_eq!(
954            gathered_names(&registry_service),
955            [
956                "default_g_debug",
957                "default_g_warn",
958                "second_g_debug",
959                "second_g_warn"
960            ]
961        );
962
963        // Reset restores the startup exposure across all registries.
964        registry_service.reset_runtime_filter();
965        assert_eq!(
966            gathered_names(&registry_service),
967            ["default_g_warn", "second_g_warn"]
968        );
969    }
970}