示例#1
0
文件: engine.py 项目: xuanbo241/poky
 def write_ptable(parts, target):
     with tempfile.NamedTemporaryFile(prefix="wic-sfdisk-",
                                      mode='w') as outf:
         write_sfdisk_script(outf, parts)
         cmd = "{} --no-reread {} < {} 2>/dev/null".format(
             self.sfdisk, target, outf.name)
         try:
             subprocess.check_output(cmd, shell=True)
         except subprocess.CalledProcessError as err:
             raise WicError("Can't run '{}' command: {}".format(
                 cmd, err))
示例#2
0
    def _get_bootimg_dir(cls, bootimg_dir, dirname):
        """
        Check if dirname exists in default bootimg_dir or
        in wic-tools STAGING_DIR.
        """
        for result in (bootimg_dir,
                       get_bitbake_var("STAGING_DATADIR", "wic-tools")):
            if os.path.exists("%s/%s" % (result, dirname)):
                return result

        raise WicError("Couldn't find correct bootimg_dir, exiting")
示例#3
0
 def __getattr__(self, name):
     """Get path to the executable in a lazy way."""
     if name in ("mdir", "mcopy", "mdel", "mdeltree", "sfdisk", "e2fsck",
                 "resize2fs", "mkswap", "mkdosfs", "debugfs"):
         aname = "_%s" % name
         if aname not in self.__dict__:
             setattr(self, aname, find_executable(name, self.paths))
             if aname not in self.__dict__ or self.__dict__[aname] is None:
                 raise WicError("Can't find executable '{}'".format(name))
         return self.__dict__[aname]
     return self.__dict__[name]
    def __get_rootfs_dir(rootfs_dir):
        if os.path.isdir(rootfs_dir):
            return os.path.realpath(rootfs_dir)

        image_rootfs_dir = get_bitbake_var("IMAGE_ROOTFS", rootfs_dir)
        if not os.path.isdir(image_rootfs_dir):
            raise WicError("No valid artifact IMAGE_ROOTFS from image "
                           "named %s has been found at %s, exiting." %
                           (rootfs_dir, image_rootfs_dir))

        return os.path.realpath(image_rootfs_dir)
示例#5
0
文件: direct.py 项目: mobiaqua/yocto
    def setup_workdir(self, workdir):
        if workdir:
            if os.path.exists(workdir):
                raise WicError(
                    "Internal workdir '%s' specified in wic arguments already exists!"
                    % (workdir))

            os.makedirs(workdir)
            return workdir
        else:
            return tempfile.mkdtemp(dir=self.outdir, prefix='tmp.wic.')
示例#6
0
    def do_configure_partition(cls, part, source_params, creator, cr_workdir,
                               oe_builddir, bootimg_dir, kernel_dir,
                               native_sysroot):
        """
        Called before do_prepare_partition(), creates loader-specific config
        """
        hdddir = "%s/hdd/boot" % cr_workdir

        install_cmd = "install -d %s/EFI/BOOT" % hdddir
        exec_cmd(install_cmd)

        try:
            if source_params['loader'] == 'grub-efi':
                cls.do_configure_grubefi(creator, cr_workdir)
            else:
                raise WicError("unrecognized bootimg-sota-efi loader: %s" %
                               source_params['loader'])
        except KeyError:
            raise WicError(
                "bootimg-sota-efi requires a loader, none specified")
示例#7
0
    def do_prepare_partition(cls, part, source_params, cr, cr_workdir,
                             oe_builddir, bootimg_dir, kernel_dir, rootfs_dir,
                             native_sysroot):
        """
        Called to do the actual content population for a partition i.e. it
        'prepares' the partition to be incorporated into the image.
        """
        if not kernel_dir:
            kernel_dir = get_bitbake_var("DEPLOY_DIR_IMAGE")
            if not kernel_dir:
                raise WicError("Couldn't find DEPLOY_DIR_IMAGE, exiting")

        logger.debug('Kernel dir: %s', kernel_dir)

        if 'file' not in source_params:
            raise WicError("No file specified")

        src = os.path.join(kernel_dir, source_params['file'])
        dst = os.path.join(cr_workdir,
                           "%s.%s" % (source_params['file'], part.lineno))

        if not os.path.exists(os.path.dirname(dst)):
            os.makedirs(os.path.dirname(dst))

        if 'skip' in source_params:
            sparse_copy(src, dst, skip=int(source_params['skip']))
        else:
            sparse_copy(src, dst)

        # get the size in the right units for kickstart (kB)
        du_cmd = "du -Lbks %s" % dst
        out = exec_cmd(du_cmd)
        filesize = int(out.split()[0])

        if filesize > part.size:
            part.size = filesize

        if part.label:
            RawCopyPlugin.do_image_label(part.fstype, dst, part.label)

        part.source_file = dst
