querysets.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. from django.apps import apps
  2. from django.contrib.contenttypes.models import ContentType
  3. from django.contrib.postgres.aggregates import JSONBAgg
  4. from django.db.models import OuterRef, Subquery, Q
  5. from django.db.utils import ProgrammingError
  6. from extras.models.tags import TaggedItem
  7. from utilities.query_functions import EmptyGroupByJSONBAgg
  8. from utilities.querysets import RestrictedQuerySet
  9. class ConfigContextQuerySet(RestrictedQuerySet):
  10. def get_for_object(self, obj, aggregate_data=False):
  11. """
  12. Return all applicable ConfigContexts for a given object. Only active ConfigContexts will be included.
  13. Args:
  14. aggregate_data: If True, use the JSONBAgg aggregate function to return only the list of JSON data objects
  15. """
  16. role = obj.role
  17. # Device type and location assignment is relevant only for Devices
  18. device_type = getattr(obj, 'device_type', None)
  19. location = getattr(obj, 'location', None)
  20. # Get assigned cluster, group, and type (if any)
  21. cluster = getattr(obj, 'cluster', None)
  22. cluster_type = getattr(cluster, 'type', None)
  23. cluster_group = getattr(cluster, 'group', None)
  24. # Get the group of the assigned tenant, if any
  25. tenant_group = obj.tenant.group if obj.tenant else None
  26. # Match against the directly assigned region as well as any parent regions.
  27. region = getattr(obj.site, 'region', None)
  28. regions = region.get_ancestors(include_self=True) if region else []
  29. # Match against the directly assigned site group as well as any parent site groups.
  30. sitegroup = getattr(obj.site, 'group', None)
  31. sitegroups = sitegroup.get_ancestors(include_self=True) if sitegroup else []
  32. queryset = self.filter(
  33. Q(regions__in=regions) | Q(regions=None),
  34. Q(site_groups__in=sitegroups) | Q(site_groups=None),
  35. Q(sites=obj.site) | Q(sites=None),
  36. Q(locations=location) | Q(locations=None),
  37. Q(device_types=device_type) | Q(device_types=None),
  38. Q(roles=role) | Q(roles=None),
  39. Q(platforms=obj.platform) | Q(platforms=None),
  40. Q(cluster_types=cluster_type) | Q(cluster_types=None),
  41. Q(cluster_groups=cluster_group) | Q(cluster_groups=None),
  42. Q(clusters=cluster) | Q(clusters=None),
  43. Q(tenant_groups=tenant_group) | Q(tenant_groups=None),
  44. Q(tenants=obj.tenant) | Q(tenants=None),
  45. Q(tags__slug__in=obj.tags.slugs()) | Q(tags=None),
  46. is_active=True,
  47. ).order_by('weight', 'name').distinct()
  48. if aggregate_data:
  49. return queryset.aggregate(
  50. config_context_data=JSONBAgg('data', ordering=['weight', 'name'])
  51. )['config_context_data']
  52. return queryset
  53. class ConfigContextModelQuerySet(RestrictedQuerySet):
  54. """
  55. QuerySet manager used by models which support ConfigContext (device and virtual machine).
  56. Includes a method which appends an annotation of aggregated config context JSON data objects. This is
  57. implemented as a subquery which performs all the joins necessary to filter relevant config context objects.
  58. This offers a substantial performance gain over ConfigContextQuerySet.get_for_object() when dealing with
  59. multiple objects. This allows the annotation to be entirely optional.
  60. """
  61. def annotate_config_context_data(self):
  62. """
  63. Attach the subquery annotation to the base queryset
  64. """
  65. from extras.models import ConfigContext
  66. return self.annotate(
  67. config_context_data=Subquery(
  68. ConfigContext.objects.filter(
  69. self._get_config_context_filters()
  70. ).annotate(
  71. _data=EmptyGroupByJSONBAgg('data', ordering=['weight', 'name'])
  72. ).values("_data").order_by()
  73. )
  74. ).distinct()
  75. def _get_config_context_filters(self):
  76. # Construct the set of Q objects for the specific object types
  77. tag_query_filters = {
  78. "object_id": OuterRef(OuterRef('pk')),
  79. "content_type__app_label": self.model._meta.app_label,
  80. "content_type__model": self.model._meta.model_name
  81. }
  82. base_query = Q(
  83. Q(platforms=OuterRef('platform')) | Q(platforms=None),
  84. Q(cluster_types=OuterRef('cluster__type')) | Q(cluster_types=None),
  85. Q(cluster_groups=OuterRef('cluster__group')) | Q(cluster_groups=None),
  86. Q(clusters=OuterRef('cluster')) | Q(clusters=None),
  87. Q(tenant_groups=OuterRef('tenant__group')) | Q(tenant_groups=None),
  88. Q(tenants=OuterRef('tenant')) | Q(tenants=None),
  89. Q(
  90. tags__pk__in=Subquery(
  91. TaggedItem.objects.filter(
  92. **tag_query_filters
  93. ).values_list(
  94. 'tag_id',
  95. flat=True
  96. )
  97. )
  98. ) | Q(tags=None),
  99. is_active=True,
  100. )
  101. if self.model._meta.model_name == 'device':
  102. base_query.add((Q(locations=OuterRef('location')) | Q(locations=None)), Q.AND)
  103. base_query.add((Q(device_types=OuterRef('device_type')) | Q(device_types=None)), Q.AND)
  104. base_query.add((Q(roles=OuterRef('role')) | Q(roles=None)), Q.AND)
  105. base_query.add((Q(sites=OuterRef('site')) | Q(sites=None)), Q.AND)
  106. region_field = 'site__region'
  107. sitegroup_field = 'site__group'
  108. elif self.model._meta.model_name == 'virtualmachine':
  109. base_query.add((Q(roles=OuterRef('role')) | Q(roles=None)), Q.AND)
  110. base_query.add((Q(sites=OuterRef('cluster__site')) | Q(sites=None)), Q.AND)
  111. base_query.add(Q(device_types=None), Q.AND)
  112. region_field = 'cluster__site__region'
  113. sitegroup_field = 'cluster__site__group'
  114. base_query.add(
  115. (Q(
  116. regions__tree_id=OuterRef(f'{region_field}__tree_id'),
  117. regions__level__lte=OuterRef(f'{region_field}__level'),
  118. regions__lft__lte=OuterRef(f'{region_field}__lft'),
  119. regions__rght__gte=OuterRef(f'{region_field}__rght'),
  120. ) | Q(regions=None)),
  121. Q.AND
  122. )
  123. base_query.add(
  124. (Q(
  125. site_groups__tree_id=OuterRef(f'{sitegroup_field}__tree_id'),
  126. site_groups__level__lte=OuterRef(f'{sitegroup_field}__level'),
  127. site_groups__lft__lte=OuterRef(f'{sitegroup_field}__lft'),
  128. site_groups__rght__gte=OuterRef(f'{sitegroup_field}__rght'),
  129. ) | Q(site_groups=None)),
  130. Q.AND
  131. )
  132. return base_query
  133. class ObjectChangeQuerySet(RestrictedQuerySet):
  134. def valid_models(self):
  135. # Exclude any change records which refer to an instance of a model that's no longer installed. This
  136. # can happen when a plugin is removed but its data remains in the database, for example.
  137. try:
  138. content_types = ContentType.objects.get_for_models(*apps.get_models()).values()
  139. except ProgrammingError:
  140. # Handle the case where the database schema has not yet been initialized
  141. content_types = ContentType.objects.none()
  142. content_type_ids = set(
  143. ct.pk for ct in content_types
  144. )
  145. return self.filter(changed_object_type_id__in=content_type_ids)