Create a single Linode VM.
487138
def create(vm_):
    '''
    
    '''
    name = vm_['name']
    try:
        # Check for required profile parameters before sending any API calls.
        if vm_['profile'] and config.is_profile_configured(__opts__,
                                                           __active_provider_name__ or 'linode',
                                                           vm_['profile'],
                                                           vm_=vm_) is False:
            return False
    except AttributeError:
        pass

    if _validate_name(name) is False:
        return False

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

    data = {}
    kwargs = {'name': name}

    plan_id = None
    size = vm_.get('size')
    if size:
        kwargs['size'] = size
        plan_id = get_plan_id(kwargs={'label': size})

    datacenter_id = None
    location = vm_.get('location')
    if location:
        try:
            datacenter_id = get_datacenter_id(location)
        except KeyError:
            # Linode's default datacenter is Dallas, but we still have to set one to
            # use the create function from Linode's API. Dallas's datacenter id is 2.
            datacenter_id = 2

    clonefrom_name = vm_.get('clonefrom')
    cloning = True if clonefrom_name else False
    if cloning:
        linode_id = get_linode_id_from_name(clonefrom_name)
        clone_source = get_linode(kwargs={'linode_id': linode_id})

        kwargs = {
            'clonefrom': clonefrom_name,
            'image': 'Clone of {0}'.format(clonefrom_name),
        }

        if size is None:
            size = clone_source['TOTALRAM']
            kwargs['size'] = size
            plan_id = clone_source['PLANID']

        if location is None:
            datacenter_id = clone_source['DATACENTERID']

        # Create new Linode from cloned Linode
        try:
            result = clone(kwargs={'linode_id': linode_id,
                                   'datacenter_id': datacenter_id,
                                   'plan_id': plan_id})
        except Exception as err:
            log.error(
                'Error cloning \'%s\' on Linode.\n\n'
                'The following exception was thrown by Linode when trying to '
                'clone the specified machine:\n%s',
                clonefrom_name, err, exc_info_on_loglevel=logging.DEBUG
            )
            return False
    else:
        kwargs['image'] = vm_['image']

        # Create Linode
        try:
            result = _query('linode', 'create', args={
                'PLANID': plan_id,
                'DATACENTERID': datacenter_id
            })
        except Exception as err:
            log.error(
                'Error creating %s on Linode\n\n'
                'The following exception was thrown by Linode when trying to '
                'run the initial deployment:\n%s',
                name, err, exc_info_on_loglevel=logging.DEBUG
            )
            return False

    if 'ERRORARRAY' in result:
        for error_data in result['ERRORARRAY']:
            log.error(
                'Error creating %s on Linode\n\n'
                'The Linode API returned the following: %s\n',
                name, error_data['ERRORMESSAGE']
            )
            return False

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

    node_id = _clean_data(result)['LinodeID']
    data['id'] = node_id

    if not _wait_for_status(node_id, status=(_get_status_id_by_name('brand_new'))):
        log.error(
            'Error creating %s on LINODE\n\n'
            'while waiting for initial ready status',
            name, exc_info_on_loglevel=logging.DEBUG
        )

    # Update the Linode's Label to reflect the given VM name
    update_linode(node_id, update_args={'Label': name})
    log.debug('Set name for %s - was linode%s.', name, node_id)

    # Add private IP address if requested
    private_ip_assignment = get_private_ip(vm_)
    if private_ip_assignment:
        create_private_ip(node_id)

    # Define which ssh_interface to use
    ssh_interface = _get_ssh_interface(vm_)

    # If ssh_interface is set to use private_ips, but assign_private_ip
    # wasn't set to True, let's help out and create a private ip.
    if ssh_interface == 'private_ips' and private_ip_assignment is False:
        create_private_ip(node_id)
        private_ip_assignment = True

    if cloning:
        config_id = get_config_id(kwargs={'linode_id': node_id})['config_id']
    else:
        # Create disks and get ids
        log.debug('Creating disks for %s', name)
        root_disk_id = create_disk_from_distro(vm_, node_id)['DiskID']
        swap_disk_id = create_swap_disk(vm_, node_id)['DiskID']

        # Create a ConfigID using disk ids
        config_id = create_config(kwargs={'name': name,
                                          'linode_id': node_id,
                                          'root_disk_id': root_disk_id,
                                          'swap_disk_id': swap_disk_id})['ConfigID']

    # Boot the Linode
    boot(kwargs={'linode_id': node_id,
                 'config_id': config_id,
                 'check_running': False})

    node_data = get_linode(kwargs={'linode_id': node_id})
    ips = get_ips(node_id)
    state = int(node_data['STATUS'])

    data['image'] = kwargs['image']
    data['name'] = name
    data['size'] = size
    data['state'] = _get_status_descr_by_id(state)
    data['private_ips'] = ips['private_ips']
    data['public_ips'] = ips['public_ips']

    # Pass the correct IP address to the bootstrap ssh_host key
    if ssh_interface == 'private_ips':
        vm_['ssh_host'] = data['private_ips'][0]
    else:
        vm_['ssh_host'] = data['public_ips'][0]

    # If a password wasn't supplied in the profile or provider config, set it now.
    vm_['password'] = get_password(vm_)

    # Make public_ips and private_ips available to the bootstrap script.
    vm_['public_ips'] = ips['public_ips']
    vm_['private_ips'] = ips['private_ips']

    # Send event that the instance has booted.
    __utils__['cloud.fire_event'](
        'event',
        'waiting for ssh',
        'salt/cloud/{0}/waiting_for_ssh'.format(name),
        sock_dir=__opts__['sock_dir'],
        args={'ip_address': vm_['ssh_host']},
        transport=__opts__['transport']
    )

    # Bootstrap!
    ret = __utils__['cloud.bootstrap'](vm_, __opts__)

    ret.update(data)

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

    __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
