Select and persist a PHP-FPM series for each website
This commit is contained in:
1 parent
b249cf06a9
commit
0c8a28b7e2
26 files changed
+1342
-162
No files matched your search
@@ -21,6 +21,7 @@ from .models import (
|
||||
HostingMailbox,
|
||||
HostingMailDomain,
|
||||
SitePhpSettings,
|
||||
SitePhpVersion,
|
||||
SiteSFTP,
|
||||
SiteStorageLimit,
|
||||
SiteStorageUsage,
|
||||
@@ -147,6 +148,7 @@ def cleanup_targets(account):
|
||||
WebHTTPS.objects.filter(plan__account=account),
|
||||
SiteSFTP.objects.filter(account=account),
|
||||
SitePhpSettings.objects.filter(account=account),
|
||||
SitePhpVersion.objects.filter(account=account),
|
||||
SiteStorageLimit.objects.filter(account=account),
|
||||
SiteStorageUsage.objects.filter(account=account),
|
||||
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,
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -37,6 +37,7 @@ from coulobre.php_pool_settings import (
|
||||
PhpPoolSettings,
|
||||
PhpPoolSettingsError,
|
||||
)
|
||||
from coulobre.php_runtime import validate_php_versions
|
||||
from coulobre.web_node import MAX_STORAGE_LIMIT_MIB
|
||||
|
||||
from .fields import DomainNameField
|
||||
@@ -294,6 +295,15 @@ class HostingPlan(models.Model):
|
||||
php_max_children = php_plan_field(
|
||||
"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:
|
||||
ordering = ("name", "pk")
|
||||
@@ -303,6 +313,10 @@ class HostingPlan(models.Model):
|
||||
|
||||
def clean(self):
|
||||
super().clean()
|
||||
try:
|
||||
validate_php_versions(self.allowed_php_versions())
|
||||
except ValueError as error:
|
||||
raise ValidationError({"php_versions": str(error)}) from error
|
||||
try:
|
||||
self.get_php_settings()
|
||||
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):
|
||||
name = models.CharField(max_length=120)
|
||||
@@ -762,6 +783,18 @@ class WebActivation(ProvisioningJob):
|
||||
)
|
||||
|
||||
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):
|
||||
|
||||
@@ -14,10 +14,13 @@ from coulobre.account_restore_request import (
|
||||
from coulobre.mail_dns import dkim_key
|
||||
from coulobre.mail_node import MailboxQuotaUpdate, MailboxSigningRequest
|
||||
from coulobre.php_pool_settings import PhpPoolSettings
|
||||
from coulobre.php_runtime import validate_php_version
|
||||
from coulobre.web_node import (
|
||||
MAX_STORAGE_BYTES,
|
||||
WebActivationRequest,
|
||||
WebAliasRequest,
|
||||
WebPhpRequest,
|
||||
WebPhpVersionRequest,
|
||||
WebQuotaRequest,
|
||||
WebStorageRequest,
|
||||
)
|
||||
@@ -29,36 +32,56 @@ class NodeReplyError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def activate_local_site(site):
|
||||
apply_on_local_node(
|
||||
site, "/run/coulobre-web-apply.sock", "web node", "site"
|
||||
def activate_local_site(site, php_settings, allowed_versions):
|
||||
reply = apply_on_local_node(
|
||||
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):
|
||||
return send_php_settings(site, php_settings, "activate_with_php_settings")
|
||||
def update_local_php_version(site, version):
|
||||
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):
|
||||
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),
|
||||
WebPhpRequest(site, php_settings, "set_php_settings"),
|
||||
"/run/coulobre-web-apply.sock",
|
||||
"web node",
|
||||
"PHP pool settings",
|
||||
)
|
||||
try:
|
||||
return PhpPoolSettings.from_manifest(reply.get("applied_php_settings"))
|
||||
applied = PhpPoolSettings.from_manifest(
|
||||
reply.get("applied_php_settings")
|
||||
)
|
||||
except ValueError:
|
||||
raise ValueError(
|
||||
"The web node returned invalid PHP pool settings."
|
||||
) from None
|
||||
if applied != php_settings:
|
||||
raise ValueError("The web node reported different PHP pool settings.")
|
||||
return applied
|
||||
|
||||
|
||||
def measure_local_site_storage(site):
|
||||
|
||||
@@ -104,6 +104,11 @@ def queue_web_activation(plan):
|
||||
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
|
||||
def queue_site_php_settings(account_id, php_settings, *, use_plan=False):
|
||||
account = lock_hosting_account(account_id, customer_id=None)
|
||||
|
||||
@@ -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)
|
||||
@@ -46,6 +46,7 @@ from .models import (
|
||||
HostingMailDomain,
|
||||
MailboxProvisioning,
|
||||
SitePhpSettings,
|
||||
SitePhpVersion,
|
||||
SiteSFTP,
|
||||
SiteStorageLimit,
|
||||
SiteStorageUsage,
|
||||
@@ -58,7 +59,6 @@ from .models import (
|
||||
from .node_client import (
|
||||
NodeReplyError,
|
||||
activate_local_site,
|
||||
activate_local_site_with_php,
|
||||
create_local_account_backup,
|
||||
enable_local_https,
|
||||
expire_local_account_backup,
|
||||
@@ -72,9 +72,11 @@ from .node_client import (
|
||||
set_local_site_storage_limit,
|
||||
update_local_mailbox_quota,
|
||||
update_local_php_settings,
|
||||
update_local_php_version,
|
||||
update_local_sftp,
|
||||
update_local_website_alias,
|
||||
)
|
||||
from .php_settings import plan_php_versions
|
||||
from .service_changes import apply_service_change
|
||||
from .sftp import site_is_active
|
||||
|
||||
@@ -148,6 +150,9 @@ def dispatch_web_activations():
|
||||
dispatch_provisioning_jobs(
|
||||
SitePhpSettings, set_site_php_settings, WEB_ACTIVATION_QUEUE
|
||||
)
|
||||
dispatch_provisioning_jobs(
|
||||
SitePhpVersion, set_site_php_version, WEB_ACTIVATION_QUEUE
|
||||
)
|
||||
|
||||
|
||||
@shared_task
|
||||
@@ -369,7 +374,9 @@ def dispatch_provisioning_jobs(
|
||||
def activate_web_plan(activation_id):
|
||||
if settings.LOCAL_WEB_ACTIVATION:
|
||||
run_provisioning_job(
|
||||
WebActivation.objects.select_related("plan__account"),
|
||||
WebActivation.objects.select_related(
|
||||
"plan__account__hosting_plan"
|
||||
),
|
||||
activation_id,
|
||||
apply_web_activation,
|
||||
"Could not complete the request to the local web node. "
|
||||
@@ -385,12 +392,15 @@ def apply_web_activation(activation):
|
||||
"account 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()}
|
||||
options = (
|
||||
PhpPoolSettings.from_manifest(activation.php_settings)
|
||||
if activation.php_settings is not None
|
||||
else PhpPoolSettings()
|
||||
)
|
||||
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)
|
||||
@@ -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)
|
||||
def measure_site_storage(request_id):
|
||||
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>
|
||||
{% endif %}
|
||||
</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 %}
|
||||
</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 %}
|
||||
@@ -9,7 +9,7 @@ from django.urls import reverse
|
||||
from django.utils import timezone
|
||||
|
||||
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_apply import (
|
||||
SitePaths,
|
||||
@@ -91,11 +91,11 @@ class PanelPhpSettingsTests(TestCase):
|
||||
)
|
||||
self.client.post(activation_url)
|
||||
with patch(
|
||||
"coulobre.hosting.tasks.activate_local_site_with_php",
|
||||
return_value=options,
|
||||
"coulobre.hosting.tasks.activate_local_site",
|
||||
return_value=(options, "8.5"),
|
||||
) as activate:
|
||||
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.assertEqual(
|
||||
self.client.get(self.url).context["form"].initial,
|
||||
@@ -258,10 +258,7 @@ class NativePhpSettingsTests(SimpleTestCase):
|
||||
self.assertIn("request_terminate_timeout = 35s", pool)
|
||||
applied = install_configurations(
|
||||
self.site,
|
||||
self.paths.apache,
|
||||
self.paths.enabled,
|
||||
self.paths.pool,
|
||||
self.paths.socket,
|
||||
self.paths,
|
||||
php_settings=PhpPoolSettings(max_children=5),
|
||||
)
|
||||
self.assertEqual(applied, self.options)
|
||||
@@ -284,9 +281,13 @@ class NativePhpSettingsTests(SimpleTestCase):
|
||||
self.assertEqual(
|
||||
self.runner.call_args_list,
|
||||
[
|
||||
call(PHP_FPM_BINARY, "--test"),
|
||||
call("/usr/sbin/service", PHP_SERVICE, "reload"),
|
||||
call("/usr/sbin/service", PHP_SERVICE, "reload"),
|
||||
call(DEFAULT_PHP_RUNTIME.binary, "--test"),
|
||||
call(
|
||||
"/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)
|
||||
@@ -296,5 +297,7 @@ class NativePhpSettingsTests(SimpleTestCase):
|
||||
):
|
||||
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.runner.assert_any_call(
|
||||
"/usr/sbin/service", DEFAULT_PHP_RUNTIME.service, "reload"
|
||||
)
|
||||
self.ready.assert_called_once_with(self.paths.socket)
|
||||
@@ -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))
|
||||
@@ -9,7 +9,8 @@ from django.test import SimpleTestCase, TestCase, override_settings
|
||||
from django.urls import reverse
|
||||
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 (
|
||||
HostingAccount,
|
||||
@@ -65,10 +66,15 @@ class WebActivationTests(TestCase):
|
||||
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)
|
||||
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.assertRedirects(self.client.post(self.url), self.detail)
|
||||
activation.refresh_from_db()
|
||||
@@ -125,7 +131,10 @@ class WebActivationTests(TestCase):
|
||||
)
|
||||
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)
|
||||
apply.assert_not_called()
|
||||
activation.refresh_from_db()
|
||||
@@ -150,7 +159,10 @@ class WebActivationTests(TestCase):
|
||||
activation = WebActivation.objects.create(
|
||||
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)
|
||||
apply.assert_not_called()
|
||||
WebActivation.objects.filter(pk=activation.pk).update(
|
||||
@@ -165,8 +177,9 @@ class WebActivationTests(TestCase):
|
||||
class WebActivationReplyTests(SimpleTestCase):
|
||||
def test_mismatched_node_identity_cannot_complete_activation(self):
|
||||
site = WebSite(1, "site.example")
|
||||
reply = site.manifest() | {
|
||||
"account_id": 2,
|
||||
request = WebActivationRequest(site, PhpPoolSettings(), ())
|
||||
reply = request.manifest() | {
|
||||
"site": WebSite(2, site.domain).manifest(),
|
||||
"state": "configured",
|
||||
"problem": None,
|
||||
}
|
||||
@@ -176,6 +189,6 @@ class WebActivationReplyTests(SimpleTestCase):
|
||||
json.dumps(reply).encode()
|
||||
)
|
||||
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(), ())
|
||||
@@ -5,9 +5,13 @@ from unittest.mock import call, patch
|
||||
|
||||
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_apply import install_configurations, site_status
|
||||
from coulobre.web_node_apply import (
|
||||
SitePaths,
|
||||
install_configurations,
|
||||
site_status,
|
||||
)
|
||||
|
||||
|
||||
class PhpRuntimeTests(SimpleTestCase):
|
||||
@@ -48,7 +52,14 @@ class WebNodeConfigurationTests(SimpleTestCase):
|
||||
|
||||
def install(self):
|
||||
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):
|
||||
@@ -60,9 +71,11 @@ class WebNodeConfigurationTests(SimpleTestCase):
|
||||
self.assertEqual(
|
||||
self.runner.call_args_list,
|
||||
[
|
||||
call(PHP_FPM_BINARY, "--test"),
|
||||
call(DEFAULT_PHP_RUNTIME.binary, "--test"),
|
||||
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"),
|
||||
],
|
||||
)
|
||||
@@ -88,7 +101,9 @@ class WebNodeConfigurationTests(SimpleTestCase):
|
||||
self.assertEqual(
|
||||
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"),
|
||||
],
|
||||
)
|
||||
|
||||
@@ -29,7 +29,7 @@ class WebNodeTLSTests(SimpleTestCase):
|
||||
self.http.write_text(self.site.render("apache"), encoding="utf-8")
|
||||
self.tls = self.http.with_name("coulobre-42-https.conf")
|
||||
self.enabled = http_enabled.with_name(self.tls.name)
|
||||
paths = SitePaths(
|
||||
self.paths = SitePaths(
|
||||
directory / "account",
|
||||
self.http,
|
||||
http_enabled,
|
||||
@@ -65,7 +65,8 @@ class WebNodeTLSTests(SimpleTestCase):
|
||||
)
|
||||
self.enterContext(
|
||||
patch(
|
||||
"coulobre.web_node_tls.SitePaths.for_site", return_value=paths
|
||||
"coulobre.web_node_tls.SitePaths.for_site",
|
||||
return_value=self.paths,
|
||||
)
|
||||
)
|
||||
self.enterContext(
|
||||
@@ -110,7 +111,7 @@ class WebNodeTLSTests(SimpleTestCase):
|
||||
content = self.tls.read_text()
|
||||
self.assertIn("<VirtualHost *:443>", 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(
|
||||
f'SSLCertificateFile "{self.live}/fullchain.pem"', content
|
||||
)
|
||||
|
||||
@@ -52,6 +52,11 @@ urlpatterns = [
|
||||
views.SitePhpSettingsEdit.as_view(),
|
||||
name="site_php_settings",
|
||||
),
|
||||
path(
|
||||
"accounts/<int:pk>/php-version/",
|
||||
views.SitePhpVersionEdit.as_view(),
|
||||
name="site_php_version",
|
||||
),
|
||||
path(
|
||||
"accounts/<int:pk>/aliases/new/",
|
||||
views.WebsiteAliasCreate.as_view(),
|
||||
|
||||
@@ -31,6 +31,7 @@ from django.views.generic.detail import SingleObjectMixin
|
||||
|
||||
from coulobre.dns_node import MAX_SOA_SERIAL
|
||||
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.web_node import WebSite
|
||||
|
||||
@@ -98,10 +99,17 @@ from .php_settings import (
|
||||
SitePhpSettingsForm,
|
||||
last_applied_php_settings,
|
||||
plan_php_settings,
|
||||
plan_php_versions,
|
||||
queue_site_php_settings,
|
||||
queue_web_activation,
|
||||
settings_from_form,
|
||||
)
|
||||
from .php_versions import (
|
||||
SitePhpVersionForm,
|
||||
applied_php_version,
|
||||
can_change_php_version,
|
||||
queue_php_version,
|
||||
)
|
||||
from .phpmyadmin import phpmyadmin_available
|
||||
from .reseller_accounts import create_reseller_account, save_operator_account
|
||||
from .resource_requests import (
|
||||
@@ -417,6 +425,24 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
||||
context["can_change_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"] = (
|
||||
WebsiteAlias.objects.filter(reservation__account=self.object)
|
||||
.select_related("reservation")
|
||||
@@ -653,6 +679,68 @@ class SitePhpSettingsEdit(
|
||||
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):
|
||||
permission_required = MANAGE_WEBSITE_ALIASES
|
||||
template_name = "hosting/website_alias_form.html"
|
||||
@@ -1777,6 +1865,7 @@ class HostingPlanEditor:
|
||||
"php_upload_limit_mib",
|
||||
"php_request_timeout_seconds",
|
||||
"php_max_children",
|
||||
"php_versions",
|
||||
)
|
||||
template_name = "hosting/hosting_plan_form.html"
|
||||
success_url = reverse_lazy("panel:hosting_plans")
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import os
|
||||
import stat
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from tempfile import NamedTemporaryFile
|
||||
|
||||
|
||||
@@ -52,6 +53,21 @@ def write_new_file(path, content, *, mode, group=None):
|
||||
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
|
||||
def locked_root_directory(path):
|
||||
import fcntl
|
||||
|
||||
@@ -1,6 +1,92 @@
|
||||
import re
|
||||
import subprocess
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
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():
|
||||
try:
|
||||
@@ -12,7 +98,4 @@ def php_fpm_version():
|
||||
return "8.5"
|
||||
|
||||
|
||||
PHP_VERSION = 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")
|
||||
DEFAULT_PHP_RUNTIME = PhpRuntime(php_fpm_version())
|
||||
@@ -4,14 +4,18 @@ import subprocess
|
||||
from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
|
||||
from .php_runtime import PHP_SERVICE, PHP_VERSION
|
||||
from .php_runtime import (
|
||||
DEFAULT_PHP_RUNTIME,
|
||||
PhpRuntime,
|
||||
installed_php_versions,
|
||||
)
|
||||
|
||||
SERVICES = {
|
||||
"panel": ("Coulobre Panel", "coulobre-panel.service"),
|
||||
"worker": ("Coulobre worker", "coulobre-worker.service"),
|
||||
"scheduler": ("Coulobre scheduler", "coulobre-beat.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"),
|
||||
"rabbitmq": ("RabbitMQ", "rabbitmq-server.service"),
|
||||
"bind9": ("BIND9", "named.service"),
|
||||
@@ -106,7 +110,29 @@ def unique_health_keys(pairs):
|
||||
|
||||
|
||||
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:
|
||||
reply = subprocess.run(
|
||||
(
|
||||
|
||||
@@ -12,6 +12,7 @@ from .domain_names import canonical_domain
|
||||
from .node_requests import serve_apply_request
|
||||
from .node_retirement import RetirementRequest, parse_retirement
|
||||
from .php_pool_settings import PhpPoolSettings
|
||||
from .php_runtime import validate_php_version, validate_php_versions
|
||||
from .service_access import ServiceAccessRequest, parse_service_request
|
||||
|
||||
MANIFEST_VERSION = 1
|
||||
@@ -80,11 +81,14 @@ class WebSite:
|
||||
tls_settings="",
|
||||
server_name=None,
|
||||
php_settings=None,
|
||||
socket_path=None,
|
||||
):
|
||||
resource = files("coulobre.hosting").joinpath(
|
||||
"templates", "hosting", CONFIGURATIONS[configuration]
|
||||
)
|
||||
values = self.configuration()
|
||||
if socket_path is not None:
|
||||
values["socket_path"] = socket_path
|
||||
if server_name is not None:
|
||||
values["domain"] = canonical_domain(server_name)
|
||||
template = Template(resource.read_text(encoding="utf-8"))
|
||||
@@ -135,12 +139,15 @@ class WebAlias:
|
||||
"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(
|
||||
configuration,
|
||||
port=port,
|
||||
tls_settings=tls_settings,
|
||||
server_name=self.domain,
|
||||
socket_path=socket_path,
|
||||
)
|
||||
|
||||
|
||||
@@ -220,6 +227,30 @@ def parse_web_request(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 (
|
||||
isinstance(data, dict)
|
||||
and data.keys() == {"operation", "site"}
|
||||
@@ -251,7 +282,61 @@ def parse_web_apply(data):
|
||||
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):
|
||||
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):
|
||||
from .web_node_retirement import retire_site
|
||||
|
||||
@@ -312,6 +397,7 @@ def main(argv=None):
|
||||
render.add_argument("configuration", choices=CONFIGURATIONS)
|
||||
apply = commands.add_parser("apply", help="Install a site on a web node.")
|
||||
apply.add_argument("manifest", type=Path)
|
||||
apply.add_argument("--php-version", help="Select the initial PHP series.")
|
||||
commands.add_parser(
|
||||
"apply-request",
|
||||
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"))
|
||||
site = WebSite.from_manifest(payload)
|
||||
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}.")
|
||||
elif args.command == "status":
|
||||
from .web_node_apply import site_status
|
||||
|
||||
@@ -97,11 +97,16 @@ def activate_alias(alias):
|
||||
raise ValueError("Apply the website alias as root on the web node.")
|
||||
with web.locked_web_node(fcntl.LOCK_EX):
|
||||
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)
|
||||
apache, enabled = alias_paths(alias)
|
||||
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.run("/usr/sbin/apache2ctl", "configtest")
|
||||
reload_attempts.append("apache2")
|
||||
@@ -110,19 +115,25 @@ def activate_alias(alias):
|
||||
|
||||
def provision_alias_https(alias):
|
||||
with web.locked_web_node(fcntl.LOCK_EX):
|
||||
check_https_prerequisites(
|
||||
alias.site, web.SitePaths.for_site(alias.site)
|
||||
)
|
||||
site_paths = web.SitePaths.for_site(alias.site)
|
||||
check_https_prerequisites(alias.site, site_paths)
|
||||
require_root_directory(alias_directory())
|
||||
if read_alias(alias_marker(alias)) != alias:
|
||||
raise ValueError(
|
||||
"The website alias reservation has a different identity."
|
||||
)
|
||||
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)
|
||||
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):
|
||||
@@ -146,7 +157,11 @@ def remove_alias(alias):
|
||||
"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 = []
|
||||
for (apache, enabled), contents in zip(paths, expected, strict=True):
|
||||
if os.path.lexists(apache):
|
||||
|
||||
+128
-44
@@ -3,6 +3,7 @@ import grp
|
||||
import json
|
||||
import os
|
||||
import pwd
|
||||
import socket
|
||||
import stat
|
||||
import subprocess
|
||||
import time
|
||||
@@ -16,7 +17,12 @@ from .node_files import (
|
||||
require_root_directory,
|
||||
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")
|
||||
WEB_ROOT = Path("/srv/coulobre/web")
|
||||
@@ -32,17 +38,55 @@ class SitePaths:
|
||||
enabled: Path
|
||||
pool: 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
|
||||
def for_site(cls, site):
|
||||
def for_site(cls, site, *, version=None, archived_account=None):
|
||||
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(
|
||||
account=WEB_ROOT / str(site.account_id),
|
||||
apache=APACHE_AVAILABLE / name,
|
||||
enabled=APACHE_ENABLED / name,
|
||||
pool=PHP_POOL_DIRECTORY / name,
|
||||
socket=Path(configuration["socket_path"]),
|
||||
account=account,
|
||||
apache=APACHE_AVAILABLE / f"{name}.conf",
|
||||
enabled=APACHE_ENABLED / f"{name}.conf",
|
||||
pool=runtime.pools / f"{name}.conf",
|
||||
socket=socket,
|
||||
runtime=runtime,
|
||||
routed=routed,
|
||||
)
|
||||
|
||||
|
||||
@@ -62,10 +106,15 @@ def locked_web_node(mode):
|
||||
|
||||
|
||||
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:
|
||||
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(STATE_DIRECTORY.parent, create_mode=0o750)
|
||||
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:
|
||||
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"]
|
||||
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 = (
|
||||
paths.account,
|
||||
paths.apache,
|
||||
@@ -87,19 +151,15 @@ def install_site(site, *, php_settings=None):
|
||||
paths.pool,
|
||||
paths.socket,
|
||||
)
|
||||
check_services()
|
||||
check_services(paths.runtime)
|
||||
reserve_account(site, user, owned_paths)
|
||||
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)
|
||||
return install_configurations(
|
||||
site,
|
||||
paths.apache,
|
||||
paths.enabled,
|
||||
paths.pool,
|
||||
paths.socket,
|
||||
php_settings=php_settings,
|
||||
)
|
||||
if create_route:
|
||||
paths.route.symlink_to(paths.socket)
|
||||
applied = install_configurations(site, paths, php_settings=php_settings)
|
||||
return applied, paths.runtime.version
|
||||
|
||||
|
||||
def site_status(site):
|
||||
@@ -119,14 +179,19 @@ def site_status(site):
|
||||
fcntl.flock(lock, fcntl.LOCK_SH)
|
||||
try:
|
||||
check_reservation(site)
|
||||
check_installation(site, SitePaths.for_site(site))
|
||||
paths = SitePaths.for_site(site)
|
||||
check_installation(site, paths)
|
||||
except (OSError, ValueError) as error:
|
||||
return {
|
||||
**report,
|
||||
"state": "needs_attention",
|
||||
"problem": str(error),
|
||||
}
|
||||
return {**report, "state": "configured"}
|
||||
return {
|
||||
**report,
|
||||
"state": "configured",
|
||||
"php_version": paths.runtime.version,
|
||||
}
|
||||
|
||||
|
||||
def check_reservation(site):
|
||||
@@ -143,11 +208,11 @@ def check_reservation(site):
|
||||
|
||||
def site_storage(site):
|
||||
check_reservation(site)
|
||||
paths = SitePaths.for_site(site)
|
||||
require_root_directory(paths.account)
|
||||
account = WEB_ROOT / str(site.account_id)
|
||||
require_root_directory(account)
|
||||
user = site.configuration()["service_user"]
|
||||
uid, gid = check_system_account(user, paths.account)
|
||||
public = paths.account / "public"
|
||||
uid, gid = check_system_account(user, account)
|
||||
public = account / "public"
|
||||
check_public_directory(public, uid, gid)
|
||||
return public, uid, gid
|
||||
|
||||
@@ -159,19 +224,21 @@ def check_installation(site, paths):
|
||||
paths.account,
|
||||
APACHE_AVAILABLE,
|
||||
APACHE_ENABLED,
|
||||
PHP_POOL_DIRECTORY,
|
||||
paths.pool.parent,
|
||||
):
|
||||
require_root_directory(directory)
|
||||
|
||||
user = site.configuration()["service_user"]
|
||||
uid, gid = check_system_account(user, paths.account)
|
||||
check_public_directory(paths.account / "public", uid, gid)
|
||||
check_configuration(paths.apache, site.render("apache"))
|
||||
read_managed_php_pool(site, paths.pool)
|
||||
check_configuration(
|
||||
paths.apache, site.render("apache", socket_path=paths.apache_socket)
|
||||
)
|
||||
read_managed_php_pool(site, paths.pool, socket_path=paths.socket)
|
||||
check_site_link(
|
||||
paths.enabled, Path("../sites-available") / paths.apache.name
|
||||
)
|
||||
check_services()
|
||||
check_services(paths.runtime)
|
||||
if not socket_exists(paths.socket):
|
||||
raise ValueError(
|
||||
f"PHP-FPM is missing the site socket at {paths.socket}."
|
||||
@@ -179,8 +246,8 @@ def check_installation(site, paths):
|
||||
return uid, gid
|
||||
|
||||
|
||||
def check_services():
|
||||
for service in (PHP_SERVICE, "apache2"):
|
||||
def check_services(runtime):
|
||||
for service in (runtime.service, "apache2"):
|
||||
run("/usr/sbin/service", service, "status")
|
||||
if "proxy_fcgi_module" not in run("/usr/sbin/apache2ctl", "-M"):
|
||||
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}.")
|
||||
|
||||
|
||||
def install_configurations(
|
||||
site, apache, enabled, pool, socket, *, php_settings=None
|
||||
):
|
||||
def install_configurations(site, paths, *, php_settings=None):
|
||||
from .php_pool_settings import PhpPoolSettings
|
||||
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):
|
||||
install_configuration(apache, site.render("apache"), created)
|
||||
if os.path.lexists(pool):
|
||||
_, applied = read_managed_php_pool(site, pool)
|
||||
install_configuration(
|
||||
paths.apache,
|
||||
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:
|
||||
applied = php_settings or PhpPoolSettings()
|
||||
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")
|
||||
reload_attempts.append(PHP_SERVICE)
|
||||
run("/usr/sbin/service", PHP_SERVICE, "reload")
|
||||
wait_for_socket(socket)
|
||||
reload_attempts.append(paths.runtime.service)
|
||||
run("/usr/sbin/service", paths.runtime.service, "reload")
|
||||
wait_for_socket(paths.socket)
|
||||
reload_attempts.append("apache2")
|
||||
run("/usr/sbin/service", "apache2", "reload")
|
||||
return applied
|
||||
@@ -389,6 +466,13 @@ def wait_for_socket(path):
|
||||
deadline = time.monotonic() + 15
|
||||
while time.monotonic() < deadline:
|
||||
if socket_exists(path):
|
||||
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)
|
||||
raise ValueError(f"PHP-FPM did not open {path}.")
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
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 .node_files import read_root_file, replace_configuration
|
||||
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)
|
||||
_, marker, options = content.partition("\n" + PHP_SETTINGS_COMMENT)
|
||||
try:
|
||||
@@ -22,7 +20,9 @@ def read_managed_php_pool(site, path):
|
||||
raise ValueError(
|
||||
f"Existing configuration differs at {path}."
|
||||
) 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}.")
|
||||
return content, settings
|
||||
|
||||
@@ -30,12 +30,16 @@ def read_managed_php_pool(site, path):
|
||||
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)
|
||||
paths = web.SitePaths.for_site(site)
|
||||
web.check_installation(site, paths)
|
||||
old, _ = read_managed_php_pool(site, paths.pool)
|
||||
wanted = site.render("php-fpm", php_settings=settings)
|
||||
old, _ = read_managed_php_pool(
|
||||
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)
|
||||
return settings
|
||||
|
||||
@@ -43,18 +47,18 @@ def update_php_pool(site, settings):
|
||||
def change_php_pool(paths, old, wanted):
|
||||
changed = old != wanted
|
||||
if changed:
|
||||
replace_pool_file(paths.pool, wanted)
|
||||
replace_configuration(paths.pool, wanted)
|
||||
reload_attempted = False
|
||||
try:
|
||||
web.run(web.PHP_FPM_BINARY, "--test")
|
||||
web.run(paths.runtime.binary, "--test")
|
||||
reload_attempted = True
|
||||
reload_php_pool(paths.socket)
|
||||
reload_php_pool(paths)
|
||||
except (OSError, ValueError, KeyboardInterrupt) as error:
|
||||
try:
|
||||
if changed:
|
||||
replace_pool_file(paths.pool, old)
|
||||
replace_configuration(paths.pool, old)
|
||||
if reload_attempted:
|
||||
reload_php_pool(paths.socket)
|
||||
reload_php_pool(paths)
|
||||
except (OSError, ValueError) as recovery:
|
||||
raise ValueError(
|
||||
f"{error}\nPHP-FPM rollback failed. {recovery}"
|
||||
@@ -62,21 +66,6 @@ def change_php_pool(paths, old, wanted):
|
||||
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)
|
||||
def reload_php_pool(paths):
|
||||
web.run("/usr/sbin/service", paths.runtime.service, "reload")
|
||||
web.wait_for_socket(paths.socket)
|
||||
@@ -26,7 +26,6 @@ from .web_node_tls import (
|
||||
|
||||
def retire_site(request):
|
||||
site = request.resource
|
||||
paths = web.SitePaths.for_site(site)
|
||||
with web.locked_web_node(fcntl.LOCK_EX):
|
||||
retirement = RetirementRecord(web.STATE_DIRECTORY, request)
|
||||
if retirement.is_complete:
|
||||
@@ -37,11 +36,19 @@ def retire_site(request):
|
||||
web.check_reservation(site)
|
||||
elif not (retirement.directory / "site").is_file():
|
||||
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)
|
||||
for directory in (
|
||||
web.APACHE_AVAILABLE,
|
||||
web.APACHE_ENABLED,
|
||||
web.PHP_POOL_DIRECTORY,
|
||||
paths.pool.parent,
|
||||
):
|
||||
require_root_directory(directory)
|
||||
if os.path.lexists(paths.account):
|
||||
@@ -56,7 +63,7 @@ def retire_site(request):
|
||||
require_root_directory(AUTHORIZED_KEYS)
|
||||
check_root_file(key_file, mode=0o644)
|
||||
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)
|
||||
retirement.begin()
|
||||
detach_site(site, paths, key_file, apache, retirement)
|
||||
@@ -85,9 +92,20 @@ def check_aliases(site):
|
||||
|
||||
def managed_vhosts(site, paths):
|
||||
https, enabled = https_paths(paths)
|
||||
socket = paths.apache_socket
|
||||
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:
|
||||
archive_path(path, retirement.directory / label)
|
||||
archive_path(paths.pool, retirement.directory / "php-pool")
|
||||
web.run(web.PHP_FPM_BINARY, "--test")
|
||||
web.run("/usr/sbin/service", web.PHP_SERVICE, "reload")
|
||||
web.run(paths.runtime.binary, "--test")
|
||||
web.run("/usr/sbin/service", paths.runtime.service, "reload")
|
||||
archive_path(key_file, retirement.directory / "authorized-keys")
|
||||
archive_data_directory(
|
||||
paths.account, web.WEB_ROOT, retirement.directory.name
|
||||
|
||||
@@ -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)
|
||||
@@ -100,15 +100,17 @@ def enable_https(site):
|
||||
if os.geteuid() != 0:
|
||||
raise ValueError("Run enable-https as root on the web node.")
|
||||
|
||||
with locked_web_node(fcntl.LOCK_EX):
|
||||
paths = SitePaths.for_site(site)
|
||||
apache, enabled = https_paths(paths)
|
||||
with locked_web_node(fcntl.LOCK_EX):
|
||||
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):
|
||||
config = https_configuration(site)
|
||||
def install_https_configuration(site, apache, enabled, *, socket_path=None):
|
||||
config = https_configuration(site, socket_path=socket_path)
|
||||
with configuration_installation() as (created, reload_attempts):
|
||||
install_configuration(apache, config, 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.")
|
||||
|
||||
report = {**site.manifest(), "state": "not_installed", "problem": None}
|
||||
paths = SitePaths.for_site(site)
|
||||
apache, enabled = https_paths(paths)
|
||||
try:
|
||||
apache, enabled = https_paths(SitePaths.for_site(site))
|
||||
for directory in (apache.parent, enabled.parent):
|
||||
require_root_directory(directory)
|
||||
if not (os.path.lexists(apache) or os.path.lexists(enabled)):
|
||||
return report
|
||||
with locked_web_node(fcntl.LOCK_SH):
|
||||
paths = SitePaths.for_site(site)
|
||||
check_reservation(site)
|
||||
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)
|
||||
run("/usr/sbin/apache2ctl", "configtest")
|
||||
except (OSError, ValueError) as error:
|
||||
@@ -161,7 +166,7 @@ def certbot_lineage(site):
|
||||
return CERTBOT_ROOT / "live" / name
|
||||
|
||||
|
||||
def https_configuration(site):
|
||||
def https_configuration(site, *, socket_path=None):
|
||||
lineage = certbot_lineage(site)
|
||||
name = lineage.name
|
||||
archive = CERTBOT_ROOT / "archive" / name
|
||||
@@ -205,16 +210,17 @@ def https_configuration(site):
|
||||
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)
|
||||
certificate = lineage / "fullchain.pem"
|
||||
private_key = lineage / "privkey.pem"
|
||||
return site.render(
|
||||
"apache",
|
||||
port=443,
|
||||
socket_path=socket_path,
|
||||
tls_settings=(
|
||||
"\n"
|
||||
" SSLEngine On\n"
|
||||
|
||||
Reference in new issue
Block a user