Apply web deployment manifests on Ubuntu nodes

Create isolated site accounts, validate both service configurations,
and roll back newly installed files when activation fails.
This commit is contained in:
parkel committed 2026-11-19 21:52:43 +01:00
1 parent aea049087d
commit 5384d70d03
4 files changed
+372 -1

No files matched your search

@@ -0,0 +1,75 @@
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import call, patch
from django.test import SimpleTestCase
from coulobre.web_node import WebSite
from coulobre.web_node_apply import install_configurations
class WebNodeConfigurationTests(SimpleTestCase):
def setUp(self):
directory = Path(self.enterContext(TemporaryDirectory()))
apache_available = directory / "sites-available"
apache_enabled = directory / "sites-enabled"
apache_available.mkdir()
apache_enabled.mkdir()
self.site = WebSite(42, "example.org")
self.apache = apache_available / "coulobre-42.conf"
self.enabled = apache_enabled / self.apache.name
self.pool = directory / "php.conf"
self.socket = directory / "coulobre-42.sock"
self.runner = self.enterContext(patch("coulobre.web_node_apply.run"))
self.readiness = self.enterContext(
patch("coulobre.web_node_apply.wait_for_socket")
)
def install(self):
install_configurations(
self.site, self.apache, self.enabled, self.pool, self.socket
)
def test_install_validates_both_services_before_reloading(self):
self.install()
self.assertEqual(self.apache.read_text(), self.site.render("apache"))
self.assertEqual(self.pool.read_text(), self.site.render("php-fpm"))
self.assertEqual(self.enabled.resolve(), self.apache)
self.assertEqual(
self.runner.call_args_list,
[
call("/usr/sbin/php-fpm8.5", "--test"),
call("/usr/sbin/apache2ctl", "configtest"),
call("/usr/sbin/service", "php8.5-fpm", "reload"),
call("/usr/sbin/service", "apache2", "reload"),
],
)
self.readiness.assert_called_once_with(self.socket)
def test_failed_apache_reload_rolls_back_files_and_reloads_previous_config(self):
def fail_first_apache_reload(*command):
if (
command == ("/usr/sbin/service", "apache2", "reload")
and self.apache.exists()
):
raise ValueError("Apache reload failed")
self.runner.side_effect = fail_first_apache_reload
with self.assertRaisesRegex(ValueError, "Apache reload failed"):
self.install()
self.assertFalse(self.apache.exists())
self.assertFalse(self.pool.exists())
self.assertFalse(self.enabled.is_symlink())
self.assertEqual(
self.runner.call_args_list[-2:],
[
call("/usr/sbin/service", "php8.5-fpm", "reload"),
call("/usr/sbin/service", "apache2", "reload"),
],
)
self.runner.side_effect = None
self.install()
self.assertTrue(self.enabled.is_symlink())
+9 -1
View File
@@ -73,13 +73,21 @@ def main(argv=None):
)
render.add_argument("manifest", type=Path)
render.add_argument("configuration", choices=CONFIGURATIONS)
apply = commands.add_parser("apply", help="Install a site on an Ubuntu web node.")
apply.add_argument("manifest", type=Path)
args = parser.parse_args(argv)
try:
payload = json.loads(args.manifest.read_text(encoding="utf-8"))
site = WebSite.from_manifest(payload)
if args.command == "apply":
from .web_node_apply import apply_site
apply_site(site)
print(f"Applied web configuration for {site.domain}.")
else:
sys.stdout.write(site.render(args.configuration))
except (OSError, ValueError) as error:
parser.exit(1, f"coulobre-web-node: {error}\n")
sys.stdout.write(site.render(args.configuration))
return 0
+255
View File
@@ -0,0 +1,255 @@
import fcntl
import grp
import json
import os
import pwd
import stat
import subprocess
import time
from pathlib import Path
from tempfile import NamedTemporaryFile
STATE_DIRECTORY = Path("/var/lib/coulobre/web-node")
WEB_ROOT = Path("/srv/coulobre/web")
APACHE_AVAILABLE = Path("/etc/apache2/sites-available")
APACHE_ENABLED = Path("/etc/apache2/sites-enabled")
PHP_POOL_DIRECTORY = Path("/etc/php/8.5/fpm/pool.d")
PHP_SERVICE = "php8.5-fpm"
def apply_site(site):
if os.geteuid() != 0:
raise ValueError("Run apply as root on the web node.")
for directory in (APACHE_AVAILABLE, APACHE_ENABLED, PHP_POOL_DIRECTORY):
require_root_directory(directory)
require_root_directory(STATE_DIRECTORY.parent, create_mode=0o750)
require_root_directory(STATE_DIRECTORY, create_mode=0o700)
require_root_directory(WEB_ROOT.parent, create_mode=0o755)
require_root_directory(WEB_ROOT, create_mode=0o755)
with (STATE_DIRECTORY / "apply.lock").open("a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
install_site(site)
def require_root_directory(path, *, create_mode=None):
for parent in reversed(path.parents):
check_root_directory(parent)
if create_mode is not None:
path.mkdir(mode=create_mode, exist_ok=True)
check_root_directory(path)
def check_root_directory(path):
info = path.lstat()
if not stat.S_ISDIR(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022:
raise ValueError(f"Expected a root-controlled directory at {path}.")
def install_site(site):
account_id = site.account_id
configuration = site.configuration()
user = configuration["service_user"]
account_dir = WEB_ROOT / str(account_id)
apache_config = APACHE_AVAILABLE / f"{user}.conf"
apache_link = APACHE_ENABLED / apache_config.name
php_config = PHP_POOL_DIRECTORY / apache_config.name
socket = Path(configuration["socket_path"])
owned_paths = (account_dir, apache_config, apache_link, php_config, socket)
for service in (PHP_SERVICE, "apache2"):
run("/usr/sbin/service", service, "status")
if "proxy_fcgi_module" not in run("/usr/sbin/apache2ctl", "-M"):
raise ValueError("Enable Apache's proxy_fcgi module before applying a site.")
reserve_account(site, user, owned_paths)
uid, web_gid = ensure_system_account(user, account_dir)
require_root_directory(account_dir, create_mode=0o755)
ensure_public_directory(account_dir / "public", uid, web_gid)
install_configurations(site, apache_config, apache_link, php_config, socket)
def reserve_account(site, user, paths):
marker = STATE_DIRECTORY / f"{site.account_id}.json"
manifest = site.manifest()
for existing in STATE_DIRECTORY.glob("*.json"):
saved = json.loads(read_root_file(existing))
if existing == marker:
if saved != manifest:
raise ValueError(
"The account is already reserved with a different manifest."
)
elif saved["domain"] == site.domain:
raise ValueError(
"The primary domain is already reserved by another account."
)
if os.path.lexists(marker):
return
if (
current_user(user)
or current_group(user)
or any(os.path.lexists(p) for p in paths)
):
raise ValueError(
"The web node already has unmanaged resources for this account."
)
write_new_file(marker, json.dumps(manifest) + "\n", mode=0o600)
def current_user(name):
try:
return pwd.getpwnam(name)
except KeyError:
return None
def current_group(name):
try:
return grp.getgrnam(name)
except KeyError:
return None
def ensure_system_account(user, account_dir):
account = current_user(user)
group = current_group(user)
shell = "/usr/sbin/nologin"
if account is None:
group_options = ("--user-group",)
if group is not None:
if group.gr_mem or not group.gr_gid:
raise ValueError(f"Unexpected members or ID in the {user} group.")
group_options = ("--gid", str(group.gr_gid))
run(
"/usr/sbin/useradd",
"--system",
*group_options,
"--no-create-home",
"--home-dir",
str(account_dir),
"--shell",
shell,
user,
)
account = pwd.getpwnam(user)
group = grp.getgrnam(user)
if (
not account.pw_uid
or group is None
or not group.gr_gid
or group.gr_mem
or account.pw_gid != group.gr_gid
or account.pw_dir != str(account_dir)
or account.pw_shell != shell
):
raise ValueError(f"Unexpected user or group configuration for {user}.")
return account.pw_uid, grp.getgrnam("www-data").gr_gid
def ensure_public_directory(path, uid, gid):
if not os.path.lexists(path):
path.mkdir(mode=0o700)
info = path.lstat()
if stat.S_ISDIR(info.st_mode) and info.st_uid == 0 and not any(path.iterdir()):
path.chmod(0o750)
os.chown(path, uid, gid, follow_symlinks=False)
info = path.lstat()
if (
not stat.S_ISDIR(info.st_mode)
or (info.st_uid, info.st_gid) != (uid, gid)
or stat.S_IMODE(info.st_mode) != 0o750
):
raise ValueError(f"Unexpected ownership or mode for {path}.")
def read_root_file(path):
info = path.lstat()
if not stat.S_ISREG(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022:
raise ValueError(f"Expected a root-controlled file at {path}.")
return path.read_text(encoding="utf-8")
def write_new_file(path, content, *, mode):
with NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent) as staged:
staged.write(content)
staged.flush()
os.fchmod(staged.fileno(), mode)
os.link(staged.name, path)
def install_configurations(site, apache, enabled, pool, socket):
created = []
reload_attempts = []
try:
for path, name in ((apache, "apache"), (pool, "php-fpm")):
content = site.render(name)
if os.path.lexists(path):
if read_root_file(path) != content:
raise ValueError(f"Existing configuration differs at {path}.")
else:
write_new_file(path, content, mode=0o644)
created.append(path)
link_target = Path("../sites-available") / apache.name
if os.path.lexists(enabled):
if not enabled.is_symlink() or enabled.readlink() != link_target:
raise ValueError(f"Existing Apache site link differs at {enabled}.")
else:
enabled.symlink_to(link_target)
created.append(enabled)
run("/usr/sbin/php-fpm8.5", "--test")
run("/usr/sbin/apache2ctl", "configtest")
reload_attempts.append(PHP_SERVICE)
run("/usr/sbin/service", PHP_SERVICE, "reload")
wait_for_socket(socket)
reload_attempts.append("apache2")
run("/usr/sbin/service", "apache2", "reload")
except (OSError, ValueError, KeyboardInterrupt) as error:
failures = []
for path in reversed(created):
try:
path.unlink(missing_ok=True)
except OSError as rollback_error:
failures.append(str(rollback_error))
for service in reload_attempts:
try:
run("/usr/sbin/service", service, "reload")
except (OSError, ValueError) as rollback_error:
failures.append(str(rollback_error))
if failures:
raise ValueError(
f"{error}\nRollback errors:\n" + "\n".join(failures)
) from error
raise
def wait_for_socket(path):
deadline = time.monotonic() + 15
while time.monotonic() < deadline:
try:
if stat.S_ISSOCK(path.lstat().st_mode):
return
except FileNotFoundError:
pass
time.sleep(0.1)
raise ValueError(f"PHP-FPM did not open {path}.")
def run(*command):
process = subprocess.run(
command,
capture_output=True,
text=True,
env={"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LANG": "C"},
)
if process.returncode:
message = process.stderr.strip() or process.stdout.strip()
raise ValueError(
f"{' '.join(command)} failed ({process.returncode}). {message}"
)
return process.stdout