arcbox-cli 0.6.8

Command-line interface for ArcBox
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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
//! End-to-end health checks for the paths users actually invoke.

use std::fmt::Write as _;
use std::path::Path;
use std::time::Duration;

use anyhow::{Context, Result, bail};
use arcbox_connect::v1 as pb;
use arcbox_connect::v1::SystemServiceClient;
use arcbox_constants::paths::ArcboxProfile;
use serde::Serialize;
use tokio::process::Command;

use crate::connect;

use super::OutputFormat;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
enum CheckState {
    Pass,
    Fail,
    /// The check could not be run. Reported, but never counted as a failure —
    /// see `ComponentStatus::Unknown` in the setup status module.
    Unknown,
}

#[derive(Debug, Clone, Serialize)]
struct HealthCheck {
    name: &'static str,
    status: CheckState,
    detail: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    repair: Option<&'static str>,
}

impl HealthCheck {
    fn pass(name: &'static str, detail: impl Into<String>) -> Self {
        Self {
            name,
            status: CheckState::Pass,
            detail: detail.into(),
            repair: None,
        }
    }

    fn fail(name: &'static str, detail: impl Into<String>, repair: &'static str) -> Self {
        Self {
            name,
            status: CheckState::Fail,
            detail: detail.into(),
            repair: Some(repair),
        }
    }

    fn unknown(name: &'static str, detail: impl Into<String>) -> Self {
        Self {
            name,
            status: CheckState::Unknown,
            detail: detail.into(),
            repair: None,
        }
    }
}

#[derive(Debug, Clone, Serialize)]
struct Summary {
    passed: usize,
    failed: usize,
    unknown: usize,
}

#[derive(Debug, Clone, Serialize)]
struct DoctorReport {
    healthy: bool,
    checks: Vec<HealthCheck>,
    summary: Summary,
}

impl DoctorReport {
    fn new(checks: Vec<HealthCheck>) -> Self {
        let count = |state: CheckState| checks.iter().filter(|c| c.status == state).count();
        let (passed, failed, unknown) = (
            count(CheckState::Pass),
            count(CheckState::Fail),
            count(CheckState::Unknown),
        );
        Self {
            healthy: failed == 0,
            checks,
            summary: Summary {
                passed,
                failed,
                unknown,
            },
        }
    }

    fn table(&self) -> String {
        let mut output = String::from("ArcBox Doctor\n\n");
        for check in &self.checks {
            let state = match check.status {
                CheckState::Pass => "PASS",
                CheckState::Fail => "FAIL",
                CheckState::Unknown => "UNKN",
            };
            writeln!(output, "  [{state}] {}: {}", check.name, check.detail)
                .expect("writing to a String cannot fail");
            if let Some(repair) = check.repair {
                writeln!(output, "         Repair: {repair}")
                    .expect("writing to a String cannot fail");
            }
        }
        write!(
            output,
            "\n{} passed, {} failed",
            self.summary.passed, self.summary.failed
        )
        .expect("writing to a String cannot fail");
        if self.summary.unknown > 0 {
            write!(output, ", {} unknown", self.summary.unknown)
                .expect("writing to a String cannot fail");
        }
        output
    }
}

/// Runs all diagnostic checks and prints one coherent report.
pub async fn execute(format: OutputFormat) -> Result<()> {
    let report = inspect().await;
    match format {
        OutputFormat::Table => println!("{}", report.table()),
        OutputFormat::Json => println!("{}", serde_json::to_string(&report)?),
        OutputFormat::Quiet => bail!("quiet output is not supported for doctor"),
    }
    if !report.healthy {
        bail!("ArcBox health checks failed");
    }
    Ok(())
}

