From f557b9194a4eace14a56cc3a3c7f24a69a83de07 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sat, 21 Nov 2026 14:10:34 +0100 Subject: [PATCH] Apply website storage limits from hosting accounts --- src/coulobre/hosting/admin.py | 1 + .../migrations/0024_website_storage_limits.py | 74 +++++++ src/coulobre/hosting/models.py | 21 ++ src/coulobre/hosting/node_client.py | 15 +- src/coulobre/hosting/resource_requests.py | 25 +++ src/coulobre/hosting/tasks.py | 32 +++ .../templates/hosting/account_detail.html | 2 +- .../templates/hosting/hosting_plan_list.html | 2 + .../templates/hosting/site_storage.html | 31 ++- .../hosting/site_storage_limit_form.html | 21 ++ src/coulobre/hosting/test_hosting_plans.py | 8 + .../hosting/test_site_storage_limit.py | 188 ++++++++++++++++++ src/coulobre/hosting/urls.py | 5 + src/coulobre/hosting/views.py | 69 ++++++- src/coulobre/hosting/web_node.py | 13 +- src/coulobre/settings.py | 5 + 16 files changed, 501 insertions(+), 11 deletions(-) create mode 100644 src/coulobre/hosting/migrations/0024_website_storage_limits.py create mode 100644 src/coulobre/hosting/templates/hosting/site_storage_limit_form.html create mode 100644 src/coulobre/hosting/test_site_storage_limit.py diff --git a/src/coulobre/hosting/admin.py b/src/coulobre/hosting/admin.py index 95d7887..1fde694 100644 --- a/src/coulobre/hosting/admin.py +++ b/src/coulobre/hosting/admin.py @@ -52,6 +52,7 @@ class HostingPlanAdmin(admin.ModelAdmin): "database_limit", "mailbox_limit", "mailbox_quota_mib", + "website_storage_limit_mib", ) search_fields = ("name",) diff --git a/src/coulobre/hosting/migrations/0024_website_storage_limits.py b/src/coulobre/hosting/migrations/0024_website_storage_limits.py new file mode 100644 index 0000000..01dc0ad --- /dev/null +++ b/src/coulobre/hosting/migrations/0024_website_storage_limits.py @@ -0,0 +1,74 @@ +# Generated by Django 5.2.19 on 2026-11-21 13:05 + +import django.core.validators +import django.db.models.deletion +import django.utils.timezone +from django.db import migrations, models + +import coulobre.hosting.fields + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0023_site_storage_usage"), + ] + + operations = [ + migrations.AddField( + model_name="hostingplan", + name="website_storage_limit_mib", + field=models.PositiveIntegerField( + blank=True, + help_text="Default when applying a website storage limit.", + null=True, + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(2147483647), + ], + verbose_name="website storage limit (MiB)", + ), + ), + migrations.CreateModel( + name="SiteStorageLimit", + 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)), + ( + "domain", + coulobre.hosting.fields.DomainNameField(max_length=253), + ), + ("limit_mib", models.PositiveIntegerField(null=True)), + ("applied_mib", models.PositiveIntegerField(null=True)), + ("applied_at", models.DateTimeField(null=True)), + ( + "account", + models.OneToOneField( + on_delete=django.db.models.deletion.CASCADE, + related_name="storage_limit", + to="hosting.hostingaccount", + ), + ), + ], + options={ + "abstract": False, + }, + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index 37f26fb..7cbcafd 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -28,6 +28,7 @@ from coulobre.mail_node import ( MAX_MAILBOX_QUOTA_MIB, MailboxSpec, ) +from coulobre.web_node import MAX_STORAGE_LIMIT_MIB from .fields import DomainNameField @@ -148,6 +149,16 @@ class HostingPlan(models.Model): "Applies to new mailbox requests. Leave blank for unlimited." ), ) + website_storage_limit_mib = models.PositiveIntegerField( + "website storage limit (MiB)", + blank=True, + null=True, + validators=[ + MinValueValidator(1), + MaxValueValidator(MAX_STORAGE_LIMIT_MIB), + ], + help_text="Default when applying a website storage limit.", + ) class Meta: ordering = ("name", "pk") @@ -386,6 +397,16 @@ class SiteStorageUsage(ProvisioningJob): measured_at = models.DateTimeField(null=True, blank=True) +class SiteStorageLimit(ProvisioningJob): + account = models.OneToOneField( + HostingAccount, on_delete=models.CASCADE, related_name="storage_limit" + ) + domain = DomainNameField(max_length=253) + limit_mib = models.PositiveIntegerField(null=True) + applied_mib = models.PositiveIntegerField(null=True) + applied_at = models.DateTimeField(null=True) + + class WebHTTPS(ProvisioningJob): plan = models.OneToOneField( WebProvisioningPlan, on_delete=models.CASCADE, related_name="https" diff --git a/src/coulobre/hosting/node_client.py b/src/coulobre/hosting/node_client.py index bb57120..492e901 100644 --- a/src/coulobre/hosting/node_client.py +++ b/src/coulobre/hosting/node_client.py @@ -6,7 +6,11 @@ from coulobre.account_backup_request import ( BACKUP_TIMEOUT_SECONDS, ) from coulobre.mail_node import MailboxQuotaUpdate -from coulobre.web_node import MAX_STORAGE_BYTES, WebStorageRequest +from coulobre.web_node import ( + MAX_STORAGE_BYTES, + WebQuotaRequest, + WebStorageRequest, +) RESPONSE_LIMIT = 32768 @@ -32,6 +36,15 @@ def measure_local_site_storage(site): return used_bytes +def set_local_site_storage_limit(site, limit_mib): + apply_on_local_node( + WebQuotaRequest(site, limit_mib), + "/run/coulobre-web-apply.sock", + "web node", + "website storage limit", + ) + + def enable_local_https(site): apply_on_local_node( site, "/run/coulobre-https-apply.sock", "web node", "HTTPS request" diff --git a/src/coulobre/hosting/resource_requests.py b/src/coulobre/hosting/resource_requests.py index ad1ed9d..f520939 100644 --- a/src/coulobre/hosting/resource_requests.py +++ b/src/coulobre/hosting/resource_requests.py @@ -9,6 +9,7 @@ from .models import ( HostingMailbox, HostingMailDomain, MailboxProvisioning, + SiteStorageLimit, SiteStorageUsage, ) @@ -98,6 +99,30 @@ def queue_site_storage_measurement(account_id): ) +@transaction.atomic +def queue_site_storage_limit(account_id, limit_mib): + account = lock_hosting_account(account_id, customer_id=None) + job, created = SiteStorageLimit.objects.get_or_create( + account=account, + defaults={"domain": account.primary_domain, "limit_mib": limit_mib}, + ) + if created: + return + if job.finished_at is None: + if job.domain == account.primary_domain and job.limit_mib == limit_mib: + return + raise ValidationError( + "Wait for the current storage limit request to finish." + ) + + updates = {"domain": account.primary_domain, "limit_mib": limit_mib} + if job.domain != account.primary_domain: + updates.update(applied_mib=None, applied_at=None) + SiteStorageLimit.objects.requeue( + SiteStorageLimit.objects.filter(pk=job.pk), **updates + ) + + @transaction.atomic def change_mailbox_quota(mailbox, quota_mib): lock_hosting_account(mailbox.mail_domain.account_id, customer_id=None) diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py index 4c76a60..f3face5 100644 --- a/src/coulobre/hosting/tasks.py +++ b/src/coulobre/hosting/tasks.py @@ -20,6 +20,7 @@ from .models import ( DnsPublication, MailboxProvisioning, SiteSFTP, + SiteStorageLimit, SiteStorageUsage, WebActivation, WebHTTPS, @@ -33,6 +34,7 @@ from .node_client import ( provision_local_database, provision_local_mailbox, publish_local_zone, + set_local_site_storage_limit, update_local_mailbox_quota, update_local_sftp, ) @@ -100,6 +102,14 @@ def dispatch_site_storage_measurements(): ) +@shared_task +def dispatch_site_storage_limits(): + if settings.LOCAL_WEB_ACTIVATION: + dispatch_provisioning_jobs( + SiteStorageLimit, set_site_storage_limit, WEB_ACTIVATION_QUEUE + ) + + @shared_task def dispatch_web_https(): if settings.LOCAL_WEB_HTTPS: @@ -214,6 +224,28 @@ def apply_storage_measurement(request): return {"used_bytes": used_bytes, "measured_at": timezone.now()} +@shared_task(acks_late=True, reject_on_worker_lost=True) +def set_site_storage_limit(request_id): + if settings.LOCAL_WEB_ACTIVATION: + run_provisioning_job( + SiteStorageLimit.objects.select_related("account"), + request_id, + apply_site_storage_limit, + "Could not contact the local web node. " + "Check its socket and try again.", + ) + + +def apply_site_storage_limit(request): + if request.domain != request.account.primary_domain: + raise ValueError( + "Request a storage limit for the current account domain." + ) + site = WebSite(request.account_id, request.domain) + set_local_site_storage_limit(site, request.limit_mib) + return {"applied_mib": request.limit_mib, "applied_at": timezone.now()} + + @shared_task(acks_late=True, reject_on_worker_lost=True) def enable_web_https(request_id): if settings.LOCAL_WEB_HTTPS: diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index 3f219ac..ff52fe0 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -37,7 +37,7 @@ {% endif %}
Added
{{ account.created_at|date:"j M Y, H:i" }} UTC
- {% if can_measure_site_storage or website_storage.measured_at %} + {% if can_measure_site_storage or website_storage.measured_at or can_change_site_storage_limit or website_limit.applied_at %} {% include "hosting/site_storage.html" %} {% endif %} {% if show_account_backups %} diff --git a/src/coulobre/hosting/templates/hosting/hosting_plan_list.html b/src/coulobre/hosting/templates/hosting/hosting_plan_list.html index 080c886..6dfe293 100644 --- a/src/coulobre/hosting/templates/hosting/hosting_plan_list.html +++ b/src/coulobre/hosting/templates/hosting/hosting_plan_list.html @@ -18,6 +18,7 @@ Database limit Mailbox limit Storage per new mailbox + Default website limit @@ -34,6 +35,7 @@ {{ hosting_plan.database_limit|default_if_none:"Unlimited" }} {{ hosting_plan.mailbox_limit|default_if_none:"Unlimited" }} {% if hosting_plan.mailbox_quota_mib is not None %}{{ hosting_plan.mailbox_quota_mib }} MiB{% else %}Unlimited{% endif %} + {% if hosting_plan.website_storage_limit_mib is not None %}{{ hosting_plan.website_storage_limit_mib }} MiB{% else %}Unlimited{% endif %} {% endfor %} diff --git a/src/coulobre/hosting/templates/hosting/site_storage.html b/src/coulobre/hosting/templates/hosting/site_storage.html index eb0ed10..9559b21 100644 --- a/src/coulobre/hosting/templates/hosting/site_storage.html +++ b/src/coulobre/hosting/templates/hosting/site_storage.html @@ -6,7 +6,7 @@

