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 @@ +
+
+
+

Backups

+

Includes the website and its MariaDB databases.

+
+ {% if not account_backup_pending %} +
+ {% csrf_token %} + +
+ {% endif %} +
+ {% if account_backup_jobs %} +
+ + + + + + {% for job in account_backup_jobs %} + + + + + + {% endfor %} + +
RequestedStatusArchive
{{ 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 %} +
+
+ {% else %} +

No backups requested.

+ {% endif %} +
diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index 47201fb..a11d01e 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -34,6 +34,9 @@ {% endif %}
Added
{{ account.created_at|date:"j M Y, H:i" }} UTC
+ {% if show_account_backups %} + {% include "hosting/account_backups.html" %} + {% endif %} {% if is_reseller or is_operator and perms.hosting.view_webprovisioningplan %}
diff --git a/src/coulobre/hosting/test_panel_account_backups.py b/src/coulobre/hosting/test_panel_account_backups.py new file mode 100644 index 0000000..745f0c1 --- /dev/null +++ b/src/coulobre/hosting/test_panel_account_backups.py @@ -0,0 +1,209 @@ +import json +from contextlib import redirect_stdout +from datetime import timedelta +from io import BytesIO, StringIO +from pathlib import Path +from tempfile import TemporaryDirectory +from types import SimpleNamespace +from unittest.mock import patch +from uuid import uuid4 +from zipfile import ZipFile + +from django.contrib.auth import get_user_model +from django.test import SimpleTestCase, TestCase, override_settings +from django.urls import reverse +from django.utils import timezone + +from coulobre import account_backup_request +from coulobre.account_backup import AccountBackup, main +from coulobre.account_backup_request import AccountBackupRequest +from coulobre.database_node import DEFAULT_SOCKET +from coulobre.web_node import WebSite + +from .models import AccountBackupJob, HostingAccount, HostingDatabase, Reseller +from .tasks import ( + ACCOUNT_BACKUP_LEASE, + ACCOUNT_BACKUP_QUEUE, + create_account_backup, + dispatch_account_backups, +) + + +@override_settings(LOCAL_ACCOUNT_BACKUPS=True) +class PanelAccountBackupTests(TestCase): + @classmethod + def setUpTestData(cls): + users = get_user_model().objects + cls.operator = users.create_superuser("operator") + cls.viewer = users.create_user("reseller") + cls.account = HostingAccount.objects.create( + name="Example account", + primary_domain="example.net", + reseller=Reseller.objects.create(user=cls.viewer), + ) + cls.database = HostingDatabase.objects.create( + account=cls.account, suffix="cms" + ) + + def setUp(self): + self.client.force_login(self.operator) + self.request_url = reverse( + "panel:account_backup_create", args=[self.account.pk] + ) + + def test_duplicate_requests_keep_one_queued_backup_with_the_original_plan( + self, + ): + self.assertContains( + self.client.get(self.account.get_absolute_url()), "Create backup" + ) + self.assertRedirects( + self.client.post(self.request_url), self.account.get_absolute_url() + ) + HostingDatabase.objects.create(account=self.account, suffix="shop") + self.client.post(self.request_url) + + job = AccountBackupJob.objects.get(account=self.account) + manifest = AccountBackup.from_manifest(job.manifest) + self.assertEqual(manifest.databases, (self.database.spec,)) + page = self.client.get(self.account.get_absolute_url()) + self.assertContains(page, "Queued") + self.assertNotContains(page, "Create backup") + + def test_worker_reports_the_archive_and_allows_another_backup(self): + self.client.post(self.request_url) + job = AccountBackupJob.objects.get(account=self.account) + with patch( + "coulobre.hosting.tasks.create_local_account_backup" + ) as node: + create_account_backup(job.pk) + create_account_backup(job.pk) + + node.assert_called_once_with( + AccountBackupRequest( + job.backup_id, AccountBackup.from_manifest(job.manifest) + ) + ) + page = self.client.get(self.account.get_absolute_url()) + self.assertContains(page, "Ready") + self.assertContains(page, job.archive) + self.client.post(self.request_url) + self.assertEqual(self.account.backup_jobs.count(), 2) + + def test_a_running_backup_is_only_reclaimed_after_its_own_lease(self): + self.client.post(self.request_url) + job = AccountBackupJob.objects.get(account=self.account) + job.started_at = job.last_dispatched_at = timezone.now() - timedelta( + minutes=6 + ) + job.save(update_fields=["started_at", "last_dispatched_at"]) + with ( + patch.object(create_account_backup, "apply_async") as publish, + patch( + "coulobre.hosting.tasks.create_local_account_backup" + ) as node, + ): + dispatch_account_backups() + create_account_backup(job.pk) + publish.assert_not_called() + node.assert_not_called() + + job.started_at = timezone.now() - ACCOUNT_BACKUP_LEASE + job.save(update_fields=["started_at"]) + dispatch_account_backups() + create_account_backup(job.pk) + publish.assert_called_once_with( + args=[job.pk], queue=ACCOUNT_BACKUP_QUEUE, retry=False + ) + self.assertEqual(node.call_args.args[0].backup_id, job.backup_id) + + @override_settings(LOCAL_ACCOUNT_BACKUPS=False) + def test_disabled_panel_backup_has_no_action(self): + self.assertEqual(self.client.post(self.request_url).status_code, 404) + self.assertNotContains( + self.client.get(self.account.get_absolute_url()), "Create backup" + ) + self.assertFalse(AccountBackupJob.objects.exists()) + + def test_reseller_cannot_create_or_view_backup_jobs(self): + self.client.force_login(self.viewer) + self.assertEqual(self.client.post(self.request_url).status_code, 403) + self.assertNotContains( + self.client.get(self.account.get_absolute_url()), "Create backup" + ) + self.assertFalse(AccountBackupJob.objects.exists()) + + +class AccountBackupRequestTests(SimpleTestCase): + def setUp(self): + self.directory = Path(self.enterContext(TemporaryDirectory())) + self.backup = AccountBackup(WebSite(123, "example.net"), ()) + self.request = AccountBackupRequest(uuid4(), self.backup) + self.enterContext( + patch.object( + account_backup_request, "BACKUP_DIRECTORY", self.directory + ) + ) + self.enterContext( + patch.object(account_backup_request, "require_root_directory") + ) + self.enterContext( + patch.object(account_backup_request, "check_root_file") + ) + self.enterContext( + patch.object(account_backup_request.os, "geteuid", return_value=0) + ) + self.create = self.enterContext( + patch.object( + account_backup_request, + "create_backup", + side_effect=self.write_zip, + ) + ) + + def write_zip(self, backup, archive, socket): + with ZipFile(archive, mode="x") as bundle: + bundle.writestr("manifest.json", json.dumps(backup.manifest())) + + def send(self, manifest): + source = BytesIO(json.dumps(manifest).encode()) + with ( + patch("sys.stdin", SimpleNamespace(buffer=source)), + redirect_stdout(StringIO()) as output, + ): + result = main(["create-request"]) + return result, json.loads(output.getvalue()) + + def test_replayed_request_reuses_the_published_archive(self): + archive = self.directory / f"account-123-{self.request.backup_id}.zip" + for _ in range(2): + code, report = self.send(self.request.manifest()) + self.assertEqual(code, 0) + self.assertEqual( + report, + self.request.identity() + | {"state": "configured", "problem": None}, + ) + self.create.assert_called_once_with( + self.backup, archive, DEFAULT_SOCKET + ) + + def test_request_does_not_accept_a_destination_path(self): + code, report = self.send( + self.request.manifest() | {"archive": str(self.directory)} + ) + self.assertEqual(code, 1) + self.assertEqual(report["state"], "failed") + self.create.assert_not_called() + + def test_replay_rejects_an_archive_with_a_different_plan(self): + archive = self.directory / f"account-123-{self.request.backup_id}.zip" + self.write_zip( + AccountBackup(WebSite(123, "other.example"), ()), archive, None + ) + + code, report = self.send(self.request.manifest()) + + self.assertEqual(code, 1) + self.assertIn("a different manifest", report["problem"]) + self.create.assert_not_called() diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index d08eedd..c6eb71d 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -25,6 +25,11 @@ urlpatterns = [ views.DownloadAccountBackupManifest.as_view(), name="account_backup_manifest", ), + path( + "accounts//backups/", + views.RequestAccountBackup.as_view(), + name="account_backup_create", + ), path( "accounts//sftp/", views.SiteSFTPKeys.as_view(), diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index 473dff2..7324068 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -26,11 +26,9 @@ from django.views.generic import ( ) from django.views.generic.detail import SingleObjectMixin -from coulobre.account_backup import AccountBackup from coulobre.dns_node import MAX_SOA_SERIAL from coulobre.mail_node import INVALID_LOCAL_PART from coulobre.sftp_keys import public_key_fingerprint -from coulobre.web_node import WebSite from .access import ( OperatorOnlyMixin, @@ -39,6 +37,7 @@ from .access import ( is_tenant, reseller_for_user, ) +from .account_backups import account_backup_manifest, queue_account_backup from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record from .dns_publication import queue_dns_publication from .impersonation import ( @@ -81,6 +80,10 @@ VIEW_DATABASES = "hosting.view_hostingdatabase" VIEW_DNS_ZONES = "hosting.view_hostingdnszone" VIEW_MAILBOXES = "hosting.view_hostingmailbox" EXPORT_BACKUP_MANIFEST = (VIEW_ACCOUNTS, VIEW_PLANS, VIEW_DATABASES) +MANAGE_ACCOUNT_BACKUPS = ( + *EXPORT_BACKUP_MANIFEST, + "hosting.add_accountbackupjob", +) ACTIVATE_WEB = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webactivation") ENABLE_WEB_HTTPS = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webhttps") PROVISION_DATABASE = ( @@ -235,6 +238,19 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): context["export_backup_manifest"] = not tenant and user.has_perms( EXPORT_BACKUP_MANIFEST ) + if ( + settings.LOCAL_ACCOUNT_BACKUPS + and not tenant + and user.has_perms(MANAGE_ACCOUNT_BACKUPS) + ): + jobs = list( + self.object.backup_jobs.order_by("-requested_at", "-pk")[:10] + ) + context["show_account_backups"] = True + context["account_backup_jobs"] = jobs + context["account_backup_pending"] = any( + job.finished_at is None for job in jobs + ) context["manage_sftp"] = ( settings.LOCAL_WEB_SFTP and can_manage_sftp(user) @@ -289,12 +305,8 @@ class DownloadAccountBackupManifest( def get(self, request, pk): account = get_object_or_404(HostingAccount, pk=pk) - backup = AccountBackup( - WebSite(account.pk, account.primary_domain), - tuple(database.spec for database in account.databases.all()), - ) return JsonResponse( - backup.manifest(), + account_backup_manifest(account), headers={ "Cache-Control": "private, no-store", "Content-Disposition": ( @@ -305,6 +317,19 @@ class DownloadAccountBackupManifest( ) +class RequestAccountBackup(OperatorOnlyMixin, PermissionRequiredMixin, View): + permission_required = MANAGE_ACCOUNT_BACKUPS + + def post(self, request, pk): + if not settings.LOCAL_ACCOUNT_BACKUPS: + raise Http404 + try: + queue_account_backup(pk) + except HostingAccount.DoesNotExist: + raise Http404 from None + return redirect("panel:account", pk=pk) + + class SiteSFTPKeys(PermissionRequiredMixin, FormView): form_class = SFTPKeyUploadForm template_name = "hosting/sftp_keys.html" diff --git a/src/coulobre/settings.py b/src/coulobre/settings.py index 843f4d1..0c48d05 100644 --- a/src/coulobre/settings.py +++ b/src/coulobre/settings.py @@ -128,6 +128,7 @@ LOCAL_DNS_PUBLISHING = os.environ.get("COULOBRE_LOCAL_DNS_PUBLISHING") == "1" LOCAL_MAILBOX_PROVISIONING = ( os.environ.get("COULOBRE_LOCAL_MAILBOX_PROVISIONING") == "1" ) +LOCAL_ACCOUNT_BACKUPS = os.environ.get("COULOBRE_LOCAL_ACCOUNT_BACKUPS") == "1" CELERY_BEAT_SCHEDULE = { "dispatch-web-provisioning-plans": { "task": "coulobre.hosting.tasks.dispatch_web_plans", @@ -171,3 +172,9 @@ if LOCAL_MAILBOX_PROVISIONING: "schedule": 5.0, "options": {"expires": 4.0}, } +if LOCAL_ACCOUNT_BACKUPS: + CELERY_BEAT_SCHEDULE["dispatch-account-backups"] = { + "task": "coulobre.hosting.tasks.dispatch_account_backups", + "schedule": 5.0, + "options": {"expires": 4.0}, + }