Show measured website storage on hosting accounts

This commit is contained in:
parkel committed 2026-11-21 13:40:50 +01:00
1 parent 9be1fa17b7
commit eeea33013f
11 files changed
+419 -1

No files matched your search

@@ -0,0 +1,61 @@
# Generated by Django 5.2.19 on 2026-11-21 12:37
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", "0022_mailbox_quota_updates"),
]
operations = [
migrations.CreateModel(
name="SiteStorageUsage",
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),
),
(
"used_bytes",
models.PositiveBigIntegerField(blank=True, null=True),
),
("measured_at", models.DateTimeField(blank=True, null=True)),
(
"account",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
related_name="storage_usage",
to="hosting.hostingaccount",
),
),
],
options={
"abstract": False,
},
),
]
+9
View File
@@ -377,6 +377,15 @@ class WebActivation(ProvisioningJob):
)
class SiteStorageUsage(ProvisioningJob):
account = models.OneToOneField(
HostingAccount, on_delete=models.CASCADE, related_name="storage_usage"
)
domain = DomainNameField(max_length=253)
used_bytes = models.PositiveBigIntegerField(null=True, blank=True)
measured_at = models.DateTimeField(null=True, blank=True)
class WebHTTPS(ProvisioningJob):
plan = models.OneToOneField(
WebProvisioningPlan, on_delete=models.CASCADE, related_name="https"
+17 -1
View File
@@ -6,6 +6,7 @@ from coulobre.account_backup_request import (
BACKUP_TIMEOUT_SECONDS,
)
from coulobre.mail_node import MailboxQuotaUpdate
from coulobre.web_node import MAX_STORAGE_BYTES, WebStorageRequest
RESPONSE_LIMIT = 32768
@@ -16,6 +17,21 @@ def activate_local_site(site):
)
def measure_local_site_storage(site):
reply = apply_on_local_node(
WebStorageRequest(site),
"/run/coulobre-web-apply.sock",
"web node",
"website storage measurement",
)
used_bytes = reply.get("used_bytes")
if type(used_bytes) is not int or not 0 <= used_bytes <= MAX_STORAGE_BYTES:
raise ValueError(
"The web node returned an invalid storage measurement."
)
return used_bytes
def enable_local_https(site):
apply_on_local_node(
site, "/run/coulobre-https-apply.sock", "web node", "HTTPS request"
@@ -110,7 +126,7 @@ def apply_on_local_node(
raise ValueError(invalid_response) from None
if matches:
if state == "configured" and problem is None:
return
return reply
if state == "failed" and isinstance(problem, str) and problem.strip():
raise ValueError(problem.strip()[:2000])
raise ValueError(invalid_response)
+16
View File
@@ -9,6 +9,7 @@ from .models import (
HostingMailbox,
HostingMailDomain,
MailboxProvisioning,
SiteStorageUsage,
)
@@ -82,6 +83,21 @@ def queue_mailbox_provisioning(mailbox):
MailboxProvisioning.objects.queue(mailbox=mailbox)
@transaction.atomic
def queue_site_storage_measurement(account_id):
account = lock_hosting_account(account_id, customer_id=None)
job, created = SiteStorageUsage.objects.get_or_create(
account=account, defaults={"domain": account.primary_domain}
)
if not created:
updates = {"domain": account.primary_domain}
if job.domain != account.primary_domain:
updates.update(used_bytes=None, measured_at=None)
SiteStorageUsage.objects.requeue(
SiteStorageUsage.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)
+33
View File
@@ -20,6 +20,7 @@ from .models import (
DnsPublication,
MailboxProvisioning,
SiteSFTP,
SiteStorageUsage,
WebActivation,
WebHTTPS,
WebProvisioningPlan,
@@ -28,6 +29,7 @@ from .node_client import (
activate_local_site,
create_local_account_backup,
enable_local_https,
measure_local_site_storage,
provision_local_database,
provision_local_mailbox,
publish_local_zone,
@@ -90,6 +92,14 @@ def dispatch_web_activations():
)
@shared_task
def dispatch_site_storage_measurements():
if settings.LOCAL_WEB_ACTIVATION:
dispatch_provisioning_jobs(
SiteStorageUsage, measure_site_storage, WEB_ACTIVATION_QUEUE
)
@shared_task
def dispatch_web_https():
if settings.LOCAL_WEB_HTTPS:
@@ -181,6 +191,29 @@ def apply_web_activation(activation):
activate_local_site(WebSite(plan.account_id, plan.primary_domain))
@shared_task(acks_late=True, reject_on_worker_lost=True)
def measure_site_storage(request_id):
if settings.LOCAL_WEB_ACTIVATION:
run_provisioning_job(
SiteStorageUsage.objects.select_related("account"),
request_id,
apply_storage_measurement,
"Could not contact the local web node. "
"Check its socket and try again.",
)
def apply_storage_measurement(request):
if request.domain != request.account.primary_domain:
raise ValueError(
"Request a measurement for the current account domain."
)
used_bytes = measure_local_site_storage(
WebSite(request.account_id, request.domain)
)
return {"used_bytes": used_bytes, "measured_at": timezone.now()}
@shared_task(acks_late=True, reject_on_worker_lost=True)
def enable_web_https(request_id):
if settings.LOCAL_WEB_HTTPS:
@@ -37,6 +37,9 @@
{% endif %}
<div><dt>Added</dt><dd>{{ account.created_at|date:"j M Y, H:i" }} UTC</dd></div>
</dl>
{% if can_measure_site_storage or website_storage.measured_at %}
{% include "hosting/site_storage.html" %}
{% endif %}
{% if show_account_backups %}
{% include "hosting/account_backups.html" %}
{% endif %}
@@ -0,0 +1,27 @@
<section class="surface" aria-labelledby="storage-heading">
<header class="section-heading">
<div>
<h2 id="storage-heading">Website storage</h2>
{% if website_storage.measured_at %}
<p class="heading-meta">
{{ website_storage.used_bytes|filesizeformat }} used · Measured {{ website_storage.measured_at|date:"j M Y, H:i" }} UTC
</p>
{% elif not website_storage_pending %}
<p class="heading-meta">No storage measurement yet.</p>
{% endif %}
{% if can_measure_site_storage %}
{% if website_storage_pending %}
<p class="heading-meta">Measurement queued or running.</p>
{% elif website_storage.problem %}
<p class="heading-meta">{{ website_storage.problem }}</p>
{% endif %}
{% endif %}
</div>
{% if can_measure_site_storage and not website_storage_pending %}
<form method="post" action="{% url 'panel:measure_site_storage' account.pk %}">
{% csrf_token %}
<button class="button secondary" type="submit">Measure website storage</button>
</form>
{% endif %}
</header>
</section>
+212
View File
@@ -0,0 +1,212 @@
import json
from contextlib import nullcontext, redirect_stdout
from io import BytesIO, StringIO
from pathlib import Path
from subprocess import CompletedProcess
from types import SimpleNamespace
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.template.defaultfilters import filesizeformat
from django.test import SimpleTestCase, TestCase, override_settings
from django.urls import reverse
from coulobre import web_node_storage
from coulobre.web_node import WebSite, WebStorageRequest, main
from .models import Customer, HostingAccount, SiteStorageUsage
from .node_client import measure_local_site_storage
from .tasks import (
WEB_ACTIVATION_QUEUE,
dispatch_site_storage_measurements,
measure_site_storage,
)
@override_settings(LOCAL_WEB_ACTIVATION=True)
class SiteStorageTests(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", "add_sitestorageusage"),
)
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),
)
def setUp(self):
self.client.force_login(self.operator)
self.detail_url = self.account.get_absolute_url()
self.measure_url = reverse(
"panel:measure_site_storage", args=[self.account.pk]
)
def test_operator_queues_one_measurement_and_worker_records_usage(self):
self.assertContains(
self.client.get(self.detail_url), "Measure website storage"
)
for _ in range(2):
self.assertRedirects(
self.client.post(self.measure_url), self.detail_url
)
job = SiteStorageUsage.objects.get()
with patch.object(measure_site_storage, "apply_async") as dispatch:
dispatch_site_storage_measurements.run()
dispatch_site_storage_measurements.run()
dispatch.assert_called_once_with(
args=[job.pk],
queue=WEB_ACTIVATION_QUEUE,
retry=False,
)
with patch(
"coulobre.hosting.tasks.measure_local_site_storage",
return_value=8192,
) as measure:
measure_site_storage.run(job.pk)
measure_site_storage.run(job.pk)
measure.assert_called_once_with(
WebSite(self.account.pk, "site.example")
)
job.refresh_from_db()
self.assertEqual(job.state, "configured")
self.assertEqual(job.used_bytes, 8192)
self.assertIsNotNone(job.measured_at)
self.assertContains(
self.client.get(self.detail_url), filesizeformat(8192)
)
def test_failed_refresh_preserves_the_prior_sample_and_timestamp(self):
self.client.post(self.measure_url)
job = SiteStorageUsage.objects.get()
with patch(
"coulobre.hosting.tasks.measure_local_site_storage",
return_value=8192,
):
measure_site_storage.run(job.pk)
job.refresh_from_db()
previous = job.measured_at
self.client.post(self.measure_url)
with patch(
"coulobre.hosting.tasks.measure_local_site_storage",
side_effect=ValueError("Incomplete measurement"),
):
measure_site_storage.run(job.pk)
job.refresh_from_db()
self.assertEqual(job.state, "failed")
self.assertEqual(job.measured_at, previous)
self.assertEqual(job.used_bytes, 8192)
self.client.force_login(self.customer)
page = self.client.get(self.detail_url)
self.assertContains(page, filesizeformat(8192))
self.assertNotContains(page, "Incomplete measurement")
self.assertNotContains(page, "Measure website storage")
self.assertEqual(self.client.post(self.measure_url).status_code, 403)
other = HostingAccount.objects.create(
name="Another site", primary_domain="other.example"
)
self.assertEqual(
self.client.get(other.get_absolute_url()).status_code, 404
)
def test_a_queued_measurement_does_not_run_for_an_old_domain(self):
self.client.post(self.measure_url)
job = SiteStorageUsage.objects.get()
HostingAccount.objects.filter(pk=self.account.pk).update(
primary_domain="new.example"
)
with patch(
"coulobre.hosting.tasks.measure_local_site_storage"
) as measure:
measure_site_storage.run(job.pk)
measure.assert_not_called()
job.refresh_from_db()
self.assertEqual(job.state, "failed")
self.client.post(self.measure_url)
job.refresh_from_db()
self.assertEqual(job.state, "queued")
self.assertEqual(job.domain, "new.example")
@override_settings(LOCAL_WEB_ACTIVATION=False)
def test_measurement_requires_local_web_activation(self):
self.assertNotContains(
self.client.get(self.detail_url), "Website storage"
)
self.assertEqual(self.client.post(self.measure_url).status_code, 404)
self.assertFalse(SiteStorageUsage.objects.exists())
class WebStorageCommandTests(SimpleTestCase):
def test_measurement_uses_the_site_identity_and_physical_directory_walk(
self,
):
site = WebSite(42, "site.example")
public = Path("/srv/coulobre/web/42/public")
with (
patch.object(web_node_storage.os, "geteuid", return_value=0),
patch.object(
web_node_storage, "locked_web_node", return_value=nullcontext()
),
patch.object(
web_node_storage,
"site_storage",
return_value=(public, 1001, 33),
),
patch.object(web_node_storage.subprocess, "run") as run,
):
run.return_value = CompletedProcess([], 0, b"8192\t.\0")
self.assertEqual(
web_node_storage.measure_website_storage(site), 8192
)
command = run.call_args.args[0]
self.assertIn("--no-dereference", command)
self.assertIn("--one-file-system", command)
self.assertEqual(run.call_args.kwargs["cwd"], public)
self.assertEqual(run.call_args.kwargs["user"], "coulobre-42")
self.assertEqual(run.call_args.kwargs["group"], "coulobre-42")
def test_worker_reply_identifies_the_site_and_includes_its_size(self):
site = WebSite(42, "site.example")
request = WebStorageRequest(site).manifest()
stream = SimpleNamespace(buffer=BytesIO(json.dumps(request).encode()))
with (
patch("sys.stdin", stream),
redirect_stdout(StringIO()) as output,
patch.object(
web_node_storage, "measure_website_storage", return_value=8192
),
):
self.assertEqual(main(["apply-request"]), 0)
self.assertEqual(
json.loads(output.getvalue()),
request
| {"state": "configured", "problem": None, "used_bytes": 8192},
)
def test_client_rejects_missing_or_invalid_sizes(self):
for value in (None, True, -1, 2**63, "8192"):
with (
self.subTest(value=value),
patch(
"coulobre.hosting.node_client.apply_on_local_node",
return_value={"used_bytes": value},
),
self.assertRaisesMessage(
ValueError, "invalid storage measurement"
),
):
measure_local_site_storage(WebSite(42, "site.example"))
+5
View File
@@ -20,6 +20,11 @@ urlpatterns = [
"accounts/new/", views.AccountCreate.as_view(), name="account_create"
),
path("accounts/<int:pk>/", views.AccountDetail.as_view(), name="account"),
path(
"accounts/<int:pk>/measure-storage/",
views.RequestSiteStorageMeasurement.as_view(),
name="measure_site_storage",
),
path(
"accounts/<int:pk>/backup-manifest/",
views.DownloadAccountBackupManifest.as_view(),
+31
View File
@@ -65,6 +65,7 @@ from .resource_requests import (
create_database_request,
create_mailbox_request,
queue_mailbox_provisioning,
queue_site_storage_measurement,
)
from .sftp import (
SFTPKeyUploadForm,
@@ -83,6 +84,7 @@ VIEW_CUSTOMERS = "hosting.view_customer"
VIEW_DATABASES = "hosting.view_hostingdatabase"
VIEW_DNS_ZONES = "hosting.view_hostingdnszone"
VIEW_MAILBOXES = "hosting.view_hostingmailbox"
MEASURE_SITE_STORAGE = (VIEW_ACCOUNTS, "hosting.add_sitestorageusage")
EXPORT_BACKUP_MANIFEST = (VIEW_ACCOUNTS, VIEW_PLANS, VIEW_DATABASES)
EXPORT_MAIL_BACKUP_MANIFEST = (*EXPORT_BACKUP_MANIFEST, VIEW_MAILBOXES)
MANAGE_ACCOUNT_BACKUPS = (
@@ -241,6 +243,20 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
reseller = reseller_for_user(user)
customer = customer_for_user(user)
tenant = reseller is not None or customer is not None
storage = getattr(self.object, "storage_usage", None)
if (
storage is not None
and storage.domain == self.object.primary_domain
):
context["website_storage"] = storage
context["can_measure_site_storage"] = (
settings.LOCAL_WEB_ACTIVATION
and not tenant
and user.has_perms(MEASURE_SITE_STORAGE)
)
context["website_storage_pending"] = (
storage is not None and storage.finished_at is None
)
context["export_backup_manifest"] = not tenant and user.has_perms(
EXPORT_BACKUP_MANIFEST
)
@@ -323,6 +339,21 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
return context
class RequestSiteStorageMeasurement(
OperatorOnlyMixin, PermissionRequiredMixin, View
):
permission_required = MEASURE_SITE_STORAGE
def post(self, request, pk):
if not settings.LOCAL_WEB_ACTIVATION:
raise Http404
try:
queue_site_storage_measurement(pk)
except HostingAccount.DoesNotExist:
raise Http404 from None
return redirect("panel:account", pk=pk)
class DownloadAccountBackupManifest(
OperatorOnlyMixin, PermissionRequiredMixin, View
):
+5
View File
@@ -145,6 +145,11 @@ if LOCAL_WEB_ACTIVATION:
"schedule": 5.0,
"options": {"expires": 4.0},
}
CELERY_BEAT_SCHEDULE["dispatch-site-storage-measurements"] = {
"task": "coulobre.hosting.tasks.dispatch_site_storage_measurements",
"schedule": 5.0,
"options": {"expires": 4.0},
}
if LOCAL_WEB_HTTPS:
CELERY_BEAT_SCHEDULE["dispatch-web-https"] = {
"task": "coulobre.hosting.tasks.dispatch_web_https",