async fn inspect() -> DoctorReport {
    let layout = arcbox_constants::paths::HostLayout::from_env_or_default();
    let mut checks = Vec::new();
    if let Err(error) = arcbox_core::Config::load() {
        checks.push(HealthCheck::fail(
            "Configuration",
            format!("{error:#}"),
            "Fix the active ArcBox configuration, then rerun doctor.",
        ));
    }
    let expected_socket = super::resolve_docker_socket_path();
    checks.push(check_daemon(&layout, &expected_socket));
    checks.push(check_docker_context(&expected_socket).await);
    checks.push(check_docker_cli().await);

    let shell = super::setup::shell_integration_status().await;
    checks.push(shell_check(
        "CLI symlink",
        &shell.bin_symlink,
        || {
            shell
                .bin_symlink
                .path
                .clone()
                .unwrap_or_else(|| "ArcBox abctl".to_owned())
        },
        || {
            shell.bin_symlink.path.clone().map_or_else(
                || "ArcBox abctl symlink is missing".to_owned(),
                |path| format!("missing {path}"),
            )
        },
        "Run `abctl setup install`.",
    ));
    checks.push(shell_check(
        "Shell profile",
        &shell.profile,
        || {
            shell
                .profile
                .path
                .clone()
                .unwrap_or_else(|| shell.shell.clone())
        },
        || {
            shell
                .profile
                .path
                .clone()
                .unwrap_or_else(|| "profile not detected".to_owned())
        },
        "Run `abctl setup install`.",
    ));
    checks.push(shell_check(
        "Shell PATH",
        &shell.login_path,
        || "login shell resolves ArcBox abctl".to_owned(),
        || "login shell does not resolve ArcBox abctl".to_owned(),
        "Run `abctl setup install`, then restart the shell.",
    ));
    checks.push(shell_check(
        "Shell completion",
        &shell.completions,
        || "discoverable in the login shell".to_owned(),
        || "completion is not discoverable".to_owned(),
        "Run `abctl setup install`, then restart the shell.",
    ));

    #[cfg(target_os = "macos")]
    add_macos_checks(&mut checks).await;

    DoctorReport::new(checks)
}

/// Maps a shell-integration component onto a doctor check.
///
/// A component whose check could not run stays `Unknown` here too: reporting
/// it as a failure would tell the user to repair an install that may be
/// perfectly healthy, and would fail `doctor` on a probe's own bad day.
fn shell_check(
    name: &'static str,
    component: &super::setup::ComponentStatus,
    passed: impl FnOnce() -> String,
    failed: impl FnOnce() -> String,
    repair: &'static str,
) -> HealthCheck {
    if component.is_ok() {
        HealthCheck::pass(name, passed())
    } else if component.is_failed() {
        HealthCheck::fail(
            name,
            component.detail.clone().unwrap_or_else(failed),
            repair,
        )
    } else {
        HealthCheck::unknown(
            name,
            component
                .detail
                .clone()
                .unwrap_or_else(|| format!("{name} could not be checked")),
        )
    }
}

fn check_daemon(layout: &arcbox_constants::paths::HostLayout, socket: &Path) -> HealthCheck {
    if !super::daemon::daemon_is_alive(&layout.lock_file) {
        return HealthCheck::fail(
            "Daemon",
            "daemon lock is not held",
            "Start the ArcBox daemon.",
        );
    }
    if !socket.exists() {
        return HealthCheck::fail(
            "Daemon",
            format!("Docker socket is missing at {}", socket.display()),
            "Restart the ArcBox daemon.",
        );
    }
    HealthCheck::pass("Daemon", format!("running ({})", socket.display()))
}

async fn check_docker_context(expected: &Path) -> HealthCheck {
    let output = match run_docker(&[
        "context",
        "inspect",
        "--format",
        "{{.Endpoints.docker.Host}}",
    ])
    .await
    {
        Ok(output) => output,
        Err(error) => {
            return HealthCheck::fail("Docker context", error, "Run `abctl docker setup`.");
        }
    };
    let endpoint = output.trim();
    match endpoint_matches_socket(endpoint, expected) {
        Ok(true) => HealthCheck::pass("Docker context", endpoint),
        Ok(false) => HealthCheck::fail(
            "Docker context",
            format!("{endpoint} does not select unix://{}", expected.display()),
            "Run `abctl docker setup` or select the ArcBox Docker context.",
        ),
        Err(error) => HealthCheck::fail(
            "Docker context",
            error,
            "Select a Docker context backed by the ArcBox Unix socket.",
        ),
    }
}

async fn check_docker_cli() -> HealthCheck {
    match run_docker(&["ps", "--format", "{{.ID}}"]).await {
        Ok(_) => HealthCheck::pass("Docker CLI", "`docker ps` completed"),
        Err(error) => HealthCheck::fail(
            "Docker CLI",
            error,
            "Fix the selected Docker context, then restart ArcBox if needed.",
        ),
    }
}

