Stop a gluster volume

    name
        Volume name

    force
        Force stop the volume

        .. versionadded:: 2015.8.4

    CLI Example:

    .. code-block:: bash

        salt '*' glusterfs.stop_volume mycluster
544411
def stop_volume(name, force=False):
    '''
    
    '''
    volinfo = info()
    if name not in volinfo:
        log.error('Cannot stop non-existing volume %s', name)
        return False
    if int(volinfo[name]['status']) != 1:
        log.warning('Attempt to stop already stopped volume %s', name)
        return True

    cmd = 'volume stop {0}'.format(name)
    if force:
        cmd += ' force'

    return _gluster(cmd)
106325
def stop_service(name):
        
        with win32.OpenSCManager(
            dwDesiredAccess = win32.SC_MANAGER_CONNECT
        ) as hSCManager:
            with win32.OpenService(hSCManager, name,
                                   dwDesiredAccess = win32.SERVICE_STOP
            ) as hService:
                win32.ControlService(hService, win32.SERVICE_CONTROL_STOP)
905667
def destroy(name, call=None):
    '''
    
    '''
    if call == 'function':
        raise SaltCloudException(
            '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']
    )

    vm_ = get_configured_provider()
    manager = packet.Manager(auth_token=vm_['token'])

    nodes = list_nodes_min()

    node = nodes[name]

    for project in manager.list_projects():

        for volume in manager.list_volumes(project.id):
            if volume.attached_to == node['id']:
                volume.detach()
                volume.delete()
                break

    manager.call_api("devices/{id}".format(id=node['id']), type='DELETE')

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

    return {}
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
                )
11914
def stop(name, call=None):
    '''
    
    '''
    conn = get_conn()
    node = get_node(conn, name)  # pylint: disable=not-callable
    log.debug('Node of Cloud VM: %s', node)

    status = conn.ex_shutdown_graceful(node)
    log.debug('Status of Cloud VM: %s', status)

    return status
454599
def stop(name):
    
    container_name = get_container_name(name)
    client = docker.Client()
    try:
        client.stop(container_name)
    except docker.errors.NotFound:
        pass
    except docker.errors.APIError as error:
        die(error.explanation.decode())
1252833
def delete_volume(self, volume_name: str):
        
        # Raise an exception if we are not a manager
        if not self._manager:
            raise RuntimeError('Volumes can only be deleted '
                               'on swarm manager nodes')

        # Remove volume
        self._api_client.remove_volume(volume_name)
755349
def stop(self, container, **kwargs):
        
        self.push_log("Stopping container '{0}'.".format(container))
        super(DockerFabricClient, self).stop(container, **kwargs)
