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
feat(templates): tell people whether a template actually fits the server
Juan Denisda2b77f3d2cf
diff --git a/backend/app/api/templates.py b/backend/app/api/templates.pyindex 87f0139b..271baf41 100644--- a/backend/app/api/templates.py+++ b/backend/app/api/templates.py@@ -10,7 +10,7 @@ Provides REST endpoints for:- Template repository management"""-from flask import Blueprint, request, jsonify+from flask import Blueprint, current_app, request, jsonifyfrom flask_jwt_extended import jwt_required, get_jwt_identityfrom app.middleware.rbac import admin_requiredfrom app.models import User, Application@@ -258,6 +258,24 @@ def install_template(template_id):return jsonify({'error': str(e), 'trace': error_trace}), 500+@templates_bp.route('/<template_id>/capacity', methods=['GET'])+@jwt_required()+def template_capacity(template_id):+ """Will this template fit on a given server?++ Read-only counterpart to the capacity block on /validate-install, so the+ deploy drawer can show the answer while the operator is still choosing a+ target — and update it when they switch servers — without POSTing a+ half-filled form. `server_id` omitted (or 'local') means this host.+ """+ result = TemplateService.get_template(template_id)+ if not result.get('success'):+ return jsonify({'error': 'Template not found'}), 404++ from app.services.capacity_service import check_fit+ return jsonify(check_fit(result['template'], request.args.get('server_id'))), 200++@templates_bp.route('/validate-install', methods=['POST'])@jwt_required()def validate_installation():@@ -271,8 +289,10 @@ def validate_installation():template_id = data.get('template_id')app_name = data.get('app_name')user_variables = data.get('variables', {})+ server_id = data.get('server_id') or data.get('target_server_id')errors = []+ capacity = None# Validate app nameif not app_name:@@ -308,13 +328,24 @@ def validate_installation():for var_name, var_config in raw_vars.items():if var_config.get('required', False) and var_name not in user_variables:errors.append(f'Required variable "{var_name}" is not provided')++ # Does the target have room? Advisory: it rides alongside+ # `errors` rather than in it, so a tight server informs the+ # operator without refusing the install. Never fatal — a+ # capacity probe that throws must not block a deploy.+ try:+ from app.services.capacity_service import check_fit+ capacity = check_fit(template, server_id)+ except Exception: # noqa: BLE001+ current_app.logger.warning('capacity check failed', exc_info=True)else:errors.append('Template ID is required')if errors:- return jsonify({'valid': False, 'errors': errors}), 400+ return jsonify({'valid': False, 'errors': errors,+ 'capacity': capacity}), 400- return jsonify({'valid': True}), 200+ return jsonify({'valid': True, 'capacity': capacity}), 200except Exception as e:import tracebackdiff --git a/backend/app/services/capacity_service.py b/backend/app/services/capacity_service.pynew file mode 100644index 00000000..997d5743--- /dev/null+++ b/backend/app/services/capacity_service.py@@ -0,0 +1,298 @@+"""Will this actually fit? — capacity preflight for installs.++Deploying a template checked three things: the name is free, the target server+exists, and the directory isn't taken. Nothing asked whether the box could+carry the thing, so a 2 GB app landed on a 1 GB VPS at full speed and the first+sign of trouble was the OOM killer.++Templates already describe what they cost (``requirements: memory / storage``),+the panel already knows what each server has (``Server.total_memory`` /+``total_disk``) and what it is currently using (the latest ``ServerMetrics``+sample). This service is the join, and it answers in the shape a person asks+the question: *does it fit, will it be tight, or can't we tell?*++Deliberately advisory. It reports; it never refuses. An estimate is an estimate+— real usage depends on configuration and traffic — so the operator keeps the+final say, and "tight" is a sentence to read, not a wall to argue with. The+only honest failure mode is ``unknown``: with no recent sample we say so rather+than guessing, because a confident wrong answer is worse than no answer.+"""++import logging+import re+from datetime import datetime, timedelta++logger = logging.getLogger(__name__)++# Leave this much of the box unspoken-for after the install, or call it tight.+# A fraction alone is wrong at both ends (10% of 1 GB is nothing; 10% of 64 GB+# is more than most apps need), so each is a floor-and-fraction pair.+MEMORY_RESERVE_FRACTION = 0.10+MEMORY_RESERVE_MIN = 256 * 1024 ** 2 # 256 MB+DISK_RESERVE_FRACTION = 0.10+DISK_RESERVE_MIN = 2 * 1024 ** 3 # 2 GB++#: A sample older than this describes a server we no longer know. Still shown,+#: but flagged — the numbers may predate whatever else was deployed since.+STALE_AFTER = timedelta(minutes=15)++#: Worst-first, so the overall verdict is the most severe of the per-resource+#: ones. `unknown` outranks `ok`: not knowing is not the same as being fine.+SEVERITY = ('insufficient', 'tight', 'unknown', 'ok')++_SIZE_RE = re.compile(r'^\s*([\d.]+)\s*([kmgt]?)i?b?\s*$', re.I)+_UNIT_BYTES = {'': 1, 'k': 1024, 'm': 1024 ** 2, 'g': 1024 ** 3, 't': 1024 ** 4}+++def parse_size(value):+ """``'512MB'`` / ``'2 GB'`` / ``1073741824`` -> bytes, or None if unusable.++ Catalog authors write these by hand, so the parser is forgiving about case,+ spacing and the ``i``/``B`` suffixes — and returns None rather than raising+ on anything it doesn't recognise, since a malformed estimate should degrade+ to "unknown", not break the install dialog.+ """+ if value is None:+ return None+ if isinstance(value, (int, float)):+ return int(value) if value > 0 else None+ match = _SIZE_RE.match(str(value))+ if not match:+ return None+ amount, unit = match.groups()+ try:+ return int(float(amount) * _UNIT_BYTES[unit.lower()])+ except (ValueError, KeyError):+ return None+++def format_size(num_bytes):+ """Bytes -> a short human string ('512 MB', '1.5 GB')."""+ if num_bytes is None:+ return 'unknown'+ step = float(num_bytes)+ for unit in ('B', 'KB', 'MB', 'GB', 'TB'):+ if step < 1024 or unit == 'TB':+ return f'{step:.0f} {unit}' if step >= 10 or unit == 'B' else f'{step:.1f} {unit}'+ step /= 1024+ return f'{step:.1f} TB'+++def template_footprint(template):+ """What a template says it costs, in bytes.++ Returns ``{'memory': int|None, 'disk': int|None, 'declared': {...}}``.+ Both keys are None for a template that declares nothing — about half the+ catalog today — which surfaces as an honest "unknown" rather than a zero.+ """+ requirements = (template or {}).get('requirements') or {}+ if not isinstance(requirements, dict):+ return {'memory': None, 'disk': None, 'declared': {}}+ # `storage` is the catalog's word for it; `disk` accepted for authors who+ # reach for the more obvious one.+ disk_raw = requirements.get('storage', requirements.get('disk'))+ return {+ 'memory': parse_size(requirements.get('memory')),+ 'disk': parse_size(disk_raw),+ 'declared': {k: v for k, v in requirements.items() if v is not None},+ }+++def server_headroom(server_id=None):+ """What the target has spare right now.++ ``server_id=None`` means the panel's own host. Remote servers are read from+ their newest metrics sample; the totals come from the server row, which the+ agent fills in on connect.+ """+ if not server_id or server_id == 'local':+ return _local_headroom()+ return _remote_headroom(server_id)+++def check_fit(template, server_id=None):+ """Does *template* fit on *server_id*? Advisory — see the module docstring.++ Returns a dict the install dialog can render as-is: an overall ``verdict``,+ a one-line ``headline`` and ``detail``, and a per-resource breakdown so the+ UI can show which of memory/disk is the problem.+ """+ footprint = template_footprint(template)+ headroom = server_headroom(server_id)++ checks = [+ _check_resource('memory', footprint['memory'], headroom.get('memory_free'),+ headroom.get('memory_total'),+ MEMORY_RESERVE_FRACTION, MEMORY_RESERVE_MIN),+ _check_resource('disk', footprint['disk'], headroom.get('disk_free'),+ headroom.get('disk_total'),+ DISK_RESERVE_FRACTION, DISK_RESERVE_MIN),+ ]++ verdict = _worst(check['verdict'] for check in checks)+ return {+ 'verdict': verdict,+ 'headline': _headline(verdict, headroom),+ 'detail': _detail(verdict, checks, footprint, headroom),+ 'blocking': False, # never; the operator decides+ 'requirements': footprint,+ 'server': headroom,+ 'checks': checks,+ }+++# --------------------------------------------------------------------------- #+# Internals+# --------------------------------------------------------------------------- #++def _check_resource(name, need, free, total, reserve_fraction, reserve_min):+ """One resource's verdict, with the arithmetic left visible for the UI."""+ check = {'resource': name, 'need': need, 'free': free, 'total': total,+ 'after': None, 'reserve': None, 'verdict': 'unknown'}+ if need is None or free is None:+ # Either the template never said, or we have no sample. Both are+ # "we don't know", and the caller is told which by the fields.+ return check++ reserve = max(reserve_min, int((total or 0) * reserve_fraction))+ after = free - need+ check['after'] = after+ check['reserve'] = reserve++ if after < 0:+ check['verdict'] = 'insufficient'+ elif after < reserve:+ check['verdict'] = 'tight'+ else:+ check['verdict'] = 'ok'+ return check+++def _worst(verdicts):+ seen = set(verdicts)+ for level in SEVERITY:+ if level in seen:+ return level+ return 'unknown'+++def _headline(verdict, headroom):+ if verdict == 'insufficient':+ return "This server doesn't have room for it"+ if verdict == 'tight':+ return 'It fits, but this server will be tight'+ if verdict == 'ok':+ return 'Fits comfortably'+ if not headroom.get('measured_at'):+ return "No recent readings from this server — can't check the fit"+ return "This template doesn't publish what it needs — can't check the fit"+++def _detail(verdict, checks, footprint, headroom):+ """The sentence under the headline: what it needs, against what's spare."""+ need_bits = [f'{format_size(c["need"])} {c["resource"]}'+ for c in checks if c['need'] is not None]+ free_bits = [f'{format_size(c["free"])} {c["resource"]}'+ for c in checks if c['free'] is not None]++ if not need_bits:+ return ('This template does not declare a memory or storage estimate, '+ 'so there is nothing to compare against.')+ if not free_bits:+ return (f'Needs about {" and ".join(need_bits)}. '+ 'No recent usage readings for this server, so its free space '+ 'is unknown.')++ sentence = (f'Needs about {" and ".join(need_bits)}; '+ f'this server has {" and ".join(free_bits)} free.')++ short = [c for c in checks if c['verdict'] == 'insufficient']+ if short:+ names = ' and '.join(c['resource'] for c in short)+ sentence += f' That is more {names} than it has.'+ else:+ tight = [c for c in checks if c['verdict'] == 'tight']+ if tight:+ leftovers = ' and '.join(+ f'{format_size(c["after"])} {c["resource"]}' for c in tight)+ sentence += f' Installing it would leave only {leftovers} spare.'++ if headroom.get('stale'):+ sentence += ' These readings are more than 15 minutes old.'+ return sentence+++def _local_headroom():+ """The panel's own host, read live — no sample to go stale."""+ result = {'server_id': None, 'name': 'This server', 'measured_at': None,+ 'stale': False, 'source': 'local'}+ try:+ import psutil+ except ImportError:+ return result+ try:+ memory = psutil.virtual_memory()+ disk = psutil.disk_usage('/')+ result.update({+ 'memory_total': memory.total,+ # `available`, not `free`: cache and buffers are reclaimable, and+ # counting them as used would call every healthy Linux box full.+ 'memory_free': memory.available,+ 'disk_total': disk.total,+ 'disk_free': disk.free,+ 'measured_at': datetime.utcnow().isoformat() + 'Z',+ })+ except Exception: # noqa: BLE001 — a probe failure is "unknown", not fatal+ logger.warning('capacity: could not read local host usage', exc_info=True)+ return result+++def _remote_headroom(server_id):+ """A managed server, from its newest metrics sample."""+ from app.models.server import Server, ServerMetrics++ result = {'server_id': server_id, 'name': None, 'measured_at': None,+ 'stale': False, 'source': 'agent'}+ server = Server.query.get(server_id)+ if not server:+ return result++ result['name'] = server.name+ result['memory_total'] = server.total_memory+ result['disk_total'] = server.total_disk++ sample = (ServerMetrics.query+ .filter_by(server_id=server_id)+ .order_by(ServerMetrics.timestamp.desc())+ .first())+ if not sample:+ return result++ if sample.timestamp:+ result['measured_at'] = sample.timestamp.isoformat() + 'Z'+ result['stale'] = (datetime.utcnow() - sample.timestamp) > STALE_AFTER++ if server.total_memory and sample.memory_used is not None:+ result['memory_free'] = max(0, server.total_memory - sample.memory_used)+ if sample.disk_used is not None:+ total_disk = server.total_disk or _implied_total(sample.disk_used,+ sample.disk_percent)+ if total_disk:+ result['disk_total'] = total_disk+ result['disk_free'] = max(0, total_disk - sample.disk_used)+ return result+++def _implied_total(used, percent):+ """Recover a total from used+percent when the server row never got one.++ Agents report the percentage even when the absolute total is missing from+ the row, and a disk check that silently does nothing is worse than one+ working off a derived figure.+ """+ try:+ if used and percent and percent > 0:+ return int(used / (float(percent) / 100.0))+ except (TypeError, ValueError, ZeroDivisionError):+ pass+ return Nonediff --git a/backend/templates/agentsite.yaml b/backend/templates/agentsite.yamlindex e88a91b4..8e75b2f6 100644--- a/backend/templates/agentsite.yaml+++ b/backend/templates/agentsite.yaml@@ -49,3 +49,7 @@ repo:- key: OPENROUTER_API_KEYrequired: truesecret: true++requirements:+ memory: 1GB+ storage: 4GBdiff --git a/backend/templates/authelia.yaml b/backend/templates/authelia.yamlindex 3838aaf3..70a5f965 100644--- a/backend/templates/authelia.yaml+++ b/backend/templates/authelia.yaml@@ -42,6 +42,10 @@ volumes:path: /configdescription: Authelia configuration+requirements:+ memory: 256MB+ storage: 1GB+compose:services:authelia:diff --git a/backend/templates/bookstack.yaml b/backend/templates/bookstack.yamlindex 1b98b5f7..9936ccd5 100644--- a/backend/templates/bookstack.yaml+++ b/backend/templates/bookstack.yaml@@ -35,6 +35,10 @@ volumes:path: /configdescription: BookStack configuration+requirements:+ memory: 512MB+ storage: 2GB+compose:services:bookstack:diff --git a/backend/templates/caddy.yaml b/backend/templates/caddy.yamlindex 309c7325..0033b287 100644--- a/backend/templates/caddy.yaml+++ b/backend/templates/caddy.yaml@@ -41,6 +41,10 @@ volumes:path: /srvdescription: Website files+requirements:+ memory: 256MB+ storage: 1GB+compose:services:caddy:diff --git a/backend/templates/code-server.yaml b/backend/templates/code-server.yamlindex 1c4ab489..d9ff5443 100644--- a/backend/templates/code-server.yaml+++ b/backend/templates/code-server.yaml@@ -35,6 +35,10 @@ volumes:path: /configdescription: Code Server configuration+requirements:+ memory: 1GB+ storage: 5GB+compose:services:code-server:diff --git a/backend/templates/crowdsec.yaml b/backend/templates/crowdsec.yamlindex 0a6890b5..58cda255 100644--- a/backend/templates/crowdsec.yaml+++ b/backend/templates/crowdsec.yaml@@ -33,6 +33,10 @@ volumes:path: /var/lib/crowdsec/datadescription: CrowdSec data+requirements:+ memory: 512MB+ storage: 2GB+compose:services:crowdsec:diff --git a/backend/templates/directus.yaml b/backend/templates/directus.yamlindex b2954752..7c1d492d 100644--- a/backend/templates/directus.yaml+++ b/backend/templates/directus.yaml@@ -47,6 +47,10 @@ volumes:path: /directus/extensionsdescription: Directus extensions+requirements:+ memory: 1GB+ storage: 4GB+compose:services:directus:diff --git a/backend/templates/drone.yaml b/backend/templates/drone.yamlindex 4e3e9db1..1363ce12 100644--- a/backend/templates/drone.yaml+++ b/backend/templates/drone.yaml@@ -44,6 +44,10 @@ volumes:path: /datadescription: Drone data+requirements:+ memory: 1GB+ storage: 10GB+compose:services:drone:diff --git a/backend/templates/duplicati.yaml b/backend/templates/duplicati.yamlindex e7b5cb09..eda81e70 100644--- a/backend/templates/duplicati.yaml+++ b/backend/templates/duplicati.yaml@@ -34,6 +34,10 @@ volumes:path: /backupsdescription: Local backup destination+requirements:+ memory: 512MB+ storage: 5GB+compose:services:duplicati:diff --git a/backend/templates/excalidraw.yaml b/backend/templates/excalidraw.yamlindex fc27e1ad..c8b91c25 100644--- a/backend/templates/excalidraw.yaml+++ b/backend/templates/excalidraw.yaml@@ -22,6 +22,10 @@ ports:protocol: tcpdescription: Web interface+requirements:+ memory: 256MB+ storage: 1GB+compose:services:excalidraw:diff --git a/backend/templates/filebrowser.yaml b/backend/templates/filebrowser.yamlindex e124f76d..be52acf3 100644--- a/backend/templates/filebrowser.yaml+++ b/backend/templates/filebrowser.yaml@@ -31,6 +31,10 @@ volumes:path: /databasedescription: File Browser database+requirements:+ memory: 256MB+ storage: 2GB+compose:services:filebrowser:diff --git a/backend/templates/gitlab-runner.yaml b/backend/templates/gitlab-runner.yamlindex 20d8f70d..236a9e2d 100644--- a/backend/templates/gitlab-runner.yaml+++ b/backend/templates/gitlab-runner.yaml@@ -31,6 +31,10 @@ volumes:path: /var/run/docker.sockdescription: Docker socket+requirements:+ memory: 1GB+ storage: 10GB+compose:services:gitlab-runner:diff --git a/backend/templates/grafana.yaml b/backend/templates/grafana.yamlindex 5e07d678..38b603bd 100644--- a/backend/templates/grafana.yaml+++ b/backend/templates/grafana.yaml@@ -36,6 +36,10 @@ volumes:path: /var/lib/grafanadescription: Grafana data and dashboards+requirements:+ memory: 512MB+ storage: 2GB+compose:services:grafana:diff --git a/backend/templates/grav.yaml b/backend/templates/grav.yamlindex fa532eff..b59515a5 100644--- a/backend/templates/grav.yaml+++ b/backend/templates/grav.yaml@@ -27,6 +27,10 @@ volumes:path: /var/www/html/userdescription: Grav user content+requirements:+ memory: 512MB+ storage: 2GB+compose:services:grav:diff --git a/backend/templates/homeassistant.yaml b/backend/templates/homeassistant.yamlindex 84d74235..435d17f0 100644--- a/backend/templates/homeassistant.yaml+++ b/backend/templates/homeassistant.yaml@@ -30,6 +30,10 @@ volumes:path: /configdescription: Home Assistant configuration+requirements:+ memory: 1GB+ storage: 5GB+compose:services:homeassistant:diff --git a/backend/templates/immich.yaml b/backend/templates/immich.yamlindex 15b5b33b..4641c14b 100644--- a/backend/templates/immich.yaml+++ b/backend/templates/immich.yaml@@ -35,6 +35,10 @@ volumes:path: /usr/src/app/uploaddescription: Photo uploads+requirements:+ memory: 4GB+ storage: 20GB+compose:services:immich-server:diff --git a/backend/templates/jaeger.yaml b/backend/templates/jaeger.yamlindex ce1a465d..e9a91cb0 100644--- a/backend/templates/jaeger.yaml+++ b/backend/templates/jaeger.yaml@@ -38,6 +38,10 @@ volumes:path: /badgerdescription: Badger storage for traces+requirements:+ memory: 1GB+ storage: 5GB+compose:services:jaeger:diff --git a/backend/templates/jellyfin.yaml b/backend/templates/jellyfin.yamlindex db8de56b..975dcb0b 100644--- a/backend/templates/jellyfin.yaml+++ b/backend/templates/jellyfin.yaml@@ -45,6 +45,10 @@ volumes:path: /cachedescription: Jellyfin cache+requirements:+ memory: 2GB+ storage: 20GB+compose:services:jellyfin:diff --git a/backend/templates/jenkins.yaml b/backend/templates/jenkins.yamlindex 93acba54..de101e91 100644--- a/backend/templates/jenkins.yaml+++ b/backend/templates/jenkins.yaml@@ -38,6 +38,10 @@ volumes:path: /var/jenkins_homedescription: Jenkins home directory+requirements:+ memory: 2GB+ storage: 10GB+compose:services:jenkins:diff --git a/backend/templates/jitsi.yaml b/backend/templates/jitsi.yamlindex f8139089..78eed353 100644--- a/backend/templates/jitsi.yaml+++ b/backend/templates/jitsi.yaml@@ -56,6 +56,10 @@ volumes:path: /usr/share/jitsi-meet/transcriptsdescription: Transcripts+requirements:+ memory: 2GB+ storage: 4GB+compose:services:web:diff --git a/backend/templates/keycloak.yaml b/backend/templates/keycloak.yamlindex 642ca22a..b06e8200 100644--- a/backend/templates/keycloak.yaml+++ b/backend/templates/keycloak.yaml@@ -39,6 +39,10 @@ volumes:path: /opt/keycloak/datadescription: Keycloak data+requirements:+ memory: 1GB+ storage: 2GB+compose:services:keycloak:diff --git a/backend/templates/loki.yaml b/backend/templates/loki.yamlindex 3bc4fcd5..100f20e5 100644--- a/backend/templates/loki.yaml+++ b/backend/templates/loki.yaml@@ -27,6 +27,10 @@ volumes:path: /lokidescription: Loki data storage+requirements:+ memory: 1GB+ storage: 20GB+compose:services:loki:diff --git a/backend/templates/matrix-synapse.yaml b/backend/templates/matrix-synapse.yamlindex 4473d87e..77b57eb9 100644--- a/backend/templates/matrix-synapse.yaml+++ b/backend/templates/matrix-synapse.yaml@@ -37,6 +37,10 @@ volumes:path: /datadescription: Synapse data+requirements:+ memory: 2GB+ storage: 10GB+compose:services:synapse:diff --git a/backend/templates/mattermost.yaml b/backend/templates/mattermost.yamlindex 981ee389..ef19a756 100644--- a/backend/templates/mattermost.yaml+++ b/backend/templates/mattermost.yaml@@ -44,6 +44,10 @@ volumes:path: /mattermost/pluginsdescription: Mattermost plugins+requirements:+ memory: 2GB+ storage: 5GB+compose:services:mattermost:diff --git a/backend/templates/minio.yaml b/backend/templates/minio.yamlindex 8b11a2b9..7fb6b469 100644--- a/backend/templates/minio.yaml+++ b/backend/templates/minio.yaml@@ -43,6 +43,10 @@ volumes:path: /datadescription: Object storage data+requirements:+ memory: 1GB+ storage: 20GB+compose:services:minio:diff --git a/backend/templates/mongo-express.yaml b/backend/templates/mongo-express.yamlindex 863e4673..114777d0 100644--- a/backend/templates/mongo-express.yaml+++ b/backend/templates/mongo-express.yaml@@ -38,6 +38,10 @@ ports:protocol: tcpdescription: Web interface+requirements:+ memory: 256MB+ storage: 1GB+compose:services:mongo-express:diff --git a/backend/templates/mosquitto.yaml b/backend/templates/mosquitto.yamlindex e3337227..4779a592 100644--- a/backend/templates/mosquitto.yaml+++ b/backend/templates/mosquitto.yaml@@ -41,6 +41,10 @@ volumes:path: /mosquitto/logdescription: Mosquitto logs+requirements:+ memory: 256MB+ storage: 1GB+compose:services:mosquitto:diff --git a/backend/templates/n8n.yaml b/backend/templates/n8n.yamlindex b29aeec0..7ec1a94f 100644--- a/backend/templates/n8n.yaml+++ b/backend/templates/n8n.yaml@@ -38,6 +38,10 @@ volumes:path: /home/node/.n8ndescription: n8n data+requirements:+ memory: 1GB+ storage: 2GB+compose:services:n8n:diff --git a/backend/templates/navidrome.yaml b/backend/templates/navidrome.yamlindex 6068380d..f7b601fd 100644--- a/backend/templates/navidrome.yaml+++ b/backend/templates/navidrome.yaml@@ -31,6 +31,10 @@ volumes:path: /datadescription: Navidrome data+requirements:+ memory: 512MB+ storage: 10GB+compose:services:navidrome:diff --git a/backend/templates/netdata.yaml b/backend/templates/netdata.yamlindex d88de270..e58f96dc 100644--- a/backend/templates/netdata.yaml+++ b/backend/templates/netdata.yaml@@ -33,6 +33,10 @@ volumes:path: /var/cache/netdatadescription: Netdata cache+requirements:+ memory: 512MB+ storage: 2GB+compose:services:netdata:diff --git a/backend/templates/nodered.yaml b/backend/templates/nodered.yamlindex 558cb0c4..d98ef537 100644--- a/backend/templates/nodered.yaml+++ b/backend/templates/nodered.yaml@@ -30,6 +30,10 @@ volumes:path: /datadescription: Node-RED data+requirements:+ memory: 512MB+ storage: 2GB+compose:services:nodered:diff --git a/backend/templates/outline.yaml b/backend/templates/outline.yamlindex 03ed1b24..e8d4c93d 100644--- a/backend/templates/outline.yaml+++ b/backend/templates/outline.yaml@@ -42,6 +42,10 @@ volumes:path: /var/lib/outline/datadescription: Outline data+requirements:+ memory: 1GB+ storage: 2GB+compose:services:outline:diff --git a/backend/templates/payload.yaml b/backend/templates/payload.yamlindex d7bfbed7..2cea8743 100644--- a/backend/templates/payload.yaml+++ b/backend/templates/payload.yaml@@ -34,6 +34,10 @@ volumes:path: /app/mediadescription: Uploaded media files+requirements:+ memory: 1GB+ storage: 4GB+compose:services:payload:diff --git a/backend/templates/pgadmin.yaml b/backend/templates/pgadmin.yamlindex d1a7bcfe..2f28a70c 100644--- a/backend/templates/pgadmin.yaml+++ b/backend/templates/pgadmin.yaml@@ -35,6 +35,10 @@ volumes:path: /var/lib/pgadmindescription: pgAdmin data+requirements:+ memory: 512MB+ storage: 1GB+compose:services:pgadmin:diff --git a/backend/templates/photoprism.yaml b/backend/templates/photoprism.yamlindex 9d911e87..f1abef06 100644--- a/backend/templates/photoprism.yaml+++ b/backend/templates/photoprism.yaml@@ -39,6 +39,10 @@ volumes:path: /photoprism/storagedescription: PhotoPrism storage+requirements:+ memory: 2GB+ storage: 20GB+compose:services:photoprism:diff --git a/backend/templates/phpmyadmin.yaml b/backend/templates/phpmyadmin.yamlindex 72a6fdcb..e3981225 100644--- a/backend/templates/phpmyadmin.yaml+++ b/backend/templates/phpmyadmin.yaml@@ -31,6 +31,10 @@ ports:protocol: tcpdescription: Web interface+requirements:+ memory: 256MB+ storage: 1GB+compose:services:phpmyadmin:diff --git a/backend/templates/plausible.yaml b/backend/templates/plausible.yamlindex 6c6f2992..38d2f3ea 100644--- a/backend/templates/plausible.yaml+++ b/backend/templates/plausible.yaml@@ -38,6 +38,10 @@ volumes:path: /var/lib/plausibledescription: Plausible data+requirements:+ memory: 2GB+ storage: 5GB+compose:services:plausible:diff --git a/backend/templates/plex.yaml b/backend/templates/plex.yamlindex 707cd91a..0bc7cc4c 100644--- a/backend/templates/plex.yaml+++ b/backend/templates/plex.yaml@@ -46,6 +46,10 @@ volumes:path: /transcodedescription: Transcode directory+requirements:+ memory: 2GB+ storage: 20GB+compose:services:plex:diff --git a/backend/templates/prometheus.yaml b/backend/templates/prometheus.yamlindex f6151cb9..81cf4799 100644--- a/backend/templates/prometheus.yaml+++ b/backend/templates/prometheus.yaml@@ -33,6 +33,10 @@ volumes:path: /etc/prometheusdescription: Configuration files+requirements:+ memory: 2GB+ storage: 20GB+compose:services:prometheus:diff --git a/backend/templates/redis-commander.yaml b/backend/templates/redis-commander.yamlindex b063a639..75f15d7a 100644--- a/backend/templates/redis-commander.yaml+++ b/backend/templates/redis-commander.yaml@@ -34,6 +34,10 @@ ports:protocol: tcpdescription: Web interface+requirements:+ memory: 256MB+ storage: 1GB+compose:services:redis-commander:diff --git a/backend/templates/registry.yaml b/backend/templates/registry.yamlindex 5159836d..47d2e886 100644--- a/backend/templates/registry.yaml+++ b/backend/templates/registry.yaml@@ -43,6 +43,10 @@ volumes:path: /authdescription: Authentication files+requirements:+ memory: 512MB+ storage: 20GB+compose:services:registry:diff --git a/backend/templates/rocketchat.yaml b/backend/templates/rocketchat.yamlindex 09653f43..a8974a18 100644--- a/backend/templates/rocketchat.yaml+++ b/backend/templates/rocketchat.yaml@@ -31,6 +31,10 @@ volumes:path: /app/uploadsdescription: Uploaded files+requirements:+ memory: 2GB+ storage: 5GB+compose:services:rocketchat:diff --git a/backend/templates/seafile.yaml b/backend/templates/seafile.yamlindex 685c6bb3..882b253f 100644--- a/backend/templates/seafile.yaml+++ b/backend/templates/seafile.yaml@@ -42,6 +42,10 @@ volumes:path: /shared/seafiledescription: Seafile data+requirements:+ memory: 1GB+ storage: 10GB+compose:services:seafile:diff --git a/backend/templates/sonarqube.yaml b/backend/templates/sonarqube.yamlindex 88d20c79..062ca23d 100644--- a/backend/templates/sonarqube.yaml+++ b/backend/templates/sonarqube.yaml@@ -37,6 +37,10 @@ volumes:path: /opt/sonarqube/logsdescription: SonarQube logs+requirements:+ memory: 4GB+ storage: 10GB+compose:services:sonarqube:diff --git a/backend/templates/strapi.yaml b/backend/templates/strapi.yamlindex 0c5b604a..7c59c0c6 100644--- a/backend/templates/strapi.yaml+++ b/backend/templates/strapi.yaml@@ -50,6 +50,10 @@ volumes:path: /var/lib/postgresql/datadescription: PostgreSQL data+requirements:+ memory: 2GB+ storage: 4GB+compose:services:strapi:diff --git a/backend/templates/syncthing.yaml b/backend/templates/syncthing.yamlindex 3c847353..e3d230e2 100644--- a/backend/templates/syncthing.yaml+++ b/backend/templates/syncthing.yaml@@ -42,6 +42,10 @@ volumes:path: /configdescription: Syncthing configuration+requirements:+ memory: 512MB+ storage: 10GB+compose:services:syncthing:diff --git a/backend/templates/traefik.yaml b/backend/templates/traefik.yamlindex 69ffed90..f4ecdcf3 100644--- a/backend/templates/traefik.yaml+++ b/backend/templates/traefik.yaml@@ -46,6 +46,10 @@ volumes:path: /letsencryptdescription: Let's Encrypt certificates+requirements:+ memory: 256MB+ storage: 1GB+compose:services:traefik:diff --git a/backend/templates/umami.yaml b/backend/templates/umami.yamlindex 96ed51cc..27d2e52e 100644--- a/backend/templates/umami.yaml+++ b/backend/templates/umami.yaml@@ -30,6 +30,10 @@ ports:protocol: tcpdescription: Web interface+requirements:+ memory: 512MB+ storage: 2GB+compose:services:umami:diff --git a/backend/templates/vault.yaml b/backend/templates/vault.yamlindex e0118887..427e9f6b 100644--- a/backend/templates/vault.yaml+++ b/backend/templates/vault.yaml@@ -40,6 +40,10 @@ volumes:path: /vault/logsdescription: Vault logs+requirements:+ memory: 512MB+ storage: 2GB+compose:services:vault:diff --git a/backend/templates/vaultwarden.yaml b/backend/templates/vaultwarden.yamlindex 92e0bd5a..c61de6da 100644--- a/backend/templates/vaultwarden.yaml+++ b/backend/templates/vaultwarden.yaml@@ -37,6 +37,10 @@ volumes:path: /datadescription: Vaultwarden data+requirements:+ memory: 256MB+ storage: 1GB+compose:services:vaultwarden:diff --git a/backend/templates/wikijs.yaml b/backend/templates/wikijs.yamlindex 5d7ef6bc..3ff94540 100644--- a/backend/templates/wikijs.yaml+++ b/backend/templates/wikijs.yaml@@ -31,6 +31,10 @@ volumes:path: /wiki/datadescription: Wiki.js data+requirements:+ memory: 1GB+ storage: 2GB+compose:services:wikijs:diff --git a/backend/templates/wordpress-external-db.yaml b/backend/templates/wordpress-external-db.yamlindex c0a1b697..c1dc2c73 100644--- a/backend/templates/wordpress-external-db.yaml+++ b/backend/templates/wordpress-external-db.yaml@@ -59,6 +59,10 @@ volumes:path: /var/www/htmldescription: WordPress files+requirements:+ memory: 512MB+ storage: 2GB+compose:services:wordpress:diff --git a/backend/templates/wordpress.yaml b/backend/templates/wordpress.yamlindex ac0461c1..da6d36e8 100644--- a/backend/templates/wordpress.yaml+++ b/backend/templates/wordpress.yaml@@ -45,6 +45,10 @@ volumes:path: /var/lib/mysqldescription: MySQL data+requirements:+ memory: 1GB+ storage: 5GB+compose:services:wordpress:diff --git a/backend/templates/zigbee2mqtt.yaml b/backend/templates/zigbee2mqtt.yamlindex 19a5db4f..96126969 100644--- a/backend/templates/zigbee2mqtt.yaml+++ b/backend/templates/zigbee2mqtt.yaml@@ -35,6 +35,10 @@ volumes:path: /app/datadescription: Zigbee2MQTT data+requirements:+ memory: 512MB+ storage: 2GB+compose:services:zigbee2mqtt:diff --git a/backend/tests/test_capacity_preflight.py b/backend/tests/test_capacity_preflight.pynew file mode 100644index 00000000..e5f0df9b--- /dev/null+++ b/backend/tests/test_capacity_preflight.py@@ -0,0 +1,284 @@+"""Capacity preflight for template installs (capacity_service).++Installing checked the name, the server row and the directory — never whether+the box could carry the thing, so a 2 GB app landed on a 1 GB VPS at full speed+and the OOM killer delivered the news.++The rules this pins down are the ones that make the answer trustworthy: it+advises and never blocks, it says "unknown" instead of guessing, and "tight" is+measured against what is actually free rather than what the box has in total.+"""++from datetime import datetime, timedelta++import pytest++from app import db+from app.models.server import Server, ServerMetrics+from app.services import capacity_service+from app.services.capacity_service import check_fit, parse_size, template_footprint++GB = 1024 ** 3+MB = 1024 ** 2+++def _template(memory='512MB', storage='1GB'):+ requirements = {}+ if memory is not None:+ requirements['memory'] = memory+ if storage is not None:+ requirements['storage'] = storage+ return {'id': 'demo', 'name': 'Demo', 'requirements': requirements}+++def server(app):+ """A managed server with 4 GB RAM / 100 GB disk and one usage sample."""+ row = Server(id='srv-cap-1', name='box', status='online',+ total_memory=4 * GB, total_disk=100 * GB, cpu_cores=2)+ db.session.add(row)+ db.session.commit()+ return row+++def _sample(server_id, memory_used, disk_used, age_minutes=0, disk_percent=None):+ metric = ServerMetrics(+ server_id=server_id,+ timestamp=datetime.utcnow() - timedelta(minutes=age_minutes),+ memory_used=memory_used, disk_used=disk_used,+ disk_percent=disk_percent,+ )+ db.session.add(metric)+ db.session.commit()+ return metric+++class TestParsing:+ @pytest.mark.parametrize('text,expected', [+ ('512MB', 512 * MB), ('2GB', 2 * GB), ('1 GB', GB), ('256 mb', 256 * MB),+ ('1.5GB', int(1.5 * GB)), ('2GiB', 2 * GB), ('1024', 1024), ('4G', 4 * GB),+ ])+ def test_reads_the_forms_catalog_authors_write(self, text, expected):+ assert parse_size(text) == expected++ @pytest.mark.parametrize('text', ['', 'lots', None, 'MB', '-1GB', 0])+ def test_unusable_values_are_none_not_zero(self, text):+ # None degrades to "unknown"; zero would read as "needs nothing".+ assert parse_size(text) is None++ def test_footprint_accepts_storage_or_disk(self):+ assert template_footprint({'requirements': {'storage': '2GB'}})['disk'] == 2 * GB+ assert template_footprint({'requirements': {'disk': '2GB'}})['disk'] == 2 * GB++ def test_footprint_of_a_template_that_declares_nothing(self):+ footprint = template_footprint({'id': 'x'})+ assert footprint['memory'] is None and footprint['disk'] is None+++class TestVerdicts:+ def test_comfortable_fit(self, app, server):+ _sample(server.id, memory_used=1 * GB, disk_used=10 * GB)+ result = check_fit(_template('512MB', '1GB'), server.id)+ assert result['verdict'] == 'ok'+ assert result['headline'] == 'Fits comfortably'++ def test_more_memory_than_the_server_has_free(self, app, server):+ _sample(server.id, memory_used=int(3.5 * GB), disk_used=10 * GB)+ result = check_fit(_template('2GB', '1GB'), server.id)+ assert result['verdict'] == 'insufficient'+ assert 'more memory than it has' in result['detail']++ def test_fits_but_leaves_almost_nothing(self, app, server):+ # 700 MB free, needs 512 MB — it fits, but the reserve floor is 409 MB+ # (10% of 4 GB), so this is the case worth warning about.+ _sample(server.id, memory_used=4 * GB - 700 * MB, disk_used=10 * GB)+ result = check_fit(_template('512MB', '1GB'), server.id)+ assert result['verdict'] == 'tight'+ assert 'would leave only' in result['detail']++ def test_disk_alone_can_decide_it(self, app, server):+ _sample(server.id, memory_used=1 * GB, disk_used=99 * GB)+ result = check_fit(_template('512MB', '20GB'), server.id)+ assert result['verdict'] == 'insufficient'+ assert [c['verdict'] for c in result['checks'] if c['resource'] == 'memory'] == ['ok']++ def test_the_worst_resource_decides_the_overall_verdict(self, app, server):+ _sample(server.id, memory_used=1 * GB, disk_used=99 * GB)+ result = check_fit(_template('512MB', '20GB'), server.id)+ assert result['verdict'] == 'insufficient'++ def test_it_never_blocks(self, app, server):+ _sample(server.id, memory_used=int(3.9 * GB), disk_used=99 * GB)+ result = check_fit(_template('4GB', '50GB'), server.id)+ # The operator decides. An estimate is an estimate.+ assert result['blocking'] is False+++class TestHonestUnknowns:+ def test_a_server_with_no_readings_is_unknown_not_fine(self, app, server):+ result = check_fit(_template(), server.id)+ assert result['verdict'] == 'unknown'+ assert "can't check the fit" in result['headline']++ def test_a_template_that_declares_nothing_is_unknown(self, app, server):+ _sample(server.id, memory_used=1 * GB, disk_used=10 * GB)+ result = check_fit({'id': 'x'}, server.id)+ assert result['verdict'] == 'unknown'+ assert 'does not declare' in result['detail']++ def test_unknown_outranks_ok(self, app, server):+ # Memory is fine, disk unknown (template declares no storage): the+ # honest overall answer is "we don't know", not "fits comfortably".+ _sample(server.id, memory_used=1 * GB, disk_used=10 * GB)+ result = check_fit(_template('512MB', None), server.id)+ assert result['verdict'] == 'unknown'++ def test_a_missing_server_does_not_explode(self, app):+ result = check_fit(_template(), 'no-such-server')+ assert result['verdict'] == 'unknown'++ def test_stale_readings_are_flagged_but_still_used(self, app, server):+ _sample(server.id, memory_used=1 * GB, disk_used=10 * GB, age_minutes=45)+ result = check_fit(_template('512MB', '1GB'), server.id)+ assert result['server']['stale'] is True+ assert 'more than 15 minutes old' in result['detail']+ assert result['verdict'] == 'ok'++ def test_disk_total_is_derived_when_the_row_never_got_one(self, app):+ # Agents report the percentage even when the absolute total is absent;+ # a disk check that silently does nothing is worse.+ row = Server(id='srv-cap-2', name='no-total', status='online',+ total_memory=4 * GB, total_disk=None)+ db.session.add(row)+ db.session.commit()+ _sample(row.id, memory_used=1 * GB, disk_used=50 * GB, disk_percent=50.0)++ result = check_fit(_template('512MB', '1GB'), row.id)+ assert result['server']['disk_total'] == 100 * GB+ assert result['server']['disk_free'] == 50 * GB+++class TestReserveMath:+ def test_reserve_has_a_floor_for_small_boxes(self, app):+ # 10% of 1 GB is 102 MB — too little to call healthy, so the floor+ # (256 MB) governs and this counts as tight.+ row = Server(id='srv-cap-3', name='tiny', status='online',+ total_memory=1 * GB, total_disk=20 * GB)+ db.session.add(row)+ db.session.commit()+ _sample(row.id, memory_used=1 * GB - 600 * MB, disk_used=1 * GB)++ result = check_fit(_template('400MB', '1GB'), row.id)+ memory = next(c for c in result['checks'] if c['resource'] == 'memory')+ assert memory['reserve'] == capacity_service.MEMORY_RESERVE_MIN+ assert result['verdict'] == 'tight'++ def test_reserve_scales_up_on_a_big_box(self, app):+ row = Server(id='srv-cap-4', name='big', status='online',+ total_memory=64 * GB, total_disk=1000 * GB)+ db.session.add(row)+ db.session.commit()+ _sample(row.id, memory_used=1 * GB, disk_used=1 * GB)++ result = check_fit(_template('1GB', '1GB'), row.id)+ memory = next(c for c in result['checks'] if c['resource'] == 'memory')+ assert memory['reserve'] == int(64 * GB * capacity_service.MEMORY_RESERVE_FRACTION)+++class TestEndpoint:+ def _seed_admin(self):+ from app.models import User+ from werkzeug.security import generate_password_hash+ user = User(email='[email protected]', username='cap_admin',+ password_hash=generate_password_hash('x'),+ role=User.ROLE_ADMIN, is_active=True)+ db.session.add(user)+ db.session.commit()+ return user++ def test_validate_install_reports_capacity(self, app, client, auth_headers, server):+ _sample(server.id, memory_used=1 * GB, disk_used=10 * GB)++ res = client.post('/api/v1/templates/validate-install', headers=auth_headers,+ json={'template_id': 'actualbudget', 'app_name': 'budget-app',+ 'server_id': server.id})++ assert res.status_code == 200+ body = res.get_json()+ assert body['valid'] is True+ assert body['capacity']['verdict'] in ('ok', 'tight', 'insufficient', 'unknown')+ assert body['capacity']['blocking'] is False++ def test_a_full_server_still_validates(self, app, client, auth_headers, server):+ # The install is allowed; the operator is merely told. If this ever+ # starts returning 400, the feature has become a gate.+ _sample(server.id, memory_used=4 * GB, disk_used=100 * GB)++ res = client.post('/api/v1/templates/validate-install', headers=auth_headers,+ json={'template_id': 'jenkins', 'app_name': 'ci-box',+ 'server_id': server.id})++ assert res.status_code == 200+ assert res.get_json()['capacity']['verdict'] == 'insufficient'++ def test_capacity_is_omitted_rather_than_faked_without_a_template(+ self, app, client, auth_headers):+ res = client.post('/api/v1/templates/validate-install', headers=auth_headers,+ json={'app_name': 'x'})+ assert res.status_code == 400+ assert res.get_json()['capacity'] is None++ def test_capacity_endpoint_answers_for_a_server(self, app, client, auth_headers, server):+ # The drawer reads this while the operator is still choosing a target,+ # so it must work without an app name or any form state.+ _sample(server.id, memory_used=1 * GB, disk_used=10 * GB)++ res = client.get(f'/api/v1/templates/actualbudget/capacity?server_id={server.id}',+ headers=auth_headers)++ assert res.status_code == 200+ body = res.get_json()+ assert body['verdict'] == 'ok'+ assert body['server']['name'] == 'box'+ assert body['requirements']['memory'] == 512 * MB++ def test_capacity_endpoint_defaults_to_this_host(self, app, client, auth_headers):+ # No server_id means the panel's own machine, which is the common case+ # for a single-server install.+ res = client.get('/api/v1/templates/actualbudget/capacity', headers=auth_headers)++ assert res.status_code == 200+ assert res.get_json()['server']['source'] == 'local'++ def test_capacity_endpoint_404s_for_an_unknown_template(self, app, client, auth_headers):+ res = client.get('/api/v1/templates/no-such-template/capacity', headers=auth_headers)+ assert res.status_code == 404++ def test_capacity_endpoint_needs_auth(self, app, client):+ res = client.get('/api/v1/templates/actualbudget/capacity')+ assert res.status_code == 401+++class TestLocalHost:+ def test_reads_the_panel_host_live(self, app):+ # The single-server case: no agent, no metrics row, psutil instead —+ # so `measured_at` is always now and nothing can go stale.+ headroom = capacity_service.server_headroom(None)+ assert headroom['source'] == 'local'+ assert headroom['stale'] is False+ assert headroom['memory_total'] > 0+ assert 0 < headroom['memory_free'] <= headroom['memory_total']++ def test_local_and_explicit_local_agree(self, app):+ assert (capacity_service.server_headroom('local')['source']+ == capacity_service.server_headroom(None)['source'])++ def test_a_real_template_fits_this_machine(self, app):+ from app.services.template_service import TemplateService++ template = TemplateService.get_template('actualbudget')['template']+ result = check_fit(template, None)+ # Whatever the verdict, the shape the drawer renders must be complete.+ assert result['verdict'] in ('ok', 'tight', 'insufficient', 'unknown')+ assert result['requirements']['memory'] == 512 * MB+ assert result['headline'] and result['detail']diff --git a/frontend/src/services/api/apps.js b/frontend/src/services/api/apps.jsindex a1aa002d..bd4a9afd 100644--- a/frontend/src/services/api/apps.js+++ b/frontend/src/services/api/apps.js@@ -328,13 +328,20 @@ export async function installTemplate(templateId, appName, variables = {}, optio});}-export async function validateTemplateInstall(templateId, appName, variables = {}) {+export async function validateTemplateInstall(templateId, appName, variables = {}, serverId = null) {return this.request('/templates/validate-install', {method: 'POST',- body: { template_id: templateId, app_name: appName, variables }+ body: { template_id: templateId, app_name: appName, variables, server_id: serverId }});}+// Whether a template fits on a server: what it typically needs, against what+// that server has free. Advisory — a poor verdict never blocks an install.+export async function getTemplateCapacity(templateId, serverId = null) {+ const query = serverId && serverId !== 'local' ? `?server_id=${encodeURIComponent(serverId)}` : '';+ return this.request(`/templates/${templateId}/capacity${query}`);+}+export async function testDatabaseConnection(config) {return this.request('/templates/test-db-connection', {method: 'POST',