async fn run_docker(arguments: &[&str]) -> std::result::Result<String, String> {
    let context =
        arcbox_cli::runtime_selection::docker_context_name().map_err(|error| error.to_string())?;
    let mut command = Command::new("docker");
    command
        .args(["--context", &context])
        .args(arguments)
        .kill_on_drop(true);
    let output = tokio::time::timeout(Duration::from_secs(5), command.output())
        .await
        .map_err(|_| format!("docker {} timed out", arguments.join(" ")))?
        .map_err(|error| format!("could not execute docker: {error}"))?;
    if !output.status.success() {
        return Err(format!(
            "docker {} failed: {}",
            arguments.join(" "),
            String::from_utf8_lossy(&output.stderr).trim()
        ));
    }
    String::from_utf8(output.stdout).map_err(|_| "docker output was not UTF-8".to_owned())
}

fn endpoint_matches_socket(endpoint: &str, expected: &Path) -> Result<bool, String> {
    let path = endpoint
        .strip_prefix("unix://")
        .ok_or_else(|| format!("Docker endpoint is not a Unix socket: {endpoint}"))?;
    let actual = Path::new(path);
    if actual == expected {
        return Ok(true);
    }
    let actual = std::fs::canonicalize(actual)
        .map_err(|error| format!("could not resolve Docker endpoint {endpoint}: {error}"))?;
    let expected = std::fs::canonicalize(expected).map_err(|error| {
        format!(
            "could not resolve expected Docker socket {}: {error}",
            expected.display()
        )
    })?;
    Ok(actual == expected)
}

#[cfg(target_os = "macos")]
async fn add_macos_checks(checks: &mut Vec<HealthCheck>) {
    if ArcboxProfile::from_env_or_default() == ArcboxProfile::Development {
        match setup_status().await {
            Ok(status) => {
                checks.push(if status.dns_resolver_installed {
                    HealthCheck::pass("DNS resolver", "installed for this instance")
                } else {
                    HealthCheck::fail(
                        "DNS resolver",
                        "not installed for this instance",
                        "Restart the ArcBox development instance.",
                    )
                });
                checks.push(if status.route_installed {
                    HealthCheck::pass("Container route", "installed for this instance")
                } else {
                    HealthCheck::fail(
                        "Container route",
                        "not installed for this instance",
                        "Restart the ArcBox development instance.",
                    )
                });
            }
            Err(error) => checks.push(HealthCheck::fail(
                "Instance networking",
                format!("status query failed: {error}"),
                "Restart the ArcBox development instance.",
            )),
        }
        checks.push(check_helper().await);
        return;
    }

    let dns = super::dns::inspect_status().await;
    checks.push(if dns.resolver_installed {
        HealthCheck::pass("DNS resolver", dns.resolver_path)
    } else {
        HealthCheck::fail(
            "DNS resolver",
            dns.resolver_error
                .unwrap_or_else(|| format!("missing {}", dns.resolver_path)),
            "Run `sudo abctl dns install`.",
        )
    });
    checks.push(match &dns.health {
        super::dns::DnsHealth::Healthy => HealthCheck::pass(
            "DNS service",
            format!("{} answered {}", dns.server_address, dns.query_name),
        ),
        super::dns::DnsHealth::DaemonDown => HealthCheck::fail(
            "DNS service",
            "ArcBox daemon is not running",
            "Start the ArcBox daemon.",
        ),
        super::dns::DnsHealth::Negative {
            response_code,
            description,
        } => HealthCheck::fail(
            "DNS service",
            format!("negative response {response_code}: {description}"),
            "Check the ArcBox daemon logs and DNS listener configuration.",
        ),
        super::dns::DnsHealth::ListenerAbsent => HealthCheck::fail(
            "DNS service",
            format!("no UDP listener at {}", dns.server_address),
            "Check the ArcBox daemon logs and DNS listener configuration.",
        ),
        super::dns::DnsHealth::TimedOut => HealthCheck::fail(
            "DNS service",
            format!("UDP query to {} timed out", dns.server_address),
            "Check the ArcBox daemon logs and DNS listener configuration.",
        ),
        super::dns::DnsHealth::Malformed { error } => HealthCheck::fail(
            "DNS service",
            format!("malformed response: {error}"),
            "Check the ArcBox daemon logs and DNS listener configuration.",
        ),
        super::dns::DnsHealth::Io { error } => HealthCheck::fail(
            "DNS service",
            format!("UDP probe failed: {error}"),
            "Check the ArcBox daemon logs and DNS listener configuration.",
        ),
    });
    checks.push(match &dns.system_resolver {
        super::dns::SystemResolverHealth::Healthy => HealthCheck::pass(
            "DNS system lookup",
            format!("{} resolved through macOS", dns.query_name),
        ),
        super::dns::SystemResolverHealth::TimedOut => HealthCheck::fail(
            "DNS system lookup",
            format!("resolving {} timed out", dns.query_name),
            "Check the macOS resolver configuration with `abctl dns status`.",
        ),
        super::dns::SystemResolverHealth::LookupFailed { error } => HealthCheck::fail(
            "DNS system lookup",
            format!("could not resolve {}: {error}", dns.query_name),
            "Check the macOS resolver configuration with `abctl dns status`.",
        ),
    });

    checks.push(
        match arcbox_core::bridge_discovery::find_bridge_with_vmenet() {
            Some((bridge, member)) => {
                HealthCheck::pass("Bridge NIC", format!("{bridge} with {member} member"))
            }
            None => HealthCheck::fail(
                "Bridge NIC",
                "no bridge interface with a vmenet member",
                "Restart the ArcBox daemon.",
            ),
        },
    );

    checks.push(check_container_route().await);
    checks.push(check_helper().await);
}

