Builds the Docker image associated with a given bug.

        See: `BuildManager.build`
438563
def build(self,
              bug: Bug,
              force: bool = True,
              quiet: bool = False
              ) -> None:
        
        self.__installation.build.build(bug.image,
                                        force=force,
                                        quiet=quiet)
665360
def build(self, format='qcow2', path='/tmp'):
        '''
        
        '''
        if kiwi is None:
            msg = 'Unable to build the image due to the missing dependencies: Kiwi module is not available.'
            log.error(msg)
            raise CommandExecutionError(msg)

        raise CommandExecutionError("Build is not yet implemented")
440511
def build_docker_build_command(configuration):
    
    parts = configuration.pop('docker', 'docker').split()
    parts.append('build')

    build = configuration.pop('build')

    build['path'] = os.path.join(configuration['workspace'], build['path'])
    build['file'] = os.path.join(build['path'], build['file'])

    parts.extend(build_parameter_parts(
        build, 'tag', 'file', 'no-cache', 'quiet', 'cpu-shares', 'memory'))

    parts.extend(build_dict_parameter_parts(build, 'build-arg'))
    parts.append(build.pop('path'))

    return parts
1122816
def build_docker_image(self):
        
        exception_being_handled = False
        self.builder = InsideBuilder(self.source, self.image)
        # Make sure exit_runner is defined for finally block
        exit_runner = None
        try:
            self.fs_watcher.start()
            signal.signal(signal.SIGTERM, self.throw_canceled_build_exception)
            prebuild_runner = PreBuildPluginsRunner(self.builder.tasker, self,
                                                    self.prebuild_plugins_conf,
                                                    plugin_files=self.plugin_files)
            buildstep_runner = BuildStepPluginsRunner(self.builder.tasker, self,
                                                      self.buildstep_plugins_conf,
                                                      plugin_files=self.plugin_files)
            prepublish_runner = PrePublishPluginsRunner(self.builder.tasker, self,
                                                        self.prepublish_plugins_conf,
                                                        plugin_files=self.plugin_files)
            postbuild_runner = PostBuildPluginsRunner(self.builder.tasker, self,
                                                      self.postbuild_plugins_conf,
                                                      plugin_files=self.plugin_files)
            exit_runner = ExitPluginsRunner(self.builder.tasker, self,
                                            self.exit_plugins_conf,
                                            keep_going=True,
                                            plugin_files=self.plugin_files)
            # time to run pre-build plugins, so they can access cloned repo
            logger.info("running pre-build plugins")
            try:
                prebuild_runner.run()
            except PluginFailedException as ex:
                logger.error("one or more prebuild plugins failed: %s", ex)
                raise
            except AutoRebuildCanceledException as ex:
                logger.info(str(ex))
                self.autorebuild_canceled = True
                raise

            logger.info("running buildstep plugins")
            try:
                self.build_result = buildstep_runner.run()

                if self.build_result.is_failed():
                    raise PluginFailedException(self.build_result.fail_reason)
            except PluginFailedException as ex:
                self.builder.is_built = False
                logger.error('buildstep plugin failed: %s', ex)
                raise

            self.builder.is_built = True
            if self.build_result.is_image_available():
                self.builder.image_id = self.build_result.image_id

            # run prepublish plugins
            try:
                prepublish_runner.run()
            except PluginFailedException as ex:
                logger.error("one or more prepublish plugins failed: %s", ex)
                raise

            if self.build_result.is_image_available():
                self.built_image_inspect = self.builder.inspect_built_image()
                history = self.builder.tasker.d.history(self.builder.image_id)
                diff_ids = self.built_image_inspect[INSPECT_ROOTFS][INSPECT_ROOTFS_LAYERS]

                # diff_ids is ordered oldest first
                # history is ordered newest first
                # We want layer_sizes to be ordered oldest first
                self.layer_sizes = [{"diff_id": diff_id, "size": layer['Size']}
                                    for (diff_id, layer) in zip(diff_ids, reversed(history))]

            try:
                postbuild_runner.run()
            except PluginFailedException as ex:
                logger.error("one or more postbuild plugins failed: %s", ex)
                raise

            return self.build_result
        except Exception as ex:
            logger.debug("caught exception (%r) so running exit plugins", ex)
            exception_being_handled = True
            raise
        finally:
            # We need to make sure all exit plugins are executed
            signal.signal(signal.SIGTERM, lambda *args: None)
            if exit_runner is None:
                exit_runner = ExitPluginsRunner(self.builder.tasker, self,
                                                self.exit_plugins_conf,
                                                keep_going=True,
                                                plugin_files=self.plugin_files)
            try:
                exit_runner.run(keep_going=True)
            except PluginFailedException as ex:
                logger.error("one or more exit plugins failed: %s", ex)

                # raise exception only in case that there is no previous exception being already
                # handled to prevent replacing original exceptions (root cause) with exceptions
                # from exit plugins
                if not exception_being_handled:
                    raise ex
            finally:
                self.source.remove_tmpdir()
                self.fs_watcher.finish()

            signal.signal(signal.SIGTERM, signal.SIG_DFL)
