querysets.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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. role = obj.role
  19. # Device type and location assignment is relevant only for Devices
  20. device_type = getattr(obj, 'device_type', None)
  21. location = getattr(obj, 'location', None)
  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. queryset = self.filter(
  35. Q(regions__in=regions) | Q(regions=None),
  36. Q(site_groups__in=sitegroups) | Q(site_groups=None),
  37. Q(sites=obj.site) | Q(sites=None),
  38. Q(locations=location) | Q(locations=None),
  39. Q(device_types=device_type) | Q(device_types=None),
  40. Q(roles=role) | Q(roles=None),
  41. Q(platforms=obj.platform) | Q(platforms=None),
  42. Q(cluster_types=cluster_type) | Q(cluster_types=None),
  43. Q(cluster_groups=cluster_group) | Q(cluster_groups=None),
  44. Q(clusters=cluster) | Q(clusters=None),
  45. Q(tenant_groups=tenant_group) | Q(tenant_groups=None),
  46. Q(tenants=obj.tenant) | Q(tenants=None),
  47. Q(tags__slug__in=obj.tags.slugs()) | Q(tags=None),
  48. is_active=True,
  49. ).order_by('weight', 'name').distinct()
  50. if aggregate_data:
  51. return queryset.aggregate(
  52. config_context_data=JSONBAgg('data', ordering=['weight', 'name'])
  53. )['config_context_data']
  54. return queryset
  55. class ConfigContextModelQuerySet(RestrictedQuerySet):
  56. """
  57. QuerySet manager used by models which support ConfigContext (device and virtual machine).
  58. Includes a method which appends an annotation of aggregated config context JSON data objects. This is
  59. implemented as a subquery which performs all the joins necessary to filter relevant config context objects.
  60. This offers a substantial performance gain over ConfigContextQuerySet.get_for_object() when dealing with
  61. multiple objects. This allows the annotation to be entirely optional.
  62. """
  63. def annotate_config_context_data(self):
  64. """
  65. Attach the subquery annotation to the base queryset
  66. """
  67. from extras.models import ConfigContext
  68. return self.annotate(
  69. config_context_data=Subquery(
  70. ConfigContext.objects.filter(
  71. self._get_config_context_filters()
  72. ).annotate(
  73. _data=EmptyGroupByJSONBAgg('data', ordering=['weight', 'name'])
  74. ).values("_data").order_by()
  75. )
  76. ).distinct()
  77. def _get_config_context_filters(self):
  78. # Construct the set of Q objects for the specific object types
  79. tag_query_filters = {
  80. "object_id": OuterRef(OuterRef('pk')),
  81. "content_type__app_label": self.model._meta.app_label,
  82. "content_type__model": self.model._meta.model_name
  83. }
  84. base_query = Q(
  85. Q(platforms=OuterRef('platform')) | Q(platforms=None),
  86. Q(cluster_types=OuterRef('cluster__type')) | Q(cluster_types=None),
  87. Q(cluster_groups=OuterRef('cluster__group')) | Q(cluster_groups=None),
  88. Q(clusters=OuterRef('cluster')) | Q(clusters=None),
  89. Q(tenant_groups=OuterRef('tenant__group')) | Q(tenant_groups=None),
  90. Q(tenants=OuterRef('tenant')) | Q(tenants=None),
  91. Q(
  92. tags__pk__in=Subquery(
  93. TaggedItem.objects.filter(
  94. **tag_query_filters
  95. ).values_list(
  96. 'tag_id',
  97. flat=True
  98. )
  99. )
  100. ) | Q(tags=None),
  101. is_active=True,
  102. )
  103. # Apply Location & DeviceType filters only for VirtualMachines
  104. if self.model._meta.model_name == 'device':
  105. base_query.add((Q(locations=OuterRef('location')) | Q(locations=None)), Q.AND)
  106. base_query.add((Q(device_types=OuterRef('device_type')) | Q(device_types=None)), Q.AND)
  107. elif self.model._meta.model_name == 'virtualmachine':
  108. base_query.add(Q(locations=None), Q.AND)
  109. base_query.add(Q(device_types=None), Q.AND)
  110. base_query.add((Q(roles=OuterRef('role')) | Q(roles=None)), Q.AND)
  111. base_query.add((Q(sites=OuterRef('site')) | Q(sites=None)), Q.AND)
  112. base_query.add(
  113. (Q(
  114. regions__tree_id=OuterRef('site__region__tree_id'),
  115. regions__level__lte=OuterRef('site__region__level'),
  116. regions__lft__lte=OuterRef('site__region__lft'),
  117. regions__rght__gte=OuterRef('site__region__rght'),
  118. ) | Q(regions=None)),
  119. Q.AND
  120. )
  121. base_query.add(
  122. (Q(
  123. site_groups__tree_id=OuterRef('site__group__tree_id'),
  124. site_groups__level__lte=OuterRef('site__group__level'),
  125. site_groups__lft__lte=OuterRef('site__group__lft'),
  126. site_groups__rght__gte=OuterRef('site__group__rght'),
  127. ) | Q(site_groups=None)),
  128. Q.AND
  129. )
  130. return base_query
  131. class NotificationQuerySet(RestrictedQuerySet):
  132. def unread(self):
  133. """
  134. Return only unread notifications.
  135. """
  136. return self.filter(read__isnull=True)