Exemple #1
0
    def create(self, request):
        user = request.user
        data = request.data
        try:
            self.validate_input(user, data)
        except Exception as exc:
            return failure_response(status.HTTP_400_BAD_REQUEST, exc.message)

        # Create a mutable dict and start modifying.
        data = data.copy()
        name = data.get('name')
        identity_uuid = data.get('identity')
        source_alias = data.get('source_alias')
        size_alias = data.get('size_alias')
        allocation_source_id = data.get('allocation_source_id')
        boot_scripts = data.pop("scripts", [])
        deploy = data.get('deploy')
        extra = data.get('extra')
        try:
            identity = Identity.objects.get(uuid=identity_uuid)
            allocation_source = AllocationSource.objects.get(
                source_id=allocation_source_id)
            core_instance = launch_instance(user, identity_uuid, size_alias,
                                            source_alias, name, deploy,
                                            **extra)
            # Faking a 'partial update of nothing' to allow call to 'is_valid'
            serialized_instance = InstanceSerializer(
                core_instance,
                context={'request': self.request},
                data={},
                partial=True)
            if not serialized_instance.is_valid():
                return Response(serialized_instance.errors,
                                status=status.HTTP_400_BAD_REQUEST)
            instance = serialized_instance.save()
            if boot_scripts:
                _save_scripts_to_instance(instance, boot_scripts)
            instance.change_allocation_source(allocation_source)
            return Response(serialized_instance.data,
                            status=status.HTTP_201_CREATED)
        except UnderThresholdError as ute:
            return under_threshold(ute)
        except (OverQuotaError, OverAllocationError) as oqe:
            return over_quota(oqe)
        except ProviderNotActive as pna:
            return inactive_provider(pna)
        except SizeNotAvailable as snae:
            return size_not_available(snae)
        except HypervisorCapacityError as hce:
            return over_capacity(hce)
        except SecurityGroupNotCreated:
            return connection_failure(identity)
        except (socket_error, ConnectionFailure):
            return connection_failure(identity)
        except LibcloudInvalidCredsError:
            return invalid_creds(identity)
        except Exception as exc:
            logger.exception("Encountered a generic exception. "
                             "Returning 409-CONFLICT")
            return failure_response(status.HTTP_409_CONFLICT, str(exc.message))
Exemple #2
0
 def post_instance_action(self, request, pk=None):
     user = request.user
     instance_id = pk
     instance = find_instance(instance_id)
     identity = instance.created_by_identity
     action_params = dict(request.data)
     action = action_params.pop('action')
     if type(action) == list:
         action = action[0]
     try:
         result_obj = run_instance_action(user, identity, instance_id, action, action_params)
         api_response = {
             'result': 'success',
             'message': 'The requested action <%s> was run successfully' % (action,),
             'object': result_obj,
         }
         response = Response(api_response, status=status.HTTP_200_OK)
         return response
     except (socket_error, ConnectionFailure):
         return connection_failure(identity)
     except InstanceDoesNotExist as dne:
         return failure_response(
             status.HTTP_404_NOT_FOUND,
             'Instance %s no longer exists' % (dne.message,))
     except LibcloudInvalidCredsError:
         return invalid_creds(identity)
     except HypervisorCapacityError as hce:
         return over_capacity(hce)
     except ProviderNotActive as pna:
         return inactive_provider(pna)
     except (OverQuotaError, OverAllocationError) as oqe:
         return over_quota(oqe)
     except SizeNotAvailable as snae:
         return size_not_available(snae)
     except (socket_error, ConnectionFailure):
         return connection_failure(identity)
     except VolumeMountConflict as vmc:
         return mount_failed(vmc)
     except NotImplemented:
         return failure_response(
             status.HTTP_409_CONFLICT,
             "The requested action %s is not available on this provider."
             % action)
     except ActionNotAllowed:
         return failure_response(
             status.HTTP_409_CONFLICT,
             "The requested action %s has been explicitly "
             "disabled on this provider." % action)
     except Exception as exc:
         logger.exception("Exception occurred processing InstanceAction")
         message = exc.message
         if message.startswith('409 Conflict'):
             return failure_response(
                 status.HTTP_409_CONFLICT,
                 message)
         return failure_response(
             status.HTTP_403_FORBIDDEN,
             "The requested action %s encountered "
             "an irrecoverable exception: %s"
             % (action, message))
    def create(self, request):
        request_user = request.user
        request_data = request.data

        if not request_data.items():
            return failure_response(status.HTTP_400_BAD_REQUEST,
                                    "Reuquest Data is missing")

        try:
            self._validate_data(request_user, request_data)
        except Exception as exc:
            return failure_response(status.HTTP_400_BAD_REQUEST, exc.message)

        try:
            user_allocation_source = self._create_user_allocation_source(
                request_data)
            serialized_user_allocation_source = UserAllocationSourceSerializer(
                user_allocation_source, context={'request': self.request})
            return Response(serialized_user_allocation_source.data,
                            status=status.HTTP_201_CREATED)

        except Exception as exc:
            logger.exception(
                "Encountered exception while assigning Allocation source %s to User %s"
                % (request_data['allocation_source_name'],
                   request_data['username']))
            return failure_response(status.HTTP_409_CONFLICT, str(exc.message))
    def delete(self, request):
        request_user = request.user
        request_data = request.data
        if not request_data.items():
            return failure_response(status.HTTP_400_BAD_REQUEST,
                                    "Reuquest Data is missing")

        try:
            self._validate_data(request_user, request_data, delete=True)
        except Exception as exc:
            return failure_response(
                status.HTTP_400_BAD_REQUEST,
                exc.message)

        try:
            self._delete_user_allocation_source(request_data)
            return Response(
                status=status.HTTP_200_OK)

        except Exception as exc:
            logger.exception(
                "Encountered exception while removing User %s from Allocation source %s "
                % (request_data['username']), request_data['allocation_source_name'])
            return failure_response(status.HTTP_409_CONFLICT,
                                    str(exc.message))