1129919
def create(vm_):
    '''
    
    '''
    clone_strategy = vm_.get('clone_strategy') or 'full'

    if clone_strategy not in ('quick', 'full'):
        raise SaltCloudSystemExit("'clone_strategy' must be one of quick or full. Got '{0}'".format(clone_strategy))

    ip_source = vm_.get('ip_source') or 'ip-learning'

    if ip_source not in ('ip-learning', 'qemu-agent'):
        raise SaltCloudSystemExit("'ip_source' must be one of qemu-agent or ip-learning. Got '{0}'".format(ip_source))

    validate_xml = vm_.get('validate_xml') if vm_.get('validate_xml') is not None else True

    log.info("Cloning '%s' with strategy '%s' validate_xml='%s'", vm_['name'], clone_strategy, validate_xml)

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

    # TODO: check name qemu/libvirt will choke on some characters (like '/')?
    name = vm_['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']
    )

    key_filename = config.get_cloud_config_value(
        'private_key', vm_, __opts__, search_global=False, default=None
    )
    if key_filename is not None and not os.path.isfile(key_filename):
        raise SaltCloudConfigError(
            'The defined key_filename \'{0}\' does not exist'.format(
                key_filename
            )
        )
    vm_['key_filename'] = key_filename
    # wait_for_instance requires private_key
    vm_['private_key'] = key_filename

    cleanup = []
    try:
        # clone the vm
        base = vm_['base_domain']
        conn = __get_conn(vm_['url'])

        try:
            # for idempotency the salt-bootstrap needs -F argument
            #  script_args: -F
            clone_domain = conn.lookupByName(name)
        except libvirtError as e:
            domain = conn.lookupByName(base)
            # TODO: ensure base is shut down before cloning
            xml = domain.XMLDesc(0)

            kwargs = {
                'name': name,
                'base_domain': base,
            }

            __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']
            )

            log.debug("Source machine XML '%s'", xml)

            domain_xml = ElementTree.fromstring(xml)
            domain_xml.find('./name').text = name
            if domain_xml.find('./description') is None:
                description_elem = ElementTree.Element('description')
                domain_xml.insert(0, description_elem)
            description = domain_xml.find('./description')
            description.text = "Cloned from {0}".format(base)
            domain_xml.remove(domain_xml.find('./uuid'))

            for iface_xml in domain_xml.findall('./devices/interface'):
                iface_xml.remove(iface_xml.find('./mac'))
                # enable IP learning, this might be a default behaviour...
                # Don't always enable since it can cause problems through libvirt-4.5
                if ip_source == 'ip-learning' and iface_xml.find("./filterref/parameter[@name='CTRL_IP_LEARNING']") is None:
                    iface_xml.append(ElementTree.fromstring(IP_LEARNING_XML))

            # If a qemu agent is defined we need to fix the path to its socket
            # <channel type='unix'>
            #   <source mode='bind' path='/var/lib/libvirt/qemu/channel/target/domain-<dom-name>/org.qemu.guest_agent.0'/>
            #   <target type='virtio' name='org.qemu.guest_agent.0'/>
            #   <address type='virtio-serial' controller='0' bus='0' port='2'/>
            # </channel>
            for agent_xml in domain_xml.findall("""./devices/channel[@type='unix']"""):
                #  is org.qemu.guest_agent.0 an option?
                if agent_xml.find("""./target[@type='virtio'][@name='org.qemu.guest_agent.0']""") is not None:
                    source_element = agent_xml.find("""./source[@mode='bind']""")
                    # see if there is a path element that needs rewriting
                    if source_element and 'path' in source_element.attrib:
                        path = source_element.attrib['path']
                        new_path = path.replace('/domain-{0}/'.format(base), '/domain-{0}/'.format(name))
                        log.debug("Rewriting agent socket path to %s", new_path)
                        source_element.attrib['path'] = new_path

            for disk in domain_xml.findall("""./devices/disk[@device='disk'][@type='file']"""):
                # print "Disk: ", ElementTree.tostring(disk)
                # check if we can clone
                driver = disk.find("./driver[@name='qemu']")
                if driver is None:
                    # Err on the safe side
                    raise SaltCloudExecutionFailure("Non qemu driver disk encountered bailing out.")
                disk_type = driver.attrib.get('type')
                log.info("disk attributes %s", disk.attrib)
                if disk_type == 'qcow2':
                    source = disk.find("./source").attrib['file']
                    pool, volume = find_pool_and_volume(conn, source)
                    if clone_strategy == 'quick':
                        new_volume = pool.createXML(create_volume_with_backing_store_xml(volume), 0)
                    else:
                        new_volume = pool.createXMLFrom(create_volume_xml(volume), volume, 0)
                    cleanup.append({'what': 'volume', 'item': new_volume})

                    disk.find("./source").attrib['file'] = new_volume.path()
                elif disk_type == 'raw':
                    source = disk.find("./source").attrib['file']
                    pool, volume = find_pool_and_volume(conn, source)
                    # TODO: more control on the cloned disk type
                    new_volume = pool.createXMLFrom(create_volume_xml(volume), volume, 0)
                    cleanup.append({'what': 'volume', 'item': new_volume})

                    disk.find("./source").attrib['file'] = new_volume.path()
                else:
                    raise SaltCloudExecutionFailure("Disk type '{0}' not supported".format(disk_type))

            clone_xml = salt.utils.stringutils.to_str(ElementTree.tostring(domain_xml))
            log.debug("Clone XML '%s'", clone_xml)

            validate_flags = libvirt.VIR_DOMAIN_DEFINE_VALIDATE if validate_xml else 0
            clone_domain = conn.defineXMLFlags(clone_xml, validate_flags)

            cleanup.append({'what': 'domain', 'item': clone_domain})
            clone_domain.createWithFlags(libvirt.VIR_DOMAIN_START_FORCE_BOOT)

        log.debug("VM '%s'", vm_)

        if ip_source == 'qemu-agent':
            ip_source = libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_AGENT
        elif ip_source == 'ip-learning':
            ip_source = libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE

        address = salt.utils.cloud.wait_for_ip(
            get_domain_ip,
            update_args=(clone_domain, 0, ip_source),
            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),
        )

        log.info('Address = %s', address)

        vm_['ssh_host'] = address

        # the bootstrap script needs to be installed first in /etc/salt/cloud.deploy.d/
        # salt-cloud -u is your friend
        ret = __utils__['cloud.bootstrap'](vm_, __opts__)

        __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
    except Exception as e:  # pylint: disable=broad-except
        do_cleanup(cleanup)
        # throw the root cause after cleanup
        raise e
