Add optional greenfield installation to restore menu
New restore menu option sets up a fresh Debian/Ubuntu server (packages, PostgreSQL role/database, Redis, netbox user, systemd units, optional nginx with self-signed cert) and then runs a full restore. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
f132d8878d
commit
e3f550f17a
3 files changed
+248
-12
No files matched your search
+21
-2
@@ -348,8 +348,9 @@ Im Hauptmenü auswählen:
|
||||
2. Nur Datenbank wiederherstellen
|
||||
3. Nur Media-Dateien wiederherstellen
|
||||
4. Nur Installationsdateien wiederherstellen
|
||||
5. Backup-Inhalt anzeigen
|
||||
6. Zurück zum Hauptmenü
|
||||
5. Neuinstallation auf grüner Wiese (System einrichten + Komplett-Restore)
|
||||
6. Backup-Inhalt anzeigen
|
||||
7. Zurück zum Hauptmenü
|
||||
```
|
||||
|
||||
Der Restore muss als `root` oder mit `sudo` ausgeführt werden.
|
||||
@@ -381,6 +382,24 @@ Die aktuelle Installation wird nie gelöscht:
|
||||
| `/opt/netbox` ist ein Verzeichnis | bisherige Installation wird zu `/opt/netbox_before_restore_<Zeitstempel>` umbenannt |
|
||||
| `/opt/netbox` ist ein Symlink | Wiederherstellung nach `/opt/netbox-<Version>-restored-<Zeitstempel>`, Symlink wird atomar umgestellt |
|
||||
|
||||
### Neuinstallation auf grüner Wiese (optional)
|
||||
|
||||
Menüpunkt `5` stellt ein Backup auf einem frischen Debian/Ubuntu-Server ohne vorhandene NetBox-Installation wieder her. Das Backup muss Installationsdateien und Datenbank enthalten (Format-Version 1.3 oder neuer).
|
||||
|
||||
Vor dem eigentlichen Komplett-Restore richtet das Tool ein:
|
||||
|
||||
1. Systempakete per `apt-get` (PostgreSQL, Redis, Python inkl. `venv`/`dev`, Build-Abhängigkeiten, Git).
|
||||
2. PostgreSQL-Rolle `db_user` (mit `LOGIN CREATEDB` und dem Passwort `db_pass`) und Datenbank `db_name`. Ist `db_pass` leer, wird es abgefragt.
|
||||
3. Systembenutzer `netbox`, falls nicht vorhanden.
|
||||
|
||||
Nach Wiederherstellung und `upgrade.sh`:
|
||||
|
||||
4. `gunicorn.py` und die systemd-Units aus `contrib/` nach `/etc/systemd/system` kopieren (bestehende werden nicht überschrieben) und aktivieren.
|
||||
5. Optional nginx mit `contrib/nginx.conf` und einem selbstsignierten Zertifikat (`/etc/ssl/certs/netbox.crt`) einrichten.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> `db_name`, `db_user`, `db_pass` und `netbox_path` müssen zur `configuration.py` im Backup passen. `db_host` muss `localhost` sein. Das selbstsignierte Zertifikat später durch ein echtes ersetzen.
|
||||
|
||||
### Ältere Backups
|
||||
|
||||
Backups vor Format-Version 1.3 enthalten keine Installationsdateien, lassen sich aber weiterhin wiederherstellen.
|
||||
|
||||
@@ -320,8 +320,9 @@ Main menu → `2. Restore-Menü`.
|
||||
2. Nur Datenbank wiederherstellen (database only)
|
||||
3. Nur Media-Dateien wiederherstellen (media only)
|
||||
4. Nur Installationsdateien wiederherstellen (installation files only)
|
||||
5. Backup-Inhalt anzeigen (show backup contents)
|
||||
6. Zurück zum Hauptmenü (back)
|
||||
5. Neuinstallation auf grüner Wiese (...) (greenfield install + full restore)
|
||||
6. Backup-Inhalt anzeigen (show backup contents)
|
||||
7. Zurück zum Hauptmenü (back)
|
||||
```
|
||||
|
||||
Restore must be run as `root` / with `sudo`.
|
||||
@@ -357,6 +358,24 @@ The current installation is never deleted:
|
||||
| `/opt/netbox` is a directory | current installation is renamed to `/opt/netbox_before_restore_<timestamp>`, the restored files take its place |
|
||||
| `/opt/netbox` is a symlink | restored files go to `/opt/netbox-<version>-restored-<timestamp>`, the symlink is switched atomically; the previous target stays |
|
||||
|
||||
### Greenfield installation (optional)
|
||||
|
||||
Menu item `5` restores a backup onto a fresh Debian/Ubuntu server with no existing NetBox. The backup must contain installation files and the database (format 1.3 or newer).
|
||||
|
||||
Before the full restore, the tool sets up:
|
||||
|
||||
1. System packages via `apt-get` (PostgreSQL, Redis, Python incl. `venv`/`dev`, build dependencies, Git).
|
||||
2. PostgreSQL role `db_user` (`LOGIN CREATEDB`, password `db_pass`) and database `db_name`. If `db_pass` is empty, it is prompted for.
|
||||
3. System user `netbox`, if missing.
|
||||
|
||||
After the restore and `upgrade.sh`:
|
||||
|
||||
4. `gunicorn.py` and the systemd units from `contrib/` are copied to `/etc/systemd/system` (existing ones are not overwritten) and enabled.
|
||||
5. Optionally nginx using `contrib/nginx.conf` with a self-signed certificate (`/etc/ssl/certs/netbox.crt`).
|
||||
|
||||
> [!IMPORTANT]
|
||||
> `db_name`, `db_user`, `db_pass` and `netbox_path` must match the `configuration.py` in the backup, and `db_host` must be `localhost`. Replace the self-signed certificate with a real one later.
|
||||
|
||||
### Required database privileges
|
||||
|
||||
The configured database user must be allowed to run `dropdb` and `createdb`.
|
||||
|
||||
+206
-8
@@ -667,10 +667,181 @@ RESTORE_COMPONENT_LABELS = {
|
||||
"media": "Media-Dateien",
|
||||
}
|
||||
|
||||
# Pakete für eine Neuinstallation (Debian/Ubuntu) gemäß NetBox-Installationsanleitung.
|
||||
GREENFIELD_APT_PACKAGES = (
|
||||
"postgresql",
|
||||
"redis-server",
|
||||
"python3",
|
||||
"python3-pip",
|
||||
"python3-venv",
|
||||
"python3-dev",
|
||||
"build-essential",
|
||||
"libxml2-dev",
|
||||
"libxslt1-dev",
|
||||
"libffi-dev",
|
||||
"libpq-dev",
|
||||
"libssl-dev",
|
||||
"zlib1g-dev",
|
||||
"git",
|
||||
)
|
||||
|
||||
def execute_restore(components=None):
|
||||
"""Stellt die gewählten Komponenten wieder her (None = alles, was im Backup enthalten ist)."""
|
||||
print_header("RESTORE PROZESS")
|
||||
|
||||
def sql_literal(value):
|
||||
return "'" + value.replace("'", "''") + "'"
|
||||
|
||||
|
||||
def sql_identifier(value):
|
||||
return '"' + value.replace('"', '""') + '"'
|
||||
|
||||
|
||||
def run_checked(command, description, **kwargs):
|
||||
proc = run_command(command, capture=True, **kwargs)
|
||||
if proc.returncode != 0:
|
||||
raise RuntimeError(f"{description} fehlgeschlagen: {(proc.stderr or proc.stdout).strip()}")
|
||||
return proc
|
||||
|
||||
|
||||
def greenfield_install_packages(with_nginx):
|
||||
if not shutil.which("apt-get"):
|
||||
raise RuntimeError("Neuinstallation wird nur auf Debian/Ubuntu (apt-get) unterstützt.")
|
||||
packages = list(GREENFIELD_APT_PACKAGES)
|
||||
if with_nginx:
|
||||
packages += ["nginx", "openssl"]
|
||||
env = os.environ.copy()
|
||||
env["DEBIAN_FRONTEND"] = "noninteractive"
|
||||
log_info(" -> apt-get update ...")
|
||||
run_checked(["apt-get", "update"], "apt-get update", env=env)
|
||||
log_info(" -> Installiere: " + " ".join(packages))
|
||||
proc = run_command(["apt-get", "install", "-y", *packages], env=env)
|
||||
if proc.returncode != 0:
|
||||
raise RuntimeError(f"apt-get install fehlgeschlagen (Code {proc.returncode}).")
|
||||
for service in ("postgresql", "redis-server"):
|
||||
run_command(["systemctl", "enable", "--now", service], capture=True)
|
||||
log_success("Systempakete installiert, PostgreSQL und Redis laufen.")
|
||||
|
||||
|
||||
def greenfield_setup_database():
|
||||
"""Legt PostgreSQL-Rolle und Datenbank an (Rolle darf Datenbanken erstellen)."""
|
||||
user, name, password = CONFIG["db_user"], CONFIG["db_name"], CONFIG["db_pass"]
|
||||
|
||||
def psql(sql):
|
||||
return run_checked(
|
||||
["runuser", "-u", "postgres", "--", "psql", "-v", "ON_ERROR_STOP=1", "-tAc", sql],
|
||||
"psql",
|
||||
cwd="/",
|
||||
)
|
||||
|
||||
exists = psql(f"SELECT 1 FROM pg_roles WHERE rolname = {sql_literal(user)}").stdout.strip() == "1"
|
||||
verb = "ALTER" if exists else "CREATE"
|
||||
psql(f"{verb} ROLE {sql_identifier(user)} WITH LOGIN CREATEDB PASSWORD {sql_literal(password)}")
|
||||
log_success(f"PostgreSQL-Rolle '{user}' {'aktualisiert' if exists else 'angelegt'}.")
|
||||
|
||||
db_exists = psql(f"SELECT 1 FROM pg_database WHERE datname = {sql_literal(name)}").stdout.strip() == "1"
|
||||
if not db_exists:
|
||||
psql(f"CREATE DATABASE {sql_identifier(name)} OWNER {sql_identifier(user)}")
|
||||
log_success(f"Datenbank '{name}' angelegt.")
|
||||
|
||||
|
||||
def greenfield_create_system_user():
|
||||
if run_command(["id", "netbox"], capture=True).returncode == 0:
|
||||
log_info(" -> Systembenutzer 'netbox' existiert bereits.")
|
||||
return
|
||||
run_checked(
|
||||
["adduser", "--system", "--group", "--no-create-home", "netbox"]
|
||||
if shutil.which("adduser")
|
||||
else ["useradd", "--system", "--user-group", "--no-create-home", "netbox"],
|
||||
"Anlegen des Systembenutzers netbox",
|
||||
)
|
||||
log_success("Systembenutzer 'netbox' angelegt.")
|
||||
|
||||
|
||||
def greenfield_install_services():
|
||||
"""Richtet gunicorn.py und die systemd-Units aus contrib/ ein."""
|
||||
root = CONFIG["netbox_path"]
|
||||
contrib = os.path.join(root, "contrib")
|
||||
gunicorn_target = os.path.join(root, "gunicorn.py")
|
||||
if not os.path.isfile(gunicorn_target) and os.path.isfile(os.path.join(contrib, "gunicorn.py")):
|
||||
shutil.copy2(os.path.join(contrib, "gunicorn.py"), gunicorn_target)
|
||||
|
||||
units = [name for name in os.listdir(contrib) if name.endswith((".service", ".timer"))] if os.path.isdir(contrib) else []
|
||||
if not units:
|
||||
raise RuntimeError(f"Keine systemd-Units unter {contrib} gefunden.")
|
||||
for name in units:
|
||||
target = os.path.join("/etc/systemd/system", name)
|
||||
if not os.path.exists(target):
|
||||
shutil.copy2(os.path.join(contrib, name), target)
|
||||
run_checked(["systemctl", "daemon-reload"], "systemctl daemon-reload")
|
||||
for service in NETBOX_SERVICES:
|
||||
run_checked(["systemctl", "enable", service], f"systemctl enable {service}")
|
||||
if "netbox-housekeeping.timer" in units:
|
||||
run_command(["systemctl", "enable", "--now", "netbox-housekeeping.timer"], capture=True)
|
||||
log_success("systemd-Dienste eingerichtet und aktiviert.")
|
||||
|
||||
|
||||
def greenfield_setup_nginx():
|
||||
contrib_conf = os.path.join(CONFIG["netbox_path"], "contrib", "nginx.conf")
|
||||
if not os.path.isfile(contrib_conf):
|
||||
log_warn("contrib/nginx.conf nicht gefunden; nginx wird nicht konfiguriert.")
|
||||
return
|
||||
server_name = input(" Servername für nginx/Zertifikat (z. B. netbox.example.com): ").strip() or "_"
|
||||
cert, key = "/etc/ssl/certs/netbox.crt", "/etc/ssl/private/netbox.key"
|
||||
if not (os.path.exists(cert) and os.path.exists(key)):
|
||||
cn = server_name if server_name != "_" else "netbox"
|
||||
run_checked(
|
||||
["openssl", "req", "-x509", "-nodes", "-days", "825", "-newkey", "rsa:2048",
|
||||
"-keyout", key, "-out", cert, "-subj", f"/CN={cn}"],
|
||||
"Erzeugen des selbstsignierten Zertifikats",
|
||||
)
|
||||
os.chmod(key, 0o600)
|
||||
log_info(" -> Selbstsigniertes Zertifikat erzeugt (später durch ein echtes ersetzen).")
|
||||
with open(contrib_conf, "r", encoding="utf-8") as handle:
|
||||
content = handle.read().replace("netbox.example.com", server_name)
|
||||
with open("/etc/nginx/sites-available/netbox", "w", encoding="utf-8") as handle:
|
||||
handle.write(content)
|
||||
default_site = "/etc/nginx/sites-enabled/default"
|
||||
if os.path.islink(default_site):
|
||||
os.remove(default_site)
|
||||
enabled = "/etc/nginx/sites-enabled/netbox"
|
||||
if not os.path.lexists(enabled):
|
||||
os.symlink("/etc/nginx/sites-available/netbox", enabled)
|
||||
run_checked(["nginx", "-t"], "nginx-Konfigurationstest")
|
||||
run_checked(["systemctl", "restart", "nginx"], "nginx-Neustart")
|
||||
log_success("nginx eingerichtet.")
|
||||
|
||||
|
||||
def execute_greenfield_restore():
|
||||
"""Installiert NetBox auf einem frischen System und spielt danach das komplette Backup ein."""
|
||||
print_header("NEUINSTALLATION AUS BACKUP (GRÜNE WIESE)")
|
||||
log_info(
|
||||
"Richtet auf einem frischen Debian/Ubuntu-System alles Nötige ein (Pakete, PostgreSQL, Redis, "
|
||||
"Benutzer 'netbox', systemd-Dienste, optional nginx) und führt anschließend einen Komplett-Restore aus."
|
||||
)
|
||||
log_info(
|
||||
f"Datenbank: {CONFIG['db_name']} / Benutzer: {CONFIG['db_user']} @ {CONFIG['db_host']} "
|
||||
f"– Installationspfad: {CONFIG['netbox_path']}"
|
||||
)
|
||||
log_warn("Die Werte müssen zur configuration.py im Backup passen (ggf. vorher in den Einstellungen anpassen).")
|
||||
if CONFIG["db_host"] not in ("localhost", "127.0.0.1", "::1"):
|
||||
log_error("Die Neuinstallation richtet PostgreSQL lokal ein; db_host muss localhost sein.")
|
||||
pause()
|
||||
return
|
||||
if not CONFIG["db_pass"]:
|
||||
password = input("\nPasswort für den PostgreSQL-Benutzer (wie in configuration.py): ").strip()
|
||||
if not password:
|
||||
log_error("Ohne Datenbank-Passwort ist keine Neuinstallation möglich.")
|
||||
pause()
|
||||
return
|
||||
CONFIG["db_pass"] = password
|
||||
with_nginx = input("\nnginx mit selbstsigniertem Zertifikat einrichten? (j/N): ").strip().lower() == "j"
|
||||
execute_restore(None, greenfield={"nginx": with_nginx})
|
||||
|
||||
|
||||
def execute_restore(components=None, greenfield=None):
|
||||
"""Stellt die gewählten Komponenten wieder her (None = alles, was im Backup enthalten ist).
|
||||
|
||||
greenfield: dict mit Optionen für eine Neuinstallation (siehe execute_greenfield_restore).
|
||||
"""
|
||||
print_header("RESTORE PROZESS" if not greenfield else "NEUINSTALLATION AUS BACKUP")
|
||||
|
||||
if os.name != "posix" or os.geteuid() != 0:
|
||||
log_error("Der Restore muss unter Linux als root bzw. mit sudo ausgeführt werden.")
|
||||
@@ -699,8 +870,17 @@ def execute_restore(components=None):
|
||||
log_error("Im Backup ist nichts Passendes zum Wiederherstellen enthalten.")
|
||||
pause()
|
||||
return
|
||||
if greenfield and not (available["files"] and available["db"]):
|
||||
log_error("Für eine Neuinstallation muss das Backup Installationsdateien und Datenbank enthalten.")
|
||||
pause()
|
||||
return
|
||||
|
||||
show_backup_info(restore_file, meta)
|
||||
if greenfield and os.path.lexists(CONFIG["netbox_path"]):
|
||||
log_warn(
|
||||
f"Unter {CONFIG['netbox_path']} existiert bereits etwas; es wird beim Restore beiseitegelegt, "
|
||||
"nicht gelöscht."
|
||||
)
|
||||
|
||||
backup_version = meta.get("netbox_version")
|
||||
installed_version = (
|
||||
@@ -735,6 +915,14 @@ def execute_restore(components=None):
|
||||
with zipfile.ZipFile(restore_file, "r") as zipf:
|
||||
safe_extract_zip(zipf, tmp_extract_dir)
|
||||
|
||||
if greenfield:
|
||||
log_info("Schritt 1a: Installiere Systempakete...")
|
||||
greenfield_install_packages(greenfield.get("nginx"))
|
||||
log_info("Schritt 1b: Richte PostgreSQL-Rolle und Datenbank ein...")
|
||||
greenfield_setup_database()
|
||||
log_info("Schritt 1c: Prüfe Systembenutzer 'netbox'...")
|
||||
greenfield_create_system_user()
|
||||
|
||||
log_info("Schritt 2: Stoppe NetBox-Dienste...")
|
||||
stop_services()
|
||||
services_stopped = True
|
||||
@@ -765,10 +953,18 @@ def execute_restore(components=None):
|
||||
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
|
||||
|
||||
if greenfield and greenfield.get("nginx"):
|
||||
log_info("Schritt 6: Richte nginx ein...")
|
||||
greenfield_setup_nginx()
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
log_success("RESTORE ERFOLGREICH ABGESCHLOSSEN!")
|
||||
print("=" * 60)
|
||||
@@ -803,18 +999,20 @@ def restore_menu():
|
||||
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")
|
||||
print(f" {Colors.BOLD}5.{Colors.ENDC} Neuinstallation auf grüner Wiese (System einrichten + Komplett-Restore)")
|
||||
print(f" {Colors.BOLD}6.{Colors.ENDC} Backup-Inhalt anzeigen")
|
||||
print(f" {Colors.BOLD}7.{Colors.ENDC} Zurück zum Hauptmenü\n")
|
||||
|
||||
choice = input(Colors.BOLD + "Wähle eine Aktion (1-6): " + Colors.ENDC).strip()
|
||||
choice = input(Colors.BOLD + "Wähle eine Aktion (1-7): " + 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,
|
||||
"5": execute_greenfield_restore,
|
||||
"6": show_backup_details,
|
||||
}
|
||||
if choice == "6":
|
||||
if choice == "7":
|
||||
return
|
||||
if choice in actions:
|
||||
actions[choice]()
|
||||
|
||||
Reference in new issue
Block a user