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]>
This commit is contained in:
1 parent
47e9192fda
commit
ab4a6c8958
5 files changed
+233
-10
No files matched your search
@@ -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)
|
||||
@@ -289,6 +307,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()
|
||||
@@ -297,6 +323,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,
|
||||
@@ -183,7 +186,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):
|
||||
@@ -198,7 +229,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:
|
||||
@@ -256,19 +291,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
|
||||
|
||||
@@ -706,6 +744,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.")
|
||||
@@ -731,6 +790,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)
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user