Esempio n. 1
0
def _execute_provider_action(identity, user, instance, action_name):
    driver = get_cached_driver(identity=identity)
    try:
        if not action_name:
            logger.debug("No 'action_name' provided")
            return
        elif action_name == 'Suspend':
            suspend_instance(driver, instance, identity.provider.uuid,
                             identity.uuid, user)
        elif action_name == 'Stop':
            stop_instance(driver, instance, identity.provider.uuid,
                          identity.uuid, user)
        elif action_name == 'Shelve':
            shelve_instance(driver, instance, identity.provider.uuid,
                            identity.uuid, user)
        elif action_name == 'Shelve Offload':
            offload_instance(driver, instance, identity.provider.uuid,
                             identity.uuid, user)
        elif action_name == 'Terminate':
            destroy_instance(identity.uuid, instance)
        else:
            raise Exception("Encountered Unknown Action Named %s" % action)
    except ObjectDoesNotExist:
        # This may be unreachable when null,blank = True
        logger.debug("Provider %s - 'Do Nothing' for Over Allocation" %
                     provider)
        return
Esempio n. 2
0
def _execute_provider_action(identity, user, instance, action_name):
    driver = get_cached_driver(identity=identity)

    # NOTE: This if statement is a HACK! It will be removed when IP management is enabled in an upcoming version. -SG
    reclaim_ip = True if identity.provider.location != 'iPlant Cloud - Tucson' else False
    # ENDNOTE

    # NOTE: This metadata statement is a HACK! It should be removed when all instances matching this metadata key have been removed.
    instance_has_home_mount = instance.extra['metadata'].get('atmosphere_ephemeral_home_mount', 'false').lower()
    if instance_has_home_mount == 'true' and action_name == 'Shelve':
        logger.info("Instance %s will be suspended instead of shelved, because the ephemeral storage is in /home" % instance.id)
        action_name = 'Suspend'


    logger.info("User %s has gone over their allocation on Instance %s - Enforcement Choice: %s" % (user, instance, action_name))
    try:
        if not action_name:
            logger.debug("No 'action_name' provided")
            return
        elif action_name == 'Suspend':
            suspend_instance(
                driver,
                instance,
                identity.provider.uuid,
                identity.uuid,
                user,
                reclaim_ip)
        elif action_name == 'Stop':
            stop_instance(
                driver,
                instance,
                identity.provider.uuid,
                identity.uuid,
                user,
                reclaim_ip)
        elif action_name == 'Shelve':
            shelve_instance(
                driver,
                instance,
                identity.provider.uuid,
                identity.uuid,
                user,
                reclaim_ip)
        elif action_name == 'Shelve Offload':
            offload_instance(
                driver,
                instance,
                identity.provider.uuid,
                identity.uuid,
                user,
                reclaim_ip)
        elif action_name == 'Terminate':
            destroy_instance(user, identity.uuid, instance.id)
        else:
            raise Exception("Encountered Unknown Action Named %s" % action_name)
    except ObjectDoesNotExist:
        # This may be unreachable when null,blank = True
        logger.debug("Provider %s - 'Do Nothing' for Over Allocation" % identity.provider)
        return
