Files
coulobre/src/coulobre/hosting/account_backup_forms.py
T
parkel ecded4f123
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Successful in 1m46s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Successful in 1m58s
Use local off-site destinations for manual backups and recovery
2026-12-03 21:14:02 +01:00

189 lines
6.1 KiB
Python

from uuid import uuid4
from django import forms
from django.core.exceptions import ValidationError
from coulobre.account_backup_retention import MAX_RETAINED_BACKUPS
from coulobre.account_restore_request import (
MAX_RESTORE_PATH_BYTES,
validate_restore_path,
)
from coulobre.database_node import DatabaseSpec
from .installation_features import panel_feature_allowed
from .models import AccountBackupSchedule
from .offsite_destinations import offsite_destinations
SCHEDULE_FIELDS = (
"enabled",
"frequency",
"weekday",
"time",
"include_mailboxes",
"offsite_destination",
)
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"]
destinations = (
offsite_destinations()
if panel_feature_allowed("OFFSITE_BACKUP_DESTINATIONS")
else {}
)
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()
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
class BackupRestoreForm(forms.Form):
restore_id = forms.UUIDField(initial=uuid4, widget=forms.HiddenInput)
class WebsiteRestoreForm(BackupRestoreForm):
scope = forms.ChoiceField(
choices=(("file", "One file"), ("website", "Entire website")),
initial="file",
widget=forms.RadioSelect,
)
filename = forms.CharField(
label="File path",
max_length=MAX_RESTORE_PATH_BYTES,
required=False,
strip=False,
help_text="Use a path relative to the document root.",
)
replace = forms.BooleanField(
label="Replace the existing file at this path", required=False
)
def __init__(self, *args, targets=None, **kwargs):
super().__init__(*args, **kwargs)
self.targets = targets or {}
if len(self.targets) > 1:
self.fields["site_key"] = forms.ChoiceField(
label="Website",
choices=[
(key, site.domain) for key, site in self.targets.items()
],
)
self.order_fields(["site_key", "scope", "filename", "replace"])
def clean_filename(self):
filename = self.cleaned_data["filename"]
if filename:
try:
validate_restore_path(filename)
except ValueError as error:
raise ValidationError(str(error)) from error
return filename
def clean(self):
cleaned = super().clean()
if len(self.targets) == 1:
cleaned["site_key"] = next(iter(self.targets))
if cleaned.get("scope") == "file" and cleaned.get("filename") == "":
self.add_error(
"filename", "Enter the path of the file to restore."
)
if cleaned.get("scope") == "website":
if cleaned.get("filename"):
self.add_error(
"filename", "Clear the path to restore the entire website."
)
if cleaned.get("replace"):
self.add_error(
"replace", "Replacement is only available for one file."
)
return cleaned
class ComponentRestoreForm(BackupRestoreForm):
resource = forms.ChoiceField(label="Restore target")
def __init__(self, *args, targets, **kwargs):
super().__init__(*args, **kwargs)
self.fields["resource"].choices = [
("", "Select a target"),
*(
(
key,
target.name
if isinstance(target, DatabaseSpec)
else target.address,
)
for key, target in targets.items()
),
]
class BackupRetentionForm(forms.Form):
count = forms.IntegerField(
label="Scheduled backups to keep",
min_value=1,
max_value=MAX_RETAINED_BACKUPS,
required=False,
help_text=(
"Leave blank to disable automatic expiration. "
"Manual and protected backups are kept separately."
),
)
class BackupProtectionForm(forms.Form):
protected = forms.TypedChoiceField(
label="Archive protection",
choices=(("1", "Protected"), ("0", "Eligible for retention")),
coerce=lambda value: value == "1",
)