示例#8
0
    def do_prepare_partition(cls, part, source_params, cr, cr_workdir,
                             oe_builddir, bootimg_dir, kernel_dir, rootfs_dir,
                             native_sysroot):
        """
        Called to do the actual content population for a partition i.e. it
        'prepares' the partition to be incorporated into the image.
        """
        if not bootimg_dir:
            bootimg_dir = get_bitbake_var("DEPLOY_DIR_IMAGE")
            if not bootimg_dir:
                raise WicError("Couldn't find DEPLOY_DIR_IMAGE, exiting")

        logger.debug('Bootimg dir: %s', bootimg_dir)

        if 'file' not in source_params:
            raise WicError("No file specified")

        src = os.path.join(bootimg_dir, source_params['file'])

        logger.debug('Preparing partition using image %s', src)
        part.prepare_rootfs_from_fs_image(cr_workdir, src, "")
示例#9
0
    def do_image_label(fstype, dst, label):
        # don't create label when fstype is none
        if fstype == 'none':
            return

        if fstype.startswith('ext'):
            cmd = 'tune2fs -L %s %s' % (label, dst)
        elif fstype in ('msdos', 'vfat'):
            cmd = 'dosfslabel %s %s' % (dst, label)
        elif fstype == 'btrfs':
            cmd = 'btrfs filesystem label %s %s' % (dst, label)
        elif fstype == 'swap':
            cmd = 'mkswap -L %s %s' % (label, dst)
        elif fstype in ('squashfs', 'erofs'):
            raise WicError("It's not possible to update a %s "
                           "filesystem label '%s'" % (fstype, label))
        else:
            raise WicError("Cannot update filesystem label: "
                           "Unknown fstype: '%s'" % (fstype))

        exec_cmd(cmd)
示例#10
0
    def dir(self, pnum, path):
        if pnum not in self.partitions:
            raise WicError("Partition %s is not in the image" % pnum)

        if self.partitions[pnum].fstype.startswith('ext'):
            return exec_cmd("{} {} -R 'ls -l {}'".format(
                self.debugfs, self._get_part_image(pnum), path),
                            as_shell=True)
        else:  # fat
            return exec_cmd("{} -i {} ::{}".format(self.mdir,
                                                   self._get_part_image(pnum),
                                                   path))
示例#11
0
    def _get_part_image(self, pnum):
        if pnum not in self.partitions:
            raise WicError("Partition %s is not in the image" % pnum)
        part = self.partitions[pnum]
        # check if fstype is supported
        for fstype in self.fstypes:
            if part.fstype.startswith(fstype):
                break
        else:
            raise WicError("Not supported fstype: {}".format(part.fstype))
        if pnum not in self._partimages:
            tmpf = tempfile.NamedTemporaryFile(prefix="wic-part")
            dst_fname = tmpf.name
            tmpf.close()
            sparse_copy(self.imagepath,
                        dst_fname,
                        skip=part.start,
                        length=part.size)
            self._partimages[pnum] = dst_fname

        return self._partimages[pnum]
