Files
poona-ams/backend/scripts/backup.py
T

256 lines
9.8 KiB
Python

#!/usr/bin/env python3
"""
Poona Hospital Asset Management System (AMS)
Database & Attachments Backup and Disaster Recovery Utility.
Features:
- Online SQLite backup via sqlite3.Connection.backup (transactionally consistent, no locks)
- Bundles ams.db + uploads/ directory into a single timestamped ZIP archive
- PRAGMA integrity_check validation
- Retention policy rotation (retains the latest N backups, default: 7)
- Safe restore functionality with pre-restore fallback safety copy
"""
import argparse
import datetime
import logging
import os
import shutil
import sqlite3
import sys
import tempfile
import zipfile
from pathlib import Path
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
logger = logging.getLogger("ams_backup")
def get_default_paths() -> tuple[Path, Path, Path]:
script_dir = Path(__file__).resolve().parent
backend_dir = script_dir.parent
data_dir = backend_dir / "data"
db_path = data_dir / "ams.db"
uploads_dir = data_dir / "uploads"
backups_dir = data_dir / "backups"
return db_path, uploads_dir, backups_dir
def verify_sqlite_db(db_file: Path) -> bool:
"""Run PRAGMA integrity_check on a SQLite file."""
if not db_file.exists():
logger.error("DB file not found for verification: %s", db_file)
return False
try:
conn = sqlite3.connect(str(db_file))
cursor = conn.cursor()
cursor.execute("PRAGMA integrity_check;")
rows = cursor.fetchall()
conn.close()
if len(rows) == 1 and rows[0][0] == "ok":
logger.info("SQLite integrity check PASSED for: %s", db_file.name)
return True
logger.error("SQLite integrity check FAILED: %s", rows)
return False
except Exception as e:
logger.error("Error verifying SQLite database: %s", e)
return False
def run_backup(
db_path: Path,
uploads_dir: Path,
backups_dir: Path,
keep_count: int = 7,
) -> Path | None:
"""Create a consistent online backup of SQLite DB and attachments into a ZIP archive."""
if not db_path.exists():
logger.error("Source database does not exist at %s", db_path)
return None
backups_dir.mkdir(parents=True, exist_ok=True)
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
backup_zip_path = backups_dir / f"ams_backup_{timestamp}.zip"
with tempfile.TemporaryDirectory() as temp_dir:
temp_db_path = Path(temp_dir) / "ams.db"
# 1. Perform online SQLite backup
logger.info("Starting online backup of %s ...", db_path)
src_conn = sqlite3.connect(f"file:{db_path.resolve()}?mode=ro", uri=True)
dest_conn = sqlite3.connect(str(temp_db_path))
with dest_conn:
src_conn.backup(dest_conn)
dest_conn.close()
src_conn.close()
# 2. Verify backed-up database
if not verify_sqlite_db(temp_db_path):
logger.error("Integrity check failed on temporary backup. Aborting.")
return None
# 3. Create ZIP archive
logger.info("Creating backup archive: %s", backup_zip_path)
with zipfile.ZipFile(backup_zip_path, "w", compression=zipfile.ZIP_DEFLATED) as zf:
# Add database file
zf.write(temp_db_path, arcname="ams.db")
# Add uploads directory
if uploads_dir.exists():
file_count = 0
for root, _, files in os.walk(uploads_dir):
for file in files:
full_path = Path(root) / file
rel_path = full_path.relative_to(uploads_dir)
zf.write(full_path, arcname=f"uploads/{rel_path}")
file_count += 1
logger.info("Archived %d attachment files from %s", file_count, uploads_dir)
else:
logger.warning("Uploads directory %s does not exist; skipping files.", uploads_dir)
size_mb = backup_zip_path.stat().st_size / (1024 * 1024)
logger.info("Backup successfully completed! File: %s (%.2f MB)", backup_zip_path, size_mb)
# 4. Enforce retention policy
if keep_count > 0:
existing_backups = sorted(
backups_dir.glob("ams_backup_*.zip"),
key=lambda p: p.stat().st_mtime,
reverse=True,
)
if len(existing_backups) > keep_count:
for old_backup in existing_backups[keep_count:]:
logger.info("Retention policy: removing old backup %s", old_backup.name)
try:
old_backup.unlink()
except OSError as e:
logger.warning("Failed to remove old backup %s: %s", old_backup, e)
return backup_zip_path
def run_restore(
backup_zip: Path,
db_path: Path,
uploads_dir: Path,
) -> bool:
"""Restore database and uploads from a backup ZIP file with pre-restore safety copy."""
if not backup_zip.exists():
logger.error("Backup archive %s not found.", backup_zip)
return False
logger.info("Restoring from archive: %s", backup_zip)
with tempfile.TemporaryDirectory() as temp_dir:
# Extract archive
try:
with zipfile.ZipFile(backup_zip, "r") as zf:
zf.extractall(temp_dir)
except Exception as e:
logger.error("Failed to read backup zip: %s", e)
return False
extracted_db = Path(temp_dir) / "ams.db"
if not extracted_db.exists():
logger.error("Archive does not contain ams.db. Invalid backup.")
return False
if not verify_sqlite_db(extracted_db):
logger.error("Restored ams.db failed integrity verification. Aborting restore.")
return False
# Safety backup of current db if exists
if db_path.exists():
safety_copy = db_path.with_suffix(f".safety_pre_restore_{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}.bak")
logger.info("Creating safety copy of existing DB: %s", safety_copy)
shutil.copy2(db_path, safety_copy)
# Copy restored DB into place
db_path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(extracted_db, db_path)
logger.info("Database restored successfully to %s", db_path)
# Restore uploads
extracted_uploads = Path(temp_dir) / "uploads"
if extracted_uploads.exists():
uploads_dir.mkdir(parents=True, exist_ok=True)
restored_count = 0
for root, _, files in os.walk(extracted_uploads):
for file in files:
src_f = Path(root) / file
rel_p = src_f.relative_to(extracted_uploads)
dest_f = uploads_dir / rel_p
dest_f.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src_f, dest_f)
restored_count += 1
logger.info("Restored %d attachment files to %s", restored_count, uploads_dir)
logger.info("Restore process completed successfully.")
return True
def main() -> int:
default_db, default_uploads, default_backups = get_default_paths()
parser = argparse.ArgumentParser(description="Poona Hospital AMS Backup & Recovery Utility")
subparsers = parser.add_subparsers(dest="command", help="Command to execute")
# Backup command
backup_parser = subparsers.add_parser("backup", help="Create a backup archive of DB and uploads")
backup_parser.add_argument("--db", type=Path, default=default_db, help="Path to SQLite ams.db")
backup_parser.add_argument("--uploads", type=Path, default=default_uploads, help="Path to uploads directory")
backup_parser.add_argument("--dest", type=Path, default=default_backups, help="Destination directory for backups")
backup_parser.add_argument("--keep", type=int, default=7, help="Number of latest backups to retain (0 to disable)")
# Restore command
restore_parser = subparsers.add_parser("restore", help="Restore DB and uploads from a backup ZIP archive")
restore_parser.add_argument("archive", type=Path, help="Path to backup zip archive")
restore_parser.add_argument("--db", type=Path, default=default_db, help="Destination path for ams.db")
restore_parser.add_argument("--uploads", type=Path, default=default_uploads, help="Destination directory for uploads")
# Verify command
verify_parser = subparsers.add_parser("verify", help="Verify the integrity of a backup archive or SQLite DB")
verify_parser.add_argument("target", type=Path, help="Path to ZIP archive or .db file to verify")
args = parser.parse_args()
# Default to backup if no command provided
if not args.command:
result = run_backup(default_db, default_uploads, default_backups, keep_count=7)
return 0 if result is not None else 1
if args.command == "backup":
result = run_backup(args.db, args.uploads, args.dest, keep_count=args.keep)
return 0 if result is not None else 1
if args.command == "restore":
success = run_restore(args.archive, args.db, args.uploads)
return 0 if success else 1
if args.command == "verify":
target = args.target
if target.suffix == ".zip":
with tempfile.TemporaryDirectory() as td:
with zipfile.ZipFile(target, "r") as zf:
if "ams.db" not in zf.namelist():
logger.error("ZIP does not contain ams.db")
return 1
zf.extract("ams.db", td)
db_file = Path(td) / "ams.db"
return 0 if verify_sqlite_db(db_file) else 1
elif target.suffix in (".db", ".sqlite", ".sqlite3"):
return 0 if verify_sqlite_db(target) else 1
else:
logger.error("Target must be a .zip archive or .db file")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())