Build the main image to be used for launching containers
357214
def build_main_image_cmd(self, srcdir, force):
        
        check_permissions()

        basetag = self.conf.basetag
        basedir = self.conf.basedir
        maintag = self.conf.maintag

        if not self.image_exists(tag=basetag):
            if not force:
                exit("Base image with tag {0} does not exist".format(basetag))
            else:
                echo("FORCE given. Forcefully building the base image.")
                self.build_base_image_cmd(force)

        if self.image_exists(tag=maintag):
            self.remove_image(tag=maintag)

        build_command = "/build/make-install-gluster.sh"
        container = self.create_container(image=basetag, command=build_command,
                                          volumes=["/build", "/src"])

        self.start(container, binds={basedir: "/build", srcdir: "/src"})
        echo('Building main image')
        while self.inspect_container(container)["State"]["Running"]:
            time.sleep(5)

        if not self.inspect_container(container)["State"]["ExitCode"] == 0:
            echo("Build failed")
            echo("Dumping logs")
            echo(self.logs(container))
            exit()

        # The docker remote api expects the repository and tag to be seperate
        # items for commit
        repo = maintag.split(':')[0]
        tag = maintag.split(':')[1]
        image = self.commit(container['Id'], repository=repo, tag=tag)
        echo("Built main image {0} (Id: {1})".format(maintag, image['Id']))
355919
def main(name, output, font):
    

    # The path of the directory where the final files will end up in
    bootstrapped_directory = os.getcwd() + os.sep + name.lower().replace(' ', '-') +  os.sep

    # Copy the template files to the target directory
    copy_tree(get_real_path(os.sep + 'my-cool-os-template'), bootstrapped_directory)

    # Create the necessary assembly mov instructions for printing out the output on boot
    start_byte = int('0xb8000', 16)
    instructions_list = []

    for c in output:
        char_as_hex = '0x02'+ c.encode('hex')
        instructions_list.append('\tmov word [{0}], {1} ; {2}'.format(hex(start_byte), char_as_hex, c))
        start_byte += 2

    # Render the ASCII banner to be displayed in the README (A must for any serious hobby OS project!)
    banner = Figlet(font=font).renderText(name)

    render_template_file(bootstrapped_directory  + 'README.md', {'name' : name, 'banner' : banner})
    render_template_file(bootstrapped_directory  + 'grub.cfg' , {'name' : name})
    render_template_file(bootstrapped_directory  + 'boot.asm' , {'instructions_list' : instructions_list})

    print('finished bootstrapping project into directory ' + bootstrapped_directory)