Exemple #5
0
    def retrieve(self, request, pk=None):
        """
        Retrieve a signed token for a web desktop view.
        """
        if not request.user.is_authenticated():
            raise PermissionDenied

        client = request.query_params.get('client')
        valid_guac = client == "guacamole" and settings.GUACAMOLE_ENABLED
        valid_webdesktop = client == "web_desktop"
        if not (valid_guac or valid_webdesktop):
            return failure_response(
                status.HTTP_400_BAD_REQUEST,
                'Invalid or missing "client" query paramater')

        instance = self.get_queryset().filter(provider_alias=pk).first()
        if not instance:
            return failure_response(
                status.HTTP_404_NOT_FOUND,
                'Instance %s not found / no longer exists' % pk)

        token = None
        token_url = None
        try:
            if client == 'guacamole':
                token, token_url = self.guacamole_token(instance.ip_address)
            else:
                token, token_url = self.web_desktop_token(instance.ip_address)
        except:
            logger.exception("Atmosphere failed to retrieve web token")
            return HttpResponse("Atmosphere failed to retrieve web token",
                                status=500)

        return Response({'token': token, 'token_url': token_url})
Exemple #6
0
 def perform_destroy(self, instance):
     user = self.request.user
     identity_uuid = instance.created_by_identity.uuid
     identity = Identity.objects.get(id=identity_uuid)
     try:
         # Test that there is not an attached volume BEFORE we destroy
         #NOTE: Although this is a task we are calling and waiting for response..
         core_instance = destroy_instance(
             user,
             identity_uuid,
             instance.provider_alias)
         serialized_instance = InstanceSerializer(
             core_instance, context={
                 'request': self.request},
             data={}, partial=True)
         if not serialized_instance.is_valid():
             return Response(serialized_instance.data,
                             status=status.HTTP_400_BAD_REQUEST)
         return Response(status=status.HTTP_204_NO_CONTENT)
     except VolumeAttachConflict as exc:
         message = exc.message
         return failure_response(status.HTTP_409_CONFLICT, message)
     except (socket_error, ConnectionFailure):
         return connection_failure(identity)
     except InvalidCredsError:
         return invalid_creds(identity)
     except Exception as exc:
         logger.exception("Encountered a generic exception. "
                          "Returning 409-CONFLICT")
         return failure_response(status.HTTP_409_CONFLICT,
                                 str(exc.message))
Exemple #7
0
 def post_instance_action(self, request, pk=None):
     user = request.user
     instance_id = pk
     instance = find_instance(instance_id)
     identity = instance.created_by_identity
     action_params = request.data
     action = action_params.pop('action')
     try:
         result_obj = run_instance_action(user, identity, instance_id, action, action_params)
         api_response = {
             'result': 'success',
             'message': 'The requested action <%s> was run successfully' % (action,),
             'object': result_obj,
         }
         response = Response(api_response, status=status.HTTP_200_OK)
         return response
     except (socket_error, ConnectionFailure):
         return connection_failure(identity)
     except InstanceDoesNotExist as dne:
         return failure_response(
             status.HTTP_404_NOT_FOUND,
             'Instance %s no longer exists' % (dne.message,))
     except InvalidCredsError:
         return invalid_creds(identity)
     except HypervisorCapacityError as hce:
         return over_capacity(hce)
     except ProviderNotActive as pna:
         return inactive_provider(pna)
     except (OverQuotaError, OverAllocationError) as oqe:
         return over_quota(oqe)
     except SizeNotAvailable as snae:
         return size_not_available(snae)
     except (socket_error, ConnectionFailure):
         return connection_failure(identity)
     except InvalidCredsError:
         return invalid_creds(identity)
     except VolumeMountConflict as vmc:
         return mount_failed(vmc)
     except NotImplemented:
         return failure_response(
             status.HTTP_409_CONFLICT,
             "The requested action %s is not available on this provider."
             % action_params['action'])
     except ActionNotAllowed:
         return failure_response(
             status.HTTP_409_CONFLICT,
             "The requested action %s has been explicitly "
             "disabled on this provider." % action_params['action'])
     except Exception as exc:
         logger.exception("Exception occurred processing InstanceAction")
         message = exc.message
         if message.startswith('409 Conflict'):
             return failure_response(
                 status.HTTP_409_CONFLICT,
                 message)
         return failure_response(
             status.HTTP_403_FORBIDDEN,
             "The requested action %s encountered "
             "an irrecoverable exception: %s"
             % (action_params['action'], message))
