diff --git a/deploy/panel.env.example b/deploy/panel.env.example index b9a1df7..445f065 100644 --- a/deploy/panel.env.example +++ b/deploy/panel.env.example @@ -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 diff --git a/deploy/systemd/coulobre-account-restore.socket b/deploy/systemd/coulobre-account-restore.socket index ffce980..e9588b5 100644 --- a/deploy/systemd/coulobre-account-restore.socket +++ b/deploy/systemd/coulobre-account-restore.socket @@ -1,5 +1,5 @@ [Unit] -Description=Coulobre local website restore socket +Description=Coulobre local account restore socket [Socket] ListenStream=/run/coulobre-account-restore.sock diff --git a/deploy/systemd/coulobre-account-restore@.service b/deploy/systemd/coulobre-account-restore@.service index d75e1b3..008a4b7 100644 --- a/deploy/systemd/coulobre-account-restore@.service +++ b/deploy/systemd/coulobre-account-restore@.service @@ -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 diff --git a/deploy/systemd/coulobre-account-restore@.service.d/database.conf b/deploy/systemd/coulobre-account-restore@.service.d/database.conf new file mode 100644 index 0000000..0d67695 --- /dev/null +++ b/deploy/systemd/coulobre-account-restore@.service.d/database.conf @@ -0,0 +1,6 @@ +[Unit] +After=mariadb.service + +[Service] +Environment=COULOBRE_LOCAL_DATABASE_RESTORE=1 +ReadWritePaths=-/var/lib/coulobre/database-node diff --git a/deploy/systemd/coulobre-account-restore@.service.d/mailbox.conf b/deploy/systemd/coulobre-account-restore@.service.d/mailbox.conf new file mode 100644 index 0000000..e91f3c4 --- /dev/null +++ b/deploy/systemd/coulobre-account-restore@.service.d/mailbox.conf @@ -0,0 +1,6 @@ +[Unit] +After=postfix.service dovecot.service + +[Service] +Environment=COULOBRE_LOCAL_MAILBOX_RESTORE=1 +ReadWritePaths=-/srv/coulobre-mail diff --git a/deploy/systemd/coulobre-account-restore@.service.d/website.conf b/deploy/systemd/coulobre-account-restore@.service.d/website.conf new file mode 100644 index 0000000..bed2784 --- /dev/null +++ b/deploy/systemd/coulobre-account-restore@.service.d/website.conf @@ -0,0 +1,3 @@ +[Service] +Environment=COULOBRE_LOCAL_WEBSITE_RESTORE=1 +ReadWritePaths=-/srv/coulobre/web diff --git a/docs/deployment.md b/docs/deployment.md index cc8389d..9aff926 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -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 diff --git a/docs/development.md b/docs/development.md index fe4cbc2..00536ad 100644 --- a/docs/development.md +++ b/docs/development.md @@ -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 diff --git a/src/coulobre/account_backup.py b/src/coulobre/account_backup.py index de0009b..c74e755 100644 --- a/src/coulobre/account_backup.py +++ b/src/coulobre/account_backup.py @@ -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 diff --git a/src/coulobre/account_restore_request.py b/src/coulobre/account_restore_request.py index cfbde5b..369302d 100644 --- a/src/coulobre/account_restore_request.py +++ b/src/coulobre/account_restore_request.py @@ -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 diff --git a/src/coulobre/hosting/account_backup_forms.py b/src/coulobre/hosting/account_backup_forms.py index f686036..3ef7155 100644 --- a/src/coulobre/hosting/account_backup_forms.py +++ b/src/coulobre/hosting/account_backup_forms.py @@ -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() + ), + ] diff --git a/src/coulobre/hosting/account_backups.py b/src/coulobre/hosting/account_backups.py index 032df1c..37f9fd7 100644 --- a/src/coulobre/hosting/account_backups.py +++ b/src/coulobre/hosting/account_backups.py @@ -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." - ) diff --git a/src/coulobre/hosting/backup_restores.py b/src/coulobre/hosting/backup_restores.py new file mode 100644 index 0000000..9ede726 --- /dev/null +++ b/src/coulobre/hosting/backup_restores.py @@ -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." + ) diff --git a/src/coulobre/hosting/migrations/0027_component_restore_jobs.py b/src/coulobre/hosting/migrations/0027_component_restore_jobs.py new file mode 100644 index 0000000..3970c63 --- /dev/null +++ b/src/coulobre/hosting/migrations/0027_component_restore_jobs.py @@ -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", + ) + ], + }, + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index c236a6b..591edea 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -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" diff --git a/src/coulobre/hosting/node_client.py b/src/coulobre/hosting/node_client.py index 479b699..036a3c1 100644 --- a/src/coulobre/hosting/node_client.py +++ b/src/coulobre/hosting/node_client.py @@ -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") diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py index 6486ecb..c8f320a 100644 --- a/src/coulobre/hosting/tasks.py +++ b/src/coulobre/hosting/tasks.py @@ -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 ): diff --git a/src/coulobre/hosting/templates/hosting/account_backups.html b/src/coulobre/hosting/templates/hosting/account_backups.html index ec1f7ab..b6b3269 100644 --- a/src/coulobre/hosting/templates/hosting/account_backups.html +++ b/src/coulobre/hosting/templates/hosting/account_backups.html @@ -62,8 +62,18 @@
{{ job.archive }}
- {% 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 %}
+ | Requested | Operator | Backup requested | Restore target | Status |
|---|---|---|---|---|
| {{ restore.requested_at|date:"j M Y, H:i" }} UTC | {{ restore.operator_username }} | {{ restore.backup.requested_at|date:"j M Y, H:i" }} UTC |
- {% if restore.filename %}
+ {% if restore.kind %}
+ {{ restore.get_kind_display }} {{ restore.target_name }}
+ {% elif restore.filename %}
{{ restore.filename }}
{% if restore.replace %}(replacement allowed){% endif %}
{% else %}
diff --git a/src/coulobre/hosting/templates/hosting/component_restore.html b/src/coulobre/hosting/templates/hosting/component_restore.html
new file mode 100644
index 0000000..10993c5
--- /dev/null
+++ b/src/coulobre/hosting/templates/hosting/component_restore.html
@@ -0,0 +1,26 @@
+{% extends "hosting/base.html" %}
+{% block title %}Restore {{ restore_kind }} · Coulobre Panel{% endblock %}
+{% block content %}
+ ← {{ account.name }}
+
+
+ Restore {{ restore_kind }}+ +Choose an empty managed database. Keep the application disconnected until the restore completes. + {% else %} +Choose a newly provisioned mailbox with no Maildir. Keep delivery and client access to that mailbox paused until the restore completes. + {% endif %} + + |