Compare commits

..
3 Commits
Author SHA1 Message Date
parkel db8bd69bbf Report unavailable feature setup queues as retryable
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-12-01 01:36:50 +01:00
parkel 5d62deafc3 Prepare Coulobre 1.0.0 release candidate 5 2026-12-01 01:30:42 +01:00
parkel af27f0cd95 Set up local hosting features from the installer and panel 2026-12-01 01:30:42 +01:00
10 changed files with 632 additions and 12 deletions

No files matched your search

+20
View File
@@ -660,6 +660,13 @@ class Installer:
if self.php:
options["COULOBRE_LOCAL_WEB_ACTIVATION"] = "1"
options["COULOBRE_WEBSITE_USAGE"] = "1"
options.update(
COULOBRE_WEB_FILE_MANAGER="1",
COULOBRE_WEBSITE_JOBS="1",
COULOBRE_LOCAL_ACCOUNT_BACKUPS="1",
)
if self.plan.access == "acme":
options["COULOBRE_LOCAL_WEB_HTTPS"] = "1"
if self.plan.dns.mode != "off":
options["COULOBRE_LOCAL_DNS_PUBLISHING"] = "1"
if self.plan.mail.mode != "off":
@@ -909,6 +916,19 @@ class Installer:
label="Enable website usage logging",
)
workers.append("coulobre-website-usage.socket")
features = ["website-files", "website-jobs", "account-backups"]
if self.plan.access == "acme":
features.append("website-https")
workers.extend(
run(
BINDIR / "python",
"-m",
"coulobre.local_feature_setup",
ASSETS,
*features,
label="Configure local hosting tools",
).splitlines()
)
for name in ("dns", "mail"):
target = getattr(self.plan, name)
if target.mode != "off":
+18 -4
View File
@@ -1053,10 +1053,10 @@ delivery and IMAP keep using their existing configuration.
#### Refresh an existing managed DKIM record
Upgrade the panels linked to a mail node before upgrading the mail node.
The updated panel accepts public keys from older mail nodes and publishes
the managed RSA key in SubjectPublicKeyInfo format. The existing private
key and selector stay in use.
Follow the [coordinated upgrade procedure](#coordinate-a-release-across-linked-mail-and-dns-receivers)
for linked deployments. The updated panel understands both RSA public key
encodings and publishes the managed RSA key in SubjectPublicKeyInfo format.
The existing private key and selector stay in use.
Open **Mail DNS check** for a managed mail domain and select
**Refresh mail DNS setup**. If Coulobre publishes the zone and manages its
@@ -1379,6 +1379,20 @@ together before enabling additional sites.
## Enable the website file manager
The installer enables the file manager, scheduled website jobs and local
account backups on new panels with local Apache and PHP. New installations
using Let's Encrypt for the panel also configure managed website certificates.
Scheduled jobs remain subject to the hosting package limit. An account
starts without a backup schedule.
On an existing installer-managed APT panel, use **Operator Settings →
Server**, **Security**, or **Backups**, and select **Enable** on the
corresponding row. The operation enables the selected local service and
briefly restarts the panel services. Check **Recent feature setup** for
the result. Managed website certificates require Certbot and an ACME
account. Keep using the manual steps below for custom installations or
configurations that the automatic setup flags for review.
The file manager connects to the web node on the same server as the panel.
It supports the document root of the primary site and each active
independent site. Customers can open **Files** for their websites.
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "coulobre-panel"
version = "1.0.0rc4"
version = "1.0.0rc5"
description = "A web hosting control panel for hosting providers and resellers."
readme = "README.md"
requires-python = ">=3.12"
+89 -1
View File
@@ -1,5 +1,6 @@
from email.utils import parseaddr
from importlib.metadata import PackageNotFoundError, version
from pathlib import Path
from django import forms
from django.conf import settings
@@ -9,14 +10,23 @@ from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.db import transaction
from django.db.models import F
from django.http import Http404
from django.shortcuts import redirect
from django.urls import reverse, reverse_lazy
from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache
from django.views.generic import FormView, TemplateView
from coulobre.local_feature_setup import LOCAL_FEATURES, PACKAGE_ASSETS
from coulobre.operator_node import SOCKET, OperatorRequest
from .access import is_tenant
from .installation_features import FEATURES, FeaturePolicy
from .models import InvitationMailSettings, PanelFeaturePolicy
from .models import (
InvitationMailSettings,
OperatorOperation,
PanelFeaturePolicy,
)
from .operator_tools import package_operation_pending, queue_operator_request
from .update_views import inspect_linked_nodes
@@ -173,8 +183,41 @@ class FeatureConfigurationView(UserPassesTestMixin, FormView):
def get_context_data(self, **kwargs):
section = self.kwargs.get("section")
form = kwargs.pop("form", None) or self.get_form()
targets = self.setup_targets(form)
section_settings = (
OPERATOR_FEATURE_SECTIONS[section][1] if section else None
)
jobs = OperatorOperation.objects.filter(
action="feature-enable",
target__in=[
key
for key, feature in LOCAL_FEATURES.items()
if section_settings is None
or feature.setting in section_settings
],
).order_by("-pk")
latest = {}
for job in jobs[:20]:
latest.setdefault(job.target, job)
setup = []
for feature in form.features_requiring_setup:
target = targets.get(feature.setting)
job = latest.get(target)
setup.append((feature, target, package_operation_pending(job)))
labels = {feature.setting: feature.label for feature in FEATURES}
return super().get_context_data(
selected_section=section,
form=form,
setup_features=setup,
setup_jobs=[
(
job,
labels[LOCAL_FEATURES[job.target].setting],
package_operation_pending(job),
)
for job in jobs[:5]
],
settings_tabs=tuple(
(key, label)
for key, (label, _) in OPERATOR_FEATURE_SECTIONS.items()
@@ -184,6 +227,51 @@ class FeatureConfigurationView(UserPassesTestMixin, FormView):
**kwargs,
)
def setup_targets(self, form):
if not (
settings.LOCAL_WEB_ACTIVATION
and Path(SOCKET).is_socket()
and PACKAGE_ASSETS.is_dir()
):
return {}
settings_needing_setup = {
feature.setting for feature in form.features_requiring_setup
}
return {
feature.setting: key
for key, feature in LOCAL_FEATURES.items()
if feature.setting in settings_needing_setup
and (
key != "account-backups"
or settings.LOCAL_DATABASE_PROVISIONING
)
}
def post(self, request, *args, **kwargs):
if "setup_feature" not in request.POST:
return super().post(request, *args, **kwargs)
target = request.POST["setup_feature"]
if target not in self.setup_targets(self.get_form()).values():
raise Http404
with transaction.atomic():
PanelFeaturePolicy.objects.get_or_create(pk=1)
PanelFeaturePolicy.objects.select_for_update().get(pk=1)
previous = (
OperatorOperation.objects.filter(action="feature-enable")
.order_by("-pk")
.first()
)
if package_operation_pending(previous):
messages.error(request, "Wait for the current feature setup.")
else:
queue_operator_request(
request.user,
OperatorRequest("feature-enable", target),
retryable=True,
)
messages.success(request, "Feature setup queued.")
return redirect(request.path)
def get_success_url(self):
if "section" in self.kwargs:
return reverse("panel:operator_settings", kwargs=self.kwargs)
+17 -2
View File
@@ -12,6 +12,7 @@ from django.utils.decorators import method_decorator
from django.utils.functional import cached_property
from django.views.decorators.cache import never_cache
from django.views.generic import FormView, TemplateView
from kombu.exceptions import OperationalError
from coulobre import remote_deployment
from coulobre.local_update import DEB_WHEEL
@@ -44,7 +45,7 @@ def package_operation_pending(job):
)
def queue_operator_request(user, spec, *, source=None):
def queue_operator_request(user, spec, *, source=None, retryable=False):
job = OperatorOperation.objects.create(
actor=user,
action=spec.action,
@@ -52,7 +53,21 @@ def queue_operator_request(user, spec, *, source=None):
plan=spec.plan,
source=source,
)
transaction.on_commit(lambda: run_operator_operation.delay(job.pk))
def dispatch():
try:
run_operator_operation.delay(job.pk)
except OperationalError:
if not retryable:
raise
OperatorOperation.objects.filter(
pk=job.pk, started_at__isnull=True, finished_at__isnull=True
).update(
finished_at=timezone.now(),
problem="The operator queue is unavailable. Try again.",
)
transaction.on_commit(dispatch)
class ServerUpdateForm(forms.Form):
@@ -42,17 +42,46 @@
</div>
</form>
</div>
{% if form.features_requiring_setup %}
{% if setup_features %}
<section class="surface" aria-labelledby="feature-setup-heading">
<header class="section-heading"><h2 id="feature-setup-heading">Requires setup</h2></header>
<div class="table-scroll">
<table>
<thead><tr><th scope="col">Feature</th><th scope="col">Setup</th></tr></thead>
<tbody>
{% for feature in form.features_requiring_setup %}
{% for feature, target, pending in setup_features %}
<tr>
<th scope="row">{{ feature.label }}</th>
<td>{% include "hosting/feature_setup.html" with show_dns_link=True %}</td>
<td>
{% if target and not pending %}
<form method="post" class="inline-form">
{% csrf_token %}
<button class="button secondary" type="submit" name="setup_feature" value="{{ target }}" aria-label="Enable {{ feature.label }}">Enable</button>
</form>
{% elif pending %}<p class="heading-meta">Setup in progress</p>{% endif %}
{% include "hosting/feature_setup.html" with show_dns_link=True %}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</section>
{% endif %}
{% if setup_jobs %}
<section class="surface" data-live-status="feature-setup">
<header class="section-heading"><h2>Recent feature setup</h2></header>
<div class="table-scroll">
<table>
<thead><tr><th scope="col">Feature</th><th scope="col">Status</th></tr></thead>
<tbody>
{% for job, label, pending in setup_jobs %}
<tr{% if pending %} data-live-pending{% endif %}>
<th scope="row">{{ label }}</th>
<td>
{% if job.finished_at %}{% if job.problem %}{{ job.problem }}{% else %}Ready{% endif %}
{% elif pending %}{{ job.state|capfirst }}
{% else %}Setup was interrupted. Try again.{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
@@ -4,9 +4,15 @@ from django.contrib.auth import get_user_model
from django.test import TestCase, override_settings
from django.urls import reverse
from django_otp.plugins.otp_totp.models import TOTPDevice
from kombu.exceptions import OperationalError
from .installation_features import FEATURES
from .models import AccountBackupJob, HostingAccount, PanelFeaturePolicy
from .models import (
AccountBackupJob,
HostingAccount,
OperatorOperation,
PanelFeaturePolicy,
)
@override_settings(LOCAL_ACCOUNT_BACKUPS=True, LOCAL_DNS_PUBLISHING=True)
@@ -49,6 +55,67 @@ class FeatureConfigurationTests(TestCase):
self.assertContains(page, f'href="{certificates.setup_url}"')
self.assertNotContains(page, 'name="LOCAL_WEB_HTTPS"')
@override_settings(LOCAL_WEB_ACTIVATION=True, WEB_FILE_MANAGER=False)
def test_feature_setup_queues_one_supported_host_operation(self):
path = reverse("panel:operator_settings", args=["server"])
payload = {"setup_feature": "website-files"}
self.sign_in(verified=False)
self.assertEqual(self.client.post(path, payload).status_code, 403)
self.sign_in()
module = "coulobre.hosting.installation_views"
with (
patch(f"{module}.Path") as path_factory,
patch(f"{module}.PACKAGE_ASSETS") as assets,
patch(
"coulobre.hosting.operator_tools.run_operator_operation.delay"
) as queue,
):
path_factory.return_value.is_socket.return_value = True
assets.is_dir.return_value = True
self.assertContains(self.client.get(path), 'value="website-files"')
self.assertEqual(
self.client.post(
path, {"setup_feature": "anything"}
).status_code,
404,
)
with self.captureOnCommitCallbacks(execute=True):
self.assertRedirects(
self.client.post(path, payload),
path,
fetch_redirect_response=False,
)
self.client.post(path, payload)
operation = OperatorOperation.objects.get()
self.assertEqual(operation.action, "feature-enable")
self.assertEqual(operation.target, "website-files")
self.assertEqual(operation.actor, self.operator)
queue.assert_called_once_with(operation.pk)
@override_settings(LOCAL_WEB_ACTIVATION=True, WEB_FILE_MANAGER=False)
def test_feature_setup_can_retry_after_the_broker_is_offline(self):
self.sign_in()
path = reverse("panel:operator_settings", args=["server"])
module = "coulobre.hosting.installation_views"
with (
patch(f"{module}.Path"),
patch(f"{module}.PACKAGE_ASSETS"),
patch(
"coulobre.hosting.operator_tools.run_operator_operation.delay",
side_effect=OperationalError("offline"),
),
self.captureOnCommitCallbacks(execute=True),
):
self.assertEqual(
self.client.post(
path, {"setup_feature": "website-files"}
).status_code,
302,
)
self.assertEqual(OperatorOperation.objects.get().state, "failed")
self.assertContains(self.client.get(path), "Try again.")
def test_paused_backup_option_blocks_new_jobs_but_archives_stay_visible(
self,
):
+319
View File
@@ -0,0 +1,319 @@
"""Install the local services used by the panel's feature controls."""
import argparse
import fcntl
import grp
import os
import pwd
import re
import subprocess
from dataclasses import dataclass
from importlib.metadata import version
from pathlib import Path
from . import local_update
from .node_files import (
check_root_file,
read_root_file,
replace_configuration,
require_root_directory,
write_new_file,
)
from .release_updates import Release, UpdateError
PACKAGE_ASSETS = Path("/usr/share/coulobre-panel/source/deploy")
SYSTEMD = Path("/etc/systemd/system")
SYSTEMCTL = "/usr/bin/systemctl"
CERTBOT = Path("/usr/bin/certbot")
@dataclass(frozen=True)
class LocalFeature:
setting: str
group: str
socket: str
worker: str = ""
drop_in: str = ""
@property
def units(self):
return (
f"{self.socket}.socket",
f"{self.socket}@.service",
*((f"{self.worker}.service",) if self.worker else ()),
*((self.drop_in,) if self.drop_in else ()),
)
@property
def activation_unit(self):
if self.worker:
return f"{self.worker}.service"
return f"{self.socket}.socket"
LOCAL_FEATURES = {
"website-files": LocalFeature(
"WEB_FILE_MANAGER",
"coulobre-file-requests",
"coulobre-website-files",
drop_in="coulobre-panel.service.d/website-files.conf",
),
"website-jobs": LocalFeature(
"WEBSITE_JOBS",
"coulobre-website-job-requests",
"coulobre-website-jobs",
worker="coulobre-website-job-worker",
),
"account-backups": LocalFeature(
"LOCAL_ACCOUNT_BACKUPS",
"coulobre-backup-requests",
"coulobre-account-backup",
worker="coulobre-backup-worker",
),
"website-https": LocalFeature(
"LOCAL_WEB_HTTPS",
"coulobre-https-provisioning",
"coulobre-https-apply",
worker="coulobre-https-provisioner",
),
}
def install_files(files, *, package_assets):
to_create = []
for source, destination, mode in files:
if package_assets:
require_root_directory(source.parent)
content = read_root_file(source)
else:
content = source.read_text(encoding="utf-8")
require_root_directory(destination.parent, create_mode=0o755)
try:
installed = read_root_file(destination, mode=mode)
except FileNotFoundError:
to_create.append((destination, content, mode))
else:
if installed != content:
raise ValueError(f"Review the existing file at {destination}.")
for destination, content, mode in to_create:
write_new_file(destination, content, mode=mode)
def create_service_identity(group, worker, command):
groups = (group, worker) if worker else (group,)
for name in dict.fromkeys(groups):
try:
grp.getgrnam(name)
except KeyError:
command("/usr/sbin/groupadd", "--system", name)
if not worker:
return
primary = grp.getgrnam(worker).gr_gid
try:
account = pwd.getpwnam(worker)
except KeyError:
command(
"/usr/sbin/useradd",
"--system",
"--gid",
worker,
"--no-create-home",
"--home-dir",
"/nonexistent",
"--shell",
"/usr/sbin/nologin",
worker,
)
else:
if (
account.pw_uid == 0
or account.pw_gid != primary
or account.pw_dir != "/nonexistent"
or account.pw_shell != "/usr/sbin/nologin"
or set(os.getgrouplist(worker, primary)) != {primary}
):
raise ValueError(f"Review the existing service user {worker}.")
def prepare_https(assets, command):
from .web_node_tls import ACME_WEBROOT, CERTBOT_ROOT
if not CERTBOT.is_file() or not (CERTBOT_ROOT / "accounts").is_dir():
raise ValueError(
"Set up Certbot with an ACME account for hosted websites first."
)
files = (
(
assets / "apache/acme.conf.example",
Path("/etc/apache2/conf-available/coulobre-acme.conf"),
0o644,
),
(
assets / "certbot/reload-apache.sh",
CERTBOT_ROOT / "renewal-hooks/deploy/coulobre-apache",
0o755,
),
)
for path in (
ACME_WEBROOT,
ACME_WEBROOT / ".well-known",
ACME_WEBROOT / ".well-known/acme-challenge",
CERTBOT_ROOT / "renewal-hooks",
):
require_root_directory(path, create_mode=0o755)
install_files(files, package_assets=assets == PACKAGE_ASSETS)
command("/usr/sbin/a2enmod", "ssl")
command("/usr/sbin/a2enconf", "coulobre-acme")
command("/usr/sbin/apache2ctl", "configtest")
def prepare_feature(key, assets, command):
feature = LOCAL_FEATURES[key]
install_files(
(
(assets / "systemd" / unit, SYSTEMD / unit, 0o644)
for unit in feature.units
),
package_assets=assets == PACKAGE_ASSETS,
)
if key == "website-https":
prepare_https(assets, command)
create_service_identity(feature.group, feature.worker, command)
return feature
def enable_setting(text, setting):
entry = f"COULOBRE_{setting}"
pattern = rf"^[ \t]*{entry}[ \t]*=.*$"
matches = re.findall(pattern, text, flags=re.MULTILINE)
if not matches:
if text.rstrip("\n").endswith("\\"):
raise ValueError(f"Review the end of {local_update.CONFIG}.")
if text and not text.endswith("\n"):
text += "\n"
return text + f"{entry}=1\n"
if matches == [f"{entry}=1"]:
return text
if matches == [f"{entry}=0"]:
return re.sub(pattern, f"{entry}=1", text, flags=re.MULTILINE)
raise ValueError(f"Review the existing {entry} setting.")
def active(unit):
return (
subprocess.run(
[SYSTEMCTL, "is-active", "--quiet", unit],
stdin=subprocess.DEVNULL,
env=local_update.ROOT_COMMAND_ENV,
timeout=15,
check=False,
).returncode
== 0
)
def restart_panel(command, hostname):
units = (local_update.PANEL, local_update.WORKER, local_update.BEAT)
command(SYSTEMCTL, "restart", *units, timeout=600)
with open(os.devnull, "wb") as log:
release = Release(version("coulobre-panel"), "", False, "")
local_update.verify_panel(hostname, release, log)
def enable_feature(key, command):
try:
plan = local_update.installation_plan()
except UpdateError as error:
raise ValueError(str(error)) from None
if os.environ.get("COULOBRE_LOCAL_WEB_ACTIVATION") != "1":
raise ValueError("Enable local website provisioning first.")
if key == "account-backups" and (
os.environ.get("COULOBRE_LOCAL_DATABASE_PROVISIONING") != "1"
):
raise ValueError("Enable local database provisioning first.")
require_root_directory(PACKAGE_ASSETS)
config = local_update.CONFIG
require_root_directory(config.parent)
check_root_file(config, mode=0o600)
lock = local_update.LOCK
require_root_directory(lock.parent, create_mode=0o700)
fd = os.open(lock, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, "rb") as stream:
try:
fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
raise ValueError(
"An installation update is running. Try again."
) from None
if local_update.read_status().get("state") in {
"running",
"recovery_required",
}:
raise ValueError("Resolve the current installation update first.")
apply_feature(key, plan["hostname"], config, command)
return {"enabled": True}
def apply_feature(key, hostname, config, command):
original = read_root_file(config, mode=0o600)
updated = enable_setting(original, LOCAL_FEATURES[key].setting)
feature = prepare_feature(key, PACKAGE_ASSETS, command)
unit = feature.activation_unit
units = tuple(dict.fromkeys((unit, f"{feature.socket}.socket")))
inactive = tuple(name for name in units if not active(name))
already_running = bool(feature.worker and unit not in inactive)
panel_restart_started = False
command(SYSTEMCTL, "daemon-reload")
try:
replace_configuration(config, updated, mode=0o600)
command(
SYSTEMCTL,
"restart" if already_running else "start",
unit,
timeout=600,
)
if key == "website-https":
command(SYSTEMCTL, "reload", "apache2.service")
panel_restart_started = True
restart_panel(command, hostname)
if not all(active(name) for name in units):
raise ValueError("The feature service did not start.")
command(SYSTEMCTL, "enable", unit)
except (OSError, ValueError, UpdateError) as error:
try:
replace_configuration(config, original, mode=0o600)
if inactive:
command(SYSTEMCTL, "stop", *inactive)
if already_running:
command(SYSTEMCTL, "restart", unit, timeout=600)
if panel_restart_started:
restart_panel(command, hostname)
except (OSError, ValueError, UpdateError):
raise ValueError(
"Feature setup failed. Check the panel and service journal."
) from None
raise ValueError(str(error)) from None
def main():
from .operator_node import command
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("assets", type=Path)
parser.add_argument("feature", choices=LOCAL_FEATURES, nargs="+")
args = parser.parse_args()
if os.geteuid() != 0:
parser.exit(1, "Run local feature setup as root.\n")
try:
for key in args.feature:
print(
prepare_feature(
key, args.assets.resolve(), command
).activation_unit
)
except (OSError, ValueError) as error:
parser.exit(1, f"{error}\n")
if __name__ == "__main__":
main()
+8
View File
@@ -5,6 +5,7 @@ import subprocess
from dataclasses import dataclass
from pathlib import Path
from .local_feature_setup import LOCAL_FEATURES, enable_feature
from .node_files import locked_root_directory
from .node_requests import serve_apply_request
from .release_updates import UpdateError, version_key
@@ -26,6 +27,7 @@ ACTIONS = (
"database-report",
"system-backup",
"server-tls",
"feature-enable",
)
APT = "/usr/bin/apt-get"
PANEL_PACKAGE = "coulobre-panel"
@@ -52,6 +54,9 @@ class OperatorRequest:
from .system_backup import archive_id
archive_id(self.target)
elif self.action == "feature-enable":
if self.target not in LOCAL_FEATURES:
raise ValueError("Choose a supported local feature.")
elif self.action == "package-preview" and self.target == "coulobre":
pass
elif self.target:
@@ -242,6 +247,9 @@ def apply_request(request):
from .server_tls import server_tls_report
return server_tls_report()
if request.action == "feature-enable":
with locked_root_directory(STATE):
return enable_feature(request.target, command)
if request.action == "system-backup":
if os.environ.get("COULOBRE_SYSTEM_BACKUPS") != "1":
raise ValueError(
+60
View File
@@ -0,0 +1,60 @@
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest import TestCase
from unittest.mock import Mock, patch
from . import local_feature_setup as setup
from .operator_node import OperatorRequest
class LocalFeatureSetupTests(TestCase):
def test_existing_environment_changes_only_the_selected_setting(self):
original = "COULOBRE_DB_NAME=coulobre_panel\nCOULOBRE_WEBSITE_JOBS=0\n"
self.assertEqual(
setup.enable_setting(original, "WEBSITE_JOBS"),
original.replace("WEBSITE_JOBS=0", "WEBSITE_JOBS=1"),
)
self.assertEqual(
setup.enable_setting(original, "WEB_FILE_MANAGER"),
original + "COULOBRE_WEB_FILE_MANAGER=1\n",
)
with self.assertRaisesRegex(ValueError, "Review the existing"):
setup.enable_setting(
original + 'COULOBRE_WEBSITE_JOBS="1"\n', "WEBSITE_JOBS"
)
def test_failed_activation_restores_the_original_environment(self):
with TemporaryDirectory() as directory:
config = Path(directory) / "panel.env"
original = "COULOBRE_DB_NAME=coulobre_panel\n"
config.write_text(original)
unit = setup.LOCAL_FEATURES["website-files"].activation_unit
def command(_, action, *args, **kwargs):
if action == "start":
raise ValueError("Cannot start the socket.")
with (
patch.object(setup, "read_root_file", return_value=original),
patch.object(
setup,
"prepare_feature",
return_value=setup.LOCAL_FEATURES["website-files"],
),
patch.object(setup, "active", return_value=False),
patch.object(setup, "restart_panel") as restart,
self.assertRaisesRegex(ValueError, "Cannot start the socket"),
):
apply = Mock(side_effect=command)
setup.apply_feature(
"website-files", "host.test", config, apply
)
self.assertEqual(config.read_text(), original)
apply.assert_any_call(setup.SYSTEMCTL, "stop", unit)
restart.assert_not_called()
def test_receiver_accepts_only_allowlisted_features(self):
spec = OperatorRequest("feature-enable", "website-files")
self.assertEqual(OperatorRequest.from_manifest(spec.manifest()), spec)
with self.assertRaisesRegex(ValueError, "supported local feature"):
OperatorRequest("feature-enable", "../../other")