socktop 1.60.1

Remote system monitor over WebSocket, TUI like top
Documentation
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
//! Entry point for the socktop TUI. Parses args and runs the App.

mod app;
mod history;
mod local;
mod proc_kill;
mod profiles;
mod retry;
mod types;
mod ui; // pure retry timing logic

use app::App;
use profiles::{ProfileEntry, ProfileRequest, ResolveProfile, load_profiles, save_profiles};
use std::env;
use std::io::{self, Write};

pub(crate) struct ParsedArgs {
    url: Option<String>,
    tls_ca: Option<String>,
    profile: Option<String>,
    save: bool,
    demo: bool,
    dry_run: bool, // hidden test helper: skip connecting
    metrics_interval_ms: Option<u64>,
    processes_interval_ms: Option<u64>,
    verify_hostname: bool,
    compact: bool,
}

pub(crate) fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Result<ParsedArgs, String> {
    let mut it = args.into_iter();
    let prog = it.next().unwrap_or_else(|| "socktop".into());
    let mut url: Option<String> = None;
    let mut tls_ca: Option<String> = None;
    let mut profile: Option<String> = None;
    let mut save = false;
    let mut demo = false;
    let mut dry_run = false;
    let mut metrics_interval_ms: Option<u64> = None;
    let mut processes_interval_ms: Option<u64> = None;
    let mut verify_hostname = false;
    let mut compact = false;
    while let Some(arg) = it.next() {
        match arg.as_str() {
            "-h" | "--help" => {
                return Err(format!(
                    "Usage: {prog} [--tls-ca CERT_PEM|-t CERT_PEM] [--verify-hostname] [--profile NAME|-P NAME] [--save] [--demo] [--compact] [--metrics-interval-ms N] [--processes-interval-ms N] [ws://HOST:PORT/ws]\n"
                ));
            }
            "--tls-ca" | "-t" => {
                tls_ca = it.next();
            }
            "--verify-hostname" => {
                // opt-in hostname (SAN) verification
                // default behavior is to skip it for easier home network usage
                // (still pins the provided certificate)
                verify_hostname = true;
            }
            "--profile" | "-P" => {
                profile = it.next();
            }
            "--save" => {
                save = true;
            }
            "--demo" => {
                demo = true;
            }
            "--compact" => {
                // Force the small-window layout at any terminal size. Without it the
                // layout switches on its own once the window gets too short.
                compact = true;
            }
            "--dry-run" => {
                // intentionally undocumented
                dry_run = true;
            }
            "--metrics-interval-ms" => {
                metrics_interval_ms = it.next().and_then(|v| v.parse().ok());
            }
            "--processes-interval-ms" => {
                processes_interval_ms = it.next().and_then(|v| v.parse().ok());
            }
            _ if arg.starts_with("--tls-ca=") => {
                if let Some((_, v)) = arg.split_once('=')
                    && !v.is_empty()
                {
                    tls_ca = Some(v.to_string());
                }
            }
            _ if arg.starts_with("--profile=") => {
                if let Some((_, v)) = arg.split_once('=')
                    && !v.is_empty()
                {
                    profile = Some(v.to_string());
                }
            }
            _ if arg.starts_with("--metrics-interval-ms=") => {
                if let Some((_, v)) = arg.split_once('=') {
                    metrics_interval_ms = v.parse().ok();
                }
            }
            _ if arg.starts_with("--processes-interval-ms=") => {
                if let Some((_, v)) = arg.split_once('=') {
                    processes_interval_ms = v.parse().ok();
                }
            }
            _ => {
                if url.is_none() {
                    url = Some(arg);
                } else {
                    return Err(format!(
                        "Unexpected argument. Usage: {prog} [--tls-ca CERT_PEM|-t CERT_PEM] [--verify-hostname] [--profile NAME|-P NAME] [--save] [--demo] [--compact] [ws://HOST:PORT/ws]"
                    ));
                }
            }
        }
    }
    Ok(ParsedArgs {
        url,
        tls_ca,
        profile,
        save,
        demo,
        dry_run,
        metrics_interval_ms,
        processes_interval_ms,
        verify_hostname,
        compact,
    })
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let parsed = match parse_args(env::args()) {
        Ok(v) => v,
        Err(msg) => {
            eprintln!("{msg}");
            return Ok(());
        }
    };

    //support version flag (print and exit)
    if env::args().any(|a| a == "--version" || a == "-V") {
        println!("socktop {}", env!("CARGO_PKG_VERSION"));
        return Ok(());
    }

    if parsed.demo || matches!(parsed.profile.as_deref(), Some("demo")) {
        return run_demo_mode(parsed.tls_ca.as_deref(), parsed.compact).await;
    }

    let profiles_file = load_profiles();
    let req = ProfileRequest {
        profile_name: parsed.profile.clone(),
        url: parsed.url.clone(),
        tls_ca: parsed.tls_ca.clone(),
    };

    let resolved = req.resolve(&profiles_file);
    let mut profiles_mut = profiles_file.clone();
    let (url, tls_ca, metrics_interval_ms, processes_interval_ms): (
        String,
        Option<String>,
        Option<u64>,
        Option<u64>,
    ) = match resolved {
        ResolveProfile::Direct(u, t) => {
            if let Some(name) = parsed.profile.as_ref() {
                let existing = profiles_mut.profiles.get(name);
                match existing {
                    None => {
                        let (mi, pi) = gather_intervals(
                            parsed.metrics_interval_ms,
                            parsed.processes_interval_ms,
                        )?;
                        profiles_mut.profiles.insert(
                            name.clone(),
                            ProfileEntry {
                                url: u.clone(),
                                tls_ca: t.clone(),
                                metrics_interval_ms: mi,
                                processes_interval_ms: pi,
                            },
                        );
                        let _ = save_profiles(&profiles_mut);
                        (u, t, mi, pi)
                    }
                    Some(entry) => {
                        let changed = entry.url != u || entry.tls_ca != t;
                        if changed {
                            let overwrite = if parsed.save {
                                true
                            } else {
                                prompt_yes_no(&format!(
                                    "Overwrite existing profile '{name}'? [y/N]: "
                                ))
                            };
                            if overwrite {
                                let (mi, pi) = gather_intervals(
                                    parsed.metrics_interval_ms,
                                    parsed.processes_interval_ms,
                                )?;
                                profiles_mut.profiles.insert(
                                    name.clone(),
                                    ProfileEntry {
                                        url: u.clone(),
                                        tls_ca: t.clone(),
                                        metrics_interval_ms: mi,
                                        processes_interval_ms: pi,
                                    },
                                );
                                let _ = save_profiles(&profiles_mut);
                                (u, t, mi, pi)
                            } else {
                                (u, t, entry.metrics_interval_ms, entry.processes_interval_ms)
                            }
                        } else {
                            (u, t, entry.metrics_interval_ms, entry.processes_interval_ms)
                        }
                    }
                }
            } else {
                (
                    u,
                    t,
                    parsed.metrics_interval_ms,
                    parsed.processes_interval_ms,
                )
            }
        }
        ResolveProfile::Loaded(u, t) => {
            let entry = profiles_mut
                .profiles
                .get(parsed.profile.as_ref().unwrap())
                .unwrap();
            (u, t, entry.metrics_interval_ms, entry.processes_interval_ms)
        }
        ResolveProfile::PromptSelect(mut names) => {
            if !names.iter().any(|n: &String| n == "demo") {
                names.push("demo".into());
            }
            eprintln!("Select profile:");
            for (i, n) in names.iter().enumerate() {
                eprintln!("  {}. {}", i + 1, n);
            }
            eprint!("Enter number (or blank to abort): ");
            let _ = io::stderr().flush();
            let mut line = String::new();
            if io::stdin().read_line(&mut line).is_ok() {
                if let Ok(idx) = line.trim().parse::<usize>() {
                    if (1..=names.len()).contains(&idx) {
                        let name = &names[idx - 1];
                        if name == "demo" {
                            return run_demo_mode(parsed.tls_ca.as_deref(), parsed.compact).await;
                        }
                        if let Some(entry) = profiles_mut.profiles.get(name) {
                            (
                                entry.url.clone(),
                                entry.tls_ca.clone(),
                                entry.metrics_interval_ms,
                                entry.processes_interval_ms,
                            )
                        } else {
                            return Ok(());
                        }
                    } else {
                        return Ok(());
                    }
                } else {
                    return Ok(());
                }
            } else {
                return Ok(());
            }
        }
        ResolveProfile::PromptCreate(name) => {
            eprintln!("Profile '{name}' does not exist yet.");
            let url = prompt_string("Enter URL (ws://HOST:PORT/ws or wss://...): ")?;
            if url.trim().is_empty() {
                return Ok(());
            }
            let ca = prompt_string("Enter TLS CA path (or leave blank): ")?;
            let ca_opt = if ca.trim().is_empty() {
                None
            } else {
                Some(ca.trim().to_string())
            };
            let (mi, pi) =
                gather_intervals(parsed.metrics_interval_ms, parsed.processes_interval_ms)?;
            profiles_mut.profiles.insert(
                name.clone(),
                ProfileEntry {
                    url: url.trim().to_string(),
                    tls_ca: ca_opt.clone(),
                    metrics_interval_ms: mi,
                    processes_interval_ms: pi,
                },
            );
            let _ = save_profiles(&profiles_mut);
            (url.trim().to_string(), ca_opt, mi, pi)
        }
        ResolveProfile::None => {
            //eprintln!("No URL provided and no profiles to select.");

            //first run, no args, no profiles: show welcome message and offer demo mode
            if profiles_mut.profiles.is_empty() && parsed.url.is_none() {
                eprintln!("Welcome to socktop!");
                eprintln!("It looks like this is your first time running the application.");
                eprintln!(
                    "You can connect to a socktop_agent instance to monitor system metrics and processes."
                );
                eprintln!("If you don't have an agent running, you can try the demo mode.");
                if prompt_yes_no("Would you like to start the demo mode now? [Y/n]: ") {
                    return run_demo_mode(parsed.tls_ca.as_deref(), parsed.compact).await;
                } else {
                    eprintln!("Aborting. You can run 'socktop --help' for usage information.");
                    return Ok(());
                }
            }
            return Err("No URL provided and no profiles to select.".into());
        }
    };

    let is_tls = url.starts_with("wss://");
    let has_token = url.contains("token=");
    // Only enable local process-kill when the agent is verified to be on this
    // machine; otherwise on-screen PIDs refer to a remote host and acting on
    // them locally would signal the wrong process. See local::agent_is_local.
    let is_local = local::agent_is_local(&url);
    let mut app = App::new()
        .with_intervals(metrics_interval_ms, processes_interval_ms)
        .with_status(is_tls, has_token)
        .with_compact(parsed.compact)
        .with_local(is_local);
    if parsed.dry_run {
        return Ok(());
    }
    app.run(&url, tls_ca.as_deref(), parsed.verify_hostname)
        .await
}

