# Path: lava_dispatcher/action.py
# class InfrastructureError(LAVAError):
#     """
#     Exceptions based on an error raised by a component of the
#     test which is neither the LAVA dispatcher code nor the
#     code being executed on the device under test. This includes
#     errors arising from the device (like the arndale SD controller
#     issue) and errors arising from the hardware to which the device
#     is connected (serial console connection, ethernet switches or
#     internet connection beyond the control of the device under test).
# 
#     Use LAVABug for errors arising from bugs in LAVA code.
#     """
#     error_help = "InfrastructureError: The Infrastructure is not working " \
#                  "correctly. Please report this error to LAVA admins."
#     error_type = "Infrastructure"
# 
# class JobError(LAVAError):
#     """
#     An Error arising from the information supplied as part of the TestJob
#     e.g. HTTP404 on a file to be downloaded as part of the preparation of
#     the TestJob or a download which results in a file which tar or gzip
#     does not recognise.
#     """
#     error_help = "JobError: Your job cannot terminate cleanly."
#     error_type = "Job"
# 
# class LAVABug(LAVAError):
#     """
#     An error that is raised when an un-expected error is catched. Only happen
#     when a bug is encountered.
#     """
#     error_help = "LAVABug: This is probably a bug in LAVA, please report it."
#     error_type = "Bug"
# 
# Path: lava_dispatcher/utils/constants.py
# LXC_PATH = "/var/lib/lxc"
# 
# LAVA_LXC_HOME = "/lava-lxc"
# 
# Path: lava_dispatcher/utils/compression.py
# def decompress_file(infile, compression):
#     if not compression:
#         return infile
#     if compression not in decompress_command_map.keys():
#         raise JobError("Cannot find shell command to decompress: %s" % compression)
# 
#     # Check that the command does exists
#     which(decompress_command_map[compression])
# 
#     with chdir(os.path.dirname(infile)):
#         cmd = "%s %s" % (decompress_command_map[compression], infile)
#         outfile = infile
#         if infile.endswith(compression):
#             outfile = infile[:-(len(compression) + 1)]
#         try:
#             # safe to use shell=True here, no external arguments
#             subprocess.check_output(cmd, shell=True)
#             return outfile
#         except (OSError, subprocess.CalledProcessError) as exc:
#             raise InfrastructureError('unable to decompress file %s: %s' % (infile, exc))
# 
# Path: lava_dispatcher/utils/decorator.py
# def replace_exception(cls_from, cls_to):
#     def replace_exception_wrapper(func):
#         @wraps(func)
#         def function_wrapper(*args, **kwargs):
#             try:
#                 return func(*args, **kwargs)
#             except cls_from as exc:
#                 raise cls_to(exc)
#         return function_wrapper
#     return replace_exception_wrapper


import atexit
import os
import shutil
import tarfile
import tempfile
import guestfs
import subprocess
import glob
import logging
import magic
import errno
from configobj import ConfigObj
from lava_dispatcher.action import InfrastructureError, JobError, LAVABug
from lava_dispatcher.utils.constants import (
    LXC_PATH,
    LAVA_LXC_HOME,
)
from lava_dispatcher.utils.compression import decompress_file
from lava_dispatcher.utils.decorator import replace_exception
        os.makedirs(os.path.dirname(dst), 0o755)
        shutil.copy(src, dst)
    return dst


@replace_exception(RuntimeError, JobError)
def copy_overlay_to_sparse_fs(image, overlay):
    """copy_overlay_to_sparse_fs
    """
    ext4_img = image + '.ext4'
    logger = logging.getLogger('dispatcher')
    guest = guestfs.GuestFS(python_return_dict=True)

    # Check if the given image is an Android sparse image
    if not is_sparse_image(image):
        raise JobError("Image is not an Android sparse image: %s" % image)

    subprocess.check_output(['/usr/bin/simg2img', image, ext4_img],
                            stderr=subprocess.STDOUT)
    guest.add_drive(ext4_img)
    guest.launch()
    devices = guest.list_devices()
    if not devices:
        raise InfrastructureError("Unable to prepare guestfs")
    guest.mount(devices[0], '/')
    # FIXME: max message length issues when using tar_in
    # on tar.gz.  Works fine with tar so decompressing
    # overlay first.
    if os.path.exists(overlay[:-3]):
        os.unlink(overlay[:-3])