Exemple #8
0
 def perform_destroy(self, instance):
     user = self.request.user
     identity_uuid = str(instance.created_by_identity.uuid)
     identity = Identity.objects.get(uuid=identity_uuid)
     provider_uuid = str(identity.provider.uuid)
     try:
         # Test that there is not an attached volume and destroy is ASYNC
         destroy_instance.delay(
             instance.provider_alias, user, identity_uuid)
         # NOTE: Task to delete has been queued, return 204
         serializer = InstanceSerializer(
             instance, context={
                 'request': self.request},
             data={}, partial=True)
         if not serializer.is_valid():
             return Response("Errors encountered during delete: %s" % serializer.errors,
                             status=status.HTTP_400_BAD_REQUEST)
         return Response(status=status.HTTP_204_NO_CONTENT)
     except VolumeAttachConflict as exc:
         message = exc.message
         return failure_response(status.HTTP_409_CONFLICT, message)
     except (socket_error, ConnectionFailure):
         return connection_failure(provider_uuid, identity_uuid)
     except LibcloudInvalidCredsError:
         return invalid_creds(provider_uuid, identity_uuid)
     except InstanceDoesNotExist as dne:
         return failure_response(
             status.HTTP_404_NOT_FOUND,
             'Instance %s no longer exists' % (dne.message,))
     except Exception as exc:
         logger.exception("Encountered a generic exception. "
                          "Returning 409-CONFLICT")
         return failure_response(status.HTTP_409_CONFLICT,
                                 str(exc.message))
    def create(self, request):
        request_user = request.user
        request_data = request.data

        if not request_data.items():
            return failure_response(status.HTTP_400_BAD_REQUEST,
                                    "Reuquest Data is missing")

        if not request_data['action']:
            return failure_response(status.HTTP_400_BAD_REQUEST,
                                    "Command name is missing")

        try:
            self._validate_user(request_data,request_user)
        except Exception as exc:
            return failure_response(
                status.HTTP_400_BAD_REQUEST,
                exc.message)

        action = str(request_data['action'])

        if action=='create_allocation_source':
            return self.create_allocation_source(request_data,request_user)
        elif action=='change_renewal_strategy':
            return self.change_renewal_strategy(request_data,request_user)
        elif action=='change_allocation_source_name':
            return self.change_allocation_source_name(request_data,request_user)
        elif action=='change_compute_allowed':
            return self.change_allocation_source_compute_allowed(request_data,request_user)
        else:
            return failure_response(status.HTTP_400_BAD_REQUEST,
                             "Incorrect command name")
Exemple #10
0
 def perform_destroy(self, instance):
     user = self.request.user
     identity_uuid = str(instance.created_by_identity.uuid)
     identity = Identity.objects.get(uuid=identity_uuid)
     provider_uuid = str(identity.provider.uuid)
     try:
         # Test that there is not an attached volume and destroy is ASYNC
         destroy_instance.delay(instance.provider_alias, user,
                                identity_uuid)
         # NOTE: Task to delete has been queued, return 204
         serializer = InstanceSerializer(instance,
                                         context={'request': self.request},
                                         data={},
                                         partial=True)
         if not serializer.is_valid():
             return Response("Errors encountered during delete: %s" %
                             serializer.errors,
                             status=status.HTTP_400_BAD_REQUEST)
         return Response(status=status.HTTP_204_NO_CONTENT)
     except VolumeAttachConflict as exc:
         message = exc.message
         return failure_response(status.HTTP_409_CONFLICT, message)
     except (socket_error, ConnectionFailure):
         return connection_failure(provider_uuid, identity_uuid)
     except LibcloudInvalidCredsError:
         return invalid_creds(provider_uuid, identity_uuid)
     except InstanceDoesNotExist as dne:
         return failure_response(
             status.HTTP_404_NOT_FOUND,
             'Instance %s no longer exists' % (dne.message, ))
     except Exception as exc:
         logger.exception("Encountered a generic exception. "
                          "Returning 409-CONFLICT")
         return failure_response(status.HTTP_409_CONFLICT, str(exc.message))
    def create(self, request):
        request_user = request.user
        request_data = request.data

        if not request_data.items():
            return failure_response(
                status.HTTP_400_BAD_REQUEST, "Reuquest Data is missing"
            )

        try:
            self._validate_data(request_user, request_data)
        except Exception as exc:
            return failure_response(status.HTTP_400_BAD_REQUEST, exc.message)

        try:
            instance_allocation_source = self._create_instance_allocation_source(
                request_data, request_user
            )
            serialized_instance_allocation_source = InstanceAllocationSourceSerializer(
                instance_allocation_source, context={'request': self.request}
            )
            return Response(
                serialized_instance_allocation_source.data,
                status=status.HTTP_201_CREATED
            )

        except Exception as exc:
            logger.exception(
                "Encountered exception while assigning Allocation source %s to Instance %s"
                % (
                    request_data['allocation_source_name'],
                    request_data['instance_id']
                )
            )
            return failure_response(status.HTTP_409_CONFLICT, str(exc.message))
