Ejemplo n.º 1
0
    def _do_chroot_tar(cls, target, cmd=[]):
        mountfp_xml = os.path.splitext(target)[0] + '.xml'
        if not os.path.exists(mountfp_xml):
            raise errors.CreatorError("No mount point file found for this tar "
                                      "image, please check %s" % mountfp_xml)

        import tarfile
        tar = tarfile.open(target, 'r')
        tmpdir = misc.mkdtemp()
        tar.extractall(path=tmpdir)
        tar.close()

        mntdir = misc.mkdtemp()

        loops = []
        for (mp, label, name, size, fstype) in load_mountpoints(mountfp_xml):
            if fstype in ("ext2", "ext3", "ext4"):
                myDiskMount = fs_related.ExtDiskMount
            elif fstype == "btrfs":
                myDiskMount = fs_related.BtrfsDiskMount
            elif fstype in ("vfat", "msdos"):
                myDiskMount = fs_related.VfatDiskMount
            else:
                raise errors.CreatorError("Cannot support fstype: %s" % fstype)

            name = os.path.join(tmpdir, name)
            size = size * 1024L * 1024L
            loop = myDiskMount(fs_related.SparseLoopbackDisk(name, size),
                               os.path.join(mntdir, mp.lstrip('/')),
                               fstype, size, label)

            try:
                msger.verbose("Mount %s to %s" % (mp, mntdir + mp))
                fs_related.makedirs(os.path.join(mntdir, mp.lstrip('/')))
                loop.mount()

            except:
                loop.cleanup()
                for lp in reversed(loops):
                    chroot.cleanup_after_chroot("img", lp, None, mntdir)

                shutil.rmtree(tmpdir, ignore_errors=True)
                raise

            loops.append(loop)

        try:
            if len(cmd) != 0:
                cmdline = "/usr/bin/env HOME=/root " + ' '.join(cmd)
            else:
                cmdline = "/usr/bin/env HOME=/root /bin/bash"
            chroot.chroot(mntdir, None, cmdline)
        except:
            raise errors.CreatorError("Failed to chroot to %s." % target)
        finally:
            for loop in reversed(loops):
                chroot.cleanup_after_chroot("img", loop, None, mntdir)

            shutil.rmtree(tmpdir, ignore_errors=True)
Ejemplo n.º 2
0
    def _do_chroot_tar(cls, target, cmd=[]):
        mountfp_xml = os.path.splitext(target)[0] + '.xml'
        if not os.path.exists(mountfp_xml):
            raise errors.CreatorError("No mount point file found for this tar "
                                      "image, please check %s" % mountfp_xml)

        import tarfile
        tar = tarfile.open(target, 'r')
        tmpdir = misc.mkdtemp()
        tar.extractall(path=tmpdir)
        tar.close()

        mntdir = misc.mkdtemp()

        loops = []
        for (mp, label, name, size, fstype) in load_mountpoints(mountfp_xml):
            if fstype in ("ext2", "ext3", "ext4"):
                myDiskMount = fs_related.ExtDiskMount
            elif fstype == "btrfs":
                myDiskMount = fs_related.BtrfsDiskMount
            elif fstype in ("vfat", "msdos"):
                myDiskMount = fs_related.VfatDiskMount
            else:
                raise errors.CreatorError("Cannot support fstype: %s" % fstype)

            name = os.path.join(tmpdir, name)
            size = size * 1024L * 1024L
            loop = myDiskMount(fs_related.SparseLoopbackDisk(name, size),
                               os.path.join(mntdir, mp.lstrip('/')), fstype,
                               size, label)

            try:
                msger.verbose("Mount %s to %s" % (mp, mntdir + mp))
                fs_related.makedirs(os.path.join(mntdir, mp.lstrip('/')))
                loop.mount()

            except:
                loop.cleanup()
                for lp in reversed(loops):
                    chroot.cleanup_after_chroot("img", lp, None, mntdir)

                shutil.rmtree(tmpdir, ignore_errors=True)
                raise

            loops.append(loop)

        try:
            if len(cmd) != 0:
                cmdline = "/usr/bin/env HOME=/root " + ' '.join(cmd)
            else:
                cmdline = "/usr/bin/env HOME=/root /bin/bash"
            chroot.chroot(mntdir, None, cmdline)
        except:
            raise errors.CreatorError("Failed to chroot to %s." % target)
        finally:
            for loop in reversed(loops):
                chroot.cleanup_after_chroot("img", loop, None, mntdir)

            shutil.rmtree(tmpdir, ignore_errors=True)
