1mod config;
5mod doctor;
6mod export;
7mod isolation;
8mod keys;
9mod measure;
10mod models;
11mod ports;
12mod profile;
13mod reclaim;
14mod stale;
15mod theme;
16mod tui;
17
18use crate::engine::Engine;
19use crate::{Cli, Cmd, GlobalOpts};
20use anyhow::{anyhow, Result};
21use oomtop_config::layered::{load_layered, LoadOptions, Loaded};
22use oomtop_config::paths::ConfigPaths;
23use oomtop_core::units::{format_bytes, UnitSystem};
24use std::io::{BufRead, IsTerminal, Write};
25
26#[derive(Debug)]
28pub struct UsageError(pub String);
29
30impl std::fmt::Display for UsageError {
31 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32 f.write_str(&self.0)
33 }
34}
35
36impl std::error::Error for UsageError {}
37
38pub fn usage<T>(msg: impl Into<String>) -> Result<T> {
40 Err(anyhow::Error::new(UsageError(msg.into())))
41}
42
43pub struct Ctx {
44 pub global: GlobalOpts,
45 pub opts: LoadOptions,
46 pub loaded: Loaded,
47 pub no_learn: bool,
49}
50
51impl Ctx {
52 pub fn new(global: GlobalOpts) -> Result<Self> {
53 let mut flags: Vec<(String, String)> = Vec::new();
54 for kv in &global.set {
55 let (k, v) = kv
56 .split_once('=')
57 .ok_or_else(|| UsageError(format!("--set expects KEY=VALUE, got {kv:?}")))?;
58 let k = k.trim();
59 if k.is_empty() {
60 return usage(format!("--set expects KEY=VALUE, got {kv:?}"));
61 }
62 flags.push((k.to_string(), v.trim().to_string()));
63 }
64 let quote = |s: &str| toml::Value::String(s.to_string()).to_string();
65 if let Some(t) = &global.theme {
66 flags.push(("appearance.theme".into(), quote(t)));
67 }
68 if let Some(c) = global.color {
69 flags.push(("appearance.color".into(), quote(c.as_str())));
70 }
71 if global.ascii {
72 flags.push(("appearance.glyphs".into(), quote("ascii")));
73 }
74 if global.no_learn {
75 flags.push(("personalization.learn".into(), "false".into()));
76 }
77 let opts = LoadOptions {
78 config_path: global.config.clone(),
79 flags,
80 ..Default::default()
81 };
82 let loaded = load_layered(&opts);
83 let no_learn = global.no_learn || !loaded.config.personalization.learn;
84 Ok(Ctx {
85 global,
86 opts,
87 loaded,
88 no_learn,
89 })
90 }
91
92 fn warn_config_errors(&self, creating_config: bool) {
95 let missing = self.missing_explicit_config();
96 for e in &self.loaded.errors {
97 if creating_config && missing.is_some() && e.path.as_deref() == missing {
98 continue;
99 }
100 eprintln!("oomtop: config: {e}");
101 }
102 }
103
104 fn missing_explicit_config(&self) -> Option<&std::path::Path> {
106 self.opts.explicit_config().filter(|p| !p.exists())
107 }
108
109 pub fn config(&self) -> &oomtop_config::Config {
110 &self.loaded.config
111 }
112
113 pub fn paths(&self) -> ConfigPaths {
115 self.opts.paths()
116 }
117
118 pub fn units(&self) -> UnitSystem {
119 match self.loaded.config.format.memory_units {
120 oomtop_config::model::MemoryUnits::Si => UnitSystem::Si,
121 oomtop_config::model::MemoryUnits::Iec => UnitSystem::Iec,
122 }
123 }
124
125 pub fn fmt(&self, b: u64) -> String {
127 format_bytes(b, self.units(), self.loaded.config.format.decimals as usize)
128 }
129
130 pub fn fmt_opt(&self, b: Option<u64>) -> String {
131 b.map(|b| self.fmt(b)).unwrap_or_else(|| "n/a".into())
132 }
133
134 pub fn replaying(&self) -> bool {
135 self.global.replay.is_some()
136 }
137
138 pub fn state(&self) -> Option<oomtop_state::StateDb> {
140 if self.replaying() {
141 return None;
142 }
143 match oomtop_state::StateDb::open_default() {
144 Ok(mut db) => {
145 db.set_learning(!self.no_learn);
146 let p = &self.loaded.config.personalization;
147 db.set_limits(p.retention_days, p.log_max_mb);
148 Some(db)
149 }
150 Err(e) => {
151 eprintln!("oomtop: state: {e} (continuing without the lineage journal)");
152 None
153 }
154 }
155 }
156
157 pub fn engine(&self, on_demand: bool) -> Result<Engine> {
160 self.build_engine(on_demand, false)
161 }
162
163 pub fn engine_read_only(&self, on_demand: bool) -> Result<Engine> {
167 self.build_engine(on_demand, true)
168 }
169
170 fn build_engine(&self, on_demand: bool, read_only: bool) -> Result<Engine> {
171 let state = if read_only && !oomtop_state::default_path().is_file() {
172 None
173 } else {
174 self.state()
175 };
176 let dir = self.opts.user_dir();
177 let mut e = match &self.global.replay {
178 Some(p) => Engine::replay_in(&self.loaded.config, p, Some(&dir)).map_err(|e| anyhow!(e))?,
179 None => Engine::live_in(
180 &self.loaded.config,
181 state,
182 on_demand,
183 self.global.offline || !self.loaded.config.adapters.enabled,
184 Some(&dir),
185 ),
186 };
187 e.set_learning(!self.no_learn);
188 if read_only {
189 e.set_state_read_only();
190 }
191 for err in &e.rule_errors {
192 eprintln!("oomtop: rules: {err}");
193 }
194 Ok(e)
195 }
196}
197
198pub fn out(s: &str) {
200 let mut o = std::io::stdout().lock();
201 let _ = o.write_all(s.as_bytes());
202 let _ = o.flush();
203}
204
205pub fn json_pretty<T: serde::Serialize>(v: &T) -> Result<String> {
206 Ok(serde_json::to_string_pretty(v)? + "\n")
207}
208
209pub fn err_out(s: &str) {
211 let mut o = std::io::stderr().lock();
212 let _ = o.write_all(s.as_bytes());
213 let _ = o.flush();
214}
215
216pub fn confirm(question: &str) -> Result<Option<bool>> {
218 if !std::io::stdin().is_terminal() {
219 return Ok(None);
220 }
221 eprint!("{question} [y/N] ");
222 let _ = std::io::stderr().flush();
223 let mut line = String::new();
224 std::io::stdin().lock().read_line(&mut line)?;
225 Ok(Some(matches!(
226 line.trim().to_ascii_lowercase().as_str(),
227 "y" | "yes"
228 )))
229}
230
231pub fn dispatch(cli: Cli) -> Result<i32> {
232 let ctx = Ctx::new(cli.global)?;
233 let reports_errors = matches!(
235 cli.command,
236 Some(Cmd::Config {
237 cmd: crate::ConfigCmd::Validate
238 }) | Some(Cmd::Doctor { .. })
239 );
240 let creating_config = matches!(
243 cli.command,
244 Some(Cmd::Config {
245 cmd: crate::ConfigCmd::Init { .. } | crate::ConfigCmd::Edit { .. } | crate::ConfigCmd::Set { .. }
246 })
247 );
248 if !creating_config {
249 if let Some(p) = ctx.missing_explicit_config() {
250 return usage(format!(
251 "config file not found: {} (named by --config / OOMTOP_CONFIG; create it with `oomtop --config {} config init`)",
252 p.display(),
253 p.display()
254 ));
255 }
256 }
257 if !reports_errors {
258 ctx.warn_config_errors(creating_config);
259 }
260 match cli.command {
261 None => tui::run(&ctx),
262 Some(Cmd::Headroom(a)) => measure::headroom(&ctx, a),
263 Some(Cmd::Why { json }) => measure::why(&ctx, json),
264 Some(Cmd::Models { json, no_hash }) => models::run(&ctx, json, no_hash),
265 Some(Cmd::Ports { json, exposed, links }) => ports::run(&ctx, json, exposed, links),
266 Some(Cmd::Reclaim(a)) => reclaim::run(&ctx, a),
267 Some(Cmd::Sandboxes { json }) => isolation::sandboxes(&ctx, json),
268 Some(Cmd::Ns { json }) => isolation::ns(&ctx, json),
269 Some(Cmd::Stale { json, limit }) => stale::run(&ctx, json, limit),
270 Some(Cmd::Json { compact }) => export::json(&ctx, compact),
271 Some(Cmd::Ndjson {
272 interval,
273 count,
274 discard,
275 }) => export::ndjson(&ctx, interval, count, discard),
276 Some(Cmd::Serve {
277 listen,
278 allow_host,
279 max_requests,
280 }) => export::serve(&ctx, listen, allow_host, max_requests),
281 Some(Cmd::Mcp { allow_actions }) => export::mcp(&ctx, allow_actions),
282 Some(Cmd::Doctor { json, no_probe }) => doctor::run(&ctx, json, no_probe),
283 Some(Cmd::Config { cmd }) => config::run(&ctx, cmd),
284 Some(Cmd::Theme { cmd }) => theme::run(&ctx, cmd),
285 Some(Cmd::Keys { cmd }) => keys::run(&ctx, cmd),
286 Some(Cmd::Profile { cmd }) => profile::run(&ctx, cmd),
287 }
288}