Exemple #12
0
 def perform_destroy(self, instance):
     user = self.request.user
     identity_uuid = instance.created_by_identity.uuid
     identity = Identity.objects.get(uuid=identity_uuid)
     try:
         # Test that there is not an attached volume BEFORE we destroy
         #NOTE: Although this is a task we are calling and waiting for response..
         core_instance = destroy_instance(user, identity_uuid,
                                          instance.provider_alias)
         serialized_instance = InstanceSerializer(
             core_instance,
             context={'request': self.request},
             data={},
             partial=True)
         if not serialized_instance.is_valid():
             return Response(serialized_instance.data,
                             status=status.HTTP_400_BAD_REQUEST)
         return Response(status=status.HTTP_204_NO_CONTENT)
     except VolumeAttachConflict as exc:
         message = exc.message
         return failure_response(status.HTTP_409_CONFLICT, message)
     except (socket_error, ConnectionFailure):
         return connection_failure(identity)
     except LibcloudInvalidCredsError:
         return invalid_creds(identity)
     except Exception as exc:
         logger.exception("Encountered a generic exception. "
                          "Returning 409-CONFLICT")
         return failure_response(status.HTTP_409_CONFLICT, str(exc.message))
    def create(self, request):
        request_user = request.user
        request_data = request.data

        if not request_data.items():
            return failure_response(status.HTTP_400_BAD_REQUEST,
                                    "Reuquest Data is missing")

        if not request_data['action']:
            return failure_response(status.HTTP_400_BAD_REQUEST,
                                    "Command name is missing")

        try:
            self._validate_user(request_data, request_user)
        except Exception as exc:
            return failure_response(status.HTTP_400_BAD_REQUEST, exc.message)

        action = str(request_data['action'])

        if action == 'create_allocation_source':
            return self.create_allocation_source(request_data, request_user)
        elif action == 'change_renewal_strategy':
            return self.change_renewal_strategy(request_data, request_user)
        elif action == 'change_allocation_source_name':
            return self.change_allocation_source_name(request_data,
                                                      request_user)
        elif action == 'change_compute_allowed':
            return self.change_allocation_source_compute_allowed(
                request_data, request_user)
        else:
            return failure_response(status.HTTP_400_BAD_REQUEST,
                                    "Incorrect command name")
    def create(self, request):
        user = request.user
        data = request.data
        try:
            self.validate_input(user, data)
        except Exception as exc:
            return failure_response(
                status.HTTP_400_BAD_REQUEST,
                exc.message)

        # Create a mutable dict and start modifying.
        data = data.copy()
        name = data.get('name')
        identity_uuid = data.get('identity')
        source_alias = data.get('source_alias')
        size_alias = data.get('size_alias')
        boot_scripts = data.pop("scripts", [])
        deploy = data.get('deploy')
        extra = data.get('extra')
        try:
            identity = Identity.objects.get(uuid=identity_uuid)
            core_instance = launch_instance(
                user, identity_uuid, size_alias, source_alias, name, deploy,
                **extra)
            # Faking a 'partial update of nothing' to allow call to 'is_valid'
            serialized_instance = InstanceSerializer(
                core_instance, context={'request': self.request},
                data={}, partial=True)
            if not serialized_instance.is_valid():
                return Response(serialized_instance.errors,
                                status=status.HTTP_400_BAD_REQUEST)
            instance = serialized_instance.save()
            if boot_scripts:
                _save_scripts_to_instance(instance, boot_scripts)
            return Response(
                serialized_instance.data, status=status.HTTP_201_CREATED)
        except UnderThresholdError as ute:
            return under_threshold(ute)
        except (OverQuotaError, OverAllocationError) as oqe:
            return over_quota(oqe)
        except ProviderNotActive as pna:
            return inactive_provider(pna)
        except SizeNotAvailable as snae:
            return size_not_available(snae)
        except HypervisorCapacityError as hce:
            return over_capacity(hce)
        except SecurityGroupNotCreated:
            return connection_failure(identity)
        except (socket_error, ConnectionFailure):
            return connection_failure(identity)
        except InvalidCredsError:
            return invalid_creds(identity)
        except Exception as exc:
            logger.exception("Encountered a generic exception. "
                             "Returning 409-CONFLICT")
            return failure_response(status.HTTP_409_CONFLICT,
                                    str(exc.message))
