Exemple #1
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
Exemple #2
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
    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)
Exemple #4
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
Exemple #5
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
Exemple #6
0
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
Exemple #7
0
 def intersect(self, b):
     """Return a new constraint that is the intersection of self and the
        provided constraint b.  The returned constraint will therefore be
        more restrictive than either input as it will have to satisfy
        both."""
     return parted.Constraint(
         PedConstraint=self.__constraint.intersect(b.getPedConstraint()))
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
Exemple #9
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)
Exemple #10
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)
Exemple #11
0
    def restore_from_file(self, disk):
        """ """
        with open(self.file_path, 'r') as f:
            layout = list()
            partitions = cPickle.load(f)
            for p in partitions:
                geometry = parted.geometry.Geometry(device=disk.device,
                                                    start=p.start,
                                                    length=p.length,
                                                    end=p.end)

                p_fs = None
                if p.fs is not None:
                    p_fs = parted.filesystem.FileSystem(type = p.fs,
                                                        geometry = geometry)

                partition = parted.partition.Partition(disk=disk,
                                                       type=p.type,
                                                       geometry=geometry,
                                                       fs=p_fs)

                if p.flags != "swap" and p.flags != '':
                    partition.setFlag(partition_flag_get_by_name(p.flags))
                layout.append(partition)

            disk.deleteAllPartitions()
            constraint = parted.Constraint(device=disk.device)
            for p in layout:
                disk.addPartition(p, constraint)

            disk.commitToDevice()
            disk.commitToOS()
            self._wait_devices(disk)
Exemple #12
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))
Exemple #13
0
    def partition(device):
        dev = parted.Device(path=device)
        disk = parted.freshDisk(dev, 'msdos')
        constraint = parted.Constraint(device=dev)

        new_geom = parted.Geometry(device=dev,
                                   start=1,
                                   end=(constraint.maxSize - 1))
        filesystem = parted.FileSystem(type="ext2", geometry=new_geom)
        partition = parted.Partition(disk=disk,
                                     fs=filesystem,
                                     type=parted.PARTITION_NORMAL,
                                     geometry=new_geom)
        constraint = parted.Constraint(exactGeom=new_geom)
        partition.setFlag(parted.PARTITION_BOOT)
        disk.addPartition(partition=partition, constraint=constraint)

        disk.commit()
Exemple #14
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)
Exemple #15
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)
Exemple #16
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
Exemple #17
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)
Exemple #18
0
def resize_partition(partition: parted.Partition, end):
    log.info(f'Resizing partition {partition.number} to end {end}')
    start = partition.geometry.start
    disk = partition.disk
    new_geometry = parted.Geometry(device=disk.device, start=start, end=end)
    if not disk.maximizePartition(
            partition=partition,
            constraint=parted.Constraint(exactGeom=new_geometry)):
        die(f'Partition {partition.path} resize failed')
    disk.commit()
    # Not on the path
    sh('/usr/sbin/resize2fs', partition.path)
Exemple #19
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()
Exemple #20
0
    def restore_from_file(self, disk, expand=False):
        """ """
        with open(self.file_path, 'r') as f:
            layout = list()
            partitions = cPickle.load(f)
            for p in partitions:
                geometry = parted.geometry.Geometry(device=disk.device,
                                                    start=p.start,
                                                    length=p.length,
                                                    end=p.end)

                p_fs = None
                if p.fs is not None:
                    p_fs = parted.filesystem.FileSystem(type=p.fs,
                                                        geometry=geometry)

                partition = parted.partition.Partition(disk=disk,
                                                       type=p.type,
                                                       geometry=geometry,
                                                       fs=p_fs)

                if p.flags != "swap" and p.flags != '':
                    partition.setFlag(partition_flag_get_by_name(p.flags))
                layout.append(partition)

            disk.deleteAllPartitions()
            constraint = parted.Constraint(device=disk.device)
            last_partition = len(layout)
            for n, p in enumerate(layout, 1):
                disk.addPartition(p, constraint)

                # Expand last partition
                if last_partition == n:
                    if expand:
                        if p.type == parted.PARTITION_NORMAL:
                            max_geometry = disk.calculateMaxPartitionGeometry(
                                p, constraint)
                            new_geometry = parted.Geometry(
                                geometry.device,
                                start=geometry.start,
                                end=max_geometry.end)

                            result = disk.setPartitionGeometry(
                                p, constraint, new_geometry.start,
                                new_geometry.end)
                            if not result:
                                raise ExpandingPartitionError("Extending" + \
                                                          "partition failed.")

            disk.commitToDevice()
            disk.commitToOS()
            self._wait_devices(disk)