Esempio n. 3
0
def _execute_provider_action(identity, user, instance, action_name):
    driver = get_cached_driver(identity=identity)

    # NOTE: This if statement is a HACK! It will be removed when IP management is enabled in an upcoming version. -SG
    reclaim_ip = True if identity.provider.location != 'iPlant Cloud - Tucson' else False
    # ENDNOTE

    # NOTE: This metadata statement is a HACK! It should be removed when all instances matching this metadata key have been removed.
    instance_has_home_mount = instance.extra['metadata'].get(
        'atmosphere_ephemeral_home_mount', 'false').lower()
    if instance_has_home_mount == 'true' and action_name == 'Shelve':
        logger.info(
            "Instance %s will be suspended instead of shelved, because the ephemeral storage is in /home"
            % instance.id)
        action_name = 'Suspend'

    logger.info(
        "User %s has gone over their allocation on Instance %s - Enforcement Choice: %s"
        % (user, instance, action_name))
    try:
        if not action_name:
            logger.debug("No 'action_name' provided")
            return
        elif action_name == 'Suspend':
            suspend_instance(driver, instance, identity.provider.uuid,
                             identity.uuid, user, reclaim_ip)
        elif action_name == 'Stop':
            stop_instance(driver, instance, identity.provider.uuid,
                          identity.uuid, user, reclaim_ip)
        elif action_name == 'Shelve':
            shelve_instance(driver, instance, identity.provider.uuid,
                            identity.uuid, user, reclaim_ip)
        elif action_name == 'Shelve Offload':
            offload_instance(driver, instance, identity.provider.uuid,
                             identity.uuid, user, reclaim_ip)
        elif action_name == 'Terminate':
            destroy_instance(user, identity.uuid, instance.id)
        else:
            raise Exception("Encountered Unknown Action Named %s" %
                            action_name)
    except ObjectDoesNotExist:
        # This may be unreachable when null,blank = True
        logger.debug("Provider %s - 'Do Nothing' for Over Allocation" %
                     identity.provider)
        return
Esempio n. 4
0
def _execute_provider_action(identity, user, instance, action_name):
    driver = get_cached_driver(identity=identity)
    try:
        if not action_name:
            logger.debug("No 'action_name' provided")
            return
        elif action_name == 'Suspend':
            suspend_instance(
                driver,
                instance,
                identity.provider.uuid,
                identity.uuid,
                user)
        elif action_name == 'Stop':
            stop_instance(
                driver,
                instance,
                identity.provider.uuid,
                identity.uuid,
                user)
        elif action_name == 'Shelve':
            shelve_instance(
                driver,
                instance,
                identity.provider.uuid,
                identity.uuid,
                user)
        elif action_name == 'Shelve Offload':
            offload_instance(
                driver,
                instance,
                identity.provider.uuid,
                identity.uuid,
                user)
        elif action_name == 'Terminate':
            destroy_instance(user, identity.uuid, instance)
        else:
            raise Exception("Encountered Unknown Action Named %s" % action)
    except ObjectDoesNotExist:
        # This may be unreachable when null,blank = True
        logger.debug(
            "Provider %s - 'Do Nothing' for Over Allocation" %
            provider)
        return
Esempio n. 5
0
def _execute_provider_action(identity, user, instance, action_name):
    driver = get_cached_driver(identity=identity)

    # NOTE: This if statement is a HACK! It will be removed when IP management is enabled in an upcoming version. -SG
    reclaim_ip = True if identity.provider.location != 'iPlant Cloud - Tucson' else False
    # ENDNOTE

    logger.info(
        "User %s has gone over their allocation on Instance %s - Enforcement Choice: %s"
        % (user, instance, action_name))
    try:
        if not action_name:
            logger.debug("No 'action_name' provided")
            return
        elif action_name == 'Suspend':
            suspend_instance(driver, instance, identity.provider.uuid,
                             identity.uuid, user, reclaim_ip)
        elif action_name == 'Stop':
            stop_instance(driver, instance, identity.provider.uuid,
                          identity.uuid, user, reclaim_ip)
        elif action_name == 'Shelve':
            shelve_instance(driver, instance, identity.provider.uuid,
                            identity.uuid, user, reclaim_ip)
        elif action_name == 'Shelve Offload':
            offload_instance(driver, instance, identity.provider.uuid,
                             identity.uuid, user, reclaim_ip)
        elif action_name == 'Terminate':
            destroy_instance(user, identity.uuid, instance.id)
        else:
            raise Exception("Encountered Unknown Action Named %s" %
                            action_name)
    except ObjectDoesNotExist:
        # This may be unreachable when null,blank = True
        logger.debug("Provider %s - 'Do Nothing' for Over Allocation" %
                     identity.provider)
        return
