Skip to main content

Developer Guide - CS Monitor

Welcome to the CS Monitor source code! This guide covers the installation, configuration, and architecture for developers who want to extend or modify the project.

🛠 Prerequisites

Before you start, ensure you have the following installed:

  • OS: Linux (Ubuntu recommended), macOS, or Windows.
  • Backend: Python 3.12+, Docker & Docker Compose (optional for local dev).
  • Frontend: Flutter SDK (Latest Stable), Android Studio / VS Code.
  • Git: Version control.

📂 Project Structure

/CS-Monitor
├── /backend          # Django Project (DRF + Paramiko)
│   ├── /logs           # Log storage (if using file logs)
│   ├── /servercontrol  # Main Django Configuration
│   │    └──/settings
│   │       ├── base.py        # Common settings
│   │       ├── developer.py   # Dev settings (DEBUG=True)
│   │       └── production.py  # Prod settings
│   ├── /sshmanager
│   │   ├── /views          # Modularized Views
│   │   │   ├── api_servers.py
│   │   │   ├── commands_views.py 
│   │   │   ├── files_views.py
│   │   │   └── ...
│   │   ├── models.py
│   │   ├── serializers.py  
│   │   └── utils.py        # SSH & Paramiko Logic (Core)
│   ├── requirements.txt    
│   └── manage.py
├── /frontend          # Flutter Application
│   ├── /android       # Android Native Config
│   ├── /ios           # iOS Native Config
│   ├── /lib
│   │   ├── /core
│   │   │   └── constants.dart 
│   │   ├── /l10n      # Internationalization (.arb files)
│   │   ├── /models    # Data Models (mirroring Backend)
│   │   ├── /screens   # UI Screens
│   │   ├── /services  # API Service & Preferences
│   │   └── /widgets   # Reusable UI Components
│   └── pubspec.yaml
├── /docker            # Deployment configurations
└── README.md

🐍 Backend Setup (Django)

The backend handles SSH connections using Paramiko and exposes data via Django Rest Framework.

  1. Navigate to the backend folder:

    cd backend
    
  2. Create a Virtual Environment:

    python3 -m venv venv
    source venv/bin/activate  # On Windows: venv\Scripts\activate
    
  3. Install Dependencies:

    pip install -r requirements.txt
    
  4. Database Migration: Default uses SQLite for development.

    python manage.py migrate
    python manage.py createsuperuser  # Create your admin account
    
  5. Run Local Server:

    python manage.py runserver 0.0.0.0:8000
    

    The API will be available at http://localhost:8000/api/

💡 Key Backend Concepts

  • SSH Connections: Logic located in backend/sshmanager/utils.py. We use Paramiko to execute commands securely.
  • Security: Passwords and Private Keys are encrypted in the database using Django's crypto libraries (check backend/servercontrol/settings/base.py for encryption keys).
  • Environment Variables: We use .env files for security (check backend/.env.example).

🧠 Backend Code Breakdown

Here is a detailed explanation of the key files inside the sshmanager app.

1. Views Modules (/sshmanager/views/)

These files handle the API logic.

File Name Description
api_crud.py Monitoring Config API. Standard endpoints to add/edit Services and Log paths. Supports filtering by server_id.
api_servers.py Server Inventory API. Manages the list of servers. Handles secure credential storage via POST/PUT.
commands_views.py System Control Logic.
ExecuteCommandView: Handles the CMD Runner and "Sudo Injection".
ManageServiceView: Controls systemctl. Enforces "Protected Service" rules.
MaintenanceView: Executes custom maintenance scripts.
files_views.py File System API. The backend for the File Explorer.
ListFilesView: Navigates directories.
FileEditorView: Logic for the In-App Code Editor.
FileManagerActionsView: Create, Delete, Rename logic.
logs_views.py Logs Reader API. Retrieves the last N lines of a log. Dynamically switches between tail (files) and journalctl (services).
resources_views.py Dashboard Metrics. Fetches real-time CPU, RAM, and Disk usage using optimized shell commands (top, free, df).

2. Other Key Files

  • Models (models.py): Defines schema for Servers, Services, and Logs. Security: Implements EncryptedCharField. If the DB is stolen, credentials remain unreadable without the SECRET_KEY.
  • Serializers (serializers.py): Converts models to JSON. Security: Marks password and private_key as write_only. Credentials are never exposed in GET requests.
  • Utils (utils.py) - The Core ⚙️: Wraps the Paramiko library. The ServerCommander class abstracts Local vs. Remote execution, meaning the API doesn't need to know how to execute a command, just what to execute.