106563
def delete_disk(kwargs=None, call=None):
    '''
    
    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The delete_disk function must be called with -f or --function.'
        )

    if not kwargs or 'disk_name' not in kwargs:
        log.error(
            'A disk_name must be specified when deleting a disk.'
        )
        return False

    conn = get_conn()

    disk = conn.ex_get_volume(kwargs.get('disk_name'))

    __utils__['cloud.fire_event'](
        'event',
        'delete disk',
        'salt/cloud/disk/deleting',
        args={
            'name': disk.name,
            'location': disk.extra['zone'].name,
            'size': disk.size,
        },
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    try:
        result = conn.destroy_volume(disk)
    except ResourceInUseError as exc:
        log.error(
            'Disk %s is in use and must be detached before deleting.\n'
            'The following exception was thrown by libcloud:\n%s',
            disk.name, exc, exc_info_on_loglevel=logging.DEBUG
        )
        return False

    __utils__['cloud.fire_event'](
        'event',
        'deleted disk',
        'salt/cloud/disk/deleted',
        args={
            'name': disk.name,
            'location': disk.extra['zone'].name,
            'size': disk.size,
        },
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )
    return result
12356
def destroy(name, conn=None, 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']
    )

    if not conn:
        conn = get_conn()   # pylint: disable=E0602

    node = get_node(conn, name)
    profiles = get_configured_provider()['profiles']  # pylint: disable=E0602
    if node is None:
        log.error('Unable to find the VM %s', name)
    profile = None
    if 'metadata' in node.extra and 'profile' in node.extra['metadata']:
        profile = node.extra['metadata']['profile']

    flush_mine_on_destroy = False
    if profile and profile in profiles and 'flush_mine_on_destroy' in profiles[profile]:
        flush_mine_on_destroy = profiles[profile]['flush_mine_on_destroy']

    if flush_mine_on_destroy:
        log.info('Clearing Salt Mine: %s', name)

        mopts_ = salt.config.DEFAULT_MINION_OPTS
        conf_path = '/'.join(__opts__['conf_file'].split('/')[:-1])
        mopts_.update(
            salt.config.minion_config(os.path.join(conf_path, 'minion'))
        )
        client = salt.client.get_local_client(mopts_)
        minions = client.cmd(name, 'mine.flush')

    log.info('Clearing Salt Mine: %s, %s', name, flush_mine_on_destroy)
    log.info('Destroying VM: %s', name)
    ret = conn.destroy_node(node)
    if ret:
        log.info('Destroyed VM: %s', name)
        # Fire destroy action
        __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__['delete_sshkeys'] is True:
            public_ips = getattr(node, __opts__.get('ssh_interface', 'public_ips'))
            if public_ips:
                salt.utils.cloud.remove_sshkey(public_ips[0])

            private_ips = getattr(node, __opts__.get('ssh_interface', 'private_ips'))
            if private_ips:
                salt.utils.cloud.remove_sshkey(private_ips[0])

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

        return True

    log.error('Failed to Destroy VM: %s', name)
    return False
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
189469
def stop(name, kill=False):
    '''
    
    '''
    if _sd_version() >= 219:
        if kill:
            action = 'terminate'
        else:
            action = 'poweroff'
        ret = _machinectl('{0} {1}'.format(action, name))
    else:
        cmd = 'systemctl stop systemd-nspawn@{0}'.format(name)
        ret = __salt__['cmd.run_all'](cmd, python_shell=False)

    if ret['retcode'] != 0:
        __context__['retcode'] = salt.defaults.exitcodes.EX_UNAVAILABLE
        return False
    return True
554082
def destroy(name, call=None):
    '''
    
    '''
    if call == 'function':
        raise SaltCloudSystemExit(
            'The destroy action must be called with -d, --destroy, '
            '-a or --action.'
        )

    node_metadata = _get_node(name)
    instance_id = node_metadata['instanceId']
    sir_id = node_metadata.get('spotInstanceRequestId')
    protected = show_term_protect(
        name=name,
        instance_id=instance_id,
        call='action',
        quiet=True
    )

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

    if protected == 'true':
        raise SaltCloudSystemExit(
            'This instance has been protected from being destroyed. '
            'Use the following command to disable protection:\n\n'
            'salt-cloud -a disable_term_protect {0}'.format(
                name
            )
        )

    ret = {}

    # Default behavior is to rename EC2 VMs when destroyed
    # via salt-cloud, unless explicitly set to False.
    rename_on_destroy = config.get_cloud_config_value('rename_on_destroy',
                                                      get_configured_provider(),
                                                      __opts__,
                                                      search_global=False)
    if rename_on_destroy is not False:
        newname = '{0}-DEL{1}'.format(name, uuid.uuid4().hex)
        rename(name, kwargs={'newname': newname}, call='action')
        log.info(
            'Machine will be identified as %s until it has been '
            'cleaned up.', newname
        )
        ret['newname'] = newname

    params = {'Action': 'TerminateInstances',
              'InstanceId.1': instance_id}

    location = get_location()
    provider = get_provider()
    result = aws.query(params,
                       location=location,
                       provider=provider,
                       opts=__opts__,
                       sigver='4')

    log.info(result)
    ret.update(result[0])

    # If this instance is part of a spot instance request, we
    # need to cancel it as well
    if sir_id is not None:
        params = {'Action': 'CancelSpotInstanceRequests',
                  'SpotInstanceRequestId.1': sir_id}
        result = aws.query(params,
                           location=location,
                           provider=provider,
                           opts=__opts__,
                           sigver='4')
        ret['spotInstance'] = result[0]

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

    __utils__['cloud.cachedir_index_del'](name)

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

    return ret
15384
def _stop_instance(self):
        
        try:
            vm_stop = self.compute.virtual_machines.power_off(
                self.running_instance_id, self.running_instance_id
            )
        except Exception as error:
            raise AzureCloudException(
                'Unable to stop instance: {0}.'.format(error)
            )

        vm_stop.wait()
1166881
def suspend(name, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The suspend action must be called with '
            '-a or --action.'
        )

    vm_properties = [
        "name",
        "summary.runtime.powerState"
    ]

    vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)

    for vm in vm_list:
        if vm["name"] == name:
            if vm["summary.runtime.powerState"] == "poweredOff":
                ret = 'cannot suspend in powered off state'
                log.info('VM %s %s', name, ret)
                return ret
            elif vm["summary.runtime.powerState"] == "suspended":
                ret = 'already suspended'
                log.info('VM %s %s', name, ret)
                return ret
            try:
                log.info('Suspending VM %s', name)
                task = vm["object"].Suspend()
                salt.utils.vmware.wait_for_task(task, name, 'suspend')
            except Exception as exc:
                log.error(
                    'Error while suspending VM %s: %s',
                    name, exc,
                    # Show the traceback if the debug logging level is enabled
                    exc_info_on_loglevel=logging.DEBUG
                )
                return 'failed to suspend'

    return 'suspended'
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")
238746
def stop_containers(self):
        
        while len(self._containers):
            container = self._containers.pop()
            try:
                container.kill(signal.SIGKILL)
            except docker.errors.APIError:  # probably doesn't exist anymore
                pass