Manages Ghost IOS support.

        :param vm: VM instance
190116
def _set_ghost_ios(self, vm):
        

        if not vm.mmap:
            raise DynamipsError("mmap support is required to enable ghost IOS support")

        if vm.platform == "c7200" and vm.npe == "npe-g2":
            log.warning("Ghost IOS is not supported for c7200 with NPE-G2")
            return

        ghost_file = vm.formatted_ghost_file()

        module_workdir = vm.project.module_working_directory(self.module_name.lower())
        ghost_file_path = os.path.join(module_workdir, ghost_file)
        if ghost_file_path not in self._ghost_files:
            # create a new ghost IOS instance
            ghost_id = str(uuid4())
            ghost = Router("ghost-" + ghost_file, ghost_id, vm.project, vm.manager, platform=vm.platform, hypervisor=vm.hypervisor, ghost_flag=True)
            try:
                yield from ghost.create()
                yield from ghost.set_image(vm.image)
                yield from ghost.set_ghost_status(1)
                yield from ghost.set_ghost_file(ghost_file_path)
                yield from ghost.set_ram(vm.ram)
                try:
                    yield from ghost.start()
                    yield from ghost.stop()
                    self._ghost_files.add(ghost_file_path)
                except DynamipsError:
                    raise
                finally:
                    yield from ghost.clean_delete()
            except DynamipsError as e:
                log.warn("Could not create ghost instance: {}".format(e))

        if vm.ghost_file != ghost_file and os.path.isfile(ghost_file_path):
            # set the ghost file to the router
            yield from vm.set_ghost_status(2)
            yield from vm.set_ghost_file(ghost_file_path)
283273
def legacy_networking(self, legacy_networking):
        

        if legacy_networking:
            log.info('QEMU VM "{name}" [{id}] has enabled legacy networking'.format(name=self._name, id=self._id))
        else:
            log.info('QEMU VM "{name}" [{id}] has disabled legacy networking'.format(name=self._name, id=self._id))
        self._legacy_networking = legacy_networking
271764
def get_vm_by_name(content, name, regex=False):
    '''
    
    '''
    return get_object_by_name(content, vim.VirtualMachine, name, regex)
1281921
def execute(node):
    
    with hide('everything'):
        virt = json.loads(sudo('ohai virtualization'))
    if not len(virt) or virt[0][1] != "host":
        # It may work for virtualization solutions other than Xen
        print("This node is not a Xen host, doing nothing")
        return
    node['virtualization'] = {
        'role': 'host',
        'system': 'xen',
        'vms': [],
    }
    # VMs
    with hide('everything'):
        vm_list = sudo("xm list")
    for vm in vm_list.split("\n")[2:]:
        data = vm.split()
        if len(data) != 6:
            break
        node['virtualization']['vms'].append({
            'fqdn': data[0], 'RAM': data[2], 'cpus': data[3]})
    print("Found {0} VMs for this Xen host".format(
          len(node['virtualization']['vms'])))
    # Save node file and remove the returned temp file
    del node['name']
    os.remove(chef.save_config(node, True))
47102
def get_vm(self, at_header: BlockHeader=None) -> 'BaseVM':
        
        header = self.ensure_header(at_header)
        vm_class = self.get_vm_class_for_block_number(header.block_number)
        return vm_class(header=header, chaindb=self.chaindb)
1365112
def _attach(cls, iface_id, vm_id):
        
        oper = cls.call('hosting.vm.iface_attach', vm_id, iface_id)
        return oper
922064
def delete_vm(self, userid):
        """"""
        LOG.info("Begin to delete vm %s", userid)
        self._smtclient.delete_vm(userid)

        # remove userid from smapi namelist
        self._smtclient.namelist_remove(self._namelist, userid)
        LOG.info("Complete delete vm %s", userid)
364682
def resume(self):
        

        yield from self._control_vm("resume")
        self.status = "started"
        log.info("VirtualBox VM '{name}' [{id}] resumed".format(name=self.name, id=self.id))
1311309
def manage_extant(self, **kwargs):
        '''
        '''

        self._check_device_number(kwargs['devices'])
        self.trust_domain = TrustDomain(
            devices=kwargs['devices'],
            partition=kwargs['device_group_partition']
        )
        self.device_group = DeviceGroup(**kwargs)
        self.cluster = Cluster(**kwargs)
486746
def vm_absent(name, archive=False):
    '''
    

    '''
    name = name.lower()
    ret = {'name': name,
           'changes': {},
           'result': None,
           'comment': ''}

    if name not in __salt__['vmadm.list'](order='hostname'):
        # we're good
        ret['result'] = True
        ret['comment'] = 'vm {0} is absent'.format(name)
    else:
        # delete vm
        if not __opts__['test']:
            # set archive to true if needed
            if archive:
                __salt__['vmadm.update'](vm=name, key='hostname', archive_on_delete=True)

            ret['result'] = __salt__['vmadm.delete'](name, key='hostname')
        else:
            ret['result'] = True

        if not isinstance(ret['result'], bool) and ret['result'].get('Error'):
            ret['result'] = False
            ret['comment'] = 'failed to delete vm {0}'.format(name)
        else:
            ret['comment'] = 'vm {0} deleted'.format(name)
            ret['changes'][name] = None

    return ret
