Add managed MariaDB database backups and restore #24

Merged
parkel merged 2 commits from feature/mariadb-database-backups into main 2026-11-21 11:56:22 +01:00
7 changed files with 505 additions and 3 deletions

No files matched your search

+4
View File
@@ -350,6 +350,10 @@ The MariaDB node stores the application login in the root-only file
`/var/lib/coulobre/database-node/<database-name>.json`. Use the credentials
from that file when configuring the hosted application.
Use the MariaDB node commands to create a compressed SQL dump for an individual
managed database and restore it to an empty database with the same identity.
[Database backup and restore](development.md#back-up-and-restore-a-managed-database)
## Publish local DNS zones from the panel
Enable the [DNS publishing socket](development.md#enable-local-dns-publishing)
+39 -1
View File
@@ -157,11 +157,49 @@ message when the installation needs attention.
| --- | --- | --- |
| `configured` | 0 | All checks passed. |
| `not_installed` | 2 | The registry, database, and login are absent. |
| `needs_attention` | 2 | An installation is incomplete or differs from the expected configuration. |
| `needs_attention` | 2 | Provisioning or restore is incomplete, or the installation differs from the expected configuration. |
Exit code `1` indicates an invalid manifest or an unavailable check, for example
when the MariaDB administrative connection fails.
### Back up and restore a managed database
Run these commands as root on the MariaDB node. Install the MariaDB client
utilities and the Coulobre package with its `mariadb` extra. Use the same
database manifest and socket as for provisioning. Add `--socket PATH` when
using a custom socket.
```sh
sudo install -d -m 0700 /var/backups/coulobre
sudo /opt/coulobre/bin/coulobre-database-node backup-database \
coulobre-database-1.json /var/backups/coulobre/database-1.sql.gz
```
The node writes a gzip-compressed SQL dump containing the database's schema,
rows, views, triggers, routines, and events. Database objects with a definer
must use the managed application login. The dump uses a single transaction
for InnoDB data. Pause schema changes and writes to nontransactional tables
during backup. Choose a new filename for each backup and keep archives in a
root-controlled directory with file permissions of `0600`.
To restore, apply the original manifest on the destination node and leave the
new database empty. Transfer the archive to a root-controlled directory on that
node and ensure it is owned by root with permissions of `0600`.
```sh
sudo /opt/coulobre/bin/coulobre-database-node restore-database \
coulobre-database-1.json /var/backups/coulobre/database-1.sql.gz
```
The node checks the gzip stream and its database identity before running the
SQL. The archive needs temporary space for the uncompressed SQL on the same
filesystem. Use the destination node's application credentials and keep the
application disconnected until the restore completes.
MariaDB can commit schema changes before reporting a restore error. If an
import fails, `status` reports `needs_attention`. Inspect the partial database
and return it to an empty state before retrying with the same manifest.
### Enable local database provisioning
On a MariaDB node using `/run/mysqld/mysqld.sock`, install the matching Coulobre
+22
View File
@@ -86,6 +86,18 @@ def main(argv=None):
)
status.add_argument("manifest", type=Path)
status.add_argument("--socket", type=Path, default=DEFAULT_SOCKET)
backup = commands.add_parser(
"backup-database", help="Write a logical dump of a managed database."
)
backup.add_argument("manifest", type=Path)
backup.add_argument("archive", type=Path)
backup.add_argument("--socket", type=Path, default=DEFAULT_SOCKET)
restore = commands.add_parser(
"restore-database", help="Restore a dump to an empty managed database."
)
restore.add_argument("manifest", type=Path)
restore.add_argument("archive", type=Path)
restore.add_argument("--socket", type=Path, default=DEFAULT_SOCKET)
args = parser.parse_args(argv)
if args.command == "apply-request":
@@ -112,6 +124,16 @@ def main(argv=None):
report = database_status(database, args.socket)
print(json.dumps(report, indent=2))
return 0 if report["state"] == "configured" else 2
elif args.command == "backup-database":
from .database_node_backup import backup_database
report = backup_database(database, args.socket, args.archive)
print(json.dumps(report, indent=2))
elif args.command == "restore-database":
from .database_node_backup import restore_database
report = restore_database(database, args.socket, args.archive)
print(json.dumps(report, indent=2))
else:
print(
json.dumps(
+19 -2
View File
@@ -104,6 +104,13 @@ def database_status(database, socket):
def check_database(driver, cursor, database, socket, record_path):
record = checked_credentials(driver, cursor, database, socket, record_path)
return "configured" if record is not None else "not_installed"
def checked_credentials(
driver, cursor, database, socket, record_path, *, restoring=False
):
name = database.name
schema, users = read_resources(cursor, name)
ready_path = record_path.with_suffix(".ready")
@@ -115,11 +122,13 @@ def check_database(driver, cursor, database, socket, record_path):
"The database, login, or completion marker has no local "
"credentials record."
)
return "not_installed"
return None
record = load_credentials(database, socket, record_path)
if not check_completion_marker(ready_path, record):
raise ValueError("The database installation is incomplete.")
if not restoring:
check_restore_complete(record_path)
password_hash = native_password_hash(record["password"])
check_resources(
schema,
@@ -157,10 +166,18 @@ def check_database(driver, cursor, database, socket, record_path):
"The stored application credentials cannot open the managed "
"database."
) from None
return "configured"
return record
def check_restore_complete(record_path):
if os.path.lexists(record_path.with_suffix(".restore-pending")):
raise ValueError(
"A MariaDB restore has not completed for this database."
)
def install_database(cursor, database, socket, record_path):
check_restore_complete(record_path)
name = database.name
schema, users = read_resources(cursor, name)
ready_path = record_path.with_suffix(".ready")
+245
View File
@@ -0,0 +1,245 @@
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)
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()
return database.manifest() | {
"kind": "coulobre_mariadb_restore",
"database": database.name,
"archive": str(archive),
}
@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:
header = data.readline(MAX_HEADER_BYTES + 1)
if header != backup_header(database):
raise ValueError(
"Expected a native dump for this MariaDB database."
)
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 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."
)
@@ -218,6 +218,21 @@ class DatabaseProvisioningTests(SimpleTestCase):
)
driver.connect.return_value.close.assert_called_once()
def test_unfinished_restore_blocks_status_and_provisioning(self):
credentials = self.set_configured_resources()
marker = self.record.with_suffix(".restore-pending")
marker.write_text(credentials["ownership"] + "\n")
driver = Mock()
with self.assertRaisesRegex(ValueError, "restore has not completed"):
self.check_status(driver)
driver.connect.assert_not_called()
self.cursor.reset_mock()
with self.assertRaisesRegex(ValueError, "restore has not completed"):
self.apply()
self.cursor.execute.assert_not_called()
def test_status_rejects_database_grants_with_unescaped_wildcards(self):
driver = Mock()
credentials = self.set_configured_resources()
@@ -0,0 +1,161 @@
import gzip
import stat
from contextlib import nullcontext
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import Mock, patch
from django.test import SimpleTestCase
from coulobre import database_node_backup
from coulobre.database_node import DEFAULT_SOCKET, DatabaseSpec
DUMP = b"CREATE TABLE posts (id INT PRIMARY KEY);\n"
class DatabaseBackupTests(SimpleTestCase):
def setUp(self):
directory = Path(self.enterContext(TemporaryDirectory()))
self.database = DatabaseSpec(42, "site_db")
self.archive = directory / "database.sql.gz"
self.credentials = directory / f"{self.database.name}.json"
self.marker = self.credentials.with_suffix(".restore-pending")
self.record = {
"ownership": "test-ownership",
"password": "test-password",
"socket": str(DEFAULT_SOCKET),
"user": self.database.name,
}
self.cursor = Mock()
self.cursor.fetchone.return_value = None
self.enterContext(
patch.object(database_node_backup.os, "geteuid", return_value=0)
)
self.enterContext(
patch.object(database_node_backup, "require_root_directory")
)
self.enterContext(
patch.object(database_node_backup, "check_root_file")
)
self.managed = self.enterContext(
patch.object(
database_node_backup,
"managed_database",
side_effect=lambda *args, **kwargs: nullcontext(
(self.cursor, self.record, self.credentials)
),
)
)
def backup(self):
return database_node_backup.backup_database(
self.database, DEFAULT_SOCKET, self.archive
)
def restore(self):
return database_node_backup.restore_database(
self.database, DEFAULT_SOCKET, self.archive
)
def write_archive(self, database=None):
self.archive.write_bytes(
gzip.compress(
database_node_backup.backup_header(database or self.database)
+ DUMP
)
)
def test_backup_publishes_private_archive_with_database_identity(self):
def dump(command, output):
self.assertEqual(command[0], "/usr/bin/mariadb-dump")
self.assertIn(f"--user={self.database.name}", command)
self.assertNotIn(self.record["password"], " ".join(command))
options = Path(command[1].removeprefix("--defaults-file="))
self.assertEqual(stat.S_IMODE(options.stat().st_mode), 0o600)
output.write(DUMP)
with patch.object(
database_node_backup, "write_dump", side_effect=dump
):
report = self.backup()
self.assertEqual(report["database"], self.database.name)
self.assertEqual(stat.S_IMODE(self.archive.stat().st_mode), 0o600)
self.assertEqual(
gzip.decompress(self.archive.read_bytes()),
database_node_backup.backup_header(self.database) + DUMP,
)
self.assertEqual(list(self.archive.parent.iterdir()), [self.archive])
def test_failed_dump_leaves_no_archive(self):
with (
patch.object(
database_node_backup, "write_dump", side_effect=ValueError
),
self.assertRaises(ValueError),
):
self.backup()
self.assertFalse(self.archive.exists())
def test_restore_rejects_archives_for_a_different_database(self):
self.write_archive(DatabaseSpec(43, self.database.suffix))
with self.assertRaisesRegex(ValueError, "for this MariaDB database"):
self.restore()
self.managed.assert_not_called()
def test_restore_checks_the_entire_archive_before_connecting(self):
self.write_archive()
self.archive.write_bytes(self.archive.read_bytes()[:-4])
with self.assertRaisesRegex(ValueError, "damaged or incomplete"):
self.restore()
self.managed.assert_not_called()
def test_restore_rejects_a_nonempty_database(self):
self.write_archive()
self.cursor.fetchone.return_value = (1,)
with self.assertRaisesRegex(ValueError, "empty managed database"):
self.restore()
self.assertFalse(self.marker.exists())
def test_restore_uses_the_scoped_login_and_clears_the_marker_on_success(
self,
):
self.write_archive()
def import_dump(command, source):
self.assertIn("--sandbox", command)
self.assertIn("--local-infile=0", command)
self.assertIn(f"--user={self.database.name}", command)
self.assertIn(f"--database={self.database.name}", command)
self.assertEqual(source.read(), DUMP)
self.assertTrue(self.marker.exists())
with patch.object(
database_node_backup, "import_dump", side_effect=import_dump
):
report = self.restore()
self.assertEqual(report["database"], self.database.name)
self.assertFalse(self.marker.exists())
def test_failed_restore_keeps_the_marker(self):
self.write_archive()
with (
patch.object(
database_node_backup, "import_dump", side_effect=ValueError
),
self.assertRaises(ValueError),
):
self.restore()
self.assertEqual(
self.marker.read_text(), self.record["ownership"] + "\n"
)