Pack a container image into a .tar.bz2 archive.

    Args:
        in_container (str): Path string to the container image.
        out_file (str): Output file name.
552952
def pack_container(in_container, out_file):
    
    container_filename = local.path(out_file).basename
    out_container = local.cwd / "container-out" / container_filename
    out_dir = out_container.dirname

    # Pack the results to: container-out
    with local.cwd(in_container):
        tar("cjf", out_container, ".")
    c_hash = download.update_hash(out_container)
    if out_dir.exists():
        mkdir("-p", out_dir)
    mv(out_container, out_file)
    mv(out_container + ".hash", out_file + ".hash")

    new_container = {"path": out_file, "hash": str(c_hash)}
    CFG["container"]["known"] += new_container
1114713
def plot_images(self, outfile):
        
        sum_struct = self.__images[0].sites
        for image in self.__images:
            for site_i in self.__relax_sites:
                sum_struct.append(PeriodicSite(image.sites[site_i].specie,
                                               image.sites[site_i].frac_coords,
                                               self.__images[0].lattice,
                                               to_unit_cell=True,
                                               coords_are_cartesian=False))
        sum_struct = Structure.from_sites(sum_struct, validate_proximity=False)
        p = Poscar(sum_struct)
        p.write_file(outfile)
911764
def out_to_in(self, out_file):
        
        in_file = os.path.basename(out_file).replace("out", "in", 1)
        dest = os.path.join(self.indir.path, in_file)

        if os.path.exists(dest) and not os.path.islink(dest):
            logger.warning("Will overwrite %s with %s" % (dest, out_file))

        os.rename(out_file, dest)
        return dest
920581
async def container_load(self, container_type, params=None, container=None):
        
        raw_container = container_is_raw(container_type, params)
        c_len = await load_uvarint(self.iobj)
        elem_ver = await load_uvarint(self.iobj) if not raw_container else 0

        # if container and c_len != len(container):
        #     raise ValueError('Size mismatch')

        elem_type = x.container_elem_type(container_type, params)
        res = container if container else []
        for i in range(c_len):
            try:
                self.tracker.push_index(i)
                fvalue = await self._load_field(elem_type,
                                                params[1:] if params else None,
                                                x.eref(res, i) if container else None)
                self.tracker.pop()
            except Exception as e:
                raise helpers.ArchiveException(e, tracker=self.tracker) from e

            if not container:
                res.append(fvalue)
        return res
879577
async def _dump_container(self, writer, container, container_type, params=None):
        
        await self._dump_container_size(writer, len(container), container_type)

        elem_type = container_elem_type(container_type, params)

        for idx, elem in enumerate(container):
            try:
                self.tracker.push_index(idx)
                await self.dump_field(
                    writer, elem, elem_type, params[1:] if params else None
                )
                self.tracker.pop()
            except Exception as e:
                raise helpers.ArchiveException(e, tracker=self.tracker) from e
392916
def run_in_container(command, container_dir):
    
    container_p = local.path(container_dir)
    with local.cwd(container_p):
        uchrt = uchroot.with_mounts()
        uchrt = uchrt["-E", "-A", "-u", "0", "-g", "0", "-C", "-w", "/", "-r",
                      container_p]
        uchrt = uchrt["--"]

        cmd_path = container_p / command[0].lstrip('/')
        if not cmd_path.exists():
            LOG.error("The command does not exist inside the container! %s",
                      cmd_path)
            return

        cmd = uchrt[command]
        return cmd & FG
695804
def put_container(self, url, container, container_headers=None):
        

        headers, container_uri = self._return_base_data(
            url=url,
            container=container,
            container_headers=container_headers
        )

        resp = self._header_getter(
            uri=container_uri,
            headers=headers
        )
        if resp.status_code == 404:
            return self._putter(uri=container_uri, headers=headers)
        else:
            return resp
392067
def __save_output(self):
        
        out = zipfile.ZipFile(self.outputfilename, 'w')

        for info_zip in self.infile.infolist():

            if info_zip.filename in self.templated_files:
                # Template file - we have edited these.

                # get a temp file
                streamout = open(get_secure_filename(), "w+b")
                fname, output_stream = self.output_streams[
                    self.templated_files.index(info_zip.filename)
                ]

                transformer = get_list_transformer(self.namespaces)
                remapped_stream = output_stream | transformer

                # write the whole stream to it
                for chunk in remapped_stream.serialize():
                    streamout.write(chunk.encode('utf-8'))
                    yield True

                # close the temp file to flush all data and make sure we get
                # it back when writing to the zip archive.
                streamout.close()

                # write the full file to archive
                out.write(streamout.name, fname)

                # remove temp file
                os.unlink(streamout.name)

            else:
                # Copy other files straight from the source archive.
                out.writestr(info_zip, self.infile.read(info_zip.filename))

        # Save images in the "Pictures" sub-directory of the archive.
        for identifier, data in self.images.items():
            out.writestr(PY3O_IMAGE_PREFIX + identifier, data)

        # close the zipfile before leaving
        out.close()
        yield True