Esempio n. 6
0
    def post(self, request, provider_uuid, identity_uuid, instance_id):
        """Authentication Required, Attempt a specific instance action,
        including necessary parameters.
        """
        # Service-specific call to action
        action_params = request.DATA
        if not action_params.get('action', None):
            return failure_response(
                status.HTTP_400_BAD_REQUEST,
                'POST request to /action require a BODY with \'action\'.')
        result_obj = None
        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:
            return failure_response(
                status.HTTP_400_BAD_REQUEST,
                'Instance %s no longer exists' % (instance_id,))
        action = action_params['action']
        try:
            if 'volume' in action:
                volume_id = action_params.get('volume_id')
                mount_location = action_params.get('mount_location', None)
                device = action_params.get('device', None)
                if 'attach_volume' == action:
                    if mount_location == 'null' or mount_location == 'None':
                        mount_location = None
                    if device == 'null' or device == 'None':
                        device = None
                    future_mount_location =\
                        task.attach_volume_task(esh_driver,
                                                esh_instance.alias,
                                                volume_id,
                                                device,
                                                mount_location)
                elif 'mount_volume' == action:
                    future_mount_location =\
                        task.mount_volume_task(esh_driver,
                                               esh_instance.alias,
                                               volume_id, device,
                                               mount_location)
                elif 'unmount_volume' == action:
                    (result, error_msg) =\
                        task.unmount_volume_task(esh_driver,
                                                 esh_instance.alias,
                                                 volume_id, device,
                                                 mount_location)
                elif 'detach_volume' == action:
                    (result, error_msg) =\
                        task.detach_volume_task(esh_driver,
                                                esh_instance.alias,
                                                volume_id)
                    if not result and error_msg:
                        # Return reason for failed detachment
                        return failure_response(
                            status.HTTP_400_BAD_REQUEST,
                            error_msg)
                # Task complete, convert the volume and return the object
                esh_volume = esh_driver.get_volume(volume_id)
                core_volume = convert_esh_volume(esh_volume,
                                                 provider_uuid,
                                                 identity_uuid,
                                                 user)
                result_obj =\
                    VolumeSerializer(core_volume,
                                     context={"request": request}).data
            elif 'resize' == action:
                size_alias = action_params.get('size', '')
                if type(size_alias) == int:
                    size_alias = str(size_alias)
                resize_instance(esh_driver, esh_instance, size_alias,
                                provider_uuid, identity_uuid, user)
            elif 'confirm_resize' == action:
                confirm_resize(esh_driver, esh_instance,
                               provider_uuid, identity_uuid, user)
            elif 'revert_resize' == action:
                esh_driver.revert_resize_instance(esh_instance)
            elif 'redeploy' == action:
                redeploy_init(esh_driver, esh_instance, countdown=None)
            elif 'resume' == action:
                result_obj = resume_instance(esh_driver, esh_instance,
                                             provider_uuid, identity_uuid,
                                             user)
            elif 'suspend' == action:
                result_obj = suspend_instance(esh_driver, esh_instance,
                                              provider_uuid, identity_uuid,
                                              user)
            elif 'shelve' == action:
                result_obj = shelve_instance(esh_driver, esh_instance,
                                             provider_uuid, identity_uuid,
                                             user)
            elif 'unshelve' == action:
                result_obj = unshelve_instance(esh_driver, esh_instance,
                                               provider_uuid, identity_uuid,
                                               user)
            elif 'shelve_offload' == action:
                result_obj = offload_instance(esh_driver, esh_instance)
            elif 'start' == action:
                start_instance(esh_driver, esh_instance,
                               provider_uuid, identity_uuid, user)
            elif 'stop' == action:
                stop_instance(esh_driver, esh_instance,
                              provider_uuid, identity_uuid, user)
            elif 'reset_network' == action:
                esh_driver.reset_network(esh_instance)
            elif 'console' == action:
                result_obj = esh_driver._connection\
                                       .ex_vnc_console(esh_instance)
            elif 'reboot' == action:
                reboot_type = action_params.get('reboot_type', 'SOFT')
                reboot_instance(esh_driver, esh_instance,
                                identity_uuid, user, reboot_type)
            elif 'rebuild' == action:
                machine_alias = action_params.get('machine_alias', '')
                machine = esh_driver.get_machine(machine_alias)
                esh_driver.rebuild_instance(esh_instance, machine)
            else:
                return failure_response(
                    status.HTTP_400_BAD_REQUEST,
                    'Unable to to perform action %s.' % (action))
            api_response = {
                'result': 'success',
                'message': 'The requested action <%s> was run successfully'
                % action_params['action'],
                'object': result_obj,
            }
            response = Response(api_response, status=status.HTTP_200_OK)
            return response
        except HypervisorCapacityError, hce:
            return over_capacity(hce)
