Files

351 lines
14 KiB
Python

#!/usr/bin/env python3
"""
XYZ 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 (and db.sqlite3) + uploads/ directory into a single timestamped archive (.tar.gz or .zip)
- 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
from pathlib import Path
import shutil
import sqlite3
import sys
import tarfile
import tempfile
import zipfile
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_db_path(db_url: str | None, backend_dir: Path) -> Path:
"""Resolve database URL to a filesystem Path.
Rules:
- If db_url is empty, None, or starts with 'sqlite:///:memory:', fall back to backend_dir / 'data' / 'ams.db'
- If it starts with 'sqlite:////' (4 slashes, absolute path), strip 'sqlite:///' and return Path('/app/data/ams.db') (absolute)
- If it starts with 'sqlite:///' (3 slashes), strip 'sqlite:///' and:
- if the remainder starts with '/' (absolute), return Path(remainder)
- if the remainder starts with './' or is a relative path, return (backend_dir / remainder).resolve()
- If it is not a sqlite URL, fall back to backend_dir / 'data' / 'ams.db'
"""
if not db_url or not db_url.strip() or db_url.strip().startswith("sqlite:///:memory:"):
return backend_dir / "data" / "ams.db"
clean_url = db_url.strip()
if not clean_url.startswith("sqlite:///"):
return backend_dir / "data" / "ams.db"
remainder = clean_url[len("sqlite:///"):]
if not remainder or remainder == ":memory:":
return backend_dir / "data" / "ams.db"
if remainder.startswith("/"):
return Path(remainder)
p = Path(remainder)
if p.is_absolute():
return p
return (backend_dir / remainder).resolve()
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_url = os.environ.get("DATABASE_URL", "").strip()
db_path = get_db_path(db_url, backend_dir)
upload_env = os.environ.get("UPLOAD_DIR", "").strip()
if upload_env:
uploads_dir = Path(upload_env)
if not uploads_dir.is_absolute():
uploads_dir = backend_dir / uploads_dir
else:
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 create_backup(
db_path: Path | None = None,
uploads_dir: Path | None = None,
dest_dir: Path | None = None,
backups_dir: Path | None = None,
keep_count: int = 7,
archive_format: str = "tar.gz",
) -> Path | None:
"""Create a consistent online backup of SQLite DB and attachments into a .tar.gz or .zip archive."""
backend_dir = Path(__file__).resolve().parent.parent
if db_path is None:
db_url = os.environ.get("DATABASE_URL")
db_path = get_db_path(db_url, backend_dir)
target_dir = dest_dir or backups_dir or (backend_dir / "data" / "backups")
if not db_path.exists():
logger.error("Source database does not exist at %s", db_path)
return None
if uploads_dir is None:
upload_env = os.environ.get("UPLOAD_DIR", "").strip()
uploads_dir = Path(upload_env) if upload_env else (backend_dir / "data" / "uploads")
target_dir.mkdir(parents=True, exist_ok=True)
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
is_tar = archive_format in ("tar.gz", "tar", "tgz")
ext = "tar.gz" if is_tar else "zip"
backup_file_path = target_dir / f"ams_backup_{timestamp}.{ext}"
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 archive
logger.info("Creating backup archive: %s", backup_file_path)
if is_tar:
with tarfile.open(backup_file_path, "w:gz") as tf:
# Add database under both ams.db and db.sqlite3 for compatibility
tf.add(temp_db_path, arcname="db.sqlite3")
tf.add(temp_db_path, arcname="ams.db")
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)
tf.add(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)
else:
with zipfile.ZipFile(backup_file_path, "w", compression=zipfile.ZIP_DEFLATED) as zf:
zf.write(temp_db_path, arcname="ams.db")
zf.write(temp_db_path, arcname="db.sqlite3")
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_file_path.stat().st_size / (1024 * 1024)
logger.info("Backup successfully completed! File: %s (%.2f MB)", backup_file_path, size_mb)
# 4. Enforce retention policy
if keep_count > 0:
existing_backups = sorted(
list(target_dir.glob("ams_backup_*.tar.gz")) + list(target_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_file_path
run_backup = create_backup
def run_restore(
backup_archive: Path,
db_path: Path,
uploads_dir: Path,
) -> bool:
"""Restore database and uploads from a backup archive (.tar.gz or .zip) with pre-restore safety copy."""
if not backup_archive.exists():
logger.error("Backup archive %s not found.", backup_archive)
return False
logger.info("Restoring from archive: %s", backup_archive)
with tempfile.TemporaryDirectory() as temp_dir:
# Extract archive
try:
if str(backup_archive).endswith((".tar.gz", ".tgz")):
with tarfile.open(backup_archive, "r:gz") as tf:
tf.extractall(temp_dir)
else:
with zipfile.ZipFile(backup_archive, "r") as zf:
zf.extractall(temp_dir)
except Exception as e:
logger.error("Failed to read backup archive: %s", e)
return False
extracted_db = Path(temp_dir) / "ams.db"
if not extracted_db.exists():
extracted_db = Path(temp_dir) / "db.sqlite3"
if not extracted_db.exists():
logger.error("Archive does not contain ams.db or db.sqlite3. Invalid backup.")
return False
if not verify_sqlite_db(extracted_db):
logger.error("Restored database 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="XYZ 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)")
backup_parser.add_argument("--format", choices=["tar.gz", "zip"], default="tar.gz", help="Archive format")
# Restore command
restore_parser = subparsers.add_parser("restore", help="Restore DB and uploads from a backup archive")
restore_parser.add_argument("archive", type=Path, help="Path to backup archive (.tar.gz or .zip)")
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 archive (.tar.gz or .zip) or .db file to verify")
args = parser.parse_args()
# Default to backup if no command provided
if not args.command:
result = create_backup(default_db, default_uploads, default_backups, keep_count=7, archive_format="tar.gz")
return 0 if result is not None else 1
if args.command == "backup":
result = create_backup(args.db, args.uploads, args.dest, keep_count=args.keep, archive_format=args.format)
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 str(target).endswith((".tar.gz", ".tgz")):
with tempfile.TemporaryDirectory() as td:
with tarfile.open(target, "r:gz") as tf:
names = tf.getnames()
db_name = "ams.db" if "ams.db" in names else ("db.sqlite3" if "db.sqlite3" in names else None)
if not db_name:
logger.error("Archive does not contain ams.db or db.sqlite3")
return 1
tf.extract(db_name, td)
db_file = Path(td) / db_name
return 0 if verify_sqlite_db(db_file) else 1
elif target.suffix == ".zip":
with tempfile.TemporaryDirectory() as td:
with zipfile.ZipFile(target, "r") as zf:
names = zf.namelist()
db_name = "ams.db" if "ams.db" in names else ("db.sqlite3" if "db.sqlite3" in names else None)
if not db_name:
logger.error("ZIP does not contain ams.db or db.sqlite3")
return 1
zf.extract(db_name, td)
db_file = Path(td) / db_name
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 .tar.gz/.zip archive or .db file")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())