Stop a VM in DimensionData.

    name:
        The name of the VM to stop.

    CLI Example:

    .. code-block:: bash

        salt-cloud -a stop vm_name
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
1056448
async def terminate_vm(self, preset, vm_id):
        
        vmshepherd = self.request.app.vmshepherd
        preset = vmshepherd.preset_manager.get_preset(preset)
        await preset.iaas.terminate_vm(vm_id)
        return 'OK'
355964
def destroy_vm_vdis(name=None, session=None, call=None):
    '''
    

    '''
    if session is None:
        session = _get_session()
    ret = {}
    # get vm object
    vms = session.xenapi.VM.get_by_name_label(name)
    if len(vms) == 1:
        # read virtual block device (vdb)
        vbds = session.xenapi.VM.get_VBDs(vms[0])
        if vbds is not None:
            x = 0
            for vbd in vbds:
                vbd_record = session.xenapi.VBD.get_record(vbd)
                if vbd_record['VDI'] != 'OpaqueRef:NULL':
                    # read vdi on vdb
                    vdi_record = session.xenapi.VDI.get_record(
                        vbd_record['VDI'])
                    if 'iso' not in vdi_record['name_label']:
                        session.xenapi.VDI.destroy(vbd_record['VDI'])
                        ret['vdi-{}'.format(x)] = vdi_record['name_label']
                x += 1
    return ret
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')
1016445
def destroy_template(name=None, call=None, kwargs=None):
    '''
    

    '''
    if call == 'action':
        raise SaltCloudSystemExit(
            'The destroy_template function must be called with  -f.'
        )
    if kwargs is None:
        kwargs = {}
    name = kwargs.get('name', None)
    session = _get_session()
    vms = session.xenapi.VM.get_all_records()
    ret = {}
    found = False
    for vm in vms:
        record = session.xenapi.VM.get_record(vm)
        if record['is_a_template']:
            if record['name_label'] == name:
                found = True
                # log.debug(record['name_label'])
                session.xenapi.VM.destroy(vm)
                ret[name] = {'status': 'destroyed'}
    if not found:
        ret[name] = {'status': 'not found'}
    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
159452
def purge(name, delete_key=True):
    '''
    
    '''
    ret = {}
    client = salt.client.get_local_client(__opts__['conf_file'])
    data = vm_info(name, quiet=True)
    if not data:
        __jid_event__.fire_event({'error': 'Failed to find VM {0} to purge'.format(name)}, 'progress')
        return 'fail'
    host = next(six.iterkeys(data))
    try:
        cmd_ret = client.cmd_iter(
                host,
                'virt.purge',
                [name, True],
                timeout=600)
    except SaltClientError as client_error:
        return 'Virtual machine {0} could not be purged: {1}'.format(name, client_error)

    for comp in cmd_ret:
        ret.update(comp)

    if delete_key:
        log.debug('Deleting key %s', name)
        skey = salt.key.Key(__opts__)
        skey.delete_key(name)
    __jid_event__.fire_event({'message': 'Purged VM {0}'.format(name)}, 'progress')
    return 'good'
488154
def stop(vm_):
    '''
    
    '''
    with _get_xapi_session() as xapi:
        vm_uuid = _get_label_uuid(xapi, 'VM', vm_)
        if vm_uuid is False:
            return False
        try:
            xapi.VM.hard_shutdown(vm_uuid)
            return True
        except Exception:
            return False
180864
def stop(args):
    
    p = OptionParser(stop.__doc__)
    p.add_option("--profile", default="mvrad-datasci-role", help="Profile name")
    opts, args = p.parse_args(args)

    if len(args) != 0:
        sys.exit(not p.print_help())

    role(["htang"])
    session = boto3.Session(profile_name=opts.profile)
    client = session.client('ec2')
    s = InstanceSkeleton()

    # Make sure the instance id is NOT empty
    instance_id = s.instance_id
    if instance_id == "":
        logging.error("Cannot find instance_id {}".format(instance_id))
        sys.exit(1)

    block_device_mappings = []
    for volume in s.volumes:
        block_device_mappings.append(
            {
                "DeviceName": volume["Device"],
                "NoDevice": ""
            }
        )

    new_image_name = "htang-dev-{}-{}".format(timestamp(), int(time.time()))
    response = client.create_image(
        InstanceId=instance_id,
        Name=new_image_name,
        BlockDeviceMappings=block_device_mappings
    )
    print(response, file=sys.stderr)
    new_image_id = response["ImageId"]

    image_status = ""
    while image_status != "available":
        logging.debug("Waiting for image to be ready")
        time.sleep(10)
        response = client.describe_images(ImageIds=[new_image_id])
        image_status = response["Images"][0]["State"]

    # Delete old image, snapshot and shut down instance
    old_image_id = s.image_id
    response = client.describe_images(ImageIds=[old_image_id])
    old_snapshot_id = response["Images"][0]["BlockDeviceMappings"][0]["Ebs"]["SnapshotId"]
    response = client.deregister_image(ImageId=old_image_id)
    print(response, file=sys.stderr)
    response = client.delete_snapshot(SnapshotId=old_snapshot_id)
    print(response, file=sys.stderr)
    response = client.terminate_instances(InstanceIds=[instance_id])
    print(response, file=sys.stderr)

    # Save new image id
    s.save_image_id(new_image_id)
    s.save_instance_id("", "")
