fix(backend): make PostgreSQL backup tools portable #31
5 changed files with 326 additions and 83 deletions
92
hesabixAPI/app/core/postgres_tools.py
Normal file
92
hesabixAPI/app/core/postgres_tools.py
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
"""Locate PostgreSQL command-line tools on Windows and POSIX hosts."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
from collections.abc import Mapping
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class PostgreSQLToolNotFoundError(FileNotFoundError):
|
||||
"""Raised when a required PostgreSQL client executable cannot be found."""
|
||||
|
||||
|
||||
def _version_key(path: Path) -> tuple[int, ...]:
|
||||
numbers = re.findall(r"\d+", path.name)
|
||||
return tuple(int(number) for number in numbers) or (0,)
|
||||
|
||||
|
||||
def _installation_bin_dirs(environment: Mapping[str, str], platform: str) -> list[Path]:
|
||||
if platform == "nt":
|
||||
roots: list[Path] = []
|
||||
for variable in ("ProgramFiles", "ProgramFiles(x86)"):
|
||||
value = environment.get(variable)
|
||||
if value:
|
||||
roots.append(Path(value) / "PostgreSQL")
|
||||
|
||||
directories: list[Path] = []
|
||||
for root in roots:
|
||||
try:
|
||||
versions = sorted(
|
||||
(entry for entry in root.iterdir() if entry.is_dir()),
|
||||
key=_version_key,
|
||||
reverse=True,
|
||||
)
|
||||
except OSError:
|
||||
continue
|
||||
directories.extend(version / "bin" for version in versions)
|
||||
return directories
|
||||
|
||||
directories = [Path("/usr/bin"), Path("/usr/local/bin")]
|
||||
version_root = Path("/usr/lib/postgresql")
|
||||
try:
|
||||
versions = sorted(
|
||||
(entry for entry in version_root.iterdir() if entry.is_dir()),
|
||||
key=_version_key,
|
||||
reverse=True,
|
||||
)
|
||||
except OSError:
|
||||
versions = []
|
||||
directories.extend(version / "bin" for version in versions)
|
||||
return directories
|
||||
|
||||
|
||||
def resolve_postgres_tool(
|
||||
tool: str,
|
||||
*,
|
||||
environment: Mapping[str, str] | None = None,
|
||||
platform: str | None = None,
|
||||
) -> Path:
|
||||
"""Resolve ``tool`` without assuming a shell-specific PATH layout.
|
||||
|
||||
``HESABIX_POSTGRES_BIN_DIR`` is authoritative when set. Otherwise the
|
||||
current PATH and common PostgreSQL installation directories are searched.
|
||||
"""
|
||||
environment = environment or os.environ
|
||||
platform = platform or os.name
|
||||
executable_name = f"{tool}.exe" if platform == "nt" else tool
|
||||
|
||||
configured_dir = environment.get("HESABIX_POSTGRES_BIN_DIR", "").strip()
|
||||
if configured_dir:
|
||||
configured_path = Path(configured_dir).expanduser() / executable_name
|
||||
if configured_path.is_file():
|
||||
return configured_path.resolve()
|
||||
raise PostgreSQLToolNotFoundError(
|
||||
f"{tool} was not found in HESABIX_POSTGRES_BIN_DIR: {configured_dir}"
|
||||
)
|
||||
|
||||
path_value = environment.get("PATH")
|
||||
from_path = shutil.which(executable_name, path=path_value)
|
||||
if from_path:
|
||||
return Path(from_path).resolve()
|
||||
|
||||
for directory in _installation_bin_dirs(environment, platform):
|
||||
candidate = directory / executable_name
|
||||
if candidate.is_file():
|
||||
return candidate.resolve()
|
||||
|
||||
raise PostgreSQLToolNotFoundError(
|
||||
f"{tool} was not found. Install PostgreSQL client tools or set HESABIX_POSTGRES_BIN_DIR."
|
||||
)
|
||||
|
|
@ -2,6 +2,7 @@
|
|||
سرویس بکاپ دیتابیس PostgreSQL برای مدیر سیستم.
|
||||
پشتیبانی از سه روش تحویل: دانلود مستقیم، ایمیل، FTP.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
|
|
@ -9,14 +10,14 @@ import io
|
|||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
from datetime import datetime
|
||||
from typing import Literal
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.settings import get_settings
|
||||
from adapters.db.models.file_storage import StorageConfig
|
||||
from app.core.postgres_tools import PostgreSQLToolNotFoundError, resolve_postgres_tool
|
||||
from app.core.settings import get_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
|
@ -43,11 +44,18 @@ class DatabaseBackupService:
|
|||
"""
|
||||
env = os.environ.copy()
|
||||
env["PGPASSWORD"] = self.settings.db_password
|
||||
# سرویس با PATH محدود (فقط .venv/bin) اجرا میشود؛ pg_dump در /usr/bin است
|
||||
env["PATH"] = "/usr/bin:/usr/local/bin:" + env.get("PATH", "")
|
||||
|
||||
try:
|
||||
pg_dump = resolve_postgres_tool("pg_dump", environment=env)
|
||||
except PostgreSQLToolNotFoundError as e:
|
||||
logger.error("database_backup_pg_dump_not_found: %s", e)
|
||||
raise DatabaseBackupError(
|
||||
"ابزار pg_dump یافت نشد. PostgreSQL client tools را نصب کنید یا "
|
||||
"HESABIX_POSTGRES_BIN_DIR را تنظیم کنید."
|
||||
) from e
|
||||
|
||||
cmd = [
|
||||
"pg_dump",
|
||||
str(pg_dump),
|
||||
"-h",
|
||||
self.settings.db_host,
|
||||
"-p",
|
||||
|
|
@ -90,7 +98,8 @@ class DatabaseBackupService:
|
|||
except FileNotFoundError as e:
|
||||
logger.error("database_backup_pg_dump_not_found: %s", e)
|
||||
raise DatabaseBackupError(
|
||||
"ابزار pg_dump یافت نشد. لطفاً PostgreSQL client tools را نصب کنید."
|
||||
"ابزار pg_dump اجرا نشد. PostgreSQL client tools و مقدار "
|
||||
"HESABIX_POSTGRES_BIN_DIR را بررسی کنید."
|
||||
) from e
|
||||
except Exception as e:
|
||||
logger.exception("database_backup_unexpected_error error=%s", str(e))
|
||||
|
|
|
|||
|
|
@ -2,16 +2,19 @@
|
|||
سرویس ریستور کامل دیتابیس PostgreSQL برای مدیر سیستم.
|
||||
از فایل بکاپ .sql یا .sql.gz با pg_dump ایجاد شده استفاده میکند.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
from typing import Callable
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
from app.core.postgres_tools import PostgreSQLToolNotFoundError, resolve_postgres_tool
|
||||
from app.core.settings import get_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
|
@ -36,7 +39,29 @@ class DatabaseRestoreService:
|
|||
def _progress(self, percent: int, message: str) -> None:
|
||||
if self._on_progress:
|
||||
self._on_progress(percent, message)
|
||||
logger.info("database_restore_progress", percent=percent, message=message)
|
||||
logger.info("database_restore_progress percent=%s message=%s", percent, message)
|
||||
|
||||
@staticmethod
|
||||
def _prepare_sql_file(file_path: str, is_gz: bool) -> tuple[str, Path | None]:
|
||||
"""Return a plain SQL path, expanding gzip with Python when needed."""
|
||||
if not is_gz:
|
||||
return file_path, None
|
||||
|
||||
temporary_path: Path | None = None
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(
|
||||
prefix="hesabix-restore-",
|
||||
suffix=".sql",
|
||||
delete=False,
|
||||
) as destination:
|
||||
temporary_path = Path(destination.name)
|
||||
with gzip.open(file_path, "rb") as source:
|
||||
shutil.copyfileobj(source, destination, length=1024 * 1024)
|
||||
return str(temporary_path), temporary_path
|
||||
except Exception:
|
||||
if temporary_path is not None:
|
||||
temporary_path.unlink(missing_ok=True)
|
||||
raise
|
||||
|
||||
def restore(self, file_path: str) -> None:
|
||||
"""
|
||||
|
|
@ -52,17 +77,28 @@ class DatabaseRestoreService:
|
|||
is_sql = basename.endswith(".sql") or is_gz
|
||||
|
||||
if not is_sql:
|
||||
raise DatabaseRestoreError(
|
||||
"فرمت فایل نامعتبر است. فایل باید .sql یا .sql.gz باشد."
|
||||
)
|
||||
raise DatabaseRestoreError("فرمت فایل نامعتبر است. فایل باید .sql یا .sql.gz باشد.")
|
||||
|
||||
env = os.environ.copy()
|
||||
env["PGPASSWORD"] = self.settings.db_password
|
||||
|
||||
try:
|
||||
psql = resolve_postgres_tool("psql", environment=env)
|
||||
except PostgreSQLToolNotFoundError as e:
|
||||
raise DatabaseRestoreError(
|
||||
"ابزار psql یافت نشد. PostgreSQL client tools را نصب کنید یا "
|
||||
"HESABIX_POSTGRES_BIN_DIR را تنظیم کنید."
|
||||
) from e
|
||||
|
||||
try:
|
||||
restore_file_path, temporary_sql_path = self._prepare_sql_file(file_path, is_gz)
|
||||
except (OSError, gzip.BadGzipFile, EOFError) as e:
|
||||
raise DatabaseRestoreError(f"فایل فشرده بکاپ قابل خواندن نیست: {e}") from e
|
||||
|
||||
def run_psql(db_name: str, sql: str, description: str) -> None:
|
||||
result = subprocess.run(
|
||||
[
|
||||
"psql",
|
||||
str(psql),
|
||||
"-h",
|
||||
self.settings.db_host,
|
||||
"-p",
|
||||
|
|
@ -87,86 +123,41 @@ class DatabaseRestoreService:
|
|||
f"{description} ناموفق بود: {stderr or result.stdout or 'خطای نامشخص'}"
|
||||
) from None
|
||||
|
||||
self._progress(5, "قطع اتصالات به دیتابیس")
|
||||
db_name_safe = self.settings.db_name.replace("'", "''")
|
||||
try:
|
||||
run_psql(
|
||||
"postgres",
|
||||
(
|
||||
f"SELECT pg_terminate_backend(pid) FROM pg_stat_activity "
|
||||
f"WHERE datname = '{db_name_safe}' AND pid <> pg_backend_pid();"
|
||||
),
|
||||
"قطع اتصالات",
|
||||
)
|
||||
except DatabaseRestoreError as e:
|
||||
logger.warning("terminate_connections_failed: %s", e)
|
||||
self._progress(10, "ادامه ریستور (قطع اتصالات ناتوان بود)")
|
||||
self._progress(5, "قطع اتصالات به دیتابیس")
|
||||
db_name_safe = self.settings.db_name.replace("'", "''")
|
||||
try:
|
||||
run_psql(
|
||||
"postgres",
|
||||
(
|
||||
f"SELECT pg_terminate_backend(pid) FROM pg_stat_activity "
|
||||
f"WHERE datname = '{db_name_safe}' AND pid <> pg_backend_pid();"
|
||||
),
|
||||
"قطع اتصالات",
|
||||
)
|
||||
except DatabaseRestoreError as e:
|
||||
logger.warning("terminate_connections_failed: %s", e)
|
||||
self._progress(10, "ادامه ریستور (قطع اتصالات ناتوان بود)")
|
||||
|
||||
self._progress(15, "حذف دیتابیس فعلی")
|
||||
db_name_id = self.settings.db_name.replace('"', '""') # for identifier
|
||||
try:
|
||||
self._progress(15, "حذف دیتابیس فعلی")
|
||||
db_name_id = self.settings.db_name.replace('"', '""') # for identifier
|
||||
run_psql(
|
||||
"postgres",
|
||||
f'DROP DATABASE IF EXISTS "{db_name_id}";',
|
||||
"حذف دیتابیس",
|
||||
)
|
||||
except DatabaseRestoreError:
|
||||
raise
|
||||
|
||||
self._progress(25, "ایجاد دیتابیس جدید")
|
||||
try:
|
||||
self._progress(25, "ایجاد دیتابیس جدید")
|
||||
run_psql(
|
||||
"postgres",
|
||||
f'CREATE DATABASE "{db_name_id}";',
|
||||
"ایجاد دیتابیس",
|
||||
)
|
||||
except DatabaseRestoreError:
|
||||
raise
|
||||
|
||||
self._progress(35, "اجرای فایل بکاپ")
|
||||
if is_gz:
|
||||
proc = subprocess.Popen(
|
||||
["gunzip", "-c", file_path],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
env=env,
|
||||
)
|
||||
psql_proc = subprocess.Popen(
|
||||
[
|
||||
"psql",
|
||||
"-h",
|
||||
self.settings.db_host,
|
||||
"-p",
|
||||
str(self.settings.db_port),
|
||||
"-U",
|
||||
self.settings.db_user,
|
||||
"-d",
|
||||
self.settings.db_name,
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
"-f",
|
||||
"-",
|
||||
],
|
||||
stdin=proc.stdout,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
env=env,
|
||||
)
|
||||
proc.stdout.close()
|
||||
out, err = psql_proc.communicate(timeout=7200)
|
||||
if proc.wait(timeout=5) != 0:
|
||||
raise DatabaseRestoreError(
|
||||
f"فشردهسازی ناموفق بود: {(proc.stderr or b'').decode('utf-8', errors='replace')}"
|
||||
)
|
||||
if psql_proc.returncode != 0:
|
||||
err_str = (err or b"").decode("utf-8", errors="replace").strip()
|
||||
raise DatabaseRestoreError(
|
||||
f"اجرای بکاپ ناموفق بود: {err_str[:500]}"
|
||||
)
|
||||
else:
|
||||
self._progress(35, "اجرای فایل بکاپ")
|
||||
result = subprocess.run(
|
||||
[
|
||||
"psql",
|
||||
str(psql),
|
||||
"-h",
|
||||
self.settings.db_host,
|
||||
"-p",
|
||||
|
|
@ -178,7 +169,7 @@ class DatabaseRestoreService:
|
|||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
"-f",
|
||||
file_path,
|
||||
restore_file_path,
|
||||
],
|
||||
env=env,
|
||||
capture_output=True,
|
||||
|
|
@ -187,8 +178,8 @@ class DatabaseRestoreService:
|
|||
)
|
||||
if result.returncode != 0:
|
||||
stderr = (result.stderr or result.stdout or "").strip()
|
||||
raise DatabaseRestoreError(
|
||||
f"اجرای بکاپ ناموفق بود: {stderr[:500]}"
|
||||
)
|
||||
|
||||
self._progress(100, "ریستور با موفقیت انجام شد")
|
||||
raise DatabaseRestoreError(f"اجرای بکاپ ناموفق بود: {stderr[:500]}")
|
||||
self._progress(100, "ریستور با موفقیت انجام شد")
|
||||
finally:
|
||||
if temporary_sql_path is not None:
|
||||
temporary_sql_path.unlink(missing_ok=True)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,83 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.database_backup_service import DatabaseBackupService
|
||||
from app.services.database_restore_service import DatabaseRestoreService
|
||||
|
||||
|
||||
def _settings() -> SimpleNamespace:
|
||||
return SimpleNamespace(
|
||||
db_host="localhost",
|
||||
db_port=5432,
|
||||
db_user="hesabix",
|
||||
db_password="secret-for-test",
|
||||
db_name="hesabix_test",
|
||||
)
|
||||
|
||||
|
||||
def test_backup_uses_resolved_pg_dump_without_rewriting_path(monkeypatch) -> None:
|
||||
service = DatabaseBackupService.__new__(DatabaseBackupService)
|
||||
service.db = None
|
||||
service.settings = _settings()
|
||||
observed: dict[str, object] = {}
|
||||
|
||||
def fake_resolve(tool, *, environment):
|
||||
observed["resolver_path"] = environment.get("PATH")
|
||||
assert tool == "pg_dump"
|
||||
return Path("C:/PostgreSQL/16/bin/pg_dump.exe")
|
||||
|
||||
def fake_run(command, **kwargs):
|
||||
observed["command"] = command
|
||||
observed["run_path"] = kwargs["env"].get("PATH")
|
||||
return subprocess.CompletedProcess(command, 0, stdout=b"SELECT 1;", stderr=b"")
|
||||
|
||||
monkeypatch.setenv("PATH", "original-test-path")
|
||||
monkeypatch.setattr("app.services.database_backup_service.resolve_postgres_tool", fake_resolve)
|
||||
monkeypatch.setattr("app.services.database_backup_service.subprocess.run", fake_run)
|
||||
|
||||
assert service.create_backup(compress=False) == b"SELECT 1;"
|
||||
assert observed["command"][0] == "C:\\PostgreSQL\\16\\bin\\pg_dump.exe"
|
||||
assert observed["resolver_path"] == "original-test-path"
|
||||
assert observed["run_path"] == "original-test-path"
|
||||
|
||||
|
||||
def test_gzip_restore_is_expanded_before_psql_and_temp_file_is_removed(
|
||||
monkeypatch,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
backup_path = tmp_path / "backup.sql.gz"
|
||||
with gzip.open(backup_path, "wb") as compressed:
|
||||
compressed.write(b"SELECT 42;\n")
|
||||
|
||||
service = DatabaseRestoreService.__new__(DatabaseRestoreService)
|
||||
service.settings = _settings()
|
||||
service._on_progress = lambda _percent, _message: None
|
||||
commands: list[list[str]] = []
|
||||
restore_sql_path: Path | None = None
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.database_restore_service.resolve_postgres_tool",
|
||||
lambda tool, *, environment: Path("C:/PostgreSQL/16/bin/psql.exe"),
|
||||
)
|
||||
|
||||
def fake_run(command, **kwargs):
|
||||
nonlocal restore_sql_path
|
||||
commands.append(command)
|
||||
if "-f" in command:
|
||||
restore_sql_path = Path(command[command.index("-f") + 1])
|
||||
assert restore_sql_path != backup_path
|
||||
assert restore_sql_path.read_bytes() == b"SELECT 42;\n"
|
||||
return subprocess.CompletedProcess(command, 0, stdout="", stderr="")
|
||||
|
||||
monkeypatch.setattr("app.services.database_restore_service.subprocess.run", fake_run)
|
||||
|
||||
service.restore(str(backup_path))
|
||||
|
||||
assert len(commands) == 4
|
||||
assert all(command[0].endswith("psql.exe") for command in commands)
|
||||
assert restore_sql_path is not None
|
||||
assert not restore_sql_path.exists()
|
||||
68
hesabixAPI/tests/test_postgres_tools.py
Normal file
68
hesabixAPI/tests/test_postgres_tools.py
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.postgres_tools import PostgreSQLToolNotFoundError, resolve_postgres_tool
|
||||
|
||||
|
||||
def test_configured_windows_bin_directory_is_authoritative(tmp_path: Path) -> None:
|
||||
executable = tmp_path / "psql.exe"
|
||||
executable.write_bytes(b"")
|
||||
|
||||
result = resolve_postgres_tool(
|
||||
"psql",
|
||||
environment={"HESABIX_POSTGRES_BIN_DIR": str(tmp_path), "PATH": ""},
|
||||
platform="nt",
|
||||
)
|
||||
|
||||
assert result == executable.resolve()
|
||||
|
||||
|
||||
def test_invalid_configured_directory_does_not_fall_back_to_path(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
with pytest.raises(PostgreSQLToolNotFoundError, match="HESABIX_POSTGRES_BIN_DIR"):
|
||||
resolve_postgres_tool(
|
||||
"pg_dump",
|
||||
environment={
|
||||
"HESABIX_POSTGRES_BIN_DIR": str(tmp_path / "missing"),
|
||||
"PATH": str(tmp_path),
|
||||
},
|
||||
platform="nt",
|
||||
)
|
||||
|
||||
|
||||
def test_windows_installations_are_searched_newest_first(tmp_path: Path) -> None:
|
||||
old_bin = tmp_path / "PostgreSQL" / "15" / "bin"
|
||||
new_bin = tmp_path / "PostgreSQL" / "16" / "bin"
|
||||
old_bin.mkdir(parents=True)
|
||||
new_bin.mkdir(parents=True)
|
||||
(old_bin / "psql.exe").write_bytes(b"")
|
||||
expected = new_bin / "psql.exe"
|
||||
expected.write_bytes(b"")
|
||||
|
||||
result = resolve_postgres_tool(
|
||||
"psql",
|
||||
environment={"ProgramFiles": str(tmp_path), "PATH": ""},
|
||||
platform="nt",
|
||||
)
|
||||
|
||||
assert result == expected.resolve()
|
||||
|
||||
|
||||
def test_posix_path_resolution_does_not_add_windows_suffix(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
executable = tmp_path / "pg_dump"
|
||||
executable.write_bytes(b"")
|
||||
monkeypatch.setattr(
|
||||
"app.core.postgres_tools.shutil.which",
|
||||
lambda name, path=None: str(executable) if name == "pg_dump" else None,
|
||||
)
|
||||
|
||||
result = resolve_postgres_tool("pg_dump", environment={"PATH": str(tmp_path)}, platform="posix")
|
||||
|
||||
assert result == executable.resolve()
|
||||
Loading…
Reference in a new issue