mirror of
https://github.com/jhd3197/ServerKit.git
synced 2026-12-01 20:55:16 +09:00
Mount site adoption on the apps blueprint
The adoption routes added a blueprint to the curated core registry, which is kept exact on purpose. They now register on the existing apps blueprint as an area module, the way the server area modules do, under /apps/host-sites. The host-managed check becomes a function that compares the attribute, so services handed a stand-in app object (as the lifecycle tests do) get False instead of an AttributeError.
This commit is contained in:
1 parent
ebb19c8444
commit
2366d8b9bf
12 files changed
+61
-39
No files matched your search
+1
-1
@@ -619,7 +619,7 @@ platform infrastructure; new capability areas ship as Marketplace extensions.
|
||||
Issue #269 — a site already running on the host was invisible to the panel.
|
||||
|
||||
- [x] Discover the sites host nginx serves: vhost, document root, PHP-FPM pool and version, WordPress database, certificate.
|
||||
- [x] Adopt a site in place (`serverkit adopt-site`, the Services page, `POST /site-adoption/adopt`), dry run by default, writing rows and never config.
|
||||
- [x] Adopt a site in place (`serverkit adopt-site`, the Services page, `POST /apps/host-sites/adopt`), dry run by default, writing rows and never config.
|
||||
- [x] `managed_by = host`: the vhost writer, drift repair, lifecycle and delete paths leave a host-managed site's running config alone.
|
||||
- [x] Report unmanaged sites in the doctor and on Services.
|
||||
- [x] Document the hand-migration path that ends in adoption (`docs/COEXISTENCE.md`).
|
||||
|
||||
@@ -11,6 +11,7 @@ from sqlalchemy.orm import joinedload
|
||||
from app import db
|
||||
from app.api._query import apply_query, QueryParseError
|
||||
from app.models import Application, User
|
||||
from app.models.application import is_host_managed
|
||||
from app.utils.slug import app_name_clash_error, slugify
|
||||
from app.services.build_service import BuildService
|
||||
from app.services.docker_service import DockerService
|
||||
@@ -85,7 +86,7 @@ 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:
|
||||
elif is_host_managed(app):
|
||||
# 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')
|
||||
@@ -2415,3 +2416,7 @@ def delete_app_db_snapshot(app_id, snapshot_id):
|
||||
db.session.delete(snapshot)
|
||||
db.session.commit()
|
||||
return jsonify({'success': True, 'message': 'Snapshot deleted'}), 200
|
||||
|
||||
|
||||
# Area modules register their routes on apps_bp when imported.
|
||||
from app.api import apps_adoption # noqa: E402,F401
|
||||
@@ -1,24 +1,24 @@
|
||||
"""Site adoption API — register sites that already run on this host.
|
||||
"""Site adoption routes — 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.
|
||||
An area module of the apps blueprint: importing it registers the routes on
|
||||
``apps_bp`` (see the bottom of app/api/apps.py), so they live under
|
||||
/api/v1/apps/host-sites. 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 flask import jsonify, request
|
||||
|
||||
from app.api._request import json_object
|
||||
from app.api.apps import apps_bp
|
||||
from app.exceptions import field_required
|
||||
from app.middleware.rbac import admin_required, get_current_user
|
||||
from app.services import site_adoption_service
|
||||
|
||||
site_adoption_bp = Blueprint('site_adoption', __name__)
|
||||
|
||||
|
||||
@site_adoption_bp.route('/sites', methods=['GET'])
|
||||
@apps_bp.route('/host-sites', methods=['GET'])
|
||||
@admin_required
|
||||
def list_sites():
|
||||
def list_host_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()
|
||||
@@ -29,9 +29,9 @@ def list_sites():
|
||||
}), 200
|
||||
|
||||
|
||||
@site_adoption_bp.route('/adopt', methods=['POST'])
|
||||
@apps_bp.route('/host-sites/adopt', methods=['POST'])
|
||||
@admin_required
|
||||
def adopt_site():
|
||||
def adopt_host_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()
|
||||
@@ -271,7 +271,6 @@ 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',
|
||||
|
||||
@@ -195,8 +195,9 @@ class Application(JsonColumnMixin, TimestampMixin, SoftDeleteMixin, db.Model):
|
||||
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
|
||||
path that touches nginx or the runtime for an app checks this (through
|
||||
:func:`is_host_managed`, which also accepts a stand-in object)."""
|
||||
return is_host_managed(self)
|
||||
|
||||
@property
|
||||
def live_domains(self):
|
||||
@@ -362,3 +363,14 @@ def _clear_cron_association(mapper, connection, target):
|
||||
CronService.clear_application(target.id)
|
||||
except Exception: # noqa: BLE001 - cleanup must not block app deletion
|
||||
pass
|
||||
|
||||
|
||||
def is_host_managed(app):
|
||||
"""Whether ``app`` is an adopted host site (``managed_by == 'host'``).
|
||||
|
||||
A function rather than only the property so the services that guard on
|
||||
it can be handed any app-shaped object: a plain attribute comparison
|
||||
answers False for one that has no ``managed_by``, where reading a
|
||||
property off a stand-in would raise or, on a mock, read as true.
|
||||
"""
|
||||
return getattr(app, 'managed_by', None) == Application.MANAGED_BY_HOST
|
||||
@@ -145,7 +145,8 @@ def _refuse_host_managed(app, action):
|
||||
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:
|
||||
from app.models.application import is_host_managed
|
||||
if is_host_managed(app):
|
||||
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.')
|
||||
|
||||
@@ -28,6 +28,7 @@ import shutil
|
||||
|
||||
from app import db
|
||||
from app.models import Application
|
||||
from app.models.application import is_host_managed
|
||||
from app.services.cron_service import CronService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -206,7 +207,7 @@ def suspend_application(app, user_id=None):
|
||||
except Exception as exc: # noqa: BLE001
|
||||
results['docker'] = {'error': str(exc)}
|
||||
|
||||
if app.is_host_managed:
|
||||
if is_host_managed(app):
|
||||
# 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.
|
||||
|
||||
@@ -342,9 +342,10 @@ def _nginx_list_resources():
|
||||
.filter(Domain.deleted_at.is_(None))
|
||||
.distinct()
|
||||
.all())
|
||||
from app.models.application import is_host_managed
|
||||
# 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]
|
||||
return [(app.id, app.name) for app in rows if not is_host_managed(app)]
|
||||
|
||||
|
||||
def _nginx_render_expected(app_id):
|
||||
|
||||
@@ -536,13 +536,14 @@ class SiteDomainService:
|
||||
domains (nothing to publish), ``(None, reason)`` when it can't be
|
||||
published via host nginx.
|
||||
"""
|
||||
from app.models.application import is_host_managed
|
||||
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:
|
||||
if is_host_managed(app):
|
||||
return None, ('This site is host-managed: ServerKit records its domains '
|
||||
'but does not rewrite its nginx config.')
|
||||
|
||||
|
||||
@@ -164,7 +164,7 @@ def test_php_version_falls_back_to_the_socket_name(app, host):
|
||||
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'},
|
||||
resp = client.post('/api/v1/apps/host-sites/adopt', json={'site': 'shop.example.com'},
|
||||
headers=headers_for(admin))
|
||||
assert resp.status_code == 200
|
||||
body = resp.get_json()
|
||||
@@ -189,7 +189,7 @@ def test_adopt_records_the_site_and_writes_nothing_to_the_host(client, host, adm
|
||||
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',
|
||||
resp = client.post('/api/v1/apps/host-sites/adopt',
|
||||
json={'site': 'shop.example.com', 'dry_run': False},
|
||||
headers=headers_for(admin))
|
||||
assert resp.status_code == 201, resp.get_json()
|
||||
@@ -217,18 +217,18 @@ def test_adopt_records_the_site_and_writes_nothing_to_the_host(client, host, adm
|
||||
|
||||
|
||||
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()
|
||||
listing = client.get('/api/v1/apps/host-sites', headers=headers_for(admin)).get_json()
|
||||
assert (listing['unmanaged'], listing['adoptable']) == (3, 2)
|
||||
|
||||
client.post('/api/v1/site-adoption/adopt',
|
||||
client.post('/api/v1/apps/host-sites/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()
|
||||
listing = client.get('/api/v1/apps/host-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',
|
||||
again = client.post('/api/v1/apps/host-sites/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']
|
||||
@@ -240,7 +240,7 @@ def test_an_adopted_site_is_no_longer_reported_or_adoptable(client, host, admin)
|
||||
('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},
|
||||
resp = client.post('/api/v1/apps/host-sites/adopt', json={'site': site, 'dry_run': False},
|
||||
headers=headers_for(admin))
|
||||
assert resp.status_code == status
|
||||
|
||||
@@ -248,11 +248,11 @@ def test_adopt_refuses_what_it_should_not_register(client, host, admin, site, st
|
||||
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',
|
||||
assert client.get('/api/v1/apps/host-sites',
|
||||
headers=headers_for(developer)).status_code == 403
|
||||
assert client.post('/api/v1/site-adoption/adopt', json={'site': 'docs.example.com'},
|
||||
assert client.post('/api/v1/apps/host-sites/adopt', json={'site': 'docs.example.com'},
|
||||
headers=headers_for(developer)).status_code == 403
|
||||
assert client.get('/api/v1/site-adoption/sites').status_code == 401
|
||||
assert client.get('/api/v1/apps/host-sites').status_code == 401
|
||||
|
||||
|
||||
# ------------------------------------- the panel leaves the running config alone
|
||||
@@ -260,7 +260,7 @@ def test_adoption_is_admin_only(client, host, app):
|
||||
@pytest.fixture
|
||||
def adopted(client, host, admin):
|
||||
from app.models.application import Application
|
||||
client.post('/api/v1/site-adoption/adopt',
|
||||
client.post('/api/v1/apps/host-sites/adopt',
|
||||
json={'site': 'shop.example.com', 'dry_run': False}, headers=headers_for(admin))
|
||||
return Application.query_active().filter_by(name='shop-example-com').one()
|
||||
|
||||
@@ -280,7 +280,7 @@ 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',
|
||||
client.post('/api/v1/apps/host-sites/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'])
|
||||
@@ -364,7 +364,7 @@ def test_doctor_reports_unmanaged_sites_until_they_are_adopted(client, host, adm
|
||||
# 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',
|
||||
client.post('/api/v1/apps/host-sites/adopt',
|
||||
json={'site': 'shop.example.com', 'dry_run': False}, headers=headers_for(admin))
|
||||
assert 'sites.unmanaged.shop.example.com.conf' not in unmanaged()
|
||||
|
||||
|
||||
+4
-2
@@ -159,6 +159,7 @@ Regenerate (backend/):
|
||||
- `GET /api-keys/{key_id}`
|
||||
- `GET /apps`
|
||||
- `GET /apps/attachments/services`
|
||||
- `GET /apps/host-sites`
|
||||
- `GET /apps/p/{slug}`
|
||||
- `GET /apps/{app_id}`
|
||||
- `GET /apps/{app_id}/attachments`
|
||||
@@ -599,6 +600,7 @@ Regenerate (backend/):
|
||||
- `GET /servers/{server_id}/system/metrics`
|
||||
- `GET /servers/{server_id}/timeline`
|
||||
- `GET /services`
|
||||
- `GET /services/host-sites`
|
||||
- `GET /services/{app_id}`
|
||||
- `GET /services/{app_id}/backup-policy`
|
||||
- `GET /services/{app_id}/backups`
|
||||
@@ -625,7 +627,6 @@ Regenerate (backend/):
|
||||
- `GET /shared/tags`
|
||||
- `GET /shared/variable-groups`
|
||||
- `GET /shared/variable-groups/{group_id}`
|
||||
- `GET /site-adoption/sites`
|
||||
- `GET /source-connections/admin/bitbucket`
|
||||
- `GET /source-connections/admin/github`
|
||||
- `GET /source-connections/admin/github/app-manifest`
|
||||
@@ -771,6 +772,7 @@ Regenerate (backend/):
|
||||
- `POST /api-keys/{key_id}/rotate`
|
||||
- `POST /apps`
|
||||
- `POST /apps/from-repository`
|
||||
- `POST /apps/host-sites/adopt`
|
||||
- `POST /apps/htaccess-convert`
|
||||
- `POST /apps/manual`
|
||||
- `POST /apps/move-to-project`
|
||||
@@ -1187,6 +1189,7 @@ Regenerate (backend/):
|
||||
- `POST /servers/{server_id}/terminal`
|
||||
- `POST /services`
|
||||
- `POST /services/from-repository`
|
||||
- `POST /services/host-sites/adopt`
|
||||
- `POST /services/manual`
|
||||
- `POST /services/move-to-project`
|
||||
- `POST /services/sweep-idle`
|
||||
@@ -1217,7 +1220,6 @@ Regenerate (backend/):
|
||||
- `POST /shared/variable-groups/{group_id}/attach`
|
||||
- `POST /shared/variable-groups/{group_id}/detach`
|
||||
- `POST /shared/variable-groups/{group_id}/variables`
|
||||
- `POST /site-adoption/adopt`
|
||||
- `POST /source-connections/admin/github/app-manifest/complete`
|
||||
- `POST /source-connections/bitbucket/callback`
|
||||
- `POST /source-connections/github/callback`
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
// Site adoption (/api/v1/site-adoption) — register sites that already run on
|
||||
// Site adoption (/api/v1/apps/host-sites) — register sites that already run on
|
||||
// this host. Discovery is read-only; adopting records rows and never rewrites
|
||||
// the running nginx / PHP-FPM config. Admin-only on the server.
|
||||
|
||||
export async function getHostSites() {
|
||||
return this.request('/site-adoption/sites');
|
||||
return this.request('/apps/host-sites');
|
||||
}
|
||||
|
||||
// A dry run unless `apply` is true: the server's default answer is the plan.
|
||||
export async function adoptHostSite(site, { name, apply = false } = {}) {
|
||||
return this.request('/site-adoption/adopt', {
|
||||
return this.request('/apps/host-sites/adopt', {
|
||||
method: 'POST',
|
||||
body: { site, name: name || undefined, dry_run: !apply },
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user