Skip to main content

reth_tasks/
utils.rs

1//! Task utility functions.
2
3use reth_concurrency::sync::thread;
4
5#[doc(hidden)]
6pub use reth_concurrency::sync::Once;
7pub use thread_priority::{self, *};
8
9/// Runs the given closure exactly once per call site.
10///
11/// Each invocation expands to its own `static Once`, so two `once!` calls in the same function
12/// are independent. Useful for one-time thread setup (priority, affinity) on threads that may
13/// be re-entered (e.g. tokio blocking pool).
14#[macro_export]
15macro_rules! once {
16    ($e:expr) => {{
17        static ONCE: $crate::utils::Once = $crate::utils::Once::new();
18        ONCE.call_once($e);
19    }};
20}
21
22/// Increases the current thread's priority.
23///
24/// Tries [`ThreadPriority::Max`] first. If that fails (e.g. missing `CAP_SYS_NICE`),
25/// falls back to a moderate bump via [`ThreadPriority::Crossplatform`] (~5 nice points
26/// on unix). Failures are logged at `debug` level.
27pub fn increase_thread_priority() {
28    let thread_name = thread::current().name().unwrap_or("unnamed").to_string();
29    if let Err(err) = ThreadPriority::Max.set_for_current() {
30        tracing::debug!(%thread_name, ?err, "failed to set max thread priority, trying moderate bump; grant CAP_SYS_NICE to the process to enable this");
31        // Crossplatform value 62/99 ≈ nice -5 on unix.
32        let fallback = ThreadPriority::Crossplatform(
33            ThreadPriorityValue::try_from(62u8).expect("62 is within the valid 0..100 range"),
34        );
35        if let Err(err) = fallback.set_for_current() {
36            tracing::debug!(%thread_name, ?err, "failed to set moderate thread priority");
37        }
38    }
39}
40
41/// Deprioritizes known background threads spawned by third-party libraries (`tracing-appender`,
42/// `reqwest`) by scanning `/proc/<pid>/task/` for matching thread names and setting `SCHED_IDLE`
43/// scheduling policy on them.
44///
45/// This is a hack: these threads are spawned by libraries that do not expose a way to hook into
46/// thread initialization or expose the TIDs, so we have to discover them after the fact by
47/// reading `/proc`.
48///
49/// Should be called once after tracing is initialized.
50///
51/// No-op on non-Linux platforms.
52#[allow(clippy::missing_const_for_fn)]
53pub fn deprioritize_background_threads() {
54    #[cfg(target_os = "linux")]
55    _deprioritize_background_threads();
56}
57
58/// Thread name prefixes to deprioritize.
59///
60/// Do not re-add the OTLP span exporter (`OpenTelemetry.T`) to avoid CPU spinning.
61/// See <https://github.com/paradigmxyz/reth/pull/27370>.
62#[cfg(target_os = "linux")]
63const DEPRIORITIZE_THREAD_PREFIXES: &[&str] = &["tracing-appende", "reqwest-interna"];
64
65#[cfg(target_os = "linux")]
66fn _deprioritize_background_threads() {
67    let pid = std::process::id();
68    let task_dir = format!("/proc/{pid}/task");
69
70    let entries = match std::fs::read_dir(&task_dir) {
71        Ok(entries) => entries,
72        Err(err) => {
73            tracing::debug!(%err, "failed to read /proc task directory");
74            return;
75        }
76    };
77
78    for entry in entries.filter_map(Result::ok) {
79        let tid_str = entry.file_name();
80        let Some(tid_str) = tid_str.to_str() else { continue };
81        let Ok(tid) = tid_str.parse::<i32>() else { continue };
82
83        let comm_path = format!("{task_dir}/{tid_str}/comm");
84        let comm = match std::fs::read_to_string(&comm_path) {
85            Ok(c) => c,
86            Err(_) => continue,
87        };
88        let comm = comm.trim();
89
90        if !DEPRIORITIZE_THREAD_PREFIXES.iter().any(|prefix| comm.starts_with(prefix)) {
91            continue;
92        }
93
94        // SCHED_IDLE is the lowest-priority scheduling class. The kernel will only schedule these
95        // threads when no other (SCHED_OTHER/SCHED_BATCH/RT) threads need the CPU.
96        // SAFETY: sched_setscheduler is safe to call with a valid TID.
97        unsafe {
98            let param = libc::sched_param { sched_priority: 0 };
99            if libc::sched_setscheduler(tid, libc::SCHED_IDLE, std::ptr::from_ref(&param)) != 0 {
100                tracing::debug!(
101                    tid,
102                    comm,
103                    err = std::io::Error::last_os_error().to_string(),
104                    "failed to set SCHED_IDLE"
105                );
106            }
107        }
108
109        tracing::debug!(tid, comm, "deprioritized background thread (SCHED_IDLE)");
110    }
111}