433948
def env_updated(self,
                    kb_app,
                    sphinx_app: Sphinx,
                    sphinx_env: BuildEnvironment,
                    resource
                    ):
        

        docname = resource.docname
        srcdir = sphinx_app.env.srcdir
        source_imgpath = self.source_filename(docname, srcdir)

        # Copy the image to the Sphinx build directory
        build_dir = sphinx_app.outdir
        docpath = Path(docname)
        parent = docpath.parent
        target_imgpath = str(Path(build_dir, parent, self.filename))

        # Does the target dir exist yet in the build dir? Probably not. If
        # not, make it
        target_dir = Path(build_dir, parent)
        if not target_dir.exists():
            target_dir.mkdir(parents=True, exist_ok=True)

        shutil.copy(source_imgpath, target_imgpath)
1146462
def _build_one(self, req, output_dir, python_tag=None):
        
        # Install build deps into temporary directory (PEP 518)
        with req.build_env:
            return self._build_one_inside_env(req, output_dir,
                                              python_tag=python_tag)
260229
def provision(self,
                  bug: Bug,
                  *,
                  plugins: Optional[List[Tool]] = None
                  ) -> Container:
        
        if plugins is None:
            plugins = []

        logger.info("provisioning container for bug: %s", bug.name)
        endpoint = 'bugs/{}/provision'.format(bug.name)
        payload = {
            'plugins': [p.to_dict() for p in plugins]
        }  # type: Dict[str, Any]
        r = self.__api.post(endpoint, json=payload)

        if r.status_code == 200:
            container = Container.from_dict(r.json())
            logger.info("provisioned container (id: %s) for bug: %s",
                               container.uid,
                               bug.name)
            return container

        if r.status_code == 404:
            raise KeyError("no bug registered with given name: {}".format(bug.name))

        self.__api.handle_erroneous_response(r)
