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(databases): curated engine config tuner
Juan Denis1fb7b81c3290
diff --git a/backend/app/api/db_tuner.py b/backend/app/api/db_tuner.pynew file mode 100644index 00000000..0817459e--- /dev/null+++ b/backend/app/api/db_tuner.py@@ -0,0 +1,100 @@+"""Curated DB config tuner API.++Target addressing (consistent with the databases API, which addresses Docker+databases as ``/databases/docker/<container>/...`` by container *name*):++- ``<target>`` is normally the Docker **container name**, with the engine+ passed as ``?engine=mysql|mariadb|postgresql`` (query param on GET, body+ field on POST).+- As a convenience, an all-digits ``<target>`` is treated as a **managed+ database id** (``managed_databases`` row with ``host_kind='docker'``); its+ ``container_ref``/``engine``/admin credentials are used automatically.++MySQL auth follows the existing convention: the password travels in the+``X-DB-Password`` header (never in the URL), user via ``user`` param/field.++All endpoints are admin-only; ``apply`` requires an explicit settings payload+— suggestions are never auto-applied.+"""+from flask import Blueprint, request, jsonify+from flask_jwt_extended import jwt_required++from app.middleware.rbac import admin_required+from app.services.db_config_tuner_service import DbConfigTunerService++db_tuner_bp = Blueprint('db_tuner', __name__)+++def _build_target(target, data):+ """Resolve <target> + request context into the service target dict.+ → (target_dict, None) or (None, (json, status))."""+ data = data or {}+ password = request.headers.get('X-DB-Password') or data.get('password')+ user = data.get('user') or request.args.get('user')++ if target.isdigit():+ from app.services.managed_database_service import ManagedDatabaseService+ managed = ManagedDatabaseService.get(int(target))+ if not managed:+ return None, (jsonify({'error': 'Managed database not found'}), 404)+ if managed.host_kind != 'docker' or not managed.container_ref:+ return None, (jsonify({'error': 'Managed database is not a Docker container target'}), 400)+ engine = DbConfigTunerService.normalize_engine(managed.engine)+ if not engine:+ return None, (jsonify({'error': f'Unsupported engine: {managed.engine}'}), 400)+ if not password and managed.admin_secret_encrypted:+ from app.utils.crypto import decrypt_secret_safe+ password = decrypt_secret_safe(managed.admin_secret_encrypted)+ return {+ 'container': managed.container_ref,+ 'engine': engine,+ 'user': user or managed.admin_username,+ 'password': password,+ }, None++ engine = DbConfigTunerService.normalize_engine(+ data.get('engine') or request.args.get('engine'))+ if not engine:+ return None, (jsonify({'error': 'engine is required (mysql|mariadb|postgresql)'}), 400)+ return {'container': target, 'engine': engine, 'user': user, 'password': password}, None+++@db_tuner_bp.route('/<target>/inspect', methods=['GET'])+@jwt_required()+@admin_required+def inspect_target(target):+ """Current vs RAM-aware suggested values for the curated settings."""+ resolved, err = _build_target(target, None)+ if err:+ return err+ dedicated = str(request.args.get('dedicated', '')).lower() in ('1', 'true', 'yes')+ result = DbConfigTunerService.inspect(resolved, is_dedicated=dedicated)+ return jsonify(result), 200 if 'error' not in result else 400+++@db_tuner_bp.route('/<target>/apply', methods=['POST'])+@jwt_required()+@admin_required+def apply_target(target):+ """Apply an explicit operator-chosen settings dict (restarts the engine)."""+ data = request.get_json() or {}+ if not data.get('settings'):+ return jsonify({'error': 'settings is required'}), 400+ resolved, err = _build_target(target, data)+ if err:+ return err+ result = DbConfigTunerService.apply(resolved, data['settings'])+ return jsonify(result), 200 if 'error' not in result else 400+++@db_tuner_bp.route('/<target>/rollback', methods=['POST'])+@jwt_required()+@admin_required+def rollback_target(target):+ """Restore the pre-apply config and restart the engine."""+ data = request.get_json() or {}+ resolved, err = _build_target(target, data)+ if err:+ return err+ result = DbConfigTunerService.rollback(resolved)+ return jsonify(result), 200 if 'error' not in result else 400diff --git a/backend/app/services/db_config_tuner_service.py b/backend/app/services/db_config_tuner_service.pynew file mode 100644index 00000000..2705f665--- /dev/null+++ b/backend/app/services/db_config_tuner_service.py@@ -0,0 +1,568 @@+"""Curated database config tuner — vetted engine settings with RAM-aware+suggestions, applied to Dockerised MySQL/MariaDB/PostgreSQL containers and+rolled back cleanly.++Design notes:+- The catalog (``CURATED_SETTINGS``) is deliberately tiny: only settings with+ well-known rules of thumb and a safe min/max envelope. Nothing outside the+ catalog can ever be written.+- **Never auto-applies.** ``inspect()`` only reads and computes suggestions;+ ``apply()`` requires an explicit settings payload from the operator.+- MySQL/MariaDB: writes a ServerKit-owned drop-in+ (``/etc/mysql/conf.d/serverkit-tuner.cnf``) into the container via+ ``docker cp``. PostgreSQL: uses ``ALTER SYSTEM`` (persists to+ ``postgresql.auto.conf``), with a file-level backup of that conf for+ rollback even if the engine fails to boot.+- Every previous state is kept as a timestamped backup under+ ``STATE_DIR/<engine>/<container>/`` on the panel host, so ``rollback()``+ works after a bad apply — including the "engine never came back" case.+- All shell/docker/SQL goes through small choke points (``_docker``,+ ``_exec_sql``, ``_restart``, ``_host_ram_mb``, ``_sleep``,+ ``_linux_supported``) so tests can stub them.+- Linux/Docker only, like the rest of the service layer.+"""+import logging+import json+import os+import sys+import time+from datetime import datetime++from app import paths++logger = logging.getLogger(__name__)++# Where the MySQL drop-in lives inside the container (the official mysql and+# mariadb images both include this conf.d directory by default).+MYSQL_DROPIN_PATH = '/etc/mysql/conf.d/serverkit-tuner.cnf'++DROPIN_HEADER = '# Managed by ServerKit config tuner. Do not edit by hand.'++# Engines the tuner understands. mariadb/percona are the mysql dialect.+_ENGINE_ALIASES = {'mysql': 'mysql', 'mariadb': 'mysql', 'percona': 'mysql',+ 'postgres': 'postgresql', 'postgresql': 'postgresql'}+++def _clamp(value, lo, hi):+ return max(lo, min(hi, value))+++# ── Curated catalog ──────────────────────────────────────────────────────────+# Each entry: description (one operator-friendly sentence), unit, safe min/max+# (canonical unit), type (how values parse/render), and suggest(total_ram_mb,+# is_dedicated) — standard rules of thumb, later clamped into [min, max].+#+# types: 'size_mb' memory size, canonical MB+# 'int' plain integer (e.g. connections)+# 'bool' 0/1 toggle+# 'float_s' seconds as a float+# 'int_ms' integer milliseconds+CURATED_SETTINGS = {+ 'mysql': {+ 'innodb_buffer_pool_size': {+ 'description': 'Main InnoDB data/index cache; the single most impactful MySQL memory setting.',+ 'unit': 'MB', 'type': 'size_mb', 'min': 128, 'max': 262144,+ 'suggest': lambda ram_mb, dedicated=False: ram_mb * (0.5 if dedicated else 0.25),+ },+ 'max_connections': {+ 'description': 'Maximum simultaneous client connections; each connection costs roughly 12 MB of RAM.',+ 'unit': 'connections', 'type': 'int', 'min': 25, 'max': 5000,+ 'suggest': lambda ram_mb, dedicated=False: _clamp(ram_mb // 12, 100, 1000),+ },+ 'slow_query_log': {+ 'description': 'Log queries slower than long_query_time so slow spots can actually be found.',+ 'unit': 'on/off', 'type': 'bool', 'min': 0, 'max': 1,+ 'suggest': lambda ram_mb, dedicated=False: 1,+ },+ 'long_query_time': {+ 'description': 'Seconds a query must run before it counts as slow and gets logged.',+ 'unit': 'seconds', 'type': 'float_s', 'min': 0.1, 'max': 60,+ 'suggest': lambda ram_mb, dedicated=False: 1.0,+ },+ 'tmp_table_size': {+ 'description': 'Largest in-memory temporary table before MySQL spills it to disk.',+ 'unit': 'MB', 'type': 'size_mb', 'min': 16, 'max': 1024,+ 'suggest': lambda ram_mb, dedicated=False: _clamp(ram_mb * 0.02, 32, 512),+ },+ 'max_heap_table_size': {+ 'description': 'Cap for MEMORY tables; keep it equal to tmp_table_size (the lower of the two wins).',+ 'unit': 'MB', 'type': 'size_mb', 'min': 16, 'max': 1024,+ 'suggest': lambda ram_mb, dedicated=False: _clamp(ram_mb * 0.02, 32, 512),+ },+ 'innodb_log_file_size': {+ 'description': 'Redo log size; roughly a quarter of the buffer pool smooths out write bursts.',+ 'unit': 'MB', 'type': 'size_mb', 'min': 64, 'max': 8192,+ 'suggest': lambda ram_mb, dedicated=False: ram_mb * ((0.5 if dedicated else 0.25) / 4),+ },+ },+ 'postgresql': {+ 'shared_buffers': {+ 'description': "PostgreSQL's own page cache; about a quarter of RAM is the standard starting point.",+ 'unit': 'MB', 'type': 'size_mb', 'min': 128, 'max': 16384,+ 'suggest': lambda ram_mb, dedicated=False: ram_mb * 0.25,+ },+ 'work_mem': {+ 'description': 'Memory each sort/hash operation may use — every connection can use several at once.',+ 'unit': 'MB', 'type': 'size_mb', 'min': 4, 'max': 256,+ 'suggest': lambda ram_mb, dedicated=False: _clamp(ram_mb // 64, 4, 256),+ },+ 'maintenance_work_mem': {+ 'description': 'Memory for VACUUM, CREATE INDEX and other maintenance; ~5% of RAM speeds these up a lot.',+ 'unit': 'MB', 'type': 'size_mb', 'min': 64, 'max': 2048,+ 'suggest': lambda ram_mb, dedicated=False: _clamp(ram_mb * 0.05, 64, 2048),+ },+ 'max_connections': {+ 'description': 'Maximum simultaneous client connections; prefer a pooler over a huge number here.',+ 'unit': 'connections', 'type': 'int', 'min': 25, 'max': 5000,+ 'suggest': lambda ram_mb, dedicated=False: 200 if dedicated else 100,+ },+ 'effective_cache_size': {+ 'description': 'Planner hint for total OS + database cache; not an allocation, just an estimate.',+ 'unit': 'MB', 'type': 'size_mb', 'min': 256, 'max': 786432,+ 'suggest': lambda ram_mb, dedicated=False: ram_mb * (0.75 if dedicated else 0.5),+ },+ 'log_min_duration_statement': {+ 'description': 'Log any statement running longer than this many milliseconds (the slow-query log).',+ 'unit': 'ms', 'type': 'int_ms', 'min': 100, 'max': 600000,+ 'suggest': lambda ram_mb, dedicated=False: 1000,+ },+ },+}+++class DbConfigTunerService:+ """Inspect / apply / rollback curated engine settings on DB containers."""++ # Panel-host directory holding drop-ins + timestamped rollback backups.+ STATE_DIR = os.path.join(paths.SERVERKIT_DIR, 'db-tuner')++ # ── choke points (stub these in tests) ──────────────────────────────────++ @classmethod+ def _linux_supported(cls):+ return sys.platform.startswith('linux')++ @classmethod+ def _docker(cls, args, timeout=60):+ """Run a docker CLI command. Single shell choke point."""+ import subprocess+ try:+ result = subprocess.run(['docker'] + list(args),+ capture_output=True, text=True, timeout=timeout)+ return {+ 'success': result.returncode == 0,+ 'output': result.stdout,+ 'error': (result.stderr.strip() or 'docker command failed')+ if result.returncode != 0 else None,+ }+ except Exception as e:+ return {'success': False, 'output': '', 'error': str(e)}++ @classmethod+ def _exec_sql(cls, target, sql):+ """Run SQL inside the target's container. Single SQL choke point.++ ``target``: {'container', 'engine', 'user', 'password'}.+ Returns {'success', 'output', 'error'} with machine-readable output+ (tab-separated, no headers/decorations).+ """+ args = ['exec']+ if target['engine'] == 'mysql':+ if target.get('password'):+ args += ['-e', 'MYSQL_PWD=%s' % target['password']]+ args += [target['container'], 'mysql', '-u', target.get('user') or 'root',+ '-N', '-B', '-e', sql]+ else:+ args += [target['container'], 'psql', '-U', target.get('user') or 'postgres',+ '-t', '-A', '-F', '\t', '-c', sql]+ return cls._docker(args, timeout=30)++ @classmethod+ def _restart(cls, container):+ """Restart the container via the existing DockerService path."""+ from app.services.docker_service import DockerService+ return DockerService.restart_container(container)++ @classmethod+ def _host_ram_mb(cls):+ import psutil+ return int(psutil.virtual_memory().total / (1024 * 1024))++ @classmethod+ def _sleep(cls, seconds):+ time.sleep(seconds)++ # ── helpers ──────────────────────────────────────────────────────────────++ @staticmethod+ def normalize_engine(engine):+ return _ENGINE_ALIASES.get((engine or '').strip().lower())++ @classmethod+ def _guard(cls, target):+ """Common precondition check → error string or None."""+ if not cls._linux_supported():+ return 'The config tuner is only available on Linux hosts running Docker'+ if not target.get('container'):+ return 'A Docker container target is required'+ if target.get('engine') not in CURATED_SETTINGS:+ return 'engine must be mysql or postgresql'+ return None++ @classmethod+ def _ram_mb(cls, container):+ """Container memory limit if set, else host RAM. → (mb, source)."""+ res = cls._docker(['inspect', '--format', '{{.HostConfig.Memory}}', container],+ timeout=15)+ if res['success']:+ try:+ limit = int(res['output'].strip())+ if limit > 0:+ return int(limit / (1024 * 1024)), 'container_limit'+ except ValueError:+ pass+ return cls._host_ram_mb(), 'host_total'++ @classmethod+ def suggest_value(cls, engine, key, total_ram_mb, is_dedicated=False):+ """Suggested value for a catalog key, clamped into its safe range."""+ entry = CURATED_SETTINGS[engine][key]+ value = _clamp(entry['suggest'](total_ram_mb, is_dedicated),+ entry['min'], entry['max'])+ if entry['type'] == 'float_s':+ return round(float(value), 2)+ return int(round(value))++ @classmethod+ def validate_settings(cls, engine, settings):+ """Only curated keys, only values inside the safe envelope.+ → error string or None; also coerces values in place."""+ if not isinstance(settings, dict) or not settings:+ return 'settings must be a non-empty object of {key: value}'+ catalog = CURATED_SETTINGS[engine]+ for key, value in list(settings.items()):+ entry = catalog.get(key)+ if entry is None:+ return f"'{key}' is not a tunable setting for {engine}"+ try:+ value = float(value)+ except (TypeError, ValueError):+ return f"'{key}' must be a number"+ if value < entry['min'] or value > entry['max']:+ return (f"'{key}' must be between {entry['min']} and "+ f"{entry['max']} {entry['unit']}")+ settings[key] = round(value, 2) if entry['type'] == 'float_s' else int(value)+ return None++ # ── current-value parsing ────────────────────────────────────────────────++ @staticmethod+ def _mysql_to_canonical(entry, raw):+ raw = (raw or '').strip()+ if entry['type'] == 'size_mb':+ return round(float(raw) / (1024 * 1024), 2) # SHOW VARIABLES → bytes+ if entry['type'] == 'bool':+ return 1 if raw.upper() in ('ON', '1', 'TRUE') else 0+ if entry['type'] == 'float_s':+ return round(float(raw), 2)+ return int(float(raw))++ @staticmethod+ def _pg_to_canonical(entry, setting, unit):+ value = float(setting)+ unit = (unit or '').strip()+ if entry['type'] == 'size_mb':+ factor = {'8kB': 8.0 / 1024, 'kB': 1.0 / 1024, 'MB': 1.0,+ 'GB': 1024.0, 'B': 1.0 / (1024 * 1024)}.get(unit, 1.0)+ return round(value * factor, 2)+ if entry['type'] == 'int_ms':+ factor = {'s': 1000, 'min': 60000}.get(unit, 1)+ return int(value * factor)+ return int(value)++ @classmethod+ def _read_current(cls, target):+ """Live current values from the engine. → (dict|None, error|None)."""+ engine = target['engine']+ keys = sorted(CURATED_SETTINGS[engine])+ quoted = ', '.join("'%s'" % k for k in keys)+ if engine == 'mysql':+ sql = f'SHOW VARIABLES WHERE Variable_name IN ({quoted});'+ else:+ sql = f'SELECT name, setting, unit FROM pg_settings WHERE name IN ({quoted});'+ res = cls._exec_sql(target, sql)+ if not res['success']:+ return None, res.get('error') or 'Could not query the database engine'++ current = {}+ for line in (res['output'] or '').strip().splitlines():+ parts = line.rstrip('\n').split('\t')+ if not parts or parts[0] in ('Variable_name', 'name'):+ continue # tolerate a header row+ key = parts[0].strip()+ entry = CURATED_SETTINGS[engine].get(key)+ if entry is None:+ continue+ try:+ if engine == 'mysql':+ current[key] = cls._mysql_to_canonical(entry, parts[1])+ else:+ unit = parts[2] if len(parts) > 2 else ''+ current[key] = cls._pg_to_canonical(entry, parts[1], unit)+ except (IndexError, ValueError):+ logger.debug('Unparseable current value for %s: %r', key, line)+ return current, None++ # ── rendering ────────────────────────────────────────────────────────────++ @classmethod+ def render_mysql_dropin(cls, settings):+ """The serverkit-tuner.cnf content for a validated settings dict."""+ lines = [DROPIN_HEADER, '[mysqld]']+ catalog = CURATED_SETTINGS['mysql']+ for key in sorted(settings):+ entry = catalog[key]+ value = settings[key]+ if entry['type'] == 'size_mb':+ rendered = f'{int(value)}M'+ elif entry['type'] == 'bool':+ rendered = str(1 if value else 0)+ elif entry['type'] == 'float_s':+ rendered = str(round(float(value), 2))+ else:+ rendered = str(int(value))+ lines.append(f'{key} = {rendered}')+ return '\n'.join(lines) + '\n'++ @staticmethod+ def _pg_literal(entry, value):+ if entry['type'] == 'size_mb':+ return f"'{int(value)}MB'"+ if entry['type'] == 'bool':+ return 'on' if value else 'off'+ if entry['type'] == 'float_s':+ return str(round(float(value), 2))+ return str(int(value))++ # ── backup bookkeeping (panel host) ─────────────────────────────────────++ @classmethod+ def _state_dir(cls, target, create=False):+ d = os.path.join(cls.STATE_DIR, target['engine'], target['container'])+ if create:+ os.makedirs(d, exist_ok=True)+ return d++ @classmethod+ def _latest_backup(cls, target):+ """Newest previous-* backup file path, or None."""+ d = cls._state_dir(target)+ if not os.path.isdir(d):+ return None+ backups = sorted(f for f in os.listdir(d) if f.startswith('previous-'))+ return os.path.join(d, backups[-1]) if backups else None++ @classmethod+ def _snapshot_container_file(cls, target, container_path, suffix):+ """Copy a file out of the container as a timestamped backup. If the+ file doesn't exist yet, record an ``.absent`` marker so rollback knows+ to delete rather than restore. → backup path."""+ d = cls._state_dir(target, create=True)+ stamp = datetime.utcnow().strftime('%Y%m%d%H%M%S')+ backup = os.path.join(d, f'previous-{stamp}{suffix}')+ res = cls._docker(['cp', f"{target['container']}:{container_path}", backup],+ timeout=30)+ if not res['success']:+ backup = os.path.join(d, f'previous-{stamp}.absent')+ with open(backup, 'w') as fh:+ fh.write(container_path + '\n')+ return backup++ @classmethod+ def _restore_container_file(cls, target, backup, container_path):+ """Put a backup back into the container (or delete the file if the+ backup is an absence marker). → {'success', 'error'}."""+ if backup.endswith('.absent'):+ return cls._docker(['exec', target['container'], 'rm', '-f', container_path],+ timeout=30)+ return cls._docker(['cp', backup, f"{target['container']}:{container_path}"],+ timeout=30)++ # ── engine liveness ──────────────────────────────────────────────────────++ @classmethod+ def _wait_ready(cls, target, attempts=10, delay=2):+ """Simple ping loop (SELECT 1) after a restart."""+ for i in range(attempts):+ if i:+ cls._sleep(delay)+ if cls._exec_sql(target, 'SELECT 1;')['success']:+ return True+ return False++ # ── public API ───────────────────────────────────────────────────────────++ @classmethod+ def inspect(cls, target, is_dedicated=False):+ """Current vs suggested for every curated setting. Read-only —+ suggestions are NEVER applied automatically."""+ err = cls._guard(target)+ if err:+ return {'error': err}++ current, err = cls._read_current(target)+ if err:+ return {'error': err}++ engine = target['engine']+ ram_mb, ram_source = cls._ram_mb(target['container'])++ settings, diff = [], []+ for key in sorted(CURATED_SETTINGS[engine]):+ entry = CURATED_SETTINGS[engine][key]+ suggested = cls.suggest_value(engine, key, ram_mb, is_dedicated)+ cur = current.get(key)+ differs = cur is not None and float(cur) != float(suggested)+ if differs:+ diff.append(key)+ settings.append({+ 'key': key,+ 'description': entry['description'],+ 'unit': entry['unit'],+ 'min': entry['min'],+ 'max': entry['max'],+ 'current': cur,+ 'suggested': suggested,+ 'differs': differs,+ })++ return {+ 'engine': engine,+ 'container': target['container'],+ 'ram_mb': ram_mb,+ 'ram_source': ram_source,+ 'is_dedicated': bool(is_dedicated),+ 'settings': settings,+ 'diff': diff,+ 'can_rollback': cls._latest_backup(target) is not None,+ }++ @classmethod+ def apply(cls, target, settings):+ """Apply an explicit, operator-chosen settings dict. Backs up the+ previous state, restarts the container, verifies the engine came back,+ and rolls back automatically if it didn't."""+ err = cls._guard(target)+ if err:+ return {'error': err}+ settings = dict(settings or {})+ err = cls.validate_settings(target['engine'], settings)+ if err:+ return {'error': err}++ if target['engine'] == 'mysql':+ return cls._apply_mysql(target, settings)+ return cls._apply_postgresql(target, settings)++ @classmethod+ def _apply_mysql(cls, target, settings):+ container = target['container']+ backup = cls._snapshot_container_file(target, MYSQL_DROPIN_PATH, '.cnf')++ # Stage the new drop-in on the panel host, then copy it in.+ d = cls._state_dir(target, create=True)+ staged = os.path.join(d, 'serverkit-tuner.cnf')+ with open(staged, 'w') as fh:+ fh.write(cls.render_mysql_dropin(settings))+ res = cls._docker(['cp', staged, f'{container}:{MYSQL_DROPIN_PATH}'], timeout=30)+ if not res['success']:+ return {'error': f"Could not write the drop-in into the container: {res['error']}"}++ return cls._restart_and_verify(target, backup, MYSQL_DROPIN_PATH, settings)++ @classmethod+ def _apply_postgresql(cls, target, settings):+ # Find postgresql.auto.conf (what ALTER SYSTEM writes) for file-level+ # rollback even when the engine won't boot back up.+ res = cls._exec_sql(target, 'SHOW data_directory;')+ if not res['success']:+ return {'error': res.get('error') or 'Could not determine the data directory'}+ data_dir = (res['output'] or '').strip().splitlines()+ data_dir = data_dir[0].strip() if data_dir else ''+ if not data_dir:+ return {'error': 'Could not determine the data directory'}+ auto_conf = data_dir.rstrip('/') + '/postgresql.auto.conf'++ backup = cls._snapshot_container_file(target, auto_conf, '.auto.conf')++ catalog = CURATED_SETTINGS['postgresql']+ for key in sorted(settings):+ literal = cls._pg_literal(catalog[key], settings[key])+ res = cls._exec_sql(target, f'ALTER SYSTEM SET {key} = {literal};')+ if not res['success']:+ # Nothing took effect yet (needs a restart) — restore the conf+ # so no partial ALTERs linger, and bail.+ cls._restore_container_file(target, backup, auto_conf)+ return {'error': f"ALTER SYSTEM failed for '{key}': {res['error']}"}++ # Remember where auto.conf lives so rollback works without SQL.+ with open(os.path.join(cls._state_dir(target, create=True), 'applied.json'), 'w') as fh:+ json.dump({'auto_conf': auto_conf, 'settings': settings}, fh)++ return cls._restart_and_verify(target, backup, auto_conf, settings)++ @classmethod+ def _restart_and_verify(cls, target, backup, container_path, settings):+ """Shared apply tail: restart, ping, roll back on failure."""+ container = target['container']+ res = cls._restart(container)+ if not res.get('success'):+ cls._restore_container_file(target, backup, container_path)+ return {'error': f"Container restart failed: {res.get('error')}; previous config restored"}++ if not cls._wait_ready(target):+ cls._restore_container_file(target, backup, container_path)+ cls._restart(container)+ cls._wait_ready(target)+ return {'error': 'Engine did not come back after the restart; '+ 'previous config restored and container restarted again'}++ return {'success': True, 'applied': settings, 'restarted': True,+ 'backup': os.path.basename(backup)}++ @classmethod+ def rollback(cls, target):+ """Restore the most recent pre-apply config and restart the engine."""+ err = cls._guard(target)+ if err:+ return {'error': err}+ backup = cls._latest_backup(target)+ if not backup:+ return {'error': 'No previous configuration to roll back to'}++ if target['engine'] == 'mysql':+ container_path = MYSQL_DROPIN_PATH+ else:+ applied = os.path.join(cls._state_dir(target), 'applied.json')+ try:+ with open(applied) as fh:+ container_path = json.load(fh)['auto_conf']+ except (OSError, ValueError, KeyError):+ return {'error': 'Rollback metadata is missing; cannot locate postgresql.auto.conf'}++ res = cls._restore_container_file(target, backup, container_path)+ if not res['success']:+ return {'error': f"Could not restore the previous config: {res['error']}"}++ restart = cls._restart(target['container'])+ if not restart.get('success'):+ return {'error': f"Config restored but the restart failed: {restart.get('error')}"}+ if not cls._wait_ready(target):+ return {'error': 'Config restored but the engine did not come back; check the container logs'}++ # Consume the backup so can_rollback reflects reality.+ try:+ os.remove(backup)+ except OSError:+ pass+ return {'success': True, 'restored': os.path.basename(backup), 'restarted': True}diff --git a/backend/tests/test_db_config_tuner.py b/backend/tests/test_db_config_tuner.pynew file mode 100644index 00000000..d2cf19ba--- /dev/null+++ b/backend/tests/test_db_config_tuner.py@@ -0,0 +1,371 @@+"""Curated DB config tuner — suggestion formulas, validation, drop-in+rendering, apply/rollback flow (docker + fs stubbed), inspect parsing."""+import os++import pytest++from app.services.db_config_tuner_service import (+ CURATED_SETTINGS, MYSQL_DROPIN_PATH, DbConfigTunerService as S,+)+++MYSQL_TARGET = {'container': 'app-db-1', 'engine': 'mysql', 'user': 'root', 'password': 'pw'}+PG_TARGET = {'container': 'app-pg-1', 'engine': 'postgresql', 'user': 'postgres', 'password': None}+++def tuner(tmp_path, monkeypatch):+ """Stub every choke point; record calls. Returns a mutable control dict."""+ ctl = {+ 'docker_calls': [],+ 'sql_calls': [],+ 'restarts': [],+ 'sql': lambda target, sql: {'success': True, 'output': '1\n', 'error': None},+ 'docker': lambda args: {'success': True, 'output': '', 'error': None},+ 'restart_ok': True,+ }+ monkeypatch.setattr(S, 'STATE_DIR', str(tmp_path))+ monkeypatch.setattr(S, '_linux_supported', classmethod(lambda cls: True))+ monkeypatch.setattr(S, '_sleep', classmethod(lambda cls, s: None))+ monkeypatch.setattr(S, '_host_ram_mb', classmethod(lambda cls: 8192))++ def fake_docker(cls, args, timeout=60):+ ctl['docker_calls'].append(list(args))+ return ctl['docker'](list(args))++ def fake_sql(cls, target, sql):+ ctl['sql_calls'].append(sql)+ return ctl['sql'](target, sql)++ def fake_restart(cls, container):+ ctl['restarts'].append(container)+ return {'success': ctl['restart_ok']}++ monkeypatch.setattr(S, '_docker', classmethod(fake_docker))+ monkeypatch.setattr(S, '_exec_sql', classmethod(fake_sql))+ monkeypatch.setattr(S, '_restart', classmethod(fake_restart))+ return ctl+++# ── suggestion formulas (deterministic RAM inputs) ──────────────────────────++def test_mysql_suggestions_8g_shared():+ assert S.suggest_value('mysql', 'innodb_buffer_pool_size', 8192) == 2048 # 25%+ assert S.suggest_value('mysql', 'max_connections', 8192) == 682 # ram/12+ assert S.suggest_value('mysql', 'slow_query_log', 8192) == 1+ assert S.suggest_value('mysql', 'long_query_time', 8192) == 1.0+ assert S.suggest_value('mysql', 'tmp_table_size', 8192) == 164 # 2%+ assert S.suggest_value('mysql', 'max_heap_table_size', 8192) == 164+ assert S.suggest_value('mysql', 'innodb_log_file_size', 8192) == 512 # pool/4+++def test_mysql_suggestions_dedicated_doubles_pool():+ assert S.suggest_value('mysql', 'innodb_buffer_pool_size', 8192, is_dedicated=True) == 4096+ assert S.suggest_value('mysql', 'innodb_log_file_size', 8192, is_dedicated=True) == 1024+++def test_pg_suggestions_8g():+ assert S.suggest_value('postgresql', 'shared_buffers', 8192) == 2048 # 25%+ assert S.suggest_value('postgresql', 'work_mem', 8192) == 128 # ram/64+ assert S.suggest_value('postgresql', 'maintenance_work_mem', 8192) == 410 # 5%+ assert S.suggest_value('postgresql', 'max_connections', 8192) == 100+ assert S.suggest_value('postgresql', 'max_connections', 8192, is_dedicated=True) == 200+ assert S.suggest_value('postgresql', 'effective_cache_size', 8192) == 4096 # 50%+ assert S.suggest_value('postgresql', 'effective_cache_size', 8192, is_dedicated=True) == 6144+ assert S.suggest_value('postgresql', 'log_min_duration_statement', 8192) == 1000+++def test_suggestions_clamped_to_safe_range():+ # Tiny box: 25% of 256MB would be 64MB — below shared_buffers' 128MB floor.+ assert S.suggest_value('postgresql', 'shared_buffers', 256) == 128+ # Monster box: pg shared_buffers capped at 16GB.+ assert S.suggest_value('postgresql', 'shared_buffers', 1024 * 1024) == 16384+ assert S.suggest_value('mysql', 'innodb_buffer_pool_size', 256) == 128+++# ── validation ───────────────────────────────────────────────────────────────++def test_validate_rejects_unknown_key():+ err = S.validate_settings('mysql', {'innodb_evil_flag': 1})+ assert err and 'innodb_evil_flag' in err+++def test_validate_rejects_out_of_range():+ err = S.validate_settings('mysql', {'max_connections': 999999})+ assert err and 'max_connections' in err+ err = S.validate_settings('postgresql', {'work_mem': 1})+ assert err and 'work_mem' in err+++def test_validate_rejects_non_numeric_and_empty():+ assert S.validate_settings('mysql', {'max_connections': 'lots'})+ assert S.validate_settings('mysql', {})+ assert S.validate_settings('mysql', None)+++def test_validate_accepts_and_coerces():+ settings = {'max_connections': '500', 'long_query_time': 2.5}+ assert S.validate_settings('mysql', settings) is None+ assert settings['max_connections'] == 500+ assert settings['long_query_time'] == 2.5+++def test_apply_surfaces_validation_error(tuner):+ result = S.apply(MYSQL_TARGET, {'not_a_setting': 1})+ assert 'error' in result and 'not_a_setting' in result['error']+ result = S.apply(MYSQL_TARGET, {'innodb_buffer_pool_size': 1}) # below 128MB floor+ assert 'error' in result+++# ── drop-in rendering ────────────────────────────────────────────────────────++def test_render_mysql_dropin_content():+ content = S.render_mysql_dropin({+ 'innodb_buffer_pool_size': 2048,+ 'slow_query_log': 1,+ 'long_query_time': 1.0,+ 'max_connections': 300,+ })+ assert content.startswith('# Managed by ServerKit')+ assert '[mysqld]' in content+ assert 'innodb_buffer_pool_size = 2048M' in content # MB → M suffix+ assert 'slow_query_log = 1' in content+ assert 'long_query_time = 1.0' in content+ assert 'max_connections = 300' in content+ assert content.endswith('\n')+++def test_pg_literals():+ cat = CURATED_SETTINGS['postgresql']+ assert S._pg_literal(cat['shared_buffers'], 2048) == "'2048MB'"+ assert S._pg_literal(cat['max_connections'], 200) == '200'+ assert S._pg_literal(cat['log_min_duration_statement'], 1000) == '1000'+++# ── inspect parsing ──────────────────────────────────────────────────────────++def test_inspect_mysql_parses_show_variables(tuner):+ output = (+ 'innodb_buffer_pool_size\t134217728\n' # 128MB in bytes+ 'innodb_log_file_size\t50331648\n' # 48MB+ 'long_query_time\t10.000000\n'+ 'max_connections\t151\n'+ 'max_heap_table_size\t16777216\n'+ 'slow_query_log\tOFF\n'+ 'tmp_table_size\t16777216\n'+ )+ tuner['sql'] = lambda t, sql: {'success': True, 'output': output, 'error': None}+ # No container memory limit → falls back to host RAM (stubbed 8192).+ tuner['docker'] = lambda args: {'success': True, 'output': '0\n', 'error': None}++ result = S.inspect(MYSQL_TARGET)+ assert result['engine'] == 'mysql'+ assert result['ram_mb'] == 8192 and result['ram_source'] == 'host_total'+ rows = {r['key']: r for r in result['settings']}+ assert rows['innodb_buffer_pool_size']['current'] == 128+ assert rows['innodb_buffer_pool_size']['suggested'] == 2048+ assert rows['innodb_buffer_pool_size']['differs'] is True+ assert rows['slow_query_log']['current'] == 0+ assert rows['long_query_time']['current'] == 10.0+ assert rows['max_connections']['current'] == 151+ assert 'innodb_buffer_pool_size' in result['diff']+ assert result['can_rollback'] is False+++def test_inspect_pg_parses_pg_settings_units(tuner):+ output = (+ 'effective_cache_size\t524288\t8kB\n' # 4096 MB+ 'log_min_duration_statement\t-1\tms\n'+ 'maintenance_work_mem\t65536\tkB\n' # 64 MB+ 'max_connections\t100\t\n'+ 'shared_buffers\t16384\t8kB\n' # 128 MB+ 'work_mem\t4096\tkB\n' # 4 MB+ )+ tuner['sql'] = lambda t, sql: {'success': True, 'output': output, 'error': None}+ # Container has a 4GB memory limit.+ tuner['docker'] = lambda args: {'success': True, 'output': str(4 * 1024 ** 3) + '\n',+ 'error': None}++ result = S.inspect(PG_TARGET)+ assert result['ram_mb'] == 4096 and result['ram_source'] == 'container_limit'+ rows = {r['key']: r for r in result['settings']}+ assert rows['shared_buffers']['current'] == 128+ assert rows['shared_buffers']['suggested'] == 1024 # 25% of 4096+ assert rows['effective_cache_size']['current'] == 4096+ assert rows['maintenance_work_mem']['current'] == 64+ assert rows['work_mem']['current'] == 4+ assert rows['max_connections']['current'] == 100+ assert rows['max_connections']['differs'] is False+++def test_inspect_engine_query_failure_is_clean_error(tuner):+ tuner['sql'] = lambda t, sql: {'success': False, 'output': '', 'error': 'access denied'}+ result = S.inspect(MYSQL_TARGET)+ assert result == {'error': 'access denied'}+++def test_non_linux_is_clean_error(tuner, monkeypatch):+ monkeypatch.setattr(S, '_linux_supported', classmethod(lambda cls: False))+ assert 'error' in S.inspect(MYSQL_TARGET)+ assert 'error' in S.apply(MYSQL_TARGET, {'max_connections': 300})+ assert 'error' in S.rollback(MYSQL_TARGET)+++# ── apply / rollback flow (mysql) ────────────────────────────────────────────++def _mysql_docker_stub(ctl, existing_dropin=None):+ """docker stub that emulates cp-out (existing drop-in or absent) and+ accepts cp-in / exec rm."""+ def docker(args):+ if args[0] == 'cp' and args[1].startswith('app-db-1:'):+ if existing_dropin is None:+ return {'success': False, 'output': '', 'error': 'no such file'}+ with open(args[2], 'w') as fh:+ fh.write(existing_dropin)+ return {'success': True, 'output': '', 'error': None}+ return {'success': True, 'output': '', 'error': None}+ ctl['docker'] = docker+++def test_apply_mysql_happy_path(tuner, tmp_path):+ _mysql_docker_stub(tuner, existing_dropin='[mysqld]\nmax_connections = 100\n')+ result = S.apply(MYSQL_TARGET, {'max_connections': 300, 'slow_query_log': 1})++ assert result.get('success') is True+ assert result['applied'] == {'max_connections': 300, 'slow_query_log': 1}+ assert tuner['restarts'] == ['app-db-1']++ # Timestamped backup of the previous drop-in was kept on the panel host.+ state = tmp_path / 'mysql' / 'app-db-1'+ backups = [f for f in os.listdir(state) if f.startswith('previous-') and f.endswith('.cnf')]+ assert len(backups) == 1+ assert (state / backups[0]).read_text() == '[mysqld]\nmax_connections = 100\n'++ # The staged drop-in was rendered and docker cp'd into the container.+ staged = state / 'serverkit-tuner.cnf'+ assert 'max_connections = 300' in staged.read_text()+ assert ['cp', str(staged), f'app-db-1:{MYSQL_DROPIN_PATH}'] in tuner['docker_calls']++ # And inspect now offers a rollback.+ assert S._latest_backup(MYSQL_TARGET) is not None+++def test_apply_mysql_first_time_records_absent_marker(tuner, tmp_path):+ _mysql_docker_stub(tuner, existing_dropin=None)+ result = S.apply(MYSQL_TARGET, {'max_connections': 300})+ assert result.get('success') is True+ state = tmp_path / 'mysql' / 'app-db-1'+ assert any(f.endswith('.absent') for f in os.listdir(state))+++def test_apply_mysql_ping_failure_rolls_back(tuner):+ _mysql_docker_stub(tuner, existing_dropin='[mysqld]\nold = 1\n')+ tuner['sql'] = lambda t, sql: {'success': False, 'output': '', 'error': 'down'}++ result = S.apply(MYSQL_TARGET, {'max_connections': 300})+ assert 'error' in result and 'restored' in result['error']+ # Restarted twice: once for the apply, once after restoring the backup.+ assert tuner['restarts'] == ['app-db-1', 'app-db-1']+ # The backup was cp'd back into the container.+ restore_calls = [c for c in tuner['docker_calls']+ if c[0] == 'cp' and c[2] == f'app-db-1:{MYSQL_DROPIN_PATH}'+ and 'previous-' in c[1]]+ assert restore_calls+++def test_apply_mysql_restart_failure_restores_file(tuner):+ _mysql_docker_stub(tuner, existing_dropin='[mysqld]\nold = 1\n')+ tuner['restart_ok'] = False+ result = S.apply(MYSQL_TARGET, {'max_connections': 300})+ assert 'error' in result and 'restored' in result['error']+++def test_rollback_mysql_restores_and_consumes_backup(tuner):+ _mysql_docker_stub(tuner, existing_dropin='[mysqld]\nold = 1\n')+ assert S.apply(MYSQL_TARGET, {'max_connections': 300}).get('success')+ tuner['restarts'].clear()++ result = S.rollback(MYSQL_TARGET)+ assert result.get('success') is True+ assert tuner['restarts'] == ['app-db-1']+ # Backup consumed — nothing further to roll back to.+ assert S._latest_backup(MYSQL_TARGET) is None+ assert 'error' in S.rollback(MYSQL_TARGET)+++def test_rollback_mysql_absent_marker_deletes_dropin(tuner):+ _mysql_docker_stub(tuner, existing_dropin=None)+ assert S.apply(MYSQL_TARGET, {'max_connections': 300}).get('success')++ result = S.rollback(MYSQL_TARGET)+ assert result.get('success') is True+ assert ['exec', 'app-db-1', 'rm', '-f', MYSQL_DROPIN_PATH] in tuner['docker_calls']+++def test_rollback_without_backup_is_clean_error(tuner):+ assert 'error' in S.rollback(MYSQL_TARGET)+++# ── apply / rollback flow (postgresql) ───────────────────────────────────────++def _pg_sql_stub(ctl, alter_ok=True):+ def sql(target, statement):+ if statement.startswith('SHOW data_directory'):+ return {'success': True, 'output': '/var/lib/postgresql/data\n', 'error': None}+ if statement.startswith('ALTER SYSTEM'):+ return {'success': alter_ok, 'output': '',+ 'error': None if alter_ok else 'permission denied'}+ return {'success': True, 'output': '1\n', 'error': None}+ ctl['sql'] = sql+++def test_apply_pg_happy_path(tuner, tmp_path):+ _pg_sql_stub(tuner)++ def docker(args):+ if args[0] == 'cp' and args[1].startswith('app-pg-1:'):+ with open(args[2], 'w') as fh:+ fh.write("shared_buffers = '128MB'\n")+ return {'success': True, 'output': '', 'error': None}+ return {'success': True, 'output': '', 'error': None}+ tuner['docker'] = docker++ result = S.apply(PG_TARGET, {'shared_buffers': 1024, 'max_connections': 200})+ assert result.get('success') is True+ assert tuner['restarts'] == ['app-pg-1']+ # ALTER SYSTEM per key, size rendered with MB unit.+ alters = [s for s in tuner['sql_calls'] if s.startswith('ALTER SYSTEM')]+ assert "ALTER SYSTEM SET shared_buffers = '1024MB';" in alters+ assert 'ALTER SYSTEM SET max_connections = 200;' in alters+ # auto.conf backed up + metadata saved for SQL-free rollback.+ state = tmp_path / 'postgresql' / 'app-pg-1'+ assert any(f.endswith('.auto.conf') for f in os.listdir(state))+ assert (state / 'applied.json').exists()+++def test_apply_pg_alter_failure_restores_conf_without_restart(tuner):+ _pg_sql_stub(tuner, alter_ok=False)+ result = S.apply(PG_TARGET, {'shared_buffers': 1024})+ assert 'error' in result and 'ALTER SYSTEM' in result['error']+ assert tuner['restarts'] == [] # nothing took effect, no restart+++def test_rollback_pg_uses_saved_auto_conf_path(tuner):+ _pg_sql_stub(tuner)++ def docker(args):+ if args[0] == 'cp' and args[1].startswith('app-pg-1:'):+ with open(args[2], 'w') as fh:+ fh.write("shared_buffers = '128MB'\n")+ return {'success': True, 'output': '', 'error': None}+ tuner['docker'] = docker++ assert S.apply(PG_TARGET, {'shared_buffers': 1024}).get('success')+ tuner['docker_calls'].clear()++ result = S.rollback(PG_TARGET)+ assert result.get('success') is True+ restore = [c for c in tuner['docker_calls']+ if c[0] in ('cp', 'exec') and+ 'postgresql.auto.conf' in ' '.join(c)]+ assert restorediff --git a/frontend/src/components/databases/ConfigTunerPanel.jsx b/frontend/src/components/databases/ConfigTunerPanel.jsxnew file mode 100644index 00000000..4c12841a--- /dev/null+++ b/frontend/src/components/databases/ConfigTunerPanel.jsx@@ -0,0 +1,212 @@+import { useState, useEffect, useCallback } from 'react';+import { RefreshCw, Undo2, Wand2 } from 'lucide-react';+import api from '../../services/api';+import { useToast } from '../../contexts/ToastContext';+import { useConfirm } from '../../hooks/useConfirm';+import { Button } from '@/components/ui/button';++// Curated config tuner: a small set of vetted engine settings with RAM-aware+// suggested values. Shows current vs suggested; the operator picks which+// settings to apply — nothing is ever applied automatically. Applying writes+// a ServerKit-owned config drop-in and restarts the DB container; a backup of+// the previous config is kept so it can be rolled back cleanly.+//+// Props:+// target — Docker container name (or managed database id as a string)+// engine — 'mysql' | 'mariadb' | 'postgresql' (optional for managed ids)+// user — DB admin user (optional)+// password — DB admin password, sent via X-DB-Password (optional)+export default function ConfigTunerPanel({ target, engine, user, password }) {+ const toast = useToast();+ const { confirm } = useConfirm();+ const [data, setData] = useState(null);+ const [error, setError] = useState(null);+ const [loading, setLoading] = useState(true);+ const [busy, setBusy] = useState(false);+ const [dedicated, setDedicated] = useState(false);+ const [selected, setSelected] = useState({}); // key -> bool+ const [values, setValues] = useState({}); // key -> edited target value++ const load = useCallback(async (isDedicated) => {+ setLoading(true);+ setError(null);+ try {+ const res = await api.inspectDbTuner(target, {+ engine, user, password, dedicated: isDedicated,+ });+ setData(res);+ const next = {};+ (res?.settings || []).forEach((s) => { next[s.key] = s.suggested; });+ setValues(next);+ setSelected({});+ } catch (err) {+ setError(err.message || 'Failed to inspect the database configuration');+ } finally {+ setLoading(false);+ }+ }, [target, engine, user, password]);++ useEffect(() => { load(dedicated); }, [load, dedicated]);++ function clampValue(setting, raw) {+ const num = Number(raw);+ if (Number.isNaN(num)) return setting.suggested;+ return Math.min(setting.max, Math.max(setting.min, num));+ }++ function setValue(key, raw) {+ setValues((prev) => ({ ...prev, [key]: raw }));+ }++ function commitValue(setting) {+ setValues((prev) => ({ ...prev, [setting.key]: clampValue(setting, prev[setting.key]) }));+ }++ function toggle(key) {+ setSelected((prev) => ({ ...prev, [key]: !prev[key] }));+ }++ const selectedKeys = Object.keys(selected).filter((k) => selected[k]);++ async function applySelected() {+ if (!selectedKeys.length) return;+ const ok = await confirm({+ title: `Apply ${selectedKeys.length} setting${selectedKeys.length === 1 ? '' : 's'}?`,+ message: 'Applying restarts the database engine — connected apps will see a short '+ + 'interruption. The previous configuration is backed up and can be rolled back.',+ confirmText: 'Apply and restart',+ danger: true,+ });+ if (!ok) return;+ setBusy(true);+ try {+ const settings = {};+ selectedKeys.forEach((k) => {+ const setting = data.settings.find((s) => s.key === k);+ settings[k] = clampValue(setting, values[k]);+ });+ await api.applyDbTunerSettings(target, settings, { engine, user, password });+ toast.success('Settings applied and engine restarted');+ await load(dedicated);+ } catch (err) {+ toast.error(err.message || 'Failed to apply settings');+ } finally {+ setBusy(false);+ }+ }++ async function rollback() {+ const ok = await confirm({+ title: 'Roll back to the previous configuration?',+ message: 'The last backed-up configuration is restored and the database engine '+ + 'is restarted.',+ confirmText: 'Roll back and restart',+ danger: true,+ });+ if (!ok) return;+ setBusy(true);+ try {+ await api.rollbackDbTuner(target, { engine, user, password });+ toast.success('Previous configuration restored');+ await load(dedicated);+ } catch (err) {+ toast.error(err.message || 'Rollback failed');+ } finally {+ setBusy(false);+ }+ }++ if (loading) return <p className="db-tuner__hint">Reading engine configuration…</p>;+ if (error) return <p className="db-tuner__error">{error}</p>;+ if (!data) return null;++ return (+ <div className="db-tuner">+ <div className="db-tuner__head">+ <p className="db-tuner__hint">+ Suggestions are based on {data.ram_mb} MB of RAM+ ({data.ram_source === 'container_limit' ? 'container memory limit' : 'host total'}).+ Nothing is applied until you choose to.+ </p>+ <label className="db-tuner__dedicated">+ <input+ type="checkbox"+ checked={dedicated}+ onChange={(e) => setDedicated(e.target.checked)}+ />+ Dedicated DB server+ </label>+ <Button type="button" size="sm" variant="ghost" onClick={() => load(dedicated)} aria-label="Refresh">+ <RefreshCw size={14} /> Refresh+ </Button>+ </div>++ <div className="db-tuner__table-wrap">+ <table className="db-tuner__table">+ <thead>+ <tr>+ <th aria-label="Select" />+ <th>Setting</th>+ <th>Current</th>+ <th>Suggested</th>+ <th>Target value</th>+ </tr>+ </thead>+ <tbody>+ {data.settings.map((s) => (+ <tr key={s.key} className={s.differs ? 'is-diff' : ''}>+ <td>+ <input+ type="checkbox"+ checked={!!selected[s.key]}+ onChange={() => toggle(s.key)}+ aria-label={`Select ${s.key}`}+ />+ </td>+ <td>+ <span className="db-tuner__key">{s.key}</span>+ <span className="db-tuner__desc">{s.description}</span>+ </td>+ <td className="db-tuner__num">+ {s.current != null ? `${s.current} ${s.unit}` : '—'}+ </td>+ <td className={`db-tuner__num${s.differs ? ' db-tuner__num--suggest' : ''}`}>+ {s.suggested} {s.unit}+ </td>+ <td>+ <input+ className="db-tuner__input"+ type="number"+ min={s.min}+ max={s.max}+ step="any"+ value={values[s.key] ?? ''}+ onChange={(e) => setValue(s.key, e.target.value)}+ onBlur={() => commitValue(s)}+ aria-label={`Target value for ${s.key}`}+ />+ <span className="db-tuner__range">{s.min}–{s.max} {s.unit}</span>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>++ <div className="db-tuner__actions">+ <Button+ type="button"+ disabled={busy || selectedKeys.length === 0}+ onClick={applySelected}+ >+ <Wand2 size={14} /> Apply selected ({selectedKeys.length})+ </Button>+ {data.can_rollback && (+ <Button type="button" variant="outline" disabled={busy} onClick={rollback}>+ <Undo2 size={14} /> Roll back last apply+ </Button>+ )}+ </div>+ </div>+ );+}diff --git a/frontend/src/services/api/dbTuner.js b/frontend/src/services/api/dbTuner.jsnew file mode 100644index 00000000..c9213c70--- /dev/null+++ b/frontend/src/services/api/dbTuner.js@@ -0,0 +1,34 @@+// Curated DB config tuner — vetted engine settings with RAM-aware+// suggestions. Target is a Docker container name (engine passed alongside)+// or a managed database id. Passwords travel via X-DB-Password, never URLs.++function tunerHeaders(password) {+ return password ? { 'X-DB-Password': password } : {};+}++export async function inspectDbTuner(target, { engine, dedicated, user, password } = {}) {+ const params = new URLSearchParams();+ if (engine) params.set('engine', engine);+ if (dedicated) params.set('dedicated', 'true');+ if (user) params.set('user', user);+ const qs = params.toString();+ return this.request(`/db-tuner/${encodeURIComponent(target)}/inspect${qs ? `?${qs}` : ''}`, {+ headers: tunerHeaders(password),+ });+}++export async function applyDbTunerSettings(target, settings, { engine, user, password } = {}) {+ return this.request(`/db-tuner/${encodeURIComponent(target)}/apply`, {+ method: 'POST',+ body: { settings, engine, user },+ headers: tunerHeaders(password),+ });+}++export async function rollbackDbTuner(target, { engine, user, password } = {}) {+ return this.request(`/db-tuner/${encodeURIComponent(target)}/rollback`, {+ method: 'POST',+ body: { engine, user },+ headers: tunerHeaders(password),+ });+}diff --git a/frontend/src/styles/pages/_db-tuner.scss b/frontend/src/styles/pages/_db-tuner.scssnew file mode 100644index 00000000..b38ad93b--- /dev/null+++ b/frontend/src/styles/pages/_db-tuner.scss@@ -0,0 +1,128 @@+// ============================================+// DB CONFIG TUNER+// Curated engine settings: current vs suggested, apply/rollback.+// ============================================++.db-tuner {+ display: flex;+ flex-direction: column;+ gap: $space-4;++ &__head {+ display: flex;+ align-items: center;+ gap: $space-3;+ }++ &__hint {+ flex: 1;+ margin: 0;+ font-size: 0.8125rem;+ color: $text-secondary;+ }++ &__error {+ margin: 0;+ font-size: 0.8125rem;+ color: $color-danger;+ }++ &__dedicated {+ display: inline-flex;+ align-items: center;+ gap: $space-2;+ font-size: 0.8125rem;+ color: $text-secondary;+ white-space: nowrap;+ cursor: pointer;+ }++ &__table-wrap {+ overflow-x: auto;+ border: 1px solid $border-color;+ border-radius: $radius-md;+ }++ &__table {+ width: 100%;+ border-collapse: collapse;+ font-size: 0.8125rem;++ th,+ td {+ padding: $space-2 $space-3;+ text-align: left;+ border-bottom: 1px solid $border-subtle;+ vertical-align: top;+ }++ th {+ color: $text-secondary;+ font-weight: 600;+ background: $bg-secondary;+ white-space: nowrap;+ }++ tbody tr:last-child td {+ border-bottom: none;+ }++ tbody tr.is-diff {+ background: $bg-hover;+ }+ }++ &__key {+ display: block;+ font-family: $font-mono;+ color: $text-primary;+ }++ &__desc {+ display: block;+ margin-top: 2px;+ color: $text-muted;+ font-size: 0.75rem;+ max-width: 340px;+ }++ &__num {+ font-family: $font-mono;+ white-space: nowrap;+ color: $text-secondary;++ &--suggest {+ color: $accent-primary;+ font-weight: 600;+ }+ }++ &__input {+ width: 110px;+ padding: 4px $space-2;+ background: $bg-input;+ border: 1px solid $border-color;+ border-radius: $radius-md;+ color: $text-primary;+ font-family: $font-mono;+ font-size: 0.8125rem;++ &:focus {+ outline: none;+ border-color: $border-active;+ }+ }++ &__range {+ display: block;+ margin-top: 2px;+ font-size: 0.6875rem;+ color: $text-muted;+ }++ &__actions {+ display: flex;+ align-items: center;+ gap: $space-3;+ }+}