69 lines
2.2 KiB
Python
69 lines
2.2 KiB
Python
import re
|
|
from shutil import copyfileobj
|
|
|
|
from .database_node import DATABASE_SUFFIX_PATTERN
|
|
from .directadmin import (
|
|
BackupInventory,
|
|
backup_members,
|
|
member_path,
|
|
open_backup,
|
|
)
|
|
|
|
|
|
def database_suffix(username, source):
|
|
normalized = source.lower()
|
|
suffix = normalized.removeprefix(f"{username.lower()}_")
|
|
if suffix == normalized or not re.fullmatch(
|
|
DATABASE_SUFFIX_PATTERN, suffix
|
|
):
|
|
return None
|
|
return suffix
|
|
|
|
|
|
def read_resource(backup, matches, read):
|
|
account = BackupInventory()
|
|
resource = None
|
|
with open_backup(backup) as archive:
|
|
for member in backup_members(archive):
|
|
parts = member_path(member)
|
|
if parts == ("backup", "user.conf"):
|
|
account.visit(archive, member)
|
|
if not matches(parts):
|
|
continue
|
|
if resource is not None:
|
|
raise ValueError("The backup repeats the selected resource.")
|
|
if not member.isreg() or member.size <= 0:
|
|
raise ValueError(
|
|
"The selected resource must be a nonempty file."
|
|
)
|
|
with archive.extractfile(member) as stream:
|
|
resource = read(stream, member.size)
|
|
if account.username is None:
|
|
raise ValueError(
|
|
"Expected a DirectAdmin account backup with backup/user.conf."
|
|
)
|
|
if resource is None:
|
|
raise ValueError("The backup does not contain the selected resource.")
|
|
return account.username, resource
|
|
|
|
|
|
def copy_database_dump(database, backup, source, destination):
|
|
if not re.fullmatch(r"[a-zA-Z0-9_]{1,64}", source):
|
|
raise ValueError("Enter the original DirectAdmin database name.")
|
|
|
|
def copy_dump(stream, size):
|
|
copyfileobj(stream, destination, length=1024 * 1024)
|
|
if destination.tell() != size:
|
|
raise ValueError("The DirectAdmin database dump is incomplete.")
|
|
return size
|
|
|
|
username, _ = read_resource(
|
|
backup,
|
|
lambda parts: parts == ("backup", f"{source}.sql"),
|
|
copy_dump,
|
|
)
|
|
if database_suffix(username, source) != database.suffix:
|
|
raise ValueError(
|
|
"The source database does not match the destination suffix."
|
|
)
|