294596
def base64ToImage(imgData, out_path, out_file):
        
        fh = open(os.path.join(out_path, out_file), "wb")
        fh.write(imgData.decode('base64'))
        fh.close()
        del fh
        return os.path.join(out_path, out_file)
86385
def MakeZip(self, input_dir, output_file):
    

    logging.info("Generating zip template file at %s", output_file)
    zf = zipfile.ZipFile(output_file, "w")
    oldwd = os.getcwd()
    os.chdir(input_dir)
    for path in ["debian", "rpmbuild", "fleetspeak"]:
      for root, _, files in os.walk(path):
        for f in files:
          zf.write(os.path.join(root, f))
    zf.close()
    os.chdir(oldwd)
632367
def _export_local_images(project, image, z):
    
    from ..compute import MODULES

    for module in MODULES:
        try:
            img_directory = module.instance().get_images_directory()
        except NotImplementedError:
            # Some modules don't have images
            continue

        directory = os.path.split(img_directory)[-1:][0]
        if os.path.exists(image):
            path = image
        else:
            path = os.path.join(img_directory, image)

        if os.path.exists(path):
            arcname = os.path.join("images", directory, os.path.basename(image))
            z.write(path, arcname)
            return
1288704
async def blob(self, elem=None, elem_type=None, params=None):
        
        elem_type = elem_type if elem_type else elem.__class__
        if hasattr(elem_type, "serialize_archive"):
            elem = elem_type() if elem is None else elem
            return await elem.serialize_archive(
                self, elem=elem, elem_type=elem_type, params=params
            )

        if self.writing:
            return await dump_blob(
                self.iobj, elem=elem, elem_type=elem_type, params=params
            )
        else:
            return await load_blob(
                self.iobj, elem_type=elem_type, params=params, elem=elem
            )
1278752
def read(self, container: Container, filepath: str) -> str:
        
        logger.debug("reading contents of file [%s] inside container [%s]",
                     filepath, container.id)
        filepath_orig = filepath
        filepath = self._resolve_path(container, filepath)

        # TODO what if the file doesn't exist?
        # TODO what if we encounter a permissions problem?

        # copy the contents the file to a temporary file on the host machine
        # TODO ensure correct permissions
        (_, fn_host) = tempfile.mkstemp(suffix='.bugzoo')
        try:
            # TODO we can probably move 'copy_from' to this manager
            self.__mgr_ctr.copy_from(container, filepath, fn_host)
            with open(fn_host, 'rb') as fh:
                blob = fh.read()
        finally:
            os.remove(fn_host)

        # detect encoding
        logger.debug("detecting encoding for file [%s] in container [%s]",
                     filepath_orig, container.id)
        chardet_res = chardet.detect(blob)
        encoding = chardet_res['encoding']
        confidence = chardet_res['confidence']
        logger.debug("detected encoding of file [%s] in container [%s]: %s (%.3f confidence)",  # noqa: pycodestyle
                     filepath_orig, container.id, encoding, confidence)

        # if no encoding is detected, return an empty file
        if encoding is None:
            return ''

        # decode file
        logger.debug("decoding file [%s] in container [%s]",
                     filepath_orig, container.id)
        try:
            contents = blob.decode(encoding)
        except UnicodeDecodeError:
            logger.exception("failed to decode contents of file [%s] in container [%s]",  # noqa: pycodestyle
                             filepath_orig, container.id)
            raise
        logger.debug("decoded file [%s] in container [%s]",
                     filepath_orig, container.id)

        logger.debug("read contents of file [%s] inside container [%s]",
                     filepath_orig, container.id)
        return contents
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))
655805
def _dir_tar_out(self):
        """"""
        return os.path.join(self.proj.tar_direc_out, self.proj.name,
                            self.model.name, self.run.name)
587287
def _pack_output(self, init_parameter):
        
        output = {}
        for i, param in enumerate(init_parameter):
            output[self.key_order[i]] = param
        return output
327316
def pack(name, root, path=None, pack_format='tar', compress='bzip2'):
    '''
    
    '''
    if pack_format == 'tar':
        _tar(name, root, path, compress)