Compare commits

...
22 Commits
Author SHA1 Message Date
MrBlakeandClaude Opus 5.5 72e04fe086 feat(i18n): translate UI and import messages to English with German catalogue
English is now the source language for the dashboard, forms, menu, JavaScript progress texts and all import/export messages; a complete German catalogue ships as package data. Tenant-error detection also accepts the error code and the active-language message of netbox_utilities, and no longer imports netbox_utilities when it is installed but not enabled. A test keeps the README NetBox range in sync with min_version/max_version.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 21:26:52 +01:00
MrBlakeandClaude Opus 5.5 409b239fca docs: add screenshots and generalise README
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 20:58:12 +01:00
MrBlakeandClaude Opus 5.5 5fd246edb8 feat: add force mode to skip failing objects during import
- Force mode rolls back each failing object via a savepoint, skips it
  with a warning and continues instead of aborting the whole import.
  Unresolvable references and deferred phases (relations, custom field
  values, rack placements, many-to-many, cable paths) are guarded too.
- Skip records with dangling generic references instead of writing NULL
  into non-nullable columns (e.g. NetBox Documentation assignments).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 13:59:45 +02:00
MrBlake b947df022b Merge branch 'main' of https://git.mrblake.cc/MrBlake/NetBox-Export
# Conflicts:
#	README.md
2026-10-19 13:48:51 +02:00
MrBlakeandClaude Opus 5.5 ab4a6c8958 feat: support NetBox Utilities disk management
- Use conditional unique constraints as import identity only when the
  record matches the condition, and filter target candidates by it.
  Replaced disks no longer overwrite active disks in the same slot.
- Export disk bay templates together with their device type dependency.
- Skip records of the optional NetBox Utilities plugin with a warning
  when it is not installed on the target instead of aborting the import.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 13:46:27 +02:00
MrBlakeandClaude Opus 5.5 44149acf16 Fix importing IP ranges
IPRange.save() computes its size from start_address.ip, but the importer assigned the archived addresses as plain strings, so every archive containing IP ranges failed with "'str' object has no attribute 'ip'". Convert values of NetBox IP fields with the field's to_python(). This also affects NetBox 4.6.

IP ranges also had no natural key, so importing into an instance that already contained the range created a duplicate. Match them by (vrf, start_address, end_address).

Verified with a real export and repeated imports on NetBox 4.7.2; the version stays 0.3.14 because Netbox-Utilities only enables its integration for known versions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 15:21:11 +02:00
MrBlakeandClaude Opus 5.5 0fdde044e1 Avoid deprecated select_related() call on Django 6.1
NetBox 4.7.2 ships Django 6.1, which deprecates select_related() without arguments (an error in Django 7). Only call it when the model has foreign keys; behaviour is unchanged. Verified with NetBox 4.7.2. Bump version to 0.3.14, the version Netbox-Utilities already expects for its rack width integration.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 14:14:49 +02:00
MrBlakeandClaude Opus 5.5 9a1e702099 docs: rewrite README in English with standard structure
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-09-30 13:36:42 +02:00
MrBlakeandClaude Sonnet 5 47e9192fda feat: support NetBox 4.7.x
Raise max_version to 4.7.99 and update README references from
NetBox 4.6.x-only to 4.6.x/4.7.x. No plugin API usage requires
changes for 4.7 compatibility (PluginConfig, PluginMenuItem,
get_plugin_config remain stable); full pytest suite passes.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-17 09:24:18 +02:00
MrBlake d183334104 fix: restore PostgreSQL range values during import 2026-09-02 11:11:43 +02:00
MrBlake e44e27d307 fix: preserve cable paths across export and import 2026-08-24 16:41:57 +02:00
MrBlake 05e33a87a9 fix: resize oversized image attachments during import 2026-08-05 15:56:09 +02:00
MrBlake 80469ede34 fix: derive image attachment dimensions during import 2026-08-05 15:43:15 +02:00
MrBlake 4ba41953c1 fix: reconcile rack placement conflicts during import 2026-08-05 15:01:28 +02:00
MrBlake d4ba5de2e7 fix: prevent module component duplication during import 2026-08-05 14:24:46 +02:00
MrBlake 8107e152d2 fix: reconcile component mappings by natural key 2026-08-05 14:05:40 +02:00
MrBlake f22276d68d fix: reassign unique imported relations atomically 2026-08-05 13:56:16 +02:00
MrBlake 3eb1729c93 fix: resolve constrained relations before insert 2026-08-05 13:46:59 +02:00
MrBlake 985b66c96f fix: assign fallback tenant during imports 2026-08-05 13:39:18 +02:00
MrBlake 7a018807d8 fix: honor tenant validation during plugin imports 2026-08-05 13:28:01 +02:00
MrBlake f558832cd2 fix: use form URL for progress requests 2026-08-05 13:13:46 +02:00
MrBlake e061c2b02d fix: tolerate missing external import references 2026-08-05 13:09:47 +02:00
32 changed files with 3312 additions and 244 deletions

No files matched your search

+196 -63
View File
@@ -1,37 +1,74 @@
# NetBox-Export
NetBox-Export ist ein Plugin für NetBox 4.6.x. Es exportiert einen abgegrenzten
Mandanten- oder Standortbereich als portables ZIP-Archiv und importiert ihn in
eine zweite NetBox-Instanz.
Export a scoped tenant or site area as a portable ZIP archive and import it into
a second NetBox instance.
Unterstützte Startpunkte:
| | |
|---|---|
| **Plugin name** | `netbox_export` |
| **Package** | `netbox-export` |
| **NetBox** | `4.6.0` – `4.7.x` |
| **Python** | `>=3.12` |
| **Repository** | <https://git.mrblake.cc/MrBlake/NetBox-Export> |
- Mandantengruppe einschließlich Untergruppen und Mandanten
- einzelner Mandant
- Region einschließlich Unterregionen und Standorten
- einzelner Standort
- Lokation einschließlich Unterlokationen
## Screenshots
Der Export folgt den Besitzbeziehungen zu DCIM-, IPAM-, Circuit-,
Virtualisierungs-, VPN-, Wireless-, Kontakt-, Tag- und Bilddaten. Benötigte
Stammdaten werden als Abhängigkeiten mitgenommen. Primärschlüssel der
Quellinstanz werden nie direkt als Zielschlüssel verwendet.
Export and import page:
![Export and import page](docs/screenshots/export.png)
## Features
Supported starting points:
- tenant group including sub-groups and tenants
- single tenant
- region including sub-regions and sites
- single site
- location including sub-locations
The export follows ownership relations to DCIM, IPAM, circuit, virtualisation,
VPN, wireless, contact, tag and image data. Required master data is included as
dependencies. Primary keys of the source instance are never used directly as
target keys.
## Compatibility
- NetBox `4.6.0` – `4.7.x`
- Python `>=3.12`
- Source and target must run the same NetBox version and the same plugins,
plugin versions and migrations.
## Installation
Das Plugin muss auf beiden NetBox-Instanzen installiert sein.
The plugin must be installed on **both** NetBox instances. All paths assume a
standard installation under `/opt/netbox`.
### 1. Install the package
```bash
cd /opt/netbox
source venv/bin/activate
pip install --upgrade --force-reinstall \
/opt/netbox/venv/bin/pip install --upgrade --force-reinstall \
"git+https://git.mrblake.cc/MrBlake/NetBox-Export.git@main"
# Prüfen, ob das Modul im NetBox-venv verfügbar ist
python -c "import netbox_export; print(netbox_export.__file__)"
```
In `configuration.py` ergänzen:
For reproducible production installs, replace `main` with a release tag or a
full commit ID.
### 2. Add the plugin to `local_requirements.txt`
This makes `upgrade.sh` reinstall the plugin automatically on every NetBox upgrade:
```bash
grep -qxF "git+https://git.mrblake.cc/MrBlake/NetBox-Export.git@main" /opt/netbox/local_requirements.txt \
|| echo "git+https://git.mrblake.cc/MrBlake/NetBox-Export.git@main" | sudo tee -a /opt/netbox/local_requirements.txt
```
If the repository is private, the NetBox server needs a read-only deploy token
or an SSH key. Do not store credentials in `local_requirements.txt`.
### 3. Enable the plugin
In `/opt/netbox/netbox/netbox/configuration.py`:
```python
PLUGINS = [
@@ -43,70 +80,166 @@ PLUGINS_CONFIG = {
"max_objects": 50000,
"max_archive_size_mb": 250,
"query_batch_size": 500,
# Auf beiden Instanzen identisch setzen, um Archive zu signieren.
"archive_signing_key": "eine-lange-zufaellige-geheime-zeichenfolge",
# Set identically on both instances to sign archives.
"archive_signing_key": "a-long-random-secret-string",
},
}
```
Anschließend:
If other plugins are already configured, add `netbox_export` to the existing
list and dictionary instead of replacing them.
### 4. Apply migrations, collect static files, restart
```bash
cd /opt/netbox/netbox
python manage.py migrate netbox_export
python manage.py collectstatic --no-input
/opt/netbox/venv/bin/python manage.py migrate netbox_export
/opt/netbox/venv/bin/python manage.py collectstatic --no-input
sudo systemctl restart netbox netbox-rq
```
Falls `ModuleNotFoundError: No module named 'netbox_export'` erscheint, wurde
das Paket nicht in `/opt/netbox/venv` installiert. In diesem Fall den obigen
Installationsblock erneut ausführen und darauf achten, dass
`/opt/netbox/venv/bin/python` verwendet wird:
If `ModuleNotFoundError: No module named 'netbox_export'` appears, the package
was not installed into `/opt/netbox/venv`. Check with:
```bash
/opt/netbox/venv/bin/python -m pip install --upgrade --force-reinstall \
"git+https://git.mrblake.cc/MrBlake/NetBox-Export.git@main"
/opt/netbox/venv/bin/python -c \
"import netbox_export; print(netbox_export.__file__)"
/opt/netbox/venv/bin/python -c "import netbox_export; print(netbox_export.__file__)"
```
Bei einer Docker-Installation wird das Paket in das eigene NetBox-Image
aufgenommen; danach wird der Container mit dem aktivierten Plugin neu gebaut und
die Migration ausgeführt.
For Docker installations, add the package to your NetBox image, rebuild the
container with the plugin enabled and run the migration.
## Verwendung
## Update
Die Oberfläche liegt unter **Plugins > NetBox-Export > Export / Import** und ist
aus Sicherheitsgründen nur für Superuser sichtbar.
```bash
/opt/netbox/venv/bin/pip install --upgrade --force-reinstall \
"git+https://git.mrblake.cc/MrBlake/NetBox-Export.git@main"
1. Auf Instanz A den Typ und das konkrete Objekt wählen und das ZIP exportieren.
2. Auf Instanz B das ZIP zunächst mit **Nur prüfen** verarbeiten.
3. Nach erfolgreichem Prüflauf **Nur prüfen** deaktivieren, den schreibenden
Import bestätigen und das Archiv erneut hochladen.
cd /opt/netbox/netbox
/opt/netbox/venv/bin/python manage.py migrate netbox_export
/opt/netbox/venv/bin/python manage.py collectstatic --no-input
sudo systemctl restart netbox netbox-rq
```
Der Import läuft atomar. Bei einem Fehler werden alle Datenbankänderungen
zurückgerollt. Die Konfliktstrategie **Aktualisieren** nutzt zuerst die dauerhaft
gespeicherte Zuordnung aus Quellinstanz, Modell und Quell-ID; bei einem ersten
Import werden vorhandene Objekte über ihre eindeutigen Fachschlüssel erkannt.
`--force-reinstall` makes pip pick up branch changes even if the package
version has not been bumped. Update source and target instance together.
## Verhalten und Grenzen
When NetBox itself is upgraded, `upgrade.sh` reinstalls the plugin from
`local_requirements.txt` and runs migrations and `collectstatic`:
- Quelle und Ziel müssen NetBox 4.6.x und dieselben Plugins/Modelle verwenden.
- Benutzerkonten und Berechtigungen werden nicht exportiert. Referenzen auf
Benutzer oder Gruppen müssen auf dem Ziel bereits eindeutig vorhanden sein.
- Der Import erstellt und aktualisiert Objekte. Zielobjekte, die im Archiv nicht
vorkommen, werden bewusst nicht gelöscht.
- Fehlende Bilddateien werden im Archiv vermerkt, können aber nicht rekonstruiert
werden.
- Große Exporte werden synchron verarbeitet. `max_objects` begrenzt Laufzeit und
Speicherverbrauch.
- `query_batch_size` steuert die Größe gebündelter Datenbankabfragen. Der
Standardwert `500` ist für typische PostgreSQL-Installationen geeignet;
Werte zwischen `250` und `1000` erlauben eine Anpassung an Arbeitsspeicher und
Datenbankleistung.
```bash
sudo /opt/netbox/upgrade.sh
sudo systemctl restart netbox netbox-rq
```
## Tests
## Uninstall
1. Remove `"netbox_export"` from `PLUGINS` and `PLUGINS_CONFIG`.
2. Remove the line from `/opt/netbox/local_requirements.txt`.
3. Uninstall the package and restart NetBox:
```bash
/opt/netbox/venv/bin/pip uninstall netbox-export
sudo systemctl restart netbox netbox-rq
```
## Configuration
| Key | Default | Description |
|---|---|---|
| `max_objects` | `50000` | Upper limit of objects per export (runtime and memory) |
| `max_archive_size_mb` | `250` | Maximum archive size |
| `query_batch_size` | `500` | Size of batched database queries; `250`–`1000` is reasonable |
| `archive_signing_key` | – | Shared secret to sign archives; must be identical on both instances |
## Usage
The UI is located under **Plugins > NetBox-Export > Export / Import** and, for
security reasons, is only visible to superusers.
1. On instance A, choose the type and the specific object and export the ZIP.
2. On instance B, first process the ZIP with **Dry run only**.
3. After a successful dry run, disable **Dry run only**, confirm the writing
import and upload the archive again.
The import is atomic: on error, all database changes are rolled back. The
conflict strategy **Update** first uses the stored mapping of source instance,
model and source ID; on a first import, existing objects are matched by their
unique natural keys.
**Force mode** skips objects whose import fails (database errors, unresolvable
references, failing plugin validation) instead of rolling back the whole
import. Each failing object is rolled back individually via a savepoint and
listed as a warning in the import report; references to it are omitted. The
conflict strategy **Abort import** still aborts on existing objects.
### Behaviour and limits
- User accounts and permissions are not exported. Missing or ambiguous user and
group references are omitted and reported as warnings; if a new record
strictly requires such a reference, only that record is skipped.
- The import creates and updates objects. Target objects not contained in the
archive are intentionally **not** deleted.
- Missing image files are noted in the archive but cannot be reconstructed.
- Large exports are processed synchronously; `max_objects` limits runtime and memory.
### Plugin compatibility
- Tenant-related models and files of NetBox-SLM, Netbox-Documentation and
NetBox-VM-Import are included. Private or temporary plugin models are not exported.
- The mandatory tenant assignment of Netbox-Utilities is respected: an object is
only saved after its tenant has been imported. If no tenant can be resolved,
an existing tenant `Auto-Import` is used or created, and the import report
says so.
- Relations checked by plugin database constraints (e.g. the platform of
NetBox-SLM software installations) are resolved before the first save.
- Unique optional relations such as primary IPs of devices and VMs are assigned
in a second phase; stale target assignments are released atomically and logged.
- Stored import mappings are validated against the current natural key on
repeated imports, correcting the mapping instead of creating duplicates.
- Automatic component replication is disabled for new modules; ports,
interfaces and bays are created solely from archive records.
- Devices are placed in racks in a separate final phase so position swaps work
without temporary double occupancy. For foreign occupants, **Update** releases
the target device with a warning, **Skip** leaves the imported device without
a position, and **Abort import** reports the rack conflict. Multi-U and
full-depth occupancy are considered.
- Front/rear port mappings of patch panels are exported as separate records and
synced on **Update**; cable paths are recalculated after import. This requires
an archive created with version `0.3.12` or newer.
- PostgreSQL range fields (e.g. VLAN ID ranges of VLAN groups) are stored typed;
text values from older versions are still recognised.
- Image width and height are read from the archived file. Images above NetBox's
25-megapixel limit are scaled down to at most 20 megapixels with a warning; a
hard source limit of 100 megapixels applies.
- The optional disk management of Netbox-Utilities is fully supported when the
plugin is installed: disks, RAID groups and slot layouts of devices as well as
disk bay templates of the required device types. Replaced disks are not
confused with active disks in the same slot. If Netbox-Utilities is missing on
the target, its records are skipped with a warning instead of aborting the import.
- Encrypted credentials of NetBox-VM-Import are only usable with an identical
Django `SECRET_KEY`; otherwise set the password again on the target.
### Language
The plugin is available in English (source) and German. Switch the display
language as usual in the user profile (**Preferences → Language**); import
reports and error messages follow it. Translations live in
`netbox_export/locale/de/LC_MESSAGES/`.
## Development and tests
```bash
python -m pytest
```
After changing user-visible strings, update and compile the German catalogue:
```bash
cd netbox_export
django-admin makemessages -l de --no-location
msgfmt -o locale/de/LC_MESSAGES/django.mo locale/de/LC_MESSAGES/django.po
```
## License
Apache License 2.0 — see [LICENSE](LICENSE).
Binary file not shown.