Exemple #21
0
    def setUp(self):
        RequiresDevice.setUp(self)
        align1 = parted.Alignment(offset=10, grainSize=5)
        align2 = parted.Alignment(offset=10, grainSize=5)
        geom1 = parted.Geometry(device=self.device, start=0, length=50)
        geom2 = parted.Geometry(device=self.device, start=25, length=50)

        self.c = parted.Constraint(startAlign=align1,
                                   endAlign=align2,
                                   startRange=geom1,
                                   endRange=geom2,
                                   minSize=10,
                                   maxSize=100)
Exemple #22
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)
Exemple #23
0
    def _computeResize(self, partition):
        # compute new size for partition
        currentGeom = partition.geometry
        currentDev = currentGeom.device
        newLen = long(self.targetSize * 1024 * 1024) / currentDev.sectorSize
        newGeometry = parted.Geometry(device=currentDev,
                                      start=currentGeom.start,
                                      length=newLen)
        # and align the end sector
        newGeometry.end = self.disk.format.endAlignment.alignDown(
            newGeometry, newGeometry.end)
        constraint = parted.Constraint(exactGeom=newGeometry)

        return (constraint, newGeometry)
Exemple #24
0
 def createpartitions(self):
     ''' Partition the LVM volume into persistent and swap partitions
         using the parted module.
     '''
     dev = parted.Device(path=self.lvpath)
     dev.removeFromCache()
     disk = parted.freshDisk(dev, 'msdos')
     constraint = parted.Constraint(device=dev)
     persist_size = int(0.75 * constraint.maxSize);
     self.createpartition(device=dev, disk=disk, start=1,
                      end=(persist_size - 1) , type="ext4")
     self.createpartition(device=dev, disk=disk, start=persist_size,
                      end=(constraint.maxSize - 1) , type="linux-swap(v1)")
     disk.commit()
    def addPartition(self, *args, **kwargs):
        partition = kwargs.get("partition", None)
        if not partition:
            partition = args[0]
        geometry = partition.geometry
        constraint = kwargs.get("constraint", None)
        if not constraint and len(args) > 1:
            constraint = args[1]
        elif not constraint:
            constraint = parted.Constraint(exactGeom=geometry)

        new_partition = parted.Partition(disk=self.partedDisk,
                                         type=partition.type,
                                         geometry=geometry)
        self.partedDisk.addPartition(partition=new_partition,
                                     constraint=constraint)
Exemple #26
0
    def createPartitions(self, start, end):
        """ Cree des partition  fat32 et ext4"""
        print("\nDisque =", self.disque, " , START = ", start, ", END = ", end)
        ptype = _ped.PARTITION_NORMAL

        geometry = parted.Geometry(device=self.dev, start=start, end=end)
        partition = parted.Partition(disk=self.partitions,
                                     type=ptype,
                                     geometry=geometry)
        constraint = parted.Constraint(exactGeom=geometry)

        if self.partitions.addPartition(partition=partition,
                                        constraint=constraint):
            self.partitions.commit()
        else:
            print("Error disk.addPartition in " + self.disque)
        time.sleep(1)
Exemple #27
0
    def runTest(self):
        align1 = parted.Alignment(offset=10, grainSize=5)
        align2 = parted.Alignment(offset=10, grainSize=5)
        geom1 = parted.Geometry(device=self.device, start=0, length=50)
        geom2 = parted.Geometry(device=self.device, start=0, length=100)

        # Check that not passing enough args to parted.Constraint.__init__
        # is caught.
        self.assertRaises(parted.ConstraintException, parted.Constraint)
        self.assertRaises(parted.ConstraintException,
                          parted.Constraint,
                          startAlign=align1,
                          endAlign=align2)

        # And then the correct ways of creating a _ped.Constraint.
        c = parted.Constraint(minGeom=geom1, maxGeom=geom2)
        self.assertIsInstance(c, parted.Constraint)

        c = parted.Constraint(minGeom=geom1)
        self.assertIsInstance(c, parted.Constraint)

        c = parted.Constraint(maxGeom=geom2)
        self.assertIsInstance(c, parted.Constraint)

        c = parted.Constraint(exactGeom=geom1)
        self.assertIsInstance(c, parted.Constraint)

        c = parted.Constraint(device=self.device)
        self.assertIsInstance(c, parted.Constraint)

        c = parted.Constraint(startAlign=align1,
                              endAlign=align2,
                              startRange=geom1,
                              endRange=geom2,
                              minSize=10,
                              maxSize=100)
        self.assertIsInstance(c, parted.Constraint)

        # Use a _ped.Constraint as the initializer
        pc = _ped.Constraint(align1.getPedAlignment(),
                             align2.getPedAlignment(), geom1.getPedGeometry(),
                             geom2.getPedGeometry(), 10, 100)
        c = parted.Constraint(PedConstraint=pc)
        self.assertIsInstance(c, parted.Constraint)
        self.assertEqual(c.getPedConstraint(), pc)
