Compare commits

...
11 Commits
Author SHA1 Message Date
parkel 847337bfc3 Merge pull request 'Prepare the Coulobre v0.2.0-rc.1 release candidate' (#55) from release/v0.2.0-rc.1 into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #55
2026-11-21 18:01:16 +01:00
parkel df527438da Document the in-place panel upgrade procedure
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-21 17:52:19 +01:00
parkel 75032fa004 Prepare Coulobre 0.2.0rc1 package metadata 2026-11-21 17:52:19 +01:00
parkel 7411d59a02 Merge pull request 'Show local and remote service health in the admin panel' (#54) from feature/admin-service-health into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #54
2026-11-21 17:50:27 +01:00
parkel 274554a555 Deploy a periodic collector and read-only remote health probes
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-21 17:43:17 +01:00
parkel 37b4a66ba4 Collect and display per-node service health observations 2026-11-21 17:43:17 +01:00
parkel 9a09314758 Merge pull request 'Provision mail and publish DNS on separate servers' (#53) from feature/remote-mail-dns-nodes into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #53
2026-11-21 17:36:53 +01:00
parkel 8974b55f98 Use transport-neutral DNS and mailbox failure messages
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-21 17:32:52 +01:00
parkel 066fbd9be3 Document separate and shared DNS and mail nodes 2026-11-21 17:31:00 +01:00
parkel dc19e4a59a Relay DNS and mailbox provisioning over restricted SSH connections 2026-11-21 17:31:00 +01:00
parkel df9f7c3284 Merge pull request 'Prepare the Coulobre v0.1.0-rc.1 release candidate' (#51) from release/v0.1.0-rc.1 into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #51
2026-11-21 17:10:26 +01:00
29 changed files with 1064 additions and 9 deletions

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,20 @@
Match User coulobre-dns-request,coulobre-mail-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
Match User coulobre-dns-request
ForceCommand /usr/bin/socat -t 185 STDIO UNIX-CONNECT:/run/coulobre-dns-apply.sock
Match User coulobre-mail-request
ForceCommand /usr/bin/socat -t 185 STDIO UNIX-CONNECT:/run/coulobre-mail-apply.sock
Match all
@@ -0,0 +1,13 @@
Host coulobre-dns-node
HostName dns.example.org
Port 22
User coulobre-dns-request
IdentityFile /etc/coulobre-remote/dns/id_ed25519
IdentityAgent none
IdentitiesOnly yes
PreferredAuthentications publickey
UserKnownHostsFile /etc/coulobre-remote/dns/known_hosts
GlobalKnownHostsFile none
StrictHostKeyChecking yes
BatchMode yes
ConnectTimeout 5
+13
View File
@@ -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
@@ -0,0 +1,13 @@
Host coulobre-mail-node
HostName mail.example.org
Port 22
User coulobre-mail-request
IdentityFile /etc/coulobre-remote/mail/id_ed25519
IdentityAgent none
IdentitiesOnly yes
PreferredAuthentications publickey
UserKnownHostsFile /etc/coulobre-remote/mail/known_hosts
GlobalKnownHostsFile none
StrictHostKeyChecking yes
BatchMode yes
ConnectTimeout 5
+2
View File
@@ -8,10 +8,12 @@ COULOBRE_DB_USER=coulobre
COULOBRE_DB_PASSWORD=
COULOBRE_DB_HOST=/run/mysqld/mysqld.sock
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_HTTPS=1
# COULOBRE_LOCAL_WEB_SFTP=1
# COULOBRE_LOCAL_DATABASE_PROVISIONING=1
# These two switches also enable provisioners using the SSH service drop-ins.
# COULOBRE_LOCAL_DNS_PUBLISHING=1
# COULOBRE_LOCAL_MAILBOX_PROVISIONING=1
# COULOBRE_LOCAL_DATABASE_CREDENTIALS=1
@@ -0,0 +1,11 @@
[Unit]
Description=Coulobre remote BIND9 publishing request
[Service]
User=coulobre-dns-publisher
Group=coulobre-dns-publisher
UMask=0077
ReadWritePaths=
ExecStart=
ExecStart=/usr/bin/ssh -T -F /etc/coulobre-remote/dns/ssh_config coulobre-dns-node
RuntimeMaxSec=190s
@@ -1,5 +1,5 @@
[Unit]
Description=Coulobre Panel local BIND9 publishing worker
Description=Coulobre Panel BIND9 publishing worker
Requires=coulobre-dns-apply.socket
Wants=network-online.target
After=network-online.target coulobre-dns-apply.socket mariadb.service rabbitmq-server.service
+18
View File
@@ -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
+10
View File
@@ -0,0 +1,10 @@
[Unit]
Description=Refresh Coulobre service health observations
[Timer]
OnActiveSec=10s
OnUnitInactiveSec=1min
AccuracySec=5s
[Install]
WantedBy=timers.target
@@ -0,0 +1,11 @@
[Unit]
Description=Coulobre remote mailbox provisioning request
[Service]
User=coulobre-mail-provisioner
Group=coulobre-mail-provisioner
UMask=0077
StateDirectory=
ExecStart=
ExecStart=/usr/bin/ssh -T -F /etc/coulobre-remote/mail/ssh_config coulobre-mail-node
RuntimeMaxSec=190s
@@ -1,5 +1,5 @@
[Unit]
Description=Coulobre Panel local mailbox provisioning worker
Description=Coulobre Panel mailbox provisioning worker
Requires=coulobre-mail-apply.socket
Wants=network-online.target
After=network-online.target coulobre-mail-apply.socket mariadb.service rabbitmq-server.service
+266 -1
View File
@@ -177,7 +177,45 @@ connected. Follow their logs with `journalctl`.
sudo journalctl -u coulobre-panel -u coulobre-worker -u coulobre-beat
```
### Verify a new installation
## Upgrade an existing panel
Download and unpack the new source release. Back up the panel database and
the configuration in `/etc/coulobre/` and in the service files you manage.
Stop the web process and scheduler. Let running jobs finish, then stop the
worker and any enabled provisioning, backup, or health collector units.
```sh
sudo systemctl stop coulobre-panel.service coulobre-beat.service
```
After the running jobs finish, stop the general worker. If service health is
enabled, stop both its timer and service before changing the package.
```sh
sudo systemctl stop coulobre-worker.service
# If service health is enabled:
# sudo systemctl stop coulobre-health.timer coulobre-health.service
```
From the unpacked source release, upgrade the existing virtual environment
and use the [management command helper](#prepare-the-panel).
```sh
sudo /opt/coulobre/bin/pip install --upgrade '.[server,mariadb]'
panel_manage migrate --noinput
panel_manage collectstatic --noinput
```
Review the release notes and apply any configuration or unit changes they
describe. Reload systemd, start the main services and any optional units you
stopped, and verify the deployment with a test account.
```sh
sudo systemctl daemon-reload
sudo systemctl start coulobre-panel.service coulobre-worker.service coulobre-beat.service
```
## Verify a new installation
Use a test hosting plan, account, and domain for these checks. Enable the
local services that the installation will offer before checking them.
@@ -760,6 +798,9 @@ database. Sign out of phpMyAdmin to end its session.
## Publish local DNS zones from the panel
To publish to BIND9 on another host, use the
[separate-node setup](#provision-mail-and-dns-on-separate-servers).
Enable the [DNS publishing socket](development.md#enable-local-dns-publishing)
on the panel host. Install the BIND9 publishing worker under a dedicated
identity with access to that socket.
@@ -791,6 +832,9 @@ finishes. Use **Retry publishing** if the current revision failed.
## Provision local mailboxes from the panel
To provision Postfix and Dovecot on another host, use the
[separate-node setup](#provision-mail-and-dns-on-separate-servers).
Set up [Postfix and Dovecot](development.md#apply-a-mailbox-manifest) on the
Ubuntu 24.04 or 26.04 panel host and enable the
[mailbox provisioning socket](development.md#enable-local-mailbox-provisioning).
@@ -834,3 +878,224 @@ the node command for manually provisioned mailboxes.
Back up mail on the node that hosts the mailbox. The archive can be used to
recover messages and folders into a newly provisioned mailbox with the same
address. [Mailbox backup and restore](development.md#back-up-and-restore-a-mailbox)
## Provision mail and DNS on separate servers
Choose one destination per service. For example, run mail locally and publish
DNS to a separate authoritative server. The panel uses the same worker and
job history for each deployment. On the panel server, install the SSH
drop-in only for a service that uses another host.
Several Coulobre installations under the same administration can share a
destination. Generate a separate key per sending installation and service.
The receiver accepts each key separately, and removing its line revokes that
installation's access. Each receiver can manage any Coulobre resource on its
service. Assign each domain to one installation for changes to its zones and
mailboxes.
Use the values for each service below when following the commands.
| Value | DNS | Mail |
| --- | --- | --- |
| `node` | `dns` | `mail` |
| `request_group` | `coulobre-dns-provisioning` | `coulobre-mail-provisioning` |
| `receiver` | `coulobre-dns-request` | `coulobre-mail-request` |
| `worker` | `coulobre-dns-publisher` | `coulobre-mail-provisioner` |
| Worker unit | `coulobre-dns-publisher.service` | `coulobre-mailbox-provisioner.service` |
| Panel flag | `COULOBRE_LOCAL_DNS_PUBLISHING=1` | `COULOBRE_LOCAL_MAILBOX_PROVISIONING=1` |
### Prepare the panel's SSH identity
Start from the same Coulobre source release on both hosts. For DNS, set these
variables on the panel host. For mail, substitute the values in the table.
```sh
node=dns
request_group=coulobre-dns-provisioning
worker=coulobre-dns-publisher
sudo apt install openssh-client
getent group "$request_group" >/dev/null || sudo groupadd --system "$request_group"
id "$worker" >/dev/null 2>&1 || sudo useradd --system --user-group \
--no-create-home --home-dir /nonexistent --shell /usr/sbin/nologin "$worker"
sudo install -d -o root -g root -m 0755 /etc/coulobre-remote
sudo install -d -o root -g "$worker" -m 0750 "/etc/coulobre-remote/$node"
sudo install -o root -g "$worker" -m 0640 \
"deploy/openssh/$node-node-client.conf.example" "/etc/coulobre-remote/$node/ssh_config"
sudo sh -c 'umask 077; ssh-keygen -t ed25519 -N "" -f "$1/id_ed25519"' \
sh "/etc/coulobre-remote/$node"
sudo chown "$worker:$worker" "/etc/coulobre-remote/$node/id_ed25519"
sudo cat "/etc/coulobre-remote/$node/id_ed25519.pub"
```
Set `HostName` and `Port` in the SSH client configuration. Obtain the
destination's SSH host public key through your existing administrative
connection. Put the hostname or IP address, key type, and public key on one
line in `/etc/coulobre-remote/` under the service's `known_hosts` file. For a
port other than 22, use `[hostname]:port` in that line. Make the file owned
by root and readable by the worker group. The worker checks this pinned host
key before sending a request. [OpenSSH client configuration](https://man.openbsd.org/ssh_config)
### Install the node on the destination
On the destination, unpack the source release and install the Coulobre node
commands in `/opt/coulobre`.
```sh
sudo apt install python3-venv openssh-server socat
sudo python3 -m venv /opt/coulobre
sudo /opt/coulobre/bin/pip install .
```
Set up [BIND9](development.md#apply-a-zone-manifest) or
[Postfix and Dovecot](development.md#apply-a-mailbox-manifest), then enable
the corresponding [DNS socket](development.md#enable-local-dns-publishing) or
[mailbox socket](development.md#enable-local-mailbox-provisioning). The
destination runs the local socket service shipped with Coulobre.
Save the panel's public key from the previous step as `panel-node.pub` on
the destination. Create a receiver with only the socket group for that
service. This example uses DNS. Substitute the values for a mail node.
```sh
request_group=coulobre-dns-provisioning
receiver=coulobre-dns-request
id "$receiver" >/dev/null 2>&1 || sudo useradd --system --user-group --groups "$request_group" \
--no-create-home --home-dir / --shell /bin/sh "$receiver"
sudo install -d -o root -g root -m 0755 /etc/ssh/coulobre-node-keys
authorized_keys="/etc/ssh/coulobre-node-keys/$receiver"
sudo touch "$authorized_keys"
sudo chown root:root "$authorized_keys"
sudo chmod 0644 "$authorized_keys"
sudo tee -a "$authorized_keys" < panel-node.pub >/dev/null
sudo install -m 0644 deploy/openssh/coulobre-node-requests.conf.example \
/etc/ssh/sshd_config.d/00-coulobre-node-requests.conf
sudo sshd -t
sudo systemctl reload-or-restart ssh.service
```
The receiver authenticates with the panel's key and runs a fixed relay to
the service socket. The socket's systemd service validates and applies the
request. [OpenSSH server configuration](https://man.openbsd.org/sshd_config)
### Enable the remote destination on the panel
Use the matching worker from the table. The commands below use DNS.
```sh
node=dns
worker_unit=coulobre-dns-publisher.service
unit="coulobre-$node-apply"
sudo install -m 0644 "deploy/systemd/$unit.socket" \
"deploy/systemd/$unit@.service" "deploy/systemd/$worker_unit" /etc/systemd/system/
sudo install -D -m 0644 "deploy/systemd/$unit@.service.d/remote.conf" \
"/etc/systemd/system/$unit@.service.d/remote.conf"
sudo systemctl daemon-reload
```
Set the corresponding flag from the table in `/etc/coulobre/panel.env`. The
flag enables the existing panel actions and queue for that service. Restart
the panel and its general worker so they pick up the setting, then enable
the dedicated worker.
```sh
sudo systemctl restart coulobre-panel coulobre-worker coulobre-beat
sudo systemctl enable --now "$worker_unit"
```
Use **Publish zone** or **Provision mailbox** and check the status on the
account page. After correcting a connection or host key problem, use the
corresponding retry action. Check the panel-side relay log with
`sudo journalctl -u 'coulobre-dns-apply@*.service'` for DNS or
`sudo journalctl -u 'coulobre-mail-apply@*.service'` for mail.
When moving an existing service, migrate its data and provisioning state and
let outstanding jobs finish before switching destinations.
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).
## 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.
+2 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "coulobre-panel"
version = "0.1.0rc1"
version = "0.2.0rc1"
description = "A web hosting control panel for hosting providers and resellers."
readme = "README.md"
requires-python = ">=3.12"
@@ -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",
)
]
+4
View File
@@ -212,6 +212,10 @@ def apply_on_local_node(
if len(body) > RESPONSE_LIMIT:
raise ValueError(f"The {node} returned an oversized response.")
if not body:
raise ValueError(
f"The {node} closed the connection without a response."
)
invalid_response = (
f"The {node} returned an invalid response for this {resource}."
)
@@ -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;
+4 -4
View File
@@ -498,8 +498,8 @@ def publish_dns_zone(publication_id):
DnsPublication.objects.all(),
publication_id,
apply_dns_publication,
"Could not complete the request to the local BIND9 node. "
"Check its socket and try again.",
"Could not complete the request to the BIND9 node. "
"Check the node connection and try again.",
)
@@ -516,8 +516,8 @@ def provision_mailbox(provisioning_id):
MailboxProvisioning.objects.select_related("mailbox__mail_domain"),
provisioning_id,
apply_mailbox_provisioning,
"Could not complete the request to the local mail node. "
"Check its socket and try again.",
"Could not complete the request to the mail node. "
"Check the node connection and try again.",
)
@@ -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 %}
@@ -149,6 +149,22 @@ class DnsPublicationTests(TestCase):
class DnsPublicationSocketTests(SimpleTestCase):
def test_closed_connection_reports_a_missing_reply(self):
zone = DnsZone(
"site.example",
1,
("ns.provider.example",),
"hostmaster.site.example",
)
with patch("coulobre.hosting.node_client.socket.socket") as socket:
connection = socket.return_value.__enter__.return_value
connection.makefile.return_value.__enter__.return_value = BytesIO()
with self.assertRaisesMessage(
ValueError,
"The BIND9 node closed the connection without a response.",
):
publish_local_zone(zone)
def test_receipt_must_identify_the_exact_soa_serial(self):
zone = DnsZone(
"site.example",
@@ -116,7 +116,7 @@ class MailboxProvisioningTests(TestCase):
detail = self.client.get(self.detail)
self.assertContains(detail, "Retry provisioning")
self.assertContains(
detail, "Could not complete the request to the local mail node"
detail, "Could not complete the request to the mail node"
)
self.assertRedirects(self.client.post(self.url), self.detail)
job.refresh_from_db()
+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"