Пример #1
0
    def update_reseller_billing_plan(self, request, pk):
        del pk  # unused
        client = self.get_object()
        plan_id = request.data['plan']
        reseller_service_id = request.data['service']

        try:
            plan = PricingPlan.objects.get(id=plan_id)
        except PricingPlan.DoesNotExist:
            raise ObjectNotFound({'detail': _('Plan not found')})

        try:
            reseller_service = Service.objects.get(id=reseller_service_id)
        except Service.DoesNotExist:
            raise ObjectNotFound({'detail': _('Service not found')})

        reseller_service.reseller_resources.plan = plan
        reseller_service.reseller_resources.save()
        for service in Service.objects.filter(
                client__reseller_resources=reseller_service.reseller_resources
        ):
            service.reseller_service_dynamic_usage.plan = plan
            service.reseller_service_dynamic_usage.save()

        return Response({'detail': 'Plan updated'})
Пример #2
0
    def dissociate_user(self, request, pk):
        del pk  # unused
        if reseller_active_features.is_enabled('demo'):
            raise ForbiddenException(
                detail=_('Operation not allowed in demo mode'))

        client = self.get_object()
        try:
            # delete the cart related to client
            client_cart = client.fleio_cart
            client_cart.delete()
        except Client.fleio_cart.RelatedObjectDoesNotExist:
            pass
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user_model = get_user_model()
        try:
            user = user_model.objects.get(
                id=serializer.validated_data['user_id'])
            try:
                # delete the cart related to user
                user_cart = user.fleio_cart
                user_cart.delete()
            except user_model.fleio_cart.RelatedObjectDoesNotExist:
                pass
        except user_model.DoesNotExist:
            raise ObjectNotFound({'detail': _('User not found')})
        UserToClient.objects.filter(user=user, client=client).delete()
        return Response({'detail': _('User dissociated')})
Пример #3
0
 def create_options(self, request):
     options = dict()
     options['products'] = [{
         'id': pack.id,
         'name': pack.name,
         'description': pack.description
     } for pack in Product.objects.all()]
     if not options['products']:
         raise ObjectNotFound('No products exist')
     options['cycles'] = CyclePeriods.choices
     options['currencies'] = CurrencySerializer(
         instance=Currency.objects.all(), many=True).data
     if not options['currencies']:
         raise ObjectNotFound('No currencies exist')
     options['statuses'] = PublicStatuses.choices
     return Response({'create_options': options})
Пример #4
0
 def get_snapshots_for_instance(self, request):
     instance_uuid = request.GET.get('instance_uuid', None)
     # check if the user requests snapshots for an instance that he owns
     instance = Instance.objects.filter(id=instance_uuid).first()
     if not instance:
         raise APIBadRequest(
             _('Cannot get snapshots for non existing instance.'))
     client_project = Project.objects.filter(
         service__client__in=request.user.clients.all()).first(
         )  # type: Project
     if not client_project:
         raise APIBadRequest(_('Client does not have any project.'))
     if instance.project.project_id != client_project.project_id:
         raise ObjectNotFound()
     volume_attachments = VolumeAttachments.objects.filter(
         server_id=instance_uuid).values('volume_id')
     volumes = Volume.objects.filter(id__in=volume_attachments)
     volume_snapshots_qs = VolumeSnapshot.objects.filter(volume__in=volumes)
     volume_snapshots_count = volume_snapshots_qs.count()
     volume_snapshots_uuids = volume_snapshots_qs.values('id')
     image_snapshots = Image.objects.get_images_for_project(
         project_id=client_project.project_id).filter(
             Q(volume_snapshot_uuid__in=volume_snapshots_uuids)
             | Q(instance_uuid=instance_uuid))
     serializer = ImageSerializer(image_snapshots, many=True)
     return Response({
         'objects': serializer.data,
         'volume_snapshots_count': volume_snapshots_count,
     })
Пример #5
0
def generate_revenue_report(self, monthly_report_id, **kwargs):
    del self, kwargs  # unused
    try:
        monthly_report = MonthlyRevenueReport.objects.get(id=monthly_report_id)
    except MonthlyRevenueReport.DoesNotExist:
        raise ObjectNotFound(_('Could not find monthly revenue report to work with.'))
    location_report = LocationReport(start_date=monthly_report.start_date, end_date=monthly_report.end_date)
    location_report.save_report()
Пример #6
0
 def deactivate(self, request, pk):
     del request, pk  # unused
     image = self.get_object()
     try:
         Images(api_session=self.os_admin_api.session).deactivate(image=image)
     except (Exception, HTTPNotFound) as e:
         if type(e) == HTTPNotFound:
             raise ObjectNotFound(detail=e.details)
         LOG.exception(e)
         handle(self.request)
     return Response({'detail': _('Image {} deactivated').format(image)})