Esempio n. 7
0
    def post(self, request, provider_uuid, identity_uuid, instance_id):
        """Authentication Required, Attempt a specific instance action,
        including necessary parameters.
        """
        # Service-specific call to action
        action_params = request.DATA
        if not action_params.get('action', None):
            return failure_response(
                status.HTTP_400_BAD_REQUEST,
                'POST request to /action require a BODY with \'action\'.')
        result_obj = None
        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:
            return failure_response(
                status.HTTP_400_BAD_REQUEST,
                'Instance %s no longer exists' % (instance_id,))
        action = action_params['action']
        try:
            if 'volume' in action:
                volume_id = action_params.get('volume_id')
                mount_location = action_params.get('mount_location', None)
                device = action_params.get('device', None)
                if 'attach_volume' == action:
                    if mount_location == 'null' or mount_location == 'None':
                        mount_location = None
                    if device == 'null' or device == 'None':
                        device = None
                    task.attach_volume_task(esh_driver,
                                            esh_instance.alias,
                                            volume_id,
                                            device,
                                            mount_location)
                elif 'mount_volume' == action:
                    task.mount_volume_task(esh_driver,
                                           esh_instance.alias,
                                           volume_id, device,
                                           mount_location)
                elif 'unmount_volume' == action:
                    (result, error_msg) =\
                        task.unmount_volume_task(esh_driver,
                                                 esh_instance.alias,
                                                 volume_id, device,
                                                 mount_location)
                elif 'detach_volume' == action:
                    (result, error_msg) =\
                        task.detach_volume_task(esh_driver,
                                                esh_instance.alias,
                                                volume_id)
                    if not result and error_msg:
                        # Return reason for failed detachment
                        return failure_response(
                            status.HTTP_400_BAD_REQUEST,
                            error_msg)
                # Task complete, convert the volume and return the object
                esh_volume = esh_driver.get_volume(volume_id)
                core_volume = convert_esh_volume(esh_volume,
                                                 provider_uuid,
                                                 identity_uuid,
                                                 user)
                result_obj =\
                    VolumeSerializer(core_volume,
                                     context={"request": request}).data
            elif 'resize' == action:
                size_alias = action_params.get('size', '')
                if isinstance(size_alias, int):
                    size_alias = str(size_alias)
                resize_instance(esh_driver, esh_instance, size_alias,
                                provider_uuid, identity_uuid, user)
            elif 'confirm_resize' == action:
                confirm_resize(esh_driver, esh_instance,
                               provider_uuid, identity_uuid, user)
            elif 'revert_resize' == action:
                esh_driver.revert_resize_instance(esh_instance)
            elif 'redeploy' == action:
                redeploy_init(esh_driver, esh_instance)
            elif 'resume' == action:
                result_obj = resume_instance(esh_driver, esh_instance,
                                             provider_uuid, identity_uuid,
                                             user)
            elif 'suspend' == action:
                result_obj = suspend_instance(esh_driver, esh_instance,
                                              provider_uuid, identity_uuid,
                                              user)
            elif 'shelve' == action:
                result_obj = shelve_instance(esh_driver, esh_instance,
                                             provider_uuid, identity_uuid,
                                             user)
            elif 'unshelve' == action:
                result_obj = unshelve_instance(esh_driver, esh_instance,
                                               provider_uuid, identity_uuid,
                                               user)
            elif 'shelve_offload' == action:
                result_obj = offload_instance(esh_driver, esh_instance)
            elif 'start' == action:
                start_instance(esh_driver, esh_instance,
                               provider_uuid, identity_uuid, user)
            elif 'stop' == action:
                stop_instance(esh_driver, esh_instance,
                              provider_uuid, identity_uuid, user)
            elif 'reset_network' == action:
                esh_driver.reset_network(esh_instance)
            elif 'console' == action:
                result_obj = esh_driver._connection\
                                       .ex_vnc_console(esh_instance)
            elif 'reboot' == action:
                reboot_type = action_params.get('reboot_type', 'SOFT')
                reboot_instance(esh_driver, esh_instance,
                                identity_uuid, user, reboot_type)
            elif 'rebuild' == action:
                machine_alias = action_params.get('machine_alias', '')
                machine = esh_driver.get_machine(machine_alias)
                esh_driver.rebuild_instance(esh_instance, machine)
            else:
                return failure_response(
                    status.HTTP_400_BAD_REQUEST,
                    'Unable to to perform action %s.' % (action))
            api_response = {
                'result': 'success',
                'message': 'The requested action <%s> was run successfully'
                % action_params['action'],
                'object': result_obj,
            }
            response = Response(api_response, status=status.HTTP_200_OK)
            return response
        except HypervisorCapacityError as hce:
            return over_capacity(hce)
        except OverQuotaError as oqe:
            return over_quota(oqe)
        except OverAllocationError as oae:
            return over_quota(oae)
        except SizeNotAvailable as snae:
            return size_not_availabe(snae)
        except (socket_error, ConnectionFailure):
            return connection_failure(provider_uuid, identity_uuid)
        except InvalidCredsError:
            return invalid_creds(provider_uuid, identity_uuid)
        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_404_FORBIDDEN,
                "The requested action %s encountered "
                "an irrecoverable exception: %s"
                % (action_params['action'], message))
