def stop(container: ContainerApiMixin): """ Stops a docker container which is running in detached mode :param container: An instance of a container :return: """ try: yield container finally: container.stop()
def cleanup(container: ContainerApiMixin): """ Cleans up a docker container which is running in detached mode :param container: An instance of a container :return: """ try: yield container finally: container.remove(force=True)
def put_file(*, container: ContainerApiMixin, src: File, dest: Path) -> (): """ Puts a file on the host into a container. This method will create an in memory tar archive, add the src file to this and upload it to the docker container where it will be unarchived at dest. :param container: The container to write to :param src: The path to the source file on the host :param dest: The path to the target file in the container :return: """ with SpooledTemporaryFile(max_size=MAX_SPOOL_SIZE) as tar_b: tarinfo = tarfile.TarInfo(name=os.path.basename(dest)) tarinfo.size = getattr(src, "size", sys.getsizeof(src)) with tarfile.open(fileobj=tar_b, mode="w") as tar, src.open("rb") as f: tar.addfile(tarinfo, fileobj=f) tar_b.seek(0) container.put_archive(os.path.dirname(dest), tar_b)
def put_file(*, container: ContainerApiMixin, src: File, dest: str) -> (): """ Puts a file on the host into a container. This method will create an in memory tar archive, add the src file to this and upload it to the docker container where it will be unarchived at dest. :param container: The container to write to :param src: The path to the source file on the host :param dest: The path to the target file in the container :return: """ tar_b = io.BytesIO() tarinfo = tarfile.TarInfo(name=os.path.basename(dest)) tarinfo.size = src.size with tarfile.open(fileobj=tar_b, mode="w") as tar, src.open("rb") as f: tar.addfile(tarinfo, fileobj=f) tar_b.seek(0) container.put_archive(os.path.dirname(dest), tar_b)
def get_file(*, container: ContainerApiMixin, src: Path): tarstrm, info = container.get_archive(src) if info["size"] > 2e9: raise ValueError(f"File {src} is too big to be decompressed.") file_obj = io.BytesIO() for ts in tarstrm: file_obj.write(ts) file_obj.seek(0) tar = tarfile.open(mode="r", fileobj=file_obj) content = tar.extractfile(src.name) return content
def get_file(*, container: ContainerApiMixin, src: Path, dest: Path): """Gets a file from src in the container and writes it to dest""" tarstrm, info = container.get_archive(src) with SpooledTemporaryFile(max_size=MAX_SPOOL_SIZE) as ftmp, open( dest, "wb") as outfile: for t in tarstrm: ftmp.write(t) ftmp.seek(0) tar = tarfile.open(mode="r", fileobj=ftmp) infile = tar.extractfile(src.name) buffer = True while buffer: buffer = infile.read(1024) outfile.write(buffer)