zc2 0.0.50

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
//! The machine check shared by `zc doctor`, `zc setup` and the desktop app's
//! first-run "Check this machine" screen (zc#509, plan snapshot S2).
//!
//! Every check is read-only and bounded in time: nothing here installs,
//! starts or signs in. `zc doctor --json` prints [`Report`], which the app
//! reads through its bundled zc.

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,
    /// Works, but something is worth knowing (shown, never blocks setup).
    Warn,
    /// Sharing cannot work until this is fixed.
    Fail,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Check {
    /// Stable id: `profile`, `signed_in`, `hub`, `cpu`, `memory`, `disk`,
    /// `runtime`, `node_key`, `action_key`.
    pub id: String,
    pub label: String,
    pub status: Status,
    pub detail: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Report {
    /// `lab` | `staging` | `prod`.
    pub env: String,
    pub api_url: String,
    pub os: String,
    pub arch: String,
    pub checks: Vec<Check>,
}

impl Report {
    /// No check failed.
    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(),
    }
}

/// Total memory in bytes.
pub fn total_memory() -> Option<u64> {
    #[cfg(target_os = "linux")]
    {
        let meminfo = std::fs::read_to_string("/proc/meminfo").ok()?;
        let read = |p: &str| std::fs::read_to_string(p).ok();
        let own = read("/proc/self/cgroup").unwrap_or_default();
        Some(effective_memory(
            meminfo_total(&meminfo)?,
            cgroup_memory_limit(&own, &read),
        ))
    }
    #[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
    }
}

/// `MemTotal` of `/proc/meminfo`, in bytes.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub fn meminfo_total(meminfo: &str) -> Option<u64> {
    let kb: u64 = meminfo
        .lines()
        .find(|l| l.starts_with("MemTotal:"))?
        .split_whitespace()
        .nth(1)?
        .parse()
        .ok()?;
    Some(kb * 1024)
}

/// The memory limit this process runs under, when one is visible: the lowest
/// cgroup v2 `memory.max` from its own cgroup (named by `/proc/self/cgroup`) up
/// to the namespace root, where an LXC's limit shows; else cgroup v1
/// `memory.limit_in_bytes`. "max" and unreadable files are no limit. Inside a
/// container `/proc/meminfo` usually shows the HOST's RAM, so a percentage
/// budget must be taken of this limit instead (zc#604). A process whose limit
/// sits on an ancestor it cannot see (a pod inside an LXC) still reads the
/// host's RAM: there, set an absolute `ZAKURO_BUDGET_MEMORY`.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub fn cgroup_memory_limit(
    self_cgroup: &str,
    read: &dyn Fn(&str) -> Option<String>,
) -> Option<u64> {
    let parse = |v: Option<String>| -> Option<u64> {
        let v = v?;
        let v = v.trim();
        if v == "max" {
            return None;
        }
        v.parse::<u64>().ok()
    };
    if let Some(path) = self_cgroup.lines().find_map(|l| l.strip_prefix("0::")) {
        let mut dir = path.trim().trim_end_matches('/').to_string();
        let mut lowest: Option<u64> = None;
        loop {
            if let Some(v) = parse(read(&format!("/sys/fs/cgroup{dir}/memory.max"))) {
                lowest = Some(lowest.map_or(v, |l| l.min(v)));
            }
            if dir.is_empty() {
                break;
            }
            dir = match dir.rfind('/') {
                Some(i) => dir[..i].to_string(),
                None => String::new(),
            };
        }
        if lowest.is_some() {
            return lowest;
        }
    }
    parse(read("/sys/fs/cgroup/memory/memory.limit_in_bytes"))
}

/// The memory this machine can use: its RAM, or a lower container limit.
/// cgroup v1 reports "no limit" as a huge number, which the `min` ignores.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub fn effective_memory(meminfo_total: u64, cgroup_limit: Option<u64>) -> u64 {
    match cgroup_limit {
        Some(l) if l > 0 => meminfo_total.min(l),
        _ => meminfo_total,
    }
}

