Configure and monitor off-site copies in the hosting panel
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s

This commit is contained in:
parkel committed 2026-11-22 16:14:55 +01:00
1 parent ab16c9db62
commit 0b93754e4c
8 files changed
+428 -3

No files matched your search

@@ -1,6 +1,7 @@
from uuid import uuid4
from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from coulobre.account_backup_retention import MAX_RETAINED_BACKUPS
@@ -18,6 +19,7 @@ SCHEDULE_FIELDS = (
"weekday",
"time",
"include_mailboxes",
"offsite_destination",
)
@@ -47,6 +49,15 @@ class AccountBackupScheduleForm(forms.Form):
self.allow_mail = allow_mail
if not allow_mail and not self.initial.get("include_mailboxes"):
del self.fields["include_mailboxes"]
destinations = settings.OFFSITE_BACKUP_DESTINATIONS
current = self.initial.get("offsite_destination")
if destinations or current:
choices = [("", "Local archive only"), *destinations.items()]
if current and current not in destinations:
choices.append((current, f"{current} (unavailable)"))
self.fields["offsite_destination"] = forms.ChoiceField(
choices=choices, required=False, label="Off-site destination"
)
def clean(self):
cleaned = super().clean()
@@ -28,6 +28,28 @@
{% else %}
{{ job.state|capfirst }}
{% endif %}
{% with transfer=job.offsite_transfer %}
{% if transfer %}
<div>Off-site · {{ transfer.label }} · {{ transfer.status }}</div>
{% if transfer.verified_at %}
<div>{{ transfer.verified_at|date:"j M Y, H:i" }} UTC</div>
<details>
<summary>Recovery details</summary>
<div>Backup ID <code>{{ job.backup_id }}</code></div>
<div>Account ID <code>{{ job.account_id }}</code></div>
<div>Destination ID <code>{{ transfer.destination }}</code></div>
</details>
{% elif transfer.problem %}
<div>{{ transfer.problem }}</div>
{% if can_retry_offsite and transfer.status == "Failed" %}
<form method="post" action="{% url 'panel:retry_offsite_backup' account.pk job.pk %}">
{% csrf_token %}
<button type="submit" class="button secondary">Retry off-site copy</button>
</form>
{% endif %}
{% endif %}
{% endif %}
{% endwith %}
</td>
<td>
{% if job.expired_at %}
@@ -0,0 +1,266 @@
import json
from datetime import timedelta
from pathlib import Path
from unittest.mock import patch
from uuid import uuid4
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.test import SimpleTestCase, TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from coulobre.account_backup import AccountBackup
from coulobre.offsite_backup import OffsiteBackupRequest, destination_labels
from coulobre.offsite_node import OffsiteRepositoryError, Repository
from coulobre.web_node import WebSite
from .account_backups import queue_account_backup, queue_due_account_backups
from .backup_retention import plan_backup_expirations
from .models import (
AccountBackupExpiration,
HostingAccount,
OffsiteBackupTransfer,
)
from .offsite_backups import MAX_ATTEMPTS, OFFSITE_BACKUP_QUEUE
from .tasks import dispatch_offsite_backups, transfer_offsite_backup
class OffsiteRepositoryTests(SimpleTestCase):
def test_destination_profiles_and_requests_are_bounded(self):
request = OffsiteBackupRequest(42, uuid4(), "vault")
self.assertEqual(
OffsiteBackupRequest.from_manifest(request.manifest()), request
)
for destination in ("../vault", "elsewhere:repo", "A", "two words"):
with (
self.subTest(destination=destination),
self.assertRaises(ValueError),
):
destination_labels({destination: "Fixture"})
self.assertNotIn("password", request.manifest())
def test_snapshot_lookup_checks_archive_identity_and_checksum_metadata(
self,
):
request = OffsiteBackupRequest(42, uuid4(), "vault")
repository = Repository(Path("/etc/coulobre/offsite/vault"))
entry = {
"id": "a" * 64,
"paths": [f"/{request.archive_name}"],
"tags": [request.tag, "coulobre-sha256-" + "b" * 64],
}
with patch.object(
Repository, "run", return_value=json.dumps([entry])
) as restic:
self.assertEqual(
repository.snapshot(request), ("a" * 64, "b" * 64)
)
restic.assert_called_once_with(
"--json", "snapshots", "--tag", request.tag, capture=True
)
for entries in ([entry, entry], [entry | {"paths": ["/another.zip"]}]):
with (
patch.object(
Repository, "run", return_value=json.dumps(entries)
),
self.assertRaises(OffsiteRepositoryError),
):
repository.snapshot(request)
@override_settings(
LOCAL_ACCOUNT_BACKUPS=True,
LOCAL_BACKUP_RETENTION=True,
OFFSITE_BACKUP_DESTINATIONS={"vault": "Off-site vault"},
)
class OffsiteBackupWorkflowTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.operator = get_user_model().objects.create_superuser("operator")
cls.account = HostingAccount.objects.create(
name="Off-site fixture",
primary_domain="example.test",
scheduled_backups_to_keep=1,
)
def setUp(self):
self.client.force_login(self.operator)
self.now = timezone.now()
self.history = reverse(
"panel:account_backup_archives", args=[self.account.pk]
)
self.schedule = reverse(
"panel:account_backup_schedule", args=[self.account.pk]
)
def archive(self, *, age=0, **values):
requested = self.now - timedelta(days=age)
spec = AccountBackup(
WebSite(self.account.pk, self.account.primary_domain), ()
)
return self.account.backup_jobs.create(
**(
{
"manifest": spec.manifest(),
"finished_at": requested,
"requested_at": requested,
"scheduled_for": requested,
}
| values
)
)
def transfer(self, archive=None, **values):
return OffsiteBackupTransfer.objects.create(
backup=self.archive() if archive is None else archive,
destination="vault",
next_attempt_at=self.now,
**values,
)
def test_only_scheduled_backups_capture_the_configured_destination(self):
response = self.client.post(
self.schedule,
{
"enabled": "on",
"frequency": "daily",
"time": "10:00",
"offsite_destination": "vault",
},
)
self.assertRedirects(response, self.account.get_absolute_url())
schedule = self.account.backup_schedule
self.assertEqual(schedule.offsite_destination, "vault")
schedule.next_run_at = self.now
schedule.save(update_fields=["next_run_at"])
queue_due_account_backups(self.now)
offsite = OffsiteBackupTransfer.objects.get()
self.assertEqual(offsite.backup.scheduled_for, self.now)
self.assertEqual(offsite.destination, "vault")
offsite.backup.finished_at = self.now
offsite.backup.save(update_fields=["finished_at"])
queue_account_backup(self.account.pk)
self.assertEqual(OffsiteBackupTransfer.objects.count(), 1)
self.assertTrue(
self.account.backup_jobs.filter(
scheduled_for__isnull=True
).exists()
)
self.assertContains(
self.client.post(
self.schedule,
{
"enabled": "on",
"frequency": "daily",
"time": "10:00",
"offsite_destination": "../../elsewhere",
},
),
"Select a valid choice",
)
def test_only_finished_local_archives_are_dispatched(self):
ready = self.transfer()
self.transfer(self.archive(finished_at=None))
self.transfer(self.archive(problem="Local backup failed"))
self.transfer(self.archive(expired_at=self.now))
with patch.object(transfer_offsite_backup, "apply_async") as publish:
dispatch_offsite_backups.run()
publish.assert_called_once_with(
args=[ready.pk],
queue=OFFSITE_BACKUP_QUEUE,
retry=False,
)
def test_retry_is_bounded_and_duplicate_delivery_does_not_reupload(self):
transfer = self.transfer()
with patch(
"coulobre.hosting.offsite_backups.apply_offsite_transfer",
side_effect=OSError("secret fixture"),
) as send:
for attempt in range(MAX_ATTEMPTS):
OffsiteBackupTransfer.objects.filter(pk=transfer.pk).update(
next_attempt_at=self.now
)
transfer_offsite_backup.run(transfer.pk)
transfer_offsite_backup.run(transfer.pk)
self.assertEqual(send.call_count, attempt + 1)
transfer.refresh_from_db()
self.assertIsNotNone(transfer.finished_at)
self.assertNotIn("secret fixture", transfer.problem)
self.assertContains(
self.client.get(self.history), "Retry off-site copy"
)
retry = reverse(
"panel:retry_offsite_backup",
args=[self.account.pk, transfer.backup_id],
)
self.assertRedirects(self.client.post(retry), self.history)
transfer.refresh_from_db()
self.assertEqual(transfer.attempts, 0)
with patch(
"coulobre.hosting.offsite_backups.apply_offsite_transfer",
return_value=("a" * 64, "b" * 64),
) as send:
transfer_offsite_backup.run(transfer.pk)
transfer_offsite_backup.run(transfer.pk)
send.assert_called_once()
transfer.refresh_from_db()
self.assertEqual(transfer.snapshot, "a" * 64)
self.assertEqual(transfer.sha256, "b" * 64)
self.assertIsNotNone(transfer.verified_at)
self.assertContains(
self.client.get(self.history), "Off-site vault · Verified"
)
self.assertEqual(self.client.post(retry).status_code, 409)
def test_retention_keeps_the_source_and_waits_for_a_verified_successor(
self,
):
previous = self.archive(age=3)
waiting = self.transfer(
self.archive(age=2), problem="Unavailable", finished_at=self.now
)
newest = self.transfer(self.archive(age=1))
plan_backup_expirations(self.now)
self.assertFalse(AccountBackupExpiration.objects.exists())
newest.verified_at = newest.finished_at = self.now
newest.save(update_fields=["verified_at", "finished_at"])
plan_backup_expirations(self.now)
expiration = AccountBackupExpiration.objects.get()
self.assertEqual(expiration.backup, previous)
self.assertEqual(expiration.keeper_ids, [str(newest.backup.backup_id)])
self.assertFalse(
AccountBackupExpiration.objects.filter(
backup=waiting.backup
).exists()
)
def test_retry_permission_and_account_scope(self):
transfer = self.transfer(finished_at=self.now, problem="Failed")
user = get_user_model().objects.create_user("limited-operator")
user.user_permissions.add(
*Permission.objects.filter(
codename__in=[
"view_hostingaccount",
"view_webprovisioningplan",
"view_hostingdatabase",
"add_accountbackupjob",
]
)
)
self.client.force_login(user)
retry = reverse(
"panel:retry_offsite_backup",
args=[self.account.pk, transfer.backup_id],
)
self.assertEqual(self.client.post(retry).status_code, 403)
self.client.force_login(self.operator)
other = HostingAccount.objects.create(
name="Foreign", primary_domain="foreign.test"
)
scoped = reverse(
"panel:retry_offsite_backup", args=[other.pk, transfer.backup_id]
)
self.assertEqual(self.client.post(scoped).status_code, 404)
+5
View File
@@ -184,6 +184,11 @@ urlpatterns = [
views.AccountBackupArchiveList.as_view(),
name="account_backup_archives",
),
path(
"accounts/<int:pk>/backups/<int:backup_pk>/offsite/retry/",
views.RetryOffsiteBackup.as_view(),
name="retry_offsite_backup",
),
path(
"accounts/<int:pk>/backups/retention/",
views.EditBackupRetention.as_view(),
+29 -3
View File
@@ -103,6 +103,7 @@ from .models import (
WebsiteDomain,
WebsiteRestoreJob,
)
from .offsite_backups import retry_offsite_transfer
from .php_settings import (
SitePhpSettingsForm,
last_applied_php_settings,
@@ -188,6 +189,10 @@ MANAGE_BACKUP_SCHEDULE = (
*MANAGE_ACCOUNT_BACKUPS,
"hosting.change_accountbackupschedule",
)
RETRY_OFFSITE_BACKUP = (
*MANAGE_ACCOUNT_BACKUPS,
"hosting.change_offsitebackuptransfer",
)
MANAGE_BACKUP_RETENTION = (
*MANAGE_ACCOUNT_BACKUPS,
VIEW_MAILBOXES,
@@ -522,6 +527,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
):
can_view_mailboxes = user.has_perm(VIEW_MAILBOXES)
context["show_account_backups"] = True
context["can_retry_offsite"] = user.has_perms(RETRY_OFFSITE_BACKUP)
context["manage_backup_retention"] = (
settings.LOCAL_BACKUP_RETENTION
and user.has_perms(MANAGE_BACKUP_RETENTION)
@@ -998,9 +1004,9 @@ class RequestAccountBackup(OperatorOnlyMixin, PermissionRequiredMixin, View):
def visible_account_backups(account, user):
backups = account.backup_jobs.select_related("expiration").order_by(
"-requested_at", "-pk"
)
backups = account.backup_jobs.select_related(
"expiration", "offsite_transfer"
).order_by("-requested_at", "-pk")
if not user.has_perm(VIEW_MAILBOXES):
backups = backups.exclude(manifest__has_key="mailboxes")
return backups
@@ -1029,6 +1035,7 @@ class AccountBackupArchiveList(
def get_context_data(self, **kwargs):
context = super().get_context_data(account=self.account, **kwargs)
user = self.request.user
context["can_retry_offsite"] = user.has_perms(RETRY_OFFSITE_BACKUP)
context["manage_backup_retention"] = (
settings.LOCAL_BACKUP_RETENTION
and user.has_perms(MANAGE_BACKUP_RETENTION)
@@ -1048,6 +1055,25 @@ class AccountBackupArchiveList(
return context
class RetryOffsiteBackup(OperatorOnlyMixin, PermissionRequiredMixin, View):
permission_required = RETRY_OFFSITE_BACKUP
def post(self, request, pk, backup_pk):
if not settings.LOCAL_ACCOUNT_BACKUPS:
raise Http404
account = get_object_or_404(HostingAccount, pk=pk)
backup = get_object_or_404(
visible_account_backups(account, request.user),
pk=backup_pk,
offsite_transfer__isnull=False,
)
try:
retry_offsite_transfer(backup.offsite_transfer)
except ValidationError as error:
return provisioning_conflict(error)
return redirect("panel:account_backup_archives", pk=pk)
class BackupRetentionView(
OperatorOnlyMixin, PermissionRequiredMixin, FormView
):
+4
View File
@@ -18,6 +18,10 @@ SERVICES = {
"Coulobre website job worker",
"coulobre-website-job-worker.service",
),
"offsite-backups": (
"Coulobre off-site backup worker",
"coulobre-offsite-worker.service",
),
"apache": ("Apache", "apache2.service"),
"php-fpm": ("PHP-FPM", f"{DEFAULT_PHP_RUNTIME.service}.service"),
"mariadb": ("MariaDB", "mariadb.service"),