diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c18dd8d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +__pycache__/ diff --git a/README.de.md b/README.de.md new file mode 100644 index 0000000..a51c20e --- /dev/null +++ b/README.de.md @@ -0,0 +1,1114 @@ +# NetBox Backup, Restore & Upgrade Tool + +🇬🇧 [English version](README.md) + +Ein interaktives Python-Werkzeug zur Sicherung, Wiederherstellung und Aktualisierung einer NetBox-Installation unter Linux. + +Das Skript kombiniert folgende Aufgaben in einer einfachen Terminal-Oberfläche: + +- PostgreSQL-Datenbank sichern +- NetBox-Media-Dateien sichern +- Komplette Installationsdateien sichern (Konfiguration, `local_requirements.txt`, LDAP, Skripte, Reports, ...) +- Backups als ZIP-Datei speichern +- Alles oder einzelne Komponenten über ein Restore-Menü wiederherstellen +- Vor jedem Upgrade automatisch ein vollständiges Backup erstellen +- Neue NetBox-Releases herunterladen und installieren +- Konfiguration, LDAP-Einstellungen, Plugins, Media-Dateien, Reports und Custom Scripts übernehmen +- NetBox-Dienste stoppen, starten und überprüfen +- Die bisherige Installation für einen möglichen Rollback aufbewahren + +> [!IMPORTANT] +> Dieses Projekt ist kein offizielles Werkzeug des NetBox-Projekts. Teste Backup, Restore und Upgrade zuerst auf einer Testinstanz. Ein aktuelles, extern gespeichertes Backup sollte vor jedem Upgrade vorhanden sein. + +--- + +## Inhaltsverzeichnis + +1. [Voraussetzungen](#voraussetzungen) +2. [Installation](#installation) +3. [Schnellstart](#schnellstart) +4. [Konfiguration](#konfiguration) +5. [Backup erstellen](#backup-erstellen) +6. [Restore-Menü](#restore-menü) +7. [NetBox upgraden](#netbox-upgraden) +8. [Übernommene Dateien und Verzeichnisse](#übernommene-dateien-und-verzeichnisse) +9. [Plugins und LDAP](#plugins-und-ldap) +10. [CSRF Trusted Origins](#csrf-trusted-origins) +11. [Rollback-Verhalten](#rollback-verhalten) +12. [Backup-Aufbau](#backup-aufbau) +13. [Troubleshooting](#troubleshooting) +14. [Sicherheitshinweise](#sicherheitshinweise) +15. [Bekannte Einschränkungen](#bekannte-einschränkungen) + +--- + +## Voraussetzungen + +### Betriebssystem + +Das Tool ist für eine klassische NetBox-Installation unter Linux vorgesehen. Die Upgrade-Funktion benötigt: + +- Linux beziehungsweise ein POSIX-System +- `systemd` +- Root-Rechte +- Schreibzugriff auf `/opt` +- Internetzugriff auf GitHub + +### Python + +- Python 3.8 oder neuer empfohlen +- Es werden ausschließlich Module aus der Python-Standardbibliothek verwendet +- Zusätzliche Python-Pakete sind für das Tool selbst nicht erforderlich + +### Systemprogramme + +Folgende Programme müssen verfügbar sein: + +| Programm | Verwendung | +|---|---| +| `pg_dump` | PostgreSQL-Datenbank sichern | +| `pg_restore` | PostgreSQL-Dump wiederherstellen | +| `dropdb` | Vorhandene Zieldatenbank beim Restore löschen | +| `createdb` | Zieldatenbank neu erstellen | +| `systemctl` | NetBox-Dienste stoppen und starten | +| `cp` | Konfiguration und lokale Daten beim Upgrade übernehmen | +| `chown` | Eigentümer der wiederhergestellten Media-Dateien setzen | +| `git` | Optional zur Erkennung der installierten NetBox-Version | + +Unter Debian oder Ubuntu können die PostgreSQL-Clientprogramme beispielsweise über das Paket `postgresql-client` bereitgestellt werden. + +### NetBox-Verzeichnisstruktur + +Standardmäßig erwartet das Tool NetBox unter: + +```text +/opt/netbox +``` + +Dabei werden unter anderem folgende Pfade erwartet: + +```text +/opt/netbox/upgrade.sh +/opt/netbox/netbox/netbox/configuration.py +/opt/netbox/netbox/media/ +``` + +`/opt/netbox` darf entweder ein normales Verzeichnis oder ein Symlink auf ein versionsbezogenes Verzeichnis sein. + +### NetBox-Dienste + +Das Skript verwendet standardmäßig diese Service-Namen: + +```text +netbox +netbox-rq +``` + +Bei abweichenden Unit-Namen muss die Konstante `NETBOX_SERVICES` im Skript angepasst werden. + +--- + +## Installation + +Skript nach `/usr/local/sbin` oder in ein anderes geeignetes Verzeichnis kopieren: + +```bash +sudo cp nettmanage.py /usr/local/sbin/netbox-tool +sudo chmod 750 /usr/local/sbin/netbox-tool +sudo chown root:root /usr/local/sbin/netbox-tool +``` + +Anschließend starten: + +```bash +sudo /usr/local/sbin/netbox-tool +``` + +Alternativ direkt aus dem aktuellen Ordner: + +```bash +chmod +x nettmanage.py +sudo ./nettmanage.py +``` + +Optional kann vorab die Python-Syntax geprüft werden: + +```bash +python3 -m py_compile nettmanage.py +``` + +--- + +## Schnellstart + +Nach dem Start erscheint das Hauptmenü: + +```text +============================================================ + NETBOX BACKUP, RESTORE & UPGRADE TOOL +============================================================ + + 1. Backup erstellen + 2. Restore-Menü (Backup wiederherstellen) + 3. NetBox upgraden + 4. Einstellungen prüfen / anpassen + 5. Beenden +``` + +Empfohlene Reihenfolge vor einem Upgrade: + +1. Einstellungen kontrollieren, insbesondere `backup_dir`. +2. Release Notes der Zielversion lesen. +3. Plugin-Kompatibilität prüfen. +4. Upgrade starten – ein vollständiges Backup wird automatisch erstellt. +5. Pre-Upgrade-Backup auf ein anderes System kopieren. +6. Weboberfläche, Worker, Plugins und Logs kontrollieren. + +--- + +## Konfiguration + +Die Standardwerte befinden sich am Anfang des Skripts: + +```python +CONFIG = { + "netbox_path": "/opt/netbox", + "db_host": "localhost", + "db_name": "netbox", + "db_user": "netbox", + "db_pass": "", + "backup_dir": "/tmp", + "python_path": "", +} +``` + +### Konfigurationswerte + +| Schlüssel | Beschreibung | Standard | +|---|---|---| +| `netbox_path` | Aktiver NetBox-Installationspfad | `/opt/netbox` | +| `db_host` | PostgreSQL-Server | `localhost` | +| `db_name` | Name der NetBox-Datenbank | `netbox` | +| `db_user` | PostgreSQL-Benutzer | `netbox` | +| `db_pass` | PostgreSQL-Passwort | leer | +| `backup_dir` | Ziel für Backups und temporäre Dateien; das Restore-Menü listet die hier gefundenen Backups | `/tmp` | +| `python_path` | Optionaler Python-Interpreter für `upgrade.sh` | leer | + +### Python-Version für das Upgrade festlegen + +Normalerweise verwendet `upgrade.sh` den passenden Standardinterpreter. Falls eine bestimmte Python-Version benötigt wird, kann sie angegeben werden: + +```python +"python_path": "/usr/bin/python3.12", +``` + +Das Skript setzt dann beim Aufruf von `upgrade.sh` die Umgebungsvariable `PYTHON`. + +### Datenbankpasswort + +Ist `db_pass` gesetzt, wird es für PostgreSQL-Befehle über die Umgebungsvariable `PGPASSWORD` bereitgestellt. + +Aus Sicherheitsgründen ist eine PostgreSQL-Passwortdatei häufig besser geeignet: + +```text +/root/.pgpass +``` + +Beispiel: + +```text +localhost:5432:netbox:netbox:MEIN_PASSWORT +``` + +Berechtigungen setzen: + +```bash +chmod 600 /root/.pgpass +``` + +Danach kann `db_pass` im Skript leer bleiben. + +> [!NOTE] +> Änderungen über das Menü **Einstellungen prüfen / anpassen** gelten nur für den aktuell laufenden Prozess. Sie werden nicht dauerhaft in einer Datei gespeichert. Für dauerhafte Änderungen muss der `CONFIG`-Block im Skript angepasst werden. + +--- + +## Backup erstellen + +Im Hauptmenü auswählen: + +```text +1. Backup erstellen +``` + +### Auswahlmöglichkeiten + +Das Tool fragt, ob folgende Komponenten gesichert werden sollen: + +- PostgreSQL-Datenbank +- Media-Dateien +- Installationsdateien (komplette Kopie des NetBox-Verzeichnisses) + +### Installationsdateien + +Gesichert wird der gesamte Inhalt des (aufgelösten) `netbox_path`, unter anderem: + +- `netbox/netbox/configuration.py` und `ldap_config.py` +- `local_requirements.txt`, `gunicorn.py` +- `netbox/scripts/`, `netbox/reports/` +- `upgrade.sh` und der NetBox-Quellcode der installierten Version + +Ausgenommen sind `venv/` und `netbox/static/` (werden von `upgrade.sh` neu erzeugt), `netbox/media/` (eigene Komponente) sowie `__pycache__/`. + +Rechte, Besitzer und Symlinks werden in `files_manifest.json` festgehalten und beim Restore wiederhergestellt. + +Beim Datenbank-Backup können zusätzlich Daten bestimmter Tabellen ausgelassen werden. + +### Changelog auslassen + +Bei Auswahl dieser Option wird der Inhalt der Tabelle `extras_objectchange` nicht exportiert: + +```text +Changelog (extras_objectchange) auslassen? Spart viel Platz. (j/N) +``` + +Die Tabellenstruktur bleibt im Dump erhalten. Nur die darin gespeicherten Daten werden übersprungen. + +Diese Option kann die Backup-Größe deutlich reduzieren, wenn die Änderungsprotokollierung sehr umfangreich ist. + +### Benutzer auslassen + +Folgende Tabelleninhalte werden dabei nicht exportiert: + +```text +auth_user +auth_group +users_token +``` + +> [!WARNING] +> Das Auslassen von Benutzern kann beim Restore zu Fremdschlüsselproblemen oder fehlenden Zuordnungen führen. Verwende diese Option nur, wenn das Zielsystem bereits passende Benutzer besitzt oder du die Folgen genau kennst. + +### Backup-Datei + +Die Datei wird nach folgendem Schema erzeugt: + +```text +netbox_backup_YYYYMMDD_HHMMSS.zip +``` + +Beispiel: + +```text +/tmp/netbox_backup_20260720_143500.zip +``` + +Nach erfolgreicher Erstellung zeigt das Tool den vollständigen Pfad an. Die ZIP-Datei wird mit den Rechten `600` angelegt, da sie Dump und `configuration.py` (inkl. `SECRET_KEY`) enthält. + +### Backup anschließend prüfen + +Datei anzeigen: + +```bash +ls -lh /tmp/netbox_backup_*.zip +``` + +ZIP-Inhalt prüfen: + +```bash +unzip -l /tmp/netbox_backup_20260720_143500.zip +``` + +Prüfsumme erzeugen: + +```bash +sha256sum /tmp/netbox_backup_20260720_143500.zip +``` + +Backup auf einen externen Speicher kopieren: + +```bash +scp /tmp/netbox_backup_20260720_143500.zip backupserver:/srv/backups/netbox/ +``` + +Ein Backup sollte nicht ausschließlich unter `/tmp` verbleiben. Je nach Systemkonfiguration kann dieses Verzeichnis beim Neustart geleert werden. + +--- + +## Restore-Menü + +Im Hauptmenü auswählen: + +```text +2. Restore-Menü (Backup wiederherstellen) +``` + +```text + 1. Komplett-Restore (alles, was im Backup enthalten ist) + 2. Nur Datenbank wiederherstellen + 3. Nur Media-Dateien wiederherstellen + 4. Nur Installationsdateien wiederherstellen + 5. Backup-Inhalt anzeigen + 6. Zurück zum Hauptmenü +``` + +Der Restore muss als `root` oder mit `sudo` ausgeführt werden. + +> [!CAUTION] +> Der Restore überschreibt die vorhandenen Daten der Zielinstanz. Beim Datenbank-Restore wird die konfigurierte PostgreSQL-Datenbank gelöscht und neu erstellt. + +### Backup auswählen + +Alle `netbox_*.zip`-Dateien in `backup_dir` werden – neueste zuerst – mit Größe und Datum aufgelistet. Auswahl per Nummer oder Eingabe eines beliebigen Pfads. Vor der Bestätigung zeigt das Tool die Metadaten an. Stammt eine allein wiederhergestellte Datenbank von einer neueren NetBox-Version als der installierten, erscheint eine Warnung. + +### Ablauf + +1. Archiv in ein temporäres Verzeichnis unter `backup_dir` entpacken. +2. `netbox` und `netbox-rq` stoppen. +3. Gewählte Komponenten wiederherstellen: + - **Installationsdateien:** in ein neues Verzeichnis entpacken, Rechte/Besitzer/Symlinks setzen und umschalten. Wird Media nicht mit wiederhergestellt, werden die aktuellen Media-Dateien übernommen. + - **Datenbank:** `dropdb`, `createdb`, `pg_restore`. + - **Media:** `netbox/media/` ersetzen, Eigentümer `netbox:netbox`. +4. `upgrade.sh` ausführen (nur bei Datenbank oder Installationsdateien; erzeugt das venv neu, installiert `local_requirements.txt`, führt Migrationen aus, sammelt Static Files). +5. Dienste neu starten und prüfen. + +### Installationsdateien wiederherstellen + +Die aktuelle Installation wird nie gelöscht: + +| Aufbau | Verhalten | +|---|---| +| `/opt/netbox` ist ein Verzeichnis | bisherige Installation wird zu `/opt/netbox_before_restore_` umbenannt | +| `/opt/netbox` ist ein Symlink | Wiederherstellung nach `/opt/netbox--restored-`, Symlink wird atomar umgestellt | + +### Ältere Backups + +Backups vor Format-Version 1.3 enthalten keine Installationsdateien, lassen sich aber weiterhin wiederherstellen. + +### Benötigte Datenbankrechte + +Der konfigurierte Datenbankbenutzer muss für den Restore ausreichende Rechte besitzen. Insbesondere müssen `dropdb` und `createdb` mit diesem Benutzer funktionieren. + +Test: + +```bash +sudo -u postgres psql -c "\du" +``` + +Falls der NetBox-Datenbankbenutzer keine Datenbanken erstellen darf, muss der Ablauf angepasst oder ein administrativer PostgreSQL-Benutzer verwendet werden. + +### Restore-Befehl im Hintergrund + +Der Dump wird sinngemäß so importiert: + +```bash +pg_restore \ + -h localhost \ + -U netbox \ + -d netbox \ + --clean \ + --if-exists \ + --no-owner \ + netbox_database.dump +``` + +Meldungen von `pg_restore` werden angezeigt. Da PostgreSQL auch bei einzelnen Warnungen einen Rückgabecode ungleich null liefern kann, meldet das Tool den Restore als abgeschlossen und gibt vorhandene Hinweise aus. Kontrolliere anschließend die Datenbank und die NetBox-Logs. + +### Media-Dateien + +Vorhandene Media-Dateien unter folgendem Pfad werden ersetzt: + +```text +/opt/netbox/netbox/media +``` + +Danach setzt das Tool den Eigentümer auf: + +```text +netbox:netbox +``` + +--- + +## NetBox upgraden + +Im Hauptmenü auswählen: + +```text +3. NetBox upgraden +``` + +Die Upgrade-Funktion muss als `root` oder mit `sudo` ausgeführt werden. + +### Zielversion + +Die Version kann mit oder ohne vorangestelltes `v` eingegeben werden: + +```text +4.6.5 +``` + +oder: + +```text +v4.6.5 +``` + +Akzeptiert werden ausschließlich stabile Versionsnummern im Format: + +```text +X.Y.Z +``` + +Pre-Releases wie `4.6.0-beta1` werden nicht akzeptiert. + +### Versionsprüfung + +Das Tool versucht die installierte NetBox-Version über mehrere Methoden zu erkennen: + +- Name des tatsächlichen Installationsverzeichnisses +- exaktes Git-Tag +- NetBox-Python-Paket im vorhandenen virtuellen Environment +- NetBox-Versionsdateien + +Die Zielversion muss höher als die erkannte installierte Version sein. Downgrades werden nicht automatisiert. + +Bei einem erkannten Major-Sprung gibt das Tool eine zusätzliche Warnung aus. + +### Upgrade-Ablauf + +Das Tool führt folgende Schritte durch: + +1. Zielversion validieren. +2. Bestehende NetBox-Installation prüfen. +3. Bestätigung verlangen, dass die Release Notes geprüft wurden. +4. Abfragen, ob das automatische Backup übersprungen werden soll (Standard: nein). +5. Optional die vorkonfigurierten Plugins ergänzen. +6. LDAP-Konfiguration erkennen. +7. `CSRF_TRUSTED_ORIGINS` prüfen oder ergänzen. +8. **Vollständiges Pre-Upgrade-Backup erstellen.** +9. Release-Archiv von GitHub herunterladen. +10. TAR-Archiv sicher entpacken und prüfen. +11. Lokale Dateien und Verzeichnisse übernehmen. +12. Dienste stoppen. +13. Installationsverzeichnisse beziehungsweise Symlink umschalten. +14. `/opt/netbox/upgrade.sh` ausführen. +15. Dienste neu starten und Status prüfen. +16. Alte Installation als Rückfalloption behalten. + +### Automatisches Backup vor dem Upgrade + +Bevor etwas verändert wird, erstellt das Tool ein vollständiges Backup (Datenbank, Media, Installationsdateien): + +```text +netbox_pre_upgrade_vX.Y.Z_YYYYMMDD_HHMMSS.zip +``` + +Fehlt `pg_dump` oder schlägt das Backup fehl, wird das Upgrade abgebrochen, bevor etwas verändert wurde. Überspringen ist nur mit expliziter Eingabe von `OHNE BACKUP` möglich. Scheitert das Upgrade nach Start von `upgrade.sh`, gibt das Tool den Pfad dieses Backups für einen Komplett-Restore aus. + +### Download-Adresse + +Das Release wird nach diesem Schema geladen: + +```text +https://github.com/netbox-community/netbox/archive/refs/tags/vX.Y.Z.tar.gz +``` + +Das temporäre Archiv wird nach dem Upgrade wieder gelöscht. + +### Downtime + +Backup, Download, Entpacken und die Vorbereitung der neuen Installation erfolgen vor dem Stoppen der Dienste. Die eigentliche Downtime beginnt erst bei der Umschaltung auf die neue Installation. + +### Dienste + +Vor der Umschaltung werden folgende Dienste gestoppt: + +```text +netbox +netbox-rq +``` + +Nach erfolgreichem `upgrade.sh` werden beide Dienste neu gestartet und mit `systemctl is-active` geprüft. + +--- + +## Übernommene Dateien und Verzeichnisse + +Beim Upgrade werden folgende Inhalte aus der bestehenden Installation in das neue Release kopiert. + +### Pflichtdatei + +```text +netbox/netbox/configuration.py +``` + +Fehlt diese Datei, wird das Upgrade abgebrochen. + +### Optionale Dateien + +```text +netbox/netbox/ldap_config.py +local_requirements.txt +gunicorn.py +``` + +Fehlende optionale Dateien führen nicht zum Abbruch. + +### Optionale Verzeichnisse + +```text +netbox/media/ +netbox/scripts/ +netbox/reports/ +``` + +Die Inhalte werden unter Erhaltung von Rechten, Zeitstempeln und symbolischen Eigenschaften mit `cp -a` kopiert. + +### Nicht automatisch übernommene Anpassungen + +Manuelle Änderungen an Dateien aus dem eigentlichen NetBox-Quellcode werden nicht automatisch erkannt oder zusammengeführt. Dazu zählen beispielsweise direkt modifizierte Templates, Python-Dateien oder statische Dateien außerhalb der oben genannten Pfade. + +Solche Änderungen sollten als Plugin, Custom Script oder über einen dokumentierten Deployment-Prozess umgesetzt werden. + +--- + +## Plugins und LDAP + +### Vorhandene Requirements + +Eine bestehende Datei wird übernommen: + +```text +/opt/netbox/local_requirements.txt +``` + +Vorhandene Einträge bleiben erhalten. Das Tool versucht Paketnamen zu erkennen und fügt ein Paket nicht erneut hinzu, wenn bereits ein unversionierter oder gepinnter Eintrag existiert. + +Beispiele, die als dasselbe Paket erkannt werden: + +```text +netbox-topology-views +netbox-topology-views==4.2.1 +netbox_topology_views>=4.0 +``` + +### Vorkonfigurierte Plugins + +Auf Wunsch ergänzt das Tool folgende Einträge: + +```text +netbox-topology-views +netbox-attachments +netbox-ping +netbox-reorder-rack +netbox-secrets +netbox-inventory +git+https://git.mrblake.cc/MrBlake/NetBox-VM-Import.git#egg=netbox_vmware_importer +``` + +Diese Liste befindet sich in der Konstante: + +```python +DEFAULT_PLUGIN_REQUIREMENTS +``` + +Sie kann vor der Nutzung an die eigene Umgebung angepasst werden. + +### LDAP + +Wird folgende Datei in der bestehenden Installation gefunden: + +```text +/opt/netbox/netbox/netbox/ldap_config.py +``` + +führt das Tool zwei Aktionen aus: + +1. `ldap_config.py` wird in die neue Installation kopiert. +2. `django-auth-ldap` wird in `local_requirements.txt` sichergestellt. + +### Plugin-Kompatibilität + +Das Tool kann nicht zuverlässig prüfen, ob ein Plugin die Zielversion von NetBox unterstützt. Diese Prüfung erfolgt spätestens beim Installieren der Requirements durch `upgrade.sh`. + +Vor dem Upgrade sollten für jedes Plugin geprüft werden: + +- unterstützte NetBox-Version +- unterstützte Python-Version +- erforderliche Migrationsschritte +- geänderte Konfigurationswerte +- bekannte Inkompatibilitäten + +Ein nicht kompatibles Plugin kann `upgrade.sh` abbrechen oder NetBox nach dem Neustart am Starten hindern. + +--- + +## CSRF Trusted Origins + +Das Tool prüft, ob in `configuration.py` eine direkte Zuweisung vorhanden ist: + +```python +CSRF_TRUSTED_ORIGINS = [ + "https://netbox.example.local", +] +``` + +Während des Upgrades können neue Origins kommagetrennt eingegeben werden: + +```text +https://netbox.example.local,http://192.168.1.50 +``` + +Zulässig sind ausschließlich Origins mit: + +- `http://` +- `https://` +- Hostname oder IP-Adresse +- optionalem Port +- keinem Pfad +- keiner Query +- keinem Fragment + +Gültig: + +```text +https://netbox.example.local +http://192.168.1.50 +https://netbox.example.local:8443 +``` + +Ungültig: + +```text +netbox.example.local +https://netbox.example.local/netbox +https://netbox.example.local?test=1 +``` + +Werden neue Origins eingegeben, hängt das Tool einen neuen Block an `configuration.py` an: + +```python +# Automatisch durch das NetBox-Upgrade-Tool gesetzt +CSRF_TRUSTED_ORIGINS = [ + 'https://netbox.example.local', + 'http://192.168.1.50', +] +``` + +> [!NOTE] +> Existiert bereits eine direkte Zuweisung und werden zusätzlich neue Werte eingegeben, enthält die Datei anschließend zwei Zuweisungen. In Python gilt die zuletzt ausgewertete Zuweisung. Prüfe die Datei nach dem Upgrade und konsolidiere die Einstellung bei Bedarf. + +Dynamisch importierte oder programmatisch zusammengesetzte CSRF-Einstellungen können durch die einfache Prüfung möglicherweise nicht erkannt werden. Das Tool warnt in diesem Fall und verlangt eine zusätzliche Bestätigung. + +--- + +## Rollback-Verhalten + +Das Rollback-Verhalten hängt davon ab, wann ein Fehler auftritt. + +### Fehler vor dem Start von `upgrade.sh` + +Tritt der Fehler nach der Verzeichnisumschaltung, aber vor dem Start von `upgrade.sh` auf, versucht das Tool automatisch: + +1. die bisherige Installation wieder zu aktivieren, +2. die NetBox-Dienste neu zu starten. + +In diesem Stadium wurden noch keine NetBox-Datenbankmigrationen durch das neue Release ausgeführt. + +### Fehler nach dem Start von `upgrade.sh` + +Sobald `upgrade.sh` gestartet wurde, erfolgt kein automatischer vollständiger Rollback mehr. + +Grund: Datenbankmigrationen könnten bereits ganz oder teilweise ausgeführt worden sein. Eine reine Rückschaltung des Programmverzeichnisses könnte dann eine ältere NetBox-Version mit einem neueren Datenbankschema kombinieren. + +Vollständiger Rollback über das Restore-Menü: + +1. Restore-Menü → `1. Komplett-Restore`. +2. Das Backup `netbox_pre_upgrade_v…` auswählen. +3. Das Tool stoppt die Dienste, stellt Installationsdateien, Datenbank und Media wieder her, führt `upgrade.sh` der alten Version aus und startet die Dienste. +4. Logs prüfen. + +### Normales Verzeichnis + +Ist `/opt/netbox` ein normales Verzeichnis, wird die alte Installation beispielsweise hier abgelegt: + +```text +/opt/netbox_old_20260720_143500 +``` + +Existiert der Name bereits, hängt das Tool eine laufende Nummer an. + +### Symlink-Installation + +Ist `/opt/netbox` ein Symlink, wird das neue Release beispielsweise hier installiert: + +```text +/opt/netbox-4.6.5 +``` + +Der Symlink `/opt/netbox` wird atomar auf das neue Verzeichnis umgestellt. Das vorherige Release-Verzeichnis bleibt bestehen. + +Das Zielverzeichnis darf noch nicht existieren. Bei einem bereits vorhandenen `/opt/netbox-4.6.5` bricht das Tool ab, damit keine vorhandenen Daten überschrieben werden. + +--- + +## Backup-Aufbau + +Ein vollständiges ZIP-Backup besitzt folgenden Aufbau: + +```text +netbox_backup_YYYYMMDD_HHMMSS.zip +├── metadata.json +├── netbox_database.dump (Datenbank) +├── media/ (Media-Dateien) +├── files_manifest.json (Rechte, Besitzer, Symlinks) +└── files/ (Installationsdateien) +``` + +Je nach gewähltem Backup-Umfang können einzelne Teile fehlen. + +### Metadaten + +Beispiel einer `metadata.json`: + +```json +{ + "version": "1.3", + "timestamp": "20260720_143500", + "source_db": "netbox", + "netbox_path": "/opt/netbox", + "netbox_root": "/opt/netbox-4.6.4", + "netbox_version": "4.6.4", + "contains_db": true, + "contains_media": true, + "contains_files": true, + "excluded_changelog": false, + "excluded_users": false +} +``` + +Diese Datei wird beim Restore verwendet, um den enthaltenen Umfang zu bestimmen. + +### Sicherheit beim Entpacken + +Das Tool prüft ZIP- und TAR-Pfade vor dem Entpacken, um Path-Traversal-Angriffe zu verhindern. TAR-Archive mit symbolischen Links oder Hardlinks werden abgelehnt. + +Trotzdem sollten ausschließlich Backups und Release-Archive aus vertrauenswürdigen Quellen verwendet werden. + +--- + +## Troubleshooting + +### `pg_dump: command not found` + +PostgreSQL-Client installieren: + +```bash +sudo apt update +sudo apt install postgresql-client +``` + +Bei mehreren PostgreSQL-Versionen sollte eine zum Server passende Client-Version verwendet werden. + +### PostgreSQL fragt nach einem Passwort + +Möglichkeiten: + +- `db_pass` im Skript setzen +- `/root/.pgpass` konfigurieren +- lokale PostgreSQL-Authentifizierung passend einrichten + +### `dropdb` oder `createdb` schlägt fehl + +Der konfigurierte Benutzer besitzt vermutlich nicht die erforderlichen Rechte. + +PostgreSQL-Rollen prüfen: + +```bash +sudo -u postgres psql -c "\du" +``` + +Alternativ den Restore-Ablauf so anpassen, dass administrative Datenbankaktionen mit einem separaten PostgreSQL-Benutzer ausgeführt werden. + +### Zielversion wird nicht gefunden + +Fehlermeldung: + +```text +NetBox-Release vX.Y.Z wurde auf GitHub nicht gefunden. +``` + +Prüfen: + +- Schreibweise der Version +- Internetzugriff +- DNS-Auflösung +- Proxy- oder Firewall-Regeln +- Existenz des Releases + +### Download schlägt über einen Proxy fehl + +Python berücksichtigt üblicherweise die Standardvariablen: + +```bash +export HTTPS_PROXY=http://proxy.example.local:3128 +export HTTP_PROXY=http://proxy.example.local:3128 +sudo -E ./nettmanage.py +``` + +Beachte die Sicherheitsauswirkungen von `sudo -E`. + +### `configuration.py` fehlt + +Das Tool erwartet: + +```text +/opt/netbox/netbox/netbox/configuration.py +``` + +Prüfe `CONFIG["netbox_path"]` und die tatsächliche NetBox-Verzeichnisstruktur. + +### Dienst startet nach dem Upgrade nicht + +Status prüfen: + +```bash +systemctl status netbox --no-pager -l +systemctl status netbox-rq --no-pager -l +``` + +Logs prüfen: + +```bash +journalctl -u netbox -n 200 --no-pager +journalctl -u netbox-rq -n 200 --no-pager +``` + +Häufige Ursachen: + +- inkompatibles Plugin +- falsche Python-Version +- fehlende Systembibliothek +- Fehler in `configuration.py` +- Fehler in `ldap_config.py` +- unvollständige Datenbankmigration +- falsche Dateirechte +- geänderte NetBox-Konfigurationsoptionen + +### `upgrade.sh` schlägt bei einem Plugin fehl + +Plugin vorübergehend in `local_requirements.txt` auskommentieren oder entfernen, sofern das für die betreffende Migration zulässig ist. Anschließend Plugin-Dokumentation prüfen und eine kompatible Version eintragen. + +Vor Änderungen immer sicherstellen, dass ein vollständiges Backup vorhanden ist. + +### Falscher Python-Interpreter + +Im Einstellungsmenü oder dauerhaft im `CONFIG`-Block setzen: + +```python +"python_path": "/usr/bin/python3.12", +``` + +Pfad prüfen: + +```bash +ls -l /usr/bin/python3.12 +/usr/bin/python3.12 --version +``` + +### Media-Dateien besitzen falsche Rechte + +Prüfen: + +```bash +ls -ld /opt/netbox/netbox/media +find /opt/netbox/netbox/media -maxdepth 2 -printf '%u:%g %p\n' | head +``` + +Korrigieren: + +```bash +sudo chown -R netbox:netbox /opt/netbox/netbox/media +``` + +### Upgrade wurde mit `Strg+C` unterbrochen + +Das globale `KeyboardInterrupt`-Handling beendet das Programm. Wurde `upgrade.sh` bereits gestartet, darf nicht davon ausgegangen werden, dass ein automatischer Rollback erfolgt ist. + +Vorgehen: + +1. Dienststatus prüfen. +2. Prozessliste auf laufende Upgrade-, Pip- oder Migrationsprozesse prüfen. +3. Installationspfad und Symlink-Ziel prüfen. +4. Datenbankschema nicht ohne Backup zurücksetzen. +5. Logs und Ausgabe des Upgrades auswerten. + +--- + +## Sicherheitshinweise + +### Root-Rechte + +Backup-Funktionen können je nach Dateirechten möglicherweise ohne Root-Rechte funktionieren. Restore und Upgrade benötigen jedoch erhöhte Rechte für: + +- Zugriff auf `/opt/netbox` +- `systemctl` +- `chown` +- Verzeichnisumschaltung + +Führe das Tool deshalb für administrative Vorgänge mit `sudo` aus. + +### Passwörter im Quelltext + +Ein Datenbankpasswort im `CONFIG`-Block ist für jeden Benutzer lesbar, der Zugriff auf die Skriptdatei besitzt. + +Empfehlungen: + +- Passwort möglichst über `.pgpass` bereitstellen +- Skript nur für Root lesbar machen +- keine Skripte mit Zugangsdaten in öffentliche Repositories übertragen +- Backups verschlüsselt speichern + +Geeignete Rechte: + +```bash +sudo chown root:root /usr/local/sbin/netbox-tool +sudo chmod 700 /usr/local/sbin/netbox-tool +``` + +### Backup-Schutz + +Ein NetBox-Datenbankbackup kann sensible Informationen enthalten, beispielsweise: + +- Benutzerkonten +- API-Tokens +- Geräte- und Standortdaten +- IP-Adressen +- Secrets aus Plugins +- Dokumente und Bilder + +Backups sollten deshalb: + +- verschlüsselt übertragen werden +- verschlüsselt gespeichert werden +- nur für berechtigte Personen zugänglich sein +- nach einem definierten Aufbewahrungsplan gelöscht werden + +### `/tmp` als Backup-Ziel + +`/tmp` ist als Standardwert bequem, aber nicht als dauerhafter Backup-Speicher geeignet. Ändere `backup_dir` beispielsweise auf: + +```python +"backup_dir": "/srv/backups/netbox", +``` + +Verzeichnis vorbereiten: + +```bash +sudo install -d -m 700 -o root -g root /srv/backups/netbox +``` + +### Release- und Plugin-Quellen + +Das NetBox-Release wird von GitHub geladen. Ein Plugin-Requirement verweist zusätzlich auf einen externen Git-Server. + +Prüfe vor dem Einsatz: + +- Vertrauen in die Quelle +- Erreichbarkeit +- TLS- und Zertifikatskette +- gewünschte Version beziehungsweise Commit-Pinning +- interne Richtlinien für Software-Lieferketten + +Für reproduzierbare Installationen sollten Plugin-Versionen oder Commits möglichst fest vorgegeben werden. + +--- + +## Bekannte Einschränkungen + +- Einstellungen aus dem Menü werden nicht dauerhaft gespeichert. +- Das Tool prüft Plugin-Kompatibilität nicht vorab. +- Es liest oder interpretiert keine NetBox-Release Notes automatisch. +- Major-Upgrade-Pfade werden nur gewarnt, nicht vollständig validiert. +- Ein automatischer Datenbank-Rollback nach gestarteter Migration ist absichtlich nicht implementiert. +- PostgreSQL-Backup und Restore verwenden denselben konfigurierten Datenbankbenutzer. +- Die Service-Namen `netbox` und `netbox-rq` sind fest vorkonfiguriert. +- Zusätzliche Dienste wie ein separater Housekeeping-Service, Reverse Proxy oder Monitoring-Agent werden nicht neu gestartet. +- Manuelle Änderungen am NetBox-Quellcode werden nicht übernommen. +- Bei neu eingegebenen CSRF-Origins wird ein zusätzlicher Konfigurationsblock angehängt, statt einen bestehenden Block strukturell zu bearbeiten. +- Das Skript führt keinen automatischen HTTP-Healthcheck der NetBox-Weboberfläche durch. +- Es wird keine automatische Backup-Rotation durchgeführt; Pre-Upgrade-Backups sammeln sich in `backup_dir`. +- Das venv ist nicht Teil des Backups und wird beim Restore von `upgrade.sh` neu erzeugt (benötigt Zugriff auf PyPI bzw. einen Mirror). +- Das Backup wird nicht automatisch verschlüsselt. + +--- + +## Empfohlene Prüfung nach einem Upgrade + +Dienststatus: + +```bash +systemctl status netbox netbox-rq --no-pager +``` + +Fehler in den Logs: + +```bash +journalctl -u netbox -u netbox-rq --since "15 minutes ago" --no-pager +``` + +Weboberfläche prüfen: + +- Anmeldung funktioniert +- Startseite lädt ohne Fehler +- Objekte und IPAM-Daten sind vorhanden +- Bilder und Dokumente sind erreichbar +- Custom Scripts und Reports sind vorhanden +- Hintergrundjobs werden verarbeitet +- LDAP-Anmeldung funktioniert +- Plugins werden geladen +- API-Aufrufe funktionieren + +Installierte Version über die NetBox-Weboberfläche oder die lokale Installation kontrollieren. + +Alte Installation und Backup erst entfernen, wenn die neue Version erfolgreich geprüft und für stabil befunden wurde. + +--- + +## Beispiel für einen sicheren Upgrade-Ablauf + +```bash +# 1. Tool starten +sudo /usr/local/sbin/netbox-tool + +# 2. Menüpunkt 3 wählen – das Backup wird automatisch erstellt: +# /srv/backups/netbox/netbox_pre_upgrade_v4.6.5_20260720_143500.zip + +# 3. Backup extern sichern +scp /srv/backups/netbox/netbox_pre_upgrade_v4.6.5_20260720_143500.zip \ + backupserver:/srv/backups/netbox/ + +# 4. Prüfsumme speichern +sha256sum /srv/backups/netbox/netbox_pre_upgrade_v4.6.5_20260720_143500.zip \ + > /srv/backups/netbox/netbox_pre_upgrade_v4.6.5_20260720_143500.zip.sha256 + +# 5. Nach dem Upgrade Dienste und Logs prüfen +systemctl status netbox netbox-rq --no-pager +journalctl -u netbox -u netbox-rq --since "15 minutes ago" --no-pager +``` + +--- + +## Haftungsausschluss + +Die Nutzung erfolgt auf eigene Verantwortung. Ein Upgrade kann durch inkompatible Plugins, geänderte Konfigurationsoptionen, Datenbankmigrationen, fehlende Abhängigkeiten oder lokale Anpassungen fehlschlagen. + +Vor produktiven Änderungen sollten immer vorhanden sein: + +- ein getestetes Datenbankbackup +- ein getestetes Media-Backup +- ein dokumentierter Rollback-Plan +- ein Wartungsfenster +- Zugriff auf System- und Datenbankkonsole +- eine getestete Wiederherstellung auf einer separaten Instanz \ No newline at end of file diff --git a/README.md b/README.md index cda83f1..3fb1895 100644 --- a/README.md +++ b/README.md @@ -1,66 +1,58 @@ # NetBox Backup, Restore & Upgrade Tool -An interactive Python tool to back up, restore and upgrade a NetBox -installation on Linux. +🇩🇪 [Deutsche Version](README.de.md) -| | | -|---|---| -| **Type** | Interactive command-line tool (Python, standard library only) | -| **Platform** | Linux server running NetBox, with `systemd` | -| **Python** | `>=3.8` | -| **Repository** | | +An interactive Python tool for backing up, restoring and upgrading a NetBox installation on Linux. -> [!IMPORTANT] -> This is not an official tool of the NetBox project. Test backup, restore and -> upgrade on a test instance first. Keep a current, externally stored backup -> before every upgrade. - -## Contents - -1. [Features](#features) -2. [Requirements](#requirements) -3. [Installation](#installation) -4. [Quick start](#quick-start) -5. [Configuration](#configuration) -6. [Creating a backup](#creating-a-backup) -7. [Restoring a backup](#restoring-a-backup) -8. [Upgrading NetBox](#upgrading-netbox) -9. [Carried-over files and directories](#carried-over-files-and-directories) -10. [Plugins and LDAP](#plugins-and-ldap) -11. [CSRF trusted origins](#csrf-trusted-origins) -12. [Rollback behaviour](#rollback-behaviour) -13. [Backup layout](#backup-layout) -14. [Troubleshooting](#troubleshooting) -15. [Security notes](#security-notes) -16. [Known limitations](#known-limitations) - -The tool's menus and prompts are in German; this README quotes them verbatim -with an English translation. - -## Features +The script combines the following tasks in a simple terminal interface: - Back up the PostgreSQL database - Back up NetBox media files -- Store backups as a ZIP file -- Restore database and media files +- Back up the complete installation files (configuration, `local_requirements.txt`, LDAP settings, scripts, reports, ...) +- Store everything in a single ZIP file +- Restore everything or individual components (database, media, installation files) via a restore menu - Download and install new NetBox releases -- Carry over configuration, LDAP settings, plugins, media files, reports and - custom scripts -- Stop, start and check the NetBox services +- Automatically create a full backup before every upgrade +- Carry over configuration, LDAP settings, plugins, media files, reports and custom scripts +- Stop, start and verify the NetBox services - Keep the previous installation for a possible rollback +> [!IMPORTANT] +> This project is not an official tool of the NetBox project. Test backup, restore and upgrade on a test instance first. Always keep a current backup stored on another system before upgrading. + +--- + +## Table of contents + +1. [Requirements](#requirements) +2. [Installation](#installation) +3. [Quick start](#quick-start) +4. [Configuration](#configuration) +5. [Creating a backup](#creating-a-backup) +6. [Restore menu](#restore-menu) +7. [Upgrading NetBox](#upgrading-netbox) +8. [Files and directories carried over](#files-and-directories-carried-over) +9. [Plugins and LDAP](#plugins-and-ldap) +10. [CSRF trusted origins](#csrf-trusted-origins) +11. [Rollback behaviour](#rollback-behaviour) +12. [Backup layout](#backup-layout) +13. [Troubleshooting](#troubleshooting) +14. [Security notes](#security-notes) +15. [Known limitations](#known-limitations) + +--- + ## Requirements ### Operating system -The tool targets a classic NetBox installation on Linux. The upgrade function -requires: +The tool targets a classic NetBox installation on Linux. Restore and upgrade require: - Linux or another POSIX system - `systemd` - root privileges -- write access to `/opt` -- internet access to GitHub +- write access to `/opt` (or the parent directory of `netbox_path`) +- internet access to GitHub (upgrade only) ### Python @@ -70,23 +62,28 @@ requires: ### System programs -| Program | Used for | +| Program | Purpose | |---|---| -| `pg_dump` | Back up the PostgreSQL database | +| `pg_dump` | Back up the PostgreSQL database (also required for the automatic pre-upgrade backup) | | `pg_restore` | Restore a PostgreSQL dump | -| `dropdb` | Drop the existing target database on restore | +| `dropdb` | Drop the existing target database during restore | | `createdb` | Re-create the target database | | `systemctl` | Stop and start the NetBox services | -| `cp` | Carry over configuration and local data on upgrade | +| `cp` | Carry over configuration and local data during upgrade | | `chown` | Set the owner of restored media files | -| `git` | Optional, to detect the installed NetBox version | +| `git` | Optional, used to detect the installed NetBox version | -On Debian or Ubuntu, the PostgreSQL client programs are provided by the -`postgresql-client` package, for example. +On Debian or Ubuntu the PostgreSQL client programs are provided by the `postgresql-client` package. ### NetBox directory layout -By default the tool expects NetBox under `/opt/netbox`, including: +By default the tool expects NetBox in: + +```text +/opt/netbox +``` + +Among others, these paths are expected: ```text /opt/netbox/upgrade.sh @@ -94,7 +91,7 @@ By default the tool expects NetBox under `/opt/netbox`, including: /opt/netbox/netbox/media/ ``` -`/opt/netbox` may be a regular directory or a symlink to a versioned directory. +`/opt/netbox` may be a regular directory or a symlink to a version-specific directory. ### NetBox services @@ -105,69 +102,71 @@ netbox netbox-rq ``` -For different unit names, adjust the `NETBOX_SERVICES` constant in the script. +If your unit names differ, adjust the `NETBOX_SERVICES` constant in the script. + +--- ## Installation Copy the script to `/usr/local/sbin` or another suitable directory: ```bash -sudo cp netbox_backup_restore_upgrade.py /usr/local/sbin/netbox-tool -sudo chmod 750 /usr/local/sbin/netbox-tool +sudo cp nettmanage.py /usr/local/sbin/netbox-tool +sudo chmod 700 /usr/local/sbin/netbox-tool sudo chown root:root /usr/local/sbin/netbox-tool ``` -Then start it: +Then run it: ```bash sudo /usr/local/sbin/netbox-tool ``` -Or run it directly from the current folder: +Or run it directly from the current directory: ```bash -chmod +x netbox_backup_restore_upgrade.py -sudo ./netbox_backup_restore_upgrade.py +chmod +x nettmanage.py +sudo ./nettmanage.py ``` Optionally check the Python syntax first: ```bash -python3 -m py_compile netbox_backup_restore_upgrade.py +python3 -m py_compile nettmanage.py ``` +--- + ## Quick start -After starting, the main menu appears: +After starting, the main menu appears (the user interface is in German): ```text ============================================================ NETBOX BACKUP, RESTORE & UPGRADE TOOL ============================================================ - 1. Backup erstellen - 2. Backup wiederherstellen - 3. NetBox upgraden - 4. Einstellungen prüfen / anpassen - 5. Beenden + 1. Backup erstellen (create backup) + 2. Restore-Menü (Backup wiederherstellen) (restore menu) + 3. NetBox upgraden (upgrade NetBox) + 4. Einstellungen prüfen / anpassen (settings) + 5. Beenden (exit) ``` -(1 create backup, 2 restore backup, 3 upgrade NetBox, 4 check/adjust settings, -5 quit) - Recommended order before an upgrade: -1. Check the settings. -2. Create a full database and media backup. -3. Copy the backup file to another system. -4. Read the release notes of the target version. -5. Check plugin compatibility. -6. Start the upgrade. -7. Check web interface, worker, plugins and logs. +1. Check the settings, especially `backup_dir`. +2. Read the release notes of the target version. +3. Check plugin compatibility. +4. Start the upgrade – a full backup is created automatically. +5. Copy the pre-upgrade backup to another system. +6. Check the web UI, worker, plugins and logs. + +--- ## Configuration -The defaults are at the top of the script: +The defaults are defined at the top of the script: ```python CONFIG = { @@ -181,6 +180,8 @@ CONFIG = { } ``` +### Configuration values + | Key | Description | Default | |---|---|---| | `netbox_path` | Active NetBox installation path | `/opt/netbox` | @@ -188,75 +189,89 @@ CONFIG = { | `db_name` | Name of the NetBox database | `netbox` | | `db_user` | PostgreSQL user | `netbox` | | `db_pass` | PostgreSQL password | empty | -| `backup_dir` | Target for backups and temporary archives | `/tmp` | +| `backup_dir` | Target for backups and temporary files; the restore menu lists backups found here | `/tmp` | | `python_path` | Optional Python interpreter for `upgrade.sh` | empty | ### Python version for the upgrade -Normally `upgrade.sh` uses the appropriate default interpreter. If a specific -Python version is required, set it: +Normally `upgrade.sh` uses the appropriate default interpreter. If a specific Python version is required: ```python "python_path": "/usr/bin/python3.12", ``` -The script then sets the `PYTHON` environment variable when calling -`upgrade.sh`. +The script then sets the `PYTHON` environment variable when calling `upgrade.sh`. ### Database password -If `db_pass` is set, it is passed to the PostgreSQL commands via the -`PGPASSWORD` environment variable. +If `db_pass` is set, it is passed to PostgreSQL commands via the `PGPASSWORD` environment variable. -For security, a PostgreSQL password file is often better suited: -`/root/.pgpass`, for example +A PostgreSQL password file is usually the better choice: + +```text +/root/.pgpass +``` + +Example: ```text localhost:5432:netbox:netbox:MY_PASSWORD ``` -with permissions - ```bash chmod 600 /root/.pgpass ``` -`db_pass` can then stay empty in the script. +`db_pass` can then stay empty. > [!NOTE] -> Changes made via **Einstellungen prüfen / anpassen** (check/adjust settings) -> apply only to the running process and are not saved to a file. For permanent -> changes, edit the `CONFIG` block in the script. +> Changes made via the **settings** menu only apply to the running process. They are not saved. For permanent changes edit the `CONFIG` block in the script. + +--- ## Creating a backup -Choose `1. Backup erstellen` in the main menu. +Main menu → `1. Backup erstellen`. -### Options +### Components -The tool asks whether to back up: +The tool asks which components to back up: -- the PostgreSQL database -- media files +1. **PostgreSQL database** (`pg_dump -Fc`) +2. **Media files** (`netbox/media/`) +3. **Installation files** – a complete copy of the NetBox installation directory -For the database backup, the data of certain tables can be skipped. +The installation files contain everything in the (resolved) `netbox_path`, for example: -### Skipping the changelog +- `netbox/netbox/configuration.py` +- `netbox/netbox/ldap_config.py` +- `local_requirements.txt` +- `gunicorn.py` +- `netbox/scripts/`, `netbox/reports/` +- `upgrade.sh` and the NetBox source code of the installed version -With this option, the contents of the `extras_objectchange` table are not -exported: +Excluded, because they are re-created by `upgrade.sh` or backed up separately: + +```text +venv/ (virtual environment, re-created by upgrade.sh) +netbox/static/ (collectstatic output, re-created by upgrade.sh) +netbox/media/ (backed up as its own component) +__pycache__/ +``` + +File permissions, owners and symlinks are recorded in `files_manifest.json` inside the archive and re-applied on restore. + +### Excluding the change log ```text Changelog (extras_objectchange) auslassen? Spart viel Platz. (j/N) ``` -(Skip changelog? Saves a lot of space. y/N.) The table structure stays in the -dump; only its data is skipped. This can reduce the backup size considerably -when change logging is extensive. +The table structure stays in the dump, only its data is skipped. This can reduce the backup size considerably. -### Skipping users +### Excluding users -The contents of these tables are not exported: +The data of these tables is not exported: ```text auth_user @@ -265,20 +280,21 @@ users_token ``` > [!WARNING] -> Skipping users can lead to foreign-key problems or missing assignments on -> restore. Only use this option if the target system already has matching -> users or you know the consequences exactly. +> Excluding users can cause foreign key errors or missing assignments on restore. Only use this option if the target system already has matching users or you know the consequences. ### Backup file -The file is named after this pattern: - ```text netbox_backup_YYYYMMDD_HHMMSS.zip ``` -for example `/tmp/netbox_backup_20260720_143500.zip`. On success, the tool -shows the full path. +Example: + +```text +/tmp/netbox_backup_20260720_143500.zip +``` + +The ZIP file is created with mode `600` (readable by root only), because it contains the database dump and `configuration.py` including `SECRET_KEY` and database credentials. ### Verifying the backup @@ -286,118 +302,138 @@ shows the full path. ls -lh /tmp/netbox_backup_*.zip unzip -l /tmp/netbox_backup_20260720_143500.zip sha256sum /tmp/netbox_backup_20260720_143500.zip -``` - -Copy the backup to external storage: - -```bash scp /tmp/netbox_backup_20260720_143500.zip backupserver:/srv/backups/netbox/ ``` -Do not leave a backup only in `/tmp`; depending on the system configuration, -this directory may be cleared on reboot. +The contents can also be shown via restore menu → `5. Backup-Inhalt anzeigen`. -## Restoring a backup +Do not keep backups only in `/tmp`; depending on the system it may be cleared on reboot. -Choose `2. Backup wiederherstellen` in the main menu. +--- + +## Restore menu + +Main menu → `2. Restore-Menü`. + +```text + 1. Komplett-Restore (alles, was im Backup enthalten ist) (full restore) + 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) +``` + +Restore must be run as `root` / with `sudo`. > [!CAUTION] -> Restoring overwrites the existing data of the target instance. The configured -> PostgreSQL database is dropped and re-created. +> A restore overwrites the data of the instance. When restoring the database, the configured PostgreSQL database is dropped and re-created. -### Steps +### Selecting a backup -1. Confirm the safety prompt. -2. Enter the full path to the ZIP file. -3. The archive is extracted into a temporary directory. -4. `metadata.json` is checked. -5. If included, the database is dropped and re-created. -6. The PostgreSQL dump is imported. -7. If included, media files are replaced. -8. `upgrade.sh` is run. -9. `netbox` and `netbox-rq` are restarted. +All `netbox_*.zip` files in `backup_dir` are listed, newest first, with size and date. Select one by number or enter any path to a backup ZIP file. + +Before confirming, the tool shows the backup's metadata (date, NetBox version, contained components). If you restore only the database and it comes from a **newer** NetBox version than the installed one, a warning is shown – in that case also restore the installation files. + +### Process + +1. Extract the archive into a temporary directory inside `backup_dir`. +2. Stop `netbox` and `netbox-rq`. +3. Restore the selected components: + - **Installation files:** extracted to a new directory, permissions/owners/symlinks re-applied, then switched in (see below). If media is not restored at the same time, the current media files are copied into the restored installation. + - **Database:** `dropdb`, `createdb`, `pg_restore`. + - **Media:** replace `netbox/media/` and set the owner to `netbox:netbox`. +4. Run `upgrade.sh` (only if database or installation files were restored). This re-creates the venv, installs `local_requirements.txt`, runs migrations and collects static files. +5. Restart and verify the services. + +If an error occurs, the tool tries to start the services again. + +### Restoring installation files + +The current installation is never deleted: + +| Layout | Behaviour | +|---|---| +| `/opt/netbox` is a directory | current installation is renamed to `/opt/netbox_before_restore_`, the restored files take its place | +| `/opt/netbox` is a symlink | restored files go to `/opt/netbox--restored-`, the symlink is switched atomically; the previous target stays | ### Required database privileges -The configured database user needs sufficient privileges for the restore; in -particular, `dropdb` and `createdb` must work with this user. Check with: +The configured database user must be allowed to run `dropdb` and `createdb`. ```bash sudo -u postgres psql -c "\du" ``` -If the NetBox database user may not create databases, adapt the procedure or -use an administrative PostgreSQL user. - -### Restore command +### pg_restore The dump is imported roughly like this: ```bash -pg_restore \ - -h localhost \ - -U netbox \ - -d netbox \ - --clean \ - --no-owner \ - netbox_database.dump +pg_restore -h localhost -U netbox -d netbox --clean --if-exists --no-owner netbox_database.dump ``` -Messages from `pg_restore` are shown. Since PostgreSQL may return a non-zero -exit code even for individual warnings, the tool reports the restore as -finished and prints any notices. Check the database and the NetBox logs -afterwards. +Because PostgreSQL may return a non-zero exit code for individual warnings, the tool reports the restore as completed and prints the messages. Check the database and NetBox logs afterwards. -### Media files +### Backups from older tool versions -Existing media files under `/opt/netbox/netbox/media` are replaced, and their -owner is then set to `netbox:netbox`. +Backups created before format version 1.3 contain no installation files. They can still be restored; options 1–3 work as before, option 4 reports that the component is missing. + +--- ## Upgrading NetBox -Choose `3. NetBox upgraden` in the main menu. The upgrade must be run as -`root` or with `sudo`. +Main menu → `3. NetBox upgraden`. Must be run as `root` / with `sudo`. ### Target version -The version can be entered with or without a leading `v`, for example `4.6.5` -or `v4.6.5`. Only stable version numbers in the format `X.Y.Z` are accepted; -pre-releases such as `4.6.0-beta1` are rejected. +The version can be entered with or without a leading `v` (`4.6.5` or `v4.6.5`). Only stable versions in the format `X.Y.Z` are accepted; pre-releases such as `4.6.0-beta1` are rejected. ### Version check -The tool tries to detect the installed NetBox version via: +The installed version is detected via: -- the name of the actual installation directory +- the name of the real installation directory - an exact Git tag -- the NetBox Python package in the existing virtual environment +- the NetBox Python package in the existing venv - NetBox version files -The target version must be higher than the detected installed version. -Downgrades are not automated. A detected major-version jump triggers an -additional warning. +The target version must be higher than the installed version. Downgrades are not automated. A major version jump triggers an additional warning. -### Upgrade steps +### Automatic pre-upgrade backup + +Before anything is changed, the tool creates a **full backup** (database, media and installation files): + +```text +netbox_pre_upgrade_vX.Y.Z_YYYYMMDD_HHMMSS.zip +``` + +in `backup_dir`. If `pg_dump` is missing or the backup fails, the upgrade is aborted before anything is changed. + +Skipping the backup is possible but requires typing `OHNE BACKUP` explicitly. + +If the upgrade fails after `upgrade.sh` was started, the tool prints the path of this backup so it can be restored via restore menu → `1. Komplett-Restore`. + +### Upgrade process 1. Validate the target version. 2. Check the existing NetBox installation. -3. Ask for confirmation of backup and release notes. -4. Optionally add the preconfigured plugins. -5. Detect the LDAP configuration. -6. Check or add `CSRF_TRUSTED_ORIGINS`. -7. Download the release archive from GitHub. -8. Safely extract and check the TAR archive. -9. Carry over local files and directories. -10. Stop the services. -11. Switch installation directories or the symlink. -12. Run `/opt/netbox/upgrade.sh`. -13. Restart the services. -14. Check the service status. -15. Keep the old installation as a fallback. +3. Ask for confirmation that the release notes were read. +4. Ask whether to skip the automatic backup (default: no). +5. Optionally add the preconfigured plugins. +6. Detect the LDAP configuration. +7. Check or add `CSRF_TRUSTED_ORIGINS`. +8. **Create the full pre-upgrade backup.** +9. Download the release archive from GitHub. +10. Safely extract and verify the TAR archive. +11. Carry over local files and directories. +12. Stop the services. +13. Switch the installation directory or symlink. +14. Run `/opt/netbox/upgrade.sh`. +15. Restart the services and verify their status. +16. Keep the old installation as a fallback. -### Download address - -The release is downloaded from: +### Download URL ```text https://github.com/netbox-community/netbox/archive/refs/tags/vX.Y.Z.tar.gz @@ -407,27 +443,21 @@ The temporary archive is deleted after the upgrade. ### Downtime -Download, extraction and preparation of the new installation happen before the -services are stopped. Downtime only starts when switching to the new -installation. +Backup, download, extraction and preparation happen before the services are stopped. Downtime starts with the switch to the new installation. -### Services +--- -`netbox` and `netbox-rq` are stopped before the switch. After a successful -`upgrade.sh`, both are restarted and checked with `systemctl is-active`. +## Files and directories carried over -## Carried-over files and directories +During the upgrade, these items are copied from the existing installation into the new release. -On upgrade, these contents are copied from the existing installation into the -new release. - -### Required file +### Mandatory file ```text netbox/netbox/configuration.py ``` -If this file is missing, the upgrade is aborted. +If it is missing, the upgrade is aborted. ### Optional files @@ -445,24 +475,19 @@ netbox/scripts/ netbox/reports/ ``` -Contents are copied with `cp -a`, preserving permissions, timestamps and -symbolic links. +Copied with `cp -a`, preserving permissions, timestamps and symlinks. -### Customisations that are not carried over +### Not carried over automatically -Manual changes to files of the NetBox source code itself are not detected or -merged — for example directly modified templates, Python files or static files -outside the paths above. Implement such changes as a plugin, custom script or -through a documented deployment process. +Manual changes to NetBox source files (templates, Python files, static files outside the paths above) are not detected or merged during the upgrade. They are, however, part of the installation files backup. Implement such changes as a plugin, custom script or documented deployment step. + +--- ## Plugins and LDAP ### Existing requirements -An existing `/opt/netbox/local_requirements.txt` is carried over and its -entries are kept. The tool recognises package names and does not add a package -again if an unversioned or pinned entry already exists. These are treated as -the same package: +An existing `/opt/netbox/local_requirements.txt` is copied into the new release. Existing entries are kept unchanged. The tool detects package names and does not add a package again if an unversioned or pinned entry already exists: ```text netbox-topology-views @@ -472,8 +497,7 @@ netbox_topology_views>=4.0 ### Preconfigured plugins -On request, the tool adds the entries of the `DEFAULT_PLUGIN_REQUIREMENTS` -constant, which ships with: +On request the tool adds: ```text netbox-topology-views @@ -485,21 +509,18 @@ netbox-inventory git+https://git.mrblake.cc/MrBlake/NetBox-VM-Import.git#egg=netbox_vmware_importer ``` -Adapt this list to your environment before use. +The list is defined in `DEFAULT_PLUGIN_REQUIREMENTS` and can be adapted. ### LDAP -If `/opt/netbox/netbox/netbox/ldap_config.py` exists in the current -installation, the tool: +If `/opt/netbox/netbox/netbox/ldap_config.py` exists: -1. copies `ldap_config.py` into the new installation, and -2. ensures `django-auth-ldap` is in `local_requirements.txt`. +1. `ldap_config.py` is copied into the new installation. +2. `django-auth-ldap` is ensured in `local_requirements.txt`. ### Plugin compatibility -The tool cannot reliably check whether a plugin supports the target NetBox -version; at the latest, this surfaces when `upgrade.sh` installs the -requirements. Before upgrading, check for every plugin: +The tool cannot reliably check whether a plugin supports the target NetBox version. This is checked at the latest when `upgrade.sh` installs the requirements. Before upgrading, check for each plugin: - supported NetBox version - supported Python version @@ -507,8 +528,9 @@ requirements. Before upgrading, check for every plugin: - changed configuration values - known incompatibilities -An incompatible plugin can abort `upgrade.sh` or prevent NetBox from starting -after the restart. +An incompatible plugin can abort `upgrade.sh` or prevent NetBox from starting. + +--- ## CSRF trusted origins @@ -516,161 +538,164 @@ The tool checks whether `configuration.py` contains a direct assignment: ```python CSRF_TRUSTED_ORIGINS = [ - "https://netbox.example.com", + "https://netbox.example.local", ] ``` During the upgrade, new origins can be entered comma-separated: ```text -https://netbox.example.com,http://192.0.2.50 +https://netbox.example.local,http://192.168.1.50 ``` -Only origins with `http://` or `https://`, a host name or IP address and an -optional port are accepted — no path, query or fragment. +Only origins with `http://` or `https://`, a host name or IP, an optional port and no path, query or fragment are accepted. Valid: ```text -https://netbox.example.com -http://192.0.2.50 -https://netbox.example.com:8443 +https://netbox.example.local +http://192.168.1.50 +https://netbox.example.local:8443 ``` Invalid: ```text -netbox.example.com -https://netbox.example.com/netbox -https://netbox.example.com?test=1 +netbox.example.local +https://netbox.example.local/netbox +https://netbox.example.local?test=1 ``` -When new origins are entered, the tool appends a new block to -`configuration.py`: +New origins are appended as a new block to `configuration.py`: ```python # Automatisch durch das NetBox-Upgrade-Tool gesetzt CSRF_TRUSTED_ORIGINS = [ - 'https://netbox.example.com', - 'http://192.0.2.50', + 'https://netbox.example.local', + 'http://192.168.1.50', ] ``` > [!NOTE] -> If a direct assignment already exists and new values are entered as well, the -> file then contains two assignments; in Python the last one wins. Check the -> file after the upgrade and consolidate the setting if needed. +> If a direct assignment already exists and new values are entered, the file contains two assignments afterwards; the last one wins. Review and consolidate the file after the upgrade. -Dynamically imported or programmatically built CSRF settings may not be -detected by this simple check. The tool warns in that case and asks for an -additional confirmation. +Dynamically imported or computed CSRF settings may not be detected. In that case the tool warns and asks for an extra confirmation. + +--- ## Rollback behaviour -Rollback depends on when an error occurs. - ### Error before `upgrade.sh` starts -If the error happens after the directory switch but before `upgrade.sh` -starts, the tool automatically tries to re-activate the previous installation -and restart the NetBox services. At this point, no database migrations of the -new release have run. +If the error occurs after the directory switch but before `upgrade.sh` starts, the tool automatically: -### Error after `upgrade.sh` starts +1. re-activates the previous installation, +2. restarts the NetBox services. -Once `upgrade.sh` has started, there is no automatic full rollback: database -migrations may already have run fully or partially, and switching only the -program directory back could combine an older NetBox with a newer database -schema. +No database migrations of the new release have run at this point. -A full rollback typically requires: +### Error after `upgrade.sh` started -1. Stop the services. -2. Re-activate the previous installation. -3. Restore the database from the backup made before the upgrade. -4. Restore media files from the same backup if needed. -5. Run the old installation's `upgrade.sh` or the necessary maintenance steps. -6. Start the services and check the logs. +Once `upgrade.sh` has started, there is no automatic full rollback, because database migrations may already have been applied. + +Full rollback using the restore menu: + +1. Restore menu → `1. Komplett-Restore`. +2. Select the `netbox_pre_upgrade_v…` backup. +3. The tool stops the services, restores installation files, database and media, runs `upgrade.sh` of the old version and restarts the services. +4. Check the logs. ### Regular directory -If `/opt/netbox` is a regular directory, the old installation is moved, for -example, to `/opt/netbox_old_20260720_143500`. If that name exists, a running -number is appended. +The old installation is kept, e.g. at: + +```text +/opt/netbox_old_20260720_143500 +``` + +If the name exists, a running number is appended. ### Symlink installation -If `/opt/netbox` is a symlink, the new release is installed, for example, to -`/opt/netbox-4.6.5`, and the symlink is switched atomically. The previous -release directory is kept. The target directory must not exist yet; if -`/opt/netbox-4.6.5` already exists, the tool aborts so no data is overwritten. +The new release is installed, e.g. at `/opt/netbox-4.6.5`, and the `/opt/netbox` symlink is switched atomically. The previous release directory remains. If `/opt/netbox-4.6.5` already exists, the tool aborts. + +--- ## Backup layout -A full ZIP backup looks like this: - ```text netbox_backup_YYYYMMDD_HHMMSS.zip ├── metadata.json -├── netbox_database.dump -└── media/ +├── netbox_database.dump (database) +├── media/ (media files) +├── files_manifest.json (permissions, owners, symlinks of the installation files) +└── files/ (installation files) + ├── upgrade.sh + ├── local_requirements.txt + ├── gunicorn.py + └── netbox/ + ├── netbox/configuration.py + ├── netbox/ldap_config.py + ├── scripts/ + └── reports/ ``` -Depending on the chosen scope, `netbox_database.dump` or `media/` may be -missing. +Depending on the chosen scope, individual parts may be missing. ### Metadata -Example `metadata.json`, used on restore to determine the included scope: - ```json { - "version": "1.2", + "version": "1.3", "timestamp": "20260720_143500", "source_db": "netbox", + "netbox_path": "/opt/netbox", + "netbox_root": "/opt/netbox-4.6.4", + "netbox_version": "4.6.4", "contains_db": true, "contains_media": true, + "contains_files": true, "excluded_changelog": false, "excluded_users": false } ``` +The restore uses this file to determine the contained components. + ### Safe extraction -The tool checks ZIP and TAR paths before extracting to prevent path traversal. -TAR archives containing symbolic or hard links are rejected. Still, only use -backups and release archives from trusted sources. +ZIP and TAR paths are checked before extraction to prevent path traversal. TAR archives with symlinks or hard links are rejected. Symlinks of the installation are not stored in the ZIP but re-created from the manifest. Only use backups and release archives from trusted sources. + +--- ## Troubleshooting ### `pg_dump: command not found` -Install the PostgreSQL client: - ```bash sudo apt update sudo apt install postgresql-client ``` -With several PostgreSQL versions, use a client version matching the server. +Use a client version matching the server. Without `pg_dump` the upgrade aborts, because the automatic backup cannot be created. ### PostgreSQL asks for a password -- set `db_pass` in the script, -- configure `/root/.pgpass`, or -- set up local PostgreSQL authentication accordingly. +- set `db_pass` in the script +- configure `/root/.pgpass` +- configure local PostgreSQL authentication ### `dropdb` or `createdb` fails -The configured user probably lacks the required privileges. Check the -PostgreSQL roles: +The configured user probably lacks the required privileges: ```bash sudo -u postgres psql -c "\du" ``` -Alternatively, adapt the restore so administrative database actions run with a -separate PostgreSQL user. +### Restore: "Dienst ... läuft trotz Stop-Befehl weiter" + +A service could not be stopped. Check `systemctl status netbox netbox-rq` and stop it manually before retrying. ### Target version not found @@ -678,27 +703,23 @@ separate PostgreSQL user. NetBox-Release vX.Y.Z wurde auf GitHub nicht gefunden. ``` -(Release not found on GitHub.) Check the spelling of the version, internet -access, DNS resolution, proxy or firewall rules and whether the release exists. +Check the spelling, internet access, DNS, proxy/firewall rules and whether the release exists. ### Download fails behind a proxy -Python usually honours the standard variables: - ```bash -export HTTPS_PROXY=http://proxy.example.com:3128 -export HTTP_PROXY=http://proxy.example.com:3128 -sudo -E ./netbox_backup_restore_upgrade.py +export HTTPS_PROXY=http://proxy.example.local:3128 +export HTTP_PROXY=http://proxy.example.local:3128 +sudo -E ./nettmanage.py ``` -Mind the security implications of `sudo -E`. +Be aware of the security implications of `sudo -E`. ### `configuration.py` is missing -The tool expects `/opt/netbox/netbox/netbox/configuration.py`. Check -`CONFIG["netbox_path"]` and the actual NetBox directory layout. +The tool expects `/opt/netbox/netbox/netbox/configuration.py`. Check `CONFIG["netbox_path"]`. -### Service does not start after the upgrade +### Service does not start after upgrade or restore ```bash systemctl status netbox --no-pager -l @@ -707,70 +728,49 @@ journalctl -u netbox -n 200 --no-pager journalctl -u netbox-rq -n 200 --no-pager ``` -Common causes: an incompatible plugin, a wrong Python version, a missing system -library, errors in `configuration.py` or `ldap_config.py`, an incomplete -database migration, wrong file permissions or changed NetBox configuration -options. +Common causes: incompatible plugin, wrong Python version, missing system library, errors in `configuration.py` or `ldap_config.py`, incomplete migrations, wrong file permissions, changed configuration options. -### `upgrade.sh` fails on a plugin +### `upgrade.sh` fails because of a plugin -Temporarily comment out or remove the plugin in `local_requirements.txt`, if -that is acceptable for the migration in question. Then check the plugin -documentation and enter a compatible version. Always make sure a full backup -exists before making changes. +Temporarily comment out or remove the plugin in `local_requirements.txt`, if that is acceptable for the migration, then install a compatible version. Make sure a full backup exists first. ### Wrong Python interpreter -Set it in the settings menu or permanently in the `CONFIG` block: - ```python "python_path": "/usr/bin/python3.12", ``` -Check the path: - ```bash -ls -l /usr/bin/python3.12 /usr/bin/python3.12 --version ``` ### Media files have wrong permissions ```bash -ls -ld /opt/netbox/netbox/media -find /opt/netbox/netbox/media -maxdepth 2 -printf '%u:%g %p\n' | head sudo chown -R netbox:netbox /opt/netbox/netbox/media ``` -### Upgrade interrupted with Ctrl+C +### Upgrade or restore interrupted with Ctrl+C -The global `KeyboardInterrupt` handler terminates the program. If `upgrade.sh` -had already started, do not assume an automatic rollback happened: +The program exits. If `upgrade.sh` had already started, do not assume a rollback happened: 1. Check the service status. -2. Check the process list for running upgrade, pip or migration processes. +2. Check for running upgrade, pip or migration processes. 3. Check the installation path and symlink target. 4. Do not reset the database schema without a backup. -5. Evaluate the logs and the upgrade output. +5. Review the output and logs. + +--- ## Security notes ### Root privileges -Depending on file permissions, backup functions may work without root. Restore -and upgrade need elevated privileges for access to `/opt/netbox`, -`systemctl`, `chown` and the directory switch, so run the tool with `sudo` for -administrative tasks. +Backups may work without root depending on file permissions. Restore and upgrade require root for `/opt/netbox`, `systemctl`, `chown` and the directory switch. ### Passwords in the source code -A database password in the `CONFIG` block is readable by every user who can -read the script. Recommendations: - -- provide the password via `.pgpass` where possible -- make the script readable by root only -- never commit scripts with credentials to public repositories -- store backups encrypted +A database password in the `CONFIG` block is readable by anyone who can read the script. Prefer `.pgpass`, make the script readable by root only and never commit credentials. ```bash sudo chown root:root /usr/local/sbin/netbox-tool @@ -779,16 +779,13 @@ sudo chmod 700 /usr/local/sbin/netbox-tool ### Protecting backups -A NetBox database backup can contain sensitive information such as user -accounts, API tokens, device and site data, IP addresses, secrets from plugins, -documents and images. Backups should be transferred and stored encrypted, be -accessible only to authorised people and be deleted according to a defined -retention plan. +A backup contains sensitive data: user accounts, API tokens, device and location data, IP addresses, plugin secrets, documents and images, and – with installation files – `configuration.py` including `SECRET_KEY` and database credentials. + +Backups are created with mode `600`. They should also be transferred and stored encrypted, be accessible only to authorised persons and be deleted according to a retention plan. ### `/tmp` as backup target -`/tmp` is a convenient default but not suitable as permanent backup storage. -Change `backup_dir`, for example: +`/tmp` is convenient as a default but not suitable as permanent backup storage. Change `backup_dir`, for example: ```python "backup_dir": "/srv/backups/netbox", @@ -800,30 +797,28 @@ sudo install -d -m 700 -o root -g root /srv/backups/netbox ### Release and plugin sources -The NetBox release is downloaded from GitHub, and one plugin requirement points -to an external Git server. Before use, check trust in the source, reachability, -the TLS certificate chain, the desired version or commit pinning, and internal -software supply-chain policies. For reproducible installations, pin plugin -versions or commits. +The NetBox release is downloaded from GitHub, one plugin requirement points to an external Git server. Check trust, availability, TLS, version/commit pinning and your supply chain policies. + +--- ## Known limitations -- Settings changed in the menu are not saved permanently. +- Settings changed in the menu are not saved. - Plugin compatibility is not checked in advance. -- NetBox release notes are not read or interpreted automatically. -- Major upgrade paths only trigger a warning and are not fully validated. -- An automatic database rollback after a started migration is intentionally not - implemented. -- PostgreSQL backup and restore use the same configured database user. +- Release notes are not read or interpreted automatically. +- Major upgrade paths are only warned about, not fully validated. +- An automatic database rollback after migrations started is intentionally not implemented; use the restore menu with the pre-upgrade backup. +- Backup and restore use the same configured database user. - The service names `netbox` and `netbox-rq` are hard-coded. -- Additional services such as a separate housekeeping service, reverse proxy or - monitoring agent are not restarted. -- Manual changes to the NetBox source code are not carried over. -- Newly entered CSRF origins are appended as an additional block instead of - editing an existing one. -- No automatic HTTP health check of the NetBox web interface. -- No automatic backup rotation. +- Additional services (housekeeping, reverse proxy, monitoring) are not restarted. +- Manual changes to the NetBox source are not carried over during upgrade (but are included in the installation files backup). +- New CSRF origins are appended as an additional block instead of editing an existing one. +- No automatic HTTP health check of the web UI. +- No automatic backup rotation – pre-upgrade backups accumulate in `backup_dir`. - Backups are not encrypted automatically. +- The venv is not part of the backup; it is re-created by `upgrade.sh` on restore, which requires access to PyPI (or your package mirror). + +--- ## Recommended checks after an upgrade @@ -832,51 +827,43 @@ systemctl status netbox netbox-rq --no-pager journalctl -u netbox -u netbox-rq --since "15 minutes ago" --no-pager ``` -In the web interface, check that: +In the web UI check that login, the start page, objects and IPAM data, images and documents, custom scripts and reports, background jobs, LDAP login, plugins and the API work. -- login works -- the home page loads without errors -- objects and IPAM data are present -- images and documents are reachable -- custom scripts and reports are present -- background jobs are processed -- LDAP login works -- plugins are loaded -- API calls work +Only remove the old installation and the backup once the new version has been verified and is stable. -Check the installed version in the web interface or the local installation. -Only remove the old installation and the backup once the new version has been -verified and found stable. +--- ## Example of a safe upgrade ```bash -# 1. Start the tool +# 1. Start the tool and choose menu item 3 (upgrade) sudo /usr/local/sbin/netbox-tool +# -> a full backup is created automatically: +# /srv/backups/netbox/netbox_pre_upgrade_v4.6.5_20260720_143500.zip -# 2. Choose menu item 1 and create a full backup - -# 3. Store the backup externally -scp /srv/backups/netbox/netbox_backup_20260720_143500.zip \ +# 2. Copy the backup to another system +scp /srv/backups/netbox/netbox_pre_upgrade_v4.6.5_20260720_143500.zip \ backupserver:/srv/backups/netbox/ -# 4. Save a checksum -sha256sum /srv/backups/netbox/netbox_backup_20260720_143500.zip \ - > /srv/backups/netbox/netbox_backup_20260720_143500.zip.sha256 +# 3. Store a checksum +sha256sum /srv/backups/netbox/netbox_pre_upgrade_v4.6.5_20260720_143500.zip \ + > /srv/backups/netbox/netbox_pre_upgrade_v4.6.5_20260720_143500.zip.sha256 -# 5. Start the tool again and choose menu item 3 -sudo /usr/local/sbin/netbox-tool - -# 6. After the upgrade, check services and logs +# 4. Check services and logs systemctl status netbox netbox-rq --no-pager journalctl -u netbox -u netbox-rq --since "15 minutes ago" --no-pager + +# If something is wrong: start the tool, menu 2 -> 1 (full restore) +# and select the pre-upgrade backup. ``` +--- + ## Disclaimer -Use at your own risk. An upgrade can fail because of incompatible plugins, -changed configuration options, database migrations, missing dependencies or -local customisations. Before production changes, always have: +Use at your own risk. An upgrade can fail due to incompatible plugins, changed configuration options, database migrations, missing dependencies or local changes. + +Before production changes, always have: - a tested database backup - a tested media backup diff --git a/nettmanage.py b/nettmanage.py index b0d11a7..07f024b 100644 --- a/nettmanage.py +++ b/nettmanage.py @@ -3,6 +3,7 @@ import json import os import re import shutil +import stat import subprocess import sys import tarfile @@ -44,6 +45,12 @@ DEFAULT_PLUGIN_REQUIREMENTS = ( ) 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 @@ -178,26 +185,115 @@ def execute_backup(): ) 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.") pause() return - media_path = os.path.join(CONFIG["netbox_path"], "netbox/media") - stamp = datetime.now().strftime("%Y%m%d_%H%M%S") - archive_name = f"netbox_backup_{stamp}" - zip_file_path = os.path.join(CONFIG["backup_dir"], f"{archive_name}.zip") - tmp_dir = os.path.join(CONFIG["backup_dir"], f"nb_tmp_{stamp}") + try: + zip_file_path = create_backup( + do_db=do_db, + do_media=do_media, + 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: # 1. Datenbank-Dump + dump_file = os.path.join(tmp_dir, "netbox_database.dump") if do_db: log_info("\nSchritt 1: Erstelle PostgreSQL-Datenbank-Dump...") - dump_file = os.path.join(tmp_dir, "netbox_database.dump") - env = os.environ.copy() if CONFIG["db_pass"]: env["PGPASSWORD"] = CONFIG["db_pass"] @@ -231,7 +327,6 @@ def execute_backup(): log_info(" -> Benutzer-Daten werden übersprungen.") process = run_command(cmd, env=env, capture=True) - if process.returncode != 0: log_error(f"pg_dump fehlgeschlagen: {process.stderr}") raise RuntimeError("Datenbank-Backup fehlgeschlagen.") @@ -240,196 +335,439 @@ def execute_backup(): log_info("\nSchritt 1: Datenbank-Backup übersprungen.") # 2. Media-Dateien + media_files = [] if do_media: - log_info("Schritt 2: Kopiere Media-Dateien (Bilder, Dokumente)...") - if os.path.exists(media_path): - dst_media = os.path.join(tmp_dir, "media") - shutil.copytree(media_path, dst_media, dirs_exist_ok=True) - log_success("Media-Ordner erfolgreich gesichert.") + log_info("Schritt 2: Sammle Media-Dateien (Bilder, Dokumente)...") + if os.path.isdir(media_path): + for current, _, filenames in os.walk(media_path): + for filename in filenames: + 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: log_warn(f"Kein Media-Verzeichnis unter {media_path} gefunden.") else: log_info("Schritt 2: Media-Backup übersprungen.") - # 3. Metadaten - log_info("Schritt 3: Erstelle Metadaten...") + # 3. Installationsdateien + 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 = { - "version": "1.2", + "version": BACKUP_FORMAT_VERSION, "timestamp": stamp, "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_media": do_media, + "contains_files": do_files, "excluded_changelog": exclude_changelog, "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 - log_info(f"Schritt 4: Komprimiere Daten nach {zip_file_path} ...") - with zipfile.ZipFile(zip_file_path, "w", zipfile.ZIP_DEFLATED) as zipf: - for root, _, files in os.walk(tmp_dir): - for filename in files: - full_path = os.path.join(root, filename) - rel_path = os.path.relpath(full_path, tmp_dir) - zipf.write(full_path, rel_path) - - 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}") + # 5. ZIP erstellen (nur für root lesbar, da Konfiguration und Dump Geheimnisse enthalten) + log_info(f"Schritt 5: Komprimiere Daten nach {zip_file_path} ...") + fd = os.open(zip_file_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + zip_created = True + with os.fdopen(fd, "wb") as raw_handle, zipfile.ZipFile( + raw_handle, "w", zipfile.ZIP_DEFLATED, allowZip64=True + ) as zipf: + zipf.writestr("metadata.json", json.dumps(meta, indent=4)) + if do_db: + zipf.write(dump_file, "netbox_database.dump") + for full_path, rel_path in media_files: + zipf.write(full_path, f"media/{rel_path}") + if do_files: + zipf.writestr("files_manifest.json", json.dumps(manifest, indent=1)) + for full_path, rel_path in install_files: + 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: if os.path.exists(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") - 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.") pause() 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") - tmp_extract_dir = f"/tmp/nb_restore_{stamp}" - os.makedirs(tmp_extract_dir, exist_ok=True) + os.makedirs(CONFIG["backup_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: log_info(f"\nSchritt 1: Entpacke {restore_file} ...") with zipfile.ZipFile(restore_file, "r") as zipf: safe_extract_zip(zipf, tmp_extract_dir) - meta_file = os.path.join(tmp_extract_dir, "metadata.json") - if not os.path.exists(meta_file): - raise RuntimeError("Ungültiges Backup: metadata.json fehlt.") + log_info("Schritt 2: Stoppe NetBox-Dienste...") + stop_services() + services_stopped = True - with open(meta_file, "r", encoding="utf-8") as file_handle: - meta = json.load(file_handle) - - # 2. Datenbank-Restore - if meta.get("contains_db", True): - log_info("Schritt 2: Stelle PostgreSQL-Datenbank wieder her...") - dump_file = os.path.join(tmp_extract_dir, "netbox_database.dump") - 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 "files" in selected: + log_info("Schritt 3a: Stelle Installationsdateien wieder her...") + file_switch = restore_installation_files( + tmp_extract_dir, + meta, + stamp, + keep_current_media="media" not in selected, ) - if drop_proc.returncode != 0: - raise RuntimeError(f"dropdb fehlgeschlagen: {drop_proc.stderr.strip()}") + log_success(f"Installation wiederhergestellt unter: {file_switch['new_path']}") + if file_switch.get("old_path"): + log_info(f" -> Bisherige Installation verbleibt unter: {file_switch['old_path']}") - 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()}") + if "db" in selected: + log_info("Schritt 3b: Stelle PostgreSQL-Datenbank wieder her...") + restore_database(os.path.join(tmp_extract_dir, "netbox_database.dump")) - log_info("Importiere Dump...") - proc_restore = run_command( - [ - "pg_restore", - "-h", - CONFIG["db_host"], - "-U", - CONFIG["db_user"], - "-d", - CONFIG["db_name"], - "--clean", - "--no-owner", - dump_file, - ], - env=env, - capture=True, - ) + if "media" in selected: + log_info("Schritt 3c: Stelle Media-Dateien wieder her...") + restore_media(os.path.join(tmp_extract_dir, "media")) - 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.") + 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 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...") restart_services(strict=True) + services_stopped = False print("\n" + "=" * 60) log_success("RESTORE ERFOLGREICH ABGESCHLOSSEN!") @@ -437,12 +775,54 @@ def execute_restore(): except Exception as 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: if os.path.exists(tmp_extract_dir): shutil.rmtree(tmp_extract_dir) 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 # ========================================== @@ -864,13 +1244,24 @@ def execute_upgrade(): ) 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}") - if input("Backup erstellt und Release Notes geprüft? (j/N): ").strip().lower() != "j": - log_info("Upgrade abgebrochen. Bitte zuerst Backup und Release Notes prüfen.") + if input("Release Notes geprüft? (j/N): ").strip().lower() != "j": + log_info("Upgrade abgebrochen. Bitte zuerst die Release Notes prüfen.") pause() 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 = ( input("Genannte Standard-Plugins in local_requirements.txt ergänzen? (J/n): ") .strip() @@ -929,6 +1320,7 @@ def execute_upgrade(): switch_state = None services_stopped = False upgrade_started = False + backup_file = None try: if not shutil.which("cp"): @@ -937,6 +1329,16 @@ def execute_upgrade(): raise RuntimeError("Der Befehl 'systemctl' wurde nicht gefunden.") 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( prefix=f"netbox-v{target_version}-", suffix=".tar.gz", @@ -1053,7 +1455,13 @@ def execute_upgrade(): "Datenbank-Migrationen könnten bereits angewendet worden sein." ) 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: restart_services(strict=False) services_stopped = False @@ -1102,7 +1510,7 @@ def main_menu(): while True: print_header("NETBOX BACKUP, RESTORE & UPGRADE TOOL") 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}4.{Colors.ENDC} Einstellungen prüfen / anpassen") print(f" {Colors.BOLD}5.{Colors.ENDC} Beenden\n") @@ -1112,7 +1520,7 @@ def main_menu(): if choice == "1": execute_backup() elif choice == "2": - execute_restore() + restore_menu() elif choice == "3": execute_upgrade() elif choice == "4":