Ejemplo n.º 3
0
    def do_unpack(cls, srcimg):
        img = srcimg
        imgsize = misc.get_file_size(img) * 1024L * 1024L
        imgmnt = misc.mkdtemp()
        disk = fs_related.SparseLoopbackDisk(img, imgsize)
        imgloop = PartitionedMount(imgmnt, skipformat=True)
        imgloop.add_disk('/dev/sdb', disk)
        imgloop.add_partition(imgsize / 1024 / 1024,
                              "/dev/sdb",
                              "/",
                              "vfat",
                              boot=False)
        try:
            imgloop.mount()
        except errors.MountError:
            imgloop.cleanup()
            raise

        # legacy LiveOS filesystem layout support, remove for F9 or F10
        if os.path.exists(imgmnt + "/squashfs.img"):
            squashimg = imgmnt + "/squashfs.img"
        else:
            squashimg = imgmnt + "/LiveOS/squashfs.img"

        tmpoutdir = misc.mkdtemp()
        # unsquashfs requires outdir mustn't exist
        shutil.rmtree(tmpoutdir, ignore_errors=True)
        misc.uncompress_squashfs(squashimg, tmpoutdir)

        try:
            # legacy LiveOS filesystem layout support, remove for F9 or F10
            if os.path.exists(tmpoutdir + "/os.img"):
                os_image = tmpoutdir + "/os.img"
            else:
                os_image = tmpoutdir + "/LiveOS/ext3fs.img"

            if not os.path.exists(os_image):
                raise errors.CreatorError(
                    "'%s' is not a valid live CD ISO : neither "
                    "LiveOS/ext3fs.img nor os.img exist" % img)
            imgname = os.path.basename(srcimg)
            imgname = os.path.splitext(imgname)[0] + ".img"
            rtimage = os.path.join(
                tempfile.mkdtemp(dir="/var/tmp", prefix="tmp"), imgname)
            shutil.copyfile(os_image, rtimage)

        finally:
            imgloop.cleanup()
            shutil.rmtree(tmpoutdir, ignore_errors=True)
            shutil.rmtree(imgmnt, ignore_errors=True)

        return rtimage
Ejemplo n.º 4
0
    def do_chroot(cls, target):
        os_image = cls.do_unpack(target)
        os_image_dir = os.path.dirname(os_image)

        # unpack image to target dir
        imgsize = misc.get_file_size(os_image) * 1024L * 1024L
        imgtype = misc.get_image_type(os_image)
        if imgtype == "btrfsimg":
            fstype = "btrfs"
            myDiskMount = fs_related.BtrfsDiskMount
        elif imgtype in ("ext3fsimg", "ext4fsimg"):
            fstype = imgtype[:4]
            myDiskMount = fs_related.ExtDiskMount
        else:
            raise errors.CreatorError("Unsupported filesystem type: %s" %
                                      fstype)

        extmnt = misc.mkdtemp()
        extloop = myDiskMount(fs_related.SparseLoopbackDisk(os_image, imgsize),
                              extmnt, fstype, 4096, "%s label" % fstype)

        try:
            extloop.mount()

        except errors.MountError:
            extloop.cleanup()
            shutil.rmtree(extmnt, ignore_errors=True)
            raise

        try:
            chroot.chroot(extmnt, None, "/bin/env HOME=/root /bin/bash")
        except:
            raise errors.CreatorError("Failed to chroot to %s." % target)
        finally:
            chroot.cleanup_after_chroot("img", extloop, os_image_dir, extmnt)
Ejemplo n.º 5
0
    def do_chroot(cls, target):#chroot.py parse opts&args
        img = target
        imgsize = misc.get_file_size(img) * 1024L * 1024L
        imgtype = misc.get_image_type(img)
        if imgtype == "btrfsimg":
            fstype = "btrfs"
            myDiskMount = fs_related.BtrfsDiskMount
        elif imgtype in ("ext3fsimg", "ext4fsimg"):
            fstype = imgtype[:4]
            myDiskMount = fs_related.ExtDiskMount
        else:
            raise errors.CreatorError("Unsupported filesystem type: %s" % imgtype)

        extmnt = misc.mkdtemp()
        extloop = myDiskMount(fs_related.SparseLoopbackDisk(img, imgsize),
                                                         extmnt,
                                                         fstype,
                                                         4096,
                                                         "%s label" % fstype)
        try:
            extloop.mount()

        except errors.MountError:
            extloop.cleanup()
            shutil.rmtree(extmnt, ignore_errors = True)
            raise

        try:
            chroot.chroot(extmnt, None,  "/bin/env HOME=/root /bin/bash")
        except:
            raise errors.CreatorError("Failed to chroot to %s." %img)
        finally:
            chroot.cleanup_after_chroot("img", extloop, None, extmnt)
