def delete(self, request, provider_uuid, identity_uuid, volume_id):
     """
     Destroys the volume and updates the DB
     """
     user = request.user
     # Ensure volume exists
     esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
     if not esh_driver:
         return invalid_creds(provider_uuid, identity_uuid)
     try:
         esh_volume = esh_driver.get_volume(volume_id)
     except ConnectionFailure:
         return connection_failure(provider_uuid, identity_uuid)
     except InvalidCredsError:
         return invalid_creds(provider_uuid, identity_uuid)
     except Exception as exc:
         logger.exception("Encountered a generic exception. "
                          "Returning 409-CONFLICT")
         return failure_response(status.HTTP_409_CONFLICT,
                                 str(exc.message))
     if not esh_volume:
         return volume_not_found(volume_id)
     core_volume = convert_esh_volume(esh_volume, provider_uuid,
                                      identity_uuid, user)
     # Delete the object, update the DB
     esh_driver.destroy_volume(esh_volume)
     core_volume.end_date = now()
     core_volume.save()
     # Return the object
     serialized_data = VolumeSerializer(core_volume,
                                        context={'request': request}).data
     response = Response(serialized_data)
     return response
    def get(self, request, provider_uuid, identity_uuid):
        """
        """
        esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
        if not esh_driver:
            return invalid_creds(provider_uuid, identity_uuid)
        try:
            esh_snapshots = esh_driver._connection.ex_list_snapshots()
        except MalformedResponseError:
            return malformed_response(provider_uuid, identity_uuid)
        except InvalidCredsError:
            return invalid_creds(provider_uuid, identity_uuid)
        snapshot_data = []
        for ss in esh_snapshots:
            snapshot_data.append({
                'id': ss.id,
                'name': ss.extra['name'],
                'size': ss.size,
                'description': ss.extra['description'],
                'created': ss.extra['created'],
                'status': ss.extra['status'],
                'volume_id': ss.extra['volume_id'], })

        response = Response(snapshot_data)
        return response
Exemplo n.º 3
0
def destroy_volume_or_fail(volume, user, cascade=False):
    """
    Destroy the volume specified

    :param cascade: Cascades through and destroy volume snapshots
                    (defaults is False)
    :type cascade: ``bool``
    """
    provider = volume.instance_source.provider
    identity = volume.instance_source.created_by_identity
    # FIXME: fix prepare_driver to take a user directly
    request = Request(user)
    driver = prepare_driver(request, provider.uuid, identity.uuid,
                            raise_exception=True)

    # retrieve volume or fail with not found
    esh_volume = driver.get_volume(volume.identifier)

    if esh_volume is None:
        raise exceptions.NotFound(
            "The `%s` could not be found."
            % volume.identifier)

    # if cascade True and snapshots exist delete all snapshots
    if cascade:
        snapshots = esh_volume.list_snapshots()
        for snapshot in snapshots:
            driver.destroy_snapshot(snapshot)

    # destroy the volume successfully or raise an exception
    if not driver.destroy_volume(esh_volume):
        raise Exception("Encountered an error destroying the volume.")
Exemplo n.º 4
0
    def get(self, request, provider_uuid, identity_uuid, size_alias):
        """
        Lookup the size information (Lookup using the given provider/identity)
        Update on server DB (If applicable)
        """
        user = request.user
        try:
            esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
        except ProviderNotActive as pna:
            return inactive_provider(pna)
        except Exception as e:
            return failure_response(
                status.HTTP_409_CONFLICT,
                e.message)

        if not esh_driver:
            return invalid_creds(provider_uuid, identity_uuid)
        esh_size = esh_driver.get_size(size_alias)
        if not esh_size:
            return failure_response(
                status.HTTP_404_NOT_FOUND,
                'Size %s not found' % (size_alias,))
        core_size = convert_esh_size(esh_size, provider_uuid)
        serialized_data = ProviderSizeSerializer(core_size).data
        response = Response(serialized_data)
        return response
Exemplo n.º 5
0
    def get(self, request, provider_uuid, identity_uuid):
        """
        """
        try:
            esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
        except ProviderNotActive as pna:
            return inactive_provider(pna)
        except Exception as e:
            return failure_response(
                status.HTTP_409_CONFLICT,
                e.message)
        if not esh_driver:
            return invalid_creds(provider_uuid, identity_uuid)
        try:
            esh_snapshots = esh_driver._connection.ex_list_snapshots()
        except LibcloudBadResponseError:
            return malformed_response(provider_uuid, identity_uuid)
        except LibcloudInvalidCredsError:
            return invalid_creds(provider_uuid, identity_uuid)
        snapshot_data = []
        for ss in esh_snapshots:
            snapshot_data.append({
                'id': ss.id,
                'name': ss.extra['name'],
                'size': ss.size,
                'description': ss.extra['description'],
                'created': ss.extra['created'],
                'status': ss.extra['status'],
                'volume_id': ss.extra['volume_id'], })

        response = Response(snapshot_data)
        return response
Exemplo n.º 6
0
    def get(self, request, provider_uuid, identity_uuid, instance_id):
        """
        Authentication Required, get instance details.
        """
        user = request.user
        # NOTE: This 'Scheme' should be used across
        #       the ENTIRE API v1 (Machines, Volumes, Sizes)
        # NOTE: Especially the part below, where you end date
        #       all the things that are 'inactive'
        try:
            provider = Provider.objects.get(uuid=provider_uuid)
            if not provider.is_current():
                raise ProviderNotActive(provider)
        except Provider.DoesNotExist:
            return invalid_creds(provider_uuid, identity_uuid)
        except ProviderNotActive as pna:
            return inactive_provider(pna)

        # Cleared provider testing -- ready for driver prep.
        try:
            esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
            if not esh_driver:
                return invalid_creds(provider_uuid, identity_uuid)
            logger.info("InstanceQuery Looking for %s" % instance_id)
            esh_instance = esh_driver.get_instance(instance_id)
            logger.info("InstanceQuery Found instance %s" % esh_instance)
        except (socket_error, ConnectionFailure):
            logger.exception("Connection failure prevented InstanceQuery")
            return connection_failure(provider_uuid, identity_uuid)
        except LibcloudInvalidCredsError:
            logger.exception("Invalid credentialsprevented InstanceQuery")
            return invalid_creds(provider_uuid, identity_uuid)
        except Exception as exc:
            logger.exception("Encountered a generic exception. "
                             "Returning 409-CONFLICT")
            return failure_response(status.HTTP_409_CONFLICT,
                                    str(exc.message))

        # NOTE: Especially THIS part below, where you end date all the
        #       things that are 'inactive'
        if not esh_instance:
            try:
                core_inst = CoreInstance.objects.get(
                    provider_alias=instance_id,
                    source__provider__uuid=provider_uuid,
                    created_by_identity__uuid=identity_uuid)
                core_inst.end_date_all()
            except CoreInstance.DoesNotExist:
                pass
            return instance_not_found(instance_id)

        core_instance = convert_esh_instance(esh_driver, esh_instance,
                                             provider_uuid, identity_uuid,
                                             user)
        serialized_data = InstanceSerializer(
            core_instance,
            context={"request": request}).data
        response = Response(serialized_data)
        response['Cache-Control'] = 'no-cache'
        return response
Exemplo n.º 7
0
    def get(self, request, provider_uuid, identity_uuid):
        """
        Retrieves list of volumes and updates the DB
        """
        user = request.user
        esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
        if not esh_driver:
            return invalid_creds(provider_uuid, identity_uuid)
        volume_list_method = esh_driver.list_volumes

        if AccountProvider.objects.filter(identity__uuid=identity_uuid):
            # Instance list method changes when using the OPENSTACK provider
            volume_list_method = esh_driver.list_all_volumes
        try:
            esh_volume_list = volume_list_method()
        except MalformedResponseError:
            return malformed_response(provider_id, identity_id)
        except InvalidCredsError:
            return invalid_creds(provider_id, identity_id)

        core_volume_list = [convert_esh_volume(volume, provider_uuid,
                                               identity_uuid, user)
                            for volume in esh_volume_list]
        serializer = VolumeSerializer(core_volume_list,
                                      context={'request': request}, many=True)
        response = Response(serializer.data)
        return response
