Merge pull request 'Enforce website storage quotas on ext4 web nodes' (#33) from feature/website-storage-quotas into main
Reviewed-on: #33
This commit was merged in pull request #33.
This commit is contained in:
commit
1844271bba
20 files changed
+759
-11
No files matched your search
@@ -216,6 +216,11 @@ 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)
|
||||
|
||||
To enforce hard limits, prepare a dedicated ext4 volume with user quotas for
|
||||
the managed sites. Use **Change storage limit** on the deployed account to
|
||||
apply the hosting plan's default or choose a per-site value.
|
||||
[Website storage quotas](development.md#apply-a-website-storage-limit)
|
||||
|
||||
## Enable HTTPS for hosted websites
|
||||
|
||||
Once a site is active, obtain the website certificate with Certbot on the
|
||||
|
||||
@@ -35,6 +35,10 @@ new mailbox requested under the plan. The account page shows each mailbox's
|
||||
assigned limit. Leave the field blank to omit a Coulobre storage limit.
|
||||
[Configure Dovecot quota enforcement](#enforce-mailbox-storage-limits)
|
||||
|
||||
Set **Website storage limit (MiB)** to supply the initial value when an
|
||||
operator applies a website quota from the account page.
|
||||
[Apply a website storage limit](#apply-a-website-storage-limit)
|
||||
|
||||
Changing or reassigning a plan preserves existing databases and mailboxes. If
|
||||
the new limit is at or below current usage, the panel blocks additional
|
||||
requests of that type. Changing the plan's storage limit applies to new
|
||||
@@ -914,6 +918,41 @@ 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.
|
||||
|
||||
### Apply a website storage limit
|
||||
|
||||
Mount a dedicated ext4 filesystem with user quotas at `/srv/coulobre/web`.
|
||||
For a new filesystem, the `mke2fs` options `-O quota -E quotatype=usrquota`
|
||||
create the user quota metadata. Use the `usrquota` mount option. The web node
|
||||
expects document roots on this volume without nested mounts. Check whether
|
||||
user quotas are active with
|
||||
`sudo quotaon -p -u /srv/coulobre/web`.
|
||||
[ext4 mount options](https://www.kernel.org/doc/html/v7.0/admin-guide/ext4.html)
|
||||
|
||||
On the local installation, open a deployed hosting account and select
|
||||
**Change storage limit** under **Website storage**. An operator with **Can
|
||||
change site storage limit** can apply the hosting plan's default or enter
|
||||
another value in MiB. Clear the field to remove the space limit. The page
|
||||
shows the last confirmed limit and any pending update.
|
||||
|
||||
On a separate web node, apply a limit using the deployed site manifest.
|
||||
|
||||
```sh
|
||||
sudo /opt/coulobre/bin/coulobre-web-node set-storage-limit \
|
||||
coulobre-web-plan-1.json --limit-mib 1024
|
||||
sudo /opt/coulobre/bin/coulobre-web-node storage-limit coulobre-web-plan-1.json
|
||||
```
|
||||
|
||||
Use `--unlimited` with `set-storage-limit` to remove the space limit. Linux
|
||||
enforces a hard quota on bytes charged to the site's system user anywhere
|
||||
on that filesystem. A lower limit can block new writes while existing
|
||||
files are retained. The CLI reports the enforced limit and charged usage.
|
||||
The panel's website measurement reports allocated space in the document root.
|
||||
[Linux quota API](https://man7.org/linux/man-pages/man2/quotactl.2.html)
|
||||
|
||||
The local web socket accepts the same update as JSON with
|
||||
`"operation": "set_storage_limit"`, the deployment manifest under `"site"`,
|
||||
and a positive integer or `null` under `"limit_mib"`.
|
||||
|
||||
## Install SFTP keys on a web node
|
||||
|
||||
Generate an Ed25519 key on the computer that will connect and choose a
|
||||
|
||||
@@ -52,6 +52,7 @@ class HostingPlanAdmin(admin.ModelAdmin):
|
||||
"database_limit",
|
||||
"mailbox_limit",
|
||||
"mailbox_quota_mib",
|
||||
"website_storage_limit_mib",
|
||||
)
|
||||
search_fields = ("name",)
|
||||
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
{% 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 %}
|
||||
{% 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 %}
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
<th scope="col">Database limit</th>
|
||||
<th scope="col">Mailbox limit</th>
|
||||
<th scope="col">Storage per new mailbox</th>
|
||||
<th scope="col">Default website limit</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -34,6 +35,7 @@
|
||||
<td>{{ hosting_plan.database_limit|default_if_none:"Unlimited" }}</td>
|
||||
<td>{{ hosting_plan.mailbox_limit|default_if_none:"Unlimited" }}</td>
|
||||
<td>{% if hosting_plan.mailbox_quota_mib is not None %}{{ hosting_plan.mailbox_quota_mib }} MiB{% else %}Unlimited{% endif %}</td>
|
||||
<td>{% if hosting_plan.website_storage_limit_mib is not None %}{{ hosting_plan.website_storage_limit_mib }} MiB{% else %}Unlimited{% endif %}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<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 %}
|
||||
{% elif can_measure_site_storage and not website_storage_pending %}
|
||||
<p class="heading-meta">No storage measurement yet.</p>
|
||||
{% endif %}
|
||||
{% if can_measure_site_storage %}
|
||||
@@ -16,12 +16,29 @@
|
||||
<p class="heading-meta">{{ website_storage.problem }}</p>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
{% if website_limit.applied_at %}
|
||||
<p class="heading-meta">
|
||||
Last applied limit {% if website_limit.applied_mib is not None %}{{ website_limit.applied_mib }} MiB{% else %}Unlimited{% endif %}
|
||||
</p>
|
||||
{% endif %}
|
||||
{% if can_change_site_storage_limit %}
|
||||
{% if website_limit_pending %}
|
||||
<p class="heading-meta">Storage limit update queued or running.</p>
|
||||
{% elif website_limit.problem %}
|
||||
<p class="heading-meta">{{ website_limit.problem }}</p>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="form-actions">
|
||||
{% 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 %}
|
||||
{% if can_change_site_storage_limit and not website_limit_pending %}
|
||||
<a class="button secondary" href="{% url 'panel:site_storage_limit' account.pk %}">Change storage limit</a>
|
||||
{% 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>
|
||||
@@ -0,0 +1,21 @@
|
||||
{% extends "hosting/base.html" %}
|
||||
{% block title %}Change website storage limit · Coulobre Panel{% endblock %}
|
||||
{% block content %}
|
||||
<a class="back-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
|
||||
<header class="page-heading">
|
||||
<div>
|
||||
<h1>Change website storage limit</h1>
|
||||
<p class="heading-meta domain">{{ account.primary_domain }}</p>
|
||||
</div>
|
||||
</header>
|
||||
<section class="surface editor-surface">
|
||||
<form method="post" class="editor">
|
||||
{% csrf_token %}
|
||||
{{ form.as_div }}
|
||||
<div class="form-actions">
|
||||
<button class="button primary" type="submit">Apply storage limit</button>
|
||||
<a class="button secondary" href="{{ account.get_absolute_url }}">Cancel</a>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -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(
|
||||
|
||||
@@ -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})
|
||||
@@ -25,6 +25,11 @@ urlpatterns = [
|
||||
views.RequestSiteStorageMeasurement.as_view(),
|
||||
name="measure_site_storage",
|
||||
),
|
||||
path(
|
||||
"accounts/<int:pk>/storage-limit/",
|
||||
views.SiteStorageLimitEdit.as_view(),
|
||||
name="site_storage_limit",
|
||||
),
|
||||
path(
|
||||
"accounts/<int:pk>/backup-manifest/",
|
||||
views.DownloadAccountBackupManifest.as_view(),
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -12,6 +12,7 @@ from .node_requests import serve_apply_request
|
||||
|
||||
MANIFEST_VERSION = 1
|
||||
MAX_STORAGE_BYTES = 2**63 - 1
|
||||
MAX_STORAGE_LIMIT_MIB = 2**31 - 1
|
||||
CONFIGURATIONS = {
|
||||
"apache": "apache-vhost.conf",
|
||||
"php-fpm": "php-fpm-pool.conf",
|
||||
@@ -84,6 +85,29 @@ class WebStorageRequest:
|
||||
return {"operation": "measure_storage", "site": self.site.manifest()}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WebQuotaRequest:
|
||||
site: WebSite
|
||||
limit_mib: int | None
|
||||
|
||||
def __post_init__(self):
|
||||
if self.limit_mib is not None and (
|
||||
type(self.limit_mib) is not int
|
||||
or not 1 <= self.limit_mib <= MAX_STORAGE_LIMIT_MIB
|
||||
):
|
||||
raise ValueError(
|
||||
f"Use a website storage limit between 1 and "
|
||||
f"{MAX_STORAGE_LIMIT_MIB} MiB."
|
||||
)
|
||||
|
||||
def manifest(self):
|
||||
return {
|
||||
"operation": "set_storage_limit",
|
||||
"site": self.site.manifest(),
|
||||
"limit_mib": self.limit_mib,
|
||||
}
|
||||
|
||||
|
||||
def parse_web_request(data):
|
||||
if (
|
||||
isinstance(data, dict)
|
||||
@@ -91,6 +115,14 @@ def parse_web_request(data):
|
||||
and data["operation"] == "measure_storage"
|
||||
):
|
||||
return WebStorageRequest(WebSite.from_manifest(data["site"]))
|
||||
if (
|
||||
isinstance(data, dict)
|
||||
and data.keys() == {"operation", "site", "limit_mib"}
|
||||
and data["operation"] == "set_storage_limit"
|
||||
):
|
||||
return WebQuotaRequest(
|
||||
WebSite.from_manifest(data["site"]), data["limit_mib"]
|
||||
)
|
||||
return WebSite.from_manifest(data)
|
||||
|
||||
|
||||
@@ -100,6 +132,12 @@ def apply_web_request(request):
|
||||
|
||||
return {"used_bytes": measure_website_storage(request.site)}
|
||||
|
||||
if isinstance(request, WebQuotaRequest):
|
||||
from .web_node_quota import apply_website_limit
|
||||
|
||||
apply_website_limit(request)
|
||||
return None
|
||||
|
||||
from .web_node_apply import apply_site
|
||||
|
||||
apply_site(request)
|
||||
@@ -130,6 +168,22 @@ def main(argv=None):
|
||||
"storage-usage", help="Measure the allocated space in a document root."
|
||||
)
|
||||
usage.add_argument("manifest", type=Path)
|
||||
quota = commands.add_parser(
|
||||
"storage-limit", help="Inspect the website user's filesystem quota."
|
||||
)
|
||||
quota.add_argument("manifest", type=Path)
|
||||
set_quota = commands.add_parser(
|
||||
"set-storage-limit", help="Apply a hard storage limit to a website."
|
||||
)
|
||||
set_quota.add_argument("manifest", type=Path)
|
||||
limit = set_quota.add_mutually_exclusive_group(required=True)
|
||||
limit.add_argument("--limit-mib", type=int)
|
||||
limit.add_argument(
|
||||
"--unlimited",
|
||||
dest="limit_mib",
|
||||
action="store_const",
|
||||
const=None,
|
||||
)
|
||||
https = commands.add_parser(
|
||||
"enable-https",
|
||||
help="Enable HTTPS with an existing Certbot certificate.",
|
||||
@@ -226,6 +280,16 @@ def main(argv=None):
|
||||
"used_bytes": measure_website_storage(site)
|
||||
}
|
||||
print(json.dumps(report, indent=2))
|
||||
elif args.command == "storage-limit":
|
||||
from .web_node_quota import website_limit_status
|
||||
|
||||
print(json.dumps(website_limit_status(site), indent=2))
|
||||
elif args.command == "set-storage-limit":
|
||||
from .web_node_quota import apply_website_limit
|
||||
|
||||
request = WebQuotaRequest(site, args.limit_mib)
|
||||
report = apply_website_limit(request)
|
||||
print(json.dumps(report, indent=2))
|
||||
elif args.command == "enable-https":
|
||||
from .web_node_tls import enable_https
|
||||
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
import ctypes
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
from . import web_node_apply as web
|
||||
|
||||
# Linux sys/quota.h user quota commands and the block-limits field mask.
|
||||
GET_QUOTA = 0x800007 << 8
|
||||
SET_QUOTA = 0x800008 << 8
|
||||
BLOCK_LIMITS = 1
|
||||
QUOTA_BLOCK_BYTES = 1024
|
||||
|
||||
|
||||
class UserQuota(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("block_hard_limit", ctypes.c_uint64),
|
||||
("block_soft_limit", ctypes.c_uint64),
|
||||
("used_bytes", ctypes.c_uint64),
|
||||
("inode_hard_limit", ctypes.c_uint64),
|
||||
("inode_soft_limit", ctypes.c_uint64),
|
||||
("used_inodes", ctypes.c_uint64),
|
||||
("block_expiry", ctypes.c_uint64),
|
||||
("inode_expiry", ctypes.c_uint64),
|
||||
("valid", ctypes.c_uint32),
|
||||
]
|
||||
|
||||
|
||||
def website_limit_status(site):
|
||||
if os.geteuid() != 0:
|
||||
raise ValueError("Run storage-limit as root on the web node.")
|
||||
with web.locked_web_node(fcntl.LOCK_SH):
|
||||
public, uid, _ = web.site_storage(site)
|
||||
quota = read_user_quota(quota_device(public), uid)
|
||||
return quota_report(site, quota)
|
||||
|
||||
|
||||
def apply_website_limit(request):
|
||||
if os.geteuid() != 0:
|
||||
raise ValueError("Run set-storage-limit as root on the web node.")
|
||||
site = request.site
|
||||
hard_limit = (request.limit_mib or 0) * 1024
|
||||
with web.locked_web_node(fcntl.LOCK_EX):
|
||||
public, uid, _ = web.site_storage(site)
|
||||
device = quota_device(public)
|
||||
quota = read_user_quota(device, uid)
|
||||
if quota.block_hard_limit != hard_limit or quota.block_soft_limit:
|
||||
new_limits = UserQuota(
|
||||
block_hard_limit=hard_limit, valid=BLOCK_LIMITS
|
||||
)
|
||||
quota_control(SET_QUOTA, device, uid, new_limits)
|
||||
quota = read_user_quota(device, uid)
|
||||
if quota.block_hard_limit != hard_limit or quota.block_soft_limit:
|
||||
raise ValueError(
|
||||
"Linux did not apply the requested website storage limit."
|
||||
)
|
||||
return quota_report(site, quota)
|
||||
|
||||
|
||||
def quota_report(site, quota):
|
||||
return site.manifest() | {
|
||||
"limit_bytes": (quota.block_hard_limit * QUOTA_BLOCK_BYTES) or None,
|
||||
"used_bytes": quota.used_bytes,
|
||||
}
|
||||
|
||||
|
||||
def quota_device(public):
|
||||
root = web.WEB_ROOT
|
||||
problem = f"Mount a dedicated ext4 volume with usrquota at {root}."
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[
|
||||
"/usr/bin/findmnt",
|
||||
"--json",
|
||||
"--submounts",
|
||||
"--mountpoint",
|
||||
str(root),
|
||||
"--output",
|
||||
"TARGET,SOURCE,FSTYPE,FSROOT,FS-OPTIONS",
|
||||
],
|
||||
capture_output=True,
|
||||
check=True,
|
||||
text=True,
|
||||
env={"PATH": "/usr/bin:/bin", "LC_ALL": "C"},
|
||||
timeout=5,
|
||||
)
|
||||
(volume,) = json.loads(result.stdout)["filesystems"]
|
||||
if (
|
||||
volume["target"] != str(root)
|
||||
or volume["fstype"] != "ext4"
|
||||
or volume["fsroot"] != "/"
|
||||
or "usrquota" not in volume["fs-options"].split(",")
|
||||
):
|
||||
raise ValueError
|
||||
device = Path(volume["source"])
|
||||
if not device.is_absolute():
|
||||
raise ValueError
|
||||
info = device.stat()
|
||||
if (
|
||||
not stat.S_ISBLK(info.st_mode)
|
||||
or info.st_rdev != public.stat().st_dev
|
||||
or info.st_rdev == root.parent.stat().st_dev
|
||||
):
|
||||
raise ValueError
|
||||
except (
|
||||
KeyError,
|
||||
OSError,
|
||||
TypeError,
|
||||
ValueError,
|
||||
subprocess.SubprocessError,
|
||||
):
|
||||
raise ValueError(problem) from None
|
||||
|
||||
for child in volume.get("children", ()):
|
||||
target = Path(child["target"])
|
||||
if target.is_relative_to(public) or public.is_relative_to(target):
|
||||
raise ValueError(
|
||||
"Remove nested mounts from this document root "
|
||||
"before applying a quota."
|
||||
)
|
||||
return device
|
||||
|
||||
|
||||
def read_user_quota(device, uid):
|
||||
quota = UserQuota()
|
||||
quota_control(GET_QUOTA, device, uid, quota)
|
||||
if not quota.valid & BLOCK_LIMITS:
|
||||
raise ValueError(
|
||||
"Linux did not report the website user's quota limits."
|
||||
)
|
||||
return quota
|
||||
|
||||
|
||||
def quota_control(command, device, uid, quota):
|
||||
quotactl = ctypes.CDLL(None, use_errno=True).quotactl
|
||||
quotactl.argtypes = (
|
||||
ctypes.c_int,
|
||||
ctypes.c_char_p,
|
||||
ctypes.c_uint,
|
||||
ctypes.POINTER(UserQuota),
|
||||
)
|
||||
quotactl.restype = ctypes.c_int
|
||||
if quotactl(command, os.fsencode(device), uid, ctypes.byref(quota)) != 0:
|
||||
reason = os.strerror(ctypes.get_errno())
|
||||
raise ValueError(
|
||||
f"Linux could not access the website user's quota. {reason}."
|
||||
)
|
||||
Reference in new issue
Block a user