Ejemplo n.º 6
0
 def __init__(self, rootdir, distro, arch=None):
     self.rootdir = misc.mkdtemp(dir=rootdir, prefix=distro)
     self.distro = distro
     self.arch = arch
     self.logfile = None
     self.pkgslist = []
     self.repomd = None
 def __init__(self, rootdir, distro, arch=None):
     self.rootdir = misc.mkdtemp(dir=rootdir, prefix=distro)
     self.distro = distro
     self.arch = arch
     self.logfile = None
     self.pkgslist = []
     self.repomd = None
Ejemplo n.º 8
0
    def do_unpack(cls, srcimg):
        srcimgsize = (misc.get_file_size(srcimg)) * 1024L * 1024L
        srcmnt = misc.mkdtemp("srcmnt")
        disk = fs_related.SparseLoopbackDisk(srcimg, srcimgsize)
        srcloop = PartitionedMount(srcmnt, skipformat = True)

        srcloop.add_disk('/dev/sdb', disk)
        srcloop.add_partition(srcimgsize/1024/1024, "/dev/sdb", "/", "ext3", boot=False)
        try:
            srcloop.mount()

        except errors.MountError:
            srcloop.cleanup()
            raise

        image = os.path.join(tempfile.mkdtemp(dir = "/var/tmp", prefix = "tmp"), "target.img")
        args = ['dd', "if=%s" % srcloop.partitions[0]['device'], "of=%s" % image]

        msger.info("`dd` image ...")
        rc = runner.show(args)
        srcloop.cleanup()
        shutil.rmtree(os.path.dirname(srcmnt), ignore_errors = True)

        if rc != 0:
            raise errors.CreatorError("Failed to dd")
        else:
            return image
Ejemplo n.º 9
0
    def do_unpack(cls, srcimg):
        srcimgsize = (misc.get_file_size(srcimg)) * 1024L * 1024L
        srcmnt = misc.mkdtemp("srcmnt")
        disk = fs_related.SparseLoopbackDisk(srcimg, srcimgsize)
        srcloop = PartitionedMount({'/dev/sdb': disk}, srcmnt, skipformat=True)

        srcloop.add_partition(srcimgsize / 1024 / 1024,
                              "/dev/sdb",
                              "/",
                              "ext3",
                              boot=False)
        try:
            srcloop.mount()

        except errors.MountError:
            srcloop.cleanup()
            raise

        image = os.path.join(tempfile.mkdtemp(dir="/var/tmp", prefix="tmp"),
                             "target.img")
        args = [
            'dd',
            "if=%s" % srcloop.partitions[0]['device'],
            "of=%s" % image
        ]

        msger.info("`dd` image ...")
        rc = runner.show(args)
        srcloop.cleanup()
        shutil.rmtree(os.path.dirname(srcmnt), ignore_errors=True)

        if rc != 0:
            raise errors.CreatorError("Failed to dd")
        else:
            return image
Ejemplo n.º 10
0
    def do_unpack(cls, srcimg):
        img = srcimg
        imgsize = misc.get_file_size(img) * 1024L * 1024L
        imgmnt = misc.mkdtemp()
        disk = fs_related.SparseLoopbackDisk(img, imgsize)
        imgloop = PartitionedMount(imgmnt, skipformat = True)
        imgloop.add_disk('/dev/sdb', disk)
        imgloop.add_partition(imgsize/1024/1024, "/dev/sdb", "/", "vfat", boot=False)
        try:
            imgloop.mount()
        except errors.MountError:
            imgloop.cleanup()
            raise

        # legacy LiveOS filesystem layout support, remove for F9 or F10
        if os.path.exists(imgmnt + "/squashfs.img"):
            squashimg = imgmnt + "/squashfs.img"
        else:
            squashimg = imgmnt + "/LiveOS/squashfs.img"

        tmpoutdir = misc.mkdtemp()
        # unsquashfs requires outdir mustn't exist
        shutil.rmtree(tmpoutdir, ignore_errors = True)
        misc.uncompress_squashfs(squashimg, tmpoutdir)

        try:
            # legacy LiveOS filesystem layout support, remove for F9 or F10
            if os.path.exists(tmpoutdir + "/os.img"):
                os_image = tmpoutdir + "/os.img"
            else:
                os_image = tmpoutdir + "/LiveOS/ext3fs.img"

            if not os.path.exists(os_image):
                raise errors.CreatorError("'%s' is not a valid live CD ISO : neither "
                                          "LiveOS/ext3fs.img nor os.img exist" %img)
            imgname = os.path.basename(srcimg)
            imgname = os.path.splitext(imgname)[0] + ".img"
            rtimage = os.path.join(tempfile.mkdtemp(dir = "/var/tmp", prefix = "tmp"), imgname)
            shutil.copyfile(os_image, rtimage)

        finally:
            imgloop.cleanup()
            shutil.rmtree(tmpoutdir, ignore_errors = True)
            shutil.rmtree(imgmnt, ignore_errors = True)

        return rtimage
