def get_projects(self, user): model = self.MODEL_CLASSES[self.data['model_name']] queryset = structure_filters.filter_queryset_for_user(model.objects.all(), user) if 'uuid' in self.data and self.data['uuid']: queryset = queryset.filter(uuid=self.data['uuid']) if self.data['model_name'] == 'project': return queryset.all() elif self.data['model_name'] == 'project_group': projects = structure_models.Project.objects.filter(project_groups__in=list(queryset)) return structure_filters.filter_queryset_for_user(projects, user) else: projects = structure_models.Project.objects.filter(customer__in=list(queryset)) return structure_filters.filter_queryset_for_user(projects, user)
def _get_permitted_objects_uuids(self, user): """ Return list object available UUIDs for user """ # XXX: this method has to be refactored, because it adds dependencies from iaas and structure apps from nodeconductor.structure import models as structure_models from nodeconductor.structure.filters import filter_queryset_for_user return { 'user_uuid': [user.uuid.hex], 'project_uuid': filter_queryset_for_user( structure_models.Project.objects.all(), user).values_list('uuid', flat=True), 'project_group_uuid': filter_queryset_for_user( structure_models.ProjectGroup.objects.all(), user).values_list('uuid', flat=True), 'customer_uuid': filter_queryset_for_user( structure_models.Customer.objects.all(), user).values_list('uuid', flat=True), }
def _get_filtered_data(self, objects, serializer): try: user = self.context['request'].user except (KeyError, AttributeError): return None queryset = filter_queryset_for_user(objects, user) serializer_instance = serializer(queryset, many=True, context=self.context) return serializer_instance.data
def get(self, request, format=None): usage_stats = [] aggregate_model_name = request.query_params.get( 'aggregate', 'customer') if aggregate_model_name not in self.aggregate_models.keys(): return Response( 'Get parameter "aggregate" can take only this values: ' % ', '.join(self.aggregate_models.keys()), status=status.HTTP_400_BAD_REQUEST) # This filters out the things we group by (aka aggregate root) to those that can be seen # by currently logged in user. aggregate_queryset = self._get_aggregate_queryset( request, aggregate_model_name) if 'uuid' in request.query_params: aggregate_queryset = aggregate_queryset.filter( uuid=request.query_params['uuid']) # This filters out the vm Instances to those that can be seen # by currently logged in user. This is done within each aggregate root separately. visible_instances = structure_filters.filter_queryset_for_user( models.Instance.objects.all(), request.user) for aggregate_object in aggregate_queryset: # Narrow down the instance scope to aggregate root. instances = visible_instances.filter(**self._get_aggregate_filter( aggregate_model_name, aggregate_object)) if instances: hour = 60 * 60 data = { 'start_timestamp': request.query_params.get('from', int(time.time() - hour)), 'end_timestamp': request.query_params.get('to', int(time.time())), 'segments_count': request.query_params.get('datapoints', 6), 'item': request.query_params.get('item'), } serializer = serializers.UsageStatsSerializer(data=data) serializer.is_valid(raise_exception=True) stats = serializer.get_stats(instances) usage_stats.append({ 'name': aggregate_object.name, 'datapoints': stats }) else: usage_stats.append({ 'name': aggregate_object.name, 'datapoints': [] }) return Response(usage_stats, status=status.HTTP_200_OK)
def stats(self, request): queryset = structure_filters.filter_queryset_for_user( models.InstanceLicense.objects.all(), request.user) queryset = self._filter_queryset(queryset) aggregate_parameters = self.request.query_params.getlist( 'aggregate', []) aggregate_parameter_to_field_map = { 'project': [ 'instance__cloud_project_membership__project__uuid', 'instance__cloud_project_membership__project__name', ], 'project_group': [ 'instance__cloud_project_membership__project__project_groups__uuid', 'instance__cloud_project_membership__project__project_groups__name', ], 'type': ['template_license__license_type'], 'name': ['template_license__name'], } aggregate_fields = [] for aggregate_parameter in aggregate_parameters: if aggregate_parameter not in aggregate_parameter_to_field_map: return Response( 'Licenses statistics can not be aggregated by %s' % aggregate_parameter, status=status.HTTP_400_BAD_REQUEST) aggregate_fields += aggregate_parameter_to_field_map[ aggregate_parameter] queryset = queryset.values(*aggregate_fields).annotate( count=django_models.Count('id', distinct=True)) # This hack can be removed when https://code.djangoproject.com/ticket/16735 will be closed # Replace databases paths by normal names. Ex: instance__project__uuid is replaced by project_uuid name_replace_map = { 'instance__cloud_project_membership__project__uuid': 'project_uuid', 'instance__cloud_project_membership__project__name': 'project_name', 'instance__cloud_project_membership__project__project_groups__uuid': 'project_group_uuid', 'instance__cloud_project_membership__project__project_groups__name': 'project_group_name', 'template_license__license_type': 'type', 'template_license__name': 'name', } for d in queryset: for db_name, output_name in name_replace_map.iteritems(): if db_name in d: d[output_name] = d[db_name] del d[db_name] return Response(queryset)
def get_fields(self): fields = super(PermissionFieldFilteringMixin, self).get_fields() try: request = self.context['request'] user = request.user except (KeyError, AttributeError): return fields for field_name in self.get_filtered_field_names(): fields[field_name].queryset = filter_queryset_for_user( fields[field_name].queryset, user) return fields
def get(self, request, format=None): customer_statistics = [] customer_queryset = structure_filters.filter_queryset_for_user( Customer.objects.all(), request.user) for customer in customer_queryset: projects_count = structure_filters.filter_queryset_for_user( Project.objects.filter(customer=customer), request.user).count() project_groups_count = structure_filters.filter_queryset_for_user( ProjectGroup.objects.filter(customer=customer), request.user).count() instances_count = structure_filters.filter_queryset_for_user( models.Instance.objects.filter( cloud_project_membership__project__customer=customer), request.user).count() customer_statistics.append({ 'name': customer.name, 'abbreviation': customer.abbreviation, 'projects': projects_count, 'project_groups': project_groups_count, 'instances': instances_count, }) return Response(customer_statistics, status=status.HTTP_200_OK)
def get_fields(self): fields = super(InstanceBackupRestorationSerializer, self).get_fields() try: request = self.context['view'].request user = request.user except (KeyError, AttributeError): return fields clouds = structure_filters.filter_queryset_for_user( models.Cloud.objects.all(), user) fields['template'].queryset = fields['template'].queryset.filter( images__cloud__in=clouds).distinct() return fields
def filter_clouds(clouds, request): related_clouds = clouds.all() try: user = request.user related_clouds = filter_queryset_for_user(related_clouds, user) except AttributeError: pass from nodeconductor.iaas.serializers import BasicCloudSerializer serializer_instance = BasicCloudSerializer(related_clouds, many=True, context={'request': request}) return serializer_instance.data
def get_fields(self): fields = super(InstanceCreateSerializer, self).get_fields() fields['system_volume_size'].required = False try: request = self.context['view'].request user = request.user except (KeyError, AttributeError): return fields fields['ssh_public_key'].queryset = fields['ssh_public_key'].queryset.filter(user=user) clouds = structure_filters.filter_queryset_for_user(models.Cloud.objects.all(), user) fields['template'].queryset = fields['template'].queryset.filter(images__cloud__in=clouds).distinct() return fields
def get_stats(self, user): start_datetime = core_utils.timestamp_to_datetime(self.data['start_timestamp']) end_datetime = core_utils.timestamp_to_datetime(self.data['end_timestamp']) model = self.MODEL_CLASSES[self.data['model_name']] filtered_queryset = filters.filter_queryset_for_user(model.objects.all(), user) created_datetimes = ( filtered_queryset .filter(created__gte=start_datetime, created__lte=end_datetime) .values('created') .annotate(count=django_models.Count('id', distinct=True))) time_and_value_list = [ (core_utils.datetime_to_timestamp(dt['created']), dt['count']) for dt in created_datetimes] return core_utils.format_time_and_value_to_segment_list( time_and_value_list, self.data['segments_count'], self.data['start_timestamp'], self.data['end_timestamp'])
def filtered_for_user(self, user, queryset=None): from nodeconductor.quotas import utils if queryset is None: queryset = self.get_queryset() # XXX: This circular dependency will be removed then filter_queryset_for_user # will be moved to model manager method from nodeconductor.structure.filters import filter_queryset_for_user quota_scope_models = utils.get_models_with_quotas() query = Q() for model in quota_scope_models: user_object_ids = filter_queryset_for_user( model.objects.all(), user).values_list('id', flat=True) content_type_id = ct_models.ContentType.objects.get_for_model( model).id query |= Q(object_id__in=user_object_ids, content_type_id=content_type_id) return queryset.filter(query)
def propagate_new_users_key_to_his_projects_clouds(sender, instance=None, created=False, **kwargs): if not created: return public_key = instance from nodeconductor.iaas.models import CloudProjectMembership membership_queryset = filter_queryset_for_user( CloudProjectMembership.objects.all(), public_key.user) membership_pks = membership_queryset.values_list('pk', flat=True) if membership_pks: # Note: importing here to avoid circular import hell from nodeconductor.iaas import tasks tasks.push_ssh_public_keys.delay([public_key.uuid.hex], list(membership_pks))
def get_queryset(self): queryset = super(TemplateViewSet, self).get_queryset() user = self.request.user if not user.is_staff: queryset = queryset.exclude(is_active=False) if self.request.method == 'GET': cloud_uuid = self.request.query_params.get('cloud') if cloud_uuid is not None: cloud_queryset = structure_filters.filter_queryset_for_user( models.Cloud.objects.all(), user) try: cloud = cloud_queryset.get(uuid=cloud_uuid) except models.Cloud.DoesNotExist: return queryset.none() queryset = queryset.filter(images__cloud=cloud) return queryset
def _get_aggregate_queryset(self, request, aggregate_model_name): model = self.aggregate_models[aggregate_model_name]['model'] return structure_filters.filter_queryset_for_user( model.objects.all(), request.user)
def _get_user_visible_model_instances_ids(self, user, model): queryset = structure_filters.filter_queryset_for_user( model.objects.all(), user) return queryset.values_list('pk', flat=True)