/// Free bytes on the file system holding `path`.
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() };
        // SAFETY: `c` is a valid NUL-terminated path and `st` a writable statvfs.
        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;

/// What a machine needs to lend anything useful: below these, a warning.
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",
        ),
    }
}

/// `GET <hub>/api/health`, timed.
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)
}

/// Signed in = an API key in `~/.zakuro/credentials` (or `ZAKURO_API_KEY`).
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")
    }
}

/// Run every check. `with_network` adds the hub round trip.
pub fn machine_report(with_network: bool) -> Report {
    let resolved = crate::profile::resolve();
    let api_url = resolved.api_url.0.clone();
    // The hub this machine talks to names the environment: a LaunchAgent or
    // an app started from Finder has no ZAKURO_ENV, so the profile alone says
    // prod while `zc login --staging` pointed the credentials at staging.
    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()
        },
        // Workers run on the host without one; only containerised jobs need it.
        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,
    }
}

/// One line per check, as `zc doctor` and `zc setup` print them.
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());
    }

    #[test]
    fn a_container_memory_limit_lowers_the_total() {
        let meminfo = "MemTotal:       65728352 kB\nMemFree: 1 kB\n";
        let host = meminfo_total(meminfo).unwrap();
        assert_eq!(host, 65728352 * 1024);
        // cgroup v2, own path.
        let files = |p: &str| match p {
            "/sys/fs/cgroup/kubepods/pod1/c1/memory.max" => Some("17179869184\n".to_string()),
            _ => None,
        };
        let lim = cgroup_memory_limit("0::/kubepods/pod1/c1\n", &files);
        assert_eq!(lim, Some(17179869184));
        assert_eq!(effective_memory(host, lim), 17179869184);
        // cgroup v2: own cgroup unlimited, the limit on the namespace root (an LXC).
        let lxc = |p: &str| match p {
            "/sys/fs/cgroup/user.slice/session-1.scope/memory.max" => Some("max\n".to_string()),
            "/sys/fs/cgroup/user.slice/memory.max" => Some("max\n".to_string()),
            "/sys/fs/cgroup/memory.max" => Some("8589934592\n".to_string()),
            _ => None,
        };
        assert_eq!(
            cgroup_memory_limit("0::/user.slice/session-1.scope\n", &lxc),
            Some(8589934592)
        );
        // The lowest limit on the way up wins.
        let nested = |p: &str| match p {
            "/sys/fs/cgroup/a/b/memory.max" => Some("4294967296".to_string()),
            "/sys/fs/cgroup/memory.max" => Some("8589934592".to_string()),
            _ => None,
        };
        assert_eq!(cgroup_memory_limit("0::/a/b", &nested), Some(4294967296));
        // cgroup v2 with no limit ("max"): the host's RAM.
        let unlimited = |p: &str| (p == "/sys/fs/cgroup/memory.max").then(|| "max\n".to_string());
        assert_eq!(cgroup_memory_limit("0::/\n", &unlimited), None);
        // cgroup v1: a limit, and the "unlimited" sentinel the min ignores.
        let v1 = |p: &str| {
            (p == "/sys/fs/cgroup/memory/memory.limit_in_bytes").then(|| "8589934592".to_string())
        };
        assert_eq!(
            effective_memory(host, cgroup_memory_limit("", &v1)),
            8589934592
        );
        let v1_none = |p: &str| {
            (p == "/sys/fs/cgroup/memory/memory.limit_in_bytes")
                .then(|| "9223372036854771712".to_string())
        };
        assert_eq!(
            effective_memory(host, cgroup_memory_limit("", &v1_none)),
            host
        );
        // Nothing readable: the host's RAM.
        assert_eq!(
            effective_memory(host, cgroup_memory_limit("", &|_| None)),
            host
        );
    }
}