137770
def main():
    """"""
    if (sys.version_info < (2, 7)):
        sys.exit("This program requires python version 2.7 or later")

    # Options and arguments
    p = optparse.OptionParser(description='IIIF Image API static file generator',
                              usage='usage: %prog [options] file [[file2..]] (-h for help)',
                              version='%prog ' + __version__)

    p.add_option('--dst', '-d', action='store', default='/tmp',
                 help="Destination directory for images [default '%default']")
    p.add_option('--tilesize', '-t', action='store', type='int', default=512,
                 help="Tilesize in pixels [default %default]")
    p.add_option('--api-version', '--api', '-a', action='store', default='2.1',
                 help="API version, may be 1.1, 2.0 or 2.1 [default %default]")
    p.add_option('--prefix', '-p', action='store', default=None,
                 help="URI prefix for where the images will be served from (default '%default'). "
                      "An empty prefix may be OK if the HTML page including the image shares the "
                      "the same root on the same server as the images, otherwise a full URL should "
                      "be specified. This is used to construct the @id in the info.json")
    p.add_option('--identifier', '-i', action='store', default=None,
                 help="Identifier for the image that will be used in place of the filename "
                      "(minus extension). Notes that this option cannot be used if more than "
                      "one image file is to be processed")
    p.add_option('--extra', '-e', action='append', default=[],
                 help="Extra request parameters to be used to generate static files, may be "
                      "repeated (e.g. '/full/90,/0/default.jpg' for a 90 wide thumnail)")
    p.add_option('--write-html', action='store', default=None,
                 help="Write HTML page to the specified directory using the 'identifier.html' "
                      "as the filename. HTML will launch OpenSeadragon for this image and to "
                      "display some of information about info.json and tile locations. HTML will "
                      "assume OpenSeadragon at relative path openseadragonVVV/openseadragon.min.js "
                      "and user-interface icons in openseadragonVVV/images, where VVV are the "
                      "three parts of the version number. The --include-osd flag is also specified "
                      "then OpenSeadragon will be copied to these locations")
    p.add_option('--include-osd', action='store_true',
                 help="Include OpenSeadragon files with --write-html flag")
    p.add_option('--osd-version', action='store', default='2.0.0',
                 help="Generate static images for older versions of OpenSeadragon. Use of versions "
                      "prior to 1.2.1 will force use of /w,h/ for size parameter instead of /w,/. "
                      "Likely useful only in combination with --api-version=1.1 "
                      "[default %default]")
    p.add_option('--osd-width', action='store', type='int', default='500',
                 help="Width of OpenSeadragon pane in pixels. Applies only with "
                      "--write-html [default %default]")
    p.add_option('--osd-height', action='store', type='int', default='500',
                 help="Height of OpenSeadragon pane in pixels. Applies only with "
                      "--write-html [default %default]")
    p.add_option('--generator', action='store_true', default=False,
                 help="Use named generator modules in iiif.generators package instead "
                      "of a starting image [default %default]")
    p.add_option('--max-image-pixels', action='store', type='int', default=0,
                 help="Set the maximum number of pixels in an image. A non-zero value "
                      "will set a hard limit on the image size. If left unset then the "
                      "default configuration of the Python Image Libary (PIL) will give "
                      "a DecompressionBombWarning if the image size exceeds a default "
                      "maximum, but otherwise continue as normal")
    p.add_option('--dryrun', '-n', action='store_true',
                 help="Do not write anything, say what would be done")
    p.add_option('--quiet', '-q', action='store_true',
                 help="Quite (no output unless there is a warning/error)")
    p.add_option('--verbose', '-v', action='store_true',
                 help="Verbose")

    (opt, sources) = p.parse_args()

    level = logging.DEBUG if (opt.verbose) else \
        logging.WARNING if (opt.quiet) else logging.INFO
    logging.basicConfig(format='%(name)s: %(message)s',
                        level=level)
    logger = logging.getLogger(os.path.basename(__file__))

    if (not opt.write_html and opt.include_osd):
        logger.warn(
            "--include-osd has no effect without --write-html, ignoring")
    if (len(sources) == 0):
        logger.warn("No sources specified, nothing to do, bye! (-h for help)")
    elif (len(sources) > 1 and opt.identifier):
        logger.error(
            "Cannot use --identifier/-i option with multiple sources, aborting.")
    else:
        try:
            sg = IIIFStatic(dst=opt.dst, tilesize=opt.tilesize,
                            api_version=opt.api_version, dryrun=opt.dryrun,
                            prefix=opt.prefix, osd_version=opt.osd_version,
                            generator=opt.generator,
                            max_image_pixels=opt.max_image_pixels,
                            extras=opt.extra)
            for source in sources:
                # File or directory (or neither)?
                if (os.path.isfile(source) or opt.generator):
                    logger.info("source file: %s" % (source))
                    sg.generate(source, identifier=opt.identifier)
                    if (opt.write_html):
                        sg.write_html(html_dir=opt.write_html, include_osd=opt.include_osd,
                                      osd_width=opt.osd_width, osd_height=opt.osd_height)
                elif (os.path.isdir(source)):
                    logger.warn(
                        "Ignoring source '%s': directory coversion not supported" % (source))
                else:
                    logger.warn(
                        "Ignoring source '%s': neither file nor path" % (source))
        except (IIIFStaticError, IIIFError) as e:
            # catch known errors and report nicely...
            logger.error("Error: " + str(e))
314765
function initContainer(opts) {
    var apps, appDir;

    container = opts.container;

    // if batch, preload that dir
    container === 'batch' ?
        opts.preload.push('batch') :
        opts.preload.push('middleware');

    if (container === 'webserver') {
        appDir = path.join(opts.rootDir, '/app');
        apps = fs.readdirSync(appDir);
        _.each(apps, function (app) {
            opts.preload = opts.preload.concat([
                'app/' + app + '/filters',
                'app/' + app + '/utils'
            ]);
        });
    }

    init(opts);
}
1364867
def make_image(self, conf, images, chain=None, parent_chain=None, made=None, ignore_deps=False, ignore_parent=False, pushing=False):
        """"""
        made = {} if made is None else made
        chain = [] if chain is None else chain
        parent_chain = [] if parent_chain is None else parent_chain

        if conf.name in made:
            return

        if conf.name in chain and not ignore_deps:
            raise BadCommand("Recursive dependency images", chain=chain + [conf.name])

        if conf.name in parent_chain and not ignore_parent:
            raise BadCommand("Recursive FROM statements", chain=parent_chain + [conf.name])

        if conf.name not in images:
            raise NoSuchImage(looking_for=conf.name, available=images.keys())

        if not ignore_deps:
            for dependency, image in conf.dependency_images():
                self.make_image(images[dependency], images, chain=chain + [conf.name], made=made, pushing=pushing)

        if not ignore_parent:
            for dep in conf.commands.dependent_images:
                if not isinstance(dep, six.string_types):
                    self.make_image(dep, images, chain, parent_chain + [conf.name], made=made, pushing=pushing)

        # Should have all our dependencies now
        log.info("Making image for '%s' (%s)", conf.name, conf.image_name)
        cached = self.build_image(conf, pushing=pushing)
        made[conf.name] = True
        return cached
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)
466905
def render_import_image(self, use_auth=None):
        
        # import_image is a multi-phase plugin
        phases = ('postbuild_plugins', 'exit_plugins')
        plugin = 'import_image'

        for phase in phases:
            if self.spec.imagestream_name.value is None or self.spec.imagestream_url.value is None:
                logger.info("removing %s from request, "
                            "registry or repo url is not defined", plugin)
                self.dj.remove_plugin(phase, plugin)
                continue

            if self.dj.dock_json_has_plugin_conf(phase, plugin):
                self.dj.dock_json_set_arg(phase, plugin, 'imagestream',
                                          self.spec.imagestream_name.value)
                self.dj.dock_json_set_arg(phase, plugin, 'docker_image_repo',
                                          self.spec.imagestream_url.value)
                self.dj.dock_json_set_arg(phase, plugin, 'url',
                                          self.spec.builder_openshift_url.value)
                self.dj.dock_json_set_arg(phase, plugin, 'build_json_dir',
                                          self.spec.builder_build_json_dir.value)

                use_auth = self.spec.use_auth.value
                if use_auth is not None:
                    self.dj.dock_json_set_arg(phase, plugin, 'use_auth', use_auth)

                if self.spec.imagestream_insecure_registry.value:
                    self.dj.dock_json_set_arg(phase, plugin, 'insecure_registry', True)
825315
def _build_arguments(self):
        
        self._parser.add_argument(
            'image_name',
            metavar='IMAGE_NAME',
            type=six.text_type,
            help='Name of the image example: \"namespace/repository\"'
        )
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 );
		}
	}
126585
def main(input_file, output, format):
    """"""

    try:
        process_image(input_file, subfolder=output, ext=format)
    except Exception as e:
        sys.exit(e)
201206
def build(path: str) -> dict:
    """"""
    update_base_image(path)
    match = file_pattern.search(os.path.basename(path))
    build_id = match.group('id')
    tags = [
        '{}:{}-{}'.format(HUB_PREFIX, version, build_id),
        '{}:latest-{}'.format(HUB_PREFIX, build_id),
        '{}:current-{}'.format(HUB_PREFIX, build_id)
    ]
    if build_id == 'standard':
        tags.append('{}:latest'.format(HUB_PREFIX))

    command = 'docker build --file "{}" {} .'.format(
        path,
        ' '.join(['-t {}'.format(t) for t in tags])
    )

    print('[BUILDING]:', build_id)
    os.system(command)

    return dict(
        id=build_id,
        path=path,
        command=command,
        tags=tags
    )
1115741
def BuildTemplate(self,
                    context=None,
                    output=None,
                    fleetspeak_service_config=None):
    """"""
    context = context or []
    context.append("Arch:%s" % self.GetArch())
    # Platform context has common platform settings, Target has template build
    # specific stuff.
    self.platform = platform.system()
    context.append("Platform:%s" % self.platform)
    context.append("Target:%s" % self.platform)
    if "Target:Linux" in context:
      context.append(self.GetPackageFormat())

    template_path = None
    if output:
      template_path = os.path.join(
          output,
          grr_config.CONFIG.Get(
              "PyInstaller.template_filename", context=context))

    builder_obj = self.GetBuilder(context, fleetspeak_service_config)
    builder_obj.MakeExecutableTemplate(output_file=template_path)
129439
def build_base_image_cmd(self, force):
        
        check_permissions()

        basetag = self.conf.basetag
        basedir = self.conf.basedir
        verbose = self.conf.verbose

        if self.image_exists(tag=basetag):
            if not force:
                echo("Image with tag '{0}' already exists".format(basetag))
                return self.image_by_tag(basetag)
            else:
                self.remove_image(basetag)
        echo("Building base image")
        stream = self.build(path=basedir, rm=True, tag=basetag)
        err = self.__handle_build_stream(stream, verbose)
        if err:
            echo("Building base image failed with following error:")
            echo(err)
            return None

        image = self.image_by_tag(basetag)
        echo("Built base image {0} (Id: {1})".format(basetag, image['Id']))
        return image
619769
def real_main(release_url=None,
              tests_json_path=None,
              upload_build_id=None,
              upload_release_name=None):
    """"""
    coordinator = workers.get_coordinator()
    fetch_worker.register(coordinator)
    coordinator.start()

    data = open(FLAGS.tests_json_path).read()
    tests = load_tests(data)

    item = DiffMyImages(
        release_url,
        tests,
        upload_build_id,
        upload_release_name,
        heartbeat=workers.PrintWorkflow)
    item.root = True

    coordinator.input_queue.put(item)
    coordinator.wait_one()
    coordinator.stop()
    coordinator.join()
856931
def Build(self):
    """"""
    self.SetupVars()
    self.Clean()

    if not os.path.exists(args.grr_src):
      self.GitCheckoutGRR()
    proto_sdist = self.MakeProtoSdist()
    core_sdist = self.MakeCoreSdist()
    client_sdist = self.MakeClientSdist()
    client_builder_sdist = self.MakeClientBuilderSdist()

    self.InstallGRR(proto_sdist)
    self.InstallGRR(core_sdist)
    self.InstallGRR(client_sdist)
    self.InstallGRR(client_builder_sdist)
    self.BuildTemplates()
    if args.test_repack_install:
      self._RepackTemplates()
      self._InstallInstallers()
108154
def create(image_data):
        

        # convert environment variables to Kubernetes objects
        env_variables = []
        for key, value in image_data.env_variables.items():
            env_variables.append(client.V1EnvVar(name=key, value=value))

        # convert exposed ports to Kubernetes objects
        exposed_ports = []
        if image_data.exposed_ports is not None:
            for port in image_data.exposed_ports:
                splits = port.split("/", 1)
                port = int(splits[0])
                protocol = splits[1].upper() if len(splits) > 1 else None
                exposed_ports.append(client.V1ContainerPort(container_port=port, protocol=protocol))

        # generate container name {image-name}-{username}-{random-4-letters}
        # take just name of image and remove tag
        image_name = image_data.name.split("/")[-1].split(":")[0]
        random_string = ''.join(
            random.choice(string.ascii_lowercase + string.digits) for _ in range(4))
        container_name = '{image_name}-{user_name}-{random_string}'.format(
            image_name=image_name,
            user_name=getpass.getuser(),
            random_string=random_string)

        container = client.V1Container(command=image_data.command,
                                       env=env_variables,
                                       image=image_data.name,
                                       name=container_name,
                                       ports=exposed_ports)

        pod_metadata = client.V1ObjectMeta(name=container_name + "-pod")
        pod_spec = client.V1PodSpec(containers=[container])
        pod = client.V1Pod(spec=pod_spec, metadata=pod_metadata)

        return pod
10579
def stage(self, startimage, newimage):
        
        client = utils.get_client()
        cprint('  Copying file from "%s:/%s" \n                 to "%s://%s/"'
               % (self.sourceimage, self.sourcepath, startimage, self.destpath),
               'blue')

        # copy build artifacts from the container if necessary
        cachedir = self._setcache(client)
        cacherelpath = os.path.relpath(cachedir, TMPDIR)

        # if cached file doesn't exist (presumably purged by OS), trigger it to be recreated
        if os.path.exists(cachedir) and not os.path.exists(os.path.join(cachedir, 'content.tar')):
            shutil.rmtree(cachedir)

        if not os.path.exists(cachedir):
            print(' * Creating cache at %s' % cacherelpath)
            container = client.containers.create(self.sourceimage)
            try:
                tarfile_stream, tarfile_stats = container.get_archive(self.sourcepath)
            except docker.errors.NotFound:
                raise errors.MissingFileError(
                        'Cannot copy file "%s" from image "%s" - it does not exist!' %
                        (self.sourcepath, self.sourceimage))

            # write files to disk (would be nice to stream them, haven't gotten it to work)
            tempdir = tempfile.mkdtemp(dir=BUILD_TEMPDIR)
            with open(os.path.join(tempdir, 'content.tar'), 'wb') as localfile:
                for chunk in tarfile_stream:
                    localfile.write(chunk)
            os.mkdir(cachedir)
            os.rename(tempdir, cachedir)
        else:
            print('  Using cached files from %s' % cacherelpath)

        # write Dockerfile for the new image and then build it
        dockerfile = 'FROM %s\nADD content.tar %s' % (startimage, self.destpath)
        with open(os.path.join(cachedir, 'Dockerfile'), 'w') as df:
            df.write(dockerfile)

        buildargs = dict(path=cachedir,
                         tag=newimage,
                         decode=True)
        utils.set_build_cachefrom(self.cache_from, buildargs, client)

        # Build and show logs
        stream = client.api.build(**buildargs)
        try:
            utils.stream_docker_logs(stream, newimage)
        except ValueError as e:
            raise errors.BuildError(dockerfile, e.args[0], build_args=buildargs)