예제 #1
0
파일: parted.py 프로젝트: ryan-blakley/pbr
    def create_uefi_usb(self, disk):
        """
        Create the partition table on a usb, to make it bootable.
        :param disk: USB device name.
        :return:
        """
        self.log.debug(f"parted: create_legacy_usb: disk:{disk}")
        self.init_disk(disk, "msdos")

        geometry = parted.Geometry(device=self.device, start=2048, end=206849)
        partition = parted.Partition(disk=self.pdisk,
                                     type=parted.PARTITION_NORMAL,
                                     geometry=geometry)

        self.pdisk.addPartition(
            partition=partition,
            constraint=self.device.optimalAlignedConstraint)
        partition.setFlag(parted.PARTITION_BOOT)
        partition.setFlag(parted.PARTITION_ESP)

        geometry = parted.Geometry(device=self.device,
                                   start=206850,
                                   length=self.device.getLength() - 206850)
        partition = parted.Partition(disk=self.pdisk,
                                     type=parted.PARTITION_NORMAL,
                                     geometry=geometry)

        self.pdisk.addPartition(
            partition=partition,
            constraint=self.device.optimalAlignedConstraint)

        self.pdisk.commit()

        self.device.removeFromCache()
예제 #2
0
파일: hdimg.py 프로젝트: a-darwish/elbe
def create_partition(disk, part, ptype, fslabel, size_in_sectors,
                     current_sector):

    # pylint: disable=too-many-arguments

    sector_size = 512
    if part.text("size") == "remain" and disk.type == "gpt":
        sz = size_in_sectors - 35 - current_sector
    elif part.text("size") == "remain":
        sz = size_in_sectors - current_sector
    else:
        sz = size_to_int(part.text("size")) / sector_size

    g = parted.Geometry(device=disk.device, start=current_sector, length=sz)
    if ptype != parted.PARTITION_EXTENDED and \
       part.text("label") in fslabel and \
       fslabel[part.text("label")].fstype == "vfat":

        fs = simple_fstype("fat32")
        ppart = parted.Partition(disk, ptype, fs, geometry=g)
        if disk.type != "gpt":
            ppart.setFlag(_ped.PARTITION_LBA)
    else:
        ppart = parted.Partition(disk, ptype, geometry=g)

    cons = parted.Constraint(exactGeom=g)
    disk.addPartition(ppart, cons)

    if part.has("bootable"):
        ppart.setFlag(_ped.PARTITION_BOOT)

    if part.has("biosgrub"):
        ppart.setFlag(_ped.PARTITION_BIOS_GRUB)

    return ppart
예제 #3
0
    def create_partition(self, start, end, type, hints):
        drvsectors = self.drive.get_length()
        if self.disk is None:
            self.disk = self.drive.disk_open()
        if self.disk is None:
            raise RuntimeError, "drive has no partition table"

        if "primary" in hints:
            if self.primarynum > 4:
                raise RuntimeError, "out of primary partitions"
            if self.isext:
                raise RuntimeError, "cannot create primary partition after extended partition"
            partnum = self.primarynum
            self.primarynum = self.primarynum + 1
            parttypecode = parted.PED_PARTITION_PRIMARY
        else:
            if not self.isext:
                if self.primarynum > 4:
                    raise RuntimeError, "out of slots for extended partition"
                self.disk.add_partition(
                    parted.Partition(self.disk,
                                     parted.PED_PARTITION_EXTENDED,
                                     None, start, drvsectors - 1))
            self.primarynum = self.primarynum + 1
            self.isext = 1
            partnum = self.extnum
            self.extnum = self.extnum + 1
            parttypecode = parted.PED_PARTITION_LOGICAL

        drvnewpart = parted.Partition(self.disk, parttypecode, type,
                                      start, end)
        self.disk.add_partition(drvnewpart)

        partdevice = "%s%d" % (self.drive.get_path(), partnum)
        return partdevice