1306207
def do_build(self):
		
		shutit_global.shutit_global_object.yield_to_draw()
		cfg = self.cfg
		self.log('PHASE: build, repository work', level=logging.DEBUG)
		module_id_list = self.module_ids()
		if self.build['deps_only']:
			module_id_list_build_only = filter(lambda x: cfg[x]['shutit.core.module.build'], module_id_list)
		for module_id in module_id_list:
			module = self.shutit_map[module_id]
			self.log('Considering whether to build: ' + module.module_id, level=logging.INFO)
			if cfg[module.module_id]['shutit.core.module.build']:
				if self.build['delivery'] not in module.ok_delivery_methods:
					self.fail('Module: ' + module.module_id + ' can only be built with one of these --delivery methods: ' + str(module.ok_delivery_methods) + '\nSee shutit build -h for more info, or try adding: --delivery <method> to your shutit invocation') # pragma: no cover
				if self.is_installed(module):
					self.build['report'] = (self.build['report'] + '\nBuilt already: ' + module.module_id + ' with run order: ' + str(module.run_order))
				else:
					# We move to the module directory to perform the build, returning immediately afterwards.
					if self.build['deps_only'] and module_id == module_id_list_build_only[-1]:
						# If this is the last module, and we are only building deps, stop here.
						self.build['report'] = (self.build['report'] + '\nSkipping: ' + module.module_id + ' with run order: ' + str(module.run_order) + '\n\tas this is the final module and we are building dependencies only')
					else:
						revert_dir = os.getcwd()
						self.get_current_shutit_pexpect_session_environment().module_root_dir = os.path.dirname(self.shutit_file_map[module_id])
						self.chdir(self.get_current_shutit_pexpect_session_environment().module_root_dir)
						self.login(prompt_prefix=module_id,command=shutit_global.shutit_global_object.bash_startup_command,echo=False)
						self.build_module(module)
						self.logout(echo=False)
						self.chdir(revert_dir)
			if self.is_installed(module):
				self.log('Starting module',level=logging.DEBUG)
				if not module.start(self):
					self.fail(module.module_id + ' failed on start', shutit_pexpect_child=self.get_shutit_pexpect_session_from_id('target_child').pexpect_child)
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
1036421
def build(build_name='default')
      description = Fudge::Parser.new.parse('Fudgefile')
      Fudge::Runner.new(description).run_build(build_name, options)
    end
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)
435508
def update_image(self, container_name, image_name):
        
        code, container = self.get_container(container_name)
        if code != httplib.OK:
            self.logger.error("Container %s is not exists. error code %s, error message %s", container_name, code,
                              container)
            return False

        _, old_image_name, _ = utils.parse_image_name(container.image)
        repository, name, version = utils.parse_image_name(image_name)
        if not repository or repository.lower() != DOCKER_NEG:
            self.logger.error("You image %s must have a 'docker.neg/' prefix string", image_name)
            return False

        if not repo.image_exists(name, tag=version):
            self.logger.error("You image %s must be location in docker.neg repository.", image_name)
            return False

        if old_image_name.lower() != name.lower():
            self.logger.error("You image %s must be same with container's Image.", image_name, container.image)
            return False

        code, result = self.update(container_name, tag=version)
        if code != httplib.OK:
            self.logger.error("Update container %s with image failure, code %s, result %s", container_name, code,
                              result)
            return False

        return True
1328631
def build(self, _resource, _cache=True, updatecontent=True, **kwargs):
        
        result = None

        if _cache and _resource in self._schemasbyresource:
            result = self._schemasbyresource[_resource]

        else:
            for builder in self._builders.values():
                try:
                    result = builder.build(_resource=_resource, **kwargs)

                except Exception:
                    pass

                else:
                    break

            if result is None:
                raise ValueError('No builder found for {0}'.format(_resource))

            if _cache:
                self._schemasbyresource[_resource] = result

            if updatecontent:
                from ..utils import updatecontent
                updatecontent(result, updateparents=False)

        return result
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
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))
115392
def build_from_source(version, **kwargs):
        
        mvn = os.path.join(Spark.svm_version_path(version), 'build', 'mvn')
        Spark.chmod_add_excute(mvn)
        p = subprocess.Popen([mvn, '-DskipTests', 'clean', 'package'], cwd=Spark.svm_version_path(version))
        p.wait()
        return p.returncode
704015
def generate(job,
             build_path: str,
             from_image: str,
             build_steps: Optional[List[str]] = None,
             env_vars: Optional[List[Tuple[str, str]]] = None,
             nvidia_bin: str = None,
             set_lang_env: bool = True,
             uid: int = None,
             gid: int = None) -> bool:
    """"""
    rendered_dockerfile = dockerizer_generate(repo_path=build_path,
                                              from_image=from_image,
                                              build_steps=build_steps,
                                              env_vars=env_vars,
                                              nvidia_bin=nvidia_bin,
                                              set_lang_env=set_lang_env,
                                              uid=uid,
                                              gid=gid)

    if rendered_dockerfile:
        job.log_dockerfile(dockerfile=rendered_dockerfile)
    return True