925528
async def create_vm(self, *, preset_name, image, flavor, security_groups=None,
                        userdata=None, key_name=None, availability_zone=None,
                        subnet=None):
        
        info = {
            'id': next(self._id_it),
            'name': preset_name,
            'ip': ['127.0.0.1'],
            'created': 0,
            'state': VmState.RUNNING,
            'flavor': flavor,
            'image': image,
            'metadata': {'test-meta': 'abctest'},
            'timed_shutdown_at': 1522753481,
            'tags': ['a-tag', 'b-tag', 'c-tag']
        }
        logging.debug('Prepare vm: %s', info)
        vm = Vm(self, **info)
        self._vms[vm.id] = vm
        logging.debug('Create: %s', vm)
        return None
30715
def vms(message, level=1):
    """"""
    if verbose is not None and verbose != False:
        if isinstance(verbose, bool) or (isinstance(verbose, int) and level <= verbose):
            std(message)
745729
def build(args) -> None:
    """"""
    venv_exe = shutil.which('virtualenv')
    pyexe = shutil.which(args.pyexe)
    if not venv_exe:
        logging.warn("virtualenv wasn't found in path, it's recommended to install virtualenv to manage python environments")
    if not pyexe:
        logging.warn("Python executable %s not found in path", args.pyexe)
    if args.cmake_options:
        cmake = CMake(args.cmake_options)
    else:
        cmake = CMake()
    cmake()
    create_virtualenv(venv_exe, pyexe, args.venv)
