Apply and inspect web deployments on Ubuntu nodes #3

Merged
parkel merged 3 commits from feature/web-node-provisioning into main 2026-11-19 22:02:36 +01:00
4 changed files with 199 additions and 37 deletions
Showing only changes of commit af16adf216 - Show all commits

No files matched your search

+17
View File
@@ -100,6 +100,23 @@ removes the configuration it added. It reloads the prior configuration for
affected services and reports any recovery errors. The account reservation and
document root stay available for the next attempt.
Check the local deployment state with the same manifest.
```sh
sudo /opt/coulobre/bin/coulobre-web-node status coulobre-web-plan-1.json
```
The JSON report includes the manifest identity and one of three states.
- `configured` means the reservation, Unix account, document root, service
configuration, running services, and PHP-FPM socket match the manifest.
- `not_installed` means the node has no reservation for the account.
- `needs_attention` includes the first mismatch or service problem found.
The status command reads local state. It exits with code 0 for `configured`,
code 2 for the other report states, and code 1 if it cannot read the manifest
or inspect the node. Use an HTTP request to verify the site's response as well.
## Run an isolated PHP test site
Open a completed preview for the account's current domain and select **Download
+50 -1
View File
@@ -1,3 +1,4 @@
import json
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import call, patch
@@ -5,7 +6,7 @@ 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
from coulobre.web_node_apply import install_configurations, site_status
class WebNodeConfigurationTests(SimpleTestCase):
@@ -73,3 +74,51 @@ class WebNodeConfigurationTests(SimpleTestCase):
self.runner.side_effect = None
self.install()
self.assertTrue(self.enabled.is_symlink())
class WebNodeStatusTests(SimpleTestCase):
def setUp(self):
self.state = Path(self.enterContext(TemporaryDirectory()))
self.site = WebSite(42, "example.org")
self.marker = self.state / "42.json"
self.enterContext(patch("coulobre.web_node_apply.STATE_DIRECTORY", self.state))
self.enterContext(patch("coulobre.web_node_apply.os.geteuid", return_value=0))
self.enterContext(patch("coulobre.web_node_apply.require_root_directory"))
self.enterContext(
patch("coulobre.web_node_apply.read_root_file", side_effect=Path.read_text)
)
self.inspect = self.enterContext(
patch("coulobre.web_node_apply.check_installation")
)
def reserve(self, site):
self.marker.write_text(json.dumps(site.manifest()), encoding="utf-8")
(self.state / "apply.lock").touch()
def test_unreserved_account_leaves_state_untouched(self):
self.assertEqual(site_status(self.site)["state"], "not_installed")
self.assertEqual(list(self.state.iterdir()), [])
self.inspect.assert_not_called()
def test_configured_account_then_reports_local_drift(self):
self.reserve(self.site)
self.assertEqual(site_status(self.site)["state"], "configured")
self.inspect.side_effect = ValueError("The configuration has changed.")
self.assertEqual(
site_status(self.site),
{
**self.site.manifest(),
"state": "needs_attention",
"problem": "The configuration has changed.",
},
)
def test_different_manifest_reports_a_conflict_without_inspecting_files(self):
self.reserve(WebSite(42, "different.example"))
report = site_status(self.site)
self.assertEqual(report["state"], "needs_attention")
self.assertIn("different manifest", report["problem"])
self.inspect.assert_not_called()
+10
View File
@@ -75,6 +75,10 @@ def main(argv=None):
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)
status = commands.add_parser(
"status", help="Check a site's local configuration and services."
)
status.add_argument("manifest", type=Path)
args = parser.parse_args(argv)
try:
@@ -85,6 +89,12 @@ def main(argv=None):
apply_site(site)
print(f"Applied web configuration for {site.domain}.")
elif args.command == "status":
from .web_node_apply import site_status
report = site_status(site)
print(json.dumps(report, indent=2))
return 0 if report["state"] == "configured" else 2
else:
sys.stdout.write(site.render(args.configuration))
except (OSError, ValueError) as error:
+122 -36
View File
@@ -6,6 +6,7 @@ import pwd
import stat
import subprocess
import time
from dataclasses import dataclass
from pathlib import Path
from tempfile import NamedTemporaryFile
@@ -15,6 +16,28 @@ 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"
SITE_SHELL = "/usr/sbin/nologin"
@dataclass(frozen=True)
class SitePaths:
account: Path
apache: Path
enabled: Path
pool: Path
socket: Path
@classmethod
def for_site(cls, site):
configuration = site.configuration()
name = f"{configuration['service_user']}.conf"
return cls(
account=WEB_ROOT / str(site.account_id),
apache=APACHE_AVAILABLE / name,
enabled=APACHE_ENABLED / name,
pool=PHP_POOL_DIRECTORY / name,
socket=Path(configuration["socket_path"]),
)
def apply_site(site):
@@ -48,26 +71,66 @@ def check_root_directory(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)
user = site.configuration()["service_user"]
paths = SitePaths.for_site(site)
owned_paths = (paths.account, paths.apache, paths.enabled, paths.pool, paths.socket)
check_services()
reserve_account(site, user, owned_paths)
uid, web_gid = ensure_system_account(user, paths.account)
require_root_directory(paths.account, create_mode=0o755)
ensure_public_directory(paths.account / "public", uid, web_gid)
install_configurations(site, paths.apache, paths.enabled, paths.pool, paths.socket)
def site_status(site):
if os.geteuid() != 0:
raise ValueError("Run status as root on the web node.")
report = {**site.manifest(), "state": "not_installed", "problem": None}
try:
require_root_directory(STATE_DIRECTORY)
except FileNotFoundError:
return report
marker = STATE_DIRECTORY / f"{site.account_id}.json"
if not os.path.lexists(marker):
return report
with (STATE_DIRECTORY / "apply.lock").open("r") as lock:
fcntl.flock(lock, fcntl.LOCK_SH)
try:
if json.loads(read_root_file(marker)) != site.manifest():
raise ValueError("The account is reserved with a different manifest.")
check_installation(site, SitePaths.for_site(site))
except (OSError, ValueError) as error:
return {**report, "state": "needs_attention", "problem": str(error)}
return {**report, "state": "configured"}
def check_installation(site, paths):
for directory in (
paths.account,
APACHE_AVAILABLE,
APACHE_ENABLED,
PHP_POOL_DIRECTORY,
):
require_root_directory(directory)
user = site.configuration()["service_user"]
uid, gid = check_system_account(user, paths.account)
check_public_directory(paths.account / "public", uid, gid)
check_configuration(paths.apache, site.render("apache"))
check_configuration(paths.pool, site.render("php-fpm"))
check_site_link(paths.enabled, Path("../sites-available") / paths.apache.name)
check_services()
if not socket_exists(paths.socket):
raise ValueError(f"PHP-FPM is missing the site socket at {paths.socket}.")
def check_services():
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)
raise ValueError("Enable Apache's proxy_fcgi module on the web node.")
def reserve_account(site, user, paths):
@@ -113,11 +176,9 @@ def current_group(name):
def ensure_system_account(user, account_dir):
account = current_user(user)
group = current_group(user)
shell = "/usr/sbin/nologin"
if account is None:
if current_user(user) is None:
group_options = ("--user-group",)
group = current_group(user)
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.")
@@ -130,24 +191,31 @@ def ensure_system_account(user, account_dir):
"--home-dir",
str(account_dir),
"--shell",
shell,
SITE_SHELL,
user,
)
account = pwd.getpwnam(user)
group = grp.getgrnam(user)
return check_system_account(user, account_dir)
def check_system_account(user, account_dir):
account = current_user(user)
group = current_group(user)
if (
not account.pw_uid
account is None
or 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
or account.pw_shell != SITE_SHELL
):
raise ValueError(f"Unexpected user or group configuration for {user}.")
return account.pw_uid, grp.getgrnam("www-data").gr_gid
web_group = current_group("www-data")
if web_group is None:
raise ValueError("The Apache www-data group is missing.")
return account.pw_uid, web_group.gr_gid
def ensure_public_directory(path, uid, gid):
@@ -157,7 +225,11 @@ def ensure_public_directory(path, uid, gid):
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()
check_public_directory(path, uid, gid)
def check_public_directory(path, uid, gid):
info = path.lstat()
if (
not stat.S_ISDIR(info.st_mode)
or (info.st_uid, info.st_gid) != (uid, gid)
@@ -188,16 +260,14 @@ def install_configurations(site, apache, enabled, pool, socket):
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}.")
check_configuration(path, content)
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}.")
check_site_link(enabled, link_target)
else:
enabled.symlink_to(link_target)
created.append(enabled)
@@ -228,18 +298,34 @@ def install_configurations(site, apache, enabled, pool, socket):
raise
def check_configuration(path, content):
if read_root_file(path) != content:
raise ValueError(f"Existing configuration differs at {path}.")
def check_site_link(enabled, target):
if not enabled.is_symlink() or enabled.readlink() != target:
raise ValueError(
f"Expected the Apache site link at {enabled} to point to {target}."
)
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
if socket_exists(path):
return
time.sleep(0.1)
raise ValueError(f"PHP-FPM did not open {path}.")
def socket_exists(path):
try:
return stat.S_ISSOCK(path.lstat().st_mode)
except FileNotFoundError:
return False
def run(*command):
process = subprocess.run(
command,