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]>
This commit is contained in:
1 parent
b947df022b
commit
5fd246edb8
5 files changed
+226
-14
No files matched your search
@@ -160,6 +160,12 @@ 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
|
model and source ID; on a first import, existing objects are matched by their
|
||||||
unique natural keys.
|
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
|
### Behaviour and limits
|
||||||
|
|
||||||
- User accounts and permissions are not exported. Missing or ambiguous user and
|
- User accounts and permissions are not exported. Missing or ambiguous user and
|
||||||
|
|||||||
@@ -57,6 +57,15 @@ class ImportForm(forms.Form):
|
|||||||
initial=True,
|
initial=True,
|
||||||
help_text="Führt den vollständigen Import aus und setzt die Datenbanktransaktion anschließend zurück.",
|
help_text="Führt den vollständigen Import aus und setzt die Datenbanktransaktion anschließend zurück.",
|
||||||
)
|
)
|
||||||
|
force = forms.BooleanField(
|
||||||
|
label="Force-Modus (Fehler überspringen)",
|
||||||
|
required=False,
|
||||||
|
initial=False,
|
||||||
|
help_text=(
|
||||||
|
"Objekte, deren Import fehlschlägt, werden einzeln übersprungen, statt den gesamten Import "
|
||||||
|
"zurückzurollen. Übersprungene Objekte werden im Bericht als Warnung aufgeführt."
|
||||||
|
),
|
||||||
|
)
|
||||||
confirm_apply = forms.BooleanField(
|
confirm_apply = forms.BooleanField(
|
||||||
label="Ich bestätige den schreibenden Import",
|
label="Ich bestätige den schreibenden Import",
|
||||||
required=False,
|
required=False,
|
||||||
|
|||||||
@@ -594,11 +594,14 @@ def _set_generic_relations(obj, record, resolver, *, allow_deferred: bool):
|
|||||||
continue
|
continue
|
||||||
value, available = resolver.resolve(spec)
|
value, available = resolver.resolve(spec)
|
||||||
if available:
|
if available:
|
||||||
if value is MISSING_REFERENCE:
|
if value is MISSING_REFERENCE or value is None:
|
||||||
|
# A dangling generic reference is exported as None.
|
||||||
ct_field = obj._meta.get_field(field.ct_field)
|
ct_field = obj._meta.get_field(field.ct_field)
|
||||||
id_field = obj._meta.get_field(field.fk_field)
|
id_field = obj._meta.get_field(field.fk_field)
|
||||||
if not ct_field.null or not id_field.null:
|
if not ct_field.null or not id_field.null:
|
||||||
missing_required.append(name)
|
missing_required.append(name)
|
||||||
|
elif value is None:
|
||||||
|
setattr(obj, name, None)
|
||||||
else:
|
else:
|
||||||
setattr(obj, name, value)
|
setattr(obj, name, value)
|
||||||
elif allow_deferred:
|
elif allow_deferred:
|
||||||
@@ -752,6 +755,36 @@ def _apply_m2m(obj, record, resolver):
|
|||||||
manager.set(values)
|
manager.set(values)
|
||||||
|
|
||||||
|
|
||||||
|
def _save_record(obj, resolver, record_id, compatibility, *, force: bool):
|
||||||
|
if not force:
|
||||||
|
_release_port_mapping_conflicts(obj, resolver, record_id)
|
||||||
|
compatibility.save(obj)
|
||||||
|
return
|
||||||
|
with transaction.atomic():
|
||||||
|
_release_port_mapping_conflicts(obj, resolver, record_id)
|
||||||
|
compatibility.save(obj)
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_deferred_relation(obj, name, value, compatibility):
|
||||||
|
compatibility.release_unique_relation(obj, name, value)
|
||||||
|
setattr(obj, name, value)
|
||||||
|
compatibility.save(obj, update_fields=[name])
|
||||||
|
|
||||||
|
|
||||||
|
def _forced(force, warnings, label, func, *args, **kwargs):
|
||||||
|
"""Run func; in force mode roll back only its savepoint and record a warning on error."""
|
||||||
|
if not force:
|
||||||
|
return func(*args, **kwargs)
|
||||||
|
try:
|
||||||
|
with transaction.atomic():
|
||||||
|
return func(*args, **kwargs)
|
||||||
|
except ImportConflictError:
|
||||||
|
raise
|
||||||
|
except Exception as exc: # noqa: BLE001 - force mode skips any failing step
|
||||||
|
warnings.append(f"Force-Modus: {label} wurde wegen eines Fehlers übersprungen: {exc}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _skip_uninstalled_optional_models(records, resolver, report):
|
def _skip_uninstalled_optional_models(records, resolver, report):
|
||||||
"""Drop records of optional plugins which are not installed on the target."""
|
"""Drop records of optional plugins which are not installed on the target."""
|
||||||
missing_labels = set()
|
missing_labels = set()
|
||||||
@@ -773,7 +806,9 @@ def _skip_uninstalled_optional_models(records, resolver, report):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def import_archive(parsed: ParsedArchive, *, conflict_strategy: str, dry_run: bool) -> ImportReport:
|
def import_archive(
|
||||||
|
parsed: ParsedArchive, *, conflict_strategy: str, dry_run: bool, force: bool = False
|
||||||
|
) -> ImportReport:
|
||||||
if conflict_strategy not in ("update", "skip", "fail"):
|
if conflict_strategy not in ("update", "skip", "fail"):
|
||||||
raise ArchiveValidationError("Unbekannte Konfliktstrategie.")
|
raise ArchiveValidationError("Unbekannte Konfliktstrategie.")
|
||||||
source_version = str(parsed.manifest.get("source_netbox_version", ""))
|
source_version = str(parsed.manifest.get("source_netbox_version", ""))
|
||||||
@@ -863,8 +898,19 @@ def import_archive(parsed: ParsedArchive, *, conflict_strategy: str, dry_run: bo
|
|||||||
if device_placement is not None:
|
if device_placement is not None:
|
||||||
_stage_device_placement(obj)
|
_stage_device_placement(obj)
|
||||||
compatibility.prepare_initial_save(obj, is_new=existing is None)
|
compatibility.prepare_initial_save(obj, is_new=existing is None)
|
||||||
_release_port_mapping_conflicts(obj, resolver, record_id)
|
try:
|
||||||
compatibility.save(obj)
|
_save_record(obj, resolver, record_id, compatibility, force=force)
|
||||||
|
except Exception as exc:
|
||||||
|
if not force or isinstance(exc, ImportConflictError):
|
||||||
|
raise
|
||||||
|
resolver.skipped.add(record_id)
|
||||||
|
report.warnings.append(
|
||||||
|
f"Force-Modus: {record_id} wurde wegen eines Fehlers übersprungen: {exc}"
|
||||||
|
)
|
||||||
|
report.add(record["model"], "skipped")
|
||||||
|
pending.pop(record_id)
|
||||||
|
progressed = True
|
||||||
|
continue
|
||||||
action = "updated" if existing is not None else "created"
|
action = "updated" if existing is not None else "created"
|
||||||
writable.add(record_id)
|
writable.add(record_id)
|
||||||
deferred_relations.extend((record_id, name, spec) for name, spec in unresolved)
|
deferred_relations.extend((record_id, name, spec) for name, spec in unresolved)
|
||||||
@@ -883,6 +929,15 @@ def import_archive(parsed: ParsedArchive, *, conflict_strategy: str, dry_run: bo
|
|||||||
progressed = True
|
progressed = True
|
||||||
if not progressed:
|
if not progressed:
|
||||||
blocked = ", ".join(list(pending)[:10])
|
blocked = ", ".join(list(pending)[:10])
|
||||||
|
if force:
|
||||||
|
for record_id, record in pending.items():
|
||||||
|
resolver.skipped.add(record_id)
|
||||||
|
report.add(record["model"], "skipped")
|
||||||
|
report.warnings.append(
|
||||||
|
f"Force-Modus: {len(pending)} Objekt(e) mit nicht auflösbaren Referenzen "
|
||||||
|
f"wurden übersprungen: {blocked}"
|
||||||
|
)
|
||||||
|
break
|
||||||
raise ArchiveValidationError(
|
raise ArchiveValidationError(
|
||||||
f"Erforderliche Referenzen konnten nicht aufgelöst werden: {blocked}"
|
f"Erforderliche Referenzen konnten nicht aufgelöst werden: {blocked}"
|
||||||
)
|
)
|
||||||
@@ -895,10 +950,16 @@ def import_archive(parsed: ParsedArchive, *, conflict_strategy: str, dry_run: bo
|
|||||||
raise ArchiveValidationError(f"Referenz {name} für {record_id} konnte nicht aufgelöst werden.")
|
raise ArchiveValidationError(f"Referenz {name} für {record_id} konnte nicht aufgelöst werden.")
|
||||||
if value is MISSING_REFERENCE:
|
if value is MISSING_REFERENCE:
|
||||||
continue
|
continue
|
||||||
obj = resolved[record_id]
|
_forced(
|
||||||
compatibility.release_unique_relation(obj, name, value)
|
force,
|
||||||
setattr(obj, name, value)
|
report.warnings,
|
||||||
compatibility.save(obj, update_fields=[name])
|
f"Referenz {name} für {record_id}",
|
||||||
|
_apply_deferred_relation,
|
||||||
|
resolved[record_id],
|
||||||
|
name,
|
||||||
|
value,
|
||||||
|
compatibility,
|
||||||
|
)
|
||||||
|
|
||||||
for record_id, name, spec in deferred_generic:
|
for record_id, name, spec in deferred_generic:
|
||||||
if record_id not in writable:
|
if record_id not in writable:
|
||||||
@@ -911,7 +972,14 @@ def import_archive(parsed: ParsedArchive, *, conflict_strategy: str, dry_run: bo
|
|||||||
obj = resolved[record_id]
|
obj = resolved[record_id]
|
||||||
setattr(obj, name, value)
|
setattr(obj, name, value)
|
||||||
field = next(field for field in generic_foreign_keys(type(obj)) if field.name == name)
|
field = next(field for field in generic_foreign_keys(type(obj)) if field.name == name)
|
||||||
compatibility.save(obj, update_fields=[field.ct_field, field.fk_field])
|
_forced(
|
||||||
|
force,
|
||||||
|
report.warnings,
|
||||||
|
f"Generische Referenz {name} für {record_id}",
|
||||||
|
compatibility.save,
|
||||||
|
obj,
|
||||||
|
update_fields=[field.ct_field, field.fk_field],
|
||||||
|
)
|
||||||
|
|
||||||
for record_id, name, encoded in deferred_values:
|
for record_id, name, encoded in deferred_values:
|
||||||
if record_id not in writable:
|
if record_id not in writable:
|
||||||
@@ -921,9 +989,20 @@ def import_archive(parsed: ParsedArchive, *, conflict_strategy: str, dry_run: bo
|
|||||||
raise ArchiveValidationError(f"Custom-Field-Referenz {name} für {record_id} fehlt.")
|
raise ArchiveValidationError(f"Custom-Field-Referenz {name} für {record_id} fehlt.")
|
||||||
obj = resolved[record_id]
|
obj = resolved[record_id]
|
||||||
setattr(obj, name, value)
|
setattr(obj, name, value)
|
||||||
compatibility.save(obj, update_fields=[name])
|
_forced(
|
||||||
|
force,
|
||||||
|
report.warnings,
|
||||||
|
f"Custom-Field-Wert {name} für {record_id}",
|
||||||
|
compatibility.save,
|
||||||
|
obj,
|
||||||
|
update_fields=[name],
|
||||||
|
)
|
||||||
|
|
||||||
_apply_device_placements(
|
_forced(
|
||||||
|
force,
|
||||||
|
report.warnings,
|
||||||
|
"Rackplatzierung der Geräte",
|
||||||
|
_apply_device_placements,
|
||||||
deferred_device_placements,
|
deferred_device_placements,
|
||||||
resolved,
|
resolved,
|
||||||
resolver,
|
resolver,
|
||||||
@@ -932,10 +1011,25 @@ def import_archive(parsed: ParsedArchive, *, conflict_strategy: str, dry_run: bo
|
|||||||
)
|
)
|
||||||
|
|
||||||
for record_id, record in records.items():
|
for record_id, record in records.items():
|
||||||
if record_id in writable:
|
if record_id in writable and record_id not in resolver.skipped:
|
||||||
_apply_m2m(resolved[record_id], record, resolver)
|
_forced(
|
||||||
|
force,
|
||||||
|
report.warnings,
|
||||||
|
f"Mehrfachzuordnungen für {record_id}",
|
||||||
|
_apply_m2m,
|
||||||
|
resolved[record_id],
|
||||||
|
record,
|
||||||
|
resolver,
|
||||||
|
)
|
||||||
|
|
||||||
_rebuild_imported_cable_paths(records, resolved)
|
_forced(
|
||||||
|
force,
|
||||||
|
report.warnings,
|
||||||
|
"Neuberechnung der Kabelpfade",
|
||||||
|
_rebuild_imported_cable_paths,
|
||||||
|
records,
|
||||||
|
resolved,
|
||||||
|
)
|
||||||
|
|
||||||
if dry_run:
|
if dry_run:
|
||||||
transaction.set_rollback(True)
|
transaction.set_rollback(True)
|
||||||
|
|||||||
@@ -78,6 +78,7 @@ class DashboardView(UserPassesTestMixin, View):
|
|||||||
parsed,
|
parsed,
|
||||||
conflict_strategy=form.cleaned_data["conflict_strategy"],
|
conflict_strategy=form.cleaned_data["conflict_strategy"],
|
||||||
dry_run=form.cleaned_data["dry_run"],
|
dry_run=form.cleaned_data["dry_run"],
|
||||||
|
force=form.cleaned_data["force"],
|
||||||
)
|
)
|
||||||
except ExportImportError as exc:
|
except ExportImportError as exc:
|
||||||
form.add_error(None, str(exc))
|
form.add_error(None, str(exc))
|
||||||
|
|||||||
@@ -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
|
||||||
Reference in new issue
Block a user