querysets.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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. class ConfigContextQuerySet(RestrictedQuerySet):
  7. def get_for_object(self, obj, aggregate_data=False):
  8. """
  9. Return all applicable ConfigContexts for a given object. Only active ConfigContexts will be included.
  10. Args:
  11. aggregate_data: If True, use the JSONBAgg aggregate function to return only the list of JSON data objects
  12. """
  13. # `device_role` for Device; `role` for VirtualMachine
  14. role = getattr(obj, 'device_role', None) or obj.role
  15. # Device type assignment is relevant only for Devices
  16. device_type = getattr(obj, 'device_type', None)
  17. # Get assigned cluster, group, and type (if any)
  18. cluster = getattr(obj, 'cluster', None)
  19. cluster_type = getattr(cluster, 'type', None)
  20. cluster_group = getattr(cluster, 'group', None)
  21. # Get the group of the assigned tenant, if any
  22. tenant_group = obj.tenant.group if obj.tenant else None
  23. # Match against the directly assigned region as well as any parent regions.
  24. region = getattr(obj.site, 'region', None)
  25. regions = region.get_ancestors(include_self=True) if region else []
  26. # Match against the directly assigned site group as well as any parent site groups.
  27. sitegroup = getattr(obj.site, 'group', None)
  28. sitegroups = sitegroup.get_ancestors(include_self=True) if sitegroup else []
  29. queryset = self.filter(
  30. Q(regions__in=regions) | Q(regions=None),
  31. Q(site_groups__in=sitegroups) | Q(site_groups=None),
  32. Q(sites=obj.site) | Q(sites=None),
  33. Q(device_types=device_type) | Q(device_types=None),
  34. Q(roles=role) | Q(roles=None),
  35. Q(platforms=obj.platform) | Q(platforms=None),
  36. Q(cluster_types=cluster_type) | Q(cluster_types=None),
  37. Q(cluster_groups=cluster_group) | Q(cluster_groups=None),
  38. Q(clusters=cluster) | Q(clusters=None),
  39. Q(tenant_groups=tenant_group) | Q(tenant_groups=None),
  40. Q(tenants=obj.tenant) | Q(tenants=None),
  41. Q(tags__slug__in=obj.tags.slugs()) | Q(tags=None),
  42. is_active=True,
  43. ).order_by('weight', 'name').distinct()
  44. if aggregate_data:
  45. return queryset.aggregate(
  46. config_context_data=JSONBAgg('data', ordering=['weight', 'name'])
  47. )['config_context_data']
  48. return queryset
  49. class ConfigContextModelQuerySet(RestrictedQuerySet):
  50. """
  51. QuerySet manager used by models which support ConfigContext (device and virtual machine).
  52. Includes a method which appends an annotation of aggregated config context JSON data objects. This is
  53. implemented as a subquery which performs all the joins necessary to filter relevant config context objects.
  54. This offers a substantial performance gain over ConfigContextQuerySet.get_for_object() when dealing with
  55. multiple objects. This allows the annotation to be entirely optional.
  56. """
  57. def annotate_config_context_data(self):
  58. """
  59. Attach the subquery annotation to the base queryset
  60. """
  61. from extras.models import ConfigContext
  62. return self.annotate(
  63. config_context_data=Subquery(
  64. ConfigContext.objects.filter(
  65. self._get_config_context_filters()
  66. ).annotate(
  67. _data=EmptyGroupByJSONBAgg('data', ordering=['weight', 'name'])
  68. ).values("_data").order_by()
  69. )
  70. ).distinct()
  71. def _get_config_context_filters(self):
  72. # Construct the set of Q objects for the specific object types
  73. tag_query_filters = {
  74. "object_id": OuterRef(OuterRef('pk')),
  75. "content_type__app_label": self.model._meta.app_label,
  76. "content_type__model": self.model._meta.model_name
  77. }
  78. base_query = Q(
  79. Q(platforms=OuterRef('platform')) | Q(platforms=None),
  80. Q(cluster_types=OuterRef('cluster__type')) | Q(cluster_types=None),
  81. Q(cluster_groups=OuterRef('cluster__group')) | Q(cluster_groups=None),
  82. Q(clusters=OuterRef('cluster')) | Q(clusters=None),
  83. Q(tenant_groups=OuterRef('tenant__group')) | Q(tenant_groups=None),
  84. Q(tenants=OuterRef('tenant')) | Q(tenants=None),
  85. Q(
  86. tags__pk__in=Subquery(
  87. TaggedItem.objects.filter(
  88. **tag_query_filters
  89. ).values_list(
  90. 'tag_id',
  91. flat=True
  92. )
  93. )
  94. ) | Q(tags=None),
  95. is_active=True,
  96. )
  97. if self.model._meta.model_name == 'device':
  98. base_query.add((Q(device_types=OuterRef('device_type')) | Q(device_types=None)), Q.AND)
  99. base_query.add((Q(roles=OuterRef('device_role')) | Q(roles=None)), Q.AND)
  100. base_query.add((Q(sites=OuterRef('site')) | Q(sites=None)), Q.AND)
  101. region_field = 'site__region'
  102. sitegroup_field = 'site__group'
  103. elif self.model._meta.model_name == 'virtualmachine':
  104. base_query.add((Q(roles=OuterRef('role')) | Q(roles=None)), Q.AND)
  105. base_query.add((Q(sites=OuterRef('cluster__site')) | Q(sites=None)), Q.AND)
  106. base_query.add(Q(device_types=None), Q.AND)
  107. region_field = 'cluster__site__region'
  108. sitegroup_field = 'cluster__site__group'
  109. base_query.add(
  110. (Q(
  111. regions__tree_id=OuterRef(f'{region_field}__tree_id'),
  112. regions__level__lte=OuterRef(f'{region_field}__level'),
  113. regions__lft__lte=OuterRef(f'{region_field}__lft'),
  114. regions__rght__gte=OuterRef(f'{region_field}__rght'),
  115. ) | Q(regions=None)),
  116. Q.AND
  117. )
  118. base_query.add(
  119. (Q(
  120. site_groups__tree_id=OuterRef(f'{sitegroup_field}__tree_id'),
  121. site_groups__level__lte=OuterRef(f'{sitegroup_field}__level'),
  122. site_groups__lft__lte=OuterRef(f'{sitegroup_field}__lft'),
  123. site_groups__rght__gte=OuterRef(f'{sitegroup_field}__rght'),
  124. ) | Q(site_groups=None)),
  125. Q.AND
  126. )
  127. return base_query