703461
def power_cycle_vm(virtual_machine, action='on'):
    '''
    
    '''
    if action == 'on':
        try:
            task = virtual_machine.PowerOn()
            task_name = 'power on'
        except vim.fault.NoPermission as exc:
            log.exception(exc)
            raise salt.exceptions.VMwareApiError(
                'Not enough permissions. Required privilege: '
                '{}'.format(exc.privilegeId))
        except vim.fault.VimFault as exc:
            log.exception(exc)
            raise salt.exceptions.VMwareApiError(exc.msg)
        except vmodl.RuntimeFault as exc:
            log.exception(exc)
            raise salt.exceptions.VMwareRuntimeError(exc.msg)
    elif action == 'off':
        try:
            task = virtual_machine.PowerOff()
            task_name = 'power off'
        except vim.fault.NoPermission as exc:
            log.exception(exc)
            raise salt.exceptions.VMwareApiError(
                'Not enough permissions. Required privilege: '
                '{}'.format(exc.privilegeId))
        except vim.fault.VimFault as exc:
            log.exception(exc)
            raise salt.exceptions.VMwareApiError(exc.msg)
        except vmodl.RuntimeFault as exc:
            log.exception(exc)
            raise salt.exceptions.VMwareRuntimeError(exc.msg)
    else:
        raise salt.exceptions.ArgumentValueError('The given action is not supported')
    try:
        wait_for_task(task, get_managed_object_name(virtual_machine), task_name)
    except salt.exceptions.VMwareFileNotFoundError as exc:
        raise salt.exceptions.VMwarePowerOnError(' '.join([
            'An error occurred during power',
            'operation, a file was not found: {0}'.format(exc)]))
    return virtual_machine
399558
def set_ghost_file(self, ghost_file):
        

        yield from self._hypervisor.send('vm set_ghost_file "{name}" {ghost_file}'.format(name=self._name,
                                                                                          ghost_file=shlex.quote(ghost_file)))

        log.info('Router "{name}" [{id}]: ghost file set to {ghost_file}'.format(name=self._name,
                                                                                 id=self._id,
                                                                                 ghost_file=ghost_file))

        self._ghost_file = ghost_file
1119323
def update(cls, id, memory, cores, console, password, background,
               max_memory):
        """"""
        if not background and not cls.intty():
            background = True

        vm_params = {}

        if memory:
            vm_params['memory'] = memory

        if cores:
            vm_params['cores'] = cores

        if console:
            vm_params['console'] = console

        if password:
            vm_params['password'] = password

        if max_memory:
            vm_params['vm_max_memory'] = max_memory

        result = cls.call('hosting.vm.update', cls.usable_id(id), vm_params)
        if background:
            return result

        # interactive mode, run a progress bar
        cls.echo('Updating your Virtual Machine %s.' % id)
        cls.display_progress(result)
490549
def start(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_start_node(node)
    log.debug('Status of Cloud VM: %s', status)

    return status
1172010
def cli(env, **args):
    """"""

    vsi = SoftLayer.VSManager(env.client)
    _validate_args(env, args)
    create_args = _parse_create_args(env.client, args)
    test = args.get('test', False)
    do_create = not (args.get('export') or test)

    if do_create:
        if not (env.skip_confirmations or formatting.confirm(
                "This action will incur charges on your account. Continue?")):
            raise exceptions.CLIAbort('Aborting virtual server order.')

    if args.get('export'):
        export_file = args.pop('export')
        template.export_to_template(export_file, args, exclude=['wait', 'test'])
        env.fout('Successfully exported options to a template file.')

    else:
        result = vsi.order_guest(create_args, test)
        output = _build_receipt_table(result, args.get('billing'), test)

        if do_create:
            env.fout(_build_guest_table(result))
        env.fout(output)

        if args.get('wait'):
            virtual_guests = utils.lookup(result, 'orderDetails', 'virtualGuests')
            guest_id = virtual_guests[0]['id']
            click.secho("Waiting for %s to finish provisioning..." % guest_id, fg='green')
            ready = vsi.wait_for_ready(guest_id, args.get('wait') or 1)
            if ready is False:
                env.out(env.fmt(output))
                raise exceptions.CLIHalt(code=1)
667380
def set_vm_status(self, boot_on_next_reset):
        
        data = {
            "Oem": {
                "Hpe": {
                    "BootOnNextServerReset": boot_on_next_reset
                    }
                }
            }
        self._conn.patch(self.path, data=data)
1151743
def list_vms(self, allow_clone=False):
        

        vbox_vms = []
        result = yield from self.execute("list", ["vms"])
        for line in result:
            if len(line) == 0 or line[0] != '"' or line[-1:] != "}":
                continue  # Broken output (perhaps a carriage return in VM name)
            vmname, _ = line.rsplit(' ', 1)
            vmname = vmname.strip('"')
            if vmname == "<inaccessible>":
                continue  # ignore inaccessible VMs
            extra_data = yield from self.execute("getextradata", [vmname, "GNS3/Clone"])
            if allow_clone or len(extra_data) == 0 or not extra_data[0].strip() == "Value: yes":
                # get the amount of RAM
                info_results = yield from self.execute("showvminfo", [vmname, "--machinereadable"])
                ram = 0
                for info in info_results:
                    try:
                        name, value = info.split('=', 1)
                        if name.strip() == "memory":
                            ram = int(value.strip())
                            break
                    except ValueError:
                        continue
                vbox_vms.append({"vmname": vmname, "ram": ram})
        return vbox_vms