diff --git a/README.md b/README.md index bb7e460f3..28015acbc 100644 --- a/README.md +++ b/README.md @@ -153,7 +153,7 @@ logs with the host's details into Downloads for a bug report. reims-ctl list # the VMs and whether they run reims-ctl set mac --memory 12G --resolution 1920x1080 # applies at the next start reims-ctl command mac # the QEMU command it runs, as a shell script -reims-ctl report mac # logs, settings and the host's details, zipped, for a bug report +reims-ctl report mac # logs, settings, the host's details and its vulkaninfo, zipped, for a bug report reims-ctl update # pull the checkout and install again reims-ctl update --channel development # switch to the development branch first (stable is master) ``` diff --git a/crates/reims-ctl/src/cli.rs b/crates/reims-ctl/src/cli.rs index 9fd2b4db4..f2264522c 100644 --- a/crates/reims-ctl/src/cli.rs +++ b/crates/reims-ctl/src/cli.rs @@ -149,6 +149,7 @@ pub enum Cmd { serial: bool, }, /// Zip a VM's logs, settings and the host's details into Downloads, for a bug report + #[command(after_help = report_help())] Report { name: String }, /// Update reims-ctl and its QEMU from the checkout it was installed from #[command(after_help = update_help())] @@ -195,6 +196,19 @@ first. Ctrl-] disconnects; the VM keeps running. Alt+key is Cmd+key. The Cmd, Opt, Ctrl and Shift \ buttons on the top row hold that key for the next key or click."; +/// What `reims-ctl report --help` ends with: what the zip holds. +fn report_help() -> String { + format!( + "The zip holds system.txt, what this host is and the warnings the VM gets; \ + vulkaninfo.txt, all vulkaninfo says about this host's Vulkan drivers and GPUs, below a \ + line that says how it ended: its exit status, that it was stopped after {} s, or that \ + vulkaninfo isn't installed (on Linux and on a Mac, the vulkan-tools package has it); \ + vm.toml, the VM's settings; launch.sh, the QEMU command reims-ctl runs; state.txt, \ + whether the VM runs; and logs/, the end of each of its logs.", + logs::VULKANINFO_LIMIT.as_secs() + ) +} + /// What `reims-ctl update --help` ends with: when it builds, then [`UPDATE_MIGRATIONS`]. fn update_help() -> String { format!( diff --git a/crates/reims-ctl/src/logs.rs b/crates/reims-ctl/src/logs.rs index 2192659f0..d9dc5384a 100644 --- a/crates/reims-ctl/src/logs.rs +++ b/crates/reims-ctl/src/logs.rs @@ -1,5 +1,6 @@ -//! Bug reports: a zip of a VM's logs, its settings, the exact QEMU command and what the host -//! is, in the downloads folder, for someone to attach to a report. +//! Bug reports: a zip of a VM's logs, its settings, the exact QEMU command, what the host is +//! and vulkaninfo's whole report of it, in the downloads folder, for someone to attach to a +//! report. use crate::host::{Host, Os}; use crate::runtime; @@ -8,18 +9,28 @@ use anyhow::{Context, Result}; use std::io::Write; use std::path::{Path, PathBuf}; use std::process::Command; +use std::sync::{Arc, Mutex, mpsc}; +use std::time::{Duration, Instant}; -/// The most of one log a report takes: its end. +/// The most of one log a report takes: its end. The most of each of a tool's streams it takes: +/// their start. const LOG_CAP: u64 = 64 << 20; +/// How long one run of vulkaninfo may take: a GPU driver that hangs can hold it forever, and +/// the report goes on without the rest of its output. +pub const VULKANINFO_LIMIT: Duration = Duration::from_secs(30); + pub fn bundle(vm: &Vm, host: Host) -> Result { let stamp = runtime::now_stamp("%Y%m%d-%H%M%S"); let out = crate::paths::downloads_dir().join(format!("reims-ctl-{}-{stamp}.zip", vm.name())); let mut zip = Zip::create(&out)?; let prefix = format!("reims-ctl-{}-{stamp}", vm.name()); + let vulkaninfo = run_limited(Command::new("vulkaninfo"), VULKANINFO_LIMIT); + let system = system_info(host, &runtime::warnings(vm, host), &vulkaninfo.end); + zip.add(&format!("{prefix}/system.txt"), system.as_bytes())?; zip.add( - &format!("{prefix}/system.txt"), - system_info(host, &runtime::warnings(vm, host)).as_bytes(), + &format!("{prefix}/vulkaninfo.txt"), + vulkaninfo.report("vulkaninfo").as_bytes(), )?; if let Ok(t) = std::fs::read(vm.dir.join(crate::vm::CONFIG_FILE)) { zip.add(&format!("{prefix}/vm.toml"), &t)?; @@ -80,10 +91,186 @@ fn run(cmd: &str, args: &[&str]) -> String { } } +/// A tool's run under a time limit ([`run_limited`]): what it wrote to each stream, and how it +/// ended. +struct Limited { + stdout: Vec, + stderr: Vec, + end: End, +} + +/// How a run under a time limit ended. +#[derive(Debug)] +enum End { + /// It exited, with this status. + Exited(std::process::ExitStatus), + /// It still ran at its limit, this long, and was killed. + TimedOut(Duration), + /// It did not start, or could not be waited for: `NotFound` from its start where the tool + /// is not installed. + Failed(std::io::Error), +} + +impl End { + /// One line that says how `tool`'s run ended. + fn says(&self, tool: &str) -> String { + match self { + End::Exited(status) => format!("{tool} ended with {status}"), + End::TimedOut(limit) => { + format!("{tool} timed out after {} s and was stopped", limit.as_secs()) + } + End::Failed(e) if e.kind() == std::io::ErrorKind::NotFound => { + format!("{tool} is not installed on this host") + } + End::Failed(e) => format!("{tool} did not run: {e}"), + } + } +} + +impl Limited { + /// The run's file in a report, as `vulkaninfo.txt` holds vulkaninfo's: the line that says + /// how it ended, then what it wrote to stdout and to stderr, each under its title, unless + /// it failed with nothing written. + fn report(&self, tool: &str) -> String { + let mut s = format!("{}\n", self.end.says(tool)); + if matches!(self.end, End::Failed(_)) && self.stdout.is_empty() && self.stderr.is_empty() { + return s; + } + for (title, out) in [("stdout", &self.stdout), ("stderr", &self.stderr)] { + s.push_str(&format!("\n== {title}\n{}", String::from_utf8_lossy(out))); + } + s + } +} + +/// Runs `cmd`, with no input, for at most `limit`, keeping what it writes to stdout and to +/// stderr (the first [`LOG_CAP`] bytes of each). A run still going at its limit is killed, and +/// what it wrote until then is kept: a GPU driver that hangs can hold a tool forever, and the +/// report goes on without it. The killed process is waited for on a thread of its own, which +/// nothing joins, since a process stuck in a driver can outlive its kill; its streams' readers +/// get a second more. +fn run_limited(mut cmd: Command, limit: Duration) -> Limited { + use std::process::Stdio; + let child = cmd + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn(); + let mut child = match child { + Ok(c) => c, + Err(e) => { + return Limited { + stdout: Vec::new(), + stderr: Vec::new(), + end: End::Failed(e), + }; + } + }; + let (done, drained) = mpsc::channel(); + let stdout = drain(child.stdout.take(), done.clone()); + let stderr = drain(child.stderr.take(), done); + let deadline = Instant::now() + limit; + let end = loop { + match child.try_wait() { + Ok(Some(status)) => break End::Exited(status), + Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(20)), + waited => { + let _ = child.kill(); + std::thread::spawn(move || { + let _ = child.wait(); + }); + break match waited { + Err(e) => End::Failed(e), + _ => End::TimedOut(limit), + }; + } + } + }; + // Its streams end with it, unless a process it started holds them open: their readers get + // a second more. + let by = Instant::now() + Duration::from_secs(1); + for _ in 0..2 { + if drained + .recv_timeout(by.saturating_duration_since(Instant::now())) + .is_err() + { + break; + } + } + let take = |b: &Arc>>| { + std::mem::take(&mut *b.lock().unwrap_or_else(|e| e.into_inner())) + }; + Limited { + stdout: take(&stdout), + stderr: take(&stderr), + end, + } +} + +/// Reads `pipe` to its end on a thread of its own, into the buffer it returns, which keeps its +/// first [`LOG_CAP`] bytes, and then tells `done`. +fn drain( + pipe: Option, + done: mpsc::Sender<()>, +) -> Arc>> { + let buf = Arc::new(Mutex::new(Vec::new())); + let Some(mut pipe) = pipe else { + let _ = done.send(()); + return buf; + }; + let kept = Arc::clone(&buf); + std::thread::spawn(move || { + let mut chunk = vec![0u8; 64 << 10]; + loop { + match pipe.read(&mut chunk) { + Ok(0) => break, + Ok(n) => { + let mut b = kept.lock().unwrap_or_else(|e| e.into_inner()); + let room = (LOG_CAP as usize).saturating_sub(b.len()); + b.extend_from_slice(&chunk[..n.min(room)]); + } + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(_) => break, + } + } + let _ = done.send(()); + }); + buf +} + +/// system.txt's `vulkaninfo --summary`: the first 80 lines it writes, stdout then stderr, and +/// how it ended where it did not exit with success. It runs only where `whole`, the run of the +/// whole report, exited: where vulkaninfo is not installed, or that run timed out or failed, +/// the section says so instead, and holds the report up no longer. +fn vulkan_summary(whole: &End) -> String { + match whole { + End::Exited(_) => {} + End::Failed(e) if e.kind() == std::io::ErrorKind::NotFound => { + return whole.says("vulkaninfo"); + } + _ => return format!("not run: {} (vulkaninfo.txt)", whole.says("vulkaninfo")), + } + let mut cmd = Command::new("vulkaninfo"); + cmd.arg("--summary"); + let run = run_limited(cmd, VULKANINFO_LIMIT); + let out = [run.stdout, run.stderr].concat(); + let mut s = String::from_utf8_lossy(&out) + .lines() + .take(80) + .collect::>() + .join("\n"); + if !matches!(run.end, End::Exited(status) if status.success()) { + s.push('\n'); + s.push_str(&run.end.says("vulkaninfo --summary")); + } + s +} + /// What the host is: the parts a report about a guest's graphics needs. /// What the host is, and `warnings`, the ones reims-ctl gives the VM as the report is made: what -/// its user was shown. -pub fn system_info(host: Host, warnings: &[String]) -> String { +/// its user was shown. `vulkaninfo` is how the run of vulkaninfo's whole report ended +/// ([`vulkan_summary`]). +fn system_info(host: Host, warnings: &[String], vulkaninfo: &End) -> String { let mut s = String::new(); let mut section = |title: &str, body: String| { s.push_str(&format!("== {title}\n{body}\n\n")); @@ -169,16 +356,7 @@ pub fn system_info(host: Host, warnings: &[String]) -> String { }) .collect::>(); section("vulkan gpus", gpus.join("\n")); - section( - "vulkaninfo --summary", - run( - "sh", - &[ - "-c", - "command -v vulkaninfo >/dev/null && vulkaninfo --summary 2>&1 | head -80", - ], - ), - ); + section("vulkaninfo --summary", vulkan_summary(vulkaninfo)); section( "nvidia", run( @@ -336,6 +514,103 @@ mod tests { assert_eq!(warnings_list(&["one".into(), "two".into()]), "- one\n- two"); } + /// What the run tests run as a tool: this test binary, which, where `REIMS_CTL_TEST_TOOL` is + /// `write`, writes more than a pipe holds to stdout and a line to stderr and exits with 3, + /// and where it is `hang`, writes a line and sleeps past the limit the test gives it. + #[test] + fn a_tool() { + let mut out = std::io::stdout(); + match std::env::var("REIMS_CTL_TEST_TOOL").as_deref() { + Ok("write") => { + for i in 0..20_000 { + writeln!(out, "line {i} of the tool's report").unwrap(); + } + out.flush().unwrap(); + std::io::stderr().write_all(b"a warning\n").unwrap(); + std::process::exit(3); + } + Ok("hang") => { + out.write_all(b"before the hang\n").unwrap(); + out.flush().unwrap(); + std::thread::sleep(Duration::from_secs(60)); + } + _ => {} + } + } + + /// This test binary as a tool that does what `mode` names ([`a_tool`]). + fn tool(mode: &str) -> Command { + let mut c = Command::new(std::env::current_exe().unwrap()); + c.args(["--exact", "logs::tests::a_tool", "--nocapture"]) + .env("REIMS_CTL_TEST_TOOL", mode); + c + } + + /// A tool that exits is kept whole, past what a pipe holds, each of its streams under its + /// title, below a first line that says how it exited. + #[test] + fn a_tool_that_exits_is_kept_whole_below_its_exit_status() { + let run = run_limited(tool("write"), Duration::from_secs(60)); + assert!( + matches!(run.end, End::Exited(s) if s.code() == Some(3)), + "{:?}", + run.end + ); + let report = run.report("vulkaninfo"); + let (first, rest) = report.split_once('\n').unwrap(); + assert!( + first.starts_with("vulkaninfo ended with ") && first.ends_with('3'), + "{first}" + ); + let (stdout, stderr) = rest.split_once("\n== stderr\n").unwrap(); + assert!(stdout.starts_with("\n== stdout\n"), "{stdout:.300}"); + assert!(stdout.contains("line 0 of the tool's report\n")); + assert!(stdout.ends_with("\nline 19999 of the tool's report\n")); + assert!(stderr.contains("a warning\n"), "{stderr}"); + } + + /// A tool still running at its limit is stopped there, and its file keeps what it wrote + /// until then, below a first line that says it timed out; system.txt's summary does not run + /// it again. + #[test] + fn a_tool_past_its_limit_is_stopped_and_what_it_wrote_kept() { + let started = Instant::now(); + let run = run_limited(tool("hang"), Duration::from_secs(3)); + assert!( + started.elapsed() < Duration::from_secs(10), + "{:?}", + started.elapsed() + ); + let report = run.report("vulkaninfo"); + assert!( + report.starts_with("vulkaninfo timed out after 3 s and was stopped\n"), + "{report}" + ); + assert!(report.contains("before the hang\n"), "{report}"); + assert_eq!( + vulkan_summary(&run.end), + "not run: vulkaninfo timed out after 3 s and was stopped (vulkaninfo.txt)" + ); + } + + /// A tool that is not installed is said to be, in one line, in its file and in system.txt's + /// summary. + #[test] + fn a_tool_not_installed_says_so_in_one_line() { + let run = run_limited( + Command::new("reims-ctl-test-no-such-tool"), + Duration::from_secs(10), + ); + assert_eq!( + run.report("vulkaninfo"), + "vulkaninfo is not installed on this host\n" + ); + assert_eq!( + vulkan_summary(&run.end), + "vulkaninfo is not installed on this host" + ); + } + #[test] fn zip_is_readable_by_unzip() { let dir = std::env::temp_dir().join(format!("reims-ctl-zip-{}", std::process::id())); diff --git a/crates/reims-ctl/src/tui.rs b/crates/reims-ctl/src/tui.rs index ae548edd9..e77c0994b 100644 --- a/crates/reims-ctl/src/tui.rs +++ b/crates/reims-ctl/src/tui.rs @@ -3059,8 +3059,8 @@ of its own. A VM runs reims-vgpu's own GPU device unless its settings choose ano l turn its logs on or off L view its QEMU log in less: :n shows the serial console, / searches, F follows the log as it grows, q comes back - b write a bug report: its logs, settings, command and this host's details, - zipped into your Downloads folder + b write a bug report: its logs, settings, command, this host's details and + all vulkaninfo says of its Vulkan drivers, zipped into your Downloads folder d delete it U make it a new OpenCore image with the installed reims-util, presenting the same Mac, for its graphics: on reims-vgpu with the macOS drivers of its GPU