示例#12
0
    def do_configure_grubefi(cls, creator, cr_workdir):
        """
        Create loader-specific (grub-efi) config
        """
        configfile = creator.ks.bootloader.configfile
        custom_cfg = None
        if configfile:
            custom_cfg = get_custom_config(configfile)
            if custom_cfg:
                # Use a custom configuration for grub
                grubefi_conf = custom_cfg
                logger.debug(
                    "Using custom configuration file "
                    "%s for grub.cfg", configfile)
            else:
                raise WicError("configfile is specified but failed to "
                               "get it from %s." % configfile)

        if not custom_cfg:
            # Create grub configuration using parameters from wks file
            bootloader = creator.ks.bootloader

            grubefi_conf = ""
            grubefi_conf += "serial --unit=0 --speed=115200 --word=8 --parity=no --stop=1\n"
            grubefi_conf += "default=boot\n"
            grubefi_conf += "timeout=%s\n" % bootloader.timeout
            grubefi_conf += "set root='hd0,gpt2'\n"
            grubefi_conf += "menuentry 'boot'{\n"

            kernel_image = get_bitbake_var("KERNEL_IMAGE")
            kernel = "/boot/%s" % kernel_image

            grubefi_conf += "linux %s root=/dev/sda2 rootwait %s\n" \
                            % (kernel, bootloader.append)

            initrd_image = get_bitbake_var("INITRD_IMAGE")
            initrd = "/boot/%s" % initrd_image

            grubefi_conf += "initrd %s\n" % initrd

            grubefi_conf += "}\n"

        logger.debug("Writing grubefi config %s/hdd/boot/EFI/BOOT/grub.cfg",
                     cr_workdir)
        cfg = open("%s/hdd/boot/EFI/BOOT/grub.cfg" % cr_workdir, "w")
        cfg.write(grubefi_conf)
        cfg.close()

        cfg = open("%s/hdd/boot/EFI/BOOT/grub-mkimage.cfg" % cr_workdir, "w")
        mkimage_conf = "set root='hd0,gpt1'\n"
        mkimage_conf += "set prefix=($root)/EFI/BOOT\n"
        cfg.write(mkimage_conf)
        cfg.close()
示例#13
0
def verify_build_env():
    """
    Verify that the build environment is sane.

    Returns True if it is, false otherwise
    """
    if not os.environ.get("BUILDDIR"):
        raise WicError(
            "BUILDDIR not found, exiting. (Did you forget to source oe-init-build-env?)"
        )

    return True
示例#14
0
    def do_configure_grubefi(cls, part, creator, target_dir):
        """
        Create loader-specific (grub-efi) config
        """
        configfile = creator.ks.bootloader.configfile
        if configfile:
            grubefi_conf = get_custom_config(configfile)
            if grubefi_conf:
                logger.debug("Using custom configuration file %s for grub.cfg",
                             configfile)
            else:
                raise WicError(
                    "configfile is specified "
                    "but failed to get it from %s", configfile)
        else:
            splash = os.path.join(target_dir, "splash.jpg")
            if os.path.exists(splash):
                splashline = "menu background splash.jpg"
            else:
                splashline = ""

            bootloader = creator.ks.bootloader

            grubefi_conf = ""
            grubefi_conf += "serial --unit=0 --speed=115200 --word=8 "
            grubefi_conf += "--parity=no --stop=1\n"
            grubefi_conf += "default=boot\n"
            grubefi_conf += "timeout=%s\n" % (bootloader.timeout or 10)
            grubefi_conf += "\n"
            grubefi_conf += "search --set=root --label %s " % part.label
            grubefi_conf += "\n"
            grubefi_conf += "menuentry 'boot'{\n"

            kernel = get_bitbake_var("KERNEL_IMAGETYPE")
            if get_bitbake_var("INITRAMFS_IMAGE_BUNDLE") == "1":
                if get_bitbake_var("INITRAMFS_IMAGE"):
                    kernel = "%s-%s.bin" % \
                        (get_bitbake_var("KERNEL_IMAGETYPE"), get_bitbake_var("INITRAMFS_LINK_NAME"))

            grubefi_conf += "linux /%s rootwait %s\n" \
                            % (kernel, bootloader.append)
            grubefi_conf += "initrd /initrd \n"
            grubefi_conf += "}\n"

            if splashline:
                grubefi_conf += "%s\n" % splashline

        cfg_path = os.path.join(target_dir, "grub.cfg")
        logger.debug("Writing grubefi config %s", cfg_path)

        with open(cfg_path, "w") as cfg:
            cfg.write(grubefi_conf)
    def remove_ext(self, pnum, path, recursive):
        """
        Remove files/dirs and their contents from the partition.
        This only applies to ext* partition.
        """
        abs_path = re.sub('\/\/+', '/', path)
        cmd = "{} {} -wR 'rm \"{}\"'".format(self.debugfs,
                                            self._get_part_image(pnum),
                                            abs_path)
        out = exec_cmd(cmd , as_shell=True)
        for line in out.splitlines():
            if line.startswith("rm:"):
                if "file is a directory" in line:
                    if recursive:
                        # loop through content and delete them one by one if
                        # flaged with -r
                        subdirs = iter(self.dir(pnum, abs_path).splitlines())
                        next(subdirs)
                        for subdir in subdirs:
                            dir = subdir.split(':')[1].split(" ", 1)[1]
                            if not dir == "." and not dir == "..":
                                self.remove_ext(pnum, "%s/%s" % (abs_path, dir), recursive)

                    rmdir_out = exec_cmd("{} {} -wR 'rmdir \"{}\"'".format(self.debugfs,
                                                    self._get_part_image(pnum),
                                                    abs_path.rstrip('/'))
                                                    , as_shell=True)

                    for rmdir_line in rmdir_out.splitlines():
                        if "directory not empty" in rmdir_line:
                            raise WicError("Could not complete operation: \n%s \n"
                                            "use -r to remove non-empty directory" % rmdir_line)
                        if rmdir_line.startswith("rmdir:"):
                            raise WicError("Could not complete operation: \n%s "
                                            "\n%s" % (str(line), rmdir_line))

                else:
                    raise WicError("Could not complete operation: \n%s "
                                    "\nUnable to remove %s" % (str(line), abs_path))
