Skip to main content

tilo_rt/
stall.rs

1//! What a process was doing when it stalled.
2//!
3//! A server that stops answering for half a minute says nothing on its own: its log shows the
4//! silence and the reconnects after it, never what held it. A process that [`watch`]es names the
5//! work it does ([`doing`]) and keeps a heartbeat on its runtime ([`heartbeat`]); when a piece of
6//! work takes longer than the watch's threshold, or the heartbeat stops, a thread of its own logs
7//! the work outstanding, each thread's state as the kernel has it, and every thread's stack,
8//! read with `eu-stack` (or `gdb`) on this process. Once per stall: it logs again only after the
9//! process answered again, and at most once in [`QUIET`].
10//!
11//! Nothing is watched in a process that never called [`watch`]: [`doing`] then costs a load.
12//! A page has no threads to watch with and never watches: what watches is not compiled there,
13//! because std has no clock in a browser page and a read of one that could never run is still a
14//! read the page's lint refuses.
15#![cfg_attr(
16    target_family = "wasm",
17    allow(
18        dead_code,
19        reason = "a page has no thread to watch with; it names its work all the same"
20    )
21)]
22
23use std::borrow::Cow;
24#[cfg(not(target_family = "wasm"))]
25use std::collections::BTreeMap;
26#[cfg(not(target_family = "wasm"))]
27use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
28#[cfg(not(target_family = "wasm"))]
29use std::sync::{Mutex, OnceLock};
30use std::time::Duration;
31#[cfg(not(target_family = "wasm"))]
32use std::time::Instant;
33
34#[cfg(not(target_family = "wasm"))]
35use tilo_lock::MutexRecover as _;
36
37/// The least time between two reports: a stall that clears and comes back at once is one stall.
38pub const QUIET: Duration = Duration::from_secs(30);
39
40/// How often the watch looks, and the heartbeat beats.
41const LOOK: Duration = Duration::from_millis(500);
42
43/// The most of the stacks' text one report carries.
44#[cfg(target_os = "linux")]
45const MOST_STACK_TEXT: usize = 256 * 1024;
46
47/// The longest a stack reader may take before it is given up.
48#[cfg(target_os = "linux")]
49const STACK_READ: Duration = Duration::from_secs(20);
50
51#[cfg(not(target_family = "wasm"))]
52static WATCH: OnceLock<Watch> = OnceLock::new();
53
54#[cfg(not(target_family = "wasm"))]
55struct Watch {
56    /// How long a piece of work may take, or the heartbeat stay quiet, before it is a stall.
57    threshold: Duration,
58    /// When the watch started: the clock [`Self::beat`] and the work's starts count from.
59    started: Instant,
60    /// The work under way, by its number: what it is and when it began.
61    doing: Mutex<BTreeMap<u64, (Cow<'static, str>, Duration)>>,
62    next: AtomicU64,
63    /// When the heartbeat last beat, in milliseconds since [`Self::started`]; 0 before it ever
64    /// did, which is no stall.
65    beat: AtomicU64,
66    beating: AtomicBool,
67}
68
69/// Start watching this process for stalls of `threshold` and longer. Further calls do nothing.
70/// A process on the web has no threads to watch with, and is never watched.
71pub fn watch(threshold: Duration) {
72    #[cfg(not(target_family = "wasm"))]
73    {
74        let mut first = false;
75        let watch = WATCH.get_or_init(|| {
76            first = true;
77            Watch {
78                threshold,
79                started: Instant::now(),
80                doing: Mutex::default(),
81                next: AtomicU64::new(0),
82                beat: AtomicU64::new(0),
83                beating: AtomicBool::new(false),
84            }
85        });
86        if first {
87            let started = crate::spawn_thread("stall-watch", move || watch.look());
88            if let Err(error) = started {
89                tracing::warn!(%error, "the stall watch could not start");
90            }
91        }
92    }
93    #[cfg(target_family = "wasm")]
94    let _ = threshold;
95}
96
97/// Keep a heartbeat on the runtime `handle` drives: a task that marks every half second that
98/// the runtime ran it. A runtime whose workers are all held stops beating, and the watch says
99/// so. Nothing without [`watch`].
100pub fn heartbeat(handle: &tokio::runtime::Handle) {
101    #[cfg(not(target_family = "wasm"))]
102    {
103        let Some(watch) = WATCH.get() else {
104            return;
105        };
106        if watch.beating.swap(true, Ordering::AcqRel) {
107            return;
108        }
109        handle.spawn(async move {
110            // A runtime that shuts down drops this task: its heartbeat ends with it, and the
111            // next runtime given one beats in its place. One left marked as beating would read
112            // as a runtime quiet for ever, and hide every later stall behind that one.
113            let _ends = Unbeat(watch);
114            loop {
115                watch
116                    .beat
117                    .store(watch.since_start().max(1), Ordering::Release);
118                crate::sleep(LOOK).await;
119            }
120        });
121    }
122    #[cfg(target_family = "wasm")]
123    let _ = handle;
124}
125
126/// What ends a runtime's heartbeat when its task is dropped with its runtime.
127#[cfg(not(target_family = "wasm"))]
128struct Unbeat(&'static Watch);
129
130#[cfg(not(target_family = "wasm"))]
131impl Drop for Unbeat {
132    fn drop(&mut self) {
133        self.0.beat.store(0, Ordering::Release);
134        self.0.beating.store(false, Ordering::Release);
135    }
136}
137
138/// The work `what` is under way until the answer is dropped: past the watch's threshold it is
139/// a stall, and named in the report. Nothing without [`watch`].
140#[must_use = "the work is watched until this is dropped"]
141pub fn doing(what: impl Into<Cow<'static, str>>) -> Doing {
142    #[cfg(not(target_family = "wasm"))]
143    let number = WATCH.get().map(|watch| {
144        let number = watch.next.fetch_add(1, Ordering::Relaxed);
145        watch
146            .doing
147            .lock_recover()
148            .insert(number, (what.into(), watch.started.elapsed()));
149        number
150    });
151    #[cfg(target_family = "wasm")]
152    let number = {
153        // A page watches nothing and never reports a stall: the name the work goes by is only
154        // dropped here.
155        let _named: Cow<'static, str> = what.into();
156        None::<u64>
157    };
158    Doing(number)
159}
160
161/// A piece of work under watch ([`doing`]), until it is dropped.
162pub struct Doing(Option<u64>);
163
164impl Drop for Doing {
165    fn drop(&mut self) {
166        #[cfg(not(target_family = "wasm"))]
167        if let (Some(number), Some(watch)) = (self.0, WATCH.get()) {
168            watch.doing.lock_recover().remove(&number);
169        }
170    }
171}
172
173#[cfg(not(target_family = "wasm"))]
174impl Watch {
175    fn since_start(&self) -> u64 {
176        u64::try_from(self.started.elapsed().as_millis()).unwrap_or(u64::MAX)
177    }
178
179    /// The stall now, said as its lines: the work longer than the threshold, and how long the
180    /// heartbeat was quiet when it is longer; `None` when nothing is stalled.
181    fn stalled(&self) -> Option<Vec<String>> {
182        let now = self.started.elapsed();
183        let mut lines: Vec<String> = self
184            .doing
185            .lock_recover()
186            .values()
187            .filter_map(|(what, began)| {
188                let took = now.saturating_sub(*began);
189                (took >= self.threshold).then(|| format!("{what}: {} ms so far", took.as_millis()))
190            })
191            .collect();
192        let beat = self.beat.load(Ordering::Acquire);
193        let quiet = self.since_start().saturating_sub(beat);
194        if beat > 0 && Duration::from_millis(quiet) >= self.threshold {
195            lines.push(format!("the runtime's heartbeat: quiet for {quiet} ms"));
196        }
197        (!lines.is_empty()).then_some(lines)
198    }
199
200    fn look(&self) {
201        let mut reported: Option<Instant> = None;
202        let mut in_stall = false;
203        loop {
204            std::thread::sleep(LOOK);
205            let Some(lines) = self.stalled() else {
206                in_stall = false;
207                continue;
208            };
209            if in_stall || reported.is_some_and(|at| at.elapsed() < QUIET) {
210                continue;
211            }
212            in_stall = true;
213            reported = Some(Instant::now());
214            tracing::warn!(
215                outstanding = %lines.join("; "),
216                threads = %threads(),
217                stacks = %stacks(),
218                "this process stalled; what it was doing"
219            );
220        }
221    }
222}
223
224/// Each thread of this process with its state and what the kernel says it waits in: what a
225/// stall looks like without a stack reader.
226fn threads() -> String {
227    let Ok(tasks) = std::fs::read_dir("/proc/self/task") else {
228        return "unreadable".into();
229    };
230    let mut lines: Vec<String> = tasks
231        .flatten()
232        .filter_map(|task| {
233            let dir = task.path();
234            let stat = std::fs::read_to_string(dir.join("stat")).ok()?;
235            // The name is in parentheses and may hold blanks; the state follows it.
236            let (name, rest) = stat.split_once(" (")?.1.rsplit_once(") ")?;
237            let state = rest.split(' ').next().unwrap_or("?");
238            let wchan = std::fs::read_to_string(dir.join("wchan")).unwrap_or_default();
239            let tid = task.file_name().to_string_lossy().into_owned();
240            Some(format!("{tid} {name} {state} {wchan}"))
241        })
242        .collect();
243    lines.sort();
244    lines.join(" | ")
245}
246
247/// Every thread's stack, read by a debugger this process lets attach to it for the read.
248#[cfg(target_os = "linux")]
249fn stacks() -> String {
250    let pid = std::process::id().to_string();
251    // A process may only be traced by its ancestors unless it says otherwise.
252    // SAFETY: PR_SET_PTRACER takes a pid (here: any) and touches no memory.
253    unsafe {
254        libc::prctl(libc::PR_SET_PTRACER, libc::PR_SET_PTRACER_ANY, 0, 0, 0);
255    }
256    let readers: [(&str, Vec<&str>); 2] = [
257        ("eu-stack", vec!["-p", &pid]),
258        (
259            "gdb",
260            vec!["-p", &pid, "-batch", "-ex", "thread apply all bt"],
261        ),
262    ];
263    let mut said = Vec::new();
264    for (reader, args) in readers {
265        match read_with(reader, &args) {
266            Ok(text) => {
267                said.clear();
268                said.push(text);
269                break;
270            }
271            Err(why) => said.push(format!("{reader}: {why}")),
272        }
273    }
274    // SAFETY: as above; 0 takes the permission back.
275    unsafe {
276        libc::prctl(libc::PR_SET_PTRACER, 0, 0, 0, 0);
277    }
278    let mut text = said.join("\n");
279    if text.len() > MOST_STACK_TEXT {
280        let end = (0..=MOST_STACK_TEXT)
281            .rev()
282            .find(|end| text.is_char_boundary(*end))
283            .unwrap_or(0);
284        text.truncate(end);
285        text.push_str("\n…");
286    }
287    text
288}
289
290#[cfg(not(target_os = "linux"))]
291fn stacks() -> String {
292    "no stack reader on this platform".into()
293}
294
295/// What `reader` with `args` printed, given up after [`STACK_READ`].
296#[cfg(target_os = "linux")]
297fn read_with(reader: &str, args: &[&str]) -> Result<String, String> {
298    use std::io::Read as _;
299    let mut child = std::process::Command::new(reader)
300        .args(args)
301        .stdin(std::process::Stdio::null())
302        .stdout(std::process::Stdio::piped())
303        .stderr(std::process::Stdio::piped())
304        .spawn()
305        .map_err(|error| error.to_string())?;
306    let began = Instant::now();
307    let status = loop {
308        if let Some(status) = child.try_wait().map_err(|error| error.to_string())? {
309            break status;
310        }
311        if began.elapsed() >= STACK_READ {
312            let _ = child.kill();
313            let _ = child.wait();
314            return Err(format!("gave up after {} s", STACK_READ.as_secs()));
315        }
316        std::thread::sleep(Duration::from_millis(50));
317    };
318    let mut out = String::new();
319    if let Some(mut stdout) = child.stdout.take() {
320        let _ = stdout.read_to_string(&mut out);
321    }
322    if out.trim().is_empty() || !status.success() && !out.contains("TID") && !out.contains("Thread")
323    {
324        let mut err = String::new();
325        if let Some(mut stderr) = child.stderr.take() {
326            let _ = stderr.read_to_string(&mut err);
327        }
328        return Err(format!("{status}: {}", err.trim()));
329    }
330    Ok(out)
331}
332
333#[cfg(test)]
334mod tests {
335    use super::*;
336
337    /// Work longer than the threshold is a stall, named with how long it ran; work that ended
338    /// is not, and neither is a heartbeat that never beat.
339    #[test]
340    fn work_past_the_threshold_is_a_stall_and_names_itself() {
341        let watch = Watch {
342            threshold: Duration::from_millis(50),
343            started: Instant::now(),
344            doing: Mutex::default(),
345            next: AtomicU64::new(0),
346            beat: AtomicU64::new(0),
347            beating: AtomicBool::new(false),
348        };
349        watch
350            .doing
351            .lock_recover()
352            .insert(0, ("a commit of the tree".into(), Duration::ZERO));
353        assert!(watch.stalled().is_none(), "not yet past the threshold");
354        std::thread::sleep(Duration::from_millis(80));
355        let lines = watch.stalled().expect("past the threshold it is a stall");
356        assert!(lines[0].starts_with("a commit of the tree: "), "{lines:?}");
357        watch.doing.lock_recover().clear();
358        assert!(watch.stalled().is_none(), "work that ended is no stall");
359        watch.beat.store(1, Ordering::Release);
360        let lines = watch.stalled().expect("a quiet heartbeat is a stall");
361        assert!(
362            lines[0].starts_with("the runtime's heartbeat: quiet for"),
363            "{lines:?}"
364        );
365    }
366
367    /// A runtime that shuts down takes its heartbeat with it, and is no stall from then on; the
368    /// next runtime given one beats in its place, so a stall of that one is heard.
369    #[test]
370    fn a_heartbeat_ends_with_its_runtime_and_the_next_one_beats() {
371        watch(Duration::from_secs(3600));
372        let watching = WATCH.get().unwrap();
373        // A runtime driven for a moment, while its heartbeat is waited for.
374        let beats = |runtime: &tokio::runtime::Runtime| {
375            heartbeat(runtime.handle());
376            std::thread::scope(|scope| {
377                scope.spawn(|| runtime.block_on(crate::sleep(Duration::from_millis(300))));
378                let started = Instant::now();
379                while watching.beat.load(Ordering::Acquire) == 0 {
380                    assert!(started.elapsed() < Duration::from_secs(10), "no beat");
381                    std::thread::sleep(Duration::from_millis(10));
382                }
383            });
384        };
385        let runtime = || {
386            tokio::runtime::Builder::new_current_thread()
387                .enable_all()
388                .build()
389                .unwrap()
390        };
391        let first = runtime();
392        beats(&first);
393        first.shutdown_timeout(Duration::from_secs(1));
394        assert_eq!(
395            watching.beat.load(Ordering::Acquire),
396            0,
397            "a runtime that shut down still beats"
398        );
399        assert!(!watching.beating.load(Ordering::Acquire));
400        let next = runtime();
401        beats(&next);
402        next.shutdown_timeout(Duration::from_secs(1));
403    }
404
405    /// The threads' states read on this machine, one per thread.
406    #[cfg(target_os = "linux")]
407    #[test]
408    fn every_thread_is_named_with_its_state() {
409        let said = threads();
410        assert!(said.split(" | ").count() >= 1, "{said}");
411        assert!(said.contains(&std::process::id().to_string()) || !said.is_empty());
412    }
413}