📱 Frontend Setup (Flutter)

The mobile app connects to the Django Backend.

  1. Navigate to the frontend folder:

    cd frontend
    
  2. Install Dependencies:

    flutter pub get
    
  3. Run the App:

    flutter run
    
  4. Configure Backend URL (First Run):

    • Android Emulator: Use http://10.0.2.2:8000.
    • Physical Device: Ensure your phone and PC are on the same Wi-Fi and use your PC's local IP (e.g., http://192.168.1.50:8000).

🍎 iOS Note

This project supports iOS. However, to build the .ipa or run on the iOS Simulator, you must use a macOS computer with Xcode installed.

🔐 Biometrics

Biometric logic (FaceID/Fingerprint) is handled by the local_auth package. * Android: Config in android/app/src/main/AndroidManifest.xml. * iOS: Config in ios/Runner/Info.plist.


🧩 Frontend Code Breakdown

1. Key Dependencies (pubspec.yaml)

Package Purpose
flutter_secure_storage Critical. Stores URL/Token securely (AES). Pinned to v9.2.2 for max compatibility.
local_auth Handles Biometric authentication.
ansicolor Parses ANSI colors for the CMD Runner.
flutter_localizations Multi-language engine (generate: true).

2. Key Files (lib/)

File Description
lib/main.dart The Brain. Manages App Lifecycle, Biometric Security Loop, and Global Theming.
lib/services/api_service.dart Network Layer. Singleton for HTTP requests. Handles Login/Logout and Token storage.
lib/services/preferences_service.dart UX Persistence. Remembers the last active server ID.
lib/screens/console_screen.dart Remote Terminal. Terminal emulator UI with ANSI color support.
lib/screens/file_editor_screen.dart Code Editor. Monospace editor for modifying remote files.
lib/screens/file_manager_screen.dart File Explorer. Recursive directory navigation.
lib/screens/home_screen.dart Dashboard. Aggregates data (Resources, Services) using parallel execution.
lib/screens/log_viewer_screen.dart Log Reader. Terminal-style UI for reading logs.
lib/screens/login_screen.dart First Run Wizard. Handles initial connection and "Smart URL" logic.
lib/screens/server_config_screen.dart Add/Edit Server. Dynamic form for SSH and Maintenance config.
lib/screens/server_list_screen.dart Inventory. Lists servers and sets the "Active" one.
lib/widgets/resource_card.dart Health Monitor. Visual CPU/RAM bars with dynamic coloring.
lib/widgets/service_card.dart Service Controller. Manages service state and protects critical services.

🚀 Extending the Functionality

1. Extending the SSH Manager

To add a new capability (e.g., download_file), modify backend/sshmanager/utils.py. Pattern to follow: You must handle both scenarios in ServerCommander:

def new_feature(self, arg):
    # 1. Local Logic
    if self.server.is_local:
        return local_result_using_os_lib
    # 2. Remote Logic
    else:
        if not self.client: self.connect()
        return self.client.exec_command("...")

2. Adding Database Fields

If you want to track more info (e.g., a description field for Servers):

  1. Edit backend/sshmanager/models.py:

    description = models.TextField(blank=True)
    
  2. Create and apply migration:

    python manage.py makemigrations
    python manage.py migrate
    
  3. Important: Update serializers.py to expose the field to the API:

    class ServerSerializer(...):
        class Meta:
            fields = [..., 'description']
    

3. Adding a CMD Runner Button

To add a quick button in the terminal: 1. Open lib/screens/console_screen.dart. 2. Add your command to the _shortcuts list:

final List<String> _shortcuts = [
      "ls -la", ..., "my-new-command"
    ];
    


❓ Troubleshooting

  • Paramiko Connection Error: Ensure the target server allows SSH connections and credentials are correct. Check if the IP is whitelisted on the server's firewall.
  • Flutter "Connection Refused": Check your IP. Android Emulator cannot see localhost, use 10.0.2.2.
  • Biometrics not working on Emulator: You must configure a PIN/Fingerprint in the Emulator settings first.

Happy Coding! Developed by CoreSaaS

Need more help? Contact support

💬
Asistente CoreSaaS BETA
⚠️ Límite: 10 consultas por sesión
×