def call_func_with_temp_dir(func, keep_tmp):
    """Manages the creation and cleanup of the temporary directory.

  This function calls the given function after first creating a temporary
  directory. It also cleans up the temporary directory.

  Args:
    func: The function to call. Should accept one parameter, the path to the
      temporary directory.
    keep_tmp: Keep the temporary directory after processing is complete.
  """

    # Create a temporary directory. This will serve as the parent of directories
    # we use when we extract items from the input target files packages, and also
    # a scratch directory that we use for temporary files.

    temp_dir = common.MakeTempDir(prefix='merge_target_files_')

    try:
        func(temp_dir)
    finally:
        if keep_tmp:
            logger.info('keeping %s', temp_dir)
        else:
            common.Cleanup()
def merge_target_files_with_temp_dir(system_target_files, other_target_files,
                                     output_target_files, keep_tmp):
    """Manage the creation and cleanup of the temporary directory.

  This function wraps merge_target_files after first creating a temporary
  directory. It also cleans up the temporary directory.

  Args:
    system_target_files: The name of the zip archive containing the system
    partial target files package.

    other_target_files: The name of the zip archive containing the other
    partial target files package.

    output_target_files: The name of the output zip archive target files
    package created by merging system and other.

    keep_tmp: Keep the temporary directory after processing is complete.

  Returns:
    On success, 0. Otherwise, a non-zero exit code.
  """

    # Create a temporary directory. This will serve as the parent of directories
    # we use when we extract items from the input target files packages, and also
    # a scratch directory that we use for temporary files.

    logger.info('starting: merge system %s and other %s into output %s',
                system_target_files, other_target_files, output_target_files)

    temp_dir = common.MakeTempDir(prefix='merge_target_files_')

    try:
        return merge_target_files(temp_dir=temp_dir,
                                  system_target_files=system_target_files,
                                  other_target_files=other_target_files,
                                  output_target_files=output_target_files)
    except:
        raise
    finally:
        if keep_tmp:
            logger.info('keeping %s', temp_dir)
        else:
            common.Cleanup()
Beispiel #3
0
  def test_CheckHeadroom_WithMke2fsOutput(self):
    """Tests the result parsing from actual call to mke2fs."""
    input_dir = common.MakeTempDir()
    output_image = common.MakeTempFile(suffix='.img')
    command = ['mkuserimg_mke2fs.sh', input_dir, output_image, 'ext4',
               '/system', '409600', '-j', '0']
    ext4fs_output, exit_code = RunCommand(command)
    self.assertEqual(0, exit_code)

    prop_dict = {
        'fs_type' : 'ext4',
        'partition_headroom' : '40960',
        'mount_point' : 'system',
    }
    self.assertTrue(CheckHeadroom(ext4fs_output, prop_dict))

    prop_dict = {
        'fs_type' : 'ext4',
        'partition_headroom' : '413696',
        'mount_point' : 'system',
    }
    self.assertFalse(CheckHeadroom(ext4fs_output, prop_dict))

    common.Cleanup()
                lines = f.read()
            logger.info("Building super image from info dict...")
            return BuildSuperImageFromDict(
                common.LoadDictionaryFromLines(lines.split("\n")), out)

    raise ValueError("{} is not a dictionary or a valid path".format(inp))


def main(argv):

    args = common.ParseOptions(argv, __doc__)

    if len(args) != 2:
        common.Usage(__doc__)
        sys.exit(1)

    common.InitLogging()

    BuildSuperImage(args[0], args[1])


if __name__ == "__main__":
    try:
        common.CloseInheritedPipes()
        main(sys.argv[1:])
    except common.ExternalError:
        logger.exception("\n   ERROR:\n")
        sys.exit(1)
    finally:
        common.Cleanup()
 def tearDown(self):
     common.Cleanup()