示例#16
0
    def _get_syslinux_dir(cls, bootimg_dir):
        """
        Get path to syslinux from either default bootimg_dir
        or wic-tools STAGING_DIR.
        """
        for path in (bootimg_dir, get_bitbake_var("STAGING_DATADIR", "wic-tools")):
            if not path:
                continue
            syslinux_dir = os.path.join(path, 'syslinux')
            if os.path.exists(syslinux_dir):
                return syslinux_dir

        raise WicError("Couldn't find syslinux directory, exiting")
示例#17
0
def exec_native_cmd(cmd_and_args, native_sysroot, pseudo=""):
    """
    Execute native command, catching stderr, stdout

    Need to execute as_shell if the command uses wildcards

    Always need to execute native commands as_shell
    """
    # The reason -1 is used is because there may be "export" commands.
    args = cmd_and_args.split(';')[-1].split()
    logger.debug(args)

    if pseudo:
        cmd_and_args = pseudo + cmd_and_args

    hosttools_dir = get_bitbake_var("HOSTTOOLS_DIR")
    target_sys = get_bitbake_var("TARGET_SYS")

    native_paths = "%s/sbin:%s/usr/sbin:%s/usr/bin:%s/usr/bin/%s:%s/bin:%s" % \
                   (native_sysroot, native_sysroot,
                    native_sysroot, native_sysroot, target_sys,
                    native_sysroot, hosttools_dir)

    native_cmd_and_args = "export PATH=%s:$PATH;%s" % \
                   (native_paths, cmd_and_args)
    logger.debug("exec_native_cmd: %s", native_cmd_and_args)

    # If the command isn't in the native sysroot say we failed.
    if find_executable(args[0], native_paths):
        ret, out = _exec_cmd(native_cmd_and_args, True)
    else:
        ret = 127
        out = "can't find native executable %s in %s" % (args[0], native_paths)

    prog = args[0]
    # shell command-not-found
    if ret == 127 \
       or (pseudo and ret == 1 and out == "Can't find '%s' in $PATH." % prog):
        msg = "A native program %s required to build the image "\
              "was not found (see details above).\n\n" % prog
        recipe = NATIVE_RECIPES.get(prog)
        if recipe:
            msg += "Please make sure wic-tools have %s-native in its DEPENDS, "\
                   "build it with 'bitbake wic-tools' and try again.\n" % recipe
        else:
            msg += "Wic failed to find a recipe to build native %s. Please "\
                   "file a bug against wic.\n" % prog
        raise WicError(msg)

    return ret, out
示例#18
0
    def do_prepare_partition(
        cls,
        part,
        source_params,
        cr,
        cr_workdir,
        oe_builddir,
        bootimg_dir,
        kernel_dir,
        rootfs_dir_dict,
        native_sysroot,
    ):
        """Populate a partition from a subdirectory of the root file system."""
        try:
            rootfs_dir = rootfs_dir_dict["ROOTFS_DIR"]
        except KeyError:
            raise WicError("Couldn't find rootfs dir, exiting")

        try:
            subdir = source_params["subdir"].strip("/")
        except KeyError:
            raise WicError(
                "Required source parameter 'subdir' not found, exiting"
            )

        subdir_src = os.path.join(rootfs_dir, subdir)
        subdir_dst = os.path.join(cr_workdir, subdir)

        logger.debug("Rootfs dir: {}".format(rootfs_dir))
        logger.debug("Subdir source dir: {}".format(subdir_src))
        logger.debug("Subdir dest dir: {}".format(subdir_dst))

        shutil.copytree(subdir_src, subdir_dst)

        part.prepare_rootfs(
            cr_workdir, oe_builddir, subdir_dst, native_sysroot
        )