#[cfg(target_os = "macos")]
async fn check_container_route() -> HealthCheck {
    match setup_status().await {
        Ok(status) if status.route_installed => {
            HealthCheck::pass("Container route", "installed for this instance")
        }
        Ok(_) => HealthCheck::fail(
            "Container route",
            "not installed for this instance",
            "Restart the ArcBox daemon to reconcile networking.",
        ),
        Err(error) => HealthCheck::fail(
            "Container route",
            format!("status query failed: {error}"),
            "Restart the ArcBox daemon.",
        ),
    }
}

#[cfg(target_os = "macos")]
async fn check_helper() -> HealthCheck {
    let minimum = arcbox_constants::helper::MIN_HELPER_VERSION;
    match arcbox_helper::client::Client::probe_version().await {
        Ok(version) => match (
            arcbox_constants::helper::parse_helper_version(&version),
            arcbox_constants::helper::parse_semver_triple(minimum),
        ) {
            (Some(installed), Some(required))
                if arcbox_constants::helper::helper_version_satisfies(installed, required) =>
            {
                HealthCheck::pass("ArcBoxHelper", format!("reachable ({version})"))
            }
            _ => HealthCheck::fail(
                "ArcBoxHelper",
                format!("installed {version}, required {minimum}"),
                "Run `sudo abctl _install --no-daemon --no-shell`.",
            ),
        },
        Err(error) => HealthCheck::fail(
            "ArcBoxHelper",
            error.to_string(),
            "Run `sudo abctl _install --no-daemon --no-shell`.",
        ),
    }
}

async fn setup_status() -> Result<pb::SetupStatus> {
    let (transport, config) = connect::daemon(&super::resolve_grpc_socket_path());
    let response = SystemServiceClient::new(transport, config)
        .get_setup_status(pb::Empty::default())
        .await
        .context("failed to query daemon setup status")?;
    Ok(response.into_owned())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn partial_report_is_unhealthy_in_both_formats() {
        let report = DoctorReport::new(vec![
            HealthCheck::pass("Docker CLI", "ok"),
            HealthCheck::fail("DNS service", "timed out", "check logs"),
        ]);

        assert!(!report.healthy);
        assert_eq!(report.summary.passed, 1);
        assert_eq!(report.summary.failed, 1);
        assert!(report.table().contains("[FAIL] DNS service"));
        let json = serde_json::to_value(report).unwrap();
        assert_eq!(json["healthy"], false);
        assert_eq!(json["checks"][1]["status"], "fail");
    }

    #[test]
    fn docker_context_must_select_the_expected_unix_socket() {
        let directory = tempfile::tempdir().unwrap();
        let socket = directory.path().join("docker.sock");
        std::fs::write(&socket, []).unwrap();
        let alias = directory.path().join("alias.sock");
        #[cfg(unix)]
        std::os::unix::fs::symlink(&socket, &alias).unwrap();

        assert_eq!(
            endpoint_matches_socket(&format!("unix://{}", alias.display()), &socket),
            Ok(true)
        );
        assert_eq!(
            endpoint_matches_socket("tcp://127.0.0.1:2375", &socket),
            Err("Docker endpoint is not a Unix socket: tcp://127.0.0.1:2375".to_owned())
        );
        assert!(
            endpoint_matches_socket(
                &format!("unix://{}", directory.path().join("missing.sock").display()),
                &socket
            )
            .unwrap_err()
            .contains("could not resolve Docker endpoint")
        );
    }
}