Quellcode durchsuchen

Closes #23293: Batch connected endpoint lookups in REST API lists

Endpoint lists loaded the objects of every connected cable path one
query at a time. GenericArrayForeignKey now loads prefetched objects in
the fetch mode of their paths, and the five endpoint viewsets declare
their connection lookups as field prefetches, so brief and field-limited
reads skip them.
Martin Hauser vor 5 Tagen
Ursprung
Commit
cb3b70812e

+ 10 - 15
netbox/dcim/api/views.py

@@ -57,6 +57,11 @@ class CableTerminationsPrefetch(Prefetch):
 # Mixins
 
 class PathEndpointMixin:
+    field_prefetches = {
+        ('link_peers', 'link_peers_type'): (CableTerminationsPrefetch(),),
+        ('connected_endpoints', 'connected_endpoints_type'): ('_path__path_objects',),
+        ('connected_endpoints_reachable',): ('_path',),
+    }
 
     @action(detail=True, url_path='trace')
     def trace(self, request, pk):
@@ -479,33 +484,25 @@ class ModuleViewSet(NetBoxModelViewSet):
 #
 
 class ConsolePortViewSet(PathEndpointMixin, NetBoxModelViewSet):
-    queryset = ConsolePort.objects.fetch_mode(FETCH_PEERS).prefetch_related(
-        '_path', CableTerminationsPrefetch(),
-    )
+    queryset = ConsolePort.objects.fetch_mode(FETCH_PEERS)
     serializer_class = serializers.ConsolePortSerializer
     filterset_class = filtersets.ConsolePortFilterSet
 
 
 class ConsoleServerPortViewSet(PathEndpointMixin, NetBoxModelViewSet):
-    queryset = ConsoleServerPort.objects.fetch_mode(FETCH_PEERS).prefetch_related(
-        '_path', CableTerminationsPrefetch(),
-    )
+    queryset = ConsoleServerPort.objects.fetch_mode(FETCH_PEERS)
     serializer_class = serializers.ConsoleServerPortSerializer
     filterset_class = filtersets.ConsoleServerPortFilterSet
 
 
 class PowerPortViewSet(PathEndpointMixin, NetBoxModelViewSet):
-    queryset = PowerPort.objects.fetch_mode(FETCH_PEERS).prefetch_related(
-        '_path', CableTerminationsPrefetch(),
-    )
+    queryset = PowerPort.objects.fetch_mode(FETCH_PEERS)
     serializer_class = serializers.PowerPortSerializer
     filterset_class = filtersets.PowerPortFilterSet
 
 
 class PowerOutletViewSet(PathEndpointMixin, NetBoxModelViewSet):
-    queryset = PowerOutlet.objects.fetch_mode(FETCH_PEERS).prefetch_related(
-        '_path', CableTerminationsPrefetch(),
-    )
+    queryset = PowerOutlet.objects.fetch_mode(FETCH_PEERS)
     serializer_class = serializers.PowerOutletSerializer
     filterset_class = filtersets.PowerOutletFilterSet
 
@@ -658,9 +655,7 @@ class PowerPanelViewSet(NetBoxModelViewSet):
 #
 
 class PowerFeedViewSet(PathEndpointMixin, NetBoxModelViewSet):
-    queryset = PowerFeed.objects.fetch_mode(FETCH_PEERS).prefetch_related(
-        '_path', CableTerminationsPrefetch(),
-    )
+    queryset = PowerFeed.objects.fetch_mode(FETCH_PEERS)
     serializer_class = serializers.PowerFeedSerializer
     filterset_class = filtersets.PowerFeedFilterSet
 

+ 138 - 6
netbox/dcim/tests/test_api.py

@@ -23,7 +23,16 @@ from core.choices import ObjectChangeActionChoices
 from core.models import ObjectChange, ObjectType
 from dcim.api.serializers import InterfaceSerializer
 from dcim.api.serializers_.nested import NestedDeviceBaySerializer, NestedDeviceSerializer
-from dcim.api.views import CableTerminationsPrefetch, DeviceViewSet, InterfaceViewSet
+from dcim.api.views import (
+    CableTerminationsPrefetch,
+    ConsolePortViewSet,
+    ConsoleServerPortViewSet,
+    DeviceViewSet,
+    InterfaceViewSet,
+    PowerFeedViewSet,
+    PowerOutletViewSet,
+    PowerPortViewSet,
+)
 from dcim.choices import *
 from dcim.constants import *
 from dcim.graphql.types import _CABLE_TERMINATION_MODELS
@@ -243,6 +252,79 @@ class Mixins:
                     elif params == 'brief=1':
                         self.assertGreater(savings.pop(), 0)
 