Esempio n. 8
0
def main():
    '''
    This script will set active instances that come up for Invariant #12 on 
    https://tasmo.atmo.cloud to 'shelved' status and will be run via cron
    every Tuesday morning.
    '''
    query = '''SELECT
      instance.id,
      instance.name,
      instance.provider_alias,
       CASE
           WHEN instance_source.provider_id = 4
               THEN 'IU'
           WHEN instance_source.provider_id = 5
               THEN 'TACC'
           ELSE 'UNKNOWN' END            AS instance_provider_label,
      instance.start_date,
      instance.end_date,
      last_status.name                  AS last_status,
      last_status.activity              AS last_status_activity,
      last_status.start_date            AS last_status_start_date,
      last_status.end_date              AS last_status_end_date,
      i_als.name                        AS instance_allocation_source,
      au.username,
      au.is_staff,
      au.is_superuser,
      string_agg(current_als.name, ',') AS current_allocation_sources
    FROM instance
      LEFT OUTER JOIN instance_allocation_source_snapshot ialss ON instance.id = ialss.instance_id
      LEFT OUTER JOIN allocation_source i_als ON ialss.allocation_source_id = i_als.id
      LEFT OUTER JOIN atmosphere_user au ON instance.created_by_id = au.id
      LEFT OUTER JOIN user_allocation_source uals
        ON au.id = uals.user_id AND ialss.allocation_source_id = uals.allocation_source_id
      LEFT OUTER JOIN user_allocation_source current_uals on au.id = current_uals.user_id
      LEFT OUTER JOIN allocation_source current_als on current_uals.allocation_source_id = current_als.id
      LEFT OUTER JOIN instance_source ON instance.source_id = instance_source.id
      LEFT JOIN LATERAL
                (
                SELECT
                  ish.start_date,
                  ish.end_date,
                  status.name,
                  ish.activity
                FROM instance_status_history ish
                  LEFT JOIN instance_status status on ish.status_id = status.id
                WHERE ish.instance_id = instance.id
                ORDER BY ish.id DESC
                LIMIT 1
                ) last_status ON TRUE
    WHERE
      instance.end_date IS NULL
      AND last_status.name NOT IN ('shelved_offloaded', 'shelved')
      AND (uals.allocation_source_id IS NULL
           OR ialss.allocation_source_id IS NULL)
    GROUP BY
      instance.id,
      i_als.id,
      instance_source.provider_id,
      au.id,
      last_status.start_date,
      last_status.end_date,
      last_status.name,
      last_status.activity'''

    active_instances_to_shelve = []

    query_instances = Instance.objects.raw(raw_query=query)

    # Getting whitelisted allocation sources
    whitelist = getattr(settings, "ALLOCATION_OVERRIDES_NEVER_ENFORCE")

    # Only want ones that are not by 'atmoadmin'
    for instance in query_instances:
        if instance.created_by.username != 'atmoadmin' and \
            instance.allocation_source and instance.allocation_source.name not in whitelist:
            active_instances_to_shelve.append(instance)

    # Here they are, set them to shelved
    for inst in active_instances_to_shelve:
        reclaim_ip = True

        provider_id = inst.source.provider_id
        provider = Provider.objects.get(pk=provider_id)

        if not provider:
            print 'Provider not found, skipping'    # output to log in service
            continue

        identity = Identity.objects.get(
            created_by__username=inst.username, provider=provider
        )

        try:
            driver = get_cached_driver(identity=identity)
            esh_instance = driver.get_instance(inst.provider_alias)
            '''if driver:
                print 'got driver'
                print inst.name
                print inst.provider_alias
                print inst.allocation_source.name
                print identity.provider.id
                print identity.id
                print identity.created_by
                print inst.last_status
                print '***'
            else:
                print 'no driver'
            '''

            if inst.last_status == 'active' or inst.last_status == 'shutoff' or \
                inst.last_status == 'deploy_error' or inst.last_status == 'deploying' or \
                inst.last_status == 'suspended':
                shelve_instance(
                    driver, esh_instance, identity.provider.uuid, identity.uuid,
                    identity.created_by, reclaim_ip
                )
                print "Shelved instance %s (%s) on allocation %s for user %s" % (
                    inst.id, inst.name, inst.allocation_source.name,
                    inst.created_by.username
                )
            if inst.last_status == 'error':
                raise Exception('Did not shelve instance due to ERROR status')
        except Exception as e:
            print "Could not shelve Instance %s (%s) on allocation %s for user %s - Exception: %s" % (
                inst.id, inst.name, inst.allocation_source.name,
                inst.created_by.username, e
            )
        continue
