dcantrell / pyparted

Python bindings for GNU parted (libparted)
GNU General Public License v2.0
85 stars 42 forks source link

Unrecognized disk label for disk that exists and is discoverable #83

Closed goigle closed 2 years ago

goigle commented 2 years ago

I am trying to create a partition on /dev/sda, but for some reason pyparted is having issues. At first I was directly creating the device based on the path, but that gave the 'unrecognized disk label' error so I tried enumerating the disks and checking the path but I had the same results. The disk is a 120GB SATA SSD on /dev/sda. It works fine and GParted isn't having issues.

libparted-dev is on version 3.3-4ubuntu0.20.04.1. I'm on Ubuntu 20.04.3 LTS with Python 3.8.10.

Offending code (args.device is '/dev/sda'):

    devs = parted.getAllDevices()
    dev = None
    for d  in devs:
        print(f'Discovered {d.path}')
        if d.path == args.device:
            dev = d

    if dev is None:
        print(f'Could not find device {args.device}')

    capacity = dev.getSize("GB")
    if capacity > 200:
        ans = input(f'{dev.path} is a {capacity}GB drive, are you sure you have the right device? (y/n): ')
        if ans.lower() != 'y':
            return
    print(f'Clearing partitions on {dev.path}')
    dev.clobber()
    # error is on this line
    disk = parted.newDisk(dev)

Console Output:

Discovered /dev/sda
Discovered /dev/nvme0n1
Discovered /dev/nvme1n1
Clearing partitions on /dev/sda
Traceback (most recent call last):
  File "provision.py", line 107, in <module>
    main()
  File "provision.py", line 58, in main
    disk = parted.newDisk(dev)
  File "/home/j/projects/analysis_python/hw-provision/env/lib/python3.8/site-packages/parted/decorators.py", line 42, in new
    ret = fn(*args, **kwds)
  File "/home/j/projects/analysis_python/hw-provision/env/lib/python3.8/site-packages/parted/__init__.py", line 485, in newDisk
    peddisk = disk_new(device.getPedDevice())
_ped.DiskException: /dev/sda: unrecognised disk label
dcantrell commented 2 years ago

Since you are using clobber() on the device, it is destroying the disk label. newDisk() can't work without a disk label. If you want to create a new Disk object with a specific lable, you need to use freshDisk:

dev.clobber()
disk = parted.freshDisk(dev, TYPE)

Where TYPE is a value from the parted.diskType dict. Such as parted.diskType["gpt"]:

disk = parted.freshDisk(dev, parted.diskType["gpt"])

Which will create a new Disk object for dev that has a GPT disk label.

dcantrell commented 2 years ago

Note that you will need to use disk.commitToDevice() to write the label to the disk, otherwise it's just all in memory.