Beispiel #6
0
def main(argv):
    def option_handler(o, a):
        if o in ("-b", "--board_config"):
            pass  # deprecated
        elif o in ("-k", "--package_key"):
            OPTIONS.package_key = a
        elif o in ("-i", "--incremental_from"):
            OPTIONS.incremental_source = a
        elif o in ("-w", "--wipe_user_data"):
            OPTIONS.wipe_user_data = True
        elif o in ("-n", "--no_prereq"):
            OPTIONS.omit_prereq = True
        elif o in ("-e", "--extra_script"):
            OPTIONS.extra_script = a
        elif o in ("-a", "--aslr_mode"):
            if a in ("on", "On", "true", "True", "yes", "Yes"):
                OPTIONS.aslr_mode = True
            else:
                OPTIONS.aslr_mode = False
        elif o in ("--worker_threads"):
            OPTIONS.worker_threads = int(a)
        elif o in ("--backup"):
            OPTIONS.backuptool = bool(a.lower() == 'true')
        elif o in ("--override_device"):
            OPTIONS.override_device = a
        elif o in ("--override_prop"):
            OPTIONS.override_prop = bool(a.lower() == 'true')
        else:
            return False
        return True

    args = common.ParseOptions(argv,
                               __doc__,
                               extra_opts="b:k:i:d:wne:a:",
                               extra_long_opts=[
                                   "board_config=", "package_key=",
                                   "incremental_from=", "wipe_user_data",
                                   "no_prereq", "extra_script=",
                                   "worker_threads=", "aslr_mode=", "backup=",
                                   "override_device=", "override_prop="
                               ],
                               extra_option_handler=option_handler)

    if len(args) < 2:
        common.Usage(__doc__)
        sys.exit(1)

    for arg in args[2:]:
        OPTIONS.require_verbatim.add(arg)
    print "OPTIONS.require_verbatim: %r" % OPTIONS.require_verbatim

    if OPTIONS.extra_script is not None:
        OPTIONS.extra_script = open(OPTIONS.extra_script).read()

    print "unzipping target target-files..."
    OPTIONS.input_tmp, input_zip = common.UnzipTemp(args[0])

    OPTIONS.target_tmp = OPTIONS.input_tmp
    OPTIONS.info_dict = common.LoadInfoDict(input_zip)

    # If this image was originally labelled with SELinux contexts, make sure we
    # also apply the labels in our new image. During building, the "file_contexts"
    # is in the out/ directory tree, but for repacking from target-files.zip it's
    # in the root directory of the ramdisk.
    if "selinux_fc" in OPTIONS.info_dict:
        OPTIONS.info_dict["selinux_fc"] = os.path.join(OPTIONS.input_tmp,
                                                       "BOOT", "RAMDISK",
                                                       "file_contexts")

    if OPTIONS.verbose:
        print "--- target info ---"
        common.DumpInfoDict(OPTIONS.info_dict)

    if OPTIONS.device_specific is None:
        OPTIONS.device_specific = OPTIONS.info_dict.get(
            "tool_extensions", None)
    if OPTIONS.device_specific is not None:
        OPTIONS.device_specific = os.path.normpath(OPTIONS.device_specific)
        print "using device-specific extensions in", OPTIONS.device_specific

    temp_zip_file = tempfile.NamedTemporaryFile()
    output_zip = zipfile.ZipFile(temp_zip_file,
                                 "w",
                                 compression=zipfile.ZIP_DEFLATED)

    if OPTIONS.incremental_source is None:
        WriteFullOTAPackage(input_zip, output_zip)
        if OPTIONS.package_key is None:
            OPTIONS.package_key = OPTIONS.info_dict.get(
                "default_system_dev_certificate",
                "build/target/product/security/testkey")
    else:
        print "unzipping source target-files..."
        OPTIONS.source_tmp, source_zip = common.UnzipTemp(
            OPTIONS.incremental_source)
        OPTIONS.target_info_dict = OPTIONS.info_dict
        OPTIONS.source_info_dict = common.LoadInfoDict(source_zip)
        if OPTIONS.package_key is None:
            OPTIONS.package_key = OPTIONS.source_info_dict.get(
                "default_system_dev_certificate",
                "build/target/product/security/testkey")
        if OPTIONS.verbose:
            print "--- source info ---"
            common.DumpInfoDict(OPTIONS.source_info_dict)
        WriteIncrementalOTAPackage(input_zip, source_zip, output_zip)

    output_zip.close()

    SignOutput(temp_zip_file.name, args[1])
    temp_zip_file.close()

    common.Cleanup()

    print "done."