Skip to main content

oomtop_cli/commands/
mod.rs

1//! Subcommand implementations. Every command gets a [`Ctx`]: the layered config (UX §12.1.3) built from the
2//! global flags, the config paths it resolved to, and helpers to build the engine and format numbers.
3
4mod config;
5mod doctor;
6mod export;
7mod isolation;
8mod keys;
9mod measure;
10mod models;
11mod ports;
12mod profile;
13mod reclaim;
14mod stale;
15mod table;
16mod theme;
17mod tui;
18
19use crate::engine::Engine;
20use crate::{Cli, Cmd, GlobalOpts};
21use anyhow::{anyhow, Result};
22use oomtop_config::layered::{load_layered, LoadOptions, Loaded};
23use oomtop_config::paths::ConfigPaths;
24use oomtop_core::units::{format_bytes, UnitSystem};
25use std::io::{BufRead, IsTerminal, Write};
26
27/// A bad argument discovered after parsing (exit code 2, like clap's own usage errors).
28#[derive(Debug)]
29pub struct UsageError(pub String);
30
31impl std::fmt::Display for UsageError {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        f.write_str(&self.0)
34    }
35}
36
37impl std::error::Error for UsageError {}
38
39/// `Err(UsageError)` as an anyhow error.
40pub fn usage<T>(msg: impl Into<String>) -> Result<T> {
41    Err(anyhow::Error::new(UsageError(msg.into())))
42}
43
44pub struct Ctx {
45    pub global: GlobalOpts,
46    pub opts: LoadOptions,
47    pub loaded: Loaded,
48    /// `--no-learn`, `OOMTOP_NO_LEARN=1` or `personalization.learn = false`.
49    pub no_learn: bool,
50}
51
52impl Ctx {
53    pub fn new(global: GlobalOpts) -> Result<Self> {
54        let mut flags: Vec<(String, String)> = Vec::new();
55        for kv in &global.set {
56            let (k, v) = kv
57                .split_once('=')
58                .ok_or_else(|| UsageError(format!("--set expects KEY=VALUE, got {kv:?}")))?;
59            let k = k.trim();
60            if k.is_empty() {
61                return usage(format!("--set expects KEY=VALUE, got {kv:?}"));
62            }
63            flags.push((k.to_string(), v.trim().to_string()));
64        }
65        let quote = |s: &str| toml::Value::String(s.to_string()).to_string();
66        if let Some(t) = &global.theme {
67            flags.push(("appearance.theme".into(), quote(t)));
68        }
69        if let Some(c) = global.color {
70            flags.push(("appearance.color".into(), quote(c.as_str())));
71        }
72        if global.ascii {
73            flags.push(("appearance.glyphs".into(), quote("ascii")));
74        }
75        if global.no_learn {
76            flags.push(("personalization.learn".into(), "false".into()));
77        }
78        let opts = LoadOptions {
79            config_path: global.config.clone(),
80            flags,
81            ..Default::default()
82        };
83        let loaded = load_layered(&opts);
84        let no_learn = global.no_learn || !loaded.config.personalization.learn;
85        Ok(Ctx {
86            global,
87            opts,
88            loaded,
89            no_learn,
90        })
91    }
92
93    /// Reports config problems once on stderr (the offending layer was skipped). `creating_config`: the
94    /// command is about to create the `--config` file, so "not found" is not worth a warning.
95    fn warn_config_errors(&self, creating_config: bool) {
96        let missing = self.missing_explicit_config();
97        for e in &self.loaded.errors {
98            if creating_config && missing.is_some() && e.path.as_deref() == missing {
99                continue;
100            }
101            eprintln!("oomtop: config: {e}");
102        }
103    }
104
105    /// The file named by `--config` / `OOMTOP_CONFIG` when it does not exist.
106    fn missing_explicit_config(&self) -> Option<&std::path::Path> {
107        self.opts.explicit_config().filter(|p| !p.exists())
108    }
109
110    pub fn config(&self) -> &oomtop_config::Config {
111        &self.loaded.config
112    }
113
114    /// Paths of the effective user config directory (moves with `--config`).
115    pub fn paths(&self) -> ConfigPaths {
116        self.opts.paths()
117    }
118
119    pub fn units(&self) -> UnitSystem {
120        match self.loaded.config.format.memory_units {
121            oomtop_config::model::MemoryUnits::Si => UnitSystem::Si,
122            oomtop_config::model::MemoryUnits::Iec => UnitSystem::Iec,
123        }
124    }
125
126    /// Bytes in the configured units and decimals.
127    pub fn fmt(&self, b: u64) -> String {
128        format_bytes(b, self.units(), self.loaded.config.format.decimals as usize)
129    }
130
131    pub fn fmt_opt(&self, b: Option<u64>) -> String {
132        b.map(|b| self.fmt(b)).unwrap_or_else(|| "n/a".into())
133    }
134
135    pub fn replaying(&self) -> bool {
136        self.global.replay.is_some()
137    }
138
139    /// The state store (none while replaying: a fixture must never write this machine's journal).
140    pub fn state(&self) -> Option<oomtop_state::StateDb> {
141        if self.replaying() {
142            return None;
143        }
144        match oomtop_state::StateDb::open_default() {
145            Ok(mut db) => {
146                db.set_learning(!self.no_learn);
147                let p = &self.loaded.config.personalization;
148                db.set_limits(p.retention_days, p.log_max_mb);
149                Some(db)
150            }
151            Err(e) => {
152                eprintln!("oomtop: state: {e} (continuing without the lineage journal)");
153                None
154            }
155        }
156    }
157
158    /// The pipeline: live sampling of this machine, or `--replay FIXTURE`. `on_demand` = two samples 150 ms
159    /// apart per snapshot (one-shot commands and MCP), so CPU % and rates are real.
160    pub fn engine(&self, on_demand: bool) -> Result<Engine> {
161        self.build_engine(on_demand, false)
162    }
163
164    /// Like [`Ctx::engine`], for commands that must leave no trace (`reclaim --dry-run`): an existing state
165    /// store is read for the lineage journal — so the plan is the one a real run would make — and never
166    /// written; when there is none, none is created.
167    pub fn engine_read_only(&self, on_demand: bool) -> Result<Engine> {
168        self.build_engine(on_demand, true)
169    }
170
171    fn build_engine(&self, on_demand: bool, read_only: bool) -> Result<Engine> {
172        let state = if read_only && !oomtop_state::default_path().is_file() {
173            None
174        } else {
175            self.state()
176        };
177        let dir = self.opts.user_dir();
178        let mut e = match &self.global.replay {
179            Some(p) => Engine::replay_in(&self.loaded.config, p, Some(&dir)).map_err(|e| anyhow!(e))?,
180            None => Engine::live_in(
181                &self.loaded.config,
182                state,
183                on_demand,
184                self.global.offline || !self.loaded.config.adapters.enabled,
185                Some(&dir),
186            ),
187        };
188        e.set_learning(!self.no_learn);
189        if read_only {
190            e.set_state_read_only();
191        }
192        for err in &e.rule_errors {
193            eprintln!("oomtop: rules: {err}");
194        }
195        Ok(e)
196    }
197}
198
199/// Writes to stdout; a closed pipe (`| head`) is not an error.
200pub fn out(s: &str) {
201    let mut o = std::io::stdout().lock();
202    let _ = o.write_all(s.as_bytes());
203    let _ = o.flush();
204}
205
206pub fn json_pretty<T: serde::Serialize>(v: &T) -> Result<String> {
207    Ok(serde_json::to_string_pretty(v)? + "\n")
208}
209
210/// Writes to stderr (human text next to a machine-readable stdout).
211pub fn err_out(s: &str) {
212    let mut o = std::io::stderr().lock();
213    let _ = o.write_all(s.as_bytes());
214    let _ = o.flush();
215}
216
217/// Asks a yes/no question on the terminal. `Ok(None)` when stdin is not a terminal (no one to ask).
218pub fn confirm(question: &str) -> Result<Option<bool>> {
219    if !std::io::stdin().is_terminal() {
220        return Ok(None);
221    }
222    eprint!("{question} [y/N] ");
223    let _ = std::io::stderr().flush();
224    let mut line = String::new();
225    std::io::stdin().lock().read_line(&mut line)?;
226    Ok(Some(matches!(
227        line.trim().to_ascii_lowercase().as_str(),
228        "y" | "yes"
229    )))
230}
231
232pub fn dispatch(cli: Cli) -> Result<i32> {
233    let ctx = Ctx::new(cli.global)?;
234    // `config validate` / `doctor` report config errors themselves.
235    let reports_errors = matches!(
236        cli.command,
237        Some(Cmd::Config {
238            cmd: crate::ConfigCmd::Validate
239        }) | Some(Cmd::Doctor { .. })
240    );
241    // `config init | edit | set` create the file `--config` names; for everything else a missing explicit
242    // config file is a usage error (a typo must not silently mean "defaults").
243    let creating_config = matches!(
244        cli.command,
245        Some(Cmd::Config {
246            cmd: crate::ConfigCmd::Init { .. } | crate::ConfigCmd::Edit { .. } | crate::ConfigCmd::Set { .. }
247        })
248    );
249    if !creating_config {
250        if let Some(p) = ctx.missing_explicit_config() {
251            return usage(format!(
252                "config file not found: {} (named by --config / OOMTOP_CONFIG; create it with `oomtop --config {} config init`)",
253                p.display(),
254                p.display()
255            ));
256        }
257    }
258    if !reports_errors {
259        ctx.warn_config_errors(creating_config);
260    }
261    match cli.command {
262        None => tui::run(&ctx),
263        Some(Cmd::Headroom(a)) => measure::headroom(&ctx, a),
264        Some(Cmd::Why { json }) => measure::why(&ctx, json),
265        Some(Cmd::Models { json, no_hash }) => models::run(&ctx, json, no_hash),
266        Some(Cmd::Ports { json, exposed, links }) => ports::run(&ctx, json, exposed, links),
267        Some(Cmd::Reclaim(a)) => reclaim::run(&ctx, a),
268        Some(Cmd::Sandboxes { json }) => isolation::sandboxes(&ctx, json),
269        Some(Cmd::Ns { json }) => isolation::ns(&ctx, json),
270        Some(Cmd::Stale { json, limit }) => stale::run(&ctx, json, limit),
271        Some(Cmd::Json { compact }) => export::json(&ctx, compact),
272        Some(Cmd::Ndjson {
273            interval,
274            count,
275            discard,
276        }) => export::ndjson(&ctx, interval, count, discard),
277        Some(Cmd::Serve {
278            listen,
279            allow_host,
280            max_requests,
281        }) => export::serve(&ctx, listen, allow_host, max_requests),
282        Some(Cmd::Mcp { allow_actions }) => export::mcp(&ctx, allow_actions),
283        Some(Cmd::Doctor { json, no_probe }) => doctor::run(&ctx, json, no_probe),
284        Some(Cmd::Config { cmd }) => config::run(&ctx, cmd),
285        Some(Cmd::Theme { cmd }) => theme::run(&ctx, cmd),
286        Some(Cmd::Keys { cmd }) => keys::run(&ctx, cmd),
287        Some(Cmd::Profile { cmd }) => profile::run(&ctx, cmd),
288    }
289}