Skip to main content

saluki_app/metrics/
mod.rs

1//! Metrics.
2
3use std::{sync::OnceLock, time::Duration};
4
5use async_trait::async_trait;
6use metrics::{gauge, Gauge, Level};
7use saluki_common::sync::shutdown::ShutdownHandle;
8use saluki_core::{
9    observability::metrics::initialize_shared_metrics_state,
10    runtime::{self, InitializationError, Supervisable, Supervisor, SupervisorFuture},
11};
12use saluki_error::{ErrorContext as _, GenericError};
13use saluki_metrics::static_metrics;
14use tokio::{runtime::Handle, select, time::sleep};
15
16mod api;
17pub use self::api::{MetricsAPIHandler, MetricsOverrideWorker};
18
19/// Returns the configuration name of a metrics level, such as `info`.
20pub(crate) fn level_name(level: Level) -> &'static str {
21    match level {
22        Level::TRACE => "trace",
23        Level::DEBUG => "debug",
24        Level::INFO => "info",
25        Level::WARN => "warn",
26        Level::ERROR => "error",
27    }
28}
29
30/// Initializes the metrics subsystem for `metrics`.
31///
32/// The given prefix is used to namespace all metrics that are emitted by the application, and is prepended to all
33/// metrics, followed by a period (for example, `<prefix>.<metric name>`). The given default level seeds the runtime
34/// filter and is what the filter is restored to when [`MetricsAPIHandler`]'s reset route is invoked.
35///
36/// Returns a [`Supervisor`] holding the subsystem's background workers. The caller must arrange for it to run --
37/// typically by adding it to a parent supervisor -- or internal metrics are never flushed to subscribers.
38///
39/// # Errors
40///
41/// If the metrics subsystem was already initialized, or its supervisor can't be constructed, an error will be
42/// returned.
43pub(crate) async fn initialize_metrics(
44    metrics_prefix: impl Into<String>, default_level: Level, minimum_level: Level,
45) -> Result<Supervisor, GenericError> {
46    // We forward to the implementation in `saluki_core` so that we can have this crate be the collection point of all
47    // helpers/types that are specific to generic application setup/initialization.
48    //
49    // The implementation itself has to live in `saluki_core`, however, to have access to all of the underlying types
50    // that are created and used to install the global recorder, such that they need not be exposed publicly.
51    let (filter_handle, flusher) =
52        saluki_core::observability::metrics::initialize_metrics(metrics_prefix.into(), default_level).await?;
53
54    let override_processor = MetricsOverrideWorker::new(filter_handle, minimum_level);
55
56    // Subscribe to the registry now rather than when the worker starts, so that flushes landing between here and the
57    // supervisor running are still folded into the shared state.
58    let reflector = initialize_shared_metrics_state()?;
59
60    // Capture the current runtime handle eagerly so the runtime metrics worker measures the runtime that owns
61    // bootstrap, regardless of where the worker future eventually executes under the supervisor.
62    let runtime = RuntimeMetricsWorker::new("primary", Handle::current());
63
64    let mut supervisor = Supervisor::new("metrics").error_context("Failed to construct metrics supervisor.")?;
65    supervisor.add_worker(flusher);
66    supervisor.add_worker(runtime);
67    supervisor.add_worker(override_processor);
68
69    // Hosted rather than needed: the reflector worker treats an exhausted source as terminal and returns normally, so
70    // restarting it would only hand it the same dead source again.
71    supervisor.add_worker(runtime::supervisable(reflector).hosted().build());
72
73    Ok(supervisor)
74}
75
76/// Emits the startup metrics for the application.
77///
78/// This is generally meant to be called after the application has been initialized, in order to indicate the
79/// application has completed start-up and is now running.
80///
81/// Must be called after the metrics subsystem has been initialized.
82pub fn emit_startup_metrics() {
83    // We hold the handle for the life of the process so it doesn't get idle reaped.
84    static RUNNING: OnceLock<Gauge> = OnceLock::new();
85
86    let app_details = saluki_metadata::get_app_details();
87    let app_version = if app_details.is_dev_build() {
88        format!("{}-dev-{}", app_details.version().raw(), app_details.git_hash(),)
89    } else {
90        app_details.version().raw().to_string()
91    };
92
93    // Emit a "running" metric to indicate that the application is running.
94    let running = RUNNING.get_or_init(|| gauge!("running", "version" => app_version));
95    running.set(1.0);
96}
97
98/// Collects Tokio runtime metrics from the given runtime handle.
99///
100/// All metrics generated will include a `runtime_id` label which maps to the given runtime ID. This allows for
101/// differentiating between multiple runtimes that may be running in the same process.
102pub async fn collect_runtime_metrics(runtime_id: &str, handle: Handle) {
103    // Grab the total number of runtime workers to properly initialize/register our metrics.
104    let runtime_metrics = RuntimeMetrics::with_workers(runtime_id, handle.metrics().num_workers());
105
106    // With our metrics registered, enter the main loop where we periodically scrape the metrics.
107    loop {
108        let latest_runtime_metrics = handle.metrics();
109        runtime_metrics.update(&latest_runtime_metrics);
110
111        sleep(Duration::from_secs(5)).await;
112    }
113}
114
115/// A worker that periodically collects Tokio runtime metrics.
116///
117/// The runtime is captured at construction time so that the metrics measured always describe the runtime that
118/// owned the bootstrap, regardless of where this worker eventually executes under a supervisor.
119pub struct RuntimeMetricsWorker {
120    runtime_id: String,
121    handle: Handle,
122}
123
124impl RuntimeMetricsWorker {
125    /// Creates a new `RuntimeMetricsWorker` that collects metrics from the given runtime.
126    pub fn new<S: Into<String>>(runtime_id: S, handle: Handle) -> Self {
127        Self {
128            runtime_id: runtime_id.into(),
129            handle,
130        }
131    }
132}
133
134#[async_trait]
135impl Supervisable for RuntimeMetricsWorker {
136    fn name(&self) -> &str {
137        "tokio-runtime-metrics-collector"
138    }
139
140    async fn initialize(&self, process_shutdown: ShutdownHandle) -> Result<SupervisorFuture, InitializationError> {
141        let runtime_id = self.runtime_id.clone();
142        let handle = self.handle.clone();
143
144        Ok(Box::pin(async move {
145            select! {
146                _ = process_shutdown => {},
147                _ = collect_runtime_metrics(&runtime_id, handle) => {},
148            }
149
150            Ok(())
151        }))
152    }
153}
154
155#[static_metrics(prefix = runtime_worker, labels(runtime_id, worker_idx))]
156#[derive(Clone)]
157struct WorkerMetrics {
158    #[metric(level = trace)]
159    local_queue_depth: Gauge,
160    #[metric(level = trace)]
161    local_schedule_count: Gauge,
162    #[metric(level = trace)]
163    mean_poll_time: Gauge,
164    #[metric(level = trace)]
165    noop_count: Gauge,
166    #[metric(level = trace)]
167    overflow_count: Gauge,
168    #[metric(level = trace)]
169    park_count: Gauge,
170    #[metric(level = trace)]
171    park_unpark_count: Gauge,
172    #[metric(level = trace)]
173    poll_count: Gauge,
174    #[metric(level = trace)]
175    steal_count: Gauge,
176    #[metric(level = trace)]
177    steal_operations: Gauge,
178    #[metric(level = trace)]
179    total_busy_duration: Gauge,
180}
181
182impl WorkerMetrics {
183    fn with_worker_idx(runtime_id: &str, worker_idx: usize) -> Self {
184        Self::new(runtime_id, worker_idx)
185    }
186
187    fn update(&self, worker_idx: usize, metrics: &tokio::runtime::RuntimeMetrics) {
188        self.local_queue_depth()
189            .set(metrics.worker_local_queue_depth(worker_idx) as f64);
190        self.local_schedule_count()
191            .set(metrics.worker_local_schedule_count(worker_idx) as f64);
192        self.mean_poll_time()
193            .set(metrics.worker_mean_poll_time(worker_idx).as_nanos() as f64);
194        self.noop_count().set(metrics.worker_noop_count(worker_idx) as f64);
195        self.overflow_count()
196            .set(metrics.worker_overflow_count(worker_idx) as f64);
197        self.park_count().set(metrics.worker_park_count(worker_idx) as f64);
198        self.park_unpark_count()
199            .set(metrics.worker_park_unpark_count(worker_idx) as f64);
200        self.poll_count().set(metrics.worker_poll_count(worker_idx) as f64);
201        self.steal_count().set(metrics.worker_steal_count(worker_idx) as f64);
202        self.steal_operations()
203            .set(metrics.worker_steal_operations(worker_idx) as f64);
204        self.total_busy_duration()
205            .set(metrics.worker_total_busy_duration(worker_idx).as_nanos() as f64);
206    }
207}
208
209#[static_metrics(prefix = runtime, labels(runtime_id))]
210#[derive(Clone)]
211struct GlobalRuntimeMetrics {
212    #[metric(level = debug)]
213    num_alive_tasks: Gauge,
214    #[metric(level = debug)]
215    blocking_queue_depth: Gauge,
216    #[metric(level = debug)]
217    budget_forced_yield_count: Gauge,
218    #[metric(level = debug)]
219    global_queue_depth: Gauge,
220    #[metric(level = debug)]
221    io_driver_fd_deregistered_count: Gauge,
222    #[metric(level = debug)]
223    io_driver_fd_registered_count: Gauge,
224    #[metric(level = debug)]
225    io_driver_ready_count: Gauge,
226    #[metric(level = debug)]
227    num_blocking_threads: Gauge,
228    #[metric(level = debug)]
229    num_idle_blocking_threads: Gauge,
230    #[metric(level = debug)]
231    num_workers: Gauge,
232    #[metric(level = debug)]
233    remote_schedule_count: Gauge,
234    #[metric(level = debug)]
235    spawned_tasks_count: Gauge,
236}
237
238struct RuntimeMetrics {
239    global: GlobalRuntimeMetrics,
240    workers: Vec<WorkerMetrics>,
241}
242
243impl RuntimeMetrics {
244    fn with_workers(runtime_id: &str, workers_len: usize) -> Self {
245        let mut workers = Vec::with_capacity(workers_len);
246        for i in 0..workers_len {
247            workers.push(WorkerMetrics::with_worker_idx(runtime_id, i));
248        }
249
250        Self {
251            global: GlobalRuntimeMetrics::new(runtime_id),
252            workers,
253        }
254    }
255
256    fn update(&self, metrics: &tokio::runtime::RuntimeMetrics) {
257        self.global.num_alive_tasks().set(metrics.num_alive_tasks() as f64);
258        self.global
259            .blocking_queue_depth()
260            .set(metrics.blocking_queue_depth() as f64);
261        self.global
262            .budget_forced_yield_count()
263            .set(metrics.budget_forced_yield_count() as f64);
264        self.global
265            .global_queue_depth()
266            .set(metrics.global_queue_depth() as f64);
267        self.global
268            .io_driver_fd_deregistered_count()
269            .set(metrics.io_driver_fd_deregistered_count() as f64);
270        self.global
271            .io_driver_fd_registered_count()
272            .set(metrics.io_driver_fd_registered_count() as f64);
273        self.global
274            .io_driver_ready_count()
275            .set(metrics.io_driver_ready_count() as f64);
276        self.global
277            .num_blocking_threads()
278            .set(metrics.num_blocking_threads() as f64);
279        self.global
280            .num_idle_blocking_threads()
281            .set(metrics.num_idle_blocking_threads() as f64);
282        self.global.num_workers().set(metrics.num_workers() as f64);
283        self.global
284            .remote_schedule_count()
285            .set(metrics.remote_schedule_count() as f64);
286        self.global
287            .spawned_tasks_count()
288            .set(metrics.spawned_tasks_count() as f64);
289
290        for (worker_idx, worker) in self.workers.iter().enumerate() {
291            worker.update(worker_idx, metrics);
292        }
293    }
294}