Parse vm_present vm config
186447
def _parse_vmconfig(config, instances):
    '''
    
    '''
    vmconfig = None

    if isinstance(config, (salt.utils.odict.OrderedDict)):
        vmconfig = salt.utils.odict.OrderedDict()
        for prop in config:
            if prop not in instances:
                vmconfig[prop] = config[prop]
            else:
                if not isinstance(config[prop], (salt.utils.odict.OrderedDict)):
                    continue
                vmconfig[prop] = []
                for instance in config[prop]:
                    instance_config = config[prop][instance]
                    instance_config[instances[prop]] = instance
                    ## some property are lowercase
                    if 'mac' in instance_config:
                        instance_config['mac'] = instance_config['mac'].lower()
                    vmconfig[prop].append(instance_config)
    else:
        log.error('smartos.vm_present::parse_vmconfig - failed to parse')

    return vmconfig
516922
def _get_vms_from_directory(self, directory):
        

        vmware_vms = []
        log.info('Searching for VMware VMs in directory "{}"'.format(directory))
        for path, _, filenames in os.walk(directory):
            for filename in filenames:
                if os.path.splitext(filename)[1] == ".vmx":
                    vmx_path = os.path.join(path, filename)
                    log.debug('Reading VMware VMX file "{}"'.format(vmx_path))
                    try:
                        pairs = self.parse_vmware_file(vmx_path)
                        if "displayname" in pairs:
                            log.debug('Found VM named "{}"'.format(pairs["displayname"]))
                            vmware_vms.append({"vmname": pairs["displayname"], "vmx_path": vmx_path})
                    except OSError as e:
                        log.warning('Could not read VMware VMX file "{}": {}'.format(vmx_path, e))
                        continue
        return vmware_vms
477014
def vm_info(name, quiet=False):
    '''
    
    '''
    data = query(quiet=True)
    return _find_vm(name, data, quiet)
1338961
def avail_images(call=None):
    '''
    
    '''
    if call == 'action':
        raise SaltCloudSystemExit(
            'The avail_images function must be called with '
            '-f or --function, or with the --list-images option.'
        )

    templates = {}
    vm_properties = [
        "name",
        "config.template",
        "config.guestFullName",
        "config.hardware.numCPU",
        "config.hardware.memoryMB"
    ]

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

    for vm in vm_list:
        if "config.template" in vm and vm["config.template"]:
            templates[vm["name"]] = {
                'name': vm["name"],
                'guest_fullname': vm["config.guestFullName"] if "config.guestFullName" in vm else "N/A",
                'cpus': vm["config.hardware.numCPU"] if "config.hardware.numCPU" in vm else "N/A",
                'ram': vm["config.hardware.memoryMB"] if "config.hardware.memoryMB" in vm else "N/A"
            }

    return templates
789111
def load_vm_uuid_by_name(self, si, vcenter_data_model, vm_name):
        
        path = VMLocation.combine([vcenter_data_model.default_datacenter, vm_name])
        paths = path.split('/')
        name = paths[len(paths) - 1]
        path = VMLocation.combine(paths[:len(paths) - 1])
        vm = self.pv_service.find_vm_by_name(si, path, name)
        if not vm:
            raise ValueError('Could not find the vm in the given path: {0}/{1}'.format(path, name))

        if isinstance(vm, vim.VirtualMachine):
            return vm.config.uuid

        raise ValueError('The given object is not a vm: {0}/{1}'.format(path, name))
1090163
def get_size(vm_):
    '''
    
    '''
    sizes = avail_sizes()
    vm_size = six.text_type(config.get_cloud_config_value(
        'size', vm_, __opts__, search_global=False
    ))
    for size in sizes:
        if vm_size.lower() == sizes[size]['slug']:
            return sizes[size]['slug']
    raise SaltCloudNotFound(
        'The specified size, \'{0}\', could not be found.'.format(vm_size)
    )
552758
def get_vm_instances(instance_id=None):
    """"""
    return get_instances(device_owners=[n_const.DEVICE_OWNER_COMPUTE_PREFIX],
                         vnic_type=portbindings.VNIC_NORMAL,
                         instance_id=instance_id)
416214
def _check_virtualenv():
    
    from os import waitpid
    from subprocess import Popen, PIPE
    penvs = Popen("source /usr/local/bin/virtualenvwrapper.sh; workon",
                 shell=True, executable="/bin/bash", stdout=PIPE, stderr=PIPE)
    waitpid(penvs.pid, 0)
    envs = penvs.stdout.readlines()
    enverr = penvs.stderr.readlines()
    result = (settings.venv + '\n') in envs and len(enverr) == 0

    vms("Find virtualenv: {}".format(' '.join(envs).replace('\n', '')))
    vms("Find virtualenv | stderr: {}".format(' '.join(enverr)))
    
    if not result:
        info(envs)
        err("The virtualenv '{}' does not exist; can't use CI server.".format(settings.venv))
        if len(enverr) > 0:
            map(err, enverr)
    return result
