Set up local hosting features from the installer and panel
This commit is contained in:
1 parent
aec32f1c91
commit
af27f0cd95
8 files changed
+584
-9
No files matched your search
@@ -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,37 @@ 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)
|
||||
jobs = OperatorOperation.objects.filter(
|
||||
action="feature-enable",
|
||||
).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]
|
||||
if job.target in LOCAL_FEATURES
|
||||
]
|
||||
if section != "general"
|
||||
else ()
|
||||
),
|
||||
settings_tabs=tuple(
|
||||
(key, label)
|
||||
for key, (label, _) in OPERATOR_FEATURE_SECTIONS.items()
|
||||
@@ -184,6 +223,49 @@ 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)
|
||||
)
|
||||
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)
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -6,7 +6,12 @@ from django.urls import reverse
|
||||
from django_otp.plugins.otp_totp.models import TOTPDevice
|
||||
|
||||
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 +54,44 @@ 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)
|
||||
|
||||
def test_paused_backup_option_blocks_new_jobs_but_archives_stay_visible(
|
||||
self,
|
||||
):
|
||||
|
||||
@@ -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()
|
||||
@@ -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(
|
||||
|
||||
@@ -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")
|
||||
Reference in new issue
Block a user