1#![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
37pub const QUIET: Duration = Duration::from_secs(30);
39
40const LOOK: Duration = Duration::from_millis(500);
42
43#[cfg(target_os = "linux")]
45const MOST_STACK_TEXT: usize = 256 * 1024;
46
47#[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 threshold: Duration,
58 started: Instant,
60 doing: Mutex<BTreeMap<u64, (Cow<'static, str>, Duration)>>,
62 next: AtomicU64,
63 beat: AtomicU64,
66 beating: AtomicBool,
67}
68
69pub 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
97pub 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 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#[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#[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 let _named: Cow<'static, str> = what.into();
156 None::<u64>
157 };
158 Doing(number)
159}
160
161pub 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 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
224fn 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 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#[cfg(target_os = "linux")]
249fn stacks() -> String {
250 let pid = std::process::id().to_string();
251 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 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#[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 #[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 #[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 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 #[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}