1309447
private VirtualMachine createLinuxVm(VirtualMachine.DefinitionStages.WithOS virtualMachineBuilder) {
    return virtualMachineBuilder
        .withPopularLinuxImage(KnownLinuxVirtualMachineImage.valueOf(template.imageId()))
        .withRootUsername(username)
        .withRootPassword(password)
        .withSize(hardware)
        .create();
  }
75955
def create(self, name, plugin_name, plugin_version,
               cluster_template_id=None, default_image_id=None,
               is_transient=None, description=None, cluster_configs=None,
               node_groups=None, user_keypair_id=None,
               anti_affinity=None, net_id=None, count=None,
               use_autoconfig=None, shares=None,
               is_public=None, is_protected=None):
        """"""

        data = {
            'name': name,
            'plugin_name': plugin_name,
            'plugin_version': plugin_version,
        }

        return self._do_create(data, cluster_template_id, default_image_id,
                               is_transient, description, cluster_configs,
                               node_groups, user_keypair_id, anti_affinity,
                               net_id, count, use_autoconfig, shares,
                               is_public, is_protected, api_ver=2)
217565
def create(vm_):
    '''
    
    '''
    name = vm_['name']

    if not is_profile_configured(vm_):
        return False

    __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 Packet VM %s', name)

    manager = packet.Manager(auth_token=vm_['token'])

    __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']
    )

    device = manager.create_device(project_id=vm_['project_id'],
                                hostname=name,
                                plan=vm_['size'], facility=vm_['location'],
                                operating_system=vm_['image'])

    device = _wait_for_status('device', device.id, status="active")

    if device.state != "active":
        log.error(
            'Error creating %s on PACKET\n\n'
            'while waiting for initial ready status',
            name, exc_info_on_loglevel=logging.DEBUG
        )

    # Define which ssh_interface to use
    ssh_interface = _get_ssh_interface(vm_)

    # Pass the correct IP address to the bootstrap ssh_host key
    if ssh_interface == 'private_ips':
        for ip in device.ip_addresses:
            if ip['public'] is False:
                vm_['ssh_host'] = ip['address']
                break
    else:
        for ip in device.ip_addresses:
            if ip['public'] is True:
                vm_['ssh_host'] = ip['address']
                break

    key_filename = config.get_cloud_config_value(
        'private_key', vm_, __opts__, search_global=False, default=None
    )

    vm_['key_filename'] = key_filename

    vm_['private_key'] = key_filename

    # Bootstrap!
    ret = __utils__['cloud.bootstrap'](vm_, __opts__)

    ret.update({'device': device.__dict__})

    if vm_.get('storage_tier') and vm_.get('storage_size'):
        # create storage and attach it to device

        volume = manager.create_volume(
            vm_['project_id'], "{0}_storage".format(name), vm_.get('storage_tier'),
            vm_.get('storage_size'), vm_.get('location'), snapshot_count=vm_.get('storage_snapshot_count', 0),
            snapshot_frequency=vm_.get('storage_snapshot_frequency'))

        volume.attach(device.id)

        volume = _wait_for_status('volume', volume.id, status="active")

        if volume.state != "active":
            log.error(
                'Error creating %s on PACKET\n\n'
                'while waiting for initial ready status',
                name, exc_info_on_loglevel=logging.DEBUG
            )

        ret.update({'volume': volume.__dict__})

    log.info('Created Cloud VM \'%s\'', name)

    log.debug(
        '\'%s\' VM creation details:\n%s',
        name, pprint.pformat(device.__dict__)
    )

    __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
262678
def create(cls, path):
        """"""
        cmd = [HG, 'init', path]
        subprocess.check_call(cmd)
        return cls(path)
