.. versionadded:: 2019.2.0

    Stop (deallocate) a VM

    CLI Examples:

    .. code-block:: bash

         salt-cloud -a stop myminion
423816
def stop(name, call=None):
    '''
    
    '''
    if call == 'function':
        raise SaltCloudSystemExit(
            'The stop action must be called with -a or --action.'
        )

    compconn = get_conn(client_type='compute')

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

    ret = {}
    if not resource_group:
        groups = list_resource_groups()
        for group in groups:
            try:
                instance = compconn.virtual_machines.deallocate(
                    vm_name=name,
                    resource_group_name=group
                )
                instance.wait()
                vm_result = instance.result()
                ret = vm_result.as_dict()
                break
            except CloudError as exc:
                if 'was not found' in exc.message:
                    continue
                else:
                    ret = {'error': exc.message}
        if not ret:
            __utils__['azurearm.log_cloud_error']('compute', 'Unable to find virtual machine with name: {0}'.format(name))
            ret = {'error': 'Unable to find virtual machine with name: {0}'.format(name)}
    else:
        try:
            instance = compconn.virtual_machines.deallocate(
                    vm_name=name,
                    resource_group_name=resource_group
                )
            instance.wait()
            vm_result = instance.result()
            ret = vm_result.as_dict()
        except CloudError as exc:
            __utils__['azurearm.log_cloud_error']('compute', 'Error attempting to stop {0}: {1}'.format(name, exc.message))
            ret = {'error': exc.message}

    return ret
339257
function stop() {
  return new Promise((resolve) => {
    if (child && child.kill) {
      debug('stopping test server');
      child.kill('SIGTERM');
      process.removeListener('exit', stop);
      child = null;
      debug('stopped test server');
    }

    resolve();
  });
}
219112
def stop(self):
        

        yield from self._stop_ubridge()
        with (yield from self._execute_lock):
            # stop the QEMU process
            self._hw_virtualization = False
            if self.is_running():
                log.info('Stopping QEMU VM "{}" PID={}'.format(self._name, self._process.pid))
                try:
                    if self.acpi_shutdown:
                        yield from self._control_vm("system_powerdown")
                        yield from gns3server.utils.asyncio.wait_for_process_termination(self._process, timeout=30)
                    else:
                        self._process.terminate()
                        yield from gns3server.utils.asyncio.wait_for_process_termination(self._process, timeout=3)
                except ProcessLookupError:
                    pass
                except asyncio.TimeoutError:
                    if self._process:
                        try:
                            self._process.kill()
                        except ProcessLookupError:
                            pass
                        if self._process.returncode is None:
                            log.warn('QEMU VM "{}" PID={} is still running'.format(self._name, self._process.pid))
            self._process = None
            self._stop_cpulimit()
            yield from super().stop()
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()
929569
def destroy_vm_by_name(self, si, vm_name, vm_path, logger):
        
        if vm_name is not None:
            vm = self.find_vm_by_name(si, vm_path, vm_name)
            if vm:
                return self.destroy_vm(vm, logger)
        raise ValueError('vm not found')
886438
async def terminate_vm(self, vm_id):
        
        if vm_id not in self._vms:
            raise DummyIaasVmNotFound()
        del self._vms[vm_id]
        return None
1204202
def stop(self, *args):
        

        if self.volumes: 
            volumes = " --bind " + " --bind ".join(self.volumes)
        else:
            volumes = ""
        
        self._print("Stopping container [{}]. The container ID is printed below.".format(self.name))
        utils.xrun("singularity", ["instance.stop {0:s}".format(self.name)])

        self.status = "exited"

        return 0
430374
def stop(name, call=None):
    
    if call != 'action':
        raise SaltCloudSystemExit(
            'The instance action must be called with -a or --action.'
        )

    log.info("Stopping machine: %s", name)
    vb_stop_vm(name)
    machine = vb_get_machine(name)
    del machine["name"]
    return treat_machine_dict(machine)
1126150
def destroy(device):
    '''
    
    '''
    try:
        details = detail(device)
    except CommandExecutionError:
        return False

    stop_cmd = ['mdadm', '--stop', device]
    zero_cmd = ['mdadm', '--zero-superblock']

    if __salt__['cmd.retcode'](stop_cmd, python_shell=False) == 0:
        for number in details['members']:
            zero_cmd.append(details['members'][number]['device'])
        __salt__['cmd.retcode'](zero_cmd, python_shell=False)

    # Remove entry from config file:
    if __grains__.get('os_family') == 'Debian':
        cfg_file = '/etc/mdadm/mdadm.conf'
    else:
        cfg_file = '/etc/mdadm.conf'

    try:
        __salt__['file.replace'](cfg_file, 'ARRAY {0} .*'.format(device), '')
    except SaltInvocationError:
        pass

    if __salt__['raid.list']().get(device) is None:
        return True
    else:
        return False
1183124
def cli(env, identifier, purge):
    
    manager = PlacementManager(env.client)
    group_id = helpers.resolve_id(manager.resolve_ids, identifier, 'placement_group')

    if purge:
        placement_group = manager.get_object(group_id)
        guest_list = ', '.join([guest['fullyQualifiedDomainName'] for guest in placement_group['guests']])
        if len(placement_group['guests']) < 1:
            raise exceptions.CLIAbort('No virtual servers were found in placement group %s' % identifier)

        click.secho("You are about to delete the following guests!\n%s" % guest_list, fg='red')
        if not (env.skip_confirmations or formatting.confirm("This action will cancel all guests! Continue?")):
            raise exceptions.CLIAbort('Aborting virtual server order.')
        vm_manager = VSManager(env.client)
        for guest in placement_group['guests']:
            click.secho("Deleting %s..." % guest['fullyQualifiedDomainName'])
            vm_manager.cancel_instance(guest['id'])
        return

    click.secho("You are about to delete the following placement group! %s" % identifier, fg='red')
    if not (env.skip_confirmations or formatting.confirm("This action will cancel the placement group! Continue?")):
        raise exceptions.CLIAbort('Aborting virtual server order.')
    cancel_result = manager.delete(group_id)
    if cancel_result:
        click.secho("Placement Group %s has been canceld." % identifier, fg='green')