Exemplo n.º 8
0
def get_esh_instance(request, provider_uuid, identity_uuid, instance_id):
    esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
    if not esh_driver:
        raise InvalidCredsError(
            "Provider_uuid && identity_uuid "
            "did not produce a valid combination")
    esh_instance = None
    try:
        esh_instance = esh_driver.get_instance(instance_id)
    except (socket_error, ConnectionFailure):
        return connection_failure(provider_uuid, identity_uuid)
    except InvalidCredsError:
        return invalid_creds(provider_uuid, identity_uuid)
    except Exception as exc:
        logger.exception("Encountered a generic exception. "
                         "Returning 409-CONFLICT")
        return failure_response(status.HTTP_409_CONFLICT,
                                str(exc.message))

    if not esh_instance:
        # End date everything
        try:
            core_inst = CoreInstance.objects.get(
                provider_alias=instance_id,
                source__provider__uuid=provider_uuid,
                created_by_identity__uuid=identity_uuid)
            core_inst.end_date_all()
        except CoreInstance.DoesNotExist:
            pass
    return esh_instance
Exemplo n.º 9
0
    def get(self, request, provider_uuid, identity_uuid, machine_id):
        user = request.user
        try:
            esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
        except ProviderNotActive as pna:
            return inactive_provider(pna)
        except Exception as e:
            return failure_response(
                status.HTTP_409_CONFLICT,
                e.message)

        if not esh_driver:
            return invalid_creds(provider_uuid, identity_uuid)
        # TODO: Need to determine that identity_uuid is ALLOWED to
        # see machine_id.
        # if not covered by calling as the users driver..
        esh_machine = esh_driver.get_machine(machine_id)
        core_machine = convert_esh_machine(esh_driver, esh_machine,
                                           provider_uuid, user)
        if not core_machine:
            return failure_response(
                status.HTTP_400_BAD_REQUEST,
                "Could not retrieve machine with ID = %s" % machine_id)
        if not core_machine.application_version.application.icon:
            return None
        app_icon = core_machine.application_version.application.icon
        image_name, image_ext = os.path.splitext(app_icon.name)
        return Response(app_icon.file)
Exemplo n.º 10
0
    def get(self, request, provider_uuid, identity_uuid, machine_id):
        """
        Details view for specific machine
        (Lookup using the given provider/identity)
        """
        user = request.user
        try:
            esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
        except ProviderNotActive as pna:
            return inactive_provider(pna)
        except Exception as e:
            return failure_response(
                status.HTTP_409_CONFLICT,
                e.message)

        if not esh_driver:
            return invalid_creds(provider_uuid, identity_uuid)
        # TODO: Need to determine that identity_uuid is ALLOWED to
        # see machine_id. if not covered by calling as the users driver..
        esh_machine = esh_driver.get_machine(machine_id)
        core_machine = convert_esh_machine(esh_driver, esh_machine,
                                           provider_uuid, user)
        serialized_data = ProviderMachineSerializer(
            core_machine,
            request_user=request.user).data
        response = Response(serialized_data)
        return response
Exemplo n.º 11
0
def create_volume_or_fail(name, size, user, provider, identity,
                          image_id=None, snapshot_id=None):
    snapshot = None
    image = None
    # FIXME: fix prepare_driver to take a user directly
    request = Request(user)
    driver = prepare_driver(request, provider.uuid, identity.uuid,
                            raise_exception=True)

    if snapshot_id:
        snapshot = driver._connection.ex_get_snapshot(image_id)

    if image_id:
        image = driver.get_machine(image_id)
        restrict_size_by_image(size, image)

    #: Guard against both snapshot and image being present
    assert snapshot is None or image is None, (
        "A volume can only be constructed from a `snapshot` "
        "or an `image` not both.")

    #: Create the volume or raise an exception
    _, volume = create_volume(driver, identity.uuid, name, size,
                              snapshot=snapshot, image=image,
                              raise_exception=True)
    return volume
 def get(self, request, provider_uuid, identity_uuid, volume_id):
     """
     """
     user = request.user
     esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
     if not esh_driver:
         return invalid_creds(provider_uuid, identity_uuid)
     try:
         esh_volume = esh_driver.get_volume(volume_id)
     except ConnectionFailure:
         return connection_failure(provider_uuid, identity_uuid)
     except InvalidCredsError:
         return invalid_creds(provider_uuid, identity_uuid)
     except Exception as exc:
         logger.exception("Encountered a generic exception. "
                          "Returning 409-CONFLICT")
         return failure_response(status.HTTP_409_CONFLICT,
                                 str(exc.message))
     if not esh_volume:
         try:
             source = InstanceSource.objects.get(
                 identifier=volume_id,
                 provider__uuid=provider_uuid)
             source.end_date = datetime.now()
             source.save()
         except (InstanceSource.DoesNotExist, CoreVolume.DoesNotExist):
             pass
         return volume_not_found(volume_id)
     core_volume = convert_esh_volume(esh_volume, provider_uuid,
                                      identity_uuid, user)
     serialized_data = VolumeSerializer(core_volume,
                                        context={'request': request}).data
     response = Response(serialized_data)
     return response
Exemplo n.º 13
0
def get_core_instance(request, provider_uuid, identity_uuid, instance_id):
    user = request.user
    esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
    esh_instance = get_esh_instance(request, provider_uuid, identity_uuid, instance_id)
    core_instance = convert_esh_instance(esh_driver, esh_instance,
                                         provider_uuid, identity_uuid, user)
    return core_instance
Exemplo n.º 14
0
 def get(self, request, provider_uuid, identity_uuid):
     """
     Returns a list of all instances
     """
     user = request.user
     esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
     if not esh_driver:
         return invalid_creds(provider_uuid, identity_uuid)
     identity = Identity.objects.get(uuid=identity_uuid)
     try:
         esh_instance_list = get_cached_instances(identity=identity)
     except MalformedResponseError:
         return malformed_response(provider_uuid, identity_uuid)
     except (socket_error, ConnectionFailure):
         return connection_failure(provider_uuid, identity_uuid)
     except InvalidCredsError:
         return invalid_creds(provider_uuid, identity_uuid)
     core_instance_list = [convert_esh_instance(esh_driver,
                                                inst,
                                                provider_uuid,
                                                identity_uuid,
                                                user)
                           for inst in esh_instance_list]
     # TODO: Core/Auth checks for shared instances
     serialized_data = InstanceSerializer(core_instance_list,
                                          context={"request": request},
                                          many=True).data
     response = Response(serialized_data)
     response['Cache-Control'] = 'no-cache'
     return response
Exemplo n.º 15
0
 def get(self, request, provider_uuid, identity_uuid):
     """
     Using provider and identity, getlist of machines
     TODO: Cache this request
     """
     # TODO: Decide how we should pass this in (I.E. GET query string?)
     active = False
     user = request.user
     esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
     if not esh_driver:
         return invalid_creds(provider_uuid, identity_uuid)
     try:
         esh_size_list = esh_driver.list_sizes()
     except MalformedResponseError:
         return malformed_response(provider_uuid, identity_uuid)
     except InvalidCredsError:
         return invalid_creds(provider_uuid, identity_uuid)
     except (socket_error, ConnectionFailure):
         return connection_failure(provider_uuid, identity_uuid)
     all_size_list = [convert_esh_size(size, provider_uuid)
                      for size in esh_size_list]
     if active:
         all_size_list = [s for s in all_size_list if s.active()]
     serialized_data = ProviderSizeSerializer(all_size_list, many=True).data
     response = Response(serialized_data)
     return response
    def get(self, request, provider_uuid, identity_uuid):
        """
        Retrieves list of volumes and updates the DB
        """
        user = request.user
        esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
        if not esh_driver:
            return invalid_creds(provider_uuid, identity_uuid)
        volume_list_method = esh_driver.list_volumes

        if AccountProvider.objects.filter(identity__uuid=identity_uuid):
            # Instance list method changes when using the OPENSTACK provider
            volume_list_method = esh_driver.list_all_volumes
        try:
            esh_volume_list = volume_list_method()
        except (socket_error, ConnectionFailure):
            return connection_failure(provider_uuid, identity_uuid)
        except MalformedResponseError:
            return malformed_response(provider_uuid, identity_uuid)
        except InvalidCredsError:
            return invalid_creds(provider_uuid, identity_uuid)
        except Exception:
            logger.exception("Uncaught Exception in Volume list method")
            return failure_response(
                status.HTTP_500_INTERNAL_SERVER_ERROR,
                'Volume list method failed. Contact support')

        core_volume_list = [convert_esh_volume(volume, provider_uuid,
                                               identity_uuid, user)
                            for volume in esh_volume_list]
        serializer = VolumeSerializer(core_volume_list,
                                      context={'request': request}, many=True)
        response = Response(serializer.data)
        return response
