diff --git a/deploy/panel.env.example b/deploy/panel.env.example index 3cac097..c276f0d 100644 --- a/deploy/panel.env.example +++ b/deploy/panel.env.example @@ -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 diff --git a/deploy/systemd/coulobre-database-apply.socket b/deploy/systemd/coulobre-database-apply.socket new file mode 100644 index 0000000..9ff1076 --- /dev/null +++ b/deploy/systemd/coulobre-database-apply.socket @@ -0,0 +1,14 @@ +[Unit] +Description=Coulobre local MariaDB provisioning socket + +[Socket] +ListenStream=/run/coulobre-database-apply.sock +SocketUser=root +SocketGroup=coulobre-db-provisioning +SocketMode=0660 +Accept=yes +MaxConnections=4 +RemoveOnStop=true + +[Install] +WantedBy=sockets.target diff --git a/deploy/systemd/coulobre-database-apply@.service b/deploy/systemd/coulobre-database-apply@.service new file mode 100644 index 0000000..b185bbb --- /dev/null +++ b/deploy/systemd/coulobre-database-apply@.service @@ -0,0 +1,21 @@ +[Unit] +Description=Coulobre local MariaDB provisioning request +After=mariadb.service +CollectMode=inactive-or-failed + +[Service] +Type=exec +User=root +WorkingDirectory=/opt/coulobre +StateDirectory=coulobre/database-node +StateDirectoryMode=0700 +UMask=0077 +ExecStart=/opt/coulobre/bin/coulobre-database-node apply-request +StandardInput=socket +StandardOutput=socket +StandardError=journal +RuntimeMaxSec=3min +NoNewPrivileges=true +PrivateTmp=true +ProtectHome=true +ProtectSystem=strict diff --git a/deploy/systemd/coulobre-database-provisioner.service b/deploy/systemd/coulobre-database-provisioner.service new file mode 100644 index 0000000..c13027c --- /dev/null +++ b/deploy/systemd/coulobre-database-provisioner.service @@ -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 diff --git a/docs/deployment.md b/docs/deployment.md index 918369b..5a5057e 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -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/.json`. Use the credentials +from that file when configuring the hosted application. diff --git a/docs/development.md b/docs/development.md index ab25b90..e2b6e69 100644 --- a/docs/development.md +++ b/docs/development.md @@ -142,6 +142,28 @@ message when the installation needs attention. Exit code `1` indicates an invalid manifest or an unavailable check, for example when the MariaDB administrative connection fails. +### Enable local database provisioning + +On a MariaDB node using `/run/mysqld/mysqld.sock`, install the matching Coulobre +package with its `mariadb` extra in a root-owned virtual environment at +`/opt/coulobre`. Enable the local provisioning socket. + +```sh +getent group coulobre-db-provisioning >/dev/null || sudo groupadd --system coulobre-db-provisioning +sudo install -m 0644 deploy/systemd/coulobre-database-apply.socket \ + deploy/systemd/coulobre-database-apply@.service /etc/systemd/system/ +sudo systemctl daemon-reload +sudo systemctl enable --now coulobre-database-apply.socket +``` + +Grant the socket group only to the service identity responsible for database +provisioning. Send one version 1 MariaDB database manifest as UTF-8 JSON to +`/run/coulobre-database-apply.sock`. The limit is 4 KiB. Close the writing half +of the socket and read the JSON reply to EOF. For a valid manifest, the reply +includes its identity, a state of `configured` or `failed`, and a diagnostic +on failure. +MariaDB passwords stay in the root-only credentials files on the node. + ## Render a BIND9 zone Open a hosting account and select **Add DNS zone** to configure a zone for diff --git a/src/coulobre/database_node.py b/src/coulobre/database_node.py index e390386..61a6462 100644 --- a/src/coulobre/database_node.py +++ b/src/coulobre/database_node.py @@ -4,6 +4,8 @@ import re from dataclasses import dataclass from pathlib import Path +from .node_requests import serve_apply_request + MANIFEST_VERSION = 1 MANIFEST_KIND = "mariadb_database" DEFAULT_SOCKET = Path("/run/mysqld/mysqld.sock") @@ -66,6 +68,10 @@ def main(argv=None): ) apply.add_argument("manifest", type=Path) apply.add_argument("--socket", type=Path, default=DEFAULT_SOCKET) + commands.add_parser( + "apply-request", + help="Apply one MariaDB manifest from standard input and report JSON.", + ) status = commands.add_parser( "status", help="Check a database and its local login on MariaDB." ) @@ -73,6 +79,15 @@ def main(argv=None): status.add_argument("--socket", type=Path, default=DEFAULT_SOCKET) args = parser.parse_args(argv) + if args.command == "apply-request": + from .database_node_apply import apply_database + + return serve_apply_request( + MANIFEST_VERSION, + DatabaseSpec.from_manifest, + lambda database: apply_database(database, DEFAULT_SOCKET), + ) + try: payload = json.loads(args.manifest.read_text(encoding="utf-8")) database = DatabaseSpec.from_manifest(payload) diff --git a/src/coulobre/hosting/migrations/0014_database_provisioning.py b/src/coulobre/hosting/migrations/0014_database_provisioning.py new file mode 100644 index 0000000..69c0ea3 --- /dev/null +++ b/src/coulobre/hosting/migrations/0014_database_provisioning.py @@ -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, + }, + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index ecffbd5..42844a8 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -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" + ) diff --git a/src/coulobre/hosting/web_activation.py b/src/coulobre/hosting/node_client.py similarity index 58% rename from src/coulobre/hosting/web_activation.py rename to src/coulobre/hosting/node_client.py index aa95e93..e003383 100644 --- a/src/coulobre/hosting/web_activation.py +++ b/src/coulobre/hosting/node_client.py @@ -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(): diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py index 10f6773..5181308 100644 --- a/src/coulobre/hosting/tasks.py +++ b/src/coulobre/hosting/tasks.py @@ -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) diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index d858710..ba38818 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -62,7 +62,17 @@ {{ database }} {% if is_operator %} - Download manifest + +
+ Download manifest + {% if manage_database_provisioning %} + {% include "hosting/database_provisioning.html" with provisioning=database.provisioning %} + {% endif %} +
+ {% if manage_database_provisioning and database.provisioning.problem %} +

{{ database.provisioning.problem }}

+ {% endif %} + {% endif %} {% endfor %} diff --git a/src/coulobre/hosting/templates/hosting/database_provisioning.html b/src/coulobre/hosting/templates/hosting/database_provisioning.html new file mode 100644 index 0000000..f827f9c --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/database_provisioning.html @@ -0,0 +1,21 @@ +{% if provisioning.state == "configured" %} + Configured +{% elif provisioning.state == "failed" %} + Provisioning failed +{% elif provisioning.state == "running" %} + Provisioning +{% elif provisioning %} + Queued +{% endif %} +{% if local_database_enabled %} + {% if not provisioning or provisioning.state == "failed" %} +
+ {% csrf_token %} + {% if provisioning %} + + {% else %} + + {% endif %} +
+ {% endif %} +{% endif %} diff --git a/src/coulobre/hosting/test_database_node_apply.py b/src/coulobre/hosting/test_database_node_apply.py index c477f84..8171a1f 100644 --- a/src/coulobre/hosting/test_database_node_apply.py +++ b/src/coulobre/hosting/test_database_node_apply.py @@ -1,12 +1,15 @@ import json import stat +from contextlib import redirect_stdout +from io import BytesIO, StringIO from pathlib import Path from tempfile import TemporaryDirectory +from types import SimpleNamespace from unittest.mock import Mock, patch from django.test import SimpleTestCase -from coulobre.database_node import DatabaseSpec +from coulobre.database_node import DEFAULT_SOCKET, DatabaseSpec, main from coulobre.database_node_apply import ( MANAGED_COMMENT_PREFIX, check_database, @@ -15,6 +18,42 @@ from coulobre.database_node_apply import ( ) +class DatabaseApplyRequestTests(SimpleTestCase): + def setUp(self): + self.database = DatabaseSpec(42, "site_db") + self.apply = self.enterContext( + patch( + "coulobre.database_node_apply.apply_database", + return_value=Path("/private/credentials.json"), + ) + ) + + def request(self, manifest): + data = BytesIO(json.dumps(manifest).encode()) + output = StringIO() + with ( + patch("sys.stdin", SimpleNamespace(buffer=data)), + redirect_stdout(output), + ): + code = main(["apply-request"]) + return code, json.loads(output.getvalue()) + + def test_request_uses_the_local_socket_and_reports_only_manifest_identity(self): + manifest = self.database.manifest() + code, reply = self.request(manifest) + self.apply.assert_called_once_with(self.database, DEFAULT_SOCKET) + self.assertEqual(code, 0) + self.assertEqual(reply, manifest | {"state": "configured", "problem": None}) + + def test_request_rejects_a_socket_supplied_by_the_client(self): + code, reply = self.request( + self.database.manifest() | {"socket": "/tmp/custom.sock"} + ) + self.assertEqual(code, 1) + self.assertEqual(reply["state"], "failed") + self.apply.assert_not_called() + + class DatabaseProvisioningTests(SimpleTestCase): def setUp(self): root = Path(self.enterContext(TemporaryDirectory())) diff --git a/src/coulobre/hosting/test_database_provisioning.py b/src/coulobre/hosting/test_database_provisioning.py new file mode 100644 index 0000000..9ac4856 --- /dev/null +++ b/src/coulobre/hosting/test_database_provisioning.py @@ -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) diff --git a/src/coulobre/hosting/test_web_activation.py b/src/coulobre/hosting/test_web_activation.py index 1e053dc..789647c 100644 --- a/src/coulobre/hosting/test_web_activation.py +++ b/src/coulobre/hosting/test_web_activation.py @@ -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() diff --git a/src/coulobre/hosting/test_web_node_manifest.py b/src/coulobre/hosting/test_web_node_manifest.py index 1471c63..2f49af2 100644 --- a/src/coulobre/hosting/test_web_node_manifest.py +++ b/src/coulobre/hosting/test_web_node_manifest.py @@ -6,7 +6,8 @@ from unittest.mock import patch from django.test import SimpleTestCase -from coulobre.web_node import MAX_REQUEST_BYTES, WebSite, main +from coulobre.node_requests import MAX_REQUEST_BYTES +from coulobre.web_node import WebSite, main class WebSiteManifestTests(SimpleTestCase): diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index 98c32d1..af31eef 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -36,6 +36,11 @@ urlpatterns = [ views.DownloadDatabaseManifest.as_view(), name="database_manifest", ), + path( + "databases//provision/", + views.RequestDatabaseProvisioning.as_view(), + name="database_provision", + ), path( "accounts//dns-zones/new/", views.DnsZoneCreate.as_view(), diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index ac4ea49..5681723 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -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) diff --git a/src/coulobre/node_requests.py b/src/coulobre/node_requests.py new file mode 100644 index 0000000..7055796 --- /dev/null +++ b/src/coulobre/node_requests.py @@ -0,0 +1,24 @@ +import json +import sys + +MAX_REQUEST_BYTES = 4096 + + +def serve_apply_request(manifest_version, parse_manifest, apply): + 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 + spec = parse_manifest(payload) + report = spec.manifest() + apply(spec) + 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 diff --git a/src/coulobre/settings.py b/src/coulobre/settings.py index ed19104..3538c88 100644 --- a/src/coulobre/settings.py +++ b/src/coulobre/settings.py @@ -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}, + } diff --git a/src/coulobre/web_node.py b/src/coulobre/web_node.py index 64576f4..7a5ece2 100644 --- a/src/coulobre/web_node.py +++ b/src/coulobre/web_node.py @@ -8,9 +8,9 @@ from string import Template from .directadmin import DOCUMENT_ROOTS from .domain_names import canonical_domain +from .node_requests import serve_apply_request MANIFEST_VERSION = 1 -MAX_REQUEST_BYTES = 4096 CONFIGURATIONS = {"apache": "apache-vhost.conf", "php-fpm": "php-fpm-pool.conf"} @@ -67,28 +67,6 @@ 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) @@ -117,7 +95,9 @@ def main(argv=None): args = parser.parse_args(argv) if args.command == "apply-request": - return apply_request() + from .web_node_apply import apply_site + + return serve_apply_request(MANIFEST_VERSION, WebSite.from_manifest, apply_site) try: payload = json.loads(args.manifest.read_text(encoding="utf-8"))