repair_local_postgres.py 14.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
from __future__ import annotations

import argparse
import os
import shutil
import subprocess
import sys
import tempfile
from dataclasses import dataclass
from pathlib import Path

from services.shared.config.base import PROJECT_ROOT

from .prepare_local_postgres import (
    DatabaseConfig,
    build_database_config,
    connect_database,
    load_effective_env_values,
    probe_target_database,
    resolve_runtime_env_file,
    safe_text,
    test_tcp_port,
    validate_database_config,
)


LOCAL_HOSTS = {"127.0.0.1", "localhost", "::1"}
DEFAULT_PROJECT_LOCAL_PORT = 55432
DEFAULT_CLUSTER_DIR = PROJECT_ROOT / "var" / "db" / "postgres-local"
DEFAULT_LOG_FILE = PROJECT_ROOT / "var" / "logs" / "postgres-local.log"
ENV_KEYS_TO_SYNC = {
    "DB_HOST": "127.0.0.1",
    "DB_DIALECT": "postgresql",
}


@dataclass(frozen=True)
class RepairResult:
    status: str
    message: str
    used_project_cluster: bool = False
    env_file_changed: bool = False
    port: int | None = None


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description=(
            "Repair the pure-local PostgreSQL workflow by provisioning a "
            "project-managed fallback cluster when the system instance is "
            "missing or has mismatched credentials."
        ),
    )
    parser.add_argument(
        "--env-file",
        help="Optional env file override. Defaults to .env.local first, then .env.",
    )
    parser.add_argument(
        "--port",
        type=int,
        default=DEFAULT_PROJECT_LOCAL_PORT,
        help=f"Preferred port for the project-managed fallback cluster. Default: {DEFAULT_PROJECT_LOCAL_PORT}",
    )
    parser.add_argument(
        "--cluster-dir",
        default=str(DEFAULT_CLUSTER_DIR),
        help="Optional PGDATA override for the project-managed fallback cluster.",
    )
    parser.add_argument(
        "--timeout",
        type=float,
        default=3.0,
        help="TCP/database connect timeout in seconds. Default: 3.0",
    )
    return parser.parse_args()


def print_step(message: str) -> None:
    print(f"[postgres-repair] {message}")


def run_command(
    command: list[str],
    *,
    cwd: Path | None = None,
    env: dict[str, str] | None = None,
    check: bool = True,
    capture_output: bool = True,
) -> subprocess.CompletedProcess[str]:
    result = subprocess.run(
        command,
        cwd=cwd,
        env=env,
        capture_output=capture_output,
        text=capture_output,
        encoding="utf-8" if capture_output else None,
        errors="replace" if capture_output else None,
    )
    if check and result.returncode != 0:
        raise RuntimeError(
            f"Command failed ({result.returncode}): {' '.join(command)}\n"
            f"stdout:\n{result.stdout or ''}\n"
            f"stderr:\n{result.stderr or ''}"
        )
    return result


def is_local_postgres_candidate(config: DatabaseConfig) -> bool:
    return config.dialect in {"postgres", "postgresql"} and config.host.lower() in LOCAL_HOSTS


def find_postgres_bin_dir() -> Path | None:
    explicit = os.getenv("BETTAFISH_PG_BIN_DIR")
    candidates: list[Path] = []
    if explicit:
        candidates.append(Path(explicit).expanduser())

    for binary_name in ("pg_ctl", "pg_ctl.exe"):
        binary = shutil.which(binary_name)
        if binary:
            candidates.append(Path(binary).resolve().parent)

    for env_key in ("ProgramFiles", "ProgramFiles(x86)"):
        root = os.getenv(env_key)
        if not root:
            continue
        postgres_root = Path(root) / "PostgreSQL"
        if not postgres_root.exists():
            continue
        candidates.extend(sorted(postgres_root.glob("*/bin"), reverse=True))

    seen: set[str] = set()
    for candidate in candidates:
        key = str(candidate).lower()
        if key in seen:
            continue
        seen.add(key)
        if (candidate / "pg_ctl.exe").exists() and (candidate / "initdb.exe").exists():
            return candidate

    return None


def ensure_cluster_dir_state(cluster_dir: Path) -> None:
    if not cluster_dir.exists():
        cluster_dir.mkdir(parents=True, exist_ok=True)
        return

    if (cluster_dir / "PG_VERSION").exists():
        return

    if any(cluster_dir.iterdir()):
        raise RuntimeError(
            f"Cluster directory exists but is not a PostgreSQL data directory: {cluster_dir}"
        )