+    class ConnectedEndpointsMixin(FieldPrefetchMixin):
+        peer_termination_type = None
+        field_prefetch_cases = (
+            'omit=link_peers,link_peers_type', 'fields=id,link_peers&omit=link_peers',
+            'omit=connected_endpoints,connected_endpoints_type',
+        )
+        # Each declared lookup, loaded statically as the reference
+        eager_prefetches = (CableTerminationsPrefetch(), '_path__path_objects')
+
+        def _cable_to_peers(self, count):
+            """Cable the first endpoints to peers on an unnamed device, and return the peers by endpoint."""
+            if self.peer_termination_type is None:
+                raise NotImplementedError(_("Test case must set peer_termination_type"))
+            # Unnamed, so the device display of each peer reads its device type and manufacturer
+            peer_device = create_test_device(None, site=Site.objects.first())
+            peers = {}
+            for index, obj in enumerate(self.model.objects.order_by('pk')[:count]):
+                peers[obj] = self.peer_termination_type.objects.create(device=peer_device, name=f'Peer {index}')
+                Cable(a_terminations=[obj], b_terminations=[peers[obj]]).save()
+            return peers
+
+        def _create_field_prefetch_scopes(self):
+            """Return filters for one and for two endpoints cabled to peers."""
+            pks = [obj.pk for obj in self._cable_to_peers(2)]
+            return [f'id={pks[0]}', f'id={pks[0]}&id={pks[1]}']
+
+        def test_list_objects_connected_endpoints_query_count(self):
+            """
+            Listing path endpoints loads their connected endpoints, and the endpoints' devices and cables, with the
+            same number of queries however many endpoints are listed.
+            """
+            self.add_permissions(f'dcim.view_{self.model._meta.model_name}')
+            peers = self._cable_to_peers(3)
+
+            def check_results(objs, results):
+                endpoints = {
+                    result['id']: [endpoint['name'] for endpoint in result['connected_endpoints']]
+                    for result in results
+                }
+                self.assertEqual(endpoints, {obj.pk: [peers[obj].name] for obj in objs})
+
+            assert_list_query_count_is_constant(
+                self,
+                self._get_list_url(),
+                lambda objs: {'id': [obj.pk for obj in objs], 'fields': 'id,connected_endpoints'},
+                list(peers),
+                check_results,
+            )
+
+        def test_list_objects_connected_endpoints_reachable_query_count(self):
+            """
+            Listing path endpoints with their reachability alone loads their cable paths, and none of the paths'
+            objects.
+            """
+            self.add_permissions(f'dcim.view_{self.model._meta.model_name}')
+            pks = [obj.pk for obj in self._cable_to_peers(3)]
+
+            def get(fields):
+                with CaptureQueriesContext(connection) as queries:
+                    response = self.client.get(self._get_list_url(), {'id': pks, 'fields': fields}, **self.header)
+                self.assertHttpStatus(response, status.HTTP_200_OK)
+                # Token authentication refreshes last_used once a minute
+                count = sum('"users_token"' not in query['sql'] for query in queries.captured_queries)
+                return response.data['results'], count
+
+            # Warm per-process caches (e.g. ContentType)
+            get('id,connected_endpoints_reachable')
+            results, reachable_count = get('id,connected_endpoints_reachable')
+            _, id_count = get('id')
+            self.assertEqual([result['connected_endpoints_reachable'] for result in results], [True, True, True])
+            # One query for the cable paths
+            self.assertEqual(reachable_count, id_count + 1)
+
 
 class RegionTestCase(APIViewTestCases.APIViewTestCase):
     model = Region
@@ -4236,8 +4318,14 @@ class ModuleTestCase(APIViewTestCases.APIViewTestCase):
         self.assertHttpStatus(response, status.HTTP_400_BAD_REQUEST)
 
 
-class ConsolePortTestCase(Mixins.ComponentTraceMixin, Mixins.LinkPeersMixin, APIViewTestCases.APIViewTestCase):
+class ConsolePortTestCase(
+    Mixins.ComponentTraceMixin,
+    Mixins.LinkPeersMixin,
+    Mixins.ConnectedEndpointsMixin,
+    APIViewTestCases.APIViewTestCase,
+):
     model = ConsolePort
+    viewset = ConsolePortViewSet
     brief_fields = ['_occupied', 'cable', 'description', 'device', 'display', 'id', 'name', 'url']
     bulk_update_data = {
         'description': 'New description',
@@ -4281,9 +4369,40 @@ class ConsolePortTestCase(Mixins.ComponentTraceMixin, Mixins.LinkPeersMixin, API
             },
         ]
 