fn prompt_yes_no(prompt: &str) -> bool {
    eprint!("{prompt}");
    let _ = io::stderr().flush();
    let mut line = String::new();
    if io::stdin().read_line(&mut line).is_ok() {
        matches!(line.trim().to_ascii_lowercase().as_str(), "y" | "yes")
    } else {
        false
    }
}
fn prompt_string(prompt: &str) -> io::Result<String> {
    eprint!("{prompt}");
    let _ = io::stderr().flush();
    let mut line = String::new();
    io::stdin().read_line(&mut line)?;
    Ok(line)
}

fn gather_intervals(
    arg_metrics: Option<u64>,
    arg_procs: Option<u64>,
) -> Result<(Option<u64>, Option<u64>), Box<dyn std::error::Error>> {
    let default_metrics = 500u64;
    let default_procs = 2000u64;
    let metrics = match arg_metrics {
        Some(v) => Some(v),
        None => {
            let inp = prompt_string(&format!(
                "Metrics interval ms (default {default_metrics}, Enter for default): "
            ))?;
            let t = inp.trim();
            if t.is_empty() {
                Some(default_metrics)
            } else {
                Some(t.parse()?)
            }
        }
    };
    let procs = match arg_procs {
        Some(v) => Some(v),
        None => {
            let inp = prompt_string(&format!(
                "Processes interval ms (default {default_procs}, Enter for default): "
            ))?;
            let t = inp.trim();
            if t.is_empty() {
                Some(default_procs)
            } else {
                Some(t.parse()?)
            }
        }
    };
    Ok((metrics, procs))
}