Esempio n. 9
0
    def post(self, request, provider_uuid, identity_uuid, instance_id):
        """Authentication Required, Attempt a specific instance action,
        including necessary parameters.
        """
        # Service-specific call to action
        action_params = request.DATA
        if not action_params.get('action', None):
            return failure_response(
                status.HTTP_400_BAD_REQUEST,
                'POST request to /action require a BODY with \'action\'.')
        result_obj = None
        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 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 failure_response(
                status.HTTP_400_BAD_REQUEST,
                'Instance %s no longer exists' % (instance_id,))
        action = action_params['action']
        try:
            if 'volume' in action:
                volume_id = action_params.get('volume_id')
                mount_location = action_params.get('mount_location', None)
                device = action_params.get('device', None)
                if 'attach_volume' == action:
                    if mount_location == 'null' or mount_location == 'None':
                        mount_location = None
                    if device == 'null' or device == 'None':
                        device = None
                    future_mount_location =\
                        task.attach_volume_task(esh_driver,
                                                esh_instance.alias,
                                                volume_id,
                                                device,
                                                mount_location)
                elif 'mount_volume' == action:
                    future_mount_location =\
                        task.mount_volume_task(esh_driver,
                                               esh_instance.alias,
                                               volume_id, device,
                                               mount_location)
                elif 'unmount_volume' == action:
                    (result, error_msg) =\
                        task.unmount_volume_task(esh_driver,
                                                 esh_instance.alias,
                                                 volume_id, device,
                                                 mount_location)
                elif 'detach_volume' == action:
                    (result, error_msg) =\
                        task.detach_volume_task(esh_driver,
                                                esh_instance.alias,
                                                volume_id)
                    if not result and error_msg:
                        # Return reason for failed detachment
                        return failure_response(
                            status.HTTP_400_BAD_REQUEST,
                            error_msg)
                # Task complete, convert the volume and return the object
                esh_volume = esh_driver.get_volume(volume_id)
                core_volume = convert_esh_volume(esh_volume,
                                                 provider_uuid,
                                                 identity_uuid,
                                                 user)
                result_obj =\
                    VolumeSerializer(core_volume,
                                     context={"request": request}).data
            elif 'resize' == action:
                size_alias = action_params.get('size', '')
                if type(size_alias) == int:
                    size_alias = str(size_alias)
                resize_instance(esh_driver, esh_instance, size_alias,
                                provider_uuid, identity_uuid, user)
            elif 'confirm_resize' == action:
                confirm_resize(esh_driver, esh_instance,
                               provider_uuid, identity_uuid, user)
            elif 'revert_resize' == action:
                esh_driver.revert_resize_instance(esh_instance)
            elif 'redeploy' == action:
                redeploy_init(esh_driver, esh_instance, countdown=None)
            elif 'resume' == action:
                result_obj = resume_instance(esh_driver, esh_instance,
                                             provider_uuid, identity_uuid,
                                             user)
            elif 'suspend' == action:
                result_obj = suspend_instance(esh_driver, esh_instance,
                                              provider_uuid, identity_uuid,
                                              user)
            elif 'shelve' == action:
                result_obj = shelve_instance(esh_driver, esh_instance,
                                             provider_uuid, identity_uuid,
                                             user)
            elif 'unshelve' == action:
                result_obj = unshelve_instance(esh_driver, esh_instance,
                                               provider_uuid, identity_uuid,
                                               user)
            elif 'shelve_offload' == action:
                result_obj = offload_instance(esh_driver, esh_instance)
            elif 'start' == action:
                start_instance(esh_driver, esh_instance,
                               provider_uuid, identity_uuid, user)
            elif 'stop' == action:
                stop_instance(esh_driver, esh_instance,
                              provider_uuid, identity_uuid, user)
            elif 'reset_network' == action:
                esh_driver.reset_network(esh_instance)
            elif 'console' == action:
                result_obj = esh_driver._connection\
                                       .ex_vnc_console(esh_instance)
            elif 'reboot' == action:
                reboot_type = action_params.get('reboot_type', 'SOFT')
                reboot_instance(esh_driver, esh_instance,
                                identity_uuid, user, reboot_type)
            elif 'rebuild' == action:
                machine_alias = action_params.get('machine_alias', '')
                machine = esh_driver.get_machine(machine_alias)
                esh_driver.rebuild_instance(esh_instance, machine)
            else:
                return failure_response(
                    status.HTTP_400_BAD_REQUEST,
                    'Unable to to perform action %s.' % (action))
            api_response = {
                'result': 'success',
                'message': 'The requested action <%s> was run successfully'
                % action_params['action'],
                'object': result_obj,
            }
            response = Response(api_response, status=status.HTTP_200_OK)
            return response
        except HypervisorCapacityError, hce:
            return over_capacity(hce)