pyparted icon indicating copy to clipboard operation
pyparted copied to clipboard

Can't set partition location, probably due to constraint

Open ukoda opened this issue 6 months ago • 1 comments

I'm trying to create a backup and restore utility for Raspberry Pi systems. I am using the version of pyparted from pip. When I try restore the partitions to a new disk the partition alignment is not as I specify which appears to be due to the constraint setting and leaves the last partition grossly undersized.

The simplest example of this issue can be seen when trying to create a single partition that would be the boot partition on a RPi system. Using a NVMe drive on a USB adaptor I can do this fine manually with fdisk:

root@san:/backup/san# fdisk -l /dev/sda
Disk /dev/sda: 119.24 GiB, 128035676160 bytes, 250069680 sectors
Disk model: Tech            
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disklabel type: dos
Disk identifier: 0x957e6c15

Device     Boot Start     End Sectors  Size Id Type
/dev/sda1        8192 1056767 1048576  512M  c W95 FAT32 (LBA)

This is the test code I wrote, based on the example code in this repo, to show the issue:

import parted

device = parted.getDevice('/dev/sda')
device.clobber()
disk = parted.freshDisk(device, "msdos")
geometry = parted.Geometry(
    device=device,
    start=8192,
    end=1056767
)
filesystem = parted.FileSystem('fat32', geometry=geometry)
partition = parted.Partition(
    disk=disk,
    type=parted.PARTITION_NORMAL,
    fs=filesystem,
    geometry=geometry
)
disk.addPartition(
    partition=partition, constraint=device.optimalAlignedConstraint
)
disk.commit()

However it results in:

Disk /dev/sda: 119.24 GiB, 128035676160 bytes, 250069680 sectors
Disk model: Tech            
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disklabel type: dos
Disk identifier: 0x5f47ce36

Device     Boot  Start     End Sectors  Size Id Type
/dev/sda1       522240 1044479  522240  255M  b W95 FAT32

I can get closer if I change the constraint to:

    partition=partition, constraint=device.minimalAlignedConstraint

to get:

Device     Boot Start     End Sectors  Size Id Type
/dev/sda1        8160 1056719 1048560  512M  b W95 FAT32

But this still adds up to a problem over 3 partitions.

I have tried several other options but can't get it to honor the actual values I want.

Also of note is the partition Id is being set to 'b', not 'c'. Not sure if this will cause problems with the restored system yet.

ukoda avatar Jun 23 '25 20:06 ukoda

For now I am working around the problem by using sfdisk from a subprocess call. Not ideal but it does give me the partitions I need to move forward with my utility.

ukoda avatar Jun 27 '25 23:06 ukoda