Merge pull request 'Show local and remote service health in the admin panel' (#54) from feature/admin-service-health into main
Reviewed-on: #54
This commit was merged in pull request #54.
This commit is contained in:
commit
7411d59a02
18 files changed
+785
No files matched your search
@@ -0,0 +1,15 @@
|
|||||||
|
Match User coulobre-health-request
|
||||||
|
AuthenticationMethods publickey
|
||||||
|
PubkeyAuthentication yes
|
||||||
|
PasswordAuthentication no
|
||||||
|
KbdInteractiveAuthentication no
|
||||||
|
AuthorizedKeysFile /etc/ssh/coulobre-node-keys/%u
|
||||||
|
AuthorizedKeysCommand none
|
||||||
|
TrustedUserCAKeys none
|
||||||
|
DisableForwarding yes
|
||||||
|
PermitTunnel no
|
||||||
|
PermitTTY no
|
||||||
|
PermitUserRC no
|
||||||
|
ForceCommand /opt/coulobre/bin/coulobre-service-health
|
||||||
|
|
||||||
|
Match all
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
Host mail-01
|
||||||
|
HostName mail.example.org
|
||||||
|
Port 22
|
||||||
|
User coulobre-health-request
|
||||||
|
IdentityFile /etc/coulobre-health/id_ed25519
|
||||||
|
UserKnownHostsFile /etc/coulobre-health/known_hosts
|
||||||
|
|
||||||
|
Host dns-01
|
||||||
|
HostName dns.example.org
|
||||||
|
Port 22
|
||||||
|
User coulobre-health-request
|
||||||
|
IdentityFile /etc/coulobre-health/id_ed25519
|
||||||
|
UserKnownHostsFile /etc/coulobre-health/known_hosts
|
||||||
@@ -8,6 +8,7 @@ COULOBRE_DB_USER=coulobre
|
|||||||
COULOBRE_DB_PASSWORD=
|
COULOBRE_DB_PASSWORD=
|
||||||
COULOBRE_DB_HOST=/run/mysqld/mysqld.sock
|
COULOBRE_DB_HOST=/run/mysqld/mysqld.sock
|
||||||
COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre
|
COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre
|
||||||
|
# COULOBRE_SERVICE_HEALTH='{"panel-01":{"local":["panel","worker","scheduler","apache","mariadb","rabbitmq"]}}'
|
||||||
# COULOBRE_LOCAL_WEB_ACTIVATION=1
|
# COULOBRE_LOCAL_WEB_ACTIVATION=1
|
||||||
# COULOBRE_LOCAL_WEB_HTTPS=1
|
# COULOBRE_LOCAL_WEB_HTTPS=1
|
||||||
# COULOBRE_LOCAL_WEB_SFTP=1
|
# COULOBRE_LOCAL_WEB_SFTP=1
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Coulobre service health collector
|
||||||
|
Wants=network-online.target
|
||||||
|
After=network-online.target mariadb.service
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=oneshot
|
||||||
|
User=coulobre-health
|
||||||
|
Group=coulobre-health
|
||||||
|
EnvironmentFile=/etc/coulobre/panel.env
|
||||||
|
WorkingDirectory=/opt/coulobre
|
||||||
|
ExecStart=/opt/coulobre/bin/python -m django collect_service_health
|
||||||
|
TimeoutStartSec=5min
|
||||||
|
UMask=0077
|
||||||
|
NoNewPrivileges=true
|
||||||
|
PrivateTmp=true
|
||||||
|
ProtectHome=true
|
||||||
|
ProtectSystem=strict
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Refresh Coulobre service health observations
|
||||||
|
|
||||||
|
[Timer]
|
||||||
|
OnActiveSec=10s
|
||||||
|
OnUnitInactiveSec=1min
|
||||||
|
AccuracySec=5s
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=timers.target
|
||||||
@@ -977,3 +977,87 @@ When moving an existing service, migrate its data and provisioning state and
|
|||||||
let outstanding jobs finish before switching destinations.
|
let outstanding jobs finish before switching destinations.
|
||||||
For mail on a separate server, retrieve logins on the mail node, and use the
|
For mail on a separate server, retrieve logins on the mail node, and use the
|
||||||
[separate-node backup workflow](development.md#bundle-backups-from-separate-nodes).
|
[separate-node backup workflow](development.md#bundle-backups-from-separate-nodes).
|
||||||
|
|
||||||
|
## Monitor local and remote services
|
||||||
|
|
||||||
|
The panel's **Service health** page shows the latest observation and timestamp
|
||||||
|
for each configured service and node. Superusers and operators with **Can
|
||||||
|
view service health** can open the page. The collector checks systemd unit
|
||||||
|
states. Use the corresponding service tests to check mail delivery, DNS
|
||||||
|
answers, or website responses. The collector and dashboard both need the
|
||||||
|
panel database to record and display observations.
|
||||||
|
|
||||||
|
Set `COULOBRE_SERVICE_HEALTH` in `/etc/coulobre/panel.env`. This example checks
|
||||||
|
local panel services and two records for remote mail and DNS services.
|
||||||
|
|
||||||
|
```ini
|
||||||
|
COULOBRE_SERVICE_HEALTH='{"panel-01":{"local":["panel","worker","scheduler","apache","php-fpm","mariadb","rabbitmq"]},"mail-01":{"ssh":["postfix","dovecot"]},"dns-01":{"ssh":["bind9"]}}'
|
||||||
|
```
|
||||||
|
|
||||||
|
Choose an ID for each node using lower-case letters, numbers, and hyphens,
|
||||||
|
starting with a letter. Keep the IDs stable for the same hosts. List one
|
||||||
|
`local` node per panel installation and use `ssh` for each additional host.
|
||||||
|
Use `bind9`, `postfix`, and `dovecot` under `local` for co-located services.
|
||||||
|
Remote checks accept those same three service names. The SSH client matches
|
||||||
|
each remote node ID to a `Host` entry.
|
||||||
|
|
||||||
|
Install the collector with a dedicated service identity after updating the
|
||||||
|
panel package.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo useradd --system --user-group --no-create-home --home-dir /nonexistent \
|
||||||
|
--shell /usr/sbin/nologin coulobre-health
|
||||||
|
sudo install -m 0644 deploy/systemd/coulobre-health.service \
|
||||||
|
deploy/systemd/coulobre-health.timer /etc/systemd/system/
|
||||||
|
panel_manage migrate --noinput
|
||||||
|
panel_manage collectstatic --noinput
|
||||||
|
sudo systemctl daemon-reload
|
||||||
|
sudo systemctl restart coulobre-panel
|
||||||
|
sudo systemctl enable --now coulobre-health.timer
|
||||||
|
```
|
||||||
|
|
||||||
|
The timer runs again one minute after each collection finishes. **Unknown**
|
||||||
|
means there is no reading or the collector could not obtain a unit state.
|
||||||
|
**Stale** shows the last observation when it is at least five minutes old.
|
||||||
|
To run a check immediately, use `sudo systemctl start coulobre-health.service`.
|
||||||
|
[systemctl unit properties](https://www.freedesktop.org/software/systemd/man/latest/systemctl.html)
|
||||||
|
|
||||||
|
### Enable read-only remote checks
|
||||||
|
|
||||||
|
Set up a collector key on the panel host. Configure an SSH alias for each
|
||||||
|
remote node and pin that server's verified SSH host public key in the
|
||||||
|
collector's `known_hosts` file. Use `[hostname]:port` for a nonstandard port.
|
||||||
|
Keep the configuration and host keys owned by root and readable by the
|
||||||
|
`coulobre-health` group.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo apt install openssh-client
|
||||||
|
sudo install -d -o root -g coulobre-health -m 0750 /etc/coulobre-health
|
||||||
|
sudo install -o root -g coulobre-health -m 0640 \
|
||||||
|
deploy/openssh/health-client.conf.example /etc/coulobre-health/ssh_config
|
||||||
|
sudo ssh-keygen -t ed25519 -N '' -f /etc/coulobre-health/id_ed25519
|
||||||
|
sudo chown coulobre-health:coulobre-health /etc/coulobre-health/id_ed25519
|
||||||
|
sudo cat /etc/coulobre-health/id_ed25519.pub
|
||||||
|
```
|
||||||
|
|
||||||
|
On each remote host, install the same Coulobre package in `/opt/coulobre`.
|
||||||
|
Save the collector public key as `panel-health.pub`. Use the key only for
|
||||||
|
the receiver below. The SSH account runs the fixed status command under its
|
||||||
|
own unprivileged identity.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo apt install openssh-server
|
||||||
|
sudo useradd --system --user-group --no-create-home --home-dir / --shell /bin/sh \
|
||||||
|
coulobre-health-request
|
||||||
|
sudo install -d -m 0755 /etc/ssh/coulobre-node-keys
|
||||||
|
sudo install -o root -g root -m 0644 panel-health.pub \
|
||||||
|
/etc/ssh/coulobre-node-keys/coulobre-health-request
|
||||||
|
sudo install -m 0644 deploy/openssh/coulobre-health-request.conf.example \
|
||||||
|
/etc/ssh/sshd_config.d/00-coulobre-health-request.conf
|
||||||
|
sudo sshd -t
|
||||||
|
sudo systemctl reload-or-restart ssh.service
|
||||||
|
```
|
||||||
|
|
||||||
|
Restart the panel after adding node IDs. Run the collector and open **Service
|
||||||
|
health** to check the remote readings. Recovery of the SSH connection or the
|
||||||
|
service is reflected by the next successful check.
|
||||||
@@ -22,6 +22,7 @@ coulobre-directadmin = "coulobre.directadmin:main"
|
|||||||
coulobre-dns-node = "coulobre.dns_node:main"
|
coulobre-dns-node = "coulobre.dns_node:main"
|
||||||
coulobre-mail-node = "coulobre.mail_node:main"
|
coulobre-mail-node = "coulobre.mail_node:main"
|
||||||
coulobre-service-credentials = "coulobre.service_credentials:main"
|
coulobre-service-credentials = "coulobre.service_credentials:main"
|
||||||
|
coulobre-service-health = "coulobre.service_health:main"
|
||||||
coulobre-web-node = "coulobre.web_node:main"
|
coulobre-web-node = "coulobre.web_node:main"
|
||||||
|
|
||||||
[project.optional-dependencies]
|
[project.optional-dependencies]
|
||||||
|
|||||||
@@ -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",
|
||||||
|
)
|
||||||
|
],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -809,3 +809,19 @@ class MailboxProvisioning(ProvisioningJob):
|
|||||||
HostingMailbox, on_delete=models.CASCADE, related_name="provisioning"
|
HostingMailbox, on_delete=models.CASCADE, related_name="provisioning"
|
||||||
)
|
)
|
||||||
quota_update = models.BooleanField(default=False)
|
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;
|
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 {
|
.nav-icon-customers {
|
||||||
position: relative;
|
position: relative;
|
||||||
height: 0.46rem;
|
height: 0.46rem;
|
||||||
|
|||||||
@@ -41,6 +41,12 @@
|
|||||||
Web provisioning
|
Web provisioning
|
||||||
</a>
|
</a>
|
||||||
{% endif %}
|
{% 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 %}
|
{% endwith %}
|
||||||
</nav>
|
</nav>
|
||||||
<div class="sidebar-account">
|
<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 %}
|
||||||
@@ -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'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,12 +4,16 @@ from django.urls import path
|
|||||||
from . import views
|
from . import views
|
||||||
from .backup_restores import RestoreKind
|
from .backup_restores import RestoreKind
|
||||||
from .credential_views import DatabaseCredentialView, MailboxCredentialView
|
from .credential_views import DatabaseCredentialView, MailboxCredentialView
|
||||||
|
from .health_views import ServiceHealthView
|
||||||
from .phpmyadmin import PhpMyAdminLaunch, redeem_phpmyadmin
|
from .phpmyadmin import PhpMyAdminLaunch, redeem_phpmyadmin
|
||||||
|
|
||||||
app_name = "panel"
|
app_name = "panel"
|
||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
path("", views.AccountList.as_view(), name="accounts"),
|
path("", views.AccountList.as_view(), name="accounts"),
|
||||||
|
path(
|
||||||
|
"service-health/", ServiceHealthView.as_view(), name="service_health"
|
||||||
|
),
|
||||||
path(
|
path(
|
||||||
"sign-in/",
|
"sign-in/",
|
||||||
LoginView.as_view(
|
LoginView.as_view(
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -4,6 +4,8 @@ from urllib.parse import urlsplit
|
|||||||
|
|
||||||
from django.core.exceptions import ImproperlyConfigured
|
from django.core.exceptions import ImproperlyConfigured
|
||||||
|
|
||||||
|
from .service_health import load_health_targets
|
||||||
|
|
||||||
|
|
||||||
def required_env(name):
|
def required_env(name):
|
||||||
value = os.environ.get(name)
|
value = os.environ.get(name)
|
||||||
@@ -119,6 +121,13 @@ CELERY_BROKER_URL = os.environ.get(
|
|||||||
CELERY_BROKER_TRANSPORT_OPTIONS = {"confirm_publish": True}
|
CELERY_BROKER_TRANSPORT_OPTIONS = {"confirm_publish": True}
|
||||||
CELERY_TASK_DEFAULT_QUEUE = "coulobre"
|
CELERY_TASK_DEFAULT_QUEUE = "coulobre"
|
||||||
CELERY_TASK_IGNORE_RESULT = True
|
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_ACTIVATION = os.environ.get("COULOBRE_LOCAL_WEB_ACTIVATION") == "1"
|
||||||
LOCAL_WEB_HTTPS = os.environ.get("COULOBRE_LOCAL_WEB_HTTPS") == "1"
|
LOCAL_WEB_HTTPS = os.environ.get("COULOBRE_LOCAL_WEB_HTTPS") == "1"
|
||||||
LOCAL_WEB_SFTP = os.environ.get("COULOBRE_LOCAL_WEB_SFTP") == "1"
|
LOCAL_WEB_SFTP = os.environ.get("COULOBRE_LOCAL_WEB_SFTP") == "1"
|
||||||
|
|||||||
Reference in new issue
Block a user