Apply and inspect web deployments on Ubuntu nodes #3
No files matched your search
@@ -2,8 +2,6 @@
|
|||||||
|
|
||||||
- Use Gitea issues for work items and milestones for release planning.
|
- Use Gitea issues for work items and milestones for release planning.
|
||||||
- Start changes on a dedicated branch from the default branch, named main.
|
- Start changes on a dedicated branch from the default branch, named main.
|
||||||
- Keep related commits on the same branch and open one pull request when they
|
|
||||||
form a coherent change that can be reviewed and verified together.
|
|
||||||
- Reference the relevant issue in the pull request and describe what changed and
|
- Reference the relevant issue in the pull request and describe what changed and
|
||||||
how it was verified.
|
how it was verified.
|
||||||
- Submit changes for review before merging into main.
|
- Submit changes for review before merging into main.
|
||||||
|
|||||||
@@ -48,6 +48,75 @@ to RabbitMQ. After a broker outage, queued requests resume when the worker and
|
|||||||
scheduler reconnect. Plans that remain incomplete five minutes after dispatch
|
scheduler reconnect. Plans that remain incomplete five minutes after dispatch
|
||||||
are eligible for delivery again.
|
are eligible for delivery again.
|
||||||
|
|
||||||
|
## Render configuration on a web node
|
||||||
|
|
||||||
|
Open a completed preview for the account's current domain and select **Download
|
||||||
|
deployment manifest**. The versioned JSON file contains the account ID and
|
||||||
|
primary domain. The web node command validates those values and derives the
|
||||||
|
system user, document root, and PHP-FPM socket from the account ID.
|
||||||
|
|
||||||
|
Install the panel package on the node at the same revision as the panel that
|
||||||
|
created the manifest. The command renders configuration to standard output.
|
||||||
|
Run it as a regular user in a directory for reviewing the generated files.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
coulobre-web-node render coulobre-web-plan-1.json apache > apache.conf
|
||||||
|
coulobre-web-node render coulobre-web-plan-1.json php-fpm > php-fpm.conf
|
||||||
|
```
|
||||||
|
|
||||||
|
The command reads the manifest and packaged templates locally. The isolated
|
||||||
|
Ubuntu check below demonstrates loading the configuration.
|
||||||
|
|
||||||
|
## Apply a manifest on an Ubuntu web node
|
||||||
|
|
||||||
|
Use a dedicated Ubuntu 26.04 node with Apache and PHP 8.5 FPM installed from
|
||||||
|
the distribution packages. Enable FastCGI in Apache and start the native
|
||||||
|
services before applying a manifest.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo apt install apache2 php8.5-fpm
|
||||||
|
sudo a2enmod proxy_fcgi
|
||||||
|
sudo service php8.5-fpm start
|
||||||
|
sudo service apache2 restart
|
||||||
|
```
|
||||||
|
|
||||||
|
Install the matching Coulobre package in a root-owned virtual environment on
|
||||||
|
the node. Review the completed preview and transfer its deployment manifest
|
||||||
|
to the node. Apply it with the node operator account.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo /opt/coulobre/bin/coulobre-web-node apply coulobre-web-plan-1.json
|
||||||
|
```
|
||||||
|
|
||||||
|
The command reserves the account ID and domain on the node, creates a system
|
||||||
|
user and a document root under `/srv/coulobre/web/<account-id>/public`, and
|
||||||
|
installs Apache and PHP-FPM configuration. It validates both configurations,
|
||||||
|
reloads PHP-FPM, waits for the per-site socket, then reloads Apache.
|
||||||
|
|
||||||
|
Reapply the same manifest to retry or verify an existing installation. The
|
||||||
|
node checks the account registry for domain conflicts and protects existing
|
||||||
|
configuration files. If a configuration check or reload fails, the command
|
||||||
|
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
|
## Run an isolated PHP test site
|
||||||
|
|
||||||
Open a completed preview for the account's current domain and select **Download
|
Open a completed preview for the account's current domain and select **Download
|
||||||
|
|||||||
@@ -15,6 +15,9 @@ dependencies = [
|
|||||||
"idna>=3,<4",
|
"idna>=3,<4",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[project.scripts]
|
||||||
|
coulobre-web-node = "coulobre.web_node:main"
|
||||||
|
|
||||||
[project.optional-dependencies]
|
[project.optional-dependencies]
|
||||||
dev = ["ruff>=0.11,<1"]
|
dev = ["ruff>=0.11,<1"]
|
||||||
mariadb = ["mysqlclient>=2.2.1,<3"]
|
mariadb = ["mysqlclient>=2.2.1,<3"]
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import idna
|
||||||
|
from django.core.exceptions import ValidationError
|
||||||
|
from django.core.validators import DomainNameValidator
|
||||||
|
|
||||||
|
validate_domain = DomainNameValidator(accept_idna=False)
|
||||||
|
|
||||||
|
|
||||||
|
def canonical_domain(value):
|
||||||
|
try:
|
||||||
|
domain = (
|
||||||
|
idna.encode(value.strip(), uts46=True).decode("ascii").removesuffix(".")
|
||||||
|
)
|
||||||
|
validate_domain(domain)
|
||||||
|
except (idna.IDNAError, ValidationError) as error:
|
||||||
|
raise ValueError("Enter a valid domain name.") from error
|
||||||
|
return domain
|
||||||
@@ -1,9 +1,7 @@
|
|||||||
import idna
|
|
||||||
from django.core.exceptions import ValidationError
|
from django.core.exceptions import ValidationError
|
||||||
from django.core.validators import DomainNameValidator
|
|
||||||
from django.db import models
|
from django.db import models
|
||||||
|
|
||||||
validate_domain = DomainNameValidator(accept_idna=False)
|
from coulobre.domain_names import canonical_domain, validate_domain
|
||||||
|
|
||||||
|
|
||||||
class DomainNameField(models.CharField):
|
class DomainNameField(models.CharField):
|
||||||
@@ -15,10 +13,6 @@ class DomainNameField(models.CharField):
|
|||||||
return value
|
return value
|
||||||
|
|
||||||
try:
|
try:
|
||||||
domain = idna.encode(value.strip(), uts46=True).decode("ascii")
|
return canonical_domain(value)
|
||||||
except idna.IDNAError as error:
|
except ValueError as error:
|
||||||
raise ValidationError(validate_domain.message, code="invalid") from error
|
raise ValidationError(validate_domain.message, code="invalid") from error
|
||||||
|
|
||||||
domain = domain.removesuffix(".")
|
|
||||||
validate_domain(domain)
|
|
||||||
return domain
|
|
||||||
@@ -2,11 +2,11 @@ from datetime import timedelta
|
|||||||
|
|
||||||
from celery import shared_task
|
from celery import shared_task
|
||||||
from django.db.models import Q
|
from django.db.models import Q
|
||||||
from django.template.loader import render_to_string
|
|
||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
|
|
||||||
|
from coulobre.web_node import WebSite
|
||||||
|
|
||||||
from .models import WebProvisioningPlan
|
from .models import WebProvisioningPlan
|
||||||
from .web_node import web_site_configuration
|
|
||||||
|
|
||||||
REDISPATCH_AFTER = timedelta(minutes=5)
|
REDISPATCH_AFTER = timedelta(minutes=5)
|
||||||
|
|
||||||
@@ -37,7 +37,5 @@ def render_web_plan(plan_id):
|
|||||||
if plan is None:
|
if plan is None:
|
||||||
return
|
return
|
||||||
|
|
||||||
apache_config = render_to_string(
|
apache_config = WebSite(plan.account_id, plan.primary_domain).render("apache")
|
||||||
"hosting/apache-vhost.conf", web_site_configuration(plan)
|
|
||||||
)
|
|
||||||
pending.update(apache_config=apache_config, completed_at=timezone.now())
|
pending.update(apache_config=apache_config, completed_at=timezone.now())
|
||||||
@@ -1,14 +1,14 @@
|
|||||||
<VirtualHost *:80>
|
<VirtualHost *:80>
|
||||||
ServerName {{ domain }}
|
ServerName $domain
|
||||||
DocumentRoot "{{ document_root }}"
|
DocumentRoot "$document_root"
|
||||||
|
|
||||||
<Directory "{{ document_root }}">
|
<Directory "$document_root">
|
||||||
AllowOverride None
|
AllowOverride None
|
||||||
Options None
|
Options None
|
||||||
Require all granted
|
Require all granted
|
||||||
</Directory>
|
</Directory>
|
||||||
|
|
||||||
<FilesMatch "\.php$">
|
<FilesMatch "\.php$$">
|
||||||
SetHandler "proxy:unix:{{ socket_path }}|fcgi://localhost/"
|
SetHandler "proxy:unix:$socket_path|fcgi://localhost/"
|
||||||
</FilesMatch>
|
</FilesMatch>
|
||||||
</VirtualHost>
|
</VirtualHost>
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
[{{ service_user }}]
|
[$service_user]
|
||||||
user = {{ service_user }}
|
user = $service_user
|
||||||
group = {{ service_user }}
|
group = $service_user
|
||||||
listen = {{ socket_path }}
|
listen = $socket_path
|
||||||
listen.owner = www-data
|
listen.owner = www-data
|
||||||
listen.group = www-data
|
listen.group = www-data
|
||||||
listen.mode = 0660
|
listen.mode = 0660
|
||||||
|
|||||||
@@ -24,7 +24,10 @@
|
|||||||
<header class="section-heading">
|
<header class="section-heading">
|
||||||
<h2 id="configuration-heading">Virtual host configuration</h2>
|
<h2 id="configuration-heading">Virtual host configuration</h2>
|
||||||
{% if plan.can_export %}
|
{% if plan.can_export %}
|
||||||
<a class="button secondary" href="{% url 'panel:download_smoke_bundle' plan.pk %}">Download test bundle</a>
|
<div class="form-actions">
|
||||||
|
<a class="button secondary" href="{% url 'panel:download_deployment_manifest' plan.pk %}">Download deployment manifest</a>
|
||||||
|
<a class="button secondary" href="{% url 'panel:download_smoke_bundle' plan.pk %}">Download test bundle</a>
|
||||||
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</header>
|
</header>
|
||||||
<pre class="configuration"><code>{{ plan.apache_config }}</code></pre>
|
<pre class="configuration"><code>{{ plan.apache_config }}</code></pre>
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ from django.contrib.auth import get_user_model
|
|||||||
from django.test import TestCase
|
from django.test import TestCase
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
|
|
||||||
|
from coulobre.web_node import WebSite
|
||||||
|
|
||||||
from .models import HostingAccount, WebProvisioningPlan
|
from .models import HostingAccount, WebProvisioningPlan
|
||||||
from .tasks import render_web_plan
|
from .tasks import render_web_plan
|
||||||
|
|
||||||
@@ -25,6 +27,9 @@ class WebSmokeBundleTests(TestCase):
|
|||||||
def setUp(self):
|
def setUp(self):
|
||||||
self.client.force_login(self.operator)
|
self.client.force_login(self.operator)
|
||||||
self.download = reverse("panel:download_smoke_bundle", args=[self.plan.pk])
|
self.download = reverse("panel:download_smoke_bundle", args=[self.plan.pk])
|
||||||
|
self.manifest = reverse(
|
||||||
|
"panel:download_deployment_manifest", args=[self.plan.pk]
|
||||||
|
)
|
||||||
|
|
||||||
def test_export_uses_the_reviewed_preview_and_matching_php_fpm_settings(self):
|
def test_export_uses_the_reviewed_preview_and_matching_php_fpm_settings(self):
|
||||||
render_web_plan.run(self.plan.pk)
|
render_web_plan.run(self.plan.pk)
|
||||||
@@ -57,17 +62,44 @@ class WebSmokeBundleTests(TestCase):
|
|||||||
|
|
||||||
def test_pending_and_stale_previews_cannot_be_exported(self):
|
def test_pending_and_stale_previews_cannot_be_exported(self):
|
||||||
self.assertEqual(self.client.get(self.download).status_code, 409)
|
self.assertEqual(self.client.get(self.download).status_code, 409)
|
||||||
|
self.assertEqual(self.client.get(self.manifest).status_code, 409)
|
||||||
render_web_plan.run(self.plan.pk)
|
render_web_plan.run(self.plan.pk)
|
||||||
HostingAccount.objects.filter(pk=self.account.pk).update(
|
HostingAccount.objects.filter(pk=self.account.pk).update(
|
||||||
primary_domain="updated.example"
|
primary_domain="updated.example"
|
||||||
)
|
)
|
||||||
|
|
||||||
self.assertEqual(self.client.get(self.download).status_code, 409)
|
self.assertEqual(self.client.get(self.download).status_code, 409)
|
||||||
|
self.assertEqual(self.client.get(self.manifest).status_code, 409)
|
||||||
detail = self.client.get(reverse("panel:plan", args=[self.plan.pk]))
|
detail = self.client.get(reverse("panel:plan", args=[self.plan.pk]))
|
||||||
self.assertNotContains(detail, "Download test bundle")
|
self.assertNotContains(detail, "Download test bundle")
|
||||||
|
self.assertNotContains(detail, "Download deployment manifest")
|
||||||
|
|
||||||
def test_download_requires_plan_view_permission(self):
|
def test_download_requires_plan_view_permission(self):
|
||||||
render_web_plan.run(self.plan.pk)
|
render_web_plan.run(self.plan.pk)
|
||||||
self.client.force_login(self.viewer)
|
self.client.force_login(self.viewer)
|
||||||
|
|
||||||
self.assertEqual(self.client.get(self.download).status_code, 403)
|
self.assertEqual(self.client.get(self.download).status_code, 403)
|
||||||
|
self.assertEqual(self.client.get(self.manifest).status_code, 403)
|
||||||
|
|
||||||
|
def test_manifest_reproduces_preview_and_pool_on_the_node(self):
|
||||||
|
render_web_plan.run(self.plan.pk)
|
||||||
|
|
||||||
|
detail = self.client.get(reverse("panel:plan", args=[self.plan.pk]))
|
||||||
|
self.assertContains(detail, "Download deployment manifest")
|
||||||
|
response = self.client.get(self.manifest)
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
self.assertIn(".json", response["Content-Disposition"])
|
||||||
|
self.assertEqual(
|
||||||
|
response.json(),
|
||||||
|
{"version": 1, "account_id": self.account.pk, "domain": "example.org"},
|
||||||
|
)
|
||||||
|
|
||||||
|
self.plan.refresh_from_db()
|
||||||
|
site = WebSite.from_manifest(response.json())
|
||||||
|
self.assertEqual(site.render("apache"), self.plan.apache_config)
|
||||||
|
bundle = self.client.get(self.download)
|
||||||
|
with tarfile.open(fileobj=BytesIO(bundle.content)) as archive:
|
||||||
|
self.assertEqual(
|
||||||
|
site.render("php-fpm"),
|
||||||
|
archive.extractfile("php-fpm.conf").read().decode(),
|
||||||
|
)
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
import json
|
||||||
|
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, site_status
|
||||||
|
|
||||||
|
|
||||||
|
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())
|
||||||
|
|
||||||
|
|
||||||
|
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()
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
from django.test import SimpleTestCase
|
||||||
|
|
||||||
|
from coulobre.web_node import WebSite
|
||||||
|
|
||||||
|
|
||||||
|
class WebSiteManifestTests(SimpleTestCase):
|
||||||
|
def test_manifest_derives_paths_and_canonicalizes_the_domain(self):
|
||||||
|
site = WebSite.from_manifest(
|
||||||
|
{"version": 1, "account_id": 42, "domain": "BÜCHER.example."}
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(site.manifest()["domain"], "xn--bcher-kva.example")
|
||||||
|
self.assertIn(
|
||||||
|
'DocumentRoot "/srv/coulobre/web/42/public"', site.render("apache")
|
||||||
|
)
|
||||||
|
self.assertIn('FilesMatch "\\.php$"', site.render("apache"))
|
||||||
|
self.assertIn("listen = /run/php/coulobre-42.sock", site.render("php-fpm"))
|
||||||
|
|
||||||
|
def test_manifest_rejects_wrong_versions_and_untrusted_configuration(self):
|
||||||
|
manifest = {"version": 1, "account_id": 42, "domain": "example.org"}
|
||||||
|
invalid = (
|
||||||
|
{"version": 2},
|
||||||
|
{"version": True},
|
||||||
|
{"account_id": True},
|
||||||
|
{"account_id": -1},
|
||||||
|
{"account_id": 2**63},
|
||||||
|
{"account_id": "../../etc"},
|
||||||
|
{"domain": "example.org\nServerAlias *"},
|
||||||
|
{"domain": "localhost"},
|
||||||
|
{"document_root": "/tmp"},
|
||||||
|
)
|
||||||
|
for change in invalid:
|
||||||
|
with self.subTest(change=change), self.assertRaises(ValueError):
|
||||||
|
WebSite.from_manifest(manifest | change)
|
||||||
@@ -26,7 +26,12 @@ urlpatterns = [
|
|||||||
path("plans/<int:pk>/", views.PlanDetail.as_view(), name="plan"),
|
path("plans/<int:pk>/", views.PlanDetail.as_view(), name="plan"),
|
||||||
path(
|
path(
|
||||||
"plans/<int:pk>/smoke-bundle/",
|
"plans/<int:pk>/smoke-bundle/",
|
||||||
views.DownloadWebSmokeBundle.as_view(),
|
views.DownloadWebPlan.as_view(),
|
||||||
name="download_smoke_bundle",
|
name="download_smoke_bundle",
|
||||||
),
|
),
|
||||||
|
path(
|
||||||
|
"plans/<int:pk>/deployment-manifest/",
|
||||||
|
views.DownloadWebPlan.as_view(manifest=True),
|
||||||
|
name="download_deployment_manifest",
|
||||||
|
),
|
||||||
]
|
]
|
||||||
@@ -7,7 +7,7 @@ from django.views.generic import CreateView, DetailView, ListView, UpdateView
|
|||||||
from django.views.generic.detail import SingleObjectMixin
|
from django.views.generic.detail import SingleObjectMixin
|
||||||
|
|
||||||
from .models import HostingAccount, WebProvisioningPlan
|
from .models import HostingAccount, WebProvisioningPlan
|
||||||
from .web_node import build_web_smoke_bundle
|
from .web_node import build_web_smoke_bundle, serialize_deployment_manifest
|
||||||
|
|
||||||
VIEW_ACCOUNTS = "hosting.view_hostingaccount"
|
VIEW_ACCOUNTS = "hosting.view_hostingaccount"
|
||||||
CHANGE_ACCOUNTS = "hosting.change_hostingaccount"
|
CHANGE_ACCOUNTS = "hosting.change_hostingaccount"
|
||||||
@@ -97,7 +97,9 @@ class PlanDetail(PermissionRequiredMixin, DetailView):
|
|||||||
context_object_name = "plan"
|
context_object_name = "plan"
|
||||||
|
|
||||||
|
|
||||||
class DownloadWebSmokeBundle(PlanDetail):
|
class DownloadWebPlan(PlanDetail):
|
||||||
|
manifest = False
|
||||||
|
|
||||||
def render_to_response(self, context, **response_kwargs):
|
def render_to_response(self, context, **response_kwargs):
|
||||||
plan = self.object
|
plan = self.object
|
||||||
if not plan.can_export:
|
if not plan.can_export:
|
||||||
@@ -107,11 +109,21 @@ class DownloadWebSmokeBundle(PlanDetail):
|
|||||||
content_type="text/plain",
|
content_type="text/plain",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if self.manifest:
|
||||||
|
content = serialize_deployment_manifest(plan)
|
||||||
|
extension = "json"
|
||||||
|
content_type = "application/json"
|
||||||
|
else:
|
||||||
|
content = build_web_smoke_bundle(plan)
|
||||||
|
extension = "tar"
|
||||||
|
content_type = "application/x-tar"
|
||||||
return HttpResponse(
|
return HttpResponse(
|
||||||
build_web_smoke_bundle(plan),
|
content,
|
||||||
content_type="application/x-tar",
|
content_type=content_type,
|
||||||
headers={
|
headers={
|
||||||
"Cache-Control": "private, no-store",
|
"Cache-Control": "private, no-store",
|
||||||
"Content-Disposition": f'attachment; filename="coulobre-web-plan-{plan.pk}.tar"',
|
"Content-Disposition": (
|
||||||
|
f'attachment; filename="coulobre-web-plan-{plan.pk}.{extension}"'
|
||||||
|
),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -4,24 +4,20 @@ from io import BytesIO
|
|||||||
|
|
||||||
from django.template.loader import render_to_string
|
from django.template.loader import render_to_string
|
||||||
|
|
||||||
|
from coulobre.web_node import WebSite
|
||||||
|
|
||||||
def web_site_configuration(plan):
|
|
||||||
service_user = f"coulobre-{plan.account_id}"
|
def serialize_deployment_manifest(plan):
|
||||||
return {
|
site = WebSite(plan.account_id, plan.primary_domain)
|
||||||
"account_id": plan.account_id,
|
return json.dumps(site.manifest(), indent=2) + "\n"
|
||||||
"domain": plan.primary_domain,
|
|
||||||
"service_user": service_user,
|
|
||||||
"document_root": f"/srv/coulobre/web/{plan.account_id}/public",
|
|
||||||
"socket_path": f"/run/php/{service_user}.sock",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def build_web_smoke_bundle(plan):
|
def build_web_smoke_bundle(plan):
|
||||||
configuration = web_site_configuration(plan)
|
site = WebSite(plan.account_id, plan.primary_domain)
|
||||||
files = {
|
files = {
|
||||||
"site.json": json.dumps(configuration, indent=2) + "\n",
|
"site.json": json.dumps(site.configuration(), indent=2) + "\n",
|
||||||
"apache.conf": plan.apache_config,
|
"apache.conf": plan.apache_config,
|
||||||
"php-fpm.conf": render_to_string("hosting/php-fpm-pool.conf", configuration),
|
"php-fpm.conf": site.render("php-fpm"),
|
||||||
"public/index.php": render_to_string("hosting/smoke-index.php"),
|
"public/index.php": render_to_string("hosting/smoke-index.php"),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,103 @@
|
|||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from importlib.resources import files
|
||||||
|
from pathlib import Path
|
||||||
|
from string import Template
|
||||||
|
|
||||||
|
from .domain_names import canonical_domain
|
||||||
|
|
||||||
|
MANIFEST_VERSION = 1
|
||||||
|
CONFIGURATIONS = {"apache": "apache-vhost.conf", "php-fpm": "php-fpm-pool.conf"}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class WebSite:
|
||||||
|
account_id: int
|
||||||
|
domain: str
|
||||||
|
|
||||||
|
def __post_init__(self):
|
||||||
|
if type(self.account_id) is not int or not 1 <= self.account_id <= 2**63 - 1:
|
||||||
|
raise ValueError("The account ID must be a positive 64-bit integer.")
|
||||||
|
if not isinstance(self.domain, str):
|
||||||
|
raise ValueError("The domain must be a string.")
|
||||||
|
object.__setattr__(self, "domain", canonical_domain(self.domain))
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_manifest(cls, data):
|
||||||
|
if not isinstance(data, dict) or data.keys() != {
|
||||||
|
"version",
|
||||||
|
"account_id",
|
||||||
|
"domain",
|
||||||
|
}:
|
||||||
|
raise ValueError(
|
||||||
|
"Expected a manifest with version, account_id, and domain."
|
||||||
|
)
|
||||||
|
version = data["version"]
|
||||||
|
if type(version) is not int or version != MANIFEST_VERSION:
|
||||||
|
raise ValueError("Unsupported web deployment manifest version.")
|
||||||
|
return cls(data["account_id"], data["domain"])
|
||||||
|
|
||||||
|
def manifest(self):
|
||||||
|
return {
|
||||||
|
"version": MANIFEST_VERSION,
|
||||||
|
"account_id": self.account_id,
|
||||||
|
"domain": self.domain,
|
||||||
|
}
|
||||||
|
|
||||||
|
def configuration(self):
|
||||||
|
service_user = f"coulobre-{self.account_id}"
|
||||||
|
return {
|
||||||
|
"account_id": self.account_id,
|
||||||
|
"domain": self.domain,
|
||||||
|
"service_user": service_user,
|
||||||
|
"document_root": f"/srv/coulobre/web/{self.account_id}/public",
|
||||||
|
"socket_path": f"/run/php/{service_user}.sock",
|
||||||
|
}
|
||||||
|
|
||||||
|
def render(self, configuration):
|
||||||
|
resource = files("coulobre.hosting").joinpath(
|
||||||
|
"templates", "hosting", CONFIGURATIONS[configuration]
|
||||||
|
)
|
||||||
|
return Template(resource.read_text(encoding="utf-8")).substitute(
|
||||||
|
self.configuration()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv=None):
|
||||||
|
parser = argparse.ArgumentParser(prog="coulobre-web-node")
|
||||||
|
commands = parser.add_subparsers(dest="command", required=True)
|
||||||
|
render = commands.add_parser(
|
||||||
|
"render", help="Render configuration from a site manifest."
|
||||||
|
)
|
||||||
|
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)
|
||||||
|
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:
|
||||||
|
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}.")
|
||||||
|
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:
|
||||||
|
parser.exit(1, f"coulobre-web-node: {error}\n")
|
||||||
|
|
||||||
|
return 0
|
||||||
@@ -0,0 +1,341 @@
|
|||||||
|
import fcntl
|
||||||
|
import grp
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import pwd
|
||||||
|
import stat
|
||||||
|
import subprocess
|
||||||
|
import time
|
||||||
|
from dataclasses import dataclass
|
||||||
|
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"
|
||||||
|
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):
|
||||||
|
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):
|
||||||
|
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 on the web node.")
|
||||||
|
|
||||||
|
|
||||||
|
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):
|
||||||
|
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.")
|
||||||
|
group_options = ("--gid", str(group.gr_gid))
|
||||||
|
run(
|
||||||
|
"/usr/sbin/useradd",
|
||||||
|
"--system",
|
||||||
|
*group_options,
|
||||||
|
"--no-create-home",
|
||||||
|
"--home-dir",
|
||||||
|
str(account_dir),
|
||||||
|
"--shell",
|
||||||
|
SITE_SHELL,
|
||||||
|
user,
|
||||||
|
)
|
||||||
|
return check_system_account(user, account_dir)
|
||||||
|
|
||||||
|
|
||||||
|
def check_system_account(user, account_dir):
|
||||||
|
account = current_user(user)
|
||||||
|
group = current_group(user)
|
||||||
|
if (
|
||||||
|
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 != SITE_SHELL
|
||||||
|
):
|
||||||
|
raise ValueError(f"Unexpected user or group configuration for {user}.")
|
||||||
|
|
||||||
|
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):
|
||||||
|
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)
|
||||||
|
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)
|
||||||
|
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):
|
||||||
|
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):
|
||||||
|
check_site_link(enabled, link_target)
|
||||||
|
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 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:
|
||||||
|
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,
|
||||||
|
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
|
||||||
Reference in new issue
Block a user