613711
def create(vm_=None, call=None):
    '''
    
    '''
    if call:
        raise SaltCloudSystemExit(
            'You cannot create an instance with -a or -f.'
        )

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

    # Check for private_key and keyfile name for bootstrapping new instances
    deploy = config.get_cloud_config_value(
        'deploy', vm_, __opts__, default=True
    )
    win_password = config.get_cloud_config_value(
        'win_password', vm_, __opts__, default=''
    )
    key_filename = config.get_cloud_config_value(
        'private_key', vm_, __opts__, search_global=False, default=None
    )
    if deploy:
        # The private_key and keyname settings are only needed for bootstrapping
        # new instances when deploy is True
        _validate_key_path_and_mode(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']
    )
    __utils__['cloud.cachedir_index_add'](
        vm_['name'], vm_['profile'], 'ec2', vm_['driver']
    )

    vm_['key_filename'] = key_filename
    # wait_for_instance requires private_key
    vm_['private_key'] = key_filename

    # Get SSH Gateway config early to verify the private_key,
    # if used, exists or not. We don't want to deploy an instance
    # and not be able to access it via the gateway.
    vm_['gateway'] = get_ssh_gateway_config(vm_)

    location = get_location(vm_)
    vm_['location'] = location

    log.info('Creating Cloud VM %s in %s', vm_['name'], location)
    vm_['usernames'] = salt.utils.cloud.ssh_usernames(
        vm_,
        __opts__,
        default_users=(
            'ec2-user',  # Amazon Linux, Fedora, RHEL; FreeBSD
            'centos',    # CentOS AMIs from AWS Marketplace
            'ubuntu',    # Ubuntu
            'admin',     # Debian GNU/Linux
            'bitnami',   # BitNami AMIs
            'root'       # Last resort, default user on RHEL 5, SUSE
        )
    )

    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'] = salt.utils.cloud.gen_keys(
                salt.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
        if keyname(vm_) is None:
            raise SaltCloudSystemExit(
                'The required \'keyname\' configuration setting is missing from the '
                '\'ec2\' driver.'
            )

        data, vm_ = request_instance(vm_, location)

        # If data is a str, it's an error
        if isinstance(data, six.string_types):
            log.error('Error requesting instance: %s', data)
            return {}

        # Pull the instance ID, valid for both spot and normal instances

        # Multiple instances may have been spun up, get all their IDs
        vm_['instance_id_list'] = []
        for instance in data:
            vm_['instance_id_list'].append(instance['instanceId'])

        vm_['instance_id'] = vm_['instance_id_list'].pop()
        if vm_['instance_id_list']:
            # Multiple instances were spun up, get one now, and queue the rest
            queue_instances(vm_['instance_id_list'])

    # Wait for vital information, such as IP addresses, to be available
    # for the new instance
    data = query_instance(vm_)

    # Now that the instance is available, tag it appropriately. Should
    # mitigate race conditions with tags
    tags = config.get_cloud_config_value('tag',
                                         vm_,
                                         __opts__,
                                         {},
                                         search_global=False)
    if not isinstance(tags, dict):
        raise SaltCloudConfigError(
            '\'tag\' should be a dict.'
        )

    for value in six.itervalues(tags):
        if not isinstance(value, six.string_types):
            raise SaltCloudConfigError(
                '\'tag\' values must be strings. Try quoting the values. '
                'e.g. "2013-09-19T20:09:46Z".'
            )

    tags['Name'] = vm_['name']

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

    salt.utils.cloud.wait_for_fun(
        set_tags,
        timeout=30,
        name=vm_['name'],
        tags=tags,
        instance_id=vm_['instance_id'],
        call='action',
        location=location
    )

    # Once instance tags are set, tag the spot request if configured
    if 'spot_config' in vm_ and 'tag' in vm_['spot_config']:

        if not isinstance(vm_['spot_config']['tag'], dict):
            raise SaltCloudConfigError(
                '\'tag\' should be a dict.'
            )

        for value in six.itervalues(vm_['spot_config']['tag']):
            if not isinstance(value, str):
                raise SaltCloudConfigError(
                    '\'tag\' values must be strings. Try quoting the values. '
                    'e.g. "2013-09-19T20:09:46Z".'
                )

        spot_request_tags = {}

        if 'spotRequestId' not in vm_:
            raise SaltCloudConfigError('Failed to find spotRequestId')

        sir_id = vm_['spotRequestId']

        spot_request_tags['Name'] = vm_['name']

        for k, v in six.iteritems(vm_['spot_config']['tag']):
            spot_request_tags[k] = v

        __utils__['cloud.fire_event'](
            'event',
            'setting tags',
            'salt/cloud/spot_request_{0}/tagging'.format(sir_id),
            args={'tags': spot_request_tags},
            sock_dir=__opts__['sock_dir'],
            transport=__opts__['transport']
        )
        salt.utils.cloud.wait_for_fun(
            set_tags,
            timeout=30,
            name=vm_['name'],
            tags=spot_request_tags,
            instance_id=sir_id,
            call='action',
            location=location
        )

    network_interfaces = config.get_cloud_config_value(
        'network_interfaces',
        vm_,
        __opts__,
        search_global=False
    )

    if network_interfaces:
        _update_enis(network_interfaces, data, vm_)

    # At this point, the node is created and tagged, and now needs to be
    # bootstrapped, once the necessary port is available.
    log.info('Created node %s', vm_['name'])

    instance = data[0]['instancesSet']['item']

    # Wait for the necessary port to become available to bootstrap
    if ssh_interface(vm_) == 'private_ips':
        ip_address = instance['privateIpAddress']
        log.info('Salt node data. Private_ip: %s', ip_address)
    else:
        ip_address = instance['ipAddress']
        log.info('Salt node data. Public_ip: %s', ip_address)
    vm_['ssh_host'] = ip_address

    if salt.utils.cloud.get_salt_interface(vm_, __opts__) == 'private_ips':
        salt_ip_address = instance['privateIpAddress']
        log.info('Salt interface set to: %s', salt_ip_address)
    else:
        salt_ip_address = instance['ipAddress']
        log.debug('Salt interface set to: %s', salt_ip_address)
    vm_['salt_host'] = salt_ip_address

    if deploy:
        display_ssh_output = config.get_cloud_config_value(
            'display_ssh_output', vm_, __opts__, default=True
        )

        vm_ = wait_for_instance(
            vm_, data, ip_address, display_ssh_output
        )

    # The instance is booted and accessible, let's Salt it!
    ret = instance.copy()

    # Get ANY defined volumes settings, merging data, in the following order
    # 1. VM config
    # 2. Profile config
    # 3. Global configuration
    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={'volumes': 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,
                'zone': ret['placement']['availabilityZone'],
                'instance_id': ret['instanceId'],
                'del_all_vols_on_destroy': vm_.get('del_all_vols_on_destroy', False)
            },
            call='action'
        )
        ret['Attached Volumes'] = created

    # Associate instance with a ssm document, if present
    ssm_document = config.get_cloud_config_value(
        'ssm_document', vm_, __opts__, None, search_global=False
    )
    if ssm_document:
        log.debug('Associating with ssm document: %s', ssm_document)
        assoc = ssm_create_association(
            vm_['name'],
            {'ssm_document': ssm_document},
            instance_id=vm_['instance_id'],
            call='action'
        )
        if isinstance(assoc, dict) and assoc.get('error', None):
            log.error(
                'Failed to associate instance %s with ssm document %s',
                vm_['instance_id'], ssm_document
            )
            return {}

    for key, value in six.iteritems(__utils__['cloud.bootstrap'](vm_, __opts__)):
        ret.setdefault(key, value)

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

    event_data = {
        'name': vm_['name'],
        'profile': vm_['profile'],
        'provider': vm_['driver'],
        'instance_id': vm_['instance_id'],
    }
    if volumes:
        event_data['volumes'] = volumes
    if ssm_document:
        event_data['ssm_document'] = ssm_document

    __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']
    )

    # Ensure that the latest node data is returned
    node = _get_node(instance_id=vm_['instance_id'])
    __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
    ret.update(node)

    # Add any block device tags specified
    ex_blockdevicetags = {}
    blockdevicemappings_holder = block_device_mappings(vm_)
    if blockdevicemappings_holder:
        for _bd in blockdevicemappings_holder:
            if 'tag' in _bd:
                ex_blockdevicetags[_bd['DeviceName']] = _bd['tag']

    block_device_volume_id_map = {}

    if ex_blockdevicetags:
        for _device, _map in six.iteritems(ret['blockDeviceMapping']):
            bd_items = []
            if isinstance(_map, dict):
                bd_items.append(_map)
            else:
                for mapitem in _map:
                    bd_items.append(mapitem)

            for blockitem in bd_items:
                if blockitem['deviceName'] in ex_blockdevicetags and 'Name' not in ex_blockdevicetags[blockitem['deviceName']]:
                    ex_blockdevicetags[blockitem['deviceName']]['Name'] = vm_['name']
                if blockitem['deviceName'] in ex_blockdevicetags:
                    block_device_volume_id_map[blockitem[ret['rootDeviceType']]['volumeId']] = ex_blockdevicetags[blockitem['deviceName']]

    if block_device_volume_id_map:

        for volid, tags in six.iteritems(block_device_volume_id_map):
            __utils__['cloud.fire_event'](
                'event',
                'setting tags',
                'salt/cloud/block_volume_{0}/tagging'.format(str(volid)),
                args={'tags': tags},
                sock_dir=__opts__['sock_dir'],
                transport=__opts__['transport']
            )

            __utils__['cloud.wait_for_fun'](
                set_tags,
                timeout=30,
                name=vm_['name'],
                tags=tags,
                resource_id=volid,
                call='action',
                location=location
            )

    return ret