def ensure_cluster_initialized(
    *,
    bin_dir: Path,
    cluster_dir: Path,
    user: str,
    password: str,
) -> bool:
    if (cluster_dir / "PG_VERSION").exists():
        return False

    ensure_cluster_dir_state(cluster_dir)
    cluster_dir.mkdir(parents=True, exist_ok=True)
    temp_dir = PROJECT_ROOT / "var" / "tmp"
    temp_dir.mkdir(parents=True, exist_ok=True)

    fd, password_file_raw = tempfile.mkstemp(
        prefix="bettafish-postgres-init-",
        suffix=".pw",
        dir=temp_dir,
        text=True,
    )
    password_file = Path(password_file_raw)
    try:
        with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
            handle.write(password)
            handle.write("\n")

        initdb = str(bin_dir / "initdb.exe")
        result = run_command(
            [
                initdb,
                "-D",
                str(cluster_dir),
                "-U",
                user,
                f"--pwfile={password_file}",
                "--auth=scram-sha-256",
                "--encoding=UTF8",
            ],
        )
        if result.stdout.strip():
            print_step(result.stdout.strip())
        if result.stderr.strip():
            print_step(result.stderr.strip())
        return True
    finally:
        password_file.unlink(missing_ok=True)


def write_cluster_runtime_config(cluster_dir: Path, port: int) -> None:
    auto_conf = cluster_dir / "postgresql.auto.conf"
    auto_conf.write_text(
        "# Managed by scripts.dev.repair_local_postgres\n"
        f"listen_addresses = '127.0.0.1,::1'\n"
        f"port = {port}\n",
        encoding="utf-8",
    )


def pg_ctl_status(bin_dir: Path, cluster_dir: Path) -> int:
    pg_ctl = str(bin_dir / "pg_ctl.exe")
    result = run_command(
        [pg_ctl, "-D", str(cluster_dir), "status"],
        check=False,
        capture_output=False,
    )
    return result.returncode


def stop_cluster(bin_dir: Path, cluster_dir: Path) -> None:
    pg_ctl = str(bin_dir / "pg_ctl.exe")
    run_command(
        [pg_ctl, "-D", str(cluster_dir), "-w", "stop"],
        check=False,
        capture_output=False,
    )


def start_cluster(bin_dir: Path, cluster_dir: Path, log_file: Path) -> None:
    log_file.parent.mkdir(parents=True, exist_ok=True)
    pg_ctl = str(bin_dir / "pg_ctl.exe")
    result = run_command(
        [pg_ctl, "-D", str(cluster_dir), "-l", str(log_file), "-w", "start"],
        check=False,
        capture_output=False,
    )
    if result.returncode != 0:
        raise RuntimeError(
            f"Unable to start project-managed PostgreSQL cluster.\n"
            f"stdout:\n{result.stdout}\n"
            f"stderr:\n{result.stderr}"
        )


def can_connect_to_postgres(
    *,
    user: str,
    password: str,
    port: int,
    timeout: float,
) -> bool:
    config = DatabaseConfig(
        dialect="postgresql",
        host="127.0.0.1",
        port=port,
        user=user,
        password=password,
        database="postgres",
        charset="utf8mb4",
    )
    try:
        with connect_database(config, "postgres", timeout=timeout):
            return True
    except Exception:
        return False


def choose_project_local_port(
    *,
    preferred_port: int,
    user: str,
    password: str,
    timeout: float,
    allow_running_port_reuse: bool,
) -> int:
    for candidate in range(preferred_port, preferred_port + 20):
        if not test_tcp_port("127.0.0.1", candidate, timeout=timeout):
            return candidate
        if allow_running_port_reuse and can_connect_to_postgres(
            user=user,
            password=password,
            port=candidate,
            timeout=timeout,
        ):
            return candidate

    raise RuntimeError(
        f"No usable port was found for the project-managed PostgreSQL cluster "
        f"starting from {preferred_port}."
    )


def update_env_file(path: Path, replacements: dict[str, str]) -> bool:
    original = path.read_text(encoding="utf-8", errors="replace")
    newline = "\r\n" if "\r\n" in original else "\n"
    lines = original.splitlines()
    updated: list[str] = []
    seen: set[str] = set()

    for line in lines:
        stripped = line.strip()
        if not stripped or stripped.startswith("#") or "=" not in line:
            updated.append(line)
            continue

        key, _ = line.split("=", 1)
        key = key.strip()
        if key in replacements:
            updated.append(f"{key}={replacements[key]}")
            seen.add(key)
        else:
            updated.append(line)

    for key, value in replacements.items():
        if key not in seen:
            updated.append(f"{key}={value}")

    rendered = newline.join(updated).rstrip() + newline
    if rendered == original:
        return False

    path.write_text(rendered, encoding="utf-8")
    return True


def run_prepare_local_postgres(env_file: Path, *extra_args: str) -> None:
    env = os.environ.copy()
    env.setdefault("PYTHONIOENCODING", "utf-8")
    env.setdefault("PYTHONUTF8", "1")
    env.setdefault("PYTHONUNBUFFERED", "1")
    command = [
        sys.executable,
        "-X",
        "utf8",
        "-m",
        "scripts.dev.prepare_local_postgres",
        "--env-file",
        str(env_file),
        *extra_args,
    ]
    result = subprocess.run(command, cwd=PROJECT_ROOT, env=env)
    if result.returncode != 0:
        raise RuntimeError(
            f"prepare_local_postgres failed with exit code {result.returncode}"
        )


