Merge pull request 'Select a PHP-FPM version per website' (#83) from feature/site-php-runtime into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s

Reviewed-on: #83
This commit was merged in pull request #83.
This commit is contained in:
parkel committed 2026-11-22 00:00:04 +01:00
commit f6888a11b9
28 files changed
+1409 -168

No files matched your search

+50 -1
View File
@@ -327,7 +327,54 @@ the managed sites. Use **Change storage limit** on the deployed account to
apply the hosting plan's default or choose a per-site value. apply the hosting plan's default or choose a per-site value.
[Website storage quotas](development.md#apply-a-website-storage-limit) [Website storage quotas](development.md#apply-a-website-storage-limit)
### Configure PHP per website ### Choose PHP versions for hosted websites
Use the distribution PHP-FPM packages for a single PHP series. To offer more
series on the same node, enable an APT archive that supplies co-installable
PHP-FPM packages for the node's distribution. DEB.SURY.ORG supplies signed
packages for Debian 13 and Ubuntu. Follow its keyring and `Signed-By`
instructions for the node's release. [DEB.SURY.ORG setup](https://packages.sury.org/php/README.txt)
Install and start each series you want to offer. Install the application's
required PHP extensions for each series it will use. APT remains responsible
for package and security updates.
```sh
sudo apt install php8.5-fpm php8.6-fpm
sudo systemctl enable --now php8.5-fpm php8.6-fpm
```
Under **Hosting plans**, enter the **Allowed PHP series** as a comma-separated
list, such as `8.5, 8.6`. A blank list makes every installed stable series
available. New website activations select the newest installed stable series
in the plan. Each active site retains its recorded series when a package or
plan changes. APT patch releases update that series in place.
Use **Change PHP version** on an active account to schedule a switch.
Assigned customers can change their own sites. Operators need permission to
view the account and **Can change site php version**. The page shows the
active series and the progress of the request. Site aliases, including
aliases served over HTTPS, switch with the primary site.
Coulobre validates the target pool and waits for its socket before switching
traffic. It retains the website's PHP pool limits. If a request fails,
check the worker's diagnostic, correct the problem, and submit the same
series again. The web node can confirm a switch whose reply was interrupted.
On upgrade, existing local activations retain the previously used series.
The existing Apache configurations move to the shared socket route during
the first version change. Preview and apply manifests keep their account
and domain identity. Upgrade the panel and local activation worker together.
To withdraw a series, remove it from plan allowlists and explicitly move
each website that uses it. Verify the new PHP version over HTTP and HTTPS.
Check the old series' pool directory for website or tool pools before stopping
its service and removing the package. Retain working configuration for the
series while any pool still needs it. phpMyAdmin, Roundcube, and command-line
jobs use their own configured runtimes. Use a versioned command such as
`php8.5` for a job that must stay on a specific series.
### Configure PHP pool limits per website
Under **Hosting plans**, set default PHP memory, upload size, request timeout, Under **Hosting plans**, set default PHP memory, upload size, request timeout,
or PHP-FPM worker limits. The panel captures these values when an operator or PHP-FPM worker limits. The panel captures these values when an operator
@@ -1635,6 +1682,8 @@ COULOBRE_SERVICE_HEALTH='{"panel-01":{"local":["panel","worker","scheduler","apa
Choose an ID for each node using lower-case letters, numbers, and hyphens, Choose an ID for each node using lower-case letters, numbers, and hyphens,
starting with a letter. Keep the IDs stable for the same hosts. List one starting with a letter. Keep the IDs stable for the same hosts. List one
`local` node per panel installation and use `ssh` for each additional host. `local` node per panel installation and use `ssh` for each additional host.
Use `php-fpm` under `local` to monitor the installed stable PHP-FPM services.
The check reports a problem when any of those services is unavailable.
Use `bind9`, `postfix`, `dovecot`, `spamd`, and `spamass-milter` under Use `bind9`, `postfix`, `dovecot`, `spamd`, and `spamass-milter` under
`local` for co-located services or under `ssh` for separate nodes. Only `local` for co-located services or under `ssh` for separate nodes. Only
list the spam filter units where filtering is configured. Update the list the spam filter units where filtering is configured. Update the
+15 -3
View File
@@ -41,7 +41,7 @@ operator applies a website quota from the account page.
Set optional PHP resource defaults on a hosting plan. Coulobre applies them 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 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). account page. See [website PHP settings](deployment.md#configure-php-pool-limits-per-website).
Changing or reassigning a plan preserves existing databases and mailboxes. If Changing or reassigning a plan preserves existing databases and mailboxes. If
the new limit is at or below current usage, the panel blocks additional the new limit is at or below current usage, the panel blocks additional
@@ -812,8 +812,11 @@ sudo /opt/coulobre/bin/coulobre-web-node apply coulobre-web-plan-1.json
The command reserves the account ID and domain on the node, creates a system The command reserves the account ID and domain on the node, creates a system
user and a document root under `/srv/coulobre/web/<account-id>/public`, and user and a document root under `/srv/coulobre/web/<account-id>/public`, and
installs Apache and PHP-FPM configuration. It validates both configurations, installs Apache and PHP-FPM configuration. It selects the newest stable
reloads PHP-FPM, waits for the per-site socket, then reloads Apache. installed series for a new site. Pass `--php-version 8.5` to select a
specific installed series at initial activation. It validates both
configurations, reloads PHP-FPM, waits for the per-site socket, then reloads
Apache. Reapplying the manifest preserves the active series.
Reapply the same manifest to retry or verify an existing installation. The Reapply the same manifest to retry or verify an existing installation. The
node checks the account registry for domain conflicts and protects existing node checks the account registry for domain conflicts and protects existing
@@ -832,6 +835,7 @@ The JSON report includes the manifest identity and one of three states.
- `configured` means the reservation, Unix account, document root, service - `configured` means the reservation, Unix account, document root, service
configuration, running services, and PHP-FPM socket match the manifest. configuration, running services, and PHP-FPM socket match the manifest.
The report includes the active `php_version`.
- `not_installed` means the node has no reservation for the account. - `not_installed` means the node has no reservation for the account.
- `needs_attention` includes the first mismatch or service problem found. - `needs_attention` includes the first mismatch or service problem found.
@@ -931,6 +935,14 @@ read the JSON reply to EOF. A `configured` reply includes the account ID and
domain. A `failed` reply includes a diagnostic in `problem`. Retry the same domain. A `failed` reply includes a diagnostic in `problem`. Retry the same
manifest if the connection closes before a reply arrives. manifest if the connection closes before a reply arrives.
The panel uses `activate_with_runtime` with a deployment manifest under
`site`, the PHP limits under `php_settings`, and an `allowed_versions`
array of PHP series. An empty array allows all installed stable series.
A successful reply includes the `applied_php_version` and
`applied_php_settings`. To change the active pool, send `set_php_version`
with the same `site` and a `php_version` series. Retry the same request
after an interrupted reply to confirm the applied series.
The socket also accepts a storage request with The socket also accepts a storage request with
`"operation": "measure_storage"` and the deployment manifest under `"site"`. `"operation": "measure_storage"` and the deployment manifest under `"site"`.
A successful reply includes the request identity and `used_bytes`. A successful reply includes the request identity and `used_bytes`.
@@ -21,6 +21,7 @@ from .models import (
HostingMailbox, HostingMailbox,
HostingMailDomain, HostingMailDomain,
SitePhpSettings, SitePhpSettings,
SitePhpVersion,
SiteSFTP, SiteSFTP,
SiteStorageLimit, SiteStorageLimit,
SiteStorageUsage, SiteStorageUsage,
@@ -147,6 +148,7 @@ def cleanup_targets(account):
WebHTTPS.objects.filter(plan__account=account), WebHTTPS.objects.filter(plan__account=account),
SiteSFTP.objects.filter(account=account), SiteSFTP.objects.filter(account=account),
SitePhpSettings.objects.filter(account=account), SitePhpSettings.objects.filter(account=account),
SitePhpVersion.objects.filter(account=account),
SiteStorageLimit.objects.filter(account=account), SiteStorageLimit.objects.filter(account=account),
SiteStorageUsage.objects.filter(account=account), SiteStorageUsage.objects.filter(account=account),
account.backup_jobs.all(), account.backup_jobs.all(),
@@ -0,0 +1,96 @@
from platform import freedesktop_os_release
import django.db.models.deletion
import django.utils.timezone
from django.db import migrations, models
import coulobre.hosting.fields
def record_legacy_php_version(apps, schema_editor):
try:
release = freedesktop_os_release()
except OSError:
release = {}
version = "8.5"
if release.get("ID") == "debian" and release.get("VERSION_ID") == "13":
version = "8.4"
activation = apps.get_model("hosting", "WebActivation")
activation.objects.using(schema_editor.connection.alias).filter(
finished_at__isnull=False, problem="", applied_php_version=""
).update(applied_php_version=version)
class Migration(migrations.Migration):
dependencies = [
("hosting", "0041_audited_support_writes"),
]
operations = [
migrations.AddField(
model_name="hostingplan",
name="php_versions",
field=models.CharField(
blank=True,
help_text=(
"Comma-separated series such as 8.4, 8.5. "
"Leave blank for all installed stable series."
),
max_length=120,
verbose_name="Allowed PHP series",
),
),
migrations.AddField(
model_name="webactivation",
name="applied_php_version",
field=models.CharField(blank=True, max_length=5),
),
migrations.RunPython(
record_legacy_php_version, migrations.RunPython.noop
),
migrations.CreateModel(
name="SitePhpVersion",
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_version", models.CharField(max_length=5)),
(
"applied_version",
models.CharField(blank=True, max_length=5),
),
(
"account",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
related_name="php_version_job",
to="hosting.hostingaccount",
),
),
],
options={
"abstract": False,
},
),
]
+33
View File
@@ -37,6 +37,7 @@ from coulobre.php_pool_settings import (
PhpPoolSettings, PhpPoolSettings,
PhpPoolSettingsError, PhpPoolSettingsError,
) )
from coulobre.php_runtime import validate_php_versions
from coulobre.web_node import MAX_STORAGE_LIMIT_MIB from coulobre.web_node import MAX_STORAGE_LIMIT_MIB
from .fields import DomainNameField from .fields import DomainNameField
@@ -294,6 +295,15 @@ class HostingPlan(models.Model):
php_max_children = php_plan_field( php_max_children = php_plan_field(
"max_children", "Maximum PHP-FPM workers" "max_children", "Maximum PHP-FPM workers"
) )
php_versions = models.CharField(
"Allowed PHP series",
max_length=120,
blank=True,
help_text=(
"Comma-separated series such as 8.4, 8.5. "
"Leave blank for all installed stable series."
),
)
class Meta: class Meta:
ordering = ("name", "pk") ordering = ("name", "pk")
@@ -303,6 +313,10 @@ class HostingPlan(models.Model):
def clean(self): def clean(self):
super().clean() super().clean()
try:
validate_php_versions(self.allowed_php_versions())
except ValueError as error:
raise ValidationError({"php_versions": str(error)}) from error
try: try:
self.get_php_settings() self.get_php_settings()
except PhpPoolSettingsError as error: except PhpPoolSettingsError as error:
@@ -318,6 +332,13 @@ class HostingPlan(models.Model):
} }
) )
def allowed_php_versions(self):
if not self.php_versions:
return ()
return tuple(
version.strip() for version in self.php_versions.split(",")
)
class HostingAccount(models.Model): class HostingAccount(models.Model):
name = models.CharField(max_length=120) name = models.CharField(max_length=120)
@@ -762,6 +783,18 @@ class WebActivation(ProvisioningJob):
) )
php_settings = models.JSONField(null=True, blank=True) php_settings = models.JSONField(null=True, blank=True)
applied_php_version = models.CharField(max_length=5, blank=True)
class SitePhpVersion(ProvisioningJob):
account = models.OneToOneField(
HostingAccount,
on_delete=models.CASCADE,
related_name="php_version_job",
)
domain = DomainNameField(max_length=253)
requested_version = models.CharField(max_length=5)
applied_version = models.CharField(max_length=5, blank=True)
class SitePhpSettings(ProvisioningJob): class SitePhpSettings(ProvisioningJob):
+37 -14
View File
@@ -14,10 +14,13 @@ from coulobre.account_restore_request import (
from coulobre.mail_dns import dkim_key from coulobre.mail_dns import dkim_key
from coulobre.mail_node import MailboxQuotaUpdate, MailboxSigningRequest from coulobre.mail_node import MailboxQuotaUpdate, MailboxSigningRequest
from coulobre.php_pool_settings import PhpPoolSettings from coulobre.php_pool_settings import PhpPoolSettings
from coulobre.php_runtime import validate_php_version
from coulobre.web_node import ( from coulobre.web_node import (
MAX_STORAGE_BYTES, MAX_STORAGE_BYTES,
WebActivationRequest,
WebAliasRequest, WebAliasRequest,
WebPhpRequest, WebPhpRequest,
WebPhpVersionRequest,
WebQuotaRequest, WebQuotaRequest,
WebStorageRequest, WebStorageRequest,
) )
@@ -29,36 +32,56 @@ class NodeReplyError(ValueError):
pass pass
def activate_local_site(site): def activate_local_site(site, php_settings, allowed_versions):
apply_on_local_node( reply = apply_on_local_node(
site, "/run/coulobre-web-apply.sock", "web node", "site" WebActivationRequest(site, php_settings, allowed_versions),
"/run/coulobre-web-apply.sock",
"web node",
"website activation",
) )
try:
version = reply.get("applied_php_version")
validate_php_version(version)
options = PhpPoolSettings.from_manifest(
reply.get("applied_php_settings")
)
except ValueError:
raise NodeReplyError(
"The web node returned invalid PHP configuration."
) from None
return options, version
def activate_local_site_with_php(site, php_settings): def update_local_php_version(site, version):
return send_php_settings(site, php_settings, "activate_with_php_settings") reply = apply_on_local_node(
WebPhpVersionRequest(site, version),
"/run/coulobre-web-apply.sock",
"web node",
"PHP version change",
)
if reply.get("applied_php_version") != version:
raise NodeReplyError("The web node reported a different PHP series.")
return version
def update_local_php_settings(site, 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( reply = apply_on_local_node(
WebPhpRequest(site, php_settings, operation), WebPhpRequest(site, php_settings, "set_php_settings"),
"/run/coulobre-web-apply.sock", "/run/coulobre-web-apply.sock",
"web node", "web node",
"PHP pool settings", "PHP pool settings",
) )
try: try:
return PhpPoolSettings.from_manifest(reply.get("applied_php_settings")) applied = PhpPoolSettings.from_manifest(
reply.get("applied_php_settings")
)
except ValueError: except ValueError:
raise ValueError( raise ValueError(
"The web node returned invalid PHP pool settings." "The web node returned invalid PHP pool settings."
) from None ) from None
if applied != php_settings:
raise ValueError("The web node reported different PHP pool settings.")
return applied
def measure_local_site_storage(site): def measure_local_site_storage(site):
+5
View File
@@ -104,6 +104,11 @@ def queue_web_activation(plan):
WebActivation.objects.requeue(activations) WebActivation.objects.requeue(activations)
def plan_php_versions(account):
plan = account.hosting_plan
return plan.allowed_php_versions() if plan is not None else ()
@transaction.atomic @transaction.atomic
def queue_site_php_settings(account_id, php_settings, *, use_plan=False): def queue_site_php_settings(account_id, php_settings, *, use_plan=False):
account = lock_hosting_account(account_id, customer_id=None) account = lock_hosting_account(account_id, customer_id=None)
+90
View File
@@ -0,0 +1,90 @@
from django import forms
from django.core.exceptions import ValidationError
from django.db import transaction
from coulobre.php_runtime import available_php_versions
from .access import customer_for_user, is_tenant
from .models import SitePhpVersion, WebActivation
from .php_settings import plan_php_versions
from .resource_requests import lock_hosting_account, require_active_services
CHANGE_PHP_VERSION = (
"hosting.view_hostingaccount",
"hosting.change_sitephpversion",
)
class SitePhpVersionForm(forms.Form):
version = forms.ChoiceField(label="PHP series")
def __init__(self, *args, versions, **kwargs):
super().__init__(*args, **kwargs)
self.fields["version"].choices = [
(version, f"PHP {version}") for version in versions
]
def can_change_php_version(request):
user = request.user
return getattr(request, "impersonation", None) is None and (
customer_for_user(user) is not None
or (not is_tenant(user) and user.has_perms(CHANGE_PHP_VERSION))
)
def applied_php_version(account, job):
if job is not None and job.applied_version:
return job.applied_version
return (
active_web_activations(account)
.order_by("-finished_at", "-pk")
.values_list("applied_php_version", flat=True)
.first()
)
def active_web_activations(account):
return WebActivation.objects.filter(
plan__account=account,
plan__primary_domain=account.primary_domain,
finished_at__isnull=False,
problem="",
)
@transaction.atomic
def queue_php_version(account_id, version, *, customer_id=None):
account = lock_hosting_account(account_id, customer_id)
require_active_services(account)
if not active_web_activations(account).exists():
raise ValidationError("Activate the website before changing PHP.")
if version not in available_php_versions(plan_php_versions(account)):
raise ValidationError(
"Select an installed PHP series allowed by the plan."
)
jobs = SitePhpVersion.objects.filter(account=account)
job = jobs.first()
if job is not None and job.finished_at is None:
if (
job.domain == account.primary_domain
and job.requested_version == version
):
return
raise ValidationError("Wait for the current PHP change to finish.")
current = (
job
if job is not None and job.domain == account.primary_domain
else None
)
if version == applied_php_version(account, current) and not (
current is not None and current.problem
):
return
changes = {"domain": account.primary_domain, "requested_version": version}
if job is None:
SitePhpVersion.objects.create(account=account, **changes)
else:
if current is None:
changes["applied_version"] = ""
SitePhpVersion.objects.requeue(jobs, **changes)
+47 -8
View File
@@ -46,6 +46,7 @@ from .models import (
HostingMailDomain, HostingMailDomain,
MailboxProvisioning, MailboxProvisioning,
SitePhpSettings, SitePhpSettings,
SitePhpVersion,
SiteSFTP, SiteSFTP,
SiteStorageLimit, SiteStorageLimit,
SiteStorageUsage, SiteStorageUsage,
@@ -58,7 +59,6 @@ from .models import (
from .node_client import ( from .node_client import (
NodeReplyError, NodeReplyError,
activate_local_site, activate_local_site,
activate_local_site_with_php,
create_local_account_backup, create_local_account_backup,
enable_local_https, enable_local_https,
expire_local_account_backup, expire_local_account_backup,
@@ -72,9 +72,11 @@ from .node_client import (
set_local_site_storage_limit, set_local_site_storage_limit,
update_local_mailbox_quota, update_local_mailbox_quota,
update_local_php_settings, update_local_php_settings,
update_local_php_version,
update_local_sftp, update_local_sftp,
update_local_website_alias, update_local_website_alias,
) )
from .php_settings import plan_php_versions
from .service_changes import apply_service_change from .service_changes import apply_service_change
from .sftp import site_is_active from .sftp import site_is_active
@@ -148,6 +150,9 @@ def dispatch_web_activations():
dispatch_provisioning_jobs( dispatch_provisioning_jobs(
SitePhpSettings, set_site_php_settings, WEB_ACTIVATION_QUEUE SitePhpSettings, set_site_php_settings, WEB_ACTIVATION_QUEUE
) )
dispatch_provisioning_jobs(
SitePhpVersion, set_site_php_version, WEB_ACTIVATION_QUEUE
)
@shared_task @shared_task
@@ -369,7 +374,9 @@ def dispatch_provisioning_jobs(
def activate_web_plan(activation_id): def activate_web_plan(activation_id):
if settings.LOCAL_WEB_ACTIVATION: if settings.LOCAL_WEB_ACTIVATION:
run_provisioning_job( run_provisioning_job(
WebActivation.objects.select_related("plan__account"), WebActivation.objects.select_related(
"plan__account__hosting_plan"
),
activation_id, activation_id,
apply_web_activation, apply_web_activation,
"Could not complete the request to the local web node. " "Could not complete the request to the local web node. "
@@ -385,12 +392,15 @@ def apply_web_activation(activation):
"account domain." "account domain."
) )
site = WebSite(plan.account_id, plan.primary_domain) site = WebSite(plan.account_id, plan.primary_domain)
if activation.php_settings is None: options = (
activate_local_site(site) PhpPoolSettings.from_manifest(activation.php_settings)
return None if activation.php_settings is not None
options = PhpPoolSettings.from_manifest(activation.php_settings) else PhpPoolSettings()
applied = activate_local_site_with_php(site, options) )
return {"php_settings": applied.manifest()} applied, version = activate_local_site(
site, options, plan_php_versions(plan.account)
)
return {"php_settings": applied.manifest(), "applied_php_version": version}
@shared_task(acks_late=True, reject_on_worker_lost=True) @shared_task(acks_late=True, reject_on_worker_lost=True)
@@ -481,6 +491,35 @@ def apply_site_php_settings(job):
} }
@shared_task(acks_late=True, reject_on_worker_lost=True)
def set_site_php_version(job_id):
if settings.LOCAL_WEB_ACTIVATION:
run_provisioning_job(
SitePhpVersion.objects.select_related("account__hosting_plan"),
job_id,
apply_site_php_version,
"Could not confirm the PHP change on the web node. "
"Retry the request.",
)
def apply_site_php_version(job):
account = job.account
if account.retired_at or account.services_suspended:
raise ValueError("The hosting account is suspended or retired.")
if job.domain != account.primary_domain or not site_is_active(account):
raise ValueError("Activate the current website before changing PHP.")
versions = plan_php_versions(account)
if versions and job.requested_version not in versions:
raise ValueError("The hosting plan no longer allows this PHP series.")
site = WebSite(job.account_id, job.domain)
return {
"applied_version": update_local_php_version(
site, job.requested_version
)
}
@shared_task(acks_late=True, reject_on_worker_lost=True) @shared_task(acks_late=True, reject_on_worker_lost=True)
def measure_site_storage(request_id): def measure_site_storage(request_id):
if settings.LOCAL_WEB_ACTIVATION: if settings.LOCAL_WEB_ACTIVATION:
@@ -12,5 +12,15 @@
<a class="button secondary" href="{% url 'panel:site_php_settings' account.pk %}">Change PHP settings</a> <a class="button secondary" href="{% url 'panel:site_php_settings' account.pk %}">Change PHP settings</a>
{% endif %} {% endif %}
</header> </header>
{% if website_php_version %}<p>Active version <strong>PHP {{ website_php_version }}</strong></p>{% endif %}
{% if website_php_version_job and website_php_version_job.finished_at is None %}
<p>Changing to PHP {{ website_php_version_job.requested_version }}. Reload this page to check progress.</p>
{% elif website_php_version_job.problem %}
<p>The change to PHP {{ website_php_version_job.requested_version }} needs attention.</p>
{% if is_operator %}<p>{{ website_php_version_job.problem }}</p>{% endif %}
{% endif %}
{% if can_change_php_version %}
<a class="button secondary" href="{% url 'panel:site_php_version' account.pk %}">Change PHP version</a>
{% endif %}
{% include "hosting/php_setting_values.html" with limits=website_php_settings only %} {% include "hosting/php_setting_values.html" with limits=website_php_settings only %}
</section> </section>
@@ -0,0 +1,19 @@
{% extends "hosting/base.html" %}
{% block title %}Change PHP version · Coulobre Panel{% endblock %}
{% block content %}
<a class="back-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
<header class="page-heading">
<h1>Change PHP version</h1>
{% if current_version %}<p>Current version for {{ account.primary_domain }} is PHP {{ current_version }}.</p>{% endif %}
</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 PHP version</button>
<a class="button secondary" href="{{ account.get_absolute_url }}">Cancel</a>
</div>
</form>
</section>
{% endblock %}
+15 -12
View File
@@ -9,7 +9,7 @@ from django.urls import reverse
from django.utils import timezone from django.utils import timezone
from coulobre.php_pool_settings import PhpPoolSettings from coulobre.php_pool_settings import PhpPoolSettings
from coulobre.php_runtime import PHP_FPM_BINARY, PHP_SERVICE from coulobre.php_runtime import DEFAULT_PHP_RUNTIME
from coulobre.web_node import WebPhpRequest, WebSite, parse_web_request from coulobre.web_node import WebPhpRequest, WebSite, parse_web_request
from coulobre.web_node_apply import ( from coulobre.web_node_apply import (
SitePaths, SitePaths,
@@ -91,11 +91,11 @@ class PanelPhpSettingsTests(TestCase):
) )
self.client.post(activation_url) self.client.post(activation_url)
with patch( with patch(
"coulobre.hosting.tasks.activate_local_site_with_php", "coulobre.hosting.tasks.activate_local_site",
return_value=options, return_value=(options, "8.5"),
) as activate: ) as activate:
activate_web_plan(job.pk) activate_web_plan(job.pk)
activate.assert_called_once_with(self.site, options) activate.assert_called_once_with(self.site, options, ())
self.assertContains(self.client.get(self.account_url), "256 MiB") self.assertContains(self.client.get(self.account_url), "256 MiB")
self.assertEqual( self.assertEqual(
self.client.get(self.url).context["form"].initial, self.client.get(self.url).context["form"].initial,
@@ -258,10 +258,7 @@ class NativePhpSettingsTests(SimpleTestCase):
self.assertIn("request_terminate_timeout = 35s", pool) self.assertIn("request_terminate_timeout = 35s", pool)
applied = install_configurations( applied = install_configurations(
self.site, self.site,
self.paths.apache, self.paths,
self.paths.enabled,
self.paths.pool,
self.paths.socket,
php_settings=PhpPoolSettings(max_children=5), php_settings=PhpPoolSettings(max_children=5),
) )
self.assertEqual(applied, self.options) self.assertEqual(applied, self.options)
@@ -284,9 +281,13 @@ class NativePhpSettingsTests(SimpleTestCase):
self.assertEqual( self.assertEqual(
self.runner.call_args_list, self.runner.call_args_list,
[ [
call(PHP_FPM_BINARY, "--test"), call(DEFAULT_PHP_RUNTIME.binary, "--test"),
call("/usr/sbin/service", PHP_SERVICE, "reload"), call(
call("/usr/sbin/service", PHP_SERVICE, "reload"), "/usr/sbin/service", DEFAULT_PHP_RUNTIME.service, "reload"
),
call(
"/usr/sbin/service", DEFAULT_PHP_RUNTIME.service, "reload"
),
], ],
) )
self.ready.assert_called_once_with(self.paths.socket) self.ready.assert_called_once_with(self.paths.socket)
@@ -296,5 +297,7 @@ class NativePhpSettingsTests(SimpleTestCase):
): ):
self.paths.pool.write_text(self.default_pool, encoding="utf-8") self.paths.pool.write_text(self.default_pool, encoding="utf-8")
change_php_pool(self.paths, self.default_pool, self.default_pool) change_php_pool(self.paths, self.default_pool, self.default_pool)
self.runner.assert_any_call("/usr/sbin/service", PHP_SERVICE, "reload") self.runner.assert_any_call(
"/usr/sbin/service", DEFAULT_PHP_RUNTIME.service, "reload"
)
self.ready.assert_called_once_with(self.paths.socket) self.ready.assert_called_once_with(self.paths.socket)
+214
View File
@@ -0,0 +1,214 @@
import os
from dataclasses import replace
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.test import SimpleTestCase, TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from coulobre import web_node_runtime
from coulobre.php_pool_settings import PhpPoolSettings
from coulobre.php_runtime import PhpRuntime, available_php_versions
from coulobre.web_node import WebPhpVersionRequest, WebSite, parse_web_request
from coulobre.web_node_apply import SitePaths
from .models import (
Customer,
HostingAccount,
HostingPlan,
SitePhpVersion,
WebActivation,
WebProvisioningPlan,
)
from .tasks import (
WEB_ACTIVATION_QUEUE,
dispatch_web_activations,
set_site_php_version,
)
@override_settings(LOCAL_WEB_ACTIVATION=True)
class PanelPhpVersionTests(TestCase):
@classmethod
def setUpTestData(cls):
users = get_user_model().objects
cls.customer = Customer.objects.create(user=users.create_user("owner"))
cls.outsider = Customer.objects.create(user=users.create_user("other"))
plan = HostingPlan.objects.create(name="PHP", php_versions="8.4, 8.5")
cls.account = HostingAccount.objects.create(
name="Example",
primary_domain="example.net",
customer=cls.customer,
hosting_plan=plan,
)
cls.site = WebSite(cls.account.pk, cls.account.primary_domain)
preview = WebProvisioningPlan.objects.create(
account=cls.account,
primary_domain=cls.site.domain,
completed_at=timezone.now(),
apache_config=cls.site.render("apache"),
)
WebActivation.objects.create(
plan=preview, finished_at=timezone.now(), applied_php_version="8.4"
)
def setUp(self):
self.enterContext(
patch(
"coulobre.php_runtime.installed_php_versions",
return_value=("8.6", "8.5", "8.4"),
)
)
self.client.force_login(self.customer.user)
self.url = reverse("panel:site_php_version", args=[self.account.pk])
def test_customer_can_switch_only_their_site_to_a_plan_version(self):
self.assertContains(self.client.get(self.url), "PHP 8.4")
self.assertNotContains(self.client.get(self.url), "PHP 8.6")
self.assertContains(
self.client.post(self.url, {"version": "8.6"}), "valid choice"
)
self.client.force_login(self.outsider.user)
self.assertEqual(
self.client.post(self.url, {"version": "8.5"}).status_code, 404
)
self.assertFalse(SitePhpVersion.objects.exists())
self.client.force_login(self.customer.user)
self.assertRedirects(
self.client.post(self.url, {"version": "8.5"}),
self.account.get_absolute_url(),
)
job = SitePhpVersion.objects.get()
self.assertEqual(job.applied_version, "")
with patch.object(set_site_php_version, "apply_async") as publish:
dispatch_web_activations()
publish.assert_called_once_with(
args=[job.pk], queue=WEB_ACTIVATION_QUEUE, retry=False
)
with patch(
"coulobre.hosting.tasks.update_local_php_version",
return_value="8.5",
) as change:
set_site_php_version(job.pk)
change.assert_called_once_with(self.site, "8.5")
job.refresh_from_db()
self.assertEqual(job.applied_version, "8.5")
self.assertContains(
self.client.get(self.account.get_absolute_url()), "PHP 8.5"
)
def test_worker_rechecks_plan_and_failed_job_keeps_previous_version(self):
self.client.post(self.url, {"version": "8.5"})
job = SitePhpVersion.objects.get()
HostingPlan.objects.filter(pk=self.account.hosting_plan_id).update(
php_versions="8.4"
)
with patch(
"coulobre.hosting.tasks.update_local_php_version"
) as change:
set_site_php_version(job.pk)
change.assert_not_called()
job.refresh_from_db()
self.assertEqual(job.state, "failed")
self.assertEqual(job.applied_version, "")
self.assertContains(
self.client.get(self.account.get_absolute_url()), "PHP 8.4"
)
class PhpRuntimeInventoryTests(SimpleTestCase):
def test_apt_inventory_uses_installed_stable_series_in_numeric_order(self):
with patch("coulobre.php_runtime.subprocess.run") as command:
command.return_value.stdout = (
"php8.4-fpm\tinstalled\t8.4.28-1~deb13u1\n"
"php8.6-fpm\tinstalled\t1:8.6.0-3+debsuryorg13.1+1\n"
"php8.7-fpm\tinstalled\t8.7.0~rc1-1\n"
"php8.5-fpm\tconfig-files\t8.5.13-3\n"
"php8.10-fpm\tinstalled\t8.10.2-1\n"
)
self.assertEqual(available_php_versions(), ("8.10", "8.6", "8.4"))
self.assertEqual(available_php_versions(("8.4", "8.5")), ("8.4",))
def test_switch_request_only_accepts_a_php_series(self):
site = WebSite(42, "example.net")
request = WebPhpVersionRequest(site, "8.5")
self.assertEqual(parse_web_request(request.manifest()), request)
for invalid in ("8.5.0", "8.5/../", None, 8.5):
with self.subTest(invalid=invalid), self.assertRaises(ValueError):
parse_web_request(
request.manifest() | {"php_version": invalid}
)
class WebPhpSwitchTests(SimpleTestCase):
def setUp(self):
directory = Path(self.enterContext(TemporaryDirectory()))
self.site = WebSite(42, "example.net")
self.current = SitePaths(
directory,
directory / "site.conf",
directory / "enabled.conf",
directory / "8.4.conf",
directory / "8.4.sock",
PhpRuntime("8.4"),
routed=True,
)
self.target = replace(
self.current,
pool=directory / "8.5.conf",
socket=directory / "8.5.sock",
runtime=PhpRuntime("8.5"),
)
self.settings = PhpPoolSettings(memory_limit_mib=192)
self.original = self.site.render(
"php-fpm",
php_settings=self.settings,
socket_path=self.current.socket,
)
self.current.pool.write_text(self.original)
self.current.route.symlink_to(self.current.socket)
self.runner = self.enterContext(patch("coulobre.web_node_apply.run"))
self.enterContext(
patch(
"coulobre.web_node_php.read_root_file",
side_effect=Path.read_text,
)
)
self.ready = self.enterContext(
patch("coulobre.web_node_apply.wait_for_socket")
)
def test_target_must_be_ready_before_switching_the_shared_socket(self):
def listen(socket):
self.assertEqual(socket, self.target.socket)
self.assertEqual(
self.current.route.readlink(), self.current.socket
)
self.ready.side_effect = listen
web_node_runtime.switch_pool(self.site, self.current, self.target)
self.assertEqual(self.current.route.readlink(), self.target.socket)
self.assertFalse(self.current.pool.exists())
self.assertIn(
"php_admin_value[memory_limit] = 192M",
self.target.pool.read_text(),
)
def test_failure_reinstates_the_old_pool_if_the_route_changed(self):
self.runner.side_effect = [
"",
"",
ValueError("Cannot unload"),
"",
"",
"",
"",
]
with self.assertRaisesMessage(ValueError, "Cannot unload"):
web_node_runtime.switch_pool(self.site, self.current, self.target)
self.assertEqual(self.current.route.readlink(), self.current.socket)
self.assertEqual(self.current.pool.read_text(), self.original)
self.assertFalse(os.path.lexists(self.target.pool))
+22 -9
View File
@@ -9,7 +9,8 @@ from django.test import SimpleTestCase, TestCase, override_settings
from django.urls import reverse from django.urls import reverse
from django.utils import timezone from django.utils import timezone
from coulobre.web_node import WebSite from coulobre.php_pool_settings import PhpPoolSettings
from coulobre.web_node import WebActivationRequest, WebSite
from .models import ( from .models import (
HostingAccount, HostingAccount,
@@ -65,10 +66,15 @@ class WebActivationTests(TestCase):
args=[activation.pk], queue="coulobre-web-activation", retry=False args=[activation.pk], queue="coulobre-web-activation", retry=False
) )
with patch("coulobre.hosting.tasks.activate_local_site") as apply: with patch(
"coulobre.hosting.tasks.activate_local_site",
return_value=(PhpPoolSettings(), "8.5"),
) as apply:
activate_web_plan.run(activation.pk) activate_web_plan.run(activation.pk)
activate_web_plan.run(activation.pk) activate_web_plan.run(activation.pk)
apply.assert_called_once_with(WebSite(self.account.pk, "site.example")) apply.assert_called_once_with(
WebSite(self.account.pk, "site.example"), PhpPoolSettings(), ()
)
self.assertContains(self.client.get(self.detail), "Configured") self.assertContains(self.client.get(self.detail), "Configured")
self.assertRedirects(self.client.post(self.url), self.detail) self.assertRedirects(self.client.post(self.url), self.detail)
activation.refresh_from_db() activation.refresh_from_db()
@@ -125,7 +131,10 @@ class WebActivationTests(TestCase):
) )
self.assertEqual(self.client.post(self.url).status_code, 409) self.assertEqual(self.client.post(self.url).status_code, 409)
with patch("coulobre.hosting.tasks.activate_local_site") as apply: with patch(
"coulobre.hosting.tasks.activate_local_site",
return_value=(PhpPoolSettings(), "8.5"),
) as apply:
activate_web_plan.run(activation.pk) activate_web_plan.run(activation.pk)
apply.assert_not_called() apply.assert_not_called()
activation.refresh_from_db() activation.refresh_from_db()
@@ -150,7 +159,10 @@ class WebActivationTests(TestCase):
activation = WebActivation.objects.create( activation = WebActivation.objects.create(
plan=self.plan, started_at=timezone.now() plan=self.plan, started_at=timezone.now()
) )
with patch("coulobre.hosting.tasks.activate_local_site") as apply: with patch(
"coulobre.hosting.tasks.activate_local_site",
return_value=(PhpPoolSettings(), "8.5"),
) as apply:
activate_web_plan.run(activation.pk) activate_web_plan.run(activation.pk)
apply.assert_not_called() apply.assert_not_called()
WebActivation.objects.filter(pk=activation.pk).update( WebActivation.objects.filter(pk=activation.pk).update(
@@ -165,8 +177,9 @@ class WebActivationTests(TestCase):
class WebActivationReplyTests(SimpleTestCase): class WebActivationReplyTests(SimpleTestCase):
def test_mismatched_node_identity_cannot_complete_activation(self): def test_mismatched_node_identity_cannot_complete_activation(self):
site = WebSite(1, "site.example") site = WebSite(1, "site.example")
reply = site.manifest() | { request = WebActivationRequest(site, PhpPoolSettings(), ())
"account_id": 2, reply = request.manifest() | {
"site": WebSite(2, site.domain).manifest(),
"state": "configured", "state": "configured",
"problem": None, "problem": None,
} }
@@ -176,6 +189,6 @@ class WebActivationReplyTests(SimpleTestCase):
json.dumps(reply).encode() json.dumps(reply).encode()
) )
with self.assertRaisesMessage( with self.assertRaisesMessage(
ValueError, "invalid response for this site" ValueError, "invalid response for this website activation"
): ):
activate_local_site(site) activate_local_site(site, PhpPoolSettings(), ())
+21 -6
View File
@@ -5,9 +5,13 @@ from unittest.mock import call, patch
from django.test import SimpleTestCase from django.test import SimpleTestCase
from coulobre.php_runtime import PHP_FPM_BINARY, PHP_SERVICE, php_fpm_version from coulobre.php_runtime import DEFAULT_PHP_RUNTIME, php_fpm_version
from coulobre.web_node import WebSite from coulobre.web_node import WebSite
from coulobre.web_node_apply import install_configurations, site_status from coulobre.web_node_apply import (
SitePaths,
install_configurations,
site_status,
)
class PhpRuntimeTests(SimpleTestCase): class PhpRuntimeTests(SimpleTestCase):
@@ -48,7 +52,14 @@ class WebNodeConfigurationTests(SimpleTestCase):
def install(self): def install(self):
install_configurations( install_configurations(
self.site, self.apache, self.enabled, self.pool, self.socket self.site,
SitePaths(
self.pool.parent,
self.apache,
self.enabled,
self.pool,
self.socket,
),
) )
def test_install_validates_both_services_before_reloading(self): def test_install_validates_both_services_before_reloading(self):
@@ -60,9 +71,11 @@ class WebNodeConfigurationTests(SimpleTestCase):
self.assertEqual( self.assertEqual(
self.runner.call_args_list, self.runner.call_args_list,
[ [
call(PHP_FPM_BINARY, "--test"), call(DEFAULT_PHP_RUNTIME.binary, "--test"),
call("/usr/sbin/apache2ctl", "configtest"), call("/usr/sbin/apache2ctl", "configtest"),
call("/usr/sbin/service", PHP_SERVICE, "reload"), call(
"/usr/sbin/service", DEFAULT_PHP_RUNTIME.service, "reload"
),
call("/usr/sbin/service", "apache2", "reload"), call("/usr/sbin/service", "apache2", "reload"),
], ],
) )
@@ -88,7 +101,9 @@ class WebNodeConfigurationTests(SimpleTestCase):
self.assertEqual( self.assertEqual(
self.runner.call_args_list[-2:], self.runner.call_args_list[-2:],
[ [
call("/usr/sbin/service", PHP_SERVICE, "reload"), call(
"/usr/sbin/service", DEFAULT_PHP_RUNTIME.service, "reload"
),
call("/usr/sbin/service", "apache2", "reload"), call("/usr/sbin/service", "apache2", "reload"),
], ],
) )
+4 -3
View File
@@ -29,7 +29,7 @@ class WebNodeTLSTests(SimpleTestCase):
self.http.write_text(self.site.render("apache"), encoding="utf-8") self.http.write_text(self.site.render("apache"), encoding="utf-8")
self.tls = self.http.with_name("coulobre-42-https.conf") self.tls = self.http.with_name("coulobre-42-https.conf")
self.enabled = http_enabled.with_name(self.tls.name) self.enabled = http_enabled.with_name(self.tls.name)
paths = SitePaths( self.paths = SitePaths(
directory / "account", directory / "account",
self.http, self.http,
http_enabled, http_enabled,
@@ -65,7 +65,8 @@ class WebNodeTLSTests(SimpleTestCase):
) )
self.enterContext( self.enterContext(
patch( patch(
"coulobre.web_node_tls.SitePaths.for_site", return_value=paths "coulobre.web_node_tls.SitePaths.for_site",
return_value=self.paths,
) )
) )
self.enterContext( self.enterContext(
@@ -110,7 +111,7 @@ class WebNodeTLSTests(SimpleTestCase):
content = self.tls.read_text() content = self.tls.read_text()
self.assertIn("<VirtualHost *:443>", content) self.assertIn("<VirtualHost *:443>", content)
self.assertIn('DocumentRoot "/srv/coulobre/web/42/public"', content) self.assertIn('DocumentRoot "/srv/coulobre/web/42/public"', content)
self.assertIn("proxy:unix:/run/php/coulobre-42.sock", content) self.assertIn(f"proxy:unix:{self.paths.apache_socket}", content)
self.assertIn( self.assertIn(
f'SSLCertificateFile "{self.live}/fullchain.pem"', content f'SSLCertificateFile "{self.live}/fullchain.pem"', content
) )
+5
View File
@@ -52,6 +52,11 @@ urlpatterns = [
views.SitePhpSettingsEdit.as_view(), views.SitePhpSettingsEdit.as_view(),
name="site_php_settings", name="site_php_settings",
), ),
path(
"accounts/<int:pk>/php-version/",
views.SitePhpVersionEdit.as_view(),
name="site_php_version",
),
path( path(
"accounts/<int:pk>/aliases/new/", "accounts/<int:pk>/aliases/new/",
views.WebsiteAliasCreate.as_view(), views.WebsiteAliasCreate.as_view(),
+89
View File
@@ -31,6 +31,7 @@ from django.views.generic.detail import SingleObjectMixin
from coulobre.dns_node import MAX_SOA_SERIAL from coulobre.dns_node import MAX_SOA_SERIAL
from coulobre.mail_node import INVALID_LOCAL_PART from coulobre.mail_node import INVALID_LOCAL_PART
from coulobre.php_runtime import available_php_versions
from coulobre.sftp_keys import public_key_fingerprint from coulobre.sftp_keys import public_key_fingerprint
from coulobre.web_node import WebSite from coulobre.web_node import WebSite
@@ -98,10 +99,17 @@ from .php_settings import (
SitePhpSettingsForm, SitePhpSettingsForm,
last_applied_php_settings, last_applied_php_settings,
plan_php_settings, plan_php_settings,
plan_php_versions,
queue_site_php_settings, queue_site_php_settings,
queue_web_activation, queue_web_activation,
settings_from_form, settings_from_form,
) )
from .php_versions import (
SitePhpVersionForm,
applied_php_version,
can_change_php_version,
queue_php_version,
)
from .phpmyadmin import phpmyadmin_available from .phpmyadmin import phpmyadmin_available
from .reseller_accounts import create_reseller_account, save_operator_account from .reseller_accounts import create_reseller_account, save_operator_account
from .resource_requests import ( from .resource_requests import (
@@ -417,6 +425,24 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
context["can_change_php_settings"] = ( context["can_change_php_settings"] = (
not tenant and user.has_perms(CHANGE_SITE_PHP_SETTINGS) not tenant and user.has_perms(CHANGE_SITE_PHP_SETTINGS)
) )
version_job = getattr(self.object, "php_version_job", None)
if (
version_job is not None
and version_job.domain != self.object.primary_domain
):
version_job = None
context["website_php_version"] = applied_php_version(
self.object, version_job
)
context["website_php_version_job"] = version_job
context["can_change_php_version"] = (
can_change_php_version(self.request)
and not self.object.services_suspended
and (
version_job is None
or version_job.finished_at is not None
)
)
context["website_aliases"] = ( context["website_aliases"] = (
WebsiteAlias.objects.filter(reservation__account=self.object) WebsiteAlias.objects.filter(reservation__account=self.object)
.select_related("reservation") .select_related("reservation")
@@ -653,6 +679,68 @@ class SitePhpSettingsEdit(
return redirect(self.account) return redirect(self.account)
class SitePhpVersionEdit(PermissionRequiredMixin, FormView):
form_class = SitePhpVersionForm
template_name = "hosting/site_php_version_form.html"
def dispatch(self, request, *args, **kwargs):
if not settings.LOCAL_WEB_ACTIVATION:
raise Http404
return super().dispatch(request, *args, **kwargs)
def has_permission(self):
return can_change_php_version(self.request)
@cached_property
def account(self):
accounts = HostingAccount.objects.select_related(
"hosting_plan", "php_version_job"
)
customer = customer_for_user(self.request.user)
if customer is not None:
accounts = accounts.filter(customer=customer)
return get_object_or_404(
accounts, pk=self.kwargs["pk"], retired_at__isnull=True
)
@cached_property
def version(self):
job = getattr(self.account, "php_version_job", None)
if job is not None and job.domain != self.account.primary_domain:
job = None
return applied_php_version(self.account, job)
def get_initial(self):
return {"version": self.version}
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs["versions"] = available_php_versions(
plan_php_versions(self.account)
)
return kwargs
def get_context_data(self, **kwargs):
return super().get_context_data(
account=self.account, current_version=self.version, **kwargs
)
def form_valid(self, form):
customer = customer_for_user(self.request.user)
try:
queue_php_version(
self.account.pk,
form.cleaned_data["version"],
customer_id=customer.pk if customer is not None else None,
)
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): class WebsiteAliasEditor(OperatorOnlyMixin, PermissionRequiredMixin, FormView):
permission_required = MANAGE_WEBSITE_ALIASES permission_required = MANAGE_WEBSITE_ALIASES
template_name = "hosting/website_alias_form.html" template_name = "hosting/website_alias_form.html"
@@ -1777,6 +1865,7 @@ class HostingPlanEditor:
"php_upload_limit_mib", "php_upload_limit_mib",
"php_request_timeout_seconds", "php_request_timeout_seconds",
"php_max_children", "php_max_children",
"php_versions",
) )
template_name = "hosting/hosting_plan_form.html" template_name = "hosting/hosting_plan_form.html"
success_url = reverse_lazy("panel:hosting_plans") success_url = reverse_lazy("panel:hosting_plans")
+16
View File
@@ -1,6 +1,7 @@
import os import os
import stat import stat
from contextlib import contextmanager from contextlib import contextmanager
from pathlib import Path
from tempfile import NamedTemporaryFile from tempfile import NamedTemporaryFile
@@ -52,6 +53,21 @@ def write_new_file(path, content, *, mode, group=None):
os.link(staged.name, path) os.link(staged.name, path)
def replace_configuration(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)
@contextmanager @contextmanager
def locked_root_directory(path): def locked_root_directory(path):
import fcntl import fcntl
+87 -4
View File
@@ -1,6 +1,92 @@
import re
import subprocess
from dataclasses import dataclass
from pathlib import Path from pathlib import Path
from platform import freedesktop_os_release from platform import freedesktop_os_release
PHP_SERIES = re.compile(r"[1-9][0-9]?\.(?:0|[1-9][0-9]?)")
def validate_php_version(version):
if not isinstance(version, str) or not PHP_SERIES.fullmatch(version):
raise ValueError("Enter a PHP series such as 8.5.")
def validate_php_versions(versions):
if not isinstance(versions, (list, tuple)) or len(versions) > 20:
raise ValueError("Enter a list of up to 20 PHP series.")
for version in versions:
validate_php_version(version)
if len(set(versions)) != len(versions):
raise ValueError("Enter each PHP series only once.")
@dataclass(frozen=True)
class PhpRuntime:
version: str
def __post_init__(self):
validate_php_version(self.version)
@property
def service(self):
return f"php{self.version}-fpm"
@property
def binary(self):
return f"/usr/sbin/php-fpm{self.version}"
@property
def pools(self):
return Path(f"/etc/php/{self.version}/fpm/pool.d")
def installed_php_versions():
try:
result = subprocess.run(
(
"/usr/bin/dpkg-query",
"--show",
"--showformat=${Package}\t${db:Status-Status}\t${Version}\n",
"php*-fpm",
),
capture_output=True,
text=True,
timeout=3,
)
except (OSError, subprocess.TimeoutExpired):
return ()
versions = []
for line in result.stdout.splitlines():
fields = line.split("\t")
if len(fields) != 3:
continue
package, state, release = fields
version = package.removeprefix("php").removesuffix("-fpm")
if (
state == "installed"
and package == f"php{version}-fpm"
and PHP_SERIES.fullmatch(version)
and re.match(
rf"(?:\d+:)?{re.escape(version)}\.\d+(?:[-+]|$)", release
)
):
versions.append(version)
return tuple(sorted(set(versions), key=php_version_order, reverse=True))
def php_version_order(version):
return tuple(map(int, version.split(".")))
def available_php_versions(allowed=()):
return tuple(
version
for version in installed_php_versions()
if not allowed or version in allowed
)
def php_fpm_version(): def php_fpm_version():
try: try:
@@ -12,7 +98,4 @@ def php_fpm_version():
return "8.5" return "8.5"
PHP_VERSION = php_fpm_version() DEFAULT_PHP_RUNTIME = PhpRuntime(php_fpm_version())
PHP_SERVICE = f"php{PHP_VERSION}-fpm"
PHP_FPM_BINARY = f"/usr/sbin/php-fpm{PHP_VERSION}"
PHP_POOL_DIRECTORY = Path(f"/etc/php/{PHP_VERSION}/fpm/pool.d")
+29 -3
View File
@@ -4,14 +4,18 @@ import subprocess
from dataclasses import dataclass from dataclasses import dataclass
from enum import StrEnum from enum import StrEnum
from .php_runtime import PHP_SERVICE, PHP_VERSION from .php_runtime import (
DEFAULT_PHP_RUNTIME,
PhpRuntime,
installed_php_versions,
)
SERVICES = { SERVICES = {
"panel": ("Coulobre Panel", "coulobre-panel.service"), "panel": ("Coulobre Panel", "coulobre-panel.service"),
"worker": ("Coulobre worker", "coulobre-worker.service"), "worker": ("Coulobre worker", "coulobre-worker.service"),
"scheduler": ("Coulobre scheduler", "coulobre-beat.service"), "scheduler": ("Coulobre scheduler", "coulobre-beat.service"),
"apache": ("Apache", "apache2.service"), "apache": ("Apache", "apache2.service"),
"php-fpm": (f"PHP {PHP_VERSION} FPM", f"{PHP_SERVICE}.service"), "php-fpm": ("PHP-FPM", f"{DEFAULT_PHP_RUNTIME.service}.service"),
"mariadb": ("MariaDB", "mariadb.service"), "mariadb": ("MariaDB", "mariadb.service"),
"rabbitmq": ("RabbitMQ", "rabbitmq-server.service"), "rabbitmq": ("RabbitMQ", "rabbitmq-server.service"),
"bind9": ("BIND9", "named.service"), "bind9": ("BIND9", "named.service"),
@@ -106,7 +110,29 @@ def unique_health_keys(pairs):
def check_unit(service): def check_unit(service):
unit = SERVICES[service][1] if service == "php-fpm":
versions = installed_php_versions()
if versions:
results = {
read_unit(f"{PhpRuntime(version).service}.service")
for version in versions
}
return next(
result
for result in (
HealthResult.FAILED,
HealthResult.QUERY_FAILED,
HealthResult.MISSING,
HealthResult.INACTIVE,
HealthResult.TRANSITIONING,
HealthResult.ACTIVE,
)
if result in results
)
return read_unit(SERVICES[service][1])
def read_unit(unit):
try: try:
reply = subprocess.run( reply = subprocess.run(
( (
+93 -3
View File
@@ -12,6 +12,7 @@ from .domain_names import canonical_domain
from .node_requests import serve_apply_request from .node_requests import serve_apply_request
from .node_retirement import RetirementRequest, parse_retirement from .node_retirement import RetirementRequest, parse_retirement
from .php_pool_settings import PhpPoolSettings from .php_pool_settings import PhpPoolSettings
from .php_runtime import validate_php_version, validate_php_versions
from .service_access import ServiceAccessRequest, parse_service_request from .service_access import ServiceAccessRequest, parse_service_request
MANIFEST_VERSION = 1 MANIFEST_VERSION = 1
@@ -80,11 +81,14 @@ class WebSite:
tls_settings="", tls_settings="",
server_name=None, server_name=None,
php_settings=None, php_settings=None,
socket_path=None,
): ):
resource = files("coulobre.hosting").joinpath( resource = files("coulobre.hosting").joinpath(
"templates", "hosting", CONFIGURATIONS[configuration] "templates", "hosting", CONFIGURATIONS[configuration]
) )
values = self.configuration() values = self.configuration()
if socket_path is not None:
values["socket_path"] = socket_path
if server_name is not None: if server_name is not None:
values["domain"] = canonical_domain(server_name) values["domain"] = canonical_domain(server_name)
template = Template(resource.read_text(encoding="utf-8")) template = Template(resource.read_text(encoding="utf-8"))
@@ -135,12 +139,15 @@ class WebAlias:
"domain": self.domain, "domain": self.domain,
} }
def render(self, configuration, *, port=80, tls_settings=""): def render(
self, configuration, *, port=80, tls_settings="", socket_path=None
):
return self.site.render( return self.site.render(
configuration, configuration,
port=port, port=port,
tls_settings=tls_settings, tls_settings=tls_settings,
server_name=self.domain, server_name=self.domain,
socket_path=socket_path,
) )
@@ -220,6 +227,30 @@ def parse_web_request(data):
def parse_web_apply(data): def parse_web_apply(data):
if (
isinstance(data, dict)
and data.get("operation") == "activate_with_runtime"
):
if data.keys() != {
"operation",
"site",
"php_settings",
"allowed_versions",
}:
raise ValueError(
"Expected a website activation with a PHP runtime."
)
return WebActivationRequest(
WebSite.from_manifest(data["site"]),
PhpPoolSettings.from_manifest(data["php_settings"]),
data["allowed_versions"],
)
if isinstance(data, dict) and data.get("operation") == "set_php_version":
if data.keys() != {"operation", "site", "php_version"}:
raise ValueError("Expected a website and a PHP series.")
return WebPhpVersionRequest(
WebSite.from_manifest(data["site"]), data["php_version"]
)
if ( if (
isinstance(data, dict) isinstance(data, dict)
and data.keys() == {"operation", "site"} and data.keys() == {"operation", "site"}
@@ -251,7 +282,61 @@ def parse_web_apply(data):
return parse_service_request(data, WebSite.from_manifest) return parse_service_request(data, WebSite.from_manifest)
@dataclass(frozen=True)
class WebActivationRequest:
site: WebSite
php_settings: PhpPoolSettings
allowed_versions: tuple[str, ...]
def __post_init__(self):
validate_php_versions(self.allowed_versions)
object.__setattr__(
self, "allowed_versions", tuple(self.allowed_versions)
)
def manifest(self):
return {
"operation": "activate_with_runtime",
"site": self.site.manifest(),
"php_settings": self.php_settings.manifest(),
"allowed_versions": list(self.allowed_versions),
}
@dataclass(frozen=True)
class WebPhpVersionRequest:
site: WebSite
version: str
def __post_init__(self):
validate_php_version(self.version)
def manifest(self):
return {
"operation": "set_php_version",
"site": self.site.manifest(),
"php_version": self.version,
}
def apply_web_request(request): def apply_web_request(request):
if isinstance(request, WebActivationRequest):
from .web_node_apply import apply_site_with_runtime
settings, version = apply_site_with_runtime(
request.site,
php_settings=request.php_settings,
allowed=request.allowed_versions,
)
return {
"applied_php_settings": settings.manifest(),
"applied_php_version": version,
}
if isinstance(request, WebPhpVersionRequest):
from .web_node_runtime import switch_php_version
version = switch_php_version(request.site, request.version)
return {"applied_php_version": version}
if isinstance(request, RetirementRequest): if isinstance(request, RetirementRequest):
from .web_node_retirement import retire_site from .web_node_retirement import retire_site
@@ -312,6 +397,7 @@ def main(argv=None):
render.add_argument("configuration", choices=CONFIGURATIONS) render.add_argument("configuration", choices=CONFIGURATIONS)
apply = commands.add_parser("apply", help="Install a site on a web node.") apply = commands.add_parser("apply", help="Install a site on a web node.")
apply.add_argument("manifest", type=Path) apply.add_argument("manifest", type=Path)
apply.add_argument("--php-version", help="Select the initial PHP series.")
commands.add_parser( commands.add_parser(
"apply-request", "apply-request",
help="Apply one site manifest from standard input and report JSON.", help="Apply one site manifest from standard input and report JSON.",
@@ -438,9 +524,13 @@ def main(argv=None):
payload = json.loads(args.manifest.read_text(encoding="utf-8")) payload = json.loads(args.manifest.read_text(encoding="utf-8"))
site = WebSite.from_manifest(payload) site = WebSite.from_manifest(payload)
if args.command == "apply": if args.command == "apply":
from .web_node_apply import apply_site from .web_node_apply import apply_site_with_runtime
apply_site(site) if args.php_version is not None:
validate_php_version(args.php_version)
apply_site_with_runtime(
site, allowed=(args.php_version,) if args.php_version else ()
)
print(f"Applied web configuration for {site.domain}.") print(f"Applied web configuration for {site.domain}.")
elif args.command == "status": elif args.command == "status":
from .web_node_apply import site_status from .web_node_apply import site_status
+23 -8
View File
@@ -97,11 +97,16 @@ def activate_alias(alias):
raise ValueError("Apply the website alias as root on the web node.") raise ValueError("Apply the website alias as root on the web node.")
with web.locked_web_node(fcntl.LOCK_EX): with web.locked_web_node(fcntl.LOCK_EX):
web.check_reservation(alias.site) web.check_reservation(alias.site)
web.check_installation(alias.site, web.SitePaths.for_site(alias.site)) paths = web.SitePaths.for_site(alias.site)
web.check_installation(alias.site, paths)
reserve_alias(alias) reserve_alias(alias)
apache, enabled = alias_paths(alias) apache, enabled = alias_paths(alias)
with web.configuration_installation() as (created, reload_attempts): with web.configuration_installation() as (created, reload_attempts):
web.install_configuration(apache, alias.render("apache"), created) web.install_configuration(
apache,
alias.render("apache", socket_path=paths.apache_socket),
created,
)
web.enable_apache_site(apache, enabled, created) web.enable_apache_site(apache, enabled, created)
web.run("/usr/sbin/apache2ctl", "configtest") web.run("/usr/sbin/apache2ctl", "configtest")
reload_attempts.append("apache2") reload_attempts.append("apache2")
@@ -110,19 +115,25 @@ def activate_alias(alias):
def provision_alias_https(alias): def provision_alias_https(alias):
with web.locked_web_node(fcntl.LOCK_EX): with web.locked_web_node(fcntl.LOCK_EX):
check_https_prerequisites( site_paths = web.SitePaths.for_site(alias.site)
alias.site, web.SitePaths.for_site(alias.site) check_https_prerequisites(alias.site, site_paths)
)
require_root_directory(alias_directory()) require_root_directory(alias_directory())
if read_alias(alias_marker(alias)) != alias: if read_alias(alias_marker(alias)) != alias:
raise ValueError( raise ValueError(
"The website alias reservation has a different identity." "The website alias reservation has a different identity."
) )
apache, enabled = alias_paths(alias) apache, enabled = alias_paths(alias)
web.check_configuration(apache, alias.render("apache")) web.check_configuration(
apache,
alias.render("apache", socket_path=site_paths.apache_socket),
)
web.check_site_link(enabled, Path("../sites-available") / apache.name) web.check_site_link(enabled, Path("../sites-available") / apache.name)
ensure_certificate(alias) ensure_certificate(alias)
install_https_configuration(alias, *alias_paths(alias, https=True)) install_https_configuration(
alias,
*alias_paths(alias, https=True),
socket_path=site_paths.apache_socket,
)
def remove_alias(alias): def remove_alias(alias):
@@ -146,7 +157,11 @@ def remove_alias(alias):
"The website alias reservation has a different identity." "The website alias reservation has a different identity."
) )
expected = (alias.render("apache"), render_https_configuration(alias)) socket = web.SitePaths.for_site(alias.site).apache_socket
expected = (
alias.render("apache", socket_path=socket),
render_https_configuration(alias, socket_path=socket),
)
links = [] links = []
for (apache, enabled), contents in zip(paths, expected, strict=True): for (apache, enabled), contents in zip(paths, expected, strict=True):
if os.path.lexists(apache): if os.path.lexists(apache):
+129 -45
View File
@@ -3,6 +3,7 @@ import grp
import json import json
import os import os
import pwd import pwd
import socket
import stat import stat
import subprocess import subprocess
import time import time
@@ -16,7 +17,12 @@ from .node_files import (
require_root_directory, require_root_directory,
write_new_file, write_new_file,
) )
from .php_runtime import PHP_FPM_BINARY, PHP_POOL_DIRECTORY, PHP_SERVICE from .php_runtime import (
DEFAULT_PHP_RUNTIME,
PHP_SERIES,
PhpRuntime,
available_php_versions,
)
STATE_DIRECTORY = Path("/var/lib/coulobre/web-node") STATE_DIRECTORY = Path("/var/lib/coulobre/web-node")
WEB_ROOT = Path("/srv/coulobre/web") WEB_ROOT = Path("/srv/coulobre/web")
@@ -32,17 +38,55 @@ class SitePaths:
enabled: Path enabled: Path
pool: Path pool: Path
socket: Path socket: Path
runtime: PhpRuntime = DEFAULT_PHP_RUNTIME
routed: bool = False
@property
def route(self):
# This route survives PHP service restarts and reboots.
return self.account / ".coulobre-php.sock"
@property
def apache_socket(self):
return self.route if self.routed else self.socket
@classmethod @classmethod
def for_site(cls, site): def for_site(cls, site, *, version=None, archived_account=None):
configuration = site.configuration() configuration = site.configuration()
name = f"{configuration['service_user']}.conf" name = configuration["service_user"]
account = WEB_ROOT / str(site.account_id)
socket = Path(configuration["socket_path"])
runtime = DEFAULT_PHP_RUNTIME
route = (archived_account or account) / ".coulobre-php.sock"
routed = version is not None or os.path.lexists(route)
if version is not None:
runtime = PhpRuntime(version)
socket = socket.with_name(f"{name}-{version}.sock")
elif routed:
require_root_directory(route.parent)
info = route.lstat()
if not stat.S_ISLNK(info.st_mode) or info.st_uid != 0:
raise ValueError(
f"Expected a root-owned PHP route at {route}."
)
target = route.readlink()
series = target.stem.removeprefix(f"{name}-")
if target != socket:
if not (
PHP_SERIES.fullmatch(series)
and target == socket.with_name(f"{name}-{series}.sock")
):
raise ValueError(f"Unexpected PHP socket at {route}.")
runtime = PhpRuntime(series)
socket = target
return cls( return cls(
account=WEB_ROOT / str(site.account_id), account=account,
apache=APACHE_AVAILABLE / name, apache=APACHE_AVAILABLE / f"{name}.conf",
enabled=APACHE_ENABLED / name, enabled=APACHE_ENABLED / f"{name}.conf",
pool=PHP_POOL_DIRECTORY / name, pool=runtime.pools / f"{name}.conf",
socket=Path(configuration["socket_path"]), socket=socket,
runtime=runtime,
routed=routed,
) )
@@ -62,10 +106,15 @@ def locked_web_node(mode):
def apply_site(site, *, php_settings=None): def apply_site(site, *, php_settings=None):
applied, _ = apply_site_with_runtime(site, php_settings=php_settings)
return applied
def apply_site_with_runtime(site, *, php_settings=None, allowed=()):
if os.geteuid() != 0: if os.geteuid() != 0:
raise ValueError("Run apply as root on the web node.") raise ValueError("Run apply as root on the web node.")
for directory in (APACHE_AVAILABLE, APACHE_ENABLED, PHP_POOL_DIRECTORY): for directory in (APACHE_AVAILABLE, APACHE_ENABLED):
require_root_directory(directory) require_root_directory(directory)
require_root_directory(STATE_DIRECTORY.parent, create_mode=0o750) require_root_directory(STATE_DIRECTORY.parent, create_mode=0o750)
require_root_directory(STATE_DIRECTORY, create_mode=0o700) require_root_directory(STATE_DIRECTORY, create_mode=0o700)
@@ -74,12 +123,27 @@ def apply_site(site, *, php_settings=None):
with (STATE_DIRECTORY / "apply.lock").open("a") as lock: with (STATE_DIRECTORY / "apply.lock").open("a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX) fcntl.flock(lock, fcntl.LOCK_EX)
return install_site(site, php_settings=php_settings) return install_site(site, php_settings=php_settings, allowed=allowed)
def install_site(site, *, php_settings=None): def install_site(site, *, php_settings=None, allowed=()):
user = site.configuration()["service_user"] user = site.configuration()["service_user"]
paths = SitePaths.for_site(site) paths = SitePaths.for_site(site)
create_route = not (
paths.routed
or (
os.path.lexists(STATE_DIRECTORY / f"{site.account_id}.json")
and (os.path.lexists(paths.apache) or os.path.lexists(paths.pool))
)
)
if create_route:
versions = available_php_versions(allowed)
if not versions:
raise ValueError(
"Install a stable PHP-FPM series allowed for this site."
)
paths = SitePaths.for_site(site, version=versions[0])
require_root_directory(paths.pool.parent)
owned_paths = ( owned_paths = (
paths.account, paths.account,
paths.apache, paths.apache,
@@ -87,19 +151,15 @@ def install_site(site, *, php_settings=None):
paths.pool, paths.pool,
paths.socket, paths.socket,
) )
check_services() check_services(paths.runtime)
reserve_account(site, user, owned_paths) reserve_account(site, user, owned_paths)
uid, web_gid = ensure_system_account(user, paths.account) uid, web_gid = ensure_system_account(user, paths.account)
require_root_directory(paths.account, create_mode=0o755) require_root_directory(paths.account, create_mode=0o755)
ensure_public_directory(paths.account / "public", uid, web_gid) ensure_public_directory(paths.account / "public", uid, web_gid)
return install_configurations( if create_route:
site, paths.route.symlink_to(paths.socket)
paths.apache, applied = install_configurations(site, paths, php_settings=php_settings)
paths.enabled, return applied, paths.runtime.version
paths.pool,
paths.socket,
php_settings=php_settings,
)
def site_status(site): def site_status(site):
@@ -119,14 +179,19 @@ def site_status(site):
fcntl.flock(lock, fcntl.LOCK_SH) fcntl.flock(lock, fcntl.LOCK_SH)
try: try:
check_reservation(site) check_reservation(site)
check_installation(site, SitePaths.for_site(site)) paths = SitePaths.for_site(site)
check_installation(site, paths)
except (OSError, ValueError) as error: except (OSError, ValueError) as error:
return { return {
**report, **report,
"state": "needs_attention", "state": "needs_attention",
"problem": str(error), "problem": str(error),
} }
return {**report, "state": "configured"} return {
**report,
"state": "configured",
"php_version": paths.runtime.version,
}
def check_reservation(site): def check_reservation(site):
@@ -143,11 +208,11 @@ def check_reservation(site):
def site_storage(site): def site_storage(site):
check_reservation(site) check_reservation(site)
paths = SitePaths.for_site(site) account = WEB_ROOT / str(site.account_id)
require_root_directory(paths.account) require_root_directory(account)
user = site.configuration()["service_user"] user = site.configuration()["service_user"]
uid, gid = check_system_account(user, paths.account) uid, gid = check_system_account(user, account)
public = paths.account / "public" public = account / "public"
check_public_directory(public, uid, gid) check_public_directory(public, uid, gid)
return public, uid, gid return public, uid, gid
@@ -159,19 +224,21 @@ def check_installation(site, paths):
paths.account, paths.account,
APACHE_AVAILABLE, APACHE_AVAILABLE,
APACHE_ENABLED, APACHE_ENABLED,
PHP_POOL_DIRECTORY, paths.pool.parent,
): ):
require_root_directory(directory) require_root_directory(directory)
user = site.configuration()["service_user"] user = site.configuration()["service_user"]
uid, gid = check_system_account(user, paths.account) uid, gid = check_system_account(user, paths.account)
check_public_directory(paths.account / "public", uid, gid) check_public_directory(paths.account / "public", uid, gid)
check_configuration(paths.apache, site.render("apache")) check_configuration(
read_managed_php_pool(site, paths.pool) paths.apache, site.render("apache", socket_path=paths.apache_socket)
)
read_managed_php_pool(site, paths.pool, socket_path=paths.socket)
check_site_link( check_site_link(
paths.enabled, Path("../sites-available") / paths.apache.name paths.enabled, Path("../sites-available") / paths.apache.name
) )
check_services() check_services(paths.runtime)
if not socket_exists(paths.socket): if not socket_exists(paths.socket):
raise ValueError( raise ValueError(
f"PHP-FPM is missing the site socket at {paths.socket}." f"PHP-FPM is missing the site socket at {paths.socket}."
@@ -179,8 +246,8 @@ def check_installation(site, paths):
return uid, gid return uid, gid
def check_services(): def check_services(runtime):
for service in (PHP_SERVICE, "apache2"): for service in (runtime.service, "apache2"):
run("/usr/sbin/service", service, "status") run("/usr/sbin/service", service, "status")
if "proxy_fcgi_module" not in run("/usr/sbin/apache2ctl", "-M"): if "proxy_fcgi_module" not in run("/usr/sbin/apache2ctl", "-M"):
raise ValueError("Enable Apache's proxy_fcgi module on the web node.") raise ValueError("Enable Apache's proxy_fcgi module on the web node.")
@@ -304,28 +371,38 @@ def check_public_directory(path, uid, gid):
raise ValueError(f"Unexpected ownership or mode for {path}.") raise ValueError(f"Unexpected ownership or mode for {path}.")
def install_configurations( def install_configurations(site, paths, *, php_settings=None):
site, apache, enabled, pool, socket, *, php_settings=None
):
from .php_pool_settings import PhpPoolSettings from .php_pool_settings import PhpPoolSettings
from .web_node_php import read_managed_php_pool from .web_node_php import read_managed_php_pool
apache_socket = paths.apache_socket if paths.routed else None
pool_socket = paths.socket if paths.routed else None
with configuration_installation() as (created, reload_attempts): with configuration_installation() as (created, reload_attempts):
install_configuration(apache, site.render("apache"), created) install_configuration(
if os.path.lexists(pool): paths.apache,
_, applied = read_managed_php_pool(site, pool) site.render("apache", socket_path=apache_socket),
created,
)
if os.path.lexists(paths.pool):
_, applied = read_managed_php_pool(
site, paths.pool, socket_path=pool_socket
)
else: else:
applied = php_settings or PhpPoolSettings() applied = php_settings or PhpPoolSettings()
install_configuration( install_configuration(
pool, site.render("php-fpm", php_settings=applied), created paths.pool,
site.render(
"php-fpm", php_settings=applied, socket_path=pool_socket
),
created,
) )
enable_apache_site(apache, enabled, created) enable_apache_site(paths.apache, paths.enabled, created)
run(PHP_FPM_BINARY, "--test") run(paths.runtime.binary, "--test")
run("/usr/sbin/apache2ctl", "configtest") run("/usr/sbin/apache2ctl", "configtest")
reload_attempts.append(PHP_SERVICE) reload_attempts.append(paths.runtime.service)
run("/usr/sbin/service", PHP_SERVICE, "reload") run("/usr/sbin/service", paths.runtime.service, "reload")
wait_for_socket(socket) wait_for_socket(paths.socket)
reload_attempts.append("apache2") reload_attempts.append("apache2")
run("/usr/sbin/service", "apache2", "reload") run("/usr/sbin/service", "apache2", "reload")
return applied return applied
@@ -389,7 +466,14 @@ def wait_for_socket(path):
deadline = time.monotonic() + 15 deadline = time.monotonic() + 15
while time.monotonic() < deadline: while time.monotonic() < deadline:
if socket_exists(path): if socket_exists(path):
return with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as probe:
probe.settimeout(0.1)
try:
probe.connect(str(path))
except OSError:
pass
else:
return
time.sleep(0.1) time.sleep(0.1)
raise ValueError(f"PHP-FPM did not open {path}.") raise ValueError(f"PHP-FPM did not open {path}.")
+20 -31
View File
@@ -1,15 +1,13 @@
import fcntl import fcntl
import json import json
import os import os
from pathlib import Path
from tempfile import NamedTemporaryFile
from . import web_node_apply as web from . import web_node_apply as web
from .node_files import read_root_file from .node_files import read_root_file, replace_configuration
from .php_pool_settings import PHP_SETTINGS_COMMENT, PhpPoolSettings from .php_pool_settings import PHP_SETTINGS_COMMENT, PhpPoolSettings
def read_managed_php_pool(site, path): def read_managed_php_pool(site, path, *, socket_path=None):
content = read_root_file(path) content = read_root_file(path)
_, marker, options = content.partition("\n" + PHP_SETTINGS_COMMENT) _, marker, options = content.partition("\n" + PHP_SETTINGS_COMMENT)
try: try:
@@ -22,7 +20,9 @@ def read_managed_php_pool(site, path):
raise ValueError( raise ValueError(
f"Existing configuration differs at {path}." f"Existing configuration differs at {path}."
) from None ) from None
if content != site.render("php-fpm", php_settings=settings): if content != site.render(
"php-fpm", php_settings=settings, socket_path=socket_path
):
raise ValueError(f"Existing configuration differs at {path}.") raise ValueError(f"Existing configuration differs at {path}.")
return content, settings return content, settings
@@ -30,12 +30,16 @@ def read_managed_php_pool(site, path):
def update_php_pool(site, settings): def update_php_pool(site, settings):
if os.geteuid() != 0: if os.geteuid() != 0:
raise ValueError("Update PHP pool settings as root on the web node.") 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): with web.locked_web_node(fcntl.LOCK_EX):
web.check_reservation(site) web.check_reservation(site)
paths = web.SitePaths.for_site(site)
web.check_installation(site, paths) web.check_installation(site, paths)
old, _ = read_managed_php_pool(site, paths.pool) old, _ = read_managed_php_pool(
wanted = site.render("php-fpm", php_settings=settings) site, paths.pool, socket_path=paths.socket
)
wanted = site.render(
"php-fpm", php_settings=settings, socket_path=paths.socket
)
change_php_pool(paths, old, wanted) change_php_pool(paths, old, wanted)
return settings return settings
@@ -43,18 +47,18 @@ def update_php_pool(site, settings):
def change_php_pool(paths, old, wanted): def change_php_pool(paths, old, wanted):
changed = old != wanted changed = old != wanted
if changed: if changed:
replace_pool_file(paths.pool, wanted) replace_configuration(paths.pool, wanted)
reload_attempted = False reload_attempted = False
try: try:
web.run(web.PHP_FPM_BINARY, "--test") web.run(paths.runtime.binary, "--test")
reload_attempted = True reload_attempted = True
reload_php_pool(paths.socket) reload_php_pool(paths)
except (OSError, ValueError, KeyboardInterrupt) as error: except (OSError, ValueError, KeyboardInterrupt) as error:
try: try:
if changed: if changed:
replace_pool_file(paths.pool, old) replace_configuration(paths.pool, old)
if reload_attempted: if reload_attempted:
reload_php_pool(paths.socket) reload_php_pool(paths)
except (OSError, ValueError) as recovery: except (OSError, ValueError) as recovery:
raise ValueError( raise ValueError(
f"{error}\nPHP-FPM rollback failed. {recovery}" f"{error}\nPHP-FPM rollback failed. {recovery}"
@@ -62,21 +66,6 @@ def change_php_pool(paths, old, wanted):
raise raise
def replace_pool_file(path, content): def reload_php_pool(paths):
with NamedTemporaryFile( web.run("/usr/sbin/service", paths.runtime.service, "reload")
mode="w", encoding="utf-8", dir=path.parent, delete=False web.wait_for_socket(paths.socket)
) 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)
+25 -7
View File
@@ -26,7 +26,6 @@ from .web_node_tls import (
def retire_site(request): def retire_site(request):
site = request.resource site = request.resource
paths = web.SitePaths.for_site(site)
with web.locked_web_node(fcntl.LOCK_EX): with web.locked_web_node(fcntl.LOCK_EX):
retirement = RetirementRecord(web.STATE_DIRECTORY, request) retirement = RetirementRecord(web.STATE_DIRECTORY, request)
if retirement.is_complete: if retirement.is_complete:
@@ -37,11 +36,19 @@ def retire_site(request):
web.check_reservation(site) web.check_reservation(site)
elif not (retirement.directory / "site").is_file(): elif not (retirement.directory / "site").is_file():
raise ValueError("The original website reservation is missing.") raise ValueError("The original website reservation is missing.")
archived_account = web.WEB_ROOT / ".retired" / request.operation_id
account = web.WEB_ROOT / str(site.account_id)
paths = web.SitePaths.for_site(
site,
archived_account=archived_account
if not account.exists()
else None,
)
check_aliases(site) check_aliases(site)
for directory in ( for directory in (
web.APACHE_AVAILABLE, web.APACHE_AVAILABLE,
web.APACHE_ENABLED, web.APACHE_ENABLED,
web.PHP_POOL_DIRECTORY, paths.pool.parent,
): ):
require_root_directory(directory) require_root_directory(directory)
if os.path.lexists(paths.account): if os.path.lexists(paths.account):
@@ -56,7 +63,7 @@ def retire_site(request):
require_root_directory(AUTHORIZED_KEYS) require_root_directory(AUTHORIZED_KEYS)
check_root_file(key_file, mode=0o644) check_root_file(key_file, mode=0o644)
if os.path.lexists(paths.pool): if os.path.lexists(paths.pool):
read_managed_php_pool(site, paths.pool) read_managed_php_pool(site, paths.pool, socket_path=paths.socket)
apache = managed_vhosts(site, paths) apache = managed_vhosts(site, paths)
retirement.begin() retirement.begin()
detach_site(site, paths, key_file, apache, retirement) detach_site(site, paths, key_file, apache, retirement)
@@ -85,9 +92,20 @@ def check_aliases(site):
def managed_vhosts(site, paths): def managed_vhosts(site, paths):
https, enabled = https_paths(paths) https, enabled = https_paths(paths)
socket = paths.apache_socket
return ( return (
(paths.apache, paths.enabled, site.render("apache"), "apache-http"), (
(https, enabled, render_https_configuration(site), "apache-https"), paths.apache,
paths.enabled,
site.render("apache", socket_path=socket),
"apache-http",
),
(
https,
enabled,
render_https_configuration(site, socket_path=socket),
"apache-https",
),
) )
@@ -104,8 +122,8 @@ def detach_site(site, paths, key_file, apache, retirement):
for path, _, _, label in apache: for path, _, _, label in apache:
archive_path(path, retirement.directory / label) archive_path(path, retirement.directory / label)
archive_path(paths.pool, retirement.directory / "php-pool") archive_path(paths.pool, retirement.directory / "php-pool")
web.run(web.PHP_FPM_BINARY, "--test") web.run(paths.runtime.binary, "--test")
web.run("/usr/sbin/service", web.PHP_SERVICE, "reload") web.run("/usr/sbin/service", paths.runtime.service, "reload")
archive_path(key_file, retirement.directory / "authorized-keys") archive_path(key_file, retirement.directory / "authorized-keys")
archive_data_directory( archive_data_directory(
paths.account, web.WEB_ROOT, retirement.directory.name paths.account, web.WEB_ROOT, retirement.directory.name
+196
View File
@@ -0,0 +1,196 @@
import fcntl
import os
from dataclasses import replace
from pathlib import Path
from tempfile import TemporaryDirectory
from . import web_node_apply as web
from .node_files import (
read_root_file,
replace_configuration,
require_root_directory,
write_new_file,
)
from .php_runtime import DEFAULT_PHP_RUNTIME, installed_php_versions
from .web_node_aliases import alias_directory, alias_paths, read_alias
from .web_node_php import (
read_managed_php_pool,
reload_php_pool,
)
from .web_node_tls import https_paths, render_https_configuration
def switch_php_version(site, version):
if os.geteuid() != 0:
raise ValueError(
"Change the website PHP series as root on the web node."
)
with web.locked_web_node(fcntl.LOCK_EX):
web.check_reservation(site)
current = web.SitePaths.for_site(site)
if version not in installed_php_versions():
raise ValueError(
f"Install stable PHP {version} FPM on the web node."
)
if current.socket.name == f"coulobre-{site.account_id}.sock" and (
current.routed or current.runtime.version != version
):
current = route_legacy_site(site, current)
web.check_installation(site, current)
if current.routed:
# The previous request may have switched the route already.
remove_inactive_pools(site, current)
if current.runtime.version == version:
return version
target = web.SitePaths.for_site(site, version=version)
require_root_directory(target.pool.parent)
web.check_services(target.runtime)
switch_pool(site, current, target)
return version
def change_route(paths):
with TemporaryDirectory(dir=paths.route.parent) as directory:
staged = Path(directory) / "socket"
staged.symlink_to(paths.socket)
staged.replace(paths.route)
def route_legacy_site(site, paths):
for directory in (
paths.account,
paths.apache.parent,
paths.enabled.parent,
):
require_root_directory(directory)
legacy = replace(paths, routed=False)
managed = [(paths.apache, paths.enabled, site, False)]
https, enabled = https_paths(paths)
managed.append((https, enabled, site, True))
directory = alias_directory()
if os.path.lexists(directory):
require_root_directory(directory)
for marker in directory.glob("*.json"):
alias = read_alias(marker)
if alias.site == site:
managed.append((*alias_paths(alias), alias, False))
managed.append((*alias_paths(alias, https=True), alias, True))
changes = []
for config, link, resource, tls in managed:
if os.path.lexists(link):
web.check_site_link(link, Path("../sites-available") / config.name)
if not os.path.lexists(config):
if os.path.lexists(link) or config == paths.apache:
raise ValueError(f"Missing managed configuration at {config}.")
continue
before, after = (
(
render_https_configuration(resource, socket_path=socket)
if tls
else resource.render("apache", socket_path=socket)
)
for socket in (legacy.socket, paths.route)
)
actual = read_root_file(config)
if actual not in (before, after):
raise ValueError(f"Existing configuration differs at {config}.")
if actual != after:
changes.append((config, actual, after))
routed = replace(paths, routed=True)
if not paths.routed:
change_route(routed)
updated = []
try:
for path, before, after in changes:
updated.append((path, before))
replace_configuration(path, after)
reload_apache()
except (OSError, ValueError, KeyboardInterrupt):
for path, before in reversed(updated):
replace_configuration(path, before)
if not paths.routed:
paths.route.unlink()
reload_apache()
raise
return routed
def reload_apache():
web.run("/usr/sbin/apache2ctl", "configtest")
web.run("/usr/sbin/service", "apache2", "reload")
def switch_pool(site, current, target):
previous, settings = read_managed_php_pool(
site, current.pool, socket_path=current.socket
)
desired = site.render(
"php-fpm", php_settings=settings, socket_path=target.socket
)
if os.path.lexists(target.pool):
read_managed_php_pool(site, target.pool, socket_path=target.socket)
replace_configuration(target.pool, desired)
else:
if os.path.lexists(target.socket):
raise ValueError(f"Unexpected PHP socket at {target.socket}.")
write_new_file(target.pool, desired, mode=0o644)
target_reload = False
try:
web.run(target.runtime.binary, "--test")
target_reload = True
reload_php_pool(target)
change_route(target)
current.pool.unlink()
remove_pool_from_service(current)
except (OSError, ValueError, KeyboardInterrupt) as error:
try:
if current.route.readlink() == target.socket:
if not os.path.lexists(current.pool):
write_new_file(current.pool, previous, mode=0o644)
web.run(current.runtime.binary, "--test")
reload_php_pool(current)
change_route(current)
target.pool.unlink(missing_ok=True)
if target_reload:
remove_pool_from_service(target)
except (OSError, ValueError) as recovery:
raise ValueError(
f"{error}\nPHP-FPM rollback failed. {recovery}"
) from error
raise
def remove_pool_from_service(paths):
web.run(paths.runtime.binary, "--test")
web.run("/usr/sbin/service", paths.runtime.service, "reload")
def remove_inactive_pools(site, current):
legacy = DEFAULT_PHP_RUNTIME.version
legacy_socket = Path(site.configuration()["socket_path"])
for version in installed_php_versions():
if version == current.runtime.version:
continue
paths = web.SitePaths.for_site(site, version=version)
if os.path.lexists(paths.pool):
require_root_directory(paths.pool.parent)
content = read_root_file(paths.pool)
listen = f"listen = {legacy_socket}\n"
if version == legacy and listen in content.splitlines(
keepends=True
):
paths = replace(paths, socket=legacy_socket)
read_managed_php_pool(site, paths.pool, socket_path=paths.socket)
paths.pool.unlink()
try:
remove_pool_from_service(paths)
except (OSError, ValueError, KeyboardInterrupt):
write_new_file(paths.pool, content, mode=0o644)
raise
elif os.path.lexists(paths.socket) or (
version == legacy and os.path.lexists(legacy_socket)
):
remove_pool_from_service(paths)
+17 -11
View File
@@ -100,15 +100,17 @@ def enable_https(site):
if os.geteuid() != 0: if os.geteuid() != 0:
raise ValueError("Run enable-https as root on the web node.") raise ValueError("Run enable-https as root on the web node.")
paths = SitePaths.for_site(site)
apache, enabled = https_paths(paths)
with locked_web_node(fcntl.LOCK_EX): with locked_web_node(fcntl.LOCK_EX):
paths = SitePaths.for_site(site)
apache, enabled = https_paths(paths)
check_https_prerequisites(site, paths) check_https_prerequisites(site, paths)
install_https_configuration(site, apache, enabled) install_https_configuration(
site, apache, enabled, socket_path=paths.apache_socket
)
def install_https_configuration(site, apache, enabled): def install_https_configuration(site, apache, enabled, *, socket_path=None):
config = https_configuration(site) config = https_configuration(site, socket_path=socket_path)
with configuration_installation() as (created, reload_attempts): with configuration_installation() as (created, reload_attempts):
install_configuration(apache, config, created) install_configuration(apache, config, created)
enable_apache_site(apache, enabled, created) enable_apache_site(apache, enabled, created)
@@ -129,17 +131,20 @@ def https_status(site):
raise ValueError("Run https-status as root on the web node.") raise ValueError("Run https-status as root on the web node.")
report = {**site.manifest(), "state": "not_installed", "problem": None} report = {**site.manifest(), "state": "not_installed", "problem": None}
paths = SitePaths.for_site(site)
apache, enabled = https_paths(paths)
try: try:
apache, enabled = https_paths(SitePaths.for_site(site))
for directory in (apache.parent, enabled.parent): for directory in (apache.parent, enabled.parent):
require_root_directory(directory) require_root_directory(directory)
if not (os.path.lexists(apache) or os.path.lexists(enabled)): if not (os.path.lexists(apache) or os.path.lexists(enabled)):
return report return report
with locked_web_node(fcntl.LOCK_SH): with locked_web_node(fcntl.LOCK_SH):
paths = SitePaths.for_site(site)
check_reservation(site) check_reservation(site)
check_installation(site, paths) check_installation(site, paths)
check_configuration(apache, https_configuration(site)) check_configuration(
apache,
https_configuration(site, socket_path=paths.apache_socket),
)
check_site_link(enabled, Path("../sites-available") / apache.name) check_site_link(enabled, Path("../sites-available") / apache.name)
run("/usr/sbin/apache2ctl", "configtest") run("/usr/sbin/apache2ctl", "configtest")
except (OSError, ValueError) as error: except (OSError, ValueError) as error:
@@ -161,7 +166,7 @@ def certbot_lineage(site):
return CERTBOT_ROOT / "live" / name return CERTBOT_ROOT / "live" / name
def https_configuration(site): def https_configuration(site, *, socket_path=None):
lineage = certbot_lineage(site) lineage = certbot_lineage(site)
name = lineage.name name = lineage.name
archive = CERTBOT_ROOT / "archive" / name archive = CERTBOT_ROOT / "archive" / name
@@ -205,16 +210,17 @@ def https_configuration(site):
str(chain_file), str(chain_file),
) )
return render_https_configuration(site) return render_https_configuration(site, socket_path=socket_path)
def render_https_configuration(site): def render_https_configuration(site, *, socket_path=None):
lineage = certbot_lineage(site) lineage = certbot_lineage(site)
certificate = lineage / "fullchain.pem" certificate = lineage / "fullchain.pem"
private_key = lineage / "privkey.pem" private_key = lineage / "privkey.pem"
return site.render( return site.render(
"apache", "apache",
port=443, port=443,
socket_path=socket_path,
tls_settings=( tls_settings=(
"\n" "\n"
" SSLEngine On\n" " SSLEngine On\n"