示例#19
0
    def _syslinux_config(cls, bootloader):
        """
        Generate syslinux configuration or take a custom one as such.
        """
        custom = None
        if bootloader.configfile:
            custom = get_custom_config(bootloader.configfile)
            if custom:
                logger.debug(
                    "Using custom configuration file %s "
                    "for syslinux.cfg", bootloader.configfile)
                return custom
            else:
                raise WicError("configfile is specified but failed to "
                               "get it from %s." % bootloader.configfile)

        # We try to comply to the stock syslinux.bbclass for the basic
        # configuration variables.
        serial = get_bitbake_var("SYSLINUX_SERIAL")
        serial_tty = get_bitbake_var("SYSLINUX_SERIAL_TTY")
        prompt = get_bitbake_var("SYSLINUX_PROMPT")
        timeout = get_bitbake_var("SYSLINUX_TIMEOUT")
        allow_options = get_bitbake_var("SYSLINUX_ALLOWOPTIONS")
        initrd = ("initrd=/initrd" if get_bitbake_var("INITRD") else "")
        append = get_bitbake_var("APPEND")

        cfg = "UI menu.c32\n"
        cfg += "\n"
        cfg += "PROMPT " + str(prompt or 0) + "\n"
        cfg += "TIMEOUT " + str(timeout or 50) + "\n"
        cfg += "\n"
        cfg += "ALLOWOPTIONS " + str(allow_options or 1) + "\n"
        cfg += "SERIAL " + str(serial or "0 38400") + "\n"
        cfg += "DEFAULT rootfs1\n"
        cfg += "\n"
        cfg += "LABEL rootfs1\n"
        cfg += "    KERNEL /vmlinuz\n"
        cfg += "    APPEND label=rootfs1 rootwait root=LABEL=rootfs1"
        cfg += " %s" % (serial_tty or "console=ttyS0,38400n8")
        cfg += " " + initrd
        cfg += "\n"
        cfg += "LABEL rootfs2\n"
        cfg += "    KERNEL /vmlinuz\n"
        cfg += "    APPEND label=rootfs2 rootwait root=LABEL=rootfs2"
        cfg += " %s" % (serial_tty or "console=ttyS0,38400n8")
        cfg += " " + initrd
        cfg += "\n"

        return cfg
