Add full installation backup, restore menu and pre-upgrade backup
- Backups can now include a complete copy of the NetBox installation files (configuration, local_requirements.txt, LDAP, scripts, reports) with permissions, owners and symlinks recorded in a manifest - New restore menu: full restore or database/media/installation files individually, backup selection from backup_dir, backup info view - Restore stops services before touching the database and keeps the previous installation when restoring files - Upgrade automatically creates a full backup before any change - Backup ZIPs are created with mode 600 - English README, German README moved to README.de.md and updated Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
cb32ebd7d8
commit
81ce2ab392
4 files changed
+2072
-731
No files matched your search
@@ -0,0 +1 @@
|
|||||||
|
__pycache__/
|
||||||
+1114
File diff suppressed because it is too large.
Load diff
+572
-164
@@ -3,6 +3,7 @@ import json
|
|||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import shutil
|
import shutil
|
||||||
|
import stat
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
import tarfile
|
import tarfile
|
||||||
@@ -44,6 +45,12 @@ DEFAULT_PLUGIN_REQUIREMENTS = (
|
|||||||
)
|
)
|
||||||
LDAP_REQUIREMENT = "django-auth-ldap"
|
LDAP_REQUIREMENT = "django-auth-ldap"
|
||||||
|
|
||||||
|
BACKUP_FORMAT_VERSION = "1.3"
|
||||||
|
# Relativ zum NetBox-Verzeichnis: werden nicht als Installationsdateien gesichert.
|
||||||
|
# venv und static erzeugt upgrade.sh neu, Media wird separat gesichert.
|
||||||
|
FILES_EXCLUDE_DIRS = ("venv", "netbox/media", "netbox/static")
|
||||||
|
FILES_EXCLUDE_NAMES = ("__pycache__",)
|
||||||
|
|
||||||
|
|
||||||
# ==========================================
|
# ==========================================
|
||||||
# Hilfsfunktionen für die Shell-GUI
|
# Hilfsfunktionen für die Shell-GUI
|
||||||
@@ -178,26 +185,115 @@ def execute_backup():
|
|||||||
)
|
)
|
||||||
|
|
||||||
do_media = input("\n 2. Media-Dateien (Bilder/Dokumente) sichern? (J/n): ").strip().lower() != "n"
|
do_media = input("\n 2. Media-Dateien (Bilder/Dokumente) sichern? (J/n): ").strip().lower() != "n"
|
||||||
|
do_files = (
|
||||||
|
input(
|
||||||
|
"\n 3. Installationsdateien (Konfiguration, local_requirements.txt, Skripte, "
|
||||||
|
"Reports, ...) sichern? (J/n): "
|
||||||
|
)
|
||||||
|
.strip()
|
||||||
|
.lower()
|
||||||
|
!= "n"
|
||||||
|
)
|
||||||
|
|
||||||
if not do_db and not do_media:
|
if not do_db and not do_media and not do_files:
|
||||||
log_warn("Keine Komponenten zum Sichern ausgewählt. Abbruch.")
|
log_warn("Keine Komponenten zum Sichern ausgewählt. Abbruch.")
|
||||||
pause()
|
pause()
|
||||||
return
|
return
|
||||||
|
|
||||||
media_path = os.path.join(CONFIG["netbox_path"], "netbox/media")
|
try:
|
||||||
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
zip_file_path = create_backup(
|
||||||
archive_name = f"netbox_backup_{stamp}"
|
do_db=do_db,
|
||||||
zip_file_path = os.path.join(CONFIG["backup_dir"], f"{archive_name}.zip")
|
do_media=do_media,
|
||||||
tmp_dir = os.path.join(CONFIG["backup_dir"], f"nb_tmp_{stamp}")
|
do_files=do_files,
|
||||||
|
exclude_changelog=exclude_changelog,
|
||||||
|
exclude_users=exclude_users,
|
||||||
|
)
|
||||||
|
print("\n" + "=" * 60)
|
||||||
|
log_success("BACKUP ERFOLGREICH ABGESCHLOSSEN!")
|
||||||
|
log_success(f"Datei liegt hier: {zip_file_path}")
|
||||||
|
print("=" * 60)
|
||||||
|
except Exception as exc:
|
||||||
|
log_error(f"Kritischer Fehler: {exc}")
|
||||||
|
pause()
|
||||||
|
|
||||||
os.makedirs(tmp_dir, exist_ok=True)
|
|
||||||
|
def _manifest_entry(full_path, rel_path, kind):
|
||||||
|
file_stat = os.lstat(full_path)
|
||||||
|
entry = {
|
||||||
|
"path": rel_path,
|
||||||
|
"type": kind,
|
||||||
|
"mode": stat.S_IMODE(file_stat.st_mode),
|
||||||
|
"uid": file_stat.st_uid,
|
||||||
|
"gid": file_stat.st_gid,
|
||||||
|
}
|
||||||
|
if kind == "symlink":
|
||||||
|
entry["target"] = os.readlink(full_path)
|
||||||
|
return entry
|
||||||
|
|
||||||
|
|
||||||
|
def collect_installation_files(root):
|
||||||
|
"""Sammelt alle Dateien der Installation (ohne venv, Media, static und Caches).
|
||||||
|
|
||||||
|
Liefert eine Liste (absoluter Pfad, relativer Pfad) der zu sichernden Dateien
|
||||||
|
sowie ein Manifest mit Rechten, Besitzern und Symlinks.
|
||||||
|
"""
|
||||||
|
files = []
|
||||||
|
manifest = [_manifest_entry(root, ".", "dir")]
|
||||||
|
|
||||||
|
for current, dirnames, filenames in os.walk(root, followlinks=False):
|
||||||
|
rel_dir = os.path.relpath(current, root)
|
||||||
|
rel_dir = "" if rel_dir == "." else rel_dir.replace(os.sep, "/")
|
||||||
|
|
||||||
|
kept_dirs = []
|
||||||
|
for name in sorted(dirnames):
|
||||||
|
rel_path = f"{rel_dir}/{name}" if rel_dir else name
|
||||||
|
full_path = os.path.join(current, name)
|
||||||
|
if name in FILES_EXCLUDE_NAMES or rel_path in FILES_EXCLUDE_DIRS:
|
||||||
|
continue
|
||||||
|
if os.path.islink(full_path):
|
||||||
|
manifest.append(_manifest_entry(full_path, rel_path, "symlink"))
|
||||||
|
continue
|
||||||
|
manifest.append(_manifest_entry(full_path, rel_path, "dir"))
|
||||||
|
kept_dirs.append(name)
|
||||||
|
dirnames[:] = kept_dirs
|
||||||
|
|
||||||
|
for name in sorted(filenames):
|
||||||
|
rel_path = f"{rel_dir}/{name}" if rel_dir else name
|
||||||
|
full_path = os.path.join(current, name)
|
||||||
|
if os.path.islink(full_path):
|
||||||
|
manifest.append(_manifest_entry(full_path, rel_path, "symlink"))
|
||||||
|
continue
|
||||||
|
if not os.path.isfile(full_path):
|
||||||
|
continue
|
||||||
|
manifest.append(_manifest_entry(full_path, rel_path, "file"))
|
||||||
|
files.append((full_path, rel_path))
|
||||||
|
|
||||||
|
return files, manifest
|
||||||
|
|
||||||
|
|
||||||
|
def create_backup(
|
||||||
|
do_db=True,
|
||||||
|
do_media=True,
|
||||||
|
do_files=True,
|
||||||
|
exclude_changelog=False,
|
||||||
|
exclude_users=False,
|
||||||
|
name_prefix="netbox_backup",
|
||||||
|
):
|
||||||
|
"""Erstellt ein ZIP-Backup und gibt dessen Pfad zurück. Wirft bei Fehlern eine Exception."""
|
||||||
|
netbox_root = os.path.realpath(CONFIG["netbox_path"])
|
||||||
|
media_path = os.path.join(netbox_root, "netbox", "media")
|
||||||
|
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||||
|
|
||||||
|
os.makedirs(CONFIG["backup_dir"], exist_ok=True)
|
||||||
|
zip_file_path = unique_path(os.path.join(CONFIG["backup_dir"], f"{name_prefix}_{stamp}.zip"))
|
||||||
|
tmp_dir = tempfile.mkdtemp(prefix=f"nb_tmp_{stamp}_", dir=CONFIG["backup_dir"])
|
||||||
|
zip_created = False
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 1. Datenbank-Dump
|
# 1. Datenbank-Dump
|
||||||
|
dump_file = os.path.join(tmp_dir, "netbox_database.dump")
|
||||||
if do_db:
|
if do_db:
|
||||||
log_info("\nSchritt 1: Erstelle PostgreSQL-Datenbank-Dump...")
|
log_info("\nSchritt 1: Erstelle PostgreSQL-Datenbank-Dump...")
|
||||||
dump_file = os.path.join(tmp_dir, "netbox_database.dump")
|
|
||||||
|
|
||||||
env = os.environ.copy()
|
env = os.environ.copy()
|
||||||
if CONFIG["db_pass"]:
|
if CONFIG["db_pass"]:
|
||||||
env["PGPASSWORD"] = CONFIG["db_pass"]
|
env["PGPASSWORD"] = CONFIG["db_pass"]
|
||||||
@@ -231,7 +327,6 @@ def execute_backup():
|
|||||||
log_info(" -> Benutzer-Daten werden übersprungen.")
|
log_info(" -> Benutzer-Daten werden übersprungen.")
|
||||||
|
|
||||||
process = run_command(cmd, env=env, capture=True)
|
process = run_command(cmd, env=env, capture=True)
|
||||||
|
|
||||||
if process.returncode != 0:
|
if process.returncode != 0:
|
||||||
log_error(f"pg_dump fehlgeschlagen: {process.stderr}")
|
log_error(f"pg_dump fehlgeschlagen: {process.stderr}")
|
||||||
raise RuntimeError("Datenbank-Backup fehlgeschlagen.")
|
raise RuntimeError("Datenbank-Backup fehlgeschlagen.")
|
||||||
@@ -240,196 +335,439 @@ def execute_backup():
|
|||||||
log_info("\nSchritt 1: Datenbank-Backup übersprungen.")
|
log_info("\nSchritt 1: Datenbank-Backup übersprungen.")
|
||||||
|
|
||||||
# 2. Media-Dateien
|
# 2. Media-Dateien
|
||||||
|
media_files = []
|
||||||
if do_media:
|
if do_media:
|
||||||
log_info("Schritt 2: Kopiere Media-Dateien (Bilder, Dokumente)...")
|
log_info("Schritt 2: Sammle Media-Dateien (Bilder, Dokumente)...")
|
||||||
if os.path.exists(media_path):
|
if os.path.isdir(media_path):
|
||||||
dst_media = os.path.join(tmp_dir, "media")
|
for current, _, filenames in os.walk(media_path):
|
||||||
shutil.copytree(media_path, dst_media, dirs_exist_ok=True)
|
for filename in filenames:
|
||||||
log_success("Media-Ordner erfolgreich gesichert.")
|
full_path = os.path.join(current, filename)
|
||||||
|
if os.path.isfile(full_path):
|
||||||
|
rel_path = os.path.relpath(full_path, media_path).replace(os.sep, "/")
|
||||||
|
media_files.append((full_path, rel_path))
|
||||||
|
log_success(f"{len(media_files)} Media-Dateien gefunden.")
|
||||||
else:
|
else:
|
||||||
log_warn(f"Kein Media-Verzeichnis unter {media_path} gefunden.")
|
log_warn(f"Kein Media-Verzeichnis unter {media_path} gefunden.")
|
||||||
else:
|
else:
|
||||||
log_info("Schritt 2: Media-Backup übersprungen.")
|
log_info("Schritt 2: Media-Backup übersprungen.")
|
||||||
|
|
||||||
# 3. Metadaten
|
# 3. Installationsdateien
|
||||||
log_info("Schritt 3: Erstelle Metadaten...")
|
install_files = []
|
||||||
|
manifest = []
|
||||||
|
if do_files:
|
||||||
|
log_info(f"Schritt 3: Sammle Installationsdateien aus {netbox_root} ...")
|
||||||
|
if not os.path.isdir(netbox_root):
|
||||||
|
raise RuntimeError(f"NetBox-Verzeichnis nicht gefunden: {netbox_root}")
|
||||||
|
install_files, manifest = collect_installation_files(netbox_root)
|
||||||
|
log_info(
|
||||||
|
" -> Ausgenommen: " + ", ".join(FILES_EXCLUDE_DIRS + FILES_EXCLUDE_NAMES)
|
||||||
|
+ " (werden von upgrade.sh neu erzeugt bzw. separat gesichert)"
|
||||||
|
)
|
||||||
|
log_success(f"{len(install_files)} Installationsdateien gefunden.")
|
||||||
|
else:
|
||||||
|
log_info("Schritt 3: Sicherung der Installationsdateien übersprungen.")
|
||||||
|
|
||||||
|
# 4. Metadaten
|
||||||
|
log_info("Schritt 4: Erstelle Metadaten...")
|
||||||
meta = {
|
meta = {
|
||||||
"version": "1.2",
|
"version": BACKUP_FORMAT_VERSION,
|
||||||
"timestamp": stamp,
|
"timestamp": stamp,
|
||||||
"source_db": CONFIG["db_name"],
|
"source_db": CONFIG["db_name"],
|
||||||
|
"netbox_path": CONFIG["netbox_path"],
|
||||||
|
"netbox_root": netbox_root,
|
||||||
|
"netbox_version": detect_netbox_version(netbox_root) if os.path.isdir(netbox_root) else None,
|
||||||
"contains_db": do_db,
|
"contains_db": do_db,
|
||||||
"contains_media": do_media,
|
"contains_media": do_media,
|
||||||
|
"contains_files": do_files,
|
||||||
"excluded_changelog": exclude_changelog,
|
"excluded_changelog": exclude_changelog,
|
||||||
"excluded_users": exclude_users,
|
"excluded_users": exclude_users,
|
||||||
}
|
}
|
||||||
with open(os.path.join(tmp_dir, "metadata.json"), "w", encoding="utf-8") as file_handle:
|
|
||||||
json.dump(meta, file_handle, indent=4)
|
|
||||||
|
|
||||||
# 4. ZIP erstellen
|
# 5. ZIP erstellen (nur für root lesbar, da Konfiguration und Dump Geheimnisse enthalten)
|
||||||
log_info(f"Schritt 4: Komprimiere Daten nach {zip_file_path} ...")
|
log_info(f"Schritt 5: Komprimiere Daten nach {zip_file_path} ...")
|
||||||
with zipfile.ZipFile(zip_file_path, "w", zipfile.ZIP_DEFLATED) as zipf:
|
fd = os.open(zip_file_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||||
for root, _, files in os.walk(tmp_dir):
|
zip_created = True
|
||||||
for filename in files:
|
with os.fdopen(fd, "wb") as raw_handle, zipfile.ZipFile(
|
||||||
full_path = os.path.join(root, filename)
|
raw_handle, "w", zipfile.ZIP_DEFLATED, allowZip64=True
|
||||||
rel_path = os.path.relpath(full_path, tmp_dir)
|
) as zipf:
|
||||||
zipf.write(full_path, rel_path)
|
zipf.writestr("metadata.json", json.dumps(meta, indent=4))
|
||||||
|
if do_db:
|
||||||
print("\n" + "=" * 60)
|
zipf.write(dump_file, "netbox_database.dump")
|
||||||
log_success("BACKUP ERFOLGREICH ABGESCHLOSSEN!")
|
for full_path, rel_path in media_files:
|
||||||
log_success(f"Datei liegt hier: {zip_file_path}")
|
zipf.write(full_path, f"media/{rel_path}")
|
||||||
print("=" * 60)
|
if do_files:
|
||||||
|
zipf.writestr("files_manifest.json", json.dumps(manifest, indent=1))
|
||||||
except Exception as exc:
|
for full_path, rel_path in install_files:
|
||||||
log_error(f"Kritischer Fehler: {exc}")
|
zipf.write(full_path, f"files/{rel_path}")
|
||||||
|
except Exception:
|
||||||
|
if zip_created and os.path.exists(zip_file_path):
|
||||||
|
os.remove(zip_file_path)
|
||||||
|
raise
|
||||||
finally:
|
finally:
|
||||||
if os.path.exists(tmp_dir):
|
if os.path.exists(tmp_dir):
|
||||||
shutil.rmtree(tmp_dir)
|
shutil.rmtree(tmp_dir)
|
||||||
pause()
|
|
||||||
|
return zip_file_path
|
||||||
|
|
||||||
|
|
||||||
def execute_restore():
|
# ==========================================
|
||||||
|
# Kernfunktionen: Restore
|
||||||
|
# ==========================================
|
||||||
|
def list_backups():
|
||||||
|
backup_dir = CONFIG["backup_dir"]
|
||||||
|
if not os.path.isdir(backup_dir):
|
||||||
|
return []
|
||||||
|
candidates = [
|
||||||
|
os.path.join(backup_dir, name)
|
||||||
|
for name in os.listdir(backup_dir)
|
||||||
|
if name.startswith("netbox_") and name.endswith(".zip")
|
||||||
|
]
|
||||||
|
return sorted(candidates, key=os.path.getmtime, reverse=True)
|
||||||
|
|
||||||
|
|
||||||
|
def choose_backup_file():
|
||||||
|
backups = list_backups()
|
||||||
|
if backups:
|
||||||
|
log_info(f"Gefundene Backups in {CONFIG['backup_dir']}:")
|
||||||
|
for index, path in enumerate(backups, 1):
|
||||||
|
size_mb = os.path.getsize(path) / (1024 * 1024)
|
||||||
|
modified = datetime.fromtimestamp(os.path.getmtime(path)).strftime("%Y-%m-%d %H:%M")
|
||||||
|
print(f" {Colors.BOLD}{index}.{Colors.ENDC} {os.path.basename(path)} ({size_mb:.1f} MB, {modified})")
|
||||||
|
else:
|
||||||
|
log_info(f"Keine Backups in {CONFIG['backup_dir']} gefunden.")
|
||||||
|
|
||||||
|
raw = input("\nNummer oder Pfad zur Backup-ZIP-Datei (leer = Abbruch): ").strip()
|
||||||
|
if not raw:
|
||||||
|
return None
|
||||||
|
if raw.isdigit() and backups and 1 <= int(raw) <= len(backups):
|
||||||
|
return backups[int(raw) - 1]
|
||||||
|
if os.path.isfile(raw):
|
||||||
|
return raw
|
||||||
|
log_error(f"Die Datei '{raw}' existiert nicht!")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def read_backup_metadata(path):
|
||||||
|
with zipfile.ZipFile(path, "r") as zipf:
|
||||||
|
names = set(zipf.namelist())
|
||||||
|
if "metadata.json" not in names:
|
||||||
|
raise RuntimeError("Ungültiges Backup: metadata.json fehlt.")
|
||||||
|
meta = json.loads(zipf.read("metadata.json").decode("utf-8"))
|
||||||
|
meta.setdefault("contains_db", True)
|
||||||
|
meta.setdefault("contains_media", True)
|
||||||
|
meta.setdefault("contains_files", any(name.startswith("files/") for name in names))
|
||||||
|
return meta
|
||||||
|
|
||||||
|
|
||||||
|
def show_backup_info(path, meta):
|
||||||
|
def yes_no(value):
|
||||||
|
return "ja" if value else "nein"
|
||||||
|
|
||||||
|
print()
|
||||||
|
log_info(f"Backup: {path}")
|
||||||
|
print(f" Erstellt: {meta.get('timestamp', 'unbekannt')}")
|
||||||
|
print(f" Format-Version: {meta.get('version', 'unbekannt')}")
|
||||||
|
print(f" NetBox-Version: {meta.get('netbox_version') or 'unbekannt'}")
|
||||||
|
print(f" Quell-Datenbank: {meta.get('source_db', 'unbekannt')}")
|
||||||
|
print(f" Datenbank: {yes_no(meta.get('contains_db'))}")
|
||||||
|
if meta.get("contains_db"):
|
||||||
|
print(f" ohne Changelog: {yes_no(meta.get('excluded_changelog'))}")
|
||||||
|
print(f" ohne Benutzer: {yes_no(meta.get('excluded_users'))}")
|
||||||
|
print(f" Media-Dateien: {yes_no(meta.get('contains_media'))}")
|
||||||
|
print(f" Installation: {yes_no(meta.get('contains_files'))}")
|
||||||
|
|
||||||
|
|
||||||
|
def apply_manifest(root, manifest):
|
||||||
|
"""Stellt Symlinks, Besitzer und Rechte gemäß Backup-Manifest wieder her."""
|
||||||
|
for entry in manifest:
|
||||||
|
rel_path = entry.get("path", ".")
|
||||||
|
path = root if rel_path in ("", ".") else os.path.join(root, *rel_path.split("/"))
|
||||||
|
|
||||||
|
if entry.get("type") == "symlink":
|
||||||
|
if os.path.lexists(path):
|
||||||
|
continue
|
||||||
|
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||||
|
os.symlink(entry["target"], path)
|
||||||
|
if hasattr(os, "lchown"):
|
||||||
|
try:
|
||||||
|
os.lchown(path, entry["uid"], entry["gid"])
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
continue
|
||||||
|
|
||||||
|
if entry.get("type") == "dir":
|
||||||
|
os.makedirs(path, exist_ok=True)
|
||||||
|
if not os.path.lexists(path):
|
||||||
|
continue
|
||||||
|
if hasattr(os, "chown"):
|
||||||
|
try:
|
||||||
|
os.chown(path, entry["uid"], entry["gid"])
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
os.chmod(path, entry["mode"])
|
||||||
|
|
||||||
|
|
||||||
|
def restore_installation_files(extract_dir, meta, stamp, keep_current_media):
|
||||||
|
"""Ersetzt die NetBox-Installation durch die Dateien aus dem Backup.
|
||||||
|
|
||||||
|
Die bisherige Installation bleibt erhalten (umbenannt bzw. als altes Symlink-Ziel).
|
||||||
|
"""
|
||||||
|
source = os.path.join(extract_dir, "files")
|
||||||
|
if not os.path.isdir(source):
|
||||||
|
raise RuntimeError("Ungültiges Backup: Ordner files/ fehlt.")
|
||||||
|
manifest_file = os.path.join(extract_dir, "files_manifest.json")
|
||||||
|
manifest = []
|
||||||
|
if os.path.isfile(manifest_file):
|
||||||
|
with open(manifest_file, "r", encoding="utf-8") as file_handle:
|
||||||
|
manifest = json.load(file_handle)
|
||||||
|
else:
|
||||||
|
log_warn("Kein files_manifest.json im Backup; Rechte/Besitzer bleiben Standard.")
|
||||||
|
|
||||||
|
if not os.path.isfile(os.path.join(source, "netbox", "netbox", "configuration.py")):
|
||||||
|
raise RuntimeError("Backup enthält keine netbox/netbox/configuration.py.")
|
||||||
|
if not os.path.isfile(os.path.join(source, "upgrade.sh")):
|
||||||
|
raise RuntimeError("Backup enthält kein upgrade.sh und ist nicht plausibel.")
|
||||||
|
|
||||||
|
netbox_path = os.path.abspath(CONFIG["netbox_path"])
|
||||||
|
parent = os.path.dirname(netbox_path.rstrip("/")) or "/"
|
||||||
|
current_root = os.path.realpath(netbox_path) if os.path.lexists(netbox_path) else None
|
||||||
|
|
||||||
|
staged = unique_path(os.path.join(parent, f".netbox-restore-{stamp}"))
|
||||||
|
shutil.move(source, staged)
|
||||||
|
apply_manifest(staged, manifest)
|
||||||
|
|
||||||
|
if keep_current_media and current_root:
|
||||||
|
current_media = os.path.join(current_root, "netbox", "media")
|
||||||
|
if os.path.isdir(current_media):
|
||||||
|
copy_directory_contents_preserve(current_media, os.path.join(staged, "netbox", "media"))
|
||||||
|
log_info(" -> Aktuelle Media-Dateien in die wiederhergestellte Installation übernommen.")
|
||||||
|
|
||||||
|
if os.path.islink(netbox_path):
|
||||||
|
old_link_target = os.readlink(netbox_path)
|
||||||
|
version = meta.get("netbox_version") or "unknown"
|
||||||
|
final_path = unique_path(os.path.join(parent, f"netbox-{version}-restored-{stamp}"))
|
||||||
|
os.rename(staged, final_path)
|
||||||
|
temporary_link = unique_path(os.path.join(parent, f".netbox-link-{stamp}"))
|
||||||
|
os.symlink(final_path, temporary_link)
|
||||||
|
os.replace(temporary_link, netbox_path)
|
||||||
|
return {
|
||||||
|
"mode": "symlink",
|
||||||
|
"old_link_target": old_link_target,
|
||||||
|
"old_path": current_root,
|
||||||
|
"new_path": final_path,
|
||||||
|
}
|
||||||
|
|
||||||
|
old_path = None
|
||||||
|
if os.path.lexists(netbox_path):
|
||||||
|
old_path = unique_path(f"{netbox_path.rstrip('/')}_before_restore_{stamp}")
|
||||||
|
os.rename(netbox_path, old_path)
|
||||||
|
try:
|
||||||
|
os.rename(staged, netbox_path)
|
||||||
|
except Exception:
|
||||||
|
if old_path:
|
||||||
|
os.rename(old_path, netbox_path)
|
||||||
|
raise
|
||||||
|
return {"mode": "directory", "old_path": old_path, "new_path": netbox_path}
|
||||||
|
|
||||||
|
|
||||||
|
def restore_database(dump_file):
|
||||||
|
if not os.path.exists(dump_file):
|
||||||
|
raise RuntimeError("Ungültiges Backup: netbox_database.dump fehlt.")
|
||||||
|
|
||||||
|
env = os.environ.copy()
|
||||||
|
if CONFIG["db_pass"]:
|
||||||
|
env["PGPASSWORD"] = CONFIG["db_pass"]
|
||||||
|
|
||||||
|
log_info("Lösche und erstelle Datenbank neu (Bereinigung)...")
|
||||||
|
drop_proc = run_command(
|
||||||
|
["dropdb", "-h", CONFIG["db_host"], "-U", CONFIG["db_user"], "--if-exists", CONFIG["db_name"]],
|
||||||
|
env=env,
|
||||||
|
capture=True,
|
||||||
|
)
|
||||||
|
if drop_proc.returncode != 0:
|
||||||
|
raise RuntimeError(f"dropdb fehlgeschlagen: {drop_proc.stderr.strip()}")
|
||||||
|
|
||||||
|
create_proc = run_command(
|
||||||
|
[
|
||||||
|
"createdb",
|
||||||
|
"-h",
|
||||||
|
CONFIG["db_host"],
|
||||||
|
"-U",
|
||||||
|
CONFIG["db_user"],
|
||||||
|
"-O",
|
||||||
|
CONFIG["db_user"],
|
||||||
|
CONFIG["db_name"],
|
||||||
|
],
|
||||||
|
env=env,
|
||||||
|
capture=True,
|
||||||
|
)
|
||||||
|
if create_proc.returncode != 0:
|
||||||
|
raise RuntimeError(f"createdb fehlgeschlagen: {create_proc.stderr.strip()}")
|
||||||
|
|
||||||
|
log_info("Importiere Dump...")
|
||||||
|
proc_restore = run_command(
|
||||||
|
[
|
||||||
|
"pg_restore",
|
||||||
|
"-h",
|
||||||
|
CONFIG["db_host"],
|
||||||
|
"-U",
|
||||||
|
CONFIG["db_user"],
|
||||||
|
"-d",
|
||||||
|
CONFIG["db_name"],
|
||||||
|
"--clean",
|
||||||
|
"--if-exists",
|
||||||
|
"--no-owner",
|
||||||
|
dump_file,
|
||||||
|
],
|
||||||
|
env=env,
|
||||||
|
capture=True,
|
||||||
|
)
|
||||||
|
if proc_restore.returncode != 0:
|
||||||
|
log_warn(
|
||||||
|
f"pg_restore wurde mit Code {proc_restore.returncode} beendet:\n"
|
||||||
|
f"{proc_restore.stderr.strip()}"
|
||||||
|
)
|
||||||
|
log_success("Datenbank-Wiederherstellung abgeschlossen.")
|
||||||
|
|
||||||
|
|
||||||
|
def restore_media(source_media):
|
||||||
|
media_path = os.path.join(CONFIG["netbox_path"], "netbox", "media")
|
||||||
|
if not os.path.isdir(source_media):
|
||||||
|
log_warn("Backup enthält laut Metadaten Media-Dateien, der Ordner fehlt jedoch.")
|
||||||
|
return
|
||||||
|
if os.path.exists(media_path):
|
||||||
|
shutil.rmtree(media_path)
|
||||||
|
shutil.copytree(source_media, media_path)
|
||||||
|
run_command(["chown", "-R", "netbox:netbox", media_path], capture=True)
|
||||||
|
log_success("Media-Dateien wiederhergestellt.")
|
||||||
|
|
||||||
|
|
||||||
|
def run_netbox_upgrade_script():
|
||||||
|
upgrade_script = os.path.join(CONFIG["netbox_path"], "upgrade.sh")
|
||||||
|
if not os.path.exists(upgrade_script):
|
||||||
|
log_warn(f"Kein upgrade.sh unter {upgrade_script} gefunden.")
|
||||||
|
return
|
||||||
|
upgrade_env = os.environ.copy()
|
||||||
|
if CONFIG.get("python_path"):
|
||||||
|
upgrade_env["PYTHON"] = CONFIG["python_path"]
|
||||||
|
upgrade_proc = run_command(
|
||||||
|
[upgrade_script],
|
||||||
|
env=upgrade_env,
|
||||||
|
cwd=CONFIG["netbox_path"],
|
||||||
|
capture=False,
|
||||||
|
)
|
||||||
|
if upgrade_proc.returncode != 0:
|
||||||
|
raise RuntimeError(f"upgrade.sh fehlgeschlagen (Code {upgrade_proc.returncode}).")
|
||||||
|
log_success("Upgrade-Skript erfolgreich durchgelaufen.")
|
||||||
|
|
||||||
|
|
||||||
|
RESTORE_COMPONENT_LABELS = {
|
||||||
|
"files": "Installationsdateien",
|
||||||
|
"db": "Datenbank",
|
||||||
|
"media": "Media-Dateien",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def execute_restore(components=None):
|
||||||
|
"""Stellt die gewählten Komponenten wieder her (None = alles, was im Backup enthalten ist)."""
|
||||||
print_header("RESTORE PROZESS")
|
print_header("RESTORE PROZESS")
|
||||||
log_warn("ACHTUNG: Dieser Vorgang überschreibt bestehende Daten auf der Ziel-Instanz!")
|
|
||||||
confirm = input("Bist du sicher, dass du fortfahren möchtest? (j/N): ")
|
|
||||||
|
|
||||||
if confirm.lower() != "j":
|
if os.name != "posix" or os.geteuid() != 0:
|
||||||
|
log_error("Der Restore muss unter Linux als root bzw. mit sudo ausgeführt werden.")
|
||||||
|
pause()
|
||||||
|
return
|
||||||
|
|
||||||
|
restore_file = choose_backup_file()
|
||||||
|
if not restore_file:
|
||||||
|
pause()
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
meta = read_backup_metadata(restore_file)
|
||||||
|
except Exception as exc:
|
||||||
|
log_error(f"Backup kann nicht gelesen werden: {exc}")
|
||||||
|
pause()
|
||||||
|
return
|
||||||
|
|
||||||
|
available = {key: bool(meta.get(f"contains_{key}")) for key in RESTORE_COMPONENT_LABELS}
|
||||||
|
requested = set(available) if components is None else set(components)
|
||||||
|
selected = [key for key in RESTORE_COMPONENT_LABELS if key in requested and available[key]]
|
||||||
|
for key in requested:
|
||||||
|
if not available[key] and components is not None:
|
||||||
|
log_warn(f"{RESTORE_COMPONENT_LABELS[key]} sind in diesem Backup nicht enthalten.")
|
||||||
|
if not selected:
|
||||||
|
log_error("Im Backup ist nichts Passendes zum Wiederherstellen enthalten.")
|
||||||
|
pause()
|
||||||
|
return
|
||||||
|
|
||||||
|
show_backup_info(restore_file, meta)
|
||||||
|
|
||||||
|
backup_version = meta.get("netbox_version")
|
||||||
|
installed_version = (
|
||||||
|
detect_netbox_version(os.path.realpath(CONFIG["netbox_path"]))
|
||||||
|
if os.path.isdir(CONFIG["netbox_path"])
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
if "db" in selected and "files" not in selected and backup_version and installed_version:
|
||||||
|
if version_tuple(backup_version) > version_tuple(installed_version):
|
||||||
|
log_warn(
|
||||||
|
f"Die Datenbank stammt von NetBox v{backup_version}, installiert ist v{installed_version}. "
|
||||||
|
"Ältere NetBox-Versionen können neuere Datenbankschemata nicht verwenden. "
|
||||||
|
"Ggf. zusätzlich die Installationsdateien wiederherstellen."
|
||||||
|
)
|
||||||
|
|
||||||
|
print()
|
||||||
|
log_warn("ACHTUNG: Dieser Vorgang überschreibt bestehende Daten auf dieser Instanz!")
|
||||||
|
log_info("Wird wiederhergestellt: " + ", ".join(RESTORE_COMPONENT_LABELS[key] for key in selected))
|
||||||
|
if input("Bist du sicher, dass du fortfahren möchtest? (j/N): ").strip().lower() != "j":
|
||||||
log_info("Abbruch durch Benutzer.")
|
log_info("Abbruch durch Benutzer.")
|
||||||
pause()
|
pause()
|
||||||
return
|
return
|
||||||
|
|
||||||
restore_file = input("\nPfad zur Backup-ZIP-Datei (z. B. /tmp/netbox_backup.zip): ").strip()
|
|
||||||
|
|
||||||
if not restore_file or not os.path.exists(restore_file):
|
|
||||||
log_error(f"Die Datei '{restore_file}' existiert nicht!")
|
|
||||||
pause()
|
|
||||||
return
|
|
||||||
|
|
||||||
media_path = os.path.join(CONFIG["netbox_path"], "netbox/media")
|
|
||||||
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||||
tmp_extract_dir = f"/tmp/nb_restore_{stamp}"
|
os.makedirs(CONFIG["backup_dir"], exist_ok=True)
|
||||||
os.makedirs(tmp_extract_dir, exist_ok=True)
|
tmp_extract_dir = tempfile.mkdtemp(prefix=f"nb_restore_{stamp}_", dir=CONFIG["backup_dir"])
|
||||||
|
services_stopped = False
|
||||||
|
file_switch = None
|
||||||
|
|
||||||
try:
|
try:
|
||||||
log_info(f"\nSchritt 1: Entpacke {restore_file} ...")
|
log_info(f"\nSchritt 1: Entpacke {restore_file} ...")
|
||||||
with zipfile.ZipFile(restore_file, "r") as zipf:
|
with zipfile.ZipFile(restore_file, "r") as zipf:
|
||||||
safe_extract_zip(zipf, tmp_extract_dir)
|
safe_extract_zip(zipf, tmp_extract_dir)
|
||||||
|
|
||||||
meta_file = os.path.join(tmp_extract_dir, "metadata.json")
|
log_info("Schritt 2: Stoppe NetBox-Dienste...")
|
||||||
if not os.path.exists(meta_file):
|
stop_services()
|
||||||
raise RuntimeError("Ungültiges Backup: metadata.json fehlt.")
|
services_stopped = True
|
||||||
|
|
||||||
with open(meta_file, "r", encoding="utf-8") as file_handle:
|
if "files" in selected:
|
||||||
meta = json.load(file_handle)
|
log_info("Schritt 3a: Stelle Installationsdateien wieder her...")
|
||||||
|
file_switch = restore_installation_files(
|
||||||
# 2. Datenbank-Restore
|
tmp_extract_dir,
|
||||||
if meta.get("contains_db", True):
|
meta,
|
||||||
log_info("Schritt 2: Stelle PostgreSQL-Datenbank wieder her...")
|
stamp,
|
||||||
dump_file = os.path.join(tmp_extract_dir, "netbox_database.dump")
|
keep_current_media="media" not in selected,
|
||||||
if not os.path.exists(dump_file):
|
|
||||||
raise RuntimeError("Ungültiges Backup: netbox_database.dump fehlt.")
|
|
||||||
|
|
||||||
env = os.environ.copy()
|
|
||||||
if CONFIG["db_pass"]:
|
|
||||||
env["PGPASSWORD"] = CONFIG["db_pass"]
|
|
||||||
|
|
||||||
log_info("Lösche und erstelle Datenbank neu (Bereinigung)...")
|
|
||||||
drop_proc = run_command(
|
|
||||||
[
|
|
||||||
"dropdb",
|
|
||||||
"-h",
|
|
||||||
CONFIG["db_host"],
|
|
||||||
"-U",
|
|
||||||
CONFIG["db_user"],
|
|
||||||
"--if-exists",
|
|
||||||
CONFIG["db_name"],
|
|
||||||
],
|
|
||||||
env=env,
|
|
||||||
capture=True,
|
|
||||||
)
|
)
|
||||||
if drop_proc.returncode != 0:
|
log_success(f"Installation wiederhergestellt unter: {file_switch['new_path']}")
|
||||||
raise RuntimeError(f"dropdb fehlgeschlagen: {drop_proc.stderr.strip()}")
|
if file_switch.get("old_path"):
|
||||||
|
log_info(f" -> Bisherige Installation verbleibt unter: {file_switch['old_path']}")
|
||||||
|
|
||||||
create_proc = run_command(
|
if "db" in selected:
|
||||||
[
|
log_info("Schritt 3b: Stelle PostgreSQL-Datenbank wieder her...")
|
||||||
"createdb",
|
restore_database(os.path.join(tmp_extract_dir, "netbox_database.dump"))
|
||||||
"-h",
|
|
||||||
CONFIG["db_host"],
|
|
||||||
"-U",
|
|
||||||
CONFIG["db_user"],
|
|
||||||
"-O",
|
|
||||||
CONFIG["db_user"],
|
|
||||||
CONFIG["db_name"],
|
|
||||||
],
|
|
||||||
env=env,
|
|
||||||
capture=True,
|
|
||||||
)
|
|
||||||
if create_proc.returncode != 0:
|
|
||||||
raise RuntimeError(f"createdb fehlgeschlagen: {create_proc.stderr.strip()}")
|
|
||||||
|
|
||||||
log_info("Importiere Dump...")
|
if "media" in selected:
|
||||||
proc_restore = run_command(
|
log_info("Schritt 3c: Stelle Media-Dateien wieder her...")
|
||||||
[
|
restore_media(os.path.join(tmp_extract_dir, "media"))
|
||||||
"pg_restore",
|
|
||||||
"-h",
|
|
||||||
CONFIG["db_host"],
|
|
||||||
"-U",
|
|
||||||
CONFIG["db_user"],
|
|
||||||
"-d",
|
|
||||||
CONFIG["db_name"],
|
|
||||||
"--clean",
|
|
||||||
"--no-owner",
|
|
||||||
dump_file,
|
|
||||||
],
|
|
||||||
env=env,
|
|
||||||
capture=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
if proc_restore.returncode != 0:
|
if "db" in selected or "files" in selected:
|
||||||
log_warn(
|
log_info("Schritt 4: Führe NetBox upgrade.sh aus (venv, Migrationen, Static Files)...")
|
||||||
f"pg_restore wurde mit Code {proc_restore.returncode} beendet:\n"
|
run_netbox_upgrade_script()
|
||||||
f"{proc_restore.stderr.strip()}"
|
|
||||||
)
|
|
||||||
log_success("Datenbank-Wiederherstellung abgeschlossen.")
|
|
||||||
else:
|
else:
|
||||||
log_info("Schritt 2: Übersprungen (Keine Datenbank im Backup enthalten).")
|
log_info("Schritt 4: upgrade.sh nicht erforderlich (nur Media wiederhergestellt).")
|
||||||
|
|
||||||
# 3. Media-Restore
|
|
||||||
if meta.get("contains_media", True):
|
|
||||||
log_info("Schritt 3: Stelle Media-Dateien wieder her...")
|
|
||||||
src_media = os.path.join(tmp_extract_dir, "media")
|
|
||||||
if os.path.exists(src_media):
|
|
||||||
if os.path.exists(media_path):
|
|
||||||
shutil.rmtree(media_path)
|
|
||||||
shutil.copytree(src_media, media_path, dirs_exist_ok=True)
|
|
||||||
run_command(["chown", "-R", "netbox:netbox", media_path], capture=True)
|
|
||||||
log_success("Media-Dateien wiederhergestellt.")
|
|
||||||
else:
|
|
||||||
log_warn("Backup enthält laut Metadaten Media-Dateien, der Ordner fehlt jedoch.")
|
|
||||||
else:
|
|
||||||
log_info("Schritt 3: Übersprungen (Keine Media-Dateien im Backup enthalten).")
|
|
||||||
|
|
||||||
# 4. NetBox upgrade.sh
|
|
||||||
log_info("Schritt 4: Führe NetBox upgrade.sh aus (Cache-Clear & Migrationen)...")
|
|
||||||
upgrade_script = os.path.join(CONFIG["netbox_path"], "upgrade.sh")
|
|
||||||
if os.path.exists(upgrade_script):
|
|
||||||
upgrade_env = os.environ.copy()
|
|
||||||
if CONFIG.get("python_path"):
|
|
||||||
upgrade_env["PYTHON"] = CONFIG["python_path"]
|
|
||||||
upgrade_proc = run_command(
|
|
||||||
[upgrade_script],
|
|
||||||
env=upgrade_env,
|
|
||||||
cwd=CONFIG["netbox_path"],
|
|
||||||
capture=False,
|
|
||||||
)
|
|
||||||
if upgrade_proc.returncode != 0:
|
|
||||||
raise RuntimeError(f"upgrade.sh fehlgeschlagen (Code {upgrade_proc.returncode}).")
|
|
||||||
log_success("Upgrade-Skript erfolgreich durchgelaufen.")
|
|
||||||
else:
|
|
||||||
log_warn(f"Kein upgrade.sh unter {upgrade_script} gefunden.")
|
|
||||||
|
|
||||||
# 5. Services-Restart
|
|
||||||
log_info("Schritt 5: Starte NetBox-Dienste neu...")
|
log_info("Schritt 5: Starte NetBox-Dienste neu...")
|
||||||
restart_services(strict=True)
|
restart_services(strict=True)
|
||||||
|
services_stopped = False
|
||||||
|
|
||||||
print("\n" + "=" * 60)
|
print("\n" + "=" * 60)
|
||||||
log_success("RESTORE ERFOLGREICH ABGESCHLOSSEN!")
|
log_success("RESTORE ERFOLGREICH ABGESCHLOSSEN!")
|
||||||
@@ -437,12 +775,54 @@ def execute_restore():
|
|||||||
|
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
log_error(f"Fehler beim Restore: {exc}")
|
log_error(f"Fehler beim Restore: {exc}")
|
||||||
|
if file_switch and file_switch.get("old_path"):
|
||||||
|
log_info(f"Vorherige Installation liegt weiterhin unter: {file_switch['old_path']}")
|
||||||
|
if services_stopped:
|
||||||
|
restart_services(strict=False)
|
||||||
finally:
|
finally:
|
||||||
if os.path.exists(tmp_extract_dir):
|
if os.path.exists(tmp_extract_dir):
|
||||||
shutil.rmtree(tmp_extract_dir)
|
shutil.rmtree(tmp_extract_dir)
|
||||||
pause()
|
pause()
|
||||||
|
|
||||||
|
|
||||||
|
def show_backup_details():
|
||||||
|
print_header("BACKUP-INHALT ANZEIGEN")
|
||||||
|
restore_file = choose_backup_file()
|
||||||
|
if restore_file:
|
||||||
|
try:
|
||||||
|
show_backup_info(restore_file, read_backup_metadata(restore_file))
|
||||||
|
except Exception as exc:
|
||||||
|
log_error(f"Backup kann nicht gelesen werden: {exc}")
|
||||||
|
pause()
|
||||||
|
|
||||||
|
|
||||||
|
def restore_menu():
|
||||||
|
while True:
|
||||||
|
print_header("RESTORE-MENÜ")
|
||||||
|
print(f" {Colors.BOLD}1.{Colors.ENDC} Komplett-Restore (alles, was im Backup enthalten ist)")
|
||||||
|
print(f" {Colors.BOLD}2.{Colors.ENDC} Nur Datenbank wiederherstellen")
|
||||||
|
print(f" {Colors.BOLD}3.{Colors.ENDC} Nur Media-Dateien wiederherstellen")
|
||||||
|
print(f" {Colors.BOLD}4.{Colors.ENDC} Nur Installationsdateien wiederherstellen")
|
||||||
|
print(f" {Colors.BOLD}5.{Colors.ENDC} Backup-Inhalt anzeigen")
|
||||||
|
print(f" {Colors.BOLD}6.{Colors.ENDC} Zurück zum Hauptmenü\n")
|
||||||
|
|
||||||
|
choice = input(Colors.BOLD + "Wähle eine Aktion (1-6): " + Colors.ENDC).strip()
|
||||||
|
actions = {
|
||||||
|
"1": lambda: execute_restore(None),
|
||||||
|
"2": lambda: execute_restore({"db"}),
|
||||||
|
"3": lambda: execute_restore({"media"}),
|
||||||
|
"4": lambda: execute_restore({"files"}),
|
||||||
|
"5": show_backup_details,
|
||||||
|
}
|
||||||
|
if choice == "6":
|
||||||
|
return
|
||||||
|
if choice in actions:
|
||||||
|
actions[choice]()
|
||||||
|
return
|
||||||
|
log_error("Ungültige Eingabe.")
|
||||||
|
time.sleep(1)
|
||||||
|
|
||||||
|
|
||||||
# ==========================================
|
# ==========================================
|
||||||
# Kernfunktionen: NetBox-Upgrade
|
# Kernfunktionen: NetBox-Upgrade
|
||||||
# ==========================================
|
# ==========================================
|
||||||
@@ -864,13 +1244,24 @@ def execute_upgrade():
|
|||||||
)
|
)
|
||||||
|
|
||||||
print()
|
print()
|
||||||
log_warn("Vor jedem Upgrade sind ein aktuelles Datenbank-/Media-Backup und die Release Notes Pflicht.")
|
|
||||||
log_info(f"Release Notes: https://github.com/netbox-community/netbox/releases/tag/v{target_version}")
|
log_info(f"Release Notes: https://github.com/netbox-community/netbox/releases/tag/v{target_version}")
|
||||||
if input("Backup erstellt und Release Notes geprüft? (j/N): ").strip().lower() != "j":
|
if input("Release Notes geprüft? (j/N): ").strip().lower() != "j":
|
||||||
log_info("Upgrade abgebrochen. Bitte zuerst Backup und Release Notes prüfen.")
|
log_info("Upgrade abgebrochen. Bitte zuerst die Release Notes prüfen.")
|
||||||
pause()
|
pause()
|
||||||
return
|
return
|
||||||
|
|
||||||
|
log_info(
|
||||||
|
"Vor dem Upgrade wird automatisch ein vollständiges Backup "
|
||||||
|
"(Datenbank, Media und Installationsdateien) erstellt."
|
||||||
|
)
|
||||||
|
skip_backup = False
|
||||||
|
if input("Automatisches Backup überspringen? (j/N): ").strip().lower() == "j":
|
||||||
|
log_warn("Ohne Backup ist bei fehlgeschlagenen Migrationen keine Wiederherstellung möglich!")
|
||||||
|
if input("Wirklich OHNE Backup fortfahren? Zur Bestätigung 'OHNE BACKUP' eingeben: ").strip() != "OHNE BACKUP":
|
||||||
|
log_info("Backup wird erstellt.")
|
||||||
|
else:
|
||||||
|
skip_backup = True
|
||||||
|
|
||||||
include_plugins = (
|
include_plugins = (
|
||||||
input("Genannte Standard-Plugins in local_requirements.txt ergänzen? (J/n): ")
|
input("Genannte Standard-Plugins in local_requirements.txt ergänzen? (J/n): ")
|
||||||
.strip()
|
.strip()
|
||||||
@@ -929,6 +1320,7 @@ def execute_upgrade():
|
|||||||
switch_state = None
|
switch_state = None
|
||||||
services_stopped = False
|
services_stopped = False
|
||||||
upgrade_started = False
|
upgrade_started = False
|
||||||
|
backup_file = None
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if not shutil.which("cp"):
|
if not shutil.which("cp"):
|
||||||
@@ -937,6 +1329,16 @@ def execute_upgrade():
|
|||||||
raise RuntimeError("Der Befehl 'systemctl' wurde nicht gefunden.")
|
raise RuntimeError("Der Befehl 'systemctl' wurde nicht gefunden.")
|
||||||
|
|
||||||
os.makedirs(CONFIG["backup_dir"], exist_ok=True)
|
os.makedirs(CONFIG["backup_dir"], exist_ok=True)
|
||||||
|
|
||||||
|
if skip_backup:
|
||||||
|
log_warn("Schritt 0: Backup auf Wunsch übersprungen.")
|
||||||
|
else:
|
||||||
|
log_info("Schritt 0: Erstelle Backup vor dem Upgrade...")
|
||||||
|
if not shutil.which("pg_dump"):
|
||||||
|
raise RuntimeError("Der Befehl 'pg_dump' wurde nicht gefunden; Backup nicht möglich.")
|
||||||
|
backup_file = create_backup(name_prefix=f"netbox_pre_upgrade_v{target_version}")
|
||||||
|
log_success(f"Backup erstellt: {backup_file}")
|
||||||
|
|
||||||
fd, archive_path = tempfile.mkstemp(
|
fd, archive_path = tempfile.mkstemp(
|
||||||
prefix=f"netbox-v{target_version}-",
|
prefix=f"netbox-v{target_version}-",
|
||||||
suffix=".tar.gz",
|
suffix=".tar.gz",
|
||||||
@@ -1053,7 +1455,13 @@ def execute_upgrade():
|
|||||||
"Datenbank-Migrationen könnten bereits angewendet worden sein."
|
"Datenbank-Migrationen könnten bereits angewendet worden sein."
|
||||||
)
|
)
|
||||||
log_info(f"Vorherige Installation liegt weiterhin unter: {switch_state['old_path']}")
|
log_info(f"Vorherige Installation liegt weiterhin unter: {switch_state['old_path']}")
|
||||||
log_info("Für einen vollständigen Rollback Datenbank/Media aus dem Backup wiederherstellen.")
|
if backup_file:
|
||||||
|
log_info(
|
||||||
|
"Für einen vollständigen Rollback im Restore-Menü 'Komplett-Restore' "
|
||||||
|
f"mit diesem Backup ausführen: {backup_file}"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
log_info("Für einen vollständigen Rollback Datenbank/Media aus einem Backup wiederherstellen.")
|
||||||
elif services_stopped:
|
elif services_stopped:
|
||||||
restart_services(strict=False)
|
restart_services(strict=False)
|
||||||
services_stopped = False
|
services_stopped = False
|
||||||
@@ -1102,7 +1510,7 @@ def main_menu():
|
|||||||
while True:
|
while True:
|
||||||
print_header("NETBOX BACKUP, RESTORE & UPGRADE TOOL")
|
print_header("NETBOX BACKUP, RESTORE & UPGRADE TOOL")
|
||||||
print(f" {Colors.BOLD}1.{Colors.ENDC} Backup erstellen")
|
print(f" {Colors.BOLD}1.{Colors.ENDC} Backup erstellen")
|
||||||
print(f" {Colors.BOLD}2.{Colors.ENDC} Backup wiederherstellen")
|
print(f" {Colors.BOLD}2.{Colors.ENDC} Restore-Menü (Backup wiederherstellen)")
|
||||||
print(f" {Colors.BOLD}3.{Colors.ENDC} NetBox upgraden")
|
print(f" {Colors.BOLD}3.{Colors.ENDC} NetBox upgraden")
|
||||||
print(f" {Colors.BOLD}4.{Colors.ENDC} Einstellungen prüfen / anpassen")
|
print(f" {Colors.BOLD}4.{Colors.ENDC} Einstellungen prüfen / anpassen")
|
||||||
print(f" {Colors.BOLD}5.{Colors.ENDC} Beenden\n")
|
print(f" {Colors.BOLD}5.{Colors.ENDC} Beenden\n")
|
||||||
@@ -1112,7 +1520,7 @@ def main_menu():
|
|||||||
if choice == "1":
|
if choice == "1":
|
||||||
execute_backup()
|
execute_backup()
|
||||||
elif choice == "2":
|
elif choice == "2":
|
||||||
execute_restore()
|
restore_menu()
|
||||||
elif choice == "3":
|
elif choice == "3":
|
||||||
execute_upgrade()
|
execute_upgrade()
|
||||||
elif choice == "4":
|
elif choice == "4":
|
||||||
|
|||||||
Reference in new issue
Block a user