After

Width:  |  Height:  |  Size: 106 KiB

+3 -3
View File
@@ -7,11 +7,11 @@ class NetBoxExportConfig(PluginConfig):
name = "netbox_export"
verbose_name = "NetBox-Export"
description = "Portable ZIP export and import for tenants and locations"
version = "0.3.0"
author = "NetBox Export contributors"
version = "0.3.14"
author = "Codex & Claude"
base_url = "netbox-export"
min_version = "4.6.0"
max_version = "4.6.99"
max_version = "4.7.99"
required_settings: ClassVar[list[str]] = []
default_settings: ClassVar[dict] = {
"max_objects": 50000,
+31 -21
View File
@@ -1,26 +1,27 @@
from dcim.models import Location, Region, Site
from django import forms
from django.utils.translation import gettext_lazy as _
from tenancy.models import Tenant, TenantGroup
class ExportForm(forms.Form):
scope_type = forms.ChoiceField(
label="Exportbereich",
label=_("Export scope"),
choices=(
("tenant_group", "Mandantengruppe"),
("tenant", "Mandant"),
("region", "Region"),
("site", "Standort"),
("location", "Lokation"),
("tenant_group", _("Tenant group")),
("tenant", _("Tenant")),
("region", _("Region")),
("site", _("Site")),
("location", _("Location")),
),
)
tenant_group = forms.ModelChoiceField(
label="Mandantengruppe", queryset=TenantGroup.objects.all(), required=False
label=_("Tenant group"), queryset=TenantGroup.objects.all(), required=False
)
tenant = forms.ModelChoiceField(label="Mandant", queryset=Tenant.objects.all(), required=False)
region = forms.ModelChoiceField(label="Region", queryset=Region.objects.all(), required=False)
site = forms.ModelChoiceField(label="Standort", queryset=Site.objects.all(), required=False)
location = forms.ModelChoiceField(label="Lokation", queryset=Location.objects.all(), required=False)
tenant = forms.ModelChoiceField(label=_("Tenant"), queryset=Tenant.objects.all(), required=False)
region = forms.ModelChoiceField(label=_("Region"), queryset=Region.objects.all(), required=False)
site = forms.ModelChoiceField(label=_("Site"), queryset=Site.objects.all(), required=False)
location = forms.ModelChoiceField(label=_("Location"), queryset=Location.objects.all(), required=False)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@@ -32,38 +33,47 @@ class ExportForm(forms.Form):
scope_type = cleaned.get("scope_type")
selected = cleaned.get(scope_type) if scope_type else None
if scope_type and selected is None:
self.add_error(scope_type, "Bitte ein Objekt für den Exportbereich auswählen.")
self.add_error(scope_type, _("Select an object for the export scope."))
cleaned["scope_object"] = selected
return cleaned
class ImportForm(forms.Form):
archive = forms.FileField(
label="NetBox-Export-Archiv",
label=_("NetBox-Export archive"),
widget=forms.ClearableFileInput(attrs={"accept": ".zip,application/zip"}),
)
conflict_strategy = forms.ChoiceField(
label="Vorhandene Objekte",
label=_("Existing objects"),
choices=(
("update", "Aktualisieren"),
("skip", "Überspringen"),
("fail", "Import abbrechen"),
("update", _("Update")),
("skip", _("Skip")),
("fail", _("Abort import")),
),
initial="update",
)
dry_run = forms.BooleanField(
label="Nur prüfen (keine Änderungen)",
label=_("Check only (no changes)"),
required=False,
initial=True,
help_text="Führt den vollständigen Import aus und setzt die Datenbanktransaktion anschließend zurück.",
help_text=_("Runs the complete import and then rolls back the database transaction."),
)
force = forms.BooleanField(
label=_("Force mode (skip errors)"),
required=False,
initial=False,
help_text=_(
"Objects that fail to import are skipped individually instead of rolling back the whole import. "
"Skipped objects are listed as warnings in the report."
),
)
confirm_apply = forms.BooleanField(
label="Ich bestätige den schreibenden Import",
label=_("I confirm the writing import"),
required=False,
)
def clean(self):
cleaned = super().clean()
if not cleaned.get("dry_run") and not cleaned.get("confirm_apply"):
self.add_error("confirm_apply", "Für einen schreibenden Import ist die Bestätigung erforderlich.")
self.add_error("confirm_apply", _("Confirmation is required for a writing import."))
return cleaned
Binary file not shown.
@@ -0,0 +1,428 @@
msgid ""
msgstr ""
"Project-Id-Version: netbox-export\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-10-26 21:17+0100\n"
"PO-Revision-Date: 2026-10-26 21:20+0100\n"
"Language-Team: German\n"
"Language: de\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
msgid "Export scope"
msgstr "Exportbereich"
msgid "Tenant group"
msgstr "Mandantengruppe"
msgid "Tenant"
msgstr "Mandant"
msgid "Region"
msgstr "Region"
msgid "Site"
msgstr "Standort"
msgid "Location"
msgstr "Lokation"
msgid "Select an object for the export scope."
msgstr "Bitte ein Objekt für den Exportbereich auswählen."
msgid "NetBox-Export archive"
msgstr "NetBox-Export-Archiv"
msgid "Existing objects"
msgstr "Vorhandene Objekte"
msgid "Update"
msgstr "Aktualisieren"
msgid "Skip"
msgstr "Überspringen"
msgid "Abort import"
msgstr "Import abbrechen"
msgid "Check only (no changes)"
msgstr "Nur prüfen (keine Änderungen)"
msgid "Runs the complete import and then rolls back the database transaction."
msgstr ""
"Führt den vollständigen Import aus und setzt die Datenbanktransaktion "
"anschließend zurück."
msgid "Force mode (skip errors)"
msgstr "Force-Modus (Fehler überspringen)"
msgid ""
"Objects that fail to import are skipped individually instead of rolling back "
"the whole import. Skipped objects are listed as warnings in the report."
msgstr ""
"Objekte, deren Import fehlschlägt, werden einzeln übersprungen, statt den "
"gesamten Import zurückzurollen. Übersprungene Objekte werden im Bericht als "
"Warnung aufgeführt."
msgid "I confirm the writing import"
msgstr "Ich bestätige den schreibenden Import"
msgid "Confirmation is required for a writing import."
msgstr "Für einen schreibenden Import ist die Bestätigung erforderlich."
msgid "Export / Import"
msgstr "Export / Import"
#, python-format
msgid "Duplicate file path in archive: %(path)s"
msgstr "Doppelter Dateipfad im Archiv: %(path)s"
#, python-format
msgid "Unsafe file path in archive: %(path)s"
msgstr "Unsicherer Dateipfad im Archiv: %(path)s"
msgid "The archive exceeds the configured maximum size."
msgstr "Das Archiv überschreitet die konfigurierte Maximalgröße."
msgid "The uploaded file is not a valid ZIP archive."
msgstr "Die hochgeladene Datei ist kein gültiges ZIP-Archiv."
msgid "The archive contains too many files."
msgstr "Das Archiv enthält zu viele Dateien."
msgid "manifest.json or objects.ndjson is missing from the archive."
msgstr "manifest.json oder objects.ndjson fehlt im Archiv."
msgid "The extracted archive content is too large."
msgstr "Der entpackte Archivinhalt ist zu groß."
msgid "The archive has an impermissible compression ratio."
msgstr "Das Archiv weist ein unzulässiges Kompressionsverhältnis auf."
msgid "The archive metadata is invalid."
msgstr "Die Metadaten im Archiv sind ungültig."
msgid "The archive format or its version is not supported."
msgstr "Das Archivformat oder dessen Version wird nicht unterstützt."
msgid "The object file does not match its checksum."
msgstr "Die Objektdatei stimmt nicht mit ihrer Prüfsumme überein."
msgid "The archive signature is invalid or missing."
msgstr "Die Archivsignatur ist ungültig oder fehlt."
msgid ""
"The archive is signed but was not verified because no key is configured."
msgstr ""
"Das Archiv ist signiert, aber ohne konfigurierten Schlüssel nicht "
"verifiziert."
msgid "The archive is not signed."
msgstr "Das Archiv ist nicht signiert."
msgid "The archive contains too many objects."
msgstr "Das Archiv enthält zu viele Objekte."
msgid "objects.ndjson contains invalid JSON."
msgstr "objects.ndjson enthält ungültiges JSON."
msgid "The file list does not match the manifest."
msgstr "Die Dateiliste stimmt nicht mit dem Manifest überein."
#, python-format
msgid "The checksum of file %(name)s is invalid."
msgstr "Die Prüfsumme der Datei %(name)s ist ungültig."
msgid "The object count does not match the manifest."
msgstr "Die Objektanzahl stimmt nicht mit dem Manifest überein."
#, python-format
msgid ""
"The export would contain more than %(max)s objects. Narrow the scope or "
"increase max_objects."
msgstr ""
"Der Export würde mehr als %(max)s Objekte enthalten. Bitte den Bereich "
"verkleinern oder max_objects erhöhen."
#, python-format
msgid "The model %(model)s is not installed on the target instance."
msgstr "Das Modell %(model)s ist auf der Zielinstanz nicht installiert."
#, python-format
msgid ""
"Stored mapping for %(record)s was corrected from target ID %(old)s to target "
"ID %(new)s because the natural key %(key)s already exists."
msgstr ""
"Gespeicherte Zuordnung für %(record)s wurde von Ziel-ID %(old)s auf Ziel-ID "
"%(new)s korrigiert, da der Fachschlüssel %(key)s bereits existiert."
#, python-format
msgid "Rack reference for %(record)s could not be resolved."
msgstr "Rack-Referenz für %(record)s konnte nicht aufgelöst werden."
#, python-format
msgid "Rack position for %(record)s was omitted because no rack is assigned."
msgstr ""
"Rackplatz für %(record)s wurde ausgelassen, da kein Rack zugeordnet ist."
#, python-format
msgid ""
"Rack position conflict for %(record)s: %(target)s is occupied by target "
"device(s) %(occupants)s."
msgstr ""
"Rackplatzkonflikt für %(record)s: %(target)s ist durch Zielgerät(e) "
"%(occupants)s belegt."
#, python-format
msgid ""
"Rack position for %(record)s was skipped: %(target)s remains occupied by "
"target device(s) %(occupants)s. The imported device was saved without a rack "
"position."
msgstr ""
"Rackplatz für %(record)s wurde übersprungen: %(target)s bleibt durch "
"Zielgerät(e) %(occupants)s belegt. Das importierte Gerät wurde ohne Position"
" im Rack gespeichert."
#, python-format
msgid ""
"Rack position conflict for %(record)s resolved: target device(s) "
"%(occupants)s were removed from %(target)s and left without a rack position."
msgstr ""
"Rackplatzkonflikt für %(record)s gelöst: Zielgerät(e) %(occupants)s wurden "
"aus %(target)s gelöst und ohne Position im Rack belassen."
#, python-format
msgid ""
"Port mapping(s) %(ids)s were replaced by %(record)s so the front/rear port "
"cabling matches the source."
msgstr ""
"Portzuordnung(en) %(ids)s wurden durch %(record)s ersetzt, damit die "
"Front-/Rear-Port-Verkabelung der Quelle entspricht."
#, python-format
msgid "The image exceeds the safe import limit of %(max)s pixels."
msgstr "Das Bild überschreitet die sichere Importgrenze von %(max)s Pixeln."
#, python-format
msgid ""
"The image with %(pixels)s pixels exceeds the safe import limit of %(max)s "
"pixels."
msgstr ""
"Das Bild mit %(pixels)s Pixeln überschreitet die sichere Importgrenze von "
"%(max)s Pixeln."
#, python-format
msgid "Image for %(record)s was downscaled from %(old)s to %(new)s pixels."
msgstr "Bild für %(record)s wurde von %(old)s auf %(new)s Pixel verkleinert."
#, python-format
msgid "M2M reference for %(record)s could not be resolved."
msgstr "M2M-Referenz für %(record)s konnte nicht aufgelöst werden."
#, python-format
msgid "Force mode: %(label)s was skipped because of an error: %(error)s"
msgstr ""
"Force-Modus: %(label)s wurde wegen eines Fehlers übersprungen: %(error)s"
#, python-format
msgid ""
"Objects of type %(model)s were skipped because the related optional plugin "
"is not installed on the target instance."
msgstr ""
"Objekte vom Typ %(model)s wurden übersprungen, da das zugehörige optionale "
"Plugin auf der Zielinstanz nicht installiert ist."
msgid "Unknown conflict strategy."
msgstr "Unbekannte Konfliktstrategie."
#, python-format
msgid ""
"NetBox versions are not compatible: source %(source)s, target %(target)s."
msgstr ""
"NetBox-Versionen sind nicht kompatibel: Quelle %(source)s, Ziel %(target)s."
msgid "The source instance ID is missing or invalid."
msgstr "Die Quellinstanz-Kennung fehlt oder ist ungültig."
msgid "An object record is incomplete."
msgstr "Ein Objektdatensatz ist unvollständig."
#, python-format
msgid "Duplicate object ID in archive: %(record)s"
msgstr "Doppelte Objekt-ID im Archiv: %(record)s"
#, python-format
msgid "Target object already exists: %(record)s"
msgstr "Zielobjekt existiert bereits: %(record)s"
#, python-format
msgid ""
"Force mode: %(count)s object(s) with unresolvable references were skipped: "
"%(blocked)s"
msgstr ""
"Force-Modus: %(count)s Objekt(e) mit nicht auflösbaren Referenzen wurden "
"übersprungen: %(blocked)s"
#, python-format
msgid "Required references could not be resolved: %(blocked)s"
msgstr "Erforderliche Referenzen konnten nicht aufgelöst werden: %(blocked)s"
#, python-format
msgid "Reference %(name)s for %(record)s could not be resolved."
msgstr "Referenz %(name)s für %(record)s konnte nicht aufgelöst werden."
#, python-format
msgid "Reference %(name)s for %(record)s"
msgstr "Referenz %(name)s für %(record)s"
#, python-format
msgid "Generic reference %(name)s for %(record)s is missing."
msgstr "Generische Referenz %(name)s für %(record)s fehlt."
#, python-format
msgid "Generic reference %(name)s for %(record)s"
msgstr "Generische Referenz %(name)s für %(record)s"
#, python-format
msgid "Custom field reference %(name)s for %(record)s is missing."
msgstr "Custom-Field-Referenz %(name)s für %(record)s fehlt."
#, python-format
msgid "Custom field value %(name)s for %(record)s"
msgstr "Custom-Field-Wert %(name)s für %(record)s"
msgid "Rack placement of devices"
msgstr "Rackplatzierung der Geräte"
#, python-format
msgid "Many-to-many assignments for %(record)s"
msgstr "Mehrfachzuordnungen für %(record)s"
msgid "Recalculation of cable paths"
msgstr "Neuberechnung der Kabelpfade"
#, python-format
msgid "The import was rolled back: %(error)s"
msgstr "Der Import wurde zurückgerollt: %(error)s"
msgid ""
"The tenant \"Auto-Import\" was used automatically as a fallback tenant for "
"the dry run; it is not created or changed permanently."
msgstr ""
"Für den Prüflauf wurde der Mandant \"Auto-Import\" automatisch als "
"Ersatzmandant verwendet; er wird nicht dauerhaft angelegt oder geändert."
msgid ""
"The tenant \"Auto-Import\" was created automatically and assigned to objects "
"without a resolvable tenant."
msgstr ""
"Der Mandant \"Auto-Import\" wurde automatisch erstellt und Objekten ohne "
"auflösbaren Mandanten zugewiesen."
msgid ""
"The existing tenant \"Auto-Import\" was selected automatically for objects "
"without a resolvable tenant."
msgstr ""
"Der vorhandene Mandant \"Auto-Import\" wurde automatisch für Objekte ohne "
"auflösbaren Mandanten ausgewählt."
#, python-format
msgid ""
"Unique reference %(field)s was released from target object(s) %(ids)s and "
"reassigned to the imported object."
msgstr ""
"Eindeutige Referenz %(field)s wurde von Zielobjekt(en) %(ids)s gelöst und "
"dem importierten Objekt neu zugeordnet."
#, python-format
msgid ""
"%(record)s (%(model)s) was skipped because of a missing required reference: "
"%(fields)s."
msgstr ""
"%(record)s (%(model)s) wurde wegen fehlender Pflichtreferenz übersprungen: "
"%(fields)s."
msgid "not found"
msgstr "nicht gefunden"
msgid "not unique"
msgstr "nicht eindeutig"
#, python-format
msgid "External reference omitted: %(model)s with %(lookup)s (%(reason)s)."
msgstr "Externe Referenz ausgelassen: %(model)s mit %(lookup)s (%(reason)s)."
#, python-format
msgid "References to the skipped object %(record)s were omitted."
msgstr "Referenzen auf das übersprungene Objekt %(record)s wurden ausgelassen."
msgid "An object reference in the archive is invalid."
msgstr "Eine Objektreferenz im Archiv ist ungültig."
msgid "Dry run successful"
msgstr "Prüflauf erfolgreich"
msgid "Import completed"
msgstr "Import abgeschlossen"
#, python-format
msgid "%(created)s created, %(updated)s updated, %(skipped)s skipped."
msgstr ""
"%(created)s erstellt, %(updated)s aktualisiert, %(skipped)s übersprungen."
#, python-format
msgid "Source: %(label)s (%(count)s objects)."
msgstr "Quelle: %(label)s (%(count)s Objekte)."
msgid "Model"
msgstr "Modell"
msgid "Created"
msgstr "Erstellt"
msgid "Updated"
msgstr "Aktualisiert"
msgid "Skipped"
msgstr "Übersprungen"
msgid "Export"
msgstr "Export"
msgid "Preparing export ..."
msgstr "Export wird vorbereitet ..."
msgid "Export progress"
msgstr "Exportfortschritt"
msgid "Export ZIP"
msgstr "ZIP exportieren"
msgid "Import"
msgstr "Import"
msgid "Uploading archive ..."
msgstr "Archiv wird hochgeladen ..."
msgid "Import progress"
msgstr "Importfortschritt"
msgid "Process archive"
msgstr "Archiv verarbeiten"
msgid "Transferring ZIP ..."
msgstr "ZIP wird übertragen ..."
msgid "Export completed"
msgstr "Export abgeschlossen"
msgid "Export failed"
msgstr "Export fehlgeschlagen"
msgid "Checking and processing archive ..."
msgstr "Archiv wird geprüft und verarbeitet ..."
msgid "Import failed"
msgstr "Import fehlgeschlagen"
+2 -1
View File
@@ -1,9 +1,10 @@
from django.utils.translation import gettext_lazy as _
from netbox.plugins import PluginMenuItem
menu_items = (
PluginMenuItem(
link="plugins:netbox_export:dashboard",
link_text="Export / Import",
link_text=_("Export / Import"),
staff_only=True,
),
)
+21 -20
View File
@@ -12,6 +12,7 @@ from pathlib import PurePosixPath
from typing import BinaryIO
from django.core.serializers.json import DjangoJSONEncoder
from django.utils.translation import gettext as _
from .exceptions import ArchiveValidationError
@@ -54,7 +55,7 @@ def build_archive(manifest: dict, records: Iterable[dict], assets: dict[str, byt
for path, content in assets.items():
safe_path = _safe_member_name(path)
if safe_path in normalized_assets:
raise ArchiveValidationError(f"Doppelter Dateipfad im Archiv: {safe_path}")
raise ArchiveValidationError(_("Duplicate file path in archive: %(path)s") % {"path": safe_path})
normalized_assets[safe_path] = content
assets = normalized_assets
object_data = b"\n".join(_json_bytes(record) for record in records) + b"\n"
@@ -94,7 +95,7 @@ def build_archive(manifest: dict, records: Iterable[dict], assets: dict[str, byt
def _safe_member_name(name: str) -> str:
normalized = posixpath.normpath(name.replace("\\", "/"))
if normalized.startswith(("../", "/")) or normalized in ("", ".", ".."):
raise ArchiveValidationError(f"Unsicherer Dateipfad im Archiv: {name}")
raise ArchiveValidationError(_("Unsafe file path in archive: %(path)s") % {"path": name})
return normalized
@@ -118,52 +119,52 @@ def read_archive(
else:
raw = source.read(max_size + 1)
if len(raw) > max_size:
raise ArchiveValidationError("Das Archiv überschreitet die konfigurierte Maximalgröße.")
raise ArchiveValidationError(_("The archive exceeds the configured maximum size."))
try:
archive = zipfile.ZipFile(io.BytesIO(raw))
except zipfile.BadZipFile as exc:
raise ArchiveValidationError("Die hochgeladene Datei ist kein gültiges ZIP-Archiv.") from exc
raise ArchiveValidationError(_("The uploaded file is not a valid ZIP archive.")) from exc
with archive:
names = {}
for info in archive.infolist():
name = _safe_member_name(info.filename)
if name in names:
raise ArchiveValidationError(f"Doppelter Dateipfad im Archiv: {name}")
raise ArchiveValidationError(_("Duplicate file path in archive: %(path)s") % {"path": name})
names[name] = info
if len(names) > max_objects * 5 + 2:
raise ArchiveValidationError("Das Archiv enthält zu viele Dateien.")
raise ArchiveValidationError(_("The archive contains too many files."))
if MANIFEST_NAME not in names or OBJECTS_NAME not in names:
raise ArchiveValidationError("manifest.json oder objects.ndjson fehlt im Archiv.")
raise ArchiveValidationError(_("manifest.json or objects.ndjson is missing from the archive."))
total_size = sum(info.file_size for info in names.values())
if total_size > max_size * 4:
raise ArchiveValidationError("Der entpackte Archivinhalt ist zu groß.")
raise ArchiveValidationError(_("The extracted archive content is too large."))
if any(info.file_size > 0 and info.compress_size * 200 < info.file_size for info in names.values()):
raise ArchiveValidationError("Das Archiv weist ein unzulässiges Kompressionsverhältnis auf.")
raise ArchiveValidationError(_("The archive has an impermissible compression ratio."))
try:
manifest = json.loads(archive.read(MANIFEST_NAME))
object_data = archive.read(OBJECTS_NAME)
except (KeyError, ValueError, UnicodeDecodeError) as exc:
raise ArchiveValidationError("Die Metadaten im Archiv sind ungültig.") from exc
raise ArchiveValidationError(_("The archive metadata is invalid.")) from exc
if manifest.get("format") != FORMAT_NAME or manifest.get("format_version") != FORMAT_VERSION:
raise ArchiveValidationError("Das Archivformat oder dessen Version wird nicht unterstützt.")
raise ArchiveValidationError(_("The archive format or its version is not supported."))
checksum = hashlib.sha256(object_data).hexdigest()
if not hmac.compare_digest(checksum, str(manifest.get("objects_sha256", ""))):
raise ArchiveValidationError("Die Objektdatei stimmt nicht mit ihrer Prüfsumme überein.")
raise ArchiveValidationError(_("The object file does not match its checksum."))
warnings = []
signature = manifest.get("signature")
if signing_key:
expected = _signature(manifest, signing_key)
if not signature or not hmac.compare_digest(expected, signature):
raise ArchiveValidationError("Die Archivsignatur ist ungültig oder fehlt.")
raise ArchiveValidationError(_("The archive signature is invalid or missing."))
elif signature:
warnings.append("Das Archiv ist signiert, aber ohne konfigurierten Schlüssel nicht verifiziert.")
warnings.append(_("The archive is signed but was not verified because no key is configured."))
else:
warnings.append("Das Archiv ist nicht signiert.")
warnings.append(_("The archive is not signed."))
records = []
try:
@@ -171,9 +172,9 @@ def read_archive(
if line:
records.append(json.loads(line))
if len(records) > max_objects:
raise ArchiveValidationError("Das Archiv enthält zu viele Objekte.")
raise ArchiveValidationError(_("The archive contains too many objects."))
except (ValueError, UnicodeDecodeError) as exc:
raise ArchiveValidationError("objects.ndjson enthält ungültiges JSON.") from exc
raise ArchiveValidationError(_("objects.ndjson contains invalid JSON.")) from exc
assets = {
name: archive.read(name)
@@ -182,11 +183,11 @@ def read_archive(
}
declared_assets = manifest.get("assets_sha256", {})
if set(declared_assets) != set(assets):
raise ArchiveValidationError("Die Dateiliste stimmt nicht mit dem Manifest überein.")
raise ArchiveValidationError(_("The file list does not match the manifest."))
for name, content in assets.items():
actual = hashlib.sha256(content).hexdigest()
if not hmac.compare_digest(actual, str(declared_assets.get(name, ""))):
raise ArchiveValidationError(f"Die Prüfsumme der Datei {name} ist ungültig.")
raise ArchiveValidationError(_("The checksum of file %(name)s is invalid.") % {"name": name})
if manifest.get("object_count") != len(records):
raise ArchiveValidationError("Die Objektanzahl stimmt nicht mit dem Manifest überein.")
raise ArchiveValidationError(_("The object count does not match the manifest."))
return ParsedArchive(manifest=manifest, records=records, assets=assets, warnings=warnings)
+29
View File
@@ -28,6 +28,19 @@ def model_label(model) -> str:
return model._meta.label_lower
def is_range_value(value) -> bool:
return all(
hasattr(value, attribute)
for attribute in ("lower", "upper", "lower_inc", "upper_inc", "isempty")
)
def _make_range(lower, upper, bounds, empty):
from django.db.backends.postgresql.psycopg_any import Range
return Range(lower, upper, bounds, empty=empty)
def encode_scalar(value):
if value is None or isinstance(value, (bool, int, float, str)):
return value
@@ -45,6 +58,15 @@ def encode_scalar(value):
return {"$type": "duration", "value": value.total_seconds()}
if isinstance(value, bytes):
return {"$type": "bytes", "value": base64.b64encode(value).decode("ascii")}
if is_range_value(value):
bounds = ("[" if value.lower_inc else "(") + ("]" if value.upper_inc else ")")
return {
"$type": "range",
"lower": encode_scalar(value.lower),
"upper": encode_scalar(value.upper),
"bounds": bounds,
"empty": value.isempty,
}
if isinstance(value, (list, tuple)):
return [encode_scalar(item) for item in value]
if isinstance(value, dict):
@@ -61,6 +83,13 @@ def decode_scalar(value):
return value
kind = value["$type"]
raw = value.get("value")
if kind == "range":
return _make_range(
decode_scalar(value.get("lower")),
decode_scalar(value.get("upper")),
value.get("bounds", "[)"),
bool(value.get("empty", False)),
)
decoders = {
"decimal": decimal.Decimal,
"uuid": uuid.UUID,
+1 -1
View File
@@ -39,7 +39,7 @@ def export_scope(
"created_at": datetime.now(UTC).isoformat(),
"source_instance": str(InstanceIdentity.local_id()),
"source_netbox_version": getattr(getattr(settings, "RELEASE", None), "version", "4.6"),
"plugin_version": "0.3.0",
"plugin_version": "0.3.14",
"scope": {
"type": scope_type,
"source_pk": str(scope_id),
+49 -5
View File
@@ -6,6 +6,7 @@ from django.apps import apps
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.translation import gettext as _
from .codec import object_key
from .exceptions import GraphLimitError
@@ -31,6 +32,18 @@ EXCLUDED_MODELS = {
}
SCOPE_LINK_FIELDS = {"tenant", "site", "location", "region"}
PEER_CONTAINER_MODELS = {"dcim.cable", "circuits.circuit", "circuits.virtualcircuit"}
PRIVATE_EXPORTABLE_MODELS = {
# NetBox derives cable paths from these mappings, but marks the model private
# because it has no public API of its own.
"dcim.portmapping",
}
# Optional plugin models that extend a dependency (e.g. a device type) one-to-one.
# They are exported together with that dependency even though it is not a member.
DEPENDENCY_EXTENSION_MODELS = {
# NetBox Utilities: disk bay template of a device type.
"netbox_utilities.diskbaytemplate",
}
def is_exportable_model(model) -> bool:
@@ -40,6 +53,10 @@ def is_exportable_model(model) -> bool:
and not opts.abstract
and not opts.proxy
and not opts.auto_created
and (
not getattr(model, "_netbox_private", False)
or opts.label_lower in PRIVATE_EXPORTABLE_MODELS
)
and opts.app_label not in EXCLUDED_APP_LABELS
and opts.label_lower not in EXCLUDED_MODELS
)
@@ -95,7 +112,12 @@ class ObjectGraph:
self.dependencies: dict[str, models.Model] = {}
self._custom_field_cache = {}
self._models = exportable_models()
self._reverse_fields, self._generic_fields, self._peer_fields = self._build_relation_indexes()
(
self._reverse_fields,
self._generic_fields,
self._peer_fields,
self._extension_fields,
) = self._build_relation_indexes()
@property
def objects(self) -> dict[str, models.Model]:
@@ -105,6 +127,7 @@ class ObjectGraph:
reverse_fields = defaultdict(lambda: defaultdict(list))
generic_fields = defaultdict(list)
peer_fields = defaultdict(list)
extension_fields = defaultdict(list)
for candidate_model in self._models:
for relation_field in candidate_model._meta.concrete_fields:
if not isinstance(relation_field, (models.ForeignKey, models.OneToOneField)):
@@ -117,17 +140,24 @@ class ObjectGraph:
reverse_fields[related_model][candidate_model].append(relation_field)
if related_model._meta.label_lower in PEER_CONTAINER_MODELS:
peer_fields[candidate_model].append(relation_field)
if (
candidate_model._meta.label_lower in DEPENDENCY_EXTENSION_MODELS
and isinstance(relation_field, models.OneToOneField)
):
extension_fields[related_model].append((candidate_model, relation_field))
for generic_field in candidate_model._meta.private_fields:
if isinstance(generic_field, GenericForeignKey):
generic_fields[candidate_model].append(generic_field)
return reverse_fields, generic_fields, peer_fields
return reverse_fields, generic_fields, peer_fields, extension_fields
def _check_limit(self):
object_count = len(self.members) + len(self.dependencies)
if object_count > self.max_objects:
raise GraphLimitError(
f"Der Export würde mehr als {self.max_objects} Objekte enthalten. "
"Bitte den Bereich verkleinern oder max_objects erhöhen."
_(
"The export would contain more than %(max)s objects. "
"Narrow the scope or increase max_objects."
) % {"max": self.max_objects}
)
def add_member(self, obj) -> bool:
@@ -219,7 +249,10 @@ class ObjectGraph:
)
for object_batch in _chunks(objects, self.query_batch_size):
object_ids = [obj.pk for obj in object_batch]
queryset = model._default_manager.filter(pk__in=object_ids).select_related(*foreign_keys).order_by("pk")
queryset = model._default_manager.filter(pk__in=object_ids).order_by("pk")
if foreign_keys:
# select_related() without arguments is deprecated since Django 6.1.
queryset = queryset.select_related(*foreign_keys)
if prefetch_fields:
queryset = queryset.prefetch_related(*prefetch_fields)
yield from queryset.iterator(chunk_size=self.query_batch_size)
@@ -280,6 +313,14 @@ class ObjectGraph:
chunk_size=self.query_batch_size
)
def _extension_objects(self, model, objects):
object_ids = [obj.pk for obj in objects]
for extension_model, relation_field in self._extension_fields.get(model, ()):
for id_batch in _chunks(object_ids, self.query_batch_size):
yield from extension_model._default_manager.filter(
**{f"{relation_field.attname}__in": id_batch}
).iterator(chunk_size=self.query_batch_size)
def _collect_dependencies(self):
pending = dict(self.members)
scanned = set()
@@ -288,6 +329,9 @@ class ObjectGraph:
for model, objects in self._group_by_model(pending.values()).items():
custom_fields = self.custom_fields_for_model(model)
loaded_objects = list(self._load_objects(model, objects))
for extension in self._extension_objects(model, loaded_objects):
if self.add_dependency(extension):
next_pending[object_key(extension)] = extension
for related in self._custom_value_dependencies(loaded_objects, custom_fields):
if self.add_dependency(related):
next_pending[object_key(related)] = related
File diff suppressed because it is too large. Load diff
+207
View File
@@ -0,0 +1,207 @@
from __future__ import annotations
from functools import cache
from django.apps import apps
from django.core.exceptions import FieldDoesNotExist, ValidationError
from django.db import models
from django.utils.translation import gettext as _
AUTO_IMPORT_TENANT_NAME = "Auto-Import"
AUTO_IMPORT_TENANT_SLUG = "auto-import"
MISSING_TENANT_MESSAGE = "Für dieses Objekt muss ein Mandant angegeben werden." # netbox_utilities before i18n
MISSING_TENANT_CODE = "tenant_required"
# Apps of optional plugins whose data is exported when installed on the source
# and skipped (instead of failing the import) when missing on the target.
OPTIONAL_PLUGIN_APP_LABELS = frozenset({"netbox_utilities"})
def is_optional_plugin_model(label: str) -> bool:
return label.split(".", 1)[0] in OPTIONAL_PLUGIN_APP_LABELS
def netbox_utilities_tenant_required() -> bool:
"""Return the effective tenant policy without requiring the optional plugin."""
if not apps.is_installed("netbox_utilities"): # importing its models while disabled raises RuntimeError
return False
try:
from netbox_utilities.runtime import tenant_required
except ImportError:
return False
return bool(tenant_required())
def netbox_utilities_tenant_messages() -> set[str]:
"""Messages netbox_utilities may raise for a missing tenant, in the active language."""
messages = {MISSING_TENANT_MESSAGE}
if not apps.is_installed("netbox_utilities"):
return messages
try:
from netbox_utilities.tenant_validation import VALIDATION_MESSAGE
except ImportError:
return messages
messages.add(str(VALIDATION_MESSAGE))
return messages
def is_tenant_relation(field) -> bool:
if field.name != "tenant":
return False
related_model = getattr(field.remote_field, "model", None)
return getattr(getattr(related_model, "_meta", None), "label_lower", None) == "tenancy.tenant"
def is_module_relation(field) -> bool:
if field.name != "module":
return False
related_model = getattr(field.remote_field, "model", None)
return getattr(getattr(related_model, "_meta", None), "label_lower", None) == "dcim.module"
def condition_field_names(condition):
for child in getattr(condition, "children", ()):
if isinstance(child, tuple):
yield child[0].split("__", 1)[0]
else:
yield from condition_field_names(child)
@cache
def check_constraint_field_names(model) -> frozenset[str]:
if model is None:
return frozenset()
names = set()
for constraint in model._meta.constraints:
if isinstance(constraint, models.CheckConstraint):
names.update(condition_field_names(constraint.condition))
return frozenset(names)
def relation_required_before_save(field) -> bool:
return (
is_tenant_relation(field)
or is_module_relation(field)
or field.name in check_constraint_field_names(getattr(field, "model", None))
)
def relation_should_be_deferred(field) -> bool:
return bool(field.null and field.unique and not relation_required_before_save(field))
class PluginCompatibility:
def __init__(
self,
warnings,
*,
dry_run: bool,
tenant_required: bool | None = None,
tenant_model_loader=None,
):
self.warnings = warnings
self.dry_run = dry_run
self.tenant_required = (
netbox_utilities_tenant_required() if tenant_required is None else tenant_required
)
self.tenant_model_loader = tenant_model_loader or (lambda: apps.get_model("tenancy.tenant"))
self._fallback_tenant = None
@staticmethod
def _supports_tenant(obj) -> bool:
try:
field = obj._meta.get_field("tenant")
except FieldDoesNotExist:
return False
return is_tenant_relation(field)
@staticmethod
def _is_missing_tenant_error(exc: ValidationError) -> bool:
if any(getattr(error, "code", None) == MISSING_TENANT_CODE for error in getattr(exc, "error_list", ())):
return True
return not netbox_utilities_tenant_messages().isdisjoint(exc.messages)
def _auto_import_tenant(self):
if self._fallback_tenant is not None:
return self._fallback_tenant
model = self.tenant_model_loader()
tenant = model._default_manager.filter(name=AUTO_IMPORT_TENANT_NAME).order_by("pk").first()
created = tenant is None
if tenant is None:
slug = AUTO_IMPORT_TENANT_SLUG
suffix = 2
while model._default_manager.filter(slug=slug).exists():
slug = f"{AUTO_IMPORT_TENANT_SLUG}-{suffix}"
suffix += 1
tenant = model._default_manager.create(name=AUTO_IMPORT_TENANT_NAME, slug=slug)
if self.dry_run:
message = (
_(
'The tenant "Auto-Import" was used automatically as a fallback tenant for the dry run; '
"it is not created or changed permanently."
)
)
elif created:
message = (
_(
'The tenant "Auto-Import" was created automatically and assigned to objects without a '
"resolvable tenant."
)
)
else:
message = (
_(
'The existing tenant "Auto-Import" was selected automatically for objects without a '
"resolvable tenant."
)
)
self.warnings.append(message)
self._fallback_tenant = tenant
return tenant
def _assign_fallback_tenant(self, obj, *, force: bool = False) -> bool:
if getattr(obj, "tenant_id", None) is not None or not self._supports_tenant(obj):
return False
if not force and not self.tenant_required:
return False
obj.tenant = self._auto_import_tenant()
return True
def save(self, obj, **kwargs):
self._assign_fallback_tenant(obj)
try:
return obj.save(**kwargs)
except ValidationError as exc:
if not self._is_missing_tenant_error(exc) or not self._assign_fallback_tenant(obj, force=True):
raise
return obj.save(**kwargs)
@staticmethod
def prepare_initial_save(obj, *, is_new: bool):
if is_new and obj._meta.label_lower == "dcim.module":
# Module.save() otherwise replicates ModuleType components which are
# imported explicitly from the archive and may already exist.
obj._disable_replication = True
def release_unique_relation(self, obj, field_name: str, value):
field = obj._meta.get_field(field_name)
if value is None or not relation_should_be_deferred(field):
return
conflicts = type(obj)._default_manager.filter(**{field.attname: value.pk})
if obj.pk is not None:
conflicts = conflicts.exclude(pk=obj.pk)
conflict_ids = list(conflicts.values_list("pk", flat=True))
if not conflict_ids:
return
type(obj)._default_manager.filter(pk__in=conflict_ids).update(**{field.attname: None})
identifiers = ", ".join(str(pk) for pk in conflict_ids)
self.warnings.append(
_(
"Unique reference %(field)s was released from target object(s) %(ids)s and reassigned to the "
"imported object."
)
% {"field": f"{obj._meta.label_lower}.{field_name}", "ids": identifiers}
)
+72
View File
@@ -0,0 +1,72 @@
from __future__ import annotations
from django.utils.translation import gettext as _
from .codec import decode_scalar
from .exceptions import ArchiveValidationError
MISSING_REFERENCE = object()
class ReferenceResolver:
def __init__(self, resolved, warnings, model_loader):
self.resolved = resolved
self.warnings = warnings
self.model_loader = model_loader
self.skipped = set()
self._external_cache = {}
self._warning_keys = set()
def warn(self, key, message):
if key not in self._warning_keys:
self._warning_keys.add(key)
self.warnings.append(message)
def skip(self, record_id, model_label, field_names):
self.skipped.add(record_id)
fields = ", ".join(field_names)
self.warn(
("skipped", record_id),
_("%(record)s (%(model)s) was skipped because of a missing required reference: %(fields)s.")
% {"record": record_id, "model": model_label, "fields": fields},
)
def _external_object(self, spec):
cache_key = repr(spec)
if cache_key in self._external_cache:
return self._external_cache[cache_key]
model = self.model_loader(spec["model"])
lookup = {key: decode_scalar(value) for key, value in spec.get("lookup", {}).items()}
reason = None
try:
value = model._default_manager.get(**lookup)
except model.DoesNotExist:
value = MISSING_REFERENCE
reason = _("not found")
except model.MultipleObjectsReturned:
value = MISSING_REFERENCE
reason = _("not unique")
if value is MISSING_REFERENCE:
self.warn(
("external", cache_key),
_("External reference omitted: %(model)s with %(lookup)s (%(reason)s).")
% {"model": spec["model"], "lookup": lookup, "reason": reason},
)
self._external_cache[cache_key] = value
return value
def resolve(self, spec):
if spec is None:
return None, True
if "ref" in spec:
record_id = spec["ref"]
if record_id in self.skipped:
self.warn(
("internal", record_id),
_("References to the skipped object %(record)s were omitted.") % {"record": record_id},
)
return MISSING_REFERENCE, True
return self.resolved.get(record_id), record_id in self.resolved
if "external" in spec:
return self._external_object(spec["external"]), True
raise ArchiveValidationError(_("An object reference in the archive is invalid."))
@@ -1,5 +1,6 @@
{% extends 'base/layout.html' %}
{% load form_helpers %}
{% load i18n %}
{% block title %}NetBox-Export{% endblock title %}
@@ -19,18 +20,22 @@
{% if report %}
<div class="alert {% if report.dry_run %}alert-info{% else %}alert-success{% endif %}" role="alert">
<h2 class="h4 mb-2">
{% if report.dry_run %}Prüflauf erfolgreich{% else %}Import abgeschlossen{% endif %}
{% if report.dry_run %}{% trans "Dry run successful" %}{% else %}{% trans "Import completed" %}{% endif %}
</h2>
<div>
{{ report.created }} erstellt, {{ report.updated }} aktualisiert, {{ report.skipped }} übersprungen.
Quelle: {{ manifest.scope.label }} ({{ manifest.object_count }} Objekte).
{% blocktrans trimmed with created=report.created updated=report.updated skipped=report.skipped %}
{{ created }} created, {{ updated }} updated, {{ skipped }} skipped.
{% endblocktrans %}
{% blocktrans trimmed with label=manifest.scope.label count=manifest.object_count %}
Source: {{ label }} ({{ count }} objects).
{% endblocktrans %}
</div>
{% for warning in report.warnings %}<div class="mt-1">{{ warning }}</div>{% endfor %}
</div>
<div class="table-responsive mb-4">
<table class="table table-sm table-hover">
<thead>
<tr><th>Modell</th><th class="text-end">Erstellt</th><th class="text-end">Aktualisiert</th><th class="text-end">Übersprungen</th></tr>
<tr><th>{% trans "Model" %}</th><th class="text-end">{% trans "Created" %}</th><th class="text-end">{% trans "Updated" %}</th><th class="text-end">{% trans "Skipped" %}</th></tr>
</thead>
<tbody>
{% for model, counts in report.models.items %}
@@ -50,7 +55,7 @@
<div class="col-12 col-xl-6">
<div class="card h-100">
<div class="card-header">
<h2 class="card-title"><i class="mdi mdi-download me-1" aria-hidden="true"></i> Export</h2>
<h2 class="card-title"><i class="mdi mdi-download me-1" aria-hidden="true"></i> {% trans "Export" %}</h2>
</div>
<form method="post" id="netbox-export-form" novalidate>
{% csrf_token %}
@@ -64,15 +69,15 @@
<div class="card-footer text-end">
<div id="export-progress" class="mb-3 text-start" hidden aria-live="polite">
<div class="d-flex justify-content-between mb-1">
<span class="progress-label">Export wird vorbereitet ...</span>
<span class="progress-label">{% trans "Preparing export ..." %}</span>
<span class="progress-percent"></span>
</div>
<div class="progress" role="progressbar" aria-label="Exportfortschritt" aria-valuemin="0" aria-valuemax="100">
<div class="progress" role="progressbar" aria-label="{% trans "Export progress" %}" aria-valuemin="0" aria-valuemax="100">
<div class="progress-bar progress-bar-striped progress-bar-animated" style="width: 100%"></div>
</div>
</div>
<button type="submit" class="btn btn-primary">
<i class="mdi mdi-archive-arrow-down me-1" aria-hidden="true"></i> ZIP exportieren
<i class="mdi mdi-archive-arrow-down me-1" aria-hidden="true"></i> {% trans "Export ZIP" %}
</button>
</div>
</form>
@@ -82,7 +87,7 @@
<div class="col-12 col-xl-6">
<div class="card h-100">
<div class="card-header">
<h2 class="card-title"><i class="mdi mdi-upload me-1" aria-hidden="true"></i> Import</h2>
<h2 class="card-title"><i class="mdi mdi-upload me-1" aria-hidden="true"></i> {% trans "Import" %}</h2>
</div>
<form method="post" id="netbox-import-form" enctype="multipart/form-data" novalidate>
{% csrf_token %}
@@ -96,15 +101,15 @@
<div class="card-footer text-end">
<div id="import-progress" class="mb-3 text-start" hidden aria-live="polite">
<div class="d-flex justify-content-between mb-1">
<span class="progress-label">Archiv wird hochgeladen ...</span>
<span class="progress-label">{% trans "Uploading archive ..." %}</span>
<span class="progress-percent"></span>
</div>
<div class="progress" role="progressbar" aria-label="Importfortschritt" aria-valuemin="0" aria-valuemax="100">
<div class="progress" role="progressbar" aria-label="{% trans "Import progress" %}" aria-valuemin="0" aria-valuemax="100">
<div class="progress-bar progress-bar-striped progress-bar-animated" style="width: 0%"></div>
</div>
</div>
<button type="submit" class="btn btn-primary">
<i class="mdi mdi-archive-arrow-up me-1" aria-hidden="true"></i> Archiv verarbeiten
<i class="mdi mdi-archive-arrow-up me-1" aria-hidden="true"></i> {% trans "Process archive" %}
</button>
</div>
</form>
@@ -115,8 +120,10 @@
{% block javascript %}
{{ block.super }}
{{ js_messages|json_script:"netbox-export-messages" }}
<script>
(() => {
const msg = JSON.parse(document.getElementById('netbox-export-messages').textContent);
const typeSelect = document.getElementById('id_export-scope_type');
const names = ['tenant_group', 'tenant', 'region', 'site', 'location'];
const refresh = () => {
@@ -149,6 +156,8 @@
form.setAttribute('aria-busy', busy ? 'true' : 'false');
};
const formTarget = (form) => form.getAttribute('action') || window.location.href;
const updateProgress = (container, label, percent = null, state = 'active') => {
const bar = container.querySelector('.progress-bar');
const progress = container.querySelector('[role="progressbar"]');
@@ -176,15 +185,15 @@
event.preventDefault();
if (!exportForm.reportValidity()) return;
setBusy(exportForm, true);
updateProgress(exportProgress, 'Export wird vorbereitet ...');
updateProgress(exportProgress, msg.preparing_export);
const request = new XMLHttpRequest();
request.open('POST', exportForm.action || window.location.href);
request.open('POST', formTarget(exportForm));
request.responseType = 'blob';
request.onprogress = (progressEvent) => {
if (!progressEvent.lengthComputable) return;
const percent = Math.min(99, Math.round((progressEvent.loaded / progressEvent.total) * 100));
updateProgress(exportProgress, 'ZIP wird übertragen ...', percent);
updateProgress(exportProgress, msg.transferring_zip, percent);
};
request.onload = async () => {
const contentType = request.getResponseHeader('Content-Type') || '';
@@ -200,11 +209,11 @@
link.click();
link.remove();
window.setTimeout(() => URL.revokeObjectURL(downloadUrl), 1000);
updateProgress(exportProgress, 'Export abgeschlossen', 100, 'success');
updateProgress(exportProgress, msg.export_done, 100, 'success');
setBusy(exportForm, false);
};
request.onerror = () => {
updateProgress(exportProgress, 'Export fehlgeschlagen', 100, 'error');
updateProgress(exportProgress, msg.export_failed, 100, 'error');
setBusy(exportForm, false);
};
request.send(new FormData(exportForm));
@@ -217,21 +226,21 @@
event.preventDefault();
if (!importForm.reportValidity()) return;
setBusy(importForm, true);
updateProgress(importProgress, 'Archiv wird hochgeladen ...', 0);
updateProgress(importProgress, msg.uploading, 0);
const request = new XMLHttpRequest();
request.open('POST', importForm.action || window.location.href);
request.open('POST', formTarget(importForm));
request.upload.onprogress = (progressEvent) => {
if (!progressEvent.lengthComputable) return;
const percent = Math.min(100, Math.round((progressEvent.loaded / progressEvent.total) * 100));
updateProgress(importProgress, 'Archiv wird hochgeladen ...', percent);
updateProgress(importProgress, msg.uploading, percent);
};
request.upload.onload = () => {
updateProgress(importProgress, 'Archiv wird geprüft und verarbeitet ...');
updateProgress(importProgress, msg.processing);
};
request.onload = () => replacePage(request.responseText);
request.onerror = () => {
updateProgress(importProgress, 'Import fehlgeschlagen', 100, 'error');
updateProgress(importProgress, msg.import_failed, 100, 'error');
setBusy(importForm, false);
};
request.send(new FormData(importForm));
+11
View File
@@ -2,6 +2,7 @@ from django.contrib.auth.mixins import UserPassesTestMixin
from django.http import HttpResponse
from django.shortcuts import render
from django.utils.text import slugify
from django.utils.translation import gettext as _
from django.views import View
from netbox.plugins import get_plugin_config
@@ -25,6 +26,15 @@ class DashboardView(UserPassesTestMixin, View):
"import_form": import_form or ImportForm(prefix="import"),
"report": report,
"manifest": manifest,
"js_messages": {
"preparing_export": _("Preparing export ..."),
"transferring_zip": _("Transferring ZIP ..."),
"export_done": _("Export completed"),
"export_failed": _("Export failed"),
"uploading": _("Uploading archive ..."),
"processing": _("Checking and processing archive ..."),
"import_failed": _("Import failed"),
},
}
def get(self, request):
@@ -78,6 +88,7 @@ class DashboardView(UserPassesTestMixin, View):
parsed,
conflict_strategy=form.cleaned_data["conflict_strategy"],
dry_run=form.cleaned_data["dry_run"],
force=form.cleaned_data["force"],
)
except ExportImportError as exc:
form.add_error(None, str(exc))
+6 -2
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "netbox-export"
version = "0.3.0"
version = "0.3.14"
description = "Portable ZIP export and import for scoped NetBox data"
readme = "README.md"
requires-python = ">=3.12"
@@ -20,7 +20,11 @@ classifiers = [
include = ["netbox_export*"]
[tool.setuptools.package-data]
netbox_export = ["templates/**/*.html"]
netbox_export = [
"templates/**/*.html",
"locale/*/LC_MESSAGES/*.po",
"locale/*/LC_MESSAGES/*.mo",
]
[tool.pytest.ini_options]
testpaths = ["tests"]
+1 -1
View File
@@ -6,7 +6,7 @@ from django.conf import settings
if not settings.configured:
settings.configure(
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
INSTALLED_APPS=["django.contrib.contenttypes"],
INSTALLED_APPS=["django.contrib.contenttypes", "netbox_export"],
SECRET_KEY="tests",
)
+7 -7
View File
@@ -34,13 +34,13 @@ def test_archive_round_trip():
assert parsed.records == records()
assert parsed.assets == {"assets/a.txt": b"data"}
assert parsed.warnings == ["Das Archiv ist nicht signiert."]
assert parsed.warnings == ["The archive is not signed."]
def test_signed_archive_requires_matching_key():
payload = build_archive(manifest(), records(), {}, signing_key="secret-a")
with pytest.raises(ArchiveValidationError, match="Archivsignatur"):
with pytest.raises(ArchiveValidationError, match="archive signature"):
read_archive(payload, max_size=1024 * 1024, max_objects=10, signing_key="secret-b")
@@ -49,7 +49,7 @@ def test_signed_archive_without_local_key_is_not_claimed_as_verified():
parsed = read_archive(payload, max_size=1024 * 1024, max_objects=10)
assert parsed.warnings == ["Das Archiv ist signiert, aber ohne konfigurierten Schlüssel nicht verifiziert."]
assert parsed.warnings == ["The archive is signed but was not verified because no key is configured."]
def test_modified_object_stream_is_rejected():
@@ -63,7 +63,7 @@ def test_modified_object_stream_is_rejected():
content = content.replace(b"Berlin", b"Hamburg")
target.writestr(info, content)
with pytest.raises(ArchiveValidationError, match="Prüfsumme"):
with pytest.raises(ArchiveValidationError, match="checksum"):
read_archive(output.getvalue(), max_size=1024 * 1024, max_objects=10)
@@ -78,7 +78,7 @@ def test_modified_asset_is_rejected():
content = b"modified"
target.writestr(info, content)
with pytest.raises(ArchiveValidationError, match="Prüfsumme der Datei"):
with pytest.raises(ArchiveValidationError, match="checksum of file"):
read_archive(output.getvalue(), max_size=1024 * 1024, max_objects=10)
@@ -88,12 +88,12 @@ def test_path_traversal_is_rejected():
with zipfile.ZipFile(output, "w") as archive:
archive.writestr("../manifest.json", json.dumps(manifest()))
with pytest.raises(ArchiveValidationError, match="Dateipfad"):
with pytest.raises(ArchiveValidationError, match="file path"):
read_archive(output.getvalue(), max_size=1024 * 1024, max_objects=10)
def test_object_limit_is_enforced():
payload = build_archive(manifest(), records() * 2, {})
with pytest.raises(ArchiveValidationError, match="zu viele Objekte"):
with pytest.raises(ArchiveValidationError, match="too many objects"):
read_archive(payload, max_size=1024 * 1024, max_objects=1)
+80
View File
@@ -0,0 +1,80 @@
from types import SimpleNamespace
from unittest.mock import MagicMock
from netbox_export.services import importer
from netbox_export.services.importer import (
_rebuild_imported_cable_paths,
_release_port_mapping_conflicts,
)
class FakeQuerySet(list):
def exclude(self, **kwargs):
return FakeQuerySet(item for item in self if item.pk != kwargs["pk"])
def order_by(self, *args):
return self
class FakeManager:
def __init__(self, objects):
self.objects = FakeQuerySet(objects)
self.filters = []
def select_for_update(self):
return self
def filter(self, *args, **kwargs):
self.filters.append((args, kwargs))
return FakeQuerySet(self.objects)
def test_port_mapping_conflicts_are_replaced_before_save():
deleted = []
conflict = SimpleNamespace(pk=12, delete=lambda: deleted.append(12))
class PortMapping:
_meta = SimpleNamespace(label_lower="dcim.portmapping")
_default_manager = FakeManager([conflict])
mapping = PortMapping()
mapping.pk = 11
mapping.front_port_id = 21
mapping.front_port_position = 1
mapping.rear_port_id = 31
mapping.rear_port_position = 1
resolver = SimpleNamespace(warn=MagicMock())
_release_port_mapping_conflicts(mapping, resolver, "dcim.portmapping:99")
assert deleted == [12]
resolver.warn.assert_called_once()
assert "front/rear port cabling" in resolver.warn.call_args.args[1]
def test_imported_cable_terminations_trigger_netbox_path_rebuild(monkeypatch):
cables = [SimpleNamespace(pk=7), SimpleNamespace(pk=9)]
class Cable:
_default_manager = FakeManager(cables)
trace_paths = SimpleNamespace(send=MagicMock())
monkeypatch.setattr(importer, "_model_for", lambda label: Cable)
monkeypatch.setattr(importer, "_trace_paths_signal", lambda: trace_paths)
records = {
"dcim.cabletermination:1": {"model": "dcim.cabletermination"},
"dcim.cabletermination:2": {"model": "dcim.cabletermination"},
"dcim.device:3": {"model": "dcim.device"},
}
resolved = {
"dcim.cabletermination:1": SimpleNamespace(cable_id=7),
"dcim.cabletermination:2": SimpleNamespace(cable_id=9),
"dcim.device:3": object(),
}
_rebuild_imported_cable_paths(records, resolved)
assert all(cable._terminations_modified is True for cable in cables)
assert trace_paths.send.call_count == 2
trace_paths.send.assert_any_call(Cable, instance=cables[0], created=False)
trace_paths.send.assert_any_call(Cable, instance=cables[1], created=False)
+52
View File
@@ -1,10 +1,34 @@
import datetime
import decimal
import uuid
from dataclasses import dataclass
import pytest
from netbox_export.services import codec
from netbox_export.services.codec import decode_scalar, encode_scalar
@dataclass
class FakeRange:
lower: object = None
upper: object = None
bounds: str = "[)"
empty: bool = False
@property
def lower_inc(self):
return not self.empty and self.bounds[0] == "["
@property
def upper_inc(self):
return not self.empty and self.bounds[1] == "]"
@property
def isempty(self):
return self.empty
def test_scalar_round_trip():
value = {
"decimal": decimal.Decimal("12.340"),
@@ -17,3 +41,31 @@ def test_scalar_round_trip():
assert decode_scalar(encode_scalar(value)) == value
def test_postgresql_range_round_trip(monkeypatch):
monkeypatch.setattr(
codec,
"_make_range",
lambda lower, upper, bounds, empty: FakeRange(lower, upper, bounds, empty),
)
value = FakeRange(1, 56, "[)")
encoded = encode_scalar(value)
assert encoded == {
"$type": "range",
"lower": 1,
"upper": 56,
"bounds": "[)",
"empty": False,
}
assert decode_scalar(encoded) == value
def test_real_psycopg_range_round_trip():
pytest.importorskip("psycopg")
from django.db.backends.postgresql.psycopg_any import NumericRange
value = NumericRange(1, 56, "[)")
assert decode_scalar(encode_scalar(value)) == value
+15
View File
@@ -0,0 +1,15 @@
from pathlib import Path
def test_form_action_field_cannot_shadow_request_target():
template = (
Path(__file__).parents[1]
/ "netbox_export"
/ "templates"
/ "netbox_export"
/ "dashboard.html"
).read_text(encoding="utf-8")
assert "form.getAttribute('action')" in template
assert "exportForm.action" not in template
assert "importForm.action" not in template
+291
View File
@@ -0,0 +1,291 @@
from decimal import Decimal
from types import SimpleNamespace
from typing import ClassVar
import pytest
from django.db import connection, models
from netbox_export.services.exceptions import ImportConflictError
from netbox_export.services.importer import (
DeferredDevicePlacement,
_apply_device_placements,
_defer_device_placement,
_save_device_placement,
_stage_device_placement,
)
from netbox_export.services.plugin_compat import PluginCompatibility
from netbox_export.services.references import ReferenceResolver
pytestmark = pytest.mark.django_db(transaction=True)
class PlacementRack(models.Model):
name = models.CharField(max_length=64)
class Meta:
app_label = "placement_tests"
class PlacementDeviceType(models.Model):
u_height = models.DecimalField(max_digits=4, decimal_places=1, default=1)
is_full_depth = models.BooleanField(default=False)
class Meta:
app_label = "placement_tests"
class PlacementDevice(models.Model):
name = models.CharField(max_length=64)
device_type = models.ForeignKey(PlacementDeviceType, on_delete=models.PROTECT)
rack = models.ForeignKey(PlacementRack, on_delete=models.PROTECT, null=True)
position = models.DecimalField(max_digits=4, decimal_places=1, null=True)
face = models.CharField(max_length=16, null=True)
class Meta:
app_label = "placement_tests"
constraints: ClassVar[list] = [
models.UniqueConstraint(
fields=("rack", "position", "face"),
name="placement_tests_unique_rack_position_face",
)
]
@pytest.fixture
def placement_schema():
with connection.schema_editor() as schema_editor:
schema_editor.create_model(PlacementRack)
schema_editor.create_model(PlacementDeviceType)
schema_editor.create_model(PlacementDevice)
try:
yield
finally:
with connection.schema_editor() as schema_editor:
schema_editor.delete_model(PlacementDevice)
schema_editor.delete_model(PlacementDeviceType)
schema_editor.delete_model(PlacementRack)
def placement_context(device, rack, *, position="31.0", face="front"):
record_id = "dcim.device:77"
resolved = {record_id: device, "dcim.rack:2": rack}
warnings = []
resolver = ReferenceResolver(resolved, warnings, lambda label: None)
compatibility = PluginCompatibility(warnings, dry_run=False, tenant_required=False)
placement = DeferredDevicePlacement(
rack_spec={"ref": "dcim.rack:2"},
position=Decimal(position) if position is not None else None,
face=face,
)
return record_id, resolved, warnings, resolver, compatibility, placement
def test_device_placement_is_removed_from_initial_record():
model = SimpleNamespace(_meta=SimpleNamespace(label_lower="dcim.device"))
record = {
"fields": {"name": "Router 1", "position": {"$type": "decimal", "value": "31.0"}, "face": "front"},
"relations": {"site": {"ref": "dcim.site:1"}, "rack": {"ref": "dcim.rack:2"}},
}
prepared, placement = _defer_device_placement(model, record)
assert prepared["fields"] == {"name": "Router 1"}
assert prepared["relations"] == {"site": {"ref": "dcim.site:1"}}
assert placement == DeferredDevicePlacement(
rack_spec={"ref": "dcim.rack:2"},
position=Decimal("31.0"),
face="front",
)
assert "position" in record["fields"]
assert "rack" in record["relations"]
def test_saving_placement_persists_location_inherited_from_rack():
location = object()
rack = SimpleNamespace(location=location)
device = SimpleNamespace(rack=None, position=None, face=None, location=None)
saved = []
compatibility = SimpleNamespace(save=lambda obj, **kwargs: saved.append((obj, kwargs)))
_save_device_placement(device, rack, Decimal("31.0"), "front", compatibility)
assert device.location is location
assert saved == [
(
device,
{"update_fields": ["rack", "position", "face", "location"]},
)
]
def test_update_releases_exact_rack_occupant_and_places_imported_device(placement_schema):
rack = PlacementRack.objects.create(name="R01")
device_type = PlacementDeviceType.objects.create()
occupant = PlacementDevice.objects.create(
name="Existing", device_type=device_type, rack=rack, position=Decimal("31.0"), face="front"
)
imported = PlacementDevice.objects.create(name="Imported", device_type=device_type)
record_id, resolved, warnings, resolver, compatibility, placement = placement_context(imported, rack)
_apply_device_placements(
[(record_id, placement)],
resolved,
resolver,
compatibility,
conflict_strategy="update",
)
occupant.refresh_from_db()
imported.refresh_from_db()
assert (occupant.rack, occupant.position, occupant.face) == (rack, None, None)
assert (imported.rack, imported.position, imported.face) == (rack, Decimal("31.0"), "front")
assert len(warnings) == 1
assert f"target device(s) {occupant.pk} (Existing)" in warnings[0]
def test_skip_keeps_occupant_and_leaves_imported_device_unpositioned(placement_schema):
rack = PlacementRack.objects.create(name="R01")
device_type = PlacementDeviceType.objects.create()
occupant = PlacementDevice.objects.create(
name="Existing", device_type=device_type, rack=rack, position=Decimal("31.0"), face="front"
)
imported = PlacementDevice.objects.create(name="Imported", device_type=device_type)
record_id, resolved, warnings, resolver, compatibility, placement = placement_context(imported, rack)
_apply_device_placements(
[(record_id, placement)],
resolved,
resolver,
compatibility,
conflict_strategy="skip",
)
occupant.refresh_from_db()
imported.refresh_from_db()
assert (occupant.rack, occupant.position, occupant.face) == (rack, Decimal("31.0"), "front")
assert (imported.rack, imported.position, imported.face) == (rack, None, None)
assert len(warnings) == 1
assert "was saved without a rack position" in warnings[0]
def test_fail_reports_rack_conflict_before_database_constraint(placement_schema):
rack = PlacementRack.objects.create(name="R01")
device_type = PlacementDeviceType.objects.create()
PlacementDevice.objects.create(
name="Existing", device_type=device_type, rack=rack, position=Decimal("31.0"), face="front"
)
imported = PlacementDevice.objects.create(name="Imported", device_type=device_type)
record_id, resolved, _, resolver, compatibility, placement = placement_context(imported, rack)
with pytest.raises(ImportConflictError, match="Rack position conflict.*Rack R01"):
_apply_device_placements(
[(record_id, placement)],
resolved,
resolver,
compatibility,
conflict_strategy="fail",
)
def test_half_depth_devices_can_share_position_on_opposite_faces(placement_schema):
rack = PlacementRack.objects.create(name="R01")
device_type = PlacementDeviceType.objects.create(is_full_depth=False)
occupant = PlacementDevice.objects.create(
name="Existing", device_type=device_type, rack=rack, position=Decimal("31.0"), face="front"
)
imported = PlacementDevice.objects.create(name="Imported", device_type=device_type)
record_id, resolved, warnings, resolver, compatibility, placement = placement_context(
imported, rack, face="rear"
)
_apply_device_placements(
[(record_id, placement)],
resolved,
resolver,
compatibility,
conflict_strategy="update",
)
occupant.refresh_from_db()
imported.refresh_from_db()
assert occupant.position == Decimal("31.0")
assert (imported.position, imported.face) == (Decimal("31.0"), "rear")
assert warnings == []
def test_full_depth_multi_u_overlap_is_released(placement_schema):
rack = PlacementRack.objects.create(name="R01")
full_depth = PlacementDeviceType.objects.create(u_height=Decimal("2.0"), is_full_depth=True)
half_depth = PlacementDeviceType.objects.create(u_height=Decimal("1.0"), is_full_depth=False)
occupant = PlacementDevice.objects.create(
name="Existing",
device_type=full_depth,
rack=rack,
position=Decimal("30.5"),
face="front",
)
imported = PlacementDevice.objects.create(name="Imported", device_type=half_depth)
record_id, resolved, warnings, resolver, compatibility, placement = placement_context(
imported, rack, position="31.0", face="rear"
)
_apply_device_placements(
[(record_id, placement)],
resolved,
resolver,
compatibility,
conflict_strategy="update",
)
occupant.refresh_from_db()
imported.refresh_from_db()
assert occupant.position is None
assert (imported.position, imported.face) == (Decimal("31.0"), "rear")
assert len(warnings) == 1
def test_imported_devices_can_swap_rack_positions(placement_schema):
rack = PlacementRack.objects.create(name="R01")
device_type = PlacementDeviceType.objects.create()
first = PlacementDevice.objects.create(
name="First", device_type=device_type, rack=rack, position=Decimal("10.0"), face="front"
)
second = PlacementDevice.objects.create(
name="Second", device_type=device_type, rack=rack, position=Decimal("20.0"), face="front"
)
for device in (first, second):
_stage_device_placement(device)
device.save(update_fields=["position", "face"])
resolved = {
"dcim.device:1": first,
"dcim.device:2": second,
"dcim.rack:2": rack,
}
warnings = []
resolver = ReferenceResolver(resolved, warnings, lambda label: None)
compatibility = PluginCompatibility(warnings, dry_run=False, tenant_required=False)
placements = [
(
"dcim.device:1",
DeferredDevicePlacement({"ref": "dcim.rack:2"}, Decimal("20.0"), "front"),
),
(
"dcim.device:2",
DeferredDevicePlacement({"ref": "dcim.rack:2"}, Decimal("10.0"), "front"),
),
]
_apply_device_placements(
placements,
resolved,
resolver,
compatibility,
conflict_strategy="update",
)
first.refresh_from_db()
second.refresh_from_db()
assert first.position == Decimal("20.0")
assert second.position == Decimal("10.0")
assert warnings == []
+107
View File
@@ -0,0 +1,107 @@
import io
from django.core.files.storage import InMemoryStorage
from django.db import models
from PIL import Image
from netbox_export.services import importer as importer_module
from netbox_export.services.importer import _cleanup_files, _set_files
class ImageAsset(models.Model):
image = models.ImageField(
upload_to="test-images",
height_field="image_height",
width_field="image_width",
)
image_height = models.PositiveSmallIntegerField()
image_width = models.PositiveSmallIntegerField()
class Meta:
app_label = "file_import_tests"
def image_bytes(width=3, height=2):
output = io.BytesIO()
Image.new("RGB", (width, height), color="white").save(output, format="PNG")
return output.getvalue()
def image_record():
return {
"files": {
"image": {
"path": "assets/extras.imageattachment_17/image/server-room.png",
"name": "image-attachments/location_2_Serverraum.jpg",
}
}
}
def test_dry_run_derives_required_image_dimensions_without_storing_file():
obj = ImageAsset()
assets = {"assets/extras.imageattachment_17/image/server-room.png": image_bytes()}
saved_files = []
_set_files(obj, image_record(), assets, saved_files, dry_run=True)
assert (obj.image_width, obj.image_height) == (3, 2)
assert not obj.image
assert saved_files == []
def test_file_import_keeps_derived_dimensions_after_storage_save(monkeypatch):
field = ImageAsset._meta.get_field("image")
storage = InMemoryStorage()
monkeypatch.setattr(field, "storage", storage)
obj = ImageAsset()
assets = {"assets/extras.imageattachment_17/image/server-room.png": image_bytes(5, 4)}
saved_files = []
_set_files(obj, image_record(), assets, saved_files, dry_run=False)
assert (obj.image_width, obj.image_height) == (5, 4)
assert storage.exists(obj.image.name)
assert saved_files == [(storage, obj.image.name)]
_cleanup_files(saved_files)
assert not storage.exists(obj.image.name)
def test_oversized_image_is_resized_after_pillow_bomb_error(monkeypatch):
monkeypatch.setattr(importer_module, "NETBOX_IMAGE_MAX_PIXELS", 50)
monkeypatch.setattr(importer_module, "IMPORTED_IMAGE_TARGET_PIXELS", 40)
monkeypatch.setattr(importer_module, "IMPORTED_IMAGE_SOURCE_MAX_PIXELS", 200)
monkeypatch.setattr(Image, "MAX_IMAGE_PIXELS", 50)
field = ImageAsset._meta.get_field("image")
storage = InMemoryStorage()
monkeypatch.setattr(field, "storage", storage)
obj = ImageAsset()
record = image_record()
record["id"] = "extras.imageattachment:17"
assets = {"assets/extras.imageattachment_17/image/server-room.png": image_bytes(11, 10)}
import_warnings = []
saved_files = []
_set_files(
obj,
record,
assets,
saved_files,
dry_run=False,
import_warnings=import_warnings,
)
assert obj.image_width * obj.image_height <= 40
with storage.open(obj.image.name, "rb") as stored_file, Image.open(stored_file) as stored_image:
assert stored_image.size == (obj.image_width, obj.image_height)
assert stored_image.format == "PNG"
assert import_warnings == [
(
f"Image for extras.imageattachment:17 was downscaled from 11×10 to "
f"{obj.image_width}×{obj.image_height} pixels."
)
]
assert Image.MAX_IMAGE_PIXELS == 50
_cleanup_files(saved_files)
+102
View File
@@ -0,0 +1,102 @@
import uuid
import pytest
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import connection, models
from netbox_export.services.archive import ParsedArchive
from netbox_export.services.exceptions import ArchiveValidationError
from netbox_export.services import importer as importer_module
from netbox_export.services.importer import import_archive
pytestmark = pytest.mark.django_db(transaction=True)
class FragileObject(models.Model):
name = models.CharField(max_length=50)
class Meta:
app_label = "force_tests"
def save(self, *args, **kwargs):
if self.name == "bad":
raise ValueError("kaputt")
return super().save(*args, **kwargs)
class Assignment(models.Model):
assigned_object_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
assigned_object_id = models.PositiveBigIntegerField()
assigned_object = GenericForeignKey("assigned_object_type", "assigned_object_id")
class Meta:
app_label = "force_tests"
@pytest.fixture
def force_tables(monkeypatch):
test_models = {"force_tests.fragileobject": FragileObject, "force_tests.assignment": Assignment}
monkeypatch.setattr(importer_module, "_model_for", test_models.__getitem__)
with connection.schema_editor() as schema_editor:
schema_editor.create_model(FragileObject)
schema_editor.create_model(Assignment)
yield
with connection.schema_editor() as schema_editor:
schema_editor.delete_model(Assignment)
schema_editor.delete_model(FragileObject)
def archive(*records):
return ParsedArchive(
manifest={"source_instance": str(uuid.uuid4())},
records=list(records),
assets={},
warnings=[],
)
def fragile(pk, name):
return {
"id": f"force_tests.fragileobject:{pk}",
"model": "force_tests.fragileobject",
"source_pk": str(pk),
"fields": {"name": name},
"relations": {},
}
def test_failing_record_aborts_import_without_force(force_tables):
with pytest.raises(ArchiveValidationError, match="kaputt"):
import_archive(archive(fragile(1, "ok"), fragile(2, "bad")), conflict_strategy="update", dry_run=False)
assert FragileObject.objects.count() == 0
def test_force_mode_skips_only_the_failing_record(force_tables):
report = import_archive(
archive(fragile(1, "ok"), fragile(2, "bad")),
conflict_strategy="update",
dry_run=False,
force=True,
)
assert list(FragileObject.objects.values_list("name", flat=True)) == ["ok"]
assert report.created == 1
assert report.skipped == 1
assert any("force_tests.fragileobject:2" in warning and "kaputt" in warning for warning in report.warnings)
def test_dangling_generic_reference_skips_record_instead_of_writing_null(force_tables):
record = {
"id": "force_tests.assignment:1",
"model": "force_tests.assignment",
"source_pk": "1",
"fields": {},
"relations": {},
"generic_relations": {"assigned_object": None},
}
report = import_archive(archive(record), conflict_strategy="update", dry_run=False)
assert Assignment.objects.count() == 0
assert report.skipped == 1
+30
View File
@@ -36,6 +36,36 @@ class GraphDetail(models.Model):
app_label = "graph_tests"
class PrivateGraphModel(models.Model):
_netbox_private = True
class Meta:
app_label = "graph_tests"
class PortMapping(models.Model):
_netbox_private = True
class Meta:
app_label = "dcim"
class CablePath(models.Model):
_netbox_private = True
class Meta:
app_label = "dcim"
def test_private_plugin_models_are_not_exportable():
assert graph_module.is_exportable_model(PrivateGraphModel) is False
def test_private_port_mappings_are_exported_but_cable_paths_are_not():
assert graph_module.is_exportable_model(PortMapping) is True
assert graph_module.is_exportable_model(CablePath) is False
def test_batched_graph_collects_members_and_dependencies(monkeypatch):
graph_models = (GraphParent, GraphReference, GraphChild, GraphDetail)
with connection.schema_editor() as schema_editor:
+299
View File
@@ -0,0 +1,299 @@
import uuid
from typing import ClassVar
import pytest
from django.db import connection, models
from netbox_export.services import importer as importer_module
from netbox_export.services.importer import (
_field_kwargs,
_find_existing,
_identity_lookup,
)
from netbox_export.services.plugin_compat import PluginCompatibility
from netbox_export.services.references import ReferenceResolver
pytestmark = pytest.mark.django_db(transaction=True)
class Tenant(models.Model):
class Meta:
app_label = "tenancy"
class TenantManagedObject(models.Model):
tenant = models.ForeignKey(Tenant, on_delete=models.PROTECT, null=True)
class Meta:
app_label = "compat_tests"
class Platform(models.Model):
class Meta:
app_label = "compat_tests"
class ConstrainedInstallation(models.Model):
platform = models.ForeignKey(Platform, on_delete=models.PROTECT, null=True)
class Meta:
app_label = "compat_tests"
constraints: ClassVar[list] = [
models.CheckConstraint(
condition=models.Q(platform__isnull=False),
name="compat_tests_installation_platform",
)
]
class UniqueAddress(models.Model):
class Meta:
app_label = "compat_tests"
class UniqueAddressOwner(models.Model):
primary_ip6 = models.OneToOneField(UniqueAddress, on_delete=models.SET_NULL, null=True)
class Meta:
app_label = "compat_tests"
class Device(models.Model):
class Meta:
app_label = "dcim"
class RearPort(models.Model):
device = models.ForeignKey(Device, on_delete=models.CASCADE)
name = models.CharField(max_length=64)
class Meta:
app_label = "dcim"
constraints: ClassVar[list] = [
models.UniqueConstraint(
fields=("device", "name"),
name="dcim_rearport_unique_device_name",
)
]
class Module(models.Model):
class Meta:
app_label = "dcim"
class ModuleBay(models.Model):
device = models.ForeignKey(Device, on_delete=models.CASCADE)
module = models.ForeignKey(Module, on_delete=models.CASCADE)
name = models.CharField(max_length=64)
class Meta:
app_label = "dcim"
class ModularRearPort(models.Model):
module = models.ForeignKey(Module, on_delete=models.SET_NULL, null=True)
class Meta:
app_label = "compat_tests"
def tenant_record():
return {
"fields": {},
"relations": {"tenant": {"ref": "tenancy.tenant:23"}},
}
def test_unresolved_tenant_always_blocks_initial_save():
resolver = ReferenceResolver({}, [], lambda label: None)
kwargs, unresolved, unresolved_values, missing_required = _field_kwargs(
TenantManagedObject,
tenant_record(),
resolver,
tenant_required=True,
)
assert kwargs is None
assert unresolved == []
assert unresolved_values == []
assert missing_required == []
def test_unresolved_tenant_also_blocks_when_policy_detection_is_unavailable():
resolver = ReferenceResolver({}, [], lambda label: None)
kwargs, unresolved, unresolved_values, missing_required = _field_kwargs(
TenantManagedObject,
tenant_record(),
resolver,
tenant_required=False,
)
assert kwargs is None
assert unresolved == []
assert unresolved_values == []
assert missing_required == []
def test_unresolved_relation_in_check_constraint_blocks_initial_save():
resolver = ReferenceResolver({}, [], lambda label: None)
record = {
"fields": {},
"relations": {"platform": {"ref": "compat_tests.platform:5"}},
}
kwargs, unresolved, unresolved_values, missing_required = _field_kwargs(
ConstrainedInstallation,
record,
resolver,
tenant_required=False,
)
assert kwargs is None
assert unresolved == []
assert unresolved_values == []
assert missing_required == []
def test_modular_component_waits_for_module_before_initial_save():
resolver = ReferenceResolver({}, [], lambda label: None)
record = {
"fields": {},
"relations": {"module": {"ref": "dcim.module:12"}},
}
kwargs, unresolved, unresolved_values, missing_required = _field_kwargs(
ModularRearPort,
record,
resolver,
tenant_required=False,
)
assert kwargs is None
assert unresolved == []
assert unresolved_values == []
assert missing_required == []
def test_module_bay_identity_includes_owning_module():
device = Device(pk=210)
module = Module(pk=12)
resolver = ReferenceResolver(
{
"dcim.device:210": device,
"dcim.module:12": module,
},
[],
lambda label: None,
)
record = {
"fields": {"name": "3-LC"},
"relations": {
"device": {"ref": "dcim.device:210"},
"module": {"ref": "dcim.module:12"},
},
}
lookup = _identity_lookup(ModuleBay, record, resolver)
assert lookup == {"device": device, "module": module, "name": "3-LC"}
def test_resolved_nullable_unique_relation_is_deferred():
address = UniqueAddress(pk=50)
resolver = ReferenceResolver(
{"compat_tests.uniqueaddress:50": address},
[],
lambda label: None,
)
record = {
"fields": {},
"relations": {"primary_ip6": {"ref": "compat_tests.uniqueaddress:50"}},
}
kwargs, unresolved, unresolved_values, missing_required = _field_kwargs(
UniqueAddressOwner,
record,
resolver,
tenant_required=False,
)
assert kwargs == {}
assert unresolved == [("primary_ip6", {"ref": "compat_tests.uniqueaddress:50"})]
assert unresolved_values == []
assert missing_required == []
def test_existing_unique_relation_is_released_before_reassignment():
with connection.schema_editor() as schema_editor:
schema_editor.create_model(UniqueAddress)
schema_editor.create_model(UniqueAddressOwner)
try:
address = UniqueAddress.objects.create()
previous_owner = UniqueAddressOwner.objects.create(primary_ip6=address)
imported_owner = UniqueAddressOwner()
warnings = []
compatibility = PluginCompatibility(warnings, dry_run=False, tenant_required=False)
compatibility.release_unique_relation(imported_owner, "primary_ip6", address)
imported_owner.primary_ip6 = address
imported_owner.save()
previous_owner.refresh_from_db()
assert previous_owner.primary_ip6 is None
assert imported_owner.primary_ip6 == address
assert warnings == [
(
"Unique reference compat_tests.uniqueaddressowner.primary_ip6 was released from target "
f"object(s) {previous_owner.pk} and reassigned to the imported object."
)
]
finally:
with connection.schema_editor() as schema_editor:
schema_editor.delete_model(UniqueAddressOwner)
schema_editor.delete_model(UniqueAddress)
def test_natural_key_rebinds_stale_mapping_instead_of_creating_duplicate(monkeypatch):
with connection.schema_editor() as schema_editor:
schema_editor.create_model(Device)
schema_editor.create_model(RearPort)
try:
device = Device.objects.create()
natural = RearPort.objects.create(device=device, name="3-LC")
stale_mapping_target = RearPort(pk=999, device=device, name="Alt")
monkeypatch.setattr(
importer_module,
"_mapped_object",
lambda source_instance, record, model: stale_mapping_target,
)
warnings = []
resolver = ReferenceResolver(
{"dcim.device:160": device},
warnings,
lambda label: None,
)
record = {
"id": "dcim.rearport:77",
"model": "dcim.rearport",
"source_pk": "77",
"fields": {"name": "3-LC"},
"relations": {"device": {"ref": "dcim.device:160"}},
}
existing = _find_existing(uuid.uuid4(), RearPort, record, resolver)
assert existing == natural
assert warnings == [
(
"Stored mapping for dcim.rearport:77 was corrected from target ID 999 to "
f"target ID {natural.pk} because the natural key "
f"{{'device': <Device: Device object ({device.pk})>, 'name': '3-LC'}} already exists."
)
]
finally:
with connection.schema_editor() as schema_editor:
schema_editor.delete_model(RearPort)
schema_editor.delete_model(Device)
+38
View File
@@ -0,0 +1,38 @@
import ast
import re
from pathlib import Path
ROOT = Path(__file__).parents[1]
def _plugin_versions():
tree = ast.parse((ROOT / "netbox_export" / "__init__.py").read_text(encoding="utf-8"))
values = {
target.id: node.value.value
for node in ast.walk(tree)
if isinstance(node, ast.Assign) and isinstance(node.value, ast.Constant)
for target in node.targets
if isinstance(target, ast.Name)
}
return values["min_version"], values["max_version"]
def test_readme_netbox_range_matches_plugin_config():
min_version, max_version = _plugin_versions()
major, minor, patch = max_version.split(".")
upper = f"{major}.{minor}.x" if patch == "99" else max_version # 4.7.99 is documented as 4.7.x
expected = f"`{min_version}` – `{upper}`"
readme = (ROOT / "README.md").read_text(encoding="utf-8")
assert f"| **NetBox** | {expected} |" in readme
assert f"- NetBox {expected}" in readme
def test_german_catalog_is_complete():
po = ROOT / "netbox_export" / "locale" / "de" / "LC_MESSAGES" / "django.po"
content = po.read_text(encoding="utf-8")
entries = re.findall(r'^msgid ((?:".*"\n)+)msgstr ((?:".*"\n?)+)', content, re.MULTILINE)
assert "#, fuzzy" not in content
assert [msgid for msgid, msgstr in entries[1:] if msgstr.strip() == '""'] == []
assert po.with_suffix(".mo").is_file()
+120
View File
@@ -0,0 +1,120 @@
import uuid
from typing import ClassVar
import pytest
from django.db import connection, models
from netbox_export.services import graph as graph_module
from netbox_export.services import importer as importer_module
from netbox_export.services.archive import ParsedArchive
from netbox_export.services.importer import _find_existing, import_archive
from netbox_export.services.references import ReferenceResolver
pytestmark = pytest.mark.django_db(transaction=True)
class DiskDeviceType(models.Model):
class Meta:
app_label = "disk_tests"
class DiskDevice(models.Model):
device_type = models.ForeignKey(DiskDeviceType, on_delete=models.PROTECT)
class Meta:
app_label = "disk_tests"
class DiskBayTemplate(models.Model):
device_type = models.OneToOneField(DiskDeviceType, on_delete=models.CASCADE)
slot_count = models.PositiveSmallIntegerField()
class Meta:
app_label = "netbox_utilities"
class Disk(models.Model):
device = models.ForeignKey(DiskDevice, on_delete=models.CASCADE)
slot = models.PositiveSmallIntegerField()
status = models.CharField(max_length=20, default="active")
serial = models.CharField(max_length=100, blank=True)
class Meta:
app_label = "netbox_utilities"
constraints: ClassVar[list] = [
models.UniqueConstraint(
fields=("device", "slot"),
condition=~models.Q(status="replaced"),
name="disk_tests_unique_occupied_slot",
)
]
MODELS = (DiskDeviceType, DiskDevice, DiskBayTemplate, Disk)
@pytest.fixture
def disk_tables():
with connection.schema_editor() as schema_editor:
for model in MODELS:
schema_editor.create_model(model)
yield
with connection.schema_editor() as schema_editor:
for model in reversed(MODELS):
schema_editor.delete_model(model)
def disk_record(pk, status, serial):
return {
"id": f"netbox_utilities.disk:{pk}",
"model": "netbox_utilities.disk",
"source_pk": str(pk),
"fields": {"slot": 0, "status": status, "serial": serial},
"relations": {"device": {"ref": "disk_tests.diskdevice:1"}},
}
def test_replaced_disk_does_not_match_occupied_slot(disk_tables, monkeypatch):
device = DiskDevice.objects.create(device_type=DiskDeviceType.objects.create())
active = Disk.objects.create(device=device, slot=0, status="active", serial="NEW")
monkeypatch.setattr(importer_module, "_mapped_object", lambda *args: None)
resolver = ReferenceResolver({"disk_tests.diskdevice:1": device}, [], lambda label: None)
assert _find_existing(uuid.uuid4(), Disk, disk_record(1, "replaced", "OLD"), resolver) is None
assert _find_existing(uuid.uuid4(), Disk, disk_record(2, "active", "NEW"), resolver) == active
def test_disk_bay_template_is_exported_with_device_type(disk_tables, monkeypatch):
device_type = DiskDeviceType.objects.create()
template = DiskBayTemplate.objects.create(device_type=device_type, slot_count=12)
device = DiskDevice.objects.create(device_type=device_type)
disk = Disk.objects.create(device=device, slot=0)
monkeypatch.setattr(graph_module, "exportable_models", lambda: MODELS)
graph = graph_module.ObjectGraph(max_objects=100).collect([device])
assert graph_module.object_key(disk) in graph.members
assert graph_module.object_key(device_type) in graph.dependencies
assert graph_module.object_key(template) in graph.dependencies
def test_netbox_utilities_records_are_skipped_without_plugin():
parsed = ParsedArchive(
manifest={"source_instance": str(uuid.uuid4())},
records=[
{
"id": "netbox_utilities.raidgroup:1",
"model": "netbox_utilities.raidgroup",
"source_pk": "1",
"fields": {"name": "R1"},
"relations": {},
}
],
assets={},
warnings=[],
)
report = import_archive(parsed, conflict_strategy="update", dry_run=True)
assert report.skipped == 1
assert any("netbox_utilities.raidgroup" in warning for warning in report.warnings)
+203
View File
@@ -0,0 +1,203 @@
from types import SimpleNamespace
from django.core.exceptions import FieldDoesNotExist, ValidationError
from django.db import models
from netbox_export.services.plugin_compat import (
MISSING_TENANT_MESSAGE,
PluginCompatibility,
check_constraint_field_names,
is_module_relation,
is_tenant_relation,
relation_required_before_save,
relation_should_be_deferred,
)
def relation_field(name="tenant", related_label="tenancy.tenant"):
related_model = SimpleNamespace(_meta=SimpleNamespace(label_lower=related_label))
return SimpleNamespace(name=name, remote_field=SimpleNamespace(model=related_model))
class FakeQuerySet:
def __init__(self, result=None, exists=False):
self.result = result
self._exists = exists
def order_by(self, *fields):
return self
def first(self):
return self.result
def exists(self):
return self._exists
class FakeTenantManager:
def __init__(self, existing=None):
self.existing = existing
self.created = []
def filter(self, **lookup):
if "name" in lookup:
return FakeQuerySet(self.existing)
return FakeQuerySet(exists=False)
def create(self, **values):
tenant = SimpleNamespace(pk=42, **values)
self.created.append(tenant)
return tenant
class FakeTenantModel:
_default_manager = FakeTenantManager()
class FakeMeta:
def get_field(self, name):
if name != "tenant":
raise FieldDoesNotExist(name)
return relation_field()
class TenantRequiredObject:
_meta = FakeMeta()
def __init__(self):
self.tenant_id = None
self.save_calls = 0
@property
def tenant(self):
return None
@tenant.setter
def tenant(self, value):
self.tenant_id = value.pk
def save(self, **kwargs):
self.save_calls += 1
if self.tenant_id is None:
raise ValidationError(MISSING_TENANT_MESSAGE)
def test_identifies_tenant_relation():
assert is_tenant_relation(relation_field()) is True
assert is_tenant_relation(relation_field("site", "dcim.site")) is False
def test_identifies_module_component_relation():
assert is_module_relation(relation_field("module", "dcim.module")) is True
assert is_module_relation(relation_field("device", "dcim.device")) is False
def test_new_module_disables_automatic_component_replication():
module = SimpleNamespace(_meta=SimpleNamespace(label_lower="dcim.module"))
PluginCompatibility.prepare_initial_save(module, is_new=True)
assert module._disable_replication is True
def test_existing_module_keeps_normal_save_behavior():
module = SimpleNamespace(_meta=SimpleNamespace(label_lower="dcim.module"))
PluginCompatibility.prepare_initial_save(module, is_new=False)
assert not hasattr(module, "_disable_replication")
def test_identifies_relations_used_by_check_constraint():
constraint = models.CheckConstraint(
condition=(
models.Q(device__isnull=False, virtualmachine__isnull=True)
| models.Q(device__isnull=True, virtualmachine__isnull=False)
),
name="platform",
)
model = type("ConstrainedModel", (), {"_meta": SimpleNamespace(constraints=[constraint])})
field = relation_field("device", "dcim.device")
field.model = model
assert check_constraint_field_names(model) == frozenset({"device", "virtualmachine"})
assert relation_required_before_save(field) is True
def test_nullable_unique_relation_is_deferred_unless_required_by_constraint():
regular = relation_field("primary_ip6", "ipam.ipaddress")
regular.null = True
regular.unique = True
regular.model = type(
"VirtualMachine",
(),
{"_meta": SimpleNamespace(constraints=[])},
)
assert relation_should_be_deferred(regular) is True
constrained = relation_field("platform", "dcim.device")
constrained.null = True
constrained.unique = True
constraint = models.CheckConstraint(
condition=models.Q(platform__isnull=False),
name="platform_required",
)
constrained.model = type(
"Installation",
(),
{"_meta": SimpleNamespace(constraints=[constraint])},
)
assert relation_should_be_deferred(constrained) is False
def test_creates_and_assigns_auto_import_tenant_when_policy_is_active():
manager = FakeTenantManager()
tenant_model = type("TenantModel", (), {"_default_manager": manager})
warnings = []
compatibility = PluginCompatibility(
warnings,
dry_run=False,
tenant_required=True,
tenant_model_loader=lambda: tenant_model,
)
obj = TenantRequiredObject()
compatibility.save(obj)
assert obj.tenant_id == 42
assert obj.save_calls == 1
assert len(manager.created) == 1
assert warnings == [
(
'The tenant "Auto-Import" was created automatically and assigned to objects without a '
'resolvable tenant.'
)
]
def test_validation_error_forces_fallback_for_older_plugin_versions():
existing = SimpleNamespace(pk=7, name="Auto-Import", slug="auto-import")
manager = FakeTenantManager(existing=existing)
tenant_model = type("TenantModel", (), {"_default_manager": manager})
warnings = []
compatibility = PluginCompatibility(
warnings,
dry_run=False,
tenant_required=False,
tenant_model_loader=lambda: tenant_model,
)
obj = TenantRequiredObject()
compatibility.save(obj)
assert obj.tenant_id == 7
assert obj.save_calls == 2
assert manager.created == []
assert warnings == [
(
'The existing tenant "Auto-Import" was selected automatically for objects without a '
'resolvable tenant.'
)
]
+80
View File
@@ -0,0 +1,80 @@
from dataclasses import dataclass
from netbox_export.services.importer import _coerce_model_field_value
@dataclass
class FakeRange:
lower: object = None
upper: object = None
bounds: str = "[)"
empty: bool = False
@property
def lower_inc(self):
return not self.empty and self.bounds[0] == "["
@property
def upper_inc(self):
return not self.empty and self.bounds[1] == "]"
@property
def isempty(self):
return self.empty
class IntegerField:
@staticmethod
def to_python(value):
return int(value)
class IntegerRangeField:
base_field = IntegerField()
range_type = FakeRange
class ArrayField:
base_field = IntegerRangeField()
def test_legacy_string_ranges_are_restored_for_range_array_fields():
value = ["[1, 56)", "(100, 200]", "empty"]
converted = _coerce_model_field_value(ArrayField(), value)
assert converted == [
FakeRange(1, 56, "[)"),
FakeRange(100, 200, "(]"),
FakeRange(empty=True),
]
def test_range_like_strings_remain_unchanged_for_normal_fields():
field = object()
assert _coerce_model_field_value(field, "[1, 56)") == "[1, 56)"
class BaseIPField:
@staticmethod
def to_python(value):
return ("parsed", value)
class IPAddressField(BaseIPField):
pass
class CharField:
@staticmethod
def to_python(value):
raise AssertionError("plain fields must not be converted")
def test_netbox_ip_field_values_are_converted_for_model_save():
assert _coerce_model_field_value(IPAddressField(), "192.0.2.1/24") == ("parsed", "192.0.2.1/24")
def test_other_string_values_are_left_unchanged():
assert _coerce_model_field_value(CharField(), "192.0.2.1/24") == "192.0.2.1/24"
+91
View File
@@ -0,0 +1,91 @@
from netbox_export.services.references import MISSING_REFERENCE, ReferenceResolver
class DoesNotExist(Exception):
pass
class MultipleObjectsReturned(Exception):
pass
class FakeManager:
def __init__(self, result):
self.result = result
self.calls = 0
def get(self, **lookup):
self.calls += 1
if isinstance(self.result, Exception):
raise self.result
return self.result
def fake_model(manager):
return type(
"FakeModel",
(),
{
"DoesNotExist": DoesNotExist,
"MultipleObjectsReturned": MultipleObjectsReturned,
"_default_manager": manager,
},
)
def test_missing_external_reference_is_omitted_and_warned_once():
manager = FakeManager(DoesNotExist())
model = fake_model(manager)
warnings = []
resolver = ReferenceResolver({}, warnings, lambda label: model)
spec = {"external": {"model": "users.user", "lookup": {"username": "lke"}}}
first, first_available = resolver.resolve(spec)
second, second_available = resolver.resolve(spec)
assert first is MISSING_REFERENCE
assert second is MISSING_REFERENCE
assert first_available is True
assert second_available is True
assert manager.calls == 1
assert warnings == [
"External reference omitted: users.user with {'username': 'lke'} (not found)."
]
def test_ambiguous_external_reference_is_omitted():
manager = FakeManager(MultipleObjectsReturned())
model = fake_model(manager)
warnings = []
resolver = ReferenceResolver({}, warnings, lambda label: model)
value, available = resolver.resolve(
{"external": {"model": "users.group", "lookup": {"name": "NetBox"}}}
)
assert value is MISSING_REFERENCE
assert available is True
assert warnings == [
"External reference omitted: users.group with {'name': 'NetBox'} (not unique)."
]
def test_reference_to_skipped_record_is_omitted_and_warned_once():
warnings = []
resolver = ReferenceResolver({}, warnings, lambda label: None)
resolver.skip("dcim.rackreservation:17", "dcim.rackreservation", ["user"])
first, first_available = resolver.resolve({"ref": "dcim.rackreservation:17"})
second, second_available = resolver.resolve({"ref": "dcim.rackreservation:17"})
assert first is MISSING_REFERENCE
assert second is MISSING_REFERENCE
assert first_available is True
assert second_available is True
assert warnings == [
(
"dcim.rackreservation:17 (dcim.rackreservation) was skipped because of a missing "
"required reference: user."
),
"References to the skipped object dcim.rackreservation:17 were omitted.",
]