603523
def create(self):
        """"""
        required_nodes = self._get_required_nodes()
        self.lb_attrs = self.consul.create_lb(
                self.instance_name,
                protocol=self.protocol,
                port=self.port,
                nodes=required_nodes,
                node_port=str(self.backend_port),
                algorithm=getattr(self, 'algorithm', None)
                )
73282
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 'joyent',
                                                           vm_['profile'],
                                                           vm_=vm_) is False:
            return False
    except AttributeError:
        pass

    key_filename = config.get_cloud_config_value(
        'private_key', vm_, __opts__, search_global=False, default=None
    )

    __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 in %s',
        vm_['name'], vm_.get('location', DEFAULT_LOCATION)
    )

    # added . for fqdn hostnames
    salt.utils.cloud.check_name(vm_['name'], 'a-zA-Z0-9-.')
    kwargs = {
        'name': vm_['name'],
        'image': get_image(vm_),
        'size': get_size(vm_),
        'location': vm_.get('location', DEFAULT_LOCATION)
    }
    # Let's not assign a default here; only assign a network value if
    # one is explicitly configured
    if 'networks' in vm_:
        kwargs['networks'] = vm_.get('networks')

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

    data = create_node(**kwargs)
    if data == {}:
        log.error('Error creating %s on JOYENT', vm_['name'])
        return False

    query_instance(vm_)
    data = show_instance(vm_['name'], call='action')

    vm_['key_filename'] = key_filename
    vm_['ssh_host'] = data[1]['primaryIp']

    __utils__['cloud.bootstrap'](vm_, __opts__)

    __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[1]
