ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
Add a storage overview endpoint
Juan Denisd669b7cac501
diff --git a/backend/app/api/system.py b/backend/app/api/system.pyindex 196e096e..24a90e0d 100644--- a/backend/app/api/system.py+++ b/backend/app/api/system.py@@ -190,6 +190,19 @@ def get_disk_metrics():return jsonify(SystemService.get_disk_metrics()), 200+@system_bp.route('/storage', methods=['GET'])+@admin_required+def get_storage_overview():+ """Where the panel host's disk goes, plus the retention settings that+ bound ServerKit's own share. Reads only."""+ from app.services import storage_overview_service++ try:+ return jsonify(storage_overview_service.overview()), 200+ except Exception as exc: # noqa: BLE001 - reported, not swallowed+ return unexpected_response(exc)++@system_bp.route('/disk/reclaim/report', methods=['GET'])@admin_requireddef get_disk_reclaim_report():diff --git a/backend/app/services/storage_overview_service.py b/backend/app/services/storage_overview_service.pynew file mode 100644index 00000000..57c85fe9--- /dev/null+++ b/backend/app/services/storage_overview_service.py@@ -0,0 +1,129 @@+"""Where the panel host's disk goes (plan 85 §D1).++Read-only: measures, never deletes. Cleanup stays in+``disk_reclaim_service`` (its safe candidates are what the Storage page+offers next to each number).+"""+import json+import os+import re+import shutil+import time++from app.services import storage_profile_service++RETENTION_KEYS = (+ 'telemetry.retention_days',+ 'jobs.retention_days',+ 'history.retention_days',+ 'audit_log_retention_days',+ 'storage.previous_slot_hours',+ 'storage.docker_log_max_size',+)++_DOCKER_SIZE = re.compile(r'^\s*([\d.]+)\s*([kKMGTP]?B)\s*$')+_UNITS = {'B': 1, 'kB': 1000, 'KB': 1000, 'MB': 1000 ** 2, 'GB': 1000 ** 3,+ 'TB': 1000 ** 4, 'PB': 1000 ** 5}+++def parse_docker_size(text):+ """``docker system df`` prints decimal sizes ("9.308GB", "81.92kB",+ sometimes with a "(37%)" suffix on reclaimable). Unparseable → None."""+ if not text:+ return None+ match = _DOCKER_SIZE.match(str(text).split('(')[0])+ if not match:+ return None+ return int(float(match.group(1)) * _UNITS.get(match.group(2), 1))+++def docker_usage():+ """``{type: {'bytes', 'reclaimable'}}`` from ``docker system df``, or {}+ when Docker is absent or not answering."""+ from app.services.disk_reclaim_service import _run+ ok, out, _err = _run(['docker', 'system', 'df', '--format', '{{json .}}'], timeout=60)+ if not ok:+ return {}+ usage = {}+ for line in (out or '').splitlines():+ try:+ row = json.loads(line)+ except ValueError:+ continue+ kind = {'Images': 'images', 'Containers': 'containers',+ 'Local Volumes': 'volumes', 'Build Cache': 'build_cache'}.get(row.get('Type'))+ if kind:+ usage[kind] = {'bytes': parse_docker_size(row.get('Size')),+ 'reclaimable': parse_docker_size(row.get('Reclaimable'))}+ return usage+++def _database_bytes():+ from app import db+ try:+ path = db.engine.url.database+ except Exception:+ return None+ if db.engine.dialect.name != 'sqlite' or not path or not os.path.exists(path):+ return None+ return sum(os.path.getsize(p) for p in (path, path + '-wal', path + '-shm')+ if os.path.exists(p))+++def overview():+ from app import paths+ from app.services.disk_reclaim_service import _path_size+ from app.services.settings_service import SettingsService+ from app.services import slot_retention_service++ probe = paths.SERVERKIT_DIR if os.path.isdir(paths.SERVERKIT_DIR) else os.path.abspath(os.sep)+ try:+ du = shutil.disk_usage(probe)+ disk = {'path': probe, 'total': du.total, 'used': du.used, 'free': du.free,+ 'percent': round(du.used / du.total * 100, 1) if du.total else None}+ except OSError:+ disk = {'path': probe, 'total': None, 'used': None, 'free': None, 'percent': None}++ docker = docker_usage()+ items = []++ def add(key, label, size, reclaimable=None):+ if size is not None:+ items.append({'key': key, 'label': label, 'bytes': size,+ 'reclaimable': reclaimable})++ add('docker_images', 'App images', (docker.get('images') or {}).get('bytes'),+ (docker.get('images') or {}).get('reclaimable'))+ add('docker_volumes', 'App volumes', (docker.get('volumes') or {}).get('bytes'),+ (docker.get('volumes') or {}).get('reclaimable'))+ add('docker_build_cache', 'Docker build cache',+ (docker.get('build_cache') or {}).get('bytes'),+ (docker.get('build_cache') or {}).get('reclaimable'))+ add('panel_database', 'Panel database', _database_bytes())+ for key, label, path in (('backups', 'Backups and upgrade snapshots', paths.SERVERKIT_BACKUP_DIR),+ ('panel_logs', 'Panel logs', paths.SERVERKIT_LOG_DIR)):+ if os.path.isdir(path):+ add(key, label, _path_size(path))++ previous = None+ slot = slot_retention_service.previous_slot()+ if slot:+ hours = SettingsService.get('storage.previous_slot_hours', 24)+ try:+ switched = os.lstat(slot_retention_service.INSTALL_DIR).st_mtime+ removable_at = switched + int(hours) * 3600 if int(hours) > 0 else None+ except (OSError, TypeError, ValueError):+ removable_at = None+ previous = {'path': slot, 'bytes': _path_size(slot),+ 'removable_at': removable_at,+ 'removable_now': bool(removable_at and removable_at <= time.time())}+ add('previous_install', 'Previous version (rollback)', previous['bytes'])++ items.sort(key=lambda item: item['bytes'] or 0, reverse=True)+ return {+ 'disk': disk,+ 'profile': storage_profile_service.profile_name(disk['total']),+ 'items': items,+ 'previous_install': previous,+ 'retention': {key: SettingsService.get(key) for key in RETENTION_KEYS},+ }diff --git a/backend/tests/test_storage_overview.py b/backend/tests/test_storage_overview.pynew file mode 100644index 00000000..4c2ee98e--- /dev/null+++ b/backend/tests/test_storage_overview.py@@ -0,0 +1,46 @@+"""Plan 85 §D1: the Storage page's read-only overview."""+import json++import pytest++from app.services import storage_overview_service as svc++[email protected]('text,expected', [+ ('9.308GB', 9_308_000_000), ('81.92kB', 81_920), ('0B', 0),+ ('433.6MB (37%)', 433_600_000), ('', None), ('n/a', None),+])+def test_docker_sizes_parse(text, expected):+ assert svc.parse_docker_size(text) == expected+++def test_docker_usage_reads_system_df(monkeypatch):+ from app.services import disk_reclaim_service+ lines = '\n'.join(json.dumps(row) for row in (+ {'Type': 'Images', 'Size': '9.308GB', 'Reclaimable': '1.2GB (12%)'},+ {'Type': 'Local Volumes', 'Size': '1.167GB', 'Reclaimable': '433.6MB (37%)'},+ {'Type': 'Build Cache', 'Size': '1.204GB', 'Reclaimable': '1.204GB'},+ ))+ monkeypatch.setattr(disk_reclaim_service, '_run', lambda *a, **k: (True, lines, ''))+ usage = svc.docker_usage()+ assert usage['images'] == {'bytes': 9_308_000_000, 'reclaimable': 1_200_000_000}+ assert usage['build_cache']['bytes'] == 1_204_000_000+++def test_no_docker_is_an_empty_breakdown_not_an_error(monkeypatch):+ from app.services import disk_reclaim_service+ monkeypatch.setattr(disk_reclaim_service, '_run', lambda *a, **k: (False, '', 'not found'))+ assert svc.docker_usage() == {}+++def test_overview_endpoint_is_admin_only_and_reports_retention(client, auth_headers, monkeypatch):+ from app.services import disk_reclaim_service+ monkeypatch.setattr(disk_reclaim_service, '_run', lambda *a, **k: (False, '', ''))++ assert client.get('/api/v1/system/storage').status_code == 401+ resp = client.get('/api/v1/system/storage', headers=auth_headers)+ assert resp.status_code == 200+ body = resp.get_json()+ assert body['profile'] in ('small', 'standard')+ assert set(svc.RETENTION_KEYS) <= set(body['retention'])+ assert body['disk']['total'] and isinstance(body['items'], list)