Back up plugin files referenced by model FileFields
- Scan all Django models (incl. plugins) for FileFields via manage.py shell, like the NetBox-Export plugin, and use the real MEDIA_ROOT - Store files outside MEDIA_ROOT under extra_files/ and restore them to their original path (mapped onto the current installation) - Warn about missing files and files in external storages - Bump backup format to 1.4, document in READMEs Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
c6dcb9567c
commit
0f054ef109
3 files changed
+144
-14
No files matched your search
+3
-1
@@ -435,7 +435,9 @@ Meldungen von `pg_restore` werden angezeigt. Da PostgreSQL auch bei einzelnen Wa
|
||||
|
||||
### Media-Dateien
|
||||
|
||||
Vorhandene Media-Dateien unter folgendem Pfad werden ersetzt:
|
||||
Beim Backup fragt das Tool NetBox selbst (über `manage.py shell` im venv) nach dem tatsächlichen `MEDIA_ROOT` und nach allen Dateien, die Modelle – auch von Plugins – über ein `FileField` referenzieren (Ansatz wie im Plugin [NetBox-Export](https://git.mrblake.cc/MrBlake/NetBox-Export)). Dateien außerhalb von `MEDIA_ROOT` werden zusätzlich unter `extra_files/` gesichert und beim Restore an ihren ursprünglichen Pfad zurückgeschrieben (Pfade innerhalb der alten Installation werden auf die aktuelle abgebildet). Fehlende Dateien und Dateien in externen Storages (z. B. S3) werden als Warnung gemeldet. Ohne venv (z. B. defekte Installation) wird nur `MEDIA_ROOT` gesichert.
|
||||
|
||||
Vorhandene Media-Dateien unter folgendem Pfad (bzw. dem gesicherten `MEDIA_ROOT`) werden ersetzt:
|
||||
|
||||
```text
|
||||
/opt/netbox/netbox/media
|
||||
|
||||
@@ -238,7 +238,7 @@ Main menu → `1. Backup erstellen`.
|
||||
The tool asks which components to back up:
|
||||
|
||||
1. **PostgreSQL database** (`pg_dump -Fc`)
|
||||
2. **Media files** (`netbox/media/`)
|
||||
2. **Media files** (`MEDIA_ROOT`, default `netbox/media/`). The tool also asks NetBox (via `manage.py shell` in the venv) for every file referenced by a model `FileField` – including plugins, same approach as [NetBox-Export](https://git.mrblake.cc/MrBlake/NetBox-Export). Files outside `MEDIA_ROOT` are stored under `extra_files/` and written back to their original path on restore. Missing files and files in external storages (e.g. S3) are reported as warnings.
|
||||
3. **Installation files** – a complete copy of the NetBox installation directory
|
||||
|
||||
The installation files contain everything in the (resolved) `netbox_path`, for example:
|
||||
|
||||
+140
-12
@@ -45,7 +45,7 @@ DEFAULT_PLUGIN_REQUIREMENTS = (
|
||||
)
|
||||
LDAP_REQUIREMENT = "django-auth-ldap"
|
||||
|
||||
BACKUP_FORMAT_VERSION = "1.3"
|
||||
BACKUP_FORMAT_VERSION = "1.4"
|
||||
# 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")
|
||||
@@ -271,6 +271,70 @@ def collect_installation_files(root):
|
||||
return files, manifest
|
||||
|
||||
|
||||
# Wird im NetBox-venv per "manage.py shell" ausgeführt (Ansatz wie im NetBox-Export-Plugin):
|
||||
# alle Modelle inkl. Plugins nach FileFields durchsuchen und die echten Dateipfade ermitteln.
|
||||
FILE_SCAN_CODE = r"""
|
||||
import json, os
|
||||
from django.apps import apps
|
||||
from django.conf import settings
|
||||
from django.db import models
|
||||
out = {"media_root": str(settings.MEDIA_ROOT), "files": [], "missing": [], "remote": []}
|
||||
for model in apps.get_models():
|
||||
opts = model._meta
|
||||
if opts.abstract or opts.proxy or not opts.managed:
|
||||
continue
|
||||
fields = [f for f in opts.concrete_fields if isinstance(f, models.FileField)]
|
||||
if not fields:
|
||||
continue
|
||||
for obj in model._default_manager.all().only("pk", *[f.name for f in fields]).iterator():
|
||||
for field in fields:
|
||||
value = getattr(obj, field.name)
|
||||
if not value:
|
||||
continue
|
||||
entry = {"model": opts.label_lower, "field": field.name, "name": str(value.name)}
|
||||
try:
|
||||
path = value.path
|
||||
except (NotImplementedError, AttributeError):
|
||||
out["remote"].append(entry)
|
||||
continue
|
||||
entry["path"] = os.path.realpath(path)
|
||||
out["files" if os.path.isfile(path) else "missing"].append(entry)
|
||||
print("@@NETTRANSFARE@@" + json.dumps(out))
|
||||
"""
|
||||
|
||||
|
||||
def scan_model_files(netbox_root):
|
||||
"""Ermittelt alle von Modellen (auch Plugins) referenzierten Dateien. None, wenn nicht möglich."""
|
||||
python_bin = os.path.join(netbox_root, "venv", "bin", "python")
|
||||
manage_py = os.path.join(netbox_root, "netbox", "manage.py")
|
||||
if not (os.path.isfile(python_bin) and os.path.isfile(manage_py)):
|
||||
log_warn(" -> NetBox-venv nicht gefunden; Plugin-Dateien außerhalb von media/ werden nicht erfasst.")
|
||||
return None
|
||||
proc = run_command(
|
||||
[python_bin, manage_py, "shell", "--no-imports", "-c", FILE_SCAN_CODE],
|
||||
cwd=os.path.dirname(manage_py),
|
||||
capture=True,
|
||||
)
|
||||
if proc.returncode != 0 and "--no-imports" in (proc.stderr or ""):
|
||||
proc = run_command(
|
||||
[python_bin, manage_py, "shell", "-c", FILE_SCAN_CODE],
|
||||
cwd=os.path.dirname(manage_py),
|
||||
capture=True,
|
||||
)
|
||||
for line in reversed((proc.stdout or "").splitlines()):
|
||||
if line.startswith("@@NETTRANSFARE@@"):
|
||||
return json.loads(line[len("@@NETTRANSFARE@@"):])
|
||||
log_warn(f" -> Datei-Scan über Django fehlgeschlagen: {(proc.stderr or '').strip()[-500:]}")
|
||||
return None
|
||||
|
||||
|
||||
def is_within(path, root):
|
||||
try:
|
||||
return os.path.commonpath((os.path.realpath(path), os.path.realpath(root))) == os.path.realpath(root)
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def create_backup(
|
||||
do_db=True,
|
||||
do_media=True,
|
||||
@@ -336,8 +400,14 @@ def create_backup(
|
||||
|
||||
# 2. Media-Dateien
|
||||
media_files = []
|
||||
extra_files = []
|
||||
file_scan = None
|
||||
if do_media:
|
||||
log_info("Schritt 2: Sammle Media-Dateien (Bilder, Dokumente)...")
|
||||
log_info("Schritt 2: Sammle Media-Dateien (Bilder, Dokumente, Plugin-Dateien)...")
|
||||
file_scan = scan_model_files(netbox_root)
|
||||
if file_scan and file_scan.get("media_root"):
|
||||
media_path = os.path.realpath(file_scan["media_root"])
|
||||
log_info(f" -> MEDIA_ROOT laut NetBox: {media_path}")
|
||||
if os.path.isdir(media_path):
|
||||
for current, _, filenames in os.walk(media_path):
|
||||
for filename in filenames:
|
||||
@@ -348,6 +418,28 @@ def create_backup(
|
||||
log_success(f"{len(media_files)} Media-Dateien gefunden.")
|
||||
else:
|
||||
log_warn(f"Kein Media-Verzeichnis unter {media_path} gefunden.")
|
||||
if file_scan:
|
||||
seen = set()
|
||||
for entry in file_scan["files"]:
|
||||
path = entry["path"]
|
||||
if path in seen or is_within(path, media_path):
|
||||
continue
|
||||
seen.add(path)
|
||||
extra_files.append(path)
|
||||
total = len(file_scan["files"])
|
||||
log_success(
|
||||
f"{total} von Modellen referenzierte Dateien geprüft, "
|
||||
f"{len(extra_files)} davon liegen außerhalb von MEDIA_ROOT und werden zusätzlich gesichert."
|
||||
)
|
||||
for entry in file_scan["missing"][:20]:
|
||||
log_warn(f" -> Datei fehlt auf der Platte: {entry['model']}.{entry['field']} = {entry['name']}")
|
||||
if len(file_scan["missing"]) > 20:
|
||||
log_warn(f" -> ... insgesamt {len(file_scan['missing'])} fehlende Dateien.")
|
||||
if file_scan["remote"]:
|
||||
log_warn(
|
||||
f" -> {len(file_scan['remote'])} Dateien liegen in einem externen Storage (z. B. S3) "
|
||||
"und werden nicht gesichert."
|
||||
)
|
||||
else:
|
||||
log_info("Schritt 2: Media-Backup übersprungen.")
|
||||
|
||||
@@ -379,6 +471,8 @@ def create_backup(
|
||||
"contains_db": do_db,
|
||||
"contains_media": do_media,
|
||||
"contains_files": do_files,
|
||||
"media_root": media_path if do_media else None,
|
||||
"extra_files": extra_files,
|
||||
"excluded_changelog": exclude_changelog,
|
||||
"excluded_users": exclude_users,
|
||||
}
|
||||
@@ -395,6 +489,8 @@ def create_backup(
|
||||
zipf.write(dump_file, "netbox_database.dump")
|
||||
for full_path, rel_path in media_files:
|
||||
zipf.write(full_path, f"media/{rel_path}")
|
||||
for full_path in extra_files:
|
||||
zipf.write(full_path, "extra_files/" + full_path.lstrip("/"))
|
||||
if do_files:
|
||||
zipf.writestr("files_manifest.json", json.dumps(manifest, indent=1))
|
||||
for full_path, rel_path in install_files:
|
||||
@@ -474,6 +570,8 @@ def show_backup_info(path, meta):
|
||||
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'))}")
|
||||
if meta.get("extra_files"):
|
||||
print(f" + außerhalb MEDIA_ROOT: {len(meta['extra_files'])} Plugin-Dateien")
|
||||
print(f" Installation: {yes_no(meta.get('contains_files'))}")
|
||||
|
||||
|
||||
@@ -692,16 +790,46 @@ def restore_database(dump_file, as_superuser=False):
|
||||
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):
|
||||
def restore_media(extract_dir, meta):
|
||||
source_media = os.path.join(extract_dir, "media")
|
||||
default_media = os.path.join(CONFIG["netbox_path"], "netbox", "media")
|
||||
old_root = meta.get("netbox_root")
|
||||
new_root = os.path.realpath(CONFIG["netbox_path"])
|
||||
|
||||
def map_path(path):
|
||||
# Pfade in der alten Installation auf die aktuelle Installation abbilden
|
||||
# (z. B. /opt/netbox-4.5.0/... -> /opt/netbox-4.6.1/...).
|
||||
if old_root and is_within(path, old_root):
|
||||
return os.path.join(new_root, os.path.relpath(path, old_root))
|
||||
return path
|
||||
|
||||
media_path = map_path(meta["media_root"]) if meta.get("media_root") else default_media
|
||||
|
||||
if os.path.isdir(source_media):
|
||||
if os.path.exists(media_path):
|
||||
shutil.rmtree(media_path)
|
||||
os.makedirs(os.path.dirname(media_path.rstrip("/")), exist_ok=True)
|
||||
shutil.copytree(source_media, media_path)
|
||||
run_command(["chown", "-R", "netbox:netbox", media_path], capture=True)
|
||||
log_success(f"Media-Dateien wiederhergestellt nach {media_path}.")
|
||||
else:
|
||||
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.")
|
||||
|
||||
extra_source = os.path.join(extract_dir, "extra_files")
|
||||
extra_files = meta.get("extra_files") or []
|
||||
restored = 0
|
||||
for original in extra_files:
|
||||
source = os.path.join(extra_source, *original.lstrip("/").split("/"))
|
||||
target = map_path(original)
|
||||
if not os.path.isfile(source):
|
||||
log_warn(f" -> Zusatzdatei fehlt im Backup: {target}")
|
||||
continue
|
||||
os.makedirs(os.path.dirname(target), exist_ok=True)
|
||||
shutil.copy2(source, target)
|
||||
run_command(["chown", "netbox:netbox", target], capture=True)
|
||||
restored += 1
|
||||
if extra_files:
|
||||
log_success(f"{restored} Plugin-/Zusatzdateien außerhalb von MEDIA_ROOT wiederhergestellt.")
|
||||
|
||||
|
||||
def run_netbox_upgrade_script():
|
||||
@@ -1013,7 +1141,7 @@ def execute_restore(components=None, greenfield=None):
|
||||
|
||||
if "media" in selected:
|
||||
log_info("Schritt 3c: Stelle Media-Dateien wieder her...")
|
||||
restore_media(os.path.join(tmp_extract_dir, "media"))
|
||||
restore_media(tmp_extract_dir, meta)
|
||||
|
||||
if "db" in selected or "files" in selected:
|
||||
log_info("Schritt 4: Führe NetBox upgrade.sh aus (venv, Migrationen, Static Files)...")
|
||||
|
||||
Reference in new issue
Block a user