+    def _create_field_prefetch_scopes(self):
+        """Return filters for one and for two devices whose console ports carry every declared prefetch relation."""
+        filters = []
+        for i in range(2):
+            device = create_test_device(f'Unit Device {i}')
+            peer = create_test_device(f'Unit Peer {i}')
+            panel = create_test_device(f'Unit Panel {i}')
+            # a: direct, b: through a patch panel, c: ends at the panel, d: none
+            ports = {name: ConsolePort.objects.create(device=device, name=name) for name in 'abcd'}
+            peers = {name: ConsoleServerPort.objects.create(device=peer, name=name) for name in 'ab'}
+            front_ports, rear_ports = {}, {}
+            for name in 'bc':
+                front_ports[name] = FrontPort.objects.create(device=panel, name=name, type=PortTypeChoices.TYPE_8P8C)
+                rear_ports[name] = RearPort.objects.create(device=panel, name=name, type=PortTypeChoices.TYPE_8P8C)
+                PortMapping.objects.create(device=panel, front_port=front_ports[name], rear_port=rear_ports[name])
+            for a_termination, b_termination in (
+                (ports['a'], peers['a']),
+                (ports['b'], front_ports['b']),
+                (rear_ports['b'], peers['b']),
+                (ports['c'], front_ports['c']),
+            ):
+                Cable(a_terminations=[a_termination], b_terminations=[b_termination]).save()
+            filters.append(f'device_id={device.pk}')
+        return [filters[0], '&'.join(filters)]
+
 
-class ConsoleServerPortTestCase(Mixins.ComponentTraceMixin, Mixins.LinkPeersMixin, APIViewTestCases.APIViewTestCase):
+class ConsoleServerPortTestCase(
+    Mixins.ComponentTraceMixin,
+    Mixins.LinkPeersMixin,
+    Mixins.ConnectedEndpointsMixin,
+    APIViewTestCases.APIViewTestCase,
+):
     model = ConsoleServerPort
