Measure website storage on hosting accounts #32

Merged
parkel merged 3 commits from feature/website-storage-usage into main 2026-11-21 13:57:30 +01:00
18 changed files with 565 additions and 24 deletions

No files matched your search

+4
View File
@@ -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. 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. 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 ## Enable HTTPS for hosted websites
Once a site is active, obtain the website certificate with Certbot on the Once a site is active, obtain the website certificate with Certbot on the
+24
View File
@@ -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 domain. A `failed` reply includes a diagnostic in `problem`. Retry the same
manifest if the connection closes before a reply arrives. 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 ## Install SFTP keys on a web node
Generate an Ed25519 key on the computer that will connect and choose a Generate an Ed25519 key on the computer that will connect and choose a
@@ -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): class WebHTTPS(ProvisioningJob):
plan = models.OneToOneField( plan = models.OneToOneField(
WebProvisioningPlan, on_delete=models.CASCADE, related_name="https" 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, BACKUP_TIMEOUT_SECONDS,
) )
from coulobre.mail_node import MailboxQuotaUpdate from coulobre.mail_node import MailboxQuotaUpdate
from coulobre.web_node import MAX_STORAGE_BYTES, WebStorageRequest
RESPONSE_LIMIT = 32768 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): def enable_local_https(site):
apply_on_local_node( apply_on_local_node(
site, "/run/coulobre-https-apply.sock", "web node", "HTTPS request" 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 raise ValueError(invalid_response) from None
if matches: if matches:
if state == "configured" and problem is None: if state == "configured" and problem is None:
return return reply
if state == "failed" and isinstance(problem, str) and problem.strip(): if state == "failed" and isinstance(problem, str) and problem.strip():
raise ValueError(problem.strip()[:2000]) raise ValueError(problem.strip()[:2000])
raise ValueError(invalid_response) raise ValueError(invalid_response)
+16
View File
@@ -9,6 +9,7 @@ from .models import (
HostingMailbox, HostingMailbox,
HostingMailDomain, HostingMailDomain,
MailboxProvisioning, MailboxProvisioning,
SiteStorageUsage,
) )
@@ -82,6 +83,21 @@ def queue_mailbox_provisioning(mailbox):
MailboxProvisioning.objects.queue(mailbox=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 @transaction.atomic
def change_mailbox_quota(mailbox, quota_mib): def change_mailbox_quota(mailbox, quota_mib):
lock_hosting_account(mailbox.mail_domain.account_id, customer_id=None) lock_hosting_account(mailbox.mail_domain.account_id, customer_id=None)
+33
View File
@@ -20,6 +20,7 @@ from .models import (
DnsPublication, DnsPublication,
MailboxProvisioning, MailboxProvisioning,
SiteSFTP, SiteSFTP,
SiteStorageUsage,
WebActivation, WebActivation,
WebHTTPS, WebHTTPS,
WebProvisioningPlan, WebProvisioningPlan,
@@ -28,6 +29,7 @@ from .node_client import (
activate_local_site, activate_local_site,
create_local_account_backup, create_local_account_backup,
enable_local_https, enable_local_https,
measure_local_site_storage,
provision_local_database, provision_local_database,
provision_local_mailbox, provision_local_mailbox,
publish_local_zone, 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 @shared_task
def dispatch_web_https(): def dispatch_web_https():
if settings.LOCAL_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)) 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) @shared_task(acks_late=True, reject_on_worker_lost=True)
def enable_web_https(request_id): def enable_web_https(request_id):
if settings.LOCAL_WEB_HTTPS: if settings.LOCAL_WEB_HTTPS:
@@ -37,6 +37,9 @@
{% endif %} {% endif %}
<div><dt>Added</dt><dd>{{ account.created_at|date:"j M Y, H:i" }} UTC</dd></div> <div><dt>Added</dt><dd>{{ account.created_at|date:"j M Y, H:i" }} UTC</dd></div>
</dl> </dl>
{% if can_measure_site_storage or website_storage.measured_at %}
{% include "hosting/site_storage.html" %}
{% endif %}
{% if show_account_backups %} {% if show_account_backups %}
{% include "hosting/account_backups.html" %} {% include "hosting/account_backups.html" %}
{% endif %} {% 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" "accounts/new/", views.AccountCreate.as_view(), name="account_create"
), ),
path("accounts/<int:pk>/", views.AccountDetail.as_view(), name="account"), 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( path(
"accounts/<int:pk>/backup-manifest/", "accounts/<int:pk>/backup-manifest/",
views.DownloadAccountBackupManifest.as_view(), views.DownloadAccountBackupManifest.as_view(),
+31
View File
@@ -65,6 +65,7 @@ from .resource_requests import (
create_database_request, create_database_request,
create_mailbox_request, create_mailbox_request,
queue_mailbox_provisioning, queue_mailbox_provisioning,
queue_site_storage_measurement,
) )
from .sftp import ( from .sftp import (
SFTPKeyUploadForm, SFTPKeyUploadForm,
@@ -83,6 +84,7 @@ VIEW_CUSTOMERS = "hosting.view_customer"
VIEW_DATABASES = "hosting.view_hostingdatabase" VIEW_DATABASES = "hosting.view_hostingdatabase"
VIEW_DNS_ZONES = "hosting.view_hostingdnszone" VIEW_DNS_ZONES = "hosting.view_hostingdnszone"
VIEW_MAILBOXES = "hosting.view_hostingmailbox" VIEW_MAILBOXES = "hosting.view_hostingmailbox"
MEASURE_SITE_STORAGE = (VIEW_ACCOUNTS, "hosting.add_sitestorageusage")
EXPORT_BACKUP_MANIFEST = (VIEW_ACCOUNTS, VIEW_PLANS, VIEW_DATABASES) EXPORT_BACKUP_MANIFEST = (VIEW_ACCOUNTS, VIEW_PLANS, VIEW_DATABASES)
EXPORT_MAIL_BACKUP_MANIFEST = (*EXPORT_BACKUP_MANIFEST, VIEW_MAILBOXES) EXPORT_MAIL_BACKUP_MANIFEST = (*EXPORT_BACKUP_MANIFEST, VIEW_MAILBOXES)
MANAGE_ACCOUNT_BACKUPS = ( MANAGE_ACCOUNT_BACKUPS = (
@@ -241,6 +243,20 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
reseller = reseller_for_user(user) reseller = reseller_for_user(user)
customer = customer_for_user(user) customer = customer_for_user(user)
tenant = reseller is not None or customer is not None 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( context["export_backup_manifest"] = not tenant and user.has_perms(
EXPORT_BACKUP_MANIFEST EXPORT_BACKUP_MANIFEST
) )
@@ -323,6 +339,21 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
return context 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( class DownloadAccountBackupManifest(
OperatorOnlyMixin, PermissionRequiredMixin, View OperatorOnlyMixin, PermissionRequiredMixin, View
): ):
+4 -1
View File
@@ -11,6 +11,7 @@ def serve_apply_request(
*, *,
limit=MAX_REQUEST_BYTES, limit=MAX_REQUEST_BYTES,
identity=None, identity=None,
include_result=False,
): ):
report = {"version": manifest_version} report = {"version": manifest_version}
try: try:
@@ -23,7 +24,9 @@ def serve_apply_request(
raise ValueError("Expected a UTF-8 JSON manifest.") from None raise ValueError("Expected a UTF-8 JSON manifest.") from None
spec = parse_manifest(payload) spec = parse_manifest(payload)
report = spec.manifest() if identity is None else identity(spec) 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: except (OSError, ValueError) as error:
print(json.dumps({**report, "state": "failed", "problem": str(error)})) print(json.dumps({**report, "state": "failed", "problem": str(error)}))
return 1 return 1
+5
View File
@@ -145,6 +145,11 @@ if LOCAL_WEB_ACTIVATION:
"schedule": 5.0, "schedule": 5.0,
"options": {"expires": 4.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: if LOCAL_WEB_HTTPS:
CELERY_BEAT_SCHEDULE["dispatch-web-https"] = { CELERY_BEAT_SCHEDULE["dispatch-web-https"] = {
"task": "coulobre.hosting.tasks.dispatch_web_https", "task": "coulobre.hosting.tasks.dispatch_web_https",
+46 -3
View File
@@ -11,6 +11,7 @@ from .domain_names import canonical_domain
from .node_requests import serve_apply_request from .node_requests import serve_apply_request
MANIFEST_VERSION = 1 MANIFEST_VERSION = 1
MAX_STORAGE_BYTES = 2**63 - 1
CONFIGURATIONS = { CONFIGURATIONS = {
"apache": "apache-vhost.conf", "apache": "apache-vhost.conf",
"php-fpm": "php-fpm-pool.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): def main(argv=None):
parser = argparse.ArgumentParser(prog="coulobre-web-node") parser = argparse.ArgumentParser(prog="coulobre-web-node")
commands = parser.add_subparsers(dest="command", required=True) 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", help="Check a site's local configuration and services."
) )
status.add_argument("manifest", type=Path) 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( https = commands.add_parser(
"enable-https", "enable-https",
help="Enable HTTPS with an existing Certbot certificate.", help="Enable HTTPS with an existing Certbot certificate.",
@@ -144,10 +179,11 @@ def main(argv=None):
parser.error("--replace requires --file.") parser.error("--replace requires --file.")
if args.command == "apply-request": if args.command == "apply-request":
from .web_node_apply import apply_site
return serve_apply_request( 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": if args.command == "https-request":
@@ -183,6 +219,13 @@ def main(argv=None):
report = site_status(site) report = site_status(site)
print(json.dumps(report, indent=2)) print(json.dumps(report, indent=2))
return 0 if report["state"] == "configured" else 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": elif args.command == "enable-https":
from .web_node_tls import enable_https from .web_node_tls import enable_https
+12 -1
View File
@@ -131,12 +131,23 @@ def check_reservation(site):
saved = json.loads(read_root_file(marker)) saved = json.loads(read_root_file(marker))
except FileNotFoundError: except FileNotFoundError:
raise ValueError( raise ValueError(
"Apply the site manifest before restoring website files." "Apply the site manifest before using its document root."
) from None ) from None
if saved != site.manifest(): if saved != site.manifest():
raise ValueError("The account is reserved with a different 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): def check_installation(site, paths):
for directory in ( for directory in (
paths.account, paths.account,
+1 -18
View File
@@ -10,13 +10,7 @@ from tempfile import NamedTemporaryFile, TemporaryDirectory
from .directadmin import backup_members, copy_member, member_path, open_backup from .directadmin import backup_members, copy_member, member_path, open_backup
from .node_files import check_root_file, require_root_directory from .node_files import check_root_file, require_root_directory
from .web_node_apply import ( from .web_node_apply import locked_web_node, site_storage
SitePaths,
check_public_directory,
check_reservation,
check_system_account,
locked_web_node,
)
from .web_node_restore import publish_empty_webroot from .web_node_restore import publish_empty_webroot
BACKUP_VERSION = 1 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): def write_metadata(archive, site):
metadata = { metadata = {
"version": BACKUP_VERSION, "version": BACKUP_VERSION,
+55
View File
@@ -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)