Ejemplo n.º 11
0
    def do_unpack(cls, srcimg):
        img = srcimg
        imgmnt = misc.mkdtemp()
        imgloop = fs_related.DiskMount(fs_related.LoopbackDisk(img, 0), imgmnt)
        try:
            imgloop.mount()
        except errors.MountError:
            imgloop.cleanup()
            raise

        # legacy LiveOS filesystem layout support, remove for F9 or F10
        if os.path.exists(imgmnt + "/squashfs.img"):
            squashimg = imgmnt + "/squashfs.img"
        else:
            squashimg = imgmnt + "/LiveOS/squashfs.img"

        tmpoutdir = misc.mkdtemp()
        # unsquashfs requires outdir mustn't exist
        shutil.rmtree(tmpoutdir, ignore_errors=True)
        misc.uncompress_squashfs(squashimg, tmpoutdir)

        try:
            # legacy LiveOS filesystem layout support, remove for F9 or F10
            if os.path.exists(tmpoutdir + "/os.img"):
                os_image = tmpoutdir + "/os.img"
            else:
                os_image = tmpoutdir + "/LiveOS/ext3fs.img"

            if not os.path.exists(os_image):
                raise errors.CreatorError(
                    "'%s' is not a valid live CD ISO : neither "
                    "LiveOS/ext3fs.img nor os.img exist" % img)

            imgname = os.path.basename(srcimg)
            imgname = os.path.splitext(imgname)[0] + ".img"
            rtimage = os.path.join(
                tempfile.mkdtemp(dir="/var/tmp", prefix="tmp"), imgname)
            shutil.copyfile(os_image, rtimage)

        finally:
            imgloop.cleanup()
            shutil.rmtree(tmpoutdir, ignore_errors=True)
            shutil.rmtree(imgmnt, ignore_errors=True)

        return rtimage
Ejemplo n.º 12
0
    def do_unpack(cls, srcimg):
        img = srcimg
        imgmnt = misc.mkdtemp()
        imgloop = fs_related.DiskMount(fs_related.LoopbackDisk(img, 0), imgmnt)
        try:
            imgloop.mount()
        except errors.MountError:
            imgloop.cleanup()
            raise

        # legacy LiveOS filesystem layout support, remove for F9 or F10
        if os.path.exists(imgmnt + "/squashfs.img"):
            squashimg = imgmnt + "/squashfs.img"
        else:
            squashimg = imgmnt + "/LiveOS/squashfs.img"

        tmpoutdir = misc.mkdtemp()
        # unsquashfs requires outdir mustn't exist
        shutil.rmtree(tmpoutdir, ignore_errors=True)
        misc.uncompress_squashfs(squashimg, tmpoutdir)

        try:
            # legacy LiveOS filesystem layout support, remove for F9 or F10
            if os.path.exists(tmpoutdir + "/os.img"):
                os_image = tmpoutdir + "/os.img"
            else:
                os_image = tmpoutdir + "/LiveOS/ext3fs.img"

            if not os.path.exists(os_image):
                raise errors.CreatorError(
                    "'%s' is not a valid live CD ISO : neither " "LiveOS/ext3fs.img nor os.img exist" % img
                )

            imgname = os.path.basename(srcimg)
            imgname = os.path.splitext(imgname)[0] + ".img"
            rtimage = os.path.join(tempfile.mkdtemp(dir="/var/tmp", prefix="tmp"), imgname)
            shutil.copyfile(os_image, rtimage)

        finally:
            imgloop.cleanup()
            shutil.rmtree(tmpoutdir, ignore_errors=True)
            shutil.rmtree(imgmnt, ignore_errors=True)

        return rtimage