+    viewset = ConsoleServerPortViewSet
     brief_fields = ['_occupied', 'cable', 'description', 'device', 'display', 'id', 'name', 'url']
     bulk_update_data = {
         'description': 'New description',
@@ -4328,8 +4447,14 @@ class ConsoleServerPortTestCase(Mixins.ComponentTraceMixin, Mixins.LinkPeersMixi
         ]
 
 
-class PowerPortTestCase(Mixins.ComponentTraceMixin, Mixins.LinkPeersMixin, APIViewTestCases.APIViewTestCase):
+class PowerPortTestCase(
+    Mixins.ComponentTraceMixin,
+    Mixins.LinkPeersMixin,
+    Mixins.ConnectedEndpointsMixin,
+    APIViewTestCases.APIViewTestCase,
+):
     model = PowerPort
+    viewset = PowerPortViewSet
     brief_fields = ['_occupied', 'cable', 'description', 'device', 'display', 'id', 'name', 'url']
     bulk_update_data = {
         'description': 'New description',
@@ -4371,8 +4496,14 @@ class PowerPortTestCase(Mixins.ComponentTraceMixin, Mixins.LinkPeersMixin, APIVi
         ]
 
 
-class PowerOutletTestCase(Mixins.ComponentTraceMixin, Mixins.LinkPeersMixin, APIViewTestCases.APIViewTestCase):
+class PowerOutletTestCase(
+    Mixins.ComponentTraceMixin,
+    Mixins.LinkPeersMixin,
+    Mixins.ConnectedEndpointsMixin,
+    APIViewTestCases.APIViewTestCase,
+):
     model = PowerOutlet
+    viewset = PowerOutletViewSet
     brief_fields = ['_occupied', 'cable', 'description', 'device', 'display', 'id', 'name', 'url']
     bulk_update_data = {
         'description': 'New description',
@@ -6801,8 +6932,9 @@ class PowerPanelTestCase(APIViewTestCases.APIViewTestCase):
         }
 
 
-class PowerFeedTestCase(Mixins.LinkPeersMixin, APIViewTestCases.APIViewTestCase):
+class PowerFeedTestCase(Mixins.LinkPeersMixin, Mixins.ConnectedEndpointsMixin, APIViewTestCases.APIViewTestCase):
     model = PowerFeed
+    viewset = PowerFeedViewSet
     brief_fields = ['_occupied', 'cable', 'description', 'display', 'id', 'name', 'url']
     bulk_update_data = {
         'status': 'planned',

+ 4 - 2
netbox/utilities/fields.py

@@ -281,10 +281,12 @@ class GenericArrayForeignKey(FieldCacheMixin, models.Field):
         rel_objects = []
         for (ct_id, db), fkeys in fk_dict.items():
             if ct_id in custom_queryset_dict:
-                rel_objects.extend(custom_queryset_dict[ct_id].filter(pk__in=fkeys))
+                queryset = custom_queryset_dict[ct_id].filter(pk__in=fkeys)
             else:
                 ct = self.get_content_type_by_id(id=ct_id, using=db)
-                rel_objects.extend(ct.get_all_objects_for_this_type(pk__in=fkeys))
+                queryset = ct.get_all_objects_for_this_type(pk__in=fkeys)
+            # Objects take the fetch mode of the instances they are prefetched onto, as with GenericForeignKey
+            rel_objects.extend(queryset.fetch_mode(instances[0]._state.fetch_mode))
 
         # reorganize objects to fix usage
         items = {

+ 63 - 0
netbox/utilities/tests/test_prefetch.py

@@ -1,13 +1,17 @@
 from unittest.mock import PropertyMock, patch
 
+from django.contrib.contenttypes.prefetch import GenericPrefetch
 from django.db.models import FETCH_ONE, FETCH_RAISE
 
 from circuits.models import Circuit, Provider
 from core.models import ObjectType
+from dcim.choices import PortTypeChoices
+from dcim.models import Cable, CablePath, ConsolePort, ConsoleServerPort, FrontPort, PortMapping, RearPort
 from extras.models import CachedValue
 from utilities.prefetch import get_prefetchable_fields
 from utilities.querysets import RestrictedPrefetch
 from utilities.testing.base import TestCase
+from utilities.testing.utils import create_test_device
 
 
 class GetPrefetchableFieldsTestCase(TestCase):
@@ -77,3 +81,62 @@ class RestrictedGenericForeignKeyTestCase(TestCase):
                 obj = cached_value.object
 
         self.assertEqual(obj, self.provider)
+
+
+class GenericArrayForeignKeyTestCase(TestCase):
+    """
+    Verify the prefetching behavior of GenericArrayForeignKey.
+    """
+    def setUp(self):
+        super().setUp()
+
+        # A cable path through a patch panel, whose array holds five object types
+        console_port = ConsolePort.objects.create(device=create_test_device('Device 1'), name='Console Port 1')
+        panel = create_test_device('Panel 1')
+        front_port = FrontPort.objects.create(device=panel, name='Front Port 1', type=PortTypeChoices.TYPE_8P8C)
+        rear_port = RearPort.objects.create(device=panel, name='Rear Port 1', type=PortTypeChoices.TYPE_8P8C)
+        PortMapping.objects.create(device=panel, front_port=front_port, rear_port=rear_port)
+        console_server_port = ConsoleServerPort.objects.create(
+            device=create_test_device('Peer 1'), name='Console Server Port 1'
+        )
+        Cable(a_terminations=[console_port], b_terminations=[front_port]).save()
+        Cable(a_terminations=[rear_port], b_terminations=[console_server_port]).save()
+        console_port.refresh_from_db()
+        self.cable_path_id = console_port._path_id
+
+    def _prefetch_path_objects(self, queryset, lookup='path_objects'):
+        cable_path = list(queryset.filter(pk=self.cable_path_id).prefetch_related(lookup))[0]
+        return [obj for objects in cable_path.path_objects for obj in objects]
+
+    def test_prefetch_propagates_fetch_mode(self):
+        """
+        The fetch mode of the instances being prefetched is carried over to every object prefetched onto them,
+        whatever its type.
+        """
+        objects = self._prefetch_path_objects(CablePath.objects.fetch_mode(FETCH_RAISE))
+
+        self.assertEqual({type(obj) for obj in objects}, {ConsolePort, Cable, FrontPort, RearPort, ConsoleServerPort})
+        for obj in objects:
+            self.assertIs(obj._state.fetch_mode, FETCH_RAISE)
+
+    def test_prefetch_default_fetch_mode(self):
+        """
+        A queryset which sets no fetch mode yields prefetched objects using the default mode.
+        """
+        objects = self._prefetch_path_objects(CablePath.objects.all())
+
+        self.assertEqual(len(objects), 6)
+        for obj in objects:
+            self.assertIs(obj._state.fetch_mode, FETCH_ONE)
+
+    def test_prefetch_custom_queryset_fetch_mode(self):
+        """
+        Objects from a custom queryset take the fetch mode of the instances and keep the queryset's related objects.
+        """
+        lookup = GenericPrefetch('path_objects', [ConsoleServerPort.objects.select_related('device')])
+        console_server_port = self._prefetch_path_objects(CablePath.objects.fetch_mode(FETCH_RAISE), lookup)[-1]
+
+        self.assertIsInstance(console_server_port, ConsoleServerPort)
+        self.assertIs(console_server_port._state.fetch_mode, FETCH_RAISE)
+        # FETCH_RAISE would block a device fetch the custom queryset had not loaded
+        self.assertEqual(console_server_port.device.name, 'Peer 1')