Show local and remote service health in the admin panel #54

Merged
parkel merged 2 commits from feature/admin-service-health into main 2026-11-21 17:50:28 +01:00
12 changed files with 644 additions and 0 deletions
Showing only changes of commit 37b4a66ba4 - Show all commits

No files matched your search

+1
View File
@@ -22,6 +22,7 @@ coulobre-directadmin = "coulobre.directadmin:main"
coulobre-dns-node = "coulobre.dns_node:main"
coulobre-mail-node = "coulobre.mail_node:main"
coulobre-service-credentials = "coulobre.service_credentials:main"
coulobre-service-health = "coulobre.service_health:main"
coulobre-web-node = "coulobre.web_node:main"
[project.optional-dependencies]
+81
View File
@@ -0,0 +1,81 @@
from datetime import timedelta
from django.conf import settings
from django.contrib.auth.mixins import PermissionRequiredMixin
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.service_health import HEALTH_DETAILS, SERVICES, HealthResult
from .access import OperatorOnlyMixin
from .models import ServiceHealth
STALE_AFTER = timedelta(minutes=5)
STATUS = {
HealthResult.ACTIVE: ("Active", "ready"),
HealthResult.INACTIVE: ("Unavailable", "suspended"),
HealthResult.MISSING: ("Unavailable", "suspended"),
HealthResult.FAILED: ("Unavailable", "suspended"),
HealthResult.TRANSITIONING: ("Transitioning", "pending"),
}
@method_decorator(never_cache, name="dispatch")
class ServiceHealthView(
OperatorOnlyMixin, PermissionRequiredMixin, TemplateView
):
permission_required = "hosting.view_servicehealth"
template_name = "hosting/service_health.html"
def get_context_data(self, **kwargs):
targets = settings.SERVICE_HEALTH_TARGETS
readings = {
(reading.node, reading.service): reading
for reading in ServiceHealth.objects.filter(
node__in=[target.node for target in targets]
)
}
cutoff = timezone.now() - STALE_AFTER
return super().get_context_data(
nodes=[
(
target,
[
service_row(
service,
readings.get((target.node, service)),
cutoff,
)
for service in target.services
],
)
for target in targets
],
**kwargs,
)
def service_row(service, reading, cutoff):
row = {
"name": SERVICES[service][0],
"status": "Unknown",
"style": "pending",
}
if reading is None:
return row | {"detail": "This service has never been checked."}
status, style = STATUS.get(reading.result, ("Unknown", "pending"))
detail = HEALTH_DETAILS.get(
reading.result, "The stored result is unavailable."
)
if reading.observed_at <= cutoff:
detail = f"Last check: {detail}"
status, style = "Stale", "pending"
return row | {
"status": status,
"style": style,
"detail": detail,
"observed_at": reading.observed_at,
}
@@ -0,0 +1,23 @@
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils import timezone
from coulobre.hosting.models import ServiceHealth
from coulobre.service_health import read_health
class Command(BaseCommand):
help = "Record health observations for local and remote services."
def handle(self, **options):
for target in settings.SERVICE_HEALTH_TARGETS:
observed_at = timezone.now()
for service, result in read_health(target).items():
values = {"result": result, "observed_at": observed_at}
reading, created = ServiceHealth.objects.get_or_create(
node=target.node, service=service, defaults=values
)
if not created:
ServiceHealth.objects.filter(
pk=reading.pk, observed_at__lte=observed_at
).update(**values)
@@ -0,0 +1,39 @@
# Generated by Django 5.2.19 on 2026-11-21 16:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0032_phpmyadmin_signon"),
]
operations = [
migrations.CreateModel(
name="ServiceHealth",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("node", models.CharField(max_length=63)),
("service", models.CharField(max_length=24)),
("result", models.CharField(max_length=24)),
("observed_at", models.DateTimeField()),
],
options={
"default_permissions": ("view",),
"constraints": [
models.UniqueConstraint(
fields=("node", "service"),
name="hosting_service_health_identity",
)
],
},
),
]
+16
View File
@@ -809,3 +809,19 @@ class MailboxProvisioning(ProvisioningJob):
HostingMailbox, on_delete=models.CASCADE, related_name="provisioning"
)
quota_update = models.BooleanField(default=False)
class ServiceHealth(models.Model):
node = models.CharField(max_length=63)
service = models.CharField(max_length=24)
result = models.CharField(max_length=24)
observed_at = models.DateTimeField()
class Meta:
default_permissions = ("view",)
constraints = [
models.UniqueConstraint(
fields=("node", "service"),
name="hosting_service_health_identity",
)
]
@@ -159,6 +159,13 @@ button, input, select, textarea {
background: linear-gradient(currentColor, currentColor) center 35% / 40% 1px no-repeat;
}
.nav-icon-health {
background:
linear-gradient(currentColor, currentColor) 25% bottom / 1px 40% no-repeat,
linear-gradient(currentColor, currentColor) center bottom / 1px 70% no-repeat,
linear-gradient(currentColor, currentColor) 75% bottom / 1px 55% no-repeat;
}
.nav-icon-customers {
position: relative;
height: 0.46rem;
@@ -41,6 +41,12 @@
Web provisioning
</a>
{% endif %}
{% if is_operator and perms.hosting.view_servicehealth %}
<a href="{% url 'panel:service_health' %}"{% if current == 'service_health' %} aria-current="page"{% endif %}>
<span class="nav-icon nav-icon-health" aria-hidden="true"></span>
Service health
</a>
{% endif %}
{% endwith %}
</nav>
<div class="sidebar-account">
@@ -0,0 +1,41 @@
{% extends "hosting/base.html" %}
{% block title %}Service health · Coulobre Panel{% endblock %}
{% block content %}
<header class="page-heading">
<h1>Service health</h1>
</header>
{% for node, services in nodes %}
<section class="surface" aria-labelledby="health-{{ node.node }}">
<header class="section-heading">
<h2 id="health-{{ node.node }}">{{ node.node }}</h2>
<span class="muted">{% if node.transport == 'local' %}Local{% else %}Remote{% endif %}</span>
</header>
<div class="table-scroll">
<table>
<thead>
<tr>
<th scope="col">Service</th>
<th scope="col">Status</th>
<th scope="col">Last check (UTC)</th>
<th scope="col">Details</th>
</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>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</section>
{% empty %}
<section class="surface"><p class="empty">No services are configured for health checks.</p></section>
{% endfor %}
{% endblock %}
+199
View File
@@ -0,0 +1,199 @@
import json
import subprocess
from datetime import timedelta
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
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 coulobre.service_health import (
HealthResult,
HealthTarget,
check_remote,
check_unit,
load_health_targets,
)
from .models import Customer, Reseller, ServiceHealth
TARGETS = (
HealthTarget("panel-01", "local", ("mariadb", "apache")),
HealthTarget("mail-01", "ssh", ("postfix", "dovecot")),
HealthTarget("mail-02", "ssh", ("postfix",)),
)
class ServiceHealthProbeTests(SimpleTestCase):
def test_targets_use_stable_node_ids_and_supported_services(self):
self.assertEqual(
load_health_targets(
'{"panel-01":{"local":["mariadb","apache"]}, '
'"mail-01":{"ssh":["postfix","dovecot"]}, '
'"mail-02":{"ssh":["postfix"]}}'
),
TARGETS,
)
for raw in (
'{"-oProxyCommand":{"ssh":["bind9"]}}',
'{"mail":{"ssh":["panel"]}}',
'{"mail":{"ssh":["postfix","postfix"]}}',
'{"mail":{"ssh":["postfix"]},"mail":{"ssh":["dovecot"]}}',
'{"host1":{"local":["apache"]},"host2":{"local":["mariadb"]}}',
):
with self.subTest(raw=raw), self.assertRaises(ValueError):
load_health_targets(raw)
def test_local_check_uses_read_only_systemd_properties(self):
with patch("coulobre.service_health.subprocess.run") as run:
run.side_effect = (
subprocess.CompletedProcess(
(), 0, b"LoadState=loaded\nActiveState=active\n"
),
subprocess.CompletedProcess(
(), 1, b"LoadState=not-found\nActiveState=inactive\n"
),
subprocess.TimeoutExpired((), 3),
)
self.assertEqual(check_unit("bind9"), HealthResult.ACTIVE)
self.assertEqual(check_unit("bind9"), HealthResult.MISSING)
self.assertEqual(check_unit("bind9"), HealthResult.QUERY_FAILED)
self.assertEqual(
run.call_args.args[0],
(
"/usr/bin/systemctl",
"show",
"--no-pager",
"--property=LoadState,ActiveState",
"--",
"named.service",
),
)
def test_remote_check_validates_the_peer_and_report(self):
target = TARGETS[2]
valid = {"version": 1, "services": {"postfix": "inactive"}}
with patch("coulobre.service_health.subprocess.run") as run:
run.side_effect = (
subprocess.CompletedProcess((), 0, json.dumps(valid).encode()),
subprocess.CompletedProcess(
(),
0,
b'{"version":1,"services":{"postfix":"password=secret"}}',
),
subprocess.CalledProcessError(255, ()),
)
self.assertEqual(
check_remote(target), {"postfix": HealthResult.INACTIVE}
)
self.assertEqual(
check_remote(target), {"postfix": HealthResult.INVALID_REPLY}
)
self.assertEqual(
check_remote(target), {"postfix": HealthResult.SSH_FAILED}
)
command = run.call_args.args[0]
self.assertIn("StrictHostKeyChecking=yes", command)
self.assertEqual(command[-2:], ("--", "mail-02"))
@override_settings(SERVICE_HEALTH_TARGETS=TARGETS)
class ServiceHealthPanelTests(TestCase):
@classmethod
def setUpTestData(cls):
users = get_user_model().objects
cls.admin = users.create_superuser("admin")
cls.operator = users.create_user("operator")
cls.customer = users.create_user("customer")
cls.reseller = users.create_user("reseller")
cls.viewer = users.create_user("viewer", is_staff=True)
Customer.objects.create(user=cls.customer)
Reseller.objects.create(user=cls.reseller)
permission = Permission.objects.get(codename="view_servicehealth")
for user in (cls.operator, cls.customer, cls.reseller):
user.user_permissions.add(permission)
def test_only_operators_with_permission_can_view_health(self):
url = reverse("panel:service_health")
self.assertRedirects(
self.client.get(url), f"{reverse('panel:login')}?next={url}"
)
for user, status in (
(self.admin, 200),
(self.operator, 200),
(self.viewer, 403),
(self.customer, 403),
(self.reseller, 403),
):
with self.subTest(user=user):
self.client.force_login(user)
self.assertEqual(self.client.get(url).status_code, status)
def test_view_marks_missing_and_old_observations_distinctly(self):
now = timezone.now()
for node, service, result, observed_at in (
("panel-01", "mariadb", HealthResult.ACTIVE, now),
("panel-01", "apache", HealthResult.INACTIVE, now),
(
"mail-01",
"postfix",
HealthResult.ACTIVE,
now - timedelta(minutes=6),
),
("mail-02", "postfix", HealthResult.SSH_FAILED, now),
("removed-node", "postfix", HealthResult.ACTIVE, now),
):
ServiceHealth.objects.create(
node=node,
service=service,
result=result,
observed_at=observed_at,
)
self.client.force_login(self.operator)
response = self.client.get(reverse("panel:service_health"))
self.assertContains(response, 'class="status ready">Active')
self.assertContains(response, "Unavailable")
self.assertContains(response, "Stale")
self.assertContains(response, "This service has never been checked.")
self.assertContains(
response, "Could not complete the node&#x27;s SSH probe."
)
self.assertNotContains(response, "removed-node")
self.assertIn("no-store", response["Cache-Control"])
def test_collection_keeps_nodes_independent_and_newer_results_win(self):
module = "coulobre.hosting.management.commands.collect_service_health"
now = timezone.now()
ServiceHealth.objects.create(
node="mail-01",
service="postfix",
result=HealthResult.ACTIVE,
observed_at=now + timedelta(seconds=1),
)
with (
patch(f"{module}.read_health") as read,
patch(f"{module}.timezone.now", return_value=now),
):
read.side_effect = (
dict.fromkeys(TARGETS[0].services, HealthResult.ACTIVE),
dict.fromkeys(TARGETS[1].services, HealthResult.SSH_FAILED),
{"postfix": HealthResult.FAILED},
)
call_command("collect_service_health")
self.assertEqual(ServiceHealth.objects.count(), 5)
self.assertEqual(
ServiceHealth.objects.get(
node="mail-01", service="postfix"
).result,
HealthResult.ACTIVE,
)
self.assertEqual(
ServiceHealth.objects.get(
node="mail-02", service="postfix"
).result,
HealthResult.FAILED,
)
+4
View File
@@ -4,12 +4,16 @@ from django.urls import path
from . import views
from .backup_restores import RestoreKind
from .credential_views import DatabaseCredentialView, MailboxCredentialView
from .health_views import ServiceHealthView
from .phpmyadmin import PhpMyAdminLaunch, redeem_phpmyadmin
app_name = "panel"
urlpatterns = [
path("", views.AccountList.as_view(), name="accounts"),
path(
"service-health/", ServiceHealthView.as_view(), name="service_health"
),
path(
"sign-in/",
LoginView.as_view(
+218
View File
@@ -0,0 +1,218 @@
import json
import re
import subprocess
from dataclasses import dataclass
from enum import StrEnum
SERVICES = {
"panel": ("Coulobre Panel", "coulobre-panel.service"),
"worker": ("Coulobre worker", "coulobre-worker.service"),
"scheduler": ("Coulobre scheduler", "coulobre-beat.service"),
"apache": ("Apache", "apache2.service"),
"php-fpm": ("PHP 8.5 FPM", "php8.5-fpm.service"),
"mariadb": ("MariaDB", "mariadb.service"),
"rabbitmq": ("RabbitMQ", "rabbitmq-server.service"),
"bind9": ("BIND9", "named.service"),
"postfix": ("Postfix", "postfix.service"),
"dovecot": ("Dovecot", "dovecot.service"),
}
REMOTE_SERVICES = ("bind9", "postfix", "dovecot")
REMOTE_VERSION = 1
SSH_CONFIG = "/etc/coulobre-health/ssh_config"
NODE_NAME = re.compile(r"[a-z][a-z0-9-]{0,62}")
class HealthResult(StrEnum):
ACTIVE = "active"
INACTIVE = "inactive"
TRANSITIONING = "transitioning"
MISSING = "missing"
FAILED = "failed"
QUERY_FAILED = "query_failed"
SSH_FAILED = "ssh_failed"
INVALID_REPLY = "invalid_reply"
HEALTH_DETAILS = {
HealthResult.ACTIVE: "The systemd unit is active.",
HealthResult.INACTIVE: "The systemd unit is inactive or masked.",
HealthResult.TRANSITIONING: "The systemd unit is starting or stopping.",
HealthResult.MISSING: "The systemd unit is missing.",
HealthResult.FAILED: "The systemd unit reported a failure.",
HealthResult.QUERY_FAILED: "Could not read the systemd unit state.",
HealthResult.SSH_FAILED: "Could not complete the node's SSH probe.",
HealthResult.INVALID_REPLY: "The node returned an invalid health report.",
}
UNIT_RESULTS = frozenset(HealthResult) - {
HealthResult.SSH_FAILED,
HealthResult.INVALID_REPLY,
}
@dataclass(frozen=True)
class HealthTarget:
node: str
transport: str
services: tuple[str, ...]
def load_health_targets(raw):
try:
nodes = json.loads(raw, object_pairs_hook=unique_health_keys)
except (ValueError, RecursionError):
raise ValueError(
"Expected a JSON object of service health nodes."
) from None
if not isinstance(nodes, dict):
raise ValueError("Expected a JSON object of service health nodes.")
targets = []
for node, options in nodes.items():
if not NODE_NAME.fullmatch(node) or not isinstance(options, dict):
raise ValueError("Expected a node ID and a service health object.")
if len(options) != 1 or not options.keys() <= {"local", "ssh"}:
raise ValueError("Each node needs a local or SSH service list.")
transport, services = next(iter(options.items()))
allowed = SERVICES if transport == "local" else REMOTE_SERVICES
if (
not isinstance(services, list)
or not services
or any(
not isinstance(name, str) or name not in allowed
for name in services
)
or len(set(services)) != len(services)
):
raise ValueError(
"Each node needs a list of distinct supported services."
)
targets.append(HealthTarget(node, transport, tuple(services)))
if sum(target.transport == "local" for target in targets) > 1:
raise ValueError(
"Configure one local service health node per panel host."
)
return tuple(targets)
def unique_health_keys(pairs):
values = dict(pairs)
if len(values) != len(pairs):
raise ValueError("Health configuration keys must be unique.")
return values
def check_unit(service):
unit = SERVICES[service][1]
try:
reply = subprocess.run(
(
"/usr/bin/systemctl",
"show",
"--no-pager",
"--property=LoadState,ActiveState",
"--",
unit,
),
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
timeout=3,
check=False,
)
except (OSError, subprocess.TimeoutExpired):
return HealthResult.QUERY_FAILED
state = dict(
line.split(b"=", 1)
for line in reply.stdout.splitlines()
if b"=" in line
)
load_state = state.get(b"LoadState")
if load_state == b"not-found":
return HealthResult.MISSING
if load_state == b"masked":
return HealthResult.INACTIVE
if reply.returncode or load_state != b"loaded":
return HealthResult.QUERY_FAILED
return {
b"active": HealthResult.ACTIVE,
b"reloading": HealthResult.ACTIVE,
b"refreshing": HealthResult.ACTIVE,
b"inactive": HealthResult.INACTIVE,
b"failed": HealthResult.FAILED,
b"activating": HealthResult.TRANSITIONING,
b"deactivating": HealthResult.TRANSITIONING,
b"maintenance": HealthResult.TRANSITIONING,
}.get(state.get(b"ActiveState"), HealthResult.QUERY_FAILED)
def check_remote(target):
try:
reply = subprocess.run(
(
"/usr/bin/ssh",
"-T",
"-F",
SSH_CONFIG,
"-o",
"BatchMode=yes",
"-o",
"StrictHostKeyChecking=yes",
"-o",
"GlobalKnownHostsFile=none",
"-o",
"IdentityAgent=none",
"-o",
"IdentitiesOnly=yes",
"-o",
"ConnectTimeout=4",
"--",
target.node,
),
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
timeout=15,
check=True,
)
except (OSError, subprocess.SubprocessError):
return dict.fromkeys(target.services, HealthResult.SSH_FAILED)
try:
report = (
json.loads(reply.stdout) if len(reply.stdout) <= 4096 else None
)
if (
type(report["version"]) is not int
or report["version"] != REMOTE_VERSION
):
raise ValueError
results = {
name: HealthResult(report["services"][name])
for name in target.services
}
if not set(results.values()) <= UNIT_RESULTS:
raise ValueError
except (KeyError, TypeError, ValueError, RecursionError):
return dict.fromkeys(target.services, HealthResult.INVALID_REPLY)
return results
def read_health(target):
if target.transport == "local":
return {name: check_unit(name) for name in target.services}
return check_remote(target)
def main():
print(
json.dumps(
{
"version": REMOTE_VERSION,
"services": {
name: check_unit(name) for name in REMOTE_SERVICES
},
}
)
)
return 0
+9
View File
@@ -4,6 +4,8 @@ from urllib.parse import urlsplit
from django.core.exceptions import ImproperlyConfigured
from .service_health import load_health_targets
def required_env(name):
value = os.environ.get(name)
@@ -119,6 +121,13 @@ CELERY_BROKER_URL = os.environ.get(
CELERY_BROKER_TRANSPORT_OPTIONS = {"confirm_publish": True}
CELERY_TASK_DEFAULT_QUEUE = "coulobre"
CELERY_TASK_IGNORE_RESULT = True
try:
SERVICE_HEALTH_TARGETS = load_health_targets(
os.environ.get("COULOBRE_SERVICE_HEALTH", "{}")
)
except ValueError as error:
raise ImproperlyConfigured(f"COULOBRE_SERVICE_HEALTH: {error}") from None
LOCAL_WEB_ACTIVATION = os.environ.get("COULOBRE_LOCAL_WEB_ACTIVATION") == "1"
LOCAL_WEB_HTTPS = os.environ.get("COULOBRE_LOCAL_WEB_HTTPS") == "1"
LOCAL_WEB_SFTP = os.environ.get("COULOBRE_LOCAL_WEB_SFTP") == "1"