Adopt sites already running on the host

A site set up by hand or by a migration serves traffic but has
no application, domain or WordPress row, so the panel cannot
see it. Every existing entry point creates something (a vhost,
a copy of the files), which is wrong for a site that is live.

Discovery reads the live nginx config, the PHP-FPM pools, the
certificate and wp-config.php. Adopting writes rows only, as a
dry run unless asked otherwise. The app is managed_by 'host',
and the vhost writer, drift repair, lifecycle and delete paths
leave its running config alone. The doctor reports sites nginx
serves that no application accounts for.

Part of #269.
This commit is contained in:
Juan Denis committed 2026-11-22 02:02:44 -05:00
1 parent 73e2251e28
commit 4ba435243f
12 files changed
+1077 -12

No files matched your search

+13 -2
View File
@@ -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')):
+61
View File
@@ -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
+1
View File
@@ -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',
+13 -1
View File
@@ -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.
@@ -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:
+12 -6
View File
@@ -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)}
+32
View File
@@ -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())
+3 -1
View File
@@ -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):
+2 -2
View File
@@ -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:
@@ -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/<version>/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)
@@ -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
+377
View File
@@ -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 = """<?php
define( 'DB_NAME', 'shop_wp' );
define( 'DB_USER', 'shop_user' );
define( 'DB_PASSWORD', 'never-read-this' );
define( 'DB_HOST', 'localhost' );
$table_prefix = 'shp_';
"""
@pytest.fixture
def host(tmp_path, monkeypatch):
"""A fake host: one WordPress site on PHP-FPM, one static site, one proxied
app, a www redirect, the panel's own vhost and the distro default."""
from app.services import site_adoption_service
from app.services.nginx_service import NginxService
nginx = tmp_path / 'nginx'
available, enabled = nginx / 'sites-available', nginx / 'sites-enabled'
for directory in (available, enabled, nginx / 'conf.d'):
directory.mkdir(parents=True)
php = tmp_path / 'php'
pool_dir = php / '8.4' / 'fpm' / 'pool.d'
pool_dir.mkdir(parents=True)
(pool_dir / 'shop.conf').write_text(
'; pool for the shop\n[shop]\nuser = shop\nlisten = /run/php/shop.sock\n',
encoding='utf-8')
shop_root = tmp_path / 'www' / 'shop' / 'public'
(shop_root / 'wp-includes').mkdir(parents=True)
(shop_root / 'wp-config.php').write_text(WP_CONFIG, encoding='utf-8')
(shop_root / 'wp-includes' / 'version.php').write_text(
"<?php\n$wp_version = '6.8.1';\n", encoding='utf-8')
docs_root = tmp_path / 'www' / 'docs'
docs_root.mkdir(parents=True)
files = {
'shop.example.com.conf': f"""
# Site: shop
server {{
listen 80;
server_name shop.example.com www.shop.example.com;
return 301 https://shop.example.com$request_uri;
}}
server {{
listen 443 ssl http2;
server_name shop.example.com;
root {shop_root.as_posix()};
ssl_certificate /etc/letsencrypt/live/shop.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/shop.example.com/privkey.pem;
location ~ \\.php$ {{
fastcgi_pass unix:/run/php/shop.sock;
}}
}}
""",
'docs.example.com.conf': f"""
server {{
listen 80;
server_name docs.example.com;
root "{docs_root.as_posix()}";
}}
""",
'api.example.com.conf': """
server {
listen 80;
server_name api.example.com;
location / { proxy_pass http://127.0.0.1:3210; }
}
""",
'serverkit.conf': """
server { listen 80 default_server; server_name _; root /opt/serverkit; }
""",
'default': """
server { listen 80; server_name _; root /var/www/html; }
""",
}
for name, body in files.items():
(available / name).write_text(body, encoding='utf-8')
# A copy, not a symlink: Windows dev boxes cannot create symlinks.
(enabled / name).write_text(body, encoding='utf-8')
monkeypatch.setattr(NginxService, 'NGINX_CONF_DIR', str(nginx))
monkeypatch.setattr(NginxService, 'SITES_AVAILABLE', str(available))
monkeypatch.setattr(NginxService, 'SITES_ENABLED', str(enabled))
monkeypatch.setattr(site_adoption_service, 'PHP_ETC_DIR', str(php))
return {'root': tmp_path, 'shop_root': shop_root.as_posix(),
'docs_root': docs_root.as_posix()}
def _snapshot(root):
"""Content hash of every file under the fake host."""
return {path.relative_to(root).as_posix(): hashlib.sha256(path.read_bytes()).hexdigest()
for path in sorted(root.rglob('*')) if path.is_file()}
@pytest.fixture
def admin(app):
from app import db
return make_user(db, 'adopt_admin', 'admin')
def _by_domain(sites):
return {site['primary_domain']: site for site in sites}
# --------------------------------------------------------------- discovery
def test_discovery_describes_each_site_and_skips_the_panel(app, host):
from app.services import site_adoption_service
sites = _by_domain(site_adoption_service.discover())
# The panel's own vhost and the catch-all default are not sites.
assert set(sites) == {'shop.example.com', 'docs.example.com', 'api.example.com'}
shop = sites['shop.example.com']
assert shop['kind'] == 'php' and shop['app_type'] == 'wordpress'
assert shop['root'] == host['shop_root']
# The :80 redirect block and its www name fold into the one site.
assert shop['domains'] == ['shop.example.com', 'www.shop.example.com']
# 8.4 is outside PHPService.SUPPORTED_VERSIONS — found by the pool's socket.
assert shop['php'] == {'version': '8.4', 'pool': 'shop', 'listen': '/run/php/shop.sock',
'pool_file': shop['php']['pool_file']}
assert shop['ssl']['enabled'] and shop['ssl']['letsencrypt']
assert shop['ssl']['certificate'].endswith('shop.example.com/fullchain.pem')
assert shop['wordpress']['version'] == '6.8.1'
assert shop['database'] == {'engine': 'mysql', 'name': 'shop_wp',
'user': 'shop_user', 'host': 'localhost'}
assert shop['adoptable'] and shop['linked_app'] is None
docs = sites['docs.example.com']
assert (docs['kind'], docs['app_type'], docs['adoptable']) == ('static', 'static', True)
assert docs['root'] == host['docs_root'] and docs['php'] is None
api = sites['api.example.com']
assert (api['kind'], api['port'], api['adoptable']) == ('proxy', 3210, False)
assert 'Docker Compose or systemd' in api['reason']
def test_discovery_never_exposes_the_database_password(app, host):
from app.services import site_adoption_service
assert 'never-read-this' not in repr(site_adoption_service.discover())
def test_php_version_falls_back_to_the_socket_name(app, host):
from app.services import site_adoption_service
assert site_adoption_service._php_for('unix:/run/php/php8.2-fpm.sock', [])['version'] == '8.2'
assert site_adoption_service._php_for('127.0.0.1:9000', [])['version'] is None
# ----------------------------------------------------------------- adopting
def test_dry_run_is_the_default_and_changes_nothing(client, host, admin):
from app.models.application import Application
before = _snapshot(host['root'])
resp = client.post('/api/v1/site-adoption/adopt', json={'site': 'shop.example.com'},
headers=headers_for(admin))
assert resp.status_code == 200
body = resp.get_json()
assert body['dry_run'] is True and body['adoptable'] is True
assert body['plan']['application'] == {
'name': 'shop-example-com', 'app_type': 'wordpress', 'managed_by': 'host',
'source': 'manual', 'root_path': host['shop_root'], 'php_version': '8.4'}
assert [d['name'] for d in body['plan']['domains']] == [
'shop.example.com', 'www.shop.example.com']
assert any(path.endswith('shop.example.com.conf') for path in body['plan']['untouched'])
assert Application.query.filter_by(name='shop-example-com').first() is None
assert _snapshot(host['root']) == before
def test_adopt_records_the_site_and_writes_nothing_to_the_host(client, host, admin):
from app.models.application import Application
from app.models.domain import Domain
from app.models.managed_database import ManagedDatabase
from app.models.wordpress_site import WordPressSite
before = _snapshot(host['root'])
with patch('app.services.nginx_service.NginxService.create_site',
side_effect=AssertionError('adoption wrote a vhost')), \
patch('app.services.nginx_service.NginxService.write_vhost',
side_effect=AssertionError('adoption wrote a vhost')):
resp = client.post('/api/v1/site-adoption/adopt',
json={'site': 'shop.example.com', 'dry_run': False},
headers=headers_for(admin))
assert resp.status_code == 201, resp.get_json()
assert _snapshot(host['root']) == before
app_row = Application.query_active().filter_by(name='shop-example-com').one()
assert (app_row.app_type, app_row.managed_by, app_row.source) == ('wordpress', 'host', 'manual')
assert (app_row.status, app_row.php_version, app_row.root_path) == (
'running', '8.4', host['shop_root'])
assert app_row.is_host_managed and app_row.workspace_id is not None
domains = Domain.query_active().filter_by(application_id=app_row.id).order_by(Domain.id).all()
assert [(d.name, d.is_primary, d.ssl_enabled) for d in domains] == [
('shop.example.com', True, True), ('www.shop.example.com', False, True)]
assert domains[0].ssl_certificate_path.endswith('shop.example.com/fullchain.pem')
wp = WordPressSite.query.filter_by(application_id=app_row.id).one()
assert (wp.db_name, wp.db_user, wp.db_prefix, wp.wp_version) == (
'shop_wp', 'shop_user', 'shp_', '6.8.1')
# Not a compose site: nothing invented for the container fields.
assert wp.compose_project_name is None and wp.container_prefix is None
database = ManagedDatabase.query_active().filter_by(name='shop_wp').one()
assert database.owner_application_id == app_row.id and database.origin == 'adopted'
def test_an_adopted_site_is_no_longer_reported_or_adoptable(client, host, admin):
listing = client.get('/api/v1/site-adoption/sites', headers=headers_for(admin)).get_json()
assert (listing['unmanaged'], listing['adoptable']) == (3, 2)
client.post('/api/v1/site-adoption/adopt',
json={'site': 'docs.example.com', 'dry_run': False, 'name': 'docs'},
headers=headers_for(admin))
listing = client.get('/api/v1/site-adoption/sites', headers=headers_for(admin)).get_json()
assert (listing['unmanaged'], listing['adoptable']) == (2, 1)
docs = _by_domain(listing['sites'])['docs.example.com']
assert docs['linked_app']['name'] == 'docs' and not docs['adoptable']
again = client.post('/api/v1/site-adoption/adopt',
json={'site': 'docs.example.com', 'dry_run': False},
headers=headers_for(admin))
assert again.status_code == 409 and 'Already managed' in again.get_json()['error']
@pytest.mark.parametrize('site,status', [
('api.example.com', 409), # a proxied process, not a host site
('nope.example.com', 404), # nothing nginx serves
('serverkit.conf', 404), # the panel itself is never offered
])
def test_adopt_refuses_what_it_should_not_register(client, host, admin, site, status):
resp = client.post('/api/v1/site-adoption/adopt', json={'site': site, 'dry_run': False},
headers=headers_for(admin))
assert resp.status_code == status
def test_adoption_is_admin_only(client, host, app):
from app import db
developer = make_user(db, 'adopt_dev', 'developer')
assert client.get('/api/v1/site-adoption/sites',
headers=headers_for(developer)).status_code == 403
assert client.post('/api/v1/site-adoption/adopt', json={'site': 'docs.example.com'},
headers=headers_for(developer)).status_code == 403
assert client.get('/api/v1/site-adoption/sites').status_code == 401
# ------------------------------------- the panel leaves the running config alone
@pytest.fixture
def adopted(client, host, admin):
from app.models.application import Application
client.post('/api/v1/site-adoption/adopt',
json={'site': 'shop.example.com', 'dry_run': False}, headers=headers_for(admin))
return Application.query_active().filter_by(name='shop-example-com').one()
def test_vhost_writer_and_drift_skip_a_host_managed_site(app, adopted):
from app.services import drift_service
from app.services.site_domain_service import SiteDomainService
with patch('app.services.nginx_service.NginxService.create_site',
side_effect=AssertionError('rewrote a host-managed vhost')):
result = SiteDomainService.write_app_vhost(adopted)
assert result['nginx'] is None and 'host-managed' in result['warning']
assert adopted.id not in {app_id for app_id, _ in drift_service._nginx_list_resources()}
assert drift_service._nginx_render_expected(adopted.id) == {}
def test_adding_a_domain_records_it_without_touching_nginx(client, admin, host):
# The static site, not the WordPress one: a static app has everything the
# vhost writer needs (a root), so only the host-managed guard stops it.
from app.models.application import Application
client.post('/api/v1/site-adoption/adopt',
json={'site': 'docs.example.com', 'dry_run': False}, headers=headers_for(admin))
adopted = Application.query_active().filter_by(name='docs-example-com').one()
before = _snapshot(host['root'])
# A mock, not a raising stub: the vhost writer swallows exceptions by design.
with patch('app.services.nginx_service.NginxService.create_site') as create_site:
resp = client.post('/api/v1/domains',
json={'name': 'store.example.com', 'application_id': adopted.id},
headers=headers_for(admin))
assert resp.status_code in (200, 201), resp.get_json()
create_site.assert_not_called()
assert _snapshot(host['root']) == before
@pytest.mark.parametrize('action', ['start', 'stop', 'restart'])
def test_lifecycle_refuses_instead_of_lying(client, admin, adopted, action):
resp = client.post(f'/api/v1/apps/{adopted.id}/{action}', headers=headers_for(admin))
assert resp.status_code >= 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() == []