Manage scheduled backup retention and archive history #37
No files matched your search
@@ -16,6 +16,7 @@ COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre
|
|||||||
# COULOBRE_LOCAL_MAILBOX_PROVISIONING=1
|
# COULOBRE_LOCAL_MAILBOX_PROVISIONING=1
|
||||||
# COULOBRE_LOCAL_ACCOUNT_BACKUPS=1
|
# COULOBRE_LOCAL_ACCOUNT_BACKUPS=1
|
||||||
# COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL=1
|
# COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL=1
|
||||||
|
# COULOBRE_LOCAL_BACKUP_RETENTION=1
|
||||||
# COULOBRE_LOCAL_WEBSITE_RESTORE=1
|
# COULOBRE_LOCAL_WEBSITE_RESTORE=1
|
||||||
# COULOBRE_LOCAL_DATABASE_RESTORE=1
|
# COULOBRE_LOCAL_DATABASE_RESTORE=1
|
||||||
# COULOBRE_LOCAL_MAILBOX_RESTORE=1
|
# COULOBRE_LOCAL_MAILBOX_RESTORE=1
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
[Service]
|
||||||
|
Environment=COULOBRE_LOCAL_BACKUP_RETENTION=1
|
||||||
+42
-4
@@ -402,8 +402,10 @@ of the completed ZIP. Only one backup can be queued or running for an account
|
|||||||
at a time. The node gives each backup up to 30 minutes.
|
at a time. The node gives each backup up to 30 minutes.
|
||||||
|
|
||||||
Archives are stored under `/var/lib/coulobre/account-backups/` with root-only
|
Archives are stored under `/var/lib/coulobre/account-backups/` with root-only
|
||||||
access. Retrieve archives and manage their retention on the server. Recovery
|
access. Retrieve them on the server. The account's **Backup archives** page
|
||||||
uses the existing [account bundle commands](development.md#recover-backups-from-the-bundle).
|
shows all backup requests, archive sizes reported by the node, and expiration
|
||||||
|
status. Recover archives with the
|
||||||
|
[account bundle commands](development.md#recover-backups-from-the-bundle).
|
||||||
|
|
||||||
#### Schedule backups for an account
|
#### Schedule backups for an account
|
||||||
|
|
||||||
@@ -417,8 +419,44 @@ 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,
|
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
|
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.
|
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.
|
#### Manage retention of scheduled account backups
|
||||||
|
|
||||||
|
Automatic expiration is disabled by default. To offer it in the panel,
|
||||||
|
enable local account backups first, then install the retention drop-in.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo install -D -m 0644 deploy/systemd/coulobre-account-backup@.service.d/retention.conf \
|
||||||
|
/etc/systemd/system/coulobre-account-backup@.service.d/retention.conf
|
||||||
|
sudo systemctl daemon-reload
|
||||||
|
```
|
||||||
|
|
||||||
|
Set `COULOBRE_LOCAL_BACKUP_RETENTION=1` in `/etc/coulobre/panel.env`.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
panel_manage migrate --noinput
|
||||||
|
sudo systemctl restart coulobre-panel coulobre-worker coulobre-beat coulobre-backup-worker
|
||||||
|
```
|
||||||
|
|
||||||
|
Open **Backup archives** and select **Manage retention**. Enter a count of
|
||||||
|
1 to 90 to keep the latest successful scheduled backups or clear the field
|
||||||
|
to disable expiration for the account. Manual backups and scheduled backups
|
||||||
|
marked **Protected** are kept in addition to that count. Operators need
|
||||||
|
the usual backup permissions, permission to view mailbox requests, and
|
||||||
|
**Can manage account backup retention**.
|
||||||
|
|
||||||
|
The planner selects at most one older archive per account every five
|
||||||
|
minutes. Backups used by a queued or running restore are ineligible.
|
||||||
|
The backup node checks the retained ZIP manifests and their entry lists
|
||||||
|
before removing an older archive. If any retained ZIP is missing or fails
|
||||||
|
those checks, the candidate is kept and the result appears in the archive
|
||||||
|
history. Changing the policy or protecting an archive cancels any expiration
|
||||||
|
for the account that has yet to start. An expiration already in progress can
|
||||||
|
finish.
|
||||||
|
|
||||||
|
Expired entries stay in the history and lose their restore actions. Keep
|
||||||
|
the corresponding `.expired` records beside the ZIPs to prevent a late
|
||||||
|
worker delivery from recreating an expired archive.
|
||||||
|
|
||||||
#### Restore from local account backups in the panel
|
#### Restore from local account backups in the panel
|
||||||
|
|
||||||
|
|||||||
@@ -60,13 +60,35 @@ def backup_archive(account_id, backup_id):
|
|||||||
return BACKUP_DIRECTORY / f"account-{account_id}-{backup_id}.zip"
|
return BACKUP_DIRECTORY / f"account-{account_id}-{backup_id}.zip"
|
||||||
|
|
||||||
|
|
||||||
|
def expiration_marker(archive):
|
||||||
|
return archive.with_suffix(".expired")
|
||||||
|
|
||||||
|
|
||||||
|
def parse_backup_request(data):
|
||||||
|
if isinstance(data, dict) and data.get("operation") == "expire":
|
||||||
|
from .account_backup_retention import ArchiveExpirationRequest
|
||||||
|
|
||||||
|
return ArchiveExpirationRequest.from_manifest(data)
|
||||||
|
return AccountBackupRequest.from_manifest(data)
|
||||||
|
|
||||||
|
|
||||||
|
def apply_backup_request(request):
|
||||||
|
if isinstance(request, AccountBackupRequest):
|
||||||
|
return create_requested_backup(request)
|
||||||
|
|
||||||
|
from .account_backup_retention import expire_requested_archive
|
||||||
|
|
||||||
|
return expire_requested_archive(request)
|
||||||
|
|
||||||
|
|
||||||
def serve_backup_request():
|
def serve_backup_request():
|
||||||
return serve_apply_request(
|
return serve_apply_request(
|
||||||
REQUEST_VERSION,
|
REQUEST_VERSION,
|
||||||
AccountBackupRequest.from_manifest,
|
parse_backup_request,
|
||||||
create_requested_backup,
|
apply_backup_request,
|
||||||
limit=MAX_MANIFEST_BYTES + 4096,
|
limit=MAX_MANIFEST_BYTES + 4096,
|
||||||
identity=AccountBackupRequest.identity,
|
identity=lambda request: request.identity(),
|
||||||
|
include_result=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -79,16 +101,19 @@ def create_requested_backup(request):
|
|||||||
):
|
):
|
||||||
raise ValueError("Enable mailbox backups on the local backup node.")
|
raise ValueError("Enable mailbox backups on the local backup node.")
|
||||||
with locked_root_directory(BACKUP_DIRECTORY):
|
with locked_root_directory(BACKUP_DIRECTORY):
|
||||||
ensure_requested_archive(request)
|
archive = ensure_requested_archive(request)
|
||||||
|
return {"archive_bytes": archive.stat().st_size}
|
||||||
|
|
||||||
|
|
||||||
def ensure_requested_archive(request):
|
def ensure_requested_archive(request):
|
||||||
archive = backup_archive(
|
archive = backup_archive(
|
||||||
request.backup.website.account_id, request.backup_id
|
request.backup.website.account_id, request.backup_id
|
||||||
)
|
)
|
||||||
|
if os.path.lexists(expiration_marker(archive)):
|
||||||
|
raise ValueError("This account backup has expired.")
|
||||||
if not os.path.lexists(archive):
|
if not os.path.lexists(archive):
|
||||||
create_backup(request.backup, archive, DEFAULT_SOCKET)
|
create_backup(request.backup, archive, DEFAULT_SOCKET)
|
||||||
return
|
return archive
|
||||||
|
|
||||||
check_root_file(archive, mode=0o600)
|
check_root_file(archive, mode=0o600)
|
||||||
try:
|
try:
|
||||||
@@ -102,3 +127,4 @@ def ensure_requested_archive(request):
|
|||||||
raise ValueError(
|
raise ValueError(
|
||||||
"An archive with a different manifest already exists."
|
"An archive with a different manifest already exists."
|
||||||
)
|
)
|
||||||
|
return archive
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
import json
|
||||||
|
import os
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from uuid import UUID
|
||||||
|
from zipfile import BadZipFile
|
||||||
|
|
||||||
|
from .account_backup import open_account_bundle
|
||||||
|
from .account_backup_request import (
|
||||||
|
REQUEST_VERSION,
|
||||||
|
backup_archive,
|
||||||
|
expiration_marker,
|
||||||
|
)
|
||||||
|
from .node_files import check_root_file, locked_root_directory, write_new_file
|
||||||
|
|
||||||
|
MAX_RETAINED_BACKUPS = 90
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class ArchiveExpirationRequest:
|
||||||
|
account_id: int
|
||||||
|
backup_id: UUID
|
||||||
|
keepers: tuple[UUID, ...]
|
||||||
|
|
||||||
|
def __post_init__(self):
|
||||||
|
if (
|
||||||
|
type(self.account_id) is not int
|
||||||
|
or not 1 <= self.account_id < 2**63
|
||||||
|
):
|
||||||
|
raise ValueError("Expected a valid backup account ID.")
|
||||||
|
if (
|
||||||
|
not 1 <= len(self.keepers) <= MAX_RETAINED_BACKUPS
|
||||||
|
or len(set(self.keepers)) != len(self.keepers)
|
||||||
|
or self.backup_id in self.keepers
|
||||||
|
):
|
||||||
|
raise ValueError("Expected distinct backups to retain.")
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_manifest(cls, data):
|
||||||
|
if (
|
||||||
|
not isinstance(data, dict)
|
||||||
|
or data.keys()
|
||||||
|
!= {"version", "operation", "account_id", "backup_id", "keepers"}
|
||||||
|
or type(data["version"]) is not int
|
||||||
|
or data["version"] != REQUEST_VERSION
|
||||||
|
or data["operation"] != "expire"
|
||||||
|
or not isinstance(data["keepers"], list)
|
||||||
|
or len(data["keepers"]) > MAX_RETAINED_BACKUPS
|
||||||
|
):
|
||||||
|
raise ValueError("Expected a local archive expiration request.")
|
||||||
|
|
||||||
|
return cls(
|
||||||
|
data["account_id"],
|
||||||
|
parse_uuid(data["backup_id"]),
|
||||||
|
tuple(parse_uuid(value) for value in data["keepers"]),
|
||||||
|
)
|
||||||
|
|
||||||
|
def manifest(self):
|
||||||
|
return {
|
||||||
|
"version": REQUEST_VERSION,
|
||||||
|
"operation": "expire",
|
||||||
|
"account_id": self.account_id,
|
||||||
|
"backup_id": str(self.backup_id),
|
||||||
|
"keepers": [str(backup) for backup in self.keepers],
|
||||||
|
}
|
||||||
|
|
||||||
|
def identity(self):
|
||||||
|
return {
|
||||||
|
"version": REQUEST_VERSION,
|
||||||
|
"operation": "expire",
|
||||||
|
"account_id": self.account_id,
|
||||||
|
"backup_id": str(self.backup_id),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def parse_uuid(value):
|
||||||
|
if isinstance(value, str):
|
||||||
|
try:
|
||||||
|
identifier = UUID(value)
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
if str(identifier) == value:
|
||||||
|
return identifier
|
||||||
|
raise ValueError("Expected a canonical backup ID.")
|
||||||
|
|
||||||
|
|
||||||
|
def check_backup_identity(archive, account_id):
|
||||||
|
with open_account_bundle(archive) as (_, backup):
|
||||||
|
if backup.website.account_id != account_id:
|
||||||
|
raise ValueError("The archive belongs to a different account.")
|
||||||
|
|
||||||
|
|
||||||
|
def expire_requested_archive(request):
|
||||||
|
if os.geteuid() != 0:
|
||||||
|
raise ValueError("Run archive retention as root on the backup node.")
|
||||||
|
archive = backup_archive(request.account_id, request.backup_id)
|
||||||
|
marker = expiration_marker(archive)
|
||||||
|
with locked_root_directory(archive.parent) as directory:
|
||||||
|
marked = os.path.lexists(marker)
|
||||||
|
if marked:
|
||||||
|
check_root_file(marker, mode=0o600)
|
||||||
|
if not os.path.lexists(archive):
|
||||||
|
return {"removed": True, "reason": None}
|
||||||
|
|
||||||
|
if os.environ.get("COULOBRE_LOCAL_BACKUP_RETENTION") != "1":
|
||||||
|
return {
|
||||||
|
"removed": False,
|
||||||
|
"reason": "Enable backup retention on the backup node.",
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
for backup_id in request.keepers:
|
||||||
|
retained = backup_archive(request.account_id, backup_id)
|
||||||
|
if os.path.lexists(expiration_marker(retained)):
|
||||||
|
raise ValueError("A retained archive is being removed.")
|
||||||
|
check_backup_identity(retained, request.account_id)
|
||||||
|
if os.path.lexists(archive):
|
||||||
|
check_backup_identity(archive, request.account_id)
|
||||||
|
except (OSError, BadZipFile, ValueError) as error:
|
||||||
|
return {
|
||||||
|
"removed": False,
|
||||||
|
"reason": f"Could not verify the archives. {error}",
|
||||||
|
}
|
||||||
|
|
||||||
|
# Persist the marker before removing the immutable archive.
|
||||||
|
if not marked:
|
||||||
|
write_new_file(marker, json.dumps(request.identity()), mode=0o600)
|
||||||
|
os.fsync(directory)
|
||||||
|
archive.unlink(missing_ok=True)
|
||||||
|
os.fsync(directory)
|
||||||
|
|
||||||
|
return {"removed": True, "reason": None}
|
||||||
@@ -3,6 +3,7 @@ from uuid import uuid4
|
|||||||
from django import forms
|
from django import forms
|
||||||
from django.core.exceptions import ValidationError
|
from django.core.exceptions import ValidationError
|
||||||
|
|
||||||
|
from coulobre.account_backup_retention import MAX_RETAINED_BACKUPS
|
||||||
from coulobre.account_restore_request import (
|
from coulobre.account_restore_request import (
|
||||||
MAX_RESTORE_PATH_BYTES,
|
MAX_RESTORE_PATH_BYTES,
|
||||||
validate_restore_path,
|
validate_restore_path,
|
||||||
@@ -134,3 +135,24 @@ class ComponentRestoreForm(BackupRestoreForm):
|
|||||||
for key, target in targets.items()
|
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",
|
||||||
|
)
|
||||||
@@ -34,7 +34,7 @@ def current_restore_resources(account, kind):
|
|||||||
|
|
||||||
|
|
||||||
def available_restore_resources(backup, kind, current):
|
def available_restore_resources(backup, kind, current):
|
||||||
if backup.state != "configured" or not current:
|
if not backup.archive_is_restorable or not current:
|
||||||
return {}
|
return {}
|
||||||
archive = AccountBackup.from_manifest(backup.manifest)
|
archive = AccountBackup.from_manifest(backup.manifest)
|
||||||
if archive.website.account_id != backup.account_id:
|
if archive.website.account_id != backup.account_id:
|
||||||
@@ -51,6 +51,7 @@ def queue_website_restore(
|
|||||||
backup, *, restore_id, filename, replace, operator_username
|
backup, *, restore_id, filename, replace, operator_username
|
||||||
):
|
):
|
||||||
account = lock_hosting_account(backup.account_id, customer_id=None)
|
account = lock_hosting_account(backup.account_id, customer_id=None)
|
||||||
|
backup.refresh_from_db()
|
||||||
if not backup.can_restore_website(
|
if not backup.can_restore_website(
|
||||||
WebSite(account.pk, account.primary_domain)
|
WebSite(account.pk, account.primary_domain)
|
||||||
):
|
):
|
||||||
@@ -76,6 +77,7 @@ def queue_component_restore(
|
|||||||
backup, *, restore_id, kind, resource, operator_username
|
backup, *, restore_id, kind, resource, operator_username
|
||||||
):
|
):
|
||||||
account = lock_hosting_account(backup.account_id, customer_id=None)
|
account = lock_hosting_account(backup.account_id, customer_id=None)
|
||||||
|
backup.refresh_from_db()
|
||||||
targets = available_restore_resources(
|
targets = available_restore_resources(
|
||||||
backup, kind, current_restore_resources(account, kind)
|
backup, kind, current_restore_resources(account, kind)
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,143 @@
|
|||||||
|
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,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def plan_backup_expirations(now):
|
||||||
|
scheduled_archives = Q(
|
||||||
|
**{
|
||||||
|
f"backup_jobs__{field}": value
|
||||||
|
for field, value in SCHEDULED_ARCHIVES.items()
|
||||||
|
}
|
||||||
|
)
|
||||||
|
account_ids = (
|
||||||
|
HostingAccount.objects.filter(scheduled_backups_to_keep__isnull=False)
|
||||||
|
.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 (
|
||||||
|
not keep
|
||||||
|
or AccountBackupExpiration.objects.filter(
|
||||||
|
backup__account=account, finished_at__isnull=True
|
||||||
|
).exists()
|
||||||
|
):
|
||||||
|
return
|
||||||
|
|
||||||
|
archives = account.backup_jobs.filter(**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.")
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
# Generated by Django 5.2.19 on 2026-11-21 14:03
|
||||||
|
|
||||||
|
import django.core.validators
|
||||||
|
import django.db.models.deletion
|
||||||
|
import django.utils.timezone
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
dependencies = [
|
||||||
|
("hosting", "0027_component_restore_jobs"),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddField(
|
||||||
|
model_name="accountbackupjob",
|
||||||
|
name="archive_bytes",
|
||||||
|
field=models.PositiveBigIntegerField(blank=True, null=True),
|
||||||
|
),
|
||||||
|
migrations.AddField(
|
||||||
|
model_name="accountbackupjob",
|
||||||
|
name="expired_at",
|
||||||
|
field=models.DateTimeField(blank=True, null=True),
|
||||||
|
),
|
||||||
|
migrations.AddField(
|
||||||
|
model_name="accountbackupjob",
|
||||||
|
name="retention_protected",
|
||||||
|
field=models.BooleanField(default=False),
|
||||||
|
),
|
||||||
|
migrations.AddField(
|
||||||
|
model_name="hostingaccount",
|
||||||
|
name="scheduled_backups_to_keep",
|
||||||
|
field=models.PositiveSmallIntegerField(
|
||||||
|
blank=True,
|
||||||
|
null=True,
|
||||||
|
validators=[
|
||||||
|
django.core.validators.MinValueValidator(1),
|
||||||
|
django.core.validators.MaxValueValidator(90),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
migrations.CreateModel(
|
||||||
|
name="AccountBackupExpiration",
|
||||||
|
fields=[
|
||||||
|
(
|
||||||
|
"id",
|
||||||
|
models.BigAutoField(
|
||||||
|
auto_created=True,
|
||||||
|
primary_key=True,
|
||||||
|
serialize=False,
|
||||||
|
verbose_name="ID",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"requested_at",
|
||||||
|
models.DateTimeField(default=django.utils.timezone.now),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"last_dispatched_at",
|
||||||
|
models.DateTimeField(blank=True, null=True),
|
||||||
|
),
|
||||||
|
("started_at", models.DateTimeField(blank=True, null=True)),
|
||||||
|
("finished_at", models.DateTimeField(blank=True, null=True)),
|
||||||
|
("problem", models.TextField(blank=True)),
|
||||||
|
("keeper_ids", models.JSONField()),
|
||||||
|
(
|
||||||
|
"backup",
|
||||||
|
models.OneToOneField(
|
||||||
|
on_delete=django.db.models.deletion.CASCADE,
|
||||||
|
related_name="expiration",
|
||||||
|
to="hosting.accountbackupjob",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
options={
|
||||||
|
"permissions": [
|
||||||
|
(
|
||||||
|
"manage_backup_retention",
|
||||||
|
"Can manage account backup retention",
|
||||||
|
)
|
||||||
|
],
|
||||||
|
"indexes": [
|
||||||
|
models.Index(
|
||||||
|
fields=["finished_at", "requested_at"],
|
||||||
|
name="hosting_acc_finishe_90d6fb_idx",
|
||||||
|
)
|
||||||
|
],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
migrations.AddConstraint(
|
||||||
|
model_name="hostingaccount",
|
||||||
|
constraint=models.CheckConstraint(
|
||||||
|
condition=models.Q(
|
||||||
|
("scheduled_backups_to_keep__isnull", True),
|
||||||
|
models.Q(
|
||||||
|
("scheduled_backups_to_keep__gte", 1),
|
||||||
|
("scheduled_backups_to_keep__lte", 90),
|
||||||
|
),
|
||||||
|
_connector="OR",
|
||||||
|
),
|
||||||
|
name="hosting_account_valid_backup_retention",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -11,6 +11,7 @@ from django.urls import reverse
|
|||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
|
|
||||||
from coulobre.account_backup_request import backup_archive
|
from coulobre.account_backup_request import backup_archive
|
||||||
|
from coulobre.account_backup_retention import MAX_RETAINED_BACKUPS
|
||||||
from coulobre.account_restore_request import MAX_RESTORE_PATH_BYTES
|
from coulobre.account_restore_request import MAX_RESTORE_PATH_BYTES
|
||||||
from coulobre.database_node import (
|
from coulobre.database_node import (
|
||||||
DATABASE_SUFFIX_PATTERN,
|
DATABASE_SUFFIX_PATTERN,
|
||||||
@@ -180,8 +181,28 @@ class HostingAccount(models.Model):
|
|||||||
customer = models.ForeignKey(
|
customer = models.ForeignKey(
|
||||||
Customer, on_delete=models.PROTECT, null=True, blank=True
|
Customer, on_delete=models.PROTECT, null=True, blank=True
|
||||||
)
|
)
|
||||||
|
scheduled_backups_to_keep = models.PositiveSmallIntegerField(
|
||||||
|
null=True,
|
||||||
|
blank=True,
|
||||||
|
validators=[
|
||||||
|
MinValueValidator(1),
|
||||||
|
MaxValueValidator(MAX_RETAINED_BACKUPS),
|
||||||
|
],
|
||||||
|
)
|
||||||
created_at = models.DateTimeField(auto_now_add=True)
|
created_at = models.DateTimeField(auto_now_add=True)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
constraints = [
|
||||||
|
models.CheckConstraint(
|
||||||
|
condition=models.Q(scheduled_backups_to_keep__isnull=True)
|
||||||
|
| models.Q(
|
||||||
|
scheduled_backups_to_keep__gte=1,
|
||||||
|
scheduled_backups_to_keep__lte=MAX_RETAINED_BACKUPS,
|
||||||
|
),
|
||||||
|
name="hosting_account_valid_backup_retention",
|
||||||
|
)
|
||||||
|
]
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return str(self.primary_domain)
|
return str(self.primary_domain)
|
||||||
|
|
||||||
@@ -447,6 +468,9 @@ class AccountBackupJob(ProvisioningJob):
|
|||||||
)
|
)
|
||||||
manifest = models.JSONField()
|
manifest = models.JSONField()
|
||||||
scheduled_for = models.DateTimeField(null=True, blank=True)
|
scheduled_for = models.DateTimeField(null=True, blank=True)
|
||||||
|
archive_bytes = models.PositiveBigIntegerField(null=True, blank=True)
|
||||||
|
retention_protected = models.BooleanField(default=False)
|
||||||
|
expired_at = models.DateTimeField(null=True, blank=True)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
indexes = [models.Index(fields=("finished_at", "requested_at"))]
|
indexes = [models.Index(fields=("finished_at", "requested_at"))]
|
||||||
@@ -459,13 +483,33 @@ class AccountBackupJob(ProvisioningJob):
|
|||||||
def includes_mailboxes(self):
|
def includes_mailboxes(self):
|
||||||
return "mailboxes" in self.manifest
|
return "mailboxes" in self.manifest
|
||||||
|
|
||||||
|
@property
|
||||||
|
def archive_is_restorable(self):
|
||||||
|
if self.state != "configured" or self.expired_at is not None:
|
||||||
|
return False
|
||||||
|
expiration = getattr(self, "expiration", None)
|
||||||
|
return expiration is None or expiration.finished_at is not None
|
||||||
|
|
||||||
def can_restore_website(self, site):
|
def can_restore_website(self, site):
|
||||||
return (
|
return (
|
||||||
self.state == "configured"
|
self.archive_is_restorable
|
||||||
and self.manifest.get("website") == site.manifest()
|
and self.manifest.get("website") == site.manifest()
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class AccountBackupExpiration(ProvisioningJob):
|
||||||
|
backup = models.OneToOneField(
|
||||||
|
AccountBackupJob, on_delete=models.CASCADE, related_name="expiration"
|
||||||
|
)
|
||||||
|
keeper_ids = models.JSONField()
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
indexes = [models.Index(fields=("finished_at", "requested_at"))]
|
||||||
|
permissions = [
|
||||||
|
("manage_backup_retention", "Can manage account backup retention"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
class WebsiteRestoreJob(ProvisioningJob):
|
class WebsiteRestoreJob(ProvisioningJob):
|
||||||
backup = models.ForeignKey(
|
backup = models.ForeignKey(
|
||||||
AccountBackupJob,
|
AccountBackupJob,
|
||||||
|
|||||||
@@ -100,7 +100,7 @@ def update_local_mailbox_quota(mailbox):
|
|||||||
|
|
||||||
|
|
||||||
def create_local_account_backup(request):
|
def create_local_account_backup(request):
|
||||||
apply_on_local_node(
|
reply = apply_on_local_node(
|
||||||
request,
|
request,
|
||||||
BACKUP_SOCKET,
|
BACKUP_SOCKET,
|
||||||
"backup node",
|
"backup node",
|
||||||
@@ -109,6 +109,28 @@ def create_local_account_backup(request):
|
|||||||
timeout=BACKUP_TIMEOUT_SECONDS + 15,
|
timeout=BACKUP_TIMEOUT_SECONDS + 15,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
size = reply.get("archive_bytes")
|
||||||
|
if size is not None and (type(size) is not int or not 0 < size < 2**63):
|
||||||
|
raise ValueError("The backup node returned an invalid archive size.")
|
||||||
|
return size
|
||||||
|
|
||||||
|
|
||||||
|
def expire_local_account_backup(request):
|
||||||
|
reply = apply_on_local_node(
|
||||||
|
request,
|
||||||
|
BACKUP_SOCKET,
|
||||||
|
"backup node",
|
||||||
|
"account archive expiration",
|
||||||
|
identity=request.identity(),
|
||||||
|
timeout=BACKUP_TIMEOUT_SECONDS + 15,
|
||||||
|
)
|
||||||
|
removed, reason = reply.get("removed"), reply.get("reason")
|
||||||
|
if removed is True and reason is None:
|
||||||
|
return None
|
||||||
|
if removed is False and isinstance(reason, str) and reason.strip():
|
||||||
|
return reason.strip()[:2000]
|
||||||
|
raise ValueError("The backup node returned an invalid expiration result.")
|
||||||
|
|
||||||
|
|
||||||
def restore_local_website(request):
|
def restore_local_website(request):
|
||||||
apply_on_local_node(
|
apply_on_local_node(
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
from celery import shared_task
|
from celery import shared_task
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
@@ -10,6 +11,7 @@ from coulobre.account_backup_request import (
|
|||||||
BACKUP_TIMEOUT_SECONDS,
|
BACKUP_TIMEOUT_SECONDS,
|
||||||
AccountBackupRequest,
|
AccountBackupRequest,
|
||||||
)
|
)
|
||||||
|
from coulobre.account_backup_retention import ArchiveExpirationRequest
|
||||||
from coulobre.account_restore_request import (
|
from coulobre.account_restore_request import (
|
||||||
RESTORE_TIMEOUT_SECONDS,
|
RESTORE_TIMEOUT_SECONDS,
|
||||||
ComponentRestoreRequest,
|
ComponentRestoreRequest,
|
||||||
@@ -25,7 +27,9 @@ from .backup_restores import (
|
|||||||
current_restore_resources,
|
current_restore_resources,
|
||||||
enabled_component_restores,
|
enabled_component_restores,
|
||||||
)
|
)
|
||||||
|
from .backup_retention import plan_backup_expirations
|
||||||
from .models import (
|
from .models import (
|
||||||
|
AccountBackupExpiration,
|
||||||
AccountBackupJob,
|
AccountBackupJob,
|
||||||
ComponentRestoreJob,
|
ComponentRestoreJob,
|
||||||
DatabaseProvisioning,
|
DatabaseProvisioning,
|
||||||
@@ -43,6 +47,7 @@ from .node_client import (
|
|||||||
activate_local_site,
|
activate_local_site,
|
||||||
create_local_account_backup,
|
create_local_account_backup,
|
||||||
enable_local_https,
|
enable_local_https,
|
||||||
|
expire_local_account_backup,
|
||||||
measure_local_site_storage,
|
measure_local_site_storage,
|
||||||
provision_local_database,
|
provision_local_database,
|
||||||
provision_local_mailbox,
|
provision_local_mailbox,
|
||||||
@@ -197,6 +202,20 @@ def dispatch_account_backups():
|
|||||||
kind__in=kinds,
|
kind__in=kinds,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if settings.LOCAL_BACKUP_RETENTION:
|
||||||
|
dispatch_provisioning_jobs(
|
||||||
|
AccountBackupExpiration,
|
||||||
|
expire_account_backup,
|
||||||
|
ACCOUNT_BACKUP_QUEUE,
|
||||||
|
lease=ACCOUNT_BACKUP_LEASE,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@shared_task
|
||||||
|
def plan_account_backup_expirations():
|
||||||
|
if settings.LOCAL_ACCOUNT_BACKUPS and settings.LOCAL_BACKUP_RETENTION:
|
||||||
|
plan_backup_expirations(timezone.now())
|
||||||
|
|
||||||
|
|
||||||
def dispatch_provisioning_jobs(
|
def dispatch_provisioning_jobs(
|
||||||
model, task, queue, *, lease=REDISPATCH_AFTER, **scope
|
model, task, queue, *, lease=REDISPATCH_AFTER, **scope
|
||||||
@@ -407,7 +426,53 @@ def apply_account_backup(job):
|
|||||||
raise ValueError("The backup manifest belongs to a different account.")
|
raise ValueError("The backup manifest belongs to a different account.")
|
||||||
if backup.mailboxes is not None and not settings.LOCAL_ACCOUNT_BACKUP_MAIL:
|
if backup.mailboxes is not None and not settings.LOCAL_ACCOUNT_BACKUP_MAIL:
|
||||||
raise ValueError("Enable local mailbox backups before trying again.")
|
raise ValueError("Enable local mailbox backups before trying again.")
|
||||||
create_local_account_backup(AccountBackupRequest(job.backup_id, backup))
|
size = create_local_account_backup(
|
||||||
|
AccountBackupRequest(job.backup_id, backup)
|
||||||
|
)
|
||||||
|
return {"archive_bytes": size}
|
||||||
|
|
||||||
|
|
||||||
|
class UnconfirmedArchiveExpirationError(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
@shared_task(acks_late=True, reject_on_worker_lost=True)
|
||||||
|
def expire_account_backup(job_id):
|
||||||
|
if settings.LOCAL_ACCOUNT_BACKUPS and settings.LOCAL_BACKUP_RETENTION:
|
||||||
|
try:
|
||||||
|
run_provisioning_job(
|
||||||
|
AccountBackupExpiration.objects.select_related("backup"),
|
||||||
|
job_id,
|
||||||
|
apply_backup_expiration,
|
||||||
|
"Could not finish archive expiration.",
|
||||||
|
lease=ACCOUNT_BACKUP_LEASE,
|
||||||
|
)
|
||||||
|
except UnconfirmedArchiveExpirationError:
|
||||||
|
# The same plan is dispatched again after its lease expires.
|
||||||
|
return
|
||||||
|
|
||||||
|
|
||||||
|
def apply_backup_expiration(job):
|
||||||
|
backup = job.backup
|
||||||
|
request = ArchiveExpirationRequest(
|
||||||
|
backup.account_id,
|
||||||
|
backup.backup_id,
|
||||||
|
tuple(UUID(value) for value in job.keeper_ids),
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
reason = expire_local_account_backup(request)
|
||||||
|
except (OSError, ValueError):
|
||||||
|
AccountBackupExpiration.objects.filter(
|
||||||
|
pk=job.pk, started_at=job.started_at, finished_at__isnull=True
|
||||||
|
).update(
|
||||||
|
problem="Could not confirm expiration. The worker will retry."
|
||||||
|
)
|
||||||
|
raise UnconfirmedArchiveExpirationError from None
|
||||||
|
if reason:
|
||||||
|
raise ValueError(reason)
|
||||||
|
AccountBackupJob.objects.filter(
|
||||||
|
pk=backup.pk, expired_at__isnull=True
|
||||||
|
).update(expired_at=timezone.now())
|
||||||
|
|
||||||
|
|
||||||
@shared_task(acks_late=True, reject_on_worker_lost=True)
|
@shared_task(acks_late=True, reject_on_worker_lost=True)
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
{% if account_backup_jobs %}
|
||||||
|
<div class="table-scroll">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr><th scope="col">Requested</th><th scope="col">Source</th><th scope="col">Contents</th><th scope="col">Status</th><th scope="col">Archive</th></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for job in account_backup_jobs %}
|
||||||
|
<tr>
|
||||||
|
<td>{{ job.requested_at|date:"j M Y, H:i" }} UTC</td>
|
||||||
|
<td>
|
||||||
|
{% if job.scheduled_for %}
|
||||||
|
Scheduled <time datetime="{{ job.scheduled_for|date:"c" }}">{{ job.scheduled_for|date:"j M Y, H:i" }} UTC</time>
|
||||||
|
{% else %}
|
||||||
|
Manual
|
||||||
|
{% endif %}
|
||||||
|
</td>
|
||||||
|
<td>{% if job.includes_mailboxes %}Website, databases, and mail{% else %}Website and databases{% endif %}</td>
|
||||||
|
<td>
|
||||||
|
{% if job.expired_at %}
|
||||||
|
Expired
|
||||||
|
{% elif job.state == "configured" and not job.archive_is_restorable %}
|
||||||
|
Expiration pending
|
||||||
|
{% elif job.state == "configured" %}
|
||||||
|
Ready
|
||||||
|
{% else %}
|
||||||
|
{{ job.state|capfirst }}
|
||||||
|
{% endif %}
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
{% if job.expired_at %}
|
||||||
|
Removed {{ job.expired_at|date:"j M Y, H:i" }} UTC
|
||||||
|
{% elif job.state == "configured" %}
|
||||||
|
<code>{{ job.archive }}</code>
|
||||||
|
{% if job.archive_bytes %}<div>{{ job.archive_bytes|filesizeformat }}</div>{% endif %}
|
||||||
|
{% if job.retention_protected %}<div>Protected from retention</div>{% endif %}
|
||||||
|
{% if manage_backup_retention and job.scheduled_for %}
|
||||||
|
<div><a href="{% url 'panel:account_backup_protection' account.pk job.pk %}">Manage protection</a></div>
|
||||||
|
{% endif %}
|
||||||
|
{% if manage_backup_retention and job.expiration.problem %}
|
||||||
|
<div>{{ job.expiration.problem }}</div>
|
||||||
|
{% endif %}
|
||||||
|
{% if job.pk in website_restore_sources or job.pk in database_restore_sources or job.pk in mailbox_restore_sources %}
|
||||||
|
<div class="form-actions">
|
||||||
|
{% if job.pk in website_restore_sources %}
|
||||||
|
<a href="{% url 'panel:website_restore' account.pk job.pk %}">Restore website</a>
|
||||||
|
{% endif %}
|
||||||
|
{% if job.pk in database_restore_sources %}
|
||||||
|
<a href="{% url 'panel:database_restore' account.pk job.pk %}">Restore database</a>
|
||||||
|
{% endif %}
|
||||||
|
{% if job.pk in mailbox_restore_sources %}
|
||||||
|
<a href="{% url 'panel:mailbox_restore' account.pk job.pk %}">Restore mailbox</a>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
{% elif job.problem %}
|
||||||
|
{{ job.problem }}
|
||||||
|
{% endif %}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
{% elif not account_backup_pending_hidden %}
|
||||||
|
<p class="empty">No backups requested.</p>
|
||||||
|
{% endif %}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
{% extends "hosting/base.html" %}
|
||||||
|
{% block title %}Backup archives · Coulobre Panel{% endblock %}
|
||||||
|
{% block content %}
|
||||||
|
<a class="back-link" href="{{ account.get_absolute_url }}#backups-heading">← {{ account.name }}</a>
|
||||||
|
<header class="page-heading">
|
||||||
|
<div>
|
||||||
|
<h1>Backup archives</h1>
|
||||||
|
<p class="heading-meta">{{ account.primary_domain }}</p>
|
||||||
|
</div>
|
||||||
|
{% if manage_backup_retention %}
|
||||||
|
<div class="form-actions">
|
||||||
|
<a class="button secondary" href="{% url 'panel:account_backup_retention' account.pk %}">Manage retention</a>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</header>
|
||||||
|
<section class="surface" aria-label="Backup archive history">
|
||||||
|
{% if manage_backup_retention %}
|
||||||
|
<header class="section-heading">
|
||||||
|
{% if account.scheduled_backups_to_keep %}
|
||||||
|
<p>Keep {{ account.scheduled_backups_to_keep }} scheduled backup{{ account.scheduled_backups_to_keep|pluralize }}, plus manual and protected backups.</p>
|
||||||
|
{% else %}
|
||||||
|
<p>Automatic expiration is disabled for this account.</p>
|
||||||
|
{% endif %}
|
||||||
|
</header>
|
||||||
|
{% endif %}
|
||||||
|
{% include "hosting/account_backup_archive_table.html" %}
|
||||||
|
{% include "hosting/pagination.html" %}
|
||||||
|
</section>
|
||||||
|
{% endblock %}
|
||||||
@@ -26,67 +26,16 @@
|
|||||||
</form>
|
</form>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</header>
|
</header>
|
||||||
{% if edit_account_backup_schedule %}
|
<div class="form-actions">
|
||||||
<div class="form-actions">
|
<a class="button secondary" href="{% url 'panel:account_backup_archives' account.pk %}">Backup archives</a>
|
||||||
|
{% if edit_account_backup_schedule %}
|
||||||
<a class="button secondary" href="{% url 'panel:account_backup_schedule' account.pk %}">{% if account_backup_schedule %}Edit backup schedule{% else %}Schedule backups{% endif %}</a>
|
<a class="button secondary" href="{% url 'panel:account_backup_schedule' account.pk %}">{% if account_backup_schedule %}Edit backup schedule{% else %}Schedule backups{% endif %}</a>
|
||||||
</div>
|
{% endif %}
|
||||||
{% endif %}
|
</div>
|
||||||
{% if account_backup_pending_hidden %}
|
{% if account_backup_pending_hidden %}
|
||||||
<p class="empty">A backup is already queued or running.</p>
|
<p class="empty">A backup is already queued or running.</p>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% if account_backup_jobs %}
|
{% include "hosting/account_backup_archive_table.html" %}
|
||||||
<div class="table-scroll">
|
|
||||||
<table>
|
|
||||||
<thead>
|
|
||||||
<tr><th scope="col">Requested</th><th scope="col">Source</th><th scope="col">Contents</th><th scope="col">Status</th><th scope="col">Archive</th></tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{% for job in account_backup_jobs %}
|
|
||||||
<tr>
|
|
||||||
<td>{{ job.requested_at|date:"j M Y, H:i" }} UTC</td>
|
|
||||||
<td>
|
|
||||||
{% if job.scheduled_for %}
|
|
||||||
Scheduled <time datetime="{{ job.scheduled_for|date:"c" }}">{{ job.scheduled_for|date:"j M Y, H:i" }} UTC</time>
|
|
||||||
{% else %}
|
|
||||||
Manual
|
|
||||||
{% endif %}
|
|
||||||
</td>
|
|
||||||
<td>{% if job.includes_mailboxes %}Website, databases, and mail{% else %}Website and databases{% endif %}</td>
|
|
||||||
<td>
|
|
||||||
{% if job.state == "configured" %}
|
|
||||||
Ready
|
|
||||||
{% else %}
|
|
||||||
{{ job.state|capfirst }}
|
|
||||||
{% endif %}
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
{% if job.state == "configured" %}
|
|
||||||
<code>{{ job.archive }}</code>
|
|
||||||
{% if job.pk in website_restore_sources or job.pk in database_restore_sources or job.pk in mailbox_restore_sources %}
|
|
||||||
<div class="form-actions">
|
|
||||||
{% if job.pk in website_restore_sources %}
|
|
||||||
<a href="{% url 'panel:website_restore' account.pk job.pk %}">Restore website</a>
|
|
||||||
{% endif %}
|
|
||||||
{% if job.pk in database_restore_sources %}
|
|
||||||
<a href="{% url 'panel:database_restore' account.pk job.pk %}">Restore database</a>
|
|
||||||
{% endif %}
|
|
||||||
{% if job.pk in mailbox_restore_sources %}
|
|
||||||
<a href="{% url 'panel:mailbox_restore' account.pk job.pk %}">Restore mailbox</a>
|
|
||||||
{% endif %}
|
|
||||||
</div>
|
|
||||||
{% endif %}
|
|
||||||
{% elif job.problem %}
|
|
||||||
{{ job.problem }}
|
|
||||||
{% endif %}
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
{% endfor %}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
{% elif not account_backup_pending_hidden %}
|
|
||||||
<p class="empty">No backups requested.</p>
|
|
||||||
{% endif %}
|
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
{% if backup_restore_jobs %}
|
{% if backup_restore_jobs %}
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
{% extends "hosting/base.html" %}
|
||||||
|
{% block title %}{{ title }} · Coulobre Panel{% endblock %}
|
||||||
|
{% block content %}
|
||||||
|
<a class="back-link" href="{{ back_url }}">← Backup archives</a>
|
||||||
|
<header class="page-heading">
|
||||||
|
<div>
|
||||||
|
<h1>{{ title }}</h1>
|
||||||
|
<p class="heading-meta">{{ account.primary_domain }}{% if archive %} · Backup requested {{ archive.requested_at|date:"j M Y, H:i" }} UTC{% endif %}</p>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
<section class="surface editor-surface">
|
||||||
|
<form method="post" class="editor">
|
||||||
|
{% csrf_token %}
|
||||||
|
{{ form.as_div }}
|
||||||
|
<div class="form-actions">
|
||||||
|
<button class="button primary" type="submit">Save</button>
|
||||||
|
<a class="button secondary" href="{{ back_url }}">Cancel</a>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,384 @@
|
|||||||
|
import json
|
||||||
|
from datetime import timedelta
|
||||||
|
from pathlib import Path
|
||||||
|
from tempfile import TemporaryDirectory
|
||||||
|
from unittest.mock import patch
|
||||||
|
from uuid import uuid4
|
||||||
|
from zipfile import ZipFile
|
||||||
|
|
||||||
|
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 import (
|
||||||
|
account_backup,
|
||||||
|
account_backup_request,
|
||||||
|
account_backup_retention,
|
||||||
|
)
|
||||||
|
from coulobre.account_backup import AccountBackup
|
||||||
|
from coulobre.account_backup_request import (
|
||||||
|
AccountBackupRequest,
|
||||||
|
expiration_marker,
|
||||||
|
)
|
||||||
|
from coulobre.account_backup_retention import ArchiveExpirationRequest
|
||||||
|
from coulobre.web_node import WebSite
|
||||||
|
|
||||||
|
from .backup_retention import plan_backup_expirations
|
||||||
|
from .models import (
|
||||||
|
AccountBackupExpiration,
|
||||||
|
AccountBackupJob,
|
||||||
|
ComponentRestoreJob,
|
||||||
|
HostingAccount,
|
||||||
|
WebsiteRestoreJob,
|
||||||
|
)
|
||||||
|
from .tasks import (
|
||||||
|
ACCOUNT_BACKUP_LEASE,
|
||||||
|
ACCOUNT_BACKUP_QUEUE,
|
||||||
|
dispatch_account_backups,
|
||||||
|
expire_account_backup,
|
||||||
|
plan_account_backup_expirations,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@override_settings(
|
||||||
|
LOCAL_ACCOUNT_BACKUPS=True,
|
||||||
|
LOCAL_BACKUP_RETENTION=True,
|
||||||
|
LOCAL_WEBSITE_RESTORE=True,
|
||||||
|
)
|
||||||
|
class BackupRetentionTests(TestCase):
|
||||||
|
@classmethod
|
||||||
|
def setUpTestData(cls):
|
||||||
|
cls.operator = get_user_model().objects.create_superuser("operator")
|
||||||
|
cls.account = HostingAccount.objects.create(
|
||||||
|
name="Example",
|
||||||
|
primary_domain="example.net",
|
||||||
|
scheduled_backups_to_keep=1,
|
||||||
|
)
|
||||||
|
cls.site = WebSite(cls.account.pk, cls.account.primary_domain)
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.client.force_login(self.operator)
|
||||||
|
self.now = timezone.now()
|
||||||
|
self.history_url = reverse(
|
||||||
|
"panel:account_backup_archives", args=[self.account.pk]
|
||||||
|
)
|
||||||
|
self.policy_url = reverse(
|
||||||
|
"panel:account_backup_retention", args=[self.account.pk]
|
||||||
|
)
|
||||||
|
|
||||||
|
def backup(self, age, *, scheduled=True, **overrides):
|
||||||
|
requested = self.now - timedelta(days=age)
|
||||||
|
fields = {
|
||||||
|
"requested_at": requested,
|
||||||
|
"finished_at": requested,
|
||||||
|
"scheduled_for": requested if scheduled else None,
|
||||||
|
"manifest": AccountBackup(self.site, ()).manifest(),
|
||||||
|
}
|
||||||
|
return self.account.backup_jobs.create(**(fields | overrides))
|
||||||
|
|
||||||
|
def test_retention_preserves_manual_protected_failed_and_latest_backups(
|
||||||
|
self,
|
||||||
|
):
|
||||||
|
manual = self.backup(30, scheduled=False)
|
||||||
|
protected = self.backup(20, retention_protected=True)
|
||||||
|
older = self.backup(12)
|
||||||
|
newest = self.backup(3)
|
||||||
|
self.backup(2, problem="Backup failed")
|
||||||
|
self.backup(1, finished_at=None)
|
||||||
|
|
||||||
|
plan_account_backup_expirations()
|
||||||
|
plan_account_backup_expirations()
|
||||||
|
job = AccountBackupExpiration.objects.get()
|
||||||
|
self.assertEqual(job.backup, older)
|
||||||
|
self.assertEqual(job.keeper_ids, [str(newest.backup_id)])
|
||||||
|
self.assertContains(
|
||||||
|
self.client.get(self.history_url), "Expiration pending"
|
||||||
|
)
|
||||||
|
|
||||||
|
with (
|
||||||
|
patch.object(expire_account_backup, "apply_async") as publish,
|
||||||
|
patch("coulobre.hosting.tasks.create_account_backup.apply_async"),
|
||||||
|
):
|
||||||
|
dispatch_account_backups()
|
||||||
|
publish.assert_called_once_with(
|
||||||
|
args=[job.pk], queue=ACCOUNT_BACKUP_QUEUE, retry=False
|
||||||
|
)
|
||||||
|
with patch(
|
||||||
|
"coulobre.hosting.tasks.expire_local_account_backup",
|
||||||
|
return_value=None,
|
||||||
|
) as send:
|
||||||
|
expire_account_backup(job.pk)
|
||||||
|
expire_account_backup(job.pk)
|
||||||
|
send.assert_called_once_with(
|
||||||
|
ArchiveExpirationRequest(
|
||||||
|
self.account.pk, older.backup_id, (newest.backup_id,)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self.assertIsNotNone(
|
||||||
|
self.account.backup_jobs.get(pk=older.pk).expired_at
|
||||||
|
)
|
||||||
|
for backup in (manual, protected, newest):
|
||||||
|
backup.refresh_from_db()
|
||||||
|
self.assertIsNone(backup.expired_at)
|
||||||
|
history = self.client.get(self.history_url)
|
||||||
|
self.assertContains(history, "Protected from retention")
|
||||||
|
self.assertContains(history, "Expired")
|
||||||
|
self.assertNotContains(history, older.archive)
|
||||||
|
self.assertContains(history, manual.archive)
|
||||||
|
|
||||||
|
def test_restore_and_expiration_cannot_reserve_the_same_archive(
|
||||||
|
self,
|
||||||
|
):
|
||||||
|
website = self.backup(6)
|
||||||
|
component = self.backup(5)
|
||||||
|
candidate = self.backup(4)
|
||||||
|
self.backup(1)
|
||||||
|
WebsiteRestoreJob.objects.create(
|
||||||
|
backup=website, restore_id=uuid4(), operator_username="operator"
|
||||||
|
)
|
||||||
|
ComponentRestoreJob.objects.create(
|
||||||
|
backup=component,
|
||||||
|
restore_id=uuid4(),
|
||||||
|
operator_username="operator",
|
||||||
|
kind=ComponentRestoreJob.Kind.DATABASE,
|
||||||
|
resource="cms",
|
||||||
|
)
|
||||||
|
plan_backup_expirations(self.now)
|
||||||
|
self.assertEqual(
|
||||||
|
AccountBackupExpiration.objects.get().backup, candidate
|
||||||
|
)
|
||||||
|
url = reverse(
|
||||||
|
"panel:website_restore", args=[self.account.pk, candidate.pk]
|
||||||
|
)
|
||||||
|
self.assertEqual(self.client.get(url).status_code, 404)
|
||||||
|
|
||||||
|
def test_unconfirmed_expiration_remains_pending_and_retries_the_same_plan(
|
||||||
|
self,
|
||||||
|
):
|
||||||
|
backup = self.backup(3)
|
||||||
|
self.backup(1)
|
||||||
|
plan_backup_expirations(self.now)
|
||||||
|
job = AccountBackupExpiration.objects.get(backup=backup)
|
||||||
|
with patch(
|
||||||
|
"coulobre.hosting.tasks.expire_local_account_backup",
|
||||||
|
side_effect=[TimeoutError(), None],
|
||||||
|
) as send:
|
||||||
|
expire_account_backup(job.pk)
|
||||||
|
expire_account_backup(job.pk)
|
||||||
|
job.refresh_from_db()
|
||||||
|
self.assertIsNone(job.finished_at)
|
||||||
|
self.assertIn("worker will retry", job.problem)
|
||||||
|
self.assertFalse(
|
||||||
|
AccountBackupJob.objects.get(
|
||||||
|
pk=backup.pk
|
||||||
|
).archive_is_restorable
|
||||||
|
)
|
||||||
|
self.assertEqual(send.call_count, 1)
|
||||||
|
AccountBackupExpiration.objects.filter(pk=job.pk).update(
|
||||||
|
started_at=self.now - ACCOUNT_BACKUP_LEASE
|
||||||
|
)
|
||||||
|
expire_account_backup(job.pk)
|
||||||
|
self.assertEqual(send.call_args_list[0], send.call_args_list[1])
|
||||||
|
backup.refresh_from_db()
|
||||||
|
self.assertIsNotNone(backup.expired_at)
|
||||||
|
|
||||||
|
def test_a_blocked_expiration_leaves_the_archive_restorable(self):
|
||||||
|
backup = self.backup(3)
|
||||||
|
self.backup(1)
|
||||||
|
plan_backup_expirations(self.now)
|
||||||
|
job = AccountBackupExpiration.objects.get(backup=backup)
|
||||||
|
with patch(
|
||||||
|
"coulobre.hosting.tasks.expire_local_account_backup",
|
||||||
|
return_value="A newer archive is missing.",
|
||||||
|
):
|
||||||
|
expire_account_backup(job.pk)
|
||||||
|
job.refresh_from_db()
|
||||||
|
self.assertEqual(job.state, "failed")
|
||||||
|
self.assertTrue(
|
||||||
|
AccountBackupJob.objects.get(pk=backup.pk).archive_is_restorable
|
||||||
|
)
|
||||||
|
self.assertContains(
|
||||||
|
self.client.get(self.history_url), "A newer archive is missing."
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_protection_and_policy_changes_cancel_unstarted_expirations(self):
|
||||||
|
backup = self.backup(3)
|
||||||
|
self.backup(2)
|
||||||
|
self.backup(1)
|
||||||
|
plan_backup_expirations(self.now)
|
||||||
|
job = AccountBackupExpiration.objects.get(backup=backup)
|
||||||
|
url = reverse(
|
||||||
|
"panel:account_backup_protection",
|
||||||
|
args=[self.account.pk, backup.pk],
|
||||||
|
)
|
||||||
|
self.assertRedirects(
|
||||||
|
self.client.post(url, {"protected": "1"}), self.history_url
|
||||||
|
)
|
||||||
|
backup.refresh_from_db()
|
||||||
|
job.refresh_from_db()
|
||||||
|
self.assertTrue(backup.retention_protected)
|
||||||
|
self.assertIsNotNone(job.finished_at)
|
||||||
|
|
||||||
|
plan_backup_expirations(self.now)
|
||||||
|
pending = AccountBackupExpiration.objects.get(finished_at__isnull=True)
|
||||||
|
self.assertRedirects(
|
||||||
|
self.client.post(self.policy_url, {"count": ""}), self.history_url
|
||||||
|
)
|
||||||
|
self.account.refresh_from_db()
|
||||||
|
pending.refresh_from_db()
|
||||||
|
self.assertIsNone(self.account.scheduled_backups_to_keep)
|
||||||
|
self.assertIsNotNone(pending.finished_at)
|
||||||
|
self.assertContains(
|
||||||
|
self.client.get(self.history_url),
|
||||||
|
"Automatic expiration is disabled",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_policy_and_protection_have_a_separate_operator_permission(self):
|
||||||
|
backup = self.backup(3)
|
||||||
|
url = reverse(
|
||||||
|
"panel:account_backup_protection",
|
||||||
|
args=[self.account.pk, backup.pk],
|
||||||
|
)
|
||||||
|
user = get_user_model().objects.create_user("limited")
|
||||||
|
permissions = Permission.objects.filter(
|
||||||
|
content_type__app_label="hosting"
|
||||||
|
)
|
||||||
|
user.user_permissions.add(
|
||||||
|
*permissions.filter(
|
||||||
|
codename__in=(
|
||||||
|
"view_hostingaccount",
|
||||||
|
"view_webprovisioningplan",
|
||||||
|
"view_hostingdatabase",
|
||||||
|
"add_accountbackupjob",
|
||||||
|
"manage_backup_retention",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self.client.force_login(user)
|
||||||
|
self.assertEqual(
|
||||||
|
self.client.post(self.policy_url, {"count": 2}).status_code, 403
|
||||||
|
)
|
||||||
|
self.assertEqual(
|
||||||
|
self.client.post(url, {"protected": "1"}).status_code, 403
|
||||||
|
)
|
||||||
|
self.assertNotContains(
|
||||||
|
self.client.get(self.history_url), "Manage retention"
|
||||||
|
)
|
||||||
|
user.user_permissions.add(
|
||||||
|
permissions.get(codename="view_hostingmailbox")
|
||||||
|
)
|
||||||
|
self.assertContains(
|
||||||
|
self.client.post(self.policy_url, {"count": 0}),
|
||||||
|
"greater than or equal to 1",
|
||||||
|
)
|
||||||
|
self.assertRedirects(
|
||||||
|
self.client.post(self.policy_url, {"count": 2}), self.history_url
|
||||||
|
)
|
||||||
|
self.assertContains(
|
||||||
|
self.client.get(self.history_url), "Keep 2 scheduled backups"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_archive_history_paginates_old_archives(self):
|
||||||
|
oldest = self.backup(30)
|
||||||
|
for age in range(26):
|
||||||
|
self.backup(age, scheduled=False)
|
||||||
|
self.assertNotContains(
|
||||||
|
self.client.get(self.history_url), oldest.archive
|
||||||
|
)
|
||||||
|
self.assertContains(
|
||||||
|
self.client.get(self.history_url + "?page=2"), oldest.archive
|
||||||
|
)
|
||||||
|
|
||||||
|
@override_settings(LOCAL_BACKUP_RETENTION=False)
|
||||||
|
def test_server_opt_in_is_needed_to_manage_and_plan_retention(self):
|
||||||
|
self.backup(3)
|
||||||
|
self.backup(1)
|
||||||
|
self.assertEqual(self.client.get(self.policy_url).status_code, 404)
|
||||||
|
plan_account_backup_expirations()
|
||||||
|
self.assertFalse(AccountBackupExpiration.objects.exists())
|
||||||
|
|
||||||
|
|
||||||
|
class NodeArchiveRetentionTests(SimpleTestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.directory = Path(self.enterContext(TemporaryDirectory()))
|
||||||
|
self.enterContext(
|
||||||
|
patch.object(
|
||||||
|
account_backup_request, "BACKUP_DIRECTORY", self.directory
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self.enterContext(
|
||||||
|
patch.object(
|
||||||
|
account_backup, "private_path", side_effect=lambda path: path
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self.enterContext(patch.object(account_backup, "check_root_file"))
|
||||||
|
self.enterContext(
|
||||||
|
patch.object(account_backup_retention, "check_root_file")
|
||||||
|
)
|
||||||
|
self.enterContext(
|
||||||
|
patch.object(account_backup_request.os, "geteuid", return_value=0)
|
||||||
|
)
|
||||||
|
self.enterContext(patch("coulobre.node_files.require_root_directory"))
|
||||||
|
self.enterContext(
|
||||||
|
patch.dict("os.environ", {"COULOBRE_LOCAL_BACKUP_RETENTION": "1"})
|
||||||
|
)
|
||||||
|
self.backup = AccountBackup(WebSite(42, "example.net"), ())
|
||||||
|
self.target_id = uuid4()
|
||||||
|
self.keeper_id = uuid4()
|
||||||
|
self.target = account_backup_request.backup_archive(42, self.target_id)
|
||||||
|
self.keeper = account_backup_request.backup_archive(42, self.keeper_id)
|
||||||
|
self.request = ArchiveExpirationRequest(
|
||||||
|
42, self.target_id, (self.keeper_id,)
|
||||||
|
)
|
||||||
|
|
||||||
|
def write_archive(self, path, backup):
|
||||||
|
with ZipFile(path, "w") as bundle:
|
||||||
|
bundle.writestr("manifest.json", json.dumps(backup.manifest()))
|
||||||
|
bundle.writestr("website.tar.gz", b"fixture")
|
||||||
|
|
||||||
|
def test_missing_or_foreign_keeper_preserves_the_candidate(self):
|
||||||
|
self.write_archive(self.target, self.backup)
|
||||||
|
reply = account_backup_retention.expire_requested_archive(self.request)
|
||||||
|
self.assertFalse(reply["removed"])
|
||||||
|
self.assertTrue(self.target.exists())
|
||||||
|
self.write_archive(
|
||||||
|
self.keeper, AccountBackup(WebSite(43, "other.net"), ())
|
||||||
|
)
|
||||||
|
reply = account_backup_retention.expire_requested_archive(self.request)
|
||||||
|
self.assertFalse(reply["removed"])
|
||||||
|
self.assertIn("different account", reply["reason"])
|
||||||
|
self.assertTrue(self.target.exists())
|
||||||
|
self.assertFalse(expiration_marker(self.target).exists())
|
||||||
|
|
||||||
|
def test_expiration_is_replayable_and_creation_cannot_recreate_the_archive(
|
||||||
|
self,
|
||||||
|
):
|
||||||
|
self.write_archive(self.target, self.backup)
|
||||||
|
self.write_archive(self.keeper, self.backup)
|
||||||
|
request = account_backup_request.parse_backup_request(
|
||||||
|
self.request.manifest()
|
||||||
|
)
|
||||||
|
for _ in range(2):
|
||||||
|
reply = account_backup_request.apply_backup_request(request)
|
||||||
|
self.assertEqual(reply, {"removed": True, "reason": None})
|
||||||
|
self.assertTrue(self.keeper.exists())
|
||||||
|
self.assertFalse(self.target.exists())
|
||||||
|
self.assertTrue(expiration_marker(self.target).exists())
|
||||||
|
with self.assertRaisesMessage(ValueError, "has expired"):
|
||||||
|
account_backup_request.ensure_requested_archive(
|
||||||
|
AccountBackupRequest(self.target_id, self.backup)
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_disabled_node_cannot_expire_archives(self):
|
||||||
|
self.write_archive(self.target, self.backup)
|
||||||
|
self.write_archive(self.keeper, self.backup)
|
||||||
|
with patch.dict(
|
||||||
|
"os.environ", {"COULOBRE_LOCAL_BACKUP_RETENTION": "0"}
|
||||||
|
):
|
||||||
|
reply = account_backup_retention.expire_requested_archive(
|
||||||
|
self.request
|
||||||
|
)
|
||||||
|
self.assertFalse(reply["removed"])
|
||||||
|
self.assertTrue(self.target.exists())
|
||||||
@@ -83,7 +83,8 @@ class PanelAccountBackupTests(TestCase):
|
|||||||
self.client.post(self.request_url)
|
self.client.post(self.request_url)
|
||||||
job = AccountBackupJob.objects.get(account=self.account)
|
job = AccountBackupJob.objects.get(account=self.account)
|
||||||
with patch(
|
with patch(
|
||||||
"coulobre.hosting.tasks.create_local_account_backup"
|
"coulobre.hosting.tasks.create_local_account_backup",
|
||||||
|
return_value=2048,
|
||||||
) as node:
|
) as node:
|
||||||
create_account_backup(job.pk)
|
create_account_backup(job.pk)
|
||||||
create_account_backup(job.pk)
|
create_account_backup(job.pk)
|
||||||
@@ -95,6 +96,7 @@ class PanelAccountBackupTests(TestCase):
|
|||||||
)
|
)
|
||||||
page = self.client.get(self.account.get_absolute_url())
|
page = self.client.get(self.account.get_absolute_url())
|
||||||
self.assertContains(page, "Ready")
|
self.assertContains(page, "Ready")
|
||||||
|
self.assertContains(page, "2.0\u00a0KB")
|
||||||
self.assertContains(page, job.archive)
|
self.assertContains(page, job.archive)
|
||||||
self.client.post(self.request_url)
|
self.client.post(self.request_url)
|
||||||
self.assertEqual(self.account.backup_jobs.count(), 2)
|
self.assertEqual(self.account.backup_jobs.count(), 2)
|
||||||
@@ -109,7 +111,8 @@ class PanelAccountBackupTests(TestCase):
|
|||||||
with (
|
with (
|
||||||
patch.object(create_account_backup, "apply_async") as publish,
|
patch.object(create_account_backup, "apply_async") as publish,
|
||||||
patch(
|
patch(
|
||||||
"coulobre.hosting.tasks.create_local_account_backup"
|
"coulobre.hosting.tasks.create_local_account_backup",
|
||||||
|
return_value=2048,
|
||||||
) as node,
|
) as node,
|
||||||
):
|
):
|
||||||
dispatch_account_backups()
|
dispatch_account_backups()
|
||||||
@@ -163,7 +166,8 @@ class PanelAccountBackupTests(TestCase):
|
|||||||
job = AccountBackupJob.objects.get(account=self.account)
|
job = AccountBackupJob.objects.get(account=self.account)
|
||||||
|
|
||||||
with patch(
|
with patch(
|
||||||
"coulobre.hosting.tasks.create_local_account_backup"
|
"coulobre.hosting.tasks.create_local_account_backup",
|
||||||
|
return_value=2048,
|
||||||
) as node:
|
) as node:
|
||||||
create_account_backup(job.pk)
|
create_account_backup(job.pk)
|
||||||
|
|
||||||
@@ -242,7 +246,8 @@ class PanelAccountBackupTests(TestCase):
|
|||||||
with (
|
with (
|
||||||
self.settings(LOCAL_ACCOUNT_BACKUP_MAIL=False),
|
self.settings(LOCAL_ACCOUNT_BACKUP_MAIL=False),
|
||||||
patch(
|
patch(
|
||||||
"coulobre.hosting.tasks.create_local_account_backup"
|
"coulobre.hosting.tasks.create_local_account_backup",
|
||||||
|
return_value=2048,
|
||||||
) as node,
|
) as node,
|
||||||
):
|
):
|
||||||
create_account_backup(job.pk)
|
create_account_backup(job.pk)
|
||||||
@@ -301,7 +306,11 @@ class AccountBackupRequestTests(SimpleTestCase):
|
|||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
report,
|
report,
|
||||||
self.request.identity()
|
self.request.identity()
|
||||||
| {"state": "configured", "problem": None},
|
| {
|
||||||
|
"state": "configured",
|
||||||
|
"problem": None,
|
||||||
|
"archive_bytes": archive.stat().st_size,
|
||||||
|
},
|
||||||
)
|
)
|
||||||
self.create.assert_called_once_with(
|
self.create.assert_called_once_with(
|
||||||
self.backup, archive, DEFAULT_SOCKET
|
self.backup, archive, DEFAULT_SOCKET
|
||||||
|
|||||||
@@ -41,6 +41,21 @@ urlpatterns = [
|
|||||||
views.RequestAccountBackup.as_view(),
|
views.RequestAccountBackup.as_view(),
|
||||||
name="account_backup_create",
|
name="account_backup_create",
|
||||||
),
|
),
|
||||||
|
path(
|
||||||
|
"accounts/<int:pk>/backups/archives/",
|
||||||
|
views.AccountBackupArchiveList.as_view(),
|
||||||
|
name="account_backup_archives",
|
||||||
|
),
|
||||||
|
path(
|
||||||
|
"accounts/<int:pk>/backups/retention/",
|
||||||
|
views.EditBackupRetention.as_view(),
|
||||||
|
name="account_backup_retention",
|
||||||
|
),
|
||||||
|
path(
|
||||||
|
"accounts/<int:pk>/backups/<int:backup_pk>/protection/",
|
||||||
|
views.EditBackupProtection.as_view(),
|
||||||
|
name="account_backup_protection",
|
||||||
|
),
|
||||||
path(
|
path(
|
||||||
"accounts/<int:pk>/backups/schedule/",
|
"accounts/<int:pk>/backups/schedule/",
|
||||||
views.EditAccountBackupSchedule.as_view(),
|
views.EditAccountBackupSchedule.as_view(),
|
||||||
|
|||||||
+151
-13
@@ -43,6 +43,8 @@ from .access import (
|
|||||||
from .account_backup_forms import (
|
from .account_backup_forms import (
|
||||||
SCHEDULE_FIELDS,
|
SCHEDULE_FIELDS,
|
||||||
AccountBackupScheduleForm,
|
AccountBackupScheduleForm,
|
||||||
|
BackupProtectionForm,
|
||||||
|
BackupRetentionForm,
|
||||||
ComponentRestoreForm,
|
ComponentRestoreForm,
|
||||||
WebsiteRestoreForm,
|
WebsiteRestoreForm,
|
||||||
)
|
)
|
||||||
@@ -59,6 +61,7 @@ from .backup_restores import (
|
|||||||
queue_component_restore,
|
queue_component_restore,
|
||||||
queue_website_restore,
|
queue_website_restore,
|
||||||
)
|
)
|
||||||
|
from .backup_retention import change_backup_retention, protect_backup
|
||||||
from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record
|
from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record
|
||||||
from .dns_publication import queue_dns_publication
|
from .dns_publication import queue_dns_publication
|
||||||
from .impersonation import (
|
from .impersonation import (
|
||||||
@@ -126,6 +129,11 @@ MANAGE_BACKUP_SCHEDULE = (
|
|||||||
*MANAGE_ACCOUNT_BACKUPS,
|
*MANAGE_ACCOUNT_BACKUPS,
|
||||||
"hosting.change_accountbackupschedule",
|
"hosting.change_accountbackupschedule",
|
||||||
)
|
)
|
||||||
|
MANAGE_BACKUP_RETENTION = (
|
||||||
|
*MANAGE_ACCOUNT_BACKUPS,
|
||||||
|
VIEW_MAILBOXES,
|
||||||
|
"hosting.manage_backup_retention",
|
||||||
|
)
|
||||||
RESTORE_WEBSITE = (*MANAGE_ACCOUNT_BACKUPS, "hosting.add_websiterestorejob")
|
RESTORE_WEBSITE = (*MANAGE_ACCOUNT_BACKUPS, "hosting.add_websiterestorejob")
|
||||||
COMPONENT_RESTORE_PERMISSIONS = {
|
COMPONENT_RESTORE_PERMISSIONS = {
|
||||||
RestoreKind.DATABASE: (
|
RestoreKind.DATABASE: (
|
||||||
@@ -326,15 +334,14 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
|||||||
and not tenant
|
and not tenant
|
||||||
and user.has_perms(MANAGE_ACCOUNT_BACKUPS)
|
and user.has_perms(MANAGE_ACCOUNT_BACKUPS)
|
||||||
):
|
):
|
||||||
jobs = list(
|
|
||||||
self.object.backup_jobs.order_by("-requested_at", "-pk")[:10]
|
|
||||||
)
|
|
||||||
can_view_mailboxes = user.has_perm(VIEW_MAILBOXES)
|
can_view_mailboxes = user.has_perm(VIEW_MAILBOXES)
|
||||||
context["show_account_backups"] = True
|
context["show_account_backups"] = True
|
||||||
visible_jobs = (
|
context["manage_backup_retention"] = (
|
||||||
jobs
|
settings.LOCAL_BACKUP_RETENTION
|
||||||
if can_view_mailboxes
|
and user.has_perms(MANAGE_BACKUP_RETENTION)
|
||||||
else [job for job in jobs if not job.includes_mailboxes]
|
)
|
||||||
|
visible_jobs = list(
|
||||||
|
visible_account_backups(self.object, user)[:10]
|
||||||
)
|
)
|
||||||
context["account_backup_jobs"] = visible_jobs
|
context["account_backup_jobs"] = visible_jobs
|
||||||
context.update(
|
context.update(
|
||||||
@@ -342,12 +349,14 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
|||||||
self.object, user, visible_jobs, can_view_mailboxes
|
self.object, user, visible_jobs, can_view_mailboxes
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
pending = next(
|
pending = self.object.backup_jobs.filter(
|
||||||
(job for job in jobs if job.finished_at is None), None
|
finished_at__isnull=True
|
||||||
)
|
).first()
|
||||||
context["account_backup_pending"] = pending is not None
|
context["account_backup_pending"] = pending is not None
|
||||||
context["account_backup_pending_hidden"] = (
|
context["account_backup_pending_hidden"] = (
|
||||||
pending is not None and pending not in visible_jobs
|
pending is not None
|
||||||
|
and pending.includes_mailboxes
|
||||||
|
and not can_view_mailboxes
|
||||||
)
|
)
|
||||||
context["account_backup_allow_mail"] = (
|
context["account_backup_allow_mail"] = (
|
||||||
settings.LOCAL_ACCOUNT_BACKUP_MAIL and can_view_mailboxes
|
settings.LOCAL_ACCOUNT_BACKUP_MAIL and can_view_mailboxes
|
||||||
@@ -526,6 +535,135 @@ class RequestAccountBackup(OperatorOnlyMixin, PermissionRequiredMixin, View):
|
|||||||
return redirect("panel:account", pk=pk)
|
return redirect("panel:account", pk=pk)
|
||||||
|
|
||||||
|
|
||||||
|
def visible_account_backups(account, user):
|
||||||
|
backups = account.backup_jobs.select_related("expiration").order_by(
|
||||||
|
"-requested_at", "-pk"
|
||||||
|
)
|
||||||
|
if not user.has_perm(VIEW_MAILBOXES):
|
||||||
|
backups = backups.exclude(manifest__has_key="mailboxes")
|
||||||
|
return backups
|
||||||
|
|
||||||
|
|
||||||
|
class AccountBackupArchiveList(
|
||||||
|
OperatorOnlyMixin, PermissionRequiredMixin, ListView
|
||||||
|
):
|
||||||
|
permission_required = MANAGE_ACCOUNT_BACKUPS
|
||||||
|
template_name = "hosting/account_backup_archives.html"
|
||||||
|
context_object_name = "account_backup_jobs"
|
||||||
|
paginate_by = 25
|
||||||
|
|
||||||
|
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_queryset(self):
|
||||||
|
return visible_account_backups(self.account, self.request.user)
|
||||||
|
|
||||||
|
def get_context_data(self, **kwargs):
|
||||||
|
context = super().get_context_data(account=self.account, **kwargs)
|
||||||
|
user = self.request.user
|
||||||
|
context["manage_backup_retention"] = (
|
||||||
|
settings.LOCAL_BACKUP_RETENTION
|
||||||
|
and user.has_perms(MANAGE_BACKUP_RETENTION)
|
||||||
|
)
|
||||||
|
context.update(
|
||||||
|
backup_restore_context(
|
||||||
|
self.account,
|
||||||
|
user,
|
||||||
|
list(context["account_backup_jobs"]),
|
||||||
|
user.has_perm(VIEW_MAILBOXES),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return context
|
||||||
|
|
||||||
|
|
||||||
|
class BackupRetentionView(
|
||||||
|
OperatorOnlyMixin, PermissionRequiredMixin, FormView
|
||||||
|
):
|
||||||
|
permission_required = MANAGE_BACKUP_RETENTION
|
||||||
|
template_name = "hosting/backup_retention_form.html"
|
||||||
|
|
||||||
|
def dispatch(self, request, *args, **kwargs):
|
||||||
|
if not (
|
||||||
|
settings.LOCAL_ACCOUNT_BACKUPS and settings.LOCAL_BACKUP_RETENTION
|
||||||
|
):
|
||||||
|
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_success_url(self):
|
||||||
|
return reverse("panel:account_backup_archives", args=[self.account.pk])
|
||||||
|
|
||||||
|
def get_context_data(self, **kwargs):
|
||||||
|
return super().get_context_data(
|
||||||
|
account=self.account,
|
||||||
|
title=self.title,
|
||||||
|
back_url=self.get_success_url(),
|
||||||
|
**kwargs,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class EditBackupRetention(BackupRetentionView):
|
||||||
|
form_class = BackupRetentionForm
|
||||||
|
title = "Backup retention"
|
||||||
|
|
||||||
|
def get_initial(self):
|
||||||
|
return {"count": self.account.scheduled_backups_to_keep}
|
||||||
|
|
||||||
|
def form_valid(self, form):
|
||||||
|
try:
|
||||||
|
change_backup_retention(
|
||||||
|
self.account.pk, form.cleaned_data["count"]
|
||||||
|
)
|
||||||
|
except HostingAccount.DoesNotExist:
|
||||||
|
raise Http404 from None
|
||||||
|
return super().form_valid(form)
|
||||||
|
|
||||||
|
|
||||||
|
class EditBackupProtection(BackupRetentionView):
|
||||||
|
form_class = BackupProtectionForm
|
||||||
|
title = "Archive protection"
|
||||||
|
|
||||||
|
@cached_property
|
||||||
|
def backup(self):
|
||||||
|
backup = get_object_or_404(
|
||||||
|
self.account.backup_jobs,
|
||||||
|
pk=self.kwargs["backup_pk"],
|
||||||
|
scheduled_for__isnull=False,
|
||||||
|
)
|
||||||
|
if backup.state != "configured" or backup.expired_at is not None:
|
||||||
|
raise Http404
|
||||||
|
return backup
|
||||||
|
|
||||||
|
def get_initial(self):
|
||||||
|
return {"protected": "1" if self.backup.retention_protected else "0"}
|
||||||
|
|
||||||
|
def get_context_data(self, **kwargs):
|
||||||
|
return super().get_context_data(archive=self.backup, **kwargs)
|
||||||
|
|
||||||
|
def form_valid(self, form):
|
||||||
|
try:
|
||||||
|
protect_backup(
|
||||||
|
self.account.pk,
|
||||||
|
self.backup.pk,
|
||||||
|
protected=form.cleaned_data["protected"],
|
||||||
|
)
|
||||||
|
except (HostingAccount.DoesNotExist, AccountBackupJob.DoesNotExist):
|
||||||
|
raise Http404 from None
|
||||||
|
except ValidationError as error:
|
||||||
|
form.add_error(None, error)
|
||||||
|
return self.form_invalid(form)
|
||||||
|
return super().form_valid(form)
|
||||||
|
|
||||||
|
|
||||||
def backup_restore_context(account, user, backups, can_view_mailboxes):
|
def backup_restore_context(account, user, backups, can_view_mailboxes):
|
||||||
context = {}
|
context = {}
|
||||||
history = []
|
history = []
|
||||||
@@ -581,11 +719,11 @@ class BackupRestoreView(OperatorOnlyMixin, PermissionRequiredMixin, FormView):
|
|||||||
|
|
||||||
def get_backup(self):
|
def get_backup(self):
|
||||||
backup = get_object_or_404(
|
backup = get_object_or_404(
|
||||||
AccountBackupJob.objects.select_related("account"),
|
AccountBackupJob.objects.select_related("account", "expiration"),
|
||||||
pk=self.kwargs["backup_pk"],
|
pk=self.kwargs["backup_pk"],
|
||||||
account_id=self.kwargs["pk"],
|
account_id=self.kwargs["pk"],
|
||||||
)
|
)
|
||||||
if backup.state != "configured":
|
if not backup.archive_is_restorable:
|
||||||
raise Http404
|
raise Http404
|
||||||
if backup.includes_mailboxes and not self.request.user.has_perm(
|
if backup.includes_mailboxes and not self.request.user.has_perm(
|
||||||
VIEW_MAILBOXES
|
VIEW_MAILBOXES
|
||||||
|
|||||||
@@ -132,6 +132,10 @@ LOCAL_ACCOUNT_BACKUPS = os.environ.get("COULOBRE_LOCAL_ACCOUNT_BACKUPS") == "1"
|
|||||||
LOCAL_ACCOUNT_BACKUP_MAIL = (
|
LOCAL_ACCOUNT_BACKUP_MAIL = (
|
||||||
os.environ.get("COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL") == "1"
|
os.environ.get("COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL") == "1"
|
||||||
)
|
)
|
||||||
|
LOCAL_BACKUP_RETENTION = (
|
||||||
|
LOCAL_ACCOUNT_BACKUPS
|
||||||
|
and os.environ.get("COULOBRE_LOCAL_BACKUP_RETENTION") == "1"
|
||||||
|
)
|
||||||
LOCAL_WEBSITE_RESTORE = (
|
LOCAL_WEBSITE_RESTORE = (
|
||||||
LOCAL_ACCOUNT_BACKUPS
|
LOCAL_ACCOUNT_BACKUPS
|
||||||
and os.environ.get("COULOBRE_LOCAL_WEBSITE_RESTORE") == "1"
|
and os.environ.get("COULOBRE_LOCAL_WEBSITE_RESTORE") == "1"
|
||||||
@@ -203,3 +207,10 @@ if LOCAL_ACCOUNT_BACKUPS:
|
|||||||
"schedule": 5.0,
|
"schedule": 5.0,
|
||||||
"options": {"expires": 4.0},
|
"options": {"expires": 4.0},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if LOCAL_BACKUP_RETENTION:
|
||||||
|
CELERY_BEAT_SCHEDULE["plan-account-backup-expirations"] = {
|
||||||
|
"task": "coulobre.hosting.tasks.plan_account_backup_expirations",
|
||||||
|
"schedule": 300.0,
|
||||||
|
"options": {"expires": 295.0},
|
||||||
|
}
|
||||||
Reference in new issue
Block a user