Deletes a gluster volume

    target
        Volume to delete

    stop : True
        If ``True``, stop volume before delete

    CLI Example:

    .. code-block:: bash

        salt '*' glusterfs.delete_volume <volume>
503282
def delete_volume(target, stop=True):
    '''
    
    '''
    volinfo = info()
    if target not in volinfo:
        log.error('Cannot delete non-existing volume %s', target)
        return False

    # Stop volume if requested to and it is running
    running = (volinfo[target]['status'] == '1')

    if not stop and running:
        # Fail if volume is running if stop is not requested
        log.error('Volume %s must be stopped before deletion', target)
        return False

    if running:
        if not stop_volume(target, force=True):
            return False

    cmd = 'volume delete {0}'.format(target)
    return _gluster(cmd)
658045
def delete(gandi, background, force, resource):
    
    output_keys = ['id', 'type', 'step']

    resource = sorted(tuple(set(resource)))
    possible_resources = gandi.iaas.resource_list()
    for item in resource:
        if item not in possible_resources:
            gandi.echo('Sorry virtual machine %s does not exist' % item)
            gandi.echo('Please use one of the following: %s' %
                       possible_resources)
            return

    if not force:
        instance_info = "'%s'" % ', '.join(resource)
        proceed = click.confirm("Are you sure to delete Virtual Machine %s?" %
                                instance_info)

        if not proceed:
            return

    iaas_list = gandi.iaas.list()
    stop_opers = []
    for item in resource:
        vm = next((vm for (index, vm) in enumerate(iaas_list)
                   if vm['hostname'] == item), gandi.iaas.info(item))
        if vm['state'] == 'running':
            if background:
                gandi.echo('Virtual machine not stopped, background option '
                           'disabled')
                background = False
            oper = gandi.iaas.stop(item, background)
            if not background:
                stop_opers.append(oper)

    opers = gandi.iaas.delete(resource, background)
    if background:
        for oper in stop_opers + opers:
            output_generic(gandi, oper, output_keys)

    return opers
