Standardize panel layouts and improve live service views #167

Merged
parkel merged 2 commits from fix/consistent-panel-page-layout into main 2026-11-24 00:45:27 +01:00
12 changed files with 314 additions and 114 deletions
Showing only changes of commit 605e4f9ffd - Show all commits

No files matched your search

+53 -1
View File
@@ -1,18 +1,28 @@
from datetime import timedelta
from pathlib import Path
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.core.exceptions import PermissionDenied
from django.http import HttpResponseBadRequest
from django.shortcuts import redirect
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache
from django.views.generic import TemplateView
from coulobre.operator_node import SERVICES as CONTROL_UNITS
from coulobre.operator_node import SOCKET, OperatorRequest
from coulobre.service_health import HEALTH_DETAILS, SERVICES, HealthResult
from .access import OperatorOnlyMixin
from .models import ServiceHealth
from .models import OperatorOperation, ServiceHealth
from .operator_tools import queue_operator_request
STALE_AFTER = timedelta(minutes=5)
SERVICE_ACTIONS = ("reload", "restart")
CONTROL_TARGETS = {unit: target for target, unit in CONTROL_UNITS.items()}
STATUS = {
HealthResult.ACTIVE: ("Active", "ready"),
HealthResult.INACTIVE: ("Unavailable", "suspended"),
@@ -29,8 +39,37 @@ class ServiceHealthView(
permission_required = "hosting.view_servicehealth"
template_name = "hosting/service_health.html"
def can_control(self):
user = self.request.user
return user.is_superuser and user.is_verified()
def post(self, request, *args, **kwargs):
if not self.can_control():
raise PermissionDenied
action = request.POST.get("action", "")
target = request.POST.get("target", "")
if action not in SERVICE_ACTIONS or target not in {
CONTROL_TARGETS.get(SERVICES[service][1])
for node in settings.SERVICE_HEALTH_TARGETS
if node.transport == "local"
for service in node.services
}:
return HttpResponseBadRequest("Choose a controlled local service.")
if not Path(SOCKET).is_socket():
messages.error(
request, "The local operator worker is unavailable."
)
else:
queue_operator_request(
request.user, OperatorRequest(action, target)
)
messages.success(request, "Service operation queued.")
return redirect("panel:service_health")
def get_context_data(self, **kwargs):
targets = settings.SERVICE_HEALTH_TARGETS
can_control = self.can_control()
controls_available = can_control and Path(SOCKET).is_socket()
readings = {
(reading.node, reading.service): reading
for reading in ServiceHealth.objects.filter(
@@ -48,17 +87,30 @@ class ServiceHealthView(
readings.get((target.node, service)),
cutoff,
)
| {
"control_target": CONTROL_TARGETS.get(
SERVICES[service][1]
)
}
for service in target.services
],
)
for target in targets
],
controls_available=controls_available,
show_operation_history=can_control,
jobs=OperatorOperation.objects.filter(
action__in=SERVICE_ACTIONS,
).order_by("-pk")[:20]
if can_control
else (),
**kwargs,
)
def service_row(service, reading, cutoff):
row = {
"key": service,
"name": SERVICES[service][0],
"status": "Unknown",
"style": "pending",
+61 -54
View File
@@ -3,69 +3,61 @@ from pathlib import Path
from django import forms
from django.contrib import messages
from django.db import transaction
from django.db import DatabaseError, connection, transaction
from django.shortcuts import redirect
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache
from django.views.generic import FormView, TemplateView
from coulobre.operator_node import SERVICES, SOCKET, OperatorRequest
from coulobre.operator_node import (
DATABASE_COUNTERS_QUERY,
DATABASE_VERSION_QUERY,
SOCKET,
OperatorRequest,
database_report_from_rows,
)
from .account_administration import OperatorAuthorization
from .models import OperatorOperation
from .tasks import run_operator_operation
from .update_views import inspect_linked_nodes
TOOL_ACTIONS = {
"packages": (
"Server package updates",
("package-preview", "package-upgrade"),
),
"services": ("System services", ("reload", "restart")),
"database": ("Database monitor", ("database-report",)),
}
ACTION_LABELS = {
"package-preview": "Review available updates",
"package-upgrade": "Apply reviewed updates",
"reload": "Reload",
"restart": "Restart",
"database-report": "Collect MariaDB status",
}
class OperatorToolForm(forms.Form):
action = forms.ChoiceField()
preview_id = forms.IntegerField(required=False, widget=forms.HiddenInput)
target = forms.ChoiceField(
required=False,
choices=[
("", "Select a service"),
*[(key, label) for key, label in SERVICES.items()],
],
def queue_operator_request(user, spec, *, source=None):
job = OperatorOperation.objects.create(
actor=user,
action=spec.action,
target=spec.target,
plan=spec.plan,
source=source,
)
transaction.on_commit(lambda: run_operator_operation.delay(job.pk))
class ServerUpdateForm(forms.Form):
action = forms.ChoiceField(choices=ACTION_LABELS.items())
preview_id = forms.IntegerField(required=False, widget=forms.HiddenInput)
confirm = forms.BooleanField(
required=False, label="I reviewed the change and want to apply it"
)
def __init__(self, *args, actions, preview, **kwargs):
def __init__(self, *args, preview, **kwargs):
super().__init__(*args, **kwargs)
self.preview = preview
self.initial["preview_id"] = preview.pk if preview else None
self.fields["action"].choices = [
(action, ACTION_LABELS[action]) for action in actions
]
if "reload" not in actions:
self.fields.pop("target")
if actions == ("database-report",):
self.fields.pop("confirm")
def clean(self):
data = super().clean()
if self.errors:
return data
action = data["action"]
if action in {"reload", "restart", "package-upgrade"} and not data.get(
"confirm"
):
if action == "package-upgrade" and not data.get("confirm"):
self.add_error(
"confirm", "Confirm this change before applying it."
)
@@ -80,16 +72,15 @@ class OperatorToolForm(forms.Form):
)
plan = self.preview.result.get("fingerprint", "")
try:
self.spec = OperatorRequest(action, data.get("target", ""), plan)
self.spec = OperatorRequest(action, plan=plan)
except ValueError as error:
raise forms.ValidationError(str(error)) from error
return data
class OperatorToolsView(OperatorAuthorization, FormView):
form_class = OperatorToolForm
template_name = "hosting/operator_tools.html"
page = "services"
class ServerUpdatesView(OperatorAuthorization, FormView):
form_class = ServerUpdateForm
template_name = "hosting/server_updates.html"
def preview(self):
return (
@@ -104,20 +95,14 @@ class OperatorToolsView(OperatorAuthorization, FormView):
)
def get_form_kwargs(self):
return super().get_form_kwargs() | {
"actions": TOOL_ACTIONS[self.page][1],
"preview": self.preview() if self.page == "packages" else None,
}
return super().get_form_kwargs() | {"preview": self.preview()}
def get_context_data(self, **kwargs):
title, actions = TOOL_ACTIONS[self.page]
return super().get_context_data(
title=title,
page=self.page,
available=Path(SOCKET).is_socket(),
jobs=OperatorOperation.objects.filter(action__in=actions).order_by(
"-pk"
)[:20],
jobs=OperatorOperation.objects.filter(
action__in=ACTION_LABELS
).order_by("-pk")[:20],
**kwargs,
)
@@ -145,18 +130,40 @@ class OperatorToolsView(OperatorAuthorization, FormView):
"package update.",
)
return self.form_invalid(form)
job = OperatorOperation.objects.create(
actor=self.request.user,
action=spec.action,
target=spec.target,
plan=spec.plan,
queue_operator_request(
self.request.user,
spec,
source=form.preview if spec.action == "package-upgrade" else None,
)
transaction.on_commit(lambda: run_operator_operation.delay(job.pk))
messages.success(self.request, "Host operation queued.")
return redirect(self.request.path)
def current_database_report():
if connection.vendor != "mysql":
return None
try:
with connection.cursor() as cursor:
cursor.execute(DATABASE_VERSION_QUERY)
version = cursor.fetchone()
cursor.execute(DATABASE_COUNTERS_QUERY)
return database_report_from_rows([version, *cursor.fetchall()])
except (DatabaseError, ValueError):
return None
@method_decorator(never_cache, name="dispatch")
class DatabaseMonitorView(OperatorAuthorization, TemplateView):
template_name = "hosting/database_monitor.html"
def get_context_data(self, **kwargs):
return super().get_context_data(
report=current_database_report(),
observed_at=timezone.now(),
**kwargs,
)
class ConnectedNodesView(OperatorAuthorization, TemplateView):
template_name = "hosting/connected_nodes.html"
@@ -0,0 +1,26 @@
{% extends "hosting/workspace_page.html" %}
{% block title %}Database monitor · Coulobre Panel{% endblock %}
{% block page_title %}Database monitor{% endblock %}
{% block page_actions %}
<a class="button secondary" href="{% url 'panel:database_monitor' %}">Refresh status</a>
{% endblock %}
{% block page_content %}
<section class="surface" aria-labelledby="database-status" data-live-status="database">
<header class="section-heading">
<h2 id="database-status">MariaDB status</h2>
{% if report %}<time class="muted" datetime="{{ observed_at|date:'c' }}">{{ observed_at|date:"j M Y, H:i:s" }} UTC</time>{% endif %}
</header>
{% if report %}
<dl class="details">
<div><dt>Status</dt><dd><span class="status ready">Active</span></dd></div>
<div><dt>Version</dt><dd>{{ report.database_version }}</dd></div>
<div><dt>Current connections</dt><dd>{{ report.counters.Threads_connected|default:"Unavailable" }}</dd></div>
<div><dt>Slow queries</dt><dd>{{ report.counters.Slow_queries|default:"Unavailable" }}</dd></div>
<div><dt>Uptime (seconds)</dt><dd>{{ report.counters.Uptime|default:"Unavailable" }}</dd></div>
<div><dt>Slow query logging</dt><dd>{{ report.slow_logging|yesno:"Enabled,Disabled" }}</dd></div>
</dl>
{% else %}
<p class="empty">MariaDB measurements are unavailable on this installation.</p>
{% endif %}
</section>
{% endblock %}
@@ -0,0 +1,14 @@
<section class="surface" aria-labelledby="operation-history" data-live-status="operator-history">
<header class="section-heading"><h2 id="operation-history">Operation history</h2></header>
{% for job in jobs %}
<details class="section-text">
<summary>{{ job.requested_at|date:"j M Y H:i" }} UTC · {{ job.action|capfirst }}{% if job.target %} {{ job.target }}{% endif %} · {{ job.state|capfirst }}</summary>
{% if job.actor %}<p>Requested by {{ job.actor }}</p>{% endif %}
{% if job.problem %}<p>{{ job.problem }}</p>{% endif %}
{% if job.action == 'package-preview' and job.result.fingerprint %}
<p>{{ job.result.count }} package{{ job.result.count|pluralize }} ready to update.</p>
<ul>{% for package in job.result.packages %}<li><code>{{ package }}</code></li>{% endfor %}</ul>
{% endif %}
</details>
{% empty %}<p class="empty">No operations yet.</p>{% endfor %}
</section>
@@ -1,29 +0,0 @@
{% extends "hosting/base.html" %}
{% block title %}{{ title }} · Coulobre Panel{% endblock %}
{% block content %}
<header class="page-heading"><h1>{{ title }}</h1></header>
<div class="form-actions">
{% if page == 'packages' %}<a href="{% url 'panel:updates' %}">Coulobre updates</a>
{% elif page == 'services' %}<a href="{% url 'panel:service_health' %}">Service health</a>{% endif %}
</div>
{% for message in messages %}<p class="notice" role="status">{{ message }}</p>{% endfor %}
<section class="surface editor-surface">
{% if available %}<form method="post" class="editor">{% csrf_token %}{{ form.as_div }}<button class="button primary" type="submit">Queue operation</button></form>
{% else %}<p>Enable the operator service on the host to run these operations.</p>{% endif %}
</section>
<section class="surface" aria-label="Operation history">
<header class="section-heading"><h2>Operation history</h2></header>
{% for job in jobs %}
<details class="section-text"><summary>{{ job.requested_at|date:"j M Y H:i" }} · {{ job.action }}{% if job.target %} · {{ job.target }}{% endif %} · {{ job.state|capfirst }}</summary>
{% if job.problem %}<p>{{ job.problem }}</p>{% endif %}
{% if job.action == 'package-preview' and job.result.fingerprint %}
<p>{{ job.result.count }} package{{ job.result.count|pluralize }} ready to update.</p>
<ul>{% for package in job.result.packages %}<li><code>{{ package }}</code></li>{% endfor %}</ul>
{% elif job.action == 'database-report' and job.result.database_version %}
<p>MariaDB {{ job.result.database_version }} · Slow query logging {{ job.result.slow_logging|yesno:"enabled,disabled" }}</p>
<dl>{% for key, value in job.result.counters.items %}<dt>{{ key }}</dt><dd>{{ value }}</dd>{% endfor %}</dl>
{% endif %}
</details>
{% empty %}<p class="empty">No operations yet.</p>{% endfor %}
</section>
{% endblock %}
@@ -0,0 +1,33 @@
{% extends "hosting/update_workspace.html" %}
{% block title %}Server package updates · Coulobre Panel{% endblock %}
{% block page_content %}
<section class="surface editor-surface" data-live-status="package-preview">
{% if available %}
<form method="post" class="form-actions">
{% csrf_token %}
<button class="button secondary" name="action" value="package-preview" type="submit">Review available updates</button>
</form>
{{ form.non_field_errors }}
{{ form.action.errors }}
{% if form.preview.result.count %}
<form method="post" class="editor">
{% csrf_token %}
{{ form.preview_id }}
{{ form.preview_id.errors }}
<ul class="workspace-list">
{% for package in form.preview.result.packages %}<li><code>{{ package }}</code></li>{% endfor %}
</ul>
<div>
<label for="{{ form.confirm.id_for_label }}">{{ form.confirm }} {{ form.confirm.label }}</label>
{{ form.confirm.errors }}
</div>
<button class="button primary" name="action" value="package-upgrade" type="submit">Apply reviewed updates</button>
</form>
{% else %}
{% if form.preview %}<p>No packages are ready to update.</p>{% endif %}
{{ form.preview_id.errors }}
{% endif %}
{% else %}<p>Enable the operator service on the host to review server updates.</p>{% endif %}
</section>
{% include "hosting/operator_operation_history.html" %}
{% endblock %}
@@ -1,11 +1,12 @@
{% extends "hosting/base.html" %}
{% extends "hosting/workspace_page.html" %}
{% block title %}Service health · Coulobre Panel{% endblock %}
{% block title %}System Services · Coulobre Panel{% endblock %}
{% block page_title %}System Services{% endblock %}
{% block content %}
<header class="page-heading">
<h1>Service health</h1>
</header>
{% block page_content %}
{% if show_operation_history and not controls_available %}
<p class="notice">Enable the local operator worker to reload or restart services.</p>
{% endif %}
{% for node, services in nodes %}
<section class="surface" aria-labelledby="health-{{ node.node }}">
<header class="section-heading">
@@ -20,15 +21,28 @@
<th scope="col">Status</th>
<th scope="col">Last check (UTC)</th>
<th scope="col">Details</th>
{% if controls_available and node.transport == 'local' %}<th scope="col">Actions</th>{% endif %}
</tr>
</thead>
<tbody>
{% for service in services %}
<tr>
<th scope="row">{{ service.name }}</th>
<td><span class="status {{ service.style }}">{{ service.status }}</span></td>
<td>{% if service.observed_at %}<time datetime="{{ service.observed_at|date:'c' }}">{{ service.observed_at|date:'Y-m-d H:i:s' }}</time>{% else %}—{% endif %}</td>
<td>{{ service.detail }}</td>
<td data-live-status="{{ node.node }}-{{ service.key }}-status"><span class="status {{ service.style }}">{{ service.status }}</span></td>
<td data-live-status="{{ node.node }}-{{ service.key }}-checked">{% if service.observed_at %}<time datetime="{{ service.observed_at|date:'c' }}">{{ service.observed_at|date:'Y-m-d H:i:s' }}</time>{% else %}—{% endif %}</td>
<td data-live-status="{{ node.node }}-{{ service.key }}-detail">{{ service.detail }}</td>
{% if controls_available and node.transport == 'local' %}
<td>
{% if service.control_target %}
<form class="form-actions" method="post" action="{% url 'panel:service_health' %}">
{% csrf_token %}
<input type="hidden" name="target" value="{{ service.control_target }}">
<button type="submit" class="button secondary" name="action" value="reload" aria-label="Reload {{ service.name }}">Reload</button>
<button type="submit" class="button secondary" name="action" value="restart" aria-label="Restart {{ service.name }}">Restart</button>
</form>
{% else %}—{% endif %}
</td>
{% endif %}
</tr>
{% endfor %}
</tbody>
@@ -40,4 +54,7 @@
<p class="empty">Set <code>COULOBRE_SERVICE_HEALTH</code> in <code>/etc/coulobre/panel.env</code> and enable <code>coulobre-health.timer</code> to collect service observations.</p>
</section>
{% endfor %}
{% if show_operation_history %}
{% include "hosting/operator_operation_history.html" %}
{% endif %}
{% endblock %}
@@ -12,7 +12,7 @@ from django_otp.plugins.otp_totp.models import TOTPDevice
from coulobre.mail_queue import MailQueueAction, change_queue_entry
from coulobre.operator_node import OperatorRequest, main, packages
from .models import PanelTheme
from .models import OperatorOperation, PanelTheme
class OperatorRequestTests(SimpleTestCase):
@@ -117,3 +117,32 @@ class ThemePreviewTests(TestCase):
)
self.assertRedirects(self.client.post(url, {"action": "install"}), url)
self.assertEqual(PanelTheme.objects.get().name, "Test theme")
class DatabaseMonitorTests(TestCase):
def test_verified_operator_sees_database_status_without_queueing_a_job(
self,
):
operator = get_user_model().objects.create_superuser("operator")
self.client.force_login(operator)
url = reverse("panel:database_monitor")
self.assertEqual(self.client.get(url).status_code, 403)
device = TOTPDevice.objects.create(user=operator, name="test")
session = self.client.session
session["otp_device_id"] = device.persistent_id
session.save()
report = {
"database_version": "11.8.6-MariaDB",
"slow_logging": True,
"counters": {"Threads_connected": "3", "Slow_queries": "0"},
}
with patch(
"coulobre.hosting.operator_tools.current_database_report",
return_value=report,
):
response = self.client.get(url)
self.assertContains(response, "11.8.6-MariaDB")
self.assertContains(response, "Current connections")
self.assertContains(response, "Enabled")
self.assertFalse(OperatorOperation.objects.exists())
self.assertIn("no-store", response["Cache-Control"])
+47 -1
View File
@@ -10,6 +10,7 @@ from django.core.management import call_command
from django.test import SimpleTestCase, TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from django_otp.plugins.otp_totp.models import TOTPDevice
from coulobre.service_health import (
HealthResult,
@@ -20,7 +21,13 @@ from coulobre.service_health import (
main,
)
from .models import Customer, DnsZoneDefaults, Reseller, ServiceHealth
from .models import (
Customer,
DnsZoneDefaults,
OperatorOperation,
Reseller,
ServiceHealth,
)
TARGETS = (
HealthTarget("panel-01", "local", ("mariadb", "apache")),
@@ -165,6 +172,45 @@ class ServiceHealthPanelTests(TestCase):
self.client.force_login(user)
self.assertEqual(self.client.get(url).status_code, status)
def test_only_verified_admins_can_queue_configured_local_service_actions(
self,
):
url = reverse("panel:service_health")
restart = {"action": "restart", "target": "apache"}
self.client.force_login(self.operator)
self.assertEqual(self.client.post(url, restart).status_code, 403)
self.client.force_login(self.admin)
self.assertEqual(self.client.post(url, restart).status_code, 403)
device = TOTPDevice.objects.create(user=self.admin, name="test")
session = self.client.session
session["otp_device_id"] = device.persistent_id
session.save()
with (
patch(
"coulobre.hosting.health_views.Path.is_socket",
return_value=True,
),
patch(
"coulobre.hosting.operator_tools.run_operator_operation.delay"
) as delay,
):
response = self.client.get(url)
self.assertContains(response, 'aria-label="Restart Apache"')
self.assertContains(response, 'aria-label="Reload Apache"')
self.assertNotContains(response, 'aria-label="Restart Postfix"')
remote = {"action": "restart", "target": "smtp"}
self.assertEqual(self.client.post(url, remote).status_code, 400)
self.assertFalse(OperatorOperation.objects.exists())
with self.captureOnCommitCallbacks(execute=True):
self.assertRedirects(self.client.post(url, restart), url)
job = OperatorOperation.objects.get()
self.assertEqual(
(job.action, job.target, job.actor),
("restart", "apache", self.admin),
)
delay.assert_called_once_with(job.pk)
@override_settings(
LOCAL_DNS_PUBLISHING=True,
HOSTING_NAMESERVERS=("ns.example.net",),
+5 -4
View File
@@ -54,8 +54,9 @@ from .mail_queue_views import MailQueueIndex, MailQueueView, mail_queue_action
from .operator_backups import OperatorBackupsView
from .operator_tools import (
ConnectedNodesView,
DatabaseMonitorView,
HttpDefaultsView,
OperatorToolsView,
ServerUpdatesView,
)
from .panel_content import (
AnnouncementView,
@@ -190,17 +191,17 @@ urlpatterns = [
),
path(
"service-health/actions/",
OperatorToolsView.as_view(page="services"),
ServiceHealthView.as_view(),
name="operator_service_actions",
),
path(
"updates/server-packages/",
OperatorToolsView.as_view(page="packages"),
ServerUpdatesView.as_view(),
name="server_updates",
),
path(
"server/database/",
OperatorToolsView.as_view(page="database"),
DatabaseMonitorView.as_view(),
name="database_monitor",
),
path("themes/", ThemeManagementView.as_view(), name="theme_management"),
+2 -6
View File
@@ -71,6 +71,7 @@ WORKSPACE_PARENT_ROUTES = {
"operator_settings": ("operator_settings", ("general",)),
"http_defaults": ("http_defaults", ("apache",)),
"server_updates": ("updates", ()),
"operator_service_actions": ("service_health", ()),
"mail_queue": ("mail_queue_index", ()),
"reseller": ("resellers", ()),
"reseller_edit": ("resellers", ()),
@@ -412,12 +413,7 @@ def groups_for(request, *, customer, manager):
)
if user.is_superuser:
server.append(link("connected_nodes", "Connected Nodes"))
admin_tools.extend(
(
link("operator_service_actions", "Service actions"),
link("database_monitor", "DB Monitor"),
)
)
admin_tools.append(link("database_monitor", "DB Monitor"))
groups = [
("Account Manager", accounts),
("Server Manager", server),
+17 -9
View File
@@ -27,6 +27,11 @@ ACTIONS = (
"server-tls",
)
APT = "/usr/bin/apt-get"
DATABASE_VERSION_QUERY = "SELECT @@version, @@slow_query_log"
DATABASE_COUNTERS_QUERY = (
"SHOW GLOBAL STATUS WHERE "
"Variable_name IN ('Threads_connected','Slow_queries','Uptime')"
)
@dataclass(frozen=True)
@@ -142,26 +147,29 @@ def packages(request):
def database_report():
query = (
"SELECT @@version, @@slow_query_log; SHOW GLOBAL STATUS WHERE "
"Variable_name IN ('Threads_connected','Slow_queries','Uptime');"
)
output = command(
"/usr/bin/mariadb",
"--batch",
"--skip-column-names",
"--protocol=socket",
"--execute",
query,
f"{DATABASE_VERSION_QUERY}; {DATABASE_COUNTERS_QUERY};",
)
rows = [row.split("\t") for row in output.splitlines()]
if not rows or any(len(row) != 2 for row in rows):
return database_report_from_rows(
[row.split("\t") for row in output.splitlines()]
)
def database_report_from_rows(rows):
if not rows or any(row is None or len(row) != 2 for row in rows):
raise ValueError("MariaDB returned an invalid status report.")
version, slow_log = rows[0]
counters = {key: value for key, value in rows[1:] if value.isdecimal()}
counters = {
key: str(value) for key, value in rows[1:] if str(value).isdecimal()
}
return {
"database_version": version[:80],
"slow_logging": slow_log == "1",
"slow_logging": str(slow_log).upper() in {"1", "ON"},
"counters": counters,
}