Create OpenVZ containers.

    + ctid: CTID of the container to create
434164
def create(state, host, ctid, template=None):
    '''
    
    '''

    # Check we don't already have a container with this CTID
    current_containers = host.fact.openvz_containers
    if ctid in current_containers:
        raise OperationError(
            'An OpenVZ container with CTID {0} already exists'.format(ctid),
        )

    args = ['{0}'.format(ctid)]

    if template:
        args.append('--ostemplate {0}'.format(template))

    yield 'vzctl create {0}'.format(' '.join(args))
485477
def create(self, name, plugin_name, plugin_version, flavor_id,
               description=None, volumes_per_node=None, volumes_size=None,
               node_processes=None, node_configs=None, floating_ip_pool=None,
               security_groups=None, auto_security_group=None,
               availability_zone=None, volumes_availability_zone=None,
               volume_type=None, image_id=None, is_proxy_gateway=None,
               volume_local_to_instance=None, use_autoconfig=None,
               shares=None, is_public=None, is_protected=None,
               volume_mount_prefix=None, boot_from_volume=None,
               boot_volume_type=None, boot_volume_availability_zone=None,
               boot_volume_local_to_instance=None):
        """"""

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

        return self._do_create(data, description, volumes_per_node,
                               volumes_size, node_configs, floating_ip_pool,
                               security_groups, auto_security_group,
                               availability_zone, volumes_availability_zone,
                               volume_type, image_id, is_proxy_gateway,
                               volume_local_to_instance, use_autoconfig,
                               shares, is_public, is_protected,
                               volume_mount_prefix, boot_from_volume,
                               boot_volume_type,
                               boot_volume_availability_zone,
                               boot_volume_local_to_instance)
1165916
function (elementId, containerId) {
            var container = this.$containers[containerId];
            if (!container) {
                // TODO: remove this shit
                container = this.createContainer({'class': containerId + "-container"});
                this.$containers[containerId] = container;
                this.addChild(container);
                if (this.$containerOrder[containerId]) {
                    container.setChildIndex(this.$containerOrder[containerId]);
                }
            }

            var element = this.$elements[containerId + "_" + elementId];
            if (!element) {
                element = this.createContainer({});
                container.addChild(element);
            }

            return element.$el;
        }
1336867
def create_runtime(self,
                       env,            # type: MutableMapping[Text, Text]
                       runtime_context  # type: RuntimeContext
                      ):  # type: (...) -> Tuple[List, Optional[Text]]
        
        any_path_okay = self.builder.get_requirement("DockerRequirement")[1] \
            or False
        runtime = [u"singularity", u"--quiet", u"exec", u"--contain", u"--pid",
                   u"--ipc"]
        if _singularity_supports_userns():
            runtime.append(u"--userns")
        runtime.append(u"--bind")
        runtime.append(u"{}:{}:rw".format(
            docker_windows_path_adjust(os.path.realpath(self.outdir)),
            self.builder.outdir))
        runtime.append(u"--bind")
        tmpdir = "/tmp"  # nosec
        runtime.append(u"{}:{}:rw".format(
            docker_windows_path_adjust(os.path.realpath(self.tmpdir)), tmpdir))

        self.add_volumes(self.pathmapper, runtime, any_path_okay=True,
                         secret_store=runtime_context.secret_store,
                         tmpdir_prefix=runtime_context.tmpdir_prefix)
        if self.generatemapper is not None:
            self.add_volumes(
                self.generatemapper, runtime, any_path_okay=any_path_okay,
                secret_store=runtime_context.secret_store,
                tmpdir_prefix=runtime_context.tmpdir_prefix)

        runtime.append(u"--pwd")
        runtime.append(u"%s" % (docker_windows_path_adjust(self.builder.outdir)))

        if runtime_context.custom_net:
            raise UnsupportedRequirement(
                "Singularity implementation does not support custom networking")
        elif runtime_context.disable_net:
            runtime.append(u"--net")

        env["SINGULARITYENV_TMPDIR"] = tmpdir
        env["SINGULARITYENV_HOME"] = self.builder.outdir

        for name, value in self.environment.items():
            env["SINGULARITYENV_{}".format(name)] = str(value)
        return (runtime, None)
