diff --git a/docs/deployment.md b/docs/deployment.md
index 4ef32aa..990ea85 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -212,6 +212,10 @@ 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.
+The same worker measures allocated space in a website's document root. Use
+**Measure website storage** on a deployed hosting account and reload the page
+to see the latest result. [Website storage measurement](development.md#measure-website-storage)
+
## Enable HTTPS for hosted websites
Once a site is active, obtain the website certificate with Certbot on the
diff --git a/docs/development.md b/docs/development.md
index fe5a49e..f8e5d35 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -890,6 +890,30 @@ read the JSON reply to EOF. A `configured` reply includes the account ID and
domain. A `failed` reply includes a diagnostic in `problem`. Retry the same
manifest if the connection closes before a reply arrives.
+The socket also accepts a storage request with
+`"operation": "measure_storage"` and the deployment manifest under `"site"`.
+A successful reply includes the request identity and `used_bytes`.
+
+### Measure website storage
+
+Use the deployed site manifest to measure the document root on its web node.
+
+```sh
+sudo /opt/coulobre/bin/coulobre-web-node storage-usage coulobre-web-plan-1.json
+```
+
+The command reports allocated space in bytes as reported by GNU `du` for the
+site's document root. The scan runs as the site user, counts hard-linked
+files once, and skips other filesystems. Symbolic links contribute their
+own allocated space. The scan measures files as it encounters them, so
+the total may change on a busy site. [GNU du manual](https://www.gnu.org/software/coreutils/manual/html_node/du-invocation.html)
+
+With local web activation enabled, an operator with **Can add site storage
+usage** can select **Measure website storage** on the hosting account.
+Reload the page to see the result and timestamp. The account shows the most
+recent successful result even if a later attempt fails. Customers and
+resellers can see measurements on their assigned accounts.
+
## Install SFTP keys on a web node
Generate an Ed25519 key on the computer that will connect and choose a
diff --git a/src/coulobre/hosting/migrations/0023_site_storage_usage.py b/src/coulobre/hosting/migrations/0023_site_storage_usage.py
new file mode 100644
index 0000000..c9bc866
--- /dev/null
+++ b/src/coulobre/hosting/migrations/0023_site_storage_usage.py
@@ -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,
+ },
+ ),
+ ]
diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py
index 36a7dd6..37f26fb 100644
--- a/src/coulobre/hosting/models.py
+++ b/src/coulobre/hosting/models.py
@@ -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"
diff --git a/src/coulobre/hosting/node_client.py b/src/coulobre/hosting/node_client.py
index 5b3e933..bb57120 100644
--- a/src/coulobre/hosting/node_client.py
+++ b/src/coulobre/hosting/node_client.py
@@ -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)
diff --git a/src/coulobre/hosting/resource_requests.py b/src/coulobre/hosting/resource_requests.py
index b5cd920..ad1ed9d 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,
+ 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)
diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py
index 9035b98..4c76a60 100644
--- a/src/coulobre/hosting/tasks.py
+++ b/src/coulobre/hosting/tasks.py
@@ -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:
diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html
index c846bb3..3f219ac 100644
--- a/src/coulobre/hosting/templates/hosting/account_detail.html
+++ b/src/coulobre/hosting/templates/hosting/account_detail.html
@@ -37,6 +37,9 @@
{% endif %}
Added{{ account.created_at|date:"j M Y, H:i" }} UTC
+ {% 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 %}
diff --git a/src/coulobre/hosting/templates/hosting/site_storage.html b/src/coulobre/hosting/templates/hosting/site_storage.html
new file mode 100644
index 0000000..eb0ed10
--- /dev/null
+++ b/src/coulobre/hosting/templates/hosting/site_storage.html
@@ -0,0 +1,27 @@
+
+
+
+
Website storage
+ {% if website_storage.measured_at %}
+
+ {{ website_storage.used_bytes|filesizeformat }} used ยท Measured {{ website_storage.measured_at|date:"j M Y, H:i" }} UTC
+
+ {% elif not website_storage_pending %}
+
No storage measurement yet.
+ {% endif %}
+ {% if can_measure_site_storage %}
+ {% if website_storage_pending %}
+
Measurement queued or running.
+ {% elif website_storage.problem %}
+
{{ website_storage.problem }}
+ {% endif %}
+ {% endif %}
+
+ {% if can_measure_site_storage and not website_storage_pending %}
+
+ {% endif %}
+
+
diff --git a/src/coulobre/hosting/test_site_storage.py b/src/coulobre/hosting/test_site_storage.py
new file mode 100644
index 0000000..c597376
--- /dev/null
+++ b/src/coulobre/hosting/test_site_storage.py
@@ -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"))
diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py
index fea27c2..040b970 100644
--- a/src/coulobre/hosting/urls.py
+++ b/src/coulobre/hosting/urls.py
@@ -20,6 +20,11 @@ urlpatterns = [
"accounts/new/", views.AccountCreate.as_view(), name="account_create"
),
path("accounts//", views.AccountDetail.as_view(), name="account"),
+ path(
+ "accounts//measure-storage/",
+ views.RequestSiteStorageMeasurement.as_view(),
+ name="measure_site_storage",
+ ),
path(
"accounts//backup-manifest/",
views.DownloadAccountBackupManifest.as_view(),
diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py
index db773c6..6a1a36e 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_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
):
diff --git a/src/coulobre/node_requests.py b/src/coulobre/node_requests.py
index 085da16..072bec8 100644
--- a/src/coulobre/node_requests.py
+++ b/src/coulobre/node_requests.py
@@ -11,6 +11,7 @@ def serve_apply_request(
*,
limit=MAX_REQUEST_BYTES,
identity=None,
+ include_result=False,
):
report = {"version": manifest_version}
try:
@@ -23,7 +24,9 @@ def serve_apply_request(
raise ValueError("Expected a UTF-8 JSON manifest.") from None
spec = parse_manifest(payload)
report = spec.manifest() if identity is None else identity(spec)
- apply(spec)
+ result = apply(spec)
+ if include_result and result is not None:
+ report.update(result)
except (OSError, ValueError) as error:
print(json.dumps({**report, "state": "failed", "problem": str(error)}))
return 1
diff --git a/src/coulobre/settings.py b/src/coulobre/settings.py
index b677560..c1876ab 100644
--- a/src/coulobre/settings.py
+++ b/src/coulobre/settings.py
@@ -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",
diff --git a/src/coulobre/web_node.py b/src/coulobre/web_node.py
index 78de9a0..719625e 100644
--- a/src/coulobre/web_node.py
+++ b/src/coulobre/web_node.py
@@ -11,6 +11,7 @@ from .domain_names import canonical_domain
from .node_requests import serve_apply_request
MANIFEST_VERSION = 1
+MAX_STORAGE_BYTES = 2**63 - 1
CONFIGURATIONS = {
"apache": "apache-vhost.conf",
"php-fpm": "php-fpm-pool.conf",
@@ -75,6 +76,36 @@ class WebSite:
)
+@dataclass(frozen=True)
+class WebStorageRequest:
+ site: WebSite
+
+ def manifest(self):
+ return {"operation": "measure_storage", "site": self.site.manifest()}
+
+
+def parse_web_request(data):
+ if (
+ isinstance(data, dict)
+ and data.keys() == {"operation", "site"}
+ and data["operation"] == "measure_storage"
+ ):
+ return WebStorageRequest(WebSite.from_manifest(data["site"]))
+ return WebSite.from_manifest(data)
+
+
+def apply_web_request(request):
+ if isinstance(request, WebStorageRequest):
+ from .web_node_storage import measure_website_storage
+
+ return {"used_bytes": measure_website_storage(request.site)}
+
+ from .web_node_apply import apply_site
+
+ apply_site(request)
+ return None
+
+
def main(argv=None):
parser = argparse.ArgumentParser(prog="coulobre-web-node")
commands = parser.add_subparsers(dest="command", required=True)
@@ -95,6 +126,10 @@ def main(argv=None):
"status", help="Check a site's local configuration and services."
)
status.add_argument("manifest", type=Path)
+ usage = commands.add_parser(
+ "storage-usage", help="Measure the allocated space in a document root."
+ )
+ usage.add_argument("manifest", type=Path)
https = commands.add_parser(
"enable-https",
help="Enable HTTPS with an existing Certbot certificate.",
@@ -144,10 +179,11 @@ def main(argv=None):
parser.error("--replace requires --file.")
if args.command == "apply-request":
- from .web_node_apply import apply_site
-
return serve_apply_request(
- MANIFEST_VERSION, WebSite.from_manifest, apply_site
+ MANIFEST_VERSION,
+ parse_web_request,
+ apply_web_request,
+ include_result=True,
)
if args.command == "https-request":
@@ -183,6 +219,13 @@ def main(argv=None):
report = site_status(site)
print(json.dumps(report, indent=2))
return 0 if report["state"] == "configured" else 2
+ elif args.command == "storage-usage":
+ from .web_node_storage import measure_website_storage
+
+ report = site.manifest() | {
+ "used_bytes": measure_website_storage(site)
+ }
+ print(json.dumps(report, indent=2))
elif args.command == "enable-https":
from .web_node_tls import enable_https
diff --git a/src/coulobre/web_node_apply.py b/src/coulobre/web_node_apply.py
index 3ad34c6..47eb507 100644
--- a/src/coulobre/web_node_apply.py
+++ b/src/coulobre/web_node_apply.py
@@ -131,12 +131,23 @@ def check_reservation(site):
saved = json.loads(read_root_file(marker))
except FileNotFoundError:
raise ValueError(
- "Apply the site manifest before restoring website files."
+ "Apply the site manifest before using its document root."
) from None
if saved != site.manifest():
raise ValueError("The account is reserved with a different manifest.")
+def site_storage(site):
+ check_reservation(site)
+ paths = SitePaths.for_site(site)
+ require_root_directory(paths.account)
+ user = site.configuration()["service_user"]
+ uid, gid = check_system_account(user, paths.account)
+ public = paths.account / "public"
+ check_public_directory(public, uid, gid)
+ return public, uid, gid
+
+
def check_installation(site, paths):
for directory in (
paths.account,
diff --git a/src/coulobre/web_node_backup.py b/src/coulobre/web_node_backup.py
index e72698e..19d35e3 100644
--- a/src/coulobre/web_node_backup.py
+++ b/src/coulobre/web_node_backup.py
@@ -10,13 +10,7 @@ from tempfile import NamedTemporaryFile, TemporaryDirectory
from .directadmin import backup_members, copy_member, member_path, open_backup
from .node_files import check_root_file, require_root_directory
-from .web_node_apply import (
- SitePaths,
- check_public_directory,
- check_reservation,
- check_system_account,
- locked_web_node,
-)
+from .web_node_apply import locked_web_node, site_storage
from .web_node_restore import publish_empty_webroot
BACKUP_VERSION = 1
@@ -83,17 +77,6 @@ def restore_native_website(site, backup, *, filename=None, replace=False):
}
-def site_storage(site):
- check_reservation(site)
- paths = SitePaths.for_site(site)
- require_root_directory(paths.account)
- user = site.configuration()["service_user"]
- uid, gid = check_system_account(user, paths.account)
- public = paths.account / "public"
- check_public_directory(public, uid, gid)
- return public, uid, gid
-
-
def write_metadata(archive, site):
metadata = {
"version": BACKUP_VERSION,
diff --git a/src/coulobre/web_node_storage.py b/src/coulobre/web_node_storage.py
new file mode 100644
index 0000000..5c796f7
--- /dev/null
+++ b/src/coulobre/web_node_storage.py
@@ -0,0 +1,55 @@
+import fcntl
+import os
+import subprocess
+
+from .web_node import MAX_STORAGE_BYTES
+from .web_node_apply import locked_web_node, site_storage
+
+
+def measure_website_storage(site):
+ if os.geteuid() != 0:
+ raise ValueError("Run storage-usage as root on the web node.")
+ with locked_web_node(fcntl.LOCK_SH):
+ public, _, _ = site_storage(site)
+ user = site.configuration()["service_user"]
+ try:
+ result = subprocess.run(
+ [
+ "/usr/bin/du",
+ "--summarize",
+ "--block-size=1",
+ "--one-file-system",
+ "--no-dereference",
+ "--null",
+ "--",
+ ".",
+ ],
+ cwd=public,
+ user=user,
+ group=user,
+ extra_groups=[],
+ env={"PATH": "/usr/bin:/bin", "LC_ALL": "C"},
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL,
+ timeout=60,
+ )
+ except subprocess.TimeoutExpired:
+ raise ValueError(
+ "Measuring the website's storage timed out."
+ ) from None
+ if result.returncode:
+ raise ValueError(
+ "Could not measure all files in the document root."
+ )
+ size, _, entry = result.stdout.partition(b"\t")
+ if (
+ entry != b".\0"
+ or not size.isdigit()
+ or len(size) > 19
+ or int(size) > MAX_STORAGE_BYTES
+ ):
+ raise ValueError(
+ "The disk usage command returned an invalid result."
+ )
+ return int(size)