fix(backup): select restore-compatible PostgreSQL clients (#7638)

This commit is contained in:
Aqr-K
2026-11-27 18:51:01 +08:00
committed by GitHub
parent da978d051c
commit 5cea0898e3
4 changed files with 160 additions and 16 deletions

View File

@@ -5,6 +5,7 @@
from __future__ import annotations
import os
import re
import shutil
import sqlite3
import subprocess
@@ -239,10 +240,10 @@ class PostgreSQLBackupBackend:
def create(self, destination: Path) -> None:
"""
创建 PostgreSQL custom-format 在线备份。
用可向当前服务端还原的客户端创建在线归档。
"""
command = [
self._require_tool(self._pg_dump),
self._restore_compatible_tool(self._pg_dump),
"--format=custom",
"--no-owner",
"--no-acl",
@@ -273,7 +274,7 @@ class PostgreSQLBackupBackend:
在 CLI 离线进程中覆盖当前 PostgreSQL 数据库内容。
"""
command = [
self._require_tool(self._pg_restore),
self._restore_compatible_tool(self._pg_restore),
"--clean",
"--if-exists",
"--no-owner",
@@ -285,6 +286,8 @@ class PostgreSQLBackupBackend:
]
result = self._run(command, include_password=True)
if result.returncode != 0:
if "unsupported version" in result.stderr and "file header" in result.stderr:
raise RuntimeError("当前 pg_restore 无法读取该归档格式,请先在独立空库验证归档转换或使用兼容版本的归档")
raise RuntimeError(f"pg_restore 执行失败,退出码 {result.returncode}")
def _connection_arguments(self) -> list[str]:
@@ -318,11 +321,41 @@ class PostgreSQLBackupBackend:
check=False,
)
def _require_tool(self, executable: str) -> str:
def _restore_compatible_tool(self, executable: str) -> str:
"""
通过当前解析器确认 PostgreSQL 客户端可用。
优先选择与活动库匹配的客户端,拒绝已知不能还原的版本组合。
:param executable: 当前操作使用的 PostgreSQL 客户端名称或路径
:return: 用于本次备份或还原的可执行文件路径
"""
return _require_tool(executable, self._tool_resolver)
with self._engine.connect() as connection:
server = connection.dialect.server_version_info
if not server:
raise RuntimeError("无法识别 PostgreSQL 服务端版本")
major = server[0]
is_tool_name = Path(executable).name == executable
if is_tool_name:
versioned = self._tool_resolver(f"/usr/lib/postgresql/{major}/bin/{executable}")
if versioned:
return versioned
default = _require_tool(executable, self._tool_resolver)
result = self._run([default, "--version"], include_password=False)
client = re.search(r"\(PostgreSQL\)\s+(\d+)(?=\.|\s|$)", result.stdout)
if result.returncode or client is None:
raise RuntimeError("无法识别 PostgreSQL 客户端版本")
client_major = int(client[1])
# 17 起生成的还原脚本含旧服务端无法识别的 transaction_timeout 设置。
if major < 17 <= client_major:
# 镜像内的 16 客户端仍可用于 12 至 15 的宿主数据库。
if is_tool_name and 12 <= major < 16:
compatible = self._tool_resolver(f"/usr/lib/postgresql/16/bin/{executable}")
if compatible:
return compatible
raise RuntimeError(
f"PostgreSQL {client_major} 客户端无法直接还原到 PostgreSQL {major},"
f"请安装 PostgreSQL {major} 客户端后重试"
)
return default
def _environment(self, *, include_password: bool) -> dict[str, str]:
"""

View File

@@ -99,6 +99,7 @@ RUN apt-get update \
nano \
unar \
supervisor \
postgresql-client-16 \
postgresql-client-18 \
libchromaprint-tools \
libjemalloc2 \

View File

@@ -6,6 +6,7 @@ from __future__ import annotations
import sqlite3
import subprocess
from contextlib import closing
from pathlib import Path
from types import SimpleNamespace
from typing import Any
@@ -95,6 +96,8 @@ class _Runner:
"""
command = list(command)
self.calls.append((command, kwargs))
if command[1:] == ["--version"]:
return subprocess.CompletedProcess(command, 0, f"{command[0]} (PostgreSQL) 18.7", "")
if "--file" in command:
Path(command[command.index("--file") + 1]).write_bytes(b"PGDMP")
stdout = "; archive listing" if command[:2] == ["pg_restore", "--list"] else ""
@@ -117,19 +120,70 @@ class _FailedRunner:
return subprocess.CompletedProcess(command, 1, "", "invalid archive")
def _postgres_backend(runner: _Runner) -> PostgreSQLBackupBackend:
@pytest.mark.parametrize("stderr, diagnostic", [
("pg_restore: error: unsupported version (1.16) in file header", "独立空库验证归档"),
("pg_restore: transaction failed", "pg_restore 执行失败,退出码 1"),
])
def test_postgresql_restore_failure_preserves_diagnostic(tmp_path, stderr, diagnostic):
"""
旧客户端的归档错误提供可行的恢复路径,其他错误仍返回真实退出状态。
"""
archive = tmp_path / "legacy.dump"
archive.write_bytes(b"PGDMP")
supported = _Runner()
def runner(command, **kwargs):
"""
只有还原命令失败,版本查询沿用真实 CLI 格式。
"""
if "--clean" in command:
return subprocess.CompletedProcess(command, 1, "", stderr)
return supported(command, **kwargs)
with pytest.raises(RuntimeError, match=diagnostic):
_postgres_backend(runner).restore(archive)
def test_postgresql_backup_rejects_empty_archive_even_after_success(tmp_path):
"""
进程退出成功但归档为空时,备份不能进入恢复清单。
"""
supported = _Runner()
def runner(command, **kwargs):
"""
让客户端返回成功,但不产生备份数据。
"""
result = supported(command, **kwargs)
if "--file" in command:
Path(command[command.index("--file") + 1]).write_bytes(b"")
return result
with pytest.raises(RuntimeError, match="未生成有效的备份文件"):
_postgres_backend(runner).create(tmp_path / "empty.dump")
def _postgres_backend(runner: _Runner, *, server_major: int = 18,
installed_client: int | None = None) -> PostgreSQLBackupBackend:
engine = SimpleNamespace(
url=make_url(
"postgresql://moviepilot:secret@database.internal:5432/moviepilot"
"?sslmode=require"
),
dispose=Mock(),
connect=Mock(return_value=closing(SimpleNamespace(
dialect=SimpleNamespace(server_version_info=(server_major, 14)), close=Mock(),
))),
)
return PostgreSQLBackupBackend(
engine,
runner=runner,
tool_resolver=lambda executable: executable,
)
def resolve(executable: str) -> str | None:
"""
模拟 PATH 中的 18 客户端,以及可选的系统版本目录。
"""
if not executable.startswith("/") or executable.startswith(f"/usr/lib/postgresql/{installed_client}/bin/"):
return executable
return None
return PostgreSQLBackupBackend(engine, runner=runner, tool_resolver=resolve)
def test_postgresql_backup_keeps_password_out_of_command_and_file(tmp_path: Path) -> None:
@@ -142,7 +196,7 @@ def test_postgresql_backup_keeps_password_out_of_command_and_file(tmp_path: Path
backend.create(artifact)
command, kwargs = runner.calls[0]
command, kwargs = runner.calls[-1]
assert "--format=custom" in command
assert "secret" not in " ".join(command)
assert kwargs["env"]["PGPASSWORD"] == "secret"
@@ -163,7 +217,7 @@ def test_postgresql_verify_and_restore_use_pg_restore(tmp_path: Path) -> None:
backend.restore(artifact)
verify_command, verify_kwargs = runner.calls[0]
restore_command, restore_kwargs = runner.calls[1]
restore_command, restore_kwargs = runner.calls[-1]
assert verify_command == ["pg_restore", "--list", str(artifact)]
assert "PGPASSWORD" not in verify_kwargs["env"]
assert "--single-transaction" in restore_command
@@ -171,6 +225,58 @@ def test_postgresql_verify_and_restore_use_pg_restore(tmp_path: Path) -> None:
assert restore_kwargs["env"]["PGPASSWORD"] == "secret"
def test_postgresql_16_prefers_matching_clients_for_backup_and_restore(tmp_path: Path) -> None:
"""
服务器为 PostgreSQL 16 时使用同大版本工具,避开 PATH 中默认的 PostgreSQL 18 客户端。
"""
runner = _Runner()
backend = _postgres_backend(runner, server_major=16, installed_client=16)
artifact = tmp_path / "backup.dump"
backend.create(artifact)
backend.restore(artifact)
assert [cmd[0] for cmd, _ in runner.calls] == [
"/usr/lib/postgresql/16/bin/pg_dump",
"/usr/lib/postgresql/16/bin/pg_restore",
]
@pytest.mark.parametrize("server_major", [12, 13, 14, 15])
def test_older_postgresql_uses_compatible_packaged_client(tmp_path: Path, server_major: int) -> None:
"""
升级常见旧版本时,从 PATH 中的 18 客户端回退到镜像版本目录中的 16 客户端。
"""
runner = _Runner()
backend = _postgres_backend(runner, server_major=server_major, installed_client=16)
artifact = tmp_path / "backup.dump"
backend.create(artifact)
backend.restore(artifact)
dump, restore = [cmd for cmd, _ in runner.calls if cmd[1:] != ["--version"]]
assert dump[0] == "/usr/lib/postgresql/16/bin/pg_dump"
assert restore[0] == "/usr/lib/postgresql/16/bin/pg_restore"
assert artifact.read_bytes() == b"PGDMP"
def test_postgresql_16_rejects_unsupported_clients_before_writing(tmp_path: Path) -> None:
"""
只有 PostgreSQL 18 工具时,数据库和归档都不应被修改。
"""
runner = _Runner()
backend = _postgres_backend(runner, server_major=16)
artifact = tmp_path / "backup.dump"
with pytest.raises(RuntimeError, match="请安装 PostgreSQL 16 客户端"):
backend.create(artifact)
assert not artifact.exists()
with pytest.raises(RuntimeError, match="请安装 PostgreSQL 16 客户端"):
backend.restore(artifact)
assert [cmd for cmd, _ in runner.calls] == [["pg_dump", "--version"], ["pg_restore", "--version"]]
assert all("PGPASSWORD" not in kwargs["env"] for _, kwargs in runner.calls)
def test_postgresql_backup_can_be_verified_without_active_engine(tmp_path: Path) -> None:
"""
PostgreSQL 归档校验只依赖 pg_restore,不连接活动数据库。
@@ -234,6 +340,9 @@ def test_postgresql_source_install_reports_missing_native_client() -> None:
engine = SimpleNamespace(
url=make_url("postgresql://moviepilot:secret@database/moviepilot"),
dispose=Mock(),
connect=Mock(return_value=closing(SimpleNamespace(
dialect=SimpleNamespace(server_version_info=(16, 14)), close=Mock(),
))),
)
backend = PostgreSQLBackupBackend(
engine,

View File

@@ -6,7 +6,7 @@ import re
from pathlib import Path
def test_runtime_image_installs_postgresql_18_client_from_pgdg() -> None:
def test_runtime_image_installs_postgresql_clients_from_pgdg() -> None:
"""
Trixie 镜像必须从签名的 PGDG 源安装固定主版本客户端。
"""
@@ -33,7 +33,8 @@ def test_runtime_image_installs_postgresql_18_client_from_pgdg() -> None:
assert f"chmod 0644 {keyring}" in dockerfile
assert f"signed-by={keyring}" in dockerfile
assert "https://apt.postgresql.org/pub/repos/apt trixie-pgdg main" in dockerfile
assert re.search(r"^\s+postgresql-client-18 \\$", dockerfile, re.MULTILINE)
for major in (16, 18):
assert re.search(rf"^\s+postgresql-client-{major} \\$", dockerfile, re.MULTILINE)
assert not re.search(r"^\s+postgresql-client \\$", dockerfile, re.MULTILINE)