Exemple #15
0
 def list(self, request, *args, **kwargs):
     """
     Force an abnormal behavior when no query_params are passed
     """
     query_params = self.request.query_params
     if not query_params.items():
         return failure_response(status.HTTP_400_BAD_REQUEST,
                                 "The reporting API should be accessed via the query parameters:"
                                 " ['start_date', 'end_date', 'provider_id']")
     try:
         results = super(ReportingViewSet, self).list(request, *args, **kwargs)
     except ValueError:
         return failure_response(status.HTTP_400_BAD_REQUEST, 'Invalid filter parameters')
     return results
    def perform_destroy(self, allocation_source, request=None):

        if not hasattr(self, 'request'):
            self.request = request

        request_user = self.request.user
        request_data = {}
        request_data['allocation_source_name'] = allocation_source.name

        # validate user
        try:
            self._validate_user(request_user)
        except Exception as exc:
            return failure_response(
                status.HTTP_400_BAD_REQUEST,
                exc.message)

        # validate patched fields and update allocation source model
        try:
            self._validate_params(request_data)
            # create payload
            payload = {}
            payload['allocation_source_name'] = str(request_data['allocation_source_name'])
            payload['delete_date'] = str(timezone.now().strftime("%Y-%m-%dT%H:%M:%S+00:00"))

            EventTable.create_event(
                'allocation_source_removed',
                payload,
                payload['allocation_source_name'])

        except Exception as exc:
            return failure_response(
                status.HTTP_400_BAD_REQUEST,
                exc.message)

        try:
            allocation_source = allocation_source

            serialized_allocation_source = AllocationSourceSerializer(
                allocation_source, context={'request': self.request})
            return Response(
                serialized_allocation_source.data,
                status=status.HTTP_200_OK)

        except Exception as exc:
            logger.exception(
                "Encountered exception while removing Allocation Source")
            return failure_response(status.HTTP_409_CONFLICT,
                                    str(exc.message))
    def change_renewal_strategy(self, request_data, request_user):
        try:
            self._validate_for_change_renewal_strategy(request_user,
                                                       request_data)
        except Exception as exc:
            return failure_response(status.HTTP_400_BAD_REQUEST, exc.message)
        try:
            allocation_source = self._change_renewal_strategy(request_data)
            serialized_allocation_source = AllocationSourceSerializer(
                allocation_source, context={'request': self.request})
            return Response(serialized_allocation_source.data,
                            status=status.HTTP_201_CREATED)

        except Exception as exc:
            logger.exception(
                "Encountered exception while changing renewal strategy")
            return failure_response(status.HTTP_409_CONFLICT, str(exc.message))
    def change_allocation_source_compute_allowed(self, request_data, request_user):
        try:
            self._validate_for_change_allocation_source_compute_allowed(request_user, request_data)
        except Exception as exc:
            return failure_response(
                status.HTTP_400_BAD_REQUEST,
                exc.message)
        try:
            allocation_source = self._change_allocation_source_compute_allowed(request_data)
            serialized_allocation_source = AllocationSourceSerializer(
                allocation_source, context={'request': self.request})
            return Response(serialized_allocation_source.data, status=status.HTTP_201_CREATED)

        except Exception as exc:
            logger.exception("Encountered exception while changing renewal strategy")
            return failure_response(status.HTTP_409_CONFLICT,
                                    str(exc.message))
Exemple #19
0
 def list(self, request, *args, **kwargs):
     """
     Force an abnormal behavior when no query_params are passed
     """
     query_params = self.request.query_params
     if not query_params.items():
         return failure_response(
             status.HTTP_400_BAD_REQUEST,
             "The reporting API should be accessed via the query parameters:"
             " ['start_date', 'end_date', 'provider_id']")
     try:
         results = super(ReportingViewSet,
                         self).list(request, *args, **kwargs)
     except ValueError:
         return failure_response(status.HTTP_400_BAD_REQUEST,
                                 'Invalid filter parameters')
     return results
 def retrieve(self, *args, **kwargs):
     instance = self.get_object()
     params = self.request.query_params
     try:
         instance_metrics = get_instance_metrics(instance, params)
     except Exception as exc:
         logger.exception("Failed to retrieve instance metrics")
         return failure_response(status.HTTP_409_CONFLICT, str(exc.message))
     return Response(instance_metrics)