Пример #7
0
 def perform_update(self, serializer):
     db_project = Project.objects.get(id=serializer.validated_data['id'])
     openstack_project = OpenstackProject.with_admin_session(
         db_project.project_id)
     try:
         openstack_project.update(
             name=serializer.validated_data['name'],
             description=serializer.validated_data['description'],
             enabled=not serializer.validated_data['disabled'])
     except NotFound as e:
         raise ObjectNotFound(detail=e)
Пример #8
0
 def associate_user(self, request, pk):
     del pk  # unused
     client = self.get_object()
     serializer = self.get_serializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     user_model = get_user_model()
     try:
         user = user_model.objects.get(
             id=serializer.validated_data['user_id'])
     except user_model.DoesNotExist:
         raise ObjectNotFound({'detail': _('User not found')})
     UserToClient.objects.create(user=user, client=client)
     return Response({'detail': _('User associated')})
Пример #9
0
    def create_options(self, request):
        del request  # unused
        options = dict()
        options['groups'] = [{
            'id': group.id,
            'name': group.name,
            'description': group.description
        } for group in ProductGroup.objects.filter(visible=True).all()]
        if not options['groups']:
            raise ObjectNotFound('No product groups exist')
        modules_queryset = ProductModule.objects.filter(
            plugin__enabled=True).exclude(
                plugin__staff_feature_name__in=staff_active_features.
                get_disabled_features())
        options['modules'] = {
            module.id: {
                'id':
                module.id,
                'name':
                module.name,
                'plugin':
                module.plugin_label
                if module.plugin_label and PluginUtils.has_staff_component(
                    plugin_label=module.plugin_label,
                    component_name='ProductSettings') else None,
                'description':
                module.description
            }
            for module in modules_queryset
        }
        if not options['modules']:
            raise ObjectNotFound('No product modules exist')

        options['product_types'] = ProductType.choices
        options['statuses'] = PublicStatuses.choices
        options['price_models'] = PricingModel.choices
        options['auto_setups'] = ProductAutoSetup.choices

        return Response(options)
Пример #10
0
 def change_pricing_plan(self, service: Service, new_plan_id):
     try:
         db_plan = PricingPlan.objects.get(pk=new_plan_id)
     except ObjectDoesNotExist:
         raise ObjectNotFound(detail=_('Pricing plan does not exist'))
     else:
         # TODO: see if this is correct
         if self.reseller_usage:
             service.reseller_service_dynamic_usage.plan = db_plan
             service.reseller_service_dynamic_usage.save(
                 update_fields=['plan'])
         else:
             service.service_dynamic_usage.plan = db_plan
             service.service_dynamic_usage.save(update_fields=['plan'])
Пример #11
0
    def reactivate(self, request, pk):
        del request, pk  # unused

        image = self.get_object()
        if not active_features.is_enabled('openstack.images.updatecreate'):
            raise ForbiddenException(_('Image reactivation not allowed'))
        try:
            self.os_api.images.reactivate(image=image)
        except (Exception, GlanceNotFoundException) as e:
            if type(e) == GlanceNotFoundException:
                raise ObjectNotFound(detail=e.details)
            LOG.exception(e)
            handle(self.request)
        return Response({'detail': _('Image {} reactivated').format(image)})
Пример #12
0
    def update_reseller_enduser_panel_url(self, request, pk):
        del pk  # unused
        client = self.get_object()
        enduser_panel_url = request.data['enduser_panel_url']
        reseller_service_id = request.data['service']

        try:
            reseller_service = Service.objects.get(id=reseller_service_id)
        except Service.DoesNotExist:
            raise ObjectNotFound({'detail': _('Service not found')})

        reseller_service.reseller_resources.enduser_panel_url = enduser_panel_url
        reseller_service.reseller_resources.save()

        return Response({'detail': 'Enduser panel url updated'})
Пример #13
0
    def change_configuration(self, request, pk):
        del pk  # unused
        serializer = ConfigurationIdSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        client = self.get_object()
        try:
            config = Configuration.objects.get(
                pk=serializer.validated_data['configuration'])
        except Configuration.DoesNotExist:
            raise ObjectNotFound({'detail': _('Configuration does not exist')})

        client.configuration = config
        client.save(update_fields=['configuration'])

        return Response({'detail': _('Ok')})
