From cfc3e1d7c50a7f76b604dbdfc92323c8a1f1ea12 Mon Sep 17 00:00:00 2001 From: noah Date: Sun, 20 Sep 2026 10:54:52 -0600 Subject: [PATCH] GUI round 12 (#12): scan miner logs over the firmware API (PIC + metrics) Adds a right-click "View log (API)..." action that fetches a miner's log through its firmware API and regex-scans it -- the "logs through API" path for PIC detection and other metrics without SSH. Per firmware (crates/alkane-gui/src/log_scan.rs, curl-based like the access probe, stdout drained on a thread so a large log never deadlocks the pipe): - VNish: POST /api/v1/unlock -> bearer -> GET /api/v1/logs/miner (the full miner log: PSU init, per-chain chip detection, tuning, errors). - Stock Antminer: GET /cgi-bin/log.cgi (digest); older models (Z15) that do not serve it are reported as "no log over its web API". - WhatsMiner: get_error_code on :4028 (unauthenticated) formatted as the log. The summary regex reports PIC status ("not present (no-PIC miner)" / "present -- "), the latest per-chain chip-detection line, and recent errors from the log history. Creds reuse the round 12 #13 per-firmware defaults (VNish password, else "admin"; Antminer web login from the saved global creds). Verified live: VNish S19j Pro (10.7.1.25) log -> "PIC: not present (log reports a no-PIC miner)" + chains + recent errors; WhatsMiner (10.8.1.45) -> its active error codes; Z15 (10.5.1.196) -> honest "no log over its web API". Unit tests for the summary + a headless ALKANE_LOG_SCAN diagnostic; self-test passes. Note: WhatsMiner fault codes already surface in the Errors column via asic-rs's get_error_code -> messages; this adds the raw-log view and the PIC scan on top. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh --- crates/alkane-gui/src/access_probe.rs | 23 +++ crates/alkane-gui/src/log_scan.rs | 264 ++++++++++++++++++++++++++ crates/alkane-gui/src/main.rs | 26 +++ crates/alkane-gui/src/ui.rs | 63 ++++++ 4 files changed, 376 insertions(+) create mode 100644 crates/alkane-gui/src/log_scan.rs diff --git a/crates/alkane-gui/src/access_probe.rs b/crates/alkane-gui/src/access_probe.rs index 31dd3ecf..4919eeb8 100644 --- a/crates/alkane-gui/src/access_probe.rs +++ b/crates/alkane-gui/src/access_probe.rs @@ -131,6 +131,29 @@ fn whatsminer_password_candidates() -> Vec { vec!["admin".to_string(), "super".to_string()] } +/// Fetch a WhatsMiner's active fault codes over the unauthenticated :4028 +/// get_error_code command and format them one per line for the log viewer +/// (round 12 #12). Returns None if the miner does not answer. +pub fn whatsminer_get_error_code(ip: &str) -> Option { + let resp = wm_rpc(ip, "{\"command\":\"get_error_code\"}", Duration::from_secs(6)).ok()?; + let v: serde_json::Value = serde_json::from_str(&resp).ok()?; + let codes = v.get("Msg").and_then(|m| m.get("error_code")).and_then(|c| c.as_array()); + let mut lines = vec![format!("WhatsMiner get_error_code ({ip}):")]; + match codes { + Some(arr) if !arr.is_empty() => { + for entry in arr { + if let Some(obj) = entry.as_object() { + for (code, when) in obj { + lines.push(format!(" error {code}: {}", when.as_str().unwrap_or(""))); + } + } + } + } + _ => lines.push(" no active error codes".to_string()), + } + Some(lines.join("\n")) +} + /// One WhatsMiner :4028 request/response (the miner closes the socket after it /// replies). Returns the NUL-trimmed body. fn wm_rpc(ip: &str, payload: &str, timeout: Duration) -> Result { diff --git a/crates/alkane-gui/src/log_scan.rs b/crates/alkane-gui/src/log_scan.rs new file mode 100644 index 00000000..b5ff859f --- /dev/null +++ b/crates/alkane-gui/src/log_scan.rs @@ -0,0 +1,264 @@ +//! Fetch a miner's log over its firmware API and regex-scan it for useful +//! signals (round 12 #12). This is the "logs through API" path the operator +//! asked for: where a firmware exposes its log we can read board/PIC lines and +//! other metrics without SSH. +//! +//! Per firmware: +//! - VNish (aftermarket Antminer): POST /api/v1/unlock to get a bearer token, +//! then GET /api/v1/logs/miner -- the full miner log (PSU init, per-chain +//! chip detection, tuning, errors). +//! - Stock Antminer: GET /cgi-bin/log.cgi behind digest auth (older models +//! such as the Z15 do not serve it -> reported as unavailable). +//! - WhatsMiner: the btminer log is not exposed on :4028, but get_error_code +//! (unauthenticated) returns the active fault codes, which we format as the +//! log view. +//! +//! We shell out to `curl` (already a dependency of the access probe) so the +//! offline/vendored build gains no new crate, and cap the fetched text so a huge +//! log never bloats the viewer. + +use std::process::Command; +use std::time::Duration; + +/// Cap on the log text we keep for display (bytes); the regex summary is still +/// computed over everything fetched. +const MAX_LOG_BYTES: usize = 256 * 1024; + +/// A fetched log plus the signals a regex pass pulled out of it. +pub struct LogScan { + /// The (possibly tail-trimmed) log text for the viewer. + pub text: String, + /// One-line-per-finding summary shown above the log. + pub summary: Vec, +} + +/// Fetch and scan one miner's log. `brand` is the make ("Antminer"/"Whatsminer"), +/// `firmware` the family ("VNish"/"Stock"/...). `vnish_pass`/`wm` creds are used +/// where that firmware needs auth. Returns `Err` only when no log could be read. +pub fn scan_log( + ip: &str, + brand: &str, + firmware: &str, + vnish_pass: &str, + antminer_user: &str, + antminer_pass: &str, +) -> Result { + let raw = if firmware.eq_ignore_ascii_case("vnish") { + fetch_vnish_log(ip, vnish_pass)? + } else if brand.eq_ignore_ascii_case("whatsminer") { + fetch_whatsminer_errors(ip)? + } else { + // Stock / other Antminer-family web firmware. + fetch_antminer_log(ip, antminer_user, antminer_pass)? + }; + let summary = summarize_log(&raw); + Ok(LogScan { text: tail(&raw, MAX_LOG_BYTES), summary }) +} + +/// Keep the last `max` bytes of `s` (a log's tail is the freshest), on a line +/// boundary, with a marker when trimmed. +fn tail(s: &str, max: usize) -> String { + if s.len() <= max { + return s.to_string(); + } + let start = s.len() - max; + // advance to the next line boundary so we don't cut a line in half + let start = s[start..] + .find('\n') + .map(|i| start + i + 1) + .unwrap_or(start); + format!("[... earlier log trimmed ...]\n{}", &s[start..]) +} + +/// Regex-free scan for the high-value signals in a miner log: PIC / hashboard +/// firmware lines, per-chain chip detection, and the most recent errors. +fn summarize_log(log: &str) -> Vec { + let mut out = Vec::new(); + let lc_has = |line: &str, needle: &str| line.to_ascii_lowercase().contains(needle); + + // PIC / hashboard-controller status from the log. Aftermarket firmwares state + // it explicitly ("no-PIC miner"); stock boot logs print a PIC version. This + // is the log-regex PIC scan the operator asked for (round 12 #12). + let pic_lines: Vec<&str> = log.lines().filter(|l| lc_has(l, "pic")).collect(); + if pic_lines.iter().any(|l| lc_has(l, "no-pic") || lc_has(l, "no pic")) { + out.push("PIC: not present (log reports a no-PIC miner)".to_string()); + } else if let Some(l) = pic_lines + .iter() + .find(|l| lc_has(l, "version") || lc_has(l, "fw") || lc_has(l, "found")) + { + out.push(format!("PIC: present -- {}", l.trim())); + } else if !pic_lines.is_empty() { + out.push(format!("PIC: {} log line(s) mention PIC", pic_lines.len())); + for l in pic_lines.iter().take(3) { + out.push(format!(" {}", l.trim())); + } + } else { + out.push("PIC: no PIC lines in the log".to_string()); + } + + // Latest per-chain chip-detection line (the most recent board bring-up). + if let Some(l) = log.lines().rev().find(|l| lc_has(l, "chips detected")) { + out.push(format!("Chains: {}", l.trim())); + } + + // Recent errors (log history, beyond asic-rs's current-message snapshot). + // Skip the get_error_code header line (it contains "error" but is not one). + let errors: Vec<&str> = log + .lines() + .rev() + .filter(|l| (lc_has(l, "error") || lc_has(l, "fail")) && !lc_has(l, "get_error_code")) + .take(3) + .collect(); + if errors.is_empty() { + out.push("Errors: none in the log".to_string()); + } else { + out.push(format!("Errors: {} recent", errors.len())); + for l in errors { + out.push(format!(" {}", l.trim())); + } + } + out +} + +/// VNish: unlock -> bearer -> the full miner log. +fn fetch_vnish_log(ip: &str, pass: &str) -> Result { + let unlock = curl(&[ + "-s", + "--connect-timeout", + "5", + "--max-time", + "9", + "-X", + "POST", + "-H", + "Content-Type: application/json", + "-d", + &format!("{{\"pw\":\"{pass}\"}}"), + &format!("http://{ip}/api/v1/unlock"), + ])?; + let token = serde_json::from_str::(&unlock) + .ok() + .and_then(|v| v.get("token").and_then(|t| t.as_str()).map(str::to_string)) + .filter(|t| !t.is_empty()) + .ok_or_else(|| "VNish unlock rejected (check the VNish password in scan credentials)".to_string())?; + let log = curl(&[ + "-s", + "--connect-timeout", + "5", + "--max-time", + "12", + "-H", + &format!("Authorization: Bearer {token}"), + &format!("http://{ip}/api/v1/logs/miner"), + ])?; + if log.trim().is_empty() { + return Err("VNish returned an empty log".to_string()); + } + Ok(log) +} + +/// Stock Antminer web log (digest auth). Absent on older models (404). +fn fetch_antminer_log(ip: &str, user: &str, pass: &str) -> Result { + let body = curl(&[ + "-s", + "--digest", + "-u", + &format!("{user}:{pass}"), + "--connect-timeout", + "5", + "--max-time", + "12", + &format!("http://{ip}/cgi-bin/log.cgi"), + ])?; + if body.contains("404 - Not Found") || body.trim().is_empty() { + return Err("this firmware does not expose a log over its web API".to_string()); + } + Ok(body) +} + +/// WhatsMiner: format the active error codes (get_error_code, unauthenticated). +fn fetch_whatsminer_errors(ip: &str) -> Result { + let resp = crate::access_probe::whatsminer_get_error_code(ip) + .ok_or_else(|| "WhatsMiner did not answer get_error_code on :4028".to_string())?; + Ok(resp) +} + +/// Run curl and return stdout, with a hard wall-clock cap. stdout is drained on a +/// separate thread so a large log (hundreds of KB) never deadlocks on a full pipe +/// -- the reason a naive "wait then read" times out on the VNish log. +fn curl(args: &[&str]) -> Result { + use std::io::Read; + let mut cmd = Command::new("curl"); + cmd.args(args); + cmd.stdout(std::process::Stdio::piped()); + cmd.stderr(std::process::Stdio::null()); + let mut child = cmd.spawn().map_err(|e| format!("spawn curl: {e}"))?; + let mut stdout = child.stdout.take().ok_or("no curl stdout")?; + let reader = std::thread::spawn(move || { + let mut buf = Vec::new(); + let _ = stdout.read_to_end(&mut buf); + buf + }); + let timeout = Duration::from_secs(20); + let start = std::time::Instant::now(); + let mut timed_out = false; + loop { + match child.try_wait().map_err(|e| e.to_string())? { + Some(_) => break, + None => { + if start.elapsed() >= timeout { + let _ = child.kill(); + timed_out = true; + break; + } + std::thread::sleep(Duration::from_millis(50)); + } + } + } + let buf = reader.join().unwrap_or_default(); + if timed_out && buf.is_empty() { + return Err("log fetch timed out".into()); + } + Ok(String::from_utf8_lossy(&buf).into_owned()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn summarize_finds_pic_chains_and_errors() { + let log = "\ +[t] INFO: Initializing PSU +[t] INFO: chain#1 - 126 chips detected +[t] INFO: check PIC on chain 1: version 0x03 +[t] ERROR: Failed load miner config +[t] INFO: chain#2 - 126 chips detected"; + let s = summarize_log(log); + assert!(s.iter().any(|l| l.contains("PIC: present")), "PIC present: {s:?}"); + assert!(s.iter().any(|l| l.contains("chips detected")), "chains: {s:?}"); + assert!(s.iter().any(|l| l.contains("Errors: 1")), "errors: {s:?}"); + } + + #[test] + fn summarize_detects_no_pic_miner() { + let log = "[t] ERROR: This is a no-PIC miner, so all connected chains ...\n[t] INFO: mining"; + let s = summarize_log(log); + assert!(s.iter().any(|l| l.contains("PIC: not present")), "{s:?}"); + } + + #[test] + fn summarize_handles_no_pic_lines() { + let log = "[t] INFO: chain#1 - 126 chips detected\n[t] INFO: mining"; + let s = summarize_log(log); + assert!(s.iter().any(|l| l.contains("no PIC lines")), "{s:?}"); + } + + #[test] + fn tail_trims_on_line_boundary() { + let log = "aaaa\nbbbb\ncccc\n"; + let t = tail(log, 6); + assert!(t.starts_with("[... earlier log trimmed ...]"), "{t}"); + assert!(t.ends_with("cccc\n")); + } +} diff --git a/crates/alkane-gui/src/main.rs b/crates/alkane-gui/src/main.rs index e1557b4c..446e1450 100644 --- a/crates/alkane-gui/src/main.rs +++ b/crates/alkane-gui/src/main.rs @@ -4,6 +4,7 @@ mod access_probe; mod credentials; mod fixtures; +mod log_scan; mod model; mod naming; mod pic_probe; @@ -39,6 +40,31 @@ fn main() { std::process::exit(0); } + // Headless log-scan check: `ALKANE_LOG_SCAN=" "` fetches + // the miner's log over its firmware API and prints the regex summary (round + // 12 #12), so the VNish/Antminer/WhatsMiner log paths can be verified without + // the GUI. + if let Some(spec) = std::env::var_os("ALKANE_LOG_SCAN") { + let spec = spec.to_string_lossy(); + let mut it = spec.split_whitespace(); + let ip = it.next().unwrap_or(""); + let brand = it.next().unwrap_or(""); + let firmware = it.next().unwrap_or(""); + let (au, ap) = credentials::load_credentials().unwrap_or_else(|| ("root".into(), "root".into())); + let vp = credentials::firmware_default_for("VNish").1; + let vp = if vp.is_empty() { "admin".to_string() } else { vp }; + match log_scan::scan_log(ip, brand, firmware, &vp, &au, &ap) { + Ok(s) => { + println!("LOGSCAN {ip} ({brand}/{firmware}): {} log bytes", s.text.len()); + for line in &s.summary { + println!(" {line}"); + } + } + Err(e) => println!("LOGSCAN {ip} ({brand}/{firmware}): ERROR {e}"), + } + std::process::exit(0); + } + // Bootstrap the wx app + main frame (upstream bridge). wx_rs::init_app("alkane-toolkit", 1280, 800); // Follow the system light/dark appearance. diff --git a/crates/alkane-gui/src/ui.rs b/crates/alkane-gui/src/ui.rs index bf2c4990..b6739c87 100644 --- a/crates/alkane-gui/src/ui.rs +++ b/crates/alkane-gui/src/ui.rs @@ -56,6 +56,9 @@ const ID_CTX_POWER: i32 = 728; const ID_CTX_RESTART: i32 = 729; const ID_CTX_PIC_PROBE: i32 = 730; const ID_CTX_ACCESS_PROBE: i32 = 731; +// View a miner's log fetched over its firmware API (round 12 #12). +const ID_CTX_VIEW_LOG: i32 = 734; +const ID_LOGVIEW_CLOSE: i32 = 785; // SSH PIC-probe credentials dialog. const ID_PICSSH_OK: i32 = 780; const ID_PICSSH_CANCEL: i32 = 781; @@ -588,6 +591,8 @@ pub struct App { // Background SSH PIC probe + its credentials dialog. pic_probe: Option, pending_pic_targets: Vec<(String, String)>, + // The API log viewer dialog (round 12 #12). + logview_dialog: Widget, picssh_dialog: Widget, picssh_user_input: Widget, picssh_pass_input: Widget, @@ -859,6 +864,7 @@ pub fn build(frame: Widget) -> App { access_probe: None, pic_probe: None, pending_pic_targets: Vec::new(), + logview_dialog: frame, picssh_dialog: frame, picssh_user_input: frame, picssh_pass_input: frame, @@ -1255,6 +1261,8 @@ impl App { // Real access/lock-state check (credentialed digest GET; uses the saved // scan credentials). menu.menu_append(ID_CTX_ACCESS_PROBE, "Check access (auth)"); + // Fetch and scan this miner's log over its firmware API (round 12 #12). + menu.menu_append(ID_CTX_VIEW_LOG, "View log (API)..."); // Config actions common to the whole selection (capability // intersection): an action is offered only if every selected miner // supports it. @@ -1354,6 +1362,59 @@ impl App { wx_rs::set_status_text(&msg); } + /// Fetch the selected miner's log over its firmware API and show it in a + /// viewer with a regex summary at the top (round 12 #12). The fetch is a + /// short blocking network call (a manual, single-miner action). Returns the + /// dialog to show, or None after reporting why no log could be read. + fn build_log_view_dialog(&mut self) -> Option { + let rows = self.selected_rows(); + let r = rows.first()?; + let (ip, brand, firmware) = (r.ip.clone(), r.brand.clone(), r.firmware.clone()); + // VNish unlock password + Antminer web login: a per-firmware override + // (round 12 #13) wins, else the shipped default / saved global creds. + let vnish_pass = credentials::load_firmware_credentials() + .get("VNish") + .map(|(_, p)| p.clone()) + .filter(|p| !p.is_empty()) + .unwrap_or_else(|| credentials::firmware_default_for("VNish").1); + let vnish_pass = if vnish_pass.is_empty() { "admin".to_string() } else { vnish_pass }; + let (am_user, am_pass) = + credentials::load_credentials().unwrap_or_else(|| ("root".into(), "root".into())); + wx_rs::set_status_text(&format!("fetching log from {ip}...")); + let scan = match crate::log_scan::scan_log(&ip, &brand, &firmware, &vnish_pass, &am_user, &am_pass) { + Ok(s) => s, + Err(e) => { + self.set_error_indicator(&format!("log: {e}")); + wx_rs::set_status_text(&format!("log fetch failed for {ip}: {e}")); + return None; + } + }; + self.clear_indicator(); + wx_rs::set_status_text(&format!("{} miners", self.rows.len())); + let frame = Widget::main_frame(); + let dlg = Widget::dialog(frame, &format!("Miner log (API) -- {ip}")); + let root = Widget::box_sizer(true); + let summary = if scan.summary.is_empty() { + "(no summary)".to_string() + } else { + scan.summary.join("\n") + }; + root.add(Widget::static_text(dlg, &summary), 0, sf::BORDER_ALL, 8); + let text = Widget::text_ctrl(dlg, true); + text.set_min_size(760, 420); + text.set_value(&scan.text); + root.add(text, 1, sf::EXPAND | sf::BORDER_ALL, 8); + let btns = Widget::box_sizer(false); + btns.add_stretch(1); + btns.add(Widget::button(dlg, "Close", ID_LOGVIEW_CLOSE), 0, sf::BORDER_ALL, 6); + root.add_sizer(btns, 0, sf::EXPAND | sf::BORDER_ALL, 6); + root.set_sizer_on(dlg); + dlg.set_min_size(800, 540); + dlg.fit(dlg); + self.logview_dialog = dlg; + Some(dlg) + } + /// Build the SSH PIC-probe dialog: captures the selected miners, collects /// SSH credentials (prefilled from the saved SSH login), and on OK runs the /// on-board i2c probe. Returns None (no dialog) if nothing is selected or a @@ -1588,6 +1649,8 @@ impl App { ID_CTX_REFRESH => self.start_refresh(self.selected_ip_list()), ID_CTX_PIC_PROBE => return self.build_pic_probe_dialog(), ID_CTX_ACCESS_PROBE => self.start_access_probe(), + ID_CTX_VIEW_LOG => return self.build_log_view_dialog(), + ID_LOGVIEW_CLOSE => self.logview_dialog.close(1), ID_CTX_FLASH => { // A flash needs exclusive hardware access; don't even prompt if // any scan / refresh / action is running (re-checked at confirm).