Skip to content

skywall34/sysmon

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SysMon - System Monitor TUI

A terminal-based system monitoring application built with Rust, providing real-time insights into CPU, memory, processes, and disk usage.

Features

  • Real-time System Monitoring

    • CPU usage (average and per-core)
    • Memory and swap usage
    • Process monitoring with detailed metrics
    • Disk usage across all mounted filesystems
  • Interactive TUI

    • Navigate between System Monitor and Disk Usage pages
    • Sort processes by CPU, memory, PID, or name
    • Sort disks by name, size, used space, available space, or usage percentage
    • Search/filter processes and disks
    • Kill processes interactively
    • NEW: Directory browser with tree-like navigation
    • NEW: Browse into mount points and explore filesystem hierarchy
    • NEW: Recursive directory size calculation
  • Performance Optimized

    • Efficient filtering with query caching
    • Minimal memory allocations
    • 60 FPS refresh rate for smooth UI
    • Modular architecture with separation of concerns

Installation

Prerequisites

  • Rust 1.70 or later
  • Linux/Unix environment (uses sysinfo crate)

Build from Source

# Clone the repository
git clone <repository-url>
cd sysmon

# Build release version
cargo build --release

# Run the application
./target/release/sysmon

Usage

Navigation

Global Controls:

  • Tab - Switch between System Monitor and Disk Usage pages
  • q - Quit application
  • / - Enter search mode
  • Esc - Clear search and reset selection
  • / - Navigate through processes/disks

System Monitor Page:

  • c - Sort by CPU usage
  • m - Sort by memory usage
  • p - Sort by PID
  • n - Sort by name
  • k - Kill selected process (with confirmation)

Disk Usage Page (Mount Points View):

  • s - Sort by size
  • u - Sort by used space
  • a - Sort by available space
  • % - Sort by usage percentage
  • n - Sort by mount point name
  • f - Sort by filesystem type
  • Enter - Browse into selected mount point

Disk Usage Page (Directory Browser View):

  • Enter - Navigate into selected directory
  • Backspace - Go to parent directory
  • Esc - Return to mount points view

Search Mode:

  • Type to filter processes/disks in real-time
  • Enter or Esc - Exit search mode
  • Backspace - Delete characters

Architecture

Project Structure

sysmon/
├── src/
│   ├── main.rs                # Application entry point, event loop, state management
│   ├── ui.rs                  # TUI rendering (ratatui-based)
│   └── metrics/
│       ├── mod.rs             # Metrics aggregator module
│       ├── system.rs          # System metrics (CPU, memory, processes)
│       ├── disk.rs            # Disk metrics (mount points, disk info)
│       └── directory.rs       # Directory navigator (tree traversal, size calc)
├── Cargo.toml                 # Project dependencies
├── README.md                  # This file
└── ARCHITECTURE.md            # Detailed architecture documentation

Core Components

1. Main Application (main.rs)

Key Responsibilities:

  • Event loop management (60 FPS)
  • User input handling
  • Application state management
  • Terminal setup/cleanup with RAII guard pattern

Key Types:

  • AppState - Stores current page, sort modes, selections, search state
  • RawModeGuard - Ensures terminal cleanup on panic (RAII pattern)
  • Direction - Enum for navigation (Up/Down)

Design Patterns:

  • RAII for terminal cleanup
  • Helper functions (handle_navigation, reset_selection) for DRY code
  • Constants for magic numbers (PROCESS_VISIBLE_ROWS, DISK_VISIBLE_ROWS)

2. Metrics Module (metrics/)

The metrics module has been refactored into separate submodules for better organization and maintainability:

metrics/mod.rs - Aggregator:

  • Metrics struct that combines all metric types
  • Provides unified access to system, disk, and directory metrics

metrics/system.rs - System Metrics:

  • SystemMetrics - CPU, memory, swap, and process data
  • ProcessInfo - Individual process information
  • Process filtering and sorting with query caching
  • Per-core CPU monitoring

Key Methods:

pub fn update(&mut self, sys: &mut System)              // Refresh system metrics
pub fn filter_processes(&mut self, query: &str) -> &[ProcessInfo]  // Cached filtering
pub fn apply_sort(&mut self, mode: SortMode)            // Sort processes
pub fn memory_usage_percent(&self) -> f64               // Memory usage calculation
pub fn swap_usage_percent(&self) -> f64                 // Swap usage calculation

metrics/disk.rs - Disk Metrics:

  • DiskMetrics - Mount point and filesystem information
  • DiskInfo - Individual disk/partition data
  • Disk filtering and sorting
  • Byte formatting utilities

Key Methods:

pub fn update_disks(&mut self, disks: &Disks)           // Refresh disk metrics
pub fn filter_disks(&mut self, query: &str) -> &[DiskInfo]  // Cached filtering
pub fn apply_disk_sort(&mut self, mode: DiskSortMode)   // Sort disks
pub fn disk_used_space(disk: &DiskInfo) -> u64          // Calculate used space
pub fn disk_usage_percent(disk: &DiskInfo) -> f64       // Usage percentage
pub fn format_bytes(bytes: u64) -> String               // Human-readable sizes

