Merge pull request 'Configure PHP limits per website and hosting plan' (#39) from feature/website-php-settings into main
Reviewed-on: #39
This commit was merged in pull request #39.
This commit is contained in:
commit
377c90bdf3
20 files changed
+1133
-16
No files matched your search
@@ -221,6 +221,31 @@ 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)
|
||||
|
||||
### Configure PHP per website
|
||||
|
||||
Under **Hosting plans**, set default PHP memory, upload size, request timeout,
|
||||
or PHP-FPM worker limits. The panel captures these values when an operator
|
||||
first requests local activation. A repeat activation preserves an installed
|
||||
pool's settings.
|
||||
|
||||
On an active account, use **Change PHP settings** to set site values or apply
|
||||
the current plan defaults. This requires permission to view the account and
|
||||
**Can change site php settings**. Plan edits and reassignment take effect
|
||||
when an operator reapplies the defaults. Leave individual values blank to use
|
||||
the web node defaults. Coulobre's default pool allows two workers.
|
||||
|
||||
The upload setting applies per file. The pool sets the maximum POST body to
|
||||
one MiB above the chosen upload size. When both limits are set, choose a memory
|
||||
limit at least one MiB higher than the upload size. The timeout applies to PHP
|
||||
execution and the time PHP-FPM spends serving the request. Apache, reverse
|
||||
proxies, and PHP input limits can impose their own shorter limits.
|
||||
[PHP upload directives](https://www.php.net/manual/en/ini.core.php) ·
|
||||
[PHP-FPM pool directives](https://www.php.net/manual/en/install.fpm.configuration.php)
|
||||
|
||||
The web activation worker tests the pool configuration and reloads PHP-FPM
|
||||
before reporting success. Reload the account page to see the last applied
|
||||
values and the result of the current request.
|
||||
|
||||
### Serve additional hostnames on a website
|
||||
|
||||
After activating a website, use **Add alias** on the hosting account.
|
||||
|
||||
@@ -39,6 +39,10 @@ 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)
|
||||
|
||||
Set optional PHP resource defaults on a hosting plan. Coulobre applies them
|
||||
on first local activation and when an operator reapplies the plan on the
|
||||
account page. See [website PHP settings](deployment.md#configure-php-per-website).
|
||||
|
||||
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
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -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(
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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
|
||||
)
|
||||
@@ -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:
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -6,6 +6,6 @@ listen.owner = www-data
|
||||
listen.group = www-data
|
||||
listen.mode = 0660
|
||||
pm = ondemand
|
||||
pm.max_children = 2
|
||||
pm.max_children = $max_children
|
||||
clear_env = yes
|
||||
security.limit_extensions = .php
|
||||
@@ -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 %}
|
||||
@@ -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)
|
||||
@@ -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,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)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import json
|
||||
from dataclasses import asdict, dataclass
|
||||
|
||||
DEFAULT_MAX_CHILDREN = 2
|
||||
PHP_SETTINGS_COMMENT = "; Coulobre PHP settings "
|
||||
PHP_SETTING_BOUNDS = {
|
||||
"memory_limit_mib": (16, 4096),
|
||||
"upload_limit_mib": (1, 512),
|
||||
"request_timeout_seconds": (1, 600),
|
||||
"max_children": (1, 32),
|
||||
}
|
||||
|
||||
|
||||
class PhpPoolSettingsError(ValueError):
|
||||
def __init__(self, field, message):
|
||||
super().__init__(message)
|
||||
self.field = field
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PhpPoolSettings:
|
||||
memory_limit_mib: int | None = None
|
||||
upload_limit_mib: int | None = None
|
||||
request_timeout_seconds: int | None = None
|
||||
max_children: int | None = None
|
||||
|
||||
def __post_init__(self):
|
||||
for field, (minimum, maximum) in PHP_SETTING_BOUNDS.items():
|
||||
value = getattr(self, field)
|
||||
if value is not None and (
|
||||
type(value) is not int or not minimum <= value <= maximum
|
||||
):
|
||||
raise PhpPoolSettingsError(
|
||||
field,
|
||||
f"Enter a whole number between {minimum} and {maximum}.",
|
||||
)
|
||||
if (
|
||||
self.memory_limit_mib is not None
|
||||
and self.post_limit_mib is not None
|
||||
and self.memory_limit_mib < self.post_limit_mib
|
||||
):
|
||||
raise PhpPoolSettingsError(
|
||||
"memory_limit_mib",
|
||||
"Set the memory limit at least 1 MiB above the upload limit.",
|
||||
)
|
||||
|
||||
@property
|
||||
def post_limit_mib(self):
|
||||
return (
|
||||
self.upload_limit_mib + 1
|
||||
if self.upload_limit_mib is not None
|
||||
else None
|
||||
)
|
||||
|
||||
@property
|
||||
def worker_limit(self):
|
||||
return self.max_children or DEFAULT_MAX_CHILDREN
|
||||
|
||||
@property
|
||||
def has_overrides(self):
|
||||
return any(value is not None for value in self.manifest().values())
|
||||
|
||||
@classmethod
|
||||
def from_manifest(cls, options):
|
||||
if (
|
||||
not isinstance(options, dict)
|
||||
or options.keys() != PHP_SETTING_BOUNDS.keys()
|
||||
):
|
||||
raise ValueError("Expected the supported PHP pool settings.")
|
||||
return cls(**options)
|
||||
|
||||
def manifest(self):
|
||||
return asdict(self)
|
||||
|
||||
def render_overrides(self):
|
||||
if not self.has_overrides:
|
||||
return ""
|
||||
lines = [
|
||||
PHP_SETTINGS_COMMENT
|
||||
+ json.dumps(self.manifest(), separators=(",", ":"))
|
||||
]
|
||||
if self.memory_limit_mib is not None:
|
||||
lines.append(
|
||||
f"php_admin_value[memory_limit] = {self.memory_limit_mib}M"
|
||||
)
|
||||
if self.upload_limit_mib is not None:
|
||||
lines.extend(
|
||||
(
|
||||
"php_admin_value[upload_max_filesize] = "
|
||||
f"{self.upload_limit_mib}M",
|
||||
f"php_admin_value[post_max_size] = {self.post_limit_mib}M",
|
||||
)
|
||||
)
|
||||
if self.request_timeout_seconds is not None:
|
||||
timeout = self.request_timeout_seconds
|
||||
lines.extend(
|
||||
(
|
||||
f"php_admin_value[max_execution_time] = {timeout}",
|
||||
f"request_terminate_timeout = {timeout}s",
|
||||
"request_terminate_timeout_track_finished = yes",
|
||||
)
|
||||
)
|
||||
return "\n".join(lines) + "\n"
|
||||
@@ -10,6 +10,7 @@ from string import Template
|
||||
from .directadmin import DOCUMENT_ROOTS
|
||||
from .domain_names import canonical_domain
|
||||
from .node_requests import serve_apply_request
|
||||
from .php_pool_settings import PhpPoolSettings
|
||||
|
||||
MANIFEST_VERSION = 1
|
||||
MAX_STORAGE_BYTES = 2**63 - 1
|
||||
@@ -70,7 +71,13 @@ class WebSite:
|
||||
}
|
||||
|
||||
def render(
|
||||
self, configuration, *, port=80, tls_settings="", server_name=None
|
||||
self,
|
||||
configuration,
|
||||
*,
|
||||
port=80,
|
||||
tls_settings="",
|
||||
server_name=None,
|
||||
php_settings=None,
|
||||
):
|
||||
resource = files("coulobre.hosting").joinpath(
|
||||
"templates", "hosting", CONFIGURATIONS[configuration]
|
||||
@@ -78,7 +85,14 @@ class WebSite:
|
||||
values = self.configuration()
|
||||
if server_name is not None:
|
||||
values["domain"] = canonical_domain(server_name)
|
||||
return Template(resource.read_text(encoding="utf-8")).substitute(
|
||||
template = Template(resource.read_text(encoding="utf-8"))
|
||||
if configuration == "php-fpm":
|
||||
options = php_settings or PhpPoolSettings()
|
||||
return (
|
||||
template.substitute(values, max_children=options.worker_limit)
|
||||
+ options.render_overrides()
|
||||
)
|
||||
return template.substitute(
|
||||
values, port=port, tls_settings=tls_settings
|
||||
)
|
||||
|
||||
@@ -178,6 +192,27 @@ class WebQuotaRequest:
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WebPhpRequest:
|
||||
site: WebSite
|
||||
php_settings: PhpPoolSettings
|
||||
operation: str
|
||||
|
||||
def __post_init__(self):
|
||||
if self.operation not in (
|
||||
"activate_with_php_settings",
|
||||
"set_php_settings",
|
||||
):
|
||||
raise ValueError("Expected a PHP pool operation.")
|
||||
|
||||
def manifest(self):
|
||||
return {
|
||||
"operation": self.operation,
|
||||
"site": self.site.manifest(),
|
||||
"php_settings": self.php_settings.manifest(),
|
||||
}
|
||||
|
||||
|
||||
def parse_web_request(data):
|
||||
if (
|
||||
isinstance(data, dict)
|
||||
@@ -193,6 +228,16 @@ def parse_web_request(data):
|
||||
return WebQuotaRequest(
|
||||
WebSite.from_manifest(data["site"]), data["limit_mib"]
|
||||
)
|
||||
if isinstance(data, dict) and data.keys() == {
|
||||
"operation",
|
||||
"site",
|
||||
"php_settings",
|
||||
}:
|
||||
return WebPhpRequest(
|
||||
WebSite.from_manifest(data["site"]),
|
||||
PhpPoolSettings.from_manifest(data["php_settings"]),
|
||||
data["operation"],
|
||||
)
|
||||
if isinstance(data, dict) and data.keys() == {"operation", "alias"}:
|
||||
return WebAliasRequest(
|
||||
WebAlias.from_manifest(data["alias"]), data["operation"]
|
||||
@@ -212,6 +257,18 @@ def apply_web_request(request):
|
||||
apply_website_limit(request)
|
||||
return None
|
||||
|
||||
if isinstance(request, WebPhpRequest):
|
||||
from .web_node_apply import apply_site
|
||||
from .web_node_php import update_php_pool
|
||||
|
||||
if request.operation == "activate_with_php_settings":
|
||||
applied = apply_site(
|
||||
request.site, php_settings=request.php_settings
|
||||
)
|
||||
else:
|
||||
applied = update_php_pool(request.site, request.php_settings)
|
||||
return {"applied_php_settings": applied.manifest()}
|
||||
|
||||
if isinstance(request, WebAliasRequest):
|
||||
from .web_node_aliases import activate_alias, remove_alias
|
||||
|
||||
|
||||
@@ -62,7 +62,7 @@ def locked_web_node(mode):
|
||||
yield
|
||||
|
||||
|
||||
def apply_site(site):
|
||||
def apply_site(site, *, php_settings=None):
|
||||
if os.geteuid() != 0:
|
||||
raise ValueError("Run apply as root on the web node.")
|
||||
|
||||
@@ -75,10 +75,10 @@ def apply_site(site):
|
||||
|
||||
with (STATE_DIRECTORY / "apply.lock").open("a") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
install_site(site)
|
||||
return install_site(site, php_settings=php_settings)
|
||||
|
||||
|
||||
def install_site(site):
|
||||
def install_site(site, *, php_settings=None):
|
||||
user = site.configuration()["service_user"]
|
||||
paths = SitePaths.for_site(site)
|
||||
owned_paths = (
|
||||
@@ -93,8 +93,13 @@ def install_site(site):
|
||||
uid, web_gid = ensure_system_account(user, paths.account)
|
||||
require_root_directory(paths.account, create_mode=0o755)
|
||||
ensure_public_directory(paths.account / "public", uid, web_gid)
|
||||
install_configurations(
|
||||
site, paths.apache, paths.enabled, paths.pool, paths.socket
|
||||
return install_configurations(
|
||||
site,
|
||||
paths.apache,
|
||||
paths.enabled,
|
||||
paths.pool,
|
||||
paths.socket,
|
||||
php_settings=php_settings,
|
||||
)
|
||||
|
||||
|
||||
@@ -149,6 +154,8 @@ def site_storage(site):
|
||||
|
||||
|
||||
def check_installation(site, paths):
|
||||
from .web_node_php import read_managed_php_pool
|
||||
|
||||
for directory in (
|
||||
paths.account,
|
||||
APACHE_AVAILABLE,
|
||||
@@ -161,7 +168,7 @@ def check_installation(site, paths):
|
||||
uid, gid = check_system_account(user, paths.account)
|
||||
check_public_directory(paths.account / "public", uid, gid)
|
||||
check_configuration(paths.apache, site.render("apache"))
|
||||
check_configuration(paths.pool, site.render("php-fpm"))
|
||||
read_managed_php_pool(site, paths.pool)
|
||||
check_site_link(
|
||||
paths.enabled, Path("../sites-available") / paths.apache.name
|
||||
)
|
||||
@@ -296,10 +303,21 @@ def check_public_directory(path, uid, gid):
|
||||
raise ValueError(f"Unexpected ownership or mode for {path}.")
|
||||
|
||||
|
||||
def install_configurations(site, apache, enabled, pool, socket):
|
||||
def install_configurations(
|
||||
site, apache, enabled, pool, socket, *, php_settings=None
|
||||
):
|
||||
from .php_pool_settings import PhpPoolSettings
|
||||
from .web_node_php import read_managed_php_pool
|
||||
|
||||
with configuration_installation() as (created, reload_attempts):
|
||||
install_configuration(apache, site.render("apache"), created)
|
||||
install_configuration(pool, site.render("php-fpm"), created)
|
||||
if os.path.lexists(pool):
|
||||
_, applied = read_managed_php_pool(site, pool)
|
||||
else:
|
||||
applied = php_settings or PhpPoolSettings()
|
||||
install_configuration(
|
||||
pool, site.render("php-fpm", php_settings=applied), created
|
||||
)
|
||||
enable_apache_site(apache, enabled, created)
|
||||
|
||||
run("/usr/sbin/php-fpm8.5", "--test")
|
||||
@@ -309,6 +327,7 @@ def install_configurations(site, apache, enabled, pool, socket):
|
||||
wait_for_socket(socket)
|
||||
reload_attempts.append("apache2")
|
||||
run("/usr/sbin/service", "apache2", "reload")
|
||||
return applied
|
||||
|
||||
|
||||
def install_configuration(path, content, created):
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from tempfile import NamedTemporaryFile
|
||||
|
||||
from . import web_node_apply as web
|
||||
from .node_files import read_root_file
|
||||
from .php_pool_settings import PHP_SETTINGS_COMMENT, PhpPoolSettings
|
||||
|
||||
|
||||
def read_managed_php_pool(site, path):
|
||||
content = read_root_file(path)
|
||||
_, marker, options = content.partition("\n" + PHP_SETTINGS_COMMENT)
|
||||
try:
|
||||
if marker:
|
||||
manifest = json.loads(options.split("\n", 1)[0])
|
||||
settings = PhpPoolSettings.from_manifest(manifest)
|
||||
else:
|
||||
settings = PhpPoolSettings()
|
||||
except (ValueError, RecursionError):
|
||||
raise ValueError(
|
||||
f"Existing configuration differs at {path}."
|
||||
) from None
|
||||
if content != site.render("php-fpm", php_settings=settings):
|
||||
raise ValueError(f"Existing configuration differs at {path}.")
|
||||
return content, settings
|
||||
|
||||
|
||||
def update_php_pool(site, settings):
|
||||
if os.geteuid() != 0:
|
||||
raise ValueError("Update PHP pool settings as root on the web node.")
|
||||
paths = web.SitePaths.for_site(site)
|
||||
with web.locked_web_node(fcntl.LOCK_EX):
|
||||
web.check_reservation(site)
|
||||
web.check_installation(site, paths)
|
||||
old, _ = read_managed_php_pool(site, paths.pool)
|
||||
wanted = site.render("php-fpm", php_settings=settings)
|
||||
change_php_pool(paths, old, wanted)
|
||||
return settings
|
||||
|
||||
|
||||
def change_php_pool(paths, old, wanted):
|
||||
changed = old != wanted
|
||||
if changed:
|
||||
replace_pool_file(paths.pool, wanted)
|
||||
reload_attempted = False
|
||||
try:
|
||||
web.run("/usr/sbin/php-fpm8.5", "--test")
|
||||
reload_attempted = True
|
||||
reload_php_pool(paths.socket)
|
||||
except (OSError, ValueError, KeyboardInterrupt) as error:
|
||||
try:
|
||||
if changed:
|
||||
replace_pool_file(paths.pool, old)
|
||||
if reload_attempted:
|
||||
reload_php_pool(paths.socket)
|
||||
except (OSError, ValueError) as recovery:
|
||||
raise ValueError(
|
||||
f"{error}\nPHP-FPM rollback failed. {recovery}"
|
||||
) from error
|
||||
raise
|
||||
|
||||
|
||||
def replace_pool_file(path, content):
|
||||
with NamedTemporaryFile(
|
||||
mode="w", encoding="utf-8", dir=path.parent, delete=False
|
||||
) as temporary:
|
||||
staged = Path(temporary.name)
|
||||
try:
|
||||
temporary.write(content)
|
||||
temporary.flush()
|
||||
os.fchmod(temporary.fileno(), 0o644)
|
||||
os.fsync(temporary.fileno())
|
||||
staged.replace(path)
|
||||
finally:
|
||||
staged.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def reload_php_pool(socket):
|
||||
web.run("/usr/sbin/service", web.PHP_SERVICE, "reload")
|
||||
web.wait_for_socket(socket)
|
||||
Reference in new issue
Block a user