975488
def _parse_config(self):
        
        config = self.get_block('mlag configuration')
        cfg = dict()
        cfg.update(self._parse_domain_id(config))
        cfg.update(self._parse_local_interface(config))
        cfg.update(self._parse_peer_address(config))
        cfg.update(self._parse_peer_link(config))
        cfg.update(self._parse_shutdown(config))
        return dict(config=cfg)
84562
def parse_yaml_config(yaml_config, repo_home):
    """"""
    config = collections.defaultdict(list)

    variables = {
        'DEFAULT_CONFIGS': os.path.join(os.path.dirname(__file__), 'configs'),
        'REPO_HOME': repo_home,
    }

    for name, data in yaml_config.items():
        command = _replace_variables([data['command']], variables)[0]
        requirements = _replace_variables(
            data.get('requirements', []), variables)
        arguments = _replace_variables(data.get('arguments', []), variables)

        not_found_programs = utils.programs_not_in_path([command] +
                                                        requirements)
        if not_found_programs:
            linter_command = Partial(missing_requirements_command,
                                     not_found_programs, data['installation'])
        else:
            linter_command = Partial(lint_command, name, command, arguments,
                                     data['filter'])
        for extension in data['extensions']:
            config[extension].append(linter_command)

    return config
1083468
def _get_vm_state(self):
        

        results = yield from self.manager.execute("showvminfo", [self._vmname, "--machinereadable"])
        for info in results:
            if '=' in info:
                name, value = info.split('=', 1)
                if name == "VMState":
                    return value.strip('"')
        raise VirtualBoxError("Could not get VM state for {}".format(self._vmname))
440342
def get_default_config(self):
        
        config = super(VMSDomsCollector, self).get_default_config()
        config.update({
            'path':     'vms'
        })
        return config
1351183
def vm_configured(name, vm_name, cpu, memory, image, version, interfaces,
                  disks, scsi_devices, serial_ports, datacenter, datastore,
                  placement, cd_dvd_drives=None, sata_controllers=None,
                  advanced_configs=None, template=None, tools=True,
                  power_on=False, deploy=False):
    '''
    
    '''
    result = {'name': name,
              'result': None,
              'changes': {},
              'comment': ''}

    log.trace('Validating virtual machine configuration')
    schema = ESXVirtualMachineConfigSchema.serialize()
    log.trace('schema = %s', schema)
    try:
        jsonschema.validate({'vm_name': vm_name,
                             'cpu': cpu,
                             'memory': memory,
                             'image': image,
                             'version': version,
                             'interfaces': interfaces,
                             'disks': disks,
                             'scsi_devices': scsi_devices,
                             'serial_ports': serial_ports,
                             'cd_dvd_drives': cd_dvd_drives,
                             'sata_controllers': sata_controllers,
                             'datacenter': datacenter,
                             'datastore': datastore,
                             'placement': placement,
                             'template': template,
                             'tools': tools,
                             'power_on': power_on,
                             'deploy': deploy}, schema)
    except jsonschema.exceptions.ValidationError as exc:
        raise salt.exceptions.InvalidConfigError(exc)

    service_instance = __salt__['vsphere.get_service_instance_via_proxy']()
    try:
        __salt__['vsphere.get_vm'](vm_name, vm_properties=['name'],
                                   service_instance=service_instance)
    except salt.exceptions.VMwareObjectRetrievalError:
        vm_file = __salt__['vsphere.get_vm_config_file'](
            vm_name, datacenter,
            placement, datastore,
            service_instance=service_instance)
        if vm_file:
            if __opts__['test']:
                result.update({'comment': 'The virtual machine {0}'
                                          ' will be registered.'.format(vm_name)})
                __salt__['vsphere.disconnect'](service_instance)
                return result
            result = vm_registered(vm_name, datacenter, placement,
                                   vm_file, power_on=power_on)
            return result
        else:
            if __opts__['test']:
                result.update({'comment': 'The virtual machine {0}'
                                          ' will be created.'.format(vm_name)})
                __salt__['vsphere.disconnect'](service_instance)
                return result
            if template:
                result = vm_cloned(name)
            else:
                result = vm_created(name, vm_name, cpu, memory, image, version,
                                    interfaces, disks, scsi_devices,
                                    serial_ports, datacenter, datastore,
                                    placement, cd_dvd_drives=cd_dvd_drives,
                                    advanced_configs=advanced_configs,
                                    power_on=power_on)
            return result

    result = vm_updated(name, vm_name, cpu, memory, image, version,
                        interfaces, disks, scsi_devices,
                        serial_ports, datacenter, datastore,
                        cd_dvd_drives=cd_dvd_drives,
                        sata_controllers=sata_controllers,
                        advanced_configs=advanced_configs,
                        power_on=power_on)
    __salt__['vsphere.disconnect'](service_instance)

    log.trace(result)
    return result
