From 08bcab71448d906eaf3ab0171492c466cbf9da8b Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sat, 21 Nov 2026 16:04:33 +0100 Subject: [PATCH] Capture hosting plan PHP defaults and apply site settings through the worker --- .../migrations/0030_website_php_settings.py | 121 ++++++++++++++++ src/coulobre/hosting/models.py | 60 ++++++++ src/coulobre/hosting/node_client.py | 28 ++++ src/coulobre/hosting/php_settings.py | 137 ++++++++++++++++++ src/coulobre/hosting/tasks.py | 42 +++++- 5 files changed, 387 insertions(+), 1 deletion(-) create mode 100644 src/coulobre/hosting/migrations/0030_website_php_settings.py create mode 100644 src/coulobre/hosting/php_settings.py diff --git a/src/coulobre/hosting/migrations/0030_website_php_settings.py b/src/coulobre/hosting/migrations/0030_website_php_settings.py new file mode 100644 index 0000000..c128fd6 --- /dev/null +++ b/src/coulobre/hosting/migrations/0030_website_php_settings.py @@ -0,0 +1,121 @@ +# Generated by Django 5.2.19 on 2026-11-21 15:00 + +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", "0029_website_aliases"), + ] + + operations = [ + migrations.AddField( + model_name="hostingplan", + name="php_max_children", + field=models.PositiveIntegerField( + blank=True, + help_text="Leave blank to use the web node default.", + null=True, + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(32), + ], + verbose_name="Maximum PHP-FPM workers", + ), + ), + migrations.AddField( + model_name="hostingplan", + name="php_memory_limit_mib", + field=models.PositiveIntegerField( + blank=True, + help_text="Leave blank to use the web node default.", + null=True, + validators=[ + django.core.validators.MinValueValidator(16), + django.core.validators.MaxValueValidator(4096), + ], + verbose_name="PHP memory limit (MiB)", + ), + ), + migrations.AddField( + model_name="hostingplan", + name="php_request_timeout_seconds", + field=models.PositiveIntegerField( + blank=True, + help_text="Leave blank to use the web node default.", + null=True, + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(600), + ], + verbose_name="PHP request timeout (seconds)", + ), + ), + migrations.AddField( + model_name="hostingplan", + name="php_upload_limit_mib", + field=models.PositiveIntegerField( + blank=True, + help_text="Leave blank to use the web node default.", + null=True, + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(512), + ], + verbose_name="PHP upload limit (MiB)", + ), + ), + migrations.AddField( + model_name="webactivation", + name="php_settings", + field=models.JSONField(blank=True, null=True), + ), + migrations.CreateModel( + name="SitePhpSettings", + 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), + ), + ("requested_settings", models.JSONField()), + ("applied_settings", models.JSONField(blank=True, null=True)), + ("applied_at", models.DateTimeField(blank=True, null=True)), + ( + "account", + models.OneToOneField( + on_delete=django.db.models.deletion.CASCADE, + related_name="php_settings_job", + to="hosting.hostingaccount", + ), + ), + ], + options={ + "abstract": False, + }, + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index 7ceba5b..18ed899 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -31,6 +31,11 @@ from coulobre.mail_node import ( MAX_MAILBOX_QUOTA_MIB, MailboxSpec, ) +from coulobre.php_pool_settings import ( + PHP_SETTING_BOUNDS, + PhpPoolSettings, + PhpPoolSettingsError, +) from coulobre.web_node import MAX_STORAGE_LIMIT_MIB from .fields import DomainNameField @@ -122,6 +127,17 @@ class CustomerImpersonation(models.Model): return f"{self.operator_username} viewing as {self.customer_username}" +def php_plan_field(option, label): + minimum, maximum = PHP_SETTING_BOUNDS[option] + return models.PositiveIntegerField( + label, + blank=True, + null=True, + validators=[MinValueValidator(minimum), MaxValueValidator(maximum)], + help_text="Leave blank to use the web node default.", + ) + + class HostingPlan(models.Model): name = models.CharField(max_length=120, unique=True) description = models.CharField(max_length=240, blank=True) @@ -163,12 +179,42 @@ class HostingPlan(models.Model): help_text="Default when applying a website storage limit.", ) + php_memory_limit_mib = php_plan_field( + "memory_limit_mib", "PHP memory limit (MiB)" + ) + php_upload_limit_mib = php_plan_field( + "upload_limit_mib", "PHP upload limit (MiB)" + ) + php_request_timeout_seconds = php_plan_field( + "request_timeout_seconds", "PHP request timeout (seconds)" + ) + php_max_children = php_plan_field( + "max_children", "Maximum PHP-FPM workers" + ) + class Meta: ordering = ("name", "pk") def __str__(self): return self.name + def clean(self): + super().clean() + try: + self.get_php_settings() + except PhpPoolSettingsError as error: + raise ValidationError( + {f"php_{error.field}": str(error)} + ) from error + + def get_php_settings(self): + return PhpPoolSettings( + **{ + option: getattr(self, f"php_{option}") + for option in PHP_SETTING_BOUNDS + } + ) + class HostingAccount(models.Model): name = models.CharField(max_length=120) @@ -483,6 +529,20 @@ class WebActivation(ProvisioningJob): related_name="activation", ) + php_settings = models.JSONField(null=True, blank=True) + + +class SitePhpSettings(ProvisioningJob): + account = models.OneToOneField( + HostingAccount, + on_delete=models.CASCADE, + related_name="php_settings_job", + ) + domain = DomainNameField(max_length=253) + requested_settings = models.JSONField() + applied_settings = models.JSONField(null=True, blank=True) + applied_at = models.DateTimeField(null=True, blank=True) + class SiteStorageUsage(ProvisioningJob): account = models.OneToOneField( diff --git a/src/coulobre/hosting/node_client.py b/src/coulobre/hosting/node_client.py index c4f3420..d506cdd 100644 --- a/src/coulobre/hosting/node_client.py +++ b/src/coulobre/hosting/node_client.py @@ -10,9 +10,11 @@ from coulobre.account_restore_request import ( RESTORE_TIMEOUT_SECONDS, ) from coulobre.mail_node import MailboxQuotaUpdate +from coulobre.php_pool_settings import PhpPoolSettings from coulobre.web_node import ( MAX_STORAGE_BYTES, WebAliasRequest, + WebPhpRequest, WebQuotaRequest, WebStorageRequest, ) @@ -26,6 +28,32 @@ def activate_local_site(site): ) +def activate_local_site_with_php(site, php_settings): + return send_php_settings(site, php_settings, "activate_with_php_settings") + + +def update_local_php_settings(site, php_settings): + applied = send_php_settings(site, php_settings, "set_php_settings") + if applied != php_settings: + raise ValueError("The web node reported different PHP pool settings.") + return applied + + +def send_php_settings(site, php_settings, operation): + reply = apply_on_local_node( + WebPhpRequest(site, php_settings, operation), + "/run/coulobre-web-apply.sock", + "web node", + "PHP pool settings", + ) + try: + return PhpPoolSettings.from_manifest(reply.get("applied_php_settings")) + except ValueError: + raise ValueError( + "The web node returned invalid PHP pool settings." + ) from None + + def measure_local_site_storage(site): reply = apply_on_local_node( WebStorageRequest(site), diff --git a/src/coulobre/hosting/php_settings.py b/src/coulobre/hosting/php_settings.py new file mode 100644 index 0000000..7dc777c --- /dev/null +++ b/src/coulobre/hosting/php_settings.py @@ -0,0 +1,137 @@ +from django import forms +from django.core.exceptions import ValidationError +from django.db import transaction + +from coulobre.php_pool_settings import ( + PHP_SETTING_BOUNDS, + PhpPoolSettings, + PhpPoolSettingsError, +) + +from .models import SitePhpSettings, WebActivation +from .resource_requests import lock_hosting_account +from .sftp import site_is_active + + +def php_setting_input(option, label, *, help_text=""): + minimum, maximum = PHP_SETTING_BOUNDS[option] + return forms.IntegerField( + label=label, + min_value=minimum, + max_value=maximum, + required=False, + help_text=help_text, + ) + + +class SitePhpSettingsForm(forms.Form): + memory_limit_mib = php_setting_input( + "memory_limit_mib", "PHP memory limit (MiB)" + ) + upload_limit_mib = php_setting_input( + "upload_limit_mib", "PHP upload limit (MiB)" + ) + request_timeout_seconds = php_setting_input( + "request_timeout_seconds", "PHP request timeout (seconds)" + ) + max_children = php_setting_input("max_children", "Maximum PHP-FPM workers") + use_plan = forms.BooleanField( + label="Apply the current hosting plan defaults", + required=False, + help_text="Uses the plan's values in place of the limits above.", + ) + + def clean(self): + cleaned = super().clean() + if not self.errors and not cleaned.get("use_plan"): + try: + settings_from_form(cleaned) + except PhpPoolSettingsError as error: + self.add_error(error.field, str(error)) + return cleaned + + +def settings_from_form(data): + return PhpPoolSettings( + **{option: data[option] for option in PHP_SETTING_BOUNDS} + ) + + +def plan_php_settings(account): + plan = account.hosting_plan + return plan.get_php_settings() if plan is not None else PhpPoolSettings() + + +def last_applied_php_settings(account, job): + if job is not None and job.applied_at is not None: + return PhpPoolSettings.from_manifest(job.applied_settings) + initial = ( + WebActivation.objects.filter( + plan__account=account, + plan__primary_domain=account.primary_domain, + finished_at__isnull=False, + problem="", + php_settings__isnull=False, + ) + .order_by("-finished_at", "-pk") + .values_list("php_settings", flat=True) + .first() + ) + return ( + PhpPoolSettings.from_manifest(initial) + if initial is not None + else PhpPoolSettings() + ) + + +@transaction.atomic +def queue_web_activation(plan): + account = lock_hosting_account(plan.account_id, customer_id=None) + activations = WebActivation.objects.filter(plan=plan) + activation = activations.first() + if activation is None: + options = plan_php_settings(account) + WebActivation.objects.create( + plan=plan, + php_settings=options.manifest() if options.has_overrides else None, + ) + elif activation.problem: + WebActivation.objects.requeue(activations) + + +@transaction.atomic +def queue_site_php_settings(account_id, php_settings, *, use_plan=False): + account = lock_hosting_account(account_id, customer_id=None) + if not site_is_active(account): + raise ValidationError( + "Activate the website before changing PHP settings." + ) + if use_plan: + php_settings = plan_php_settings(account) + + changes = { + "domain": account.primary_domain, + "requested_settings": php_settings.manifest(), + } + job, created = SitePhpSettings.objects.get_or_create( + account=account, defaults=changes + ) + if created: + return + matches = ( + job.domain == changes["domain"] + and job.requested_settings == changes["requested_settings"] + ) + if job.finished_at is None: + if matches: + return + raise ValidationError( + "Wait for the current PHP settings request to finish." + ) + if matches and not job.problem: + return + if job.domain != account.primary_domain: + changes.update(applied_settings=None, applied_at=None) + SitePhpSettings.objects.requeue( + SitePhpSettings.objects.filter(pk=job.pk), **changes + ) diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py index 258b4dc..e745aa7 100644 --- a/src/coulobre/hosting/tasks.py +++ b/src/coulobre/hosting/tasks.py @@ -19,6 +19,7 @@ from coulobre.account_restore_request import ( WebsiteRestoreRequest, ) from coulobre.dns_node import DnsZone +from coulobre.php_pool_settings import PhpPoolSettings from coulobre.sftp_keys import SFTPKeys from coulobre.web_node import WebAlias, WebSite @@ -36,6 +37,7 @@ from .models import ( DatabaseProvisioning, DnsPublication, MailboxProvisioning, + SitePhpSettings, SiteSFTP, SiteStorageLimit, SiteStorageUsage, @@ -47,6 +49,7 @@ from .models import ( ) from .node_client import ( activate_local_site, + activate_local_site_with_php, create_local_account_backup, enable_local_https, expire_local_account_backup, @@ -58,6 +61,7 @@ from .node_client import ( restore_local_website, set_local_site_storage_limit, update_local_mailbox_quota, + update_local_php_settings, update_local_sftp, update_local_website_alias, ) @@ -130,6 +134,10 @@ def dispatch_web_activations(): ), ) + dispatch_provisioning_jobs( + SitePhpSettings, set_site_php_settings, WEB_ACTIVATION_QUEUE + ) + @shared_task def dispatch_site_storage_measurements(): @@ -277,7 +285,13 @@ def apply_web_activation(activation): "Request a completed Apache preview for the current " "account domain." ) - activate_local_site(WebSite(plan.account_id, plan.primary_domain)) + site = WebSite(plan.account_id, plan.primary_domain) + if activation.php_settings is None: + activate_local_site(site) + return None + options = PhpPoolSettings.from_manifest(activation.php_settings) + applied = activate_local_site_with_php(site, options) + return {"php_settings": applied.manifest()} @shared_task(acks_late=True, reject_on_worker_lost=True) @@ -342,6 +356,32 @@ def queued_website_alias(job): ) +@shared_task(acks_late=True, reject_on_worker_lost=True) +def set_site_php_settings(job_id): + if settings.LOCAL_WEB_ACTIVATION: + run_provisioning_job( + SitePhpSettings.objects.select_related("account"), + job_id, + apply_site_php_settings, + "Could not contact the local web node. " + "Check its socket and try again.", + ) + + +def apply_site_php_settings(job): + if job.domain != job.account.primary_domain: + raise ValueError( + "Request PHP settings for the current account domain." + ) + site = WebSite(job.account_id, job.domain) + options = PhpPoolSettings.from_manifest(job.requested_settings) + applied = update_local_php_settings(site, options) + return { + "applied_settings": applied.manifest(), + "applied_at": timezone.now(), + } + + @shared_task(acks_late=True, reject_on_worker_lost=True) def measure_site_storage(request_id): if settings.LOCAL_WEB_ACTIVATION: