Build docker image containing specified plugins.
19059
public String buildImage(Map<String, File> plugins) throws IOException, InterruptedException {
        LOG.debug("Building image for {}", plugins);
//        final File tempDirectory = TempFileHelper.createTempDirectory("build-image", targetDir().toPath());
        final File buildDir = new File(targetDir().getAbsolutePath() + "/docker-it/build-image");
        if (buildDir.exists()) {
            deleteDirectory(buildDir);
        }
        if (!buildDir.mkdirs()) {
            throw new IllegalStateException("Can't create temp directory " + buildDir.getAbsolutePath());
        }

        final String dockerfile = generateDockerfileFor(plugins);
        final File dockerfileFile = new File(buildDir, "Dockerfile");
        writeStringToFile(dockerfileFile, dockerfile);

        final File buildHomePath = new File(buildDir, JenkinsDockerImage.JENKINS_DEFAULT.homePath);
        final File jenkinsConfig = new File(buildHomePath, "config.xml");
        DockerHPIContainerUtil.copyResourceFromClass(DockerHPIContainerUtil.class, "config.xml", jenkinsConfig);
        writeStringToFile(new File(buildHomePath, "jenkins.install.UpgradeWizard.state"), "2.19.4");
        writeStringToFile(new File(buildHomePath, "jenkins.install.InstallUtil.lastExecVersion"), "2.19.4");

        final File pluginDir = new File(buildHomePath, "/plugins/");
        if (!pluginDir.mkdirs()) {
            throw new IllegalStateException("Can't create dirs " + pluginDir.getAbsolutePath());
        }

        for (Map.Entry<String, File> entry : plugins.entrySet()) {
            final File dst = new File(pluginDir + "/" + entry.getKey());
            copyFile(entry.getValue(), dst);
        }

        try {
            LOG.info("Building data-image...");
            return getDockerCli().buildImageCmd(buildDir)
                    .withTag(DATA_IMAGE)
                    .withForcerm(true)
                    .exec(new BuildImageResultCallback() {
                        public void onNext(BuildResponseItem item) {
                            String text = item.getStream();
                            if (nonNull(text)) {
                                LOG.debug(StringUtils.removeEnd(text, NL));
                            }
                            super.onNext(item);
                        }
                    })
                    .awaitImageId();
        } finally {
            buildDir.delete();
        }

    }
38936
def dockerfile_lines(self):
        
        w1 = colored(
                'WARNING: this build includes files that are built in other images!!! The generated'
                '\n         Dockerfile must be built in a directory that contains'
                ' the file/directory:',
                'red', attrs=['bold'])
        w2 = colored('         ' + self.sourcepath, 'red')
        w3 = (colored('         from image ', 'red')
              + colored(self.sourcepath, 'blue', attrs=['bold']))
        print('\n'.join((w1, w2, w3)))
        return ["",
                "# Warning: the file \"%s\" from the image \"%s\""
                " must be present in this build context!!" %
                (self.sourcepath, self.sourceimage),
                "ADD %s %s" % (os.path.basename(self.sourcepath), self.destpath),
                '']
856772
def build(image, build_path, tag=None, build_args=None, fromline=None, args=[]):
    

    if tag:
        image = ":".join([image, tag])

    bdir = tempfile.mkdtemp()
    os.system('cp -r {0:s}/* {1:s}'.format(build_path, bdir))
    if build_args:
        stdw = tempfile.NamedTemporaryFile(dir=bdir, mode='w')
        with open("{}/Dockerfile".format(bdir)) as std:
            dfile = std.readlines()

        for line in dfile:
            if fromline and line.lower().startswith('from'):
                stdw.write('FROM {:s}\n'.format(fromline))
            elif line.lower().startswith("cmd"):
                for arg in build_args:
                    stdw.write(arg+"\n")
                stdw.write(line)
            else:
                stdw.write(line)
        stdw.flush()
        utils.xrun("docker build", args+["--force-rm","-f", stdw.name, 
                   "-t", image, 
                    bdir])

        stdw.close()
    else:
        utils.xrun("docker build", args+["--force-rm", "-t", image, 
                    bdir])

    os.system('rm -rf {:s}'.format(bdir))
398053
private File createBuildTarBall(BuildDirs buildDirs, List<ArchiverCustomizer> archiverCustomizers,
                                    AssemblyConfiguration assemblyConfig, ArchiveCompression compression) throws MojoExecutionException {
        File archive = new File(buildDirs.getTemporaryRootDirectory(), "docker-build." + compression.getFileSuffix());
        try {
            TarArchiver archiver = createBuildArchiver(buildDirs.getOutputDirectory(), archive, assemblyConfig);
            for (ArchiverCustomizer customizer : archiverCustomizers) {
                if (customizer != null) {
                    archiver = customizer.customize(archiver);
                }
            }
            archiver.setCompression(compression.getTarCompressionMethod());
            archiver.createArchive();
            return archive;
        } catch (NoSuchArchiverException e) {
            throw new MojoExecutionException("No archiver for type 'tar' found", e);
        } catch (IOException e) {
            throw new MojoExecutionException("Cannot create archive " + archive, e);
        }
    }
334542
def generate_docker_file(py_ver: PyVer):
    """"""
    with open(os.path.join(script_templates_root, 'Dockerfile')) as fh:
        return fh.read().format(py_ver=py_ver, author=author_file)
615507
def build(client, repository_tag, docker_file, tag=None, use_cache=False):
        
        if not isinstance(client, docker.Client):
            raise TypeError("client needs to be of type docker.Client.")

        if not isinstance(docker_file, six.string_types) or not os.path.exists(docker_file):
            # TODO: need to add path stuff for git and http etc.
            raise Exception("docker file path doesn't exist: {0}".format(docker_file))

        if not isinstance(repository_tag, six.string_types):
            raise TypeError('repository must be a string')

        if not tag:
            tag = 'latest'

        if not isinstance(use_cache, bool):
            raise TypeError("use_cache must be a bool. {0} was passed.".format(use_cache))

        no_cache = not use_cache

        if ':' not in repository_tag:
            repository_tag = "{0}:{1}".format(repository_tag, tag)
        file_obj = None
        try:
            if os.path.isfile(docker_file):
                path = os.getcwd()
                docker_file = "./{0}".format(os.path.relpath(docker_file))

                # TODO: support using file_obj in the future. Needed for post pre hooks and the injector.
                # with open(docker_file) as Dockerfile:
                #     testing = Dockerfile.read()
                #     file_obj = BytesIO(testing.encode('utf-8'))

                response = client.build(
                    path=path,
                    nocache=no_cache,
                    # custom_context=True,
                    dockerfile=docker_file,
                    # fileobj=file_obj,
                    tag=repository_tag,
                    rm=True,
                    stream=True
                )
            else:
                response = client.build(path=docker_file, tag=repository_tag, rm=True, nocache=no_cache, stream=True)
        except Exception as e:
            raise e
        finally:
            if file_obj:
                file_obj.close()

        parse_stream(response)
        client.close()

        return Image(client, repository_tag)
173499
def creator(entry, config):
        """"""
        # writing Dockerfile
        dockerfile = render(config.script, model=config.model, env=config.env,
                            variables=config.variables, item=config.item)
        filename = "dockerfile.dry.run.see.comment"

        if not config.dry_run:
            temp = tempfile.NamedTemporaryFile(
                prefix="dockerfile-", mode='w+t', delete=False)
            temp.writelines(dockerfile)
            temp.close()
            filename = temp.name
            dockerfile = ''

        # rendering the Bash script for generating the Docker image
        name = entry['name'] + "-%s" % os.getpid() if entry['unique'] else entry['name']
        tag = render(entry['tag'], model=config.model, env=config.env, item=config.item)
        template_file = os.path.join(os.path.dirname(__file__), 'templates/docker-image.sh.j2')

        with open(template_file) as handle:
            template = handle.read()
            config.script = render(template, name=name, tag=tag,
                                   dockerfile_content=dockerfile,
                                   dockerfile_filename=filename)

        return Image(config)
485986
def push_images():
    # type: () -> None
    
    registry = conf.get('docker.registry')
    docker_images = conf.get('docker.images', [])

    if registry is None:
        log.err("You must define docker.registry conf variable to push images")
        sys.exit(-1)

    for image in docker_images:
        push_image(registry, image)
735038
def build_image(self, conf, pushing=False):
        """"""
        with conf.make_context() as context:
            try:
                stream = BuildProgressStream(conf.harpoon.silent_build)
                with self.remove_replaced_images(conf) as info:
                    cached = NormalBuilder().build(conf, context, stream)
                    info['cached'] = cached
            except (KeyboardInterrupt, Exception) as error:
                exc_info = sys.exc_info()
                if stream.current_container:
                    Runner().stage_build_intervention(conf, stream.current_container)

                if isinstance(error, KeyboardInterrupt):
                    raise UserQuit()
                else:
                    six.reraise(*exc_info)
            finally:
                if stream and stream.intermediate_images and conf.cleanup_intermediate_images:
                    for image in stream.intermediate_images:
                        log.info("Deleting intermediate image\timage=%s", image)
                        try:
                            conf.harpoon.docker_api.remove_image(image)
                        except Exception as error:
                            log.error("Failed to remove intermediate image\timage=%s\terror=%s", image, error)

        return cached
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)
317685
public static function build($dir, array $plugins)
    {
        if (count($plugins) === 0) {
            throw new InvalidArgumentException('There must be at least one provided plugin for image uploader');
        }

        // Default image's quality
        $quality = 75;
        $collection = array();

        foreach ($plugins as $plugin => $options) {
            switch ($plugin) {
                case 'thumb':
                    $thumb = new ThumbFactory();
                    $collection[] = $thumb->build($dir, $quality, $options);
                break;

                case 'original':
                    $original = new OriginalSizeFactory();
                    $collection[] = $original->build($dir, $quality, $options);
                break;
            }
        }

        return new UploadChain($collection);
    }
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'
575543
def runtime_to_build(runtime_deps):
    """"""
    build_deps = copy.deepcopy(runtime_deps)
    for dep in build_deps:
        if len(dep) > 0:
            dep[0] = 'BuildRequires'
    return build_deps
573446
def build(context, provider, **kwargs):  # pylint: disable=unused-argument
    """"""
    session = get_session(provider.region)
    options = kwargs.get('options', {})
    context_dict = {}
    context_dict['artifact_key_prefix'] = "%s-%s-" % (options['namespace'], options['name'])  # noqa
    default_param_name = "%shash" % context_dict['artifact_key_prefix']

    if options.get('build_output'):
        build_output = os.path.join(
            options['path'],
            options['build_output']
        )
    else:
        build_output = options['path']

    context_dict['artifact_bucket_name'] = RxrefLookup.handle(
        kwargs.get('artifact_bucket_rxref_lookup'),
        provider=provider,
        context=context
    )

    if options.get('pre_build_steps'):
        run_commands(options['pre_build_steps'], options['path'])

    context_dict['hash'] = get_hash_of_files(
        root_path=options['path'],
        directories=options.get('source_hashing', {}).get('directories')
    )

    # Now determine if the current staticsite has already been deployed
    if options.get('source_hashing', {}).get('enabled', True):
        context_dict['hash_tracking_parameter'] = options.get(
            'source_hashing', {}).get('parameter', default_param_name)

        ssm_client = session.client('ssm')

        try:
            old_parameter_value = ssm_client.get_parameter(
                Name=context_dict['hash_tracking_parameter']
            )['Parameter']['Value']
        except ssm_client.exceptions.ParameterNotFound:
            old_parameter_value = None
    else:
        context_dict['hash_tracking_disabled'] = True
        old_parameter_value = None

    context_dict['current_archive_filename'] = (
        context_dict['artifact_key_prefix'] + context_dict['hash'] + '.zip'
    )
    if old_parameter_value:
        context_dict['old_archive_filename'] = (
            context_dict['artifact_key_prefix'] + old_parameter_value + '.zip'
        )

    if old_parameter_value == context_dict['hash']:
        LOGGER.info("staticsite: skipping build; app hash %s already deployed "
                    "in this environment",
                    context_dict['hash'])
        context_dict['deploy_is_current'] = True
        return context_dict

    if does_s3_object_exist(context_dict['artifact_bucket_name'],
                            context_dict['current_archive_filename'],
                            session):
        context_dict['app_directory'] = download_and_extract_to_mkdtemp(
            context_dict['artifact_bucket_name'],
            context_dict['current_archive_filename'], session
        )
    else:
        if options.get('build_steps'):
            LOGGER.info('staticsite: executing build commands')
            run_commands(options['build_steps'], options['path'])
        zip_and_upload(build_output, context_dict['artifact_bucket_name'],
                       context_dict['current_archive_filename'], session)
        context_dict['app_directory'] = build_output

    context_dict['deploy_is_current'] = False
    return context_dict
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)
543027
def build_plugins(cls, plugins_conf):
        
        plugins = {}
        for alias, params_dict in plugins_conf.items():
            plugin_config = PluginConfig(**(params_dict.get('config') or {}))
            plugins[alias] = cls.build_plugin(class_name=params_dict['class_name'], config=plugin_config)
        return plugins
36479
def build_source_files(self):
        """"""

        from .files import BuildSourceFileAccessor
        return BuildSourceFileAccessor(self, self.dataset, self.source_fs)