Skip to main content

oxtel_tokio/
lib.rs

1//! Metrics for a tokio runtime: its workers, its tasks, the tasks waiting
2//! to run, and how busy it is. Part of
3//! [oxtel](https://github.com/agentstatelabs/oxtel).
4//!
5//! One line records them every ten seconds, for as long as the value it
6//! returns is kept:
7//!
8//! ```
9//! # #[tokio::main(flavor = "current_thread")]
10//! # async fn main() {
11//! let _runtime_metrics = oxtel_tokio::record(&tokio::runtime::Handle::current());
12//! # }
13//! ```
14//!
15//! | Metric | Type | What it is |
16//! |---|---|---|
17//! | `oxtel.tokio.worker.count` | gauge, `{thread}` | Worker threads. |
18//! | `oxtel.tokio.task.count` | gauge, `{task}` | Tasks spawned and not yet finished. |
19//! | `oxtel.tokio.global_queue.length` | gauge, `{task}` | Tasks waiting in the global queue, where tasks spawned from outside the runtime go. A queue that keeps growing means the workers can't keep up. |
20//! | `oxtel.tokio.utilization` | gauge, `1` | The share of the workers' time spent running tasks since the last recording, from 0 to 1. Near 1, the runtime is saturated. |
21//!
22//! Built with `--cfg tokio_unstable`, as tokio's own unstable metrics
23//! need, it also records the blocking pool, where `spawn_blocking` work
24//! runs:
25//!
26//! | Metric | Type | What it is |
27//! |---|---|---|
28//! | `oxtel.tokio.blocking.thread.count` | gauge, `{thread}` | Blocking threads, by `oxtel.tokio.thread.state`: `busy` or `idle`. |
29//! | `oxtel.tokio.blocking.queue.length` | gauge, `{task}` | Blocking work waiting for a thread. |
30//!
31//! The OpenTelemetry conventions don't define tokio metrics, so these are
32//! named under `oxtel.`, shaped like the conventions' own runtime metrics
33//! (`dotnet.thread_pool.*` and `nodejs.eventloop.utilization`). They're
34//! recorded through `metrics`, so they go wherever the program's recorder
35//! sends them: with `oxtel::init()`, to OTLP or Prometheus.
36//!
37//! The recording happens on a thread of its own, so it goes on when the
38//! runtime is too busy to run anything else, which is when it matters.
39//! [`Sampler`] records on demand instead, such as just before serving a
40//! scrape, and names runtimes apart when a program has several.
41
42use std::sync::mpsc;
43use std::thread::JoinHandle;
44use std::time::{Duration, Instant};
45
46use metrics::Label;
47use tokio::runtime::{Handle, RuntimeMetrics};
48
49/// How often [`record`] records.
50pub const DEFAULT_INTERVAL: Duration = Duration::from_secs(10);
51
52/// Records the runtime's metrics every [ten seconds](DEFAULT_INTERVAL), on
53/// a thread of its own, until the returned [`Recording`] is dropped.
54pub fn record(handle: &Handle) -> Recording {
55    Sampler::new(handle).spawn_every(DEFAULT_INTERVAL)
56}
57
58/// Records one runtime's metrics when asked. It remembers the last time it
59/// recorded, to say how busy the runtime has been since.
60#[derive(Debug)]
61pub struct Sampler {
62    metrics: RuntimeMetrics,
63    labels: Vec<Label>,
64    /// When it last recorded, and the workers' busy time then.
65    last: (Instant, Duration),
66}
67
68impl Sampler {
69    /// A sampler for the runtime `handle` belongs to. How busy the runtime
70    /// is gets measured from now.
71    pub fn new(handle: &Handle) -> Sampler {
72        describe_metrics();
73        let metrics = handle.metrics();
74        let busy = busy_time(&metrics);
75        Sampler {
76            metrics,
77            labels: Vec::new(),
78            last: (Instant::now(), busy),
79        }
80    }
81
82    /// Names the runtime, as the `oxtel.tokio.runtime.name` label on every
83    /// metric, for a program with more than one.
84    pub fn with_name(mut self, name: impl Into<String>) -> Self {
85        self.labels
86            .retain(|label| label.key() != "oxtel.tokio.runtime.name");
87        self.labels
88            .push(Label::new("oxtel.tokio.runtime.name", name.into()));
89        self
90    }
91
92    /// Records the metrics now.
93    pub fn sample(&mut self) {
94        let workers = self.metrics.num_workers();
95        let labels = &self.labels;
96        metrics::gauge!("oxtel.tokio.worker.count", labels.clone()).set(workers as f64);
97        metrics::gauge!("oxtel.tokio.task.count", labels.clone())
98            .set(self.metrics.num_alive_tasks() as f64);
99        metrics::gauge!("oxtel.tokio.global_queue.length", labels.clone())
100            .set(self.metrics.global_queue_depth() as f64);
101
102        let now = Instant::now();
103        let busy = busy_time(&self.metrics);
104        let (then, busy_then) = std::mem::replace(&mut self.last, (now, busy));
105        let available = (now - then).as_secs_f64() * workers as f64;
106        if cfg!(target_has_atomic = "64") && available > 0.0 {
107            let used = busy.saturating_sub(busy_then).as_secs_f64();
108            metrics::gauge!("oxtel.tokio.utilization", labels.clone())
109                .set((used / available).clamp(0.0, 1.0));
110        }
111
112        #[cfg(tokio_unstable)]
113        {
114            let threads = self.metrics.num_blocking_threads();
115            let idle = self.metrics.num_idle_blocking_threads();
116            for (state, count) in [("busy", threads.saturating_sub(idle)), ("idle", idle)] {
117                let mut labels = labels.clone();
118                labels.push(Label::new("oxtel.tokio.thread.state", state));
119                metrics::gauge!("oxtel.tokio.blocking.thread.count", labels).set(count as f64);
120            }
121            metrics::gauge!("oxtel.tokio.blocking.queue.length", labels.clone())
122                .set(self.metrics.blocking_queue_depth() as f64);
123        }
124    }
125
126    /// Records the metrics now and every `interval` after, on a thread of
127    /// its own, until the returned [`Recording`] is dropped.
128    pub fn spawn_every(mut self, interval: Duration) -> Recording {
129        let (stop, stopped) = mpsc::channel::<()>();
130        let thread = std::thread::Builder::new()
131            .name("oxtel-tokio".into())
132            .spawn(move || {
133                loop {
134                    self.sample();
135                    // Wakes at once when the Recording is dropped.
136                    if stopped.recv_timeout(interval) != Err(mpsc::RecvTimeoutError::Timeout) {
137                        break;
138                    }
139                }
140            })
141            .expect("a thread can be started");
142        Recording {
143            stop: Some(stop),
144            thread: Some(thread),
145        }
146    }
147}
148
149/// The workers' busy time, summed. tokio measures it only where 64-bit
150/// atomics exist; elsewhere it's always zero, and utilization isn't
151/// recorded.
152#[cfg(target_has_atomic = "64")]
153fn busy_time(metrics: &RuntimeMetrics) -> Duration {
154    (0..metrics.num_workers())
155        .map(|worker| metrics.worker_total_busy_duration(worker))
156        .sum()
157}
158
159#[cfg(not(target_has_atomic = "64"))]
160fn busy_time(_: &RuntimeMetrics) -> Duration {
161    Duration::ZERO
162}
163
164/// A runtime's metrics being recorded. Dropping it stops the recording.
165#[derive(Debug)]
166#[must_use = "recording stops when this is dropped"]
167pub struct Recording {
168    stop: Option<mpsc::Sender<()>>,
169    thread: Option<JoinHandle<()>>,
170}
171
172impl Drop for Recording {
173    fn drop(&mut self) {
174        drop(self.stop.take());
175        if let Some(thread) = self.thread.take() {
176            let _ = thread.join();
177        }
178    }
179}
180
181/// Gives the current `metrics` recorder the descriptions of the runtime
182/// metrics. [`Sampler::new`] does this.
183pub fn describe_metrics() {
184    metrics::describe_gauge!("oxtel.tokio.worker.count", "Worker threads.");
185    metrics::describe_gauge!(
186        "oxtel.tokio.task.count",
187        "Tasks spawned and not yet finished."
188    );
189    metrics::describe_gauge!(
190        "oxtel.tokio.global_queue.length",
191        "Tasks waiting in the runtime's global queue."
192    );
193    metrics::describe_gauge!(
194        "oxtel.tokio.utilization",
195        "The share of the workers' time spent running tasks, from 0 to 1."
196    );
197    #[cfg(tokio_unstable)]
198    {
199        metrics::describe_gauge!("oxtel.tokio.blocking.thread.count", "Blocking threads.");
200        metrics::describe_gauge!(
201            "oxtel.tokio.blocking.queue.length",
202            "Blocking work waiting for a thread."
203        );
204    }
205}