// Demo mode implementation
async fn run_demo_mode(
    _tls_ca: Option<&str>,
    compact: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    let port = 3231;
    let url = format!("ws://127.0.0.1:{port}/ws");
    let child = match spawn_demo_agent(port) {
        Ok(child) => child,
        // The agent ships as its own binary, so a missing one is a setup problem,
        // not a crash: tell the user how to fix it instead of dumping an io error.
        Err(e @ DemoAgentError::NotFound(_)) => {
            eprintln!("{e}");
            return Ok(());
        }
        Err(e) => return Err(e.into()),
    };
    // Demo mode runs the real agent on loopback, so its PIDs are real local
    // processes — enable the local process-kill feature, gated the same way as
    // the normal connect path (loopback resolves local).
    let mut app = App::new()
        .with_compact(compact)
        .with_local(local::agent_is_local(&url));
    // Demo mode connects to localhost, so disable hostname verification
    tokio::select! { res=app.run(&url,None,false)=>{ drop(child); res } _=tokio::signal::ctrl_c()=>{ drop(child); Ok(()) } }
}
struct DemoGuard {
    port: u16,
    child: std::sync::Arc<std::sync::Mutex<Option<std::process::Child>>>,
}
impl Drop for DemoGuard {
    fn drop(&mut self) {
        if let Some(mut ch) = self.child.lock().unwrap().take() {
            let _ = ch.kill();
        }
        eprintln!("Stopped demo agent on port {}", self.port);
    }
}
#[derive(Debug)]
enum DemoAgentError {
    /// The socktop_agent executable could not be located.
    NotFound(std::path::PathBuf),
    Io(std::io::Error),
}