1093713
def delete_fwrule(kwargs=None, call=None):
    '''
    
    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The delete_fwrule function must be called with -f or --function.'
        )

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

    name = kwargs['name']
    conn = get_conn()

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

    try:
        result = conn.ex_destroy_firewall(
            conn.ex_get_firewall(name)
        )
    except ResourceNotFoundError as exc:
        log.error(
            'Rule %s was not found. Exception was: %s',
            name, exc, exc_info_on_loglevel=logging.DEBUG
        )
        return False

    __utils__['cloud.fire_event'](
        'event',
        'deleted firewall',
        'salt/cloud/firewall/deleted',
        args={
            'name': name,
        },
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )
    return result
234702
def stop(self):
        

        status = yield from self.get_status()
        if status != "inactive":
            try:
                yield from self._hypervisor.send('vm stop "{name}"'.format(name=self._name))
            except DynamipsError as e:
                log.warn("Could not stop {}: {}".format(self._name, e))
            self.status = "stopped"
            log.info('Router "{name}" [{id}] has been stopped'.format(name=self._name, id=self._id))
        if self._memory_watcher:
            self._memory_watcher.close()
            self._memory_watcher = None
        yield from self.save_configs()
651916
def reset(name):
    '''
    
    '''
    ret = {}
    client = salt.client.get_local_client(__opts__['conf_file'])
    data = vm_info(name, quiet=True)
    if not data:
        __jid_event__.fire_event({'message': 'Failed to find VM {0} to reset'.format(name)}, 'progress')
        return 'fail'
    host = next(six.iterkeys(data))
    try:
        cmd_ret = client.cmd_iter(
                host,
                'virt.reset',
                [name],
                timeout=600)
        for comp in cmd_ret:
            ret.update(comp)
        __jid_event__.fire_event({'message': 'Reset VM {0}'.format(name)}, 'progress')
    except SaltClientError as client_error:
        print(client_error)
    return ret
597963
def stop_agent(agent_name)
      res = false
      if (pid_file = AgentConfig.pid_file(agent_name))
        name = human_readable_name(agent_name, pid_file.identity)
        if (pid = pid_file.read_pid[:pid])
          begin
            Process.kill('TERM', pid)
            res = true
            puts "#{name} stopped"
          rescue Errno::ESRCH
            puts "#{name} not running"
          end
        elsif File.file?(pid_file.to_s)
          puts "Invalid pid file '#{pid_file.to_s}' content: #{IO.read(pid_file.to_s)}"
        else
          puts "#{name} not running"
        end
      else
        puts "Non-existent pid file for #{agent_name}"
      end
      res
    end
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()
513501
def destroy(vm_, call=None):
    ''''''
    destroy_opt = __opts__.get('destroy', False)
    profiles = __opts__.get('profiles', {})
    profile = __opts__.get('profile',
                           __opts__.get('internal_lxc_profile', []))
    path = None
    if profile and profile in profiles:
        path = profiles[profile].get('path', None)
    action = __opts__.get('action', '')
    if action != 'destroy' and not destroy_opt:
        raise SaltCloudSystemExit(
            'The destroy action must be called with -d, --destroy, '
            '-a or --action.'
        )
    if not get_configured_provider():
        return
    ret = {'comment': '{0} was not found'.format(vm_),
           'result': False}
    if _salt('lxc.info', vm_, path=path):
        __utils__['cloud.fire_event'](
            'event',
            'destroying instance',
            'salt/cloud/{0}/destroying'.format(vm_),
            args={'name': vm_, 'instance_id': vm_},
            sock_dir=__opts__['sock_dir'],
            transport=__opts__['transport']
        )
        cret = _salt('lxc.destroy', vm_, stop=True, path=path)
        ret['result'] = cret['result']
        if ret['result']:
            ret['comment'] = '{0} was destroyed'.format(vm_)
            __utils__['cloud.fire_event'](
                'event',
                'destroyed instance',
                'salt/cloud/{0}/destroyed'.format(vm_),
                args={'name': vm_, 'instance_id': vm_},
                sock_dir=__opts__['sock_dir'],
                transport=__opts__['transport']
            )
            if __opts__.get('update_cachedir', False) is True:
                __utils__['cloud.delete_minion_cachedir'](vm_, __active_provider_name__.split(':')[0], __opts__)
    return ret
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
243762
def halted(name, graceful=True):
    '''
    

    '''
    ret = {'name': name,
           'changes': {},
           'result': None,
           'comment': ''}

    zones = __salt__['zoneadm.list'](installed=True)
    if name in zones:
        ## zone exists
        if zones[name]['state'] != 'running':
            ## zone is not running
            ret['result'] = True
            ret['comment'] = 'Zone {0} already halted'.format(name)
        else:
            ## try and halt the zone
            if not __opts__['test']:
                zoneadm_res = __salt__['zoneadm.shutdown'](name) if graceful else __salt__['zoneadm.halt'](name)
            if __opts__['test'] or zoneadm_res['status']:
                ret['result'] = True
                ret['changes'][name] = 'halted'
                ret['comment'] = 'Zone {0} halted'.format(name)
            else:
                ret['result'] = False
                ret['comment'] = 'Failed to halt {0}'.format(name)
    else:
        ## zone does not exist
        ret['comment'] = []
        ret['comment'].append(
            'The zone {0} is not in the installed state.'.format(name)
        )
        for zone in zones:
            if zones[zone]['uuid'] == name:
                ret['comment'].append(
                    'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
                        zone,
                        name,
                    )
                )
        ## note: a non existing zone is not running, we do not consider this a failure
        ret['result'] = True
        ret['comment'] = "\n".join(ret['comment'])

    return ret