Пример #14
0
def refresh_license(request):
    try:
        key = Option.objects.get(section='LICENSE', field='key')
        license_key = fernet_decrypt(key.value)
    except Option.DoesNotExist as e:
        LOG.error(e)
        raise ObjectNotFound(detail=_('License not found'))
    else:
        try:
            response, status = _set_license(license_key)
            return Response({'detail': response}, status=status)
        except requests.ConnectionError as e:
            LOG.error(e)
            raise ServiceUnavailable(
                detail=_('Can\'t connect to server. '
                         'Please check your internet connection and retry.'))
Пример #15
0
    def download(self, request, pk):
        del pk, request  # unused

        if not staff_active_features.is_enabled('openstack.images.download'):
            raise ForbiddenException(_('Image download not allowed'))

        db_image = self.get_object()  # type: OpenstackImage
        try:
            images_api = Images(api_session=self.os_admin_api.session)
            image_data = images_api.download(image=db_image)
        except (Exception, HTTPNotFound) as e:
            if type(e) == HTTPNotFound:
                raise ObjectNotFound(detail=e.details)
            LOG.exception(e)
            handle(self.request)
        else:
            response = StreamingHttpResponse(streaming_content=image_data)
            response['Content-Type'] = 'application/octet-stream'
            response['Content-Disposition'] = 'attachment; filename="{}"'.format(db_image.name)
            return response
Пример #16
0
    def create_openstack_service(self, request, pk):
        del pk  # unused

        # TODO - #1019: implement proper creation of service here
        serializer = CreateServiceSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        client = self.get_object()

        if client.first_project is not None and client.first_project.deleted is False:
            raise ForbiddenException(
                {'detail': _('Client already has a project')})

        project_id = serializer.validated_data.get('project_id', 'none')

        if Client.objects.filter(
                services__openstack_project__project_id=project_id):
            raise ForbiddenException(
                {'detail': _('Project already associated with a client')})

        openstack_product = Product.objects.get(
            id=serializer.validated_data['product_id'])
        openstack_product_cycle = openstack_product.cycles.filter(
            id=serializer.validated_data['product_cycle_id'])[0]
        service_external_id = serializer.validated_data.get(
            'service_external_id', None)

        with transaction.atomic():
            if serializer.validated_data['create_new_project']:
                try:
                    ProjectModel.objects.create_project(
                        client=client,
                        openstack_product=openstack_product,
                        openstack_product_cycle=openstack_product_cycle,
                        service_external_id=service_external_id,
                    )
                except Conflict:
                    return Response(
                        status=409,
                        data={
                            'detail':
                            _('A project already exists for this client')
                        })
                except RoleDoesNotExist:
                    # TODO: going to the exact settings page and field isn't implemented yet in frontend
                    # on implementation in frontend change section and configuration_id if necessary
                    # (Issue: https://git.fleio.org/fleio/fleio/issues/1922)
                    if plugin_settings.default_role:
                        error_message = _(
                            'Role "{}" does not exist in OpenStack. Set an existing role as default '
                            'role.').format(plugin_settings.default_role)
                    else:
                        error_message = _(
                            'OpenStack role was not set in OpenStack settings -> defaults tab. '
                            'Set an existing role as default role.')
                    raise ConfigException(message=error_message,
                                          section='openstack_plugin_defaults',
                                          configuration_id='default_role')
            else:
                try:
                    project = IdentityAdminApi(
                        request_session=request.session).client.projects.get(
                            project_id)
                except NotFound:
                    raise ObjectNotFound({'detail': _('Project not found')})
                except ConnectFailure:
                    raise ServiceUnavailable(
                        {'detail': _('Could not connect to openstack')})

                with transaction.atomic():
                    try:
                        ProjectModel.objects.create_project(
                            client=client,
                            openstack_product=openstack_product,
                            openstack_product_cycle=openstack_product_cycle,
                            service_external_id=service_external_id,
                            project_id=project.id,
                            project_domain_id=project.domain_id,
                            disabled=not project.enabled,
                            extras={
                                'name': project.name,
                                'description': project.description,
                                'is_domain': project.is_domain
                            }).save()
                    except RoleDoesNotExist:
                        # TODO: going to the exact settings page and field isn't implemented yet in frontend
                        # on implementation in frontend change section and configuration_id if necessary
                        # (Issue: https://git.fleio.org/fleio/fleio/issues/1922)
                        if plugin_settings.default_role:
                            error_message = _(
                                'Role "{}" does not exist in OpenStack. Set an existing role as default '
                                'role.').format(plugin_settings.default_role)
                        else:
                            error_message = _(
                                'OpenStack role was not set in OpenStack settings -> defaults tab. '
                                'Set an existing role as default role.')
                        raise ConfigException(
                            message=error_message,
                            section='openstack_plugin_defaults',
                            configuration_id='default_role')

        return Response({'detail': _('Ok')})