Manage PHP settings from hosting plans and account pages

This commit is contained in:
parkel committed 2026-11-21 16:04:33 +01:00
1 parent 08bcab7144
commit ac7e67b9fb
8 files changed
+445 -4

No files matched your search

@@ -40,6 +40,9 @@
{% 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 website_php_settings %}
{% include "hosting/site_php_settings.html" %}
{% endif %}
{% if website_aliases or can_add_website_alias %}
{% include "hosting/website_aliases.html" %}
{% endif %}
@@ -19,6 +19,7 @@
<th scope="col">Mailbox limit</th>
<th scope="col">Storage per new mailbox</th>
<th scope="col">Default website limit</th>
<th scope="col">PHP overrides</th>
</tr>
</thead>
<tbody>
@@ -36,6 +37,7 @@
<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>
<td>{% if hosting_plan.get_php_settings.has_overrides %}Configured{% else %}Server defaults{% endif %}</td>
</tr>
{% endfor %}
</tbody>
@@ -0,0 +1,6 @@
<dl class="details">
<div><dt>PHP memory limit</dt><dd>{% if limits.memory_limit_mib %}{{ limits.memory_limit_mib }} MiB{% else %}Server default{% endif %}</dd></div>
<div><dt>PHP upload limit</dt><dd>{% if limits.upload_limit_mib %}{{ limits.upload_limit_mib }} MiB{% else %}Server default{% endif %}</dd></div>
<div><dt>PHP request timeout</dt><dd>{% if limits.request_timeout_seconds %}{{ limits.request_timeout_seconds }} s{% else %}Server default{% endif %}</dd></div>
<div><dt>Maximum PHP-FPM workers</dt><dd>{{ limits.worker_limit }}</dd></div>
</dl>
@@ -0,0 +1,16 @@
<section class="surface" aria-labelledby="php-settings-heading">
<header class="section-heading">
<div>
<h2 id="php-settings-heading">PHP settings</h2>
{% if website_php_job.state == "queued" or website_php_job.state == "running" %}
<p class="heading-meta">PHP settings update {{ website_php_job.state }}.</p>
{% elif can_change_php_settings and website_php_job.problem %}
<p class="heading-meta">{{ website_php_job.problem }}</p>
{% endif %}
</div>
{% if can_change_php_settings and website_php_job.state != "queued" and website_php_job.state != "running" %}
<a class="button secondary" href="{% url 'panel:site_php_settings' account.pk %}">Change PHP settings</a>
{% endif %}
</header>
{% include "hosting/php_setting_values.html" with limits=website_php_settings only %}
</section>
@@ -0,0 +1,30 @@
{% extends "hosting/base.html" %}
{% block title %}Change PHP settings · Coulobre Panel{% endblock %}
{% block content %}
<a class="back-link" href="{{ account.get_absolute_url }}#php-settings-heading">← {{ account.name }}</a>
<header class="page-heading">
<div>
<h1>Change PHP settings</h1>
<p class="heading-meta domain">{{ account.primary_domain }}</p>
</div>
</header>
<section class="surface editor-surface">
<form method="post" class="editor">
<p>Blank fields use the web node defaults.</p>
{% csrf_token %}
{{ form.as_div }}
<div class="form-actions">
<button class="button primary" type="submit">Apply PHP settings</button>
<a class="button secondary" href="{{ account.get_absolute_url }}#php-settings-heading">Cancel</a>
</div>
</form>
</section>
{% if account.hosting_plan %}
<section class="surface" aria-labelledby="php-plan-settings-heading">
<header class="section-heading">
<h2 id="php-plan-settings-heading">PHP defaults for {{ account.hosting_plan }}</h2>
</header>
{% include "hosting/php_setting_values.html" with limits=plan_settings only %}
</section>
{% endif %}
{% endblock %}
+300
View File
@@ -0,0 +1,300 @@
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import call, 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 django.utils import timezone
from coulobre.php_pool_settings import PhpPoolSettings
from coulobre.web_node import WebPhpRequest, WebSite, parse_web_request
from coulobre.web_node_apply import (
PHP_SERVICE,
SitePaths,
install_configurations,
)
from coulobre.web_node_php import change_php_pool, read_managed_php_pool
from .models import (
HostingAccount,
HostingPlan,
SitePhpSettings,
WebActivation,
WebProvisioningPlan,
)
from .tasks import (
WEB_ACTIVATION_QUEUE,
activate_web_plan,
dispatch_web_activations,
set_site_php_settings,
)
@override_settings(LOCAL_WEB_ACTIVATION=True)
class PanelPhpSettingsTests(TestCase):
@classmethod
def setUpTestData(cls):
users = get_user_model().objects
cls.operator = users.create_superuser("operator")
cls.package = HostingPlan.objects.create(
name="Managed",
php_memory_limit_mib=256,
php_upload_limit_mib=24,
php_request_timeout_seconds=90,
php_max_children=3,
)
cls.account = HostingAccount.objects.create(
name="Site",
primary_domain="example.net",
hosting_plan=cls.package,
)
cls.site = WebSite(cls.account.pk, cls.account.primary_domain)
cls.plan = WebProvisioningPlan.objects.create(
account=cls.account,
primary_domain=cls.site.domain,
completed_at=timezone.now(),
apache_config=cls.site.render("apache"),
)
def setUp(self):
self.client.force_login(self.operator)
self.url = reverse("panel:site_php_settings", args=[self.account.pk])
self.account_url = self.account.get_absolute_url()
def mark_site_active(self):
return WebActivation.objects.create(
plan=self.plan, finished_at=timezone.now()
)
def apply_job(self, job, options):
with patch(
"coulobre.hosting.tasks.update_local_php_settings",
return_value=options,
) as node:
set_site_php_settings(job.pk)
node.assert_called_once_with(self.site, options)
job.refresh_from_db()
self.assertEqual(job.state, "configured")
self.assertEqual(job.applied_settings, options.manifest())
def test_plan_defaults_are_snapshotted_when_activation_is_requested(self):
activation_url = reverse("panel:plan_activate", args=[self.plan.pk])
self.assertEqual(self.client.post(activation_url).status_code, 302)
job = WebActivation.objects.get(plan=self.plan)
options = self.package.get_php_settings()
self.assertEqual(job.php_settings, options.manifest())
HostingPlan.objects.filter(pk=self.package.pk).update(
php_memory_limit_mib=512
)
self.client.post(activation_url)
with patch(
"coulobre.hosting.tasks.activate_local_site_with_php",
return_value=options,
) as activate:
activate_web_plan(job.pk)
activate.assert_called_once_with(self.site, options)
self.assertContains(self.client.get(self.account_url), "256 MiB")
self.assertEqual(
self.client.get(self.url).context["form"].initial,
options.manifest(),
)
def test_applied_overrides_and_defaults_follow_the_site_worker(self):
self.mark_site_active()
overrides = PhpPoolSettings(128, 16, 30, 4)
self.assertRedirects(
self.client.post(self.url, overrides.manifest()), self.account_url
)
job = SitePhpSettings.objects.get(account=self.account)
self.assertContains(
self.client.post(self.url, {"memory_limit_mib": 96}),
"Wait for the current PHP settings request to finish.",
)
with patch.object(set_site_php_settings, "apply_async") as publish:
dispatch_web_activations()
publish.assert_called_once_with(
args=[job.pk], queue=WEB_ACTIVATION_QUEUE, retry=False
)
self.apply_job(job, overrides)
page = self.client.get(self.account_url)
self.assertContains(page, "128 MiB")
self.assertContains(page, "16 MiB")
options = self.package.get_php_settings()
self.assertRedirects(
self.client.post(self.url, {"use_plan": "on"}), self.account_url
)
self.apply_job(job, options)
self.assertContains(self.client.get(self.account_url), "24 MiB")
self.assertRedirects(self.client.post(self.url, {}), self.account_url)
self.apply_job(job, PhpPoolSettings())
def test_failed_update_preserves_the_last_applied_settings(self):
self.mark_site_active()
options = PhpPoolSettings(memory_limit_mib=96)
self.client.post(self.url, {"memory_limit_mib": 96})
job = SitePhpSettings.objects.get(account=self.account)
self.apply_job(job, options)
self.client.post(self.url, {"memory_limit_mib": 192})
with patch(
"coulobre.hosting.tasks.update_local_php_settings",
side_effect=ValueError("Reload failed."),
):
set_site_php_settings(job.pk)
job.refresh_from_db()
self.assertEqual(job.applied_settings, options.manifest())
page = self.client.get(self.account_url)
self.assertContains(page, "96 MiB")
self.assertContains(page, "Reload failed.")
def test_php_settings_are_validated_for_plans_and_individual_sites(self):
self.mark_site_active()
fields = {
"memory_limit_mib": 32,
"upload_limit_mib": 64,
"max_children": 0,
}
response = self.client.post(self.url, fields)
self.assertIn("max_children", response.context["form"].errors)
response = self.client.post(self.url, fields | {"max_children": 2})
self.assertIn("memory_limit_mib", response.context["form"].errors)
self.assertFalse(SitePhpSettings.objects.exists())
plan_url = reverse("panel:hosting_plan_create")
plan_fields = {
f"php_{field}": value for field, value in fields.items()
}
response = self.client.post(
plan_url, plan_fields | {"name": "Invalid"}
)
self.assertIn("php_max_children", response.context["form"].errors)
response = self.client.post(
plan_url, plan_fields | {"name": "Invalid", "php_max_children": 2}
)
self.assertIn("php_memory_limit_mib", response.context["form"].errors)
self.assertEqual(HostingPlan.objects.count(), 1)
def test_php_settings_require_an_active_site_and_operator_permission(self):
self.assertContains(
self.client.post(self.url, {"memory_limit_mib": 128}),
"Activate the website before changing PHP settings.",
)
self.mark_site_active()
viewer = get_user_model().objects.create_user("viewer")
viewer.user_permissions.add(
Permission.objects.get(codename="view_hostingaccount")
)
self.client.force_login(viewer)
self.assertContains(self.client.get(self.account_url), "PHP settings")
self.assertNotContains(
self.client.get(self.account_url), "Change PHP settings"
)
self.assertEqual(
self.client.post(self.url, {"memory_limit_mib": 128}).status_code,
403,
)
self.assertFalse(SitePhpSettings.objects.exists())
class NativePhpSettingsTests(SimpleTestCase):
def setUp(self):
directory = Path(self.enterContext(TemporaryDirectory()))
self.site = WebSite(42, "example.net")
available = directory / "sites-available"
active = directory / "sites-enabled"
available.mkdir()
active.mkdir()
self.paths = SitePaths(
directory / "site",
available / "coulobre-42.conf",
active / "coulobre-42.conf",
directory / "php.conf",
directory / "php.sock",
)
self.enterContext(
patch(
"coulobre.web_node_php.read_root_file",
side_effect=Path.read_text,
)
)
self.runner = self.enterContext(patch("coulobre.web_node_apply.run"))
self.ready = self.enterContext(
patch("coulobre.web_node_apply.wait_for_socket")
)
self.options = PhpPoolSettings(128, 24, 35, 3)
self.default_pool = self.site.render("php-fpm")
def test_request_rejects_unknown_fields_and_nonnumeric_options(self):
request = WebPhpRequest(self.site, self.options, "set_php_settings")
self.assertEqual(parse_web_request(request.manifest()), request)
for malformed in (
{"max_children": True},
{"upload_limit_mib": "8M"},
{"arbitrary": 1},
):
payload = request.manifest() | {
"php_settings": self.options.manifest() | malformed
}
with (
self.subTest(malformed=malformed),
self.assertRaises(ValueError),
):
parse_web_request(payload)
def test_generated_php_settings_survive_activation(
self,
):
pool = self.site.render("php-fpm", php_settings=self.options)
self.paths.pool.write_text(pool, encoding="utf-8")
self.assertEqual(
read_managed_php_pool(self.site, self.paths.pool),
(pool, self.options),
)
self.assertIn("pm.max_children = 3", pool)
self.assertIn("php_admin_value[post_max_size] = 25M", pool)
self.assertIn("request_terminate_timeout = 35s", pool)
applied = install_configurations(
self.site,
self.paths.apache,
self.paths.enabled,
self.paths.pool,
self.paths.socket,
php_settings=PhpPoolSettings(max_children=5),
)
self.assertEqual(applied, self.options)
self.assertEqual(self.paths.pool.read_text(), pool)
self.paths.pool.write_text(
pool.replace("pm.max_children = 3", "pm.max_children = 6")
)
with self.assertRaisesMessage(
ValueError, "Existing configuration differs"
):
read_managed_php_pool(self.site, self.paths.pool)
def test_reload_failure_restores_the_previous_pool_and_reloads_it(self):
self.paths.pool.write_text(self.default_pool, encoding="utf-8")
updated_pool = self.site.render("php-fpm", php_settings=self.options)
self.runner.side_effect = ["valid", ValueError("Cannot reload."), ""]
with self.assertRaisesMessage(ValueError, "Cannot reload."):
change_php_pool(self.paths, self.default_pool, updated_pool)
self.assertEqual(self.paths.pool.read_text(), self.default_pool)
self.assertEqual(
self.runner.call_args_list,
[
call("/usr/sbin/php-fpm8.5", "--test"),
call("/usr/sbin/service", PHP_SERVICE, "reload"),
call("/usr/sbin/service", PHP_SERVICE, "reload"),
],
)
self.ready.assert_called_once_with(self.paths.socket)
def test_unchanged_settings_still_reload_after_interrupted_application(
self,
):
self.paths.pool.write_text(self.default_pool, encoding="utf-8")
change_php_pool(self.paths, self.default_pool, self.default_pool)
self.runner.assert_any_call("/usr/sbin/service", PHP_SERVICE, "reload")
self.ready.assert_called_once_with(self.paths.socket)
+5
View File
@@ -21,6 +21,11 @@ urlpatterns = [
"accounts/new/", views.AccountCreate.as_view(), name="account_create"
),
path("accounts/<int:pk>/", views.AccountDetail.as_view(), name="account"),
path(
"accounts/<int:pk>/php-settings/",
views.SitePhpSettingsEdit.as_view(),
name="site_php_settings",
),
path(
"accounts/<int:pk>/aliases/new/",
views.WebsiteAliasCreate.as_view(),
+83 -4
View File
@@ -83,13 +83,20 @@ from .models import (
HostingMailbox,
HostingPlan,
Reseller,
WebActivation,
WebHTTPS,
WebProvisioningPlan,
WebsiteAlias,
WebsiteDomain,
WebsiteRestoreJob,
)
from .php_settings import (
SitePhpSettingsForm,
last_applied_php_settings,
plan_php_settings,
queue_site_php_settings,
queue_web_activation,
settings_from_form,
)
from .reseller_accounts import create_reseller_account
from .resource_requests import (
change_mailbox_quota,
@@ -127,6 +134,7 @@ 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")
CHANGE_SITE_PHP_SETTINGS = (VIEW_ACCOUNTS, "hosting.change_sitephpsettings")
EXPORT_BACKUP_MANIFEST = (VIEW_ACCOUNTS, VIEW_PLANS, VIEW_DATABASES)
EXPORT_MAIL_BACKUP_MANIFEST = (*EXPORT_BACKUP_MANIFEST, VIEW_MAILBOXES)
MANAGE_ACCOUNT_BACKUPS = (
@@ -343,7 +351,24 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
context["website_limit_pending"] = (
quota is not None and quota.finished_at is None
)
site_active = (
settings.LOCAL_WEB_ACTIVATION or settings.LOCAL_WEB_SFTP
) and site_is_active(self.object)
if settings.LOCAL_WEB_ACTIVATION:
php_job = getattr(self.object, "php_settings_job", None)
if (
php_job is not None
and php_job.domain != self.object.primary_domain
):
php_job = None
if site_active:
context["website_php_settings"] = last_applied_php_settings(
self.object, php_job
)
context["website_php_job"] = php_job
context["can_change_php_settings"] = (
not tenant and user.has_perms(CHANGE_SITE_PHP_SETTINGS)
)
context["website_aliases"] = (
WebsiteAlias.objects.filter(reservation__account=self.object)
.select_related("reservation")
@@ -351,7 +376,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
)
if not tenant and user.has_perms(MANAGE_WEBSITE_ALIASES):
context["manage_website_aliases"] = True
context["can_add_website_alias"] = site_is_active(self.object)
context["can_add_website_alias"] = site_active
context["can_enable_alias_https"] = (
settings.LOCAL_WEB_HTTPS
and user.has_perms(ENABLE_WEB_HTTPS)
@@ -407,7 +432,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
context["manage_sftp"] = (
settings.LOCAL_WEB_SFTP
and can_manage_sftp(user)
and (site_is_active(self.object) or hasattr(self.object, "sftp"))
and (site_active or hasattr(self.object, "sftp"))
)
if reseller is not None or (
customer is None and user.has_perm(VIEW_PLANS)
@@ -503,6 +528,56 @@ class SiteStorageLimitEdit(
return redirect(self.account)
class SitePhpSettingsEdit(
OperatorOnlyMixin, PermissionRequiredMixin, FormView
):
permission_required = CHANGE_SITE_PHP_SETTINGS
form_class = SitePhpSettingsForm
template_name = "hosting/site_php_settings_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", "php_settings_job"
),
pk=self.kwargs["pk"],
)
def get_initial(self):
job = getattr(self.account, "php_settings_job", None)
if job is not None and job.domain == self.account.primary_domain:
return job.requested_settings
return last_applied_php_settings(self.account, None).manifest()
def get_context_data(self, **kwargs):
return super().get_context_data(
account=self.account,
plan_settings=plan_php_settings(self.account),
**kwargs,
)
def form_valid(self, form):
use_plan = form.cleaned_data["use_plan"]
try:
queue_site_php_settings(
self.account.pk,
None if use_plan else settings_from_form(form.cleaned_data),
use_plan=use_plan,
)
except HostingAccount.DoesNotExist:
raise Http404 from None
except ValidationError as error:
form.add_error(None, error)
return self.form_invalid(form)
return redirect(self.account)
class WebsiteAliasEditor(OperatorOnlyMixin, PermissionRequiredMixin, FormView):
permission_required = MANAGE_WEBSITE_ALIASES
template_name = "hosting/website_alias_form.html"
@@ -1498,6 +1573,10 @@ class HostingPlanEditor:
"mailbox_limit",
"mailbox_quota_mib",
"website_storage_limit_mib",
"php_memory_limit_mib",
"php_upload_limit_mib",
"php_request_timeout_seconds",
"php_max_children",
)
template_name = "hosting/hosting_plan_form.html"
success_url = reverse_lazy("panel:hosting_plans")
@@ -1590,7 +1669,7 @@ class RequestWebActivation(
status=409,
content_type="text/plain",
)
WebActivation.objects.queue(plan=plan)
queue_web_activation(plan)
return redirect("panel:plan", pk=plan.pk)