impl std::fmt::Display for DemoAgentError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NotFound(candidate) => write!(
                f,
                "Could not start demo mode: '{}' was not found{}.\n\
                 \n\
                 Demo mode runs a local agent, which is shipped as a separate binary\n\
                 and is not installed alongside the socktop TUI. Install it with:\n\
                 \n    cargo install socktop_agent\n\n\
                 then run socktop again. See {} for other install options.",
                candidate.display(),
                // A bare file name means find_agent_executable() fell back to a PATH lookup.
                if candidate.parent().is_none_or(|p| p.as_os_str().is_empty()) {
                    " on your PATH"
                } else {
                    ""
                },
                env!("CARGO_PKG_HOMEPAGE"),
            ),
            Self::Io(e) => write!(f, "Could not start demo mode: {e}"),
        }
    }
}

impl std::error::Error for DemoAgentError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::NotFound(_) => None,
            Self::Io(e) => Some(e),
        }
    }
}

fn spawn_demo_agent(port: u16) -> Result<DemoGuard, DemoAgentError> {
    let candidate = find_agent_executable();
    let mut cmd = std::process::Command::new(&candidate);
    cmd.arg("--port").arg(port.to_string());
    cmd.env("SOCKTOP_ENABLE_SSL", "0");

    //JW: do not disable GPU and TEMP in demo mode
    //cmd.env("SOCKTOP_AGENT_GPU", "0");
    //cmd.env("SOCKTOP_AGENT_TEMP", "0");

    let child = cmd.spawn().map_err(|e| match e.kind() {
        std::io::ErrorKind::NotFound => DemoAgentError::NotFound(candidate),
        _ => DemoAgentError::Io(e),
    })?;
    std::thread::sleep(std::time::Duration::from_millis(300));
    Ok(DemoGuard {
        port,
        child: std::sync::Arc::new(std::sync::Mutex::new(Some(child))),
    })
}
fn find_agent_executable() -> std::path::PathBuf {
    if let Ok(exe) = std::env::current_exe()
        && let Some(parent) = exe.parent()
    {
        #[cfg(windows)]
        let name = "socktop_agent.exe";
        #[cfg(not(windows))]
        let name = "socktop_agent";
        let candidate = parent.join(name);
        if candidate.exists() {
            return candidate;
        }
    }
    std::path::PathBuf::from("socktop_agent")
}