Exemple #21
0
 def retrieve(self, *args, **kwargs):
     instance = self.get_object()
     params = self.request.query_params
     try:
         instance_metrics = get_instance_metrics(instance, params)
     except Exception as exc:
         logger.exception("Failed to retrieve instance metrics")
         return failure_response(status.HTTP_409_CONFLICT, str(exc.message))
     return Response(instance_metrics)
    def create(self, request):
        """
        Create allocation source and fire respective events
        """

        if not hasattr(self, 'request'):
            self.request = request

        request_user = request.user
        request_data = request.data

        if not request_data.items():
            return failure_response(status.HTTP_400_BAD_REQUEST,
                                    "Request Data is missing")

        try:
            self._validate_user(request_user)
        except Exception as exc:
            return failure_response(
                status.HTTP_400_BAD_REQUEST,
                exc.message)

        try:
            self._validate_params(request_data)
        except Exception as exc:
            return failure_response(
                status.HTTP_400_BAD_REQUEST,
                exc.message)

        try:
            allocation_source = self._create_allocation_source(request_data)
            # CHANGE SERIALIZER CLASS

            serialized_allocation_source = AllocationSourceSerializer(
                allocation_source, context={'request': self.request})
            return Response(
                serialized_allocation_source.data,
                status=status.HTTP_201_CREATED)

        except Exception as exc:
            logger.exception(
                "Encountered exception while creating Allocation Source")
            return failure_response(status.HTTP_409_CONFLICT,
                                    str(exc.message))
    def destroy(self, request, pk=None):
        user = self.request.user
        try:
            instance = Instance.objects.get(
                Q(id=pk) if isinstance(pk, int) else Q(provider_alias=pk)
            )
            identity_uuid = str(instance.created_by_identity.uuid)
            identity = Identity.objects.get(uuid=identity_uuid)
            provider_uuid = str(identity.provider.uuid)
            destroy_instance.delay(instance.provider_alias, user, identity_uuid)

            # We must invalidate the cache while we still depend on api.v1.instance
            invalidate_cached_instances(identity=identity)
            serializer = InstanceSerializer(
                instance,
                context={'request': self.request},
                data={},
                partial=True
            )
            if not serializer.is_valid():
                return Response(
                    "Errors encountered during delete: %s" % serializer.errors,
                    status=status.HTTP_400_BAD_REQUEST
                )
            return Response(status=status.HTTP_204_NO_CONTENT)
        except VolumeAttachConflict as exc:
            message = exc.message
            return failure_response(status.HTTP_409_CONFLICT, message)
        except (socket_error, ConnectionFailure):
            return connection_failure(provider_uuid, identity_uuid)
        except LibcloudInvalidCredsError:
            return invalid_creds(provider_uuid, identity_uuid)
        except InstanceDoesNotExist as dne:
            return failure_response(
                status.HTTP_404_NOT_FOUND,
                'Instance %s no longer exists' % (dne.message, )
            )
        except Exception as exc:
            logger.exception(
                "Encountered a generic exception. "
                "Returning 409-CONFLICT"
            )
            return failure_response(status.HTTP_409_CONFLICT, str(exc.message))
    def perform_destroy(self, allocation_source, request=None):

        if not hasattr(self, 'request'):
            self.request = request

        request_user = self.request.user
        request_data = {}
        request_data['allocation_source_name'] = allocation_source.name

        # validate user
        try:
            self._validate_user(request_user)
        except Exception as exc:
            return failure_response(status.HTTP_400_BAD_REQUEST, exc.message)

        # validate patched fields and update allocation source model
        try:
            self._validate_params(request_data)
            # create payload
            payload = {}
            payload['allocation_source_name'] = str(
                request_data['allocation_source_name'])
            payload['delete_date'] = str(
                timezone.now().strftime("%Y-%m-%dT%H:%M:%S+00:00"))

            EventTable.create_event('allocation_source_removed', payload,
                                    payload['allocation_source_name'])

        except Exception as exc:
            return failure_response(status.HTTP_400_BAD_REQUEST, exc.message)

        try:
            allocation_source = allocation_source

            serialized_allocation_source = AllocationSourceSerializer(
                allocation_source, context={'request': self.request})
            return Response(serialized_allocation_source.data,
                            status=status.HTTP_200_OK)

        except Exception as exc:
            logger.exception(
                "Encountered exception while removing Allocation Source")
            return failure_response(status.HTTP_409_CONFLICT, str(exc.message))
