From 5c61ddc4cc492761a02a7ccf24a1859f278c82a0 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sat, 21 Nov 2026 14:26:38 +0100 Subject: [PATCH 1/3] Queue account backups on daily and weekly schedules --- src/coulobre/hosting/account_backups.py | 84 ++++++++++++++++++- .../0025_account_backup_schedules.py | 76 +++++++++++++++++ src/coulobre/hosting/models.py | 35 ++++++++ src/coulobre/hosting/tasks.py | 2 + 4 files changed, 195 insertions(+), 2 deletions(-) create mode 100644 src/coulobre/hosting/migrations/0025_account_backup_schedules.py diff --git a/src/coulobre/hosting/account_backups.py b/src/coulobre/hosting/account_backups.py index d8d2731..1ec172d 100644 --- a/src/coulobre/hosting/account_backups.py +++ b/src/coulobre/hosting/account_backups.py @@ -1,9 +1,13 @@ +from datetime import UTC, datetime, timedelta + +from django.core.exceptions import PermissionDenied from django.db import transaction +from django.utils import timezone from coulobre.account_backup import AccountBackup from coulobre.web_node import WebSite -from .models import HostingMailbox +from .models import AccountBackupSchedule, HostingAccount, HostingMailbox from .resource_requests import lock_hosting_account @@ -24,9 +28,85 @@ def account_backup_manifest(account, *, include_mailboxes=False): @transaction.atomic def queue_account_backup(account_id, *, include_mailboxes=False): account = lock_hosting_account(account_id, customer_id=None) + _enqueue_backup(account, include_mailboxes=include_mailboxes) + + +def _enqueue_backup(account, *, include_mailboxes, scheduled_for=None): if not account.backup_jobs.filter(finished_at__isnull=True).exists(): account.backup_jobs.create( manifest=account_backup_manifest( account, include_mailboxes=include_mailboxes - ) + ), + scheduled_for=scheduled_for, ) + + +def _next_backup_run(schedule, now): + now = now.astimezone(UTC) + run_at = datetime.combine(now.date(), schedule.time, tzinfo=UTC) + if schedule.frequency == AccountBackupSchedule.Frequency.WEEKLY: + run_at += timedelta(days=(schedule.weekday - now.weekday()) % 7) + interval = timedelta(weeks=1) + else: + interval = timedelta(days=1) + return run_at if run_at > now else run_at + interval + + +@transaction.atomic +def save_backup_schedule(account_id, *, can_manage_mail, schedule_fields): + account = lock_hosting_account(account_id, customer_id=None) + schedule = getattr(account, "backup_schedule", None) + if schedule is None: + schedule = AccountBackupSchedule(account=account) + if not can_manage_mail and ( + schedule.include_mailboxes or schedule_fields["include_mailboxes"] + ): + raise PermissionDenied + + timing_changed = any( + getattr(schedule, field) != schedule_fields[field] + for field in ("enabled", "frequency", "weekday", "time") + ) + for field, value in schedule_fields.items(): + setattr(schedule, field, value) + if not schedule.enabled: + schedule.next_run_at = None + elif timing_changed or schedule.next_run_at is None: + schedule.next_run_at = _next_backup_run(schedule, timezone.now()) + schedule.save() + + +def queue_due_account_backups(now): + due_account_ids = list( + AccountBackupSchedule.objects.filter( + enabled=True, next_run_at__lte=now + ) + .order_by("next_run_at", "pk") + .values_list("account_id", flat=True)[:100] + ) + for account_id in due_account_ids: + try: + _queue_scheduled_backup(account_id, now) + except HostingAccount.DoesNotExist: + continue + + +@transaction.atomic +def _queue_scheduled_backup(account_id, now): + account = lock_hosting_account(account_id, customer_id=None) + schedule = getattr(account, "backup_schedule", None) + if ( + schedule is None + or not schedule.enabled + or schedule.next_run_at is None + or schedule.next_run_at > now + ): + return + + _enqueue_backup( + account, + include_mailboxes=schedule.include_mailboxes, + scheduled_for=schedule.next_run_at, + ) + schedule.next_run_at = _next_backup_run(schedule, now) + schedule.save(update_fields=["next_run_at"]) diff --git a/src/coulobre/hosting/migrations/0025_account_backup_schedules.py b/src/coulobre/hosting/migrations/0025_account_backup_schedules.py new file mode 100644 index 0000000..43898cd --- /dev/null +++ b/src/coulobre/hosting/migrations/0025_account_backup_schedules.py @@ -0,0 +1,76 @@ +# Generated by Django 5.2.19 on 2026-11-21 13:22 + +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0024_website_storage_limits"), + ] + + operations = [ + migrations.AddField( + model_name="accountbackupjob", + name="scheduled_for", + field=models.DateTimeField(blank=True, null=True), + ), + migrations.CreateModel( + name="AccountBackupSchedule", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("enabled", models.BooleanField(default=True)), + ( + "frequency", + models.CharField( + choices=[("daily", "Daily"), ("weekly", "Weekly")], + default="daily", + max_length=6, + ), + ), + ( + "weekday", + models.PositiveSmallIntegerField( + blank=True, + choices=[ + (0, "Monday"), + (1, "Tuesday"), + (2, "Wednesday"), + (3, "Thursday"), + (4, "Friday"), + (5, "Saturday"), + (6, "Sunday"), + ], + null=True, + ), + ), + ("time", models.TimeField(verbose_name="time (UTC)")), + ("include_mailboxes", models.BooleanField(default=False)), + ("next_run_at", models.DateTimeField(blank=True, null=True)), + ( + "account", + models.OneToOneField( + on_delete=django.db.models.deletion.CASCADE, + related_name="backup_schedule", + to="hosting.hostingaccount", + ), + ), + ], + options={ + "indexes": [ + models.Index( + fields=["enabled", "next_run_at"], + name="hosting_acc_enabled_34d512_idx", + ) + ], + }, + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index 7cbcafd..26c142f 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -445,6 +445,7 @@ class AccountBackupJob(ProvisioningJob): default=uuid.uuid4, unique=True, editable=False ) manifest = models.JSONField() + scheduled_for = models.DateTimeField(null=True, blank=True) class Meta: indexes = [models.Index(fields=("finished_at", "requested_at"))] @@ -458,6 +459,40 @@ class AccountBackupJob(ProvisioningJob): return "mailboxes" in self.manifest +class AccountBackupSchedule(models.Model): + class Frequency(models.TextChoices): + DAILY = "daily", "Daily" + WEEKLY = "weekly", "Weekly" + + class Weekday(models.IntegerChoices): + MONDAY = 0, "Monday" + TUESDAY = 1, "Tuesday" + WEDNESDAY = 2, "Wednesday" + THURSDAY = 3, "Thursday" + FRIDAY = 4, "Friday" + SATURDAY = 5, "Saturday" + SUNDAY = 6, "Sunday" + + account = models.OneToOneField( + HostingAccount, + on_delete=models.CASCADE, + related_name="backup_schedule", + ) + enabled = models.BooleanField(default=True) + frequency = models.CharField( + max_length=6, choices=Frequency, default=Frequency.DAILY + ) + weekday = models.PositiveSmallIntegerField( + choices=Weekday, null=True, blank=True + ) + time = models.TimeField("time (UTC)") + include_mailboxes = models.BooleanField(default=False) + next_run_at = models.DateTimeField(null=True, blank=True) + + class Meta: + indexes = [models.Index(fields=("enabled", "next_run_at"))] + + class DnsPublication(ProvisioningJob): zone = models.OneToOneField( HostingDnsZone, on_delete=models.CASCADE, related_name="publication" diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py index f3face5..38c74cf 100644 --- a/src/coulobre/hosting/tasks.py +++ b/src/coulobre/hosting/tasks.py @@ -14,6 +14,7 @@ from coulobre.dns_node import DnsZone from coulobre.sftp_keys import SFTPKeys from coulobre.web_node import WebSite +from .account_backups import queue_due_account_backups from .models import ( AccountBackupJob, DatabaseProvisioning, @@ -151,6 +152,7 @@ def dispatch_mailbox_provisioning(): @shared_task def dispatch_account_backups(): if settings.LOCAL_ACCOUNT_BACKUPS: + queue_due_account_backups(timezone.now()) dispatch_provisioning_jobs( AccountBackupJob, create_account_backup, -- 2.43.0 From 52e072ee91f08b02de46e3fa8b5404be7fb2f5d9 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sat, 21 Nov 2026 14:26:38 +0100 Subject: [PATCH 2/3] Manage backup schedules from the hosting account page --- src/coulobre/hosting/account_backup_forms.py | 60 ++++ .../hosting/account_backup_schedule.html | 21 ++ .../templates/hosting/account_backups.html | 26 +- .../hosting/test_account_backup_schedules.py | 279 ++++++++++++++++++ src/coulobre/hosting/urls.py | 5 + src/coulobre/hosting/views.py | 79 ++++- 6 files changed, 467 insertions(+), 3 deletions(-) create mode 100644 src/coulobre/hosting/account_backup_forms.py create mode 100644 src/coulobre/hosting/templates/hosting/account_backup_schedule.html create mode 100644 src/coulobre/hosting/test_account_backup_schedules.py diff --git a/src/coulobre/hosting/account_backup_forms.py b/src/coulobre/hosting/account_backup_forms.py new file mode 100644 index 0000000..7a11a9d --- /dev/null +++ b/src/coulobre/hosting/account_backup_forms.py @@ -0,0 +1,60 @@ +from django import forms + +from .models import AccountBackupSchedule + +SCHEDULE_FIELDS = ( + "enabled", + "frequency", + "weekday", + "time", + "include_mailboxes", +) + + +class AccountBackupScheduleForm(forms.Form): + enabled = forms.BooleanField( + label="Enable scheduled backups", required=False + ) + frequency = forms.ChoiceField( + choices=AccountBackupSchedule.Frequency.choices + ) + weekday = forms.TypedChoiceField( + choices=[("", "Select a day"), *AccountBackupSchedule.Weekday.choices], + coerce=int, + empty_value=None, + required=False, + help_text="Required for weekly backups.", + ) + time = forms.TimeField( + label="Time (UTC)", + input_formats=["%H:%M"], + widget=forms.TimeInput(format="%H:%M", attrs={"type": "time"}), + ) + include_mailboxes = forms.BooleanField(required=False) + + def __init__(self, *args, allow_mail, **kwargs): + super().__init__(*args, **kwargs) + self.allow_mail = allow_mail + if not allow_mail and not self.initial.get("include_mailboxes"): + del self.fields["include_mailboxes"] + + def clean(self): + cleaned = super().clean() + if cleaned.get("frequency") == AccountBackupSchedule.Frequency.WEEKLY: + if "weekday" in cleaned and cleaned["weekday"] is None: + self.add_error("weekday", "Select a day for weekly backups.") + else: + cleaned["weekday"] = None + + cleaned.setdefault("include_mailboxes", False) + if ( + cleaned.get("enabled") + and cleaned["include_mailboxes"] + and not self.allow_mail + ): + self.add_error( + "include_mailboxes", + "Enable local mailbox backups, clear this option, " + "or pause the schedule.", + ) + return cleaned diff --git a/src/coulobre/hosting/templates/hosting/account_backup_schedule.html b/src/coulobre/hosting/templates/hosting/account_backup_schedule.html new file mode 100644 index 0000000..703f16f --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/account_backup_schedule.html @@ -0,0 +1,21 @@ +{% extends "hosting/base.html" %} +{% block title %}Backup schedule · Coulobre Panel{% endblock %} +{% block content %} + ← {{ account.name }} +
+
+