Exemplo n.º 17
0
    def _update_machine(self, request, provider_uuid, identity_uuid, machine_id):
        # TODO: Determine who is allowed to edit machines besides
        # core_machine.owner
        user = request.user
        data = request.DATA
        esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
        if not esh_driver:
            return invalid_creds(provider_uuid, identity_uuid)
        esh_machine = esh_driver.get_machine(machine_id)
        core_machine = convert_esh_machine(esh_driver, esh_machine, provider_uuid, user)
        if not user.is_staff and user is not core_machine.application_version.application.created_by:
            logger.warn("%s is Non-staff/non-owner trying to update a machine" % (user.username))
            return failure_response(
                status.HTTP_401_UNAUTHORIZED, "Only Staff and the machine Owner " "are allowed to change machine info."
            )

        partial_update = True if request.method == "PATCH" else False
        serializer = ProviderMachineSerializer(
            core_machine, request_user=request.user, data=data, partial=partial_update
        )
        if serializer.is_valid():
            logger.info("metadata = %s" % data)
            update_machine_metadata(esh_driver, esh_machine, data)
            machine = serializer.save()
            if "created_by_identity" in request.DATA:
                identity = machine.created_by_identity
                update_application_owner(core_machine.application_version.application, identity)
            logger.info(serializer.data)
            return Response(serializer.data)
        return failure_response(status.HTTP_400_BAD_REQUEST, serializer.errors)
Exemplo n.º 18
0
 def delete(self, request, provider_uuid, identity_uuid, snapshot_id):
     """
     Destroys the volume and updates the DB
     """
     user = request.user
     # Ensure volume exists
     try:
         esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
     except ProviderNotActive as pna:
         return inactive_provider(pna)
     except Exception as e:
         return failure_response(
             status.HTTP_409_CONFLICT,
             e.message)
     if not esh_driver:
         return invalid_creds(provider_uuid, identity_uuid)
     if not can_use_snapshot(user, snapshot_id, leader_required=True):
         return member_action_forbidden(user.username, "Snapshot", snapshot_id)
     snapshot = esh_driver._connection.get_snapshot(snapshot_id)
     if not snapshot:
         return snapshot_not_found(snapshot_id)
     delete_success = esh_driver._connection.ex_delete_snapshot(snapshot)
     # NOTE: Always false until icehouse...
     #    return failure_response(
     #        status.HTTP_400_BAD_REQUEST,
     #        % snapshot_id)
     return Response(status=status.HTTP_204_NO_CONTENT)
Exemplo n.º 19
0
def provider_filtered_machines(request, provider_uuid,
                               identity_uuid, request_user=None):
    """
    Return all filtered machines. Uses the most common,
    default filtering method.
    """
    identity = Identity.objects.filter(uuid=identity_uuid)
    if not identity:
        raise ObjectDoesNotExist()

    try:
        esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
    except Exception:
        # TODO: Observe the change of 'Fail loudly' here
        # and clean up the noise, rather than hide it.
        logger.exception(
            "Driver could not be prepared - Provider: %s , Identity: %s"
            % (provider_uuid, identity_uuid))
        esh_driver = None

    if not esh_driver:
        raise LibcloudInvalidCredsError()

    logger.debug(esh_driver)

    return list_filtered_machines(esh_driver, provider_uuid, request_user)
Exemplo n.º 20
0
 def get(self, request, provider_uuid, identity_uuid, action=None):
     """
     """
     if not action:
         return failure_response(
             status.HTTP_400_BAD_REQUEST,
             'Action is not supported.'
         )
     try:
         esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
     except ProviderNotActive as pna:
         return inactive_provider(pna)
     except Exception as e:
         return failure_response(
             status.HTTP_409_CONFLICT,
             e.message)
     if not esh_driver:
         return invalid_creds(provider_uuid, identity_uuid)
     esh_meta = esh_driver.meta()
     try:
         if 'test_links' in action:
             test_links = esh_meta.test_links()
             return Response(test_links, status=status.HTTP_200_OK)
     except LibcloudInvalidCredsError:
         logger.warn('Authentication Failed. Provider-id:%s Identity-id:%s'
                     % (provider_uuid, identity_uuid))
         return failure_response(
             status.HTTP_401_UNAUTHORIZED,
             'Identity/Provider Authentication Failed')
     except NotImplemented as ne:
         logger.exception(ne)
         return failure_response(
             status.HTTP_404_NOT_FOUND,
             'The requested resource %s is not available on this provider'
             % action)
Exemplo n.º 21
0
def get_core_instance(request, provider_uuid, identity_uuid, instance_id):
    user = request.user
    esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
    esh_instance = get_esh_instance(request, provider_uuid, identity_uuid,
                                    instance_id)
    core_instance = convert_esh_instance(esh_driver, esh_instance,
                                         provider_uuid, identity_uuid, user)
    return core_instance
Exemplo n.º 22
0
 def get(self, request, provider_uuid, identity_uuid):
     user = request.user
     esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
     if not esh_driver:
         return invalid_creds(provider_uuid, identity_uuid)
     serialized_data = []
     response = Response(serialized_data)
     return response
Exemplo n.º 23
0
 def get(self, request, provider_uuid, identity_uuid):
     user = request.user
     esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
     if not esh_driver:
         return invalid_creds(provider_uuid, identity_uuid)
     serialized_data = []
     response = Response(serialized_data)
     return response
    def delete(self, request, provider_uuid, identity_uuid, instance_id):
        """Authentication Required, TERMINATE the instance.

        Be careful, there is no going back once you've deleted an instance.
        """
        user = request.user
        esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
        if not esh_driver:
            return invalid_creds(provider_uuid, identity_uuid)
        try:
            esh_instance = esh_driver.get_instance(instance_id)
        except (socket_error, ConnectionFailure):
            return connection_failure(provider_uuid, identity_uuid)
        except InvalidCredsError:
            return invalid_creds(provider_uuid, identity_uuid)
        except Exception as exc:
            logger.exception("Encountered a generic exception. " "Returning 409-CONFLICT")
            return failure_response(status.HTTP_409_CONFLICT, str(exc.message))
        try:
            # Test that there is not an attached volume BEFORE we destroy

            task.destroy_instance_task(user, esh_instance, identity_uuid)

            invalidate_cached_instances(identity=Identity.objects.get(uuid=identity_uuid))

            existing_instance = esh_driver.get_instance(instance_id)
            if existing_instance:
                # Instance will be deleted soon...
                esh_instance = existing_instance
                if esh_instance.extra and "task" not in esh_instance.extra:
                    esh_instance.extra["task"] = "queueing delete"
        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 InvalidCredsError:
            return invalid_creds(provider_uuid, identity_uuid)
        except Exception as exc:
            logger.exception("Encountered a generic exception. " "Returning 409-CONFLICT")
            return failure_response(status.HTTP_409_CONFLICT, str(exc.message))

        try:
            core_instance = convert_esh_instance(esh_driver, esh_instance, provider_uuid, identity_uuid, user)
            if core_instance:
                core_instance.end_date_all()
            else:
                logger.warn("Unable to find core instance %s." % (instance_id))
            serialized_data = InstanceSerializer(core_instance, context={"request": request}).data
            response = Response(serialized_data, status=status.HTTP_200_OK)
            response["Cache-Control"] = "no-cache"
            return response
        except (Identity.DoesNotExist) as exc:
            return failure_response(status.HTTP_400_BAD_REQUEST, "Invalid provider_uuid or identity_uuid.")
        except (socket_error, ConnectionFailure):
            return connection_failure(provider_uuid, identity_uuid)
        except InvalidCredsError:
            return invalid_creds(provider_uuid, identity_uuid)
