Third review round (over the wave 3/4 fixes) surfaced further findings, mostly in new code paths; this clears them: - HIGH the fully-built "Boards" column (Column::Hashboards: renderer, sort/filter logic, tests, a self-test check) was missing from ALL_COLUMNS, so it was unreachable in the UI and its self-test check was dead. Added to ALL_COLUMNS (opt-in; Health still shows composite board health by default) and the self-test now makes it visible -- the dot-sentinel check is live again. - HIGH apply_pools() could start a pool write during a restore-to-stock (it sets self.action directly, bypassing start_action's guard) -> same restore guard. - HIGH superseding an in-flight action/pools job left the old miners' Health cells frozen on the "…ing" label forever (the replaced handle's drain never runs) -> clear the superseded action's op-status. - HIGH clean_antminer() byte-sliced a miner-supplied model string without a char-boundary check (panic DoS) -> use get(..9). - MED access-probe errors were silently discarded -> surfaced in the indicator. - MED the pool-password file was briefly world-readable before chmod -> created 0600 from the start (OpenOptions mode). - MED a miner-controlled log response was buffered unbounded (OOM DoS) -> capped. - MED the language-menu id range was hardcoded (and 790-794 collided with the pool-preset / fw-preset dialog ids!) -> derived from Lang::all() and moved the dialog ids to a clear block. - LOW restore_vnish now sends the unlock body via stdin (password off argv), and the LuxOS restore treats a reboot-dropped/empty reply as success. Remaining round-3 findings are the previously-accepted perf tradeoffs (bulk-serial writes, per-tick refill, per-render health recompute, linear upsert), documented in code and in code-review-report.md. 99 tests + clippy-clean + selftest green (Boards-column check now live). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Djv3oncM4LxTS5tb61Ako6
315 lines
12 KiB
Rust
315 lines
12 KiB
Rust
//! 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<String>,
|
|
}
|
|
|
|
/// 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<LogScan, String> {
|
|
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();
|
|
}
|
|
// Nudge the cut forward to a UTF-8 char boundary first: a raw byte offset can
|
|
// land inside a multi-byte character and slicing there would panic (round 18
|
|
// #12; miner logs are not guaranteed pure ASCII).
|
|
let mut start = s.len() - max;
|
|
while start < s.len() && !s.is_char_boundary(start) {
|
|
start += 1;
|
|
}
|
|
// then 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<String> {
|
|
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<String, String> {
|
|
// The password goes in the POST body read from stdin (-d @-), never on argv,
|
|
// and is JSON-encoded by serde so it is both un-leakable and correctly escaped
|
|
// (round 18 #12).
|
|
let body = serde_json::json!({ "pw": pass }).to_string();
|
|
let unlock = curl(
|
|
&[
|
|
"-s",
|
|
"--connect-timeout",
|
|
"5",
|
|
"--max-time",
|
|
"9",
|
|
"-X",
|
|
"POST",
|
|
"-H",
|
|
"Content-Type: application/json",
|
|
"-d",
|
|
"@-",
|
|
&format!("http://{ip}/api/v1/unlock"),
|
|
],
|
|
Some(body.as_bytes()),
|
|
)?;
|
|
let token = serde_json::from_str::<serde_json::Value>(&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"),
|
|
],
|
|
None,
|
|
)?;
|
|
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<String, String> {
|
|
// Credentials go through a curl config on stdin (-K -), never on argv, so they
|
|
// can't be read from the process list (round 18 #12).
|
|
let config = format!("user = \"{}\"\n", curl_config_quote(&format!("{user}:{pass}")));
|
|
let body = curl(
|
|
&[
|
|
"-s",
|
|
"--digest",
|
|
"--connect-timeout",
|
|
"5",
|
|
"--max-time",
|
|
"12",
|
|
"-K",
|
|
"-",
|
|
&format!("http://{ip}/cgi-bin/log.cgi"),
|
|
],
|
|
Some(config.as_bytes()),
|
|
)?;
|
|
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<String, String> {
|
|
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], stdin_data: Option<&[u8]>) -> Result<String, String> {
|
|
use std::io::{Read, Write};
|
|
let mut cmd = Command::new("curl");
|
|
cmd.args(args);
|
|
cmd.stdout(std::process::Stdio::piped());
|
|
cmd.stderr(std::process::Stdio::null());
|
|
if stdin_data.is_some() {
|
|
cmd.stdin(std::process::Stdio::piped());
|
|
}
|
|
let mut child = cmd.spawn().map_err(|e| format!("spawn curl: {e}"))?;
|
|
if let Some(data) = stdin_data {
|
|
if let Some(mut si) = child.stdin.take() {
|
|
let _ = si.write_all(data);
|
|
} // dropping `si` closes the pipe so curl stops reading the config/body
|
|
}
|
|
let stdout = child.stdout.take().ok_or("no curl stdout")?;
|
|
let reader = std::thread::spawn(move || {
|
|
// Bound the buffer: a miner-controlled response must not exhaust memory
|
|
// (round 18 #12). The viewer only keeps the last MAX_LOG_BYTES anyway, so
|
|
// read a small multiple of that and drop the rest.
|
|
const READ_CAP: u64 = (MAX_LOG_BYTES as u64) * 8; // 2 MiB
|
|
let mut buf = Vec::new();
|
|
let _ = stdout.take(READ_CAP).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();
|
|
let _ = child.wait(); // reap so we never leave a zombie (round 18 #12)
|
|
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())
|
|
}
|
|
|
|
/// Escape a value for a curl `--config` file (double-quoted string).
|
|
fn curl_config_quote(s: &str) -> String {
|
|
s.replace('\\', "\\\\").replace('"', "\\\"")
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn tail_does_not_panic_mid_multibyte_char() {
|
|
// A byte-offset cut can land inside a multi-byte character; tail must nudge
|
|
// to a char boundary rather than panic (round 18 #12).
|
|
let s = "\u{00e9}".repeat(200); // 400 bytes of 2-byte chars, no newlines
|
|
let out = tail(&s, 101); // cut at an odd offset -> inside a char
|
|
assert!(out.starts_with("[... earlier log trimmed ...]"));
|
|
assert!(out.len() < s.len());
|
|
}
|
|
|
|
#[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"));
|
|
}
|
|
}
|