Files
coulobre/src/coulobre/hosting/account_backups.py
T

149 lines
4.9 KiB
Python

from datetime import UTC, datetime, timedelta
from django.conf import settings
from django.core.exceptions import PermissionDenied, ValidationError
from django.db import transaction
from django.utils import timezone
from coulobre.account_backup import AccountBackup
from coulobre.web_node import WebSite
from .independent_websites import active_websites
from .models import (
AccountBackupSchedule,
HostingAccount,
HostingMailbox,
OffsiteBackupTransfer,
)
from .resource_requests import lock_hosting_account, require_open_account
def mail_backups_enabled():
return (
settings.LOCAL_ACCOUNT_BACKUP_MAIL
or settings.REMOTE_ACCOUNT_BACKUP_MAIL
)
def account_backup_manifest(account, *, include_mailboxes=False):
mailboxes = None
if include_mailboxes:
requests = HostingMailbox.objects.filter(
mail_domain__account=account
).select_related("mail_domain")
mailboxes = tuple(mailbox.spec for mailbox in requests)
return AccountBackup(
WebSite(account.pk, account.primary_domain),
tuple(database.spec for database in account.databases.all()),
mailboxes,
tuple(site.spec for site in active_websites(account)),
).manifest()
@transaction.atomic
def queue_account_backup(account_id, *, include_mailboxes=False):
account = lock_hosting_account(account_id, customer_id=None)
require_open_account(account)
_enqueue_backup(account, include_mailboxes=include_mailboxes)
def _enqueue_backup(
account, *, include_mailboxes, scheduled_for=None, offsite_destination=""
):
if not account.backup_jobs.filter(finished_at__isnull=True).exists():
job = account.backup_jobs.create(
manifest=account_backup_manifest(
account, include_mailboxes=include_mailboxes
),
remote_mail=include_mailboxes
and settings.REMOTE_ACCOUNT_BACKUP_MAIL,
scheduled_for=scheduled_for,
)
if scheduled_for is not None and offsite_destination:
OffsiteBackupTransfer.objects.create(
backup=job, destination=offsite_destination
)
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)
require_open_account(account)
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
destination = schedule_fields.get(
"offsite_destination", schedule.offsite_destination
)
if (
schedule_fields["enabled"]
and destination
and destination not in settings.OFFSITE_BACKUP_DESTINATIONS
):
raise ValidationError("Choose an available off-site destination.")
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 (
account.retired_at is not None
or 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,
offsite_destination=schedule.offsite_destination,
)
schedule.next_run_at = _next_backup_run(schedule, now)
schedule.save(update_fields=["next_run_at"])