chamesle

chamesle.org: the site of Chamesle, a small Linux distribution
git clone https://github.com/tortr-rs/chamesle
Log | Files | Refs | README

partitioning.py (34413B)


      1 #!/usr/bin/python3
      2 # coding: utf-8
      3 #
      4 import json
      5 import os
      6 import re
      7 import subprocess
      8 from collections import defaultdict
      9 import gi
     10 gi.require_version('Gtk', '3.0')
     11 from gi.repository import Gtk, Gdk, GLib
     12 import parted
     13 import gettext
     14 import time
     15 from dialogs import QuestionDialog
     16 
     17 gettext.install("live-installer", "/usr/share/locale")
     18 
     19 # Used as a decorator to run things in the main loop, from another thread
     20 def idle(func):
     21     def wrapper(*args, **kwargs):
     22         GLib.idle_add(func, *args, **kwargs)
     23     return wrapper
     24 
     25 def shell_exec(command):
     26     return subprocess.Popen(command, shell=True, encoding='utf-8', errors='ignore', stdout=subprocess.PIPE)
     27 
     28 def getoutput(command):
     29     return shell_exec(command).stdout.read().strip()
     30 
     31 (IDX_PART_PATH,
     32  IDX_PART_TYPE,
     33  IDX_PART_DESCRIPTION,
     34  IDX_PART_FORMAT_AS,
     35  IDX_PART_MOUNT_AS,
     36  IDX_PART_SIZE,
     37  IDX_PART_FREE_SPACE,
     38  IDX_PART_OBJECT,
     39  IDX_PART_DISK) = range(9)
     40 
     41 def is_efi_supported():
     42     # Are we running under with efi ?
     43     os.system("modprobe efivars >/dev/null 2>&1")
     44     return os.path.exists("/proc/efi") or os.path.exists("/sys/firmware/efi")
     45 
     46 def path_exists(*args):
     47     return os.path.exists(os.path.join(*args))
     48 
     49 TMP_MOUNTPOINT = '/tmp/live-installer/tmpmount'
     50 RESOURCE_DIR = '/usr/share/live-installer/'
     51 
     52 EFI_MOUNT_POINT = '/boot/efi'
     53 SWAP_MOUNT_POINT = 'swap'
     54 
     55 def _active_swaps():
     56     try:
     57         with open('/proc/swaps', 'r') as f:
     58             return [line.split()[0] for line in f.readlines()[1:] if line.split()]
     59     except OSError:
     60         return []
     61 
     62 def get_mounted_target_partitions(partitions):
     63     mounted = []
     64     swaps = _active_swaps()
     65     for p in partitions:
     66         if not p.format_as:
     67             continue
     68         target = subprocess.run(['findmnt', '-n', '-o', 'TARGET', '--source', p.path],
     69                                 capture_output=True, text=True).stdout.strip()
     70         if (target and target != TMP_MOUNTPOINT) or p.path in swaps:
     71             mounted.append(p.path)
     72     return mounted
     73 
     74 def get_mounted_partitions_on_target_disk(disk_path):
     75     # Return mounted device paths (including active swap) whose source
     76     # begins with disk_path.
     77     paths = []
     78     output = subprocess.run(['findmnt', '-nro', 'SOURCE,TARGET'],
     79                             capture_output=True, text=True).stdout
     80     for line in output.splitlines():
     81         parts = line.split(None, 1)
     82         if len(parts) != 2:
     83             continue
     84         source, target = parts
     85         if source.startswith(disk_path) and target != TMP_MOUNTPOINT:
     86             paths.append(source)
     87     for swap in _active_swaps():
     88         if swap.startswith(disk_path) and swap not in paths:
     89             paths.append(swap)
     90     return paths
     91 
     92 def unmount_partitions(paths):
     93     # Try to release each device path (umount, or swapoff for active swap).
     94     # Returns a list of error strings.
     95     failed = []
     96     swaps = _active_swaps()
     97     for path in paths:
     98         cmd = ['swapoff', path] if path in swaps else ['umount', path]
     99         result = subprocess.run(cmd, capture_output=True, text=True)
    100         if result.returncode != 0:
    101             err = (result.stderr or result.stdout).strip() or _("unknown error")
    102             failed.append(err)
    103     return failed
    104 
    105 with open(RESOURCE_DIR + 'disk-partitions.html') as f:
    106     DISK_TEMPLATE = f.read()
    107     # cut out the single partition (skeleton) block
    108     PARTITION_TEMPLATE = re.search(r'CUT_HERE([\s\S]+?)CUT_HERE', DISK_TEMPLATE, re.MULTILINE).group(1)
    109     # delete the skeleton from original
    110     DISK_TEMPLATE = DISK_TEMPLATE.replace(PARTITION_TEMPLATE, '')
    111     # duplicate all { or } in original CSS so they don't get interpreted as part of string formatting
    112     DISK_TEMPLATE = re.sub(r'<style>[\s\S]+?</style>', lambda match: match.group().replace('{', '{{').replace('}', '}}'), DISK_TEMPLATE)
    113 
    114 
    115 def get_live_device():
    116     for mount_point in ("/live-medium", "/cdrom", "/run/live/medium"):
    117         source = subprocess.getoutput("findmnt -n -o SOURCE %s" % mount_point).split('\n')[0].strip()
    118         if source.startswith("/dev/"):
    119             parent = subprocess.getoutput("lsblk -dn -o PKNAME %s" % source).strip()
    120             return "/dev/%s" % parent if parent else source
    121     return None
    122 
    123 def get_disks():
    124     disks = []
    125     live_device = get_live_device()
    126     print("Live device: %s" % live_device)
    127     lsblk = shell_exec('LC_ALL=en_US.UTF-8 lsblk -rindo TYPE,NAME,RM,SIZE,MODEL | sort -k3,2')
    128     for line in lsblk.stdout:
    129         try:
    130             # Extract info from blkid output
    131             elements = line.strip().split(" ", 4)
    132             if len(elements) < 4:
    133                 print("Can't parse blkid output: %s" % elements)
    134                 continue
    135             device_type, device, removable, size = elements[0], elements[1], elements[2], elements[3]
    136             if len(elements) < 5:
    137                 # No model info in blkid output
    138                 model = elements[1]
    139             else:
    140                 model = elements[4]
    141 
    142             # Exclude non-disk devices (/dev/loop0 for instance)
    143             if device_type != "disk":
    144                 print("Excluding %s (not disk type)" % device)
    145                 continue
    146             device = "/dev/" + device
    147             # Exclude the live device
    148             if device == live_device:
    149                 print("Excluding %s (detected as the live device)" % device)
    150                 continue
    151             # Exclude unwanted devices
    152             if device in ['/dev/sr0', '/dev/sr1', '/dev/cdrom', '/dev/dvd', '/dev/fd0']:
    153                 print("Excluding %s" % device)
    154                 continue
    155             # Exclude hardware eMMC hardware devices
    156             if re.match("/dev/mmcblk[0-9]+boot[0-9]+$", device):
    157                 print("Excluding %s (eMMC hardware device)" % device)
    158                 continue
    159             if re.match("/dev/mmcblk[0-9]+rpmb$", device):
    160                 print("Excluding %s (eMMC hardware device)" % device)
    161                 continue
    162             # compressed swap in RAM (chamesle has it on), not a disk
    163             if re.match("/dev/zram[0-9]+$", device):
    164                 print("Excluding %s (swap in RAM)" % device)
    165                 continue
    166 
    167             # Convert size to manufacturer's size (i.e. GB, not GiB)
    168             unit_index = 'BKMGTPEZY'.index(size.upper()[-1])
    169             l10n_unit = [_('B'), _('kB'), _('MB'), _('GB'), _('TB'), 'PB', 'EB', 'ZB', 'YB'][unit_index]
    170             size = "%s %s" % (str(int(float(size[:-1]) * (1024/1000)**unit_index)), l10n_unit)
    171             model = model.replace("\\x20", " ")
    172             description = '{} ({})'.format(model.strip(), size)
    173             if int(removable):
    174                 description = _('Removable:') + ' ' + description
    175             disks.append((device, description))
    176         except Exception as detail:
    177             print("Could not parse blkid output: %s (%s)" % (line, detail))
    178     return disks
    179 
    180 def build_partitions(_installer):
    181     global installer
    182     installer = _installer
    183     installer.window.get_window().set_cursor(Gdk.Cursor.new(Gdk.CursorType.WATCH))  # "busy" cursor
    184     installer.window.set_sensitive(False)
    185     print("Starting PartitionSetup()")
    186     partition_setup = PartitionSetup()
    187     print("Finished PartitionSetup()")
    188     if partition_setup.disks:
    189         installer._selected_disk = partition_setup.disks[0][0]
    190         print("Loading HTML string")
    191         installer.partitions_browser.load_html(partition_setup.get_html(installer._selected_disk), 'file:///')
    192     print("Showing the partition screen")
    193     installer.builder.get_object("scrolled_partitions").show_all()
    194     installer.builder.get_object("treeview_disks").set_model(partition_setup)
    195     installer.builder.get_object("treeview_disks").expand_all()
    196     installer.window.get_window().set_cursor(None)
    197     installer.window.set_sensitive(True)
    198 
    199 def selection_changed(selection):
    200     model, iter = installer.builder.get_object("treeview_disks").get_selection().get_selected()
    201     if not iter: return
    202     row = model[iter]
    203     partition = row[IDX_PART_OBJECT]
    204     if (partition is None or partition.partition.type == parted.PARTITION_EXTENDED or partition.partition.number == -1):
    205         installer.builder.get_object("button_edit").set_sensitive(False)
    206     else:
    207         installer.builder.get_object("button_edit").set_sensitive(True)
    208     update_html_preview(selection)
    209 
    210 def update_html_preview(selection):
    211     model, row = selection.get_selected()
    212     try: disk = model[row][IDX_PART_DISK]
    213     except (TypeError, IndexError): return  # no disk is selected or no disk available
    214     if disk != installer._selected_disk:
    215         installer._selected_disk = disk
    216         installer.partitions_browser.load_html(model.get_html(disk), 'file:///')
    217 
    218 def edit_partition_dialog(*args):
    219     ''' assign the partition ... '''
    220     model, iter = installer.builder.get_object("treeview_disks").get_selection().get_selected()
    221     if not iter: return
    222     row = model[iter]
    223     partition = row[IDX_PART_OBJECT]
    224     if (partition.partition.type != parted.PARTITION_EXTENDED and
    225         partition.partition.number != -1):
    226         dlg = PartitionDialog(row[IDX_PART_PATH],
    227                               row[IDX_PART_MOUNT_AS],
    228                               row[IDX_PART_FORMAT_AS],
    229                               row[IDX_PART_TYPE])
    230         response_is_ok, mount_as, format_as = dlg.show()
    231         if response_is_ok:
    232             assign_mount_point(partition, mount_as, format_as)
    233 
    234 def assign_mount_point(partition, mount_point, filesystem):
    235     # Assign it in the treeview
    236     model = installer.builder.get_object("treeview_disks").get_model()
    237     for disk in model:
    238         for part in disk.iterchildren():
    239             if partition == part[IDX_PART_OBJECT]:
    240                 part[IDX_PART_MOUNT_AS] = mount_point
    241                 part[IDX_PART_FORMAT_AS] = filesystem
    242             elif mount_point == part[IDX_PART_MOUNT_AS]:
    243                 part[IDX_PART_MOUNT_AS] = ""
    244                 part[IDX_PART_FORMAT_AS] = ""
    245     # Assign it in our setup
    246     for part in installer.setup.partitions:
    247         if part == partition:
    248             partition.mount_as, partition.format_as = mount_point, filesystem
    249         elif part.mount_as == mount_point:
    250             part.mount_as, part.format_as = '', ''
    251     installer.setup.print_setup()
    252 
    253 def partitions_popup_menu(widget, event):
    254     if event.button != 3: return
    255     model, iter = installer.builder.get_object("treeview_disks").get_selection().get_selected()
    256     if not iter: return
    257     partition = model.get_value(iter, IDX_PART_OBJECT)
    258     if not partition: return
    259     partition_type = model.get_value(iter, IDX_PART_TYPE)
    260     if (partition.partition.type == parted.PARTITION_EXTENDED or
    261         partition.partition.number == -1):
    262         return
    263     menu = Gtk.Menu()
    264     menuItem = Gtk.MenuItem(_("Edit"))
    265     menuItem.connect("activate", edit_partition_dialog, None, None)
    266     menu.append(menuItem)
    267 
    268     if "swap" not in partition_type:
    269         menuItem = Gtk.SeparatorMenuItem()
    270         menu.append(menuItem)
    271         menuItem = Gtk.MenuItem(_("Assign to /"))
    272         menuItem.connect("activate", lambda w: assign_mount_point(partition, '/', 'btrfs'))
    273         menu.append(menuItem)
    274         menuItem = Gtk.MenuItem(_("Assign to /home"))
    275         menuItem.connect("activate", lambda w: assign_mount_point(partition, '/home', ''))
    276         menu.append(menuItem)
    277         if installer.setup.gptonefi:
    278             menuItem = Gtk.SeparatorMenuItem()
    279             menu.append(menuItem)
    280             menuItem = Gtk.MenuItem(_("Assign to /boot/efi"))
    281             menuItem.connect("activate", lambda w: assign_mount_point(partition, EFI_MOUNT_POINT, ''))
    282             menu.append(menuItem)
    283     menu.show_all()
    284     menu.popup(None, None, None, None, 0, event.time)
    285 
    286 def manually_edit_partitions(widget):
    287     """ Edit only known disks in gparted, selected one first """
    288     model, iter = installer.builder.get_object("treeview_disks").get_selection().get_selected()
    289     preferred = model[iter][-1] if iter else ''  # prefer disk currently selected and show it first in gparted
    290     disks = ' '.join(sorted((disk for disk,desc in model.disks), key=lambda disk: disk != preferred))
    291     os.system('umount ' + disks)  # umount disks (if possible) so gparted works out-of-the-box
    292     os.system('gparted {} &'.format(disks))
    293 
    294 def build_grub_partitions():
    295     grub_model = Gtk.ListStore(str)
    296     try: preferred = [p.partition.disk.device.path for p in installer.setup.partitions if p.mount_as == '/'][0]
    297     except IndexError: preferred = ''
    298     devices = sorted(list(d[0] for d in installer.setup.partition_setup.disks) +
    299                      list([_f for _f in (p.name for p in installer.setup.partitions) if _f]),
    300                      key=lambda path: path != None and path != preferred)
    301     for p in devices: grub_model.append([p])
    302     installer.builder.get_object("combobox_grub").set_model(grub_model)
    303     installer.builder.get_object("combobox_grub").set_active(0)
    304 
    305 class PartitionSetup(Gtk.TreeStore):
    306     def __init__(self):
    307         super(PartitionSetup, self).__init__(str,  # path
    308                                              str,  # type (fs)
    309                                              str,  # description (OS)
    310                                              str,  # format to
    311                                              str,  # mount point
    312                                              str,  # size
    313                                              str,  # free space
    314                                              object,  # partition object
    315                                              str)  # disk device path
    316         installer.setup.partitions = []
    317         installer.setup.partition_setup = self
    318         self.html_disks, self.html_chunks = {}, defaultdict(list)
    319 
    320         os.system('mkdir -p ' + TMP_MOUNTPOINT)
    321         installer.setup.gptonefi = is_efi_supported()
    322         self.disks = get_disks()
    323         print('Disks: ', self.disks)
    324         already_done_full_disk_format = False
    325         for disk_path, disk_description in self.disks:
    326             # Get the device from parted
    327             try:
    328                 print("    Analyzing path='%s' description='%s'" % (disk_path, disk_description))
    329                 disk_device = parted.getDevice(disk_path)
    330                 print("      - Found the device...")
    331             except Exception as detail:
    332                 print("      - Found an issue while looking for the device: %s" % detail)
    333                 continue
    334             # Get the partitions from parted
    335             try:
    336                 disk = parted.Disk(disk_device)
    337                 print("      - Found the disk...")
    338             except Exception as detail:
    339                 print("      - Found an issue while looking for the disk: %s" % detail)
    340                 # erasing a disk or installing next to windows: the user said yes to that already, and the
    341                 # installer partitions the disk itself. the question is only for doing it by hand
    342                 if installer.setup.automated or installer.setup.alongside:
    343                     continue
    344                 dialog = QuestionDialog(_("Installation Tool"),
    345                                         _("No partition table was found on the hard drive: %s. Do you want the installer to create a set of partitions for you? Note: This will ERASE ALL DATA present on this disk.") % disk_description,
    346                                         None, installer.window)
    347                 if not dialog: continue  # the user said No, skip this disk
    348                 try:
    349                     installer.window.get_window().set_cursor(Gdk.Cursor.new(Gdk.CursorType.WATCH))
    350                     print("Performing a full disk format")
    351                     if not already_done_full_disk_format:
    352                         assign_mount_format = full_disk_format(disk_device)
    353                         already_done_full_disk_format = True
    354                     else:
    355                         full_disk_format(disk_device) # Format but don't assign mount points
    356                     installer.window.get_window().set_cursor(None)
    357                     print("Done full disk format")
    358                     disk = parted.Disk(disk_device)
    359                     print("Got disk!")
    360                 except Exception as second_exception:
    361                     installer.window.get_window().set_cursor(None)
    362                     print("      - Found another issue while looking for the disk: %s" % detail)
    363                     continue # Something is wrong with this disk, skip it
    364 
    365             disk_iter = self.append(None, (disk_description, '', '', '', '', '', '', None, disk_path))
    366             print("      - Looking at partitions...")
    367             free_space_partition = disk.getFreeSpacePartitions()
    368             print("           -> %d free space partitions" % len(free_space_partition))
    369             primary_partitions = disk.getPrimaryPartitions()
    370             print("           -> %d primary partitions" % len(primary_partitions))
    371             logical_partitions = disk.getLogicalPartitions()
    372             print("           -> %d logical partitions" % len(logical_partitions))
    373             raid_partitions = disk.getRaidPartitions()
    374             print("           -> %d raid partitions" % len(raid_partitions))
    375             lvm_partitions = disk.getLVMPartitions()
    376             print("           -> %d LVM partitions" % len(lvm_partitions))
    377 
    378             partition_set = tuple(free_space_partition + primary_partitions + logical_partitions + raid_partitions + lvm_partitions)
    379             print("           -> set of %d partitions" % len(partition_set))
    380 
    381             partitions = []
    382             for partition in partition_set:
    383                 part = Partition(partition)
    384                 print(partition.path, part.size, part.raw_size)
    385                 # skip ranges <5MB
    386                 if part.raw_size > 5242880:
    387                     partitions.append(part)
    388                 else:
    389                     print("skipping ", partition.path, part.raw_size)
    390             partitions = sorted(partitions, key=lambda part: part.partition.geometry.start)
    391 
    392             print("      - Found partitions...")
    393             try: # assign mount_as and format_as if disk was just auto-formatted
    394                 for partition, (mount_as, format_as) in zip(partitions, assign_mount_format):
    395                     partition.mount_as = mount_as
    396                     partition.format_as = format_as
    397                 del assign_mount_format
    398             except NameError: pass
    399             print("      - Iterating partitions...")
    400             # Needed to fix the 1% minimum Partition.size_percent
    401             sum_size_percent = sum(p.size_percent for p in partitions) + 5  # 5% extra for good measure
    402             for partition in partitions:
    403                 print("        . Appending partition %s..." % partition.name)
    404                 partition.size_percent = round(partition.size_percent / sum_size_percent * 100, 0)
    405                 installer.setup.partitions.append(partition)
    406                 self.append(disk_iter, (partition.name,
    407                                         '<span foreground="{}">{}</span>'.format(partition.color, partition.type),
    408                                         partition.description,
    409                                         partition.format_as,
    410                                         partition.mount_as,
    411                                         partition.size,
    412                                         partition.free_space,
    413                                         partition,
    414                                         disk_path))
    415 
    416             print("      - Loading HTML view...")
    417             self.html_disks[disk_path] = DISK_TEMPLATE.format(PARTITIONS_HTML=''.join(PARTITION_TEMPLATE.format(p) for p in partitions))
    418 
    419     def get_html(self, disk):
    420         if disk in self.html_disks:
    421             return self.html_disks[disk]
    422         else:
    423             return ""
    424 
    425 # Returns "" for traditional devices (/dev/sda1, /dev/sdb2..etc..)
    426 # or "p" for devices using a "p" in their partition naming schemes (NVMe, eMMC..etc)
    427 # for instance /dev/mmcblk0p1 or /dev/nvme0p1
    428 def get_device_naming_scheme_prefix(device_name):
    429     if device_name[-1].isdigit():
    430         return "p"
    431     else:
    432         return ""
    433 
    434 def full_disk_format(device, create_boot=False, create_swap=True):
    435     # If some LVM volumes use the selected device, remove them.
    436     try:
    437         output = subprocess.getoutput("pvs --reportformat json")
    438         data = json.loads(output)
    439         for volume in data["report"]:
    440             for pv in volume["pv"]:
    441                 pv_name = pv["pv_name"]
    442                 vg_name = pv["vg_name"]
    443                 if pv_name.startswith(device.path) and vg_name != "":
    444                     print(f"LVM volume detected: {vg_name} on {pv_name}. Deleting it.")
    445                     os.system(f"vgremove -y {vg_name}")
    446     except Exception as e:
    447         print("Failed to detect LVM volumes!")
    448         print(e)
    449     # Disable swap in case a partition on this device is used as swap,
    450     # which would cause parted mklabel to fail.
    451     os.system("swapoff -a")
    452     # If the previous install failed some partitions will be mounted in /target, which also causes parted mklabel to fail. Unmount them.
    453     os.system("umount -R /target 2>/dev/null || true")
    454     # Create a default partition set up
    455     disk_label = ('gpt' if device.getLength('B') > 2**32*.9 * device.sectorSize  # size of disk > ~2TB
    456                            or installer.setup.gptonefi
    457                         else 'msdos')
    458     return_code = os.system("parted -s %s mklabel %s" % (device.path, disk_label))
    459     if return_code != 0:
    460         raise Exception(_("The partition table couldn't be written for %s. Restart the computer and try again.") % device.path)
    461 
    462     mkpart = (
    463         # (condition, mount_as, format_as, mkfs command, size_mb)
    464         # EFI
    465         (installer.setup.gptonefi, EFI_MOUNT_POINT, 'vfat', 'mkfs.vfat {} -F 32 ', 300),
    466         # boot
    467         (create_boot, '/boot', 'ext4', 'mkfs.ext4 -F {}', 1024),
    468         # swap - equal to RAM for hibernate to work well (but capped at ~8GB)
    469         (create_swap, SWAP_MOUNT_POINT, 'swap', 'mkswap {}', min(8800, int(round(1.1/1024 * int(getoutput("awk '/^MemTotal/{ print $2 }' /proc/meminfo")), -2)))),
    470         # root
    471         # root: btrfs, made with its subvolumes by the installer (make_root_btrfs)
    472         (True, '/', 'btrfs', 'mkfs.btrfs -f {}', 0),
    473     )
    474     run_parted = lambda cmd: os.system('parted --script --align optimal {} {} ; sync'.format(device.path, cmd))
    475     start_mb = 2
    476     partition_number = 0
    477     partition_prefix = get_device_naming_scheme_prefix(device.path)
    478     for partition in mkpart:
    479         if partition[0]:
    480             partition_number = partition_number + 1
    481             mkfs = partition[3]
    482             size_mb = partition[4]
    483             end = '{}MB'.format(start_mb + size_mb) if size_mb else '100%'
    484             mkpart_cmd = 'mkpart primary {}MB {}'.format(start_mb, end)
    485             print(mkpart_cmd)
    486             run_parted(mkpart_cmd)
    487             partition_path = "%s%s%d" % (device.path, partition_prefix, partition_number)
    488             num_tries = 0
    489             while True:
    490                 if os.path.exists(partition_path):
    491                     break
    492                 if num_tries < 5:
    493                     num_tries += 1
    494                     print("Could not find %s, waiting 1s..." % partition_path)
    495                     os.system("sync")
    496                     time.sleep(1)
    497                 else:
    498                     raise Exception(_("The partition %s could not be created. The installation will stop. Restart the computer and try again.") % partition_path)
    499             mkfs = mkfs.format(partition_path)
    500             print(mkfs)
    501             os.system(mkfs)
    502             start_mb += size_mb + 1
    503     if installer.setup.gptonefi:
    504         run_parted('set 1 boot on')
    505     return ((i[1], i[2]) for i in mkpart if i[0])
    506 
    507 
    508 def to_human_readable(size):
    509     for unit in [' ', _('kB'), _('MB'), _('GB'), _('TB'), 'PB', 'EB', 'ZB', 'YB']:
    510         if size < 1000:
    511             return "{:.1f} {}".format(size, unit)
    512         size /= 1000
    513 
    514 class Partition(object):
    515     format_as = ''
    516     mount_as = ''
    517 
    518     def __init__(self, partition):
    519         assert partition.type not in (parted.PARTITION_METADATA, parted.PARTITION_EXTENDED)
    520         self.path = str(partition.path)
    521 
    522         print("              -> Building partition object for %s" % self.path)
    523 
    524         self.partition = partition
    525         self.length = partition.getLength()
    526         print("                  . length %d" % self.length)
    527 
    528         self.size_percent = max(1, round(80*self.length/partition.disk.device.getLength(), 1))
    529         print("                  . size_percent %d" % self.size_percent)
    530 
    531         self.size = to_human_readable(partition.getLength('B'))
    532         self.raw_size = partition.getLength('B')
    533         print("                  . size %s" % self.size)
    534 
    535         # if not normal partition with /dev/sdXN path, set its name to '' and discard it from model
    536         self.name = self.path if partition.number != -1 else ''
    537         print("                  . name %s" % self.name)
    538 
    539         try:
    540             self.type = partition.fileSystem.type
    541             for fs in ('swap', 'hfs', 'ufs'):  # normalize fs variations (parted.filesystem.fileSystemType.keys())
    542                 if fs in self.type:
    543                     self.type = fs
    544             self.style = self.type
    545             print("                  . type %s" % self.type)
    546         except AttributeError:  # non-formatted partitions
    547             self.type = {
    548                 parted.PARTITION_LVM: 'LVM',
    549                 parted.PARTITION_SWAP: 'swap',
    550                 parted.PARTITION_RAID: 'RAID',  # Empty space on Extended partition is recognized as this
    551                 parted.PARTITION_PALO: 'PALO',
    552                 parted.PARTITION_PREP: 'PReP',
    553                 parted.PARTITION_LOGICAL: _('Logical partition'),
    554                 parted.PARTITION_EXTENDED: _('Extended partition'),
    555                 parted.PARTITION_FREESPACE: _('Free space'),
    556                 parted.PARTITION_HPSERVICE: 'HP Service',
    557                 parted.PARTITION_MSFT_RESERVED: 'MSFT Reserved',
    558             }.get(partition.type, _('Unknown'))
    559             self.style = {
    560                 parted.PARTITION_SWAP: 'swap',
    561                 parted.PARTITION_FREESPACE: 'freespace',
    562             }.get(partition.type, '')
    563             print("                  . type %s" % self.type)
    564 
    565         if "swap" in self.type:
    566             self.mount_as = SWAP_MOUNT_POINT
    567 
    568         # The ESP flag is the partition type (GPT GUID or MBR 0xEF) on both label types,
    569         # unlike the 'boot' flag which is just the active bit on MBR disks.
    570         try:
    571             self.is_esp = partition.active and partition.getFlag(parted.PARTITION_ESP)
    572         except Exception as detail:
    573             print("Could not read partition flags for %s: %s" % (self.path, detail))
    574             self.is_esp = False
    575         if self.is_esp:
    576             print("                  . is an EFI System Partition")
    577             if installer.setup.gptonefi:
    578                 self.mount_as = EFI_MOUNT_POINT
    579 
    580         # identify partition's description and used space
    581         try:
    582             print("                  . About to mount it...")
    583             os.system('mount --read-only {} {}'.format(self.path, TMP_MOUNTPOINT))
    584             size, free, self.used_percent, mount_point = getoutput("df {0} | grep '^{0}' | awk '{{print $2,$4,$5,$6}}' | tail -1".format(self.path)).split(None, 3)
    585             self.raw_size = int(size)*1024
    586             print("                  . size %s, free %s, self.used_percent %s, mount_point %s" % (size, free, self.used_percent, mount_point))
    587         except ValueError:
    588             print("                  . value error!")
    589             if "swap" in self.type:
    590                 self.os_fs_info, self.description, self.free_space, self.used_percent = ': '+self.type, 'swap', '', 0
    591             elif self.is_esp:
    592                 self.os_fs_info, self.description, self.free_space, self.used_percent = ': '+self.type, 'EFI System Partition', '', 0
    593             else:
    594                 print('WARNING: Partition {} or type {} failed to mount!'.format(self.path, partition.type))
    595                 self.os_fs_info, self.description, self.free_space, self.used_percent = ': '+self.type, '', '', 0
    596             print("                  . self.os_fs_info %s, self.description %s, self.free_space %s, self.used_percent %s" % (self.os_fs_info, self.description, self.free_space, self.used_percent))
    597         else:
    598             print("                  . About to find more about it...")
    599             self.size = to_human_readable(int(size)*1024)  # for mountable partitions, more accurate than the getLength size above
    600             self.free_space = to_human_readable(int(free)*1024)  # df returns values in 1024B-blocks by default
    601             self.used_percent = self.used_percent.strip('%') or 0
    602             description = ''
    603             if self.is_esp:
    604                 description = 'EFI System Partition'
    605             elif path_exists(mount_point, 'etc/linuxmint/info'):
    606                 description = getoutput("cat %s/etc/linuxmint/info | grep GRUB_TITLE" % mount_point).replace('GRUB_TITLE', '').replace('=', '').replace('"', '').strip()
    607             elif path_exists(mount_point, 'Windows/servicing/Version'):
    608                 description = 'Windows ' + {
    609                     '6.4':'10',
    610                     '6.3':'8.1',
    611                     '6.2':'8',
    612                     '6.1':'7',
    613                     '6.0':'Vista',
    614                     '5.2':'XP Pro x64',
    615                     '5.1':'XP',
    616                     '5.0':'2000',
    617                     '4.9':'ME',
    618                     '4.1':'98',
    619                     '4.0':'95',
    620                 }.get(getoutput('ls {}/Windows/servicing/Version'.format(mount_point))[:3], '')
    621             elif path_exists(mount_point, 'Boot/BCD'):
    622                 description = 'Windows bootloader/recovery'
    623             elif path_exists(mount_point, 'Windows/System32'):
    624                 description = 'Windows'
    625             elif self.type == 'hfs' and path_exists(mount_point, 'System/Library/CoreServices/SystemVersion.plist'):
    626                 description = 'Mac OS X'
    627             elif path_exists(mount_point, 'etc/'):
    628                 description = getoutput("su -c '{{ . {0}/etc/lsb-release && echo $DISTRIB_DESCRIPTION; }} || \
    629                                                 {{ . {0}/etc/os-release && echo $PRETTY_NAME; }}' live".format(mount_point)) or 'Unix'
    630             self.description = description
    631             self.os_fs_info = ': {0.description} ({0.type}; {0.size}; {0.free_space})'.format(self) if description else ': ' + self.type
    632             print("                  . self.description %s self.os_fs_info %s" % (self.description, self.os_fs_info))
    633         finally:
    634             print("                  . umounting it")
    635             os.system('umount ' + TMP_MOUNTPOINT + ' 2>/dev/null')
    636             print("                  . done")
    637 
    638         self.html_name = self.name.split('/')[-1]
    639         self.html_description = self.description
    640         if (self.size_percent < 10 and len(self.description) > 5):
    641             self.html_description = "%s..." % self.description[0:5]
    642         if (self.size_percent < 5):
    643             #Not enough space, don't write the name
    644             self.html_name = ""
    645             self.html_description = ""
    646 
    647         self.color = {
    648             # colors approximately from gparted (find matching set in usr/share/disk-partitions.html)
    649             'btrfs': '#636363',
    650             'exfat': '#47872a',
    651             'ext2':  '#2582a0',
    652             'ext3':  '#2582a0',
    653             'ext4':  '#21619e',
    654             'fat16': '#47872a',
    655             'fat32': '#47872a',
    656             'hfs':   '#636363',
    657             'jfs':   '#636363',
    658             'swap':  '#be3a37',
    659             'ntfs':  '#66a6a8',
    660             'reiserfs': '#636363',
    661             'ufs':   '#636363',
    662             'xfs':   '#636363',
    663             'zfs':   '#636363',
    664             parted.PARTITION_EXTENDED: '#a9a9a9',
    665         }.get(self.type, '#a9a9a9')
    666 
    667     def print_partition(self):
    668         print("Device: %s, format as: %s, mount as: %s" % (self.path, self.format_as, self.mount_as))
    669 
    670 
    671 class PartitionDialog(object):
    672     def __init__(self, path, mount_as, format_as, type):
    673         glade_file = RESOURCE_DIR + 'interface.ui'
    674         self.builder = Gtk.Builder()
    675         self.builder.add_from_file(glade_file)
    676         self.window = self.builder.get_object("dialog")
    677         self.window.set_title(_("Edit partition"))
    678         self.builder.get_object("label_partition").set_markup("<b>%s</b>" % _("Device:"))
    679         self.builder.get_object("label_partition_value").set_label(path)
    680         self.builder.get_object("label_use_as").set_markup(_("Format as:"))
    681         self.builder.get_object("label_mount_point").set_markup(_("Mount point:"))
    682         self.builder.get_object("button_cancel").set_label(_("Cancel"))
    683         self.builder.get_object("button_ok").set_label(_("OK"))
    684         # Build supported filesystems list
    685         model = Gtk.ListStore(str)
    686         model.append([""])
    687         filesystems = ["", "ext4", "ext3", "ext2", "btrfs", "jfs", "xfs", "fat", "vfat", "swap"]
    688         for fs in filesystems:
    689             if os.path.exists(f"/usr/bin/mkfs.{fs}") or os.path.exists(f"/usr/sbin/mkfs.{fs}"):
    690                 model.append([fs])
    691         model.append(["swap"])
    692         self.builder.get_object("combobox_use_as").set_model(model)
    693         self.builder.get_object("combobox_use_as").set_active(filesystems.index(format_as))
    694         # Build list of pre-provided mountpoints
    695         combobox = self.builder.get_object("comboboxentry_mount_point")
    696         model = Gtk.ListStore(str, str)
    697         for i in ["", "/", "/home", "/boot", "/boot/efi", "/tmp", "swap"]:
    698             model.append(["", i])
    699         combobox.set_model(model)
    700         combobox.set_entry_text_column(1)
    701         combobox.set_id_column(1)
    702         combobox.get_child().set_text(mount_as)
    703 
    704     def show(self):
    705         response = self.window.run()
    706         w = self.builder.get_object("comboboxentry_mount_point")
    707         mount_as = w.get_child().get_text().strip()
    708         w = self.builder.get_object("combobox_use_as")
    709         format_as = w.get_model()[w.get_active()][0]
    710         self.window.destroy()
    711         if response in (Gtk.ResponseType.YES, Gtk.ResponseType.APPLY, Gtk.ResponseType.OK, Gtk.ResponseType.ACCEPT):
    712             response_is_ok = True
    713         else:
    714             response_is_ok = False
    715         return response_is_ok, mount_as, format_as