Files
coulobre/src/coulobre/database_node_backup.py
T

268 lines
8.3 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):
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)
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",
"--routines",
"--events",
"--triggers",
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):
if os.geteuid() != 0:
raise ValueError("Run restore-database as root on the MariaDB node.")
archive = archive.absolute()
require_root_directory(archive.parent)
check_root_file(archive, mode=0o600)
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_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."
)