1318211
def container_new_folder(object_id, input_params={}, always_retry=True, **kwargs):
    
    return DXHTTPRequest('/%s/newFolder' % object_id, input_params, always_retry=always_retry, **kwargs)
583499
def create_container(self, image, name=None, **kwargs):
        
        name_str = " '{0}'".format(name) if name else ""
        self.push_log("Creating container{0} from image '{1}'.".format(name_str, image))
        return super(DockerFabricClient, self).create_container(image, name=name, **kwargs)
861092
def _create_container_args(kwargs):
    
    # Copy over kwargs which can be copied directly
    create_kwargs = {}
    for key in copy.copy(kwargs):
        if key in RUN_CREATE_KWARGS:
            create_kwargs[key] = kwargs.pop(key)
    host_config_kwargs = {}
    for key in copy.copy(kwargs):
        if key in RUN_HOST_CONFIG_KWARGS:
            host_config_kwargs[key] = kwargs.pop(key)

    # Process kwargs which are split over both create and host_config
    ports = kwargs.pop('ports', {})
    if ports:
        host_config_kwargs['port_bindings'] = ports

    volumes = kwargs.pop('volumes', {})
    if volumes:
        host_config_kwargs['binds'] = volumes

    network = kwargs.pop('network', None)
    if network:
        create_kwargs['networking_config'] = {network: None}
        host_config_kwargs['network_mode'] = network

    # All kwargs should have been consumed by this point, so raise
    # error if any are left
    if kwargs:
        raise create_unexpected_kwargs_error('run', kwargs)

    create_kwargs['host_config'] = HostConfig(**host_config_kwargs)

    # Fill in any kwargs which need processing by create_host_config first
    port_bindings = create_kwargs['host_config'].get('PortBindings')
    if port_bindings:
        # sort to make consistent for tests
        create_kwargs['ports'] = [tuple(p.split('/', 1))
                                  for p in sorted(port_bindings.keys())]
    if volumes:
        if isinstance(volumes, dict):
            create_kwargs['volumes'] = [
                v.get('bind') for v in volumes.values()
            ]
        else:
            create_kwargs['volumes'] = [
                _host_volume_from_bind(v) for v in volumes
            ]
    return create_kwargs