Ejemplo n.º 13
0
    def do_chroot(cls, target, cmd=[]):
        if target.endswith('.tar'):
            import tarfile
            if tarfile.is_tarfile(target):
                LoopPlugin._do_chroot_tar(target, cmd)
                return
            else:
                raise errors.CreatorError("damaged tarball for loop images")

        img = target
        imgsize = misc.get_file_size(img) * 1024L * 1024L
        imgtype = misc.get_image_type(img)
        if imgtype == "btrfsimg":
            fstype = "btrfs"
            myDiskMount = fs_related.BtrfsDiskMount
        elif imgtype in ("ext3fsimg", "ext4fsimg"):
            fstype = imgtype[:4]
            myDiskMount = fs_related.ExtDiskMount
        else:
            raise errors.CreatorError("Unsupported filesystem type: %s" \
                                      % imgtype)

        extmnt = misc.mkdtemp()
        extloop = myDiskMount(fs_related.SparseLoopbackDisk(img, imgsize),
                                                         extmnt,
                                                         fstype,
                                                         4096,
                                                         "%s label" % fstype)
        try:
            extloop.mount()

        except errors.MountError:
            extloop.cleanup()
            shutil.rmtree(extmnt, ignore_errors=True)
            raise

        try:
            if len(cmd) != 0:
                cmdline = ' '.join(cmd)
            else:
                cmdline = "/bin/bash"
            envcmd = fs_related.find_binary_inchroot("env", extmnt)
            if envcmd:
                cmdline = "%s HOME=/root %s" % (envcmd, cmdline)
            chroot.chroot(extmnt, None, cmdline)
        except:
            raise errors.CreatorError("Failed to chroot to %s." % img)
        finally:
            chroot.cleanup_after_chroot("img", extloop, None, extmnt)
Ejemplo n.º 14
0
    def do_chroot(cls, target, cmd=[]):
        if target.endswith('.tar'):
            import tarfile
            if tarfile.is_tarfile(target):
                LoopPlugin._do_chroot_tar(target, cmd)
                return
            else:
                raise errors.CreatorError("damaged tarball for loop images")

        img = target
        imgsize = misc.get_file_size(img) * 1024L * 1024L
        imgtype = misc.get_image_type(img)
        if imgtype == "btrfsimg":
            fstype = "btrfs"
            myDiskMount = fs_related.BtrfsDiskMount
        elif imgtype in ("ext3fsimg", "ext4fsimg"):
            fstype = imgtype[:4]
            myDiskMount = fs_related.ExtDiskMount
        else:
            raise errors.CreatorError("Unsupported filesystem type: %s" \
                                      % imgtype)

        extmnt = misc.mkdtemp()
        extloop = myDiskMount(fs_related.SparseLoopbackDisk(img, imgsize),
                                                         extmnt,
                                                         fstype,
                                                         4096,
                                                         "%s label" % fstype)
        try:
            extloop.mount()

        except errors.MountError:
            extloop.cleanup()
            shutil.rmtree(extmnt, ignore_errors=True)
            raise

        try:
            if cmd is not None:
                cmdline = cmd
            else:
                cmdline = "/bin/bash"
            envcmd = fs_related.find_binary_inchroot("env", extmnt)
            if envcmd:
                cmdline = "%s HOME=/root %s" % (envcmd, cmdline)
            chroot.chroot(extmnt, None, cmdline)
        except:
            raise errors.CreatorError("Failed to chroot to %s." % img)
        finally:
            chroot.cleanup_after_chroot("img", extloop, None, extmnt)
Ejemplo n.º 15
0
    def do_chroot(cls, target, cmd=[]):
        os_image = cls.do_unpack(target)
        os_image_dir = os.path.dirname(os_image)

        # unpack image to target dir
        imgsize = misc.get_file_size(os_image) * 1024L * 1024L
        imgtype = misc.get_image_type(os_image)
        if imgtype == "btrfsimg":
            fstype = "btrfs"
            myDiskMount = fs_related.BtrfsDiskMount
        elif imgtype in ("ext3fsimg", "ext4fsimg"):
            fstype = imgtype[:4]
            myDiskMount = fs_related.ExtDiskMount
        else:
            raise errors.CreatorError("Unsupported filesystem type: %s" % fstype)

        extmnt = misc.mkdtemp()
        extloop = myDiskMount(fs_related.SparseLoopbackDisk(os_image, imgsize),
                              extmnt,
                              fstype,
                              4096,
                              "%s label" % fstype)
        try:
            extloop.mount()

        except errors.MountError:
            extloop.cleanup()
            shutil.rmtree(extmnt, ignore_errors = True)
            shutil.rmtree(os_image_dir, ignore_errors = True)
            raise

        try:
            if len(cmd) != 0:
                cmdline = ' '.join(cmd)
            else:
                cmdline = "/bin/bash"
            envcmd = fs_related.find_binary_inchroot("env", extmnt)
            if envcmd:
                cmdline = "%s HOME=/root %s" % (envcmd, cmdline)
            chroot.chroot(extmnt, None, cmdline)
        except:
            raise errors.CreatorError("Failed to chroot to %s." %target)
        finally:
            chroot.cleanup_after_chroot("img", extloop, os_image_dir, extmnt)