{{ website_storage.used_bytes|filesizeformat }} used · Measured {{ website_storage.measured_at|date:"j M Y, H:i" }} UTC

- {% elif not website_storage_pending %} + {% elif can_measure_site_storage and not website_storage_pending %}

No storage measurement yet.

{% endif %} {% if can_measure_site_storage %} @@ -16,12 +16,29 @@

{{ website_storage.problem }}

{% endif %} {% endif %} + {% if website_limit.applied_at %} +

+ Last applied limit {% if website_limit.applied_mib is not None %}{{ website_limit.applied_mib }} MiB{% else %}Unlimited{% endif %} +

+ {% endif %} + {% if can_change_site_storage_limit %} + {% if website_limit_pending %} +

Storage limit update queued or running.

+ {% elif website_limit.problem %} +

{{ website_limit.problem }}

+ {% endif %} + {% endif %} + +
+ {% if can_measure_site_storage and not website_storage_pending %} +
+ {% csrf_token %} + +
+ {% endif %} + {% if can_change_site_storage_limit and not website_limit_pending %} + Change storage limit + {% endif %}
- {% if can_measure_site_storage and not website_storage_pending %} -
- {% csrf_token %} - -
- {% endif %} diff --git a/src/coulobre/hosting/templates/hosting/site_storage_limit_form.html b/src/coulobre/hosting/templates/hosting/site_storage_limit_form.html new file mode 100644 index 0000000..ab6136e --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/site_storage_limit_form.html @@ -0,0 +1,21 @@ +{% extends "hosting/base.html" %} +{% block title %}Change website storage limit · Coulobre Panel{% endblock %} +{% block content %} + ← {{ account.name }} +
+
+

