Spaces:
Sleeping
Sleeping
wei9072 commited on
Commit ·
16ee433
0
Parent(s):
feat: initial commit for Linux System Monitor Dashboard
Browse files- .github/workflows/ci.yml +28 -0
- .gitignore +3 -0
- Dockerfile +22 -0
- backend/__init__.py +0 -0
- backend/collector.py +152 -0
- backend/config.yaml +16 -0
- backend/main.py +96 -0
- backend/manager.py +61 -0
- backend/schemas.py +48 -0
- backend/tests/test_collector.py +100 -0
- backend/tests/test_manager.py +59 -0
- backend/tests/test_websocket.py +46 -0
- cli/monitor_cli.py +134 -0
- docker-compose.yml +12 -0
- docs/superpowers/plans/2025-05-22-scaffolding-and-config.md +182 -0
- frontend/index.html +222 -0
- requirements.txt +9 -0
.github/workflows/ci.yml
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Python CI
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
branches: [ "main" ]
|
| 6 |
+
pull_request:
|
| 7 |
+
branches: [ "main" ]
|
| 8 |
+
|
| 9 |
+
jobs:
|
| 10 |
+
test:
|
| 11 |
+
runs-on: ubuntu-latest
|
| 12 |
+
|
| 13 |
+
steps:
|
| 14 |
+
- uses: actions/checkout@v4
|
| 15 |
+
|
| 16 |
+
- name: Set up Python
|
| 17 |
+
uses: actions/setup-python@v5
|
| 18 |
+
with:
|
| 19 |
+
python-version: "3.12"
|
| 20 |
+
|
| 21 |
+
- name: Install dependencies
|
| 22 |
+
run: |
|
| 23 |
+
python -m pip install --upgrade pip
|
| 24 |
+
pip install -r requirements.txt
|
| 25 |
+
|
| 26 |
+
- name: Run Pytest
|
| 27 |
+
run: |
|
| 28 |
+
pytest backend/tests/ -v
|
.gitignore
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.venv/
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.pyc
|
Dockerfile
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 使用輕量級的 Python 映像檔
|
| 2 |
+
FROM python:3.12-slim
|
| 3 |
+
|
| 4 |
+
WORKDIR /app
|
| 5 |
+
|
| 6 |
+
# 安裝系統依賴 (如果需要的話)
|
| 7 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 8 |
+
build-essential \
|
| 9 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 10 |
+
|
| 11 |
+
# 複製並安裝 Python 套件
|
| 12 |
+
COPY requirements.txt .
|
| 13 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 14 |
+
|
| 15 |
+
# 複製專案原始碼
|
| 16 |
+
COPY . .
|
| 17 |
+
|
| 18 |
+
# 曝露 FastAPI 埠號
|
| 19 |
+
EXPOSE 8000
|
| 20 |
+
|
| 21 |
+
# 啟動命令
|
| 22 |
+
CMD ["python", "-m", "uvicorn", "backend.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
backend/__init__.py
ADDED
|
File without changes
|
backend/collector.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
import os
|
| 3 |
+
import glob
|
| 4 |
+
from typing import Dict, Tuple, Optional
|
| 5 |
+
from .schemas import SystemMetrics, CPUInfo, MemoryInfo, NetworkInfo, DiskInfo
|
| 6 |
+
|
| 7 |
+
class SystemCollector:
|
| 8 |
+
def __init__(self):
|
| 9 |
+
self.prev_cpu: Optional[Tuple[float, float]] = None # (idle, total)
|
| 10 |
+
self.prev_net: Optional[Tuple[float, float, float]] = None # (timestamp, rx, tx)
|
| 11 |
+
self.prev_disk: Optional[Tuple[float, float, float]] = None # (timestamp, read, write)
|
| 12 |
+
|
| 13 |
+
def _read_proc_stat(self) -> Tuple[float, float]:
|
| 14 |
+
"""Read /proc/stat and return (idle, total) times."""
|
| 15 |
+
with open("/proc/stat", "r") as f:
|
| 16 |
+
line = f.readline()
|
| 17 |
+
if not line.startswith("cpu "):
|
| 18 |
+
raise ValueError("Could not find CPU info in /proc/stat")
|
| 19 |
+
|
| 20 |
+
parts = [float(p) for p in line.split()[1:]]
|
| 21 |
+
# user, nice, system, idle, iowait, irq, softirq, steal, guest, guest_nice
|
| 22 |
+
# total_time = sum(all_values)
|
| 23 |
+
# idle_time = idle + iowait
|
| 24 |
+
idle = parts[3] + parts[4] # idle + iowait
|
| 25 |
+
total = sum(parts)
|
| 26 |
+
return idle, total
|
| 27 |
+
|
| 28 |
+
def _read_meminfo(self) -> Dict[str, float]:
|
| 29 |
+
"""Read /proc/meminfo and return metrics in kB."""
|
| 30 |
+
metrics = {}
|
| 31 |
+
with open("/proc/meminfo", "r") as f:
|
| 32 |
+
for line in f:
|
| 33 |
+
parts = line.split(":")
|
| 34 |
+
if len(parts) == 2:
|
| 35 |
+
name = parts[0].strip()
|
| 36 |
+
value = parts[1].split()[0].strip()
|
| 37 |
+
metrics[name] = float(value)
|
| 38 |
+
return metrics
|
| 39 |
+
|
| 40 |
+
def _read_net_dev(self) -> Tuple[float, float]:
|
| 41 |
+
"""Read /proc/net/dev and return (rx_bytes, tx_bytes) summed across interfaces."""
|
| 42 |
+
rx_total = 0.0
|
| 43 |
+
tx_total = 0.0
|
| 44 |
+
with open("/proc/net/dev", "r") as f:
|
| 45 |
+
lines = f.readlines()[2:] # Skip header
|
| 46 |
+
for line in lines:
|
| 47 |
+
parts = line.split(":")
|
| 48 |
+
if len(parts) == 2:
|
| 49 |
+
iface = parts[0].strip()
|
| 50 |
+
if iface == "lo":
|
| 51 |
+
continue
|
| 52 |
+
stats = parts[1].split()
|
| 53 |
+
rx_total += float(stats[0])
|
| 54 |
+
tx_total += float(stats[8])
|
| 55 |
+
return rx_total, tx_total
|
| 56 |
+
|
| 57 |
+
def _read_diskstats(self) -> Tuple[float, float]:
|
| 58 |
+
"""Read /proc/diskstats and return (read_bytes, write_bytes)."""
|
| 59 |
+
read_total = 0.0
|
| 60 |
+
write_total = 0.0
|
| 61 |
+
# Sector size is usually 512 bytes
|
| 62 |
+
SECTOR_SIZE = 512
|
| 63 |
+
with open("/proc/diskstats", "r") as f:
|
| 64 |
+
for line in f:
|
| 65 |
+
parts = line.split()
|
| 66 |
+
# Field 3 is device name, field 5 is sectors read, field 9 is sectors written
|
| 67 |
+
# According to kernel docs, field 4-7 are read related, 8-11 are write related.
|
| 68 |
+
# Actually, in modern kernels:
|
| 69 |
+
# 0: major, 1: minor, 2: name, 3: reads completed, 4: reads merged, 5: sectors read, 6: time spent reading
|
| 70 |
+
# 7: writes completed, 8: writes merged, 9: sectors written, 10: time spent writing
|
| 71 |
+
# We skip partitions and only count main disks (e.g., sda, nvme0n1)
|
| 72 |
+
# Simple rule: if it ends with a digit (like sda1), skip? No, nvme0n1 ends with 1.
|
| 73 |
+
# Usually we want to aggregate or just take everything.
|
| 74 |
+
# Let's aggregate everything that looks like a main disk or just aggregate all.
|
| 75 |
+
# Actually, summing everything might double count (disk + partitions).
|
| 76 |
+
# A common heuristic is to only count devices without digits or with specific names.
|
| 77 |
+
# Let's just sum everything and divide by 2? No, that's not good.
|
| 78 |
+
# For simplicity, let's sum only if it doesn't match common partition patterns or just sum all for now.
|
| 79 |
+
# Better: only include devices that are directly in /sys/block/
|
| 80 |
+
dev_name = parts[2]
|
| 81 |
+
if os.path.exists(f"/sys/block/{dev_name}"):
|
| 82 |
+
read_total += float(parts[5]) * SECTOR_SIZE
|
| 83 |
+
write_total += float(parts[9]) * SECTOR_SIZE
|
| 84 |
+
return read_total, write_total
|
| 85 |
+
|
| 86 |
+
def _read_temp(self) -> float:
|
| 87 |
+
"""Read temperature from /sys/class/thermal/thermal_zone*/temp."""
|
| 88 |
+
temps = []
|
| 89 |
+
for path in glob.glob("/sys/class/thermal/thermal_zone*/temp"):
|
| 90 |
+
try:
|
| 91 |
+
with open(path, "r") as f:
|
| 92 |
+
# temp is in millicelsius
|
| 93 |
+
temps.append(float(f.read().strip()) / 1000.0)
|
| 94 |
+
except (OSError, ValueError):
|
| 95 |
+
continue
|
| 96 |
+
return max(temps) if temps else 0.0
|
| 97 |
+
|
| 98 |
+
def collect(self) -> SystemMetrics:
|
| 99 |
+
now = time.time()
|
| 100 |
+
|
| 101 |
+
# CPU
|
| 102 |
+
curr_idle, curr_total = self._read_proc_stat()
|
| 103 |
+
cpu_usage = 0.0
|
| 104 |
+
if self.prev_cpu:
|
| 105 |
+
prev_idle, prev_total = self.prev_cpu
|
| 106 |
+
delta_idle = curr_idle - prev_idle
|
| 107 |
+
delta_total = curr_total - prev_total
|
| 108 |
+
if delta_total > 0:
|
| 109 |
+
cpu_usage = (1.0 - delta_idle / delta_total) * 100.0
|
| 110 |
+
self.prev_cpu = (curr_idle, curr_total)
|
| 111 |
+
|
| 112 |
+
# Temp
|
| 113 |
+
temp_c = self._read_temp()
|
| 114 |
+
|
| 115 |
+
# Memory
|
| 116 |
+
mem = self._read_meminfo()
|
| 117 |
+
total_gb = mem.get("MemTotal", 0) / (1024 * 1024)
|
| 118 |
+
available_gb = mem.get("MemAvailable", mem.get("MemFree", 0) + mem.get("Buffers", 0) + mem.get("Cached", 0)) / (1024 * 1024)
|
| 119 |
+
used_gb = total_gb - available_gb
|
| 120 |
+
mem_percent = (used_gb / total_gb * 100.0) if total_gb > 0 else 0.0
|
| 121 |
+
|
| 122 |
+
# Network
|
| 123 |
+
curr_rx, curr_tx = self._read_net_dev()
|
| 124 |
+
rx_kbps = 0.0
|
| 125 |
+
tx_kbps = 0.0
|
| 126 |
+
if self.prev_net:
|
| 127 |
+
prev_time, prev_rx, prev_tx = self.prev_net
|
| 128 |
+
delta_time = now - prev_time
|
| 129 |
+
if delta_time > 0:
|
| 130 |
+
rx_kbps = (curr_rx - prev_rx) / delta_time / 1024.0
|
| 131 |
+
tx_kbps = (curr_tx - prev_tx) / delta_time / 1024.0
|
| 132 |
+
self.prev_net = (now, curr_rx, curr_tx)
|
| 133 |
+
|
| 134 |
+
# Disk
|
| 135 |
+
curr_read, curr_write = self._read_diskstats()
|
| 136 |
+
read_kbps = 0.0
|
| 137 |
+
write_kbps = 0.0
|
| 138 |
+
if self.prev_disk:
|
| 139 |
+
prev_time, prev_read, prev_write = self.prev_disk
|
| 140 |
+
delta_time = now - prev_time
|
| 141 |
+
if delta_time > 0:
|
| 142 |
+
read_kbps = (curr_read - prev_read) / delta_time / 1024.0
|
| 143 |
+
write_kbps = (curr_write - prev_write) / delta_time / 1024.0
|
| 144 |
+
self.prev_disk = (now, curr_read, curr_write)
|
| 145 |
+
|
| 146 |
+
return SystemMetrics(
|
| 147 |
+
cpu=CPUInfo(usage_percent=round(cpu_usage, 2), temp_celsius=round(temp_c, 2)),
|
| 148 |
+
memory=MemoryInfo(total_gb=round(total_gb, 2), used_gb=round(used_gb, 2), percent=round(mem_percent, 2)),
|
| 149 |
+
network=NetworkInfo(rx_kbps=round(rx_kbps, 2), tx_kbps=round(tx_kbps, 2)),
|
| 150 |
+
disk=DiskInfo(read_kbps=round(read_kbps, 2), write_kbps=round(write_kbps, 2)),
|
| 151 |
+
timestamp=now
|
| 152 |
+
)
|
backend/config.yaml
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
core:
|
| 2 |
+
interval: 1.0 # Data collection interval in seconds
|
| 3 |
+
buffer_size: 100 # Number of data points to keep in memory
|
| 4 |
+
host: "0.0.0.0" # Server host
|
| 5 |
+
port: 8000 # Server port
|
| 6 |
+
|
| 7 |
+
metrics:
|
| 8 |
+
cpu: true
|
| 9 |
+
memory: true
|
| 10 |
+
network: true
|
| 11 |
+
disk: true
|
| 12 |
+
|
| 13 |
+
appearance:
|
| 14 |
+
theme: "dark"
|
| 15 |
+
primary_color: "#3498db"
|
| 16 |
+
chart_type: "line"
|
backend/main.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import yaml
|
| 2 |
+
import asyncio
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import List
|
| 6 |
+
from contextlib import asynccontextmanager
|
| 7 |
+
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
| 8 |
+
from fastapi.staticfiles import StaticFiles
|
| 9 |
+
from fastapi.responses import FileResponse
|
| 10 |
+
from .schemas import AppConfig, SystemMetrics
|
| 11 |
+
from .manager import SystemDataManager
|
| 12 |
+
|
| 13 |
+
# Global manager instance (will be properly initialized in lifespan)
|
| 14 |
+
manager: SystemDataManager = None
|
| 15 |
+
|
| 16 |
+
class ConnectionManager:
|
| 17 |
+
def __init__(self):
|
| 18 |
+
self.active_connections: List[WebSocket] = []
|
| 19 |
+
|
| 20 |
+
async def connect(self, websocket: WebSocket):
|
| 21 |
+
await websocket.accept()
|
| 22 |
+
self.active_connections.append(websocket)
|
| 23 |
+
|
| 24 |
+
def disconnect(self, websocket: WebSocket):
|
| 25 |
+
if websocket in self.active_connections:
|
| 26 |
+
self.active_connections.remove(websocket)
|
| 27 |
+
|
| 28 |
+
async def broadcast(self, metrics: SystemMetrics):
|
| 29 |
+
"""Broadcast metrics to all connected clients."""
|
| 30 |
+
if not self.active_connections:
|
| 31 |
+
return
|
| 32 |
+
|
| 33 |
+
message = metrics.model_dump_json()
|
| 34 |
+
# Create a copy to avoid modification during iteration
|
| 35 |
+
for connection in list(self.active_connections):
|
| 36 |
+
try:
|
| 37 |
+
await connection.send_text(message)
|
| 38 |
+
except Exception:
|
| 39 |
+
self.disconnect(connection)
|
| 40 |
+
|
| 41 |
+
connection_manager = ConnectionManager()
|
| 42 |
+
|
| 43 |
+
@asynccontextmanager
|
| 44 |
+
async def lifespan(app: FastAPI):
|
| 45 |
+
global manager
|
| 46 |
+
# Startup: load config and start background task
|
| 47 |
+
config = load_config()
|
| 48 |
+
manager = SystemDataManager(buffer_size=config.core.buffer_size)
|
| 49 |
+
# Register the broadcast callback
|
| 50 |
+
manager.broadcast_callback = connection_manager.broadcast
|
| 51 |
+
manager.start(interval=config.core.interval)
|
| 52 |
+
yield
|
| 53 |
+
# Shutdown: stop background task
|
| 54 |
+
if manager:
|
| 55 |
+
manager.stop()
|
| 56 |
+
|
| 57 |
+
app = FastAPI(title="Linux System Monitor API", lifespan=lifespan)
|
| 58 |
+
|
| 59 |
+
# Define frontend path
|
| 60 |
+
frontend_dir = Path(__file__).parent.parent / "frontend"
|
| 61 |
+
|
| 62 |
+
@app.get("/")
|
| 63 |
+
async def get_index():
|
| 64 |
+
return FileResponse(frontend_dir / "index.html")
|
| 65 |
+
|
| 66 |
+
def load_config() -> AppConfig:
|
| 67 |
+
config_path = Path(__file__).parent / "config.yaml"
|
| 68 |
+
with open(config_path, "r") as f:
|
| 69 |
+
config_data = yaml.safe_load(f)
|
| 70 |
+
return AppConfig(**config_data)
|
| 71 |
+
|
| 72 |
+
@app.get("/api/config", response_model=AppConfig)
|
| 73 |
+
async def get_config():
|
| 74 |
+
return load_config()
|
| 75 |
+
|
| 76 |
+
@app.websocket("/ws/metrics")
|
| 77 |
+
async def websocket_endpoint(websocket: WebSocket):
|
| 78 |
+
await connection_manager.connect(websocket)
|
| 79 |
+
try:
|
| 80 |
+
# Step 2: Push history on connection
|
| 81 |
+
history = manager.get_history()
|
| 82 |
+
history_data = [m.model_dump() for m in history]
|
| 83 |
+
await websocket.send_text(json.dumps(history_data))
|
| 84 |
+
|
| 85 |
+
# Keep the connection open and listen for messages (if any)
|
| 86 |
+
while True:
|
| 87 |
+
await websocket.receive_text()
|
| 88 |
+
except WebSocketDisconnect:
|
| 89 |
+
connection_manager.disconnect(websocket)
|
| 90 |
+
except Exception:
|
| 91 |
+
connection_manager.disconnect(websocket)
|
| 92 |
+
|
| 93 |
+
if __name__ == "__main__":
|
| 94 |
+
import uvicorn
|
| 95 |
+
config = load_config()
|
| 96 |
+
uvicorn.run(app, host=config.core.host, port=config.core.port)
|
backend/manager.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import collections
|
| 3 |
+
import time
|
| 4 |
+
from typing import List, Optional, Callable, Any
|
| 5 |
+
from .collector import SystemCollector
|
| 6 |
+
from .schemas import SystemMetrics
|
| 7 |
+
|
| 8 |
+
class SystemDataManager:
|
| 9 |
+
def __init__(self, buffer_size: int = 60):
|
| 10 |
+
self.collector = SystemCollector()
|
| 11 |
+
self.buffer = collections.deque(maxlen=buffer_size)
|
| 12 |
+
self.is_running = False
|
| 13 |
+
self._task: Optional[asyncio.Task] = None
|
| 14 |
+
self.broadcast_callback: Optional[Callable[[SystemMetrics], Any]] = None
|
| 15 |
+
|
| 16 |
+
def add_data_point(self, metrics: SystemMetrics):
|
| 17 |
+
"""Add a data point to the buffer."""
|
| 18 |
+
self.buffer.append(metrics)
|
| 19 |
+
if self.broadcast_callback:
|
| 20 |
+
if asyncio.iscoroutinefunction(self.broadcast_callback):
|
| 21 |
+
asyncio.create_task(self.broadcast_callback(metrics))
|
| 22 |
+
else:
|
| 23 |
+
self.broadcast_callback(metrics)
|
| 24 |
+
|
| 25 |
+
def get_history(self) -> List[SystemMetrics]:
|
| 26 |
+
"""Return all buffered data points as a list."""
|
| 27 |
+
return list(self.buffer)
|
| 28 |
+
|
| 29 |
+
def get_latest(self) -> Optional[SystemMetrics]:
|
| 30 |
+
"""Return the latest data point."""
|
| 31 |
+
if self.buffer:
|
| 32 |
+
return self.buffer[-1]
|
| 33 |
+
return None
|
| 34 |
+
|
| 35 |
+
async def collect_metrics_loop(self, interval: float = 1.0):
|
| 36 |
+
"""Background loop for collecting data."""
|
| 37 |
+
self.is_running = True
|
| 38 |
+
while self.is_running:
|
| 39 |
+
try:
|
| 40 |
+
# Perform the collection
|
| 41 |
+
metrics = self.collector.collect()
|
| 42 |
+
self.add_data_point(metrics)
|
| 43 |
+
except Exception as e:
|
| 44 |
+
# In a real app we'd log this
|
| 45 |
+
print(f"Error collecting data: {e}")
|
| 46 |
+
|
| 47 |
+
await asyncio.sleep(interval)
|
| 48 |
+
|
| 49 |
+
def start(self, interval: float = 1.0):
|
| 50 |
+
"""Start the background collection task."""
|
| 51 |
+
if self._task is None or self._task.done():
|
| 52 |
+
# We use asyncio.create_task to run it in the background
|
| 53 |
+
# Note: This requires an already running loop (like in FastAPI)
|
| 54 |
+
self._task = asyncio.create_task(self.collect_metrics_loop(interval))
|
| 55 |
+
|
| 56 |
+
def stop(self):
|
| 57 |
+
"""Stop the background collection task."""
|
| 58 |
+
self.is_running = False
|
| 59 |
+
if self._task:
|
| 60 |
+
self._task.cancel()
|
| 61 |
+
self._task = None
|
backend/schemas.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic import BaseModel
|
| 2 |
+
from typing import Dict, Any
|
| 3 |
+
|
| 4 |
+
class CPUInfo(BaseModel):
|
| 5 |
+
usage_percent: float
|
| 6 |
+
temp_celsius: float
|
| 7 |
+
|
| 8 |
+
class MemoryInfo(BaseModel):
|
| 9 |
+
total_gb: float
|
| 10 |
+
used_gb: float
|
| 11 |
+
percent: float
|
| 12 |
+
|
| 13 |
+
class NetworkInfo(BaseModel):
|
| 14 |
+
rx_kbps: float
|
| 15 |
+
tx_kbps: float
|
| 16 |
+
|
| 17 |
+
class DiskInfo(BaseModel):
|
| 18 |
+
read_kbps: float
|
| 19 |
+
write_kbps: float
|
| 20 |
+
|
| 21 |
+
class SystemMetrics(BaseModel):
|
| 22 |
+
cpu: CPUInfo
|
| 23 |
+
memory: MemoryInfo
|
| 24 |
+
network: NetworkInfo
|
| 25 |
+
disk: DiskInfo
|
| 26 |
+
timestamp: float
|
| 27 |
+
|
| 28 |
+
class CoreConfig(BaseModel):
|
| 29 |
+
interval: float
|
| 30 |
+
buffer_size: int
|
| 31 |
+
host: str
|
| 32 |
+
port: int
|
| 33 |
+
|
| 34 |
+
class MetricsConfig(BaseModel):
|
| 35 |
+
cpu: bool
|
| 36 |
+
memory: bool
|
| 37 |
+
network: bool
|
| 38 |
+
disk: bool
|
| 39 |
+
|
| 40 |
+
class AppearanceConfig(BaseModel):
|
| 41 |
+
theme: str
|
| 42 |
+
primary_color: str
|
| 43 |
+
chart_type: str
|
| 44 |
+
|
| 45 |
+
class AppConfig(BaseModel):
|
| 46 |
+
core: CoreConfig
|
| 47 |
+
metrics: MetricsConfig
|
| 48 |
+
appearance: AppearanceConfig
|
backend/tests/test_collector.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
from unittest.mock import patch, mock_open
|
| 3 |
+
import os
|
| 4 |
+
from backend.collector import SystemCollector
|
| 5 |
+
from backend.schemas import SystemMetrics
|
| 6 |
+
|
| 7 |
+
class TestSystemCollector(unittest.TestCase):
|
| 8 |
+
def setUp(self):
|
| 9 |
+
self.collector = SystemCollector()
|
| 10 |
+
|
| 11 |
+
@patch("builtins.open")
|
| 12 |
+
@patch("os.path.exists")
|
| 13 |
+
@patch("glob.glob")
|
| 14 |
+
@patch("time.time")
|
| 15 |
+
def test_collect_initial(self, mock_time, mock_glob, mock_exists, mock_file):
|
| 16 |
+
# Initial collection should return 0 for delta-based metrics
|
| 17 |
+
mock_time.return_value = 1000.0
|
| 18 |
+
mock_glob.return_value = ["/sys/class/thermal/thermal_zone0/temp"]
|
| 19 |
+
mock_exists.side_effect = lambda p: p == "/sys/block/sda"
|
| 20 |
+
|
| 21 |
+
# Mock file content
|
| 22 |
+
file_contents = {
|
| 23 |
+
"/proc/stat": "cpu 100 0 50 2000 10 0 0 0 0 0\n",
|
| 24 |
+
"/proc/meminfo": "MemTotal: 16000000 kB\nMemAvailable: 8000000 kB\n",
|
| 25 |
+
"/proc/net/dev": "header\nheader\n eth0: 1024 0 0 0 0 0 0 0 2048 0 0 0 0 0 0 0\n",
|
| 26 |
+
"/proc/diskstats": " 8 0 sda 0 0 2048 0 0 0 4096 0 0 0 0\n",
|
| 27 |
+
"/sys/class/thermal/thermal_zone0/temp": "50000\n"
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
def open_side_effect(path, mode="r"):
|
| 31 |
+
if path in file_contents:
|
| 32 |
+
return mock_open(read_data=file_contents[path])(path, mode)
|
| 33 |
+
raise FileNotFoundError(path)
|
| 34 |
+
|
| 35 |
+
mock_file.side_effect = open_side_effect
|
| 36 |
+
|
| 37 |
+
metrics = self.collector.collect()
|
| 38 |
+
|
| 39 |
+
self.assertIsInstance(metrics, SystemMetrics)
|
| 40 |
+
self.assertEqual(metrics.cpu.usage_percent, 0.0)
|
| 41 |
+
self.assertEqual(metrics.cpu.temp_celsius, 50.0)
|
| 42 |
+
self.assertEqual(metrics.memory.total_gb, round(16000000 / (1024*1024), 2))
|
| 43 |
+
self.assertEqual(metrics.memory.percent, 50.0)
|
| 44 |
+
self.assertEqual(metrics.network.rx_kbps, 0.0)
|
| 45 |
+
self.assertEqual(metrics.network.tx_kbps, 0.0)
|
| 46 |
+
self.assertEqual(metrics.disk.read_kbps, 0.0)
|
| 47 |
+
self.assertEqual(metrics.disk.write_kbps, 0.0)
|
| 48 |
+
|
| 49 |
+
@patch("builtins.open")
|
| 50 |
+
@patch("os.path.exists")
|
| 51 |
+
@patch("glob.glob")
|
| 52 |
+
@patch("time.time")
|
| 53 |
+
def test_collect_delta(self, mock_time, mock_glob, mock_exists, mock_file):
|
| 54 |
+
mock_glob.return_value = ["/sys/class/thermal/thermal_zone0/temp"]
|
| 55 |
+
mock_exists.side_effect = lambda p: p == "/sys/block/sda"
|
| 56 |
+
|
| 57 |
+
# Sample 1
|
| 58 |
+
mock_time.return_value = 1000.0
|
| 59 |
+
file_contents_1 = {
|
| 60 |
+
"/proc/stat": "cpu 100 0 50 2000 10 0 0 0 0 0\n",
|
| 61 |
+
"/proc/meminfo": "MemTotal: 16000000 kB\nMemAvailable: 8000000 kB\n",
|
| 62 |
+
"/proc/net/dev": "header\nheader\n eth0: 1024 0 0 0 0 0 0 0 2048 0 0 0 0 0 0 0\n",
|
| 63 |
+
"/proc/diskstats": " 8 0 sda 0 0 2048 0 0 0 4096 0 0 0 0\n",
|
| 64 |
+
"/sys/class/thermal/thermal_zone0/temp": "50000\n"
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
def open_side_effect_1(path, mode="r"):
|
| 68 |
+
return mock_open(read_data=file_contents_1.get(path, ""))(path, mode)
|
| 69 |
+
|
| 70 |
+
mock_file.side_effect = open_side_effect_1
|
| 71 |
+
self.collector.collect()
|
| 72 |
+
|
| 73 |
+
# Sample 2 (1 second later)
|
| 74 |
+
mock_time.return_value = 1001.0
|
| 75 |
+
# CPU: Delta Total = 175, Delta Idle = 105, Usage = 40%
|
| 76 |
+
# Net: Delta RX = 1024 bytes, Delta TX = 2048 bytes -> 1 kbps, 2 kbps
|
| 77 |
+
# Disk: Delta Read = 1024 * 512 bytes = 512 KB, Delta Write = 2048 * 512 bytes = 1024 KB -> 512 kbps, 1024 kbps
|
| 78 |
+
file_contents_2 = {
|
| 79 |
+
"/proc/stat": "cpu 150 0 70 2100 15 0 0 0 0 0\n",
|
| 80 |
+
"/proc/meminfo": "MemTotal: 16000000 kB\nMemAvailable: 8000000 kB\n",
|
| 81 |
+
"/proc/net/dev": "header\nheader\n eth0: 2048 0 0 0 0 0 0 0 4096 0 0 0 0 0 0 0\n",
|
| 82 |
+
"/proc/diskstats": " 8 0 sda 0 0 3072 0 0 0 6144 0 0 0 0\n",
|
| 83 |
+
"/sys/class/thermal/thermal_zone0/temp": "55000\n"
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
def open_side_effect_2(path, mode="r"):
|
| 87 |
+
return mock_open(read_data=file_contents_2.get(path, ""))(path, mode)
|
| 88 |
+
|
| 89 |
+
mock_file.side_effect = open_side_effect_2
|
| 90 |
+
metrics = self.collector.collect()
|
| 91 |
+
|
| 92 |
+
self.assertEqual(metrics.cpu.usage_percent, 40.0)
|
| 93 |
+
self.assertEqual(metrics.cpu.temp_celsius, 55.0)
|
| 94 |
+
self.assertEqual(metrics.network.rx_kbps, 1.0)
|
| 95 |
+
self.assertEqual(metrics.network.tx_kbps, 2.0)
|
| 96 |
+
self.assertEqual(metrics.disk.read_kbps, 512.0)
|
| 97 |
+
self.assertEqual(metrics.disk.write_kbps, 1024.0)
|
| 98 |
+
|
| 99 |
+
if __name__ == "__main__":
|
| 100 |
+
unittest.main()
|
backend/tests/test_manager.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
import asyncio
|
| 3 |
+
from backend.manager import SystemDataManager
|
| 4 |
+
from backend.schemas import SystemMetrics, CPUInfo, MemoryInfo, NetworkInfo, DiskInfo
|
| 5 |
+
|
| 6 |
+
def create_mock_metrics(timestamp: float) -> SystemMetrics:
|
| 7 |
+
return SystemMetrics(
|
| 8 |
+
cpu=CPUInfo(usage_percent=0.0, temp_celsius=0.0),
|
| 9 |
+
memory=MemoryInfo(total_gb=0.0, used_gb=0.0, percent=0.0),
|
| 10 |
+
network=NetworkInfo(rx_kbps=0.0, tx_kbps=0.0),
|
| 11 |
+
disk=DiskInfo(read_kbps=0.0, write_kbps=0.0),
|
| 12 |
+
timestamp=timestamp
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
def test_buffer_fill_and_eviction():
|
| 16 |
+
# Test with small maxlen for quick verification
|
| 17 |
+
manager = SystemDataManager(buffer_size=5)
|
| 18 |
+
|
| 19 |
+
# Fill buffer
|
| 20 |
+
for i in range(5):
|
| 21 |
+
manager.add_data_point(create_mock_metrics(float(i)))
|
| 22 |
+
|
| 23 |
+
history = manager.get_history()
|
| 24 |
+
assert len(history) == 5
|
| 25 |
+
assert history[0].timestamp == 0.0
|
| 26 |
+
assert history[4].timestamp == 4.0
|
| 27 |
+
|
| 28 |
+
# Add one more point, should evict the first one
|
| 29 |
+
manager.add_data_point(create_mock_metrics(5.0))
|
| 30 |
+
history = manager.get_history()
|
| 31 |
+
assert len(history) == 5
|
| 32 |
+
assert history[0].timestamp == 1.0
|
| 33 |
+
assert history[4].timestamp == 5.0
|
| 34 |
+
|
| 35 |
+
def test_background_task():
|
| 36 |
+
async def run_test():
|
| 37 |
+
# Test with very small interval
|
| 38 |
+
manager = SystemDataManager(buffer_size=10)
|
| 39 |
+
|
| 40 |
+
# Start loop manually (or use start() which uses asyncio.create_task)
|
| 41 |
+
# Since we want to control timing, we can run it for a bit
|
| 42 |
+
task = asyncio.create_task(manager.collect_metrics_loop(interval=0.1))
|
| 43 |
+
|
| 44 |
+
await asyncio.sleep(0.35) # Should collect about 3-4 points
|
| 45 |
+
|
| 46 |
+
manager.is_running = False # Stop the loop
|
| 47 |
+
try:
|
| 48 |
+
await asyncio.wait_for(task, timeout=1.0)
|
| 49 |
+
except asyncio.TimeoutError:
|
| 50 |
+
pass
|
| 51 |
+
|
| 52 |
+
history = manager.get_history()
|
| 53 |
+
assert len(history) >= 2 # At least 2 points collected
|
| 54 |
+
|
| 55 |
+
latest = manager.get_latest()
|
| 56 |
+
assert latest is not None
|
| 57 |
+
assert latest == history[-1]
|
| 58 |
+
|
| 59 |
+
asyncio.run(run_test())
|
backend/tests/test_websocket.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
import json
|
| 3 |
+
import asyncio
|
| 4 |
+
from fastapi.testclient import TestClient
|
| 5 |
+
import backend.main as main_module
|
| 6 |
+
from backend.schemas import SystemMetrics, CPUInfo, MemoryInfo, NetworkInfo, DiskInfo
|
| 7 |
+
|
| 8 |
+
pytestmark = pytest.mark.anyio
|
| 9 |
+
|
| 10 |
+
def create_mock_metrics(timestamp: float) -> SystemMetrics:
|
| 11 |
+
return SystemMetrics(
|
| 12 |
+
cpu=CPUInfo(usage_percent=0.0, temp_celsius=0.0),
|
| 13 |
+
memory=MemoryInfo(total_gb=0.0, used_gb=0.0, percent=0.0),
|
| 14 |
+
network=NetworkInfo(rx_kbps=0.0, tx_kbps=0.0),
|
| 15 |
+
disk=DiskInfo(read_kbps=0.0, write_kbps=0.0),
|
| 16 |
+
timestamp=timestamp
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
async def test_websocket_history_and_broadcast():
|
| 20 |
+
with TestClient(main_module.app) as client:
|
| 21 |
+
if main_module.manager:
|
| 22 |
+
main_module.manager.stop()
|
| 23 |
+
main_module.manager.buffer.clear()
|
| 24 |
+
|
| 25 |
+
# Add mock history data
|
| 26 |
+
main_module.manager.add_data_point(create_mock_metrics(1.0))
|
| 27 |
+
main_module.manager.add_data_point(create_mock_metrics(2.0))
|
| 28 |
+
|
| 29 |
+
with client.websocket_connect("/ws/metrics") as websocket:
|
| 30 |
+
# Receive initial history
|
| 31 |
+
data = websocket.receive_text()
|
| 32 |
+
history = json.loads(data)
|
| 33 |
+
assert isinstance(history, list)
|
| 34 |
+
assert len(history) >= 2
|
| 35 |
+
|
| 36 |
+
async def test_websocket_multiple_connections():
|
| 37 |
+
with TestClient(main_module.app) as client:
|
| 38 |
+
with client.websocket_connect("/ws/metrics") as ws1, \
|
| 39 |
+
client.websocket_connect("/ws/metrics") as ws2:
|
| 40 |
+
|
| 41 |
+
# Receive history on both
|
| 42 |
+
data1 = ws1.receive_text()
|
| 43 |
+
data2 = ws2.receive_text()
|
| 44 |
+
|
| 45 |
+
assert isinstance(json.loads(data1), list)
|
| 46 |
+
assert isinstance(json.loads(data2), list)
|
cli/monitor_cli.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import json
|
| 3 |
+
import sys
|
| 4 |
+
import argparse
|
| 5 |
+
import requests
|
| 6 |
+
import websockets
|
| 7 |
+
from rich.console import Console
|
| 8 |
+
from rich.table import Table
|
| 9 |
+
from rich.live import Live
|
| 10 |
+
from rich.panel import Panel
|
| 11 |
+
from rich.layout import Layout
|
| 12 |
+
from datetime import datetime
|
| 13 |
+
|
| 14 |
+
console = Console()
|
| 15 |
+
|
| 16 |
+
def get_color(value: float, warning: float = 70.0, danger: float = 90.0) -> str:
|
| 17 |
+
"""Return color based on value thresholds."""
|
| 18 |
+
if value >= danger:
|
| 19 |
+
return "bold red"
|
| 20 |
+
if value >= warning:
|
| 21 |
+
return "bold yellow"
|
| 22 |
+
return "green"
|
| 23 |
+
|
| 24 |
+
def create_dashboard(metrics: dict) -> Layout:
|
| 25 |
+
"""Create a rich layout for the dashboard."""
|
| 26 |
+
layout = Layout()
|
| 27 |
+
layout.split_column(
|
| 28 |
+
Layout(name="header", size=3),
|
| 29 |
+
Layout(name="main"),
|
| 30 |
+
Layout(name="footer", size=3)
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
# Header
|
| 34 |
+
time_str = datetime.fromtimestamp(metrics.get("timestamp", 0)).strftime("%Y-%m-%d %H:%M:%S")
|
| 35 |
+
layout["header"].update(Panel(f"[bold cyan]Linux System Monitor[/bold cyan] | Last Updated: {time_str}", style="blue"))
|
| 36 |
+
|
| 37 |
+
# Main content - Table
|
| 38 |
+
table = Table(expand=True)
|
| 39 |
+
table.add_column("Category", style="cyan", no_wrap=True)
|
| 40 |
+
table.add_column("Metric", style="magenta")
|
| 41 |
+
table.add_column("Value", justify="right")
|
| 42 |
+
|
| 43 |
+
# CPU
|
| 44 |
+
cpu = metrics.get("cpu", {})
|
| 45 |
+
usage = cpu.get("usage_percent", 0)
|
| 46 |
+
table.add_row("CPU", "Usage %", f"[{get_color(usage)}]{usage}%[/]")
|
| 47 |
+
table.add_row("CPU", "Temperature", f"{cpu.get('temp_celsius', 0)}°C")
|
| 48 |
+
|
| 49 |
+
# Memory
|
| 50 |
+
mem = metrics.get("memory", {})
|
| 51 |
+
m_usage = mem.get("percent", 0)
|
| 52 |
+
table.add_row("Memory", "Usage %", f"[{get_color(m_usage)}]{m_usage}%[/]")
|
| 53 |
+
table.add_row("Memory", "Used/Total (GB)", f"{mem.get('used_gb', 0)} / {mem.get('total_gb', 0)} GB")
|
| 54 |
+
|
| 55 |
+
# Network
|
| 56 |
+
net = metrics.get("network", {})
|
| 57 |
+
table.add_row("Network", "Download (rx)", f"[green]{net.get('rx_kbps', 0)} KB/s[/]")
|
| 58 |
+
table.add_row("Network", "Upload (tx)", f"[blue]{net.get('tx_kbps', 0)} KB/s[/]")
|
| 59 |
+
|
| 60 |
+
# Disk
|
| 61 |
+
disk = metrics.get("disk", {})
|
| 62 |
+
table.add_row("Disk", "Read Speed", f"{disk.get('read_kbps', 0)} KB/s")
|
| 63 |
+
table.add_row("Disk", "Write Speed", f"{disk.get('write_kbps', 0)} KB/s")
|
| 64 |
+
|
| 65 |
+
layout["main"].update(table)
|
| 66 |
+
layout["footer"].update(Panel("[dim]Press Ctrl+C to exit monitoring mode[/dim]", style="white"))
|
| 67 |
+
|
| 68 |
+
return layout
|
| 69 |
+
|
| 70 |
+
async def run_watch(api_url: str, ws_url: str):
|
| 71 |
+
"""Run in continuous watch mode."""
|
| 72 |
+
try:
|
| 73 |
+
async with websockets.connect(ws_url) as websocket:
|
| 74 |
+
# First message might be a list (history)
|
| 75 |
+
initial_data = await websocket.recv()
|
| 76 |
+
data = json.loads(initial_data)
|
| 77 |
+
|
| 78 |
+
# Use the latest data point from history or initial point
|
| 79 |
+
latest_metrics = data[-1] if isinstance(data, list) else data
|
| 80 |
+
|
| 81 |
+
with Live(create_dashboard(latest_metrics), refresh_per_second=4, screen=True) as live:
|
| 82 |
+
while True:
|
| 83 |
+
msg = await websocket.recv()
|
| 84 |
+
latest_metrics = json.loads(msg)
|
| 85 |
+
live.update(create_dashboard(latest_metrics))
|
| 86 |
+
except Exception as e:
|
| 87 |
+
console.print(f"[bold red]Error in WebSocket connection:[/bold red] {e}")
|
| 88 |
+
|
| 89 |
+
def run_once(api_url: str, ws_url: str):
|
| 90 |
+
"""Fetch data once and exit."""
|
| 91 |
+
try:
|
| 92 |
+
# We still use WebSocket to get the latest data point
|
| 93 |
+
async def fetch():
|
| 94 |
+
async with websockets.connect(ws_url) as websocket:
|
| 95 |
+
initial_data = await websocket.recv()
|
| 96 |
+
data = json.loads(initial_data)
|
| 97 |
+
latest_metrics = data[-1] if isinstance(data, list) else data
|
| 98 |
+
console.print(create_dashboard(latest_metrics))
|
| 99 |
+
|
| 100 |
+
asyncio.run(fetch())
|
| 101 |
+
except Exception as e:
|
| 102 |
+
console.print(f"[bold red]Error fetching data:[/bold red] {e}")
|
| 103 |
+
|
| 104 |
+
def main():
|
| 105 |
+
parser = argparse.ArgumentParser(description="Linux System Monitor CLI Client")
|
| 106 |
+
parser.add_argument("--host", default="localhost", help="Server host")
|
| 107 |
+
parser.add_argument("--port", default="8000", help="Server port")
|
| 108 |
+
parser.add_argument("--watch", action="store_true", help="Enable continuous monitoring mode")
|
| 109 |
+
|
| 110 |
+
args = parser.parse_args()
|
| 111 |
+
|
| 112 |
+
api_url = f"http://{args.host}:{args.port}/api/config"
|
| 113 |
+
ws_url = f"ws://{args.host}:{args.port}/ws/metrics"
|
| 114 |
+
|
| 115 |
+
# Verify server is up
|
| 116 |
+
try:
|
| 117 |
+
resp = requests.get(api_url, timeout=2)
|
| 118 |
+
resp.raise_for_status()
|
| 119 |
+
config = resp.json()
|
| 120 |
+
console.print(f"[green]Connected to Monitor API ({config['appearance']['theme']} theme)[/green]")
|
| 121 |
+
except Exception as e:
|
| 122 |
+
console.print(f"[bold red]Could not connect to server at {api_url}:[/bold red] {e}")
|
| 123 |
+
sys.exit(1)
|
| 124 |
+
|
| 125 |
+
if args.watch:
|
| 126 |
+
try:
|
| 127 |
+
asyncio.run(run_watch(api_url, ws_url))
|
| 128 |
+
except KeyboardInterrupt:
|
| 129 |
+
console.print("\n[yellow]Monitoring stopped by user.[/yellow]")
|
| 130 |
+
else:
|
| 131 |
+
run_once(api_url, ws_url)
|
| 132 |
+
|
| 133 |
+
if __name__ == "__main__":
|
| 134 |
+
main()
|
docker-compose.yml
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
monitor-app:
|
| 3 |
+
build: .
|
| 4 |
+
ports:
|
| 5 |
+
- "8000:8000"
|
| 6 |
+
volumes:
|
| 7 |
+
- /proc:/proc:ro
|
| 8 |
+
- /sys:/sys:ro
|
| 9 |
+
privileged: true # 讀取底層 /proc 檔案有時需要較高權限
|
| 10 |
+
restart: always
|
| 11 |
+
environment:
|
| 12 |
+
- PYTHONUNBUFFERED=1
|
docs/superpowers/plans/2025-05-22-scaffolding-and-config.md
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Task 1: Scaffolding & Config Implementation Plan
|
| 2 |
+
|
| 3 |
+
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
| 4 |
+
|
| 5 |
+
**Goal:** Create the basic configuration, data models, and FastAPI skeleton for the Linux System Monitor Dashboard.
|
| 6 |
+
|
| 7 |
+
**Architecture:**
|
| 8 |
+
- `config.yaml`: Centralized configuration using YAML.
|
| 9 |
+
- `schemas.py`: Pydantic models for data validation and API documentation.
|
| 10 |
+
- `main.py`: FastAPI application entry point with a `/api/config` endpoint.
|
| 11 |
+
|
| 12 |
+
**Tech Stack:** FastAPI, Pydantic, PyYAML, Uvicorn.
|
| 13 |
+
|
| 14 |
+
---
|
| 15 |
+
|
| 16 |
+
### Task 1.1: Create `backend/config.yaml`
|
| 17 |
+
|
| 18 |
+
**Files:**
|
| 19 |
+
- Create: `backend/config.yaml`
|
| 20 |
+
|
| 21 |
+
- [ ] **Step 1: Write `backend/config.yaml`**
|
| 22 |
+
|
| 23 |
+
```yaml
|
| 24 |
+
core:
|
| 25 |
+
interval: 1.0 # Data collection interval in seconds
|
| 26 |
+
buffer_size: 100 # Number of data points to keep in memory
|
| 27 |
+
host: "0.0.0.0" # Server host
|
| 28 |
+
port: 8000 # Server port
|
| 29 |
+
|
| 30 |
+
metrics:
|
| 31 |
+
cpu: true
|
| 32 |
+
memory: true
|
| 33 |
+
network: true
|
| 34 |
+
disk: true
|
| 35 |
+
|
| 36 |
+
appearance:
|
| 37 |
+
theme: "dark"
|
| 38 |
+
primary_color: "#3498db"
|
| 39 |
+
chart_type: "line"
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
- [ ] **Step 2: Commit**
|
| 43 |
+
|
| 44 |
+
```bash
|
| 45 |
+
git add backend/config.yaml
|
| 46 |
+
git commit -m "feat: add config.yaml"
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
---
|
| 50 |
+
|
| 51 |
+
### Task 1.2: Create `backend/schemas.py`
|
| 52 |
+
|
| 53 |
+
**Files:**
|
| 54 |
+
- Create: `backend/schemas.py`
|
| 55 |
+
|
| 56 |
+
- [ ] **Step 1: Write `backend/schemas.py`**
|
| 57 |
+
|
| 58 |
+
```python
|
| 59 |
+
from pydantic import BaseModel
|
| 60 |
+
from typing import Dict, Any
|
| 61 |
+
|
| 62 |
+
class CPUInfo(BaseModel):
|
| 63 |
+
usage_percent: float
|
| 64 |
+
temp_celsius: float
|
| 65 |
+
|
| 66 |
+
class MemoryInfo(BaseModel):
|
| 67 |
+
total_gb: float
|
| 68 |
+
used_gb: float
|
| 69 |
+
percent: float
|
| 70 |
+
|
| 71 |
+
class NetworkInfo(BaseModel):
|
| 72 |
+
rx_kbps: float
|
| 73 |
+
tx_kbps: float
|
| 74 |
+
|
| 75 |
+
class DiskInfo(BaseModel):
|
| 76 |
+
read_kbps: float
|
| 77 |
+
write_kbps: float
|
| 78 |
+
|
| 79 |
+
class SystemMetrics(BaseModel):
|
| 80 |
+
cpu: CPUInfo
|
| 81 |
+
memory: MemoryInfo
|
| 82 |
+
network: NetworkInfo
|
| 83 |
+
disk: DiskInfo
|
| 84 |
+
timestamp: float
|
| 85 |
+
|
| 86 |
+
class CoreConfig(BaseModel):
|
| 87 |
+
interval: float
|
| 88 |
+
buffer_size: int
|
| 89 |
+
host: str
|
| 90 |
+
port: int
|
| 91 |
+
|
| 92 |
+
class MetricsConfig(BaseModel):
|
| 93 |
+
cpu: bool
|
| 94 |
+
memory: bool
|
| 95 |
+
network: bool
|
| 96 |
+
disk: bool
|
| 97 |
+
|
| 98 |
+
class AppearanceConfig(BaseModel):
|
| 99 |
+
theme: str
|
| 100 |
+
primary_color: str
|
| 101 |
+
chart_type: str
|
| 102 |
+
|
| 103 |
+
class AppConfig(BaseModel):
|
| 104 |
+
core: CoreConfig
|
| 105 |
+
metrics: MetricsConfig
|
| 106 |
+
appearance: AppearanceConfig
|
| 107 |
+
```
|
| 108 |
+
|
| 109 |
+
- [ ] **Step 2: Commit**
|
| 110 |
+
|
| 111 |
+
```bash
|
| 112 |
+
git add backend/schemas.py
|
| 113 |
+
git commit -m "feat: add pydantic schemas"
|
| 114 |
+
```
|
| 115 |
+
|
| 116 |
+
---
|
| 117 |
+
|
| 118 |
+
### Task 1.3: Create `backend/main.py`
|
| 119 |
+
|
| 120 |
+
**Files:**
|
| 121 |
+
- Create: `backend/main.py`
|
| 122 |
+
|
| 123 |
+
- [ ] **Step 1: Write `backend/main.py`**
|
| 124 |
+
|
| 125 |
+
```python
|
| 126 |
+
import yaml
|
| 127 |
+
from pathlib import Path
|
| 128 |
+
from fastapi import FastAPI
|
| 129 |
+
from .schemas import AppConfig
|
| 130 |
+
|
| 131 |
+
app = FastAPI(title="Linux System Monitor API")
|
| 132 |
+
|
| 133 |
+
def load_config() -> AppConfig:
|
| 134 |
+
config_path = Path(__file__).parent / "config.yaml"
|
| 135 |
+
with open(config_path, "r") as f:
|
| 136 |
+
config_data = yaml.safe_load(f)
|
| 137 |
+
return AppConfig(**config_data)
|
| 138 |
+
|
| 139 |
+
@app.get("/api/config", response_model=AppConfig)
|
| 140 |
+
async def get_config():
|
| 141 |
+
return load_config()
|
| 142 |
+
|
| 143 |
+
if __name__ == "__main__":
|
| 144 |
+
import uvicorn
|
| 145 |
+
config = load_config()
|
| 146 |
+
uvicorn.run(app, host=config.core.host, port=config.core.port)
|
| 147 |
+
```
|
| 148 |
+
|
| 149 |
+
- [ ] **Step 2: Commit**
|
| 150 |
+
|
| 151 |
+
```bash
|
| 152 |
+
git add backend/main.py
|
| 153 |
+
git commit -m "feat: add fastapi skeleton and config endpoint"
|
| 154 |
+
```
|
| 155 |
+
|
| 156 |
+
---
|
| 157 |
+
|
| 158 |
+
### Task 1.4: Verification
|
| 159 |
+
|
| 160 |
+
**Files:**
|
| 161 |
+
- None
|
| 162 |
+
|
| 163 |
+
- [ ] **Step 1: Install dependencies**
|
| 164 |
+
|
| 165 |
+
Run: `pip install fastapi uvicorn PyYAML pydantic`
|
| 166 |
+
Expected: Installation completes successfully.
|
| 167 |
+
|
| 168 |
+
- [ ] **Step 2: Start the server**
|
| 169 |
+
|
| 170 |
+
Run: `uvicorn backend.main:app --host 0.0.0.0 --port 8000`
|
| 171 |
+
Expected: Server starts and listens on port 8000.
|
| 172 |
+
|
| 173 |
+
- [ ] **Step 3: Test the `/api/config` endpoint**
|
| 174 |
+
|
| 175 |
+
Run: `curl http://localhost:8000/api/config`
|
| 176 |
+
Expected: JSON response matching `config.yaml`.
|
| 177 |
+
|
| 178 |
+
- [ ] **Step 4: Commit**
|
| 179 |
+
|
| 180 |
+
```bash
|
| 181 |
+
git commit -m "chore: verify Task 1 implementation"
|
| 182 |
+
```
|
frontend/index.html
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="zh-TW">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 6 |
+
<title>Linux System Monitor Dashboard</title>
|
| 7 |
+
<!-- Vue 3 & ECharts via CDN -->
|
| 8 |
+
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
|
| 9 |
+
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
|
| 10 |
+
<style>
|
| 11 |
+
:root {
|
| 12 |
+
--bg-color: #f4f7f6;
|
| 13 |
+
--card-bg: #ffffff;
|
| 14 |
+
--text-color: #333333;
|
| 15 |
+
--primary-color: #3498db;
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
body.dark-theme {
|
| 19 |
+
--bg-color: #1a1a1a;
|
| 20 |
+
--card-bg: #2d2d2d;
|
| 21 |
+
--text-color: #e0e0e0;
|
| 22 |
+
--primary-color: #3498db;
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
body {
|
| 26 |
+
background-color: var(--bg-color);
|
| 27 |
+
color: var(--text-color);
|
| 28 |
+
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
| 29 |
+
margin: 0;
|
| 30 |
+
padding: 20px;
|
| 31 |
+
transition: all 0.3s ease;
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
.header {
|
| 35 |
+
display: flex;
|
| 36 |
+
justify-content: space-between;
|
| 37 |
+
align-items: center;
|
| 38 |
+
margin-bottom: 20px;
|
| 39 |
+
border-bottom: 2px solid var(--primary-color);
|
| 40 |
+
padding-bottom: 10px;
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
.status-badge {
|
| 44 |
+
padding: 5px 10px;
|
| 45 |
+
border-radius: 15px;
|
| 46 |
+
font-size: 0.8em;
|
| 47 |
+
font-weight: bold;
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
.status-connected { background: #2ecc71; color: white; }
|
| 51 |
+
.status-disconnected { background: #e74c3c; color: white; }
|
| 52 |
+
|
| 53 |
+
.dashboard {
|
| 54 |
+
display: grid;
|
| 55 |
+
grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
|
| 56 |
+
gap: 20px;
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
.card {
|
| 60 |
+
background-color: var(--card-bg);
|
| 61 |
+
border-radius: 8px;
|
| 62 |
+
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
|
| 63 |
+
padding: 15px;
|
| 64 |
+
min-height: 350px;
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
.card-title {
|
| 68 |
+
font-size: 1.2em;
|
| 69 |
+
font-weight: bold;
|
| 70 |
+
margin-bottom: 15px;
|
| 71 |
+
color: var(--primary-color);
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
.chart-container {
|
| 75 |
+
width: 100%;
|
| 76 |
+
height: 300px;
|
| 77 |
+
}
|
| 78 |
+
</style>
|
| 79 |
+
</head>
|
| 80 |
+
<body :class="{'dark-theme': config.appearance?.theme === 'dark'}">
|
| 81 |
+
<div id="app">
|
| 82 |
+
<div class="header">
|
| 83 |
+
<h1>Linux System Monitor <small style="font-size: 0.5em; opacity: 0.7;">v1.0</small></h1>
|
| 84 |
+
<div>
|
| 85 |
+
<span :class="['status-badge', isConnected ? 'status-connected' : 'status-disconnected']">
|
| 86 |
+
{{ isConnected ? 'CONNECTED' : 'DISCONNECTED' }}
|
| 87 |
+
</span>
|
| 88 |
+
</div>
|
| 89 |
+
</div>
|
| 90 |
+
|
| 91 |
+
<div class="dashboard">
|
| 92 |
+
<!-- CPU Chart -->
|
| 93 |
+
<div class="card">
|
| 94 |
+
<div class="card-title">CPU Usage (%) & Temp (°C)</div>
|
| 95 |
+
<div id="cpu-chart" class="chart-container"></div>
|
| 96 |
+
</div>
|
| 97 |
+
|
| 98 |
+
<!-- Memory Chart -->
|
| 99 |
+
<div class="card">
|
| 100 |
+
<div class="card-title">Memory Usage (%)</div>
|
| 101 |
+
<div id="mem-chart" class="chart-container"></div>
|
| 102 |
+
</div>
|
| 103 |
+
|
| 104 |
+
<!-- Network Chart -->
|
| 105 |
+
<div class="card">
|
| 106 |
+
<div class="card-title">Network Traffic (KB/s)</div>
|
| 107 |
+
<div id="net-chart" class="chart-container"></div>
|
| 108 |
+
</div>
|
| 109 |
+
|
| 110 |
+
<!-- Disk Chart -->
|
| 111 |
+
<div class="card">
|
| 112 |
+
<div class="card-title">Disk I/O (KB/s)</div>
|
| 113 |
+
<div id="disk-chart" class="chart-container"></div>
|
| 114 |
+
</div>
|
| 115 |
+
</div>
|
| 116 |
+
</div>
|
| 117 |
+
|
| 118 |
+
<script>
|
| 119 |
+
const { createApp, ref, onMounted, onUnmounted } = Vue;
|
| 120 |
+
|
| 121 |
+
createApp({
|
| 122 |
+
setup() {
|
| 123 |
+
const isConnected = ref(false);
|
| 124 |
+
const config = ref({});
|
| 125 |
+
let ws = null;
|
| 126 |
+
const charts = {};
|
| 127 |
+
|
| 128 |
+
const initChart = (id, title, color) => {
|
| 129 |
+
const chart = echarts.init(document.getElementById(id), config.value.appearance?.theme === 'dark' ? 'dark' : null);
|
| 130 |
+
chart.setOption({
|
| 131 |
+
tooltip: { trigger: 'axis' },
|
| 132 |
+
grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
|
| 133 |
+
xAxis: { type: 'time', splitLine: { show: false } },
|
| 134 |
+
yAxis: { type: 'value', boundaryGap: [0, '100%'] },
|
| 135 |
+
series: [{
|
| 136 |
+
name: title,
|
| 137 |
+
type: 'line',
|
| 138 |
+
smooth: true,
|
| 139 |
+
showSymbol: false,
|
| 140 |
+
data: [],
|
| 141 |
+
itemStyle: { color: color },
|
| 142 |
+
areaStyle: {
|
| 143 |
+
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
|
| 144 |
+
{ offset: 0, color: color },
|
| 145 |
+
{ offset: 1, color: 'rgba(255, 255, 255, 0)' }
|
| 146 |
+
])
|
| 147 |
+
}
|
| 148 |
+
}]
|
| 149 |
+
});
|
| 150 |
+
return chart;
|
| 151 |
+
};
|
| 152 |
+
|
| 153 |
+
const updateCharts = (metrics) => {
|
| 154 |
+
const time = metrics.timestamp * 1000;
|
| 155 |
+
|
| 156 |
+
// CPU
|
| 157 |
+
charts.cpu.setOption({
|
| 158 |
+
series: [{ data: [...charts.cpu.getOption().series[0].data, [time, metrics.cpu.usage_percent]].slice(-60) }]
|
| 159 |
+
});
|
| 160 |
+
|
| 161 |
+
// Memory
|
| 162 |
+
charts.mem.setOption({
|
| 163 |
+
series: [{ data: [...charts.mem.getOption().series[0].data, [time, metrics.memory.percent]].slice(-60) }]
|
| 164 |
+
});
|
| 165 |
+
|
| 166 |
+
// Network (Combined RX/TX for simplicity, or we could add another series)
|
| 167 |
+
charts.net.setOption({
|
| 168 |
+
series: [{ data: [...charts.net.getOption().series[0].data, [time, metrics.network.rx_kbps]].slice(-60) }]
|
| 169 |
+
});
|
| 170 |
+
|
| 171 |
+
// Disk
|
| 172 |
+
charts.disk.setOption({
|
| 173 |
+
series: [{ data: [...charts.disk.getOption().series[0].data, [time, metrics.disk.read_kbps]].slice(-60) }]
|
| 174 |
+
});
|
| 175 |
+
};
|
| 176 |
+
|
| 177 |
+
const handleHistory = (history) => {
|
| 178 |
+
history.forEach(metrics => {
|
| 179 |
+
const time = metrics.timestamp * 1000;
|
| 180 |
+
charts.cpu.getOption().series[0].data.push([time, metrics.cpu.usage_percent]);
|
| 181 |
+
charts.mem.getOption().series[0].data.push([time, metrics.memory.percent]);
|
| 182 |
+
charts.net.getOption().series[0].data.push([time, metrics.network.rx_kbps]);
|
| 183 |
+
charts.disk.getOption().series[0].data.push([time, metrics.disk.read_kbps]);
|
| 184 |
+
});
|
| 185 |
+
};
|
| 186 |
+
|
| 187 |
+
onMounted(async () => {
|
| 188 |
+
// 1. Fetch Config
|
| 189 |
+
try {
|
| 190 |
+
const res = await fetch('/api/config');
|
| 191 |
+
config.value = await res.json();
|
| 192 |
+
} catch (e) { console.error("Config fetch failed", e); }
|
| 193 |
+
|
| 194 |
+
// 2. Init Charts
|
| 195 |
+
charts.cpu = initChart('cpu-chart', 'CPU Usage', '#3498db');
|
| 196 |
+
charts.mem = initChart('mem-chart', 'Memory Usage', '#9b59b6');
|
| 197 |
+
charts.net = initChart('net-chart', 'Network RX', '#2ecc71');
|
| 198 |
+
charts.disk = initChart('disk-chart', 'Disk Read', '#e67e22');
|
| 199 |
+
|
| 200 |
+
// 3. Connect WebSocket
|
| 201 |
+
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
| 202 |
+
ws = new WebSocket(`${protocol}//${window.location.host}/ws/metrics`);
|
| 203 |
+
|
| 204 |
+
ws.onopen = () => { isConnected.ref = true; isConnected.value = true; };
|
| 205 |
+
ws.onclose = () => { isConnected.value = false; };
|
| 206 |
+
|
| 207 |
+
ws.onmessage = (event) => {
|
| 208 |
+
const data = JSON.parse(event.data);
|
| 209 |
+
if (Array.isArray(data)) {
|
| 210 |
+
handleHistory(data);
|
| 211 |
+
} else {
|
| 212 |
+
updateCharts(data);
|
| 213 |
+
}
|
| 214 |
+
};
|
| 215 |
+
});
|
| 216 |
+
|
| 217 |
+
return { isConnected, config };
|
| 218 |
+
}
|
| 219 |
+
}).mount('#app');
|
| 220 |
+
</script>
|
| 221 |
+
</body>
|
| 222 |
+
</html>
|
requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi
|
| 2 |
+
uvicorn
|
| 3 |
+
pyyaml
|
| 4 |
+
pydantic
|
| 5 |
+
psutil
|
| 6 |
+
pytest
|
| 7 |
+
websockets
|
| 8 |
+
requests
|
| 9 |
+
rich
|