Provision local MariaDB databases from the panel

This commit is contained in:
parkel committed 2026-11-21 01:26:10 +01:00
1 parent 091193baa0
commit 902a769eb3
14 files changed
+417 -54

No files matched your search

+1
View File
@@ -9,3 +9,4 @@ 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
# COULOBRE_LOCAL_DATABASE_PROVISIONING=1
@@ -0,0 +1,26 @@
[Unit]
Description=Coulobre Panel local MariaDB provisioning worker
Requires=coulobre-database-apply.socket
Wants=network-online.target
After=network-online.target coulobre-database-apply.socket mariadb.service rabbitmq-server.service
[Service]
Type=exec
User=coulobre-db-provisioner
Group=coulobre-db-provisioner
SupplementaryGroups=coulobre-db-provisioning
EnvironmentFile=/etc/coulobre/panel.env
WorkingDirectory=/opt/coulobre
UMask=0077
ExecStart=/opt/coulobre/bin/celery -A coulobre worker --loglevel=INFO --queues=coulobre-database-provisioning --hostname=database-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
+31
View File
@@ -211,3 +211,34 @@ 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.
## Provision local databases from the panel
Enable the [database provisioning socket](development.md#enable-local-database-provisioning)
on the panel host. Install the MariaDB worker under a dedicated identity with
access to that socket.
```sh
sudo useradd --system --user-group --no-create-home --home-dir /nonexistent \
--shell /usr/sbin/nologin coulobre-db-provisioner
sudo install -m 0644 deploy/systemd/coulobre-database-provisioner.service /etc/systemd/system/
sudo systemctl daemon-reload
```
Set `COULOBRE_LOCAL_DATABASE_PROVISIONING=1` in `/etc/coulobre/panel.env`, then
apply pending 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-database-provisioner.service
```
Open a hosting account and select **Provision database** for a database request.
Reload the account page to see the status. Use **Retry provisioning** after a
reported failure. Operators need permission to view hosting accounts and
database requests and the **Can add database provisioning** permission.
The MariaDB node stores the application login in the root-only file
`/var/lib/coulobre/database-node/<database-name>.json`. Use the credentials
from that file when configuring the hosted application.
@@ -0,0 +1,47 @@
# Generated by Django 5.2.19 on 2026-11-21 00:23
import django.db.models.deletion
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0013_web_activation"),
]
operations = [
migrations.CreateModel(
name="DatabaseProvisioning",
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)),
(
"database",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
related_name="provisioning",
to="hosting.hostingdatabase",
),
),
],
options={
"abstract": False,
},
),
]
+32 -4
View File
@@ -225,18 +225,46 @@ class WebProvisioningPlan(models.Model):
return str(self.primary_domain)
class WebActivation(models.Model):
plan = models.OneToOneField(
WebProvisioningPlan, on_delete=models.CASCADE, related_name="activation"
)
class ProvisioningJobManager(models.Manager):
def queue(self, **target):
job, created = self.get_or_create(**target)
if not created:
self.filter(pk=job.pk, finished_at__isnull=False).exclude(
problem=""
).update(
requested_at=timezone.now(),
last_dispatched_at=None,
started_at=None,
finished_at=None,
problem="",
)
class ProvisioningJob(models.Model):
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)
objects = ProvisioningJobManager()
class Meta:
abstract = 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"
class WebActivation(ProvisioningJob):
plan = models.OneToOneField(
WebProvisioningPlan, on_delete=models.CASCADE, related_name="activation"
)
class DatabaseProvisioning(ProvisioningJob):
database = models.OneToOneField(
HostingDatabase, on_delete=models.CASCADE, related_name="provisioning"
)
@@ -1,32 +1,39 @@
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()
apply_on_local_node(site, "/run/coulobre-web-apply.sock", "web node", "site")
def provision_local_database(database):
apply_on_local_node(
database, "/run/coulobre-database-apply.sock", "MariaDB node", "database"
)
def apply_on_local_node(spec, socket_path, node, resource):
manifest = spec.manifest()
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client:
client.settimeout(195)
client.connect(SOCKET_PATH)
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."
raise ValueError(f"The {node} returned an oversized response.")
invalid_response = f"The {node} returned an invalid response for this {resource}."
try:
reply = json.loads(body.decode("utf-8"))
reply_site = WebSite.from_manifest({key: reply[key] for key in manifest})
reply_spec = type(spec).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 reply_spec == spec:
if state == "configured" and problem is None:
return
if state == "failed" and isinstance(problem, str) and problem.strip():
+65 -25
View File
@@ -7,11 +7,12 @@ from django.utils import timezone
from coulobre.web_node import WebSite
from .models import WebActivation, WebProvisioningPlan
from .web_activation import activate_local_site
from .models import DatabaseProvisioning, WebActivation, WebProvisioningPlan
from .node_client import activate_local_site, provision_local_database
REDISPATCH_AFTER = timedelta(minutes=5)
WEB_ACTIVATION_QUEUE = "coulobre-web-activation"
DATABASE_PROVISIONING_QUEUE = "coulobre-database-provisioning"
@shared_task
@@ -46,10 +47,23 @@ def render_web_plan(plan_id):
@shared_task
def dispatch_web_activations():
if not settings.LOCAL_WEB_ACTIVATION:
return
if settings.LOCAL_WEB_ACTIVATION:
dispatch_provisioning_jobs(
WebActivation, activate_web_plan, WEB_ACTIVATION_QUEUE
)
@shared_task
def dispatch_database_provisioning():
if settings.LOCAL_DATABASE_PROVISIONING:
dispatch_provisioning_jobs(
DatabaseProvisioning, provision_database, DATABASE_PROVISIONING_QUEUE
)
def dispatch_provisioning_jobs(model, task, queue):
stale_before = timezone.now() - REDISPATCH_AFTER
waiting = WebActivation.objects.filter(finished_at__isnull=True)
waiting = model.objects.filter(finished_at__isnull=True)
pending = (
waiting.filter(
Q(last_dispatched_at__isnull=True) | Q(last_dispatched_at__lte=stale_before)
@@ -58,21 +72,51 @@ def dispatch_web_activations():
.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(
for job_id, requested_at in list(pending):
task.apply_async(args=[job_id], queue=queue, retry=False)
waiting.filter(pk=job_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
if settings.LOCAL_WEB_ACTIVATION:
run_provisioning_job(
WebActivation.objects.select_related("plan__account"),
activation_id,
apply_web_activation,
"Could not complete the request to the local web node. Check its socket and try again.",
)
def apply_web_activation(activation):
plan = activation.plan
if not plan.can_export:
raise ValueError(
"Request a completed Apache preview for the current account domain."
)
activate_local_site(WebSite(plan.account_id, plan.primary_domain))
@shared_task(acks_late=True, reject_on_worker_lost=True)
def provision_database(provisioning_id):
if settings.LOCAL_DATABASE_PROVISIONING:
run_provisioning_job(
DatabaseProvisioning.objects.select_related("database"),
provisioning_id,
apply_database_provisioning,
"Could not complete the request to the local MariaDB node. Check its socket and try again.",
)
def apply_database_provisioning(provisioning):
provision_local_database(provisioning.database.spec)
def run_provisioning_job(jobs, job_id, apply, connection_problem):
started_at = timezone.now()
pending = WebActivation.objects.filter(pk=activation_id, finished_at__isnull=True)
pending = jobs.filter(pk=job_id, finished_at__isnull=True)
claim = pending.filter(
Q(started_at__isnull=True) | Q(started_at__lte=started_at - REDISPATCH_AFTER)
)
@@ -80,18 +124,14 @@ def activate_web_plan(activation_id):
return
running = pending.filter(started_at=started_at)
activation = running.select_related("plan__account").first()
if activation is None:
job = running.first()
if job 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)
try:
apply(job)
except OSError:
problem = connection_problem
except ValueError as error:
problem = str(error)
running.update(finished_at=timezone.now(), problem=problem)
@@ -62,7 +62,17 @@
<tr>
<td class="domain">{{ database }}</td>
{% if is_operator %}
<td><a class="record-link" href="{% url 'panel:database_manifest' database.pk %}" aria-label="Download manifest for {{ database }}">Download manifest</a></td>
<td>
<div class="form-actions">
<a class="record-link" href="{% url 'panel:database_manifest' database.pk %}" aria-label="Download manifest for {{ database }}">Download manifest</a>
{% if manage_database_provisioning %}
{% include "hosting/database_provisioning.html" with provisioning=database.provisioning %}
{% endif %}
</div>
{% if manage_database_provisioning and database.provisioning.problem %}
<p class="heading-meta">{{ database.provisioning.problem }}</p>
{% endif %}
</td>
{% endif %}
</tr>
{% endfor %}
@@ -0,0 +1,21 @@
{% if provisioning.state == "configured" %}
<span class="status ready">Configured</span>
{% elif provisioning.state == "failed" %}
<span class="status suspended">Provisioning failed</span>
{% elif provisioning.state == "running" %}
<span class="status pending">Provisioning</span>
{% elif provisioning %}
<span class="status pending">Queued</span>
{% endif %}
{% if local_database_enabled %}
{% if not provisioning or provisioning.state == "failed" %}
<form method="post" action="{% url 'panel:database_provision' database.pk %}">
{% csrf_token %}
{% if provisioning %}
<button class="button secondary" type="submit" aria-label="Retry provisioning {{ database }}">Retry provisioning</button>
{% else %}
<button class="button secondary" type="submit" aria-label="Provision database {{ database }}">Provision database</button>
{% endif %}
</form>
{% endif %}
{% endif %}
@@ -0,0 +1,129 @@
import json
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 coulobre.database_node import DatabaseSpec
from .models import Customer, DatabaseProvisioning, HostingAccount, HostingDatabase
from .node_client import provision_local_database
from .tasks import dispatch_database_provisioning, provision_database
@override_settings(LOCAL_DATABASE_PROVISIONING=True)
class DatabaseProvisioningTests(TestCase):
@classmethod
def setUpTestData(cls):
users = get_user_model().objects
cls.operator = users.create_user("operator")
cls.permissions = Permission.objects.filter(
content_type__app_label="hosting",
codename__in=(
"view_hostingaccount",
"view_hostingdatabase",
"add_databaseprovisioning",
),
)
cls.operator.user_permissions.add(*cls.permissions)
cls.user = users.create_user("customer")
cls.user.user_permissions.add(*cls.permissions)
customer = Customer.objects.create(user=cls.user)
cls.account = HostingAccount.objects.create(
name="Example", primary_domain="site.example", customer=customer
)
cls.database = HostingDatabase.objects.create(account=cls.account, suffix="cms")
def setUp(self):
self.client.force_login(self.operator)
self.url = reverse("panel:database_provision", args=[self.database.pk])
self.detail = self.account.get_absolute_url()
def test_operator_can_queue_once_and_see_the_completed_result(self):
self.assertContains(self.client.get(self.detail), "Provision database")
self.assertEqual(self.client.get(self.url).status_code, 405)
for _ in range(2):
self.assertRedirects(self.client.post(self.url), self.detail)
job = DatabaseProvisioning.objects.get(database=self.database)
self.assertContains(self.client.get(self.detail), "Queued")
with patch.object(provision_database, "apply_async") as publish:
dispatch_database_provisioning.run()
dispatch_database_provisioning.run()
publish.assert_called_once_with(
args=[job.pk], queue="coulobre-database-provisioning", retry=False
)
with patch("coulobre.hosting.tasks.provision_local_database") as apply:
provision_database.run(job.pk)
provision_database.run(job.pk)
apply.assert_called_once_with(self.database.spec)
self.assertContains(self.client.get(self.detail), "Configured")
self.assertRedirects(self.client.post(self.url), self.detail)
job.refresh_from_db()
self.assertEqual(job.state, "configured")
def test_customer_and_operator_without_permission_cannot_provision(self):
viewer = get_user_model().objects.create_user("viewer")
viewer.user_permissions.add(
*self.permissions.exclude(codename="add_databaseprovisioning")
)
for user in (self.user, viewer):
with self.subTest(user=user):
self.client.force_login(user)
self.assertNotContains(
self.client.get(self.detail), "Provision database"
)
self.assertEqual(self.client.post(self.url).status_code, 403)
self.assertFalse(DatabaseProvisioning.objects.exists())
@override_settings(LOCAL_DATABASE_PROVISIONING=False)
def test_disabled_provisioning_preserves_existing_manifest_download(self):
detail = self.client.get(self.detail)
self.assertNotContains(detail, "Provision database")
self.assertContains(detail, "Download manifest")
self.assertEqual(self.client.post(self.url).status_code, 404)
def test_operator_can_retry_a_failed_request(self):
self.assertRedirects(self.client.post(self.url), self.detail)
job = DatabaseProvisioning.objects.get(database=self.database)
with patch(
"coulobre.hosting.tasks.provision_local_database", side_effect=OSError
):
provision_database.run(job.pk)
detail = self.client.get(self.detail)
self.assertContains(detail, "Retry provisioning")
self.assertContains(
detail, "Could not complete the request to the local MariaDB node"
)
self.assertRedirects(self.client.post(self.url), self.detail)
job.refresh_from_db()
self.assertEqual(job.state, "queued")
self.assertFalse(job.problem)
class DatabaseProvisioningSocketTests(SimpleTestCase):
def test_client_verifies_the_resource_and_uses_the_database_socket(self):
spec = DatabaseSpec(1, "cms")
manifest = spec.manifest()
reply = manifest | {"state": "configured", "problem": None}
with patch("coulobre.hosting.node_client.socket.socket") as socket:
connection = socket.return_value.__enter__.return_value
read = connection.makefile.return_value.__enter__
read.side_effect = (
BytesIO(json.dumps(reply).encode()),
BytesIO(json.dumps(reply | {"suffix": "other"}).encode()),
)
provision_local_database(spec)
connection.connect.assert_called_once_with(
"/run/coulobre-database-apply.sock"
)
sent = connection.sendall.call_args.args[0]
self.assertEqual(json.loads(sent), manifest)
with self.assertRaisesMessage(
ValueError, "invalid response for this database"
):
provision_local_database(spec)
+2 -2
View File
@@ -12,8 +12,8 @@ from django.utils import timezone
from coulobre.web_node import WebSite
from .models import HostingAccount, Reseller, WebActivation, WebProvisioningPlan
from .node_client import activate_local_site
from .tasks import REDISPATCH_AFTER, activate_web_plan, dispatch_web_activations
from .web_activation import activate_local_site
@override_settings(LOCAL_WEB_ACTIVATION=True)
@@ -146,7 +146,7 @@ class WebActivationReplyTests(SimpleTestCase):
"state": "configured",
"problem": None,
}
with patch("coulobre.hosting.web_activation.socket.socket") as socket:
with patch("coulobre.hosting.node_client.socket.socket") as socket:
connection = socket.return_value.__enter__.return_value
connection.makefile.return_value.__enter__.return_value = BytesIO(
json.dumps(reply).encode()
+5
View File
@@ -36,6 +36,11 @@ urlpatterns = [
views.DownloadDatabaseManifest.as_view(),
name="database_manifest",
),
path(
"databases/<int:pk>/provision/",
views.RequestDatabaseProvisioning.as_view(),
name="database_provision",
),
path(
"accounts/<int:pk>/dns-zones/new/",
views.DnsZoneCreate.as_view(),
+22 -13
View File
@@ -8,7 +8,6 @@ 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
@@ -29,6 +28,7 @@ from .access import (
from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record
from .models import (
Customer,
DatabaseProvisioning,
HostingAccount,
HostingDatabase,
HostingDnsZone,
@@ -52,6 +52,7 @@ 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")
PROVISION_DATABASE = (VIEW_ACCOUNTS, VIEW_DATABASES, "hosting.add_databaseprovisioning")
class AccountList(TenantScopeMixin, PermissionRequiredMixin, ListView):
@@ -190,7 +191,12 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
"-requested_at", "-pk"
)[:10]
if tenant or user.has_perm(VIEW_DATABASES):
context["databases"] = self.object.databases.all()
databases = self.object.databases.all()
if not tenant and user.has_perms(PROVISION_DATABASE):
databases = databases.select_related("provisioning")
context["manage_database_provisioning"] = True
context["local_database_enabled"] = settings.LOCAL_DATABASE_PROVISIONING
context["databases"] = databases
if tenant or user.has_perm(VIEW_DNS_ZONES):
zones = list(self.object.dns_zones.all())
context["dns_zones"] = zones
@@ -325,6 +331,19 @@ class DownloadDatabaseManifest(OperatorOnlyMixin, PermissionRequiredMixin, View)
)
class RequestDatabaseProvisioning(OperatorOnlyMixin, PermissionRequiredMixin, View):
permission_required = PROVISION_DATABASE
def post(self, request, pk):
if not settings.LOCAL_DATABASE_PROVISIONING:
raise Http404
database = get_object_or_404(
HostingDatabase.objects.select_related("account"), pk=pk
)
DatabaseProvisioning.objects.queue(database=database)
return redirect(database.account)
class DnsZoneEditor(OperatorOnlyMixin, PermissionRequiredMixin, FormView):
template_name = "hosting/dns_zone_form.html"
@@ -562,17 +581,7 @@ class RequestWebActivation(
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="",
)
WebActivation.objects.queue(plan=plan)
return redirect("panel:plan", pk=plan.pk)
+9
View File
@@ -107,6 +107,9 @@ 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"
LOCAL_DATABASE_PROVISIONING = (
os.environ.get("COULOBRE_LOCAL_DATABASE_PROVISIONING") == "1"
)
CELERY_BEAT_SCHEDULE = {
"dispatch-web-provisioning-plans": {
"task": "coulobre.hosting.tasks.dispatch_web_plans",
@@ -120,3 +123,9 @@ if LOCAL_WEB_ACTIVATION:
"schedule": 5.0,
"options": {"expires": 4.0},
}
if LOCAL_DATABASE_PROVISIONING:
CELERY_BEAT_SCHEDULE["dispatch-database-provisioning"] = {
"task": "coulobre.hosting.tasks.dispatch_database_provisioning",
"schedule": 5.0,
"options": {"expires": 4.0},
}