예제 #4
0
    def runTest(self):
        # Check that not passing args to parted.Partition.__init__ is caught.
        with self.assertRaises((parted.PartitionException,)):
            parted.Partition()

        self.assertIsInstance(self.part, parted.Partition)
        # You don't need to pass a filesystem type at all, since this partition
        # might be FREESPACE or METADATA.
        part_nofs = parted.Partition(self.disk, parted.PARTITION_NORMAL,
                                geometry=self.geom)
        self.assertIsInstance(part_nofs, parted.Partition)
예제 #5
0
def shrinkpart(part, size):
    dsk = part.disk
    dev = dsk.device
    print('Resizing partition...')
    # Create a new geometry
    newgeo = parted.Geometry(start=part.geometry.start,
                             length=parted.sizeToSectors(
                                 shrink_to, 'B', dev.sectorSize),
                             device=dev)
    logging.DEBUG(newgeo.__str__())
    # Create a new partition with our new geometry
    newpart = parted.Partition(disk=dsk,
                               type=parted.PARTITION_NORMAL,
                               geometry=newgeo)
    # Create a constraint that aligns our new geometry with the optimal alignment of the disk
    constraint = parted.Constraint(maxGeom=newgeo).intersect(
        dev.optimalAlignedConstraint)
    dsk.deletePartition(part)
    dsk.addPartition(partition=newpart, constraint=constraint)
    try:
        dsk.commit()
    except:
        pass

    return (newgeo.end + 1) * dev.sectorSize
예제 #6
0
    def partitionAdd(self,
                     disk,
                     free,
                     align=None,
                     length=None,
                     fs_type=None,
                     type=parted.PARTITION_NORMAL):
        start = free.start
        if length:
            end = start + length - 1
        else:
            end = free.end
            length = free.end - start + 1

        if not align:
            align = disk.partitionAlignment.intersect(
                disk.device.optimumAlignment)

        if not align.isAligned(free, start):
            start = align.alignNearest(free, start)

        end_align = parted.Alignment(offset=align.offset - 1,
                                     grainSize=align.grainSize)
        if not end_align.isAligned(free, end):
            end = end_align.alignNearest(free, end)

        geometry = parted.Geometry(disk.device, start=start, end=end)
        if fs_type:
            fs = parted.FileSystem(type=fs_type, geometry=geometry)
        else:
            fs = None
        partition = parted.Partition(disk, type=type, geometry=geometry, fs=fs)
        constraint = parted.Constraint(exactGeom=partition.geometry)
        disk.addPartition(partition, constraint)
        return partition
예제 #7
0
    def add_partition(self, start, end, ptype=None):
        """ Add a partition to the disklabel.

            :param int start: start sector
            :param int end: end sector
            :param ptype: partition type or None
            :type ptype: int (parted partition type constant) or NoneType

            Partition type will default to either PARTITION_NORMAL or
            PARTITION_LOGICAL, depending on whether the start sector is within
            an extended partition.
        """
        if ptype is None:
            extended = self.extended_partition
            if extended and extended.geometry.contains(start):
                ptype = parted.PARTITION_LOGICAL
            else:
                ptype = parted.PARTITION_NORMAL

        geometry = parted.Geometry(device=self.parted_device,
                                   start=start, end=end)
        new_partition = parted.Partition(disk=self.parted_disk,
                                         type=ptype,
                                         geometry=geometry)

        constraint = parted.Constraint(exactGeom=geometry)
        self.parted_disk.addPartition(partition=new_partition,
                                      constraint=constraint)
예제 #8
0
    def partition(self):
        """
        Create a partition table on the block device.

        The newly created partition will have the following characteristics:
            - a primary partition using 100% of the device capacity
            - optimal alignment given the disk topology information
            - a MS-DOS disk label for simple BIOS booting on PC-type hardware
            - marked as bootable
        """
        self.logger.info('creating primary partition')
        device = parted.getDevice(self.path)
        self.logger.debug('created %s', device)
        disk = parted.freshDisk(device, 'msdos')
        self.logger.debug('created %s', disk)
        geometry = parted.Geometry(device=device,
                                   start=1,
                                   length=device.getLength() - 1)
        self.logger.debug('created %s', geometry)
        filesystem = parted.FileSystem(type='ext3', geometry=geometry)
        self.logger.debug('created %s', filesystem)
        partition = parted.Partition(disk=disk,
                                     type=parted.PARTITION_NORMAL,
                                     fs=filesystem,
                                     geometry=geometry)
        self.logger.debug('created %s', partition)
        disk.addPartition(partition=partition,
                          constraint=device.optimalAlignedConstraint)
        partition.setFlag(parted.PARTITION_BOOT)
        disk.commit()
