1use 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#[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 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
192pub fn init_metrics(registry: &Registry) {
198 let _ = METRICS
199 .set(Metrics::new(registry))
200 .tap_err(|_| warn!("init_metrics registry overwritten"));
202}
203
204pub fn get_metrics() -> Option<&'static Metrics> {
206 METRICS.get()
207}
208
209tokio::task_local! {
210 static SERVER_TIMING: Arc<Mutex<Timer>>;
211}
212
213pub 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
230pub fn server_timing_header_key() -> &'static str {
232 Timer::header_key()
233}
234
235pub 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
260pub 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
276pub fn get_server_timing() -> Option<Arc<Mutex<Timer>>> {
279 SERVER_TIMING.try_with(|timer| timer.clone()).ok()
280}
281
282#[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
291pub 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#[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
436pub 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
459pub trait MonitoredFutureExt: Future + Sized {
464 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
481pub 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
504pub struct CancelMonitor<F: Sized> {
509 finished: bool,
510 inner: Pin<Box<F>>,
511}
512
513impl<F> CancelMonitor<F>
514where
515 F: Future,
516{
517 pub fn new(inner: F) -> Self {
520 Self {
521 finished: false,
522 inner: Box::pin(inner),
523 }
524 }
525
526 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 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 fn drop(&mut self) {
559 if !self.finished {
560 Span::current().record("cancelled", true);
561 }
562 }
563}
564
565pub 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#[derive(Clone)]
590pub struct RegistryService {
591 default_registry: Registry,
593 registries_by_id: Arc<DashMap<Uuid, Registry>>,
594 filter: Arc<Filter>,
595}
596
597impl RegistryService {
598 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 pub fn default_registry(&self) -> Registry {
611 self.default_registry.clone()
612 }
613
614 pub fn filter(&self) -> Arc<Filter> {
616 self.filter.clone()
617 }
618
619 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 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 pub fn remove(&self, registry_id: RegistryID) -> bool {
651 self.registries_by_id.remove(®istry_id).is_some()
652 }
653
654 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 pub fn gather_all(&self) -> Vec<prometheus_filtered::proto::MetricFamily> {
668 self.get_all().iter().flat_map(|r| r.gather()).collect()
669 }
670
671 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 pub fn reset_runtime_filter(&self) {
687 self.filter.reset_runtime_filter();
688 }
689}
690
691pub 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 Path::new("/.dockerenv").exists()
732}
733
734pub const METRICS_ROUTE: &str = "/metrics";
735
736pub 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 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 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
773pub 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 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 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 let registry_1_id = registry_service.add(registry_1);
848
849 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 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 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 assert!(registry_service.remove(registry_1_id));
892
893 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 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(®istry_service),
945 ["default_g_warn", "second_g_warn"]
946 );
947
948 registry_service
951 .set_runtime_filter("runtime=debug")
952 .unwrap();
953 assert_eq!(
954 gathered_names(®istry_service),
955 [
956 "default_g_debug",
957 "default_g_warn",
958 "second_g_debug",
959 "second_g_warn"
960 ]
961 );
962
963 registry_service.reset_runtime_filter();
965 assert_eq!(
966 gathered_names(®istry_service),
967 ["default_g_warn", "second_g_warn"]
968 );
969 }
970}