ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
Point container actions at the live slot
Juan Denis8bd78d69cda5
diff --git a/backend/app/services/application_lifecycle_service.py b/backend/app/services/application_lifecycle_service.pyindex 95626147..ccac35da 100644--- a/backend/app/services/application_lifecycle_service.py+++ b/backend/app/services/application_lifecycle_service.py@@ -70,6 +70,8 @@ def _is_single_container_app(app):"""if app.server_id or app.compose_file or not app.root_path:return False+ if getattr(app, 'slot_deploys_enabled', False) and app.active_slot:+ return True # a slot app runs one live container (plan 87)if not app.buildpack_type:return Falsereturn not any(@@ -80,12 +82,13 @@ def _is_single_container_app(app):def _app_container_name(app):- """The single container a build-pack deploy creates for this app.+ """The single container serving this app.- Must match ``DeploymentService._deploy_docker``, which names it- ``serverkit-app-<id>``.+ ``serverkit-app-<id>`` for an in-place deploy (``DeploymentService.+ _deploy_docker``); the live slot's container for a slot app (plan 87)."""- return f'serverkit-app-{app.id}'+ from app.services.slot_deploy_service import live_container_name+ return live_container_name(app)def _ensure_local_image_compose(app):@@ -199,6 +202,10 @@ def stop_application(app, *, user_id=None):result = ({'success': True} if not DockerService.get_container(container)else DockerService.stop_container(container))WorkerProcessService.each(app, 'stop')+ # A stopped app keeps no warm standby running behind it.+ if getattr(app, 'slot_deploys_enabled', False):+ from app.services.slot_deploy_service import SlotDeployService+ SlotDeployService.stop_standby(app)else:result = DockerService.compose_down(app.root_path,diff --git a/backend/app/services/docker_service.py b/backend/app/services/docker_service.pyindex fd8df993..d2814cfb 100644--- a/backend/app/services/docker_service.py+++ b/backend/app/services/docker_service.py@@ -515,8 +515,13 @@ class DockerService:return [{'id': container_id, 'name': container_id, 'service': 'main', 'state': 'unknown'}]return []- containers = cls.compose_ps(root_path, compose_file=compose_file)app_id = cls._app_attr(app, 'id')+ if (app_id and not compose_file and not isinstance(app, dict)+ and cls._app_attr(app, 'slot_deploys_enabled') and cls._app_attr(app, 'active_slot')):+ # A slot app (plan 87): the live slot, its standby, its workers.+ from app.services.slot_deploy_service import SlotDeployService+ return SlotDeployService.containers(app)+ containers = cls.compose_ps(root_path, compose_file=compose_file)if not containers and app_id and cls._app_attr(app, 'buildpack_type'):# A build-pack app is not a compose project: its deploy runs# `serverkit-app-<id>` plus one `serverkit-app-<id>-<process>` perdiff --git a/backend/app/services/restore_point_adapter_nginx.py b/backend/app/services/restore_point_adapter_nginx.pyindex 0757d8d3..f1c146a9 100644--- a/backend/app/services/restore_point_adapter_nginx.py+++ b/backend/app/services/restore_point_adapter_nginx.py@@ -36,11 +36,71 @@ def capture(scope_id, server_id=None):content = NginxService.read_vhost(name) if exists else Noneif exists and content is None:raise RuntimeError(f'Existing nginx vhost {name} could not be read')- return {+ payload = {'exists': exists,'enabled': os.path.exists(enabled_path),'content': content,}+ slot = _slot_state(name, content)+ if slot:+ payload['slot'] = slot+ return payload+++def _slot_app(name):+ from app.models.application import Application+ app = Application.query_active().filter_by(name=name, server_id=None).first()+ return app if app is not None and app.slot_deploys_enabled and app.active_slot else None+++def _slot_state(name, content):+ """Which slot the captured vhost points at (plan 87).++ A slot app's vhost proxies to the live slot's port; restoring the file+ without restoring the slot would point nginx at a standby that may be+ stopped. Read from the vhost bytes, not ``app.port``: a switch captures+ the OLD file after it has already moved ``app.port`` to the new slot.+ """+ import re+ from flask import has_app_context+ from app.models.app_slot import AppSlot+ ports = {int(p) for p in re.findall(r'proxy_pass http://127\.0\.0\.1:(\d+)', content or '')}+ if not ports or not has_app_context():+ return None+ app = _slot_app(name)+ if app is None:+ return None+ for row in AppSlot.query.filter_by(application_id=app.id).all():+ if row.host_port in ports:+ return {'active_slot': row.slot, 'port': row.host_port}+ return None+++def _restore_slot(name, slot):+ """Make the captured slot live again before the vhost points at it."""+ from app import db+ from app.models.app_slot import AppSlot+ from app.services.docker_service import DockerService+ app = _slot_app(name)+ if app is None or not isinstance(slot, dict) or slot.get('active_slot') == app.active_slot:+ return None+ row = AppSlot.query.filter_by(application_id=app.id, slot=slot.get('active_slot')).first()+ if row is None or not row.container_name or not DockerService.get_container(row.container_name):+ return {'success': False,+ 'error': f"Slot {slot.get('active_slot')} of {name} no longer has a container; "+ 'deploy that release again instead of restoring this vhost.'}+ started = DockerService.start_container(row.container_name)+ if not started.get('success'):+ return started+ current = AppSlot.query.filter_by(application_id=app.id, slot=app.active_slot).first()+ if current is not None:+ current.state = 'standby'+ row.state = 'live'+ app.active_slot = row.slot+ app.port = row.host_port+ app.container_id = row.container_name+ db.session.commit()+ return Nonedef _validate_payload(payload):@@ -62,6 +122,11 @@ def restore(scope_id, payload, actor=None, server_id=None):name = _validate_scope(scope_id, server_id)exists, enabled, content = _validate_payload(payload)+ if exists and payload.get('slot'):+ refused = _restore_slot(name, payload['slot'])+ if refused:+ return refused+if not exists:return NginxService.delete_site(name)diff --git a/backend/app/services/slot_deploy_service.py b/backend/app/services/slot_deploy_service.pyindex 5aa79609..58030aff 100644--- a/backend/app/services/slot_deploy_service.py+++ b/backend/app/services/slot_deploy_service.py@@ -500,6 +500,52 @@ class SlotDeployService:slot.standby_until = Nonedb.session.commit()+ @classmethod+ def stop_standby(cls, app) -> None:+ """Stop the app's warm standby now (the app itself is being stopped)."""+ for slot in AppSlot.query.filter_by(application_id=app.id, state='standby').all():+ cls._stop_standby(slot)++ @classmethod+ def containers(cls, app) -> list:+ """The live slot, the standby and the Procfile workers, for listings.++ The live container is service ``web`` (what logs and the terminal+ open by default); the standby is listed as ``standby`` so it is visible+ but never mistaken for the release that serves.+ """+ import json+ from app.services.docker_service import DockerService+ from app.services.worker_process_service import container_prefix+ live = live_container_name(app)+ rows = AppSlot.query.filter_by(application_id=app.id).all()+ slot_names = {r.container_name for r in rows if r.container_name}+ prefix = container_prefix(app)+ listed = DockerService.run(+ ['ps', '-a', '--filter', f'name=^serverkit-slot-{app.id}-',+ '--filter', f'name=^{legacy_container_name(app)}$',+ '--filter', f'name=^{prefix}',+ '--format', '{{json .}}'], timeout=30)+ result = []+ for line in (listed.get('output') or '').splitlines() if listed.get('success') else []:+ try:+ c = json.loads(line)+ except ValueError:+ continue+ name = c.get('Names') or ''+ if name == live:+ service = 'web'+ elif name in slot_names:+ service = 'standby'+ elif name.startswith(prefix):+ service = name[len(prefix):]+ else:+ continue # a stale slot container no row points at+ result.append({'id': c.get('ID'), 'name': name, 'service': service,+ 'state': (c.get('State') or '').lower()})+ order = {'web': 0, 'standby': 2}+ return sorted(result, key=lambda c: (order.get(c['service'], 1), c['service']))+@classmethoddef sweep_standby(cls) -> Dict:"""Stop warm standbys whose time is up (a builtin periodic tick).diff --git a/backend/tests/test_plan87_slot_deploys.py b/backend/tests/test_plan87_slot_deploys.pyindex 62b68ce2..876a4296 100644--- a/backend/tests/test_plan87_slot_deploys.py+++ b/backend/tests/test_plan87_slot_deploys.py@@ -464,3 +464,68 @@ def test_slots_api_round_trip(app, world, client, auth_headers):resp = client.put(f'/api/v1/apps/{row.id}/slots', headers=auth_headers, json={'enabled': 'yes'})assert resp.status_code == 400++# ── §E: everything else that touches the container follows the live slot ────++def test_restart_and_stop_act_on_the_live_slot_and_stop_the_standby(app, world, monkeypatch):+ from app.services import application_lifecycle_service as lifecycle+ from app.services.worker_process_service import WorkerProcessService+ monkeypatch.setattr(WorkerProcessService, 'each', classmethod(lambda cls, app, action: None))+ restarted = []+ monkeypatch.setattr(DockerService, 'restart_container', staticmethod(+ lambda name: restarted.append(name) or {'success': True}))+ row = _live_app(world)+ _two_deploys(world, row) # live b, standby a++ lifecycle.restart_application(row)+ assert restarted == [f'serverkit-slot-{row.id}-b']++ lifecycle.stop_application(row)+ assert world.containers[f'serverkit-slot-{row.id}-b']['running'] is False+ assert world.containers[f'serverkit-app-{row.id}']['running'] is False, 'standby stopped too'+ assert AppSlot.query.filter_by(application_id=row.id, slot='a').one().state == 'stopped'+++def test_container_listing_shows_live_standby_and_workers(app, world, monkeypatch):+ import json+ row = _live_app(world)+ _two_deploys(world, row)+ listed = [{'ID': '1', 'Names': f'serverkit-app-{row.id}', 'State': 'running'},+ {'ID': '2', 'Names': f'serverkit-slot-{row.id}-b', 'State': 'running'},+ {'ID': '3', 'Names': f'serverkit-app-{row.id}-worker', 'State': 'running'}]+ monkeypatch.setattr(DockerService, 'run', classmethod(lambda cls, args, **kw: {+ 'success': True, 'output': '\n'.join(json.dumps(c) for c in listed)}))++ containers = DockerService.get_all_app_containers(row)++ assert [(c['name'], c['service']) for c in containers] == [+ (f'serverkit-slot-{row.id}-b', 'web'),+ (f'serverkit-app-{row.id}-worker', 'worker'),+ (f'serverkit-app-{row.id}', 'standby'),+ ]+ # Status, stats, terminal and logs resolve the live container by id.+ assert DockerService.get_app_container_id(row) == f'serverkit-slot-{row.id}-b'+++def test_a_vhost_restore_point_brings_back_the_slot_it_pointed_at(app, world, monkeypatch):+ from app.services import restore_point_adapter_nginx as adapter+ from app.services.nginx_service import NginxService+ row = _live_app(world)+ _two_deploys(world, row) # live b; vhost -> b's port+ old_vhost = 'server {\n location / {\n proxy_pass http://127.0.0.1:8100;\n }\n}\n'+ monkeypatch.setattr(adapter.os.path, 'exists', lambda p: True)+ monkeypatch.setattr(NginxService, 'read_vhost', classmethod(lambda cls, name: old_vhost))++ payload = adapter.capture(row.name)+ # The captured bytes point at 8100 = slot a, whatever app.port says now.+ assert payload['slot'] == {'active_slot': 'a', 'port': 8100}++ world.containers[f'serverkit-app-{row.id}']['running'] = False # standby went cold+ monkeypatch.setattr(NginxService, 'write_vhost', classmethod(+ lambda cls, name, content, enable=True: {'success': True}))+ result = adapter.restore(row.name, payload)++ assert result['success'], result+ assert row.active_slot == 'a' and row.port == 8100+ assert world.containers[f'serverkit-app-{row.id}']['running'] is True+