예제 #9
0
def mkfakediskimg(disk_img):
    """Create a fake partitioned disk image

    :param disk_img: Full path to a partitioned disk image
    :type disk_img: str
    :returns: True if it was successful, False if something went wrong

    Include /boot, swap, and / partitions with fake kernel and /etc/passwd
    """
    try:
        mksparse(disk_img, 42 * 1024**2)
        # Make a /boot, / and swap partitions on it
        dev = parted.getDevice(disk_img)
        disk = parted.freshDisk(dev, "gpt")

        # (start, length, flags, name)
        for start, length, flags, name in [
                  (  1024**2,    1024**2, None, "boot"),
                  (2*1024**2,  2*1024**2, parted.PARTITION_SWAP, "swap"),
                  (4*1024**2, 38*1024**2, None, "root")]:
            geo = parted.Geometry(device=dev, start=start//dev.sectorSize, length=length//dev.sectorSize)
            part = parted.Partition(disk=disk, type=parted.PARTITION_NORMAL, geometry=geo)
            part.getPedPartition().set_name(name)
            disk.addPartition(partition=part)
            if flags:
                part.setFlag(flags)
        disk.commit()
        os.sync()
    except parted.PartedException:
        return False

    # Mount the disk's partitions
    loop_devs = kpartx_disk_img(disk_img)

    try:
        # Format the partitions
        runcmd(["mkfs.ext4", "/dev/mapper/" + loop_devs[0][0]])
        runcmd(["mkswap", "/dev/mapper/" + loop_devs[1][0]])
        runcmd(["mkfs.ext4", "/dev/mapper/" + loop_devs[2][0]])

        # Mount the boot partition and make a fake kernel and initrd
        boot_mnt = mount("/dev/mapper/" + loop_devs[0][0])
        try:
            mkfakebootdir(boot_mnt)
        finally:
            umount(boot_mnt)

        # Mount the / partition and make a fake / filesystem with /etc/passwd
        root_mnt = mount("/dev/mapper/" + loop_devs[2][0])
        try:
            mkfakerootdir(root_mnt)
        finally:
            umount(root_mnt)
    except Exception:
        return False
    finally:
        # Remove the disk's mounted partitions
        runcmd(["kpartx", "-d", "-s", disk_img])

    return True
예제 #10
0
 def getExtendedPartition(self):
     """Return the extended Partition, if any, on this Disk."""
     try:
         return parted.Partition(disk=self, PedPartition=self.__disk.extended_partition())
     # pylint: disable=bare-except
     except:
         return None
예제 #11
0
def create_partition(diskob, part_type, geom):
    #A lot of this is similar to Anaconda, but customized to fit our needs
    nstart = geom.start
    nend = geom.end
    # Just in case you try to create partition larger than disk.
    # This case should be caught in the frontend!
    # Never let user specify a length exceeding the free space.
    if nend > diskob.device.length - 1:
        nend = diskob.device.length - 1
    nalign = diskob.partitionAlignment
    if not nalign.isAligned(geom, nstart):
        nstart = nalign.alignNearest(geom, nstart)
    if not nalign.isAligned(geom, nend):
        nstart = nalign.alignNearest(geom, nend)
    if part_type == 1:
        nstart += nalign.grainSize
    ngeom = parted.Geometry(device=diskob.device, start=nstart, end=nend)
    if diskob.maxPartitionLength < ngeom.length:
        print('Partition is too large!')
        sys.exit(1)
    npartition = parted.Partition(disk=diskob,
                                  type=part_type,
                                  geometry=ngeom,
                                  fs=fs)
    nconstraint = parted.Constraint(exactGeom=ngeom)
    ncont = diskob.addPartition(partition=npartition, constraint=nconstraint)
예제 #12
0
def create_partition(diskob, part_type, geom):
    # A lot of this is similar to Anaconda, but customized to fit our needs
    nstart = geom.start
    nend = geom.end
    if nstart < 2048:
        nstart = 2048
    # Just in case you try to create partition larger than disk.
    # This case should be caught in the frontend!
    # Never let user specify a length exceeding the free space.
    if nend > diskob.device.length - 1:
        nend = diskob.device.length - 1
    nalign = diskob.partitionAlignment
    if not nalign.isAligned(geom, nstart):
        nstart = nalign.alignNearest(geom, nstart)
    if not nalign.isAligned(geom, nend):
        nend = nalign.alignDown(geom, nend)
    if part_type == 1:
        nstart += nalign.grainSize
    mingeom = parted.Geometry(device=diskob.device, start=nstart, end=nend-1)
    maxgeom = parted.Geometry(device=diskob.device, start=nstart, end=nend)
    if diskob.maxPartitionLength < maxgeom.length:
        txt = _('Partition is too large!')
        logging.error(txt)
        debugtxt = ("%s\n%s" % (txt, err))
        show.error(debugtxt)
        return None
    else:
        npartition = parted.Partition(disk=diskob, type=part_type, geometry=maxgeom)
        nconstraint = parted.Constraint(minGeom=mingeom, maxGeom=maxgeom)
        ncont = diskob.addPartition(partition=npartition, constraint=nconstraint)
        return npartition
예제 #13
0
def shrinkpart(part, size):
    dsk = part.disk
    dev = dsk.device
    print('Resizing partition...')
    # Create a new geometry
    newgeo = parted.Geometry(start=part.geometry.start,
                             length=parted.sizeToSectors(
                                 size, 'B', dev.sectorSize),
                             device=dev)
    #    logging.DEBUG(newgeo.__str__())
    # Create a new partition with our new geometry
    newpart = parted.Partition(disk=dsk,
                               type=parted.PARTITION_NORMAL,
                               geometry=newgeo)
    # Create a constraint that aligns our new geometry with the optimal alignment of the disk
    constraint = parted.Constraint(maxGeom=newgeo).intersect(
        dev.optimalAlignedConstraint)
    dsk.deletePartition(part)
    dsk.addPartition(partition=newpart, constraint=constraint)
    # This exception gets raised even though dsk.commit() seems to do its job just fine.
    # I am definitely not a fan of doing this, but so be it.
    try:
        dsk.commit()
    except parted._ped.IOException:
        pass

    return (newgeo.end + 1) * dev.sectorSize
    def putGeom(self, limPartList):
        #Write the disk geometry information
        #Template code @ https://bitbucket.org/rbistolfi/vinstall/wiki/pyparted
        disk = parted.freshDisk(self.dev, "msdos")
        for lpar in limPartList:
            if lpar.parttype != 'artificial':
                #TODO: should check that the geometry is within the disk
                g = parted.Geometry(device=self.dev,
                                    start=lpar.start,
                                    end=lpar.end)
                fs = parted.FileSystem(type=lpar.fstype, geometry=g)

                #TODO: eventually we should be able to handle logical/extended
                #partitions - right now it's primary only
                ptype = parted.PARTITION_NORMAL
                if lpar.parttype != 'primary':
                    raise errors.partError(lpar.parttype)

                p = parted.Partition(disk=disk, fs=fs, type=ptype, geometry=g)
                c = parted.Constraint(exactGeom=g)
                disk.addPartition(partition=p, constraint=c)
                setFlags(p, lpar.flags)
        disk.commit()

        #refresh the OS's view of the disk
        support.partprobe(self.node)

        #put file systems onto the new partitions
        for lpar in limPartList:
            if lpar.parttype != 'artificial':
                support.mkfs(lpar.composeNode(self.node), lpar.fstype)
예제 #15
0
    def apply(self, disk, simulate):
        """ Create a partition with the given type... """
        try:
            if not disk:
                raise RuntimeError("Cannot create partition on empty disk!")
            length = parted.sizeToSectors(self.size, 'B',
                                          disk.device.sectorSize)
            geom = parted.Geometry(device=self.device,
                                   start=self.part_offset,
                                   length=length)

            # Don't run off the end of the disk ...
            geom_cmp = self.get_all_remaining_geom(disk, disk.device,
                                                   self.part_offset)

            if geom_cmp.length < geom.length or geom.length < 0:
                geom = geom_cmp

            if "LVM" in self.fstype:
                fs = None
            else:
                fs = parted.FileSystem(type=self.fstype, geometry=geom)
            p = parted.Partition(disk=disk,
                                 type=self.ptype,
                                 fs=fs,
                                 geometry=geom)

            disk.addPartition(p, parted.Constraint(device=self.device))
            self.part = p
            self.part_end = self.part_offset + length
        except Exception as e:
            self.set_errors(e)
            return False
        return True
예제 #16
0
파일: disk.py 프로젝트: sil2100/pyparted
 def getPartitionBySector(self, sector):
     """Returns the Partition that contains the sector.  If the sector
        lies within a logical partition, then the logical partition is
        returned (not the extended partition)."""
     return parted.Partition(
         disk=self,
         PedPartition=self.__disk.get_partition_by_sector(sector))
예제 #17
0
 def setUp(self):
     super(PartitionGPTNewTestCase, self).setUp()
     self.geom = parted.Geometry(self.device, start=100, length=100)
     self.fs = parted.FileSystem(type='ext2', geometry=self.geom)
     self.part = parted.Partition(self.disk,
                                  parted.PARTITION_NORMAL,
                                  geometry=self.geom,
                                  fs=self.fs)
예제 #18
0
    def nextPartition(self):
        """Return the Partition following this one on the Disk."""
        partition = self.disk.getPedDisk().next_partition(self.__partition)

        if partition is None:
            return None
        else:
            return parted.Partition(disk=self.disk, PedPartition=partition)
예제 #19
0
    def runTest(self):
        self.disk.setFlag(parted.DISK_CYLINDER_ALIGNMENT)

        length = 100
        geom = parted.Geometry(self.device, start=100, length=length)
        part = parted.Partition(self.disk, parted.PARTITION_NORMAL, geometry=geom)
        constraint = parted.Constraint(exactGeom=geom)
        self.assertTrue(self.disk.addPartition(part, constraint))
예제 #20
0
def raw_format(device_path, fstype, volume_label):

    do_umount(device_path)

    # First erase MBR and partition table , if any
    os.system("dd if=/dev/zero of=%s bs=512 count=1 >/dev/null 2>&1" %
              device_path)

    device = parted.getDevice(device_path)

    # Create a default partition set up
    disk = parted.freshDisk(device, 'msdos')
    disk.commit()
    regions = disk.getFreeSpaceRegions()

    if len(regions) > 0:
        #print "Build partition"
        # Define size
        region = regions[-1]
        start = parted.sizeToSectors(1, "MiB", device.sectorSize)
        #print "start %s" % start
        end = device.getLength() - start - 1024
        #print end

        # Alignment
        #cylinder = device.endSectorToCylinder(end)
        #end = device.endCylinderToSector(cylinder)
        #print end
        try:
            geometry = parted.Geometry(device=device, start=start, end=end)
        except:
            print "Geometry error - Can't create partition"
            sys.exit(5)

        # fstype
        fs = parted.FileSystem(type=fstype, geometry=geometry)

        # Create partition
        partition = parted.Partition(disk=disk,
                                     type=parted.PARTITION_NORMAL,
                                     geometry=geometry,
                                     fs=fs)
        constraint = parted.Constraint(exactGeom=geometry)
        disk.addPartition(partition=partition, constraint=constraint)
        disk.commit()

        # Format partition according to the fstype specified
        if fstype == "fat32":
            os.system("mkdosfs -F 32 -n \"%s\" %s >/dev/null 2>&1" %
                      (volume_label, partition.path))
        if fstype == "ntfs":
            os.system("mkntfs -f -L \"%s\" %s >/dev/null 2>&1" %
                      (volume_label, partition.path))
        elif fstype == "ext4":
            os.system("mkfs.ext4 -L \"%s\" %s >/dev/null 2>&1" %
                      (volume_label, partition.path))
    sys.exit(0)
예제 #21
0
 def createpartition(self, device, disk, start, end, type):
     ''' Create a single partition of the specified type and size and add
         it to the disk object, using the parted module.
     '''
     geo = parted.Geometry(device=device, start=start, end=end)
     fs = parted.FileSystem(type=type, geometry=geo)
     part = parted.Partition(disk=disk, fs=fs, type=parted.PARTITION_NORMAL,
                             geometry=geo)
     constraint = parted.Constraint(exactGeom=geo)
     disk.addPartition(partition=part, constraint=constraint)
예제 #22
0
    def runTest(self):
        length = 100
        geom = parted.Geometry(self.device, start=100, length=length)
        part = parted.Partition(self.disk, parted.PARTITION_NORMAL, geometry=geom)
        constraint = parted.Constraint(exactGeom=geom)
        self.disk.addPartition(part, constraint)
        self.disk.commit()
        part = self.disk.partitions[0]

        self.assertEqual(part.getLength(), part.geometry.length)
        self.assertEqual(part.getLength(), length)
예제 #23
0
def __make_root__(device, start=config["ROOT"]["START"],
                  end=config["ROOT"]["END"], fs=config["ROOT"]["fs"]):
    """Make root partition"""
    # __parted__(device, ["mkpart", name, fs, str(start), str(end)])
    size = sectors_to_size(device.length, device.sectorSize)
    try:
        if start[-1] == "%":
            start = int(start[:-1]) / 100
            start = int(size * start)
    except TypeError:
        pass
    try:
        if end[-1] == "%":
            end = int(end[:-1]) / 100
            end = int(size * end)
    except TypeError:
        pass
    disk = parted.Disk(device)
    start_geo = parted.geometry.Geometry(device=device,
                                         start=parted.sizeToSectors(common.real_number(start - 20),
                                                                    "MB",
                                                                    device.sectorSize),
                                         end=parted.sizeToSectors(start + 20,
                                                                  "MB",
                                                                  device.sectorSize))
    end_geo = parted.geometry.Geometry(device=device,
                                       start=parted.sizeToSectors(common.real_number(end - 40),
                                                                  "MB",
                                                                  device.sectorSize),
                                       end=parted.sizeToSectors(end, "MB",
                                                                device.sectorSize))
    min_size = parted.sizeToSectors(common.real_number((end - start) - 150), "MB",
                                    device.sectorSize)
    max_size = parted.sizeToSectors(common.real_number((end - start) + 150), "MB",
                                    device.sectorSize)
    const = parted.Constraint(startAlign=device.optimumAlignment,
                              endAlign=device.optimumAlignment,
                              startRange=start_geo, endRange=end_geo,
                              minSize=min_size,
                              maxSize=max_size)
    geometry = parted.geometry.Geometry(start=parted.sizeToSectors(start, "MB",
                                                                   device.sectorSize),
                                        length=parted.sizeToSectors((end - start),
                                                                    "MB",
                                                                    device.sectorSize),
                                        device=device)
    new_part = parted.Partition(disk=disk,
                                type=parted.PARTITION_NORMAL,
                                geometry=geometry)
    disk.addPartition(partition=new_part, constraint=const)
    disk.commit()
    time.sleep(0.1)
    __mkfs__(new_part.path, fs)
    return new_part.path
예제 #24
0
def create_partitioning(device):
    """Returns a suitable partitioning (a disk) of the given
    device. You must specify device path (e.g. "/dev/sda"). Note that
    no changes will be made to the device. To write the partition to
    device use commit."""
    disk = parted.freshDisk(device, 'gpt')
    geometries = _compute_geometries(device)
    # Create ESP
    esp = parted.Partition(disk=disk,
                           type=parted.PARTITION_NORMAL,
                           fs=parted.FileSystem(type='fat32',
                                                geometry=geometries['esp']),
                           geometry=geometries['esp'])
    esp.setFlag(parted.PARTITION_BOOT)
    disk.addPartition(partition=esp,
                      constraint=device.optimalAlignedConstraint)
    # Create Data partition
    data = parted.Partition(disk=disk,
                            type=parted.PARTITION_NORMAL,
                            fs=parted.FileSystem(type='ext4',
                                                 geometry=geometries['data']),
                            geometry=geometries['data'])
    disk.addPartition(partition=data,
                      constraint=device.optimalAlignedConstraint)
    # Create system.a partition
    systemA = parted.Partition(
        disk=disk,
        type=parted.PARTITION_NORMAL,
        fs=parted.FileSystem(type='ext4', geometry=geometries['systemA']),
        geometry=geometries['systemA'])
    disk.addPartition(partition=systemA,
                      constraint=device.optimalAlignedConstraint)
    # Create system.b partition
    systemB = parted.Partition(
        disk=disk,
        type=parted.PARTITION_NORMAL,
        fs=parted.FileSystem(type='ext4', geometry=geometries['systemB']),
        geometry=geometries['systemB'])
    disk.addPartition(partition=systemB,
                      constraint=device.optimalAlignedConstraint)
    return (disk)
예제 #25
0
    def partition(self, offset, size, name=None, is_bootable=False):
        """Add a new partition in the image file.

        The newly added partition will be appended to the existing partition
        table on the image as defined by the volume schema.  This is all done
        by pyparted.  Please note that libparted has no means of changing the
        partition type GUID directly (this can only be done by setting
        partition flags) so this has to be done separately after *all*
        partitions have been added. The commit() operation also clobbers the
        hybrid MBR in GPT labels so be sure to first perform partitioning and
        only afterwards attempting copy operations.

        :param offset: Offset (start position) of the partition in bytes.
        :type offset: int
        :param size: Size of partition in bytes.
        :type size: int
        :param name: Name of the partition.
        :type name: str
        :param is_bootable: Toggle if the bootable flag should be set.
        :type name: bool

        """
        # When defining geometries for our partitions we can't use the pyparted
        # parted.sizeToSectors() function as it actually rounds down the sizes
        # instead of rounding up, which means you might end up not having
        # enough sectors for a partition's contents (LP: #1661298).
        if self.device is None:
            raise TypeError('No schema for device partition')
        geometry = parted.Geometry(
            device=self.device,
            start=ceil(offset / self.sector_size),
            length=ceil(size / self.sector_size))
        partition = parted.Partition(
            disk=self.disk,
            type=parted.PARTITION_NORMAL,
            geometry=geometry)
        # Force an exact geometry constraint as otherwise libparted tries to be
        # too smart and changes our geometry itself.
        constraint = parted.Constraint(exactGeom=geometry)
        self.disk.addPartition(partition, constraint)
        # XXX: Sadly the current pyparted bindings do not export a setter for
        # the partition name (LP: #1661297).  To work-around this we need to
        # reach out to the internal PedPartition object of the partition to
        # call the set_name() function. We also follow the same guideline as
        # before - for mbr labels we just ignore the name as it's not
        # supported.
        if name and self.schema is not VolumeSchema.mbr:
            partition._Partition__partition.set_name(name)
        if is_bootable:
            partition.setFlag(parted.PARTITION_BOOT)
        # Save all the partition changes so far to disk.
        self.disk.commit()
예제 #26
0
파일: fdisk.py 프로젝트: sk8abraham/forense
def particion_pri(sdb, disk, size, tipo, fin):
    geometry1 = parted.Geometry(start=fin,
                                length=parted.sizeToSectors(
                                    size, 'MiB', sdb.sectorSize),
                                device=sdb)
    filesystem1 = parted.FileSystem(type=tipo, geometry=geometry1)
    partition1 = parted.Partition(disk=disk,
                                  type=parted.PARTITION_NORMAL,
                                  fs=filesystem1,
                                  geometry=geometry1)
    disk.addPartition(partition1, constraint=sdb.optimalAlignedConstraint)
    disk.commit()
    return partition1.geometry.end
예제 #27
0
    def getFreeSpacePartitions(self):
        """Return a list of Partition objects representing the available
           free space regions on this Disk."""
        freespace = []
        part = self.__disk.next_partition()

        while part:
            if part.type & parted.PARTITION_FREESPACE:
                freespace.append(parted.Partition(disk=self, PedPartition=part))

            part = self.__disk.next_partition(part)

        return freespace
예제 #28
0
def revertRepartition(device, partition, deltastart, deltaend, unit='MiB'):
    dev = parted.getDevice(device)
    disk = parted.newDisk(dev)
    targetPartition = disk.getPartitionByPath(device + partition)
    geometry = targetPartition.geometry
    geometry.start += parted.sizeToSectors(deltastart, unit, dev.sectorSize)
    geometry.end += parted.sizeToSectors(deltaend, unit, dev.sectorSize)
    disk.deletePartition(targetPartition)
    partition = parted.Partition(disk=disk,
                                 type=parted.PARTITION_NORMAL,
                                 geometry=geometry)
    disk.addPartition(partition=partition,
                      constraint=dev.optimalAlignedConstraint)
    disk.commit()
예제 #29
0
def create_partition(disk: parted.Disk, start, end, fscode, fstype=None):
    log.info(f'Creating partition ({start}-{end}) type {fscode}')
    geometry = parted.Geometry(device=disk.device, start=start, end=end)
    new_partition = parted.Partition(disk=disk,
                                     type=parted.PARTITION_NORMAL,
                                     fs=parted.FileSystem(type=fscode,
                                                          geometry=geometry),
                                     geometry=geometry)
    if not disk.addPartition(partition=new_partition,
                             constraint=parted.Constraint(exactGeom=geometry)):
        die(f'Creating partition failed')
    disk.commit()
    if fstype:
        sh(f'mkfs.{fstype}', new_partition.path)
예제 #30
0
    def bolumOlustur(self, alan, bolumTur):

        if bolumTur == parted.PARTITION_NORMAL or bolumTur == parted.PARTITION_EXTENDED:
            for bosBolum in self.disk.getFreeSpacePartitions():
                _bolum = self.bolumBilgi(bosBolum, "GB")
                if _bolum["tur"] == parted.PARTITION_FREESPACE:
                    maksBoyut = float(_bolum["boyut"])
        elif bolumTur == bolumTur == parted.PARTITION_LOGICAL:
            for bosBolum in self.disk.getFreeSpacePartitions():
                _bolum = self.bolumBilgi(bosBolum, "GB")
                if _bolum["tur"] == 5:
                    maksBoyut = float(_bolum["boyut"])

        alignment = self.aygit.optimalAlignedConstraint
        constraint = self.aygit.getConstraint()
        data = {
            'start': constraint.startAlign.alignUp(alan, alan.start),
            'end': constraint.endAlign.alignDown(alan, alan.end),
        }

        boyut, ok = QInputDialog().getDouble(self,
                                             'Bölüm oluştur',
                                             'GB cinsinden boyut:',
                                             min=0.001,
                                             value=1,
                                             max=maksBoyut,
                                             decimals=3)

        if ok:
            data["end"] = int(data["start"]) + int(
                parted.sizeToSectors(float(boyut), "GiB",
                                     self.aygit.sectorSize))
            try:
                geometry = parted.Geometry(device=self.aygit,
                                           start=int(data["start"]),
                                           end=int(data["end"]))
                partition = parted.Partition(
                    disk=self.disk,
                    type=bolumTur,
                    geometry=geometry,
                )

                self.disk.addPartition(partition=partition,
                                       constraint=constraint)
            except (parted.PartitionException, parted.GeometryException,
                    parted.CreateException) as e:
                # GeometryException accounts for incorrect start/end values (e.g. start < end),
                # CreateException is raised e.g. when the partition doesn't fit on the disk.
                # PartedException is a generic error (e.g. start/end values out of range)
                raise RuntimeError(e.message)