Compare commits
4
Commits
893e9b34a7
...
92bd75c196
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
92bd75c196 | ||
|
|
d1ad61b121 | ||
|
|
e13adc0d4e | ||
|
|
337a078ffe |
No files matched your search
@@ -17,3 +17,5 @@ COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre
|
||||
# COULOBRE_LOCAL_ACCOUNT_BACKUPS=1
|
||||
# COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL=1
|
||||
# COULOBRE_LOCAL_WEBSITE_RESTORE=1
|
||||
# COULOBRE_LOCAL_DATABASE_RESTORE=1
|
||||
# COULOBRE_LOCAL_MAILBOX_RESTORE=1
|
||||
@@ -1,5 +1,5 @@
|
||||
[Unit]
|
||||
Description=Coulobre local website restore socket
|
||||
Description=Coulobre local account restore socket
|
||||
|
||||
[Socket]
|
||||
ListenStream=/run/coulobre-account-restore.sock
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
[Unit]
|
||||
Description=Coulobre local website restore request
|
||||
Description=Coulobre local account restore request
|
||||
CollectMode=inactive-or-failed
|
||||
|
||||
[Service]
|
||||
@@ -8,9 +8,8 @@ User=root
|
||||
WorkingDirectory=/opt/coulobre
|
||||
StateDirectory=coulobre/account-restores
|
||||
StateDirectoryMode=0700
|
||||
ReadWritePaths=-/srv/coulobre/web
|
||||
UMask=0077
|
||||
ExecStart=/opt/coulobre/bin/coulobre-account-backup restore-website-request
|
||||
ExecStart=/opt/coulobre/bin/coulobre-account-backup restore-request
|
||||
StandardInput=socket
|
||||
StandardOutput=socket
|
||||
StandardError=journal
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
[Unit]
|
||||
After=mariadb.service
|
||||
|
||||
[Service]
|
||||
Environment=COULOBRE_LOCAL_DATABASE_RESTORE=1
|
||||
ReadWritePaths=-/var/lib/coulobre/database-node
|
||||
@@ -0,0 +1,6 @@
|
||||
[Unit]
|
||||
After=postfix.service dovecot.service
|
||||
|
||||
[Service]
|
||||
Environment=COULOBRE_LOCAL_MAILBOX_RESTORE=1
|
||||
ReadWritePaths=-/srv/coulobre-mail
|
||||
@@ -0,0 +1,3 @@
|
||||
[Service]
|
||||
Environment=COULOBRE_LOCAL_WEBSITE_RESTORE=1
|
||||
ReadWritePaths=-/srv/coulobre/web
|
||||
+52
-23
@@ -420,11 +420,11 @@ 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.
|
||||
|
||||
#### Restore website files from the panel
|
||||
#### Restore from local account backups in the panel
|
||||
|
||||
Enable this feature when the website and account backup archive are on the
|
||||
same server. Install the restore socket and give the backup worker access to
|
||||
it.
|
||||
Enable local account backups first. Install the restore socket and give the
|
||||
backup worker access to it. The archive and the resources being restored
|
||||
must be on the same server.
|
||||
|
||||
```sh
|
||||
sudo groupadd --system coulobre-restore-requests
|
||||
@@ -432,35 +432,64 @@ sudo install -m 0644 deploy/systemd/coulobre-account-restore.socket \
|
||||
deploy/systemd/coulobre-account-restore@.service /etc/systemd/system/
|
||||
sudo install -D -m 0644 deploy/systemd/coulobre-backup-worker.service.d/restore.conf \
|
||||
/etc/systemd/system/coulobre-backup-worker.service.d/restore.conf
|
||||
sudo systemctl daemon-reload
|
||||
```
|
||||
|
||||
Set `COULOBRE_LOCAL_WEBSITE_RESTORE=1` in `/etc/coulobre/panel.env`.
|
||||
Enable the options you need in `/etc/coulobre/panel.env`.
|
||||
|
||||
| Setting | Additional restore permission |
|
||||
| --- | --- |
|
||||
| `COULOBRE_LOCAL_WEBSITE_RESTORE=1` | **Can add website restore job** |
|
||||
| `COULOBRE_LOCAL_DATABASE_RESTORE=1` | **Can restore an account database** |
|
||||
| `COULOBRE_LOCAL_MAILBOX_RESTORE=1` | **Can restore an account mailbox** |
|
||||
|
||||
Install the socket service drop-in for each enabled action. If you replace
|
||||
an existing website-only restore unit, install the website drop-in to keep
|
||||
website recovery enabled. MariaDB recovery uses the local default MariaDB
|
||||
socket. Mailbox recovery uses local Postfix and Dovecot.
|
||||
|
||||
```sh
|
||||
# Website restores
|
||||
sudo install -D -m 0644 deploy/systemd/coulobre-account-restore@.service.d/website.conf \
|
||||
/etc/systemd/system/coulobre-account-restore@.service.d/website.conf
|
||||
# Database restores
|
||||
sudo install -D -m 0644 deploy/systemd/coulobre-account-restore@.service.d/database.conf \
|
||||
/etc/systemd/system/coulobre-account-restore@.service.d/database.conf
|
||||
# Mailbox restores
|
||||
sudo install -D -m 0644 deploy/systemd/coulobre-account-restore@.service.d/mailbox.conf \
|
||||
/etc/systemd/system/coulobre-account-restore@.service.d/mailbox.conf
|
||||
```
|
||||
|
||||
```sh
|
||||
panel_manage migrate --noinput
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl restart coulobre-panel coulobre-worker coulobre-backup-worker
|
||||
```
|
||||
|
||||
Select **Restore website** on a completed backup for the current account and
|
||||
domain. Operators need the backup permissions listed above and **Can add
|
||||
website restore job**. A backup that includes mail also requires permission
|
||||
to view mailbox requests.
|
||||
Operators also need the backup permissions listed above and permission to
|
||||
view mailbox requests for any backup that includes mail. Select the restore
|
||||
action on a completed backup.
|
||||
|
||||
For one file, enter its path relative to the document root. Make sure the
|
||||
parent directory exists. Select **Replace the existing file at this path**
|
||||
only if an existing site-owned file should be overwritten. Choose **Entire
|
||||
website** to restore all website files to an empty document root. When
|
||||
replacing a file, its old and restored copies must fit within the website's
|
||||
storage quota during staging. The **Website restores** section records the
|
||||
source backup, operator, and result.
|
||||
- **Restore website** restores one file or all website files. A single file
|
||||
needs an existing parent directory. Select **Replace the existing file at
|
||||
this path** to permit overwriting. The old and restored copies must fit
|
||||
within the website quota during staging. The whole website option needs
|
||||
an empty document root.
|
||||
- **Restore database** offers databases listed in the backup that still
|
||||
belong to the account. Use the matching empty managed database and keep
|
||||
the application disconnected during recovery. If the import fails after
|
||||
creating objects, inspect the database before attempting another restore.
|
||||
- **Restore mailbox** offers mailboxes listed in the backup that still
|
||||
belong to the account. Use a newly provisioned mailbox with no Maildir.
|
||||
Keep delivery and client access paused for that mailbox during recovery,
|
||||
with Postfix and Dovecot running for local checks. The restored mailbox
|
||||
uses the destination credentials and current quota configuration.
|
||||
|
||||
Restore request records under `/var/lib/coulobre/account-restores/` prevent
|
||||
an interrupted worker from applying the same restore twice. Keep these
|
||||
records while corresponding jobs could still be delivered. If the panel
|
||||
cannot confirm a restore, check the destination before submitting another.
|
||||
Use the [account bundle commands](development.md#recover-backups-from-the-bundle)
|
||||
to recover databases, mail, or components on separate servers.
|
||||
The **Backup restores** section shows each target, source backup, operator,
|
||||
and result. Keep the request records under
|
||||
`/var/lib/coulobre/account-restores/` while corresponding jobs could still be
|
||||
delivered. If the panel cannot confirm a restore, check the destination
|
||||
before submitting another. For resources on separate servers, use the
|
||||
[account bundle commands](development.md#recover-backups-from-the-bundle).
|
||||
|
||||
#### Include mailboxes on the same server
|
||||
|
||||
|
||||
+3
-3
@@ -1073,9 +1073,9 @@ sudo /opt/coulobre/bin/coulobre-account-backup pack \
|
||||
|
||||
### Recover backups from the bundle
|
||||
|
||||
On a single-server installation, operators can restore one file or the entire
|
||||
website from a completed account backup. See
|
||||
[restoring from the panel](deployment.md#restore-website-files-from-the-panel).
|
||||
On a single-server installation, operators can restore a website file, an
|
||||
entire website, a database, or a mailbox from a completed account backup.
|
||||
See [restoring from the panel](deployment.md#restore-from-local-account-backups-in-the-panel).
|
||||
|
||||
Unpack to a new directory on a root-controlled path. The command verifies the
|
||||
ZIP contents and checks the identity and integrity of each compressed
|
||||
|
||||
@@ -126,8 +126,16 @@ def main(argv=None):
|
||||
"restore-website-request",
|
||||
help="Restore website files for the panel worker.",
|
||||
)
|
||||
commands.add_parser(
|
||||
"restore-request", help="Restore a component for the panel worker."
|
||||
)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
if args.command == "restore-request":
|
||||
from .account_restore_request import serve_account_restore
|
||||
|
||||
return serve_account_restore()
|
||||
|
||||
if args.command == "restore-website-request":
|
||||
from .account_restore_request import serve_website_restore
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import errno
|
||||
import json
|
||||
import os
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from shutil import copyfileobj
|
||||
@@ -10,6 +11,8 @@ from zipfile import BadZipFile
|
||||
|
||||
from .account_backup import CHUNK_BYTES, open_account_bundle
|
||||
from .account_backup_request import BACKUP_TIMEOUT_SECONDS, backup_archive
|
||||
from .database_node import DEFAULT_SOCKET, DatabaseSpec
|
||||
from .mail_node import MailboxSpec
|
||||
from .node_files import locked_root_directory, read_root_file, write_new_file
|
||||
from .node_requests import serve_apply_request
|
||||
from .web_node import WebSite
|
||||
@@ -85,6 +88,59 @@ class WebsiteRestoreRequest:
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ComponentRestoreRequest:
|
||||
restore_id: UUID
|
||||
backup_id: UUID
|
||||
account_id: int
|
||||
resource: DatabaseSpec | MailboxSpec
|
||||
|
||||
def __post_init__(self):
|
||||
if (
|
||||
type(self.account_id) is not int
|
||||
or not 1 <= self.account_id <= 2**63 - 1
|
||||
):
|
||||
raise ValueError("Expected a valid backup account ID.")
|
||||
if (
|
||||
isinstance(self.resource, DatabaseSpec)
|
||||
and self.resource.account_id != self.account_id
|
||||
):
|
||||
raise ValueError("The database must belong to the backup account.")
|
||||
|
||||
@classmethod
|
||||
def from_manifest(cls, data):
|
||||
if (
|
||||
not isinstance(data, dict)
|
||||
or data.keys()
|
||||
!= {"version", "restore_id", "backup_id", "account_id", "resource"}
|
||||
or type(data["version"]) is not int
|
||||
or data["version"] != REQUEST_VERSION
|
||||
or not isinstance(data["resource"], dict)
|
||||
):
|
||||
raise ValueError("Expected a local component restore request.")
|
||||
resource = data["resource"]
|
||||
spec = (
|
||||
DatabaseSpec.from_manifest(resource)
|
||||
if resource.get("kind") == "mariadb_database"
|
||||
else MailboxSpec.from_manifest(resource)
|
||||
)
|
||||
return cls(
|
||||
parse_uuid(data["restore_id"]),
|
||||
parse_uuid(data["backup_id"]),
|
||||
data["account_id"],
|
||||
spec,
|
||||
)
|
||||
|
||||
def manifest(self):
|
||||
return {
|
||||
"version": REQUEST_VERSION,
|
||||
"restore_id": str(self.restore_id),
|
||||
"backup_id": str(self.backup_id),
|
||||
"account_id": self.account_id,
|
||||
"resource": self.resource.manifest(),
|
||||
}
|
||||
|
||||
|
||||
def parse_uuid(value):
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
@@ -106,11 +162,53 @@ def serve_website_restore():
|
||||
)
|
||||
|
||||
|
||||
def serve_account_restore():
|
||||
return serve_apply_request(
|
||||
REQUEST_VERSION,
|
||||
parse_account_restore,
|
||||
apply_account_restore,
|
||||
limit=16 * 1024,
|
||||
)
|
||||
|
||||
|
||||
def parse_account_restore(data):
|
||||
if isinstance(data, dict) and "resource" in data:
|
||||
return ComponentRestoreRequest.from_manifest(data)
|
||||
return WebsiteRestoreRequest.from_manifest(data)
|
||||
|
||||
|
||||
def apply_account_restore(request):
|
||||
if isinstance(request, WebsiteRestoreRequest):
|
||||
if os.environ.get("COULOBRE_LOCAL_WEBSITE_RESTORE") != "1":
|
||||
raise ValueError(
|
||||
"Enable local website restores on the backup node."
|
||||
)
|
||||
restore_requested_website(request)
|
||||
else:
|
||||
restore_requested_component(request)
|
||||
|
||||
|
||||
def restore_requested_website(request):
|
||||
if os.geteuid() != 0:
|
||||
apply_restore_once(request, restore_website_from_bundle)
|
||||
|
||||
|
||||
def restore_requested_component(request):
|
||||
if isinstance(request.resource, DatabaseSpec):
|
||||
setting = "COULOBRE_LOCAL_DATABASE_RESTORE"
|
||||
feature = "database"
|
||||
else:
|
||||
setting = "COULOBRE_LOCAL_MAILBOX_RESTORE"
|
||||
feature = "mailbox"
|
||||
if os.environ.get(setting) != "1":
|
||||
raise ValueError(
|
||||
"Run restore-website-request as root on the backup node."
|
||||
f"Enable local {feature} restores on the backup node."
|
||||
)
|
||||
apply_restore_once(request, restore_component_from_bundle)
|
||||
|
||||
|
||||
def apply_restore_once(request, restore):
|
||||
if os.geteuid() != 0:
|
||||
raise ValueError("Run the account restore as root on the backup node.")
|
||||
with locked_root_directory(RESTORE_DIRECTORY) as directory:
|
||||
claim = RESTORE_DIRECTORY / f"{request.restore_id}.json"
|
||||
result = claim.with_suffix(".result")
|
||||
@@ -129,11 +227,11 @@ def restore_requested_website(request):
|
||||
) from None
|
||||
problem = json.loads(read_root_file(result, mode=0o600))
|
||||
else:
|
||||
# Persist the claim before writing website files.
|
||||
# Persist the claim before modifying the destination.
|
||||
os.fsync(directory)
|
||||
problem = None
|
||||
try:
|
||||
restore_website_from_bundle(request)
|
||||
restore(request)
|
||||
except (OSError, ValueError) as error:
|
||||
problem = str(error)
|
||||
write_new_file(result, json.dumps(problem), mode=0o600)
|
||||
@@ -145,27 +243,53 @@ def restore_requested_website(request):
|
||||
def restore_website_from_bundle(request):
|
||||
from .web_node_backup import restore_native_website
|
||||
|
||||
archive = backup_archive(request.site.account_id, request.backup_id)
|
||||
with stage_backup_component(
|
||||
request.site.account_id,
|
||||
request.backup_id,
|
||||
request.site,
|
||||
"This backup is for a different website.",
|
||||
) as staged:
|
||||
restore_native_website(
|
||||
request.site,
|
||||
staged,
|
||||
filename=request.filename,
|
||||
replace=request.replace,
|
||||
)
|
||||
|
||||
|
||||
def restore_component_from_bundle(request):
|
||||
from .database_node_backup import restore_database
|
||||
from .mail_node_backup import restore_mailbox
|
||||
|
||||
resource = request.resource
|
||||
with stage_backup_component(
|
||||
request.account_id,
|
||||
request.backup_id,
|
||||
resource,
|
||||
"The requested database or mailbox is not in this backup.",
|
||||
) as staged:
|
||||
if isinstance(resource, DatabaseSpec):
|
||||
restore_database(resource, DEFAULT_SOCKET, staged)
|
||||
else:
|
||||
restore_mailbox(resource, staged)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def stage_backup_component(account_id, backup_id, resource, missing):
|
||||
archive = backup_archive(account_id, backup_id)
|
||||
try:
|
||||
with (
|
||||
open_account_bundle(archive) as (bundle, backup),
|
||||
TemporaryDirectory(dir=RESTORE_DIRECTORY) as temporary,
|
||||
):
|
||||
if backup.website != request.site:
|
||||
raise ValueError("This backup is for a different website.")
|
||||
staged = Path(temporary) / "website.tar.gz"
|
||||
with (
|
||||
bundle.open(staged.name) as source,
|
||||
staged.open("xb") as target,
|
||||
):
|
||||
filename = component_filename(backup, resource)
|
||||
if backup.website.account_id != account_id or filename is None:
|
||||
raise ValueError(missing)
|
||||
staged = Path(temporary) / Path(filename).name
|
||||
with bundle.open(filename) as source, staged.open("xb") as target:
|
||||
os.fchmod(target.fileno(), 0o600)
|
||||
copyfileobj(source, target, length=CHUNK_BYTES)
|
||||
restore_native_website(
|
||||
request.site,
|
||||
staged,
|
||||
filename=request.filename,
|
||||
replace=request.replace,
|
||||
)
|
||||
yield staged
|
||||
except FileNotFoundError as error:
|
||||
if error.filename == str(archive):
|
||||
raise ValueError(
|
||||
@@ -182,3 +306,15 @@ def restore_website_from_bundle(request):
|
||||
raise ValueError(
|
||||
"The selected account backup ZIP is unreadable."
|
||||
) from None
|
||||
|
||||
|
||||
def component_filename(backup, resource):
|
||||
for candidate, _, filename in backup.components():
|
||||
if isinstance(candidate, MailboxSpec) and isinstance(
|
||||
resource, MailboxSpec
|
||||
):
|
||||
if candidate.address == resource.address:
|
||||
return filename
|
||||
elif candidate == resource:
|
||||
return filename
|
||||
return None
|
||||
@@ -7,6 +7,7 @@ from coulobre.account_restore_request import (
|
||||
MAX_RESTORE_PATH_BYTES,
|
||||
validate_restore_path,
|
||||
)
|
||||
from coulobre.database_node import DatabaseSpec
|
||||
|
||||
from .models import AccountBackupSchedule
|
||||
|
||||
@@ -68,8 +69,11 @@ class AccountBackupScheduleForm(forms.Form):
|
||||
return cleaned
|
||||
|
||||
|
||||
class WebsiteRestoreForm(forms.Form):
|
||||
class BackupRestoreForm(forms.Form):
|
||||
restore_id = forms.UUIDField(initial=uuid4, widget=forms.HiddenInput)
|
||||
|
||||
|
||||
class WebsiteRestoreForm(BackupRestoreForm):
|
||||
scope = forms.ChoiceField(
|
||||
choices=(("file", "One file"), ("website", "Entire website")),
|
||||
initial="file",
|
||||
@@ -111,3 +115,22 @@ class WebsiteRestoreForm(forms.Form):
|
||||
"replace", "Replacement is only available for one file."
|
||||
)
|
||||
return cleaned
|
||||
|
||||
|
||||
class ComponentRestoreForm(BackupRestoreForm):
|
||||
resource = forms.ChoiceField(label="Restore target")
|
||||
|
||||
def __init__(self, *args, targets, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields["resource"].choices = [
|
||||
("", "Select a target"),
|
||||
*(
|
||||
(
|
||||
key,
|
||||
target.name
|
||||
if isinstance(target, DatabaseSpec)
|
||||
else target.address,
|
||||
)
|
||||
for key, target in targets.items()
|
||||
),
|
||||
]
|
||||
@@ -1,6 +1,6 @@
|
||||
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.utils import timezone
|
||||
|
||||
@@ -11,7 +11,6 @@ from .models import (
|
||||
AccountBackupSchedule,
|
||||
HostingAccount,
|
||||
HostingMailbox,
|
||||
WebsiteRestoreJob,
|
||||
)
|
||||
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.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."
|
||||
)
|
||||
@@ -0,0 +1,117 @@
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db import transaction
|
||||
|
||||
from coulobre.account_backup import AccountBackup
|
||||
from coulobre.web_node import WebSite
|
||||
|
||||
from .models import ComponentRestoreJob, HostingMailbox, WebsiteRestoreJob
|
||||
from .resource_requests import lock_hosting_account
|
||||
|
||||
RestoreKind = ComponentRestoreJob.Kind
|
||||
|
||||
|
||||
def enabled_component_restores():
|
||||
return {
|
||||
kind
|
||||
for kind, enabled in (
|
||||
(RestoreKind.DATABASE, settings.LOCAL_DATABASE_RESTORE),
|
||||
(RestoreKind.MAILBOX, settings.LOCAL_MAILBOX_RESTORE),
|
||||
)
|
||||
if enabled
|
||||
}
|
||||
|
||||
|
||||
def current_restore_resources(account, kind):
|
||||
if kind == RestoreKind.DATABASE:
|
||||
return {db.suffix: db.spec for db in account.databases.all()}
|
||||
|
||||
mailboxes = HostingMailbox.objects.filter(
|
||||
mail_domain__account=account
|
||||
).select_related("mail_domain")
|
||||
resources = (mailbox.spec for mailbox in mailboxes)
|
||||
return {mailbox.address: mailbox for mailbox in resources}
|
||||
|
||||
|
||||
def available_restore_resources(backup, kind, current):
|
||||
if backup.state != "configured" or not current:
|
||||
return {}
|
||||
archive = AccountBackup.from_manifest(backup.manifest)
|
||||
if archive.website.account_id != backup.account_id:
|
||||
return {}
|
||||
if kind == RestoreKind.DATABASE:
|
||||
keys = {database.suffix for database in archive.databases}
|
||||
else:
|
||||
keys = {mailbox.address for mailbox in archive.mailboxes or ()}
|
||||
return {key: spec for key, spec in current.items() if key in keys}
|
||||
|
||||
|
||||
@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."
|
||||
)
|
||||
|
||||
_queue_restore(
|
||||
WebsiteRestoreJob.objects,
|
||||
backup,
|
||||
restore_id,
|
||||
operator_username,
|
||||
{"filename": filename, "replace": replace},
|
||||
WebsiteRestoreJob.objects.filter(
|
||||
backup__account=account, finished_at__isnull=True
|
||||
),
|
||||
"Wait for the current website restore to finish.",
|
||||
)
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
def queue_component_restore(
|
||||
backup, *, restore_id, kind, resource, operator_username
|
||||
):
|
||||
account = lock_hosting_account(backup.account_id, customer_id=None)
|
||||
targets = available_restore_resources(
|
||||
backup, kind, current_restore_resources(account, kind)
|
||||
)
|
||||
if resource not in targets:
|
||||
raise ValidationError("This restore target is no longer available.")
|
||||
|
||||
_queue_restore(
|
||||
ComponentRestoreJob.objects,
|
||||
backup,
|
||||
restore_id,
|
||||
operator_username,
|
||||
{"kind": kind, "resource": resource},
|
||||
ComponentRestoreJob.objects.filter(
|
||||
backup__account=account,
|
||||
kind=kind,
|
||||
resource=resource,
|
||||
finished_at__isnull=True,
|
||||
),
|
||||
"Wait for the current restore of this target to finish.",
|
||||
)
|
||||
|
||||
|
||||
def _queue_restore(
|
||||
jobs, backup, restore_id, operator_username, target, pending, busy
|
||||
):
|
||||
details = {
|
||||
"backup_id": backup.pk,
|
||||
"operator_username": operator_username,
|
||||
**target,
|
||||
}
|
||||
job = jobs.filter(restore_id=restore_id).first()
|
||||
if job is None:
|
||||
if pending.exists():
|
||||
raise ValidationError(busy)
|
||||
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."
|
||||
)
|
||||
@@ -0,0 +1,78 @@
|
||||
# Generated by Django 5.2.19 on 2026-11-21 13:50
|
||||
|
||||
import django.db.models.deletion
|
||||
import django.utils.timezone
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("hosting", "0026_website_restore_jobs"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name="ComponentRestoreJob",
|
||||
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)),
|
||||
("restore_id", models.UUIDField(editable=False, unique=True)),
|
||||
(
|
||||
"kind",
|
||||
models.CharField(
|
||||
choices=[
|
||||
("database", "Database"),
|
||||
("mailbox", "Mailbox"),
|
||||
],
|
||||
max_length=8,
|
||||
),
|
||||
),
|
||||
("resource", models.CharField(max_length=254)),
|
||||
("operator_username", models.CharField(max_length=150)),
|
||||
(
|
||||
"backup",
|
||||
models.ForeignKey(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
related_name="component_restores",
|
||||
to="hosting.accountbackupjob",
|
||||
),
|
||||
),
|
||||
],
|
||||
options={
|
||||
"permissions": [
|
||||
(
|
||||
"restore_account_database",
|
||||
"Can restore an account database",
|
||||
),
|
||||
(
|
||||
"restore_account_mailbox",
|
||||
"Can restore an account mailbox",
|
||||
),
|
||||
],
|
||||
"indexes": [
|
||||
models.Index(
|
||||
fields=["finished_at", "requested_at"],
|
||||
name="hosting_com_finishe_521d95_idx",
|
||||
)
|
||||
],
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -481,6 +481,35 @@ class WebsiteRestoreJob(ProvisioningJob):
|
||||
indexes = [models.Index(fields=("finished_at", "requested_at"))]
|
||||
|
||||
|
||||
class ComponentRestoreJob(ProvisioningJob):
|
||||
class Kind(models.TextChoices):
|
||||
DATABASE = "database", "Database"
|
||||
MAILBOX = "mailbox", "Mailbox"
|
||||
|
||||
backup = models.ForeignKey(
|
||||
AccountBackupJob,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="component_restores",
|
||||
)
|
||||
restore_id = models.UUIDField(unique=True, editable=False)
|
||||
kind = models.CharField(max_length=8, choices=Kind)
|
||||
resource = models.CharField(max_length=254)
|
||||
operator_username = models.CharField(max_length=150)
|
||||
|
||||
class Meta:
|
||||
indexes = [models.Index(fields=("finished_at", "requested_at"))]
|
||||
permissions = [
|
||||
("restore_account_database", "Can restore an account database"),
|
||||
("restore_account_mailbox", "Can restore an account mailbox"),
|
||||
]
|
||||
|
||||
@property
|
||||
def target_name(self):
|
||||
if self.kind == self.Kind.DATABASE:
|
||||
return DatabaseSpec(self.backup.account_id, self.resource).name
|
||||
return self.resource
|
||||
|
||||
|
||||
class AccountBackupSchedule(models.Model):
|
||||
class Frequency(models.TextChoices):
|
||||
DAILY = "daily", "Daily"
|
||||
|
||||
@@ -120,6 +120,16 @@ def restore_local_website(request):
|
||||
)
|
||||
|
||||
|
||||
def restore_local_component(request):
|
||||
apply_on_local_node(
|
||||
request,
|
||||
RESTORE_SOCKET,
|
||||
"backup node",
|
||||
"component restore",
|
||||
timeout=RESTORE_TIMEOUT_SECONDS + 15,
|
||||
)
|
||||
|
||||
|
||||
def encode_manifest(manifest):
|
||||
return json.dumps(manifest).encode("utf-8")
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ from coulobre.account_backup_request import (
|
||||
)
|
||||
from coulobre.account_restore_request import (
|
||||
RESTORE_TIMEOUT_SECONDS,
|
||||
ComponentRestoreRequest,
|
||||
WebsiteRestoreRequest,
|
||||
)
|
||||
from coulobre.dns_node import DnsZone
|
||||
@@ -19,8 +20,14 @@ from coulobre.sftp_keys import SFTPKeys
|
||||
from coulobre.web_node import WebSite
|
||||
|
||||
from .account_backups import queue_due_account_backups
|
||||
from .backup_restores import (
|
||||
available_restore_resources,
|
||||
current_restore_resources,
|
||||
enabled_component_restores,
|
||||
)
|
||||
from .models import (
|
||||
AccountBackupJob,
|
||||
ComponentRestoreJob,
|
||||
DatabaseProvisioning,
|
||||
DnsPublication,
|
||||
MailboxProvisioning,
|
||||
@@ -40,6 +47,7 @@ from .node_client import (
|
||||
provision_local_database,
|
||||
provision_local_mailbox,
|
||||
publish_local_zone,
|
||||
restore_local_component,
|
||||
restore_local_website,
|
||||
set_local_site_storage_limit,
|
||||
update_local_mailbox_quota,
|
||||
@@ -49,8 +57,12 @@ from .sftp import site_is_active
|
||||
|
||||
REDISPATCH_AFTER = timedelta(minutes=5)
|
||||
ACCOUNT_BACKUP_LEASE = timedelta(seconds=BACKUP_TIMEOUT_SECONDS + 60)
|
||||
WEBSITE_RESTORE_LEASE = timedelta(seconds=RESTORE_TIMEOUT_SECONDS + 60)
|
||||
ACCOUNT_RESTORE_LEASE = timedelta(seconds=RESTORE_TIMEOUT_SECONDS + 60)
|
||||
ACCOUNT_BACKUP_QUEUE = "coulobre-account-backups"
|
||||
UNCONFIRMED_RESTORE = (
|
||||
"Could not confirm the restore on the local backup node. "
|
||||
"Check the destination before requesting another restore."
|
||||
)
|
||||
WEB_ACTIVATION_QUEUE = "coulobre-web-activation"
|
||||
WEB_HTTPS_QUEUE = "coulobre-web-https"
|
||||
WEB_SFTP_QUEUE = "coulobre-web-sftp"
|
||||
@@ -172,14 +184,26 @@ def dispatch_account_backups():
|
||||
WebsiteRestoreJob,
|
||||
restore_website,
|
||||
ACCOUNT_BACKUP_QUEUE,
|
||||
lease=WEBSITE_RESTORE_LEASE,
|
||||
lease=ACCOUNT_RESTORE_LEASE,
|
||||
)
|
||||
|
||||
kinds = enabled_component_restores()
|
||||
if kinds:
|
||||
dispatch_provisioning_jobs(
|
||||
ComponentRestoreJob,
|
||||
restore_backup_component,
|
||||
ACCOUNT_BACKUP_QUEUE,
|
||||
lease=ACCOUNT_RESTORE_LEASE,
|
||||
kind__in=kinds,
|
||||
)
|
||||
|
||||
|
||||
def dispatch_provisioning_jobs(model, task, queue, *, lease=REDISPATCH_AFTER):
|
||||
def dispatch_provisioning_jobs(
|
||||
model, task, queue, *, lease=REDISPATCH_AFTER, **scope
|
||||
):
|
||||
now = timezone.now()
|
||||
stale_before = now - REDISPATCH_AFTER
|
||||
waiting = model.objects.filter(finished_at__isnull=True)
|
||||
waiting = model.objects.filter(finished_at__isnull=True, **scope)
|
||||
pending = (
|
||||
waiting.filter(
|
||||
Q(last_dispatched_at__isnull=True)
|
||||
@@ -393,9 +417,8 @@ def restore_website(job_id):
|
||||
WebsiteRestoreJob.objects.select_related("backup__account"),
|
||||
job_id,
|
||||
apply_website_restore,
|
||||
"Could not confirm the restore on the local backup node. "
|
||||
"Check the destination before requesting another restore.",
|
||||
lease=WEBSITE_RESTORE_LEASE,
|
||||
UNCONFIRMED_RESTORE,
|
||||
lease=ACCOUNT_RESTORE_LEASE,
|
||||
)
|
||||
|
||||
|
||||
@@ -415,6 +438,38 @@ def apply_website_restore(job):
|
||||
)
|
||||
|
||||
|
||||
@shared_task(acks_late=True, reject_on_worker_lost=True)
|
||||
def restore_backup_component(job_id):
|
||||
kinds = enabled_component_restores()
|
||||
if settings.LOCAL_ACCOUNT_BACKUPS and kinds:
|
||||
run_provisioning_job(
|
||||
ComponentRestoreJob.objects.filter(kind__in=kinds).select_related(
|
||||
"backup__account"
|
||||
),
|
||||
job_id,
|
||||
apply_component_restore,
|
||||
UNCONFIRMED_RESTORE,
|
||||
lease=ACCOUNT_RESTORE_LEASE,
|
||||
)
|
||||
|
||||
|
||||
def apply_component_restore(job):
|
||||
backup = job.backup
|
||||
resources = available_restore_resources(
|
||||
backup, job.kind, current_restore_resources(backup.account, job.kind)
|
||||
)
|
||||
target = resources.get(job.resource)
|
||||
if target is None:
|
||||
raise ValueError(
|
||||
"The backup or its restore target is no longer available."
|
||||
)
|
||||
restore_local_component(
|
||||
ComponentRestoreRequest(
|
||||
job.restore_id, backup.backup_id, backup.account_id, target
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def run_provisioning_job(
|
||||
jobs, job_id, apply, connection_problem, *, lease=REDISPATCH_AFTER
|
||||
):
|
||||
|
||||
@@ -62,8 +62,18 @@
|
||||
<td>
|
||||
{% if job.state == "configured" %}
|
||||
<code>{{ job.archive }}</code>
|
||||
{% if job.pk in website_restore_sources %}
|
||||
<div><a href="{% url 'panel:website_restore' account.pk job.pk %}">Restore website</a></div>
|
||||
{% 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 }}
|
||||
@@ -79,6 +89,6 @@
|
||||
{% endif %}
|
||||
</section>
|
||||
|
||||
{% if website_restore_jobs %}
|
||||
{% include "hosting/website_restore_history.html" %}
|
||||
{% if backup_restore_jobs %}
|
||||
{% include "hosting/backup_restore_history.html" %}
|
||||
{% endif %}
|
||||
+6
-4
@@ -1,6 +1,6 @@
|
||||
<section class="surface" aria-labelledby="website-restores-heading">
|
||||
<section class="surface" aria-labelledby="backup-restores-heading">
|
||||
<header class="section-heading">
|
||||
<h2 id="website-restores-heading">Website restores</h2>
|
||||
<h2 id="backup-restores-heading">Backup restores</h2>
|
||||
</header>
|
||||
<div class="table-scroll">
|
||||
<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>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for restore in website_restore_jobs %}
|
||||
{% for restore in backup_restore_jobs %}
|
||||
<tr>
|
||||
<td>{{ restore.requested_at|date:"j M Y, H:i" }} UTC</td>
|
||||
<td>{{ restore.operator_username }}</td>
|
||||
<td>{{ restore.backup.requested_at|date:"j M Y, H:i" }} UTC</td>
|
||||
<td>
|
||||
{% if restore.filename %}
|
||||
{% if restore.kind %}
|
||||
{{ restore.get_kind_display }} <code>{{ restore.target_name }}</code>
|
||||
{% elif restore.filename %}
|
||||
<code>{{ restore.filename }}</code>
|
||||
{% if restore.replace %}(replacement allowed){% endif %}
|
||||
{% 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)
|
||||
@@ -98,6 +98,19 @@ class MailboxBackupTests(SimpleTestCase):
|
||||
|
||||
self.assertEqual(marker.read_bytes(), b"mail already present")
|
||||
|
||||
def test_publishing_does_not_replace_a_concurrently_created_maildir(self):
|
||||
source = self.home / "restored"
|
||||
source.mkdir()
|
||||
destination = self.home / "Maildir"
|
||||
destination.mkdir()
|
||||
inode = destination.stat().st_ino
|
||||
|
||||
with self.assertRaisesMessage(ValueError, "no existing Maildir"):
|
||||
mail_node_backup.publish_maildir(source, destination)
|
||||
|
||||
self.assertEqual(destination.stat().st_ino, inode)
|
||||
self.assertTrue(source.is_dir())
|
||||
|
||||
def test_restore_refuses_a_backup_for_another_address(self):
|
||||
self.make_archive(MailboxSpec("example.net", "another"))
|
||||
|
||||
|
||||
@@ -102,7 +102,7 @@ class PanelWebsiteRestoreTests(TestCase):
|
||||
)
|
||||
self.assertEqual(WebsiteRestoreJob.objects.count(), 1)
|
||||
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, "assets/site.css")
|
||||
|
||||
@@ -199,7 +199,7 @@ class PanelWebsiteRestoreTests(TestCase):
|
||||
self.assertEqual(self.submit().status_code, 404)
|
||||
self.assertNotContains(
|
||||
self.client.get(self.account.get_absolute_url()),
|
||||
"Website restores",
|
||||
"Backup restores",
|
||||
)
|
||||
operator.user_permissions.add(
|
||||
perms.get(codename="view_hostingmailbox")
|
||||
@@ -207,7 +207,7 @@ class PanelWebsiteRestoreTests(TestCase):
|
||||
self.assertEqual(self.client.get(self.url).status_code, 200)
|
||||
self.assertContains(
|
||||
self.client.get(self.account.get_absolute_url()),
|
||||
"Website restores",
|
||||
"Backup restores",
|
||||
)
|
||||
|
||||
def test_read_only_customer_preview_cannot_queue_a_restore(self):
|
||||
|
||||
@@ -2,6 +2,7 @@ from django.contrib.auth.views import LoginView, LogoutView
|
||||
from django.urls import path
|
||||
|
||||
from . import views
|
||||
from .backup_restores import RestoreKind
|
||||
|
||||
app_name = "panel"
|
||||
|
||||
@@ -50,6 +51,16 @@ urlpatterns = [
|
||||
views.RequestWebsiteRestore.as_view(),
|
||||
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(
|
||||
"accounts/<int:pk>/sftp/",
|
||||
views.SiteSFTPKeys.as_view(),
|
||||
|
||||
+151
-38
@@ -1,3 +1,5 @@
|
||||
from operator import attrgetter
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.contrib.auth.forms import UserCreationForm
|
||||
@@ -41,14 +43,22 @@ from .access import (
|
||||
from .account_backup_forms import (
|
||||
SCHEDULE_FIELDS,
|
||||
AccountBackupScheduleForm,
|
||||
ComponentRestoreForm,
|
||||
WebsiteRestoreForm,
|
||||
)
|
||||
from .account_backups import (
|
||||
account_backup_manifest,
|
||||
queue_account_backup,
|
||||
queue_website_restore,
|
||||
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_publication import queue_dns_publication
|
||||
from .impersonation import (
|
||||
@@ -60,6 +70,7 @@ from .impersonation import (
|
||||
from .models import (
|
||||
AccountBackupJob,
|
||||
AccountBackupSchedule,
|
||||
ComponentRestoreJob,
|
||||
Customer,
|
||||
DatabaseProvisioning,
|
||||
HostingAccount,
|
||||
@@ -116,6 +127,17 @@ MANAGE_BACKUP_SCHEDULE = (
|
||||
"hosting.change_accountbackupschedule",
|
||||
)
|
||||
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")
|
||||
ENABLE_WEB_HTTPS = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webhttps")
|
||||
PROVISION_DATABASE = (
|
||||
@@ -315,24 +337,11 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
||||
else [job for job in jobs if not job.includes_mailboxes]
|
||||
)
|
||||
context["account_backup_jobs"] = visible_jobs
|
||||
if user.has_perm("hosting.add_websiterestorejob"):
|
||||
if settings.LOCAL_WEBSITE_RESTORE:
|
||||
site = WebSite(self.object.pk, self.object.primary_domain)
|
||||
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]
|
||||
context.update(
|
||||
backup_restore_context(
|
||||
self.object, user, visible_jobs, can_view_mailboxes
|
||||
)
|
||||
)
|
||||
pending = next(
|
||||
(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)
|
||||
|
||||
|
||||
class RequestWebsiteRestore(
|
||||
OperatorOnlyMixin, PermissionRequiredMixin, FormView
|
||||
):
|
||||
permission_required = RESTORE_WEBSITE
|
||||
form_class = WebsiteRestoreForm
|
||||
template_name = "hosting/website_restore.html"
|
||||
def backup_restore_context(account, user, backups, can_view_mailboxes):
|
||||
context = {}
|
||||
history = []
|
||||
kinds = {
|
||||
kind
|
||||
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 not (
|
||||
settings.LOCAL_ACCOUNT_BACKUPS and settings.LOCAL_WEBSITE_RESTORE
|
||||
):
|
||||
raise Http404
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
if user.has_perms(RESTORE_WEBSITE):
|
||||
history.extend(
|
||||
sources.select_related("backup").order_by("-requested_at", "-pk")[
|
||||
:10
|
||||
]
|
||||
)
|
||||
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
|
||||
def backup(self):
|
||||
return self.get_backup()
|
||||
|
||||
def get_backup(self):
|
||||
backup = get_object_or_404(
|
||||
AccountBackupJob.objects.select_related("account"),
|
||||
pk=self.kwargs["backup_pk"],
|
||||
account_id=self.kwargs["pk"],
|
||||
)
|
||||
site = WebSite(backup.account_id, backup.account.primary_domain)
|
||||
if not backup.can_restore_website(site):
|
||||
if backup.state != "configured":
|
||||
raise Http404
|
||||
if backup.includes_mailboxes and not self.request.user.has_perm(
|
||||
VIEW_MAILBOXES
|
||||
@@ -554,12 +600,10 @@ class RequestWebsiteRestore(
|
||||
|
||||
def form_valid(self, form):
|
||||
try:
|
||||
queue_website_restore(
|
||||
self.queue_restore(
|
||||
self.backup,
|
||||
restore_id=form.cleaned_data["restore_id"],
|
||||
filename=form.cleaned_data["filename"],
|
||||
replace=form.cleaned_data["replace"],
|
||||
operator_username=self.request.user.get_username(),
|
||||
form.cleaned_data,
|
||||
self.request.user.get_username(),
|
||||
)
|
||||
except HostingAccount.DoesNotExist:
|
||||
raise Http404 from None
|
||||
@@ -569,6 +613,75 @@ class RequestWebsiteRestore(
|
||||
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(
|
||||
OperatorOnlyMixin, PermissionRequiredMixin, FormView
|
||||
):
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import ctypes
|
||||
import errno
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
@@ -16,6 +18,9 @@ BACKUP_KIND = "coulobre_mailbox_backup"
|
||||
METADATA_NAME = "manifest.json"
|
||||
MAILDIR = "Maildir"
|
||||
MAILDIR_FOLDERS = ("cur", "new", "tmp")
|
||||
AT_FDCWD = -100
|
||||
RENAME_NOREPLACE = 1
|
||||
MAILDIR_EXISTS = "Restore requires a mailbox with no existing Maildir."
|
||||
COMMAND_ENV = {"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LC_ALL": "C"}
|
||||
|
||||
|
||||
@@ -70,8 +75,7 @@ def restore_mailbox(mailbox, archive):
|
||||
with TemporaryDirectory(dir=home.parent) as directory:
|
||||
scratch = Path(directory)
|
||||
extract_maildir(mailbox, archive, scratch, account)
|
||||
check_fresh_maildir(destination)
|
||||
(scratch / MAILDIR).rename(destination)
|
||||
publish_maildir(scratch / MAILDIR, destination)
|
||||
|
||||
return {
|
||||
"kind": "coulobre_mailbox_restore",
|
||||
@@ -93,9 +97,30 @@ def managed_mailbox(mailbox):
|
||||
|
||||
def check_fresh_maildir(destination):
|
||||
if os.path.lexists(destination):
|
||||
raise ValueError(
|
||||
"Restore requires a mailbox with no existing Maildir."
|
||||
)
|
||||
raise ValueError(MAILDIR_EXISTS)
|
||||
|
||||
|
||||
def publish_maildir(source, destination):
|
||||
rename = ctypes.CDLL(None, use_errno=True).renameat2
|
||||
rename.argtypes = (
|
||||
ctypes.c_int,
|
||||
ctypes.c_char_p,
|
||||
ctypes.c_int,
|
||||
ctypes.c_char_p,
|
||||
ctypes.c_uint,
|
||||
)
|
||||
rename.restype = ctypes.c_int
|
||||
if rename(
|
||||
AT_FDCWD,
|
||||
os.fsencode(source),
|
||||
AT_FDCWD,
|
||||
os.fsencode(destination),
|
||||
RENAME_NOREPLACE,
|
||||
):
|
||||
code = ctypes.get_errno()
|
||||
if code == errno.EEXIST:
|
||||
raise ValueError(MAILDIR_EXISTS)
|
||||
raise OSError(code, os.strerror(code), str(destination))
|
||||
|
||||
|
||||
def copy_mailbox(mailbox, snapshot):
|
||||
|
||||
@@ -136,6 +136,14 @@ LOCAL_WEBSITE_RESTORE = (
|
||||
LOCAL_ACCOUNT_BACKUPS
|
||||
and os.environ.get("COULOBRE_LOCAL_WEBSITE_RESTORE") == "1"
|
||||
)
|
||||
LOCAL_DATABASE_RESTORE = (
|
||||
LOCAL_ACCOUNT_BACKUPS
|
||||
and os.environ.get("COULOBRE_LOCAL_DATABASE_RESTORE") == "1"
|
||||
)
|
||||
LOCAL_MAILBOX_RESTORE = (
|
||||
LOCAL_ACCOUNT_BACKUPS
|
||||
and os.environ.get("COULOBRE_LOCAL_MAILBOX_RESTORE") == "1"
|
||||
)
|
||||
CELERY_BEAT_SCHEDULE = {
|
||||
"dispatch-web-provisioning-plans": {
|
||||
"task": "coulobre.hosting.tasks.dispatch_web_plans",
|
||||
|
||||
Reference in new issue
Block a user