//! 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")); } }