use serde::{Deserialize, Serialize};
use std::path::Path;
use std::time::{Duration, Instant};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Status {
Ok,
Warn,
Fail,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Check {
pub id: String,
pub label: String,
pub status: Status,
pub detail: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Report {
pub env: String,
pub api_url: String,
pub os: String,
pub arch: String,
pub checks: Vec<Check>,
}
impl Report {
pub fn ok(&self) -> bool {
self.checks.iter().all(|c| c.status != Status::Fail)
}
}
fn check(id: &str, label: impl Into<String>, status: Status, detail: impl Into<String>) -> Check {
Check {
id: id.into(),
label: label.into(),
status,
detail: detail.into(),
}
}
pub fn total_memory() -> Option<u64> {
#[cfg(target_os = "linux")]
{
let text = std::fs::read_to_string("/proc/meminfo").ok()?;
let kb: u64 = text
.lines()
.find(|l| l.starts_with("MemTotal:"))?
.split_whitespace()
.nth(1)?
.parse()
.ok()?;
Some(kb * 1024)
}
#[cfg(target_os = "macos")]
{
let out = std::process::Command::new("/usr/sbin/sysctl")
.args(["-n", "hw.memsize"])
.output()
.ok()?;
String::from_utf8_lossy(&out.stdout).trim().parse().ok()
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
{
None
}
}
pub fn free_disk(path: &Path) -> Option<u64> {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
let c = std::ffi::CString::new(path.as_os_str().as_bytes()).ok()?;
let mut st: libc::statvfs = unsafe { std::mem::zeroed() };
if unsafe { libc::statvfs(c.as_ptr(), &mut st) } != 0 {
return None;
}
#[allow(clippy::unnecessary_cast)]
Some(st.f_bavail as u64 * st.f_frsize as u64)
}
#[cfg(not(unix))]
{
let _ = path;
None
}
}
const GB: f64 = 1024.0 * 1024.0 * 1024.0;
const MIN_FREE_DISK_GB: f64 = 20.0;
const MIN_MEMORY_GB: f64 = 4.0;
pub fn cpu_check(cpus: usize) -> Check {
let lend = (cpus / 2).max(1);
check(
"cpu",
format!("{cpus} CPUs"),
if cpus >= 2 { Status::Ok } else { Status::Warn },
format!("lends up to {lend} by default (half, at least one)"),
)
}
pub fn memory_check(bytes: Option<u64>) -> Check {
match bytes {
Some(b) => {
let gb = b as f64 / GB;
check(
"memory",
format!("{gb:.0} GB memory"),
if gb >= MIN_MEMORY_GB {
Status::Ok
} else {
Status::Warn
},
if gb >= MIN_MEMORY_GB {
"enough for public jobs".to_string()
} else {
format!("under {MIN_MEMORY_GB:.0} GB: few jobs will fit")
},
)
}
None => check("memory", "Memory", Status::Warn, "could not read the total"),
}
}
pub fn disk_check(bytes: Option<u64>) -> Check {
match bytes {
Some(b) => {
let gb = b as f64 / GB;
check(
"disk",
format!("{gb:.0} GB free disk"),
if gb >= MIN_FREE_DISK_GB {
Status::Ok
} else {
Status::Warn
},
if gb >= MIN_FREE_DISK_GB {
"room for job images".to_string()
} else {
format!("under {MIN_FREE_DISK_GB:.0} GB: job images may not fit")
},
)
}
None => check(
"disk",
"Free disk",
Status::Warn,
"could not read free space",
),
}
}
fn hub_check(api_url: &str) -> Check {
let url = format!("{}/api/health", api_url.trim_end_matches('/'));
let agent = ureq::Agent::new_with_config(
ureq::Agent::config_builder()
.http_status_as_error(false)
.timeout_global(Some(Duration::from_secs(5)))
.build(),
);
let t = Instant::now();
match agent.get(&url).call() {
Ok(r) if r.status().is_success() => check(
"hub",
"Hub reachable",
Status::Ok,
format!("{} · {} ms", host_of(api_url), t.elapsed().as_millis()),
),
Ok(r) => check(
"hub",
"Hub reachable",
Status::Fail,
format!("{} answered HTTP {}", host_of(api_url), r.status().as_u16()),
),
Err(e) => check(
"hub",
"Hub reachable",
Status::Fail,
format!("{}: {e}", host_of(api_url)),
),
}
}
fn host_of(url: &str) -> &str {
let s = url.split("://").nth(1).unwrap_or(url);
s.split('/').next().unwrap_or(s)
}
pub fn signed_in_check(file_key: bool, env_key: bool) -> Check {
if file_key || env_key {
check(
"signed_in",
"Signed in",
Status::Ok,
if file_key {
"key in ~/.zakuro/credentials"
} else {
"ZAKURO_API_KEY"
},
)
} else {
check("signed_in", "Not signed in", Status::Fail, "run zc login")
}
}
pub fn machine_report(with_network: bool) -> Report {
let resolved = crate::profile::resolve();
let api_url = resolved.api_url.0.clone();
let env = crate::deeplink::env_for_api_url(Some(&api_url));
let state_dir = crate::credentials::dir();
let file_key = crate::credentials::path()
.and_then(|p| std::fs::read_to_string(p).ok())
.map(|t| crate::credentials::parse(&t))
.and_then(|m| m.get("api_key").cloned())
.is_some_and(|k| !k.trim().is_empty());
let env_key = std::env::var("ZAKURO_API_KEY").is_ok_and(|k| !k.trim().is_empty());
let mut checks = vec![check(
"profile",
format!("Profile {}", env.name()),
if resolved.unknown_env.is_some() {
Status::Warn
} else {
Status::Ok
},
match &resolved.unknown_env {
Some(v) => format!("ZAKURO_ENV={v:?} is not lab|staging|prod; using prod"),
None => host_of(&api_url).to_string(),
},
)];
checks.push(signed_in_check(file_key, env_key));
if with_network {
checks.push(hub_check(&api_url));
}
let cpus = std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(1);
checks.push(cpu_check(cpus));
checks.push(memory_check(total_memory()));
let home = state_dir
.clone()
.or_else(|| std::env::var_os("HOME").map(Into::into))
.unwrap_or_else(|| "/".into());
let probe_dir = if home.exists() { home } else { "/".into() };
checks.push(disk_check(free_disk(&probe_dir)));
let probe = crate::broker::deploy::runtime_probe();
checks.push(check(
"runtime",
if probe.available {
format!("Container runtime ({})", probe.runtime.unwrap_or("docker"))
} else {
"No container runtime".to_string()
},
if probe.available {
Status::Ok
} else {
Status::Warn
},
if probe.available {
"containerised jobs can run".to_string()
} else {
format!("host workers only: {}", probe.detail)
},
));
let node_key = crate::broker::node_identity::NodeKey::load_in(state_dir);
checks.push(match node_key {
Some(k) => check(
"node_key",
"Node identity",
Status::Ok,
format!("zc://node-{}", k.fingerprint()),
),
None => check(
"node_key",
"No node identity yet",
Status::Warn,
"created at sign-in or when sharing starts",
),
});
let link_env = env;
checks.push(match crate::deeplink::keys_for(link_env) {
Ok(k) if !k.is_empty() => check(
"action_key",
"Open in Zakuro links",
Status::Ok,
format!("hub key {}", k[0].kid),
),
Ok(_) => check(
"action_key",
"Open in Zakuro links off",
Status::Warn,
format!(
"no hub action key for {}; signed zakuro:// links are refused (set {})",
link_env.name(),
crate::deeplink::ENV_ACTION_PUBKEYS
),
),
Err(e) => check("action_key", "Open in Zakuro links", Status::Fail, e),
});
Report {
env: env.name().to_string(),
api_url,
os: std::env::consts::OS.to_string(),
arch: std::env::consts::ARCH.to_string(),
checks,
}
}
pub fn format_check(c: &Check) -> String {
let mark = match c.status {
Status::Ok => "✓",
Status::Warn => "!",
Status::Fail => "✗",
};
format!(" {mark} {:<30} {}", c.label, c.detail)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn thresholds_warn_but_never_fail_on_hardware() {
assert_eq!(cpu_check(12).status, Status::Ok);
assert!(cpu_check(12).detail.contains("up to 6"));
assert_eq!(cpu_check(1).status, Status::Warn);
assert_eq!(
memory_check(Some(36 * 1024 * 1024 * 1024)).label,
"36 GB memory"
);
assert_eq!(
memory_check(Some(2 * 1024 * 1024 * 1024)).status,
Status::Warn
);
assert_eq!(
disk_check(Some(10 * 1024 * 1024 * 1024)).status,
Status::Warn
);
assert_eq!(disk_check(None).status, Status::Warn);
assert_eq!(signed_in_check(false, false).status, Status::Fail);
assert_eq!(signed_in_check(false, true).detail, "ZAKURO_API_KEY");
}
#[test]
fn report_ok_means_nothing_failed() {
let r = Report {
env: "prod".into(),
api_url: "https://hub.zakuro-ai.com".into(),
os: "linux".into(),
arch: "x86_64".into(),
checks: vec![cpu_check(1), signed_in_check(true, false)],
};
assert!(r.ok());
let v = serde_json::to_value(&r).unwrap();
assert_eq!(v["checks"][0]["status"], "warn");
assert_eq!(
host_of("https://hub.zakuro-ai.com/api"),
"hub.zakuro-ai.com"
);
}
#[test]
fn the_real_machine_reads_without_network() {
let r = machine_report(false);
let ids: Vec<&str> = r.checks.iter().map(|c| c.id.as_str()).collect();
for id in [
"profile",
"signed_in",
"cpu",
"memory",
"disk",
"runtime",
"node_key",
"action_key",
] {
assert!(ids.contains(&id), "{id} in {ids:?}");
}
assert!(!ids.contains(&"hub"));
#[cfg(target_os = "linux")]
assert!(total_memory().unwrap() > 0);
#[cfg(unix)]
assert!(free_disk(Path::new("/")).is_some());
}
}