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

153 lines
4.9 KiB
Python

from datetime import timedelta
from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import Count, Exists, F, OuterRef, Q
from django.utils import timezone
from .models import (
AccountBackupExpiration,
ComponentRestoreJob,
HostingAccount,
WebsiteRestoreJob,
)
from .resource_requests import lock_hosting_account
EXPIRATION_RETRY_DELAY = timedelta(hours=1)
SCHEDULED_ARCHIVES = {
"scheduled_for__isnull": False,
"finished_at__isnull": False,
"problem": "",
"retention_protected": False,
"expired_at__isnull": True,
}
OFFSITE_READY = Q(offsite_transfer__isnull=True) | Q(
offsite_transfer__verified_at__isnull=False
)
def plan_backup_expirations(now):
scheduled_archives = (
Q(backup_jobs__offsite_transfer__isnull=True)
| Q(backup_jobs__offsite_transfer__verified_at__isnull=False)
) & Q(
**{
f"backup_jobs__{field}": value
for field, value in SCHEDULED_ARCHIVES.items()
}
)
account_ids = (
HostingAccount.objects.filter(
scheduled_backups_to_keep__isnull=False, retired_at__isnull=True
)
.annotate(
retention_count=Count("backup_jobs", filter=scheduled_archives)
)
.filter(retention_count__gt=F("scheduled_backups_to_keep"))
.values_list("pk", flat=True)
)
for account_id in account_ids.iterator(chunk_size=200):
try:
plan_backup_expiration(account_id, now)
except HostingAccount.DoesNotExist:
continue
@transaction.atomic
def plan_backup_expiration(account_id, now):
account = lock_hosting_account(account_id, customer_id=None)
keep = account.scheduled_backups_to_keep
if (
account.retired_at is not None
or not keep
or AccountBackupExpiration.objects.filter(
backup__account=account, finished_at__isnull=True
).exists()
):
return
archives = account.backup_jobs.filter(OFFSITE_READY, **SCHEDULED_ARCHIVES)
retained = list(
archives.order_by("-requested_at", "-pk").values_list(
"pk", "backup_id"
)[:keep]
)
if len(retained) < keep:
return
active_website_restores = WebsiteRestoreJob.objects.filter(
backup_id=OuterRef("pk"), finished_at__isnull=True
)
active_component_restores = ComponentRestoreJob.objects.filter(
backup_id=OuterRef("pk"), finished_at__isnull=True
)
oldest = (
archives.exclude(pk__in=[pk for pk, _ in retained])
.filter(
Q(expiration__isnull=True)
| Q(expiration__finished_at__lte=now - EXPIRATION_RETRY_DELAY),
~Exists(active_website_restores),
~Exists(active_component_restores),
)
.order_by("requested_at", "pk")
.first()
)
if oldest is not None:
AccountBackupExpiration.objects.update_or_create(
backup=oldest,
defaults={
"keeper_ids": [str(backup_id) for _, backup_id in retained],
"requested_at": now,
"last_dispatched_at": None,
"started_at": None,
"finished_at": None,
"problem": "",
},
)
@transaction.atomic
def change_backup_retention(account_id, count):
account = lock_hosting_account(account_id, customer_id=None)
if account.scheduled_backups_to_keep == count:
return
account.scheduled_backups_to_keep = count
account.save(update_fields=["scheduled_backups_to_keep"])
cancel_unstarted_expiration(
account, "The account retention policy changed."
)
def cancel_unstarted_expiration(account, reason):
AccountBackupExpiration.objects.filter(
backup__account=account,
started_at__isnull=True,
finished_at__isnull=True,
).update(finished_at=timezone.now(), problem=reason)
@transaction.atomic
def protect_backup(account_id, backup_id, *, protected):
account = lock_hosting_account(account_id, customer_id=None)
backup = account.backup_jobs.get(pk=backup_id, scheduled_for__isnull=False)
if backup.state != "configured" or backup.expired_at is not None:
raise ValidationError(
"Only completed scheduled archives can be protected."
)
pending = AccountBackupExpiration.objects.filter(
backup=backup, finished_at__isnull=True
)
if pending.exists() and (
not protected
or not pending.filter(started_at__isnull=True).update(
finished_at=timezone.now(), problem="The archive was protected."
)
):
raise ValidationError(
"This archive already has an expiration in progress."
)
if backup.retention_protected != protected:
backup.retention_protected = protected
backup.save(update_fields=["retention_protected"])
cancel_unstarted_expiration(account, "Archive protection changed.")