Fix greenfield restore: import DB as postgres and verify tables
- Greenfield restore runs dropdb/createdb/pg_restore as local postgres superuser with --role=db_user to avoid permission issues - Abort before upgrade.sh if core NetBox tables are missing after import - Install systemd units before upgrade.sh so error-path restarts work Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
e3f550f17a
commit
a0e3feaff4
1 file changed
+73
-6
+73
-6
@@ -570,10 +570,73 @@ def restore_installation_files(extract_dir, meta, stamp, keep_current_media):
|
||||
return {"mode": "directory", "old_path": old_path, "new_path": netbox_path}
|
||||
|
||||
|
||||
def restore_database(dump_file):
|
||||
def postgres_query(sql, database="postgres"):
|
||||
"""Führt eine SQL-Abfrage als PostgreSQL-Superuser (lokal) aus."""
|
||||
return run_checked(
|
||||
["runuser", "-u", "postgres", "--", "psql", "-d", database, "-v", "ON_ERROR_STOP=1", "-tAc", sql],
|
||||
"psql",
|
||||
cwd="/",
|
||||
).stdout.strip()
|
||||
|
||||
|
||||
def restore_database_as_superuser(dump_file):
|
||||
"""Restore über den lokalen postgres-Superuser (Neuinstallation).
|
||||
|
||||
Vermeidet Rechteprobleme des NetBox-Benutzers; alle Objekte gehören danach db_user.
|
||||
"""
|
||||
user, name = CONFIG["db_user"], CONFIG["db_name"]
|
||||
log_info("Lösche und erstelle Datenbank neu (als postgres)...")
|
||||
run_checked(["runuser", "-u", "postgres", "--", "dropdb", "--if-exists", name], "dropdb", cwd="/")
|
||||
run_checked(["runuser", "-u", "postgres", "--", "createdb", "-O", user, name], "createdb", cwd="/")
|
||||
|
||||
log_info("Importiere Dump...")
|
||||
# Dump per stdin übergeben, da das Temp-Verzeichnis für postgres nicht lesbar ist.
|
||||
with open(dump_file, "rb") as dump_handle:
|
||||
proc = subprocess.run(
|
||||
["runuser", "-u", "postgres", "--", "pg_restore", "-d", name,
|
||||
"--no-owner", "--no-privileges", f"--role={user}"],
|
||||
stdin=dump_handle,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
cwd="/",
|
||||
check=False,
|
||||
)
|
||||
if proc.returncode != 0:
|
||||
log_warn(f"pg_restore wurde mit Code {proc.returncode} beendet:\n{proc.stderr.strip()}")
|
||||
# Sicherheitshalber alles an db_user übertragen.
|
||||
postgres_query(f"REASSIGN OWNED BY postgres TO {sql_identifier(user)}", database=name)
|
||||
|
||||
|
||||
def verify_restored_database():
|
||||
"""Bricht ab, wenn zentrale NetBox-Tabellen nach dem Import fehlen."""
|
||||
env = os.environ.copy()
|
||||
if CONFIG["db_pass"]:
|
||||
env["PGPASSWORD"] = CONFIG["db_pass"]
|
||||
sql = "SELECT count(*) FROM information_schema.tables WHERE table_name IN ('dcim_device','dcim_consoleport','django_migrations')"
|
||||
proc = run_command(
|
||||
["psql", "-h", CONFIG["db_host"], "-U", CONFIG["db_user"], "-d", CONFIG["db_name"], "-tAc", sql],
|
||||
env=env,
|
||||
capture=True,
|
||||
)
|
||||
if proc.returncode != 0 or proc.stdout.strip() != "3":
|
||||
raise RuntimeError(
|
||||
"Datenbank-Import unvollständig: zentrale NetBox-Tabellen fehlen. "
|
||||
"Bitte die pg_restore-Meldungen oben prüfen (häufig: PostgreSQL-Version des Ziels älter als die der Quelle)."
|
||||
)
|
||||
log_success("Datenbank-Import geprüft: zentrale Tabellen vorhanden.")
|
||||
|
||||
|
||||
def restore_database(dump_file, as_superuser=False):
|
||||
if not os.path.exists(dump_file):
|
||||
raise RuntimeError("Ungültiges Backup: netbox_database.dump fehlt.")
|
||||
|
||||
if as_superuser:
|
||||
restore_database_as_superuser(dump_file)
|
||||
verify_restored_database()
|
||||
log_success("Datenbank-Wiederherstellung abgeschlossen.")
|
||||
return
|
||||
|
||||
env = os.environ.copy()
|
||||
if CONFIG["db_pass"]:
|
||||
env["PGPASSWORD"] = CONFIG["db_pass"]
|
||||
@@ -627,6 +690,7 @@ def restore_database(dump_file):
|
||||
f"pg_restore wurde mit Code {proc_restore.returncode} beendet:\n"
|
||||
f"{proc_restore.stderr.strip()}"
|
||||
)
|
||||
verify_restored_database()
|
||||
log_success("Datenbank-Wiederherstellung abgeschlossen.")
|
||||
|
||||
|
||||
@@ -941,22 +1005,25 @@ def execute_restore(components=None, greenfield=None):
|
||||
|
||||
if "db" in selected:
|
||||
log_info("Schritt 3b: Stelle PostgreSQL-Datenbank wieder her...")
|
||||
restore_database(os.path.join(tmp_extract_dir, "netbox_database.dump"))
|
||||
restore_database(
|
||||
os.path.join(tmp_extract_dir, "netbox_database.dump"),
|
||||
as_superuser=bool(greenfield),
|
||||
)
|
||||
|
||||
if "media" in selected:
|
||||
log_info("Schritt 3c: Stelle Media-Dateien wieder her...")
|
||||
restore_media(os.path.join(tmp_extract_dir, "media"))
|
||||
|
||||
if greenfield:
|
||||
log_info("Schritt 3d: Richte systemd-Dienste ein...")
|
||||
greenfield_install_services()
|
||||
|
||||
if "db" in selected or "files" in selected:
|
||||
log_info("Schritt 4: Führe NetBox upgrade.sh aus (venv, Migrationen, Static Files)...")
|
||||
run_netbox_upgrade_script()
|
||||
else:
|
||||
log_info("Schritt 4: upgrade.sh nicht erforderlich (nur Media wiederhergestellt).")
|
||||
|
||||
if greenfield:
|
||||
log_info("Schritt 4a: Richte systemd-Dienste ein...")
|
||||
greenfield_install_services()
|
||||
|
||||
log_info("Schritt 5: Starte NetBox-Dienste neu...")
|
||||
restart_services(strict=True)
|
||||
services_stopped = False
|
||||
|
||||
Reference in new issue
Block a user