示例#20
0
    def do_configure_grubefi(cls, creator, cr_workdir, bootpart):
        """
        Create loader-specific (grub-efi) config
        """
        configfile = creator.ks.bootloader.configfile
        custom_cfg = None
        if configfile:
            custom_cfg = get_custom_config(configfile)
            if custom_cfg:
                # Use a custom configuration for grub
                grubefi_conf = custom_cfg
                logger.debug(
                    "Using custom configuration file "
                    "%s for grub.cfg", configfile)
            else:
                raise WicError("configfile is specified but failed to "
                               "get it from %s." % configfile)

        if not custom_cfg:
            # Create grub configuration using parameters from wks file
            bootloader = creator.ks.bootloader

            kernel_initrd_path = "/"
            if get_bitbake_var("DISTRO").startswith("ubuntu"):
                kernel_initrd_path = "/boot/"

            grubefi_conf = "serial --unit=0 --speed=115200 --word=8 --parity=no --stop=1\n"
            grubefi_conf += "terminal_input --append serial\n"
            grubefi_conf += "terminal_output --append serial\n"
            grubefi_conf += "\n"
            grubefi_conf += "default=boot\n"
            grubefi_conf += "timeout=%s\n" % bootloader.timeout
            for part in creator.parts:
                if part.mountpoint == "/":
                    grubefi_conf += "regexp --set bootdisk '(hd[0-9]*),' $prefix\n"
                    grubefi_conf += "set root=$bootdisk',gpt%d'\n" % part.realnum
            grubefi_conf += "\n"
            grubefi_conf += "menuentry 'boot'{\n"
            grubefi_conf += "    linux %svmlinuz root=%s rootwait %s\n" \
                            % (kernel_initrd_path, creator.rootdev, bootloader.append or "")
            grubefi_conf += "    initrd %sinitrd.img\n" % kernel_initrd_path
            grubefi_conf += "}\n"

        logger.debug("Writing grubefi config %s/hdd/boot/EFI/BOOT/grub.cfg",
                     cr_workdir)
        cfg = open("%s/hdd/boot/EFI/BOOT/grub.cfg" % cr_workdir, "w")
        cfg.write(grubefi_conf)
        cfg.close()
    def _get_bootimg_dir(cls, bootimg_dir, dirname):
        """
        Check if dirname exists in default bootimg_dir or in STAGING_DIR.
        """
        staging_datadir = get_bitbake_var("STAGING_DATADIR")
        for result in (bootimg_dir, staging_datadir):
            if os.path.exists("%s/%s" % (result, dirname)):
                return result

        # STAGING_DATADIR is expanded with MLPREFIX if multilib is enabled
        # but dependency syslinux is still populated to original STAGING_DATADIR
        nonarch_datadir = re.sub('/[^/]*recipe-sysroot', '/recipe-sysroot', staging_datadir)
        if os.path.exists(os.path.join(nonarch_datadir, dirname)):
            return nonarch_datadir

        raise WicError("Couldn't find correct bootimg_dir, exiting")
示例#22
0
    def __init__(self, imagepath, native_sysroot):
        self.imagepath = imagepath
        self.native_sysroot = native_sysroot
        self._partitions = None
        self._mdir = None
        self._partimages = {}

        # find parted
        self.paths = "/bin:/usr/bin:/usr/sbin:/sbin/"
        if native_sysroot:
            for path in self.paths.split(':'):
                self.paths = "%s%s:%s" % (native_sysroot, path, self.paths)

        self.parted = find_executable("parted", self.paths)
        if not self.parted:
            raise WicError("Can't find executable parted")
示例#23
0
def wic_create(wks_file, rootfs_dir, bootimg_dir, kernel_dir, native_sysroot,
               options):
    """
    Create image

    wks_file - user-defined OE kickstart file
    rootfs_dir - absolute path to the build's /rootfs dir
    bootimg_dir - absolute path to the build's boot artifacts directory
    kernel_dir - absolute path to the build's kernel directory
    native_sysroot - absolute path to the build's native sysroots dir
    image_output_dir - dirname to create for image
    options - wic command line options (debug, bmap, etc)

    Normally, the values for the build artifacts values are determined
    by 'wic -e' from the output of the 'bitbake -e' command given an
    image name e.g. 'core-image-minimal' and a given machine set in
    local.conf.  If that's the case, the variables get the following
    values from the output of 'bitbake -e':

    rootfs_dir:        IMAGE_ROOTFS
    kernel_dir:        DEPLOY_DIR_IMAGE
    native_sysroot:    STAGING_DIR_NATIVE

    In the above case, bootimg_dir remains unset and the
    plugin-specific image creation code is responsible for finding the
    bootimg artifacts.

    In the case where the values are passed in explicitly i.e 'wic -e'
    is not used but rather the individual 'wic' options are used to
    explicitly specify these values.
    """

    if not os.path.exists(options.outdir):
        os.makedirs(options.outdir)

    pname = 'direct'
    plugin_class = PluginMgr.get_plugins('imager').get(pname)
    if not plugin_class:
        raise WicError('Unknown plugin: %s' % pname)

    plugin = plugin_class(wks_file, rootfs_dir, bootimg_dir, kernel_dir,
                          native_sysroot, "", options)

    plugin.do_create()

    logger.info("The image(s) were created using OE kickstart file:\n  %s",
                wks_file)
