AnyBot/src/doctor.rs

150 lines
7.2 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! 診斷 (/doctor): what this computer's AnyBot can find out about itself, one line each, ✓ or ✗
//! with the reason — the version and folders, this computer ↔ the account server (and whether
//! Tailscale goes direct or through one of its relays), the account server ↔ the brain, the last
//! sync's speed, each model service the bots use, the bots' computer, the connectors, the disk,
//! the last crash. On a screen of a brain it is this computer that is checked (where a problem
//! usually is). The checks that go over the network run on a thread of their own. Like
//! grok-build's /doctor; `make doctor` checks the build tools instead.
use std::path::Path;
/// 「/doctor」 (nothing after it).
pub fn command(text: &str) -> bool {
text.trim() == "/doctor"
}
/// One finding: fine or not, and what it says.
#[derive(Clone, Debug, PartialEq)]
pub struct Line {
pub ok: bool,
pub text: String,
}
pub fn ok(t: impl Into<String>) -> Line {
Line { ok: true, text: t.into() }
}
pub fn bad(t: impl Into<String>) -> Line {
Line { ok: false, text: t.into() }
}
/// The report: a title line, then each finding with ✓ or ✗, and a last line counting the ✗.
pub fn report(lines: &[Line]) -> String {
let bad = lines.iter().filter(|l| !l.ok).count();
let mut s = String::from("診斷(/doctor):這台電腦的 AnyBot");
for l in lines {
s.push_str(&format!("\n{} {}", if l.ok { "✓" } else { "✗" }, l.text));
}
s.push_str(&if bad == 0 { "\n全部正常。".to_string() } else { format!("\n有 {bad} 項要看一下(✗)。") });
s
}
/// The Tailscale name in an account server's address (…​.ts.net), if it is one.
pub fn tailscale_host(url: &str) -> Option<String> {
let host = url.split("://").nth(1)?.split(['/', ':']).next()?.to_string();
host.ends_with(".ts.net").then_some(host)
}
/// What `tailscale ping` said, in words: direct, or through which relay (much slower).
pub fn tailscale_path(ping: &str) -> Option<Line> {
let line = ping.lines().find(|l| l.contains("pong from"))?;
if let Some(relay) = line.split("via DERP(").nth(1).and_then(|r| r.split(')').next()) {
let ms = line.split(" in ").nth(1).unwrap_or("").trim().to_string();
return Some(bad(format!("Tailscale 沒有直連,走它在「{relay}」的中繼({ms}):大份資料會很慢。兩台通常在同一個網路卻連不直,多半是中間擋了 UDP(Tailscale 直連用 41641)")));
}
Some(ok(format!("Tailscale 直連({})", line.split("pong from").nth(1).unwrap_or("").trim())))
}
/// Ask Tailscale how it reaches `host` (None when Tailscale isn't here).
pub fn ping_tailscale(host: &str) -> Option<Line> {
for bin in ["tailscale", "/Applications/Tailscale.app/Contents/MacOS/Tailscale"] {
let out = std::process::Command::new(bin).args(["ping", "-c", "1", "--timeout", "5s", host]).output();
if let Ok(o) = out {
let text = format!("{}{}", String::from_utf8_lossy(&o.stdout), String::from_utf8_lossy(&o.stderr));
return tailscale_path(&text).or_else(|| Some(bad(format!("Tailscale 找不到 {host}:{}", text.lines().next().unwrap_or("沒有回應")))));
}
}
None
}
/// Whether commands on this computer run in a sandbox, and which.
pub fn sandbox_line() -> Line {
if cfg!(target_os = "macos") {
return if std::path::Path::new("/usr/bin/sandbox-exec").exists() { ok("指令沙盒:macOS 的 sandbox-exec") } else { bad("這台的指令沒有沙盒:找不到 /usr/bin/sandbox-exec") };
}
if cfg!(target_os = "linux") {
return match crate::landlock::abi() {
Some(v) => ok(format!("指令沙盒:Linux 的 Landlock(第 {v} 版)")),
None => bad(crate::landlock::NONE),
};
}
bad("這台的指令沒有沙盒(Windows 還沒有):指令讀得到 .ssh 這類私密資料夾,只靠安全規則擋")
}
/// Free space where the data folder is, in MB (None where `df` can't say).
pub fn free_mb(dir: &Path) -> Option<u64> {
let out = std::process::Command::new("df").args(["-Pk"]).arg(dir).output().ok()?;
let text = String::from_utf8_lossy(&out.stdout);
text.lines().nth(1)?.split_whitespace().nth(3)?.parse::<u64>().ok().map(|kb| kb / 1024)
}
/// The newest crash report in `logs`: (when, where) from its file.
pub fn last_crash(logs: &Path) -> Option<(String, String)> {
let mut reports: Vec<std::path::PathBuf> = std::fs::read_dir(logs).ok()?.flatten().map(|e| e.path()).filter(|p| p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("crash-"))).collect();
reports.sort();
let text = std::fs::read_to_string(reports.last()?).ok()?;
let field = |k: &str| text.lines().find_map(|l| l.strip_prefix(k)).unwrap_or("").trim().to_string();
Some((field("時間:"), field("位置:")))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_report_counts_what_is_wrong() {
let r = report(&[ok("版本 v1"), bad("模型服務 xAI:金鑰不對")]);
assert!(r.contains("✓ 版本 v1\n✗ 模型服務 xAI:金鑰不對") && r.ends_with("有 1 項要看一下(✗)。"), "{r}");
assert!(report(&[ok("a")]).ends_with("全部正常。"));
assert!(command(" /doctor ") && !command("/doctor x"));
}
#[test]
fn tailscale_says_direct_or_through_which_relay() {
assert_eq!(tailscale_host("https://nobledesktop.tailbcc3a6.ts.net:8443").as_deref(), Some("nobledesktop.tailbcc3a6.ts.net"));
assert_eq!(tailscale_host("https://example.com"), None);
let relayed = tailscale_path("pong from nobledesktop (100.82.106.34) via DERP(hkg) in 63ms\n").unwrap();
assert!(!relayed.ok && relayed.text.contains("「hkg」") && relayed.text.contains("63ms") && relayed.text.contains("41641"), "{relayed:?}");
let direct = tailscale_path("pong from nobledesktop (100.82.106.34) via 10.184.27.181:41641 in 4ms").unwrap();
assert!(direct.ok && direct.text.contains("10.184.27.181:41641"), "{direct:?}");
assert_eq!(tailscale_path("no reply"), None);
}
#[test]
fn the_sandbox_is_said_as_it_is() {
let l = sandbox_line();
if cfg!(target_os = "macos") {
assert!(l.ok && l.text.contains("sandbox-exec"), "{l:?}");
} else if cfg!(target_os = "linux") {
assert_eq!(l.ok, crate::landlock::abi().is_some(), "{l:?}");
} else {
assert!(!l.ok && l.text.contains("沒有沙盒"), "{l:?}");
}
}
#[test]
fn the_last_crash_and_the_disk() {
let d = std::env::temp_dir().join(format!("anybot-doctor-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
assert_eq!(last_crash(&d), None);
std::fs::write(d.join("crash-20261101-000000.000.seen.txt"), "時間:舊的\n位置:a.rs:1\n").unwrap();
std::fs::write(d.join("crash-20261117-104200.000.txt"), "時間:2026-11-17 10:42:00\n位置:src/app.rs:12\n").unwrap();
assert_eq!(last_crash(&d), Some(("2026-11-17 10:42:00".into(), "src/app.rs:12".into())));
if cfg!(unix) {
assert!(free_mb(&d).is_some_and(|mb| mb > 0));
}
let _ = std::fs::remove_dir_all(&d);
}
}