Exemple #28
0
def __make_efi__(device, start=config["EFI"]["START"],
                 end=config["EFI"]["END"]):
    """Make EFI partition"""
    disk = parted.Disk(device)
    start_geo = parted.geometry.Geometry(device=device,
                                         start=parted.sizeToSectors(start,
                                                                    "MB",
                                                                    device.sectorSize),
                                         end=parted.sizeToSectors(start + 10,
                                                                  "MB",
                                                                  device.sectorSize))
    end_geo = parted.geometry.Geometry(device=device,
                                       start=parted.sizeToSectors(common.real_number(end - 20),
                                                                  "MB",
                                                                  device.sectorSize),
                                       end=parted.sizeToSectors(end + 10,
                                                                "MB",
                                                                device.sectorSize))
    min_size = parted.sizeToSectors(common.real_number((end - start) - 25), "MB",
                                    device.sectorSize)
    max_size = parted.sizeToSectors(common.real_number((end - start) + 20), "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=start,
                                        length=parted.sizeToSectors(end - start,
                                                                    "MB",
                                                                    device.sectorSize),
                                        device=device)
    new_part = parted.Partition(disk=disk,
                                type=parted.PARTITION_NORMAL,
                                geometry=geometry)
    new_part.setFlag(parted.PARTITION_BOOT)
    disk.addPartition(partition=new_part, constraint=const)
    disk.commit()
    time.sleep(0.1)
    __mkfs_fat__(new_part.path)
    return new_part.path
def resizeToMaxExt4PartitionOptimizedForMicroSDHC(parted_disk,
                                                  desired_size_bytes=None):
    ## get largest free region
    # parted_largestfreeregion_geometry = max(parted_disk.getFreeSpaceRegions(),key=lambda x: x.getLength())

    ## define optimum settings for micrSDHC card (first 4MiB contains only MBR and everything aligned to 4MiB)
    optAlignmentForRasperry = parted_disk.device.optimumAlignment
    optAlignmentForRasperry.offset = int(4 * 1024**2 /
                                         parted_disk.device.sectorSize)  #8192
    optAlignmentForRasperry.grainSize = int(
        4 * 1024**2 / parted_disk.device.sectorSize)  #8192
    assert (optAlignmentForRasperry.offset == 8192)
    assert (optAlignmentForRasperry.grainSize == 8192)

    lastpart_start = parted_disk.partitions[-1].geometry.start

    geom = parted.Geometry(device=parted_disk.device,
                           start=lastpart_start,
                           length=parted_disk.device.length - lastpart_start)
    constraint = parted.Constraint(exactGeom=geom)
    parted_disk.maximizePartition(partition=parted_disk.partitions[-1],
                                  constraint=constraint)
Exemple #30
0
    def get_size_constraint(self, disk, new_len):
        """ Gratefully borrowed from blivet, Copyright (C) 2009 Red Hat
            https://github.com/rhinstaller/blivet/
        """
        current_geom = self.part.geometry
        current_dev = current_geom.device
        new_geometry = parted.Geometry(device=current_dev,
                                       start=current_geom.start,
                                       length=new_len)

        # and align the end sector
        alignment = disk.partitionAlignment
        if new_geometry.length < current_geom.length:
            align = alignment.alignUp
            align_geom = current_geom  # we can align up into the old geometry
        else:
            align = alignment.alignDown
            align_geom = new_geometry

        new_geometry.end = align(align_geom, new_geometry.end)
        constraint = parted.Constraint(exactGeom=new_geometry)
        return (constraint, new_geometry)