示例#24
0
    def do_configure_grubefi(cls, part, creator, cr_workdir):
        """
        Create loader-specific (grub-efi) config
        """
        configfile = creator.ks.bootloader.configfile
        if configfile:
            grubefi_conf = get_custom_config(configfile)
            if grubefi_conf:
                logger.debug("Using custom configuration file %s for grub.cfg",
                             configfile)
            else:
                raise WicError(
                    "configfile is specified "
                    "but failed to get it from %s", configfile)
        else:
            splash = os.path.join(cr_workdir, "EFI/boot/splash.jpg")
            if os.path.exists(splash):
                splashline = "menu background splash.jpg"
            else:
                splashline = ""

            bootloader = creator.ks.bootloader

            grubefi_conf = ""
            grubefi_conf += "serial --unit=0 --speed=115200 --word=8 "
            grubefi_conf += "--parity=no --stop=1\n"
            grubefi_conf += "default=boot\n"
            grubefi_conf += "timeout=%s\n" % (bootloader.timeout or 10)
            grubefi_conf += "\n"
            grubefi_conf += "search --set=root --label %s " % part.label
            grubefi_conf += "\n"
            grubefi_conf += "menuentry 'boot'{\n"

            kernel = "/bzImage"

            grubefi_conf += "linux %s rootwait %s\n" \
                            % (kernel, bootloader.append)
            grubefi_conf += "initrd /initrd \n"
            grubefi_conf += "}\n"

            if splashline:
                grubefi_conf += "%s\n" % splashline

        logger.debug("Writing grubefi config %s/EFI/BOOT/grub.cfg", cr_workdir)

        with open("%s/EFI/BOOT/grub.cfg" % cr_workdir, "w") as cfg:
            cfg.write(grubefi_conf)
    def _get_rootfs_dir(rootfs_dir):
        """
        Find rootfs pseudo dir

        If rootfs_dir is a directory consider it as rootfs directory.
        Otherwise ask bitbake about the IMAGE_ROOTFS directory.
        """
        if os.path.isdir(rootfs_dir):
            return rootfs_dir

        image_rootfs_dir = get_bitbake_var("IMAGE_ROOTFS", rootfs_dir)
        if not os.path.isdir(image_rootfs_dir):
            raise WicError("No valid artifact IMAGE_ROOTFS from image named %s "
                           "has been found at %s, exiting." %
                           (rootfs_dir, image_rootfs_dir))

        return image_rootfs_dir
    def do_prepare_partition(cls, part, source_params, creator, cr_workdir,
                             oe_builddir, bootimg_dir, kernel_dir,
                             rootfs_dir, native_sysroot):
        """
        Called to do the actual content population for a partition i.e. it
        'prepares' the partition to be incorporated into the image.
        """
        if not cls.__imgBiosObj:
            cls.__instanciateBIOSClass()

        bootimg_dir = cls.__imgBiosObj._get_bootimg_dir(bootimg_dir, 'syslinux')
        hdddir = "%s/hdd/boot" % cr_workdir

        # machine-deduction logic originally from isoimage-isohybrid.py
        initrd_dir = get_bitbake_var("DEPLOY_DIR_IMAGE")
        if not initrd_dir:
            raise WicError("Couldn't find DEPLOY_DIR_IMAGE, exiting.")
        machine = os.path.basename(initrd_dir)

        xen = "xen-" + machine + ".gz"

        cmds = ["install -m 0644 %s/%s %s/xen.gz" %
                (kernel_dir, xen, hdddir),
                "install -m 0644 %s/syslinux/mboot.c32 %s/mboot.c32" %
                (bootimg_dir, hdddir)]

        initrd = source_params.get('initrd')

        # Allow multiple 'initrds', as per the bootimg-efi class.
        # This can be used to install additional binaries for multiboot.
        # eg. TXT ACMs, XSM/Flask policy file, microcode binary
        if initrd:
            initrds = initrd.split(';')
            for initrd_file in initrds:
                cmds.append("install -m 0644 %s/%s %s/%s" %
                            (kernel_dir, initrd_file, hdddir,
                             os.path.basename(initrd_file)))

        for install_cmd in cmds:
            exec_cmd(install_cmd)

        cls.__imgBiosObj.do_prepare_partition(part, source_params,
                                              creator, cr_workdir,
                                              oe_builddir, bootimg_dir,
                                              kernel_dir, rootfs_dir,
                                              native_sysroot)
