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(backups): dynamic target-provider registry
Juan Denis8d106aa5a0ed
diff --git a/backend/app/api/backups.py b/backend/app/api/backups.pyindex 2bd0ed57..fdb00dea 100644--- a/backend/app/api/backups.py+++ b/backend/app/api/backups.py@@ -11,6 +11,50 @@ from app import db, pathsbackups_bp = Blueprint('backups', __name__)+# UI-facing metadata for the CORE target types (plan 52 D4). Extension kinds+# carry their own label/scopes in backup_kind_registry. 'server' is listed+# but flagged unimplemented so the UI never shows a dead whole-server button.+_CORE_TARGET_META = {+ 'application': {'label': 'Application', 'restore_scopes': ['full', 'files'],+ 'implemented': True},+ 'database': {'label': 'Database', 'restore_scopes': ['full'],+ 'implemented': True},+ 'files': {'label': 'Files', 'restore_scopes': ['full'], 'implemented': True},+ 'server': {'label': 'Whole server', 'restore_scopes': [], 'implemented': False},+}+++@backups_bp.route('/target-types', methods=['GET'])+@jwt_required()+def list_target_types():+ """Target types available for protection RIGHT NOW: the core set plus any+ extension-registered kinds (e.g. 'wordpress_site' only while the WordPress+ extension is installed and active). The Protection panel / restore drawer+ read this instead of hardcoding type knowledge, so an absent extension+ means an absent type — not a dead button.++ Not admin-gated: it exposes only type names/labels, and per-target policy+ routes are reachable by non-admin resource editors.+ """+ from app.models.backup_policy import VALID_TARGET_TYPES+ from app.services import backup_kind_registry+ types = []+ for t in VALID_TARGET_TYPES:+ meta = _CORE_TARGET_META.get(t, {})+ types.append({+ 'target_type': t,+ 'label': meta.get('label', t),+ 'restore_scopes': meta.get('restore_scopes'),+ 'supports_restore': bool(meta.get('restore_scopes')),+ 'implemented': meta.get('implemented', True),+ 'source': 'core',+ })+ for entry in backup_kind_registry.catalog():+ entry.setdefault('implemented', True)+ types.append(entry)+ return jsonify({'target_types': types}), 200++@backups_bp.route('', methods=['GET'])@jwt_required()@admin_required@@ -53,7 +97,19 @@ def list_policies():if enabled is not None:query = query.filter_by(enabled=str(enabled).lower() in ('1', 'true', 'yes'))policies = query.order_by(BackupPolicy.target_type, BackupPolicy.target_id).all()- return jsonify({'policies': [p.to_dict() for p in policies]}), 200+ # Flag policies whose target type currently has no provider (the extension+ # that owns it was uninstalled/disabled) so the UI can show an explicit+ # "provider missing" state instead of an apparently-healthy policy.+ from app.services import backup_kind_registry+ out = []+ for p in policies:+ d = p.to_dict()+ d['provider_missing'] = (+ p.target_type not in VALID_TARGET_TYPES+ and not backup_kind_registry.get(p.target_type)+ )+ out.append(d)+ return jsonify({'policies': out}), 200@backups_bp.route('/runs', methods=['GET'])diff --git a/backend/app/models/backup_policy.py b/backend/app/models/backup_policy.pyindex 4fd54e76..33e8422c 100644--- a/backend/app/models/backup_policy.py+++ b/backend/app/models/backup_policy.py@@ -4,11 +4,18 @@ from decimal import Decimalfrom app import db-# Every data-protection target the unified policy system can back up (§8).-# 'application' and 'wordpress_site' are the original targets; 'database',-# 'files', and 'server' were folded in from the legacy BackupService so a-# single BackupPolicy/BackupRun system covers all data-protection backups.-VALID_TARGET_TYPES = ('application', 'wordpress_site', 'database', 'files', 'server')+# Every CORE data-protection target the unified policy system can back up (§8).+# 'application' is the original target; 'database', 'files', and 'server' were+# folded in from the legacy BackupService so a single BackupPolicy/BackupRun+# system covers all data-protection backups.+#+# This is the CORE set only (plan 52 D4): extension-owned target types — e.g.+# 'wordpress_site', registered by the serverkit-wordpress extension at load —+# come from app.services.backup_kind_registry at runtime, so an absent+# extension means an absent type. The valid set at any moment is this constant+# plus the registered kinds (see BackupPolicyService.validate_target_type and+# GET /api/v1/backups/target-types).+VALID_TARGET_TYPES = ('application', 'database', 'files', 'server')def _num(value):@@ -23,8 +30,10 @@ def _num(value):class BackupPolicy(db.Model):"""Automated backup ("protection") policy for a single target.- A target is either a WordPress site (``target_type='wordpress_site'``) or a- generic application (``target_type='application'``). There is at most one+ A target is a generic application (``target_type='application'``), a+ database, a files path-list, or the whole server — plus any extension-+ registered kind (e.g. ``'wordpress_site'`` while the WordPress extension+ is installed). There is at most onepolicy per target. The cron schedule is mirrored into a ``ScheduledJob`` rowby :class:`BackupPolicyService` so firing happens on the unified job bus.diff --git a/backend/app/services/backup_drill_service.py b/backend/app/services/backup_drill_service.pyindex 6a8d2320..c7436a8a 100644--- a/backend/app/services/backup_drill_service.py+++ b/backend/app/services/backup_drill_service.py@@ -320,7 +320,19 @@ class BackupDrillService:if target_type == 'database':return cls._drill_database(policy, run, meta)if target_type == 'wordpress_site':+ # The WP drill leg replays the backup ARTIFACT layout (files.tar.gz+ # + database.sql) with core services only — it never touches the+ # WordPress extension, so it stays core and works even with the+ # extension absent (drilling an old backup of a removed site).return cls._drill_wordpress(policy, run, meta, drill_id)+ if target_type not in ('files', 'application'):+ # Unknown type: drillable only while a provider kind is registered+ # (registered kinds replay their tar via the files leg below).+ from app.services import backup_kind_registry+ if not backup_kind_registry.get(target_type):+ raise BackupDrillError(+ f"Cannot drill target type {target_type!r}: the extension "+ f"that supplies it is not installed or not active")# files + application both replay a tar chain into a scratch dir.return cls._drill_files(policy, run, meta, drill_id)diff --git a/backend/app/services/backup_kind_registry.py b/backend/app/services/backup_kind_registry.pyindex 852cd7b6..97a1f52e 100644--- a/backend/app/services/backup_kind_registry.py+++ b/backend/app/services/backup_kind_registry.py@@ -29,7 +29,8 @@ import logginglogger = logging.getLogger(__name__)-# target_type -> {'resolve': fn, 'execute': fn, 'restore': fn|None}+# target_type -> {'resolve': fn, 'execute': fn, 'restore': fn|None,+# 'label': str|None, 'restore_scopes': list|None}_KINDS = {}@@ -39,11 +40,17 @@ def core_kinds():return VALID_TARGET_TYPES-def register(target_type: str, resolve, execute, restore=None, replace: bool = False):+def register(target_type: str, resolve, execute, restore=None, replace: bool = False,+ label: str = None, restore_scopes=None):"""Register a backup target type.Namespace it after your plugin (``minecraft.world``); the bare words core- uses are reserved.+ uses are reserved. ('wordpress_site' is the WordPress extension's kind —+ it left the core set under plan 52 D4.)++ ``label`` / ``restore_scopes`` are optional UI metadata surfaced by+ ``GET /api/v1/backups/target-types`` so the Protection panel/restore+ drawer can render the kind without hardcoding its name client-side."""if not target_type:raise ValueError('a backup kind needs a target type')@@ -55,7 +62,10 @@ def register(target_type: str, resolve, execute, restore=None, replace: bool = Fraise ValueError(f'"{target_type}" is a core backup target type and cannot be overridden')if target_type in _KINDS and not replace:raise ValueError(f'backup kind "{target_type}" is already registered')- _KINDS[target_type] = {'resolve': resolve, 'execute': execute, 'restore': restore}+ _KINDS[target_type] = {+ 'resolve': resolve, 'execute': execute, 'restore': restore,+ 'label': label, 'restore_scopes': list(restore_scopes) if restore_scopes else None,+ }logger.info('Registered backup kind: %s', target_type)return _KINDS[target_type]@@ -70,6 +80,21 @@ def kinds():return sorted(_KINDS)+def catalog():+ """Registered kinds as UI-facing descriptors (newest API consumers).++ ``[{target_type, label, restore_scopes, supports_restore, source}]`` —+ merged with the core types by the ``/backups/target-types`` endpoint.+ """+ return [{+ 'target_type': t,+ 'label': (entry.get('label') or t),+ 'restore_scopes': entry.get('restore_scopes'),+ 'supports_restore': bool(entry.get('restore')),+ 'source': 'extension',+ } for t, entry in sorted(_KINDS.items())]++def clear():"""Drop every registration. Tests only."""_KINDS.clear()diff --git a/backend/app/services/backup_policy_service.py b/backend/app/services/backup_policy_service.pyindex 0c310794..7a7d8d20 100644--- a/backend/app/services/backup_policy_service.py+++ b/backend/app/services/backup_policy_service.py@@ -214,25 +214,15 @@ class BackupPolicyService:keys: name, root_path, target_type, site (wp only), app, plusdb_config (database) / file_paths (files) for the non-resource targets."""- # Checked first, and before the application fallthrough at the bottom:- # an unrecognised type there is treated as an application.+ # Checked first: extension-registered kinds (plan 52 D4 — e.g.+ # 'wordpress_site' while the WordPress extension is installed) own+ # their resolution. An unrecognised type must NEVER reach the+ # application fallthrough at the bottom (it would back up the wrong+ # thing), so unknown-without-provider raises explicitly there.from app.services import backup_kind_registryif backup_kind_registry.get(policy.target_type):return backup_kind_registry.resolve(policy)- if policy.target_type == 'wordpress_site':- from app.models.wordpress_site import WordPressSite- site = WordPressSite.query.get(policy.target_id)- if not site:- raise BackupPolicyError('WordPress site not found')- app = site.application- if not app or not app.root_path:- raise BackupPolicyError('Target path not found')- return {- 'name': app.name, 'root_path': app.root_path,- 'target_type': 'wordpress_site', 'site': site, 'app': app,- }-if policy.target_type == 'database':meta = policy.get_target_meta()# Managed database: target_id is a real FK into managed_databases and@@ -304,6 +294,15 @@ class BackupPolicyService:if policy.target_type == 'server':raise BackupPolicyError('Whole-server backups are not yet implemented')+ # Anything that is not a core type and had no registered provider above+ # is a target whose extension is absent/disabled — refuse loudly with a+ # "provider missing" error rather than mis-resolving it as an app.+ if policy.target_type != 'application':+ raise BackupPolicyError(+ f"Backup target type {policy.target_type!r} has no provider: the "+ f"extension that supplies it is not installed or not active"+ )+# applicationfrom app.models.application import Applicationapp = Application.query.get(policy.target_id)@@ -381,21 +380,6 @@ class BackupPolicyService:return backup_kind_registry.execute(policy, target, kind)meta = {'engine': target['target_type']}- if target['target_type'] == 'wordpress_site':- from app.services.wordpress_bridge import wordpress_service- WordPressService = wordpress_service()- result = WordPressService.backup_wordpress(target['root_path'], include_db=True)- if not result.get('success'):- raise BackupPolicyError(result.get('error') or 'WordPress backup failed')- storage_path = result.get('backup_path')- size = result.get('size') or cls._path_size(storage_path)- meta.update({- 'kind': 'full', 'compression': 'gzip', 'incremental': False,- 'backup_name': result.get('backup_name'), 'includes': ['files', 'database'],- 'primary_archive': os.path.join(storage_path, 'files.tar.gz'),- })- return storage_path, size, meta-if target['target_type'] == 'database':from app.services.backup_service import BackupServicecfg = target['db_config']@@ -729,14 +713,20 @@ class BackupPolicyService:# Ahead of the else-branch below, which would otherwise unpack# a plugin's archive over an application directory.backup_kind_registry.restore(policy, target, run, payload)- elif target['target_type'] == 'wordpress_site':- cls._restore_wordpress(target, run, scope, payload)elif target['target_type'] == 'database':cls._restore_database(target, run)elif target['target_type'] == 'files':cls._restore_files(target, run, payload)- else:+ elif target['target_type'] == 'application':cls._restore_application(policy, target, run, scope)+ else:+ # Registered-kind restore is handled above; reaching here means+ # the target's extension is gone (provider missing) — never+ # fall through to the application restore with foreign bytes.+ raise BackupPolicyError(+ f"Cannot restore target type {target['target_type']!r}: the "+ f"extension that supplies it is not installed or not active"+ )cls._notify('restore.completed', target['name'], {'app': target['name'], 'scope': scope,@@ -769,43 +759,6 @@ class BackupPolicyService:run.set_metadata(meta)db.session.commit()- @classmethod- def _restore_wordpress(cls, target, run, scope, payload):- """Restore a WordPress backup. 'full' (and 'tables', for now) restores- files + database; 'database' imports only the SQL dump; 'files' extracts- only the file archive."""- from app.services.wordpress_bridge import wordpress_service- WordPressService = wordpress_service()- meta = run.get_metadata() or {}- backup_dir = run.storage_path- root = target['root_path']-- if scope == 'database':- db_sql = os.path.join(backup_dir or '', 'database.sql')- if not os.path.exists(db_sql):- raise BackupPolicyError('Database dump not found in this backup')- result = WordPressService.wp_cli(root, ['db', 'import', db_sql])- if not result.get('success'):- raise BackupPolicyError(result.get('error') or 'Database restore failed')- return-- if scope == 'files':- files_archive = os.path.join(backup_dir or '', 'files.tar.gz')- if not os.path.exists(files_archive):- raise BackupPolicyError('Files archive not found in this backup')- import tarfile- with tarfile.open(files_archive, 'r:gz') as tar:- tar.extractall(os.path.dirname(root.rstrip('/')) or '/', filter='data')- return-- # full (or 'tables', approximated as full until per-table is implemented)- backup_name = meta.get('backup_name') or (os.path.basename(backup_dir) if backup_dir else None)- if not backup_name:- raise BackupPolicyError('Backup archive not found')- result = WordPressService.restore_backup(backup_name, root)- if not result.get('success'):- raise BackupPolicyError(result.get('error') or 'Restore failed')-@classmethoddef _restore_database(cls, target, run):"""Restore a standalone database from its dump (mysql/postgres/etc.)."""diff --git a/frontend/src/components/backups/ProtectionPanel.jsx b/frontend/src/components/backups/ProtectionPanel.jsxindex 0176ceea..8bf53979 100644--- a/frontend/src/components/backups/ProtectionPanel.jsx+++ b/frontend/src/components/backups/ProtectionPanel.jsx@@ -41,8 +41,27 @@ export default function ProtectionPanel({ targetType, targetId, targetName, showconst [dayFilter, setDayFilter] = useState(null); // Date | nullconst [detailRun, setDetailRun] = useState(null);const [restoreRun, setRestoreRun] = useState(null);+ // Restore scopes this target type supports, from the target-types API+ // (extension-provided types declare their own — plan 52 D4). Null until+ // loaded; RestoreDrawer falls back to its built-in defaults then.+ const [restoreScopes, setRestoreScopes] = useState(null);const reloadTimers = useRef([]);+ // Fetched once per target type, not on every load() (which refires on+ // window focus) — the type catalog changes only when extensions change.+ useEffect(() => {+ let cancelled = false;+ api.getBackupTargetTypes()+ .then((res) => {+ if (cancelled) return;+ const entry = (res?.target_types || []).find(+ (t) => t.target_type === targetType);+ setRestoreScopes(entry?.restore_scopes || null);+ })+ .catch(() => { /* optional — the drawer has sane fallbacks */ });+ return () => { cancelled = true; };+ }, [targetType]);+const load = useCallback(async () => {if (!targetId) return;try {@@ -280,6 +299,7 @@ export default function ProtectionPanel({ targetType, targetId, targetName, showonConfirm={handleRestoreConfirm}targetName={targetName}targetType={targetType}+ restoreScopes={restoreScopes}showMaintenanceModeOption={showMaintenanceModeOption}/></div>diff --git a/frontend/src/components/backups/RestoreDrawer.jsx b/frontend/src/components/backups/RestoreDrawer.jsxindex 1759aee8..195e2740 100644--- a/frontend/src/components/backups/RestoreDrawer.jsx+++ b/frontend/src/components/backups/RestoreDrawer.jsx@@ -34,6 +34,16 @@ const BASE_SCOPE_OPTIONS = [{ value: 'files', label: 'Files only' },];+// Labels for provider-declared restore scopes (plan 52 D4): extension backup+// kinds tell the panel which scopes they support via /backups/target-types,+// so the drawer no longer hardcodes which type owns which scope.+const SCOPE_LABELS = {+ full: 'Full site',+ files: 'Files only',+ database: 'Database only',+ tables: 'Selected tables',+};+const RestoreDrawer = ({run,open,@@ -41,6 +51,7 @@ const RestoreDrawer = ({onConfirm,targetName,targetType,+ restoreScopes,siteTables,showMaintenanceModeOption,}) => {@@ -66,11 +77,17 @@ const RestoreDrawer = ({const isWordPress = targetType === 'wordpress_site';const hasTables = isWordPress && !!siteTables?.length;- const scopeOptions = [- ...BASE_SCOPE_OPTIONS,- ...(isWordPress ? [{ value: 'database', label: 'Database only' }] : []),- ...(hasTables ? [{ value: 'tables', label: 'Selected tables' }] : []),- ];+ // When the target-types API answered, its provider-declared scopes win;+ // otherwise keep the legacy type-name derivation as the fallback.+ const scopeOptions = Array.isArray(restoreScopes) && restoreScopes.length+ ? restoreScopes+ .filter((s) => s !== 'tables' || (siteTables?.length > 0))+ .map((s) => ({ value: s, label: SCOPE_LABELS[s] || s }))+ : [+ ...BASE_SCOPE_OPTIONS,+ ...(isWordPress ? [{ value: 'database', label: 'Database only' }] : []),+ ...(hasTables ? [{ value: 'tables', label: 'Selected tables' }] : []),+ ];const toggleTable = (t) => {setTables((prev) => (prev.includes(t) ? prev.filter((x) => x !== t) : [...prev, t]));diff --git a/frontend/src/services/api/backupProtection.js b/frontend/src/services/api/backupProtection.jsindex 837081a7..033951c0 100644--- a/frontend/src/services/api/backupProtection.js+++ b/frontend/src/services/api/backupProtection.js@@ -64,6 +64,14 @@ export async function deleteBackupRun(targetType, targetId, runId) {// protected-resource count, the activity heatmap, and the success rate all come// from these two lists rather than from the filesystem archive listing.+// Target types available right now (core set + extension-registered kinds,+// e.g. wordpress_site only while the WordPress extension is installed). The+// Protection panel / restore drawer read this instead of hardcoding type+// knowledge, so an absent extension means an absent type (plan 52 D4).+export async function getBackupTargetTypes() {+ return this.request('/backups/target-types');+}+export async function listBackupPolicies(params = {}) {const qs = new URLSearchParams(params).toString();return this.request(`/backups/policies${qs ? `?${qs}` : ''}`);