404548
def cli(env, **args):
    """"""
    create_args = _parse_create_args(env.client, args)

    create_args['primary_disk'] = args.get('primary_disk')
    manager = CapacityManager(env.client)
    capacity_id = args.get('capacity_id')
    test = args.get('test')

    result = manager.create_guest(capacity_id, test, create_args)

    env.fout(_build_receipt(result, test))
672985
def generate(env):
    """"""
    SCons.Tool.createSharedLibBuilder(env)
    SCons.Tool.createProgBuilder(env)

    env['LINK']        = '$CC'
    env['LINKFLAGS']   = SCons.Util.CLVar('')
    env['LINKCOM']     = '$LINK -q $LINKFLAGS -e$TARGET $SOURCES $LIBS'
    env['LIBDIRPREFIX']=''
    env['LIBDIRSUFFIX']=''
    env['LIBLINKPREFIX']=''
    env['LIBLINKSUFFIX']='$LIBSUFFIX'
1151565
def build_undercloud_on_libvirt(self, image_path,
                                    rhsm=None, repositories=[]):
        """"""
        self.run('sysctl net.ipv4.ip_forward=1')
        self.fetch_image(path=image_path, dest='/home/stack/guest_image.qcow2',
                         user='stack')
        # NOTE(Gonéri): this is a hack for our OpenStack, the MTU of its outgoing route
        # is 1400 and libvirt do not provide a mechanism to adjust the guests MTU.
        self.run("LIBGUESTFS_BACKEND=direct virt-customize -a /home/stack/guest_image.qcow2 --run-command 'echo MTU=\"1400\" >> /etc/sysconfig/network-scripts/ifcfg-eth0'")

        env = Environment()
        env.loader = FileSystemLoader(pkg_data_filename('template'))
        template = env.get_template('virt-setup-env.j2')
        self.run('mkdir -p /home/stack/DIB', user='stack')
        self.run('cp -v /etc/yum.repos.d/*.repo /home/stack/DIB', user='stack')
        # NOTE(Gonéri): Hack to be sure DIB won't complain because of missing gpg files
        # self.run('sed -i "s,gpgcheck=1,gpgcheck=0," /home/stack/DIB/*.repo', user='stack')
        dib_yum_repo_conf = self.run('find /home/stack/DIB -type f', user='stack')[0].split()
        virt_setup_template = {
            'dib_yum_repo_conf': dib_yum_repo_conf,
            'node': {
                'count': 2,
                'mem': 6144,
                'cpu': 2
            },
            'undercloud_node_mem': 8192,
            'guest_image_name': '/home/stack/guest_image.qcow2'
        }

        if rhsm is not None:
            virt_setup_template['rhsm'] = {
                'login': rhsm.get('login'),
                'password': rhsm.get('password', os.environ.get('RHN_PW')),
                'pool_id': rhsm.get('pool_id', ''),
                'repositories': [i['name'] for i in repositories if i['type'] == 'rhsm_channel']
            }
        virt_setup_env = template.render(virt_setup_template)
        self.create_file('virt-setup-env', virt_setup_env, user='stack')
        self.run('virsh destroy instack', ignore_error=True)
        self.run('virsh undefine instack --remove-all-storage', ignore_error=True)
        self.run('source virt-setup-env; instack-virt-setup', user='stack')
        undercloud_ip = self.run(
            '/sbin/ip n | grep $(tripleo get-vm-mac instack) | awk \'{print $1;}\'',
            user='stack')[0]
        assert undercloud_ip, 'undercloud should have an IP'
        undercloud = Undercloud(hostname=undercloud_ip,
                                via_ip=self.hostname,
                                user='root',
                                key_filename=self._key_filename)
        return undercloud