Backup schedule

+

{{ account.primary_domain }}

+
+
+
+
+ {% csrf_token %} + {{ form.as_div }} +
+ + Cancel +
+
+
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/account_backups.html b/src/coulobre/hosting/templates/hosting/account_backups.html index 108b306..35d4008 100644 --- a/src/coulobre/hosting/templates/hosting/account_backups.html +++ b/src/coulobre/hosting/templates/hosting/account_backups.html @@ -3,6 +3,18 @@

Backups

Includes the website and its MariaDB databases.

+ {% if account_backup_schedule %} +

+ {{ account_backup_schedule.get_frequency_display }} + {% if account_backup_schedule.weekday is not None %}on {{ account_backup_schedule.get_weekday_display }}{% endif %} + at {{ account_backup_schedule.time|time:"H:i" }} UTC{% if account_backup_schedule.include_mailboxes %}, including mailboxes{% endif %}. + {% if account_backup_schedule.enabled %} + Next run {{ account_backup_schedule.next_run_at|date:"j M Y, H:i" }} UTC. + {% else %} + Schedule paused. + {% endif %} +

+ {% endif %}
{% if not account_backup_pending %}
@@ -14,6 +26,11 @@
{% endif %} + {% if edit_account_backup_schedule %} + + {% endif %} {% if account_backup_pending_hidden %}