58112
void createContainer( String imageId ) throws TargetException {

		// Get the command to pass to the container
		this.logger.info( "Creating container " + this.machineId + " from image " + imageId );

		// Extract parameters as local variables
		Map<String,String> targetProperties = this.parameters.getTargetProperties();
		String applicationName = this.parameters.getApplicationName();
		String scopedInstancePath = this.parameters.getScopedInstancePath();

		// Deal with the Docker run options
		Map<String,String> options = new HashMap<> ();
		for( Map.Entry<String,String> entry : targetProperties.entrySet()) {
			if( entry.getKey().toLowerCase().startsWith( OPTION_PREFIX_RUN )) {
				String key = entry.getKey().substring( OPTION_PREFIX_RUN.length());
				options.put( key, entry.getValue());
			}
		}

		// Deal with environment variables (user)
		List<String> env = new ArrayList<> ();
		for( Map.Entry<String,String> entry : targetProperties.entrySet()) {
			if( entry.getKey().toLowerCase().startsWith( OPTION_PREFIX_ENV )) {

				String key = entry.getKey().substring( OPTION_PREFIX_ENV.length());
				String value = entry.getValue();

				value = value.replace( "<application-name>", applicationName );
				value = value.replace( "<scoped-instance-path>", scopedInstancePath );
				value = value.replace( "<scoped-messaging_type>", Utils.getValue(
						this.parameters.getMessagingProperties(),
						MessagingConstants.MESSAGING_TYPE_PROPERTY,
						"" ));

				env.add( key + "=" + value );
			}
		}

		// Deal with environment variables (default one: the Roboconf version)
		String rbcfVersion = DockerUtils.findDefaultImageVersion( ManifestUtils.findBundleVersion());
		env.add( "RBCF_VERSION=" + rbcfVersion );

		// Deal with environment variables (default one: the user data)
		env.add( "AGENT_PARAMETERS=file:" + USER_DATA_DIR + USER_DATA_FILE );

		// Execute...
		try {
			String containerName = DockerUtils.buildContainerNameFrom( scopedInstancePath, applicationName );

			// Create a volume
			File dir = new File( this.userDataVolume, containerName );
			Utils.createDirectory( dir );
			this.containerIdToVolume.put( containerName, dir );

			String userData = UserDataHelpers.writeUserDataAsString(
					this.parameters.getMessagingProperties(),
					this.parameters.getDomain(),
					this.parameters.getApplicationName(),
					this.parameters.getScopedInstancePath());

			Utils.writeStringInto( userData, new File( dir, USER_DATA_FILE ));
			Volume volume = new Volume( USER_DATA_DIR );
			Bind volumeBind = new Bind( dir.getAbsolutePath(), volume );

			// Create the container
			CreateContainerCmd cmd = this.dockerClient.createContainerCmd( imageId )
					.withName( containerName )
					.withEnv( env )
					.withVolumes( Arrays.asList( volume ))
					.withBinds( Arrays.asList( volumeBind ));

			DockerUtils.configureOptions( options, cmd );
			CreateContainerResponse container = cmd.exec();

			// Log warnings, if any
			if( container.getWarnings() != null
					&& container.getWarnings().length > 0
					&& this.logger.isLoggable( Level.FINE )) {

				StringBuilder sb = new StringBuilder();
				sb.append( "The following warnings have been found.\n" );
				for( String s : container.getWarnings())
					sb.append( s ).append( '\n' );

				this.logger.fine( sb.toString().trim());
			}

			// And start the container
			this.dockerClient.startContainerCmd( container.getId()).exec();

			// We're done here!
			this.logger.fine( "Container " + this.machineId + " was succesfully created as " + container.getId());

			// We replace the machine ID in the instance.
			// The configurator will be stopped anyway.
			this.parameters.getScopedInstance().data.put( Instance.MACHINE_ID, container.getId());

		} catch( Exception e ) {
			throw new TargetException( e );
		}
	}
166745
def create(self, ids):
        

        url = build_uri_with_ids('api/v3/pool/deploy/%s/', ids)
        return super(ApiPoolDeploy, self).post(url)
547757
def create_tomodir(self, directory):
        
        pwd = os.getcwd()
        if not os.path.isdir(directory):
            os.makedirs(directory)
        os.chdir(directory)

        directories = (
            'config',
            'exe',
            'grid',
            'mod',
            'mod/pot',
            'mod/sens',
            'rho',
        )
        for directory in directories:
            if not os.path.isdir(directory):
                os.makedirs(directory)

        os.chdir(pwd)
1331841
def creator(entry, config):
        """"""
        template_file = os.path.join(os.path.dirname(__file__), 'templates/docker-container.sh.j2')

        with open(template_file) as handle:
            template = handle.read()
            # all fields are re-rendered via the Bash script
            wrapped_script = render(template, container={
                'image': 'centos:7' if 'image' not in entry else entry['image'],
                'remove': True if 'remove' not in entry else str(entry['remove']).lower(),
                'background': False if 'background' not in entry else str(entry['background']).lower(),
                'mount': False if 'mount' not in entry else str(entry['mount']).lower(),
                'network': '' if 'network' not in entry else entry['network'],
                'labels': {} if 'labels' not in entry else entry['labels'],
                'script': config.script
            })

            config.script = wrapped_script

        return Container(config)
929672
def create_volume(client, resource_group_name,
                  name, location,
                  template_file=None, template_uri=None):
    
    volume_properties = None

    if template_uri:
        volume_properties = shell_safe_json_parse(_urlretrieve(template_uri).decode('utf-8'), preserve_order=True)
    elif template_file:
        volume_properties = get_file_json(template_file, preserve_order=True)
        volume_properties = json.loads(json.dumps(volume_properties))
    else:
        raise CLIError('One of --template-file or --template-uri has to be specified')

    volume_properties['location'] = location
    return client.create(resource_group_name, name, volume_properties)
