Jelajahi Sumber

Fixes #23807: Prevent recreation of deleted devices and VMs (#23833)

Deleting an IP address saves the device or virtual machine that uses
it as a primary or out-of-band IP, and saving a device saves its child
devices. If another request had deleted that object in the meantime,
the save inserted it again. These saves now only update, and an object
that no longer exists is skipped.
Martin Hauser 18 jam lalu
induk
melakukan
871420f0dc

+ 8 - 2
netbox/dcim/models/devices.py

@@ -1199,13 +1199,19 @@ class Device(
             update_interface_bridges(self, self.device_type.interfacetemplates.all())
 
         # Update Site and Rack assignment for any child Devices
-        devices = Device.objects.filter(parent_bay__device=self)
+        using = self._state.db
+        devices = Device.objects.using(using).filter(parent_bay__device=self)
         for device in devices:
             device.snapshot()
             device.site = self.site
             device.rack = self.rack
             device.location = self.location
-            device.save()
+            # Prevent recreation of concurrently deleted child devices without aborting this save
+            try:
+                with transaction.atomic(using=using):
+                    device.save(using=using, force_update=True)
+            except Device.NotUpdated:
+                continue
 
     @property
     def label(self):

+ 75 - 2
netbox/dcim/tests/test_models.py

@@ -5,7 +5,7 @@ from decimal import Decimal
 from unittest.mock import patch
 
 from django.core.exceptions import ValidationError
-from django.db import connection, transaction
+from django.db import IntegrityError, connection, transaction
 from django.db.models import ProtectedError
 from django.db.models.signals import post_save
 from django.test import RequestFactory, TestCase, override_settings, tag
@@ -27,7 +27,7 @@ from tenancy.models import Tenant
 from users.models import User
 from utilities.data import drange
 from utilities.exceptions import AbortRequest
-from utilities.testing import create_test_device, create_test_image
+from utilities.testing import PinnedConnectionRouter, create_test_device, create_test_image
 from virtualization.models import Cluster, ClusterType
 
 
@@ -1444,6 +1444,79 @@ class DeviceBayTestCase(TestCase):
         self.assertEqual(change.prechange_data['site'], old_site.pk)
         self.assertEqual(change.postchange_data['site'], new_site.pk)
 
+    @tag('regression')  # Ref: #23807
+    def test_moving_parent_device_skips_concurrently_deleted_child(self):
+        DeviceBay.objects.create(device=self.parent_device, name='Bay 1', installed_device=self.child_device)
+        DeviceBay.objects.create(device=self.parent_device, name='Bay 2', installed_device=self.child_device_2)
+        new_site = Site.objects.create(name='Test Site 2', slug='test-site-2')
+        request = RequestFactory().get('/')
+        request.id = uuid.uuid4()
+        request.user = User.objects.create_user(username='testuser')
+        snapshot = Device.snapshot
+        handled = []
+
+        def snapshot_then_delete(device):
+            snapshot(device)
+            handled.append(device.pk)
+            if device.pk == self.child_device.pk:
+                # Simulate a concurrent deletion, which unseats the device before deleting its row
+                DeviceBay.objects.filter(installed_device=device).update(installed_device=None)
+                Device.objects.filter(pk=device.pk)._raw_delete(using=device._state.db)
+
+        parent = Device.objects.get(pk=self.parent_device.pk)
+        parent.snapshot()
+        parent.site = new_site
+        with event_tracking(request), patch.object(Device, 'snapshot', snapshot_then_delete):
+            parent.save()
+
+        # In any other order, a skip that ended the loop would go unnoticed
+        self.assertEqual(handled, [self.child_device.pk, self.child_device_2.pk])
+        self.assertFalse(Device.objects.filter(pk=self.child_device.pk).exists())
+        self.child_device_2.refresh_from_db()
+        self.assertEqual(self.child_device_2.site, new_site)
+        changes = ObjectChange.objects.filter(
+            request_id=request.id,
+            changed_object_type=ObjectType.objects.get_for_model(Device),
+        )
+        self.assertFalse(changes.filter(changed_object_id=self.child_device.pk).exists())
+        self.assertEqual(
+            changes.get(changed_object_id=self.child_device_2.pk).action,
+            ObjectChangeActionChoices.ACTION_UPDATE,
+        )
+
+    def test_moving_parent_device_propagates_child_save_errors(self):
+        DeviceBay.objects.create(device=self.parent_device, name='Bay 1', installed_device=self.child_device)
+        parent = Device.objects.get(pk=self.parent_device.pk)
+        parent.site = Site.objects.create(name='Test Site 2', slug='test-site-2')
+        save = Device.save
+
+        def save_or_fail(device, *args, **kwargs):
+            if device.pk == self.child_device.pk:
+                raise IntegrityError('Simulated save error')
+            return save(device, *args, **kwargs)
+
+        # Only a missing row is skipped, so any other error still aborts the save
+        with (
+            self.assertRaisesMessage(IntegrityError, 'Simulated save error'),
+            transaction.atomic(),
+            patch.object(Device, 'save', save_or_fail),
+        ):
+            parent.save()
+
+        self.assertEqual(Device.objects.get(pk=self.parent_device.pk).site, self.parent_device.site)
+
+    def test_moving_parent_device_pins_child_queries_to_saving_connection(self):
+        DeviceBay.objects.create(device=self.parent_device, name='Bay 1', installed_device=self.child_device)
+        parent = Device.objects.get(pk=self.parent_device.pk)
+        parent.site = Site.objects.create(name='Test Site 2', slug='test-site-2')
+
+        # Naming the connection keeps the parent's own save off the router
+        with override_settings(DATABASE_ROUTERS=[PinnedConnectionRouter(Device)]):
+            parent.save(using='default')
+
+        self.child_device.refresh_from_db()
+        self.assertEqual(self.child_device.site, parent.site)
+
     def test_can_disable_bay_with_existing_device(self):
         """
         Test that disabling a bay that already has a device installed does NOT raise an error

+ 20 - 12
netbox/ipam/signals.py

@@ -1,3 +1,4 @@
+from django.db import transaction
 from django.db.models.signals import post_delete, post_save, pre_delete
 from django.dispatch import receiver
 
@@ -53,27 +54,34 @@ def handle_prefix_deleted(instance, using=None, **kwargs):
 
 
 @receiver(pre_delete, sender=IPAddress)
-def clear_primary_ip(instance, **kwargs):
+def clear_primary_ip(instance, using=None, **kwargs):
     """
     When an IPAddress is deleted, trigger save() on any Devices/VirtualMachines for which it was a primary IP.
     """
     field_name = f'primary_ip{instance.family}'
-    if device := Device.objects.filter(**{field_name: instance}).first():
-        device.snapshot()
-        setattr(device, field_name, None)
-        device.save()
-    if virtualmachine := VirtualMachine.objects.filter(**{field_name: instance}).first():
-        virtualmachine.snapshot()
-        setattr(virtualmachine, field_name, None)
-        virtualmachine.save()
+    for model in (Device, VirtualMachine):
+        if obj := model.objects.using(using).filter(**{field_name: instance}).first():
+            obj.snapshot()
+            setattr(obj, field_name, None)
+            # Prevent recreation of concurrently deleted objects without aborting the deletion transaction
+            try:
+                with transaction.atomic(using=using):
+                    obj.save(using=using, force_update=True)
+            except model.NotUpdated:
+                continue
 
 
 @receiver(pre_delete, sender=IPAddress)
-def clear_oob_ip(instance, **kwargs):
+def clear_oob_ip(instance, using=None, **kwargs):
     """
     When an IPAddress is deleted, trigger save() on any Devices for which it was a OOB IP.
     """
-    if device := Device.objects.filter(oob_ip=instance).first():
+    if device := Device.objects.using(using).filter(oob_ip=instance).first():
         device.snapshot()
         device.oob_ip = None
-        device.save()
+        # Prevent recreation of a concurrently deleted device without aborting the deletion transaction
+        try:
+            with transaction.atomic(using=using):
+                device.save(using=using, force_update=True)
+        except Device.NotUpdated:
+            pass

+ 159 - 2
netbox/ipam/tests/test_signals.py

@@ -1,17 +1,20 @@
 import uuid
+from unittest.mock import patch
 
 from django.contrib.contenttypes.models import ContentType
-from django.test import RequestFactory, TestCase, override_settings
+from django.db import IntegrityError, transaction
+from django.test import RequestFactory, TestCase, override_settings, tag
 
 from core.choices import ObjectChangeActionChoices
 from core.models import ObjectChange
-from dcim.models import Location, Region, Site, SiteGroup
+from dcim.models import Device, Location, Region, Site, SiteGroup
 from ipam import signals
 from ipam.models import VRF, IPAddress, Prefix
 from netbox.context_managers import event_tracking
 from users.models import User
 from utilities.testing import PinnedConnectionRouter
 from utilities.testing.utils import create_test_device, create_test_virtualmachine
+from virtualization.models import VirtualMachine
 
 
 def _build_request(user):
@@ -21,6 +24,24 @@ def _build_request(user):
     return request
 
 
+def _delete_while_object_vanishes(ip, obj, user):
+    """Delete ip while another request deletes obj right after the receiver snapshots it."""
+    model = type(obj)
+    snapshot = model.snapshot
+    request = _build_request(user)
+
+    def snapshot_then_delete(instance):
+        snapshot(instance)
+        if instance.pk == obj.pk:
+            # Simulate a concurrent deletion without dispatching signals in this request
+            model.objects.filter(pk=instance.pk)._raw_delete(using=instance._state.db)
+
+    with event_tracking(request), patch.object(model, 'snapshot', snapshot_then_delete):
+        ip.delete()
+
+    return request
+
+
 class PrefixHierarchySignalTestCase(TestCase):
     """
     Verify ipam.signals.handle_prefix_saved / handle_prefix_deleted keep the cached
@@ -181,6 +202,94 @@ class ClearPrimaryIPSignalTestCase(TestCase):
             ).exists()
         )
 