Exemple #25
0
    def destroy(self, request, pk=None):
        user = self.request.user
        try:
            instance = Instance.objects.get(
                Q(id=pk) if isinstance(pk, int) else Q(provider_alias=pk)
            )
            identity_uuid = str(instance.created_by_identity.uuid)
            identity = Identity.objects.get(uuid=identity_uuid)
            provider_uuid = str(identity.provider.uuid)
            destroy_instance.delay(instance.provider_alias, user, identity_uuid)

            # We must invalidate the cache while we still depend on api.v1.instance
            invalidate_cached_instances(identity=identity)
            serializer = InstanceSerializer(
                instance,
                context={'request': self.request},
                data={},
                partial=True
            )
            if not serializer.is_valid():
                return Response(
                    "Errors encountered during delete: %s" % serializer.errors,
                    status=status.HTTP_400_BAD_REQUEST
                )
            return Response(status=status.HTTP_204_NO_CONTENT)
        except VolumeAttachConflict as exc:
            message = exc.message
            return failure_response(status.HTTP_409_CONFLICT, message)
        except (socket_error, ConnectionFailure):
            return connection_failure(provider_uuid, identity_uuid)
        except LibcloudInvalidCredsError:
            return invalid_creds(provider_uuid, identity_uuid)
        except InstanceDoesNotExist as dne:
            return failure_response(
                status.HTTP_404_NOT_FOUND,
                'Instance %s no longer exists' % (dne.message, )
            )
        except Exception as exc:
            logger.exception(
                "Encountered a generic exception. "
                "Returning 409-CONFLICT"
            )
            return failure_response(status.HTTP_409_CONFLICT, str(exc.message))
 def remove_user(self, request, pk=None):
     group = self.lookup_group(pk)
     data = request.data
     del_user = data.pop('username')
     user = AtmosphereUser.objects.filter(username=del_user)
     if not user.count():
         return failure_response(409, "Username %s does not exist" % del_user)
     user = user[0]
     group.user_set.remove(user)
     serialized_data = GroupSerializer(group, context={'request': request}).data
     return Response(serialized_data)
Exemple #27
0
 def create(self, *args, **kwargs):
     user = self.request.user
     data = self.request.data
     missing_keys = self.check_missing_keys(data, self.required_keys)
     if missing_keys:
         return failure_response(
             status.HTTP_400_BAD_REQUEST,
             "Missing required POST data variables : %s" % missing_keys)
     # Inject SERVER_URL settings
     data['server'] = settings.SERVER_URL
     result = self._email(user, data)
     return result
Exemple #28
0
 def create(self, *args, **kwargs):
     user = self.request.user
     data = self.request.data
     missing_keys = self.check_missing_keys(data, self.required_keys)
     if missing_keys:
         return failure_response(
             status.HTTP_400_BAD_REQUEST,
             "Missing required POST data variables : %s" % missing_keys)
     # Inject SERVER_URL settings
     data['server'] = settings.SERVER_URL
     result = self._email(user, data)
     return result
Exemple #29
0
    def retrieve(self, request, pk=None):
        """
        Retrieve a signed token for a web desktop view.
        """
        if not request.user.is_authenticated():
            raise PermissionDenied

        client = request.query_params.get('client')
        valid_guac = client == "guacamole" and settings.GUACAMOLE_ENABLED
        valid_webdesktop = client == "web_desktop"
        if not (valid_guac or valid_webdesktop):
            return failure_response(
                status.HTTP_400_BAD_REQUEST,
                'Invalid or missing "client" query paramater')

        instance = self.get_queryset().filter(provider_alias=pk).first()
        if not instance:
            return failure_response(
                status.HTTP_404_NOT_FOUND,
                'Instance %s not found / no longer exists' % pk)

        token = None
        token_url = None
        try:
            if client == 'guacamole':
                token, token_url = self.guacamole_token(instance.ip_address)
            else:
                token, token_url = self.web_desktop_token(instance.ip_address)
        except:
            logger.exception("Atmosphere failed to retrieve web token")
            return HttpResponse(
                "Atmosphere failed to retrieve web token",
                status=500)

        return Response({
            'token': token,
            'token_url': token_url
        })
    def create(self, request):
        """
        Create allocation source and fire respective events
        """

        if not hasattr(self, 'request'):
            self.request = request

        request_user = request.user
        request_data = request.data

        if not request_data.items():
            return failure_response(status.HTTP_400_BAD_REQUEST,
                                    "Request Data is missing")

        try:
            self._validate_user(request_user)
        except Exception as exc:
            return failure_response(status.HTTP_400_BAD_REQUEST, exc.message)

        try:
            self._validate_params(request_data)
        except Exception as exc:
            return failure_response(status.HTTP_400_BAD_REQUEST, exc.message)

        try:
            allocation_source = self._create_allocation_source(request_data)
            # CHANGE SERIALIZER CLASS

            serialized_allocation_source = AllocationSourceSerializer(
                allocation_source, context={'request': self.request})
            return Response(serialized_allocation_source.data,
                            status=status.HTTP_201_CREATED)

        except Exception as exc:
            logger.exception(
                "Encountered exception while creating Allocation Source")
            return failure_response(status.HTTP_409_CONFLICT, str(exc.message))
