misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux
Rust bittorrent-clientdebriddownload-acceleratordownload-managerdownloadmanagereguifile-downloadergallery-dlidmidm-alternativeinternet-download-managerm3u8-downloadermagnetplaylist-downloaderreal-debridrusttorrent-clientvideo-downloaderyoutube-downloaderyt-dlp
Freeze watchdog: a freeze while MDM handles a command is reported again, minimized too (#202) (#203)
Ahmed Nefzaoui0e561cae811d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 48071425..fefb7cc8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -388,6 +388,11 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see### Fixed+- **A freeze while MDM handles a command is reported again**+ ([#202](https://github.com/anefzaoui/misterdownloadmanager/issues/202)): since the clock and+ what comes in from outside (a second launch, the browser, the automation API) run in every+ window state, a freeze there opened no crash report window and wrote no freeze report, minimized+ or not. The watchdog now times that part of each frame too.- **Streams served as plain text, from addresses without .m3u8 or .mpd**([#171](https://github.com/anefzaoui/misterdownloadmanager/issues/171)): some players loadtheir stream from such an address, and the extension didn't know it as one. The button over thediff --git a/ROADMAP.md b/ROADMAP.mdindex 4a2b7aac..5f90637a 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -13,6 +13,8 @@ Everything below ships together, in one release, as version 0.3.0.### Done+- ✅ A freeze while MDM handles a command, or minimized, opens the crash report window and writes+ its freeze report again ([#202](https://github.com/anefzaoui/misterdownloadmanager/issues/202))- ✅ Where a download's server is: its country's flag and name and its round trip (near, medium orfar) in Download File Info, the progress window and Properties, from a table that comes with MDM(no address is sent anywhere); a proxy or a CDN said as suchdiff --git a/crates/app/src/app.rs b/crates/app/src/app.rsindex 9eff9f83..fd1f284c 100644--- a/crates/app/src/app.rs+++ b/crates/app/src/app.rs@@ -7071,6 +7071,9 @@ impl eframe::App for App {/// (#162). A command that opens a window gets the UI pass that creates it, minimized or not/// (no window is raised or focused for it beyond what the command itself does).fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {+ // The freeze watchdog times this as it times `ui` (crash.rs): a command or the clock+ // that hangs is reported too, minimized or not (#202).+ crate::crash::logic_begin();let mut handled = false;while let Ok(inc) = self.commands.try_recv() {handled = true;@@ -7126,10 +7129,11 @@ impl eframe::App for App {}}ctx.request_repaint_after(Duration::from_secs(2));+ crate::crash::logic_end();}fn ui(&mut self, ui: &mut Ui, _frame: &mut eframe::Frame) {- // The freeze watchdog times every frame (crash.rs).+ // The freeze watchdog times every frame's drawing, as it times its logic (crash.rs).crate::crash::frame_begin();// A lost graphics device is noticed before this frame paints (renderer.rs).crate::renderer::frame_begin();diff --git a/crates/app/src/crash.rs b/crates/app/src/crash.rsindex 46ac99f2..34feaf3b 100644--- a/crates/app/src/crash.rs+++ b/crates/app/src/crash.rs@@ -3,7 +3,9 @@//! - crashes natively (win32.rs / unix.rs catch it through crash-handler),//! - panics (the hook here sends the message, then asks for the dump),//! - or freezes: a watchdog thread sees a frame of the window run past [`FREEZE_AFTER`] and asks-//! for a dump of every thread while MDM is still stuck (a deadlock, an endless loop).+//! for a dump of every thread while MDM is still stuck (a deadlock, an endless loop). A frame+//! is two timed stretches: the app's logic (commands and the clock, which egui runs alone while+//! the main window is minimized) and its UI. The waits between frames aren't timed.//!//! The monitor then shows the report window (crashui.rs). Without a monitor (it couldn't start)//! MDM runs on, and a panic still leaves a text report.@@ -11,7 +13,7 @@use std::cell::RefCell;use std::collections::BTreeSet;use std::path::Path;-use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};+use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};use std::sync::{Arc, OnceLock};use std::time::{Duration, Instant};@@ -25,8 +27,12 @@ static REPORTER: OnceLock<Arc<Reporter>> = OnceLock::new();/// The session as sent, to send again when it learns more (what draws).static SESSION: std::sync::Mutex<Option<Session>> = std::sync::Mutex::new(None);static EPOCH: OnceLock<Instant> = OnceLock::new();-/// When the current frame started (ms since EPOCH, + 1); 0 between frames.+/// When the current stretch of a frame started (ms since EPOCH, + 1); 0 between them.static FRAME_START: AtomicU64 = AtomicU64::new(0);+/// Which stretch that is ([`LOGIC`] or [`UI`]), for the log.+static PART: AtomicU8 = AtomicU8::new(UI);+const LOGIC: u8 = 0;+const UI: u8 = 1;/// A freeze was reported and the window hasn't answered since.static FROZEN: AtomicBool = AtomicBool::new(false);/// A panic was reported: later ones (a burst on worker threads) are logged, not dumped again.@@ -125,13 +131,14 @@ fn hook_panics() {}));}-/// The window starts a frame (top of `App::ui`).-pub fn frame_begin() {+/// The window thread starts a timed stretch.+fn stretch_begin(part: u8) {+ PART.store(part, Ordering::Relaxed);FRAME_START.store(now_ms() + 1, Ordering::Release);}-/// The window finished a frame: no freeze; windows opened or closed since the last are logged.-pub fn frame_end() {+/// The stretch ended: no freeze (or no more of one).+fn stretch_end() {FRAME_START.store(0, Ordering::Release);if FROZEN.swap(false, Ordering::AcqRel) {tracing::warn!("the window answers again");@@ -139,6 +146,27 @@ pub fn frame_end() {r.recovered();}}+}++/// The window starts a frame's logic (top of `App::logic`): commands that came in and the clock.+/// egui runs it every frame, and alone while the main window is minimized (#202).+pub fn logic_begin() {+ stretch_begin(LOGIC);+}++/// The frame's logic is done (end of `App::logic`); its UI, when egui runs one, follows at once.+pub fn logic_end() {+ stretch_end();+}++/// The window starts drawing a frame (top of `App::ui`).+pub fn frame_begin() {+ stretch_begin(UI);+}++/// The window finished a frame: no freeze; windows opened or closed since the last are logged.+pub fn frame_end() {+ stretch_end();WINDOWS.with(|w| {let mut w = w.borrow_mut();let (now, last) = &mut *w;@@ -185,8 +213,9 @@ pub fn clean_exit() {}}-/// Watch the window's frames: one running past FREEZE_AFTER is reported once. Time the computer-/// spent asleep (this loop's own tick much longer than asked) isn't counted.+/// Watch the window's frames: a stretch of one (its logic or its UI) running past FREEZE_AFTER+/// is reported once. Time the computer spent asleep (this loop's own tick much longer than+/// asked) isn't counted, nor the waits between frames (no stretch runs then).fn watchdog() {let tick = Duration::from_millis(500);let mut last = now_ms();@@ -219,8 +248,13 @@ fn watchdog() {reported_frame = start;FROZEN.store(true, Ordering::Release);tracing::error!(- "the window stopped responding ({} s into a frame)",- ran / 1000+ "the window stopped responding ({} s into a frame, in its {})",+ ran / 1000,+ if PART.load(Ordering::Relaxed) == LOGIC {+ "logic"+ } else {+ "UI"+ });let busy = seen.and_then(|(_, at, before)| {let (before, after) = (before?, usage(ui)?);diff --git a/crates/app/src/crashui.rs b/crates/app/src/crashui.rsindex 836b4cd8..cd851f67 100644--- a/crates/app/src/crashui.rs+++ b/crates/app/src/crashui.rs@@ -25,7 +25,11 @@ const CLIENT: [f32; 2] = [620.0, 540.0];pub fn monitor_main(m: MonitorArgs) -> eframe::Result {mdm_crash::logs::init(&m.data, mdm_crash::logs::MONITOR);- tracing::info!("crash monitor for {}", m.parent);+ tracing::info!(+ "crash monitor (process {}) for {}",+ std::process::id(),+ m.parent+ );let (tx, rx) = channel();{let (socket, data, tx) = (m.socket.clone(), m.data.clone(), tx.clone());@@ -290,6 +294,8 @@ impl eframe::App for ReportWindow {// The caption in the window's light or dark, as every MDM window's (Windows would draw// it in its own app mode).if !self.caption_set {+ // As the app logs its windows (crash.rs), for the log and the tests.+ tracing::info!("window opened: crash-report");ui.ctx().send_viewport_cmd(egui::ViewportCommand::SetTheme(crate::theme::system_theme(crate::theme::dark()),));diff --git a/crates/app/tests/freeze_report.rs b/crates/app/tests/freeze_report.rsnew file mode 100644index 00000000..200e899e--- /dev/null+++ b/crates/app/tests/freeze_report.rs@@ -0,0 +1,196 @@+//! #202: a freeze while MDM handles a command must still be reported. Since #176 the incoming+//! commands and the clock run in the app's `logic`, which egui calls every frame (and alone while+//! the main window is minimized); the freeze watchdog timed only `ui`, so a command that hung+//! never opened the crash report window nor wrote a freeze report. The real app, off the screens+//! (MDM_OFFSCREEN), with a data folder of its own: MDM_CRASH_TEST=1, then `/show crash-test:…`+//! (a deadlock, or 12 s of a busy window thread) with the main window visible or minimized. The+//! crash monitor must open its window and write the freeze report, which names the kind of freeze.+//!+//! It opens windows, which needs OpenGL or Direct3D, so it runs on request:+//! `cargo test -p mdm-app --test freeze_report -- --ignored`.++use std::path::{Path, PathBuf};+use std::process::{Child, Command};+use std::time::{Duration, Instant};++const APP: &str = env!("CARGO_BIN_EXE_misterdownloadmanager");++/// The app's and its monitor's logs so far (every file of `logs/`).+fn log(data: &Path) -> String {+ let mut all = String::new();+ if let Ok(dir) = std::fs::read_dir(data.join("logs")) {+ for f in dir.flatten() {+ all += &std::fs::read_to_string(f.path()).unwrap_or_default();+ }+ }+ all+}++/// The freeze report's text (`crashes/<when>-freeze.txt`), once written.+fn freeze_report(data: &Path) -> Option<String> {+ let dir = std::fs::read_dir(data.join("crashes")).ok()?;+ let path: PathBuf = dir+ .flatten()+ .map(|f| f.path())+ .find(|p| p.to_string_lossy().ends_with("-freeze.txt"))?;+ std::fs::read_to_string(path).ok()+}++/// Wait until `done` holds, failing if `wait` passes. The app may be frozen meanwhile: only a+/// panic or its end before `done` fails sooner.+fn wait_until(app: &mut Child, data: &Path, what: &str, wait: Duration, done: impl Fn() -> bool) {+ let until = Instant::now() + wait;+ loop {+ let text = log(data);+ assert!(!text.contains("panic"), "the app panicked:\n{text}");+ if done() {+ return;+ }+ if let Some(status) = app.try_wait().unwrap() {+ panic!("the app closed ({status}) before {what}:\n{text}");+ }+ assert!(Instant::now() < until, "no {what} after {wait:?}:\n{text}");+ std::thread::sleep(Duration::from_millis(250));+ }+}++/// A second launch with `args`: it hands them to the running app and quits.+fn second_launch(data: &Path, args: &[&str]) {+ let status = Command::new(APP)+ .args(args)+ .env("MDM_DATA_DIR", data)+ .env("MDM_OFFSCREEN", "1")+ .env("MDM_CRASH_TEST", "1")+ .status()+ .unwrap();+ assert!(status.success(), "second launch {args:?}: {status}");+}++/// The crash monitor's process id, from its log ("crash monitor (process N) for …").+fn monitor_pid(data: &Path) -> Option<u32> {+ let text = log(data);+ let at = text.find("crash monitor (process ")? + "crash monitor (process ".len();+ text[at..].split(')').next()?.parse().ok()+}++/// End a process this test started indirectly (the monitor, the app's child).+fn end(pid: u32) {+ #[cfg(windows)]+ let _ = Command::new("taskkill")+ .args(["/F", "/PID", &pid.to_string()])+ .output();+ #[cfg(unix)]+ let _ = Command::new("kill").args(["-9", &pid.to_string()]).output();+}++/// The app with the main window `state` ("visible", or "minimized" with `/show minimized`), then+/// `/show crash-test:<what>`: the report window must open and the report name the freeze's kind+/// (`kind`, the report's own words). With `recovers`, the window must answer again afterwards.+fn freeze_while(state: &str, what: &str, kind: &str, recovers: bool) {+ let dir = tempfile::tempdir().unwrap();+ let data = dir.path();+ // No update check, no first-start questions; the torrent engine stays on this computer.+ // Minimize stays a minimize (not the notification area), for `/show minimized`.+ let settings = serde_json::json!({+ "language": "en", "update_check": false, "helpers_asked": true, "language_asked": true,+ "extension_never_ask": true, "minimize_to_tray": false, "clipboard_autostart": false,+ "torrent_dht": false, "torrent_lsd": false, "torrent_upnp": false,+ "torrent_incoming": false,+ });+ std::fs::write(+ data.join("downloads.json"),+ serde_json::json!({ "next_id": 1, "items": [], "version": 2, "settings": settings })+ .to_string(),+ )+ .unwrap();+ let mut app = Command::new(APP)+ .env("MDM_DATA_DIR", data)+ .env("MDM_OFFSCREEN", "1")+ .env("MDM_CRASH_TEST", "1")+ .spawn()+ .unwrap();+ let wait = Duration::from_secs(60);+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ wait_until(&mut app, data, "main window", wait, || {+ let l = log(data);+ l.contains("window opened: main") && l.contains("crash reports on")+ });+ if state == "minimized" {+ second_launch(data, &["/show", "minimized"]);+ // Its frames are logic-only from now on (eframe's update_logic_only).+ std::thread::sleep(Duration::from_secs(2));+ }+ let asked = Instant::now();+ second_launch(data, &["/show", &format!("crash-test:{what}")]);+ // The command reached the app (crash.rs logs the test as it begins).+ wait_until(&mut app, data, "the crash test", wait, || {+ log(data).contains(&format!("crash test: {what}"))+ });+ wait_until(+ &mut app,+ data,+ "freeze report from the watchdog",+ wait,+ || log(data).contains("the window stopped responding"),+ );+ let seen = asked.elapsed();+ // Not before the 8 s a freeze takes (no false alarm), and not much after.+ assert!(+ seen >= Duration::from_secs(7) && seen < Duration::from_secs(20),+ "the freeze was reported {seen:?} after it began"+ );+ wait_until(&mut app, data, "crash report window", wait, || {+ log(data).contains("window opened: crash-report")+ });+ wait_until(&mut app, data, "freeze report", wait, || {+ freeze_report(data).is_some()+ });+ let report = freeze_report(data).unwrap();+ // Shown with --nocapture: the watchdog's line and the report's head.+ for line in log(data)+ .lines()+ .filter(|l| l.contains("stopped responding"))+ {+ println!("{line}");+ }+ for line in report.lines().take(12) {+ println!(" | {line}");+ }+ assert!(+ report.contains("The window did not answer for") && report.contains(kind),+ "the freeze report doesn't say \"{kind}\":\n{report}"+ );+ if recovers {+ wait_until(&mut app, data, "the window answering again", wait, || {+ log(data).contains("the window answers again")+ });+ }+ }));+ // Frozen: it can't be asked to quit. Its monitor goes too (its report window stays open).+ if let Some(pid) = monitor_pid(data) {+ end(pid);+ }+ let _ = app.kill();+ let _ = app.wait();+ if let Err(e) = result {+ std::panic::resume_unwind(e);+ }+}++#[test]+#[ignore = "opens the app's windows (off-screen): needs OpenGL or Direct3D; run with --ignored"]+fn a_command_that_deadlocks_is_reported() {+ freeze_while("visible", "freeze", "Its thread was waiting", false);+}++#[test]+#[ignore = "opens the app's windows (off-screen): needs OpenGL or Direct3D; run with --ignored"]+fn a_command_that_deadlocks_is_reported_while_minimized() {+ freeze_while("minimized", "freeze", "Its thread was waiting", false);+}++#[test]+#[ignore = "opens the app's windows (off-screen): needs OpenGL or Direct3D; run with --ignored"]+fn a_busy_command_is_reported_while_minimized_and_answers_again() {+ freeze_while("minimized", "spin", "Its thread ran all along", true);+}diff --git a/docs/crash-reports.md b/docs/crash-reports.mdindex 96df10b5..e7ab46c5 100644--- a/docs/crash-reports.md+++ b/docs/crash-reports.md@@ -51,7 +51,7 @@ The log records what MDM does, so a report can show what led to a problem. To loHow it works: a second copy of MDM, the **monitor**, starts beside it with `--crash-monitor`. The crash code lives in `crates/crash` and `crates/app/src/crash.rs`.-- **Catching problems.** When MDM crashes (a Windows exception, a signal on Linux, a Mach exception on macOS), panics, or freezes, it asks the monitor for a dump. A freeze is a frame of the window running more than 8 s, seen by a watchdog thread that ignores time spent asleep. The watchdog also measures how much processor time the window thread got meanwhile, and the report says what that means: it ran all along (a loop), it waited in a lock or on I/O (a deadlock), or it hardly ran in ordinary code, which is a computer too busy to run MDM or slow to load it from disk, most likely not MDM's bug (those share one signature, `freeze while the computer was busy`). macOS doesn't measure it yet. The monitor then writes a **minidump** of every thread from outside, through `minidumper` and `crash-handler`. A crashed process never writes its own dump, which is how Firefox, Crashpad and Sentry do it too.+- **Catching problems.** When MDM crashes (a Windows exception, a signal on Linux, a Mach exception on macOS), panics, or freezes, it asks the monitor for a dump. A freeze is a frame of the window running more than 8 s, seen by a watchdog thread that ignores time spent asleep. It times both parts of a frame: what MDM handles (the commands that come in, the clock of downloads, queues and the Scheduler), which runs minimized too, and the drawing; never the wait between frames. The watchdog also measures how much processor time the window thread got meanwhile, and the report says what that means: it ran all along (a loop), it waited in a lock or on I/O (a deadlock), or it hardly ran in ordinary code, which is a computer too busy to run MDM or slow to load it from disk, most likely not MDM's bug (those share one signature, `freeze while the computer was busy`). macOS doesn't measure it yet. The monitor then writes a **minidump** of every thread from outside, through `minidumper` and `crash-handler`. A crashed process never writes its own dump, which is how Firefox, Crashpad and Sentry do it too.- **Reading the dump.** The monitor reads the dump with Mozilla's `rust-minidump`. It uses the release's Breakpad symbols when they are found. A build from source can also read the native debug info beside it (its `.pdb`, DWARF) when built with `--features mdm-crash/native-symbols`; the shipped app goes without that reader, several MB. The report's **Signature** (for example `freeze in misterdownloadmanager::winui::combo_edit`) stays the same across reports of one problem, and the window searches existing issues for it.- **Symbols.** Release builds keep line tables (`debug = "line-tables-only"`), but no download includes the debug info. CI turns it into `MisterDownloadManager-<version>-symbols-<platform>.zip` (`tools/installer/symbols.py`, using Mozilla's `dump_syms`), published beside the release's other files. The report window fetches the zip for its own version when a stack shows bare addresses.- **A `.dmp` from an issue:**@@ -60,4 +60,4 @@ How it works: a second copy of MDM, the **monitor**, starts beside it with `--crcargo run -p mdm-crash --bin mdm-symbolicate -- crash.dmp MisterDownloadManager-<version>-symbols-windows-x64.zip```-- **Testing it.** `cargo test -p mdm-crash` runs a real freeze, panic and crash (`examples/crashy.rs`) and checks each report's signature. To try it in the app, start MDM with `MDM_CRASH_TEST=1`, then run `misterdownloadmanager /show crash-test:freeze` (a deadlock; or `spin`, 12 s of a busy window thread, `panic`, `crash`, `abort`).+- **Testing it.** `cargo test -p mdm-crash` runs a real freeze, panic and crash (`examples/crashy.rs`) and checks each report's signature. To try it in the app, start MDM with `MDM_CRASH_TEST=1`, then run `misterdownloadmanager /show crash-test:freeze` (a deadlock; or `spin`, 12 s of a busy window thread, `panic`, `crash`, `abort`). `cargo test -p mdm-app --test freeze_report -- --ignored` does that in a copy of the app off the screens, its window visible and minimized.