542349
def _create_algo_bin(self, ro_rw_zi):
        """"""
        sect_ro, sect_rw, sect_zi = ro_rw_zi
        algo_size = sect_ro.length + sect_rw.length + sect_zi.length
        algo_data = bytearray(algo_size)
        for section in (sect_ro, sect_rw):
            start = section.start
            size = section.length
            data = section.data
            assert len(data) == size
            algo_data[start:start + size] = data
        return algo_data
399040
def create(self):
        
        if not self.linked_clone:
            yield from self._check_duplicate_linked_clone()

        yield from self.manager.check_vmrun_version()
        if self.linked_clone and not os.path.exists(os.path.join(self.working_dir, os.path.basename(self._vmx_path))):
            if self.manager.host_type == "player":
                raise VMwareError("Linked clones are not supported by VMware Player")
            # create the base snapshot for linked clones
            base_snapshot_name = "GNS3 Linked Base for clones"
            vmsd_path = os.path.splitext(self._vmx_path)[0] + ".vmsd"
            if not os.path.exists(vmsd_path):
                raise VMwareError("{} doesn't not exist".format(vmsd_path))
            try:
                vmsd_pairs = self.manager.parse_vmware_file(vmsd_path)
            except OSError as e:
                raise VMwareError('Could not read VMware VMSD file "{}": {}'.format(vmsd_path, e))
            gns3_snapshot_exists = False
            for value in vmsd_pairs.values():
                if value == base_snapshot_name:
                    gns3_snapshot_exists = True
                    break
            if not gns3_snapshot_exists:
                log.info("Creating snapshot '{}'".format(base_snapshot_name))
                yield from self._control_vm("snapshot", base_snapshot_name)

            # create the linked clone based on the base snapshot
            new_vmx_path = os.path.join(self.working_dir, self.name + ".vmx")
            yield from self._control_vm("clone",
                                        new_vmx_path,
                                        "linked",
                                        "-snapshot={}".format(base_snapshot_name),
                                        "-cloneName={}".format(self.name))

            try:
                vmsd_pairs = self.manager.parse_vmware_file(vmsd_path)
            except OSError as e:
                raise VMwareError('Could not read VMware VMSD file "{}": {}'.format(vmsd_path, e))

            snapshot_name = None
            for name, value in vmsd_pairs.items():
                if value == base_snapshot_name:
                    snapshot_name = name.split(".", 1)[0]
                    break

            if snapshot_name is None:
                raise VMwareError("Could not find the linked base snapshot in {}".format(vmsd_path))

            num_clones_entry = "{}.numClones".format(snapshot_name)
            if num_clones_entry in vmsd_pairs:
                try:
                    nb_of_clones = int(vmsd_pairs[num_clones_entry])
                except ValueError:
                    raise VMwareError("Value of {} in {} is not a number".format(num_clones_entry, vmsd_path))
                vmsd_pairs[num_clones_entry] = str(nb_of_clones - 1)

                for clone_nb in range(0, nb_of_clones):
                    clone_entry = "{}.clone{}".format(snapshot_name, clone_nb)
                    if clone_entry in vmsd_pairs:
                        del vmsd_pairs[clone_entry]

                try:
                    self.manager.write_vmware_file(vmsd_path, vmsd_pairs)
                except OSError as e:
                    raise VMwareError('Could not write VMware VMSD file "{}": {}'.format(vmsd_path, e))

            # update the VMX file path
            self._vmx_path = new_vmx_path