1use std::fmt;
7use std::io::Write;
8use std::path::PathBuf;
9
10#[cfg(target_os = "linux")]
15use astrs_manifest::RT_PRIORITY_MAX;
16use serde::Serialize;
17
18use crate::error::CliError;
19
20pub const DEFAULT_COORDINATOR_PORT: u16 = 7407;
30pub const DEFAULT_DAEMON_PORT: u16 = 7408;
32
33#[derive(Debug, Clone)]
35pub struct DoctorArgs {
36 pub json: bool,
38 pub coordinator_port: u16,
40 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
56#[serde(rename_all = "snake_case")]
57pub enum CheckStatus {
58 Ok,
60 Info,
63 Warning,
65 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#[derive(Debug, Clone, Serialize)]
82pub struct DoctorCheck {
83 pub name: String,
85 pub status: CheckStatus,
87 pub detail: String,
90}
91
92#[derive(Debug, Clone, Serialize)]
94pub struct DoctorReport {
95 pub checks: Vec<DoctorCheck>,
97}
98
99impl DoctorReport {
100 #[must_use]
102 pub fn exit_code(&self) -> i32 {
103 i32::from(self.checks.iter().any(|c| c.status == CheckStatus::Error))
104 }
105}
106
107pub 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
142fn 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
165const RTPS_SPDP_GROUP: std::net::Ipv4Addr = std::net::Ipv4Addr::new(239, 255, 0, 1);
172
173fn 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#[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#[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
288fn 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#[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#[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
352fn 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
374fn 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
406fn 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
417fn 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 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 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 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}