Create/Verify the VMs in the VM data
482470
def create_all(self):
        '''
        
        '''
        ret = []

        for vm_name, vm_details in six.iteritems(self.opts['profiles']):
            ret.append(
                {vm_name: self.create(vm_details)}
            )

        return ret
762887
def create(vm_):
    '''
    
    '''
    try:
        # Check for required profile parameters before sending any API calls.
        if vm_['profile'] and config.is_profile_configured(__opts__,
                                                           __active_provider_name__ or 'azure',
                                                           vm_['profile'],
                                                           vm_=vm_) is False:
            return False
    except AttributeError:
        pass

    __utils__['cloud.fire_event'](
        'event',
        'starting create',
        'salt/cloud/{0}/creating'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    log.info('Creating Cloud VM %s', vm_['name'])
    conn = get_conn()

    label = vm_.get('label', vm_['name'])
    service_name = vm_.get('service_name', vm_['name'])
    service_kwargs = {
        'service_name': service_name,
        'label': label,
        'description': vm_.get('desc', vm_['name']),
    }

    loc_error = False
    if 'location' in vm_:
        if 'affinity_group' in vm_:
            loc_error = True
        else:
            service_kwargs['location'] = vm_['location']
    elif 'affinity_group' in vm_:
        service_kwargs['affinity_group'] = vm_['affinity_group']
    else:
        loc_error = True

    if loc_error:
        raise SaltCloudSystemExit(
            'Either a location or affinity group must be specified, but not both'
        )

    ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
                                             default=22, search_global=True)

    ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
        name='SSH',
        protocol='TCP',
        port=ssh_port,
        local_port=22,
    )

    network_config = azure.servicemanagement.ConfigurationSet()
    network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
    network_config.configuration_set_type = 'NetworkConfiguration'

    if 'win_username' in vm_:
        system_config = azure.servicemanagement.WindowsConfigurationSet(
            computer_name=vm_['name'],
            admin_username=vm_['win_username'],
            admin_password=vm_['win_password'],
        )

        smb_port = '445'
        if 'smb_port' in vm_:
            smb_port = vm_['smb_port']

        smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
            name='SMB',
            protocol='TCP',
            port=smb_port,
            local_port=smb_port,
        )

        network_config.input_endpoints.input_endpoints.append(smb_endpoint)

        # Domain and WinRM configuration not yet supported by Salt Cloud
        system_config.domain_join = None
        system_config.win_rm = None

    else:
        system_config = azure.servicemanagement.LinuxConfigurationSet(
            host_name=vm_['name'],
            user_name=vm_['ssh_username'],
            user_password=vm_['ssh_password'],
            disable_ssh_password_authentication=False,
        )

    # TODO: Might need to create a storage account
    media_link = vm_['media_link']
    # TODO: Probably better to use more than just the name in the media_link
    media_link += '/{0}.vhd'.format(vm_['name'])
    os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)

    vm_kwargs = {
        'service_name': service_name,
        'deployment_name': service_name,
        'deployment_slot': vm_['slot'],
        'label': label,
        'role_name': vm_['name'],
        'system_config': system_config,
        'os_virtual_hard_disk': os_hd,
        'role_size': vm_['size'],
        'network_config': network_config,
    }

    if 'virtual_network_name' in vm_:
        vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
        if 'subnet_name' in vm_:
            network_config.subnet_names.append(vm_['subnet_name'])

    log.debug('vm_kwargs: %s', vm_kwargs)

    event_kwargs = {'service_kwargs': service_kwargs.copy(),
                    'vm_kwargs': vm_kwargs.copy()}
    del event_kwargs['vm_kwargs']['system_config']
    del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
    del event_kwargs['vm_kwargs']['network_config']
    __utils__['cloud.fire_event'](
        'event',
        'requesting instance',
        'salt/cloud/{0}/requesting'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )
    log.debug('vm_kwargs: %s', vm_kwargs)

    # Azure lets you open winrm on a new VM
    # Can open up specific ports in Azure; but not on Windows
    try:
        conn.create_hosted_service(**service_kwargs)
    except AzureConflictHttpError:
        log.debug('Cloud service already exists')
    except Exception as exc:
        error = 'The hosted service name is invalid.'
        if error in six.text_type(exc):
            log.error(
                'Error creating %s on Azure.\n\n'
                'The hosted service name is invalid. The name can contain '
                'only letters, numbers, and hyphens. The name must start with '
                'a letter and must end with a letter or a number.',
                vm_['name'],
                # Show the traceback if the debug logging level is enabled
                exc_info_on_loglevel=logging.DEBUG
            )
        else:
            log.error(
                'Error creating %s on Azure\n\n'
                'The following exception was thrown when trying to '
                'run the initial deployment: \n%s',
                vm_['name'], exc,
                # Show the traceback if the debug logging level is enabled
                exc_info_on_loglevel=logging.DEBUG
            )
        return False
    try:
        result = conn.create_virtual_machine_deployment(**vm_kwargs)
        log.debug('Request ID for machine: %s', result.request_id)
        _wait_for_async(conn, result.request_id)
    except AzureConflictHttpError:
        log.debug('Conflict error. The deployment may already exist, trying add_role')
        # Deleting two useless keywords
        del vm_kwargs['deployment_slot']
        del vm_kwargs['label']
        del vm_kwargs['virtual_network_name']
        result = conn.add_role(**vm_kwargs)
        _wait_for_async(conn, result.request_id)
    except Exception as exc:
        error = 'The hosted service name is invalid.'
        if error in six.text_type(exc):
            log.error(
                'Error creating %s on Azure.\n\n'
                'The VM name is invalid. The name can contain '
                'only letters, numbers, and hyphens. The name must start with '
                'a letter and must end with a letter or a number.',
                vm_['name'],
                # Show the traceback if the debug logging level is enabled
                exc_info_on_loglevel=logging.DEBUG
            )
        else:
            log.error(
                'Error creating %s on Azure.\n\n'
                'The Virtual Machine could not be created. If you '
                'are using an already existing Cloud Service, '
                'make sure you set up the `port` variable corresponding '
                'to the SSH port exists and that the port number is not '
                'already in use.\nThe following exception was thrown when trying to '
                'run the initial deployment: \n%s',
                vm_['name'], exc,
                # Show the traceback if the debug logging level is enabled
                exc_info_on_loglevel=logging.DEBUG
            )
        return False

    def wait_for_hostname():
        '''
        Wait for the IP address to become available
        '''
        try:
            conn.get_role(service_name, service_name, vm_['name'])
            data = show_instance(vm_['name'], call='action')
            if 'url' in data and data['url'] != six.text_type(''):
                return data['url']
        except AzureMissingResourceHttpError:
            pass
        time.sleep(1)
        return False

    hostname = salt.utils.cloud.wait_for_fun(
        wait_for_hostname,
        timeout=config.get_cloud_config_value(
            'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
    )

    if not hostname:
        log.error('Failed to get a value for the hostname.')
        return False

    vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
    vm_['password'] = config.get_cloud_config_value(
        'ssh_password', vm_, __opts__
    )
    ret = __utils__['cloud.bootstrap'](vm_, __opts__)

    # Attaching volumes
    volumes = config.get_cloud_config_value(
        'volumes', vm_, __opts__, search_global=True
    )
    if volumes:
        __utils__['cloud.fire_event'](
            'event',
            'attaching volumes',
            'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
            args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
            sock_dir=__opts__['sock_dir'],
            transport=__opts__['transport']
        )

        log.info('Create and attach volumes to node %s', vm_['name'])
        created = create_attach_volumes(
            vm_['name'],
            {
                'volumes': volumes,
                'service_name': service_name,
                'deployment_name': vm_['name'],
                'media_link': media_link,
                'role_name': vm_['name'],
                'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
            },
            call='action'
        )
        ret['Attached Volumes'] = created

    data = show_instance(vm_['name'], call='action')
    log.info('Created Cloud VM \'%s\'', vm_)
    log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))

    ret.update(data)

    __utils__['cloud.fire_event'](
        'event',
        'created instance',
        'salt/cloud/{0}/created'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    return ret
1024722
def main():
   

   args = GetArgs()
   if args.password:
      password = args.password
   else:
      password = getpass.getpass(prompt='Enter password for host %s and user %s: ' % (args.host,args.user))

   try:
      vmnames = args.vmname
      if not len(vmnames):
         print("No virtual machine specified for poweron")
         sys.exit()

      context = None
      if hasattr(ssl, '_create_unverified_context'):
         context = ssl._create_unverified_context()
      si = SmartConnect(host=args.host,
                        user=args.user,
                        pwd=password,
                        port=int(args.port),
                        sslContext=context)
      if not si:
         print("Cannot connect to specified host using specified username and password")
         sys.exit()

      atexit.register(Disconnect, si)

      # Retreive the list of Virtual Machines from the inventory objects
      # under the rootFolder
      content = si.content
      objView = content.viewManager.CreateContainerView(content.rootFolder,
                                                        [vim.VirtualMachine],
                                                        True)
      vmList = objView.view
      objView.Destroy()

      # Find the vm and power it on
      tasks = [vm.PowerOn() for vm in vmList if vm.name in vmnames]

      # Wait for power on to complete
      WaitForTasks(tasks, si)

      print("Virtual Machine(s) have been powered on successfully")
   except vmodl.MethodFault as e:
      print("Caught vmodl fault : " + e.msg)
   except Exception as e:
      print("Caught Exception : " + str(e))
1243471
def create(gandi, name, vm, size, snapshotprofile, datacenter, source,
           background):
    
    try:
        gandi.datacenter.is_opened(datacenter, 'iaas')
    except DatacenterLimited as exc:
        gandi.echo('/!\ Datacenter %s will be closed on %s, '
                   'please consider using another datacenter.' %
                   (datacenter, exc.date))

    if vm:
        vm_dc = gandi.iaas.info(vm)
        vm_dc_id = vm_dc['datacenter_id']
        dc_id = int(gandi.datacenter.usable_id(datacenter))
        if vm_dc_id != dc_id:
            gandi.echo('/!\ VM %s datacenter will be used instead of %s.'
                       % (vm, datacenter))
        datacenter = vm_dc_id

    output_keys = ['id', 'type', 'step']
    name = name or randomstring('vdi')

    disk_type = 'data'
    oper = gandi.disk.create(name, vm, size, snapshotprofile, datacenter,
                             source, disk_type, background)

    if background:
        output_generic(gandi, oper, output_keys)

    return oper
766144
def check(self, radl):
        """"""

        if not radl.get_system_by_name(self.id):
            raise RADLParseException("Invalid system id in the deploy.", line=self.line)

        if self.vm_number < 0:
            raise RADLParseException("Invalid number of virtual machines to deploy.",
                                     line=self.line)
703544
def create_vnic_spec(device):
        
        nic_spec = vim.vm.device.VirtualDeviceSpec()
        nic_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
        nic_spec.device = device
        return nic_spec
1016482
def create(vm_):
    '''
    
    '''
    try:
        # Check for required profile parameters before sending any API calls.
        if (vm_['profile'] and
           config.is_profile_configured(__opts__,
                                        (__active_provider_name__ or
                                         'oneandone'),
                                        vm_['profile']) is False):
            return False
    except AttributeError:
        pass

    data = None
    conn = get_conn()
    hdds = []

    # Assemble the composite server object.
    server = _get_server(vm_)

    if not bool(server.specs['hardware']['fixed_instance_size_id'])\
        and not bool(server.specs['server_type'] == 'baremetal'):
        # Assemble the hdds object.
        hdds = _get_hdds(vm_)

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

    try:
        data = conn.create_server(server=server, hdds=hdds)

        _wait_for_completion(conn,
                             get_wait_timeout(vm_),
                             data['id'])
    except Exception as exc:  # pylint: disable=W0703
        log.error(
            'Error creating %s on 1and1\n\n'
            'The following exception was thrown by the 1and1 library '
            'when trying to run the initial deployment: \n%s',
            vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
        )
        return False

    vm_['server_id'] = data['id']
    password = data['first_password']

    def __query_node_data(vm_, data):
        '''
        Query node data until node becomes available.
        '''
        running = False
        try:
            data = show_instance(vm_['name'], 'action')
            if not data:
                return False
            log.debug(
                'Loaded node data for %s:\nname: %s\nstate: %s',
                vm_['name'],
                pprint.pformat(data['name']),
                data['status']['state']
            )
        except Exception as err:
            log.error(
                'Failed to get nodes list: %s', err,
                # Show the trackback if the debug logging level is enabled
                exc_info_on_loglevel=logging.DEBUG
            )
            # Trigger a failure in the wait for IP function
            return False

        running = data['status']['state'].lower() == 'powered_on'
        if not running:
            # Still not running, trigger another iteration
            return

        vm_['ssh_host'] = data['ips'][0]['ip']

        return data

    try:
        data = salt.utils.cloud.wait_for_ip(
            __query_node_data,
            update_args=(vm_, data),
            timeout=config.get_cloud_config_value(
                'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
            interval=config.get_cloud_config_value(
                'wait_for_ip_interval', vm_, __opts__, default=10),
        )
    except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
        try:
            # It might be already up, let's destroy it!
            destroy(vm_['name'])
        except SaltCloudSystemExit:
            pass
        finally:
            raise SaltCloudSystemExit(six.text_type(exc.message))

    log.debug('VM is now running')
    log.info('Created Cloud VM %s', vm_)
    log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))

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

    if 'ssh_host' in vm_:
        vm_['password'] = password
        vm_['key_filename'] = get_key_filename(vm_)
        ret = __utils__['cloud.bootstrap'](vm_, __opts__)
        ret.update(data)
        return ret
    else:
        raise SaltCloudSystemExit('A valid IP address was not found.')
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
1140367
def create(vm_):
    '''
    
    '''
    try:
        # Check for required profile parameters before sending any API calls.
        if vm_['profile'] and config.is_profile_configured(__opts__,
                                                           __active_provider_name__ or 'aliyun',
                                                           vm_['profile'],
                                                           vm_=vm_) is False:
            return False
    except AttributeError:
        pass

    __utils__['cloud.fire_event'](
        'event',
        'starting create',
        'salt/cloud/{0}/creating'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    log.info('Creating Cloud VM %s', vm_['name'])
    kwargs = {
        'name': vm_['name'],
        'size_id': get_size(vm_),
        'image_id': get_image(vm_),
        'region_id': __get_location(vm_),
        'securitygroup_id': get_securitygroup(vm_),
    }
    if 'vswitch_id' in vm_:
        kwargs['VSwitchId'] = vm_['vswitch_id']
    if 'internet_chargetype' in vm_:
        kwargs['InternetChargeType'] = vm_['internet_chargetype']
    if 'internet_maxbandwidthin' in vm_:
        kwargs['InternetMaxBandwidthIn'] = six.text_type(vm_['internet_maxbandwidthin'])
    if 'internet_maxbandwidthout' in vm_:
        kwargs['InternetMaxBandwidthOut'] = six.text_type(vm_['internet_maxbandwidthOut'])
    if 'hostname' in vm_:
        kwargs['HostName'] = vm_['hostname']
    if 'password' in vm_:
        kwargs['Password'] = vm_['password']
    if 'instance_name' in vm_:
        kwargs['InstanceName'] = vm_['instance_name']
    if 'systemdisk_category' in vm_:
        kwargs['SystemDisk.Category'] = vm_['systemdisk_category']

    __utils__['cloud.fire_event'](
        'event',
        'requesting instance',
        'salt/cloud/{0}/requesting'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    try:
        ret = create_node(kwargs)
    except Exception as exc:
        log.error(
            'Error creating %s on Aliyun ECS\n\n'
            'The following exception was thrown when trying to '
            'run the initial deployment: %s',
            vm_['name'], six.text_type(exc),
            # Show the traceback if the debug logging level is enabled
            exc_info_on_loglevel=logging.DEBUG
        )
        return False
    # repair ip address error and start vm
    time.sleep(8)
    params = {'Action': 'StartInstance',
              'InstanceId': ret}
    query(params)

    def __query_node_data(vm_name):
        data = show_instance(vm_name, call='action')
        if not data:
            # Trigger an error in the wait_for_ip function
            return False
        if data.get('PublicIpAddress', None) is not None:
            return data

    try:
        data = salt.utils.cloud.wait_for_ip(
            __query_node_data,
            update_args=(vm_['name'],),
            timeout=config.get_cloud_config_value(
                'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
            interval=config.get_cloud_config_value(
                'wait_for_ip_interval', vm_, __opts__, default=10),
        )
    except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
        try:
            # It might be already up, let's destroy it!
            destroy(vm_['name'])
        except SaltCloudSystemExit:
            pass
        finally:
            raise SaltCloudSystemExit(six.text_type(exc))

    if data['public_ips']:
        ssh_ip = data['public_ips'][0]
    elif data['private_ips']:
        ssh_ip = data['private_ips'][0]
    else:
        log.info('No available ip:cant connect to salt')
        return False
    log.debug('VM %s is now running', ssh_ip)
    vm_['ssh_host'] = ssh_ip

    # The instance is booted and accessible, let's Salt it!
    ret = __utils__['cloud.bootstrap'](vm_, __opts__)
    ret.update(data)

    log.info('Created Cloud VM \'%s\'', vm_['name'])
    log.debug(
        '\'%s\' VM creation details:\n%s',
        vm_['name'], pprint.pformat(data)
    )

    __utils__['cloud.fire_event'](
        'event',
        'created instance',
        'salt/cloud/{0}/created'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    return ret
425197
def vms(nictag):
    '''
    
    '''
    ret = {}
    cmd = 'nictagadm vms {0}'.format(nictag)
    res = __salt__['cmd.run_all'](cmd)
    retcode = res['retcode']
    if retcode != 0:
        ret['Error'] = res['stderr'] if 'stderr' in res else 'Failed to get list of vms.'
    else:
        ret = res['stdout'].splitlines()
    return ret
18829
def _provision_vm(name=None, session=None):
    '''
    
    '''
    if session is None:
        session = _get_session()
    log.info('Provisioning VM %s', name)
    vm = _get_vm(name, session)
    task = session.xenapi.Async.VM.provision(vm)
    _run_async_task(task, session)
30436
def create_node(vm_, newid):
    '''
    
    '''
    newnode = {}

    if 'technology' not in vm_:
        vm_['technology'] = 'openvz'  # default virt tech if none is given

    if vm_['technology'] not in ['qemu', 'openvz', 'lxc']:
        # Wrong VM type given
        log.error('Wrong VM type. Valid options are: qemu, openvz (proxmox3) or lxc (proxmox4)')
        raise SaltCloudExecutionFailure

    if 'host' not in vm_:
        # Use globally configured/default location
        vm_['host'] = config.get_cloud_config_value(
            'default_host', get_configured_provider(), __opts__, search_global=False
        )

    if vm_['host'] is None:
        # No location given for the profile
        log.error('No host given to create this VM on')
        raise SaltCloudExecutionFailure

    # Required by both OpenVZ and Qemu (KVM)
    vmhost = vm_['host']
    newnode['vmid'] = newid

    for prop in 'cpuunits', 'description', 'memory', 'onboot':
        if prop in vm_:  # if the property is set, use it for the VM request
            newnode[prop] = vm_[prop]

    if vm_['technology'] == 'openvz':
        # OpenVZ related settings, using non-default names:
        newnode['hostname'] = vm_['name']
        newnode['ostemplate'] = vm_['image']

        # optional VZ settings
        for prop in ['cpus', 'disk', 'ip_address', 'nameserver',
                     'password', 'swap', 'poolid', 'storage']:
            if prop in vm_:  # if the property is set, use it for the VM request
                newnode[prop] = vm_[prop]

    elif vm_['technology'] == 'lxc':
        # LXC related settings, using non-default names:
        newnode['hostname'] = vm_['name']
        newnode['ostemplate'] = vm_['image']

        static_props = ('cpuunits', 'cpulimit', 'rootfs', 'cores', 'description', 'memory',
                        'onboot', 'net0', 'password', 'nameserver', 'swap', 'storage', 'rootfs')
        for prop in _get_properties('/nodes/{node}/lxc',
                                    'POST',
                                    static_props):
            if prop in vm_:  # if the property is set, use it for the VM request
                newnode[prop] = vm_[prop]

        if 'pubkey' in vm_:
            newnode['ssh-public-keys'] = vm_['pubkey']

        # inform user the "disk" option is not supported for LXC hosts
        if 'disk' in vm_:
            log.warning('The "disk" option is not supported for LXC hosts and was ignored')

        # LXC specific network config
        # OpenVZ allowed specifying IP and gateway. To ease migration from
        # Proxmox 3, I've mapped the ip_address and gw to a generic net0 config.
        # If you need more control, please use the net0 option directly.
        # This also assumes a /24 subnet.
        if 'ip_address' in vm_ and 'net0' not in vm_:
            newnode['net0'] = 'bridge=vmbr0,ip=' + vm_['ip_address'] + '/24,name=eth0,type=veth'

            # gateway is optional and does not assume a default
            if 'gw' in vm_:
                newnode['net0'] = newnode['net0'] + ',gw=' + vm_['gw']

    elif vm_['technology'] == 'qemu':
        # optional Qemu settings
        static_props = (
            'acpi', 'cores', 'cpu', 'pool', 'storage', 'sata0', 'ostype', 'ide2', 'net0')
        for prop in _get_properties('/nodes/{node}/qemu',
                                    'POST',
                                    static_props):
            if prop in vm_:  # if the property is set, use it for the VM request
                newnode[prop] = vm_[prop]

    # The node is ready. Lets request it to be added
    __utils__['cloud.fire_event'](
        'event',
        'requesting instance',
        'salt/cloud/{0}/requesting'.format(vm_['name']),
        args={
            'kwargs': __utils__['cloud.filter_event']('requesting', newnode, list(newnode)),
        },
        sock_dir=__opts__['sock_dir'],
    )

    log.debug('Preparing to generate a node using these parameters: %s ', newnode)
    if 'clone' in vm_ and vm_['clone'] is True and vm_['technology'] == 'qemu':
        postParams = {}
        postParams['newid'] = newnode['vmid']

        for prop in 'description', 'format', 'full', 'name':
            if 'clone_' + prop in vm_:  # if the property is set, use it for the VM request
                postParams[prop] = vm_['clone_' + prop]

        if 'host' in vm_:
            postParams['target'] = vm_['host']

        try:
            int(vm_['clone_from'])
        except ValueError:
            if ':' in vm_['clone_from']:
                vmhost = vm_['clone_from'].split(':')[0]
                vm_['clone_from'] = vm_['clone_from'].split(':')[1]

        node = query('post', 'nodes/{0}/qemu/{1}/clone'.format(
            vmhost, vm_['clone_from']), postParams)
    else:
        node = query('post', 'nodes/{0}/{1}'.format(vmhost, vm_['technology']), newnode)
    return _parse_proxmox_upid(node, vm_)
642618
def create_node(vm_):
    '''
    
    '''
    # Start the tree
    content = ET.Element('ve')

    # Name of the instance
    name = ET.SubElement(content, 'name')
    name.text = vm_['name']

    # Description, defaults to name
    desc = ET.SubElement(content, 'description')
    desc.text = config.get_cloud_config_value(
        'desc', vm_, __opts__, default=vm_['name'], search_global=False
    )

    # How many CPU cores, and how fast they are
    cpu = ET.SubElement(content, 'cpu')
    cpu.attrib['number'] = config.get_cloud_config_value(
        'cpu_number', vm_, __opts__, default='1', search_global=False
    )
    cpu.attrib['power'] = config.get_cloud_config_value(
        'cpu_power', vm_, __opts__, default='1000', search_global=False
    )

    # How many megabytes of RAM
    ram = ET.SubElement(content, 'ram-size')
    ram.text = config.get_cloud_config_value(
        'ram', vm_, __opts__, default='256', search_global=False
    )

    # Bandwidth available, in kbps
    bandwidth = ET.SubElement(content, 'bandwidth')
    bandwidth.text = config.get_cloud_config_value(
        'bandwidth', vm_, __opts__, default='100', search_global=False
    )

    # How many public IPs will be assigned to this instance
    ip_num = ET.SubElement(content, 'no-of-public-ip')
    ip_num.text = config.get_cloud_config_value(
        'ip_num', vm_, __opts__, default='1', search_global=False
    )

    # Size of the instance disk
    disk = ET.SubElement(content, 've-disk')
    disk.attrib['local'] = 'true'
    disk.attrib['size'] = config.get_cloud_config_value(
        'disk_size', vm_, __opts__, default='10', search_global=False
    )

    # Attributes for the image
    vm_image = config.get_cloud_config_value(
        'image', vm_, __opts__, search_global=False
    )
    image = show_image({'image': vm_image}, call='function')
    platform = ET.SubElement(content, 'platform')
    template = ET.SubElement(platform, 'template-info')
    template.attrib['name'] = vm_image
    os_info = ET.SubElement(platform, 'os-info')
    os_info.attrib['technology'] = image[vm_image]['technology']
    os_info.attrib['type'] = image[vm_image]['osType']

    # Username and password
    admin = ET.SubElement(content, 'admin')
    admin.attrib['login'] = config.get_cloud_config_value(
        'ssh_username', vm_, __opts__, default='root'
    )
    admin.attrib['password'] = config.get_cloud_config_value(
        'password', vm_, __opts__, search_global=False
    )

    data = ET.tostring(content, encoding='UTF-8')

    __utils__['cloud.fire_event'](
        'event',
        'requesting instance',
        'salt/cloud/{0}/requesting'.format(vm_['name']),
        args={
            'kwargs': __utils__['cloud.filter_event']('requesting', data, list(data)),
        },
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    node = query(action='ve', method='POST', data=data)
    return node
789353
def vm_running(name):
    '''
    

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

    if name in __salt__['vmadm.list'](order='hostname', search='state=running'):
        # we're good
        ret['result'] = True
        ret['comment'] = 'vm {0} already running'.format(name)
    else:
        # start the vm
        ret['result'] = True if __opts__['test'] else __salt__['vmadm.start'](name, key='hostname')
        if not isinstance(ret['result'], bool) and ret['result'].get('Error'):
            ret['result'] = False
            ret['comment'] = 'failed to start {0}'.format(name)
        else:
            ret['changes'][name] = 'running'
            ret['comment'] = 'vm {0} started'.format(name)

    return ret
556288
def create(vm_, call=None):
    '''
    '''
    prov = get_configured_provider(vm_)
    if not prov:
        return
    # we cant use profile as a configuration key as it conflicts
    # with salt cloud internals
    profile = vm_.get(
        'lxc_profile',
        vm_.get('container_profile', None))

    event_data = vm_.copy()
    event_data['profile'] = profile

    __utils__['cloud.fire_event'](
        'event',
        'starting create',
        'salt/cloud/{0}/creating'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('creating', event_data, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    ret = {'name': vm_['name'], 'changes': {}, 'result': True, 'comment': ''}
    if 'pub_key' not in vm_ and 'priv_key' not in vm_:
        log.debug('Generating minion keys for %s', vm_['name'])
        vm_['priv_key'], vm_['pub_key'] = salt.utils.cloud.gen_keys(
            salt.config.get_cloud_config_value(
                'keysize', vm_, __opts__))
    # get the minion key pair to distribute back to the container
    kwarg = copy.deepcopy(vm_)
    kwarg['host'] = prov['target']
    kwarg['profile'] = profile

    __utils__['cloud.fire_event'](
        'event',
        'requesting instance',
        'salt/cloud/{0}/requesting'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('requesting', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    cret = _runner().cmd('lxc.cloud_init', [vm_['name']], kwarg=kwarg)
    ret['runner_return'] = cret
    ret['result'] = cret['result']
    if not ret['result']:
        ret['Error'] = 'Error while creating {0},'.format(vm_['name'])
    else:
        ret['changes']['created'] = 'created'

    # When using cloud states to manage LXC containers
    # __opts__['profile'] is not implicitly reset between operations
    # on different containers. However list_nodes will hide container
    # if profile is set in opts assuming that it have to be created.
    # But in cloud state we do want to check at first if it really
    # exists hence the need to remove profile from global opts once
    # current container is created.
    if 'profile' in __opts__:
        __opts__['internal_lxc_profile'] = __opts__['profile']
        del __opts__['profile']

    __utils__['cloud.fire_event'](
        'event',
        'created instance',
        'salt/cloud/{0}/created'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    return ret
838358
def _clone_vm(image=None, name=None, session=None):
    '''
    

    '''
    if session is None:
        session = _get_session()
    log.debug('Creating VM %s by cloning %s', name, image)
    source = _get_vm(image, session)
    task = session.xenapi.Async.VM.clone(source, name)
    _run_async_task(task, session)
492168
def update_vm(vm_ref, vm_config_spec):
    '''
    
    '''
    vm_name = get_managed_object_name(vm_ref)
    log.trace('Updating vm \'%s\'', vm_name)
    try:
        task = vm_ref.ReconfigVM_Task(vm_config_spec)
    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)
    vm_ref = wait_for_task(task, vm_name, 'ReconfigureVM Task')
    return vm_ref