Skip to main content

astrs_cli/command/
doctor.rs

1//! `astrs doctor` (blueprint §17): environment checks that need no live
2//! daemon or coordinator — port availability, SHM limits, multicast
3//! availability, real-time scheduling capability (§11.3/§22), toolchain
4//! versions, runtime directory writability.
5
6use std::fmt;
7use std::io::Write;
8use std::path::PathBuf;
9
10// Only [`check_rt_capability`]'s Linux body reads this — the non-Linux
11// fallback below it is purely informational and names no priority number —
12// so importing it unconditionally would be an unused import on every other
13// platform.
14#[cfg(target_os = "linux")]
15use astrs_manifest::RT_PRIORITY_MAX;
16use serde::Serialize;
17
18use crate::error::CliError;
19
20/// The default coordinator port (blueprint §4.2: "Listens on TCP 7407
21/// (`ASTRS_COORDINATOR_PORT`; 7407 honors Atom's birthday 2003-04-07)").
22///
23/// Duplicated here (rather than depending on `astrs-transport`, which
24/// also defines `DEFAULT_COORDINATOR_PORT`) because this stage of
25/// `astrs-cli` has no other reason to depend on the transport crate at
26/// all — see this crate's top-level report for the deliberate deviation
27/// this is. Both constants must stay in sync; a snapshot test in this
28/// module pins the value.
29pub const DEFAULT_COORDINATOR_PORT: u16 = 7407;
30/// The default local daemon port (blueprint §4.2).
31pub const DEFAULT_DAEMON_PORT: u16 = 7408;
32
33/// Arguments for `astrs doctor`.
34#[derive(Debug, Clone)]
35pub struct DoctorArgs {
36    /// Emit the report as JSON instead of a table.
37    pub json: bool,
38    /// The coordinator port to probe.
39    pub coordinator_port: u16,
40    /// The local daemon port to probe.
41    pub daemon_port: u16,
42}
43
44impl Default for DoctorArgs {
45    fn default() -> Self {
46        Self {
47            json: false,
48            coordinator_port: DEFAULT_COORDINATOR_PORT,
49            daemon_port: DEFAULT_DAEMON_PORT,
50        }
51    }
52}
53
54/// How a [`DoctorCheck`] came out.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
56#[serde(rename_all = "snake_case")]
57pub enum CheckStatus {
58    /// Everything is as expected.
59    Ok,
60    /// Worth knowing, not a problem (e.g. a platform-specific check that
61    /// does not apply here).
62    Info,
63    /// Might be a problem; `astrs run`/`up` may still work.
64    Warning,
65    /// Very likely to break `astrs run`/`up`.
66    Error,
67}
68
69impl fmt::Display for CheckStatus {
70    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71        f.write_str(match self {
72            Self::Ok => "ok",
73            Self::Info => "info",
74            Self::Warning => "warning",
75            Self::Error => "error",
76        })
77    }
78}
79
80/// One environment check's outcome.
81#[derive(Debug, Clone, Serialize)]
82pub struct DoctorCheck {
83    /// A short, stable name (`"port:7407"`, `"toolchain:rustc"`, ...).
84    pub name: String,
85    /// The outcome.
86    pub status: CheckStatus,
87    /// A human-readable explanation, always present regardless of
88    /// [`Self::status`] (even a passing check says what it found).
89    pub detail: String,
90}
91
92/// The complete `astrs doctor` report.
93#[derive(Debug, Clone, Serialize)]
94pub struct DoctorReport {
95    /// Every check, in a fixed, deterministic order.
96    pub checks: Vec<DoctorCheck>,
97}
98
99impl DoctorReport {
100    /// `1` if any check is [`CheckStatus::Error`], else `0`.
101    #[must_use]
102    pub fn exit_code(&self) -> i32 {
103        i32::from(self.checks.iter().any(|c| c.status == CheckStatus::Error))
104    }
105}
106
107/// Run every `astrs doctor` check and print the report to `out`.
108///
109/// Always returns `Ok` unless writing to `out` fails — every check that
110/// can go wrong reports [`CheckStatus::Error`]/[`CheckStatus::Warning`]
111/// as *content*, matching `validate`'s own "diagnostic tools report, they
112/// do not abort" convention.
113///
114/// # Errors
115///
116/// Returns [`CliError::Io`] if writing to `out` fails.
117pub fn run(out: &mut dyn Write, args: &DoctorArgs) -> Result<DoctorReport, CliError> {
118    let checks = vec![
119        check_port("port:coordinator", args.coordinator_port),
120        check_port("port:daemon", args.daemon_port),
121        check_shm(),
122        check_multicast(),
123        check_rt_capability(),
124        check_toolchain("rustc"),
125        check_toolchain("cargo"),
126        check_runtime_dir(),
127    ];
128    let report = DoctorReport { checks };
129
130    if args.json {
131        let json = serde_json::to_string_pretty(&report).unwrap_or_else(|err| {
132            format!("{{\"error\": \"failed to serialize doctor report: {err}\"}}")
133        });
134        writeln!(out, "{json}").map_err(|e| CliError::io("<output>", e))?;
135    } else {
136        writeln!(out, "{}", render_table(&report)).map_err(|e| CliError::io("<output>", e))?;
137    }
138
139    Ok(report)
140}
141
142/// Probe whether `port` is currently bindable on loopback.
143fn check_port(name: &str, port: u16) -> DoctorCheck {
144    match std::net::TcpListener::bind(("127.0.0.1", port)) {
145        Ok(_listener) => DoctorCheck {
146            name: name.to_string(),
147            status: CheckStatus::Ok,
148            detail: format!("127.0.0.1:{port} is available"),
149        },
150        Err(err) if err.kind() == std::io::ErrorKind::AddrInUse => DoctorCheck {
151            name: name.to_string(),
152            status: CheckStatus::Warning,
153            detail: format!(
154                "127.0.0.1:{port} is already in use (a daemon/coordinator may already be running): {err}"
155            ),
156        },
157        Err(err) => DoctorCheck {
158            name: name.to_string(),
159            status: CheckStatus::Error,
160            detail: format!("could not probe 127.0.0.1:{port}: {err}"),
161        },
162    }
163}
164
165/// The multicast group RTPS SPDP participant discovery uses (blueprint
166/// §10: "SPDP: multicast 239.255.0.1, standard port mapping"). Probed
167/// directly rather than guessed at: joining it end to end is a much
168/// stronger signal than checking for the presence of a multicast-capable
169/// interface, and it is the exact address AstRS's own ROS 2 bridge will
170/// need later.
171const RTPS_SPDP_GROUP: std::net::Ipv4Addr = std::net::Ipv4Addr::new(239, 255, 0, 1);
172
173/// Probe UDP multicast join capability (blueprint §17: "multicast
174/// availability").
175///
176/// [`CheckStatus::Warning`], never [`CheckStatus::Error`], on failure:
177/// multicast is only needed for ROS 2 discovery (blueprint §10) — AstRS's
178/// own control plane (coordinator/daemon registration, §6.2–§6.4) never
179/// uses it, so a dataflow-only AstRS install is unaffected.
180fn check_multicast() -> DoctorCheck {
181    let name = "multicast".to_string();
182    let socket = match std::net::UdpSocket::bind("0.0.0.0:0") {
183        Ok(socket) => socket,
184        Err(err) => {
185            return DoctorCheck {
186                name,
187                status: CheckStatus::Warning,
188                detail: format!("could not open a UDP socket to probe multicast: {err}"),
189            };
190        }
191    };
192    match socket.join_multicast_v4(&RTPS_SPDP_GROUP, &std::net::Ipv4Addr::UNSPECIFIED) {
193        Ok(()) => DoctorCheck {
194            name,
195            status: CheckStatus::Ok,
196            detail: format!("joined the RTPS SPDP probe group {RTPS_SPDP_GROUP} successfully"),
197        },
198        Err(err) => DoctorCheck {
199            name,
200            status: CheckStatus::Warning,
201            detail: format!(
202                "could not join multicast group {RTPS_SPDP_GROUP}: {err} (ROS 2 discovery, \
203                 blueprint §10, will not work on this network; AstRS's own control plane does \
204                 not use multicast and is unaffected)"
205            ),
206        },
207    }
208}
209
210/// Probe this process's real-time scheduling capability (hard-RT executor
211/// reservations, blueprint §11.3/§22): the highest `sched_priority` a
212/// manifest `rt: { policy: fifo|rr, priority: N }` block could actually
213/// apply, combining `CAP_SYS_NICE` (unbounded — the full POSIX `1..=99`
214/// range regardless of any rlimit) with the `RLIMIT_RTPRIO` soft limit (the
215/// ceiling without it — `0`, the default for an unprivileged process, means
216/// none at all). Mirrors exactly what `astrs-daemon`'s `spawn::rt` module
217/// checks right before it would otherwise hit `EPERM`, so a `rt:`-using
218/// manifest's failure mode is visible before `astrs run` ever attempts it.
219#[cfg(target_os = "linux")]
220fn check_rt_capability() -> DoctorCheck {
221    let name = "rt".to_string();
222    let capabilities = match rustix::thread::capabilities(None) {
223        Ok(capabilities) => capabilities,
224        Err(err) => {
225            return DoctorCheck {
226                name,
227                status: CheckStatus::Warning,
228                detail: format!("could not read this process's capabilities: {err}"),
229            };
230        }
231    };
232    let has_cap_sys_nice = capabilities
233        .effective
234        .contains(rustix::thread::CapabilitySet::SYS_NICE);
235    let rtprio_soft = rustix::process::getrlimit(rustix::process::Resource::Rtprio)
236        .current
237        .unwrap_or(u64::MAX);
238    let max_priority = if has_cap_sys_nice {
239        u64::from(RT_PRIORITY_MAX)
240    } else {
241        rtprio_soft.min(u64::from(RT_PRIORITY_MAX))
242    };
243
244    if max_priority == 0 {
245        DoctorCheck {
246            name,
247            status: CheckStatus::Warning,
248            detail: "no real-time scheduling available: this process has neither \
249                     CAP_SYS_NICE nor an RLIMIT_RTPRIO soft limit above 0 — a manifest \
250                     `rt: { policy: fifo|rr, ... }` node will fail to spawn with EPERM. \
251                     Grant CAP_SYS_NICE to the daemon binary (e.g. \
252                     `setcap cap_sys_nice+ep <path-to-astrs-daemon>`) or raise \
253                     RLIMIT_RTPRIO for the user running it (e.g. an `rtprio` line in \
254                     /etc/security/limits.conf) to use it."
255                .to_string(),
256        }
257    } else {
258        DoctorCheck {
259            name,
260            status: CheckStatus::Ok,
261            detail: format!(
262                "real-time scheduling available up to priority {max_priority} (via {})",
263                if has_cap_sys_nice {
264                    "CAP_SYS_NICE"
265                } else {
266                    "RLIMIT_RTPRIO"
267                }
268            ),
269        }
270    }
271}
272
273/// Non-Linux platforms: `rt:` has no application implemented at all (see
274/// `astrs-daemon::spawn::rt`'s own module docs) — reported plainly, the same
275/// honest-fallback framing [`check_shm`] gives macOS's missing `/dev/shm`.
276#[cfg(not(target_os = "linux"))]
277fn check_rt_capability() -> DoctorCheck {
278    DoctorCheck {
279        name: "rt".to_string(),
280        status: CheckStatus::Info,
281        detail: "real-time scheduling reservations (rt:) are Linux-only; this platform \
282                 always runs nodes under the ordinary time-sharing class regardless of any \
283                 rt: block in the manifest"
284            .to_string(),
285    }
286}
287
288/// Format a byte count with the nearest binary unit, e.g. `1536` →
289/// `"1.5 KiB"`.
290fn human_bytes(bytes: u64) -> String {
291    const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
292    let mut value = bytes as f64;
293    let mut unit = 0;
294    while value >= 1024.0 && unit < UNITS.len() - 1 {
295        value /= 1024.0;
296        unit += 1;
297    }
298    if unit == 0 {
299        format!("{bytes} {}", UNITS[0])
300    } else {
301        format!("{value:.1} {}", UNITS[unit])
302    }
303}
304
305/// `/dev/shm` size on Linux (a real `statvfs`, via `rustix`, already used
306/// elsewhere in this workspace for the same syscall); a documented,
307/// `sysctl`-free informational note everywhere else (blueprint §17:
308/// "macOS SC limits" — stock macOS has no `/dev/shm` mount at all, and
309/// this importer deliberately never shells out to `sysctl(8)` to
310/// approximate a kernel SHM limit; [`check_runtime_dir`] already
311/// functionally probes the directory AstRS's own SHM broker actually
312/// needs writable).
313#[cfg(unix)]
314fn check_shm() -> DoctorCheck {
315    match rustix::fs::statvfs("/dev/shm") {
316        Ok(stat) => {
317            let total = stat.f_frsize.saturating_mul(stat.f_blocks);
318            let available = stat.f_frsize.saturating_mul(stat.f_bavail);
319            DoctorCheck {
320                name: "shm".to_string(),
321                status: CheckStatus::Ok,
322                detail: format!(
323                    "/dev/shm: {} total, {} available",
324                    human_bytes(total),
325                    human_bytes(available)
326                ),
327            }
328        }
329        Err(_) => DoctorCheck {
330            name: "shm".to_string(),
331            status: CheckStatus::Info,
332            detail: "/dev/shm is not present on this platform (expected on macOS); AstRS's \
333                     POSIX shared memory (shm_open) does not require it, and this check \
334                     deliberately does not shell out to `sysctl` to approximate a kernel limit \
335                     — see the runtime-dir check for a real writability probe instead"
336                .to_string(),
337        },
338    }
339}
340
341/// Non-Unix platforms (Windows): SHM introspection is not implemented —
342/// reported plainly rather than silently skipped.
343#[cfg(not(unix))]
344fn check_shm() -> DoctorCheck {
345    DoctorCheck {
346        name: "shm".to_string(),
347        status: CheckStatus::Info,
348        detail: "SHM introspection is implemented for Unix platforms only".to_string(),
349    }
350}
351
352/// Run `<binary> --version` and report its output.
353fn check_toolchain(binary: &str) -> DoctorCheck {
354    let name = format!("toolchain:{binary}");
355    match std::process::Command::new(binary).arg("--version").output() {
356        Ok(output) if output.status.success() => DoctorCheck {
357            name,
358            status: CheckStatus::Ok,
359            detail: String::from_utf8_lossy(&output.stdout).trim().to_string(),
360        },
361        Ok(output) => DoctorCheck {
362            name,
363            status: CheckStatus::Error,
364            detail: format!("`{binary} --version` exited with {}", output.status),
365        },
366        Err(err) => DoctorCheck {
367            name,
368            status: CheckStatus::Error,
369            detail: format!("could not run `{binary} --version`: {err}"),
370        },
371    }
372}
373
374/// The directory the daemon's Unix domain socket lives in (blueprint
375/// §4.2: `$XDG_RUNTIME_DIR/astrs/daemon.sock`), or the documented
376/// fallback when `XDG_RUNTIME_DIR` is unset (routine on macOS) — created
377/// if missing, then probed with a real create-and-remove write, not just
378/// a metadata check.
379fn check_runtime_dir() -> DoctorCheck {
380    let (dir, source) = runtime_dir();
381    if let Err(err) = std::fs::create_dir_all(&dir) {
382        return DoctorCheck {
383            name: "runtime_dir".to_string(),
384            status: CheckStatus::Error,
385            detail: format!("could not create `{}` ({source}): {err}", dir.display()),
386        };
387    }
388    let probe = dir.join(format!(".astrs-doctor-probe-{}", std::process::id()));
389    match std::fs::write(&probe, b"astrs doctor probe") {
390        Ok(()) => {
391            let _ = std::fs::remove_file(&probe);
392            DoctorCheck {
393                name: "runtime_dir".to_string(),
394                status: CheckStatus::Ok,
395                detail: format!("`{}` is writable ({source})", dir.display()),
396            }
397        }
398        Err(err) => DoctorCheck {
399            name: "runtime_dir".to_string(),
400            status: CheckStatus::Error,
401            detail: format!("`{}` exists but is not writable: {err}", dir.display()),
402        },
403    }
404}
405
406/// Resolve the runtime directory and name where it came from.
407fn runtime_dir() -> (PathBuf, &'static str) {
408    match std::env::var_os("XDG_RUNTIME_DIR") {
409        Some(value) if !value.is_empty() => (PathBuf::from(value).join("astrs"), "XDG_RUNTIME_DIR"),
410        _ => (
411            std::env::temp_dir().join("astrs"),
412            "std::env::temp_dir() fallback (XDG_RUNTIME_DIR unset)",
413        ),
414    }
415}
416
417/// Render the report as a plain, fixed-width table.
418fn render_table(report: &DoctorReport) -> String {
419    let name_width = report
420        .checks
421        .iter()
422        .map(|c| c.name.len())
423        .max()
424        .unwrap_or(4)
425        .max(4);
426    let mut out = String::new();
427    for check in &report.checks {
428        out.push_str(&format!(
429            "{:<name_width$}  {:<7}  {}\n",
430            check.name,
431            check.status.to_string(),
432            check.detail,
433        ));
434    }
435    out.push_str(&format!(
436        "\n{} check(s), exit code {}",
437        report.checks.len(),
438        report.exit_code()
439    ));
440    out
441}
442
443#[cfg(test)]
444mod tests {
445    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
446    use super::*;
447
448    #[test]
449    fn a_bound_port_is_reported_in_use() {
450        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
451        let port = listener.local_addr().unwrap().port();
452        let check = check_port("port:test", port);
453        assert_eq!(check.status, CheckStatus::Warning);
454        drop(listener);
455    }
456
457    #[test]
458    fn a_freed_port_is_reported_available() {
459        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
460        let port = listener.local_addr().unwrap().port();
461        drop(listener);
462        let check = check_port("port:test", port);
463        assert_eq!(check.status, CheckStatus::Ok);
464    }
465
466    #[test]
467    fn human_bytes_formats_common_magnitudes() {
468        assert_eq!(human_bytes(512), "512 B");
469        assert_eq!(human_bytes(1536), "1.5 KiB");
470        assert_eq!(human_bytes(1024 * 1024 * 2), "2.0 MiB");
471    }
472
473    #[test]
474    fn shm_check_never_errors_only_ok_or_info() {
475        let check = check_shm();
476        assert!(matches!(check.status, CheckStatus::Ok | CheckStatus::Info));
477    }
478
479    #[test]
480    fn toolchain_checks_find_rustc_and_cargo_in_this_dev_environment() {
481        // This crate cannot build at all without a working rustc/cargo,
482        // so both must be found in the environment running this test.
483        let rustc = check_toolchain("rustc");
484        assert_eq!(rustc.status, CheckStatus::Ok, "{rustc:?}");
485        let cargo = check_toolchain("cargo");
486        assert_eq!(cargo.status, CheckStatus::Ok, "{cargo:?}");
487    }
488
489    #[test]
490    fn toolchain_check_reports_error_for_a_nonexistent_binary() {
491        let check = check_toolchain("astrs-doctor-definitely-does-not-exist-as-a-binary");
492        assert_eq!(check.status, CheckStatus::Error);
493    }
494
495    #[test]
496    fn runtime_dir_check_creates_and_probes_writability() {
497        let check = check_runtime_dir();
498        assert_eq!(check.status, CheckStatus::Ok, "{check:?}");
499    }
500
501    #[test]
502    fn multicast_check_never_errors_only_ok_or_warning() {
503        // CI/sandboxed network namespaces routinely cannot join
504        // multicast groups at all -- this must degrade to a warning,
505        // never an error, and never panic either way.
506        let check = check_multicast();
507        assert!(
508            matches!(check.status, CheckStatus::Ok | CheckStatus::Warning),
509            "{check:?}"
510        );
511        assert!(check.detail.contains("239.255.0.1"));
512    }
513
514    #[test]
515    fn full_report_has_eight_checks_and_exit_code_is_zero_or_one() {
516        let mut out = Vec::new();
517        let report = run(&mut out, &DoctorArgs::default()).unwrap();
518        assert_eq!(report.checks.len(), 8);
519        assert!(report.exit_code() == 0 || report.exit_code() == 1);
520    }
521
522    #[test]
523    fn rt_capability_check_never_errors_only_ok_warning_or_info() {
524        // Whatever this test process's own capabilities are (root, a
525        // container with CAP_SYS_NICE dropped, macOS with no concept of
526        // either) — never a panic, never CheckStatus::Error.
527        let check = check_rt_capability();
528        assert!(
529            matches!(
530                check.status,
531                CheckStatus::Ok | CheckStatus::Warning | CheckStatus::Info
532            ),
533            "{check:?}"
534        );
535        assert_eq!(check.name, "rt");
536    }
537
538    #[cfg(target_os = "linux")]
539    #[test]
540    fn rt_capability_check_names_the_grant_when_unavailable() {
541        let check = check_rt_capability();
542        if check.status == CheckStatus::Warning {
543            assert!(check.detail.contains("CAP_SYS_NICE"), "{}", check.detail);
544            assert!(check.detail.contains("RLIMIT_RTPRIO"), "{}", check.detail);
545        }
546    }
547
548    #[cfg(not(target_os = "linux"))]
549    #[test]
550    fn rt_capability_check_is_informational_off_linux() {
551        let check = check_rt_capability();
552        assert_eq!(check.status, CheckStatus::Info);
553        assert!(check.detail.contains("Linux-only"), "{}", check.detail);
554    }
555
556    #[test]
557    fn json_output_round_trips_every_check() {
558        let mut out = Vec::new();
559        let args = DoctorArgs {
560            json: true,
561            ..DoctorArgs::default()
562        };
563        let report = run(&mut out, &args).unwrap();
564        let text = String::from_utf8(out).unwrap();
565        let value: serde_json::Value = serde_json::from_str(&text).unwrap();
566        assert_eq!(
567            value["checks"].as_array().map(Vec::len),
568            Some(report.checks.len())
569        );
570    }
571
572    #[test]
573    fn table_output_lists_every_check_name() {
574        let mut out = Vec::new();
575        let report = run(&mut out, &DoctorArgs::default()).unwrap();
576        let text = String::from_utf8(out).unwrap();
577        for check in &report.checks {
578            assert!(
579                text.contains(&check.name),
580                "missing {} in:\n{text}",
581                check.name
582            );
583        }
584    }
585
586    #[test]
587    fn default_ports_match_the_blueprint() {
588        assert_eq!(DEFAULT_COORDINATOR_PORT, 7407);
589        assert_eq!(DEFAULT_DAEMON_PORT, 7408);
590    }
591}