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
15 changed files with 239 additions and 44 deletions
Showing only changes of commit aea049087d - Show all commits

No files matched your search

-2
View File
@@ -2,8 +2,6 @@
- Use Gitea issues for work items and milestones for release planning.
- 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
how it was verified.
- Submit changes for review before merging into main.
+19
View File
@@ -48,6 +48,25 @@ to RabbitMQ. After a broker outage, queued requests resume when the worker and
scheduler reconnect. Plans that remain incomplete five minutes after dispatch
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.
## Run an isolated PHP test site
Open a completed preview for the account's current domain and select **Download
+3
View File
@@ -15,6 +15,9 @@ dependencies = [
"idna>=3,<4",
]
[project.scripts]
coulobre-web-node = "coulobre.web_node:main"
[project.optional-dependencies]
dev = ["ruff>=0.11,<1"]
mariadb = ["mysqlclient>=2.2.1,<3"]
+16
View File
@@ -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
+3 -9
View File
@@ -1,9 +1,7 @@
import idna
from django.core.exceptions import ValidationError
from django.core.validators import DomainNameValidator
from django.db import models
validate_domain = DomainNameValidator(accept_idna=False)
from coulobre.domain_names import canonical_domain, validate_domain
class DomainNameField(models.CharField):
@@ -15,10 +13,6 @@ class DomainNameField(models.CharField):
return value
try:
domain = idna.encode(value.strip(), uts46=True).decode("ascii")
except idna.IDNAError as error:
return canonical_domain(value)
except ValueError as error:
raise ValidationError(validate_domain.message, code="invalid") from error
domain = domain.removesuffix(".")
validate_domain(domain)
return domain
+3 -5
View File
@@ -2,11 +2,11 @@ from datetime import timedelta
from celery import shared_task
from django.db.models import Q
from django.template.loader import render_to_string
from django.utils import timezone
from coulobre.web_node import WebSite
from .models import WebProvisioningPlan
from .web_node import web_site_configuration
REDISPATCH_AFTER = timedelta(minutes=5)
@@ -37,7 +37,5 @@ def render_web_plan(plan_id):
if plan is None:
return
apache_config = render_to_string(
"hosting/apache-vhost.conf", web_site_configuration(plan)
)
apache_config = WebSite(plan.account_id, plan.primary_domain).render("apache")
pending.update(apache_config=apache_config, completed_at=timezone.now())
@@ -1,14 +1,14 @@
<VirtualHost *:80>
ServerName {{ domain }}
DocumentRoot "{{ document_root }}"
ServerName $domain
DocumentRoot "$document_root"
<Directory "{{ document_root }}">
<Directory "$document_root">
AllowOverride None
Options None
Require all granted
</Directory>
<FilesMatch "\.php$">
SetHandler "proxy:unix:{{ socket_path }}|fcgi://localhost/"
<FilesMatch "\.php$$">
SetHandler "proxy:unix:$socket_path|fcgi://localhost/"
</FilesMatch>
</VirtualHost>
@@ -1,7 +1,7 @@
[{{ service_user }}]
user = {{ service_user }}
group = {{ service_user }}
listen = {{ socket_path }}
[$service_user]
user = $service_user
group = $service_user
listen = $socket_path
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
@@ -24,7 +24,10 @@
<header class="section-heading">
<h2 id="configuration-heading">Virtual host configuration</h2>
{% 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 %}
</header>
<pre class="configuration"><code>{{ plan.apache_config }}</code></pre>
+32
View File
@@ -6,6 +6,8 @@ from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from coulobre.web_node import WebSite
from .models import HostingAccount, WebProvisioningPlan
from .tasks import render_web_plan
@@ -25,6 +27,9 @@ class WebSmokeBundleTests(TestCase):
def setUp(self):
self.client.force_login(self.operator)
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):
render_web_plan.run(self.plan.pk)
@@ -57,17 +62,44 @@ class WebSmokeBundleTests(TestCase):
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.manifest).status_code, 409)
render_web_plan.run(self.plan.pk)
HostingAccount.objects.filter(pk=self.account.pk).update(
primary_domain="updated.example"
)
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]))
self.assertNotContains(detail, "Download test bundle")
self.assertNotContains(detail, "Download deployment manifest")
def test_download_requires_plan_view_permission(self):
render_web_plan.run(self.plan.pk)
self.client.force_login(self.viewer)
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,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)
+6 -1
View File
@@ -26,7 +26,12 @@ urlpatterns = [
path("plans/<int:pk>/", views.PlanDetail.as_view(), name="plan"),
path(
"plans/<int:pk>/smoke-bundle/",
views.DownloadWebSmokeBundle.as_view(),
views.DownloadWebPlan.as_view(),
name="download_smoke_bundle",
),
path(
"plans/<int:pk>/deployment-manifest/",
views.DownloadWebPlan.as_view(manifest=True),
name="download_deployment_manifest",
),
]
+17 -5
View File
@@ -7,7 +7,7 @@ from django.views.generic import CreateView, DetailView, ListView, UpdateView
from django.views.generic.detail import SingleObjectMixin
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"
CHANGE_ACCOUNTS = "hosting.change_hostingaccount"
@@ -97,7 +97,9 @@ class PlanDetail(PermissionRequiredMixin, DetailView):
context_object_name = "plan"
class DownloadWebSmokeBundle(PlanDetail):
class DownloadWebPlan(PlanDetail):
manifest = False
def render_to_response(self, context, **response_kwargs):
plan = self.object
if not plan.can_export:
@@ -107,11 +109,21 @@ class DownloadWebSmokeBundle(PlanDetail):
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(
build_web_smoke_bundle(plan),
content_type="application/x-tar",
content,
content_type=content_type,
headers={
"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}"'
),
},
)
+8 -12
View File
@@ -4,24 +4,20 @@ from io import BytesIO
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}"
return {
"account_id": plan.account_id,
"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 serialize_deployment_manifest(plan):
site = WebSite(plan.account_id, plan.primary_domain)
return json.dumps(site.manifest(), indent=2) + "\n"
def build_web_smoke_bundle(plan):
configuration = web_site_configuration(plan)
site = WebSite(plan.account_id, plan.primary_domain)
files = {
"site.json": json.dumps(configuration, indent=2) + "\n",
"site.json": json.dumps(site.configuration(), indent=2) + "\n",
"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"),
}
+85
View File
@@ -0,0 +1,85 @@
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)
args = parser.parse_args(argv)
try:
payload = json.loads(args.manifest.read_text(encoding="utf-8"))
site = WebSite.from_manifest(payload)
except (OSError, ValueError) as error:
parser.exit(1, f"coulobre-web-node: {error}\n")
sys.stdout.write(site.render(args.configuration))
return 0