Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b947df022b | ||
|
|
ab4a6c8958 |
No files matched your search
@@ -199,6 +199,11 @@ unique natural keys.
|
||||
- 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.
|
||||
|
||||
|
||||
@@ -37,6 +37,13 @@ PRIVATE_EXPORTABLE_MODELS = {
|
||||
"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:
|
||||
opts = model._meta
|
||||
@@ -104,7 +111,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]:
|
||||
@@ -114,6 +126,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)):
|
||||
@@ -126,10 +139,15 @@ 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)
|
||||
@@ -292,6 +310,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()
|
||||
@@ -300,6 +326,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
|
||||
|
||||
@@ -17,6 +17,7 @@ from django.conf import settings
|
||||
from django.contrib.contenttypes.models import ContentType
|
||||
from django.core.files.base import ContentFile
|
||||
from django.db import IntegrityError, models, transaction
|
||||
from django.db.models import Value
|
||||
from PIL import Image as PillowImage
|
||||
|
||||
from netbox_export.models import ImportedObjectMapping
|
||||
@@ -26,6 +27,8 @@ from .codec import SKIP_FIELD_NAMES, decode_scalar, generic_foreign_keys, is_ran
|
||||
from .exceptions import ArchiveValidationError, ExportImportError, ImportConflictError
|
||||
from .plugin_compat import (
|
||||
PluginCompatibility,
|
||||
condition_field_names,
|
||||
is_optional_plugin_model,
|
||||
is_tenant_relation,
|
||||
relation_required_before_save,
|
||||
relation_should_be_deferred,
|
||||
@@ -191,7 +194,35 @@ def _identity_candidates(model):
|
||||
yield from model._meta.unique_together
|
||||
for constraint in model._meta.constraints:
|
||||
if isinstance(constraint, models.UniqueConstraint) and constraint.fields:
|
||||
yield tuple(constraint.fields)
|
||||
if constraint.condition is None:
|
||||
yield tuple(constraint.fields)
|
||||
else:
|
||||
yield ConditionalIdentity(constraint.fields, constraint.condition)
|
||||
|
||||
|
||||
class ConditionalIdentity(tuple):
|
||||
"""Identity fields that are only unique for rows matching a constraint condition."""
|
||||
|
||||
def __new__(cls, fields, condition):
|
||||
identity = super().__new__(cls, fields)
|
||||
identity.condition = condition
|
||||
return identity
|
||||
|
||||
|
||||
class IdentityLookup(dict):
|
||||
condition = None
|
||||
|
||||
|
||||
def _record_matches_condition(condition, scalar_values) -> bool:
|
||||
against = {}
|
||||
for name in condition_field_names(condition):
|
||||
if name not in scalar_values:
|
||||
return False
|
||||
against[name] = Value(decode_scalar(scalar_values[name]))
|
||||
try:
|
||||
return condition.check(against)
|
||||
except Exception: # noqa: BLE001 - unsupported conditions are not used as identity
|
||||
return False
|
||||
|
||||
|
||||
def _identity_lookup(model, record, resolver):
|
||||
@@ -206,7 +237,11 @@ def _identity_lookup(model, record, resolver):
|
||||
generic_storage[generic_field.ct_field] = ("content_type", spec)
|
||||
generic_storage[generic_field.fk_field] = ("object_id", spec)
|
||||
for candidate in _identity_candidates(model):
|
||||
lookup = {}
|
||||
condition = getattr(candidate, "condition", None)
|
||||
if condition is not None and not _record_matches_condition(condition, scalar_values):
|
||||
continue
|
||||
lookup = IdentityLookup()
|
||||
lookup.condition = condition
|
||||
usable = True
|
||||
for name in candidate:
|
||||
if name in scalar_values:
|
||||
@@ -264,19 +299,22 @@ def _find_existing(source_instance, model, record, resolver):
|
||||
lookup = _identity_lookup(model, record, resolver)
|
||||
if not lookup:
|
||||
return mapped
|
||||
queryset = model._default_manager.all()
|
||||
if getattr(lookup, "condition", None) is not None:
|
||||
queryset = queryset.filter(lookup.condition)
|
||||
try:
|
||||
natural = model._default_manager.get(**lookup)
|
||||
natural = queryset.get(**lookup)
|
||||
except model.DoesNotExist:
|
||||
return mapped
|
||||
except model.MultipleObjectsReturned as exc:
|
||||
raise ImportConflictError(
|
||||
f"Mehrere Zielobjekte passen auf {record['model']} mit {lookup}."
|
||||
f"Mehrere Zielobjekte passen auf {record['model']} mit {dict(lookup)}."
|
||||
) from exc
|
||||
if mapped is not None and mapped.pk != natural.pk:
|
||||
resolver.warn(
|
||||
("mapping-rebound", record["id"]),
|
||||
f"Gespeicherte Zuordnung für {record['id']} wurde von Ziel-ID {mapped.pk} auf "
|
||||
f"Ziel-ID {natural.pk} korrigiert, da der Fachschlüssel {lookup} bereits existiert.",
|
||||
f"Ziel-ID {natural.pk} korrigiert, da der Fachschlüssel {dict(lookup)} bereits existiert.",
|
||||
)
|
||||
return natural
|
||||
|
||||
@@ -714,6 +752,27 @@ def _apply_m2m(obj, record, resolver):
|
||||
manager.set(values)
|
||||
|
||||
|
||||
def _skip_uninstalled_optional_models(records, resolver, report):
|
||||
"""Drop records of optional plugins which are not installed on the target."""
|
||||
missing_labels = set()
|
||||
for record_id, record in list(records.items()):
|
||||
label = record["model"]
|
||||
if not is_optional_plugin_model(label):
|
||||
continue
|
||||
try:
|
||||
apps.get_model(label)
|
||||
except (LookupError, ValueError):
|
||||
missing_labels.add(label)
|
||||
resolver.skipped.add(record_id)
|
||||
report.add(label, "skipped")
|
||||
del records[record_id]
|
||||
for label in sorted(missing_labels):
|
||||
report.warnings.append(
|
||||
f"Objekte vom Typ {label} wurden übersprungen, da das zugehörige optionale Plugin "
|
||||
"auf der Zielinstanz nicht installiert ist."
|
||||
)
|
||||
|
||||
|
||||
def import_archive(parsed: ParsedArchive, *, conflict_strategy: str, dry_run: bool) -> ImportReport:
|
||||
if conflict_strategy not in ("update", "skip", "fail"):
|
||||
raise ArchiveValidationError("Unbekannte Konfliktstrategie.")
|
||||
@@ -739,6 +798,7 @@ def import_archive(parsed: ParsedArchive, *, conflict_strategy: str, dry_run: bo
|
||||
report = ImportReport(dry_run=dry_run, warnings=list(parsed.warnings))
|
||||
resolved = {}
|
||||
resolver = ReferenceResolver(resolved, report.warnings, _model_for)
|
||||
_skip_uninstalled_optional_models(records, resolver, report)
|
||||
compatibility = PluginCompatibility(report.warnings, dry_run=dry_run)
|
||||
deferred_relations = []
|
||||
deferred_generic = []
|
||||
|
||||
@@ -9,6 +9,13 @@ from django.db import models
|
||||
AUTO_IMPORT_TENANT_NAME = "Auto-Import"
|
||||
AUTO_IMPORT_TENANT_SLUG = "auto-import"
|
||||
MISSING_TENANT_MESSAGE = "Für dieses Objekt muss ein Mandant angegeben werden."
|
||||
# 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:
|
||||
@@ -34,12 +41,12 @@ def is_module_relation(field) -> bool:
|
||||
return getattr(getattr(related_model, "_meta", None), "label_lower", None) == "dcim.module"
|
||||
|
||||
|
||||
def _condition_field_names(condition):
|
||||
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)
|
||||
yield from condition_field_names(child)
|
||||
|
||||
|
||||
@cache
|
||||
@@ -49,7 +56,7 @@ def check_constraint_field_names(model) -> frozenset[str]:
|
||||
names = set()
|
||||
for constraint in model._meta.constraints:
|
||||
if isinstance(constraint, models.CheckConstraint):
|
||||
names.update(_condition_field_names(constraint.condition))
|
||||
names.update(condition_field_names(constraint.condition))
|
||||
return frozenset(names)
|
||||
|
||||
|
||||
|
||||
@@ -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)
|
||||
Reference in new issue
Block a user