all_smi/cli.rs
1// Copyright 2025 Lablup Inc. and Jeongkyu Shin
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::path::PathBuf;
16
17use clap::{CommandFactory, Parser, Subcommand, ValueEnum};
18
19use crate::common::paths;
20
21// Config subcommand argument types live in a sibling module so the main
22// CLI file stays within the 500-line soft limit.
23pub use crate::cli_config::{
24 ConfigAction, ConfigArgs, ConfigPathArgs, ConfigPrintArgs, ConfigPrintFormat,
25 ConfigValidateArgs,
26};
27// Service subcommand argument types, same rationale (issue #309).
28pub use crate::cli_service::{ServiceAction, ServiceArgs};
29
30/// Energy Session help block — appended at the end of `--help`.
31///
32/// Public because `main.rs` composes it with the dynamic
33/// "Configuration file" block (which has to be built at runtime to print
34/// the resolved per-user config path) before injecting the combined
35/// string via `Command::after_help`. See [`build_command_with_runtime_help`].
36pub const ENERGY_HELP: &str = "Energy Session (TUI):
37 Shows accumulated energy (kWh), avg power, and estimated cost since the
38 process started. Press R in the TUI to reset the session counter (the
39 Prometheus all_smi_energy_joules_total counter is unaffected).
40
41 Configure via [energy] in the TOML config (see `all-smi config path`
42 for the active path) or these environment variables (override the
43 config file):
44 ALL_SMI_ENERGY_PRICE $/kWh price (default 0.12; invalid hides cost)
45 ALL_SMI_ENERGY_CURRENCY Display currency code (default USD)
46 ALL_SMI_ENERGY_NO_COST=1 Hide cost column; still show kWh
47 ALL_SMI_ENERGY_WAL_PATH WAL file path (default <platform cache dir>/all-smi/energy-wal.bin)
48 ALL_SMI_ENERGY_NO_WAL=1 Disable disk WAL (in-memory counters only)
49 ALL_SMI_ENERGY_GAP_SECONDS Gap threshold for trapezoid→hold-last (1..=3600, default 10)";
50
51#[derive(Parser)]
52#[command(author, version, about, long_about = None)]
53pub struct Cli {
54 /// Override the default TOML config file path. When omitted, the loader
55 /// probes the platform-appropriate locations (run `all-smi config path`
56 /// to print the resolved location, or see the "Configuration file"
57 /// block at the bottom of this help text). A missing or malformed file
58 /// passed explicitly here is a hard error; implicit discovery silently
59 /// falls back to defaults.
60 #[arg(long, global = true, value_name = "PATH")]
61 pub config: Option<PathBuf>,
62
63 #[command(subcommand)]
64 pub command: Option<Commands>,
65}
66
67#[derive(Subcommand)]
68pub enum Commands {
69 /// Run in API mode, exposing metrics in Prometheus format.
70 Api(ApiArgs),
71 /// Run in local mode, monitoring local GPUs/NPUs. (default)
72 Local(LocalArgs),
73 /// Run in remote view mode, monitoring remote nodes via API endpoints.
74 View(ViewArgs),
75 /// Collect a one-shot machine-readable snapshot of hardware state.
76 ///
77 /// Emits JSON (default), CSV, or Prometheus exposition to stdout or a file.
78 /// Intended for scripting, CI probes, Slurm prolog/epilog hooks, and quick
79 /// `jq`/`yq` piping. Does not start a long-running server.
80 Snapshot(SnapshotArgs),
81 /// Record a live metric stream to an NDJSON file for later replay.
82 ///
83 /// Each collection cycle produces one JSON line whose shape matches the
84 /// `snapshot` subcommand (same serializer). Subsequent `all-smi view
85 /// --replay <file>` invocations reconstruct the exact TUI frames the
86 /// operator would have seen live, making post-hoc incident investigation
87 /// possible without a Prometheus retention store.
88 Record(RecordArgs),
89 /// Run self-diagnosis checks and optionally produce a support bundle.
90 ///
91 /// Emits a PASS/WARN/FAIL/SKIP report covering platform, privileges,
92 /// container runtime, every supported hardware backend (NVIDIA, AMD,
93 /// Intel GPU, Apple, Gaudi, TPU, Tenstorrent, Rebellions, Furiosa,
94 /// AWS Neuron, Windows), the relevant environment variables, and optional remote
95 /// endpoint connectivity. Every check is read-only and bounded by a
96 /// hard 3-second timeout.
97 Doctor(DoctorArgs),
98 /// Inspect, initialise, or validate the TOML configuration file.
99 /// See `all-smi config --help` for subcommands.
100 Config(ConfigArgs),
101 /// Install and control `all-smi api` as a supervised background
102 /// service.
103 ///
104 /// On Linux and macOS, the system scope requires root and registers
105 /// the service machine-wide; `--user` installs a per-user service
106 /// with no elevation. Runtime settings stay in the environment file
107 /// and the TOML config, so changing a port never requires
108 /// reinstalling.
109 /// Linux (systemd), macOS (launchd), and Windows (Service Control
110 /// Manager) are supported. `--user` applies to Linux and macOS but
111 /// has no meaning on Windows, where the Service Control Manager has
112 /// no per-user scope.
113 /// See `all-smi service --help` for subcommands.
114 Service(ServiceArgs),
115}
116
117#[derive(Parser, Clone)]
118pub struct ApiArgs {
119 /// The port to listen on for the API server. Use 0 to disable TCP listener.
120 ///
121 /// When omitted, value is taken from the config file, the
122 /// `ALL_SMI_API_PORT` env var, or the compiled default (9090).
123 #[arg(short, long)]
124 pub port: Option<u16>,
125 /// The interval in seconds at which to update the GPU information.
126 ///
127 /// When omitted, value is taken from the config file, the
128 /// `ALL_SMI_API_INTERVAL_SECS` env var, or the compiled default (3).
129 #[arg(short, long)]
130 pub interval: Option<u64>,
131 /// Include the process list in the API output.
132 ///
133 /// Use `--processes` or `--processes=true` to force-enable,
134 /// `--processes=false` to force-disable. When omitted, value is
135 /// taken from the config file or the `ALL_SMI_API_PROCESSES` env
136 /// var. An explicit CLI value overrides either source, including
137 /// turning off a value enabled by the config file.
138 #[arg(long, num_args = 0..=1, default_missing_value = "true")]
139 pub processes: Option<bool>,
140 /// Unix domain socket path for local IPC (Unix only).
141 /// When specified without a value, uses platform default:
142 /// - Linux: /var/run/all-smi.sock (fallback to /tmp/all-smi.sock if no permission)
143 /// - macOS: /tmp/all-smi.sock
144 #[cfg(unix)]
145 #[arg(short, long, num_args = 0..=1, default_missing_value = "")]
146 pub socket: Option<String>,
147}
148
149#[derive(Parser, Clone)]
150pub struct LocalArgs {
151 /// The interval in seconds at which to update the GPU information.
152 #[arg(short, long)]
153 pub interval: Option<u64>,
154 /// Hide storage rows in the TUI while continuing to collect storage data.
155 #[arg(long)]
156 pub hide_storage: bool,
157 /// Temperature in Celsius at which GPUs trigger a `warn` alert.
158 /// The matching `crit` threshold is auto-set 10°C higher unless an
159 /// explicit config file overrides it.
160 #[arg(long)]
161 pub alert_temp: Option<u32>,
162 /// Minutes of sustained idle utilization (below `util_idle_pct`) after
163 /// which the alerter emits an `ok → warn` transition.
164 #[arg(long)]
165 pub alert_util_low_mins: Option<u32>,
166}
167
168#[derive(Parser, Clone)]
169pub struct ViewArgs {
170 /// Remote HTTP endpoints separated by spaces and/or commas.
171 ///
172 /// Examples: `--hosts node-a:9090 node-b:9090`,
173 /// `--hosts node-a:9090,node-b:9090`, or a mixture of both forms.
174 /// Explicit `http://` and `https://` schemes are preserved.
175 #[arg(long, num_args = 1..)]
176 pub hosts: Option<Vec<String>>,
177 /// A file containing a list of host addresses to connect to for remote monitoring.
178 #[arg(long)]
179 pub hostfile: Option<String>,
180 /// The interval in seconds at which to update the GPU information. If not specified, uses adaptive interval based on node count.
181 #[arg(short, long)]
182 pub interval: Option<u64>,
183 /// Hide storage rows in the TUI while continuing to collect storage data.
184 #[arg(long)]
185 pub hide_storage: bool,
186 /// Temperature in Celsius at which GPUs trigger a `warn` alert.
187 /// The matching `crit` threshold is auto-set 10°C higher unless an
188 /// explicit config file overrides it.
189 #[arg(long)]
190 pub alert_temp: Option<u32>,
191 /// Minutes of sustained idle utilization (below `util_idle_pct`) after
192 /// which the alerter emits an `ok → warn` transition.
193 #[arg(long)]
194 pub alert_util_low_mins: Option<u32>,
195
196 // --- Replay mode (issue #187) --------------------------------------
197 /// Replay a recorded NDJSON stream instead of collecting live data.
198 ///
199 /// Accepts `.ndjson`, `.ndjson.zst`, `.ndjson.gz` — compression is
200 /// auto-detected from the file extension. In replay mode `--hosts`
201 /// and `--hostfile` are ignored; tabs and GPUs come entirely from the
202 /// recorded frames.
203 #[arg(long)]
204 pub replay: Option<PathBuf>,
205 /// Playback speed multiplier for `--replay`. Valid discrete values:
206 /// 0.25, 0.5, 1.0 (default), 2.0, 4.0, 8.0. Other values are accepted
207 /// at startup but the in-TUI `+`/`-` controls cycle through the
208 /// discrete ladder.
209 #[arg(long, default_value_t = 1.0)]
210 pub speed: f32,
211 /// Seek to the given timecode (`HH:MM:SS`, `MM:SS`, or bare seconds)
212 /// before starting playback.
213 #[arg(long)]
214 pub start: Option<String>,
215 /// Loop playback: when the last frame is reached, jump back to the
216 /// first frame and continue.
217 #[arg(long = "loop")]
218 pub replay_loop: bool,
219
220 // --- Agentless SSH transport (issue #194) --------------------------
221 /// Comma-separated list of SSH targets (`user@host[:port]`).
222 ///
223 /// When set, `view` connects to each target over SSH and runs
224 /// `all-smi snapshot --format json` when installed, or falls back
225 /// to `nvidia-smi` / `rocm-smi` per `--ssh-fallback`. Mutually
226 /// exclusive with `--hosts` / `--hostfile`.
227 #[arg(long)]
228 pub ssh: Option<String>,
229
230 /// Path to a hostfile listing one `user@host[:port]` target per line.
231 /// `#` comments and blank lines are ignored.
232 #[arg(long = "ssh-hostfile")]
233 pub ssh_hostfile: Option<PathBuf>,
234
235 /// Explicit SSH private key path. Overrides the default probe of
236 /// `~/.ssh/id_ed25519`, `~/.ssh/id_ecdsa`, `~/.ssh/id_rsa`.
237 #[arg(long = "ssh-key")]
238 pub ssh_key: Option<PathBuf>,
239
240 /// OpenSSH config file path. This option is accepted for compatibility
241 /// but currently has no effect; connection settings are taken from the
242 /// other SSH flags.
243 #[arg(long = "ssh-config")]
244 pub ssh_config: Option<PathBuf>,
245
246 /// Host-key policy: `yes` (default, refuse unknown), `accept-new`
247 /// (TOFU), `no` (accept any — TUI warning shown).
248 #[arg(long = "ssh-strict-host-key", default_value = "yes")]
249 pub ssh_strict_host_key: String,
250
251 /// Per-target SSH connect timeout in seconds. Remote commands have a
252 /// separate fixed 15-second execution timeout.
253 #[arg(long = "ssh-timeout-secs", default_value_t = 10)]
254 pub ssh_timeout_secs: u64,
255
256 /// Comma-separated fallback probe order (`nvidia-smi`, `rocm-smi`,
257 /// `none`). When omitted, both fallbacks are enabled.
258 #[arg(long = "ssh-fallback")]
259 pub ssh_fallback: Option<String>,
260
261 /// Path to the known_hosts file for strict / accept-new verification.
262 /// Defaults to `~/.ssh/known_hosts`.
263 #[arg(long = "ssh-known-hosts")]
264 pub ssh_known_hosts: Option<PathBuf>,
265
266 /// Maximum concurrent SSH connections (semaphore-limited). Hosts
267 /// beyond this cap stagger their initial connection attempts.
268 #[arg(long = "ssh-concurrency", default_value_t = 32)]
269 pub ssh_concurrency: usize,
270}
271
272impl ViewArgs {
273 /// Constructor used by synthetic call sites (tests, the `default_mode`
274 /// redispatch in `main.rs`, and the local-mode runner that only
275 /// needs the interval / alert CLI flags). Keeps every callsite in
276 /// one place so adding a new `ViewArgs` field doesn't force
277 /// touching each synthetic site.
278 pub fn empty() -> Self {
279 Self {
280 hosts: None,
281 hostfile: None,
282 interval: None,
283 hide_storage: false,
284 alert_temp: None,
285 alert_util_low_mins: None,
286 replay: None,
287 speed: 1.0,
288 start: None,
289 replay_loop: false,
290 ssh: None,
291 ssh_hostfile: None,
292 ssh_key: None,
293 ssh_config: None,
294 ssh_strict_host_key: "yes".to_string(),
295 ssh_timeout_secs: 10,
296 ssh_fallback: None,
297 ssh_known_hosts: None,
298 ssh_concurrency: 32,
299 }
300 }
301}
302
303/// Output format for the `snapshot` subcommand.
304#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
305pub enum SnapshotFormat {
306 /// JSON object (or JSON array when `--samples > 1`).
307 Json,
308 /// Flat CSV with a header row.
309 Csv,
310 /// Prometheus exposition format.
311 ///
312 /// MUST match byte-for-byte the output of the `api` subcommand's
313 /// `/metrics` endpoint for the same collection cycle.
314 Prometheus,
315}
316
317impl std::fmt::Display for SnapshotFormat {
318 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
319 match self {
320 Self::Json => write!(f, "json"),
321 Self::Csv => write!(f, "csv"),
322 Self::Prometheus => write!(f, "prometheus"),
323 }
324 }
325}
326
327#[derive(Parser, Clone)]
328pub struct SnapshotArgs {
329 /// Output format.
330 #[arg(long, value_enum, default_value_t = SnapshotFormat::Json)]
331 pub format: SnapshotFormat,
332
333 /// Pretty-print JSON output. Auto-off when stdout is not a TTY.
334 ///
335 /// Use `--pretty=false` to force compact output; use `--pretty=true` to
336 /// force pretty output even when piping.
337 #[arg(long, num_args = 0..=1, default_missing_value = "true")]
338 pub pretty: Option<bool>,
339
340 /// Sections to include in the output. Comma-separated.
341 ///
342 /// Valid values: `gpu`, `cpu`, `memory`, `chassis`, `process`, `storage`.
343 /// `process` and `storage` are opt-in because they are expensive.
344 #[arg(long, value_delimiter = ',', default_value = "gpu,cpu,memory,chassis")]
345 pub include: Vec<String>,
346
347 /// Comma-separated dot-path fields to select for CSV column layout.
348 ///
349 /// When omitted, CSV output uses a sensible default per included section.
350 /// Dot paths are resolved against the device's JSON representation; missing
351 /// paths yield empty cells rather than errors. Example:
352 /// `--query index,name,utilization,memory.used,memory.total`.
353 #[arg(long, value_delimiter = ',')]
354 pub query: Vec<String>,
355
356 /// Collect multiple samples spaced `--interval` seconds apart.
357 #[arg(long, default_value_t = 1)]
358 pub samples: u32,
359
360 /// Seconds between samples. Requires `--samples > 1` to have any effect.
361 #[arg(long, default_value_t = 0)]
362 pub interval: u64,
363
364 /// Per-reader timeout in milliseconds.
365 ///
366 /// Slow readers (TPU, Gaudi) that exceed this budget are recorded in the
367 /// top-level `errors` array (JSON) / `errors` column (CSV) / stderr
368 /// (Prometheus) instead of hanging the process.
369 #[arg(long, default_value_t = 5_000)]
370 pub timeout_ms: u64,
371
372 /// Write output to this file instead of stdout. Use `-` for stdout.
373 ///
374 /// On Unix the file is created with mode `0o600` (owner-only) and the
375 /// writer refuses to follow symlinks; the command fails if the target
376 /// path already exists as a symlink. The write is atomic: output first
377 /// goes to a sibling `<path>.tmp` file, is fsynced, then renamed over
378 /// the destination. On Windows the file is opened with exclusive
379 /// sharing to prevent concurrent access while it is written.
380 #[arg(long, short)]
381 pub output: Option<String>,
382}
383
384impl SnapshotArgs {
385 /// Parse and normalise `--include` into a [`SnapshotIncludes`] flag set.
386 ///
387 /// Unknown section names produce an error with a descriptive message —
388 /// clap reports this as a runtime error rather than a flag parse error,
389 /// so the caller can surface it through the standard `anyhow` chain.
390 pub fn includes(&self) -> Result<SnapshotIncludes, String> {
391 let mut set = SnapshotIncludes::default();
392 for raw in &self.include {
393 let name = raw.trim().to_ascii_lowercase();
394 match name.as_str() {
395 "" => continue,
396 "gpu" => set.gpu = true,
397 "cpu" => set.cpu = true,
398 "memory" => set.memory = true,
399 "chassis" => set.chassis = true,
400 "process" | "processes" => set.process = true,
401 "storage" | "disk" => set.storage = true,
402 other => {
403 return Err(format!(
404 "unknown --include section `{other}` (valid: gpu, cpu, memory, chassis, process, storage)"
405 ));
406 }
407 }
408 }
409 Ok(set)
410 }
411}
412
413/// Which sections are requested for the snapshot.
414#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
415pub struct SnapshotIncludes {
416 pub gpu: bool,
417 pub cpu: bool,
418 pub memory: bool,
419 pub chassis: bool,
420 pub process: bool,
421 pub storage: bool,
422}
423
424impl SnapshotIncludes {
425 /// Returns `true` if no section was requested.
426 pub fn is_empty(&self) -> bool {
427 !(self.gpu || self.cpu || self.memory || self.chassis || self.process || self.storage)
428 }
429}
430
431/// Source of live data for the `record` subcommand.
432#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, ValueEnum)]
433pub enum RecordSource {
434 /// Collect from the local hardware readers (default).
435 #[default]
436 Local,
437 /// Scrape remote `/metrics` endpoints — requires `--hosts` or
438 /// `--hostfile`. Uses the same HTTP path as `view`.
439 Remote,
440}
441
442impl std::fmt::Display for RecordSource {
443 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
444 match self {
445 Self::Local => write!(f, "local"),
446 Self::Remote => write!(f, "remote"),
447 }
448 }
449}
450
451/// Explicit compression codec for `record --compress`.
452#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, ValueEnum)]
453pub enum RecordCompression {
454 /// zstd — default on recent platforms, small + fast.
455 #[default]
456 Zstd,
457 /// gzip — universally available, slightly larger output.
458 Gzip,
459 /// No compression (pure NDJSON).
460 None,
461}
462
463impl std::fmt::Display for RecordCompression {
464 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
465 match self {
466 Self::Zstd => write!(f, "zstd"),
467 Self::Gzip => write!(f, "gzip"),
468 Self::None => write!(f, "none"),
469 }
470 }
471}
472
473#[derive(Parser, Clone, Debug)]
474pub struct RecordArgs {
475 /// Output path for the NDJSON stream.
476 #[arg(
477 long,
478 short = 'o',
479 long_help = "Output path for the NDJSON stream.\n\n\
480 When omitted, the file lands under the `record.output_dir` config \
481 value (if set), otherwise under the platform cache directory's \
482 `all-smi/records/` subdirectory, with basename \
483 `all-smi-record.ndjson.zst`. The platform cache directory is \
484 `$XDG_CACHE_HOME` (or `~/.cache`) on Linux, `~/Library/Caches` on \
485 macOS, and `%LOCALAPPDATA%` on Windows. If no home-like directory \
486 is resolvable, the file is written to the current working \
487 directory as `all-smi-record.ndjson.zst`.\n\n\
488 Extension drives compression: `.ndjson.zst` → zstd, \
489 `.ndjson.gz` → gzip, anything else → plain NDJSON. Use \
490 `--compress` to override detection."
491 )]
492 pub output: Option<PathBuf>,
493
494 /// Interval in seconds between frames.
495 #[arg(long, short = 'i', default_value_t = 3)]
496 pub interval: u64,
497
498 /// How long to record. `0` (or negative via env overrides) means
499 /// record until `SIGTERM`/`SIGINT`. Accepts a bare integer (seconds)
500 /// or a suffixed form like `30s`, `5m`, `1h`, `1d`.
501 #[arg(long, default_value = "0")]
502 pub duration: String,
503
504 /// Live data source.
505 #[arg(long, value_enum, default_value_t = RecordSource::Local)]
506 pub source: RecordSource,
507
508 /// Remote HTTP endpoints separated by spaces and/or commas when
509 /// `--source=remote`. Explicit HTTP and HTTPS schemes are preserved.
510 #[arg(long, num_args = 1..)]
511 pub hosts: Option<Vec<String>>,
512
513 /// File containing remote hosts (one per line) when `--source=remote`.
514 #[arg(long)]
515 pub hostfile: Option<String>,
516
517 /// Sections to include in each frame. Comma-separated.
518 /// Valid values: `gpu`, `cpu`, `memory`, `chassis`, `process`.
519 #[arg(long, value_delimiter = ',', default_value = "gpu,cpu,memory,chassis")]
520 pub include: Vec<String>,
521
522 /// Rotation threshold for the active segment. Accepts a size in bytes
523 /// (`1048576`) or with suffix (`1K`, `10M`, `2G`). `0` disables
524 /// rotation. For example, `--max-size 1K --max-files 3` caps the
525 /// retained stream to three segments of at most 1 KiB each.
526 #[arg(long, default_value = "100M")]
527 pub max_size: String,
528
529 /// Maximum number of rotated segments to keep (including the active
530 /// one). Oldest segment is evicted when the limit is reached.
531 #[arg(long, default_value_t = 10)]
532 pub max_files: u32,
533
534 /// Override compression codec selected by file extension.
535 #[arg(long, value_enum)]
536 pub compress: Option<RecordCompression>,
537}
538
539impl RecordArgs {
540 /// Parse `--include` into a [`SnapshotIncludes`] flag set. Shares
541 /// exactly the same semantics as [`SnapshotArgs::includes`] so the
542 /// `record` and `snapshot` subcommands stay in sync.
543 pub fn includes(&self) -> Result<SnapshotIncludes, String> {
544 let mut set = SnapshotIncludes::default();
545 for raw in &self.include {
546 let name = raw.trim().to_ascii_lowercase();
547 match name.as_str() {
548 "" => continue,
549 "gpu" => set.gpu = true,
550 "cpu" => set.cpu = true,
551 "memory" => set.memory = true,
552 "chassis" => set.chassis = true,
553 "process" | "processes" => set.process = true,
554 other => {
555 return Err(format!(
556 "unknown --include section `{other}` (valid: gpu, cpu, memory, chassis, process)"
557 ));
558 }
559 }
560 }
561 Ok(set)
562 }
563}
564
565/// Arguments for the `doctor` subcommand.
566#[derive(Parser, Clone, Debug)]
567pub struct DoctorArgs {
568 /// Emit a machine-readable JSON report instead of the human-readable
569 /// text output. The JSON schema is versioned via a top-level `schema`
570 /// field so consumers can detect incompatible changes.
571 #[arg(long)]
572 pub json: bool,
573
574 /// Include extra diagnostic detail per check (slow `system_profiler`
575 /// on macOS, verbose environment dump in the bundle, etc.).
576 #[arg(long)]
577 pub verbose: bool,
578
579 /// Write a tar.gz support bundle to this path. The archive contains
580 /// `report.txt`, `report.json`, and applicable system context files
581 /// (env, uname, lspci, lsmod, dmesg-gpu, version, and macOS-only
582 /// `system_profiler SPDisplaysDataType` when `--verbose` is set).
583 #[arg(long, value_name = "PATH")]
584 pub bundle: Option<PathBuf>,
585
586 /// By default the report and bundle scrub hostnames, IP addresses,
587 /// MAC addresses, and local usernames so the output is safe to attach
588 /// to public issues. Set this flag to preserve identifiers verbatim.
589 #[arg(long)]
590 pub include_identifiers: bool,
591
592 /// Opt-in remote endpoints to probe (host, host:port, or a full URL).
593 /// Each argument triggers DNS resolution, TCP reachability, latency
594 /// measurement, and an HTTP GET against `/metrics` when a URL is
595 /// given. May be passed multiple times.
596 #[arg(long = "remote-check", value_name = "HOST_OR_URL", num_args = 1..)]
597 pub remote_check: Vec<String>,
598
599 /// Skip checks whose ID starts with any of these prefixes. Example:
600 /// `--skip nvidia` omits every `nvidia.*` check; `--skip
601 /// nvidia.nvml.loadable` omits only that specific one. Comma-separated
602 /// values are accepted.
603 #[arg(long, value_name = "CHECK_ID", value_delimiter = ',')]
604 pub skip: Vec<String>,
605
606 /// Run only checks whose ID starts with any of these prefixes. Takes
607 /// precedence over `--skip`. Example: `--only privileges` runs only
608 /// the privileges group. Comma-separated values are accepted.
609 #[arg(long, value_name = "CHECK_ID", value_delimiter = ',')]
610 pub only: Vec<String>,
611}
612
613/// Render the runtime "Configuration file" help block. Resolved at
614/// invocation time because the canonical path embeds `$HOME` /
615/// `$XDG_CONFIG_HOME` / `%APPDATA%`, which are user-specific and not
616/// known at compile time. Issue #213.
617///
618/// Shape (intentionally short — `after_help` is shown for both `-h` and
619/// `--help`, so we keep it scannable):
620///
621/// ```text
622/// Configuration file:
623/// Optional TOML file. Precedence: CLI flags > env vars > config file > built-in defaults.
624/// Active path (this platform):
625/// <resolved-path> (active | not found)
626/// Also searched:
627/// <other-candidate> (active | not found)
628/// Inspect: all-smi config path Init: all-smi config init Print merged: all-smi config print
629/// Override path with --config <PATH>.
630/// ```
631///
632/// The "Also searched" block lists every candidate other than the active
633/// one, so a platform with a machine-wide path (Linux
634/// `/etc/all-smi/config.toml`, issue #309) surfaces it without a separate
635/// `config path` invocation. It is omitted when there is nothing else to
636/// show, which keeps the block short on platforms with a single
637/// candidate.
638pub fn config_help_block() -> String {
639 let resolved = paths::active_config_path();
640 let line = paths::format_path_with_existence(resolved.as_deref());
641
642 let others: String = paths::candidate_config_paths()
643 .iter()
644 .filter(|p| Some(p.as_path()) != resolved.as_deref())
645 .map(|p| format!("\n {}", paths::format_path_with_existence(Some(p))))
646 .collect();
647 let also = if others.is_empty() {
648 String::new()
649 } else {
650 format!("\n Also searched:{others}")
651 };
652
653 format!(
654 "Configuration file:\n \
655 Optional TOML file. Precedence: CLI flags > env vars > config file > built-in defaults.\n \
656 Active path (this platform):\n \
657 {line}{also}\n \
658 Inspect: all-smi config path Init: all-smi config init Print merged: all-smi config print\n \
659 Override path with --config <PATH>."
660 )
661}
662
663/// Build the top-level [`clap::Command`] with the runtime-composed
664/// `after_help` text injected. Callers should parse via
665/// `Cli::from_arg_matches(&Self::build_command_with_runtime_help().get_matches())`
666/// rather than `Cli::parse()` so the dynamic Configuration file block
667/// reaches `--help` output.
668pub fn build_command_with_runtime_help() -> clap::Command {
669 let config_block = config_help_block();
670 let after = format!("{config_block}\n\n{ENERGY_HELP}");
671 Cli::command().after_help(after)
672}
673
674#[cfg(test)]
675mod tests {
676 use super::*;
677
678 #[test]
679 fn hide_storage_defaults_to_false_for_local_and_view() {
680 let local = Cli::try_parse_from(["all-smi", "local"]).expect("parse local");
681 let Commands::Local(local) = local.command.expect("local command") else {
682 panic!("expected local command");
683 };
684 assert!(!local.hide_storage);
685
686 let view = Cli::try_parse_from(["all-smi", "view"]).expect("parse view");
687 let Commands::View(view) = view.command.expect("view command") else {
688 panic!("expected view command");
689 };
690 assert!(!view.hide_storage);
691 }
692
693 #[test]
694 fn hide_storage_flag_is_available_for_local_and_view() {
695 let local =
696 Cli::try_parse_from(["all-smi", "local", "--hide-storage"]).expect("parse local flag");
697 let Commands::Local(local) = local.command.expect("local command") else {
698 panic!("expected local command");
699 };
700 assert!(local.hide_storage);
701
702 let view =
703 Cli::try_parse_from(["all-smi", "view", "--hide-storage"]).expect("parse view flag");
704 let Commands::View(view) = view.command.expect("view command") else {
705 panic!("expected view command");
706 };
707 assert!(view.hide_storage);
708 }
709
710 #[test]
711 fn local_and_view_help_describe_hide_storage() {
712 let mut command = build_command_with_runtime_help();
713 for subcommand in ["local", "view"] {
714 let help = command
715 .find_subcommand_mut(subcommand)
716 .expect("monitoring subcommand")
717 .render_long_help()
718 .to_string();
719 assert!(help.contains("--hide-storage"), "{subcommand}: {help}");
720 assert!(
721 help.contains("continuing to collect storage data"),
722 "{subcommand}: {help}"
723 );
724 }
725 }
726
727 #[test]
728 fn snapshot_includes_is_empty_when_all_false() {
729 let inc = SnapshotIncludes::default();
730 assert!(inc.is_empty());
731 }
732
733 #[test]
734 fn snapshot_includes_not_empty_when_one_set() {
735 let inc = SnapshotIncludes {
736 gpu: true,
737 ..Default::default()
738 };
739 assert!(!inc.is_empty());
740 }
741
742 #[test]
743 fn snapshot_args_includes_rejects_unknown_section() {
744 let args = SnapshotArgs {
745 format: SnapshotFormat::Json,
746 pretty: None,
747 include: vec!["gpu".to_string(), "unknown_section".to_string()],
748 query: Vec::new(),
749 samples: 1,
750 interval: 0,
751 timeout_ms: 5_000,
752 output: None,
753 };
754 let result = args.includes();
755 assert!(result.is_err());
756 let msg = result.unwrap_err();
757 assert!(
758 msg.contains("unknown_section"),
759 "error must name the unknown section, got: {msg}"
760 );
761 }
762
763 #[test]
764 fn snapshot_args_includes_accepts_process_alias() {
765 // Both "process" and "processes" are valid include names.
766 let args = SnapshotArgs {
767 format: SnapshotFormat::Json,
768 pretty: None,
769 include: vec!["processes".to_string(), "disk".to_string()],
770 query: Vec::new(),
771 samples: 1,
772 interval: 0,
773 timeout_ms: 5_000,
774 output: None,
775 };
776 let result = args
777 .includes()
778 .expect("process/disk aliases should be accepted");
779 assert!(result.process);
780 assert!(result.storage);
781 }
782
783 #[test]
784 fn snapshot_format_display() {
785 assert_eq!(SnapshotFormat::Json.to_string(), "json");
786 assert_eq!(SnapshotFormat::Csv.to_string(), "csv");
787 assert_eq!(SnapshotFormat::Prometheus.to_string(), "prometheus");
788 }
789
790 // ---- Issue #213: help output exposes the active config path. ----
791
792 /// The runtime-built command must surface the new "Configuration
793 /// file" block in `--help`, plus the existing Energy Session block.
794 /// Regression guard: nobody can drop the runtime `after_help`
795 /// injection without breaking this test.
796 #[test]
797 fn help_text_contains_config_and_energy_blocks() {
798 let mut cmd = build_command_with_runtime_help();
799 let help = cmd.render_help().to_string();
800 assert!(
801 help.contains("Configuration file:"),
802 "help must contain the Configuration file block, got:\n{help}"
803 );
804 assert!(
805 help.contains("Active path (this platform):"),
806 "help must label the active path, got:\n{help}"
807 );
808 assert!(
809 help.contains("all-smi config path"),
810 "help must point at `all-smi config path`, got:\n{help}"
811 );
812 assert!(
813 help.contains("Energy Session"),
814 "existing Energy Session block must still render, got:\n{help}"
815 );
816 }
817
818 /// The `--config` flag's own docstring must no longer redirect users
819 /// to a side-effecting command (`config init`); it points at the
820 /// read-only `config path` or the inline block.
821 #[test]
822 fn config_flag_help_no_longer_only_points_at_init() {
823 let mut cmd = build_command_with_runtime_help();
824 let help = cmd.render_help().to_string();
825 // The new wording mentions `config path` somewhere in the help
826 // surface (either in the flag doc or the Configuration block).
827 assert!(
828 help.contains("config path"),
829 "help should mention `config path`, got:\n{help}"
830 );
831 }
832
833 /// Every candidate other than the active one must appear in the
834 /// help block. Issue #309 added the Linux machine-wide candidate,
835 /// which would otherwise be invisible to anyone who never runs
836 /// `all-smi config path`.
837 #[test]
838 fn config_help_block_lists_the_non_active_candidates() {
839 let block = config_help_block();
840 let active = paths::active_config_path();
841 let others: Vec<_> = paths::candidate_config_paths()
842 .into_iter()
843 .filter(|p| Some(p.as_path()) != active.as_deref())
844 .collect();
845
846 if others.is_empty() {
847 assert!(
848 !block.contains("Also searched"),
849 "with a single candidate the block must stay short, got:\n{block}"
850 );
851 } else {
852 assert!(
853 block.contains("Also searched"),
854 "extra candidates must be labelled, got:\n{block}"
855 );
856 for p in others {
857 assert!(
858 block.contains(&p.display().to_string()),
859 "candidate {} missing from the help block:\n{block}",
860 p.display()
861 );
862 }
863 }
864 }
865
866 /// The `service` subcommand must be reachable from the shipped
867 /// binary, not just defined. Regression guard for the wiring in
868 /// `main.rs` and the `Commands` enum (issue #309).
869 #[test]
870 fn service_subcommand_is_registered() {
871 let cmd = build_command_with_runtime_help();
872 let service = cmd
873 .get_subcommands()
874 .find(|s| s.get_name() == "service")
875 .expect("`all-smi service` must be a registered subcommand");
876
877 let mut actions: Vec<_> = service
878 .get_subcommands()
879 .map(|s| s.get_name().to_string())
880 .filter(|n| n != "help")
881 .collect();
882 actions.sort();
883 assert_eq!(
884 actions,
885 vec![
886 "install",
887 "restart",
888 "run",
889 "start",
890 "status",
891 "stop",
892 "uninstall"
893 ],
894 "the service subcommand set is a cross-platform contract (#310, #311)"
895 );
896
897 // `run` is the Windows Service Control Manager entry point
898 // (issue #311), not an operator-facing action, so it must stay
899 // out of `--help` on every platform. The rest must stay visible.
900 for action in service.get_subcommands() {
901 let name = action.get_name();
902 let hidden = action.is_hide_set();
903 match name {
904 "run" => assert!(hidden, "`service run` must remain hidden from --help"),
905 "help" => {}
906 other => assert!(!hidden, "`service {other}` must stay visible in --help"),
907 }
908 }
909 }
910
911 #[test]
912 fn remote_host_help_documents_space_and_comma_separators() {
913 let mut command = build_command_with_runtime_help();
914 for subcommand in ["view", "record"] {
915 let help = command
916 .find_subcommand_mut(subcommand)
917 .expect("remote-capable subcommand must exist")
918 .render_long_help()
919 .to_string();
920 assert!(
921 help.contains("spaces and/or commas"),
922 "{subcommand} help must document both host separators:\n{help}"
923 );
924 }
925 }
926
927 /// The flag spellings are part of the same contract as the
928 /// subcommand names; the macOS and Windows backends are written
929 /// against them.
930 #[test]
931 fn service_flags_match_the_documented_contract() {
932 let cmd = build_command_with_runtime_help();
933 let service = cmd
934 .get_subcommands()
935 .find(|s| s.get_name() == "service")
936 .expect("service subcommand");
937
938 let flags = |name: &str| -> Vec<String> {
939 service
940 .get_subcommands()
941 .find(|s| s.get_name() == name)
942 .unwrap_or_else(|| panic!("`service {name}` must exist"))
943 .get_arguments()
944 .filter_map(|a| a.get_long().map(str::to_string))
945 .filter(|l| l != "help" && l != "config")
946 .collect()
947 };
948
949 for expected in ["user", "service-user", "now", "force"] {
950 assert!(
951 flags("install").iter().any(|f| f == expected),
952 "`service install` must accept --{expected}, got: {:?}",
953 flags("install")
954 );
955 }
956 for action in ["start", "stop", "restart"] {
957 assert_eq!(flags(action), vec!["user".to_string()], "action: {action}");
958 }
959 assert!(flags("uninstall").iter().any(|f| f == "user"));
960 for expected in ["user", "json"] {
961 assert!(
962 flags("status").iter().any(|f| f == expected),
963 "`service status` must accept --{expected}"
964 );
965 }
966 }
967
968 #[test]
969 fn service_help_mentions_all_supported_backends_and_user_scope() {
970 let mut cmd = build_command_with_runtime_help();
971 let service = cmd
972 .find_subcommand_mut("service")
973 .expect("service subcommand");
974 let help = service.render_long_help().to_string();
975
976 assert!(
977 help.contains("Linux (systemd), macOS (launchd), and Windows (Service Control"),
978 "service help must list Linux, macOS, and Windows support, got:\n{help}"
979 );
980 assert!(
981 help.contains("On Linux and macOS, the system scope requires root"),
982 "service help must keep root wording scoped to Linux and macOS, got:\n{help}"
983 );
984 assert!(
985 help.contains("`--user` applies to Linux and macOS"),
986 "service help must describe where --user applies, got:\n{help}"
987 );
988 assert!(
989 !help.contains("tracked separately"),
990 "service help must not claim launchd is still pending, got:\n{help}"
991 );
992 }
993
994 /// `config_help_block()` must annotate the resolved path with an
995 /// existence marker — either `(active)` when present or
996 /// `(not found)` when absent. Without a marker the user cannot
997 /// tell from `--help` whether the file is there.
998 #[test]
999 fn config_help_block_carries_existence_marker() {
1000 let block = config_help_block();
1001 assert!(
1002 block.contains("(active)")
1003 || block.contains("(not found)")
1004 || block.contains("no config path"),
1005 "config_help_block must carry an existence marker, got:\n{block}"
1006 );
1007 }
1008}