Пример #1
0
    def assign_floating_ip(self, request, uuid):
        instance = self.get_object()

        serializer = serializers.AssignFloatingIpSerializer(instance,
                                                            data=request.data)
        serializer.is_valid(raise_exception=True)

        if not instance.service_project_link.external_network_id:
            return response.Response(
                {
                    'detail':
                    'External network ID of the service project link is missing.'
                },
                status=status.HTTP_409_CONFLICT)
        elif instance.service_project_link.state not in SynchronizationStates.STABLE_STATES:
            raise IncorrectStateException(
                "Service project link of instance should be in stable state.")
        elif instance.state not in instance.States.STABLE_STATES:
            raise IncorrectStateException(
                "Cannot add floating IP to instance in unstable state.")

        send_task('openstack', 'assign_floating_ip')(
            instance.uuid.hex, serializer.validated_data['floating_ip_uuid'])

        return response.Response(
            {
                'detail':
                'Assigning floating IP to the instance has been scheduled.'
            },
            status=status.HTTP_202_ACCEPTED)
Пример #2
0
def exception_handler(exc, context):
    if isinstance(exc, ProtectedError):
        dependent_meta = exc.protected_objects.model._meta

        try:
            # This exception should be raised from a viewset
            instance_meta = context['view'].get_queryset().model._meta
        except (AttributeError, KeyError):
            # Fallback, when instance being deleted cannot be inferred
            instance_name = 'object'
        else:
            instance_name = force_text(instance_meta.verbose_name)

        detail = _(
            'Cannot delete {instance_name} with existing {dependant_objects}'
        ).format(
            instance_name=instance_name,
            dependant_objects=force_text(dependent_meta.verbose_name_plural),
        )

        # We substitute exception here to get consistent representation
        # for both ProtectError and manually raised IncorrectStateException
        exc = IncorrectStateException(detail=detail)

    return rf_exception_handler(exc, context)
Пример #3
0
    def set_quotas(self, request, **kwargs):
        if not request.user.is_staff:
            raise exceptions.PermissionDenied()

        spl = self.get_object()
        if spl.state != SynchronizationStates.IN_SYNC:
            return IncorrectStateException(
                "Service project link must be in stable state.")

        serializer = serializers.ServiceProjectLinkQuotaSerializer(
            data=request.data)
        serializer.is_valid(raise_exception=True)

        data = dict(serializer.validated_data)
        if data.get('instances') is not None:
            quotas = settings.NODECONDUCTOR.get(
                'OPENSTACK_QUOTAS_INSTANCE_RATIOS', {})
            volume_ratio = quotas.get('volumes', 4)
            snapshots_ratio = quotas.get('snapshots', 20)

            data['volumes'] = volume_ratio * data['instances']
            data['snapshots'] = snapshots_ratio * data['instances']

        send_task('structure', 'sync_service_project_links')(spl.to_string(),
                                                             quotas=data)

        return response.Response({'detail': 'Quota update was scheduled'},
                                 status=status.HTTP_202_ACCEPTED)
Пример #4
0
    def perform_create(self, serializer):
        user = serializer.validated_data['user']
        template = serializer.validated_data['template']
        backend = user.tenant.get_backend()

        if user.tenant.state != models.SharepointTenant.States.ONLINE:
            raise IncorrectStateException("Tenant must be in stable state to perform site collection creation")

        try:
            storage = serializer.validated_data.pop('storage')
            backend_site = backend.site_collections.create(
                admin_id=user.admin_id,
                template_code=template.code,
                site_url=serializer.validated_data['site_url'],
                name=serializer.validated_data['name'],
                description=serializer.validated_data['description'],
                storage=storage)

        except SaltStackBackendError as e:
            raise exceptions.APIException(e.traceback_str)
        else:
            site_collection = serializer.save()
            site_collection.access_url = backend_site.url
            site_collection.save()
            site_collection.set_quota_limit(site_collection.Quotas.storage, storage)