示例#27
0
    def __init__(self, wks_file, rootfs_dir, bootimg_dir, kernel_dir,
                 native_sysroot, oe_builddir, options):
        try:
            self.ks = KickStart(wks_file)
        except KickStartError as err:
            raise WicError(str(err))

        # parse possible 'rootfs=name' items
        self.rootfs_dir = dict(
            rdir.split('=') for rdir in rootfs_dir.split(' '))
        self.bootimg_dir = bootimg_dir
        self.kernel_dir = kernel_dir
        self.native_sysroot = native_sysroot
        self.oe_builddir = oe_builddir

        self.debug = options.debug
        self.outdir = options.outdir
        self.compressor = options.compressor
        self.bmap = options.bmap
        self.no_fstab_update = options.no_fstab_update
        self.updated_fstab_path = None

        self.name = "%s-%s" % (os.path.splitext(
            os.path.basename(wks_file))[0], strftime("%Y%m%d%H%M"))
        self.workdir = self.setup_workdir(options.workdir)
        self._image = None
        self.ptable_format = self.ks.bootloader.ptable
        self.parts = self.ks.partitions

        # as a convenience, set source to the boot partition source
        # instead of forcing it to be set via bootloader --source
        for part in self.parts:
            if not self.ks.bootloader.source and part.mountpoint == "/boot":
                self.ks.bootloader.source = part.source
                break

        image_path = self._full_path(self.workdir, self.parts[0].disk,
                                     "direct")
        self._image = PartitionedImage(image_path, self.ptable_format,
                                       self.parts, self.native_sysroot,
                                       options.extra_space)
示例#28
0
    def get_partitions(self):
        if self._partitions is None:
            self._partitions = OrderedDict()
            out = exec_cmd("%s -sm %s unit B print" % (self.parted, self.imagepath))
            parttype = namedtuple("Part", "pnum start end size fstype")
            splitted = out.splitlines()
            # skip over possible errors in exec_cmd output
            try:
                idx =splitted.index("BYT;")
            except ValueError:
                raise WicError("Error getting partition information from %s" % (self.parted))
            lsector_size, psector_size, self._ptable_format = splitted[idx + 1].split(":")[3:6]
            self._lsector_size = int(lsector_size)
            self._psector_size = int(psector_size)
            for line in splitted[idx + 2:]:
                pnum, start, end, size, fstype = line.split(':')[:5]
                partition = parttype(int(pnum), int(start[:-1]), int(end[:-1]),
                                     int(size[:-1]), fstype)
                self._partitions[pnum] = partition

        return self._partitions
示例#29
0
    def do_copy_ptcm(cls, deploydir, workdir, hdddir, source_params):
        """
        Copy ptcm binary over to hdd
        """
        if 'ptcm_install' not in source_params:
            raise WicError("ptcm_install is unset!")

        if (source_params['ptcm_install'] == "1"):
            ptcm_dst_dir = "%s/EFI/BOOT" % (hdddir)
            ptcm_boot = "%s/ptcm/ptcm_boot.efi" % (deploydir)
            cls.do_sign_pe(source_params['db_key'], source_params['db_cert'],
                           ptcm_boot,
                           "%s/ptcm/ptcm_boot_signed.efi" % deploydir)
            shutil.copyfile("%s/ptcm/ptcm_boot_signed.efi" % deploydir,
                            "%s/ptcm_boot.efi" % ptcm_dst_dir)
            ptcm_rtdrv = "%s/ptcm/ptcm_rtdrv.efi" % (deploydir)
            cls.do_sign_pe(source_params['db_key'], source_params['db_cert'],
                           ptcm_rtdrv,
                           "%s/ptcm/ptcm_rtdrv_signed.efi" % deploydir)
            shutil.copyfile("%s/ptcm/ptcm_rtdrv_signed.efi" % deploydir,
                            "%s/ptcm_rtdrv.efi" % ptcm_dst_dir)
示例#30
0
    def __init__(self, imagepath, native_sysroot, fstypes=('fat', 'ext')):
        self.imagepath = imagepath
        self.native_sysroot = native_sysroot
        self.fstypes = fstypes
        self._partitions = None
        self._partimages = {}
        self._lsector_size = None
        self._psector_size = None
        self._ptable_format = None

        # find parted
        self.paths = "/bin:/usr/bin:/usr/sbin:/sbin/"
        if native_sysroot:
            for path in self.paths.split(':'):
                self.paths = "%s%s:%s" % (native_sysroot, path, self.paths)

        self.parted = find_executable("parted", self.paths)
        if not self.parted:
            raise WicError("Can't find executable parted")

        self.partitions = self.get_partitions()