Ejemplo n.º 16
0
    def do_chroot(cls, target):
        import tarfile
        if tarfile.is_tarfile(target):
            LoopPlugin._do_chroot_tar(target)
            return

        img = target
        imgsize = misc.get_file_size(img) * 1024L * 1024L
        imgtype = misc.get_image_type(img)
        if imgtype == "btrfsimg":
            fstype = "btrfs"
            myDiskMount = fs_related.BtrfsDiskMount
        elif imgtype in ("ext3fsimg", "ext4fsimg"):
            fstype = imgtype[:4]
            myDiskMount = fs_related.ExtDiskMount
        else:
            raise errors.CreatorError("Unsupported filesystem type: %s" \
                                      % imgtype)

        extmnt = misc.mkdtemp()
        extloop = myDiskMount(fs_related.SparseLoopbackDisk(img, imgsize),
                                                         extmnt,
                                                         fstype,
                                                         4096,
                                                         "%s label" % fstype)
        try:
            extloop.mount()

        except errors.MountError:
            extloop.cleanup()
            shutil.rmtree(extmnt, ignore_errors=True)
            raise

        try:
            chroot.chroot(extmnt, None,  "/bin/env HOME=/root /bin/bash")
        except:
            raise errors.CreatorError("Failed to chroot to %s." % img)
        finally:
            chroot.cleanup_after_chroot("img", extloop, None, extmnt)
Ejemplo n.º 17
0
    def do_chroot(cls, target):
        img = target
        imgsize = misc.get_file_size(img) * 1024L * 1024L
        partedcmd = fs_related.find_binary_path("parted")
        disk = fs_related.SparseLoopbackDisk(img, imgsize)
        imgmnt = misc.mkdtemp()
        imgloop = PartitionedMount({'/dev/sdb': disk}, imgmnt, skipformat=True)
        img_fstype = "ext3"

        # Check the partitions from raw disk.
        root_mounted = False
        partition_mounts = 0
        for line in runner.outs([partedcmd, "-s", img, "unit", "B",
                                 "print"]).splitlines():
            line = line.strip()

            # Lines that start with number are the partitions,
            # because parted can be translated we can't refer to any text lines.
            if not line or not line[0].isdigit():
                continue

            # Some vars have extra , as list seperator.
            line = line.replace(",", "")

            # Example of parted output lines that are handled:
            # Number  Start        End          Size         Type     File system     Flags
            #  1      512B         3400000511B  3400000000B  primary
            #  2      3400531968B  3656384511B  255852544B   primary  linux-swap(v1)
            #  3      3656384512B  3720347647B  63963136B    primary  fat16           boot, lba

            partition_info = re.split("\s+", line)

            size = partition_info[3].split("B")[0]

            if len(partition_info) < 6 or partition_info[5] in ["boot"]:
                # No filesystem can be found from partition line. Assuming
                # btrfs, because that is the only MeeGo fs that parted does
                # not recognize properly.
                # TODO: Can we make better assumption?
                fstype = "btrfs"
            elif partition_info[5] in ["ext2", "ext3", "ext4", "btrfs"]:
                fstype = partition_info[5]
            elif partition_info[5] in ["fat16", "fat32"]:
                fstype = "vfat"
            elif "swap" in partition_info[5]:
                fstype = "swap"
            else:
                raise errors.CreatorError(
                    "Could not recognize partition fs type '%s'." %
                    partition_info[5])

            if not root_mounted and fstype in [
                    "ext2", "ext3", "ext4", "btrfs"
            ]:
                # TODO: Check that this is actually the valid root partition from /etc/fstab
                mountpoint = "/"
                root_mounted = True
            elif fstype == "swap":
                mountpoint = "swap"
            else:
                # TODO: Assing better mount points for the rest of the partitions.
                partition_mounts += 1
                mountpoint = "/media/partition_%d" % partition_mounts

            if "boot" in partition_info:
                boot = True
            else:
                boot = False

            msger.verbose(
                "Size: %s Bytes, fstype: %s, mountpoint: %s, boot: %s" %
                (size, fstype, mountpoint, boot))
            # TODO: add_partition should take bytes as size parameter.
            imgloop.add_partition((int)(size) / 1024 / 1024,
                                  "/dev/sdb",
                                  mountpoint,
                                  fstype=fstype,
                                  boot=boot)

        try:
            imgloop.mount()

        except errors.MountError:
            imgloop.cleanup()
            raise

        try:
            chroot.chroot(imgmnt, None, "/bin/env HOME=/root /bin/bash")
        except:
            raise errors.CreatorError("Failed to chroot to %s." % img)
        finally:
            chroot.cleanup_after_chroot("img", imgloop, None, imgmnt)