Exemplo n.º 25
0
    def get(self, request, provider_uuid, identity_uuid, instance_id):
        """
        Authentication Required, get instance details.
        """
        user = request.user
        # NOTE: This 'Scheme' should be used across
        #       the ENTIRE API v1 (Machines, Volumes, Sizes)
        # NOTE: Especially the part below, where you end date
        #       all the things that are 'inactive'
        try:
            provider = Provider.objects.get(uuid=provider_uuid)
            if not provider.is_active():
                raise ProviderNotActive(provider)
        except Provider.DoesNotExist:
            return invalid_creds(provider_uuid, identity_uuid)
        except ProviderNotActive as pna:
            return inactive_provider(pna)

        # Cleared provider testing -- ready for driver prep.
        try:
            esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
            logger.info("InstanceQuery Looking for %s" % instance_id)
            esh_instance = esh_driver.get_instance(instance_id)
            logger.info("InstanceQuery Found instance %s" % esh_instance)
        except (socket_error, ConnectionFailure):
            logger.exception("Connection failure prevented InstanceQuery")
            return connection_failure(provider_uuid, identity_uuid)
        except LibcloudInvalidCredsError:
            logger.exception("Invalid credentialsprevented InstanceQuery")
            return invalid_creds(provider_uuid, identity_uuid)
        except Exception as exc:
            logger.exception("Encountered a generic exception. "
                             "Returning 409-CONFLICT")
            return failure_response(status.HTTP_409_CONFLICT, str(exc.message))

        # NOTE: Especially THIS part below, where you end date all the
        #       things that are 'inactive'
        if not esh_instance:
            try:
                core_inst = CoreInstance.objects.get(
                    provider_alias=instance_id,
                    source__provider__uuid=provider_uuid,
                    created_by_identity__uuid=identity_uuid)
                core_inst.end_date_all()
            except CoreInstance.DoesNotExist:
                pass
            return instance_not_found(instance_id)

        core_instance = convert_esh_instance(esh_driver, esh_instance,
                                             provider_uuid, identity_uuid,
                                             user)
        serialized_data = InstanceSerializer(core_instance,
                                             context={
                                                 "request": request
                                             }).data
        response = Response(serialized_data)
        response['Cache-Control'] = 'no-cache'
        return response
 def post(self, request, provider_uuid, identity_uuid):
     """
     Creates a new volume and adds it to the DB
     """
     user = request.user
     driver = prepare_driver(request, provider_uuid, identity_uuid)
     if not driver:
         return invalid_creds(provider_uuid, identity_uuid)
     data = request.data
     missing_keys = valid_volume_post_data(data)
     if missing_keys:
         return keys_not_found(missing_keys)
     # Pass arguments
     name = data.get('name')
     size = data.get('size')
     # Optional fields
     description = data.get('description')
     image_id = data.get('image')
     if image_id:
         image = driver.get_machine(image_id)
         image_size = image._connection.get_size(image._image)
         if int(size) > image_size + 4:
             return failure_response(
                 status.HTTP_400_BAD_REQUEST,
                 "Volumes created from images cannot exceed "
                 "more than 4GB greater than the size of "
                 "the image: %s GB" % image_size)
     else:
         image = None
     snapshot_id = data.get('snapshot')
     if snapshot_id:
         snapshot = driver._connection.ex_get_snapshot(image_id)
     else:
         snapshot = None
     try:
         success, esh_volume = create_volume(driver, identity_uuid,
                                             name, size, description,
                                             snapshot=snapshot, image=image)
     except OverQuotaError as oqe:
         return over_quota(oqe)
     except ConnectionFailure:
         return connection_failure(provider_uuid, identity_uuid)
     except MalformedResponseError:
         return malformed_response(provider_uuid, identity_uuid)
     except InvalidCredsError:
         return invalid_creds(provider_uuid, identity_uuid)
     if not success:
         return failure_response(
             status.HTTP_500_INTERNAL_SERVER_ERROR,
             'Volume creation failed. Contact support')
     # Volume creation succeeded
     core_volume = convert_esh_volume(esh_volume, provider_uuid,
                                      identity_uuid, user)
     serialized_data = VolumeSerializer(core_volume,
                                        context={'request': request}).data
     return Response(serialized_data, status=status.HTTP_201_CREATED)
Exemplo n.º 27
0
 def put(self, request, provider_uuid, identity_uuid, instance_id):
     """Authentication Required, update metadata about the instance"""
     user = request.user
     data = request.data
     # Ensure item exists on the server first
     esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
     if not esh_driver:
         return invalid_creds(provider_uuid, identity_uuid)
     if not can_use_instance(user, instance_id, leader_required=True):
         return member_action_forbidden(user.username, instance_id)
     try:
         esh_instance = esh_driver.get_instance(instance_id)
     except (socket_error, ConnectionFailure):
         return connection_failure(provider_uuid, identity_uuid)
     except LibcloudInvalidCredsError:
         return invalid_creds(provider_uuid, identity_uuid)
     except Exception as exc:
         logger.exception("Encountered a generic exception. "
                          "Returning 409-CONFLICT")
         return failure_response(status.HTTP_409_CONFLICT, str(exc.message))
     if not esh_instance:
         return instance_not_found(instance_id)
     # Gather the DB related item and update
     core_instance = convert_esh_instance(esh_driver, esh_instance,
                                          provider_uuid, identity_uuid,
                                          user)
     serializer = InstanceSerializer(core_instance,
                                     data=data,
                                     context={"request": request})
     identity = Identity.objects.get(uuid=identity_uuid)
     if serializer.is_valid():
         logger.info('metadata = %s' % data)
         #NOTE: We shouldn't allow 'full replacement' of metadata..
         # We should also validate against potentional updating of 'atmo-used metadata'
         update_metadata.s(esh_driver.__class__,
                           esh_driver.provider,
                           esh_driver.identity,
                           esh_instance.id,
                           data,
                           replace_metadata=False).apply()
         new_instance = serializer.save()
         boot_scripts = data.pop('boot_scripts', [])
         if boot_scripts:
             new_instance = _save_scripts_to_instance(
                 new_instance, boot_scripts)
             serializer = InstanceSerializer(new_instance,
                                             context={"request": request})
         invalidate_cached_instances(identity=identity)
         response = Response(serializer.data)
         logger.info('data = %s' % serializer.data)
         response['Cache-Control'] = 'no-cache'
         return response
     else:
         return Response(serializer.errors,
                         status=status.HTTP_400_BAD_REQUEST)
 def get(self, request, provider_uuid, identity_uuid, snapshot_id):
     """
     """
     esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
     if not esh_driver:
         return invalid_creds(provider_uuid, identity_uuid)
     snapshot = esh_driver._connection.get_snapshot(snapshot_id)
     if not snapshot:
         return snapshot_not_found(snapshot_id)
     response = Response(snapshot)
     return response
Exemplo n.º 29
0
 def get(self, request, provider_uuid, identity_uuid):
     """
     Returns all available URLs based on the user profile.
     """
     esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
     if not esh_driver:
         return invalid_creds(provider_uuid, identity_uuid)
     data = add_user_urls(request, provider_uuid, identity_uuid)
     if request.user.is_staff:
         add_staff_urls(request, provider_uuid, identity_uuid)
     return Response(data)
Exemplo n.º 30
0
 def get(self, request, provider_uuid, identity_uuid, snapshot_id):
     """
     """
     esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
     if not esh_driver:
         return invalid_creds(provider_uuid, identity_uuid)
     snapshot = esh_driver._connection.get_snapshot(snapshot_id)
     if not snapshot:
         return snapshot_not_found(snapshot_id)
     response = Response(snapshot)
     return response
Exemplo n.º 31
0
 def get(self, request, provider_uuid, identity_uuid):
     """
     Returns all available URLs based on the user profile.
     """
     esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
     if not esh_driver:
         return invalid_creds(provider_uuid, identity_uuid)
     data = add_user_urls(request, provider_uuid, identity_uuid)
     if request.user.is_staff:
         add_staff_urls(request, provider_uuid, identity_uuid)
     return Response(data)