metrics/directory.rs - Directory Navigator:

  • DirectoryNavigator - Directory tree traversal
  • DirectoryEntry - File/directory metadata with size
  • Recursive directory size calculation
  • Parent directory navigation

Key Methods:

pub fn enter_directory(&mut self, path: PathBuf) -> Result<(), std::io::Error>  // Navigate into directory
pub fn exit_to_parent(&mut self) -> Result<(), std::io::Error>  // Go to parent
pub fn exit_to_mount_points(&mut self)                   // Return to mount points view
pub fn filter_entries(&mut self, query: &str) -> &[DirectoryEntry]  // Filter entries

Optimizations:

  • Filter caching: Only re-filters when query changes
  • Returns references (&[T]) instead of cloning vectors
  • Implements Default trait for idiomatic Rust
  • Saturating arithmetic to prevent overflow in size calculations

3. UI Rendering (ui.rs)

Key Responsibilities:

  • TUI layout and rendering using ratatui
  • Color-coded indicators for resource usage
  • Table rendering with sort indicators
  • Dynamic filtering display

Layout Structure:

System Monitor:

┌─────────────────────────────────────────────┐
│           SYSTEM MONITOR (Header)           │
├─────────────┬───────────────────────────────┤
│  CPU Gauge  │                               │
│             │     Process Table             │
│  CPU Cores  │     (PID, Name, CPU%,         │
│             │      Memory, Status)          │
│   Memory    │                               │
│   Details   │                               │
├─────────────┴───────────────────────────────┤
│           Footer (Help Text)                │
└─────────────────────────────────────────────┘

Disk Usage (Mount Points View):

┌─────────────────────────────────────────────┐
│           DISK USAGE (Header)               │
├─────────────────────────────────────────────┤
│  Summary (Total disks, space, etc.)         │
├─────────────────────────────────────────────┤
│     Disk Table (Mount, Device, FS,          │
│      Size, Used, Avail, Use%)               │
├─────────────────────────────────────────────┤
│     Selected Disk Details                   │
├─────────────────────────────────────────────┤
│           Footer (Help Text)                │
└─────────────────────────────────────────────┘

Disk Usage (Directory Browser View):

┌─────────────────────────────────────────────┐
│           DISK USAGE (Header)               │
├─────────────────────────────────────────────┤
│  Summary (Total disks, space, etc.)         │
├─────────────────────────────────────────────┤
│  Directory Table (Name, Size)               │
│  - Shows ".." for parent directory          │
│  - Directories marked with "/" suffix       │
│  - Recursive size calculation               │
├─────────────────────────────────────────────┤
│     Selected Disk Details                   │
├─────────────────────────────────────────────┤
│           Footer (Help Text)                │
└─────────────────────────────────────────────┘

Color Scheme:

  • CPU: Green (<30%) → Yellow (30-60%) → Light Red (60-80%) → Red (>80%)
  • Memory: Green (<50%) → Yellow (50-70%) → Light Red (70-85%) → Red (>85%)
  • Disk: Green (<50%) → Yellow (50-75%) → Light Red (75-90%) → Red (>90%)

Dependencies

[dependencies]
crossterm = "0.28"        # Terminal manipulation
ratatui = "0.29"          # TUI framework
sysinfo = "0.32"          # System information

Code Quality Features

Error Handling

  • All float comparisons use .unwrap_or(Ordering::Equal) to prevent NaN panics
  • Terminal cleanup guaranteed via RawModeGuard (Drop trait)
  • Graceful degradation for missing/invalid system data

Performance

  • Minimal allocations with reference returns
  • Filter result caching (only re-filters on query change)
  • 500ms system update interval vs 16ms UI refresh
  • Efficient scroll windowing (only renders visible rows)

Maintainability

  • DRY principle: Extracted helpers for navigation and reset logic
  • Named structs instead of tuples for readability
  • Constants for magic numbers
  • Clear separation of concerns (metrics/UI/main loop)

Limitations & Future Enhancements

Current Limitations:

  • Process kill requires appropriate permissions
  • Limited to local system (no remote monitoring)
  • Fixed color thresholds (not user-configurable)

Potential Enhancements:

  • Network I/O monitoring
  • Historical graphs/charts
  • Configurable update intervals
  • Export metrics to file
  • Custom color themes
  • Multi-process tracking
  • Directory size caching to improve performance on large directories
  • File type filtering in directory browser
  • Bookmark favorite directories

Development

Running Tests

cargo test

Running with Debug Info

RUST_BACKTRACE=1 cargo run

Building for Distribution

cargo build --release --target <your-target>

License

[Your License Here]

Contributing

Contributions welcome! Please ensure:

  • Code passes cargo clippy with no warnings
  • Run cargo fmt before committing
  • Add tests for new features
  • Update this README for architectural changes

Acknowledgments

Built with:

About

Personal TUI app for system monitoring

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages