Create a single VM from a data dict
978918
def create(vm_):
    '''
    
    '''
    deploy = config.get_cloud_config_value('deploy', vm_, __opts__)
    key_filename = config.get_cloud_config_value(
        'ssh_key_file', vm_, __opts__, search_global=False, default=None
    )
    if key_filename is not None and not os.path.isfile(key_filename):
        raise SaltCloudConfigError(
            'The defined ssh_key_file \'{0}\' does not exist'.format(
                key_filename
            )
        )

    vm_['key_filename'] = key_filename

    __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']
    )
    conn = get_conn()

    if 'instance_id' in vm_:
        # This was probably created via another process, and doesn't have
        # things like salt keys created yet, so let's create them now.
        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'] = __utils__['cloud.gen_keys'](
                config.get_cloud_config_value(
                    'keysize',
                    vm_,
                    __opts__
                )
            )
    else:
        # Put together all of the information required to request the instance,
        # and then fire off the request for it
        request_instance(conn=conn, call='action', vm_=vm_)
    data = show_instance(vm_.get('instance_id', vm_['name']), conn=conn, call='action')
    log.debug('VM is now running')

    def __query_node(vm_):
        data = show_instance(vm_['name'], conn=conn, call='action')
        if 'wait_for_metadata' in vm_:
            for key, value in six.iteritems(vm_.get('wait_for_metadata', {})):
                log.debug('Waiting for metadata: %s=%s', key, value)
                if data['metadata'].get(key, None) != value:
                    log.debug('Metadata is not ready: %s=%s', key, data['metadata'].get(key))
                    return False
        return preferred_ip(vm_, data[ssh_interface(vm_)])
    try:
        ip_address = __utils__['cloud.wait_for_fun'](
            __query_node,
            vm_=vm_
        )
    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))
    log.debug('Using IP address %s', ip_address)

    salt_interface = __utils__['cloud.get_salt_interface'](vm_, __opts__)
    salt_ip_address = preferred_ip(vm_, data[salt_interface])
    log.debug('Salt interface set to: %s', salt_ip_address)

    if not ip_address:
        raise SaltCloudSystemExit('A valid IP address was not found')

    vm_['ssh_host'] = ip_address
    vm_['salt_host'] = salt_ip_address

    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)
    )

    event_data = {
        'name': vm_['name'],
        'profile': vm_['profile'],
        'provider': vm_['driver'],
        'instance_id': data['id'],
        'floating_ips': data['floating_ips'],
        'fixed_ips': data['fixed_ips'],
        'private_ips': data['private_ips'],
        'public_ips': data['public_ips'],
    }

    __utils__['cloud.fire_event'](
        'event',
        'created instance',
        'salt/cloud/{0}/created'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('created', event_data, list(event_data)),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )
    __utils__['cloud.cachedir_index_add'](vm_['name'], vm_['profile'], 'nova', vm_['driver'])
    return ret
1023713
def from_dict(cls, database, key, data, clear=False):
        
        hsh = cls(database, key)
        if clear:
            hsh.clear()
        hsh.update(data)
        return hsh
496425
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'input' in _dict:
            args['input'] = MessageInput._from_dict(_dict.get('input'))
        if 'intents' in _dict:
            args['intents'] = [
                RuntimeIntent._from_dict(x) for x in (_dict.get('intents'))
            ]
        if 'entities' in _dict:
            args['entities'] = [
                RuntimeEntity._from_dict(x) for x in (_dict.get('entities'))
            ]
        return cls(**args)
1110495
def find_vm_by_name(self, si, path, name):
        
        return self.find_obj_by_path(si, path, name, self.VM)
929598
def create_multiprocessing(parallel_data, queue=None):
    '''
    
    '''
    salt.utils.crypt.reinit_crypto()

    parallel_data['opts']['output'] = 'json'
    cloud = Cloud(parallel_data['opts'])
    try:
        output = cloud.create(
            parallel_data['profile'],
            local_master=parallel_data['local_master']
        )
    except SaltCloudException as exc:
        log.error(
            'Failed to deploy \'%s\'. Error: %s',
            parallel_data['name'], exc, exc_info_on_loglevel=logging.DEBUG
        )
        return {parallel_data['name']: {'Error': str(exc)}}

    if parallel_data['opts'].get('show_deploy_args', False) is False and isinstance(output, dict):
        output.pop('deploy_kwargs', None)

    return {
        parallel_data['name']: salt.utils.data.simple_types_filter(output)
    }
1265825
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 'softlayer',
                                                           vm_['profile'],
                                                           vm_=vm_) is False:
            return False
    except AttributeError:
        pass

    name = vm_['name']
    hostname = name
    domain = config.get_cloud_config_value(
        'domain', vm_, __opts__, default=None
    )
    if domain is None:
        SaltCloudSystemExit(
            'A domain name is required for the SoftLayer driver.'
        )

    if vm_.get('use_fqdn'):
        name = '.'.join([name, domain])
        vm_['name'] = name

    __utils__['cloud.fire_event'](
        'event',
        'starting create',
        'salt/cloud/{0}/creating'.format(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', name)
    conn = get_conn()
    kwargs = {
        'hostname': hostname,
        'domain': domain,
        'startCpus': vm_['cpu_number'],
        'maxMemory': vm_['ram'],
        'hourlyBillingFlag': vm_['hourly_billing'],
    }

    local_disk_flag = config.get_cloud_config_value(
        'local_disk', vm_, __opts__, default=False
    )
    kwargs['localDiskFlag'] = local_disk_flag

    if 'image' in vm_:
        kwargs['operatingSystemReferenceCode'] = vm_['image']
        kwargs['blockDevices'] = []
        disks = vm_['disk_size']

        if isinstance(disks, int):
            disks = [six.text_type(disks)]
        elif isinstance(disks, six.string_types):
            disks = [size.strip() for size in disks.split(',')]

        count = 0
        for disk in disks:
            # device number '1' is reserved for the SWAP disk
            if count == 1:
                count += 1
            block_device = {'device': six.text_type(count),
                            'diskImage': {'capacity': six.text_type(disk)}}
            kwargs['blockDevices'].append(block_device)
            count += 1

            # Upper bound must be 5 as we're skipping '1' for the SWAP disk ID
            if count > 5:
                log.warning('More that 5 disks were specified for %s .'
                            'The first 5 disks will be applied to the VM, '
                            'but the remaining disks will be ignored.\n'
                            'Please adjust your cloud configuration to only '
                            'specify a maximum of 5 disks.', name)
                break

    elif 'global_identifier' in vm_:
        kwargs['blockDeviceTemplateGroup'] = {
            'globalIdentifier': vm_['global_identifier']
        }

    location = get_location(vm_)
    if location:
        kwargs['datacenter'] = {'name': location}

    private_vlan = config.get_cloud_config_value(
        'private_vlan', vm_, __opts__, default=False
    )
    if private_vlan:
        kwargs['primaryBackendNetworkComponent'] = {
            'networkVlan': {
                'id': private_vlan,
            }
        }

    private_network = config.get_cloud_config_value(
        'private_network', vm_, __opts__, default=False
    )
    if bool(private_network) is True:
        kwargs['privateNetworkOnlyFlag'] = 'True'

    public_vlan = config.get_cloud_config_value(
        'public_vlan', vm_, __opts__, default=False
    )
    if public_vlan:
        kwargs['primaryNetworkComponent'] = {
            'networkVlan': {
                'id': public_vlan,
            }
        }

    public_security_groups = config.get_cloud_config_value(
        'public_security_groups', vm_, __opts__, default=False
    )
    if public_security_groups:
        secgroups = [{'securityGroup': {'id': int(sg)}}
                     for sg in public_security_groups]
        pnc = kwargs.get('primaryNetworkComponent', {})
        pnc['securityGroupBindings'] = secgroups
        kwargs.update({'primaryNetworkComponent': pnc})

    private_security_groups = config.get_cloud_config_value(
        'private_security_groups', vm_, __opts__, default=False
    )

    if private_security_groups:
        secgroups = [{'securityGroup': {'id': int(sg)}}
                     for sg in private_security_groups]
        pbnc = kwargs.get('primaryBackendNetworkComponent', {})
        pbnc['securityGroupBindings'] = secgroups
        kwargs.update({'primaryBackendNetworkComponent': pbnc})

    max_net_speed = config.get_cloud_config_value(
        'max_net_speed', vm_, __opts__, default=10
    )
    if max_net_speed:
        kwargs['networkComponents'] = [{
            'maxSpeed': int(max_net_speed)
        }]

    post_uri = config.get_cloud_config_value(
        'post_uri', vm_, __opts__, default=None
    )
    if post_uri:
        kwargs['postInstallScriptUri'] = post_uri

    dedicated_host_id = config.get_cloud_config_value(
        'dedicated_host_id', vm_, __opts__, default=None
    )
    if dedicated_host_id:
        kwargs['dedicatedHost'] = {'id': dedicated_host_id}

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

    try:
        response = conn.createObject(kwargs)
    except Exception as exc:
        log.error(
            'Error creating %s on SoftLayer\n\n'
            'The following exception was thrown when trying to '
            'run the initial deployment: \n%s', name, exc,
            # Show the traceback if the debug logging level is enabled
            exc_info_on_loglevel=logging.DEBUG
        )
        return False

    ip_type = 'primaryIpAddress'
    private_ssh = config.get_cloud_config_value(
        'private_ssh', vm_, __opts__, default=False
    )
    private_wds = config.get_cloud_config_value(
        'private_windows', vm_, __opts__, default=False
    )
    if private_ssh or private_wds or public_vlan is None:
        ip_type = 'primaryBackendIpAddress'

    def wait_for_ip():
        '''
        Wait for the IP address to become available
        '''
        nodes = list_nodes_full()
        if ip_type in nodes[hostname]:
            return nodes[hostname][ip_type]
        time.sleep(1)
        return False

    ip_address = salt.utils.cloud.wait_for_fun(
        wait_for_ip,
        timeout=config.get_cloud_config_value(
            'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
    )
    if config.get_cloud_config_value('deploy', vm_, __opts__) is not True:
        return show_instance(hostname, call='action')

    SSH_PORT = 22
    WINDOWS_DS_PORT = 445
    managing_port = SSH_PORT
    if config.get_cloud_config_value('windows', vm_, __opts__) or \
            config.get_cloud_config_value('win_installer', vm_, __opts__):
        managing_port = WINDOWS_DS_PORT

    ssh_connect_timeout = config.get_cloud_config_value(
        'ssh_connect_timeout', vm_, __opts__, 15 * 60
    )
    connect_timeout = config.get_cloud_config_value(
        'connect_timeout', vm_, __opts__, ssh_connect_timeout
    )
    if not salt.utils.cloud.wait_for_port(ip_address,
                                          port=managing_port,
                                          timeout=connect_timeout):
        raise SaltCloudSystemExit(
            'Failed to authenticate against remote ssh'
        )

    pass_conn = get_conn(service='SoftLayer_Account')
    mask = {
        'virtualGuests': {
            'powerState': '',
            'operatingSystem': {
                'passwords': ''
            },
        },
    }

    def get_credentials():
        '''
        Wait for the password to become available
        '''
        node_info = pass_conn.getVirtualGuests(id=response['id'], mask=mask)
        for node in node_info:
            if node['id'] == response['id'] and \
                            'passwords' in node['operatingSystem'] and \
                            node['operatingSystem']['passwords']:
                return node['operatingSystem']['passwords'][0]['username'], node['operatingSystem']['passwords'][0]['password']
        time.sleep(5)
        return False

    username, passwd = salt.utils.cloud.wait_for_fun(  # pylint: disable=W0633
        get_credentials,
        timeout=config.get_cloud_config_value(
            'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
    )
    response['username'] = username
    response['password'] = passwd
    response['public_ip'] = ip_address

    ssh_username = config.get_cloud_config_value(
        'ssh_username', vm_, __opts__, default=username
    )

    vm_['ssh_host'] = ip_address
    vm_['password'] = passwd
    ret = __utils__['cloud.bootstrap'](vm_, __opts__)

    ret.update(response)

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

    return ret
659231
async def get_vm(self, vm_id):
        '''
        
        '''
        result = await self.nova.servers.get(vm_id)
        return self._map_vm_structure(result["server"])
745876
def _generate_create_dict(self,
                              hostname=None,
                              domain=None,
                              flavor=None,
                              router=None,
                              datacenter=None,
                              hourly=True):
        """"""
        package = self._get_package()
        item = self._get_item(package, flavor)

        location = self._get_location(package['regions'], datacenter)
        price = self._get_price(item)

        routers = self._get_backend_router(
            location['location']['locationPackageDetails'], item)

        router = self._get_default_router(routers, router)

        hardware = {
            'hostname': hostname,
            'domain': domain,
            'primaryBackendNetworkComponent': {
                'router': {
                    'id': router
                }
            }
        }

        complex_type = "SoftLayer_Container_Product_Order_Virtual_DedicatedHost"

        order = {
            "complexType": complex_type,
            "quantity": 1,
            'location': location['keyname'],
            'packageId': package['id'],
            'prices': [{'id': price}],
            'hardware': [hardware],
            'useHourlyPricing': hourly,
        }
        return order
84105
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 'parallels',
                                                           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'])

    try:
        data = create_node(vm_)
    except Exception as exc:
        log.error(
            'Error creating %s on PARALLELS\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

    name = vm_['name']
    if not wait_until(name, 'CREATED'):
        return {'Error': 'Unable to start {0}, command timed out'.format(name)}
    start(vm_['name'], call='action')

    if not wait_until(name, 'STARTED'):
        return {'Error': 'Unable to start {0}, command timed out'.format(name)}

    def __query_node_data(vm_name):
        data = show_instance(vm_name, call='action')
        if 'public-ip' not in data['network']:
            # Trigger another iteration
            return
        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=5 * 60),
            interval=config.get_cloud_config_value(
                'wait_for_ip_interval', vm_, __opts__, default=5),
        )
    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))

    comps = data['network']['public-ip']['address'].split('/')
    public_ip = comps[0]

    vm_['ssh_host'] = public_ip
    ret = __utils__['cloud.bootstrap'](vm_, __opts__)

    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 data
370802
def create_vm(self, userid, cpu, memory, disk_list,
                  user_profile, max_cpu, max_mem, ipl_from,
                  ipl_param, ipl_loadparam):
        """"""
        LOG.info("Creating the user directory for vm %s", userid)

        info = self._smtclient.create_vm(userid, cpu, memory,
                                   disk_list, user_profile,
                                   max_cpu, max_mem, ipl_from,
                                   ipl_param, ipl_loadparam)

        # add userid into smapi namelist
        self._smtclient.namelist_add(self._namelist, userid)
        return info
1163267
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
                                          'profitbricks'),
                                         vm_['profile']) is False):
            return False
    except AttributeError:
        pass

    if 'image_alias' in vm_ and not version_compatible('4.0'):
        raise SaltCloudNotFound(
            "The 'image_alias' parameter requires the profitbricks "
            "SDK v4.0.0 or greater."
        )

    if 'image' not in vm_ and 'image_alias' not in vm_:
        log.error('The image or image_alias parameter is required.')

    signal_event(vm_, 'creating', 'starting create')

    data = None
    datacenter_id = get_datacenter_id()
    conn = get_conn()

    # Assemble list of network interfaces from the cloud profile config.
    nics = _get_nics(vm_)

    # Assemble list of volumes from the cloud profile config.
    volumes = [_get_system_volume(vm_)]
    if 'volumes' in vm_:
        volumes.extend(_get_data_volumes(vm_))

    # Assembla the composite server object.
    server = _get_server(vm_, volumes, nics)

    signal_event(vm_, 'requesting', 'requesting instance')

    try:
        data = conn.create_server(datacenter_id=datacenter_id, server=server)
        log.info(
            'Create server request ID: %s',
            data['requestId'], exc_info_on_loglevel=logging.DEBUG
        )

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

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

    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['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['state'] == 'RUNNING'
        if not running:
            # Still not running, trigger another iteration
            return

        if ssh_interface(vm_) == 'private_lan' and data['private_ips']:
            vm_['ssh_host'] = data['private_ips'][0]

        if ssh_interface(vm_) != 'private_lan' and data['public_ips']:
            vm_['ssh_host'] = data['public_ips'][0]

        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))

    signal_event(vm_, 'created', 'created instance')

    if 'ssh_host' in vm_:
        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.')
1256496
def _generate_create_dict(record, record_type, data, ttl, **kwargs):
        """"""

        # Basic dns record structure
        resource_record = {
            'host': record,
            'data': data,
            'ttl': ttl,
            'type': record_type
        }

        for (key, value) in kwargs.items():
            resource_record.setdefault(key, value)

        return resource_record
444903
def vgcreate(vgname, devices, **kwargs):
    '''
    
    '''
    if not vgname or not devices:
        return 'Error: vgname and device(s) are both required'
    if isinstance(devices, six.string_types):
        devices = devices.split(',')

    cmd = ['vgcreate', vgname]
    for device in devices:
        cmd.append(device)
    valid = ('clustered', 'maxlogicalvolumes', 'maxphysicalvolumes',
             'vgmetadatacopies', 'metadatacopies', 'physicalextentsize')
    for var in kwargs:
        if kwargs[var] and var in valid:
            cmd.append('--{0}'.format(var))
            cmd.append(kwargs[var])
    out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
    vgdata = vgdisplay(vgname)
    vgdata['Output from vgcreate'] = out[0].strip()
    return vgdata
1009118
def create(vm_):
    '''
    
    '''
    try:
        if vm_['profile'] and config.is_profile_configured(
            __opts__,
            __active_provider_name__ or 'azurearm',
            vm_['profile'],
            vm_=vm_
        ) is False:
            return False
    except AttributeError:
        pass

    if vm_.get('bootstrap_interface') is None:
        vm_['bootstrap_interface'] = 'public'

    __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']
    )
    __utils__['cloud.cachedir_index_add'](
        vm_['name'], vm_['profile'], 'azurearm', vm_['driver']
    )
    if not vm_.get('location'):
        vm_['location'] = get_location(kwargs=vm_)

    log.info('Creating Cloud VM %s in %s', vm_['name'], vm_['location'])

    vm_request = request_instance(vm_=vm_)

    if not vm_request or 'error' in vm_request:
        err_message = 'Error creating VM {0}! ({1})'.format(vm_['name'], six.text_type(vm_request))
        log.error(err_message)
        raise SaltCloudSystemExit(err_message)

    def _query_node_data(name, bootstrap_interface):
        '''
        Query node data.
        '''
        data = show_instance(name, call='action')
        if not data:
            return False
        ip_address = None
        if bootstrap_interface == 'public':
            ip_address = data['public_ips'][0]
        if bootstrap_interface == 'private':
            ip_address = data['private_ips'][0]
        if ip_address is None:
            return False
        return ip_address

    try:
        data = salt.utils.cloud.wait_for_ip(
            _query_node_data,
            update_args=(vm_['name'], vm_['bootstrap_interface'],),
            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),
            interval_multiplier=config.get_cloud_config_value(
                'wait_for_ip_interval_multiplier', vm_, __opts__, default=1),
        )
    except (
        SaltCloudExecutionTimeout,
        SaltCloudExecutionFailure,
        SaltCloudSystemExit
    ) as exc:
        try:
            log.warning(exc)
        finally:
            raise SaltCloudSystemExit(six.text_type(exc))

    vm_['ssh_host'] = data
    if not vm_.get('ssh_username'):
        vm_['ssh_username'] = config.get_cloud_config_value(
            'ssh_username', vm_, __opts__
        )
    vm_['password'] = config.get_cloud_config_value(
        'ssh_password', vm_, __opts__
    )
    ret = __utils__['cloud.bootstrap'](vm_, __opts__)

    data = show_instance(vm_['name'], call='action')
    log.info('Created Cloud VM \'%s\'', vm_['name'])
    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
113469
async def create(cls, name: str,
                     default_for_unspecified: int,
                     total_resource_slots: int,
                     max_concurrent_sessions: int,
                     max_containers_per_session: int,
                     max_vfolder_count: int,
                     max_vfolder_size: int,
                     idle_timeout: int,
                     allowed_vfolder_hosts: Sequence[str],
                     fields: Iterable[str] = None) -> dict:
        
        if fields is None:
            fields = ('name',)
        q = 'mutation($name: String!, $input: CreateKeyPairResourcePolicyInput!) {' \
            + \
            '  create_keypair_resource_policy(name: $name, props: $input) {' \
            '    ok msg resource_policy { $fields }' \
            '  }' \
            '}'
        q = q.replace('$fields', ' '.join(fields))
        variables = {
            'name': name,
            'input': {
                'default_for_unspecified': default_for_unspecified,
                'total_resource_slots': total_resource_slots,
                'max_concurrent_sessions': max_concurrent_sessions,
                'max_containers_per_session': max_containers_per_session,
                'max_vfolder_count': max_vfolder_count,
                'max_vfolder_size': max_vfolder_size,
                'idle_timeout': idle_timeout,
                'allowed_vfolder_hosts': allowed_vfolder_hosts,
            },
        }
        rqst = Request(cls.session, 'POST', '/admin/graphql')
        rqst.set_json({
            'query': q,
            'variables': variables,
        })
        async with rqst.fetch() as resp:
            data = await resp.json()
            return data['create_keypair_resource_policy']
1366299
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 'cloudstack',
                                                           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']),
        sock_dir=__opts__['sock_dir'],
        args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
        transport=__opts__['transport']
    )

    log.info('Creating Cloud VM %s', vm_['name'])
    conn = get_conn()
    # pylint: disable=not-callable
    kwargs = {
        'name': vm_['name'],
        'image': get_image(conn, vm_),
        'size': get_size(conn, vm_),
        'location': get_location(conn, vm_),
    }
    # pylint: enable=not-callable

    sg = get_security_groups(conn, vm_)
    if sg is not False:
        kwargs['ex_security_groups'] = sg

    if get_keypair(vm_) is not False:
        kwargs['ex_keyname'] = get_keypair(vm_)

    if get_networkid(vm_) is not False:
        kwargs['networkids'] = get_networkid(vm_)
        kwargs['networks'] = (   # The only attr that is used is 'id'.
                                 CloudStackNetwork(None, None, None,
                                                   kwargs['networkids'],
                                                   None, None),
                             )

    if get_project(conn, vm_) is not False:
        kwargs['project'] = get_project(conn, vm_)

    event_data = kwargs.copy()
    event_data['image'] = kwargs['image'].name
    event_data['size'] = kwargs['size'].name

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

    displayname = cloudstack_displayname(vm_)
    if displayname:
        kwargs['ex_displayname'] = displayname
    else:
        kwargs['ex_displayname'] = kwargs['name']

    volumes = {}
    ex_blockdevicemappings = block_device_mappings(vm_)
    if ex_blockdevicemappings:
        for ex_blockdevicemapping in ex_blockdevicemappings:
            if 'VirtualName' not in ex_blockdevicemapping:
                ex_blockdevicemapping['VirtualName'] = '{0}-{1}'.format(vm_['name'], len(volumes))
            __utils__['cloud.fire_event'](
                'event',
                'requesting volume',
                'salt/cloud/{0}/requesting'.format(ex_blockdevicemapping['VirtualName']),
                sock_dir=__opts__['sock_dir'],
                args={'kwargs': {'name': ex_blockdevicemapping['VirtualName'],
                                 'device': ex_blockdevicemapping['DeviceName'],
                                 'size': ex_blockdevicemapping['VolumeSize']}},
            )
            try:
                volumes[ex_blockdevicemapping['DeviceName']] = conn.create_volume(
                        ex_blockdevicemapping['VolumeSize'],
                        ex_blockdevicemapping['VirtualName']
                    )
            except Exception as exc:
                log.error(
                    'Error creating volume %s on CLOUDSTACK\n\n'
                    'The following exception was thrown by libcloud when trying to '
                    'requesting a volume: \n%s',
                    ex_blockdevicemapping['VirtualName'], exc,
                    # Show the traceback if the debug logging level is enabled
                    exc_info_on_loglevel=logging.DEBUG
                )
                return False
    else:
        ex_blockdevicemapping = {}
    try:
        data = conn.create_node(**kwargs)
    except Exception as exc:
        log.error(
            'Error creating %s on CLOUDSTACK\n\n'
            'The following exception was thrown by libcloud 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

    for device_name in six.iterkeys(volumes):
        try:
            conn.attach_volume(data, volumes[device_name], device_name)
        except Exception as exc:
            log.error(
                'Error attaching volume %s on CLOUDSTACK\n\n'
                'The following exception was thrown by libcloud when trying to '
                'attach a volume: \n%s',
                ex_blockdevicemapping.get('VirtualName', 'UNKNOWN'), exc,
                # Show the traceback if the debug logging level is enabled
                exc_info=log.isEnabledFor(logging.DEBUG)
            )
            return False

    ssh_username = config.get_cloud_config_value(
        'ssh_username', vm_, __opts__, default='root'
    )

    vm_['ssh_host'] = get_ip(data)
    vm_['password'] = data.extra['password']
    vm_['key_filename'] = get_key()
    ret = __utils__['cloud.bootstrap'](vm_, __opts__)

    ret.update(data.__dict__)

    if 'password' in data.extra:
        del data.extra['password']

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

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

    return ret
774774
def get_vm(self, name, path=""):
        """"""
        if path:
            return self.get_obj([vim.VirtualMachine], name, path=path)
        else:
            return self.get_obj([vim.VirtualMachine], name)