Files
coulobre/src/coulobre/database_node_backup.py
T

335 lines
11 KiB
Python

import gzip
import json
import os
import subprocess
import zlib
from contextlib import contextmanager
from shutil import copyfileobj
from tempfile import NamedTemporaryFile, TemporaryFile
from . import database_node_apply
from .node_files import check_root_file, require_root_directory, write_new_file
BACKUP_KIND = "coulobre_mariadb_backup"
BACKUP_VERSION = 1
HEADER_PREFIX = b"-- Coulobre MariaDB backup "
MAX_HEADER_BYTES = 4096
CLIENT_ENV = {"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LANG": "C"}
DEFINER_OBJECTS = (
("VIEWS", "TABLE_SCHEMA"),
("TRIGGERS", "TRIGGER_SCHEMA"),
("ROUTINES", "ROUTINE_SCHEMA"),
("EVENTS", "EVENT_SCHEMA"),
)
def backup_database(database, socket, archive, *, wordpress_prefix=None):
if os.geteuid() != 0:
raise ValueError("Run backup-database as root on the MariaDB node.")
archive = archive.absolute()
require_root_directory(archive.parent)
if os.path.lexists(archive):
raise ValueError("Choose a new MariaDB backup filename.")
with managed_database(database, socket) as (cursor, record, record_path):
check_definers(cursor, database.name)
if wordpress_prefix is not None:
check_wordpress_schema(cursor, database.name, wordpress_prefix)
objects = (
("--routines", "--events", "--triggers")
if wordpress_prefix is None
else ("--skip-routines", "--skip-events", "--skip-triggers")
)
with (
client_options(record, record_path.parent) as options,
NamedTemporaryFile(dir=archive.parent) as staged,
):
command = client_command("mariadb-dump", options, record) + (
"--single-transaction",
"--quick",
"--skip-lock-tables",
"--skip-add-locks",
"--skip-add-drop-table",
"--no-tablespaces",
"--hex-blob",
*objects,
database.name,
)
with gzip.GzipFile(fileobj=staged, mode="wb", filename="") as data:
data.write(backup_header(database))
write_dump(command, data)
staged.flush()
os.fsync(staged.fileno())
os.link(staged.name, archive)
return database.manifest() | {
"kind": BACKUP_KIND,
"database": database.name,
"archive": str(archive),
}
def restore_database(database, socket, archive):
archive = private_source_archive(archive)
with TemporaryFile(dir=archive.parent) as validated:
read_dump(database, archive, validated)
restore_dump(database, socket, validated)
return database.manifest() | {
"kind": "coulobre_mariadb_restore",
"database": database.name,
"archive": str(archive),
}
def restore_directadmin_database(database, socket, backup, source):
from .directadmin_payload import copy_database_dump
if os.geteuid() != 0:
raise ValueError(
"Run restore-directadmin as root on the MariaDB node."
)
with TemporaryFile() as validated:
copy_database_dump(database, backup, source, validated)
restore_dump(database, socket, validated)
return database.manifest() | {
"kind": "directadmin_database_restore",
"database": database.name,
"source_database": source,
}
def restore_dump(database, socket, validated):
validated.seek(0)
with managed_database(database, socket, restoring=True) as (
cursor,
record,
record_path,
):
check_empty_database(cursor, database.name)
with client_options(record, record_path.parent) as options:
restore_marker = mark_restore_pending(record_path, record)
command = client_command("mariadb", options, record) + (
"--batch",
"--sandbox",
"--binary-mode",
"--local-infile=0",
"--skip-reconnect",
f"--database={database.name}",
)
import_dump(command, validated)
restore_marker.unlink()
@contextmanager
def managed_database(database, socket, *, restoring=False):
socket = socket.resolve()
record_path = database_node_apply.STATE_DIRECTORY / f"{database.name}.json"
with database_node_apply.locked_cursor(database, socket) as (
driver,
cursor,
):
record = database_node_apply.checked_credentials(
driver, cursor, database, socket, record_path, restoring=restoring
)
if record is None:
raise ValueError("Apply the MariaDB database manifest first.")
yield cursor, record, record_path
def backup_header(database):
metadata = {
"version": BACKUP_VERSION,
"kind": BACKUP_KIND,
"database": database.manifest(),
}
return HEADER_PREFIX + json.dumps(metadata).encode("ascii") + b"\n"
def read_dump(database, archive, destination):
try:
with gzip.open(archive, "rb") as data:
validate_dump_header(database, data)
copyfileobj(data, destination, length=1024 * 1024)
except (EOFError, gzip.BadGzipFile, zlib.error):
raise ValueError(
"The MariaDB backup is damaged or incomplete."
) from None
if not destination.tell():
raise ValueError("The MariaDB backup is missing its SQL dump.")
def validate_dump_header(database, data):
if data.readline(MAX_HEADER_BYTES + 1) != backup_header(database):
raise ValueError("Expected a native dump for this MariaDB database.")
def check_definers(cursor, name):
expected = f"{name}@localhost"
for table, schema in DEFINER_OBJECTS:
cursor.execute(
f"SELECT 1 FROM information_schema.{table} "
f"WHERE {schema} = %s AND BINARY DEFINER <> %s LIMIT 1",
(name, expected),
)
if cursor.fetchone() is not None:
raise ValueError(
"Database objects must use the managed login as their definer."
)
def check_wordpress_schema(cursor, name, prefix):
from .wordpress_staging import validate_table_prefix
validate_table_prefix(prefix)
cursor.execute(
"SELECT TABLE_NAME, TABLE_TYPE FROM information_schema.TABLES "
"WHERE TABLE_SCHEMA = %s",
(name,),
)
tables = cursor.fetchall()
if (
not tables
or any(kind != "BASE TABLE" for _, kind in tables)
or any(not table.startswith(prefix) for table, _ in tables)
):
raise ValueError(
"Staging requires a dedicated WordPress database "
"with ordinary tables."
)
table_names = {table for table, _ in tables}
if (
not {
prefix + table
for table in ("options", "posts", "users", "usermeta")
}
<= table_names
or {prefix + table for table in ("blogs", "sitemeta", "site")}
& table_names
):
raise ValueError("Staging requires a single WordPress website.")
for table, schema in DEFINER_OBJECTS[1:]:
cursor.execute(
f"SELECT 1 FROM information_schema.{table} "
f"WHERE {schema} = %s LIMIT 1",
(name,),
)
if cursor.fetchone() is not None:
raise ValueError(
"Staging requires a database without triggers, "
"routines or events."
)
def check_empty_database(cursor, name):
for table, schema in (("TABLES", "TABLE_SCHEMA"), *DEFINER_OBJECTS[2:]):
cursor.execute(
f"SELECT 1 FROM information_schema.{table} "
f"WHERE {schema} = %s LIMIT 1",
(name,),
)
if cursor.fetchone() is not None:
raise ValueError("Restore requires an empty managed database.")
def mark_restore_pending(record_path, record):
marker = record_path.with_suffix(".restore-pending")
ownership = record["ownership"] + "\n"
if os.path.lexists(marker):
if database_node_apply.read_root_file(marker, mode=0o600) != ownership:
raise ValueError(
"The MariaDB restore marker has different ownership."
)
else:
write_new_file(marker, ownership, mode=0o600)
return marker
@contextmanager
def client_options(record, directory):
escapes = str.maketrans(
{
"\\": r"\\",
'"': r"\"",
"\n": r"\n",
"\r": r"\r",
"\t": r"\t",
"\b": r"\b",
}
)
password = record["password"].translate(escapes)
with NamedTemporaryFile(
mode="w", encoding="ascii", dir=directory
) as options:
options.write(f'[client]\npassword="{password}"\n')
options.flush()
yield options.name
def client_command(program, options, record):
return (
f"/usr/bin/{program}",
f"--defaults-file={options}",
"--protocol=socket",
f"--socket={record['socket']}",
f"--user={record['user']}",
"--default-character-set=utf8mb4",
)
def write_dump(command, output):
with subprocess.Popen(
command,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
env=CLIENT_ENV,
) as process:
try:
copyfileobj(process.stdout, output, length=1024 * 1024)
except BaseException:
process.kill()
raise
if process.wait():
raise ValueError(
"mariadb-dump could not complete the database backup."
)
def import_dump(command, data):
result = subprocess.run(
command,
stdin=data,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
env=CLIENT_ENV,
)
if result.returncode:
raise ValueError(
"MariaDB could not complete the restore. "
"Inspect the target before retrying."
)
def clone_database_from_archive(source, destination, socket, archive):
if (
source.account_id != destination.account_id
or source.name == destination.name
):
raise ValueError(
"Choose a separate database owned by the same account."
)
archive = private_source_archive(archive)
with TemporaryFile(dir=archive.parent) as validated:
read_dump(source, archive, validated)
restore_dump(destination, socket, validated)
def private_source_archive(archive):
if os.geteuid() != 0:
raise ValueError("Run database restore as root on the MariaDB node.")
archive = archive.absolute()
require_root_directory(archive.parent)
check_root_file(archive, mode=0o600)
return archive