89 lines
3.1 KiB
Python
89 lines
3.1 KiB
Python
import fcntl
|
|
import os
|
|
import shutil
|
|
import stat
|
|
from pathlib import Path
|
|
from tempfile import NamedTemporaryFile
|
|
from zipfile import ZipFile
|
|
|
|
from .database_node import DatabaseSpec
|
|
from .node_files import check_root_file, require_root_directory
|
|
from .web_node_apply import (
|
|
SitePaths,
|
|
check_reservation,
|
|
current_user,
|
|
locked_web_node,
|
|
)
|
|
|
|
|
|
def export_latest_backup(site, archive, *, database_suffix=""):
|
|
if database_suffix:
|
|
DatabaseSpec(site.account_id, database_suffix)
|
|
# A root-owned directory protects the published export.
|
|
with locked_web_node(fcntl.LOCK_EX):
|
|
check_reservation(site)
|
|
account = SitePaths.for_site(site).account
|
|
require_root_directory(account)
|
|
user = current_user(site.service_user)
|
|
if (
|
|
user is None
|
|
or user.pw_uid <= 0
|
|
or user.pw_gid <= 0
|
|
or user.pw_dir != str(account)
|
|
):
|
|
raise ValueError("The hosting account has no matching SFTP login.")
|
|
destination = account / "backups"
|
|
try:
|
|
destination.mkdir(mode=0o700)
|
|
except FileExistsError:
|
|
pass
|
|
else:
|
|
os.chown(destination, 0, user.pw_gid, follow_symlinks=False)
|
|
destination.chmod(0o750)
|
|
info = destination.lstat()
|
|
if (
|
|
not stat.S_ISDIR(info.st_mode)
|
|
or info.st_uid != 0
|
|
or info.st_gid != user.pw_gid
|
|
or stat.S_IMODE(info.st_mode) != 0o750
|
|
or account.stat().st_dev != info.st_dev
|
|
):
|
|
raise ValueError(
|
|
"The backup directory has unexpected ownership or permissions."
|
|
)
|
|
component = (
|
|
f"database-{database_suffix}.sql.gz" if database_suffix else None
|
|
)
|
|
latest = destination / (component or "latest.zip")
|
|
if os.path.lexists(latest):
|
|
info = latest.lstat()
|
|
if (
|
|
not stat.S_ISREG(info.st_mode)
|
|
or info.st_uid != user.pw_uid
|
|
or info.st_nlink != 1
|
|
):
|
|
raise ValueError(
|
|
"The previous backup export has unexpected ownership "
|
|
"or type."
|
|
)
|
|
check_root_file(archive, mode=0o600)
|
|
with NamedTemporaryFile(dir=destination, delete=False) as staged:
|
|
temporary = Path(staged.name)
|
|
try:
|
|
if component:
|
|
with (
|
|
ZipFile(archive) as bundle,
|
|
bundle.open(component) as source,
|
|
):
|
|
shutil.copyfileobj(source, staged, length=1024 * 1024)
|
|
else:
|
|
with archive.open("rb") as source:
|
|
shutil.copyfileobj(source, staged, length=1024 * 1024)
|
|
staged.flush()
|
|
os.fchown(staged.fileno(), user.pw_uid, user.pw_gid)
|
|
os.fchmod(staged.fileno(), 0o400)
|
|
os.fsync(staged.fileno())
|
|
os.replace(temporary, latest)
|
|
finally:
|
|
temporary.unlink(missing_ok=True)
|