1154641
def create(self, client_id, name, html_url, zip_url):
        """"""
        body = {
            "Name": name,
            "HtmlPageURL": html_url,
            "ZipFileURL": zip_url}
        response = self._post("/templates/%s.json" %
                              client_id, json.dumps(body))
        self.template_id = json_to_py(response)
        return self.template_id
1188337
def create(vm_):
    '''
    

    '''
    name = vm_['name']
    record = {}
    ret = {}

    # fire creating event
    __utils__['cloud.fire_event'](
        'event',
        'starting create',
        'salt/cloud/{0}/creating'.format(name),
        args={
            'name': name,
            'profile': vm_['profile'],
            'provider': vm_['driver'],
        },
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )
    log.debug('Adding %s to cloud cache.', name)
    __utils__['cloud.cachedir_index_add'](
        vm_['name'], vm_['profile'], 'xen', vm_['driver']
    )

    # connect to xen
    session = _get_session()

    # determine resource pool
    resource_pool = _determine_resource_pool(session, vm_)

    # determine storage repo
    storage_repo = _determine_storage_repo(session, resource_pool, vm_)

    # build VM
    image = vm_.get('image')
    clone = vm_.get('clone')
    if clone is None:
        clone = True
    log.debug('Clone: %s ', clone)

    # fire event to read new vm properties (requesting)
    __utils__['cloud.fire_event'](
        'event',
        'requesting instance',
        'salt/cloud/{0}/requesting'.format(name),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    # create by cloning template
    if clone:
        _clone_vm(image, name, session)
    else:
        _copy_vm(image, name, session, storage_repo)

    # provision template to vm
    _provision_vm(name, session)
    vm = _get_vm(name, session)

    # start vm
    start(name, None, session)

    # get new VM
    vm = _get_vm(name, session)

    # wait for vm to report IP via guest tools
    _wait_for_ip(name, session)

    # set static IP if configured
    _set_static_ip(name, session, vm_)

    # if not deploying salt then exit
    deploy = vm_.get('deploy', True)
    log.debug('delopy is set to %s', deploy)
    if deploy:
        record = session.xenapi.VM.get_record(vm)
        if record is not None:
            _deploy_salt_minion(name, session, vm_)
    else:
        log.debug(
            'The Salt minion will not be installed, deploy: %s',
            vm_['deploy']
        )
    record = session.xenapi.VM.get_record(vm)
    ret = show_instance(name)
    ret.update({'extra': record})

    __utils__['cloud.fire_event'](
        'event',
        'created instance',
        'salt/cloud/{0}/created'.format(name),
        args={
            'name': name,
            'profile': vm_['profile'],
            'provider': vm_['driver'],
        },
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )
    return ret
699281
def create(cls, interface_id, logical_interface_ref,
            second_interface_id=None, zone_ref=None, **kwargs):
        
        data = {'inspect_unspecified_vlans': True,
                'nicid': '{}-{}'.format(str(interface_id), str(second_interface_id)) if 
                    second_interface_id else str(interface_id),
                'logical_interface_ref': logical_interface_ref,
                'zone_ref': zone_ref}

        for k, v in kwargs.items():
            data.update({k: v})

        return cls(data)
259935
async def container(self, container=None, container_type=None, params=None):
        
        if hasattr(container_type, 'blob_serialize'):
            container = container_type() if container is None else container
            return await container.blob_serialize(self, elem=container, elem_type=container_type, params=params)

        # Container entry version + container
        if self.writing:
            return await self.container_dump(container, container_type, params)
        else:
            return await self.container_load(container_type, params=params, container=container)
783536
def start(state, host, ctid, force=False):
    '''
    
    '''

    args = ['{0}'.format(ctid)]

    if force:
        args.append('--force')

    yield 'vzctl start {0}'.format(' '.join(args))