347 lines
11 KiB
Python
347 lines
11 KiB
Python
"""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,
|
|
docker_workers,
|
|
)
|
|
|
|
|
|
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 "compose_override" in docker:
|
|
self._prefix += ("--file", str(root / docker["compose_override"]))
|
|
|
|
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._workers = docker_workers(docker)
|
|
self._project = docker["project"]
|
|
self._inspection_only = validated["site"].get("checkout_layout") == "in-place"
|
|
self._backend_network = docker.get("backend_network")
|
|
self._private_backends = docker.get("private_backends")
|
|
self._topology_runner = topology_runner
|
|
self._runner = runner
|
|
self._stop_timeout = stop_timeout
|
|
|
|
def _execute(self, operation, args, timeout):
|
|
require(not self._inspection_only, "In-place checkout lifecycle is inspection only")
|
|
|
|
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))
|
|
if self._private_backends is None:
|
|
backend = model["networks"][self._backend_network]
|
|
else:
|
|
self._require_private_backends(model)
|
|
return
|
|
except ServiceError:
|
|
raise
|
|
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 _require_private_backends(self, model):
|
|
consumers = (self._php, *self._workers)
|
|
declared = self._private_backends
|
|
networks = model["networks"]
|
|
for service in consumers:
|
|
bindings = set(model["services"][service]["networks"])
|
|
require(set(declared) <= bindings, "A service is missing a private backend binding")
|
|
require(all(not networks[name].get("external", False) or name in declared
|
|
for name in bindings), "A service uses an undeclared external backend")
|
|
|
|
for key, binding in declared.items():
|
|
network = networks[key]
|
|
require(network.get("external") is True and network.get("name") == binding["name"],
|
|
"The resolved private backend differs from the manifest")
|
|
inspection = ("docker", "network", "inspect", binding["name"])
|
|
matches = json.loads(self._topology_runner(inspection, timeout=30))
|
|
require(isinstance(matches, list) and len(matches) == 1,
|
|
"Unable to verify private Docker network")
|
|
actual = matches[0]
|
|
require(actual["Name"] == binding["name"] and actual["Internal"] is True
|
|
and actual["Driver"] == "bridge" and actual["Scope"] == "local",
|
|
"The declared private network must be an internal local bridge")
|
|
names = {item["Name"] for item in actual["Containers"].values()}
|
|
allowed = {f"{self._project}-{service}-1" for service in consumers}
|
|
require(binding["container"] in names and names <= allowed | {binding["container"]},
|
|
"The private network has unexpected members")
|
|
|
|
def quiesce(self):
|
|
|
|
if not self._workers:
|
|
return
|
|
self._execute(
|
|
"quiesce workers",
|
|
(
|
|
"stop",
|
|
"--timeout",
|
|
str(self._stop_timeout),
|
|
*self._workers,
|
|
),
|
|
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):
|
|
|
|
if not self._workers:
|
|
return
|
|
self._require_project_backend()
|
|
self._execute(
|
|
"resume workers",
|
|
(
|
|
"up",
|
|
"-d",
|
|
"--no-deps",
|
|
*self._workers,
|
|
),
|
|
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(not self._inspection_only, "In-place checkout lifecycle is inspection only")
|
|
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._workers)
|
|
|
|
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
|