querysets.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. from django.contrib.postgres.aggregates import JSONBAgg
  2. from django.db.models import OuterRef, Subquery, Q
  3. from extras.models.tags import TaggedItem
  4. from utilities.query_functions import EmptyGroupByJSONBAgg
  5. from utilities.querysets import RestrictedQuerySet
  6. __all__ = (
  7. 'ConfigContextModelQuerySet',
  8. 'ConfigContextQuerySet',
  9. 'NotificationQuerySet',
  10. )
  11. class ConfigContextQuerySet(RestrictedQuerySet):
  12. def get_for_object(self, obj, aggregate_data=False):
  13. """
  14. Return all applicable ConfigContexts for a given object. Only active ConfigContexts will be included.
  15. Args:
  16. aggregate_data: If True, use the JSONBAgg aggregate function to return only the list of JSON data objects
  17. """
  18. # Device type and location assignment are relevant only for Devices
  19. device_type = getattr(obj, 'device_type', None)
  20. location = getattr(obj, 'location', None)
  21. locations = location.get_ancestors(include_self=True) if location else []
  22. # Get assigned cluster, group, and type (if any)
  23. cluster = getattr(obj, 'cluster', None)
  24. cluster_type = getattr(cluster, 'type', None)
  25. cluster_group = getattr(cluster, 'group', None)
  26. # Get the group of the assigned tenant, if any
  27. tenant_group = obj.tenant.group if obj.tenant else None
  28. # Match against the directly assigned region as well as any parent regions.
  29. region = getattr(obj.site, 'region', None)
  30. regions = region.get_ancestors(include_self=True) if region else []
  31. # Match against the directly assigned site group as well as any parent site groups.
  32. sitegroup = getattr(obj.site, 'group', None)
  33. sitegroups = sitegroup.get_ancestors(include_self=True) if sitegroup else []
  34. # Match against the directly assigned role as well as any parent roles.
  35. device_roles = obj.role.get_ancestors(include_self=True) if obj.role else []
  36. # Match against the directly assigned platform as well as any parent platforms.
  37. platform = getattr(obj, 'platform', None)
  38. platforms = platform.get_ancestors(include_self=True) if platform else []
  39. queryset = self.filter(
  40. Q(regions__in=regions) | Q(regions=None),
  41. Q(site_groups__in=sitegroups) | Q(site_groups=None),
  42. Q(sites=obj.site) | Q(sites=None),
  43. Q(locations__in=locations) | Q(locations=None),
  44. Q(device_types=device_type) | Q(device_types=None),
  45. Q(roles__in=device_roles) | Q(roles=None),
  46. Q(platforms__in=platforms) | Q(platforms=None),
  47. Q(cluster_types=cluster_type) | Q(cluster_types=None),
  48. Q(cluster_groups=cluster_group) | Q(cluster_groups=None),
  49. Q(clusters=cluster) | Q(clusters=None),
  50. Q(tenant_groups=tenant_group) | Q(tenant_groups=None),
  51. Q(tenants=obj.tenant) | Q(tenants=None),
  52. Q(tags__slug__in=obj.tags.slugs()) | Q(tags=None),
  53. is_active=True,
  54. ).order_by('weight', 'name').distinct()
  55. if aggregate_data:
  56. return queryset.aggregate(
  57. config_context_data=JSONBAgg('data', ordering=['weight', 'name'])
  58. )['config_context_data']
  59. return queryset
  60. class ConfigContextModelQuerySet(RestrictedQuerySet):
  61. """
  62. QuerySet manager used by models which support ConfigContext (device and virtual machine).
  63. Includes a method which appends an annotation of aggregated config context JSON data objects. This is
  64. implemented as a subquery which performs all the joins necessary to filter relevant config context objects.
  65. This offers a substantial performance gain over ConfigContextQuerySet.get_for_object() when dealing with
  66. multiple objects. This allows the annotation to be entirely optional.
  67. """
  68. def annotate_config_context_data(self):
  69. """
  70. Attach the subquery annotation to the base queryset
  71. """
  72. from extras.models import ConfigContext
  73. return self.annotate(
  74. config_context_data=Subquery(
  75. ConfigContext.objects.filter(
  76. self._get_config_context_filters()
  77. ).annotate(
  78. _data=EmptyGroupByJSONBAgg('data', order_by=['weight', 'name'])
  79. ).values("_data").order_by()
  80. )
  81. )
  82. def _get_config_context_filters(self):
  83. # Construct the set of Q objects for the specific object types
  84. tag_query_filters = {
  85. "object_id": OuterRef(OuterRef('pk')),
  86. "content_type__app_label": self.model._meta.app_label,
  87. "content_type__model": self.model._meta.model_name
  88. }
  89. base_query = Q(
  90. Q(cluster_types=OuterRef('cluster__type')) | Q(cluster_types=None),
  91. Q(cluster_groups=OuterRef('cluster__group')) | Q(cluster_groups=None),
  92. Q(clusters=OuterRef('cluster')) | Q(clusters=None),
  93. Q(tenant_groups=OuterRef('tenant__group')) | Q(tenant_groups=None),
  94. Q(tenants=OuterRef('tenant')) | Q(tenants=None),
  95. Q(sites=OuterRef('site')) | Q(sites=None),
  96. Q(
  97. tags__pk__in=Subquery(
  98. TaggedItem.objects.filter(
  99. **tag_query_filters
  100. ).values_list(
  101. 'tag_id',
  102. flat=True
  103. ).distinct()
  104. )
  105. ) | Q(tags=None),
  106. is_active=True,
  107. )
  108. # Apply Location & DeviceType filters only for VirtualMachines
  109. if self.model._meta.model_name == 'device':
  110. base_query.add(
  111. (Q(
  112. locations__tree_id=OuterRef('location__tree_id'),
  113. locations__level__lte=OuterRef('location__level'),
  114. locations__lft__lte=OuterRef('location__lft'),
  115. locations__rght__gte=OuterRef('location__rght'),
  116. ) | Q(locations=None)),
  117. Q.AND
  118. )
  119. base_query.add((Q(device_types=OuterRef('device_type')) | Q(device_types=None)), Q.AND)
  120. elif self.model._meta.model_name == 'virtualmachine':
  121. base_query.add(Q(locations=None), Q.AND)
  122. base_query.add(Q(device_types=None), Q.AND)
  123. # MPTT-based filters
  124. base_query.add(
  125. (Q(
  126. regions__tree_id=OuterRef('site__region__tree_id'),
  127. regions__level__lte=OuterRef('site__region__level'),
  128. regions__lft__lte=OuterRef('site__region__lft'),
  129. regions__rght__gte=OuterRef('site__region__rght'),
  130. ) | Q(regions=None)),
  131. Q.AND
  132. )
  133. base_query.add(
  134. (Q(
  135. site_groups__tree_id=OuterRef('site__group__tree_id'),
  136. site_groups__level__lte=OuterRef('site__group__level'),
  137. site_groups__lft__lte=OuterRef('site__group__lft'),
  138. site_groups__rght__gte=OuterRef('site__group__rght'),
  139. ) | Q(site_groups=None)),
  140. Q.AND
  141. )
  142. base_query.add(
  143. (Q(
  144. roles__tree_id=OuterRef('role__tree_id'),
  145. roles__level__lte=OuterRef('role__level'),
  146. roles__lft__lte=OuterRef('role__lft'),
  147. roles__rght__gte=OuterRef('role__rght'),
  148. ) | Q(roles=None)),
  149. Q.AND
  150. )
  151. base_query.add(
  152. (Q(
  153. platforms__tree_id=OuterRef('platform__tree_id'),
  154. platforms__level__lte=OuterRef('platform__level'),
  155. platforms__lft__lte=OuterRef('platform__lft'),
  156. platforms__rght__gte=OuterRef('platform__rght'),
  157. ) | Q(platforms=None)),
  158. Q.AND
  159. )
  160. return base_query
  161. class NotificationQuerySet(RestrictedQuerySet):
  162. def unread(self):
  163. """
  164. Return only unread notifications.
  165. """
  166. return self.filter(read__isnull=True)