def ensure_existing_target_schema(env_file: Path) -> RepairResult:
    run_prepare_local_postgres(env_file, "--ensure-db", "--apply-schema")
    return RepairResult(
        status="ready",
        message="Existing PostgreSQL target was reachable and the schema was ensured.",
    )


def ensure_local_postgres_ready(
    env_file: Path,
    *,
    preferred_port: int = DEFAULT_PROJECT_LOCAL_PORT,
    cluster_dir: Path = DEFAULT_CLUSTER_DIR,
    timeout: float = 3.0,
) -> RepairResult:
    values = load_effective_env_values(env_file)
    config = build_database_config(values)

    issues = validate_database_config(config)
    if issues:
        return RepairResult(
            status="skipped",
            message="Current env file still contains placeholder values; skipped PostgreSQL auto-repair.",
        )

    if not is_local_postgres_candidate(config):
        return RepairResult(
            status="skipped",
            message=(
                f"Current database target is {config.dialect} at {config.host}:{config.port}; "
                "project-local PostgreSQL auto-repair only applies to loopback PostgreSQL."
            ),
        )

    if test_tcp_port(config.host, config.port, timeout=timeout):
        ready, status = probe_target_database(config, timeout=timeout)
        if ready:
            return RepairResult(
                status="ready",
                message=f"Current PostgreSQL target is already reachable at {config.host}:{config.port}.",
                port=config.port,
            )
        if status == "missing_database":
            print_step("Current PostgreSQL target is reachable but the database is missing; ensuring schema.")
            return ensure_existing_target_schema(env_file)

    bin_dir = find_postgres_bin_dir()
    if bin_dir is None:
        return RepairResult(
            status="failed",
            message=(
                "PostgreSQL binaries were not found. Install PostgreSQL 15+ or set "
                "BETTAFISH_PG_BIN_DIR to the bin directory."
            ),
        )

    user = config.user
    password = config.password
    cluster_already_initialized = (cluster_dir / "PG_VERSION").exists()
    selected_port = choose_project_local_port(
        preferred_port=preferred_port,
        user=user,
        password=password,
        timeout=timeout,
        allow_running_port_reuse=cluster_already_initialized,
    )

    print_step(
        "Current local PostgreSQL target is unavailable or has mismatched credentials; "
        f"switching to a project-managed fallback cluster on 127.0.0.1:{selected_port}."
    )

    initialized = ensure_cluster_initialized(
        bin_dir=bin_dir,
        cluster_dir=cluster_dir,
        user=user,
        password=password,
    )
    if initialized:
        print_step(f"Initialized project-managed PostgreSQL cluster at {cluster_dir}.")

    write_cluster_runtime_config(cluster_dir, selected_port)

    if pg_ctl_status(bin_dir, cluster_dir) == 0 and not can_connect_to_postgres(
        user=user,
        password=password,
        port=selected_port,
        timeout=timeout,
    ):
        stop_cluster(bin_dir, cluster_dir)

    if pg_ctl_status(bin_dir, cluster_dir) != 0:
        start_cluster(bin_dir, cluster_dir, DEFAULT_LOG_FILE)
        print_step("Project-managed PostgreSQL cluster is running.")

    replacements = dict(ENV_KEYS_TO_SYNC)
    replacements["DB_PORT"] = str(selected_port)
    env_file_changed = update_env_file(env_file, replacements)
    if env_file_changed:
        print_step(
            f"Updated {env_file.name} to use the project-managed PostgreSQL cluster on port {selected_port}."
        )

    run_prepare_local_postgres(env_file, "--ensure-db", "--apply-schema")

    refreshed_values = load_effective_env_values(env_file)
    refreshed_config = build_database_config(refreshed_values)
    ready, status = probe_target_database(refreshed_config, timeout=timeout)
    if not ready:
        return RepairResult(
            status="failed",
            message=f"Project-managed PostgreSQL cluster is running, but final verification failed: {status}",
            used_project_cluster=True,
            env_file_changed=env_file_changed,
            port=selected_port,
        )

    return RepairResult(
        status="repaired",
        message=(
            f"Project-managed PostgreSQL cluster is ready at 127.0.0.1:{selected_port}, "
            "and the BettaFish schema has been initialized."
        ),
        used_project_cluster=True,
        env_file_changed=env_file_changed,
        port=selected_port,
    )


def main() -> int:
    args = parse_args()
    env_file = resolve_runtime_env_file(args.env_file)
    if env_file is None:
        print_step("No env file was found. Copy `.env.local.example` to `.env.local` first.")
        return 1

    try:
        result = ensure_local_postgres_ready(
            env_file,
            preferred_port=args.port,
            cluster_dir=Path(args.cluster_dir).expanduser(),
            timeout=args.timeout,
        )
    except Exception as exc:
        print_step(f"Repair failed: {safe_text(exc)}")
        return 1

    print_step(result.message)
    return 0 if result.status in {"ready", "repaired", "skipped"} else 1


if __name__ == "__main__":
    raise SystemExit(main())