Пример #5
0
    def initialize(self, request, **kwargs):
        tenant = self.get_object()
        if tenant.initialization_status != models.SharepointTenant.InitializationStatuses.NOT_INITIALIZED:
            raise IncorrectStateException(
                "Tenant must be in 'Not initialized' state to perform initialization operation."
            )

        # create main site collection
        serializer_class = self.get_serializer_class()
        serializer = serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)

        storage = serializer.validated_data.pop('storage')
        template = serializer.validated_data.pop('template')
        user = serializer.validated_data.pop('user')
        name = serializer.validated_data.pop('name')
        description = serializer.validated_data.pop('description')

        if user.tenant != tenant:
            return response.Response(
                {'user': '******'},
                status=status.HTTP_400_BAD_REQUEST)

        tenant.initialization_status = models.SharepointTenant.InitializationStatuses.INITIALIZING
        tenant.save()

        tasks.initialize_tenant.delay(tenant.uuid.hex, template.uuid.hex,
                                      user.uuid.hex, storage, name,
                                      description)

        return response.Response(
            {'status': 'Initialization was scheduled successfully.'},
            status=status.HTTP_200_OK)
Пример #6
0
    def initial(self, request, *args, **kwargs):
        if self.action in ('update', 'partial_update', 'destroy'):
            obj = self.get_object()
            if obj and isinstance(obj, SynchronizableMixin):
                if obj.state not in SynchronizationStates.STABLE_STATES:
                    raise IncorrectStateException(
                        'Modification allowed in stable states only.')

        return super(UpdateOnlyStableMixin,
                     self).initial(request, *args, **kwargs)
Пример #7
0
    def set_created(self):
        """
        Performs following actions:
            - Freeze all invoice items
            - Change state from pending to billed
        """
        if self.state != self.States.PENDING:
            raise IncorrectStateException(_('Invoice must be in pending state.'))

        self.state = self.States.CREATED
        self.invoice_date = timezone.now().date()
        self.save(update_fields=['state', 'invoice_date'])
Пример #8
0
    def perform_create(self, serializer):
        tenant = serializer.validated_data['tenant']
        backend = self.get_backend(tenant)

        if tenant.state != Resource.States.ONLINE:
            raise IncorrectStateException(
                "Tenant must be in stable state to perform this operation")

        valid_args = [arg for arg in backend.Methods.create['input'] if arg != 'tenant']
        backend_obj = backend.create(
            **{k: v for k, v in serializer.validated_data.items() if k in valid_args and v is not None})

        obj = serializer.save(backend_id=backend_obj.id)
        self.post_create(obj, serializer, backend_obj)
Пример #9
0
    def perform_create(self, serializer):
        if not has_user_permission_for_instance(
                self.request.user, serializer.validated_data['backup_source']):
            raise PermissionDenied(
                'You do not have permission to perform this action.')

        # Check that backup source is in stable state.
        backup_source = serializer.validated_data.get('backup_source')
        state = getattr(backup_source, 'state')

        if state not in backup_source.States.STABLE_STATES:
            raise IncorrectStateException(
                'Backup source should be in stable state.')

        backup = serializer.save()
        backup.start_backup()
Пример #10
0
    def allocate_floating_ip(self, request, pk=None):
        spl = self.get_object()
        if not spl.external_network_id:
            return response.Response(
                {
                    'detail':
                    'Service project link should have an external network ID.'
                },
                status=status.HTTP_409_CONFLICT)

        elif spl.state not in SynchronizationStates.STABLE_STATES:
            raise IncorrectStateException(
                "Service project link must be in stable state.")

        send_task('openstack', 'allocate_floating_ip')(spl.to_string())

        return response.Response(
            {'detail': 'Floating IP allocation has been scheduled.'},
            status=status.HTTP_202_ACCEPTED)
Пример #11
0
    def perform_create(self, serializer):
        tenant = serializer.validated_data['tenant']
        backend = tenant.get_backend()

        if tenant.state != models.SharepointTenant.States.ONLINE:
            raise IncorrectStateException(
                "Tenant must be online to perform user creation")

        try:
            backend_user = backend.users.create(
                first_name=serializer.validated_data['first_name'],
                last_name=serializer.validated_data['last_name'],
                username=serializer.validated_data['username'],
                name=serializer.validated_data['name'],
                email=serializer.validated_data['email'])

        except SaltStackBackendError as e:
            raise exceptions.APIException(e.traceback_str)
        else:
            user = serializer.save()
            user.password = backend_user.password
            user.admin_id = backend_user.admin_id
            user.backend_id = backend_user.id
            user.save()