105072
def destroy(name, call=None):
    '''
    
    '''
    if call == 'function':
        raise SaltCloudSystemExit(
            'The destroy action must be called with -d, --destroy, '
            '-a or --action.'
        )

    __utils__['cloud.fire_event'](
        'event',
        'destroying instance',
        'salt/cloud/{0}/destroying'.format(name),
        args={'name': name},
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    vmobj = _get_vm_by_name(name)
    if vmobj is not None:
        # stop the vm
        if get_vm_status(vmid=vmobj['vmid'])['status'] != 'stopped':
            stop(name, vmobj['vmid'], 'action')

        # wait until stopped
        if not wait_for_state(vmobj['vmid'], 'stopped'):
            return {'Error': 'Unable to stop {0}, command timed out'.format(name)}

        # required to wait a bit here, otherwise the VM is sometimes
        # still locked and destroy fails.
        time.sleep(3)

        query('delete', 'nodes/{0}/{1}'.format(
            vmobj['node'], vmobj['id']
        ))
        __utils__['cloud.fire_event'](
            'event',
            'destroyed instance',
            'salt/cloud/{0}/destroyed'.format(name),
            args={'name': name},
            sock_dir=__opts__['sock_dir'],
            transport=__opts__['transport']
        )
        if __opts__.get('update_cachedir', False) is True:
            __utils__['cloud.delete_minion_cachedir'](
                name, __active_provider_name__.split(':')[0], __opts__)

        return {'Destroyed': '{0} was destroyed.'.format(name)}
787090
def volume_detach(self,
                      name,
                      timeout=300):
        '''
        
        '''
        try:
            volume = self.volume_show(name)
        except KeyError as exc:
            raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
        if not volume['attachments']:
            return True
        response = self.compute_conn.volumes.delete_server_volume(
            volume['attachments'][0]['server_id'],
            volume['attachments'][0]['id']
        )
        trycount = 0
        start = time.time()
        while True:
            trycount += 1
            try:
                response = self._volume_get(volume['id'])
                if response['status'] == 'available':
                    return response
            except Exception as exc:
                log.debug('Volume is detaching: %s', name)
                time.sleep(1)
                if time.time() - start > timeout:
                    log.error('Timed out after %d seconds '
                              'while waiting for data', timeout)
                    return False

                log.debug(
                    'Retrying volume_show() (try %d)', trycount
                )
100631
def _Close(self):
    
    self._vslvm_volume_group = None
    self._vslvm_handle.close()
    self._vslvm_handle = None

    self._file_object.close()
    self._file_object = None
760462
def close_available(self):
        
        return {
            'volume_long': self.volume_long - self.volume_long_frozen,
            'volume_short': self.volume_short - self.volume_short_frozen
        }
412409
def delete(self, force=False, **kwargs):
        
        cmdline = ["podman", "rm", "--force" if force else "", self.get_name()]
        run_cmd(cmdline)
1024165
def detach_planned_volume(mapping)
      payload = {:agent_identity => @agent_identity, :device_name => mapping[:device_name]}
      Log.info("Detaching volume #{mapping[:volume_id]} for management purposes.")
      req = RetryableRequest.new("/storage_valet/detach_volume", payload, :retry_delay => VolumeManagement::VOLUME_RETRY_SECONDS)

      req.callback do |res|
        # don't set :volume_status here as that should only be queried
        mapping[:management_status] = 'detached'
        mapping[:attempts] = nil
        yield if block_given?
      end

      req.errback do |res|
        unless InstanceState.value == 'stranded'
          # volume could already be detaching or have been deleted
          # which we can't see because of latency; go around again
          # and check state of volume later.
          Log.error("Failed to detach volume #{mapping[:volume_id]} (#{res})")
          mapping[:attempts] ||= 0
          mapping[:attempts] += 1
          # retry indefinitely so long as core api instructs us to retry or else fail after max attempts.
          if mapping[:attempts] >= VolumeManagement::MAX_VOLUME_ATTEMPTS
            strand("Exceeded maximum of #{VolumeManagement::MAX_VOLUME_ATTEMPTS} attempts detaching volume #{mapping[:volume_id]} with error: #{res}")
          else
            yield if block_given?
          end
        end
      end

      req.run
    end
247280
def cleanup_storage vm
      vm.volumes.each do |vol|
        @logger.debug "Deleting volume #{vol.name} for OpenStack host #{vm.name}"
        vm.detach_volume(vol.id)
        vol.wait_for { ready? }
        vol.destroy
      end
    end
913214
def destroy(name, call=None, kwargs=None):  # pylint: disable=unused-argument
    '''
    
    '''
    if kwargs is None:
        kwargs = {}

    if call == 'function':
        raise SaltCloudSystemExit(
            'The destroy action must be called with -d, --destroy, '
            '-a or --action.'
        )

    compconn = get_conn(client_type='compute')

    node_data = show_instance(name, call='action')
    if node_data['storage_profile']['os_disk'].get('managed_disk'):
        vhd = node_data['storage_profile']['os_disk']['managed_disk']['id']
    else:
        vhd = node_data['storage_profile']['os_disk']['vhd']['uri']

    ret = {name: {}}
    log.debug('Deleting VM')
    result = compconn.virtual_machines.delete(node_data['resource_group'], name)
    result.wait()

    if __opts__.get('update_cachedir', False) is True:
        __utils__['cloud.delete_minion_cachedir'](
           name,
           __active_provider_name__.split(':')[0],
           __opts__
        )

    cleanup_disks = config.get_cloud_config_value(
        'cleanup_disks',
        get_configured_provider(),
        __opts__,
        search_global=False,
        default=False,
    )

    if cleanup_disks:
        cleanup_vhds = kwargs.get(
            'delete_vhd',
            config.get_cloud_config_value(
                'cleanup_vhds',
                get_configured_provider(),
                __opts__,
                search_global=False,
                default=False
            )
        )

        if cleanup_vhds:
            log.debug('Deleting vhd')

            comps = vhd.split('/')
            container = comps[-2]
            blob = comps[-1]

            ret[name]['delete_disk'] = {
                'delete_disks': cleanup_disks,
                'delete_vhd': cleanup_vhds,
                'container': container,
                'blob': blob,
            }

            if vhd.startswith('http'):
                ret[name]['data'] = delete_blob(
                    kwargs={'container': container, 'blob': blob},
                    call='function'
                )
            else:
                ret[name]['data'] = delete_managed_disk(
                    kwargs={'resource_group': node_data['resource_group'],
                            'container': container,
                            'blob': blob},
                    call='function'
                )

        cleanup_data_disks = kwargs.get(
            'delete_data_disks',
            config.get_cloud_config_value(
                'cleanup_data_disks',
                get_configured_provider(),
                __opts__,
                search_global=False,
                default=False
            )
        )

        if cleanup_data_disks:
            log.debug('Deleting data_disks')
            ret[name]['data_disks'] = {}

            for disk in node_data['storage_profile']['data_disks']:
                datavhd = disk.get('managed_disk', {}).get('id') or disk.get('vhd', {}).get('uri')
                comps = datavhd.split('/')
                container = comps[-2]
                blob = comps[-1]

                ret[name]['data_disks'][disk['name']] = {
                    'delete_disks': cleanup_disks,
                    'delete_vhd': cleanup_vhds,
                    'container': container,
                    'blob': blob,
                }

                if datavhd.startswith('http'):
                    ret[name]['data'] = delete_blob(
                        kwargs={'container': container, 'blob': blob},
                        call='function'
                    )
                else:
                    ret[name]['data'] = delete_managed_disk(
                        kwargs={'resource_group': node_data['resource_group'],
                                'container': container,
                                'blob': blob},
                        call='function'
                    )

    cleanup_interfaces = config.get_cloud_config_value(
        'cleanup_interfaces',
        get_configured_provider(),
        __opts__,
        search_global=False,
        default=False
    )

    if cleanup_interfaces:
        ret[name]['cleanup_network'] = {
            'cleanup_interfaces': cleanup_interfaces,
            'resource_group': node_data['resource_group'],
            'data': [],
        }

        ifaces = node_data['network_profile']['network_interfaces']
        for iface in ifaces:
            resource_group = iface['id'].split('/')[4]
            ret[name]['cleanup_network']['data'].append(
                delete_interface(
                    kwargs={
                        'resource_group': resource_group,
                        'iface_name': iface['name'],
                    },
                    call='function',
                )
            )

    return ret
1176697
def keepvol_on_destroy(name, kwargs=None, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The keepvol_on_destroy action must be called with -a or --action.'
        )

    if not kwargs:
        kwargs = {}

    device = kwargs.get('device', None)
    volume_id = kwargs.get('volume_id', None)

    return _toggle_delvol(name=name, device=device,
                          volume_id=volume_id, value='false')
672022
def delete_api(self, ret):
        '''
        
        '''

        exists_response = __salt__['boto_apigateway.api_exists'](name=self.rest_api_name,
                                                                 description=_Swagger.AWS_API_DESCRIPTION,
                                                                 **self._common_aws_args)
        if exists_response.get('exists'):
            if __opts__['test']:
                ret['comment'] = 'Rest API named {0} is set to be deleted.'.format(self.rest_api_name)
                ret['result'] = None
                ret['abort'] = True
                return ret

            delete_api_response = __salt__['boto_apigateway.delete_api'](name=self.rest_api_name,
                                                                         description=_Swagger.AWS_API_DESCRIPTION,
                                                                         **self._common_aws_args)
            if not delete_api_response.get('deleted'):
                ret['result'] = False
                ret['abort'] = True
                if 'error' in delete_api_response:
                    ret['comment'] = 'Failed to delete rest api: {0}.'.format(delete_api_response['error']['message'])
                return ret

            ret = _log_changes(ret, 'delete_api', delete_api_response)
        else:
            ret['comment'] = ('api already absent for swagger file: '
                              '{0}, desc: {1}'.format(self.rest_api_name, self.info_json))

        return ret
920624
def destroy_ebs_volume(connection, region, volume_id, log=False):
    

    if ebs_volume_exists(connection, region, volume_id):
        if log:
            log_yellow('destroying EBS volume ...')
        try:
            connection.delete_volume(volume_id)
        except:
            # our EBS volume may be gone, but AWS info tables are stale
            # wait a bit and ask again
            sleep(5)
            if not ebs_volume_exists(connection, region, volume_id):
                pass
            else:
                raise("Couldn't delete EBS volume")
740506
def delete(self, volume_id, force=False):
        
        return self.http_delete('/volumes/%s/export'
                                % volume_id, params={'force': force})
953928
def delete_storage(kwargs=None, conn=None, call=None):
    '''
    
    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The delete_storage function must be called with -f or --function.'
        )

    if kwargs is None:
        kwargs = {}

    if 'name' not in kwargs:
        raise SaltCloudSystemExit('A name must be specified as "name"')

    if not conn:
        conn = get_conn()

    try:
        data = conn.delete_storage_account(kwargs['name'])
        return {'Success': 'The storage account was successfully deleted'}
    except AzureMissingResourceHttpError as exc:
        raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
1056671
def stop_vm(self):
        
        if self.vagrant is not None:
            if self.destroy:
                self.vagrant.destroy()
                shutil.rmtree(self.vagrant.root, ignore_errors=True)
                self.vagrant = None
            else:
                self.vagrant.halt()
987544
def delete(self):
        
        fs, path = self._get_fs(create_dir=False)
        if fs.exists(path):
            fs.remove(path)
        if self.clean_dir and fs.exists('.'):
            fs.removedir('.')
        return True