A backup is already queued or running.

{% endif %} @@ -21,12 +38,19 @@
- + {% for job in account_backup_jobs %} +
RequestedContentsStatusArchive
RequestedSourceContentsStatusArchive
{{ job.requested_at|date:"j M Y, H:i" }} UTC + {% if job.scheduled_for %} + Scheduled + {% else %} + Manual + {% endif %} + {% if job.includes_mailboxes %}Website, databases, and mail{% else %}Website and databases{% endif %} {% if job.state == "configured" %} diff --git a/src/coulobre/hosting/test_account_backup_schedules.py b/src/coulobre/hosting/test_account_backup_schedules.py new file mode 100644 index 0000000..0b48fa4 --- /dev/null +++ b/src/coulobre/hosting/test_account_backup_schedules.py @@ -0,0 +1,279 @@ +from datetime import UTC, datetime, timedelta, timezone +from unittest.mock import patch + +from django.contrib.auth import get_user_model +from django.contrib.auth.models import Permission +from django.test import TestCase, override_settings +from django.urls import reverse + +from coulobre.account_backup import AccountBackup + +from .account_backups import queue_due_account_backups +from .models import ( + AccountBackupSchedule, + HostingAccount, + HostingDatabase, + HostingMailbox, + HostingMailDomain, + Reseller, +) +from .tasks import ( + ACCOUNT_BACKUP_QUEUE, + create_account_backup, + dispatch_account_backups, +) + +MONDAY = datetime(2030, 7, 1, 2, 30, tzinfo=UTC) + + +@override_settings(LOCAL_ACCOUNT_BACKUPS=True, LOCAL_ACCOUNT_BACKUP_MAIL=False) +class AccountBackupScheduleTests(TestCase): + @classmethod + def setUpTestData(cls): + cls.operator = get_user_model().objects.create_superuser("operator") + cls.account = HostingAccount.objects.create( + name="Example account", primary_domain="example.net" + ) + + def setUp(self): + self.client.force_login(self.operator) + self.url = reverse( + "panel:account_backup_schedule", args=[self.account.pk] + ) + + def save_schedule(self, **overrides): + data = {"enabled": "on", "frequency": "daily", "time": "02:30"} + return self.client.post(self.url, data | overrides) + + def make_due(self, **fields): + defaults = {"time": MONDAY.time(), "next_run_at": MONDAY} + return AccountBackupSchedule.objects.create( + account=self.account, **(defaults | fields) + ) + + def test_daily_schedule_can_be_saved_paused_and_resumed(self): + self.assertContains( + self.client.get(self.account.get_absolute_url()), + "Schedule backups", + ) + self.assertNotContains(self.client.get(self.url), "Include mailboxes") + with patch( + "coulobre.hosting.account_backups.timezone", now=lambda: MONDAY + ): + self.assertRedirects( + self.save_schedule(), self.account.get_absolute_url() + ) + schedule = AccountBackupSchedule.objects.get(account=self.account) + self.assertEqual(schedule.next_run_at, MONDAY + timedelta(days=1)) + page = self.client.get(self.account.get_absolute_url()) + self.assertContains(page, "Next run 2 Jul 2030, 02:30 UTC") + self.assertContains(page, "Edit backup schedule") + + self.save_schedule(enabled="") + schedule.refresh_from_db() + self.assertFalse(schedule.enabled) + self.assertIsNone(schedule.next_run_at) + self.assertContains( + self.client.get(self.account.get_absolute_url()), "Schedule paused" + ) + with patch( + "coulobre.hosting.account_backups.timezone", + now=lambda: MONDAY + timedelta(days=2), + ): + self.save_schedule() + schedule.refresh_from_db() + self.assertEqual(schedule.next_run_at, MONDAY + timedelta(days=3)) + + def test_weekly_schedule_requires_a_day_and_uses_utc(self): + response = self.save_schedule(frequency="weekly") + self.assertContains(response, "Select a day for weekly backups.") + self.assertFalse(AccountBackupSchedule.objects.exists()) + now = (MONDAY - timedelta(minutes=1)).astimezone( + timezone(-timedelta(hours=4)) + ) + with patch( + "coulobre.hosting.account_backups.timezone", now=lambda: now + ): + self.assertEqual( + self.save_schedule( + frequency="weekly", weekday="0" + ).status_code, + 302, + ) + schedule = AccountBackupSchedule.objects.get(account=self.account) + self.assertEqual( + schedule.weekday, AccountBackupSchedule.Weekday.MONDAY + ) + self.assertEqual(schedule.next_run_at, MONDAY) + self.assertContains( + self.client.get(self.account.get_absolute_url()), "on Monday" + ) + + queue_due_account_backups(MONDAY) + schedule.refresh_from_db() + self.assertEqual(schedule.next_run_at, MONDAY + timedelta(weeks=1)) + + def test_saving_an_unchanged_schedule_keeps_a_due_occurrence(self): + schedule = self.make_due() + with patch( + "coulobre.hosting.account_backups.timezone", now=lambda: MONDAY + ): + self.assertEqual(self.save_schedule().status_code, 302) + schedule.refresh_from_db() + self.assertEqual(schedule.next_run_at, MONDAY) + + def test_dispatch_catches_up_once_and_uses_the_current_account_manifest( + self, + ): + schedule = self.make_due() + database = HostingDatabase.objects.create( + account=self.account, suffix="cms" + ) + now = MONDAY + timedelta(days=4, hours=1) + with ( + patch("django.utils.timezone.now", return_value=now), + patch.object(create_account_backup, "apply_async") as publish, + ): + dispatch_account_backups() + dispatch_account_backups() + + job = self.account.backup_jobs.get() + self.assertEqual(job.scheduled_for, MONDAY) + self.assertEqual( + AccountBackup.from_manifest(job.manifest).databases, + (database.spec,), + ) + publish.assert_called_once_with( + args=[job.pk], queue=ACCOUNT_BACKUP_QUEUE, retry=False + ) + schedule.refresh_from_db() + self.assertEqual(schedule.next_run_at, MONDAY + timedelta(days=5)) + self.assertContains( + self.client.get(self.account.get_absolute_url()), "Scheduled" + ) + + def test_due_time_is_skipped_while_a_manual_backup_is_pending(self): + schedule = self.make_due() + manual_url = reverse( + "panel:account_backup_create", args=[self.account.pk] + ) + self.assertEqual(self.client.post(manual_url).status_code, 302) + + queue_due_account_backups(MONDAY) + job = self.account.backup_jobs.get() + self.assertIsNone(job.scheduled_for) + schedule.refresh_from_db() + self.assertEqual(schedule.next_run_at, MONDAY + timedelta(days=1)) + self.assertContains( + self.client.get(self.account.get_absolute_url()), "Manual" + ) + + def test_dates_and_job_are_unchanged_if_scheduling_fails(self): + schedule = self.make_due() + save = "coulobre.hosting.models.AccountBackupSchedule.save" + with ( + patch(save, side_effect=RuntimeError), + self.assertRaises(RuntimeError), + ): + queue_due_account_backups(MONDAY) + schedule.refresh_from_db() + self.assertEqual(schedule.next_run_at, MONDAY) + self.assertFalse(self.account.backup_jobs.exists()) + + queue_due_account_backups(MONDAY) + self.assertEqual(self.account.backup_jobs.count(), 1) + + @override_settings(LOCAL_ACCOUNT_BACKUPS=False) + def test_schedules_are_unavailable_when_local_backups_are_disabled(self): + schedule = self.make_due() + self.assertEqual(self.client.get(self.url).status_code, 404) + self.assertEqual(self.save_schedule().status_code, 404) + dispatch_account_backups() + self.assertFalse(self.account.backup_jobs.exists()) + schedule.refresh_from_db() + self.assertEqual(schedule.next_run_at, MONDAY) + + @override_settings(LOCAL_ACCOUNT_BACKUP_MAIL=True) + def test_mail_schedule_captures_mailboxes_at_run_time(self): + with patch( + "coulobre.hosting.account_backups.timezone", + now=lambda: MONDAY - timedelta(hours=1), + ): + self.assertEqual( + self.save_schedule(include_mailboxes="on").status_code, 302 + ) + domain = HostingMailDomain.objects.create( + account=self.account, domain="example.net" + ) + mailbox = HostingMailbox.objects.create( + mail_domain=domain, local_part="support" + ) + + queue_due_account_backups(MONDAY) + job = self.account.backup_jobs.get() + self.assertEqual( + AccountBackup.from_manifest(job.manifest).mailboxes, + (mailbox.spec,), + ) + + def test_existing_mail_schedule_can_be_paused_when_mail_is_disabled(self): + schedule = self.make_due(include_mailboxes=True) + response = self.save_schedule(include_mailboxes="on") + self.assertContains(response, "Enable local mailbox backups") + self.assertEqual( + self.save_schedule(enabled="", include_mailboxes="on").status_code, + 302, + ) + schedule.refresh_from_db() + self.assertFalse(schedule.enabled) + self.assertTrue(schedule.include_mailboxes) + queue_due_account_backups(MONDAY) + self.assertFalse(self.account.backup_jobs.exists()) + + @override_settings(LOCAL_ACCOUNT_BACKUP_MAIL=True) + def test_permissions_protect_schedules_and_their_mail_settings(self): + user = get_user_model().objects.create_user("limited-operator") + permissions = Permission.objects.filter( + content_type__app_label="hosting" + ) + user.user_permissions.set( + permissions.filter( + codename__in=( + "view_hostingaccount", + "view_webprovisioningplan", + "view_hostingdatabase", + "add_accountbackupjob", + ) + ) + ) + self.client.force_login(user) + self.assertEqual(self.client.get(self.url).status_code, 403) + self.assertEqual(self.save_schedule().status_code, 403) + + user.user_permissions.add( + permissions.get(codename="change_accountbackupschedule") + ) + self.assertEqual(self.client.get(self.url).status_code, 200) + self.assertEqual( + self.save_schedule(include_mailboxes="on").status_code, 302 + ) + schedule = AccountBackupSchedule.objects.get(account=self.account) + self.assertFalse(schedule.include_mailboxes) + + AccountBackupSchedule.objects.filter(pk=schedule.pk).update( + include_mailboxes=True + ) + self.assertEqual(self.client.get(self.url).status_code, 403) + self.assertEqual(self.save_schedule().status_code, 403) + self.assertNotContains( + self.client.get(self.account.get_absolute_url()), + "Edit backup schedule", + ) + schedule.refresh_from_db() + self.assertTrue(schedule.include_mailboxes) + + Reseller.objects.create(user=user) + user.user_permissions.add( + permissions.get(codename="view_hostingmailbox") + ) + self.assertEqual(self.save_schedule().status_code, 403) diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index 65d1aee..6d95a0d 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -40,6 +40,11 @@ urlpatterns = [ views.RequestAccountBackup.as_view(), name="account_backup_create", ), + path( + "accounts//backups/schedule/", + views.EditAccountBackupSchedule.as_view(), + name="account_backup_schedule", + ), path( "accounts//sftp/", views.SiteSFTPKeys.as_view(), diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index 8594843..e5bb7db 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -2,7 +2,7 @@ from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.mixins import PermissionRequiredMixin -from django.core.exceptions import ValidationError +from django.core.exceptions import PermissionDenied, ValidationError from django.db import IntegrityError, transaction from django.db.models import Q from django.http import ( @@ -37,7 +37,12 @@ from .access import ( is_tenant, reseller_for_user, ) -from .account_backups import account_backup_manifest, queue_account_backup +from .account_backup_forms import SCHEDULE_FIELDS, AccountBackupScheduleForm +from .account_backups import ( + account_backup_manifest, + queue_account_backup, + save_backup_schedule, +) from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record from .dns_publication import queue_dns_publication from .impersonation import ( @@ -47,6 +52,7 @@ from .impersonation import ( start_impersonation, ) from .models import ( + AccountBackupSchedule, Customer, DatabaseProvisioning, HostingAccount, @@ -97,6 +103,10 @@ MANAGE_ACCOUNT_BACKUPS = ( *EXPORT_BACKUP_MANIFEST, "hosting.add_accountbackupjob", ) +MANAGE_BACKUP_SCHEDULE = ( + *MANAGE_ACCOUNT_BACKUPS, + "hosting.change_accountbackupschedule", +) ACTIVATE_WEB = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webactivation") ENABLE_WEB_HTTPS = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webhttps") PROVISION_DATABASE = ( @@ -306,6 +316,16 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): context["account_backup_allow_mail"] = ( settings.LOCAL_ACCOUNT_BACKUP_MAIL and can_view_mailboxes ) + schedule = getattr(self.object, "backup_schedule", None) + if ( + schedule is None + or not schedule.include_mailboxes + or can_view_mailboxes + ): + context["account_backup_schedule"] = schedule + context["edit_account_backup_schedule"] = user.has_perms( + MANAGE_BACKUP_SCHEDULE + ) context["manage_sftp"] = ( settings.LOCAL_WEB_SFTP and can_manage_sftp(user) @@ -470,6 +490,61 @@ class RequestAccountBackup(OperatorOnlyMixin, PermissionRequiredMixin, View): return redirect("panel:account", pk=pk) +class EditAccountBackupSchedule( + OperatorOnlyMixin, PermissionRequiredMixin, FormView +): + permission_required = MANAGE_BACKUP_SCHEDULE + form_class = AccountBackupScheduleForm + template_name = "hosting/account_backup_schedule.html" + + def dispatch(self, request, *args, **kwargs): + if not settings.LOCAL_ACCOUNT_BACKUPS: + raise Http404 + return super().dispatch(request, *args, **kwargs) + + @cached_property + def account(self): + return get_object_or_404(HostingAccount, pk=self.kwargs["pk"]) + + def get_initial(self): + schedule = getattr(self.account, "backup_schedule", None) + if schedule is None: + return { + "enabled": True, + "frequency": AccountBackupSchedule.Frequency.DAILY, + } + if schedule.include_mailboxes and not self.request.user.has_perm( + VIEW_MAILBOXES + ): + raise PermissionDenied + return {field: getattr(schedule, field) for field in SCHEDULE_FIELDS} + + def get_form_kwargs(self): + kwargs = super().get_form_kwargs() + kwargs["allow_mail"] = ( + settings.LOCAL_ACCOUNT_BACKUP_MAIL + and self.request.user.has_perm(VIEW_MAILBOXES) + ) + return kwargs + + def get_context_data(self, **kwargs): + return super().get_context_data(account=self.account, **kwargs) + + def form_valid(self, form): + try: + save_backup_schedule( + self.account.pk, + can_manage_mail=self.request.user.has_perm(VIEW_MAILBOXES), + schedule_fields=form.cleaned_data, + ) + except HostingAccount.DoesNotExist: + raise Http404 from None + return super().form_valid(form) + + def get_success_url(self): + return self.account.get_absolute_url() + + class SiteSFTPKeys(PermissionRequiredMixin, FormView): form_class = SFTPKeyUploadForm template_name = "hosting/sftp_keys.html" -- 2.43.0 From c14713b5ede544ce6c15319bd09fb6a00f902652 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sat, 21 Nov 2026 14:26:38 +0100 Subject: [PATCH 3/3] Document scheduled account backup operations --- docs/deployment.md | 23 +++++++++++++++++++++-- docs/development.md | 10 ++++++---- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/docs/deployment.md b/docs/deployment.md index 0b96f82..56cabdd 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -405,6 +405,21 @@ Archives are stored under `/var/lib/coulobre/account-backups/` with root-only access. Retrieve archives and manage their retention on the server. Recovery uses the existing [account bundle commands](development.md#recover-backups-from-the-bundle). +#### Schedule backups for an account + +Select **Schedule backups** on the account page. Choose a daily time or a +weekly day and time, all in UTC. To pause the schedule, clear +**Enable scheduled backups** and save. The account page shows the next +scheduled run and identifies the source of each backup in the history. +Operators also need **Can change account backup schedule** to manage schedules. + +The scheduler captures the account's current resources when it queues the +backup. If an account already has a backup queued or running at dispatch, +the scheduler skips that occurrence. After a period offline, it queues at +most one missed backup per account and continues with the next future time. +Scheduled ZIPs are stored alongside manual backups and require the same +server-side retention management. + #### Include mailboxes on the same server Complete the [Postfix and Dovecot setup](development.md#apply-a-mailbox-manifest) @@ -420,8 +435,12 @@ sudo systemctl daemon-reload Set `COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL=1` in `/etc/coulobre/panel.env` and restart `coulobre-panel` and `coulobre-backup-worker`. Operators with permission to view mailbox requests can select **Include mailboxes** when -creating an account backup. Provision all listed mailboxes before requesting -a backup with mail. For mailboxes on a separate server, use the +starting or scheduling an account backup. They can also edit an existing +schedule that includes mail. If you disable mailbox backups while such a +schedule is enabled, the subsequent jobs report a failure until you adjust +the schedule or re-enable local mailbox backups. Provision all listed +mailboxes before requesting a backup with mail. For mailboxes on a separate +server, use the [bundle workflow for separate nodes](development.md#bundle-backups-from-separate-nodes). ## Publish local DNS zones from the panel diff --git a/docs/development.md b/docs/development.md index 00bd9c0..9723eed 100644 --- a/docs/development.md +++ b/docs/development.md @@ -1030,10 +1030,12 @@ each listed database, and the requested mailbox archives. Back up DNS and panel settings separately. On a single-server installation, operators can start a backup of the website -and databases directly from the account page and view its status there. If -mail is hosted on that server too, enable the **Include mailboxes** option. -[Enable account backups in the panel](deployment.md#start-local-account-backups-from-the-panel), -[include local mailboxes](deployment.md#include-mailboxes-on-the-same-server) +and databases directly from the account page and view its status there. The +panel can also run one daily or weekly backup schedule per account. If mail +is hosted on that server too, enable the **Include mailboxes** option. +See [local account backups](deployment.md#start-local-account-backups-from-the-panel), +[backup schedules](deployment.md#schedule-backups-for-an-account), and +[local mailbox backups](deployment.md#include-mailboxes-on-the-same-server). If all resources in the manifest are on one server, run the account backup command there as root. To include mail, pass the manifest downloaded with -- 2.43.0