"""Controlled Docker Compose application lifecycle. The command runner must be supplied by the caller. This module does not execute subprocesses directly. """ import json import os import stat import tempfile from pathlib import Path, PurePosixPath from core.backup import sync_directory from core.site_secrets import SiteSecrets from core.configuration import ( ConfigurationError, validate_config, ) class ServiceError(RuntimeError): """Application service lifecycle operation failed.""" def require(condition, message): if not condition: raise ServiceError(message) class ServiceLifecycle: def __init__( self, config, runner, stop_timeout=90, *, site_secrets=None, topology_runner=None, ): require( callable(runner), "A command runner is required", ) require( type(stop_timeout) is int and 1 <= stop_timeout <= 300, "Invalid graceful shutdown timeout", ) try: validated = validate_config(config) except ConfigurationError: raise ServiceError( "Invalid service configuration" ) from None docker = validated["docker"] root = PurePosixPath( validated["site"]["root"] ) self._prefix = ( "docker", "compose", "--project-name", docker["project"], "--project-directory", str(root), "--file", str(root / "compose.yaml"), ) if site_secrets is not None: require(isinstance(site_secrets, SiteSecrets), "Invalid managed site secrets") self._prefix += ("--file", str(site_secrets.compose_file(validated))) self._php = docker["php_service"] self._web = docker["web_service"] self._queue = docker["queue_service"] self._scheduler = docker["scheduler_service"] self._backend_network = docker["backend_network"] self._topology_runner = topology_runner self._runner = runner self._stop_timeout = stop_timeout def _execute(self, operation, args, timeout): command = ( *self._prefix, *args, ) try: result = self._runner( command, timeout=timeout, ) except Exception: raise ServiceError( f"Service operation failed: {operation}" ) from None require( type(result) is int and result == 0, f"Service operation failed: {operation}", ) def _require_project_backend(self): require(callable(self._topology_runner), "Trusted Compose topology runner required") command = (*self._prefix, "config", "--format", "json") try: model = json.loads(self._topology_runner(command, timeout=30)) backend = model["networks"][self._backend_network] except Exception: raise ServiceError("Unable to verify Compose backend network") from None require(isinstance(backend, dict), "Invalid Compose backend network") require(backend.get("external", False) is False, "External Compose backend networks are prohibited") def quiesce(self): self._execute( "quiesce workers", ( "stop", "--timeout", str(self._stop_timeout), self._queue, self._scheduler, ), timeout=self._stop_timeout + 30, ) def restart_php(self): self._require_project_backend() self._execute( "restart PHP", ( "restart", "--timeout", str(self._stop_timeout), self._php, ), timeout=self._stop_timeout + 30, ) def validate_nginx(self): self._execute( "validate nginx", ( "exec", "-T", "--interactive=false", self._web, "nginx", "-t", ), timeout=30, ) def reload_nginx(self): self.validate_nginx() self._execute( "reload nginx", ( "exec", "-T", "--interactive=false", self._web, "nginx", "-s", "reload", ), timeout=30, ) def refresh(self): self.restart_php() self.reload_nginx() def resume(self): self._require_project_backend() self._execute( "resume workers", ( "up", "-d", "--no-deps", self._queue, self._scheduler, ), timeout=120, ) class ContainedServiceLifecycle(ServiceLifecycle): """Docker Compose lifecycle with a durable Nginx ingress gate. The controller must run under its site lock and use a protected origin for health validation. The public probe must identify the maintenance response specifically, rather than treating any error as containment. """ def __init__(self, config, runner, *, gate_directory, ingress_sealed, worker_running, stop_timeout=90, site_secrets=None, topology_runner=None): super().__init__(config, runner, stop_timeout, site_secrets=site_secrets, topology_runner=topology_runner) require(callable(ingress_sealed) and callable(worker_running), "Containment probes are required") self._gate_directory = Path(gate_directory) self._gate = self._gate_directory / "closed" self._ingress_sealed = ingress_sealed self._worker_running = worker_running self._validate_gate_directory() def _validate_gate_directory(self): root = self._gate_directory info = root.lstat() require(root.resolve() == root and stat.S_ISDIR(info.st_mode) and info.st_uid == os.geteuid() and not info.st_mode & 0o022, "Unsafe Nginx gate directory") def _sealed(self): self._validate_gate_directory() try: info = self._gate.lstat() except FileNotFoundError: return False require(stat.S_ISREG(info.st_mode) and info.st_nlink == 1 and info.st_uid == os.geteuid() and not info.st_mode & 0o022, "Unsafe Nginx maintenance sentinel") return True def _seal(self): if self._sealed(): sync_directory(self._gate_directory) return with tempfile.NamedTemporaryFile(dir=self._gate_directory, prefix=".gate-", delete=False) as handle: pending = Path(handle.name) try: os.fchmod(handle.fileno(), 0o644) handle.write(b"maintenance\n") handle.flush() os.fsync(handle.fileno()) os.replace(pending, self._gate) sync_directory(self._gate_directory) finally: pending.unlink(missing_ok=True) def _workers_are(self, running): return all(self._worker_running(name) is running for name in (self._queue, self._scheduler)) def stopped(self): return self._sealed() and self._workers_are(False) def require_contained(self): require(self.stopped() and self._ingress_sealed() is True, "HTTP and worker containment could not be verified") def quiesce(self): try: self._seal() require(self._ingress_sealed() is True, "Nginx maintenance response was not observed") finally: super().quiesce() self.require_contained() def refresh(self): self.require_contained() super().refresh() self.require_contained() def resume(self): # Called by the controller only after protected health and the # completion record have been verified under the site lock. self.require_contained() try: super().resume() require(self._workers_are(True), "Background worker startup was not verified") require(self._sealed(), "Maintenance sentinel changed during worker startup") self._gate.unlink() sync_directory(self._gate_directory) except BaseException: self.quiesce() raise