Offer database and mailbox recovery alongside website restores

This commit is contained in:
parkel committed 2026-11-21 14:54:51 +01:00
1 parent e13adc0d4e
commit d1ad61b121
9 files changed
+634 -86

No files matched your search

+24 -1
View File
@@ -7,6 +7,7 @@ from coulobre.account_restore_request import (
MAX_RESTORE_PATH_BYTES, MAX_RESTORE_PATH_BYTES,
validate_restore_path, validate_restore_path,
) )
from coulobre.database_node import DatabaseSpec
from .models import AccountBackupSchedule from .models import AccountBackupSchedule
@@ -68,8 +69,11 @@ class AccountBackupScheduleForm(forms.Form):
return cleaned return cleaned
class WebsiteRestoreForm(forms.Form): class BackupRestoreForm(forms.Form):
restore_id = forms.UUIDField(initial=uuid4, widget=forms.HiddenInput) restore_id = forms.UUIDField(initial=uuid4, widget=forms.HiddenInput)
class WebsiteRestoreForm(BackupRestoreForm):
scope = forms.ChoiceField( scope = forms.ChoiceField(
choices=(("file", "One file"), ("website", "Entire website")), choices=(("file", "One file"), ("website", "Entire website")),
initial="file", initial="file",
@@ -111,3 +115,22 @@ class WebsiteRestoreForm(forms.Form):
"replace", "Replacement is only available for one file." "replace", "Replacement is only available for one file."
) )
return cleaned 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()
),
]
+1 -36
View File
@@ -1,6 +1,6 @@
from datetime import UTC, datetime, timedelta from datetime import UTC, datetime, timedelta
from django.core.exceptions import PermissionDenied, ValidationError from django.core.exceptions import PermissionDenied
from django.db import transaction from django.db import transaction
from django.utils import timezone from django.utils import timezone
@@ -11,7 +11,6 @@ from .models import (
AccountBackupSchedule, AccountBackupSchedule,
HostingAccount, HostingAccount,
HostingMailbox, HostingMailbox,
WebsiteRestoreJob,
) )
from .resource_requests import lock_hosting_account from .resource_requests import lock_hosting_account
@@ -115,37 +114,3 @@ def _queue_scheduled_backup(account_id, now):
) )
schedule.next_run_at = _next_backup_run(schedule, now) schedule.next_run_at = _next_backup_run(schedule, now)
schedule.save(update_fields=["next_run_at"]) schedule.save(update_fields=["next_run_at"])
@transaction.atomic
def queue_website_restore(
backup, *, restore_id, filename, replace, operator_username
):
account = lock_hosting_account(backup.account_id, customer_id=None)
if not backup.can_restore_website(
WebSite(account.pk, account.primary_domain)
):
raise ValidationError(
"Choose a completed backup of the current website."
)
jobs = WebsiteRestoreJob.objects
details = {
"backup_id": backup.pk,
"filename": filename,
"replace": replace,
"operator_username": operator_username,
}
job = jobs.filter(restore_id=restore_id).first()
if job is None:
if jobs.filter(
backup__account=account, finished_at__isnull=True
).exists():
raise ValidationError(
"Wait for the current website restore to finish."
)
job, _ = jobs.get_or_create(restore_id=restore_id, defaults=details)
if any(getattr(job, field) != value for field, value in details.items()):
raise ValidationError(
"Reopen the restore form to submit a new request."
)
@@ -62,8 +62,18 @@
<td> <td>
{% if job.state == "configured" %} {% if job.state == "configured" %}
<code>{{ job.archive }}</code> <code>{{ job.archive }}</code>
{% if job.pk in website_restore_sources %} {% if job.pk in website_restore_sources or job.pk in database_restore_sources or job.pk in mailbox_restore_sources %}
<div><a href="{% url 'panel:website_restore' account.pk job.pk %}">Restore website</a></div> <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 %} {% endif %}
{% elif job.problem %} {% elif job.problem %}
{{ job.problem }} {{ job.problem }}
@@ -79,6 +89,6 @@
{% endif %} {% endif %}
</section> </section>
{% if website_restore_jobs %} {% if backup_restore_jobs %}
{% include "hosting/website_restore_history.html" %} {% include "hosting/backup_restore_history.html" %}
{% endif %} {% endif %}
@@ -1,6 +1,6 @@
<section class="surface" aria-labelledby="website-restores-heading"> <section class="surface" aria-labelledby="backup-restores-heading">
<header class="section-heading"> <header class="section-heading">
<h2 id="website-restores-heading">Website restores</h2> <h2 id="backup-restores-heading">Backup restores</h2>
</header> </header>
<div class="table-scroll"> <div class="table-scroll">
<table> <table>
@@ -8,13 +8,15 @@
<tr><th scope="col">Requested</th><th scope="col">Operator</th><th scope="col">Backup requested</th><th scope="col">Restore target</th><th scope="col">Status</th></tr> <tr><th scope="col">Requested</th><th scope="col">Operator</th><th scope="col">Backup requested</th><th scope="col">Restore target</th><th scope="col">Status</th></tr>
</thead> </thead>
<tbody> <tbody>
{% for restore in website_restore_jobs %} {% for restore in backup_restore_jobs %}
<tr> <tr>
<td>{{ restore.requested_at|date:"j M Y, H:i" }} UTC</td> <td>{{ restore.requested_at|date:"j M Y, H:i" }} UTC</td>
<td>{{ restore.operator_username }}</td> <td>{{ restore.operator_username }}</td>
<td>{{ restore.backup.requested_at|date:"j M Y, H:i" }} UTC</td> <td>{{ restore.backup.requested_at|date:"j M Y, H:i" }} UTC</td>
<td> <td>
{% if restore.filename %} {% if restore.kind %}
{{ restore.get_kind_display }} <code>{{ restore.target_name }}</code>
{% elif restore.filename %}
<code>{{ restore.filename }}</code> <code>{{ restore.filename }}</code>
{% if restore.replace %}(replacement allowed){% endif %} {% if restore.replace %}(replacement allowed){% endif %}
{% else %} {% else %}
@@ -0,0 +1,26 @@
{% extends "hosting/base.html" %}
{% block title %}Restore {{ restore_kind }} · 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>Restore {{ restore_kind }}</h1>
<p class="heading-meta">{{ account.primary_domain }} · Backup requested {{ backup.requested_at|date:"j M Y, H:i" }} UTC</p>
</div>
</header>
<section class="surface editor-surface">
{% if restore_kind == "database" %}
<p>Choose an empty managed database. Keep the application disconnected until the restore completes.</p>
{% else %}
<p>Choose a newly provisioned mailbox with no Maildir. Keep delivery and client access to that mailbox paused until the restore completes.</p>
{% endif %}
<form method="post" class="editor">
{% csrf_token %}
{{ form.as_div }}
<div class="form-actions">
<button class="button primary" type="submit">Queue {{ restore_kind }} restore</button>
<a class="button secondary" href="{{ account.get_absolute_url }}#backups-heading">Cancel</a>
</div>
</form>
</section>
{% endblock %}
@@ -0,0 +1,398 @@
import json
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_restore_request,
)
from coulobre.account_backup import AccountBackup
from coulobre.account_restore_request import (
ComponentRestoreRequest,
WebsiteRestoreRequest,
)
from coulobre.database_node import DEFAULT_SOCKET, DatabaseSpec
from coulobre.mail_node import MailboxSpec
from coulobre.web_node import WebSite
from .models import (
AccountBackupJob,
ComponentRestoreJob,
HostingAccount,
HostingDatabase,
HostingMailbox,
HostingMailDomain,
)
from .tasks import (
ACCOUNT_BACKUP_QUEUE,
dispatch_account_backups,
restore_backup_component,
)
@override_settings(
LOCAL_ACCOUNT_BACKUPS=True,
LOCAL_DATABASE_RESTORE=True,
LOCAL_MAILBOX_RESTORE=True,
)
class PanelComponentRestoreTests(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"
)
cls.database = HostingDatabase.objects.create(
account=cls.account, suffix="cms"
)
HostingDatabase.objects.create(account=cls.account, suffix="newer")
domain = HostingMailDomain.objects.create(
account=cls.account, domain="mail.example.net"
)
cls.mailbox = HostingMailbox.objects.create(
mail_domain=domain, local_part="sales", quota_mib=512
)
cls.archive = AccountBackup(
WebSite(cls.account.pk, cls.account.primary_domain),
(cls.database.spec, DatabaseSpec(cls.account.pk, "removed")),
(MailboxSpec(domain.domain, cls.mailbox.local_part, 128),),
)
cls.backup = AccountBackupJob.objects.create(
account=cls.account,
manifest=cls.archive.manifest(),
finished_at=timezone.now(),
)
def setUp(self):
self.client.force_login(self.operator)
self.database_url = reverse(
"panel:database_restore", args=[self.account.pk, self.backup.pk]
)
self.mailbox_url = reverse(
"panel:mailbox_restore", args=[self.account.pk, self.backup.pk]
)
def submit(self, url, resource, restore_id=None):
return self.client.post(
url,
{"restore_id": str(restore_id or uuid4()), "resource": resource},
)
def test_choices_intersect_the_backup_and_the_current_account(self):
account = self.client.get(self.account.get_absolute_url())
self.assertContains(account, "Restore database")
self.assertContains(account, "Restore mailbox")
page = self.client.get(self.database_url)
self.assertContains(page, self.database.spec.name)
self.assertNotContains(page, "removed")
self.assertNotContains(page, "newer")
self.assertContains(
self.client.get(self.mailbox_url), self.mailbox.spec.address
)
for resource in ("removed", "newer"):
with self.subTest(resource=resource):
self.assertContains(
self.submit(self.database_url, resource),
"Select a valid choice.",
)
self.assertFalse(ComponentRestoreJob.objects.exists())
def test_dispatch_handles_both_components_and_records_the_operator(self):
restore_id = uuid4()
target = self.account.get_absolute_url()
self.assertRedirects(
self.submit(self.database_url, self.database.suffix, restore_id),
target,
)
self.assertRedirects(
self.submit(self.database_url, self.database.suffix, restore_id),
target,
)
self.assertContains(
self.submit(self.database_url, self.database.suffix),
"Wait for the current restore of this target",
)
self.assertRedirects(
self.submit(self.mailbox_url, self.mailbox.spec.address), target
)
database_job = ComponentRestoreJob.objects.get(
kind=ComponentRestoreJob.Kind.DATABASE
)
mail_job = ComponentRestoreJob.objects.get(
kind=ComponentRestoreJob.Kind.MAILBOX
)
with patch.object(restore_backup_component, "apply_async") as publish:
dispatch_account_backups()
self.assertEqual(publish.call_count, 2)
for job in (database_job, mail_job):
publish.assert_any_call(
args=[job.pk], queue=ACCOUNT_BACKUP_QUEUE, retry=False
)
with patch("coulobre.hosting.tasks.restore_local_component") as send:
restore_backup_component(database_job.pk)
restore_backup_component(mail_job.pk)
restore_backup_component(database_job.pk)
self.assertEqual(send.call_count, 2)
self.assertEqual(
send.call_args_list[0].args[0].resource, self.database.spec
)
self.assertEqual(
send.call_args_list[1].args[0].resource, self.mailbox.spec
)
self.assertRedirects(
self.submit(self.database_url, self.database.suffix, restore_id),
target,
)
self.assertEqual(ComponentRestoreJob.objects.count(), 2)
page = self.client.get(target)
self.assertContains(page, "Backup restores")
self.assertContains(page, self.database.spec.name)
self.assertContains(page, self.mailbox.spec.address)
self.assertContains(page, "operator")
self.assertContains(page, "Restored", count=2)
def test_worker_needs_the_current_target_even_after_queueing(self):
self.assertEqual(
self.submit(self.database_url, self.database.suffix).status_code,
302,
)
self.database.delete()
job = ComponentRestoreJob.objects.get()
with patch("coulobre.hosting.tasks.restore_local_component") as send:
restore_backup_component(job.pk)
send.assert_not_called()
job.refresh_from_db()
self.assertEqual(job.state, "failed")
self.assertIn("no longer available", job.problem)
def test_database_target_does_not_depend_on_a_current_website_domain(self):
HostingAccount.objects.filter(pk=self.account.pk).update(
primary_domain="changed.example.net"
)
self.assertEqual(
self.submit(self.database_url, self.database.suffix).status_code,
302,
)
@override_settings(LOCAL_MAILBOX_RESTORE=False)
def test_disabled_component_is_not_offered_or_dispatched(self):
ComponentRestoreJob.objects.create(
backup=self.backup,
restore_id=uuid4(),
kind=ComponentRestoreJob.Kind.MAILBOX,
resource=self.mailbox.spec.address,
operator_username="operator",
)
self.assertEqual(
self.submit(
self.mailbox_url, self.mailbox.spec.address
).status_code,
404,
)
self.assertNotContains(
self.client.get(self.account.get_absolute_url()), "Restore mailbox"
)
with patch.object(restore_backup_component, "apply_async") as publish:
dispatch_account_backups()
publish.assert_not_called()
def test_restore_permissions_and_source_scope_are_independent(self):
database_only = AccountBackupJob.objects.create(
account=self.account,
manifest=AccountBackup(
self.archive.website, (self.database.spec,)
).manifest(),
finished_at=timezone.now(),
)
user = get_user_model().objects.create_user("database-operator")
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",
"restore_account_database",
)
)
)
self.client.force_login(user)
self.assertEqual(self.client.get(self.database_url).status_code, 404)
self.assertEqual(self.client.get(self.mailbox_url).status_code, 403)
url = reverse(
"panel:database_restore", args=[self.account.pk, database_only.pk]
)
self.assertEqual(
self.submit(url, self.database.suffix).status_code, 302
)
user.user_permissions.add(
permissions.get(codename="view_hostingmailbox")
)
self.assertEqual(self.client.get(self.database_url).status_code, 200)
self.assertEqual(self.client.get(self.mailbox_url).status_code, 403)
other = HostingAccount.objects.create(
name="Other", primary_domain="other.net"
)
url = reverse(
"panel:database_restore", args=[other.pk, database_only.pk]
)
self.assertEqual(
self.submit(url, self.database.suffix).status_code, 404
)
class NodeComponentRestoreTests(SimpleTestCase):
def setUp(self):
self.directory = Path(self.enterContext(TemporaryDirectory()))
self.enterContext(
patch.object(
account_restore_request, "RESTORE_DIRECTORY", self.directory
)
)
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_restore_request.os, "geteuid", return_value=0)
)
self.enterContext(patch("coulobre.node_files.require_root_directory"))
self.mailbox = MailboxSpec("mail.example.net", "sales", 128)
self.database = DatabaseSpec(42, "cms")
self.backup = AccountBackup(
WebSite(42, "example.net"), (self.database,), (self.mailbox,)
)
self.backup_id = uuid4()
self.archive = account_backup_request.backup_archive(
42, self.backup_id
)
def write_archive(self, backup):
with ZipFile(self.archive, "w") as bundle:
bundle.writestr("manifest.json", json.dumps(backup.manifest()))
for _, _, filename in backup.components():
bundle.writestr(filename, filename)
def request(self, resource):
return ComponentRestoreRequest(uuid4(), self.backup_id, 42, resource)
def test_database_request_extracts_only_its_dump(self):
self.write_archive(self.backup)
request = self.request(self.database)
def check(database, socket, staged):
self.assertEqual(database, self.database)
self.assertEqual(socket, DEFAULT_SOCKET)
self.assertEqual(list(staged.parent.iterdir()), [staged])
self.assertEqual(staged.read_bytes(), b"database-cms.sql.gz")
with (
patch.dict("os.environ", {"COULOBRE_LOCAL_DATABASE_RESTORE": "1"}),
patch(
"coulobre.database_node_backup.restore_database",
side_effect=check,
) as restore,
):
account_restore_request.apply_account_restore(
account_restore_request.parse_account_restore(
request.manifest()
)
)
restore.assert_called_once()
def test_mailbox_requires_node_opt_in_and_uses_current_quota(self):
self.write_archive(self.backup)
destination = MailboxSpec(
self.mailbox.domain, self.mailbox.local_part, 512
)
request = self.request(destination)
with (
patch.dict("os.environ", {"COULOBRE_LOCAL_MAILBOX_RESTORE": "0"}),
self.assertRaisesMessage(
ValueError, "Enable local mailbox restores"
),
):
account_restore_request.apply_account_restore(request)
def check(mailbox, staged):
self.assertEqual(mailbox, destination)
self.assertEqual(
staged.read_bytes(), b"mailboxes/mail.example.net/sales.tar.gz"
)
with (
patch.dict("os.environ", {"COULOBRE_LOCAL_MAILBOX_RESTORE": "1"}),
patch(
"coulobre.mail_node_backup.restore_mailbox", side_effect=check
) as restore,
):
account_restore_request.apply_account_restore(request)
restore.assert_called_once()
def test_shared_socket_keeps_website_restore_opt_in_separate(self):
request = WebsiteRestoreRequest(
uuid4(), self.backup_id, self.backup.website, None, False
)
env = {
"COULOBRE_LOCAL_WEBSITE_RESTORE": "0",
"COULOBRE_LOCAL_DATABASE_RESTORE": "1",
"COULOBRE_LOCAL_MAILBOX_RESTORE": "1",
}
with (
patch.dict("os.environ", env),
self.assertRaisesMessage(
ValueError, "Enable local website restores"
),
):
account_restore_request.apply_account_restore(request)
def test_component_must_match_the_archive_and_account(self):
self.write_archive(self.backup)
for resource in (
DatabaseSpec(42, "unknown"),
MailboxSpec("mail.example.net", "other"),
):
with (
self.subTest(resource=resource),
self.assertRaisesMessage(ValueError, "not in this backup"),
):
account_restore_request.restore_component_from_bundle(
self.request(resource)
)
self.write_archive(
AccountBackup(WebSite(43, "another.example"), (), (self.mailbox,))
)
with self.assertRaisesMessage(ValueError, "not in this backup"):
account_restore_request.restore_component_from_bundle(
self.request(self.mailbox)
)
payload = self.request(self.database).manifest() | {"account_id": 43}
with self.assertRaisesMessage(
ValueError, "must belong to the backup account"
):
ComponentRestoreRequest.from_manifest(payload)
+3 -3
View File
@@ -102,7 +102,7 @@ class PanelWebsiteRestoreTests(TestCase):
) )
self.assertEqual(WebsiteRestoreJob.objects.count(), 1) self.assertEqual(WebsiteRestoreJob.objects.count(), 1)
page = self.client.get(self.account.get_absolute_url()) page = self.client.get(self.account.get_absolute_url())
self.assertContains(page, "Website restores") self.assertContains(page, "Backup restores")
self.assertContains(page, "Restored") self.assertContains(page, "Restored")
self.assertContains(page, "assets/site.css") self.assertContains(page, "assets/site.css")
@@ -199,7 +199,7 @@ class PanelWebsiteRestoreTests(TestCase):
self.assertEqual(self.submit().status_code, 404) self.assertEqual(self.submit().status_code, 404)
self.assertNotContains( self.assertNotContains(
self.client.get(self.account.get_absolute_url()), self.client.get(self.account.get_absolute_url()),
"Website restores", "Backup restores",
) )
operator.user_permissions.add( operator.user_permissions.add(
perms.get(codename="view_hostingmailbox") perms.get(codename="view_hostingmailbox")
@@ -207,7 +207,7 @@ class PanelWebsiteRestoreTests(TestCase):
self.assertEqual(self.client.get(self.url).status_code, 200) self.assertEqual(self.client.get(self.url).status_code, 200)
self.assertContains( self.assertContains(
self.client.get(self.account.get_absolute_url()), self.client.get(self.account.get_absolute_url()),
"Website restores", "Backup restores",
) )
def test_read_only_customer_preview_cannot_queue_a_restore(self): def test_read_only_customer_preview_cannot_queue_a_restore(self):
+11
View File
@@ -2,6 +2,7 @@ from django.contrib.auth.views import LoginView, LogoutView
from django.urls import path from django.urls import path
from . import views from . import views
from .backup_restores import RestoreKind
app_name = "panel" app_name = "panel"
@@ -50,6 +51,16 @@ urlpatterns = [
views.RequestWebsiteRestore.as_view(), views.RequestWebsiteRestore.as_view(),
name="website_restore", name="website_restore",
), ),
path(
"accounts/<int:pk>/backups/<int:backup_pk>/restore/database/",
views.RequestComponentRestore.as_view(kind=RestoreKind.DATABASE),
name="database_restore",
),
path(
"accounts/<int:pk>/backups/<int:backup_pk>/restore/mailbox/",
views.RequestComponentRestore.as_view(kind=RestoreKind.MAILBOX),
name="mailbox_restore",
),
path( path(
"accounts/<int:pk>/sftp/", "accounts/<int:pk>/sftp/",
views.SiteSFTPKeys.as_view(), views.SiteSFTPKeys.as_view(),
+151 -38
View File
@@ -1,3 +1,5 @@
from operator import attrgetter
from django.conf import settings from django.conf import settings
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.forms import UserCreationForm
@@ -41,14 +43,22 @@ from .access import (
from .account_backup_forms import ( from .account_backup_forms import (
SCHEDULE_FIELDS, SCHEDULE_FIELDS,
AccountBackupScheduleForm, AccountBackupScheduleForm,
ComponentRestoreForm,
WebsiteRestoreForm, WebsiteRestoreForm,
) )
from .account_backups import ( from .account_backups import (
account_backup_manifest, account_backup_manifest,
queue_account_backup, queue_account_backup,
queue_website_restore,
save_backup_schedule, save_backup_schedule,
) )
from .backup_restores import (
RestoreKind,
available_restore_resources,
current_restore_resources,
enabled_component_restores,
queue_component_restore,
queue_website_restore,
)
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 (
@@ -60,6 +70,7 @@ from .impersonation import (
from .models import ( from .models import (
AccountBackupJob, AccountBackupJob,
AccountBackupSchedule, AccountBackupSchedule,
ComponentRestoreJob,
Customer, Customer,
DatabaseProvisioning, DatabaseProvisioning,
HostingAccount, HostingAccount,
@@ -116,6 +127,17 @@ MANAGE_BACKUP_SCHEDULE = (
"hosting.change_accountbackupschedule", "hosting.change_accountbackupschedule",
) )
RESTORE_WEBSITE = (*MANAGE_ACCOUNT_BACKUPS, "hosting.add_websiterestorejob") RESTORE_WEBSITE = (*MANAGE_ACCOUNT_BACKUPS, "hosting.add_websiterestorejob")
COMPONENT_RESTORE_PERMISSIONS = {
RestoreKind.DATABASE: (
*MANAGE_ACCOUNT_BACKUPS,
"hosting.restore_account_database",
),
RestoreKind.MAILBOX: (
*MANAGE_ACCOUNT_BACKUPS,
VIEW_MAILBOXES,
"hosting.restore_account_mailbox",
),
}
ACTIVATE_WEB = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webactivation") ACTIVATE_WEB = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webactivation")
ENABLE_WEB_HTTPS = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webhttps") ENABLE_WEB_HTTPS = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webhttps")
PROVISION_DATABASE = ( PROVISION_DATABASE = (
@@ -315,24 +337,11 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
else [job for job in jobs if not job.includes_mailboxes] else [job for job in jobs if not job.includes_mailboxes]
) )
context["account_backup_jobs"] = visible_jobs context["account_backup_jobs"] = visible_jobs
if user.has_perm("hosting.add_websiterestorejob"): context.update(
if settings.LOCAL_WEBSITE_RESTORE: backup_restore_context(
site = WebSite(self.object.pk, self.object.primary_domain) self.object, user, visible_jobs, can_view_mailboxes
context["website_restore_sources"] = { )
job.pk )
for job in visible_jobs
if job.can_restore_website(site)
}
restores = WebsiteRestoreJob.objects.filter(
backup__account=self.object
).select_related("backup")
if not can_view_mailboxes:
restores = restores.exclude(
backup__manifest__has_key="mailboxes"
)
context["website_restore_jobs"] = restores.order_by(
"-requested_at", "-pk"
)[:10]
pending = next( pending = next(
(job for job in jobs if job.finished_at is None), None (job for job in jobs if job.finished_at is None), None
) )
@@ -517,29 +526,66 @@ class RequestAccountBackup(OperatorOnlyMixin, PermissionRequiredMixin, View):
return redirect("panel:account", pk=pk) return redirect("panel:account", pk=pk)
class RequestWebsiteRestore( def backup_restore_context(account, user, backups, can_view_mailboxes):
OperatorOnlyMixin, PermissionRequiredMixin, FormView context = {}
): history = []
permission_required = RESTORE_WEBSITE kinds = {
form_class = WebsiteRestoreForm kind
template_name = "hosting/website_restore.html" for kind, permissions in COMPONENT_RESTORE_PERMISSIONS.items()
if user.has_perms(permissions)
}
sources = WebsiteRestoreJob.objects.filter(backup__account=account)
components = ComponentRestoreJob.objects.filter(
backup__account=account, kind__in=kinds
)
if not can_view_mailboxes:
sources = sources.exclude(backup__manifest__has_key="mailboxes")
components = components.exclude(backup__manifest__has_key="mailboxes")
def dispatch(self, request, *args, **kwargs): if user.has_perms(RESTORE_WEBSITE):
if not ( history.extend(
settings.LOCAL_ACCOUNT_BACKUPS and settings.LOCAL_WEBSITE_RESTORE sources.select_related("backup").order_by("-requested_at", "-pk")[
): :10
raise Http404 ]
return super().dispatch(request, *args, **kwargs) )
if settings.LOCAL_WEBSITE_RESTORE:
site = WebSite(account.pk, account.primary_domain)
context["website_restore_sources"] = {
backup.pk
for backup in backups
if backup.can_restore_website(site)
}
if kinds:
history.extend(
components.select_related("backup").order_by(
"-requested_at", "-pk"
)[:10]
)
for kind in kinds & enabled_component_restores():
current = current_restore_resources(account, kind)
context[f"{kind}_restore_sources"] = {
backup.pk
for backup in backups
if available_restore_resources(backup, kind, current)
}
context["backup_restore_jobs"] = sorted(
history, key=attrgetter("requested_at"), reverse=True
)[:10]
return context
class BackupRestoreView(OperatorOnlyMixin, PermissionRequiredMixin, FormView):
@cached_property @cached_property
def backup(self): def backup(self):
return self.get_backup()
def get_backup(self):
backup = get_object_or_404( backup = get_object_or_404(
AccountBackupJob.objects.select_related("account"), AccountBackupJob.objects.select_related("account"),
pk=self.kwargs["backup_pk"], pk=self.kwargs["backup_pk"],
account_id=self.kwargs["pk"], account_id=self.kwargs["pk"],
) )
site = WebSite(backup.account_id, backup.account.primary_domain) if backup.state != "configured":
if not backup.can_restore_website(site):
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
@@ -554,12 +600,10 @@ class RequestWebsiteRestore(
def form_valid(self, form): def form_valid(self, form):
try: try:
queue_website_restore( self.queue_restore(
self.backup, self.backup,
restore_id=form.cleaned_data["restore_id"], form.cleaned_data,
filename=form.cleaned_data["filename"], self.request.user.get_username(),
replace=form.cleaned_data["replace"],
operator_username=self.request.user.get_username(),
) )
except HostingAccount.DoesNotExist: except HostingAccount.DoesNotExist:
raise Http404 from None raise Http404 from None
@@ -569,6 +613,75 @@ class RequestWebsiteRestore(
return redirect(self.backup.account) return redirect(self.backup.account)
class RequestWebsiteRestore(BackupRestoreView):
permission_required = RESTORE_WEBSITE
form_class = WebsiteRestoreForm
template_name = "hosting/website_restore.html"
def dispatch(self, request, *args, **kwargs):
if not (
settings.LOCAL_ACCOUNT_BACKUPS and settings.LOCAL_WEBSITE_RESTORE
):
raise Http404
return super().dispatch(request, *args, **kwargs)
def get_backup(self):
backup = super().get_backup()
site = WebSite(backup.account_id, backup.account.primary_domain)
if not backup.can_restore_website(site):
raise Http404
return backup
def queue_restore(self, backup, data, operator_username):
queue_website_restore(
backup,
restore_id=data["restore_id"],
filename=data["filename"],
replace=data["replace"],
operator_username=operator_username,
)
class RequestComponentRestore(BackupRestoreView):
kind = None
form_class = ComponentRestoreForm
template_name = "hosting/component_restore.html"
def dispatch(self, request, *args, **kwargs):
if (
not settings.LOCAL_ACCOUNT_BACKUPS
or self.kind not in enabled_component_restores()
):
raise Http404
return super().dispatch(request, *args, **kwargs)
def get_permission_required(self):
return COMPONENT_RESTORE_PERMISSIONS[self.kind]
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
targets = available_restore_resources(
self.backup,
self.kind,
current_restore_resources(self.backup.account, self.kind),
)
if not targets:
raise Http404
kwargs["targets"] = targets
return kwargs
def get_context_data(self, **kwargs):
return super().get_context_data(restore_kind=self.kind, **kwargs)
def queue_restore(self, backup, data, operator_username):
queue_component_restore(
backup,
kind=self.kind,
operator_username=operator_username,
**data,
)
class EditAccountBackupSchedule( class EditAccountBackupSchedule(
OperatorOnlyMixin, PermissionRequiredMixin, FormView OperatorOnlyMixin, PermissionRequiredMixin, FormView
): ):