Show live database status and local service actions
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s

This commit is contained in:
parkel committed 2026-11-24 00:42:43 +01:00
1 parent 634296d988
commit 605e4f9ffd
12 files changed
+314 -114

No files matched your search

+53 -1
View File
@@ -1,18 +1,28 @@
from datetime import timedelta from datetime import timedelta
from pathlib import Path
from django.conf import settings from django.conf import settings
from django.contrib import messages
from django.contrib.auth.mixins import PermissionRequiredMixin 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 import timezone
from django.utils.decorators import method_decorator from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache from django.views.decorators.cache import never_cache
from django.views.generic import TemplateView 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 coulobre.service_health import HEALTH_DETAILS, SERVICES, HealthResult
from .access import OperatorOnlyMixin 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) STALE_AFTER = timedelta(minutes=5)
SERVICE_ACTIONS = ("reload", "restart")
CONTROL_TARGETS = {unit: target for target, unit in CONTROL_UNITS.items()}
STATUS = { STATUS = {
HealthResult.ACTIVE: ("Active", "ready"), HealthResult.ACTIVE: ("Active", "ready"),
HealthResult.INACTIVE: ("Unavailable", "suspended"), HealthResult.INACTIVE: ("Unavailable", "suspended"),
@@ -29,8 +39,37 @@ class ServiceHealthView(
permission_required = "hosting.view_servicehealth" permission_required = "hosting.view_servicehealth"
template_name = "hosting/service_health.html" 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): def get_context_data(self, **kwargs):
targets = settings.SERVICE_HEALTH_TARGETS targets = settings.SERVICE_HEALTH_TARGETS
can_control = self.can_control()
controls_available = can_control and Path(SOCKET).is_socket()
readings = { readings = {
(reading.node, reading.service): reading (reading.node, reading.service): reading
for reading in ServiceHealth.objects.filter( for reading in ServiceHealth.objects.filter(
@@ -48,17 +87,30 @@ class ServiceHealthView(
readings.get((target.node, service)), readings.get((target.node, service)),
cutoff, cutoff,
) )
| {
"control_target": CONTROL_TARGETS.get(
SERVICES[service][1]
)
}
for service in target.services for service in target.services
], ],
) )
for target in targets 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, **kwargs,
) )
def service_row(service, reading, cutoff): def service_row(service, reading, cutoff):
row = { row = {
"key": service,
"name": SERVICES[service][0], "name": SERVICES[service][0],
"status": "Unknown", "status": "Unknown",
"style": "pending", "style": "pending",
+61 -54
View File
@@ -3,69 +3,61 @@ from pathlib import Path
from django import forms from django import forms
from django.contrib import messages from django.contrib import messages
from django.db import transaction from django.db import DatabaseError, connection, transaction
from django.shortcuts import redirect from django.shortcuts import redirect
from django.utils import timezone 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 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 .account_administration import OperatorAuthorization
from .models import OperatorOperation from .models import OperatorOperation
from .tasks import run_operator_operation from .tasks import run_operator_operation
from .update_views import inspect_linked_nodes 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 = { ACTION_LABELS = {
"package-preview": "Review available updates", "package-preview": "Review available updates",
"package-upgrade": "Apply reviewed updates", "package-upgrade": "Apply reviewed updates",
"reload": "Reload",
"restart": "Restart",
"database-report": "Collect MariaDB status",
} }
class OperatorToolForm(forms.Form): def queue_operator_request(user, spec, *, source=None):
action = forms.ChoiceField() job = OperatorOperation.objects.create(
preview_id = forms.IntegerField(required=False, widget=forms.HiddenInput) actor=user,
target = forms.ChoiceField( action=spec.action,
required=False, target=spec.target,
choices=[ plan=spec.plan,
("", "Select a service"), source=source,
*[(key, label) for key, label in SERVICES.items()],
],
) )
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( confirm = forms.BooleanField(
required=False, label="I reviewed the change and want to apply it" 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) super().__init__(*args, **kwargs)
self.preview = preview self.preview = preview
self.initial["preview_id"] = preview.pk if preview else None 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): def clean(self):
data = super().clean() data = super().clean()
if self.errors: if self.errors:
return data return data
action = data["action"] action = data["action"]
if action in {"reload", "restart", "package-upgrade"} and not data.get( if action == "package-upgrade" and not data.get("confirm"):
"confirm"
):
self.add_error( self.add_error(
"confirm", "Confirm this change before applying it." "confirm", "Confirm this change before applying it."
) )
@@ -80,16 +72,15 @@ class OperatorToolForm(forms.Form):
) )
plan = self.preview.result.get("fingerprint", "") plan = self.preview.result.get("fingerprint", "")
try: try:
self.spec = OperatorRequest(action, data.get("target", ""), plan) self.spec = OperatorRequest(action, plan=plan)
except ValueError as error: except ValueError as error:
raise forms.ValidationError(str(error)) from error raise forms.ValidationError(str(error)) from error
return data return data
class OperatorToolsView(OperatorAuthorization, FormView): class ServerUpdatesView(OperatorAuthorization, FormView):
form_class = OperatorToolForm form_class = ServerUpdateForm
template_name = "hosting/operator_tools.html" template_name = "hosting/server_updates.html"
page = "services"
def preview(self): def preview(self):
return ( return (
@@ -104,20 +95,14 @@ class OperatorToolsView(OperatorAuthorization, FormView):
) )
def get_form_kwargs(self): def get_form_kwargs(self):
return super().get_form_kwargs() | { return super().get_form_kwargs() | {"preview": self.preview()}
"actions": TOOL_ACTIONS[self.page][1],
"preview": self.preview() if self.page == "packages" else None,
}
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
title, actions = TOOL_ACTIONS[self.page]
return super().get_context_data( return super().get_context_data(
title=title,
page=self.page,
available=Path(SOCKET).is_socket(), available=Path(SOCKET).is_socket(),
jobs=OperatorOperation.objects.filter(action__in=actions).order_by( jobs=OperatorOperation.objects.filter(
"-pk" action__in=ACTION_LABELS
)[:20], ).order_by("-pk")[:20],
**kwargs, **kwargs,
) )
@@ -145,18 +130,40 @@ class OperatorToolsView(OperatorAuthorization, FormView):
"package update.", "package update.",
) )
return self.form_invalid(form) return self.form_invalid(form)
job = OperatorOperation.objects.create( queue_operator_request(
actor=self.request.user, self.request.user,
action=spec.action, spec,
target=spec.target,
plan=spec.plan,
source=form.preview if spec.action == "package-upgrade" else None, 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.") messages.success(self.request, "Host operation queued.")
return redirect(self.request.path) 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): class ConnectedNodesView(OperatorAuthorization, TemplateView):
template_name = "hosting/connected_nodes.html" 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 %} {% block page_content %}
<header class="page-heading"> {% if show_operation_history and not controls_available %}
<h1>Service health</h1> <p class="notice">Enable the local operator worker to reload or restart services.</p>
</header> {% endif %}
{% for node, services in nodes %} {% for node, services in nodes %}
<section class="surface" aria-labelledby="health-{{ node.node }}"> <section class="surface" aria-labelledby="health-{{ node.node }}">
<header class="section-heading"> <header class="section-heading">
@@ -20,15 +21,28 @@
<th scope="col">Status</th> <th scope="col">Status</th>
<th scope="col">Last check (UTC)</th> <th scope="col">Last check (UTC)</th>
<th scope="col">Details</th> <th scope="col">Details</th>
{% if controls_available and node.transport == 'local' %}<th scope="col">Actions</th>{% endif %}
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{% for service in services %} {% for service in services %}
<tr> <tr>
<th scope="row">{{ service.name }}</th> <th scope="row">{{ service.name }}</th>
<td><span class="status {{ service.style }}">{{ service.status }}</span></td> <td data-live-status="{{ node.node }}-{{ service.key }}-status"><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 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>{{ service.detail }}</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> </tr>
{% endfor %} {% endfor %}
</tbody> </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> <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> </section>
{% endfor %} {% endfor %}
{% if show_operation_history %}
{% include "hosting/operator_operation_history.html" %}
{% endif %}
{% endblock %} {% 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.mail_queue import MailQueueAction, change_queue_entry
from coulobre.operator_node import OperatorRequest, main, packages from coulobre.operator_node import OperatorRequest, main, packages
from .models import PanelTheme from .models import OperatorOperation, PanelTheme
class OperatorRequestTests(SimpleTestCase): class OperatorRequestTests(SimpleTestCase):
@@ -117,3 +117,32 @@ class ThemePreviewTests(TestCase):
) )
self.assertRedirects(self.client.post(url, {"action": "install"}), url) self.assertRedirects(self.client.post(url, {"action": "install"}), url)
self.assertEqual(PanelTheme.objects.get().name, "Test theme") 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.test import SimpleTestCase, TestCase, override_settings
from django.urls import reverse from django.urls import reverse
from django.utils import timezone from django.utils import timezone
from django_otp.plugins.otp_totp.models import TOTPDevice
from coulobre.service_health import ( from coulobre.service_health import (
HealthResult, HealthResult,
@@ -20,7 +21,13 @@ from coulobre.service_health import (
main, main,
) )
from .models import Customer, DnsZoneDefaults, Reseller, ServiceHealth from .models import (
Customer,
DnsZoneDefaults,
OperatorOperation,
Reseller,
ServiceHealth,
)
TARGETS = ( TARGETS = (
HealthTarget("panel-01", "local", ("mariadb", "apache")), HealthTarget("panel-01", "local", ("mariadb", "apache")),
@@ -165,6 +172,45 @@ class ServiceHealthPanelTests(TestCase):
self.client.force_login(user) self.client.force_login(user)
self.assertEqual(self.client.get(url).status_code, status) 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( @override_settings(
LOCAL_DNS_PUBLISHING=True, LOCAL_DNS_PUBLISHING=True,
HOSTING_NAMESERVERS=("ns.example.net",), 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_backups import OperatorBackupsView
from .operator_tools import ( from .operator_tools import (
ConnectedNodesView, ConnectedNodesView,
DatabaseMonitorView,
HttpDefaultsView, HttpDefaultsView,
OperatorToolsView, ServerUpdatesView,
) )
from .panel_content import ( from .panel_content import (
AnnouncementView, AnnouncementView,
@@ -190,17 +191,17 @@ urlpatterns = [
), ),
path( path(
"service-health/actions/", "service-health/actions/",
OperatorToolsView.as_view(page="services"), ServiceHealthView.as_view(),
name="operator_service_actions", name="operator_service_actions",
), ),
path( path(
"updates/server-packages/", "updates/server-packages/",
OperatorToolsView.as_view(page="packages"), ServerUpdatesView.as_view(),
name="server_updates", name="server_updates",
), ),
path( path(
"server/database/", "server/database/",
OperatorToolsView.as_view(page="database"), DatabaseMonitorView.as_view(),
name="database_monitor", name="database_monitor",
), ),
path("themes/", ThemeManagementView.as_view(), name="theme_management"), path("themes/", ThemeManagementView.as_view(), name="theme_management"),
+2 -6
View File
@@ -71,6 +71,7 @@ WORKSPACE_PARENT_ROUTES = {
"operator_settings": ("operator_settings", ("general",)), "operator_settings": ("operator_settings", ("general",)),
"http_defaults": ("http_defaults", ("apache",)), "http_defaults": ("http_defaults", ("apache",)),
"server_updates": ("updates", ()), "server_updates": ("updates", ()),
"operator_service_actions": ("service_health", ()),
"mail_queue": ("mail_queue_index", ()), "mail_queue": ("mail_queue_index", ()),
"reseller": ("resellers", ()), "reseller": ("resellers", ()),
"reseller_edit": ("resellers", ()), "reseller_edit": ("resellers", ()),
@@ -412,12 +413,7 @@ def groups_for(request, *, customer, manager):
) )
if user.is_superuser: if user.is_superuser:
server.append(link("connected_nodes", "Connected Nodes")) server.append(link("connected_nodes", "Connected Nodes"))
admin_tools.extend( admin_tools.append(link("database_monitor", "DB Monitor"))
(
link("operator_service_actions", "Service actions"),
link("database_monitor", "DB Monitor"),
)
)
groups = [ groups = [
("Account Manager", accounts), ("Account Manager", accounts),
("Server Manager", server), ("Server Manager", server),
+17 -9
View File
@@ -27,6 +27,11 @@ ACTIONS = (
"server-tls", "server-tls",
) )
APT = "/usr/bin/apt-get" 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) @dataclass(frozen=True)
@@ -142,26 +147,29 @@ def packages(request):
def database_report(): def database_report():
query = (
"SELECT @@version, @@slow_query_log; SHOW GLOBAL STATUS WHERE "
"Variable_name IN ('Threads_connected','Slow_queries','Uptime');"
)
output = command( output = command(
"/usr/bin/mariadb", "/usr/bin/mariadb",
"--batch", "--batch",
"--skip-column-names", "--skip-column-names",
"--protocol=socket", "--protocol=socket",
"--execute", "--execute",
query, f"{DATABASE_VERSION_QUERY}; {DATABASE_COUNTERS_QUERY};",
) )
rows = [row.split("\t") for row in output.splitlines()] return database_report_from_rows(
if not rows or any(len(row) != 2 for row in 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.") raise ValueError("MariaDB returned an invalid status report.")
version, slow_log = rows[0] 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 { return {
"database_version": version[:80], "database_version": version[:80],
"slow_logging": slow_log == "1", "slow_logging": str(slow_log).upper() in {"1", "ON"},
"counters": counters, "counters": counters,
} }