+    @tag('regression')  # Ref: #23807
+    def test_device_primary_ip4_delete_skips_concurrently_deleted_device(self):
+        device = create_test_device('Device 1')
+        ip = IPAddress.objects.create(address='192.0.2.1/24')
+        device.primary_ip4 = ip
+        device.save()
+
+        request = _delete_while_object_vanishes(ip, device, self.user)
+
+        self.assertFalse(Device.objects.filter(pk=device.pk).exists())
+        self.assertFalse(
+            ObjectChange.objects.filter(
+                request_id=request.id,
+                changed_object_type=ContentType.objects.get_for_model(Device),
+                changed_object_id=device.pk,
+            ).exists()
+        )
+
+    @tag('regression')  # Ref: #23807
+    def test_vm_primary_ip4_delete_skips_concurrently_deleted_vm(self):
+        vm = create_test_virtualmachine('VM 1')
+        ip = IPAddress.objects.create(address='192.0.2.10/24')
+        vm.primary_ip4 = ip
+        vm.save()
+
+        request = _delete_while_object_vanishes(ip, vm, self.user)
+
+        self.assertFalse(VirtualMachine.objects.filter(pk=vm.pk).exists())
+        self.assertFalse(
+            ObjectChange.objects.filter(
+                request_id=request.id,
+                changed_object_type=ContentType.objects.get_for_model(VirtualMachine),
+                changed_object_id=vm.pk,
+            ).exists()
+        )
+
+    @tag('regression')  # Ref: #23807
+    def test_primary_ip_delete_updates_vm_after_concurrently_deleted_device(self):
+        device = create_test_device('Device 1')
+        vm = create_test_virtualmachine('VM 1')
+        ip = IPAddress.objects.create(address='192.0.2.1/24')
+        device.primary_ip4 = ip
+        device.save()
+        vm.primary_ip4 = ip
+        vm.save()
+
+        request = _delete_while_object_vanishes(ip, device, self.user)
+
+        self.assertFalse(Device.objects.filter(pk=device.pk).exists())
+        # Only the receiver's save() records a change, the SET_NULL fallback clears the field silently
+        change = ObjectChange.objects.get(
+            request_id=request.id,
+            changed_object_type=ContentType.objects.get_for_model(VirtualMachine),
+            changed_object_id=vm.pk,
+        )
+        self.assertEqual(change.action, ObjectChangeActionChoices.ACTION_UPDATE)
+        self.assertIsNone(change.postchange_data['primary_ip4'])
+
+    def test_primary_ip_delete_propagates_device_save_errors(self):
+        device = create_test_device('Device 1')
+        ip = IPAddress.objects.create(address='192.0.2.1/24')
+        device.primary_ip4 = ip
+        device.save()
+
+        # Only a missing row is skipped, so any other error still aborts the deletion
+        with (
+            self.assertRaisesMessage(IntegrityError, 'Simulated save error'),
+            transaction.atomic(),
+            patch.object(Device, 'save', side_effect=IntegrityError('Simulated save error')),
+        ):
+            ip.delete()
+
+        self.assertTrue(IPAddress.objects.filter(pk=ip.pk).exists())
+
+    def test_primary_ip_delete_pins_queries_to_deleting_connection(self):
+        device = create_test_device('Device 1')
+        ip = IPAddress.objects.create(address='192.0.2.1/24')
+        device.primary_ip4 = ip
+        device.save()
+        last_updated = device.last_updated
+
+        with override_settings(DATABASE_ROUTERS=[PinnedConnectionRouter(Device, VirtualMachine)]):
+            ip.delete()
+
+        # Only the receiver's save() moves last_updated, the SET_NULL fallback does not
+        device.refresh_from_db()
+        self.assertGreater(device.last_updated, last_updated)
+
 
 class ClearOOBIPSignalTestCase(TestCase):
     """
@@ -233,6 +342,54 @@ class ClearOOBIPSignalTestCase(TestCase):
             ).exists()
         )
 
+    @tag('regression')  # Ref: #23807
+    def test_device_oob_ip_delete_skips_concurrently_deleted_device(self):
+        device = create_test_device('Device 1')
+        ip = IPAddress.objects.create(address='192.0.2.1/24')
+        device.oob_ip = ip
+        device.save()
+
+        request = _delete_while_object_vanishes(ip, device, self.user)
+
+        self.assertFalse(Device.objects.filter(pk=device.pk).exists())
+        self.assertFalse(
+            ObjectChange.objects.filter(
+                request_id=request.id,
+                changed_object_type=ContentType.objects.get_for_model(Device),
+                changed_object_id=device.pk,
+            ).exists()
+        )
+
+    def test_oob_ip_delete_propagates_device_save_errors(self):
+        device = create_test_device('Device 1')
+        ip = IPAddress.objects.create(address='192.0.2.1/24')
+        device.oob_ip = ip
+        device.save()
+
+        # Only a missing row is skipped, so any other error still aborts the deletion
+        with (
+            self.assertRaisesMessage(IntegrityError, 'Simulated save error'),
+            transaction.atomic(),
+            patch.object(Device, 'save', side_effect=IntegrityError('Simulated save error')),
+        ):
+            ip.delete()
+
+        self.assertTrue(IPAddress.objects.filter(pk=ip.pk).exists())
+
+    def test_oob_ip_delete_pins_queries_to_deleting_connection(self):
+        device = create_test_device('Device 1')
+        ip = IPAddress.objects.create(address='192.0.2.1/24')
+        device.oob_ip = ip
+        device.save()
+        last_updated = device.last_updated
+
+        with override_settings(DATABASE_ROUTERS=[PinnedConnectionRouter(Device)]):
+            ip.delete()
+
+        # Only the receiver's save() moves last_updated, the SET_NULL fallback does not
+        device.refresh_from_db()
+        self.assertGreater(device.last_updated, last_updated)
+
 
 class PrefixDenormalizationTriggerTestCase(TestCase):
     """