666151
def get_host_vsan_system(service_instance, host_ref, hostname=None):
    '''
    
    '''
    if not hostname:
        hostname = salt.utils.vmware.get_managed_object_name(host_ref)
    traversal_spec = vmodl.query.PropertyCollector.TraversalSpec(
        path='configManager.vsanSystem',
        type=vim.HostSystem,
        skip=False)
    objs = salt.utils.vmware.get_mors_with_properties(
        service_instance, vim.HostVsanSystem, property_list=['config.enabled'],
        container_ref=host_ref, traversal_spec=traversal_spec)
    if not objs:
        raise VMwareObjectRetrievalError('Host\'s \'{0}\' VSAN system was '
                                         'not retrieved'.format(hostname))
    log.trace('[%s] Retrieved VSAN system', hostname)
    return objs[0]['object']
968506
async def get(self):
        
        shepherd = self.request.app.vmshepherd
        data = {'presets': {}, 'config': shepherd.config}
        presets = await shepherd.preset_manager.list_presets()
        runtime = shepherd.runtime_manager
        for name in presets:
            preset = shepherd.preset_manager.get_preset(name)
            data['presets'][name] = {
                'preset': preset,
                'vms': preset.vms,
                'runtime': await runtime.get_preset_data(name),
                'vmshepherd_id': shepherd.instance_id,
                'now': time.time()
            }
        return data
771450
def get_ssh_gateway_config(vm_):
    '''
    
    '''
    ssh_gateway = config.get_cloud_config_value(
        'ssh_gateway', vm_, __opts__, default=None,
        search_global=False
    )

    # Check to see if a SSH Gateway will be used.
    if not isinstance(ssh_gateway, six.string_types):
        return None

    # Create dictionary of configuration items

    # ssh_gateway
    ssh_gateway_config = {'ssh_gateway': ssh_gateway}

    # ssh_gateway_port
    ssh_gateway_config['ssh_gateway_port'] = config.get_cloud_config_value(
        'ssh_gateway_port', vm_, __opts__, default=None,
        search_global=False
    )

    # ssh_gateway_username
    ssh_gateway_config['ssh_gateway_user'] = config.get_cloud_config_value(
        'ssh_gateway_username', vm_, __opts__, default=None,
        search_global=False
    )

    # ssh_gateway_private_key
    ssh_gateway_config['ssh_gateway_key'] = config.get_cloud_config_value(
        'ssh_gateway_private_key', vm_, __opts__, default=None,
        search_global=False
    )

    # ssh_gateway_password
    ssh_gateway_config['ssh_gateway_password'] = config.get_cloud_config_value(
        'ssh_gateway_password', vm_, __opts__, default=None,
        search_global=False
    )

    # ssh_gateway_command
    ssh_gateway_config['ssh_gateway_command'] = config.get_cloud_config_value(
        'ssh_gateway_command', vm_, __opts__, default=None,
        search_global=False
    )

    # Check if private key exists
    key_filename = ssh_gateway_config['ssh_gateway_key']
    if key_filename is not None and not os.path.isfile(key_filename):
        raise SaltCloudConfigError(
            'The defined ssh_gateway_private_key \'{0}\' does not exist'
            .format(key_filename)
        )
    elif (
        key_filename is None and
        not ssh_gateway_config['ssh_gateway_password']
    ):
        raise SaltCloudConfigError(
            'No authentication method. Please define: '
            ' ssh_gateway_password or ssh_gateway_private_key'
        )

    return ssh_gateway_config
272558
def _create_vm_config(self, interface):
        
        # Split image ID into it's components.
        self._process_image_id()

        hardware_profile = {
            'vm_size': self.instance_type or AZURE_DEFAULT_TYPE
        }

        network_profile = {
            'network_interfaces': [{
                'id': interface.id,
                'primary': True
            }]
        }

        storage_profile = self._create_storage_profile()

        os_profile = {
            'computer_name': self.running_instance_id,
            'admin_username': self.ssh_user,
            'linux_configuration': {
                'disable_password_authentication': True,
                'ssh': {
                    'public_keys': [{
                        'path': '/home/{0}/.ssh/authorized_keys'.format(
                            self.ssh_user
                        ),
                        'key_data': self.ssh_public_key
                    }]
                }
            }
        }

        vm_config = {
            'location': self.region,
            'os_profile': os_profile,
            'hardware_profile': hardware_profile,
            'storage_profile': storage_profile,
            'network_profile': network_profile
        }

        return vm_config