Change website storage limit

+

{{ account.primary_domain }}

+
+
+
+
+ {% csrf_token %} + {{ form.as_div }} +
+ + Cancel +
+
+
+{% endblock %} diff --git a/src/coulobre/hosting/test_hosting_plans.py b/src/coulobre/hosting/test_hosting_plans.py index 72b0afe..846cdfb 100644 --- a/src/coulobre/hosting/test_hosting_plans.py +++ b/src/coulobre/hosting/test_hosting_plans.py @@ -36,6 +36,7 @@ class HostingPlanTests(TestCase): "database_limit": 0, "mailbox_limit": 5, "mailbox_quota_mib": 256, + "website_storage_limit_mib": 1024, }, ) self.assertRedirects(response, list_url) @@ -43,6 +44,7 @@ class HostingPlanTests(TestCase): self.assertEqual(plan.database_limit, 0) self.assertEqual(plan.mailbox_limit, 5) self.assertEqual(plan.mailbox_quota_mib, 256) + self.assertEqual(plan.website_storage_limit_mib, 1024) self.assertContains(self.client.get(list_url), "256 MiB") self.assertContains( @@ -68,6 +70,7 @@ class HostingPlanTests(TestCase): "database_limit": "", "mailbox_limit": 2, "mailbox_quota_mib": "", + "website_storage_limit_mib": "", }, ) self.assertRedirects(response, list_url) @@ -75,6 +78,7 @@ class HostingPlanTests(TestCase): self.assertIsNone(plan.database_limit) self.assertEqual(plan.mailbox_limit, 2) self.assertIsNone(plan.mailbox_quota_mib) + self.assertIsNone(plan.website_storage_limit_mib) self.assertContains(self.client.get(list_url), "Unlimited") self.assertContains( self.client.get(reverse("panel:accounts")), "Standard" @@ -101,11 +105,15 @@ class HostingPlanTests(TestCase): "database_limit": -1, "mailbox_limit": -2, "mailbox_quota_mib": 0, + "website_storage_limit_mib": 0, }, ) self.assertIn("database_limit", response.context["form"].errors) self.assertIn("mailbox_limit", response.context["form"].errors) self.assertIn("mailbox_quota_mib", response.context["form"].errors) + self.assertIn( + "website_storage_limit_mib", response.context["form"].errors + ) self.assertFalse(HostingPlan.objects.exists()) def test_editor_without_plan_permission_cannot_assign_in_either_interface( diff --git a/src/coulobre/hosting/test_site_storage_limit.py b/src/coulobre/hosting/test_site_storage_limit.py new file mode 100644 index 0000000..d5c0177 --- /dev/null +++ b/src/coulobre/hosting/test_site_storage_limit.py @@ -0,0 +1,188 @@ +import fcntl +import json +from contextlib import nullcontext +from pathlib import Path +from subprocess import CompletedProcess +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 import web_node_quota +from coulobre.web_node import WebQuotaRequest, WebSite, parse_web_request +from coulobre.web_node_quota import BLOCK_LIMITS, SET_QUOTA, UserQuota + +from .models import Customer, HostingAccount, HostingPlan, SiteStorageLimit +from .tasks import ( + WEB_ACTIVATION_QUEUE, + dispatch_site_storage_limits, + set_site_storage_limit, +) + + +@override_settings(LOCAL_WEB_ACTIVATION=True) +class SiteStorageLimitTests(TestCase): + @classmethod + def setUpTestData(cls): + users = get_user_model().objects + cls.operator = users.create_user("operator") + cls.customer = users.create_user("customer") + perms = Permission.objects.filter( + content_type__app_label="hosting", + codename__in=("view_hostingaccount", "change_sitestoragelimit"), + ) + for user in (cls.operator, cls.customer): + user.user_permissions.set(perms) + cls.account = HostingAccount.objects.create( + name="Site", + primary_domain="site.example", + customer=Customer.objects.create(user=cls.customer), + hosting_plan=HostingPlan.objects.create( + name="Starter", website_storage_limit_mib=512 + ), + ) + + def setUp(self): + self.site = WebSite(self.account.pk, self.account.primary_domain) + self.client.force_login(self.operator) + self.detail = self.account.get_absolute_url() + self.url = reverse("panel:site_storage_limit", args=[self.account.pk]) + + def test_plan_default_is_applied_by_the_worker_when_requested(self): + self.assertContains( + self.client.get(self.detail), "Change storage limit" + ) + response = self.client.get(self.url) + self.assertEqual(response.context["form"].initial["limit_mib"], 512) + for _ in range(2): + self.assertRedirects( + self.client.post(self.url, {"limit_mib": 512}), self.detail + ) + job = SiteStorageLimit.objects.get(account=self.account) + with patch.object(set_site_storage_limit, "apply_async") as send: + dispatch_site_storage_limits.run() + send.assert_called_once_with( + args=[job.pk], queue=WEB_ACTIVATION_QUEUE, retry=False + ) + with patch( + "coulobre.hosting.tasks.set_local_site_storage_limit" + ) as apply: + set_site_storage_limit.run(job.pk) + set_site_storage_limit.run(job.pk) + apply.assert_called_once_with(self.site, 512) + job.refresh_from_db() + self.assertEqual(job.applied_mib, 512) + self.assertIsNotNone(job.applied_at) + + self.client.force_login(self.customer) + self.assertContains( + self.client.get(self.detail), "Last applied limit 512 MiB" + ) + self.assertNotContains( + self.client.get(self.detail), "Change storage limit" + ) + self.assertEqual( + self.client.post(self.url, {"limit_mib": 16}).status_code, 403 + ) + + def test_in_flight_and_failed_changes_keep_the_previous_limit(self): + self.client.post(self.url, {"limit_mib": 512}) + queued = SiteStorageLimit.objects.get(account=self.account) + self.assertContains( + self.client.post(self.url, {"limit_mib": 1024}), + "Wait for the current storage limit request to finish.", + ) + with patch("coulobre.hosting.tasks.set_local_site_storage_limit"): + set_site_storage_limit.run(queued.pk) + queued.refresh_from_db() + last_applied = queued.applied_at + self.client.post(self.url, {"limit_mib": 1024}) + with patch( + "coulobre.hosting.tasks.set_local_site_storage_limit", + side_effect=ValueError("Quota volume unavailable"), + ): + set_site_storage_limit.run(queued.pk) + + queued.refresh_from_db() + self.assertEqual(queued.state, "failed") + self.assertEqual(queued.applied_at, last_applied) + self.assertEqual(queued.applied_mib, 512) + self.assertContains( + self.client.get(self.detail), "Quota volume unavailable" + ) + + def test_blank_limit_explicitly_requests_unlimited_storage(self): + self.assertRedirects( + self.client.post(self.url, {"limit_mib": ""}), self.detail + ) + job = SiteStorageLimit.objects.get(account=self.account) + with patch( + "coulobre.hosting.tasks.set_local_site_storage_limit" + ) as apply: + set_site_storage_limit.run(job.pk) + apply.assert_called_once_with(self.site, None) + self.assertContains( + self.client.get(self.detail), "Last applied limit Unlimited" + ) + + +class WebsiteQuotaCommandTests(SimpleTestCase): + def test_set_writes_only_block_limits_and_verifies_the_kernel_result(self): + request = WebQuotaRequest(WebSite(42, "site.example"), 512) + first = UserQuota(block_hard_limit=100, inode_hard_limit=33) + second = UserQuota(block_hard_limit=512 * 1024, inode_hard_limit=33) + device = Path("/dev/test-device") + with ( + patch.object(web_node_quota.os, "geteuid", return_value=0), + patch.object( + web_node_quota.web, + "locked_web_node", + return_value=nullcontext(), + ) as lock, + patch.object( + web_node_quota.web, + "site_storage", + return_value=(Path("/public"), 1001, 33), + ), + patch.object(web_node_quota, "quota_device", return_value=device), + patch.object( + web_node_quota, "read_user_quota", side_effect=[first, second] + ), + patch.object(web_node_quota, "quota_control") as control, + ): + report = web_node_quota.apply_website_limit(request) + + lock.assert_called_once_with(fcntl.LOCK_EX) + self.assertEqual(control.call_args.args[:3], (SET_QUOTA, device, 1001)) + settings = control.call_args.args[3] + self.assertEqual(settings.valid, BLOCK_LIMITS) + self.assertEqual(settings.block_hard_limit, 512 * 1024) + self.assertEqual(report["limit_bytes"], 512 * 1024**2) + + def test_quota_device_requires_an_ext4_user_quota_mount(self): + volume = { + "target": str(web_node_quota.web.WEB_ROOT), + "source": "/dev/test-device", + "fsroot": "/", + "fstype": "ext4", + "fs-options": "rw,quota", + } + result = CompletedProcess([], 0, json.dumps({"filesystems": [volume]})) + with ( + patch.object( + web_node_quota.subprocess, "run", return_value=result + ), + self.assertRaisesMessage( + ValueError, "dedicated ext4 volume with usrquota" + ), + ): + web_node_quota.quota_device(Path("/srv/coulobre/web/42/public")) + + def test_storage_limit_request_validates_size_and_site_identity(self): + request = WebQuotaRequest(WebSite(42, "site.example"), 512) + self.assertEqual(parse_web_request(request.manifest()), request) + for value in (0, -1, True, "512", 2**31): + with self.subTest(value=value), self.assertRaises(ValueError): + parse_web_request(request.manifest() | {"limit_mib": value}) diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index 040b970..65d1aee 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -25,6 +25,11 @@ urlpatterns = [ views.RequestSiteStorageMeasurement.as_view(), name="measure_site_storage", ), + path( + "accounts//storage-limit/", + views.SiteStorageLimitEdit.as_view(), + name="site_storage_limit", + ), path( "accounts//backup-manifest/", views.DownloadAccountBackupManifest.as_view(), diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index 6a1a36e..8594843 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -65,6 +65,7 @@ from .resource_requests import ( create_database_request, create_mailbox_request, queue_mailbox_provisioning, + queue_site_storage_limit, queue_site_storage_measurement, ) from .sftp import ( @@ -73,7 +74,11 @@ from .sftp import ( queue_sftp_keys, site_is_active, ) -from .web_node import build_web_smoke_bundle, serialize_deployment_manifest +from .web_node import ( + SiteStorageLimitForm, + build_web_smoke_bundle, + serialize_deployment_manifest, +) VIEW_ACCOUNTS = "hosting.view_hostingaccount" CHANGE_ACCOUNTS = "hosting.change_hostingaccount" @@ -85,6 +90,7 @@ VIEW_DATABASES = "hosting.view_hostingdatabase" VIEW_DNS_ZONES = "hosting.view_hostingdnszone" VIEW_MAILBOXES = "hosting.view_hostingmailbox" MEASURE_SITE_STORAGE = (VIEW_ACCOUNTS, "hosting.add_sitestorageusage") +CHANGE_SITE_STORAGE_LIMIT = (VIEW_ACCOUNTS, "hosting.change_sitestoragelimit") EXPORT_BACKUP_MANIFEST = (VIEW_ACCOUNTS, VIEW_PLANS, VIEW_DATABASES) EXPORT_MAIL_BACKUP_MANIFEST = (*EXPORT_BACKUP_MANIFEST, VIEW_MAILBOXES) MANAGE_ACCOUNT_BACKUPS = ( @@ -257,6 +263,17 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): context["website_storage_pending"] = ( storage is not None and storage.finished_at is None ) + quota = getattr(self.object, "storage_limit", None) + if quota is not None and quota.domain == self.object.primary_domain: + context["website_limit"] = quota + context["can_change_site_storage_limit"] = ( + settings.LOCAL_WEB_ACTIVATION + and not tenant + and user.has_perms(CHANGE_SITE_STORAGE_LIMIT) + ) + context["website_limit_pending"] = ( + quota is not None and quota.finished_at is None + ) context["export_backup_manifest"] = not tenant and user.has_perms( EXPORT_BACKUP_MANIFEST ) @@ -339,6 +356,55 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): return context +class SiteStorageLimitEdit( + OperatorOnlyMixin, PermissionRequiredMixin, FormView +): + permission_required = CHANGE_SITE_STORAGE_LIMIT + form_class = SiteStorageLimitForm + template_name = "hosting/site_storage_limit_form.html" + + def dispatch(self, request, *args, **kwargs): + if not settings.LOCAL_WEB_ACTIVATION: + raise Http404 + return super().dispatch(request, *args, **kwargs) + + @cached_property + def account(self): + return get_object_or_404( + HostingAccount.objects.select_related( + "hosting_plan", "storage_limit" + ), + pk=self.kwargs["pk"], + ) + + def get_initial(self): + initial = super().get_initial() + current = getattr(self.account, "storage_limit", None) + if ( + current is not None + and current.domain == self.account.primary_domain + ): + initial["limit_mib"] = current.limit_mib + elif self.account.hosting_plan is not None: + initial["limit_mib"] = ( + self.account.hosting_plan.website_storage_limit_mib + ) + return initial + + def get_context_data(self, **kwargs): + return super().get_context_data(account=self.account, **kwargs) + + def form_valid(self, form): + try: + queue_site_storage_limit( + self.account.pk, form.cleaned_data["limit_mib"] + ) + except ValidationError as error: + form.add_error(None, error) + return self.form_invalid(form) + return redirect(self.account) + + class RequestSiteStorageMeasurement( OperatorOnlyMixin, PermissionRequiredMixin, View ): @@ -895,6 +961,7 @@ class HostingPlanEditor: "database_limit", "mailbox_limit", "mailbox_quota_mib", + "website_storage_limit_mib", ) template_name = "hosting/hosting_plan_form.html" success_url = reverse_lazy("panel:hosting_plans") diff --git a/src/coulobre/hosting/web_node.py b/src/coulobre/hosting/web_node.py index 4fae3d9..f665e2d 100644 --- a/src/coulobre/hosting/web_node.py +++ b/src/coulobre/hosting/web_node.py @@ -2,9 +2,20 @@ import json import tarfile from io import BytesIO +from django import forms from django.template.loader import render_to_string -from coulobre.web_node import WebSite +from coulobre.web_node import MAX_STORAGE_LIMIT_MIB, WebSite + + +class SiteStorageLimitForm(forms.Form): + limit_mib = forms.IntegerField( + label="Storage limit (MiB)", + required=False, + min_value=1, + max_value=MAX_STORAGE_LIMIT_MIB, + help_text="Leave blank for unlimited storage.", + ) def serialize_deployment_manifest(plan): diff --git a/src/coulobre/settings.py b/src/coulobre/settings.py index c1876ab..75345d4 100644 --- a/src/coulobre/settings.py +++ b/src/coulobre/settings.py @@ -150,6 +150,11 @@ if LOCAL_WEB_ACTIVATION: "schedule": 5.0, "options": {"expires": 4.0}, } + CELERY_BEAT_SCHEDULE["dispatch-site-storage-limits"] = { + "task": "coulobre.hosting.tasks.dispatch_site_storage_limits", + "schedule": 5.0, + "options": {"expires": 4.0}, + } if LOCAL_WEB_HTTPS: CELERY_BEAT_SCHEDULE["dispatch-web-https"] = { "task": "coulobre.hosting.tasks.dispatch_web_https",