diff --git a/backend/app/api/apps.py b/backend/app/api/apps.py index 369a9adb..d8dc6c81 100644 --- a/backend/app/api/apps.py +++ b/backend/app/api/apps.py @@ -85,6 +85,13 @@ def _sync_manual_app_status(app): elif app.managed_by == 'docker_compose' and app.root_path: status = ProcessService.get_compose_project_status(app.root_path, compose_file=app.compose_file) actual = status.get('status', 'stopped') + elif app.is_host_managed: + # Served by host nginx: the site is up when nginx is. A probe that + # cannot answer leaves the recorded status alone rather than guess. + status = ProcessService.get_systemd_unit_status('nginx') + if not status.get('success') or status.get('status') == 'unknown': + return + actual = 'running' if status.get('active') else 'stopped' else: return @@ -1029,8 +1036,12 @@ def create_manual_app(): else: managed_by = 'docker_compose' - if managed_by not in ('docker_compose', 'systemd'): - return jsonify({'error': "managed_by must be 'docker_compose' or 'systemd'"}), 400 + if managed_by not in ('docker_compose', 'systemd', Application.MANAGED_BY_HOST): + return jsonify({'error': "managed_by must be 'docker_compose', 'systemd' or 'host'"}), 400 + + if managed_by == Application.MANAGED_BY_HOST and app_type not in ('php', 'static', 'wordpress'): + return jsonify({'error': "managed_by 'host' is for php, static and wordpress sites " + 'served by host nginx'}), 400 if managed_by == 'docker_compose' and not compose_file: if not os.path.exists(os.path.join(root_path, 'docker-compose.yml')): diff --git a/backend/app/api/site_adoption.py b/backend/app/api/site_adoption.py new file mode 100644 index 00000000..446f4a9e --- /dev/null +++ b/backend/app/api/site_adoption.py @@ -0,0 +1,61 @@ +"""Site adoption API — register sites that already run on this host. + +Mounted at /api/v1/site-adoption (see app/core_blueprints.py). Admin-only: +discovery reads the host's nginx, PHP-FPM and site configuration, and adopting +creates an application any admin could then operate. + +Nothing here writes to the host. See app/services/site_adoption_service.py. +""" +from flask import Blueprint, jsonify, request + +from app.api._request import json_object +from app.middleware.rbac import admin_required, get_current_user +from app.services import site_adoption_service +from app.services.site_adoption_service import SiteAdoptionError + +site_adoption_bp = Blueprint('site_adoption', __name__) + + +@site_adoption_bp.route('/sites', methods=['GET']) +@admin_required +def list_sites(): + """Every site host nginx serves, and whether an application accounts for + it. ``unmanaged`` is the drift count: live sites the panel cannot see.""" + sites = site_adoption_service.discover() + return jsonify({ + 'sites': sites, + 'unmanaged': sum(1 for site in sites if site['linked_app'] is None), + 'adoptable': sum(1 for site in sites if site['adoptable']), + }), 200 + + +@site_adoption_bp.route('/adopt', methods=['POST']) +@admin_required +def adopt_site(): + """Adopt one site. A dry run unless the body says ``"dry_run": false`` — + the default answer is the plan, never the change.""" + data = json_object() + identifier = (data.get('site') or '').strip() + if not identifier: + return jsonify({'error': 'site is required'}), 400 + name = (data.get('name') or '').strip() or None + + if data.get('dry_run', True) is not False: + site = site_adoption_service.find(identifier) + if site is None: + return jsonify({'error': f'No site served by host nginx matches "{identifier}".'}), 404 + return jsonify({'dry_run': True, 'adoptable': site['adoptable'], + 'reason': site['reason'], + 'plan': site_adoption_service.plan(site, name)}), 200 + + user = get_current_user() + from app.services.workspace_service import WorkspaceService + workspace_id = WorkspaceService.resolve_workspace_id( + user, request.headers.get('X-Workspace-Id') or request.args.get('workspace_id')) + try: + application, plan = site_adoption_service.adopt( + identifier, user, name=name, workspace_id=workspace_id) + except SiteAdoptionError as exc: + return jsonify({'error': str(exc)}), exc.status + return jsonify({'message': 'Site adopted', 'dry_run': False, 'plan': plan, + 'app': application.to_dict()}), 201 diff --git a/backend/app/core_blueprints.py b/backend/app/core_blueprints.py index 4743fbdc..68c2b669 100644 --- a/backend/app/core_blueprints.py +++ b/backend/app/core_blueprints.py @@ -271,6 +271,7 @@ CORE_BLUEPRINTS: tuple[BlueprintSpec, ...] = ( BlueprintSpec('app.api.ai', 'ai_bp', '/api/v1/ai'), BlueprintSpec('app.api.speed_test', 'speedtest_bp', '/api/v1/speedtest'), BlueprintSpec('app.api.site_imports', 'site_imports_bp', '/api/v1/imports'), + BlueprintSpec('app.api.site_adoption', 'site_adoption_bp', '/api/v1/site-adoption'), BlueprintSpec('app.api.doctor', 'doctor_bp', '/api/v1/doctor'), BlueprintSpec( 'app.api.fleet_doctor', diff --git a/backend/app/models/application.py b/backend/app/models/application.py index 479e7649..59ae2efb 100644 --- a/backend/app/models/application.py +++ b/backend/app/models/application.py @@ -88,7 +88,7 @@ class Application(JsonColumnMixin, TimestampMixin, SoftDeleteMixin, db.Model): # Manual / local service configuration compose_file = db.Column(db.String(200), nullable=True) systemd_unit = db.Column(db.String(100), nullable=True) - managed_by = db.Column(db.String(20), nullable=True) # 'docker_compose', 'systemd' + managed_by = db.Column(db.String(20), nullable=True) # 'docker_compose', 'systemd', 'host' # Ingress plane: which reverse proxy is expected to serve this app — # 'nginx' (host Nginx, the default) or 'proxy_stack' (Dockerized @@ -186,6 +186,18 @@ class Application(JsonColumnMixin, TimestampMixin, SoftDeleteMixin, db.Model): from app.utils.slug import app_name_clash_error return app_name_clash_error(cls.query.filter_by(name=name).first(), name, suffix) + # A site that was already running on the host when the panel adopted it + # (nginx + PHP-FPM, or static files): its vhost, pool and certificate + # were written by someone else and stay theirs. + MANAGED_BY_HOST = 'host' + + @property + def is_host_managed(self): + """True for an adopted host site. The panel records and observes it + but must never write, rewrite or remove its running config — every + path that touches nginx or the runtime for an app checks this.""" + return self.managed_by == self.MANAGED_BY_HOST + @property def live_domains(self): """The domains this app actually serves — tombstones excluded. diff --git a/backend/app/services/application_lifecycle_service.py b/backend/app/services/application_lifecycle_service.py index 58009d66..b5ec4510 100644 --- a/backend/app/services/application_lifecycle_service.py +++ b/backend/app/services/application_lifecycle_service.py @@ -140,8 +140,20 @@ def _ensure_local_image_compose(app): db.session.commit() +def _refuse_host_managed(app, action): + """An adopted host site is served by the host's own nginx and PHP-FPM, + shared with every other site on the box. There is no per-site runtime to + start or stop, and flipping the status column would only make the panel + lie about a site that is still serving.""" + if app.is_host_managed: + raise ApplicationLifecycleError( + f'Cannot {action} a host-managed site: it is served by this server\'s ' + 'nginx and PHP-FPM, which ServerKit does not control per site.') + + def start_application(app, *, user_id=None): """Start the configured runtime, materializing local image apps if needed.""" + _refuse_host_managed(app, 'start') # A local BYO-image docker app (image set, no source yet) has no compose to # launch — materialize one on first start so it can actually run. if app.app_type == 'docker' and not app.root_path and app.docker_image and not app.server_id: @@ -197,6 +209,7 @@ def start_application(app, *, user_id=None): def stop_application(app, *, user_id=None): """Stop the configured runtime; a vanished single container is stopped.""" + _refuse_host_managed(app, 'stop') # Handle Docker apps if app.app_type == 'docker' and app.root_path: if app.server_id: @@ -234,6 +247,7 @@ def stop_application(app, *, user_id=None): def restart_application(app, *, user_id=None): """Restart the configured runtime, requiring a deployed single container.""" + _refuse_host_managed(app, 'restart') # Handle Docker apps if app.app_type == 'docker' and app.root_path: if app.server_id: diff --git a/backend/app/services/application_restore.py b/backend/app/services/application_restore.py index 4252780d..f39bcbe2 100644 --- a/backend/app/services/application_restore.py +++ b/backend/app/services/application_restore.py @@ -206,12 +206,18 @@ def suspend_application(app, user_id=None): except Exception as exc: # noqa: BLE001 results['docker'] = {'error': str(exc)} - try: - NginxService.disable_site(app.name) - NginxService.delete_site(app.name) - results['nginx'] = {'success': True} - except Exception as exc: # noqa: BLE001 - results['nginx'] = {'error': str(exc)} + if app.is_host_managed: + # Deleting an adopted site forgets it; it does not take it offline. + # The vhost was never ours, and a site named like its vhost file + # would otherwise lose its live config here. + results['nginx'] = {'success': True, 'skipped': 'host-managed'} + else: + try: + NginxService.disable_site(app.name) + NginxService.delete_site(app.name) + results['nginx'] = {'success': True} + except Exception as exc: # noqa: BLE001 + results['nginx'] = {'error': str(exc)} try: results['cron'] = {'suspended': CronService.suspend_for_application(app.id)} diff --git a/backend/app/services/doctor_service.py b/backend/app/services/doctor_service.py index a34ccba6..bbd1548b 100644 --- a/backend/app/services/doctor_service.py +++ b/backend/app/services/doctor_service.py @@ -705,6 +705,37 @@ class DoctorService: return [_check('extensions.checks', 'Extension checks', 'warn', f'Could not collect extension checks: {e}')] + @classmethod + def _unmanaged_site_checks(cls): + """Sites host nginx is serving that no application accounts for. + + Such a site is live but invisible to the panel: no monitoring, + backups, SSL status or logs, while its database may well be listed + under Databases. One warning per site; a host with none adds nothing. + Not repairable — adopting is the operator's call, and it is one + command (or one click) away in the detail.""" + try: + from app.services import site_adoption_service + sites = site_adoption_service.unmanaged() + except Exception as e: # noqa: BLE001 + logger.warning('unmanaged-site doctor section failed: %s', e) + return [_check('sites.unmanaged', 'Unmanaged sites', 'warn', + f'Could not read the host nginx config: {e}')] + checks = [] + for site in sites: + if site['kind'] == site_adoption_service.KIND_REDIRECT: + continue # a redirect-only vhost has no site behind it + if site['adoptable']: + detail = (f"Served by host nginx ({site['vhost_file']}) but not registered " + f"in ServerKit. Adopt it from Services, or run: " + f"serverkit adopt-site {site['primary_domain']} --apply") + else: + detail = (f"Served by host nginx ({site['vhost_file']}) but not registered " + f"in ServerKit. {site['reason']}") + checks.append(_check(f"sites.unmanaged.{site['id']}", + f"Unmanaged site: {site['primary_domain']}", 'warn', detail)) + return checks + # ------------------------------------------------------------------ # # Sweep # ------------------------------------------------------------------ # @@ -718,6 +749,7 @@ class DoctorService: checks = [] checks += cls._drift_checks() checks += cls._service_checks() + checks += cls._unmanaged_site_checks() checks += cls._dns_checks() checks += cls._backup_proof_checks() checks.append(cls._cert_check()) diff --git a/backend/app/services/drift_service.py b/backend/app/services/drift_service.py index fdfdea8a..e051e0b8 100644 --- a/backend/app/services/drift_service.py +++ b/backend/app/services/drift_service.py @@ -342,7 +342,9 @@ def _nginx_list_resources(): .filter(Domain.deleted_at.is_(None)) .distinct() .all()) - return [(app.id, app.name) for app in rows] + # An adopted host site's vhost was not written by the panel, so there is + # no expected config to compare it with and nothing here may repair it. + return [(app.id, app.name) for app in rows if not app.is_host_managed] def _nginx_render_expected(app_id): diff --git a/backend/app/services/previews/plan.py b/backend/app/services/previews/plan.py index 83dd3835..caebc9fa 100644 --- a/backend/app/services/previews/plan.py +++ b/backend/app/services/previews/plan.py @@ -12,8 +12,8 @@ class PreviewError(ValueError): def validate(app, preview, settings, git_config): if app.server_id or settings.target_server_id: raise PreviewError('Generic previews currently require a local server.') - if app.compose_file or app.managed_by in ('docker_compose', 'systemd'): - raise PreviewError('Compose and systemd previews are not supported by this provisioner.') + if app.compose_file or app.managed_by in ('docker_compose', 'systemd', 'host'): + raise PreviewError('Compose, systemd and host-managed previews are not supported by this provisioner.') if app.ingress_plane not in (None, '', 'nginx'): raise PreviewError('Generic previews currently require nginx ingress.') if not app.port or not 1 <= app.port <= 65535: diff --git a/backend/app/services/site_adoption_service.py b/backend/app/services/site_adoption_service.py new file mode 100644 index 00000000..30eb997a --- /dev/null +++ b/backend/app/services/site_adoption_service.py @@ -0,0 +1,541 @@ +"""Adopt sites that already run on this host (issue #269). + +A site that was set up by hand, by a script or by a migration serves traffic +through host nginx but has no row in ``applications`` / ``domains`` / +``wordpress_sites``, so the panel cannot see it: no monitoring, backups, SSL +status or logs. The other entry points all *create* something — a vhost, a +copy of the files — which is the wrong thing to do to a site that is already +live. + +This module only ever READS the host: the live nginx config, the PHP-FPM +pools, the certificate files and ``wp-config.php``. Adopting writes database +rows and nothing else. The resulting application carries +``managed_by='host'``, which the vhost writer, the lifecycle and the delete +path all honour by leaving the running config alone +(``Application.is_host_managed``). + +``discover()`` doubles as the drift report: every site it returns without a +``linked_app`` is one serving traffic that the panel does not know about. +""" +import glob +import logging +import os +import re +from datetime import datetime + +from app import db +from app.models.application import Application +from app.models.domain import Domain +from app.services.nginx_service import NginxService +from app.utils.slug import app_name_clash_error, slugify + +logger = logging.getLogger(__name__) + +HOST_MANAGED = Application.MANAGED_BY_HOST + +# Where the distro keeps PHP-FPM pools: /etc/php//fpm/pool.d/*.conf. +# Globbed rather than iterated over a list of known versions, so a 7.4 or 8.4 +# pool is found too. +PHP_ETC_DIR = os.environ.get('PHP_ETC_DIR', '/etc/php') + +# Kinds of site a vhost can describe, and what each one adopts as. +KIND_PHP = 'php' +KIND_STATIC = 'static' +KIND_PROXY = 'proxy' +KIND_REDIRECT = 'redirect' +_ADOPTABLE_KINDS = (KIND_PHP, KIND_STATIC) + + +class SiteAdoptionError(Exception): + """Adoption refused. ``status`` is the HTTP status the API answers with.""" + + def __init__(self, message, status=400): + super().__init__(message) + self.status = status + + +# -------------------------------------------------------------------------- +# Reading nginx +# -------------------------------------------------------------------------- + +def _live_vhost_files(): + """Config files nginx is actually loading: ``sites-enabled/*`` (Debian + layout) and ``conf.d/*.conf`` (RHEL layout, and extras on Debian).""" + files = [] + enabled = NginxService.SITES_ENABLED + if os.path.isdir(enabled): + files.extend(sorted(glob.glob(os.path.join(enabled, '*')))) + conf_d = os.path.join(NginxService.NGINX_CONF_DIR, 'conf.d') + if os.path.isdir(conf_d): + files.extend(sorted(glob.glob(os.path.join(conf_d, '*.conf')))) + return [f for f in files if os.path.isfile(f)] + + +def _strip_comments(text): + return re.sub(r'(?m)#.*$', '', text) + + +def _server_blocks(text): + """The body of every ``server { ... }`` block, by brace matching.""" + blocks = [] + for match in re.finditer(r'(?:^|[\s;{}])server\s*\{', text): + depth, start = 1, match.end() + pos = start + while pos < len(text) and depth: + char = text[pos] + if char == '{': + depth += 1 + elif char == '}': + depth -= 1 + pos += 1 + if depth == 0: + blocks.append(text[start:pos - 1]) + return blocks + + +def _directive(body, name): + """Every value of directive ``name`` in ``body``, in order.""" + pattern = r'(?:^|[;{}])\s*' + re.escape(name) + r'\s+([^;{}]+);' + return [value.strip() for value in re.findall(pattern, body)] + + +def _first(values): + return values[0] if values else None + + +def _unquote(value): + return value.strip().strip('"\'') if value else value + + +def _parse_block(body): + names = [] + for value in _directive(body, 'server_name'): + for name in value.split(): + # `_` is the catch-all and `~...` a regex: neither is a domain. + if name != '_' and not name.startswith('~') and name not in names: + names.append(name) + listens = _directive(body, 'listen') + return { + 'domains': names, + 'root': _unquote(_first(_directive(body, 'root'))), + 'fastcgi_pass': _first(_directive(body, 'fastcgi_pass')), + 'proxy_pass': _first(_directive(body, 'proxy_pass')), + 'certificate': _unquote(_first(_directive(body, 'ssl_certificate'))), + 'certificate_key': _unquote(_first(_directive(body, 'ssl_certificate_key'))), + 'ssl': any('ssl' in value.split() or value.split()[0].endswith('443') + for value in listens if value.split()), + } + + +def _has_content(block): + return bool(block['root'] or block['fastcgi_pass'] or block['proxy_pass']) + + +def _related(domain_a, domain_b): + """`www.example.com` and `example.com` are the same site.""" + return domain_a == 'www.' + domain_b or domain_b == 'www.' + domain_a + + +def _merge(target, block): + for name in block['domains']: + if name not in target['domains']: + target['domains'].append(name) + for key in ('root', 'fastcgi_pass', 'proxy_pass', 'certificate', 'certificate_key'): + target[key] = target[key] or block[key] + target['ssl'] = target['ssl'] or block['ssl'] + + +def _group_blocks(blocks): + """One group per site. A port-80 redirect and its 443 twin share names and + merge; a content-less `www.` redirect folds into the site it points at.""" + groups = [] + for block in blocks: + if not block['domains']: + continue + home = next((g for g in groups if set(g['domains']) & set(block['domains'])), None) + if home is None: + groups.append(dict(block, domains=list(block['domains']))) + else: + _merge(home, block) + + sites = [g for g in groups if _has_content(g)] + for group in groups: + if _has_content(group): + continue + home = next((s for s in sites + if any(_related(a, b) for a in s['domains'] for b in group['domains'])), + None) + if home is not None: + _merge(home, group) + else: + sites.append(group) + return sites + + +# -------------------------------------------------------------------------- +# Reading PHP-FPM, certificates, WordPress +# -------------------------------------------------------------------------- + +def _fpm_pools(): + """Every PHP-FPM pool on the box: ``{version, pool, listen, file}``.""" + pools = [] + pattern = os.path.join(PHP_ETC_DIR, '*', 'fpm', 'pool.d', '*.conf') + for path in sorted(glob.glob(pattern)): + version = os.path.basename(os.path.dirname(os.path.dirname(os.path.dirname(path)))) + try: + with open(path, encoding='utf-8', errors='replace') as handle: + text = re.sub(r'(?m)^\s*[;#].*$', '', handle.read()) + except OSError: + continue + section = re.search(r'(?m)^\s*\[([^\]]+)\]', text) + listen = re.search(r'(?m)^\s*listen\s*=\s*(\S+)', text) + if listen: + pools.append({'version': version, + 'pool': section.group(1) if section else None, + 'listen': listen.group(1), 'file': path}) + return pools + + +def _php_for(fastcgi_pass, pools): + """Which PHP serves a ``fastcgi_pass`` target: matched against the pools' + ``listen``, falling back to the version in a conventional socket name.""" + target = fastcgi_pass.strip() + target = target[len('unix:'):] if target.startswith('unix:') else target + for pool in pools: + if pool['listen'] == target: + return {'version': pool['version'], 'pool': pool['pool'], + 'listen': pool['listen'], 'pool_file': pool['file']} + named = re.search(r'php-?(\d+\.\d+)', target) + return {'version': named.group(1) if named else None, 'pool': None, + 'listen': target, 'pool_file': None} + + +def _certificate_expiry(path): + try: + from cryptography import x509 + with open(path, 'rb') as handle: + cert = x509.load_pem_x509_certificate(handle.read()) + expires = getattr(cert, 'not_valid_after_utc', None) or cert.not_valid_after + return expires.replace(tzinfo=None) + except Exception: # unreadable, missing or not a PEM certificate + return None + + +_WP_DEFINE = r'''define\(\s*['"]{key}['"]\s*,\s*['"]([^'"]*)['"]''' + + +def _wordpress(root): + """What ``wp-config.php`` says about the site. The password is never read: + nothing here needs it, and a secret we do not hold cannot leak.""" + config = next((path for path in (os.path.join(root, 'wp-config.php'), + os.path.join(os.path.dirname(root.rstrip('/\\')), + 'wp-config.php')) + if os.path.isfile(path)), None) + if config is None: + return None + try: + with open(config, encoding='utf-8', errors='replace') as handle: + text = handle.read() + except OSError: + return {'config_file': config, 'readable': False} + + def define(key): + match = re.search(_WP_DEFINE.format(key=key), text) + return match.group(1) if match else None + + prefix = re.search(r'''\$table_prefix\s*=\s*['"]([^'"]+)['"]''', text) + version = None + try: + with open(os.path.join(root, 'wp-includes', 'version.php'), + encoding='utf-8', errors='replace') as handle: + found = re.search(r'''\$wp_version\s*=\s*['"]([^'"]+)['"]''', handle.read()) + version = found.group(1) if found else None + except OSError: + pass + return { + 'config_file': config, 'readable': True, 'version': version, + 'db_name': define('DB_NAME'), 'db_user': define('DB_USER'), + 'db_host': define('DB_HOST') or 'localhost', + 'table_prefix': prefix.group(1) if prefix else 'wp_', + 'multisite': bool(re.search(r'''define\(\s*['"]MULTISITE['"]\s*,\s*true''', text, re.I)), + } + + +# -------------------------------------------------------------------------- +# Discovery +# -------------------------------------------------------------------------- + +def _is_panel_vhost(path): + """ServerKit's own vhost and snippets are not sites to adopt.""" + return os.path.basename(path).lower().startswith('serverkit') + + +def _link_index(): + """Lookup tables for "is this site already an application?".""" + apps = Application.query_active().all() + by_id = {app.id: app for app in apps} + by_domain = {} + for domain in Domain.query_active().all(): + if domain.application_id in by_id: + by_domain[domain.name.lower()] = by_id[domain.application_id] + by_root = {os.path.normpath(app.root_path): app for app in apps + if app.root_path and not app.server_id} + by_name = {app.name: app for app in apps if not app.server_id} + return by_domain, by_root, by_name + + +def _linked_app(site, vhost_file, index): + by_domain, by_root, by_name = index + for domain in site['domains']: + if domain.lower() in by_domain: + return by_domain[domain.lower()] + if site['root'] and os.path.normpath(site['root']) in by_root: + return by_root[os.path.normpath(site['root'])] + # A vhost the panel wrote is named after its application. + stem = os.path.basename(vhost_file) + return by_name.get(stem) or by_name.get(stem[:-len('.conf')] if stem.endswith('.conf') else stem) + + +def _describe(site, vhost_file, pools, index, single): + primary = site['domains'][0] + stem = os.path.basename(vhost_file) + root = site['root'] + root_exists = bool(root and os.path.isdir(root)) + + if site['fastcgi_pass']: + kind = KIND_PHP + elif site['proxy_pass']: + kind = KIND_PROXY + elif root: + kind = KIND_STATIC + else: + kind = KIND_REDIRECT + + php = _php_for(site['fastcgi_pass'], pools) if kind == KIND_PHP else None + wordpress = _wordpress(root) if kind == KIND_PHP and root_exists else None + app_type = {KIND_PHP: 'wordpress' if wordpress else 'php', + KIND_STATIC: 'static'}.get(kind) + + port = None + if site['proxy_pass']: + found = re.search(r':(\d+)', site['proxy_pass'].split('//', 1)[-1]) + port = int(found.group(1)) if found else None + + certificate = site['certificate'] + expires = _certificate_expiry(certificate) if certificate else None + linked = _linked_app(site, vhost_file, index) + + reason = None + if linked is not None: + reason = f'Already managed as "{linked.name}".' + elif kind == KIND_PROXY: + reason = ('This vhost proxies to a running process. Register that process as a ' + 'service (Docker Compose or systemd) instead of adopting the vhost.') + elif kind == KIND_REDIRECT: + reason = 'This vhost only redirects; there is no site behind it to adopt.' + elif not root_exists: + reason = f'Document root does not exist: {root}' + + return { + 'id': stem if single else f'{stem}#{primary}', + 'vhost_file': os.path.realpath(vhost_file), + 'domains': list(site['domains']), + 'primary_domain': primary, + 'kind': kind, + 'app_type': app_type, + 'root': root, + 'root_exists': root_exists, + 'php': php, + 'upstream': site['proxy_pass'], + 'port': port, + 'ssl': { + 'enabled': bool(site['ssl'] and certificate), + 'certificate': certificate, + 'certificate_key': site['certificate_key'], + 'letsencrypt': bool(certificate and '/letsencrypt/' in certificate.replace('\\', '/')), + 'expires_at': expires.isoformat() if expires else None, + }, + 'wordpress': wordpress, + 'database': ({'engine': 'mysql', 'name': wordpress['db_name'], + 'user': wordpress.get('db_user'), 'host': wordpress.get('db_host')} + if wordpress and wordpress.get('db_name') else None), + 'linked_app': {'id': linked.id, 'name': linked.name} if linked is not None else None, + 'adoptable': reason is None and kind in _ADOPTABLE_KINDS, + 'reason': reason, + 'suggested_name': slugify(primary) or 'site', + } + + +def discover(): + """Every site host nginx is serving, with what backs it and whether the + panel already manages it. Read-only; an unreadable file is skipped.""" + pools = _fpm_pools() + index = _link_index() + sites = [] + for path in _live_vhost_files(): + if _is_panel_vhost(path): + continue + try: + with open(path, encoding='utf-8', errors='replace') as handle: + text = _strip_comments(handle.read()) + except OSError as exc: + logger.warning('site adoption: cannot read %s: %s', path, exc) + continue + groups = _group_blocks([_parse_block(body) for body in _server_blocks(text)]) + for group in groups: + sites.append(_describe(group, path, pools, index, single=len(groups) == 1)) + return sites + + +def unmanaged(): + """The drift list: sites serving traffic that no application accounts for.""" + return [site for site in discover() if site['linked_app'] is None] + + +def find(identifier): + """A discovered site by its id, vhost file name or any of its domains.""" + wanted = (identifier or '').strip().lower() + if not wanted: + return None + for site in discover(): + candidates = {site['id'].lower(), os.path.basename(site['vhost_file']).lower()} + candidates.update(domain.lower() for domain in site['domains']) + if wanted in candidates: + return site + return None + + +# -------------------------------------------------------------------------- +# Adopting +# -------------------------------------------------------------------------- + +def plan(site, name=None): + """What adopting ``site`` would record, and what it would leave alone. + Pure: this is the dry run, and `adopt` builds its rows from the same dict.""" + name = (name or site['suggested_name']).strip() + php = site['php'] or {} + wordpress = site['wordpress'] + return { + 'site': site['id'], + 'application': { + 'name': name, + 'app_type': site['app_type'], + 'managed_by': HOST_MANAGED, + 'source': 'manual', + 'root_path': site['root'], + 'php_version': php.get('version'), + }, + 'domains': [{ + 'name': domain, + 'is_primary': position == 0, + 'ssl_enabled': site['ssl']['enabled'], + 'ssl_certificate_path': site['ssl']['certificate'], + 'ssl_key_path': site['ssl']['certificate_key'], + 'ssl_expires_at': site['ssl']['expires_at'], + } for position, domain in enumerate(site['domains'])], + 'wordpress_site': ({ + 'wp_version': wordpress.get('version'), + 'multisite': bool(wordpress.get('multisite')), + 'db_name': wordpress.get('db_name'), + 'db_user': wordpress.get('db_user'), + 'db_host': wordpress.get('db_host'), + 'db_prefix': wordpress.get('table_prefix'), + } if wordpress and wordpress.get('readable') else None), + 'database': site['database'], + # Named so the operator can see exactly what stays as it is. + 'untouched': [path for path in (site['vhost_file'], php.get('pool_file'), + site['ssl']['certificate'], + (wordpress or {}).get('config_file')) if path], + } + + +def adopt(identifier, user, name=None, workspace_id=None): + """Register a running site as an application. Writes rows, never config. + + Returns ``(application, plan)``. Raises :class:`SiteAdoptionError` when the + site is unknown, already managed, or not something this flow adopts. + """ + site = find(identifier) + if site is None: + raise SiteAdoptionError( + f'No site served by host nginx matches "{identifier}".', status=404) + if not site['adoptable']: + raise SiteAdoptionError(site['reason'] or 'This site cannot be adopted.', status=409) + + todo = plan(site, name) + app_name = todo['application']['name'] + if not app_name or len(app_name) < 2: + raise SiteAdoptionError('Service name must be at least 2 characters.') + # Not query_active: a tombstone keeps its name reserved so a restore from + # the Recycle Bin can never collide with an app adopted in the meantime. + clash = app_name_clash_error(Application.query.filter_by(name=app_name).first(), app_name) + if clash: + raise SiteAdoptionError(clash, status=409) + + if workspace_id is None: + from app.services.workspace_service import WorkspaceService + workspace_id = WorkspaceService.ensure_default_workspace().id + + application = Application( + name=app_name, + app_type=todo['application']['app_type'], + # It is serving traffic right now; that is the whole premise. + status='running', + source='manual', + managed_by=HOST_MANAGED, + root_path=todo['application']['root_path'], + php_version=todo['application']['php_version'], + user_id=user.id, + workspace_id=workspace_id, + ) + db.session.add(application) + db.session.flush() + + for row in todo['domains']: + expires = row['ssl_expires_at'] + db.session.add(Domain( + name=row['name'], + is_primary=row['is_primary'], + ssl_enabled=row['ssl_enabled'], + ssl_certificate_path=row['ssl_certificate_path'], + ssl_key_path=row['ssl_key_path'], + ssl_expires_at=datetime.fromisoformat(expires) if expires else None, + application_id=application.id, + )) + + if todo['wordpress_site'] is not None: + from app.models.wordpress_site import WordPressSite + db.session.add(WordPressSite(application_id=application.id, **todo['wordpress_site'])) + + db.session.commit() + + if todo['database'] is not None: + _link_database(todo['database'], application) + + try: + from app.services.audit_service import AuditService + AuditService.log(action='app.adopt', user_id=user.id, target_type='application', + target_id=application.id, + details={'site': site['id'], 'domains': site['domains'], + 'vhost_file': site['vhost_file']}) + except Exception: # audit is best-effort and never blocks the adoption + logger.debug('site adoption: audit log failed', exc_info=True) + + return application, todo + + +def _link_database(database, application): + """Point the site's database at the application, so Databases stops + showing it as belonging to nothing. Best-effort: the site is adopted + either way.""" + try: + from app.services.managed_database_service import ManagedDatabaseService + host, _, port = (database.get('host') or 'localhost').partition(':') + ManagedDatabaseService.adopt( + database['engine'], host or 'localhost', database['name'], + port=int(port) if port.isdigit() else None, + owner_application_id=application.id, + workspace_id=application.workspace_id) + except Exception as exc: + logger.warning('site adoption: could not link database %s to %s: %s', + database.get('name'), application.name, exc) diff --git a/backend/app/services/site_domain_service.py b/backend/app/services/site_domain_service.py index a5d61abc..76281e64 100644 --- a/backend/app/services/site_domain_service.py +++ b/backend/app/services/site_domain_service.py @@ -538,6 +538,14 @@ class SiteDomainService: """ from app.models.domain import Domain + # An adopted host site already has a vhost someone else wrote, under a + # file name that is not the app's. Rendering one here would publish a + # second server block for the same names — or, through drift repair, + # replace the one that is serving traffic. + if app.is_host_managed: + return None, ('This site is host-managed: ServerKit records its domains ' + 'but does not rewrite its nginx config.') + # query_active, not query: Domain is soft-deleted now, so a plain query # returns tombstones and this renderer would write a deleted domain # straight back into server_name — the vhost would keep serving a domain diff --git a/backend/tests/test_site_adoption.py b/backend/tests/test_site_adoption.py new file mode 100644 index 00000000..f37d4c99 --- /dev/null +++ b/backend/tests/test_site_adoption.py @@ -0,0 +1,377 @@ +"""Adopting a site that already runs on the host (issue #269). + +The contract under test: discovery reads the live nginx / PHP-FPM / WordPress +config and describes each site; adopting writes database rows and NOTHING on +the host; and once adopted, no panel path rewrites or removes the config that +is serving the site. +""" +import hashlib +from unittest.mock import patch + +import pytest + +from factories import headers_for, make_user + +WP_CONFIG = """= 400 + assert 'host-managed' in resp.get_data(as_text=True) + assert adopted.status == 'running' + + +def test_deleting_an_adopted_site_forgets_it_but_keeps_it_serving(client, admin, adopted, host): + from app.models.application import Application + before = _snapshot(host['root']) + # Mocks, not raising stubs: the delete path catches exceptions per step, + # so a raise would be swallowed and this would pass with the guard removed. + with patch('app.services.nginx_service.NginxService.disable_site') as disable_site, \ + patch('app.services.nginx_service.NginxService.delete_site') as delete_site: + resp = client.delete(f'/api/v1/apps/{adopted.id}', headers=headers_for(admin)) + assert resp.status_code == 200, resp.get_json() + disable_site.assert_not_called() + delete_site.assert_not_called() + assert Application.query_active().filter_by(id=adopted.id).first() is None + assert _snapshot(host['root']) == before + + +def test_status_follows_nginx_and_never_guesses(app, adopted): + from app import db + from app.api.apps import _sync_manual_app_status + probe = 'app.services.process_service.ProcessService.get_systemd_unit_status' + with patch(probe, return_value={'success': True, 'status': 'inactive', 'active': False}): + _sync_manual_app_status(adopted) + assert adopted.status == 'stopped' + with patch(probe, return_value={'success': True, 'status': 'active', 'active': True}): + _sync_manual_app_status(adopted) + assert adopted.status == 'running' + # No systemd to ask (a dev box): keep what we knew. + with patch(probe, return_value={'success': True, 'status': 'unknown', 'active': False}): + _sync_manual_app_status(adopted) + assert adopted.status == 'running' + db.session.rollback() + + +def test_manual_route_accepts_host_for_sites_only(client, admin, host): + ok = client.post('/api/v1/apps/manual', headers=headers_for(admin), json={ + 'name': 'docs-manual', 'app_type': 'static', 'root_path': host['docs_root'], + 'managed_by': 'host'}) + assert ok.status_code == 201, ok.get_json() + assert ok.get_json()['app']['managed_by'] == 'host' + bad = client.post('/api/v1/apps/manual', headers=headers_for(admin), json={ + 'name': 'api-manual', 'app_type': 'docker', 'root_path': host['docs_root'], + 'managed_by': 'host'}) + assert bad.status_code == 400 + + +# ------------------------------------------------------------- drift report + +def test_doctor_reports_unmanaged_sites_until_they_are_adopted(client, host, admin): + from app.services.doctor_service import DoctorService + + def unmanaged(): + return {check['key']: check for check in DoctorService._unmanaged_site_checks()} + + checks = unmanaged() + assert set(checks) == {'sites.unmanaged.shop.example.com.conf', + 'sites.unmanaged.docs.example.com.conf', + 'sites.unmanaged.api.example.com.conf'} + shop = checks['sites.unmanaged.shop.example.com.conf'] + assert shop['status'] == 'warn' and not shop['repairable'] + assert 'serverkit adopt-site shop.example.com --apply' in shop['detail'] + # A proxied process is still reported, with why it is not adopted here. + assert 'Docker Compose or systemd' in checks['sites.unmanaged.api.example.com.conf']['detail'] + + client.post('/api/v1/site-adoption/adopt', + json={'site': 'shop.example.com', 'dry_run': False}, headers=headers_for(admin)) + assert 'sites.unmanaged.shop.example.com.conf' not in unmanaged() + + +def test_doctor_stays_quiet_on_a_host_with_no_stray_sites(app, tmp_path, monkeypatch): + from app.services.doctor_service import DoctorService + from app.services.nginx_service import NginxService + monkeypatch.setattr(NginxService, 'NGINX_CONF_DIR', str(tmp_path / 'absent')) + monkeypatch.setattr(NginxService, 'SITES_ENABLED', str(tmp_path / 'absent' / 'sites-enabled')) + assert DoctorService._unmanaged_site_checks() == []