Exemplo n.º 32
0
 def put(self, request, provider_uuid, identity_uuid, instance_id):
     """Authentication Required, update metadata about the instance"""
     user = request.user
     data = request.data
     # Ensure item exists on the server first
     esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
     if not esh_driver:
         return invalid_creds(provider_uuid, identity_uuid)
     if not can_use_instance(user, instance_id, leader_required=True):
         return member_action_forbidden(user.username, instance_id)
     try:
         esh_instance = esh_driver.get_instance(instance_id)
     except (socket_error, ConnectionFailure):
         return connection_failure(provider_uuid, identity_uuid)
     except LibcloudInvalidCredsError:
         return invalid_creds(provider_uuid, identity_uuid)
     except Exception as exc:
         logger.exception("Encountered a generic exception. "
                          "Returning 409-CONFLICT")
         return failure_response(status.HTTP_409_CONFLICT,
                                 str(exc.message))
     if not esh_instance:
         return instance_not_found(instance_id)
     # Gather the DB related item and update
     core_instance = convert_esh_instance(esh_driver, esh_instance,
                                          provider_uuid, identity_uuid,
                                          user)
     serializer = InstanceSerializer(core_instance, data=data,
                                     context={"request": request})
     identity = Identity.objects.get(uuid=identity_uuid)
     if serializer.is_valid():
         logger.info('metadata = %s' % data)
         #NOTE: We shouldn't allow 'full replacement' of metadata..
         # We should also validate against potentional updating of 'atmo-used metadata'
         update_metadata.s(esh_driver.__class__, esh_driver.provider, esh_driver.identity, esh_instance.id,
                           data, replace_metadata=False).apply()
         new_instance = serializer.save()
         boot_scripts = data.pop('boot_scripts', [])
         if boot_scripts:
             new_instance = _save_scripts_to_instance(new_instance,
                                                      boot_scripts)
             serializer = InstanceSerializer(
                 new_instance,
                 context={"request": request})
         invalidate_cached_instances(identity=identity)
         response = Response(serializer.data)
         logger.info('data = %s' % serializer.data)
         response['Cache-Control'] = 'no-cache'
         return response
     else:
         return Response(serializer.errors,
                         status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 33
0
    def patch(self, request, provider_uuid, identity_uuid, instance_id):
        """Authentication Required, update metadata about the instance"""
        user = request.user
        data = request.data
        esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
        if not esh_driver:
            return invalid_creds(provider_uuid, identity_uuid)
        try:
            esh_instance = esh_driver.get_instance(instance_id)
        except (socket_error, ConnectionFailure):
            return connection_failure(provider_uuid, identity_uuid)
        except LibcloudInvalidCredsError:
            return invalid_creds(provider_uuid, identity_uuid)
        except Exception as exc:
            logger.exception("Encountered a generic exception. "
                             "Returning 409-CONFLICT")
            return failure_response(status.HTTP_409_CONFLICT, str(exc.message))
        if not esh_instance:
            return instance_not_found(instance_id)
        # Gather the DB related item and update
        core_instance = convert_esh_instance(esh_driver, esh_instance,
                                             provider_uuid, identity_uuid,
                                             user)
        serializer = InstanceSerializer(core_instance,
                                        data=data,
                                        context={"request": request},
                                        partial=True)
        identity = Identity.objects.get(uuid=identity_uuid)
        provider = identity.provider

        if serializer.is_valid():
            logger.info('metadata = %s' % data)

            driver_class = esh_driver.__class__
            update_metadata.s(driver_class,
                              provider,
                              identity,
                              esh_instance.id,
                              data,
                              replace_metadata=False).apply()
            instance = serializer.save()
            boot_scripts = data.pop('boot_scripts', [])
            if boot_scripts:
                _save_scripts_to_instance(instance, boot_scripts)
            invalidate_cached_instances(identity=identity)
            response = Response(serializer.data)
            logger.info('data = %s' % serializer.data)
            response['Cache-Control'] = 'no-cache'
            return response
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 34
0
 def get(self, request, provider_uuid, identity_uuid, size_id):
     """
     Lookup the size information (Lookup using the given provider/identity)
     Update on server DB (If applicable)
     """
     user = request.user
     esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
     if not esh_driver:
         return invalid_creds(provider_uuid, identity_uuid)
     core_size = convert_esh_size(esh_driver.get_size(size_id), provider_uuid)
     serialized_data = ProviderSizeSerializer(core_size).data
     response = Response(serialized_data)
     return response
Exemplo n.º 35
0
 def get(self, request, provider_uuid, identity_uuid, size_id):
     """
     Lookup the size information (Lookup using the given provider/identity)
     Update on server DB (If applicable)
     """
     user = request.user
     esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
     if not esh_driver:
         return invalid_creds(provider_uuid, identity_uuid)
     core_size = convert_esh_size(esh_driver.get_size(size_id),
                                  provider_uuid)
     serialized_data = ProviderSizeSerializer(core_size).data
     response = Response(serialized_data)
     return response
Exemplo n.º 36
0
    def _update_machine(
        self, request, provider_uuid, identity_uuid, machine_id
    ):
        # TODO: Determine who is allowed to edit machines besides
        # core_machine.owner
        user = request.user
        data = request.data
        try:
            esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
        except ProviderNotActive as pna:
            return inactive_provider(pna)
        except Exception as e:
            return failure_response(status.HTTP_409_CONFLICT, e.message)

        if not esh_driver:
            return invalid_creds(provider_uuid, identity_uuid)
        esh_machine = esh_driver.get_machine(machine_id)
        core_machine = convert_esh_machine(
            esh_driver, esh_machine, provider_uuid, user
        )
        if not user.is_staff and user is not core_machine.application_version.application.created_by:
            logger.warn(
                '%s is Non-staff/non-owner trying to update a machine' %
                (user.username)
            )
            return failure_response(
                status.HTTP_401_UNAUTHORIZED,
                "Only Staff and the machine Owner "
                "are allowed to change machine info."
            )

        partial_update = True if request.method == 'PATCH' else False
        serializer = ProviderMachineSerializer(
            core_machine,
            request_user=request.user,
            data=data,
            partial=partial_update
        )
        if serializer.is_valid():
            logger.info('metadata = %s' % data)
            update_machine_metadata(esh_driver, esh_machine, data)
            machine = serializer.save()
            if 'created_by_identity' in request.data:
                identity = machine.created_by_identity
                update_application_owner(
                    core_machine.application_version.application, identity
                )
            logger.info(serializer.data)
            return Response(serializer.data)
        return failure_response(status.HTTP_400_BAD_REQUEST, serializer.errors)
Exemplo n.º 37
0
    def patch(self, request, provider_uuid, identity_uuid, instance_id):
        """Authentication Required, update metadata about the instance"""
        user = request.user
        data = request.data
        esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
        if not esh_driver:
            return invalid_creds(provider_uuid, identity_uuid)
        try:
            esh_instance = esh_driver.get_instance(instance_id)
        except (socket_error, ConnectionFailure):
            return connection_failure(provider_uuid, identity_uuid)
        except InvalidCredsError:
            return invalid_creds(provider_uuid, identity_uuid)
        except Exception as exc:
            logger.exception("Encountered a generic exception. "
                             "Returning 409-CONFLICT")
            return failure_response(status.HTTP_409_CONFLICT,
                                    str(exc.message))
        if not esh_instance:
            return instance_not_found(instance_id)
        # Gather the DB related item and update
        core_instance = convert_esh_instance(esh_driver, esh_instance,
                                             provider_uuid, identity_uuid,
                                             user)
        serializer = InstanceSerializer(
            core_instance, data=data,
            context={"request": request}, partial=True)
        identity = Identity.objects.get(uuid=identity_uuid)
        provider = identity.provider

        if serializer.is_valid():
            logger.info('metadata = %s' % data)

            driver_class = esh_driver.__class__
            update_metadata.s(driver_class, provider, identity, esh_instance.id,
                              data, replace_metadata=False).apply()
            instance = serializer.save()
            boot_scripts = data.pop('boot_scripts', [])
            if boot_scripts:
                _save_scripts_to_instance(instance, boot_scripts)
            invalidate_cached_instances(identity=identity)
            response = Response(serializer.data)
            logger.info('data = %s' % serializer.data)
            response['Cache-Control'] = 'no-cache'
            return response
        else:
            return Response(
                serializer.errors,
                status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 38
0
 def put(self, request, provider_uuid, identity_uuid, instance_id):
     """Authentication Required, update metadata about the instance"""
     user = request.user
     data = request.DATA
     # Ensure item exists on the server first
     esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
     if not esh_driver:
         return invalid_creds(provider_uuid, identity_uuid)
     try:
         esh_instance = esh_driver.get_instance(instance_id)
     except (socket_error, ConnectionFailure):
         return connection_failure(provider_uuid, identity_uuid)
     except InvalidCredsError:
         return invalid_creds(provider_uuid, identity_uuid)
     except Exception as exc:
         logger.exception("Encountered a generic exception. "
                          "Returning 409-CONFLICT")
         return failure_response(status.HTTP_409_CONFLICT,
                                 str(exc.message))
     if not esh_instance:
         return instance_not_found(instance_id)
     # Gather the DB related item and update
     core_instance = convert_esh_instance(esh_driver, esh_instance,
                                          provider_uuid, identity_uuid,
                                          user)
     serializer = InstanceSerializer(core_instance, data=data,
                                     context={"request": request})
     if serializer.is_valid():
         logger.info('metadata = %s' % data)
         update_instance_metadata(esh_driver, esh_instance, data)
         serializer.save()
         new_instance = serializer.object
         boot_scripts = data.pop('boot_scripts', [])
         if boot_scripts:
             new_instance = _save_scripts_to_instance(new_instance,
                                                      boot_scripts)
             serializer = InstanceSerializer(
                 new_instance,
                 context={"request": request})
         invalidate_cached_instances(
                 identity=Identity.objects.get(
                     uuid=identity_uuid))
         response = Response(serializer.data)
         logger.info('data = %s' % serializer.data)
         response['Cache-Control'] = 'no-cache'
         return response
     else:
         return Response(serializer.errors,
                         status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 39
0
 def put(self, request, provider_uuid, identity_uuid, instance_id):
     """Authentication Required, update metadata about the instance"""
     user = request.user
     data = request.DATA
     # Ensure item exists on the server first
     esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
     if not esh_driver:
         return invalid_creds(provider_uuid, identity_uuid)
     try:
         esh_instance = esh_driver.get_instance(instance_id)
     except ConnectionFailure:
         return connection_failure(provider_uuid, identity_uuid)
     except InvalidCredsError:
         return invalid_creds(provider_uuid, identity_uuid)
     except Exception as exc:
         logger.exception("Encountered a generic exception. "
                          "Returning 409-CONFLICT")
         return failure_response(status.HTTP_409_CONFLICT,
                                 str(exc.message))
     if not esh_instance:
         return instance_not_found(instance_id)
     # Gather the DB related item and update
     core_instance = convert_esh_instance(esh_driver, esh_instance,
                                          provider_uuid, identity_uuid,
                                          user)
     serializer = InstanceSerializer(core_instance, data=data,
                                     context={"request": request})
     if serializer.is_valid():
         logger.info('metadata = %s' % data)
         update_instance_metadata(esh_driver, esh_instance, data)
         serializer.save()
         new_instance = serializer.object
         boot_scripts = data.pop('boot_scripts', [])
         if boot_scripts:
             new_instance = _save_scripts_to_instance(new_instance,
                                                      boot_scripts)
             serializer = InstanceSerializer(
                 new_instance,
                 context={"request": request})
         invalidate_cached_instances(
                 identity=Identity.objects.get(
                     uuid=identity_uuid))
         response = Response(serializer.data)
         logger.info('data = %s' % serializer.data)
         response['Cache-Control'] = 'no-cache'
         return response
     else:
         return Response(serializer.errors,
                         status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 40
0
    def get(self, request, provider_uuid, identity_uuid):
        """
        Returns all available URLs based on the user profile.
        """
        try:
            esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
        except ProviderNotActive as pna:
            return inactive_provider(pna)
        except Exception as e:
            return failure_response(status.HTTP_409_CONFLICT, e.message)

        if not esh_driver:
            return invalid_creds(provider_uuid, identity_uuid)
        data = add_user_urls(request, provider_uuid, identity_uuid)
        return Response(data)
Exemplo n.º 41
0
    def put(self, request, provider_uuid, identity_uuid, volume_id):
        """
        Updates DB values for volume
        """
        user = request.user
        data = request.data

        # Ensure volume exists
        try:
            esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
        except ProviderNotActive as pna:
            return inactive_provider(pna)
        except Exception as e:
            return failure_response(
                status.HTTP_409_CONFLICT,
                e.message)

        if not esh_driver:
            return invalid_creds(provider_uuid, identity_uuid)
        if not can_use_volume(user, volume_id, leader_required=True):
            return member_action_forbidden(user.username, "Volume", volume_id)
        try:
            esh_volume = esh_driver.get_volume(volume_id)
        except ConnectionFailure:
            return connection_failure(provider_uuid, identity_uuid)
        except LibcloudInvalidCredsError:
            return invalid_creds(provider_uuid, identity_uuid)
        except Exception as exc:
            logger.exception("Encountered a generic exception. "
                             "Returning 409-CONFLICT")
            return failure_response(status.HTTP_409_CONFLICT,
                                    str(exc.message))
        if not esh_volume:
            return volume_not_found(volume_id)
        core_volume = convert_esh_volume(esh_volume, provider_uuid,
                                         identity_uuid, user)
        serializer = VolumeSerializer(core_volume, data=data,
                                      context={'request': request})
        if serializer.is_valid():
            serializer.save()
            _update_volume_metadata(
                esh_driver, esh_volume, data)
            response = Response(serializer.data)
            return response
        else:
            failure_response(
                status.HTTP_400_BAD_REQUEST,
                serializer.errors)
Exemplo n.º 42
0
 def get(self, request, provider_uuid, identity_uuid, snapshot_id):
     """
     """
     try:
         esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
     except ProviderNotActive as pna:
         return inactive_provider(pna)
     except Exception as e:
         return failure_response(status.HTTP_409_CONFLICT, e.message)
     if not esh_driver:
         return invalid_creds(provider_uuid, identity_uuid)
     snapshot = esh_driver._connection.get_snapshot(snapshot_id)
     if not snapshot:
         return snapshot_not_found(snapshot_id)
     response = Response(snapshot)
     return response
Exemplo n.º 43
0
    def get(self, request, provider_uuid, identity_uuid):
        data = request.DATA
        user = User.objects.filter(username=request.user)

        if user and len(user) > 0:
            user = user[0]
        else:
            return failure_response(status.HTTP_401_UNAUTHORIZED,
                                    "User not found.")
        esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
        if not esh_driver:
            return invalid_creds(provider_uuid, identity_uuid)
        # Historic Machines
        all_machines_list = all_filtered_machines()
        if all_machines_list:
            history_machine_list =\
                [m for m in all_machines_list if
                 m.application.created_by.username == user.username]
        else:
            history_machine_list = []

        page = request.QUERY_PARAMS.get('page')
        if page or len(history_machine_list) == 0:
            paginator = Paginator(history_machine_list,
                                  5,
                                  allow_empty_first_page=True)
        else:
            paginator = Paginator(history_machine_list,
                                  len(histor_machine_list),
                                  allow_empty_first_page=True)
        try:
            history_machine_page = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            history_machine_page = paginator.page(1)
        except EmptyPage:
            # Page is out of range.
            # deliver last page of results.
            history_machine_page = paginator.page(paginator.num_pages)
        serialized_data = PaginatedProviderMachineSerializer(
            history_machine_page, context={
                'request': request
            }).data
        response = Response(serialized_data)
        response['Cache-Control'] = 'no-cache'
        return response
Exemplo n.º 44
0
    def delete(self, request, provider_uuid, identity_uuid, instance_id):
        """Authentication Required, TERMINATE the instance.

        Be careful, there is no going back once you've deleted an instance.
        """
        user = request.user
        esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
        if not esh_driver:
            return invalid_creds(provider_uuid, identity_uuid)
        try:
            esh_instance = esh_driver.get_instance(instance_id)
            if not esh_instance:
                return instance_not_found(instance_id)
            #Test that there is not an attached volume BEFORE we destroy
            _check_volume_attachment(esh_driver, esh_instance)
            task.destroy_instance_task(esh_instance, identity_uuid)
            invalidate_cached_instances(identity=Identity.objects.get(uuid=identity_uuid))
            existing_instance = esh_driver.get_instance(instance_id)
            if existing_instance:
                #Instance will be deleted soon...
                esh_instance = existing_instance
                if esh_instance.extra\
                   and 'task' not in esh_instance.extra:
                    esh_instance.extra['task'] = 'queueing delete'
            core_instance = convert_esh_instance(esh_driver, esh_instance,
                                                 provider_uuid, identity_uuid,
                                                 user)
            if core_instance:
                core_instance.end_date_all()
            else:
                logger.warn("Unable to find core instance %s." % (instance_id))
            serialized_data = InstanceSerializer(core_instance,
                                                 context={"request":request}).data
            response = Response(serialized_data, status=status.HTTP_200_OK)
            response['Cache-Control'] = 'no-cache'
            return response
        except (Identity.DoesNotExist) as exc:
            return failure_response(status.HTTP_400_BAD_REQUEST,
                                    "Invalid provider_uuid or identity_uuid.")
        except VolumeAttachConflict as exc:
            message = exc.message
            return failure_response(status.HTTP_409_CONFLICT, message)
        except ConnectionFailure:
            return connection_failure(provider_uuid, identity_uuid)
        except InvalidCredsError:
            return invalid_creds(provider_uuid, identity_uuid)
Exemplo n.º 45
0
def provider_filtered_machines(request,
                               provider_uuid,
                               identity_uuid,
                               request_user=None):
    """
    Return all filtered machines. Uses the most common,
    default filtering method.
    """
    try:
        logger.debug(request)
        logger.debug("Rahr 0.")
        esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
    except:
        logger.debug("Rahr.")
    logger.debug(esh_driver)
    if not esh_driver:
        return invalid_creds(provider_uuid, identity_uuid)
    return list_filtered_machines(esh_driver, provider_uuid, request_user)
Exemplo n.º 46
0
def get_esh_instance(request, provider_uuid, identity_uuid, instance_id):
    esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
    if not esh_driver:
        raise InvalidCredsError(
                "Provider_uuid && identity_uuid "
                "did not produce a valid combination")
    esh_instance = esh_driver.get_instance(instance_id)
    if not esh_instance:
        try:
            core_inst = CoreInstance.objects.get(
                provider_alias=instance_id,
                source__provider__uuid=provider_uuid,
                created_by_identity__uuid=identity_uuid)
            core_inst.end_date_all()
        except CoreInstance.DoesNotExist:
            pass
        return esh_instance
    return esh_instance
Exemplo n.º 47
0
 def get(self, request, provider_uuid, identity_uuid, machine_id):
     """
     Details view for specific machine
     (Lookup using the given provider/identity)
     """
     user = request.user
     esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
     if not esh_driver:
         return invalid_creds(provider_uuid, identity_uuid)
     #TODO: Need to determine that identity_uuid is ALLOWED to see machine_id.
     #     if not covered by calling as the users driver..
     esh_machine = esh_driver.get_machine(machine_id)
     core_machine = convert_esh_machine(esh_driver, esh_machine,
                                        provider_uuid, user)
     serialized_data = ProviderMachineSerializer(
         core_machine, request_user=request.user).data
     response = Response(serialized_data)
     return response
Exemplo n.º 48
0
 def post(self, request, provider_uuid, identity_uuid):
     """
     Creates a new volume and adds it to the DB
     """
     user = request.user
     driver = prepare_driver(request, provider_uuid, identity_uuid)
     if not driver:
         return invalid_creds(provider_uuid, identity_uuid)
     data = request.DATA
     missing_keys = valid_volume_post_data(data)
     if missing_keys:
         return keys_not_found(missing_keys)
     #Pass arguments
     name = data.get('name')
     size = data.get('size')
     #Optional fields
     description = data.get('description')
     image_id = data.get('image')
     if image_id:
         image = driver.get_machine(image_id)
         image_size = image._connection.get_size(image._image)
         if int(size) > image_size + 4:
             return failure_response(
                 status.HTTP_400_BAD_REQUEST,
                 "Volumes created from images cannot exceed "
                 "more than 4GB greater than the size of "
                 "the image: %s GB" % image_size)
     else:
         image = None
     snapshot_id = data.get('snapshot')
     if snapshot_id:
         snapshot = driver._connection.ex_get_snapshot(image_id)
     else:
         snapshot = None
     try:
         success, esh_volume = create_volume(driver,
                                             identity_uuid,
                                             name,
                                             size,
                                             description,
                                             snapshot=snapshot,
                                             image=image)
     except OverQuotaError, oqe:
         return over_quota(oqe)
Exemplo n.º 49
0
 def get(self, request, provider_uuid, identity_uuid, machine_id):
     user = request.user
     esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
     if not esh_driver:
         return invalid_creds(provider_uuid, identity_uuid)
     #TODO: Need to determine that identity_uuid is ALLOWED to see machine_id.
     #     if not covered by calling as the users driver..
     esh_machine = esh_driver.get_machine(machine_id)
     core_machine = convert_esh_machine(esh_driver, esh_machine,
                                        provider_uuid, user)
     if not core_machine:
         return failure_response(
             status.HTTP_400_BAD_REQUEST,
             "Could not retrieve machine with ID = %s" % machine_id)
     if not core_machine.application.icon:
         return None
     app_icon = core_machine.application.icon
     image_name, image_ext = os.path.splitext(app_icon.name)
     return Response(app_icon.file)
Exemplo n.º 50
0
 def delete(self, request, provider_uuid, identity_uuid, snapshot_id):
     """
     Destroys the volume and updates the DB
     """
     #Ensure volume exists
     esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
     if not esh_driver:
         return invalid_creds(provider_uuid, identity_uuid)
     snapshot = esh_driver._connection.get_snapshot(snapshot_id)
     if not snapshot:
         return snapshot_not_found(snapshot_id)
     delete_success = esh_driver._connection.ex_delete_snapshot(snapshot)
     #NOTE: Always false until icehouse...
     #if not delete_success:
     #    return failure_response(
     #        status.HTTP_400_BAD_REQUEST,
     #        "Failed to delete snapshot %s. Please try again later."
     #        % snapshot_id)
     return Response(status=status.HTTP_204_NO_CONTENT)
Exemplo n.º 51
0
    def get(self, request, provider_uuid, identity_uuid, volume_id):
        """
        """
        user = request.user
        try:
            esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
        except ProviderNotActive as pna:
            return inactive_provider(pna)
        except Exception as e:
            return failure_response(
                status.HTTP_409_CONFLICT,
                e.message)

        if not esh_driver:
            return invalid_creds(provider_uuid, identity_uuid)
        try:
            esh_volume = esh_driver.get_volume(volume_id)
        except ConnectionFailure:
            return connection_failure(provider_uuid, identity_uuid)
        except LibcloudInvalidCredsError:
            return invalid_creds(provider_uuid, identity_uuid)
        except Exception as exc:
            logger.exception("Encountered a generic exception. "
                             "Returning 409-CONFLICT")
            return failure_response(status.HTTP_409_CONFLICT,
                                    str(exc.message))
        if not esh_volume:
            try:
                source = InstanceSource.objects.get(
                    identifier=volume_id,
                    provider__uuid=provider_uuid)
                source.end_date = datetime.now()
                source.save()
            except (InstanceSource.DoesNotExist, CoreVolume.DoesNotExist):
                pass
            return volume_not_found(volume_id)
        core_volume = convert_esh_volume(esh_volume, provider_uuid,
                                         identity_uuid, user)
        serialized_data = VolumeSerializer(core_volume,
                                           context={'request': request}).data
        response = Response(serialized_data)
        return response
Exemplo n.º 52
0
    def get(self, request, provider_uuid, identity_uuid, size_id):
        """
        Lookup the size information (Lookup using the given provider/identity)
        Update on server DB (If applicable)
        """
        user = request.user
        try:
            esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
        except ProviderNotActive as pna:
            return inactive_provider(pna)
        except Exception as e:
            return failure_response(status.HTTP_409_CONFLICT, e.message)

        if not esh_driver:
            return invalid_creds(provider_uuid, identity_uuid)
        core_size = convert_esh_size(esh_driver.get_size(size_id),
                                     provider_uuid)
        serialized_data = ProviderSizeSerializer(core_size).data
        response = Response(serialized_data)
        return response
Exemplo n.º 53
0
    def delete(self, request, provider_uuid, identity_uuid, volume_id):
        """
        Destroys the volume and updates the DB
        """
        user = request.user
        # Ensure volume exists
        try:
            esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
        except ProviderNotActive as pna:
            return inactive_provider(pna)
        except Exception as e:
            return failure_response(
                status.HTTP_409_CONFLICT,
                e.message)

        if not esh_driver:
            return invalid_creds(provider_uuid, identity_uuid)
        try:
            esh_volume = esh_driver.get_volume(volume_id)
        except ConnectionFailure:
            return connection_failure(provider_uuid, identity_uuid)
        except LibcloudInvalidCredsError:
            return invalid_creds(provider_uuid, identity_uuid)
        except Exception as exc:
            logger.exception("Encountered a generic exception. "
                             "Returning 409-CONFLICT")
            return failure_response(status.HTTP_409_CONFLICT,
                                    str(exc.message))
        if not esh_volume:
            return volume_not_found(volume_id)
        core_volume = convert_esh_volume(esh_volume, provider_uuid,
                                         identity_uuid, user)
        # Delete the object, update the DB
        esh_driver.destroy_volume(esh_volume)
        core_volume.end_date = now()
        core_volume.save()
        # Return the object
        serialized_data = VolumeSerializer(core_volume,
                                           context={'request': request}).data
        response = Response(serialized_data)
        return response
Exemplo n.º 54
0
    def get(self, request, provider_uuid, identity_uuid):
        """
        Retrieves list of volumes and updates the DB
        """
        user = request.user
        try:
            esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
        except ProviderNotActive as pna:
            return inactive_provider(pna)
        except Exception as e:
            return failure_response(
                status.HTTP_409_CONFLICT,
                e.message)
        if not esh_driver:
            return invalid_creds(provider_uuid, identity_uuid)
        volume_list_method = esh_driver.list_volumes

        if AccountProvider.objects.filter(identity__uuid=identity_uuid):
            # Instance list method changes when using the OPENSTACK provider
            volume_list_method = esh_driver.list_all_volumes
        try:
            esh_volume_list = volume_list_method()
        except (socket_error, ConnectionFailure):
            return connection_failure(provider_uuid, identity_uuid)
        except LibcloudBadResponseError:
            return malformed_response(provider_uuid, identity_uuid)
        except LibcloudInvalidCredsError:
            return invalid_creds(provider_uuid, identity_uuid)
        except Exception:
            logger.exception("Uncaught Exception in Volume list method")
            return failure_response(
                status.HTTP_500_INTERNAL_SERVER_ERROR,
                'Volume list method failed. Contact support')

        core_volume_list = [convert_esh_volume(volume, provider_uuid,
                                               identity_uuid, user)
                            for volume in esh_volume_list]
        serializer = VolumeSerializer(core_volume_list,
                                      context={'request': request}, many=True)
        response = Response(serializer.data)
        return response
Exemplo n.º 55
0
 def get(self, request, provider_uuid, identity_uuid):
     """
     Returns a list of all instances
     """
     user = request.user
     try:
         esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
     except ProviderNotActive as pna:
         return inactive_provider(pna)
     except Exception as e:
         return failure_response(status.HTTP_409_CONFLICT, e.message)
     if not esh_driver:
         return invalid_creds(provider_uuid, identity_uuid)
     identity = Identity.objects.get(uuid=identity_uuid)
     # Probably redundant
     if not user.can_use_identity(identity.id):
         return invalid_creds(provider_uuid, identity_uuid)
     try:
         esh_instance_list = get_cached_instances(identity=identity)
     except LibcloudBadResponseError:
         return malformed_response(provider_uuid, identity_uuid)
     except (socket_error, ConnectionFailure):
         return connection_failure(provider_uuid, identity_uuid)
     except LibcloudInvalidCredsError:
         return invalid_creds(provider_uuid, identity_uuid)
     core_instance_list = [
         convert_esh_instance(esh_driver, inst, provider_uuid,
                              identity_uuid, user)
         for inst in esh_instance_list
     ]
     # TODO: Core/Auth checks for shared instances
     serialized_data = InstanceSerializer(core_instance_list,
                                          context={
                                              "request": request
                                          },
                                          many=True).data
     response = Response(serialized_data)
     response['Cache-Control'] = 'no-cache'
     return response
Exemplo n.º 56
0
 def delete(self, request, provider_uuid, identity_uuid, snapshot_id):
     """
     Destroys the volume and updates the DB
     """
     # Ensure volume exists
     try:
         esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
     except ProviderNotActive as pna:
         return inactive_provider(pna)
     except Exception as e:
         return failure_response(status.HTTP_409_CONFLICT, e.message)
     if not esh_driver:
         return invalid_creds(provider_uuid, identity_uuid)
     snapshot = esh_driver._connection.get_snapshot(snapshot_id)
     if not snapshot:
         return snapshot_not_found(snapshot_id)
     delete_success = esh_driver._connection.ex_delete_snapshot(snapshot)
     # NOTE: Always false until icehouse...
     #    return failure_response(
     #        status.HTTP_400_BAD_REQUEST,
     #        % snapshot_id)
     return Response(status=status.HTTP_204_NO_CONTENT)
Exemplo n.º 57
0
 def get(self, request, provider_uuid, identity_uuid, instance_id):
     """
     Authentication Required, get instance details.
     """
     user = request.user
     esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
     if not esh_driver:
         return invalid_creds(provider_uuid, identity_uuid)
     try:
         esh_instance = esh_driver.get_instance(instance_id)
     except (socket_error, ConnectionFailure):
         return connection_failure(provider_uuid, identity_uuid)
     except InvalidCredsError:
         return invalid_creds(provider_uuid, identity_uuid)
     except Exception as exc:
         logger.exception("Encountered a generic exception. "
                          "Returning 409-CONFLICT")
         return failure_response(status.HTTP_409_CONFLICT,
                                 str(exc.message))
     if not esh_instance:
         try:
             core_inst = CoreInstance.objects.get(
                 provider_alias=instance_id,
                 source__provider__uuid=provider_uuid,
                 created_by_identity__uuid=identity_uuid)
             core_inst.end_date_all()
         except CoreInstance.DoesNotExist:
             pass
         return instance_not_found(instance_id)
     core_instance = convert_esh_instance(esh_driver, esh_instance,
                                          provider_uuid, identity_uuid,
                                          user)
     serialized_data = InstanceSerializer(
         core_instance,
         context={"request": request}).data
     response = Response(serialized_data)
     response['Cache-Control'] = 'no-cache'
     return response
Exemplo n.º 58
0
def provider_filtered_machines(request,
                               provider_uuid,
                               identity_uuid,
                               request_user=None):
    """
    Return all filtered machines. Uses the most common,
    default filtering method.
    """
    try:
        esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
    except Exception:
        #TODO: Observe the change of 'Fail loudly' here and clean up the noise, rather than hide it.
        logger.exception(
            "Driver could not be prepared - Provider: %s , Identity: %s" %
            (provider_uuid, identity_uuid))
        esh_driver = None

    if not esh_driver:
        return invalid_creds(provider_uuid, identity_uuid)

    logger.debug(esh_driver)

    return list_filtered_machines(esh_driver, provider_uuid, request_user)
Exemplo n.º 59
0
 def patch(self, request, provider_uuid, identity_uuid, volume_id):
     """
     Updates DB values for volume
     """
     user = request.user
     data = request.DATA
     #Ensure volume exists
     esh_driver = prepare_driver(request, provider_uuid, identity_uuid)
     if not esh_driver:
         return invalid_creds(provider_uuid, identity_uuid)
     try:
         esh_volume = esh_driver.get_volume(volume_id)
     except ConnectionFailure:
         return connection_failure(provider_uuid, identity_uuid)
     except InvalidCredsError:
         return invalid_creds(provider_uuid, identity_uuid)
     except Exception as exc:
         logger.exception("Encountered a generic exception. "
                          "Returning 409-CONFLICT")
         return failure_response(status.HTTP_409_CONFLICT, str(exc.message))
     if not esh_volume:
         return volume_not_found(volume_id)
     core_volume = convert_esh_volume(esh_volume, provider_uuid,
                                      identity_uuid, user)
     serializer = VolumeSerializer(core_volume,
                                   data=data,
                                   context={'request': request},
                                   partial=True)
     if serializer.is_valid():
         serializer.save()
         update_volume_metadata(esh_driver, esh_volume, data)
         response = Response(serializer.data)
         return response
     else:
         return failure_response(status.HTTP_400_BAD_REQUEST,
                                 serializer.errors)