Ejemplo n.º 18
0
Archivo: loop.py Proyecto: tizenpdk/mic
    def _stage_final_image(self):

        if self.pack_to or self.shrink_image:
            self._resparse(0)
        else:
            self._resparse()

        for item in self._instloops:
            imgfile = os.path.join(self._imgdir, item['name'])

            if item['aft_fstype'] in AFTER_MNT_FS.keys():
                mountpoint = misc.mkdtemp()
                ext4img = os.path.join(self._imgdir, item['name'])
                runner.show('mount -t ext4 %s %s' % (ext4img, mountpoint))
                runner.show('ls -al %s' % (mountpoint))
#                item['loop'].mount(None, 'not_create')
#                point_mnt = os.path.join(self._instroot, item['mountpoint'].lstrip('/'))

                fs_suffix = AFTER_MNT_FS[item['aft_fstype']]
                if item['aft_fstype'] == "squashfs":
#                    fs.mksquashfs(mountpoint, self._outdir+"/"+item['label']+fs_suffix)
                    args = "mksquashfs " + mountpoint + " " + self._imgdir+"/"+item['label']+fs_suffix
                    if item['squashfsopts']:
                        squashfsopts=item['squashfsopts'].replace(',', ' ')
                        runner.show("mksquashfs --help")
                        runner.show("%s %s" % (args, squashfsopts))
                    else:
                        runner.show("%s " % args)

                if item['aft_fstype'] == "vdfs":
                    ##FIXME temporary code - replace this with fs.mkvdfs()
                    if item['vdfsopts']:
                        vdfsopts=item['vdfsopts'].replace(',', ' ')
                    else:
                        vdfsopts="-i -z 1024M"

                    fullpathmkvdfs = "mkfs.vdfs" #find_binary_path("mkfs.vdfs")
                    runner.show("%s --help" % fullpathmkvdfs)
#                    fs.mkvdfs(mountpoint, self._outdir+"/"+item['label']+fs_suffix, vdfsopts)
                    runner.show('%s %s -r %s %s' % (fullpathmkvdfs, vdfsopts, mountpoint, self._imgdir+"/"+item['label']+fs_suffix))

                runner.show('umount %s' % mountpoint)
#               os.unlink(mountpoint)
                runner.show('mv %s %s' % (self._imgdir+"/"+item['label']+fs_suffix, self._imgdir+"/"+item['label']+".img") )
                runner.show('ls -al %s' % self._imgdir)

            if item['fstype'] == "ext4":
                if not item['cpioopts']:
                    runner.show('/sbin/tune2fs -O ^huge_file,extents,uninit_bg %s '
                            % imgfile)
                    runner.quiet(["/sbin/e2fsck", "-f", "-y", imgfile])
            self.image_files.setdefault('partitions', {}).update(
                    {item['mountpoint']: item['label']})
            if self.compress_image:
                compressing(imgfile, self.compress_image)
                self.image_files.setdefault('image_files', []).append(
                                '.'.join([item['name'], self.compress_image]))
            else:
                self.image_files.setdefault('image_files', []).append(item['name'])

        for item in os.listdir(self._imgdir):
            imgfile = os.path.join(self._imgdir, item)
            imgsize = os.path.getsize(imgfile)
            msger.info("filesystem size of %s : %s bytes" % (item, imgsize))

        self.run_sign_scripts()
        if not self.pack_to:
            for item in os.listdir(self._imgdir):
                shutil.move(os.path.join(self._imgdir, item),
                            os.path.join(self._outdir, item))
        else:
            msger.info("Pack all loop images together to %s" % self.pack_to)
            dstfile = os.path.join(self._outdir, self.pack_to)
            packing(dstfile, self._imgdir)
            self.image_files['image_files'] = [self.pack_to]


        if self.pack_to:
            mountfp_xml = os.path.splitext(self.pack_to)[0]
            mountfp_xml = misc.strip_end(mountfp_xml, '.tar') + ".xml"
        else:
            mountfp_xml = self.name + ".xml"
        # save mount points mapping file to xml
        save_mountpoints(os.path.join(self._outdir, mountfp_xml),
                         self._instloops,
                         self.target_arch)
