Queue local website activation from Apache previews

This commit is contained in:
parkel committed 2026-11-21 01:17:01 +01:00
1 parent 7f706c39b5
commit 6523c166a8
12 files changed
+459 -3

No files matched your search

+1
View File
@@ -8,3 +8,4 @@ COULOBRE_DB_USER=coulobre
COULOBRE_DB_PASSWORD= COULOBRE_DB_PASSWORD=
COULOBRE_DB_HOST=/run/mysqld/mysqld.sock COULOBRE_DB_HOST=/run/mysqld/mysqld.sock
COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre
# COULOBRE_LOCAL_WEB_ACTIVATION=1
@@ -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
+36
View File
@@ -175,3 +175,39 @@ connected. Follow their logs with `journalctl`.
```sh ```sh
sudo journalctl -u coulobre-panel -u coulobre-worker -u coulobre-beat 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.
@@ -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",
),
),
],
),
]
+18
View File
@@ -2,6 +2,7 @@ from django.conf import settings
from django.core.validators import RegexValidator from django.core.validators import RegexValidator
from django.db import models from django.db import models
from django.urls import reverse from django.urls import reverse
from django.utils import timezone
from coulobre.database_node import DATABASE_SUFFIX_PATTERN, INVALID_SUFFIX, DatabaseSpec from coulobre.database_node import DATABASE_SUFFIX_PATTERN, INVALID_SUFFIX, DatabaseSpec
from coulobre.dns_node import ( from coulobre.dns_node import (
@@ -222,3 +223,20 @@ class WebProvisioningPlan(models.Model):
def __str__(self): def __str__(self):
return str(self.primary_domain) 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"
+57 -1
View File
@@ -1,14 +1,17 @@
from datetime import timedelta from datetime import timedelta
from celery import shared_task from celery import shared_task
from django.conf import settings
from django.db.models import Q from django.db.models import Q
from django.utils import timezone from django.utils import timezone
from coulobre.web_node import WebSite 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) REDISPATCH_AFTER = timedelta(minutes=5)
WEB_ACTIVATION_QUEUE = "coulobre-web-activation"
@shared_task @shared_task
@@ -39,3 +42,56 @@ def render_web_plan(plan_id):
apache_config = WebSite(plan.account_id, plan.primary_domain).render("apache") apache_config = WebSite(plan.account_id, plan.primary_domain).render("apache")
pending.update(apache_config=apache_config, completed_at=timezone.now()) 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)
@@ -7,7 +7,7 @@
<h1>Apache preview</h1> <h1>Apache preview</h1>
<p class="heading-meta domain">{{ plan.primary_domain }}</p> <p class="heading-meta domain">{{ plan.primary_domain }}</p>
</div> </div>
{% if not plan.completed_at %} {% if not plan.completed_at or manage_activation and plan.activation and not plan.activation.finished_at %}
<a class="button secondary" href="{% url 'panel:plan' plan.pk %}">Refresh status</a> <a class="button secondary" href="{% url 'panel:plan' plan.pk %}">Refresh status</a>
{% endif %} {% endif %}
</header> </header>
@@ -35,4 +35,35 @@
{% else %} {% else %}
<p class="notice">The configuration will appear here after the worker completes the request.</p> <p class="notice">The configuration will appear here after the worker completes the request.</p>
{% endif %} {% endif %}
{% if manage_activation %}
{% with activation=plan.activation %}
{% if activation or local_activation_enabled and plan.can_export %}
<section class="surface" aria-labelledby="activation-heading">
<header class="section-heading">
<div>
<h2 id="activation-heading">Local web activation</h2>
{% if activation.state == "configured" %}
<span class="status ready">Configured</span>
{% elif activation.state == "failed" %}
<span class="status suspended">Activation failed</span>
{% elif activation.state == "running" %}
<span class="status pending">Applying</span>
{% elif activation %}
<span class="status pending">Queued</span>
{% endif %}
</div>
{% if local_activation_enabled and plan.can_export %}
{% if not activation or activation.state == "failed" %}
<form method="post" action="{% url 'panel:plan_activate' plan.pk %}">
{% csrf_token %}
<button class="button primary" type="submit">{% if activation %}Retry activation{% else %}Activate site{% endif %}</button>
</form>
{% endif %}
{% endif %}
</header>
{% if activation.problem %}<p class="empty">{{ activation.problem }}</p>{% endif %}
</section>
{% endif %}
{% endwith %}
{% endif %}
{% endblock %} {% endblock %}
+155
View File
@@ -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)
+5
View File
@@ -73,6 +73,11 @@ urlpatterns = [
), ),
path("plans/", views.PlanList.as_view(), name="plans"), path("plans/", views.PlanList.as_view(), name="plans"),
path("plans/<int:pk>/", views.PlanDetail.as_view(), name="plan"), path("plans/<int:pk>/", views.PlanDetail.as_view(), name="plan"),
path(
"plans/<int:pk>/activate/",
views.RequestWebActivation.as_view(),
name="plan_activate",
),
path( path(
"plans/<int:pk>/smoke-bundle/", "plans/<int:pk>/smoke-bundle/",
views.DownloadWebPlan.as_view(), views.DownloadWebPlan.as_view(),
+44 -1
View File
@@ -1,3 +1,4 @@
from django.conf import settings
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.mixins import PermissionRequiredMixin 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.http import Http404, HttpResponse, HttpResponseBadRequest, JsonResponse
from django.shortcuts import get_object_or_404, redirect from django.shortcuts import get_object_or_404, redirect
from django.urls import reverse, reverse_lazy from django.urls import reverse, reverse_lazy
from django.utils import timezone
from django.utils.decorators import method_decorator from django.utils.decorators import method_decorator
from django.utils.functional import cached_property from django.utils.functional import cached_property
from django.views import View from django.views import View
@@ -21,6 +23,7 @@ from .access import (
OperatorOnlyMixin, OperatorOnlyMixin,
TenantScopeMixin, TenantScopeMixin,
customer_for_user, customer_for_user,
is_tenant,
reseller_for_user, reseller_for_user,
) )
from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record
@@ -32,6 +35,7 @@ from .models import (
HostingMailbox, HostingMailbox,
HostingPlan, HostingPlan,
Reseller, Reseller,
WebActivation,
WebProvisioningPlan, WebProvisioningPlan,
) )
from .reseller_accounts import create_reseller_account from .reseller_accounts import create_reseller_account
@@ -47,6 +51,7 @@ VIEW_CUSTOMERS = "hosting.view_customer"
VIEW_DATABASES = "hosting.view_hostingdatabase" VIEW_DATABASES = "hosting.view_hostingdatabase"
VIEW_DNS_ZONES = "hosting.view_hostingdnszone" VIEW_DNS_ZONES = "hosting.view_hostingdnszone"
VIEW_MAILBOXES = "hosting.view_hostingmailbox" VIEW_MAILBOXES = "hosting.view_hostingmailbox"
ACTIVATE_WEB = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webactivation")
class AccountList(TenantScopeMixin, PermissionRequiredMixin, ListView): class AccountList(TenantScopeMixin, PermissionRequiredMixin, ListView):
@@ -526,12 +531,50 @@ class PlanList(TenantScopeMixin, PermissionRequiredMixin, ListView):
class PlanDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): class PlanDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
queryset = WebProvisioningPlan.objects.select_related("account") queryset = WebProvisioningPlan.objects.select_related("account", "activation")
permission_required = VIEW_PLANS permission_required = VIEW_PLANS
reseller_relation = "account__reseller" reseller_relation = "account__reseller"
template_name = "hosting/plan_detail.html" template_name = "hosting/plan_detail.html"
context_object_name = "plan" 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): class DownloadWebPlan(OperatorOnlyMixin, PlanDetail):
manifest = False manifest = False
+34
View File
@@ -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)
+7
View File
@@ -106,6 +106,7 @@ CELERY_BROKER_URL = os.environ.get(
CELERY_BROKER_TRANSPORT_OPTIONS = {"confirm_publish": True} CELERY_BROKER_TRANSPORT_OPTIONS = {"confirm_publish": True}
CELERY_TASK_DEFAULT_QUEUE = "coulobre" CELERY_TASK_DEFAULT_QUEUE = "coulobre"
CELERY_TASK_IGNORE_RESULT = True CELERY_TASK_IGNORE_RESULT = True
LOCAL_WEB_ACTIVATION = os.environ.get("COULOBRE_LOCAL_WEB_ACTIVATION") == "1"
CELERY_BEAT_SCHEDULE = { CELERY_BEAT_SCHEDULE = {
"dispatch-web-provisioning-plans": { "dispatch-web-provisioning-plans": {
"task": "coulobre.hosting.tasks.dispatch_web_plans", "task": "coulobre.hosting.tasks.dispatch_web_plans",
@@ -113,3 +114,9 @@ CELERY_BEAT_SCHEDULE = {
"options": {"expires": 5.0}, "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},
}