Restore databases and mailboxes from local account backups #36

Merged
parkel merged 4 commits from feature/account-backup-recovery into main 2026-11-21 14:56:59 +01:00
4 changed files with 205 additions and 23 deletions
Showing only changes of commit 337a078ffe - Show all commits

No files matched your search

+8
View File
@@ -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
+154 -18
View File
@@ -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
@@ -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"))
+30 -5
View File
@@ -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):