diff --git a/backend/scripts/backup.py b/backend/scripts/backup.py index c81f8f8..7820dff 100644 --- a/backend/scripts/backup.py +++ b/backend/scripts/backup.py @@ -5,7 +5,7 @@ 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 +- 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 @@ -15,12 +15,13 @@ import argparse import datetime import logging import os +from pathlib import Path import shutil import sqlite3 import sys +import tarfile import tempfile import zipfile -from pathlib import Path logging.basicConfig( level=logging.INFO, @@ -30,20 +31,45 @@ logging.basicConfig( 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" - # Support DATABASE_URL environment variable if set (e.g. sqlite:///./data/ams.db or sqlite:///data/ams.db) db_url = os.environ.get("DATABASE_URL", "").strip() - if db_url.startswith("sqlite:///"): - sqlite_file = db_url.replace("sqlite:///", "").lstrip("./") - db_path = Path(sqlite_file) - if not db_path.is_absolute(): - db_path = backend_dir / sqlite_file - else: - db_path = data_dir / "ams.db" + db_path = get_db_path(db_url, backend_dir) upload_env = os.environ.get("UPLOAD_DIR", "").strip() if upload_env: @@ -78,20 +104,35 @@ def verify_sqlite_db(db_file: Path) -> bool: return False -def run_backup( - db_path: Path, - uploads_dir: Path, - backups_dir: Path, +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 ZIP archive.""" + """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 - backups_dir.mkdir(parents=True, exist_ok=True) + 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") - backup_zip_path = backups_dir / f"ams_backup_{timestamp}.zip" + 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" @@ -110,32 +151,47 @@ def run_backup( 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") + # 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) - # 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) + 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( - backups_dir.glob("ams_backup_*.zip"), + list(target_dir.glob("ams_backup_*.tar.gz")) + list(target_dir.glob("ams_backup_*.zip")), key=lambda p: p.stat().st_mtime, reverse=True, ) @@ -147,36 +203,45 @@ def run_backup( except OSError as e: logger.warning("Failed to remove old backup %s: %s", old_backup, e) - return backup_zip_path + return backup_file_path + + +run_backup = create_backup def run_restore( - backup_zip: Path, + backup_archive: 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) + """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_zip) + logger.info("Restoring from archive: %s", backup_archive) with tempfile.TemporaryDirectory() as temp_dir: # Extract archive try: - with zipfile.ZipFile(backup_zip, "r") as zf: - zf.extractall(temp_dir) + 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 zip: %s", e) + logger.error("Failed to read backup archive: %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.") + 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 ams.db failed integrity verification. Aborting restore.") + logger.error("Restored database failed integrity verification. Aborting restore.") return False # Safety backup of current db if exists @@ -221,26 +286,27 @@ def main() -> int: 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 ZIP archive") - restore_parser.add_argument("archive", type=Path, help="Path to backup zip archive") + 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 ZIP archive or .db file to verify") + 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 = run_backup(default_db, default_uploads, default_backups, keep_count=7) + 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 = run_backup(args.db, args.uploads, args.dest, keep_count=args.keep) + 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": @@ -249,19 +315,32 @@ def main() -> int: if args.command == "verify": target = args.target - if target.suffix == ".zip": + 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: - if "ams.db" not in zf.namelist(): - logger.error("ZIP does not contain ams.db") + 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("ams.db", td) - db_file = Path(td) / "ams.db" + 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 .zip archive or .db file") + logger.error("Target must be a .tar.gz/.zip archive or .db file") return 1 return 0 @@ -269,4 +348,3 @@ def main() -> int: if __name__ == "__main__": sys.exit(main()) - diff --git a/backend/tests/test_backup_paths.py b/backend/tests/test_backup_paths.py new file mode 100644 index 0000000..873b1d6 --- /dev/null +++ b/backend/tests/test_backup_paths.py @@ -0,0 +1,76 @@ +import os +from pathlib import Path +import sqlite3 +import tarfile +import pytest + +from scripts.backup import create_backup, get_db_path + + +def test_get_db_path_relative_dot_slash(): + backend_dir = Path("/mock/backend").resolve() + p = get_db_path("sqlite:///./data/ams.db", backend_dir) + assert p == (backend_dir / "data" / "ams.db").resolve() + + +def test_get_db_path_relative_plain(): + backend_dir = Path("/mock/backend").resolve() + p = get_db_path("sqlite:///data/ams.db", backend_dir) + assert p == (backend_dir / "data" / "ams.db").resolve() + + +def test_get_db_path_absolute_app(): + backend_dir = Path("/mock/backend").resolve() + p = get_db_path("sqlite:////app/data/ams.db", backend_dir) + assert p == Path("/app/data/ams.db") + + +def test_get_db_path_absolute_tmp(): + backend_dir = Path("/mock/backend").resolve() + p = get_db_path("sqlite:////tmp/x/custom.db", backend_dir) + assert p == Path("/tmp/x/custom.db") + + +def test_get_db_path_fallbacks(): + backend_dir = Path("/mock/backend").resolve() + default_expected = backend_dir / "data" / "ams.db" + assert get_db_path(None, backend_dir) == default_expected + assert get_db_path("", backend_dir) == default_expected + assert get_db_path("sqlite:///:memory:", backend_dir) == default_expected + assert get_db_path("postgresql://localhost/ams", backend_dir) == default_expected + + +def test_create_backup_real_temp_sqlite_file(tmp_path): + # Create real SQLite file + db_file = tmp_path / "source.db" + conn = sqlite3.connect(str(db_file)) + cur = conn.cursor() + cur.execute("CREATE TABLE test_table (id INTEGER PRIMARY KEY, note TEXT);") + cur.execute("INSERT INTO test_table (note) VALUES ('backup test');") + conn.commit() + conn.close() + + uploads_dir = tmp_path / "uploads" + uploads_dir.mkdir() + (uploads_dir / "sample.pdf").write_bytes(b"%PDF-1.4 sample content") + + dest_dir = tmp_path / "backups" + dest_dir.mkdir() + + # Run backup producing a .tar.gz + archive_path = create_backup( + db_path=db_file, + uploads_dir=uploads_dir, + dest_dir=dest_dir, + archive_format="tar.gz", + ) + assert archive_path is not None + assert archive_path.exists() + assert str(archive_path).endswith(".tar.gz") + + # Verify that the tar.gz is valid and contains db.sqlite3 + with tarfile.open(archive_path, "r:gz") as tf: + names = tf.getnames() + assert "db.sqlite3" in names + assert "ams.db" in names + assert any("uploads/sample.pdf" in n for n in names) diff --git a/docs/ASSUMPTIONS.md b/docs/ASSUMPTIONS.md index f70160c..74dd044 100644 --- a/docs/ASSUMPTIONS.md +++ b/docs/ASSUMPTIONS.md @@ -41,3 +41,4 @@ Items marked "to be confirmed" or left flexible in the proposal are recorded her - **Insurance Policies**: A duplicate insurance policy is defined by trimmed, case-insensitive `policy_no` matching any existing policy in the database. `POST /api/insurance` rejects duplicates with HTTP 409 (`Policy number already exists.`). In bulk import, in-file duplicate rows receive `Duplicate of row N in this file.` and rows duplicating database records receive `Already exists in the system.`. - **Calibration Plans**: Each asset can have at most one calibration plan. In bulk import, rows for assets that already have a calibration plan in the database receive `Asset already has a calibration plan.`, while rows repeating an earlier row for the same asset in the same upload file receive `Duplicate of row N in this file.`. Dry run previews surface these validation errors identically. 25. **Import Template Multi-Sheet Structure (Task 2)**: All four bulk-import templates (Assets, Contracts, Calibration Plans, Insurance Policies) feature an empty data template on Sheet 1 (containing only styled headers), an 'Example' reference on Sheet 2 (with warning banner 'Example only - this sheet is ignored on import' in Row 1 and sample values in Row 2), and 'Master Reference' lookup tables on Sheet 3. All four importers read strictly the first worksheet (`wb.worksheets[0]`), ensuring sample rows and reference sheets are never accidentally imported. +26. **Backup Script Path Resolution & Dual Archive Packaging (Task 3)**: `backend/scripts/backup.py` exposes `get_db_path(db_url, backend_dir)` to accurately resolve SQLite file paths from `DATABASE_URL` across relative paths (`sqlite:///./data/ams.db`, `sqlite:///data/ams.db`), absolute POSIX/Windows paths (`sqlite:////app/data/ams.db`, `sqlite:////tmp/x/custom.db`), and in-memory or fallback scenarios. `create_backup()` supports both `.tar.gz` and `.zip` archives and packages SQLite database files under both `db.sqlite3` and `ams.db` member names for cross-environment compatibility.