Exemple #31
0
 def remove_user(self, request, pk=None):
     group = self.lookup_group(pk)
     data = request.data
     del_user = data.pop('username')
     user = AtmosphereUser.objects.filter(username=del_user)
     if not user.count():
         return failure_response(409,
                                 "Username %s does not exist" % del_user)
     user = user[0]
     group.user_set.remove(user)
     serialized_data = GroupSerializer(group, context={
         'request': request
     }).data
     return Response(serialized_data)
    def delete(self, request):
        request_user = request.user
        request_data = request.data
        if not request_data.items():
            return failure_response(
                status.HTTP_400_BAD_REQUEST, "Reuquest Data is missing"
            )

        try:
            self._validate_data(request_user, request_data, delete=True)
        except Exception as exc:
            return failure_response(status.HTTP_400_BAD_REQUEST, exc.message)

        try:
            self._delete_user_allocation_source(request_data)
            return Response(status=status.HTTP_200_OK)

        except Exception as exc:
            logger.exception(
                'Encountered exception while removing User %s from Allocation source %s',
                request_data['username'], request_data['allocation_source_name']
            )
            return failure_response(status.HTTP_409_CONFLICT, str(exc.message))
    def update(self, request, pk, *args, **fields):

        if not hasattr(self, 'request'):
            self.request = request

        request_user = request.user
        request_data = request.data
        request_data['source_id'] = pk
        request_data['allocation_source_name'] = AllocationSource.objects.filter(uuid=pk).last().name

        # check for data
        if not request_data.items():
            return failure_response(status.HTTP_400_BAD_REQUEST,
                                    "Request Data is missing")

        # validate user
        try:
            self._validate_user(request_user)
        except Exception as exc:
            return failure_response(
                status.HTTP_400_BAD_REQUEST,
                exc.message)

        # validate patched fields and update allocation source model
        try:
            self._validate_params(request_data)

            # create payload
            payload = {}
            payload['allocation_source_name'] = request_data['allocation_source_name']

            # events to call
            events = []

            # if 'name' in request_data:
            #     payload_name = payload.copy()
            #     payload_name['name'] = request_data['name']
            #     events.append((
            #         'allocation_source_name_changed',
            #         payload_name))

            if 'renewal_strategy' in request_data:
                payload_renewal_strategy = payload.copy()
                payload_renewal_strategy['renewal_strategy'] = request_data['renewal_strategy']
                events.append((
                    'allocation_source_renewal_strategy_changed',
                    payload_renewal_strategy))

            if 'compute_allowed' in request_data:
                payload_compute_allowed = payload.copy()

                payload_compute_allowed['compute_allowed'] = request_data['compute_allowed']
                events.append((
                    'allocation_source_compute_allowed_changed',
                    payload_compute_allowed))

        except Exception as exc:
            return failure_response(
                status.HTTP_400_BAD_REQUEST,
                exc.message)
        try:
            allocation_source = self._update_allocation_source(
                events, request_data)
            serialized_allocation_source = AllocationSourceSerializer(
                allocation_source, context={'request': self.request})
            return Response(
                serialized_allocation_source.data,
                status=status.HTTP_200_OK)

        except Exception as exc:
            logger.exception(
                "Encountered exception while updating Allocation Source")
            return failure_response(status.HTTP_409_CONFLICT,
                                    str(exc.message))
    def update(self, request, pk, *args, **fields):

        if not hasattr(self, 'request'):
            self.request = request

        request_user = request.user
        request_data = request.data
        request_data['source_id'] = pk
        request_data[
            'allocation_source_name'] = AllocationSource.objects.filter(
                uuid=pk).last().name

        # check for data
        if not request_data.items():
            return failure_response(status.HTTP_400_BAD_REQUEST,
                                    "Request Data is missing")

        # validate user
        try:
            self._validate_user(request_user)
        except Exception as exc:
            return failure_response(status.HTTP_400_BAD_REQUEST, exc.message)

        # validate patched fields and update allocation source model
        try:
            self._validate_params(request_data)

            # create payload
            payload = {}
            payload['allocation_source_name'] = request_data[
                'allocation_source_name']

            # events to call
            events = []

            # if 'name' in request_data:
            #     payload_name = payload.copy()
            #     payload_name['name'] = request_data['name']
            #     events.append((
            #         'allocation_source_name_changed',
            #         payload_name))

            if 'renewal_strategy' in request_data:
                payload_renewal_strategy = payload.copy()
                payload_renewal_strategy['renewal_strategy'] = request_data[
                    'renewal_strategy']
                events.append(('allocation_source_renewal_strategy_changed',
                               payload_renewal_strategy))

            if 'compute_allowed' in request_data:
                payload_compute_allowed = payload.copy()

                payload_compute_allowed['compute_allowed'] = request_data[
                    'compute_allowed']
                events.append(('allocation_source_compute_allowed_changed',
                               payload_compute_allowed))

        except Exception as exc:
            return failure_response(status.HTTP_400_BAD_REQUEST, exc.message)
        try:
            allocation_source = self._update_allocation_source(
                events, request_data)
            serialized_allocation_source = AllocationSourceSerializer(
                allocation_source, context={'request': self.request})
            return Response(serialized_allocation_source.data,
                            status=status.HTTP_200_OK)

        except Exception as exc:
            logger.exception(
                "Encountered exception while updating Allocation Source")
            return failure_response(status.HTTP_409_CONFLICT, str(exc.message))