Ejemplo n.º 19
0
    def do_chroot(cls, target, cmd=[]):
        img = target
        imgsize = misc.get_file_size(img) * 1024L * 1024L
        partedcmd = fs_related.find_binary_path("parted")
        disk = fs_related.SparseLoopbackDisk(img, imgsize)
        imgmnt = misc.mkdtemp()
        imgloop = PartitionedMount(imgmnt, skipformat = True)
        imgloop.add_disk('/dev/sdb', disk)
        img_fstype = "ext3"

        msger.info("Partition Table:")
        partnum = []
        for line in runner.outs([partedcmd, "-s", img, "print"]).splitlines():
            # no use strip to keep line output here
            if "Number" in line:
                msger.raw(line)
            if line.strip() and line.strip()[0].isdigit():
                partnum.append(line.strip()[0])
                msger.raw(line)

        rootpart = None
        if len(partnum) > 1:
            rootpart = msger.choice("please choose root partition", partnum)

        # Check the partitions from raw disk.
        # if choose root part, the mark it as mounted
        if rootpart:
            root_mounted = True
        else:
            root_mounted = False
        partition_mounts = 0
        for line in runner.outs([partedcmd,"-s",img,"unit","B","print"]).splitlines():
            line = line.strip()

            # Lines that start with number are the partitions,
            # because parted can be translated we can't refer to any text lines.
            if not line or not line[0].isdigit():
                continue

            # Some vars have extra , as list seperator.
            line = line.replace(",","")

            # Example of parted output lines that are handled:
            # Number  Start        End          Size         Type     File system     Flags
            #  1      512B         3400000511B  3400000000B  primary
            #  2      3400531968B  3656384511B  255852544B   primary  linux-swap(v1)
            #  3      3656384512B  3720347647B  63963136B    primary  fat16           boot, lba

            partition_info = re.split("\s+",line)

            size = partition_info[3].split("B")[0]

            if len(partition_info) < 6 or partition_info[5] in ["boot"]:
                # No filesystem can be found from partition line. Assuming
                # btrfs, because that is the only MeeGo fs that parted does
                # not recognize properly.
                # TODO: Can we make better assumption?
                fstype = "btrfs"
            elif partition_info[5] in ["ext2","ext3","ext4","btrfs"]:
                fstype = partition_info[5]
            elif partition_info[5] in ["fat16","fat32"]:
                fstype = "vfat"
            elif "swap" in partition_info[5]:
                fstype = "swap"
            else:
                raise errors.CreatorError("Could not recognize partition fs type '%s'." % partition_info[5])

            if rootpart and rootpart == line[0]:
                mountpoint = '/'
            elif not root_mounted and fstype in ["ext2","ext3","ext4","btrfs"]:
                # TODO: Check that this is actually the valid root partition from /etc/fstab
                mountpoint = "/"
                root_mounted = True
            elif fstype == "swap":
                mountpoint = "swap"
            else:
                # TODO: Assing better mount points for the rest of the partitions.
                partition_mounts += 1
                mountpoint = "/media/partition_%d" % partition_mounts

            if "boot" in partition_info:
                boot = True
            else:
                boot = False

            msger.verbose("Size: %s Bytes, fstype: %s, mountpoint: %s, boot: %s" % (size, fstype, mountpoint, boot))
            # TODO: add_partition should take bytes as size parameter.
            imgloop.add_partition((int)(size)/1024/1024, "/dev/sdb", mountpoint, fstype = fstype, boot = boot)

        try:
            imgloop.mount()

        except errors.MountError:
            imgloop.cleanup()
            raise

        try:
            if len(cmd) != 0:
                cmdline = ' '.join(cmd)
            else:
                cmdline = "/bin/bash"
            envcmd = fs_related.find_binary_inchroot("env", imgmnt)
            if envcmd:
                cmdline = "%s HOME=/root %s" % (envcmd, cmdline)
            chroot.chroot(imgmnt, None, cmdline)
        except:
            raise errors.CreatorError("Failed to chroot to %s." %img)
        finally:
            chroot.cleanup_after_chroot("img", imgloop, None, imgmnt)