kumo_server_runtime/
lib.rs

1use anyhow::Context;
2use kumo_prometheus::declare_metric;
3use kumo_prometheus::prometheus::IntGaugeVec;
4use parking_lot::Mutex;
5#[cfg(target_os = "linux")]
6use std::collections::BTreeMap;
7use std::collections::HashMap;
8#[cfg(target_os = "linux")]
9use std::fmt::Write;
10use std::future::Future;
11use std::sync::atomic::{AtomicUsize, Ordering};
12use std::sync::{Arc, LazyLock, Once};
13use tokio::runtime::Handle;
14use tokio::task::JoinHandle;
15use tokio::time::Duration;
16
17pub static RUNTIME: LazyLock<Runtime> =
18    LazyLock::new(|| Runtime::new("localset", |cpus| cpus / 4, &LOCALSET_THREADS).unwrap());
19
20declare_metric! {
21/// number of parked (idle) threads in a thread pool
22static PARKED_THREADS: IntGaugeVec(
23        "thread_pool_parked",
24        &["pool"]);
25}
26
27declare_metric! {
28/// number of threads in a thread pool
29static NUM_THREADS: IntGaugeVec(
30        "thread_pool_size",
31        &["pool"]);
32}
33
34declare_metric! {
35/// number of tasks waiting in a thread pool's global queue for a worker
36/// to pick them up. A sustained non-zero value means the pool's workers
37/// cannot keep up with the work scheduled on that pool.
38///
39/// {{since('dev')}}
40static GLOBAL_QUEUE_DEPTH: IntGaugeVec(
41        "thread_pool_global_queue_depth",
42        &["pool"]);
43}
44
45declare_metric! {
46/// number of tasks currently alive in a thread pool
47///
48/// {{since('dev')}}
49static ALIVE_TASKS: IntGaugeVec(
50        "thread_pool_alive_tasks",
51        &["pool"]);
52}
53
54declare_metric! {
55/// total time in seconds that a thread pool's workers have spent running
56/// tasks, summed across its workers. Refreshed once per second by the
57/// runtime metrics sampler.
58///
59/// {{since('dev')}}
60static BUSY_SECONDS: CounterVec(
61        "thread_pool_busy_seconds",
62        &["pool"]);
63}
64
65declare_metric! {
66/// number of threads in a thread pool's blocking pool, which runs
67/// spawn_blocking work and file IO
68///
69/// {{since('dev')}}
70static BLOCKING_THREADS: IntGaugeVec(
71        "thread_pool_blocking_threads",
72        &["pool"]);
73}
74
75declare_metric! {
76/// number of idle threads in a thread pool's blocking pool
77///
78/// {{since('dev')}}
79static IDLE_BLOCKING_THREADS: IntGaugeVec(
80        "thread_pool_idle_blocking_threads",
81        &["pool"]);
82}
83
84declare_metric! {
85/// number of blocking tasks waiting for a thread in a thread pool's
86/// blocking pool
87///
88/// {{since('dev')}}
89static BLOCKING_QUEUE_DEPTH: IntGaugeVec(
90        "thread_pool_blocking_queue_depth",
91        &["pool"]);
92}
93
94/// Refreshes the per-pool gauges for one runtime from tokio's runtime
95/// metrics. Call this repeatedly with the same `last_busy` map for a given
96/// pool to get correct busy-seconds deltas.
97fn sample_runtime_metrics(last_busy: &mut HashMap<String, Duration>, pool: &str, handle: &Handle) {
98    let metrics = handle.metrics();
99    let set = |gauge: &IntGaugeVec, value: usize| {
100        if let Ok(gauge) = gauge.get_metric_with_label_values(&[pool]) {
101            gauge.set(value as i64);
102        }
103    };
104    set(&GLOBAL_QUEUE_DEPTH, metrics.global_queue_depth());
105    set(&ALIVE_TASKS, metrics.num_alive_tasks());
106    set(&BLOCKING_THREADS, metrics.num_blocking_threads());
107    set(&IDLE_BLOCKING_THREADS, metrics.num_idle_blocking_threads());
108    set(&BLOCKING_QUEUE_DEPTH, metrics.blocking_queue_depth());
109
110    let busy: Duration = (0..metrics.num_workers())
111        .map(|worker| metrics.worker_total_busy_duration(worker))
112        .sum();
113    let previous = last_busy.insert(pool.to_string(), busy).unwrap_or_default();
114    if let Ok(counter) = BUSY_SECONDS.get_metric_with_label_values(&[pool]) {
115        counter.inc_by(busy.saturating_sub(previous).as_secs_f64());
116    }
117}
118
119static METRICS_SAMPLER: Once = Once::new();
120
121/// Starts the thread that samples every runtime's metrics once per second.
122fn ensure_metrics_sampler() {
123    METRICS_SAMPLER.call_once(|| {
124        std::thread::Builder::new()
125            .name("runtime metrics sampler".to_string())
126            .spawn(|| {
127                let mut last_busy = HashMap::new();
128                loop {
129                    std::thread::sleep(Duration::from_secs(1));
130                    if let Some(main) = try_get_main_runtime() {
131                        sample_runtime_metrics(&mut last_busy, "main", &main);
132                    }
133                    let handles: Vec<(String, Handle)> = RUNTIMES
134                        .lock()
135                        .iter()
136                        .map(|(name, runtime)| (name.clone(), runtime.handle().clone()))
137                        .collect();
138                    for (name, handle) in handles {
139                        sample_runtime_metrics(&mut last_busy, &name, &handle);
140                    }
141                }
142            })
143            .expect("create runtime metrics sampler thread");
144    });
145}
146
147static RUNTIMES: LazyLock<Mutex<HashMap<String, Runtime>>> =
148    LazyLock::new(|| Mutex::new(HashMap::new()));
149
150pub fn get_named_runtime(name: &str) -> Option<Runtime> {
151    RUNTIMES.lock().get(name).cloned()
152}
153
154pub static MAIN_RUNTIME: Mutex<Option<tokio::runtime::Handle>> = Mutex::new(None);
155
156pub fn assign_main_runtime(handle: tokio::runtime::Handle) {
157    MAIN_RUNTIME.lock().replace(handle);
158    ensure_metrics_sampler();
159}
160
161pub fn get_main_runtime() -> tokio::runtime::Handle {
162    MAIN_RUNTIME.lock().as_ref().map(|r| r.clone()).unwrap()
163}
164
165/// Returns the main runtime's handle, or `None` before
166/// `assign_main_runtime` has run, which is the case in unit tests.
167pub fn try_get_main_runtime() -> Option<tokio::runtime::Handle> {
168    MAIN_RUNTIME.lock().clone()
169}
170
171/// Spawn a named future onto the main runtime, or onto the current runtime
172/// when the main runtime is unassigned (eg: in unit tests).
173pub fn spawn_on_main<FUT, N: AsRef<str>>(
174    name: N,
175    fut: FUT,
176) -> std::io::Result<JoinHandle<FUT::Output>>
177where
178    FUT: Future + Send + 'static,
179    FUT::Output: Send,
180{
181    let builder = tokio::task::Builder::new().name(name.as_ref());
182    match try_get_main_runtime() {
183        Some(handle) => builder.spawn_on(fut, &handle),
184        None => builder.spawn(fut),
185    }
186}
187
188static LOCALSET_THREADS: AtomicUsize = AtomicUsize::new(0);
189
190pub fn set_localset_threads(n: usize) {
191    LOCALSET_THREADS.store(n, Ordering::SeqCst);
192}
193
194struct RuntimeInner {
195    tokio_runtime: tokio::runtime::Runtime,
196    n_threads: usize,
197    name_prefix: String,
198}
199
200#[cfg(target_os = "linux")]
201fn runtimes_by_name() -> BTreeMap<String, Runtime> {
202    RUNTIMES
203        .lock()
204        .iter()
205        .map(|(name, rt)| (name.clone(), rt.clone()))
206        .collect()
207}
208
209#[cfg(not(target_os = "linux"))]
210pub async fn dump_all_runtimes(_timeout_duration: Duration) -> String {
211    "Runtime state dumping is not supported on this system".into()
212}
213
214// NOTE: at the time of writing, calling this once will prevent a
215// subsequent graceful shutdown from completing.
216//
217// You will need to call this multiple times to allow the graceful
218// shutdown to "clock through" and finish successfully.
219// I do not know what exactly causes that stutter/stickiness.
220#[cfg(target_os = "linux")]
221pub async fn dump_all_runtimes(timeout_duration: Duration) -> String {
222    let runtimes = runtimes_by_name();
223    let mut dumps = vec![];
224
225    async fn collect_dump(
226        label: &str,
227        handle: &tokio::runtime::Handle,
228        timeout_duration: Duration,
229    ) -> String {
230        match tokio::time::timeout(timeout_duration, handle.dump()).await {
231            Err(_) => format!("Runtime {label}: Timeout while collecting runtime dump"),
232            Ok(dump) => {
233                let label = label.to_string();
234                match tokio::task::spawn_blocking(move || {
235                    let mut output = format!("Runtime: {label}\n");
236                    for (i, task) in dump.tasks().iter().enumerate() {
237                        let trace = task.trace();
238                        writeln!(&mut output, "{label} TASK {i}:\n{trace}").ok();
239                    }
240                    output
241                })
242                .await
243                .map_err(|err| format!("spawn_blocking: join failed: {err:#}"))
244                {
245                    Ok(s) | Err(s) => s,
246                }
247            }
248        }
249    }
250
251    dumps.push(collect_dump("main", &get_main_runtime(), timeout_duration).await);
252    for (label, rt) in runtimes {
253        dumps.push(collect_dump(&label, rt.handle(), timeout_duration).await);
254    }
255
256    dumps.join("\n\n")
257}
258
259#[derive(Clone)]
260pub struct Runtime {
261    inner: Arc<RuntimeInner>,
262}
263
264impl Drop for RuntimeInner {
265    fn drop(&mut self) {
266        let name = self.name_prefix.as_str();
267        PARKED_THREADS.remove_label_values(&[name]).ok();
268        NUM_THREADS.remove_label_values(&[name]).ok();
269        GLOBAL_QUEUE_DEPTH.remove_label_values(&[name]).ok();
270        ALIVE_TASKS.remove_label_values(&[name]).ok();
271        BUSY_SECONDS.remove_label_values(&[name]).ok();
272        BLOCKING_THREADS.remove_label_values(&[name]).ok();
273        IDLE_BLOCKING_THREADS.remove_label_values(&[name]).ok();
274        BLOCKING_QUEUE_DEPTH.remove_label_values(&[name]).ok();
275    }
276}
277
278impl Runtime {
279    pub fn new<F>(
280        name_prefix: &str,
281        default_size: F,
282        configured_size: &AtomicUsize,
283    ) -> anyhow::Result<Self>
284    where
285        F: FnOnce(usize) -> usize,
286    {
287        // `main` is the label the sampler assigns to the main runtime. A named
288        // pool using that name would record its metrics under the same
289        // `pool="main"` label, mixing its numbers into the main runtime's series.
290        if name_prefix == "main" {
291            anyhow::bail!("thread pool runtime name `main` is reserved for the main runtime");
292        }
293
294        let env_name = format!("KUMOD_{}_THREADS", name_prefix.to_uppercase());
295        let n_threads = match std::env::var(env_name) {
296            Ok(n) => n.parse()?,
297            Err(_) => {
298                let configured = configured_size.load(Ordering::SeqCst);
299                if configured == 0 {
300                    let cpus = available_parallelism()?;
301                    (default_size)(cpus).max(1)
302                } else {
303                    configured
304                }
305            }
306        };
307
308        let num_parked = PARKED_THREADS.get_metric_with_label_values(&[name_prefix])?;
309        let num_threads = NUM_THREADS.get_metric_with_label_values(&[name_prefix])?;
310        num_threads.set(n_threads as i64);
311
312        let next_id = Arc::new(AtomicUsize::new(0));
313
314        let tokio_runtime = tokio::runtime::Builder::new_multi_thread()
315            .enable_io()
316            .enable_time()
317            .worker_threads(n_threads)
318            .event_interval(
319                std::env::var("KUMOD_EVENT_INTERVAL")
320                    .ok()
321                    .and_then(|n| n.parse().ok())
322                    .unwrap_or(61),
323            )
324            .max_io_events_per_tick(
325                std::env::var("KUMOD_IO_EVENTS_PER_TICK")
326                    .ok()
327                    .and_then(|n| n.parse().ok())
328                    .unwrap_or(1024),
329            )
330            .on_thread_park({
331                let num_parked = num_parked.clone();
332                move || {
333                    kumo_server_memory::purge_thread_cache();
334                    num_parked.inc();
335                }
336            })
337            .thread_name_fn({
338                let name_prefix = name_prefix.to_string();
339                let next_id = next_id.clone();
340                move || {
341                    let id = next_id.fetch_add(1, Ordering::SeqCst);
342                    format!("{name_prefix}-{id}")
343                }
344            })
345            .max_blocking_threads(
346                std::env::var(format!(
347                    "KUMOD_{}_MAX_BLOCKING_THREADS",
348                    name_prefix.to_uppercase()
349                ))
350                .ok()
351                .and_then(|n| n.parse().ok())
352                .unwrap_or(512),
353            )
354            .on_thread_unpark({
355                let num_parked = num_parked.clone();
356                move || {
357                    num_parked.dec();
358                }
359            })
360            .build()?;
361
362        let runtime = Self {
363            inner: Arc::new(RuntimeInner {
364                tokio_runtime,
365                n_threads,
366                name_prefix: name_prefix.to_string(),
367            }),
368        };
369
370        let mut runtimes = RUNTIMES.lock();
371        if runtimes.contains_key(name_prefix) {
372            anyhow::bail!("thread pool runtime with name `{name_prefix}` already exists!");
373        }
374
375        runtimes.insert(name_prefix.to_string(), runtime.clone());
376        drop(runtimes);
377
378        ensure_metrics_sampler();
379        Ok(runtime)
380    }
381
382    pub fn handle(&self) -> &tokio::runtime::Handle {
383        self.inner.tokio_runtime.handle()
384    }
385
386    pub fn get_num_threads(&self) -> usize {
387        self.inner.n_threads
388    }
389
390    /// Spawn a future into this runtime
391    pub fn spawn<FUT, N: AsRef<str>>(
392        &self,
393        name: N,
394        fut: FUT,
395    ) -> std::io::Result<JoinHandle<FUT::Output>>
396    where
397        FUT: Future + Send + 'static,
398        FUT::Output: Send,
399    {
400        tokio::task::Builder::new()
401            .name(name.as_ref())
402            .spawn_on(fut, self.handle())
403    }
404}
405
406/// Schedule func to run in the main runtime pool,
407/// which is named "localset" for legacy reasons.
408pub fn rt_spawn<FUT, N: AsRef<str>>(name: N, fut: FUT) -> std::io::Result<JoinHandle<FUT::Output>>
409where
410    FUT: Future + Send + 'static,
411    FUT::Output: Send,
412{
413    tokio::task::Builder::new()
414        .name(name.as_ref())
415        .spawn_on(fut, RUNTIME.handle())
416}
417
418/// Spawn a future as a task with a name.
419/// The task is spawned into the current tokio runtime.
420pub fn spawn<FUT, N: AsRef<str>>(name: N, fut: FUT) -> std::io::Result<JoinHandle<FUT::Output>>
421where
422    FUT: Future + Send + 'static,
423    FUT::Output: Send,
424{
425    tokio::task::Builder::new().name(name.as_ref()).spawn(fut)
426}
427
428/// Run a blocking function in the worker thread pool associated
429/// with the current tokio runtime.
430pub fn spawn_blocking<F, N, R>(name: N, func: F) -> std::io::Result<JoinHandle<R>>
431where
432    F: FnOnce() -> R + Send + 'static,
433    R: Send + 'static,
434    N: AsRef<str>,
435{
436    tokio::task::Builder::new()
437        .name(name.as_ref())
438        .spawn_blocking(func)
439}
440
441/// Run a blocking function in the worker thread pool associated
442/// with the provided tokio runtime.
443pub fn spawn_blocking_on<F, N, R>(
444    name: N,
445    func: F,
446    runtime: &Handle,
447) -> std::io::Result<JoinHandle<R>>
448where
449    F: FnOnce() -> R + Send + 'static,
450    R: Send + 'static,
451    N: AsRef<str>,
452{
453    tokio::task::Builder::new()
454        .name(name.as_ref())
455        .spawn_blocking_on(func, runtime)
456}
457
458pub fn available_parallelism() -> anyhow::Result<usize> {
459    match std::env::var("KUMO_AVAILABLE_PARALLELISM") {
460        Ok(n) => n
461            .parse()
462            .context("failed to parse KUMO_AVAILABLE_PARALLELISM as a number"),
463        Err(_) => Ok(std::thread::available_parallelism()
464            .context("failed to get available_parallelism")?
465            .get()),
466    }
467}
468
469/// Decide how long to wait, if at all, before retrying after an error from
470/// `accept()`.
471///
472/// Returns `None` for connection-level errors (the peer went away between the
473/// kernel queuing the connection and our accepting it): retry these
474/// immediately. Returns a pause for everything else, such as file-descriptor
475/// exhaustion (EMFILE/ENFILE): wait out the returned duration before
476/// retrying these, since they persist across calls until some other
477/// connection closes or a resource frees up.
478pub fn accept_error_pause(err: &std::io::Error) -> Option<Duration> {
479    use std::io::ErrorKind;
480    match err.kind() {
481        ErrorKind::ConnectionRefused
482        | ErrorKind::ConnectionAborted
483        | ErrorKind::ConnectionReset => None,
484        _ => Some(Duration::from_secs(1)),
485    }
486}
487
488#[cfg(test)]
489mod tests {
490    use super::*;
491
492    #[test]
493    fn accept_error_pause_backs_off_on_fd_exhaustion() {
494        // EMFILE maps to an uncategorized ErrorKind on most platforms. The
495        // classifier must still pause rather than spin.
496        let emfile = std::io::Error::from_raw_os_error(libc::EMFILE);
497        assert_eq!(accept_error_pause(&emfile), Some(Duration::from_secs(1)));
498    }
499}