fix(release): snapshot SQLite before archiving active WAL databases

This commit is contained in:
cesnimda
2026-11-20 19:26:51 +01:00
parent a30e40bd9c
commit 908295c634
6 changed files with 256 additions and 4 deletions
+75
View File
@@ -0,0 +1,75 @@
"""Archive a volume with standalone SQLite snapshots and the remaining original files."""
from contextlib import closing
import os
from pathlib import Path
import shutil
import sqlite3
import stat
import subprocess
import sys
import tempfile
def snapshot(source, destination):
info = source.lstat()
if not stat.S_ISREG(info.st_mode):
raise ValueError('Expected a regular database file.')
with source.open('rb') as original:
if original.read(16) != b'SQLite format 3\x00':
raise ValueError('Expected a SQLite database header.')
with closing(sqlite3.connect(source.as_uri() + '?mode=ro', uri=True)) as reader:
# Establish one read transaction before copying. WAL writers may keep
# committing without moving the snapshot or restarting a large backup.
reader.execute('BEGIN')
reader.execute('PRAGMA schema_version').fetchone()
with closing(sqlite3.connect(destination)) as copied:
reader.backup(copied)
if copied.execute('PRAGMA journal_mode=DELETE').fetchone() != ('delete',):
raise ValueError('Snapshot still requires a journal.')
if hasattr(os, 'chown'):
os.chown(destination, info.st_uid, info.st_gid)
shutil.copystat(source, destination)
def archive_volume(volume, target):
def raise_walk_error(error):
raise error
# Keep uncompressed snapshots on the throwaway container filesystem.
with tempfile.TemporaryDirectory(prefix='sqlite-snapshot-') as temporary:
stage = Path(temporary)
excludes = []
snapshots = []
for folder, dirs, files in os.walk(volume, onerror=raise_walk_error):
if 'jobtracker.db' in dirs:
raise ValueError('Expected a database file.')
if 'jobtracker.db' not in files:
continue
source = Path(folder) / 'jobtracker.db'
name = source.relative_to(volume).as_posix()
staged = stage / 'snapshot' / name
staged.parent.mkdir(parents=True, exist_ok=True)
snapshot(source, staged)
snapshots.append('snapshot/' + name)
for suffix in ('', '-shm', '-wal', '-journal'):
excludes.append('--exclude=./' + name + suffix)
if not snapshots:
raise ValueError('No database found.')
# The original volume's names start with "./". Only staged members match
# this transform. Literal, anchored excludes preserve unrelated sidecars.
tar = shutil.which('tar')
if not tar:
raise FileNotFoundError('GNU tar is required.')
subprocess.run([tar, 'czf', target.name, '--anchored', '--no-wildcards', *excludes,
'--transform=flags=r;s|^snapshot/|./|', '-C', volume.as_posix(), '.',
'-C', stage.as_posix(), *snapshots],
cwd=target.parent, check=True, stderr=subprocess.DEVNULL)
if __name__ == '__main__':
try:
volume, target = map(Path, sys.argv[1:])
archive_volume(volume.resolve(strict=True), target.absolute())
except (OSError, ValueError, sqlite3.Error, subprocess.CalledProcessError):
# Member names and database contents may contain private information.
sys.exit('SQLite volume snapshot or archive creation failed.')
+99
View File
@@ -2,6 +2,7 @@
import os
import io
import gzip
from contextlib import closing
from pathlib import Path
import shlex
import shutil
@@ -451,6 +452,104 @@ class BackupSqlTrailerTests(unittest.TestCase):
self.assertNotIn('NEXT DEPLOY GATE WOULD START', result.stdout)
class BackupSqliteSnapshotTests(unittest.TestCase):
def backup(self, root):
source = (ROOT / 'deploy/deploy.sh').read_text(encoding='utf-8')
functions = []
for name in ['backup_database', 'verify_backup_file_shape', 'verify_volume_backup']:
start = source.index(name + '() {')
functions.append(source[start:source.index('\n}\n', start) + 3])
launch = next(line for line in functions[0].splitlines() if 'python:3.12.10-slim-bookworm sh -c' in line)
command = launch.split("sh -c '", 1)[1].split("'", 1)[0]
local_command = command.replace('exec python3', 'exec "$PYTHON"').replace(' /data ', ' "$VOLUME" ')
local_command = local_command.replace('"/backup/', '"$BACKUP_DIR/')
# Map only container paths and the Python executable to this host. The
# shell body, helper from stdin, SQLite, tar and validator all run.
script = '\n'.join([
'set -euo pipefail',
'BACKUP_DIR=' + shlex.quote((root / 'backups').as_posix()),
'VOLUME=' + shlex.quote((root / 'data').as_posix()),
'PYTHON=' + shlex.quote(Path(sys.executable).as_posix()),
'DATABASE_PROVIDER=sqlite; BACKUP_STAMP=fixture; DEPLOY_SKIP_DB_BACKUP=false; COMPOSE_PROJECT_NAME=fixture',
'python3() { "$PYTHON" "$@"; }',
'report_backup() { echo "FORMAT VERIFIED"; }',
'docker() {',
' if [[ "$1 $2" == "volume inspect" ]]; then return 0; fi',
' [[ "$*" == *"fixture_jobtracker_data:/data:ro "* && "$*" == *" --network none "* ]] || return 99',
' local arg',
' [[ "${!#}" == ' + shlex.quote(command) + ' ]] || return 99',
' for arg in "$@"; do case "$arg" in ARCHIVE_NAME=*) export "$arg";; esac; done',
' export PYTHON VOLUME BACKUP_DIR',
' bash -c ' + shlex.quote(local_command),
'}',
*functions,
'if ! backup_database; then exit 1; fi',
'echo "NEXT DEPLOY GATE WOULD START"',
])
env = os.environ.copy()
if os.name == 'nt':
env['PATH'] = str(Path(BASH).parents[1] / 'usr/bin') + os.pathsep + env['PATH']
return subprocess.run([BASH, '--noprofile', '--norc'], input=script, cwd=ROOT, env=env,
capture_output=True, text=True, encoding='utf-8', timeout=30)
def test_standalone_snapshot_contains_committed_wal_rows_with_writer_open(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
volume = root / 'data'
nested = volume / 'nested [copy]'
nested.mkdir(parents=True)
(volume / 'jobtracker.db-notes').write_bytes(b'attachment data')
(nested / 'unrelated.db-wal').write_bytes(b'unrelated file')
# An identically named database in a nested directory retains its path.
with closing(sqlite3.connect(nested / 'jobtracker.db')) as other:
other.execute('CREATE TABLE nested_fixture (id INTEGER)')
with closing(sqlite3.connect(volume / 'jobtracker.db')) as writer:
self.assertEqual(('wal',), writer.execute('PRAGMA journal_mode=WAL').fetchone())
writer.execute('PRAGMA wal_autocheckpoint=0')
writer.execute('CREATE TABLE receipt (id INTEGER PRIMARY KEY)')
writer.execute('INSERT INTO receipt VALUES (1)')
writer.commit()
self.assertEqual(0, writer.execute('PRAGMA wal_checkpoint(TRUNCATE)').fetchone()[0])
writer.execute('INSERT INTO receipt VALUES (2)')
writer.commit()
writer.execute('INSERT INTO receipt VALUES (3)')
self.assertGreater((volume / 'jobtracker.db-wal').stat().st_size, 0)
result = self.backup(root)
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
self.assertIn('NEXT DEPLOY GATE WOULD START', result.stdout)
writer.rollback()
self.assertEqual(0, writer.execute('PRAGMA wal_checkpoint(TRUNCATE)').fetchone()[0])
with tarfile.open(root / 'backups/jobtracker-sqlite-fixture.tar.gz') as bundle:
for sidecar in ['-wal', '-shm', '-journal']:
self.assertNotIn('./jobtracker.db' + sidecar, bundle.getnames())
for path, expected in [('./jobtracker.db-notes', b'attachment data'),
('./nested [copy]/unrelated.db-wal', b'unrelated file')]:
with bundle.extractfile(path) as stream:
self.assertEqual(expected, stream.read())
for name, query, expected in [('./jobtracker.db', 'SELECT id FROM receipt ORDER BY id', [(1,), (2,)]),
('./nested [copy]/jobtracker.db', 'SELECT * FROM nested_fixture', [])]:
with self.subTest(name=name), bundle.extractfile(name) as stream:
restored = root / 'restored.db'
restored.write_bytes(stream.read())
with closing(sqlite3.connect(restored.as_uri() + '?mode=ro', uri=True)) as copy:
self.assertEqual(expected, copy.execute(query).fetchall())
self.assertEqual(('ok',), copy.execute('PRAGMA integrity_check').fetchone())
self.assertEqual(('delete',), copy.execute('PRAGMA journal_mode').fetchone())
def test_invalid_database_prevents_archive_promotion(self):
for contents in [b'', b'SQLite format 3\x00' + bytes(200)]:
with self.subTest(size=len(contents)), tempfile.TemporaryDirectory() as temp:
root = Path(temp)
(root / 'data').mkdir()
(root / 'data/jobtracker.db').write_bytes(contents)
result = self.backup(root)
self.assertNotEqual(0, result.returncode, result.stdout + result.stderr)
self.assertNotIn('FORMAT VERIFIED', result.stdout)
self.assertNotIn('NEXT DEPLOY GATE WOULD START', result.stdout)
self.assertEqual([], list((root / 'backups').iterdir()))
class BackupDatabaseMemberTests(unittest.TestCase):
def test_host_tar_producer_with_database_and_sidecar(self):
producer = shutil.which('tar')