diff --git a/deploy/panel.env.example b/deploy/panel.env.example
index cb1f6b6..611871a 100644
--- a/deploy/panel.env.example
+++ b/deploy/panel.env.example
@@ -14,3 +14,4 @@ COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre
# COULOBRE_LOCAL_DATABASE_PROVISIONING=1
# COULOBRE_LOCAL_DNS_PUBLISHING=1
# COULOBRE_LOCAL_MAILBOX_PROVISIONING=1
+# COULOBRE_LOCAL_ACCOUNT_BACKUPS=1
diff --git a/deploy/systemd/coulobre-account-backup.socket b/deploy/systemd/coulobre-account-backup.socket
new file mode 100644
index 0000000..c2f408e
--- /dev/null
+++ b/deploy/systemd/coulobre-account-backup.socket
@@ -0,0 +1,14 @@
+[Unit]
+Description=Coulobre local account backup socket
+
+[Socket]
+ListenStream=/run/coulobre-account-backup.sock
+SocketUser=root
+SocketGroup=coulobre-backup-requests
+SocketMode=0660
+Accept=yes
+MaxConnections=4
+RemoveOnStop=true
+
+[Install]
+WantedBy=sockets.target
diff --git a/deploy/systemd/coulobre-account-backup@.service b/deploy/systemd/coulobre-account-backup@.service
new file mode 100644
index 0000000..737b868
--- /dev/null
+++ b/deploy/systemd/coulobre-account-backup@.service
@@ -0,0 +1,21 @@
+[Unit]
+Description=Coulobre local account backup request
+After=mariadb.service
+CollectMode=inactive-or-failed
+
+[Service]
+Type=exec
+User=root
+WorkingDirectory=/opt/coulobre
+StateDirectory=coulobre/account-backups coulobre/database-node
+StateDirectoryMode=0700
+UMask=0077
+ExecStart=/opt/coulobre/bin/coulobre-account-backup create-request
+StandardInput=socket
+StandardOutput=socket
+StandardError=journal
+RuntimeMaxSec=30min
+NoNewPrivileges=true
+PrivateTmp=true
+ProtectHome=true
+ProtectSystem=strict
diff --git a/deploy/systemd/coulobre-backup-worker.service b/deploy/systemd/coulobre-backup-worker.service
new file mode 100644
index 0000000..992dc99
--- /dev/null
+++ b/deploy/systemd/coulobre-backup-worker.service
@@ -0,0 +1,26 @@
+[Unit]
+Description=Coulobre Panel local account backup worker
+Requires=coulobre-account-backup.socket
+Wants=network-online.target
+After=network-online.target coulobre-account-backup.socket mariadb.service rabbitmq-server.service
+
+[Service]
+Type=exec
+User=coulobre-backup-worker
+Group=coulobre-backup-worker
+SupplementaryGroups=coulobre-backup-requests
+EnvironmentFile=/etc/coulobre/panel.env
+WorkingDirectory=/opt/coulobre
+UMask=0077
+ExecStart=/opt/coulobre/bin/celery -A coulobre worker --loglevel=INFO --queues=coulobre-account-backups --hostname=backup-worker@%H --concurrency=1 --prefetch-multiplier=1
+KillMode=mixed
+TimeoutStopSec=31min
+Restart=on-failure
+RestartSec=5s
+NoNewPrivileges=true
+PrivateTmp=true
+ProtectHome=true
+ProtectSystem=strict
+
+[Install]
+WantedBy=multi-user.target
diff --git a/src/coulobre/account_backup.py b/src/coulobre/account_backup.py
index 3ae7ecd..9ef6aca 100644
--- a/src/coulobre/account_backup.py
+++ b/src/coulobre/account_backup.py
@@ -93,8 +93,16 @@ def main(argv=None):
)
unpack.add_argument("archive", type=Path)
unpack.add_argument("directory", type=Path)
+ commands.add_parser(
+ "create-request", help="Create a local backup for the panel worker."
+ )
args = parser.parse_args(argv)
+ if args.command == "create-request":
+ from .account_backup_request import serve_backup_request
+
+ return serve_backup_request()
+
try:
if args.command == "unpack":
backup = unpack_backup(args.archive, args.directory)
diff --git a/src/coulobre/account_backup_request.py b/src/coulobre/account_backup_request.py
new file mode 100644
index 0000000..b47c4c2
--- /dev/null
+++ b/src/coulobre/account_backup_request.py
@@ -0,0 +1,108 @@
+import os
+from dataclasses import dataclass
+from pathlib import Path
+from uuid import UUID
+from zipfile import BadZipFile, ZipFile
+
+from .account_backup import (
+ MANIFEST_NAME,
+ MAX_MANIFEST_BYTES,
+ AccountBackup,
+ create_backup,
+ read_backup_manifest,
+)
+from .database_node import DEFAULT_SOCKET
+from .node_files import check_root_file, require_root_directory
+from .node_requests import serve_apply_request
+
+REQUEST_VERSION = 1
+BACKUP_DIRECTORY = Path("/var/lib/coulobre/account-backups")
+BACKUP_SOCKET = "/run/coulobre-account-backup.sock"
+BACKUP_TIMEOUT_SECONDS = 30 * 60
+
+
+@dataclass(frozen=True)
+class AccountBackupRequest:
+ backup_id: UUID
+ backup: AccountBackup
+
+ @classmethod
+ def from_manifest(cls, data):
+ if (
+ not isinstance(data, dict)
+ or data.keys() != {"version", "backup_id", "backup"}
+ or type(data["version"]) is not int
+ or data["version"] != REQUEST_VERSION
+ or not isinstance(data["backup_id"], str)
+ ):
+ raise ValueError("Expected a local account backup request.")
+ backup_id = UUID(data["backup_id"])
+ if str(backup_id) != data["backup_id"]:
+ raise ValueError("Expected a canonical backup ID.")
+ return cls(backup_id, AccountBackup.from_manifest(data["backup"]))
+
+ def manifest(self):
+ return {
+ "version": REQUEST_VERSION,
+ "backup_id": str(self.backup_id),
+ "backup": self.backup.manifest(),
+ }
+
+ def identity(self):
+ return {
+ "version": REQUEST_VERSION,
+ "backup_id": str(self.backup_id),
+ "account_id": self.backup.website.account_id,
+ }
+
+
+def backup_archive(account_id, backup_id):
+ return BACKUP_DIRECTORY / f"account-{account_id}-{backup_id}.zip"
+
+
+def serve_backup_request():
+ return serve_apply_request(
+ REQUEST_VERSION,
+ AccountBackupRequest.from_manifest,
+ create_requested_backup,
+ limit=MAX_MANIFEST_BYTES + 4096,
+ identity=AccountBackupRequest.identity,
+ )
+
+
+def create_requested_backup(request):
+ import fcntl
+
+ if os.geteuid() != 0:
+ raise ValueError("Run create-request as root on the backup node.")
+ require_root_directory(BACKUP_DIRECTORY)
+ directory = os.open(
+ BACKUP_DIRECTORY, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
+ )
+ try:
+ fcntl.flock(directory, fcntl.LOCK_EX)
+ ensure_requested_archive(request)
+ finally:
+ os.close(directory)
+
+
+def ensure_requested_archive(request):
+ archive = backup_archive(
+ request.backup.website.account_id, request.backup_id
+ )
+ if not os.path.lexists(archive):
+ create_backup(request.backup, archive, DEFAULT_SOCKET)
+ return
+
+ check_root_file(archive, mode=0o600)
+ try:
+ with ZipFile(archive) as bundle, bundle.open(MANIFEST_NAME) as source:
+ existing = read_backup_manifest(source)
+ except (BadZipFile, KeyError, RuntimeError, ValueError):
+ raise ValueError(
+ "An unreadable archive already exists for this request."
+ ) from None
+ if existing != request.backup:
+ raise ValueError(
+ "An archive with a different manifest already exists."
+ )
diff --git a/src/coulobre/hosting/account_backups.py b/src/coulobre/hosting/account_backups.py
new file mode 100644
index 0000000..8db2f47
--- /dev/null
+++ b/src/coulobre/hosting/account_backups.py
@@ -0,0 +1,20 @@
+from django.db import transaction
+
+from coulobre.account_backup import AccountBackup
+from coulobre.web_node import WebSite
+
+from .resource_requests import lock_hosting_account
+
+
+def account_backup_manifest(account):
+ return AccountBackup(
+ WebSite(account.pk, account.primary_domain),
+ tuple(database.spec for database in account.databases.all()),
+ ).manifest()
+
+
+@transaction.atomic
+def queue_account_backup(account_id):
+ account = lock_hosting_account(account_id, customer_id=None)
+ if not account.backup_jobs.filter(finished_at__isnull=True).exists():
+ account.backup_jobs.create(manifest=account_backup_manifest(account))
diff --git a/src/coulobre/hosting/migrations/0020_account_backup_job.py b/src/coulobre/hosting/migrations/0020_account_backup_job.py
new file mode 100644
index 0000000..ff5aaa7
--- /dev/null
+++ b/src/coulobre/hosting/migrations/0020_account_backup_job.py
@@ -0,0 +1,64 @@
+# Generated by Django 5.2.19 on 2026-11-21 11:25
+
+import uuid
+
+import django.db.models.deletion
+import django.utils.timezone
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("hosting", "0019_site_sftp"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="AccountBackupJob",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "requested_at",
+ models.DateTimeField(default=django.utils.timezone.now),
+ ),
+ (
+ "last_dispatched_at",
+ models.DateTimeField(blank=True, null=True),
+ ),
+ ("started_at", models.DateTimeField(blank=True, null=True)),
+ ("finished_at", models.DateTimeField(blank=True, null=True)),
+ ("problem", models.TextField(blank=True)),
+ (
+ "backup_id",
+ models.UUIDField(
+ default=uuid.uuid4, editable=False, unique=True
+ ),
+ ),
+ ("manifest", models.JSONField()),
+ (
+ "account",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="backup_jobs",
+ to="hosting.hostingaccount",
+ ),
+ ),
+ ],
+ options={
+ "indexes": [
+ models.Index(
+ fields=["finished_at", "requested_at"],
+ name="hosting_acc_finishe_d566ad_idx",
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py
index ce4988d..9b3a2fd 100644
--- a/src/coulobre/hosting/models.py
+++ b/src/coulobre/hosting/models.py
@@ -1,9 +1,12 @@
+import uuid
+
from django.conf import settings
from django.core.validators import RegexValidator
from django.db import models
from django.urls import reverse
from django.utils import timezone
+from coulobre.account_backup_request import backup_archive
from coulobre.database_node import (
DATABASE_SUFFIX_PATTERN,
INVALID_SUFFIX,
@@ -373,6 +376,23 @@ class DatabaseProvisioning(ProvisioningJob):
)
+class AccountBackupJob(ProvisioningJob):
+ account = models.ForeignKey(
+ HostingAccount, on_delete=models.CASCADE, related_name="backup_jobs"
+ )
+ backup_id = models.UUIDField(
+ default=uuid.uuid4, unique=True, editable=False
+ )
+ manifest = models.JSONField()
+
+ class Meta:
+ indexes = [models.Index(fields=("finished_at", "requested_at"))]
+
+ @property
+ def archive(self):
+ return str(backup_archive(self.account_id, self.backup_id))
+
+
class DnsPublication(ProvisioningJob):
zone = models.OneToOneField(
HostingDnsZone, on_delete=models.CASCADE, related_name="publication"
diff --git a/src/coulobre/hosting/node_client.py b/src/coulobre/hosting/node_client.py
index f6920cd..07a08f3 100644
--- a/src/coulobre/hosting/node_client.py
+++ b/src/coulobre/hosting/node_client.py
@@ -1,6 +1,11 @@
import json
import socket
+from coulobre.account_backup_request import (
+ BACKUP_SOCKET,
+ BACKUP_TIMEOUT_SECONDS,
+)
+
RESPONSE_LIMIT = 32768
@@ -51,15 +56,28 @@ def provision_local_mailbox(mailbox):
)
+def create_local_account_backup(request):
+ apply_on_local_node(
+ request,
+ BACKUP_SOCKET,
+ "backup node",
+ "account backup",
+ identity=request.identity(),
+ timeout=BACKUP_TIMEOUT_SECONDS + 15,
+ )
+
+
def encode_manifest(manifest):
return json.dumps(manifest).encode("utf-8")
-def apply_on_local_node(spec, socket_path, node, resource, *, identity=None):
+def apply_on_local_node(
+ spec, socket_path, node, resource, *, identity=None, timeout=195
+):
manifest = spec.manifest()
expected = manifest if identity is None else identity
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client:
- client.settimeout(195)
+ client.settimeout(timeout)
client.connect(socket_path)
client.sendall(encode_manifest(manifest))
client.shutdown(socket.SHUT_WR)
diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py
index d72e4ea..96077cc 100644
--- a/src/coulobre/hosting/tasks.py
+++ b/src/coulobre/hosting/tasks.py
@@ -5,11 +5,17 @@ from django.conf import settings
from django.db.models import Q
from django.utils import timezone
+from coulobre.account_backup import AccountBackup
+from coulobre.account_backup_request import (
+ BACKUP_TIMEOUT_SECONDS,
+ AccountBackupRequest,
+)
from coulobre.dns_node import DnsZone
from coulobre.sftp_keys import SFTPKeys
from coulobre.web_node import WebSite
from .models import (
+ AccountBackupJob,
DatabaseProvisioning,
DnsPublication,
MailboxProvisioning,
@@ -20,6 +26,7 @@ from .models import (
)
from .node_client import (
activate_local_site,
+ create_local_account_backup,
enable_local_https,
provision_local_database,
provision_local_mailbox,
@@ -29,6 +36,8 @@ from .node_client import (
from .sftp import site_is_active
REDISPATCH_AFTER = timedelta(minutes=5)
+ACCOUNT_BACKUP_LEASE = timedelta(seconds=BACKUP_TIMEOUT_SECONDS + 60)
+ACCOUNT_BACKUP_QUEUE = "coulobre-account-backups"
WEB_ACTIVATION_QUEUE = "coulobre-web-activation"
WEB_HTTPS_QUEUE = "coulobre-web-https"
WEB_SFTP_QUEUE = "coulobre-web-sftp"
@@ -118,15 +127,27 @@ def dispatch_mailbox_provisioning():
)
-def dispatch_provisioning_jobs(model, task, queue):
- stale_before = timezone.now() - REDISPATCH_AFTER
+@shared_task
+def dispatch_account_backups():
+ if settings.LOCAL_ACCOUNT_BACKUPS:
+ dispatch_provisioning_jobs(
+ AccountBackupJob,
+ create_account_backup,
+ ACCOUNT_BACKUP_QUEUE,
+ lease=ACCOUNT_BACKUP_LEASE,
+ )
+
+
+def dispatch_provisioning_jobs(model, task, queue, *, lease=REDISPATCH_AFTER):
+ now = timezone.now()
+ stale_before = now - REDISPATCH_AFTER
waiting = model.objects.filter(finished_at__isnull=True)
pending = (
waiting.filter(
Q(last_dispatched_at__isnull=True)
| Q(last_dispatched_at__lte=stale_before)
)
- .filter(Q(started_at__isnull=True) | Q(started_at__lte=stale_before))
+ .filter(Q(started_at__isnull=True) | Q(started_at__lte=now - lease))
.order_by("requested_at", "pk")
.values_list("pk", "requested_at")[:100]
)
@@ -257,12 +278,33 @@ def apply_mailbox_provisioning(provisioning):
provision_local_mailbox(provisioning.mailbox.spec)
-def run_provisioning_job(jobs, job_id, apply, connection_problem):
+@shared_task(acks_late=True, reject_on_worker_lost=True)
+def create_account_backup(job_id):
+ if settings.LOCAL_ACCOUNT_BACKUPS:
+ run_provisioning_job(
+ AccountBackupJob.objects.all(),
+ job_id,
+ apply_account_backup,
+ "Could not complete the request to the local backup node. "
+ "Check its socket and try again.",
+ lease=ACCOUNT_BACKUP_LEASE,
+ )
+
+
+def apply_account_backup(job):
+ backup = AccountBackup.from_manifest(job.manifest)
+ if backup.website.account_id != job.account_id:
+ raise ValueError("The backup manifest belongs to a different account.")
+ create_local_account_backup(AccountBackupRequest(job.backup_id, backup))
+
+
+def run_provisioning_job(
+ jobs, job_id, apply, connection_problem, *, lease=REDISPATCH_AFTER
+):
started_at = timezone.now()
pending = jobs.filter(pk=job_id, finished_at__isnull=True)
claim = pending.filter(
- Q(started_at__isnull=True)
- | Q(started_at__lte=started_at - REDISPATCH_AFTER)
+ Q(started_at__isnull=True) | Q(started_at__lte=started_at - lease)
)
if not claim.update(started_at=started_at):
return
diff --git a/src/coulobre/hosting/templates/hosting/account_backups.html b/src/coulobre/hosting/templates/hosting/account_backups.html
new file mode 100644
index 0000000..bb05241
--- /dev/null
+++ b/src/coulobre/hosting/templates/hosting/account_backups.html
@@ -0,0 +1,46 @@
+ No backups requested.Backups
+
+
+
+
+
+
+
+ {% for job in account_backup_jobs %}
+ Requested Status Archive
+
+ {% endfor %}
+
+ {{ job.requested_at|date:"j M Y, H:i" }} UTC
+
+ {% if job.state == "configured" %}
+ Ready
+ {% else %}
+ {{ job.state|capfirst }}
+ {% endif %}
+
+
+ {% if job.state == "configured" %}
+
+ {{ job.archive }}
+ {% elif job.problem %}
+ {{ job.problem }}
+ {% endif %}
+