From 7f706c39b5a8b14ae65c3a4e21e99fef5e25993c Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sat, 21 Nov 2026 01:10:25 +0100 Subject: [PATCH 1/2] Support local web activation over a restricted Unix socket --- deploy/systemd/coulobre-web-apply.socket | 14 +++++ deploy/systemd/coulobre-web-apply@.service | 20 +++++++ docs/deployment.md | 4 +- docs/development.md | 22 ++++++++ .../hosting/test_web_node_manifest.py | 56 ++++++++++++++++++- src/coulobre/web_node.py | 30 ++++++++++ 6 files changed, 144 insertions(+), 2 deletions(-) create mode 100644 deploy/systemd/coulobre-web-apply.socket create mode 100644 deploy/systemd/coulobre-web-apply@.service diff --git a/deploy/systemd/coulobre-web-apply.socket b/deploy/systemd/coulobre-web-apply.socket new file mode 100644 index 0000000..be70ac5 --- /dev/null +++ b/deploy/systemd/coulobre-web-apply.socket @@ -0,0 +1,14 @@ +[Unit] +Description=Coulobre local web activation socket + +[Socket] +ListenStream=/run/coulobre-web-apply.sock +SocketUser=root +SocketGroup=coulobre-web-provisioning +SocketMode=0660 +Accept=yes +MaxConnections=4 +RemoveOnStop=true + +[Install] +WantedBy=sockets.target diff --git a/deploy/systemd/coulobre-web-apply@.service b/deploy/systemd/coulobre-web-apply@.service new file mode 100644 index 0000000..700b0ab --- /dev/null +++ b/deploy/systemd/coulobre-web-apply@.service @@ -0,0 +1,20 @@ +[Unit] +Description=Coulobre local web activation request +After=apache2.service php8.5-fpm.service +CollectMode=inactive-or-failed + +[Service] +Type=exec +User=root +WorkingDirectory=/opt/coulobre +UMask=0022 +ExecStart=/opt/coulobre/bin/coulobre-web-node apply-request +StandardInput=socket +StandardOutput=socket +StandardError=journal +RuntimeMaxSec=3min +KillSignal=SIGINT +KillMode=mixed +NoNewPrivileges=true +PrivateTmp=true +ProtectHome=true diff --git a/docs/deployment.md b/docs/deployment.md index 23824cb..46ec4c7 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -157,7 +157,9 @@ to Apache workers. The scheduler stores its state in a private directory and there is one scheduler for the installation. ```sh -sudo install -m 0644 deploy/systemd/*.service /etc/systemd/system/ +sudo install -m 0644 deploy/systemd/coulobre-panel.service \ + deploy/systemd/coulobre-worker.service deploy/systemd/coulobre-beat.service \ + /etc/systemd/system/ sudo systemctl daemon-reload sudo systemctl enable --now coulobre-panel.service coulobre-worker.service coulobre-beat.service diff --git a/docs/development.md b/docs/development.md index 794eac5..ab25b90 100644 --- a/docs/development.md +++ b/docs/development.md @@ -570,6 +570,28 @@ 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. +### Enable local web activation + +On a web node with the same Apache and PHP-FPM setup, systemd can accept local +activation requests at `/run/coulobre-web-apply.sock`. Install the matching +Coulobre package in a root-owned virtual environment at `/opt/coulobre` before +enabling the socket. + +```sh +getent group coulobre-web-provisioning >/dev/null || sudo groupadd --system coulobre-web-provisioning +sudo install -m 0644 deploy/systemd/coulobre-web-apply.socket \ + deploy/systemd/coulobre-web-apply@.service /etc/systemd/system/ +sudo systemctl daemon-reload +sudo systemctl enable --now coulobre-web-apply.socket +``` + +Grant group membership only to the service identity responsible for provisioning +sites. The socket accepts one version 1 site manifest as UTF-8 JSON, up to 4 KiB. +After sending the manifest, shut down the writing half of the connection and +read the JSON reply to EOF. A `configured` reply includes the account ID and +domain. A `failed` reply includes a diagnostic in `problem`. Retry the same +manifest if the connection closes before a reply arrives. + ## Run an isolated PHP test site Open a completed preview for the account's current domain and select **Download diff --git a/src/coulobre/hosting/test_web_node_manifest.py b/src/coulobre/hosting/test_web_node_manifest.py index 8722d75..1471c63 100644 --- a/src/coulobre/hosting/test_web_node_manifest.py +++ b/src/coulobre/hosting/test_web_node_manifest.py @@ -1,6 +1,12 @@ +import json +from contextlib import redirect_stdout +from io import BytesIO, StringIO +from types import SimpleNamespace +from unittest.mock import patch + from django.test import SimpleTestCase -from coulobre.web_node import WebSite +from coulobre.web_node import MAX_REQUEST_BYTES, WebSite, main class WebSiteManifestTests(SimpleTestCase): @@ -32,3 +38,51 @@ class WebSiteManifestTests(SimpleTestCase): for change in invalid: with self.subTest(change=change), self.assertRaises(ValueError): WebSite.from_manifest(manifest | change) + + +class WebActivationRequestTests(SimpleTestCase): + def setUp(self): + self.site = WebSite(42, "example.org") + self.apply = self.enterContext(patch("coulobre.web_node_apply.apply_site")) + + def request(self, data): + output = StringIO() + with ( + patch("sys.stdin", SimpleNamespace(buffer=BytesIO(data))), + redirect_stdout(output), + ): + code = main(["apply-request"]) + return code, json.loads(output.getvalue()) + + def test_replies_with_the_identity_of_the_applied_manifest(self): + code, reply = self.request(json.dumps(self.site.manifest()).encode()) + self.apply.assert_called_once_with(self.site) + self.assertEqual(code, 0) + self.assertEqual( + reply, self.site.manifest() | {"state": "configured", "problem": None} + ) + + def test_rejects_invalid_or_oversized_input_before_apply(self): + for data in ( + b"", + b"\xff", + b"[" * MAX_REQUEST_BYTES, + b" " * (MAX_REQUEST_BYTES + 1), + json.dumps(self.site.manifest() | {"document_root": "/tmp"}).encode(), + ): + with self.subTest(length=len(data)): + code, reply = self.request(data) + self.assertEqual(code, 1) + self.assertEqual(reply["state"], "failed") + self.assertTrue(reply["problem"]) + self.apply.assert_not_called() + + def test_reports_node_failures_as_json_for_the_requested_site(self): + self.apply.side_effect = ValueError("The primary domain is already reserved.") + code, reply = self.request(json.dumps(self.site.manifest()).encode()) + self.assertEqual(code, 1) + self.assertEqual( + reply, + self.site.manifest() + | {"state": "failed", "problem": "The primary domain is already reserved."}, + ) diff --git a/src/coulobre/web_node.py b/src/coulobre/web_node.py index 4b5d668..64576f4 100644 --- a/src/coulobre/web_node.py +++ b/src/coulobre/web_node.py @@ -10,6 +10,7 @@ from .directadmin import DOCUMENT_ROOTS from .domain_names import canonical_domain MANIFEST_VERSION = 1 +MAX_REQUEST_BYTES = 4096 CONFIGURATIONS = {"apache": "apache-vhost.conf", "php-fpm": "php-fpm-pool.conf"} @@ -66,6 +67,28 @@ class WebSite: ) +def apply_request(): + from .web_node_apply import apply_site + + report = {"version": MANIFEST_VERSION} + try: + body = sys.stdin.buffer.read(MAX_REQUEST_BYTES + 1) + if len(body) > MAX_REQUEST_BYTES: + raise ValueError(f"The manifest exceeds {MAX_REQUEST_BYTES} bytes.") + try: + payload = json.loads(body.decode("utf-8")) + except (ValueError, RecursionError): + raise ValueError("Expected a UTF-8 JSON manifest.") from None + site = WebSite.from_manifest(payload) + report = site.manifest() + apply_site(site) + except (OSError, ValueError) as error: + print(json.dumps({**report, "state": "failed", "problem": str(error)})) + return 1 + print(json.dumps({**report, "state": "configured", "problem": None})) + return 0 + + def main(argv=None): parser = argparse.ArgumentParser(prog="coulobre-web-node") commands = parser.add_subparsers(dest="command", required=True) @@ -76,6 +99,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) + commands.add_parser( + "apply-request", + help="Apply one site manifest from standard input and report JSON.", + ) status = commands.add_parser( "status", help="Check a site's local configuration and services." ) @@ -89,6 +116,9 @@ def main(argv=None): restore.add_argument("--source-root", choices=DOCUMENT_ROOTS, default="public_html") args = parser.parse_args(argv) + if args.command == "apply-request": + return apply_request() + try: payload = json.loads(args.manifest.read_text(encoding="utf-8")) site = WebSite.from_manifest(payload) From 6523c166a8a2b3f7b4c3c847d927196c0850920b Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sat, 21 Nov 2026 01:17:01 +0100 Subject: [PATCH 2/2] Queue local website activation from Apache previews --- deploy/panel.env.example | 1 + deploy/systemd/coulobre-provisioner.service | 26 +++ docs/deployment.md | 36 ++++ .../hosting/migrations/0013_web_activation.py | 44 +++++ src/coulobre/hosting/models.py | 18 ++ src/coulobre/hosting/tasks.py | 58 ++++++- .../templates/hosting/plan_detail.html | 33 +++- src/coulobre/hosting/test_web_activation.py | 155 ++++++++++++++++++ src/coulobre/hosting/urls.py | 5 + src/coulobre/hosting/views.py | 45 ++++- src/coulobre/hosting/web_activation.py | 34 ++++ src/coulobre/settings.py | 7 + 12 files changed, 459 insertions(+), 3 deletions(-) create mode 100644 deploy/systemd/coulobre-provisioner.service create mode 100644 src/coulobre/hosting/migrations/0013_web_activation.py create mode 100644 src/coulobre/hosting/test_web_activation.py create mode 100644 src/coulobre/hosting/web_activation.py diff --git a/deploy/panel.env.example b/deploy/panel.env.example index 65e4928..3cac097 100644 --- a/deploy/panel.env.example +++ b/deploy/panel.env.example @@ -8,3 +8,4 @@ COULOBRE_DB_USER=coulobre COULOBRE_DB_PASSWORD= COULOBRE_DB_HOST=/run/mysqld/mysqld.sock COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre +# COULOBRE_LOCAL_WEB_ACTIVATION=1 diff --git a/deploy/systemd/coulobre-provisioner.service b/deploy/systemd/coulobre-provisioner.service new file mode 100644 index 0000000..ce76e4a --- /dev/null +++ b/deploy/systemd/coulobre-provisioner.service @@ -0,0 +1,26 @@ +[Unit] +Description=Coulobre Panel local web activation worker +Requires=coulobre-web-apply.socket +Wants=network-online.target +After=network-online.target coulobre-web-apply.socket mariadb.service rabbitmq-server.service + +[Service] +Type=exec +User=coulobre-provisioner +Group=coulobre-provisioner +SupplementaryGroups=coulobre-web-provisioning +EnvironmentFile=/etc/coulobre/panel.env +WorkingDirectory=/opt/coulobre +UMask=0077 +ExecStart=/opt/coulobre/bin/celery -A coulobre worker --loglevel=INFO --queues=coulobre-web-activation --hostname=provisioner@%H --concurrency=1 +KillMode=mixed +TimeoutStopSec=4min +Restart=on-failure +RestartSec=5s +NoNewPrivileges=true +PrivateTmp=true +ProtectHome=true +ProtectSystem=strict + +[Install] +WantedBy=multi-user.target diff --git a/docs/deployment.md b/docs/deployment.md index 46ec4c7..918369b 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -175,3 +175,39 @@ connected. Follow their logs with `journalctl`. ```sh sudo journalctl -u coulobre-panel -u coulobre-worker -u coulobre-beat ``` + +## Activate local websites from the panel + +Use the local activation worker when the panel and the Ubuntu 26.04 web node +share a server. Install Apache and PHP 8.5 FPM on the host and follow the +[web node setup](development.md#apply-a-manifest-on-an-ubuntu-web-node) and +[socket setup](development.md#enable-local-web-activation). + +Create a dedicated account and install the worker. Its systemd unit grants +access to the activation socket for this worker process. + +```sh +sudo useradd --system --user-group --no-create-home --home-dir /nonexistent \ + --shell /usr/sbin/nologin coulobre-provisioner +sudo install -m 0644 deploy/systemd/coulobre-provisioner.service /etc/systemd/system/ +sudo systemctl daemon-reload +``` + +Set `COULOBRE_LOCAL_WEB_ACTIVATION=1` in `/etc/coulobre/panel.env`, apply pending +database migrations, and restart the panel services. + +```sh +panel_manage migrate --noinput +sudo systemctl restart coulobre-panel coulobre-worker coulobre-beat +sudo systemctl enable --now coulobre-provisioner.service +``` + +Open a completed Apache preview and select **Activate site**. The panel queues +the request and shows its progress when you select **Refresh status**. Use +**Retry activation** after a reported failure. Operators need permission to view +hosting accounts and web provisioning plans and the **Can add web activation** +permission. + +The worker applies the domain shown in the preview. If the account's primary +domain changes before the worker starts, create a preview for the new domain. +An existing web node reservation stays bound to the domain it was created for. diff --git a/src/coulobre/hosting/migrations/0013_web_activation.py b/src/coulobre/hosting/migrations/0013_web_activation.py new file mode 100644 index 0000000..41613f3 --- /dev/null +++ b/src/coulobre/hosting/migrations/0013_web_activation.py @@ -0,0 +1,44 @@ +# Generated by Django 5.2.19 on 2026-11-21 00:13 + +import django.db.models.deletion +import django.utils.timezone +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0012_hosting_plan_quotas"), + ] + + operations = [ + migrations.CreateModel( + name="WebActivation", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ( + "requested_at", + models.DateTimeField(default=django.utils.timezone.now), + ), + ("last_dispatched_at", models.DateTimeField(blank=True, null=True)), + ("started_at", models.DateTimeField(blank=True, null=True)), + ("finished_at", models.DateTimeField(blank=True, null=True)), + ("problem", models.TextField(blank=True)), + ( + "plan", + models.OneToOneField( + on_delete=django.db.models.deletion.CASCADE, + related_name="activation", + to="hosting.webprovisioningplan", + ), + ), + ], + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index cd8270c..ecffbd5 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -2,6 +2,7 @@ from django.conf import settings from django.core.validators import RegexValidator from django.db import models from django.urls import reverse +from django.utils import timezone from coulobre.database_node import DATABASE_SUFFIX_PATTERN, INVALID_SUFFIX, DatabaseSpec from coulobre.dns_node import ( @@ -222,3 +223,20 @@ class WebProvisioningPlan(models.Model): def __str__(self): return str(self.primary_domain) + + +class WebActivation(models.Model): + plan = models.OneToOneField( + WebProvisioningPlan, on_delete=models.CASCADE, related_name="activation" + ) + requested_at = models.DateTimeField(default=timezone.now) + last_dispatched_at = models.DateTimeField(null=True, blank=True) + started_at = models.DateTimeField(null=True, blank=True) + finished_at = models.DateTimeField(null=True, blank=True) + problem = models.TextField(blank=True) + + @property + def state(self): + if self.finished_at is not None: + return "failed" if self.problem else "configured" + return "running" if self.started_at else "queued" diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py index fd4cf6b..10f6773 100644 --- a/src/coulobre/hosting/tasks.py +++ b/src/coulobre/hosting/tasks.py @@ -1,14 +1,17 @@ from datetime import timedelta from celery import shared_task +from django.conf import settings from django.db.models import Q from django.utils import timezone from coulobre.web_node import WebSite -from .models import WebProvisioningPlan +from .models import WebActivation, WebProvisioningPlan +from .web_activation import activate_local_site REDISPATCH_AFTER = timedelta(minutes=5) +WEB_ACTIVATION_QUEUE = "coulobre-web-activation" @shared_task @@ -39,3 +42,56 @@ def render_web_plan(plan_id): apache_config = WebSite(plan.account_id, plan.primary_domain).render("apache") pending.update(apache_config=apache_config, completed_at=timezone.now()) + + +@shared_task +def dispatch_web_activations(): + if not settings.LOCAL_WEB_ACTIVATION: + return + stale_before = timezone.now() - REDISPATCH_AFTER + waiting = WebActivation.objects.filter(finished_at__isnull=True) + pending = ( + waiting.filter( + Q(last_dispatched_at__isnull=True) | Q(last_dispatched_at__lte=stale_before) + ) + .filter(Q(started_at__isnull=True) | Q(started_at__lte=stale_before)) + .order_by("requested_at", "pk") + .values_list("pk", "requested_at")[:100] + ) + for activation_id, requested_at in list(pending): + activate_web_plan.apply_async( + args=[activation_id], queue=WEB_ACTIVATION_QUEUE, retry=False + ) + waiting.filter(pk=activation_id, requested_at=requested_at).update( + last_dispatched_at=timezone.now() + ) + + +@shared_task(acks_late=True, reject_on_worker_lost=True) +def activate_web_plan(activation_id): + if not settings.LOCAL_WEB_ACTIVATION: + return + started_at = timezone.now() + pending = WebActivation.objects.filter(pk=activation_id, finished_at__isnull=True) + claim = pending.filter( + Q(started_at__isnull=True) | Q(started_at__lte=started_at - REDISPATCH_AFTER) + ) + if not claim.update(started_at=started_at): + return + + running = pending.filter(started_at=started_at) + activation = running.select_related("plan__account").first() + if activation is None: + return + plan = activation.plan + problem = "" + if not plan.can_export: + problem = "Request a completed Apache preview for the current account domain." + else: + try: + activate_local_site(WebSite(plan.account_id, plan.primary_domain)) + except OSError: + problem = "Could not complete the request to the local web node. Check its socket and try again." + except ValueError as error: + problem = str(error) + running.update(finished_at=timezone.now(), problem=problem) diff --git a/src/coulobre/hosting/templates/hosting/plan_detail.html b/src/coulobre/hosting/templates/hosting/plan_detail.html index ea8d91b..eb5dc4c 100644 --- a/src/coulobre/hosting/templates/hosting/plan_detail.html +++ b/src/coulobre/hosting/templates/hosting/plan_detail.html @@ -7,7 +7,7 @@

Apache preview

{{ plan.primary_domain }}

- {% if not plan.completed_at %} + {% if not plan.completed_at or manage_activation and plan.activation and not plan.activation.finished_at %} Refresh status {% endif %} @@ -35,4 +35,35 @@ {% else %}

The configuration will appear here after the worker completes the request.

{% endif %} + {% if manage_activation %} + {% with activation=plan.activation %} + {% if activation or local_activation_enabled and plan.can_export %} +
+
+
+

Local web activation

+ {% if activation.state == "configured" %} + Configured + {% elif activation.state == "failed" %} + Activation failed + {% elif activation.state == "running" %} + Applying + {% elif activation %} + Queued + {% endif %} +
+ {% if local_activation_enabled and plan.can_export %} + {% if not activation or activation.state == "failed" %} +
+ {% csrf_token %} + +
+ {% endif %} + {% endif %} +
+ {% if activation.problem %}

{{ activation.problem }}

{% endif %} +
+ {% endif %} + {% endwith %} + {% endif %} {% endblock %} diff --git a/src/coulobre/hosting/test_web_activation.py b/src/coulobre/hosting/test_web_activation.py new file mode 100644 index 0000000..1e053dc --- /dev/null +++ b/src/coulobre/hosting/test_web_activation.py @@ -0,0 +1,155 @@ +import json +from datetime import timedelta +from io import BytesIO +from unittest.mock import patch + +from django.contrib.auth import get_user_model +from django.contrib.auth.models import Permission +from django.test import SimpleTestCase, TestCase, override_settings +from django.urls import reverse +from django.utils import timezone + +from coulobre.web_node import WebSite + +from .models import HostingAccount, Reseller, WebActivation, WebProvisioningPlan +from .tasks import REDISPATCH_AFTER, activate_web_plan, dispatch_web_activations +from .web_activation import activate_local_site + + +@override_settings(LOCAL_WEB_ACTIVATION=True) +class WebActivationTests(TestCase): + @classmethod + def setUpTestData(cls): + users = get_user_model().objects + cls.operator = users.create_superuser("operator") + cls.reseller_user = users.create_user("reseller") + cls.reseller_user.user_permissions.add( + *Permission.objects.filter(content_type__app_label="hosting") + ) + reseller = Reseller.objects.create(user=cls.reseller_user) + cls.account = HostingAccount.objects.create( + name="Example", primary_domain="site.example", reseller=reseller + ) + cls.plan = WebProvisioningPlan.objects.create( + account=cls.account, + primary_domain=cls.account.primary_domain, + completed_at=timezone.now(), + apache_config="ServerName site.example", + ) + + def setUp(self): + self.client.force_login(self.operator) + self.url = reverse("panel:plan_activate", args=[self.plan.pk]) + self.detail = reverse("panel:plan", args=[self.plan.pk]) + + def test_operator_can_queue_once_and_see_the_result(self): + self.assertContains(self.client.get(self.detail), "Activate site") + self.assertEqual(self.client.get(self.url).status_code, 405) + for _ in range(2): + self.assertRedirects(self.client.post(self.url), self.detail) + activation = WebActivation.objects.get(plan=self.plan) + self.assertContains(self.client.get(self.detail), "Queued") + with patch.object(activate_web_plan, "apply_async") as publish: + dispatch_web_activations.run() + dispatch_web_activations.run() + publish.assert_called_once_with( + args=[activation.pk], queue="coulobre-web-activation", retry=False + ) + + with patch("coulobre.hosting.tasks.activate_local_site") as apply: + activate_web_plan.run(activation.pk) + activate_web_plan.run(activation.pk) + apply.assert_called_once_with(WebSite(self.account.pk, "site.example")) + self.assertContains(self.client.get(self.detail), "Configured") + self.assertRedirects(self.client.post(self.url), self.detail) + activation.refresh_from_db() + self.assertEqual(activation.state, "configured") + + def test_tenants_and_operators_without_activation_permission_are_denied(self): + viewer = get_user_model().objects.create_user("viewer") + viewer.user_permissions.add( + *Permission.objects.filter( + codename__in=("view_hostingaccount", "view_webprovisioningplan") + ) + ) + for user in (viewer, self.reseller_user): + with self.subTest(user=user): + self.client.force_login(user) + self.assertNotContains(self.client.get(self.detail), "Activate site") + self.assertEqual(self.client.post(self.url).status_code, 403) + self.assertFalse(WebActivation.objects.exists()) + + @override_settings(LOCAL_WEB_ACTIVATION=False) + def test_disabled_local_activation_keeps_manifest_downloads_available(self): + self.assertNotContains(self.client.get(self.detail), "Activate site") + self.assertEqual(self.client.post(self.url).status_code, 404) + self.assertEqual( + self.client.get( + reverse("panel:download_deployment_manifest", args=[self.plan.pk]) + ).status_code, + 200, + ) + + def test_activation_rejects_a_stale_preview_before_calling_the_node(self): + for state in ("pending_preview", "stale_domain"): + with self.subTest(state=state): + if state == "pending_preview": + self.plan.completed_at = None + self.plan.save(update_fields=["completed_at"]) + else: + self.plan.completed_at = timezone.now() + self.plan.save(update_fields=["completed_at"]) + activation = WebActivation.objects.create(plan=self.plan) + HostingAccount.objects.filter(pk=self.account.pk).update( + primary_domain="new.example" + ) + self.assertEqual(self.client.post(self.url).status_code, 409) + + with patch("coulobre.hosting.tasks.activate_local_site") as apply: + activate_web_plan.run(activation.pk) + apply.assert_not_called() + activation.refresh_from_db() + self.assertEqual(activation.state, "failed") + self.assertIn("current account domain", activation.problem) + + def test_failed_activation_can_be_retried(self): + activation = WebActivation.objects.create( + plan=self.plan, last_dispatched_at=timezone.now() + ) + with patch("coulobre.hosting.tasks.activate_local_site", side_effect=OSError): + activate_web_plan.run(activation.pk) + self.assertContains(self.client.get(self.detail), "Retry activation") + self.assertRedirects(self.client.post(self.url), self.detail) + activation.refresh_from_db() + self.assertEqual(activation.state, "queued") + self.assertIsNone(activation.last_dispatched_at) + + def test_interrupted_activation_can_be_reclaimed_after_its_lease(self): + activation = WebActivation.objects.create( + plan=self.plan, started_at=timezone.now() + ) + with patch("coulobre.hosting.tasks.activate_local_site") as apply: + activate_web_plan.run(activation.pk) + apply.assert_not_called() + WebActivation.objects.filter(pk=activation.pk).update( + started_at=timezone.now() - REDISPATCH_AFTER - timedelta(seconds=1) + ) + activate_web_plan.run(activation.pk) + apply.assert_called_once() + + +class WebActivationReplyTests(SimpleTestCase): + def test_mismatched_node_identity_cannot_complete_activation(self): + site = WebSite(1, "site.example") + reply = site.manifest() | { + "account_id": 2, + "state": "configured", + "problem": None, + } + with patch("coulobre.hosting.web_activation.socket.socket") as socket: + connection = socket.return_value.__enter__.return_value + connection.makefile.return_value.__enter__.return_value = BytesIO( + json.dumps(reply).encode() + ) + with self.assertRaisesMessage(ValueError, "invalid response for this site"): + activate_local_site(site) diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index d4b6bc8..98c32d1 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -73,6 +73,11 @@ urlpatterns = [ ), path("plans/", views.PlanList.as_view(), name="plans"), path("plans//", views.PlanDetail.as_view(), name="plan"), + path( + "plans//activate/", + views.RequestWebActivation.as_view(), + name="plan_activate", + ), path( "plans//smoke-bundle/", views.DownloadWebPlan.as_view(), diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index 260d8ac..ac4ea49 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -1,3 +1,4 @@ +from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.mixins import PermissionRequiredMixin @@ -7,6 +8,7 @@ from django.db.models import Q from django.http import Http404, HttpResponse, HttpResponseBadRequest, JsonResponse from django.shortcuts import get_object_or_404, redirect from django.urls import reverse, reverse_lazy +from django.utils import timezone from django.utils.decorators import method_decorator from django.utils.functional import cached_property from django.views import View @@ -21,6 +23,7 @@ from .access import ( OperatorOnlyMixin, TenantScopeMixin, customer_for_user, + is_tenant, reseller_for_user, ) from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record @@ -32,6 +35,7 @@ from .models import ( HostingMailbox, HostingPlan, Reseller, + WebActivation, WebProvisioningPlan, ) from .reseller_accounts import create_reseller_account @@ -47,6 +51,7 @@ VIEW_CUSTOMERS = "hosting.view_customer" VIEW_DATABASES = "hosting.view_hostingdatabase" VIEW_DNS_ZONES = "hosting.view_hostingdnszone" VIEW_MAILBOXES = "hosting.view_hostingmailbox" +ACTIVATE_WEB = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webactivation") class AccountList(TenantScopeMixin, PermissionRequiredMixin, ListView): @@ -526,12 +531,50 @@ class PlanList(TenantScopeMixin, PermissionRequiredMixin, ListView): class PlanDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): - queryset = WebProvisioningPlan.objects.select_related("account") + queryset = WebProvisioningPlan.objects.select_related("account", "activation") permission_required = VIEW_PLANS reseller_relation = "account__reseller" template_name = "hosting/plan_detail.html" context_object_name = "plan" + def get_context_data(self, **kwargs): + user = self.request.user + return super().get_context_data( + manage_activation=not is_tenant(user) and user.has_perms(ACTIVATE_WEB), + local_activation_enabled=settings.LOCAL_WEB_ACTIVATION, + **kwargs, + ) + + +class RequestWebActivation( + OperatorOnlyMixin, PermissionRequiredMixin, SingleObjectMixin, View +): + queryset = WebProvisioningPlan.objects.select_related("account") + permission_required = ACTIVATE_WEB + + def post(self, request, *args, **kwargs): + if not settings.LOCAL_WEB_ACTIVATION: + raise Http404 + plan = self.get_object() + if not plan.can_export: + return HttpResponse( + "Request a completed Apache preview for the current account domain.", + status=409, + content_type="text/plain", + ) + activation, created = WebActivation.objects.get_or_create(plan=plan) + if not created: + WebActivation.objects.filter( + pk=activation.pk, finished_at__isnull=False + ).exclude(problem="").update( + requested_at=timezone.now(), + last_dispatched_at=None, + started_at=None, + finished_at=None, + problem="", + ) + return redirect("panel:plan", pk=plan.pk) + class DownloadWebPlan(OperatorOnlyMixin, PlanDetail): manifest = False diff --git a/src/coulobre/hosting/web_activation.py b/src/coulobre/hosting/web_activation.py new file mode 100644 index 0000000..aa95e93 --- /dev/null +++ b/src/coulobre/hosting/web_activation.py @@ -0,0 +1,34 @@ +import json +import socket + +from coulobre.web_node import WebSite + +SOCKET_PATH = "/run/coulobre-web-apply.sock" +RESPONSE_LIMIT = 32768 + + +def activate_local_site(site): + manifest = site.manifest() + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client: + client.settimeout(195) + client.connect(SOCKET_PATH) + client.sendall(json.dumps(manifest).encode("utf-8")) + client.shutdown(socket.SHUT_WR) + with client.makefile("rb") as response: + body = response.read(RESPONSE_LIMIT + 1) + + if len(body) > RESPONSE_LIMIT: + raise ValueError("The web node returned an oversized response.") + invalid_response = "The web node returned an invalid response for this site." + try: + reply = json.loads(body.decode("utf-8")) + reply_site = WebSite.from_manifest({key: reply[key] for key in manifest}) + state, problem = reply["state"], reply["problem"] + except (KeyError, TypeError, ValueError, RecursionError): + raise ValueError(invalid_response) from None + if reply_site == site: + if state == "configured" and problem is None: + return + if state == "failed" and isinstance(problem, str) and problem.strip(): + raise ValueError(problem.strip()[:2000]) + raise ValueError(invalid_response) diff --git a/src/coulobre/settings.py b/src/coulobre/settings.py index c81ca83..ed19104 100644 --- a/src/coulobre/settings.py +++ b/src/coulobre/settings.py @@ -106,6 +106,7 @@ CELERY_BROKER_URL = os.environ.get( CELERY_BROKER_TRANSPORT_OPTIONS = {"confirm_publish": True} CELERY_TASK_DEFAULT_QUEUE = "coulobre" CELERY_TASK_IGNORE_RESULT = True +LOCAL_WEB_ACTIVATION = os.environ.get("COULOBRE_LOCAL_WEB_ACTIVATION") == "1" CELERY_BEAT_SCHEDULE = { "dispatch-web-provisioning-plans": { "task": "coulobre.hosting.tasks.dispatch_web_plans", @@ -113,3 +114,9 @@ CELERY_BEAT_SCHEDULE = { "options": {"expires": 5.0}, }, } +if LOCAL_WEB_ACTIVATION: + CELERY_BEAT_SCHEDULE["dispatch-web-activations"] = { + "task": "coulobre.hosting.tasks.dispatch_web_activations", + "schedule": 5.0, + "options": {"expires": 4.0}, + }