# Path: lava_dispatcher/action.py
# class InfrastructureError(LAVAError):
#     """
#     Exceptions based on an error raised by a component of the
#     test which is neither the LAVA dispatcher code nor the
#     code being executed on the device under test. This includes
#     errors arising from the device (like the arndale SD controller
#     issue) and errors arising from the hardware to which the device
#     is connected (serial console connection, ethernet switches or
#     internet connection beyond the control of the device under test).
# 
#     Use LAVABug for errors arising from bugs in LAVA code.
#     """
#     error_help = "InfrastructureError: The Infrastructure is not working " \
#                  "correctly. Please report this error to LAVA admins."
#     error_type = "Infrastructure"
# 
# class JobError(LAVAError):
#     """
#     An Error arising from the information supplied as part of the TestJob
#     e.g. HTTP404 on a file to be downloaded as part of the preparation of
#     the TestJob or a download which results in a file which tar or gzip
#     does not recognise.
#     """
#     error_help = "JobError: Your job cannot terminate cleanly."
#     error_type = "Job"
# 
# class LAVABug(LAVAError):
#     """
#     An error that is raised when an un-expected error is catched. Only happen
#     when a bug is encountered.
#     """
#     error_help = "LAVABug: This is probably a bug in LAVA, please report it."
#     error_type = "Bug"
# 
# Path: lava_dispatcher/utils/constants.py
# LXC_PATH = "/var/lib/lxc"
# 
# LAVA_LXC_HOME = "/lava-lxc"
# 
# Path: lava_dispatcher/utils/compression.py
# def decompress_file(infile, compression):
#     if not compression:
#         return infile
#     if compression not in decompress_command_map.keys():
#         raise JobError("Cannot find shell command to decompress: %s" % compression)
# 
#     # Check that the command does exists
#     which(decompress_command_map[compression])
# 
#     with chdir(os.path.dirname(infile)):
#         cmd = "%s %s" % (decompress_command_map[compression], infile)
#         outfile = infile
#         if infile.endswith(compression):
#             outfile = infile[:-(len(compression) + 1)]
#         try:
#             # safe to use shell=True here, no external arguments
#             subprocess.check_output(cmd, shell=True)
#             return outfile
#         except (OSError, subprocess.CalledProcessError) as exc:
#             raise InfrastructureError('unable to decompress file %s: %s' % (infile, exc))
# 
# Path: lava_dispatcher/utils/decorator.py
# def replace_exception(cls_from, cls_to):
#     def replace_exception_wrapper(func):
#         @wraps(func)
#         def function_wrapper(*args, **kwargs):
#             try:
#                 return func(*args, **kwargs)
#             except cls_from as exc:
#                 raise cls_to(exc)
#         return function_wrapper
#     return replace_exception_wrapper


# Path: lava_dispatcher/utils/filesystem.py
import atexit
import os
import shutil
import tarfile
import tempfile
import guestfs
import subprocess
import glob
import logging
import magic
import errno
from configobj import ConfigObj
from lava_dispatcher.action import InfrastructureError, JobError, LAVABug
from lava_dispatcher.utils.constants import (
    LXC_PATH,
    LAVA_LXC_HOME,
)
from lava_dispatcher.utils.compression import decompress_file
from lava_dispatcher.utils.decorator import replace_exception

        os.makedirs(os.path.dirname(dst), 0o755)
        shutil.copy(src, dst)
    return dst


@replace_exception(RuntimeError, JobError)
def copy_overlay_to_sparse_fs(image, overlay):
    """copy_overlay_to_sparse_fs
    """
    ext4_img = image + '.ext4'
    logger = logging.getLogger('dispatcher')
    guest = guestfs.GuestFS(python_return_dict=True)

    # Check if the given image is an Android sparse image
    if not is_sparse_image(image):
        raise JobError("Image is not an Android sparse image: %s" % image)

    subprocess.check_output(['/usr/bin/simg2img', image, ext4_img],
                            stderr=subprocess.STDOUT)
    guest.add_drive(ext4_img)
    guest.launch()
    devices = guest.list_devices()
    if not devices:
        raise InfrastructureError("Unable to prepare guestfs")
    guest.mount(devices[0], '/')
    # FIXME: max message length issues when using tar_in
    # on tar.gz.  Works fine with tar so decompressing
    # overlay first.
    if os.path.exists(overlay[:-3]):
        os.unlink(overlay[:-3])

    decompressed_overlay = decompress_file(overlay, 'gz')