965190
def stop(name, call=None):
    '''
    
    '''
    datacenter_id = get_datacenter_id()
    conn = get_conn()
    node = get_node(conn, name)

    conn.stop_server(datacenter_id=datacenter_id, server_id=node['id'])

    return True
606943
def _stop(self):
        
        engine = self.current_engine()
        if "vm" in self._controller.computes:
            yield from self._controller.delete_compute("vm")
        if engine.running:
            log.info("")
            yield from engine.stop()
125006
def stop(name, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The start action must be called with -a or --action.'
        )

    log.info('Stopping node %s', name)

    return vm_action(name, kwargs={'action': 'stop'}, call=call)
1180437
def destroy(vm_name, call=None):
    '''
    
    '''
    if call and call != 'action':
        raise SaltCloudSystemExit(
            'The destroy action must be called with -d or "-a destroy".'
        )

    conn = get_conn()

    try:
        node = conn.ex_get_node(vm_name)
    except Exception as exc:  # pylint: disable=W0703
        log.error(
            'Could not locate instance %s\n\n'
            'The following exception was thrown by libcloud when trying to '
            'run the initial deployment: \n%s',
            vm_name, exc, exc_info_on_loglevel=logging.DEBUG
        )
        raise SaltCloudSystemExit(
            'Could not find instance {0}.'.format(vm_name)
        )

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

    # Use the instance metadata to see if its salt cloud profile was
    # preserved during instance create.  If so, use the profile value
    # to see if the 'delete_boot_pd' value is set to delete the disk
    # along with the instance.
    profile = None
    if node.extra['metadata'] and 'items' in node.extra['metadata']:
        for md in node.extra['metadata']['items']:
            if md['key'] == 'salt-cloud-profile':
                profile = md['value']
    vm_ = get_configured_provider()
    delete_boot_pd = False

    if profile and profile in vm_['profiles'] and 'delete_boot_pd' in vm_['profiles'][profile]:
        delete_boot_pd = vm_['profiles'][profile]['delete_boot_pd']

    try:
        inst_deleted = conn.destroy_node(node)
    except Exception as exc:  # pylint: disable=W0703
        log.error(
            'Could not destroy instance %s\n\n'
            'The following exception was thrown by libcloud when trying to '
            'run the initial deployment: \n%s',
            vm_name, exc, exc_info_on_loglevel=logging.DEBUG
        )
        raise SaltCloudSystemExit(
            'Could not destroy instance {0}.'.format(vm_name)
        )
    __utils__['cloud.fire_event'](
        'event',
        'delete instance',
        'salt/cloud/{0}/deleted'.format(vm_name),
        args={'name': vm_name},
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    if delete_boot_pd:
        log.info(
            'delete_boot_pd is enabled for the instance profile, '
            'attempting to delete disk'
            )
        __utils__['cloud.fire_event'](
            'event',
            'delete disk',
            'salt/cloud/disk/deleting',
            args={'name': vm_name},
            sock_dir=__opts__['sock_dir'],
            transport=__opts__['transport']
        )
        try:
            conn.destroy_volume(conn.ex_get_volume(vm_name))
        except Exception as exc:  # pylint: disable=W0703
            # Note that we don't raise a SaltCloudSystemExit here in order
            # to allow completion of instance deletion.  Just log the error
            # and keep going.
            log.error(
                'Could not destroy disk %s\n\n'
                'The following exception was thrown by libcloud when trying '
                'to run the initial deployment: \n%s',
                vm_name, exc, exc_info_on_loglevel=logging.DEBUG
            )
        __utils__['cloud.fire_event'](
            'event',
            'deleted disk',
            'salt/cloud/disk/deleted',
            args={'name': vm_name},
            sock_dir=__opts__['sock_dir'],
            transport=__opts__['transport']
        )

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

    return inst_deleted
3811
async def terminate_vm(self, vm_id):
        '''
         
        '''
        try:
            await self.nova.servers.force_delete(vm_id)
        except JSONDecodeError as exc:
            logging.info("nova sent 'content-type: application/json' but no content appeared, whatever")
            pass
        except Exception:
            raise
376654
def destroy(name, call=None):
    '''
    
    '''
    if call == 'function':
        raise SaltCloudSystemExit(
            'The destroy action must be called with -d, --destroy, '
            '-a, or --action.'
        )

    opts = __opts__

    __utils__['cloud.fire_event'](
        'event',
        'destroying instance',
        'salt/cloud/{0}/destroying'.format(name),
        args={'name': name},
        sock_dir=opts['sock_dir'],
        transport=opts['transport']
    )
    my_info = _get_my_info(name)
    if my_info:
        profile_name = my_info[name]['profile']
        profile = opts['profiles'][profile_name]
        host = profile['host']
        local = salt.client.LocalClient()
        ret = local.cmd(host, 'vagrant.destroy', [name])

        if ret[host]:
            __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)}
        else:
            return {'Error': 'Error destroying {}'.format(name)}
    else:
        return {'Error': 'No response from {}. Cannot destroy.'.format(name)}
544921
def stop(&block)
      block.call('stop') unless block.nil?
      pid = read_pid
      fail 'No valid PID file.' unless pid && pid > 0
      Process.kill('TERM', pid)
      delete_pid
      puts 'Process terminated.'
    end