Example #1
0
 def test_logical_volume_list_parsing(self):
     # Example contents of lvm_logv.list file
     lvm_logv_list_string = """/dev/vgtest/lvtest  Linux rev 1.0 ext4 filesystem data, UUID=b9131c40-9742-416c-b019-8b11481a86ac (extents) (64bit) (large files) (huge files)"""
     logical_volume_dict = Lvm.parse_logical_volume_device_list_string(lvm_logv_list_string)
     expected = {"/dev/vgtest/lvtest": {"metadata": "Linux rev 1.0 ext4 filesystem data, UUID=b9131c40-9742-416c-b019-8b11481a86ac (extents) (64bit) (large files) (huge files)"}}
     # pp = pprint.PrettyPrinter(indent=4)
     self.assertDictEqual(expected, logical_volume_dict)
Example #2
0
    def _scan_and_unmount_existing_lvm(self, dest_partitions, is_overwriting_partition_table):
        with self.lvm_lv_path_lock:
            self.lvm_lv_path_list.clear()

        error_message = ""
        try:
            # Gathering LVM logical volumes.
            # Start the Logical Volume Manager (LVM). Caller raises Exception on failure
            Lvm.start_lvm2(logger=None)
            vg_state_dict = Lvm.get_volume_group_state_dict(logger=None)

            for dest_partition_key in dest_partitions:
                # Figure out LVM Volume Groups and Logical Volumes
                relevant_vg_name_list = []
                for report_dict in vg_state_dict['report']:
                    for vg_dict in report_dict['vg']:
                        if 'pv_name' in vg_dict.keys() and dest_partition_key == vg_dict['pv_name']:
                            if 'vg_name' in vg_dict.keys():
                                vg_name = vg_dict['vg_name']
                            else:
                                error_message += "Could not find volume group name vg_name in " + str(vg_dict) + "\n"
                                # TODO: Re-evaluate how exactly Clonezilla uses /NOT_FOUND and whether introducing it here
                                # TODO: could improve Rescuezilla/Clonezilla interoperability.
                                continue
                            if 'pv_uuid' in vg_dict.keys():
                                pv_uuid = vg_dict['pv_uuid']
                            else:
                                error_message += "Could not find physical volume UUID pv_uuid in " + str(vg_dict) + "\n"
                                continue
                            relevant_vg_name_list.append(vg_name)
                lv_state_dict = Lvm.get_logical_volume_state_dict(logger=None)
                for report_dict in lv_state_dict['report']:
                    for lv_dict in report_dict['lv']:
                        # Only consider VGs that match the partitions to backup list
                        if 'vg_name' in lv_dict.keys() and lv_dict['vg_name'] in relevant_vg_name_list:
                            vg_name = lv_dict['vg_name']
                            if 'lv_path' in lv_dict.keys():
                                lv_path = lv_dict['lv_path']
                                is_unmounted, message = Utility.umount_warn_on_busy(lv_path)
                                if not is_unmounted:
                                    error_message += message
                                else:
                                    # TODO: Make this logic better
                                    with self.lvm_lv_path_lock:
                                        self.lvm_lv_path_list.append(lv_path)
                            else:
                                continue

            # Stop the Logical Volume Manager (LVM)
            failed_logical_volume_list, failed_volume_group_list = Lvm.shutdown_lvm2(self.builder, None)
            for failed_volume_group in failed_volume_group_list:
                error_message += "Failed to shutdown Logical Volume Manager (LVM) Volume Group (VG): " + failed_volume_group[
                    0] + "\n\n" + failed_volume_group[1]
                GLib.idle_add(self.post_lvm_preparation, is_overwriting_partition_table, False, error_message)
                return

            for failed_logical_volume in failed_logical_volume_list:
                error_message += "Failed to shutdown Logical Volume Manager (LVM) Logical Volume (LV): " + \
                          failed_logical_volume[0] + "\n\n" + failed_logical_volume[1]
                GLib.idle_add(self.post_lvm_preparation, is_overwriting_partition_table, False, error_message)
                return
            GLib.idle_add(self.post_lvm_preparation, is_overwriting_partition_table, True, error_message)
        except Exception as e:
            tb = traceback.format_exc()
            traceback.print_exc()
            message = "Unable to process Logical Volume Manager (LVMs): " + tb
            GLib.idle_add(self.post_lvm_preparation, is_overwriting_partition_table, False, error_message)
        GLib.idle_add(self.post_lvm_preparation, is_overwriting_partition_table, True, error_message)
Example #3
0
 def test_volume_group_list_parsing(self):
     # Example contents of lvm_vg_dev.list
     lvm_vg_dev_list_string = """vgtest /dev/sdb i20UTQ-OaX3-c6nB-CiBv-Gav1-hgVf-tEkO2W"""
     volume_group_dict = Lvm.parse_volume_group_device_list_string(lvm_vg_dev_list_string)
     expected = {"vgtest": {"device_node": "/dev/sdb", "uuid": "i20UTQ-OaX3-c6nB-CiBv-Gav1-hgVf-tEkO2W"}}
     self.assertDictEqual(expected, volume_group_dict)
Example #4
0
    def __init__(self, absolute_clonezilla_img_path, enduser_filename):
        self.absolute_path = absolute_clonezilla_img_path
        self.enduser_filename = enduser_filename
        self.warning_dict = {}

        statbuf = os.stat(self.absolute_path)
        self.last_modified_timestamp = format_datetime(
            datetime.fromtimestamp(statbuf.st_mtime))
        print("Last modified timestamp " + self.last_modified_timestamp)

        self.image_format = "CLONEZILLA_FORMAT"
        dir = Path(absolute_clonezilla_img_path).parent.as_posix()
        print("Clonezilla directory : " + dir)

        self.short_device_node_partition_list = []
        self.short_device_node_disk_list = []
        self.lvm_vg_dev_dict = {}
        self.lvm_logical_volume_dict = {}
        self.dev_fs_dict = {}

        self.is_needs_decryption = False
        self.ecryptfs_info_dict = None
        ecryptfs_info_filepath = os.path.join(dir, "ecryptfs.info")
        if isfile(ecryptfs_info_filepath):
            try:
                # ecryptfs.info is plain text when the directory is encrypted and produces Input/Output error when decrypted
                Utility.read_file_into_string(ecryptfs_info_filepath)
                self.is_needs_decryption = True
            except:
                self.is_needs_decryption = False

        if self.is_needs_decryption:
            self.ecryptfs_info_dict = Ecryptfs.parse_ecryptfs_info(
                Utility.read_file_into_string(ecryptfs_info_filepath))
            self.short_device_node_disk_list = self.ecryptfs_info_dict['disk']
            self.short_device_node_partition_list = self.ecryptfs_info_dict[
                'parts']
        else:
            # The 'parts' file contains space separated short partition device nodes (eg 'sda1 sda2 sda7') corresponding
            # to the partitions that were selected by the user during the original backup.
            parts_filepath = os.path.join(dir, "parts")
            if isfile(parts_filepath):
                self.short_device_node_partition_list = Utility.read_space_delimited_file_into_list(
                    parts_filepath)
            else:
                # Every Clonezilla image encountered so far has a 'parts' file, so the backup is considered invalid
                # if none is present.
                raise FileNotFoundError("Unable to locate " + parts_filepath +
                                        " or file is encrypted")

            # The 'disk' file can contain *multiple* space-separated short device nodes (eg 'sda sdb'), but most
            # users will only backup one drive at a time using Clonezilla.
            #
            # Clonezilla images created using 'saveparts' function (rather than 'savedisk') does NOT have this file.
            disk_filepath = os.path.join(dir, "disk")
            if isfile(disk_filepath):
                self.short_device_node_disk_list = Utility.read_space_delimited_file_into_list(
                    disk_filepath)
            else:
                print("Unable to locate " + disk_filepath)
                # Clonezilla images created using 'saveparts' (rather than 'savedisks') don't have this file. However, if
                # 'saveparts' is used on partitions that multiple disks that each contain partition tables then it's vital
                # that the short device nodes information is extracted in order for the user to be able to restoring their
                # intended partition table.
                #
                #
                parted_absolute_path_list = glob.glob(
                    os.path.join(dir, "*-pt.parted"))
                for parted_absolute_path in parted_absolute_path_list:
                    self.short_device_node_disk_list.append(
                        re.sub('-pt.parted', '',
                               os.path.basename(parted_absolute_path)))
                if len(self.short_device_node_disk_list) == 0:
                    # If the device list is still empty it must be due to using 'saveparts' on a drive without a
                    # partition table. Append these device odds onto the disk list for convenience.
                    self.short_device_node_disk_list += self.short_device_node_partition_list

            # TODO: Re-evaluate the need to parse this file, as far as I can tell all the information can be extracted
            # from the partition information.
            # The 'dev-fs.list' file contains the association between device nodes and the filesystems (eg '/dev/sda2 ext4')
            dev_fs_list_filepath = os.path.join(dir, "dev-fs.list")
            if isfile(dev_fs_list_filepath):
                self.dev_fs_dict = ClonezillaImage.parse_dev_fs_list_output(
                    Utility.read_file_into_string(dev_fs_list_filepath))
            else:
                # Not raising exception because older Clonezilla images don't have this file.
                print("Unable to locate " + dev_fs_list_filepath)

            # The 'blkid.list' file provides a snapshot of the partitions on the system at the time of backup. This data
            # is not particularly relevant during a restore operation, except potentially for eg, UUID.
            #
            # Danger: Do not mistake this structure for the current system's 'blkid' information.
            # TODO: Re-evaluate the need to parse this file. The risk of mistaken usage may outweigh its usefulness.
            self.blkid_dict = {}
            blkid_list_filepath = os.path.join(dir, "blkid.list")
            if isfile(blkid_list_filepath):
                self.blkid_dict = Blkid.parse_blkid_output(
                    Utility.read_file_into_string(
                        os.path.join(dir, blkid_list_filepath)))
            else:
                # Not raising exception because older Clonezilla images don't have this file.
                print("Unable to locate " + blkid_list_filepath)

            # The 'lvm_vg_dev.list' file contains the association between an LVM VG (Logical Volume Manager volume group)
            # with a name eg 'vgtest', the LVM PV (physical volume) with a UUID name, and the device node that the physical
            # volume resides on eg, /dev/sdb.
            lvm_vg_dev_list_filepath = os.path.join(dir, "lvm_vg_dev.list")
            if isfile(
                    lvm_vg_dev_list_filepath) and not self.is_needs_decryption:
                self.lvm_vg_dev_dict = Lvm.parse_volume_group_device_list_string(
                    Utility.read_file_into_string(lvm_vg_dev_list_filepath))
            else:
                print("No LVM volume group to device file detected in image")

            # The 'lvm_logv.list' file contains the association between device nodes and the filesystems (eg '/dev/sda2 ext4')
            lvm_logv_list_filepath = os.path.join(dir, "lvm_logv.list")
            if isfile(lvm_logv_list_filepath) and not self.is_needs_decryption:
                self.lvm_logical_volume_dict = Lvm.parse_logical_volume_device_list_string(
                    Utility.read_file_into_string(lvm_logv_list_filepath))
            else:
                print("No LVM logical volume file detected in image")

        self.parted_dict_dict = {}
        self.sfdisk_dict_dict = {}
        self.mbr_dict_dict = {}
        self.ebr_dict_dict = {}
        self.size_bytes = 0
        self.enduser_readable_size = "unknown"
        for short_disk_device_node in self.short_device_node_disk_list:
            self.size_bytes = 0
            # Clonezilla -pt.parted file lists size in sectors, rather than bytes (or end-user readable KB/MB/GB/TB as
            # Clonezilla's -pt.parted.compact file)
            parted_filepath = os.path.join(
                dir, short_disk_device_node + "-pt.parted")
            if isfile(parted_filepath) and not self.is_needs_decryption:
                self.parted_dict_dict[
                    short_disk_device_node] = Parted.parse_parted_output(
                        Utility.read_file_into_string(parted_filepath))
                if 'capacity' in self.parted_dict_dict[short_disk_device_node] and 'logical_sector_size' in \
                        self.parted_dict_dict[short_disk_device_node]:
                    self.size_bytes = self.parted_dict_dict[short_disk_device_node]['capacity'] * \
                                      self.parted_dict_dict[short_disk_device_node]['logical_sector_size']
                else:
                    raise Exception(
                        "Unable to calculate disk capacity using " +
                        parted_filepath + ": " +
                        str(self.parted_dict_dict[short_disk_device_node]))
            else:
                # Do not raise exception because parted partition table is not present when using 'saveparts'
                print("Unable to locate " + parted_filepath +
                      " or file is encrypted")

            if self.ecryptfs_info_dict is not None and 'size' in self.ecryptfs_info_dict.keys(
            ):
                self.enduser_readable_size = self.ecryptfs_info_dict[
                    'size'].strip("_")
            else:
                # Covert size in bytes to KB/MB/GB/TB as relevant
                self.enduser_readable_size = size(int(self.size_bytes),
                                                  system=alternative)
                sfdisk_filepath = os.path.join(
                    dir, short_disk_device_node + "-pt.sf")
                if isfile(sfdisk_filepath) and not self.is_needs_decryption:
                    sfdisk_string = Utility.read_file_into_string(
                        sfdisk_filepath)
                    self.sfdisk_dict_dict[short_disk_device_node] = {
                        'absolute_path':
                        sfdisk_filepath,
                        'sfdisk_dict':
                        Sfdisk.parse_sfdisk_dump_output(sfdisk_string),
                        'sfdisk_file_length':
                        len(sfdisk_string)
                    }
                else:
                    # Do not raise exception because sfdisk partition table is often missing using Clonezilla image format,
                    # as `sfdisk --dump` fails for disks without a partition table.
                    print("Unable to locate " + sfdisk_filepath +
                          " or file is encrypted")

            # There is a maximum of 1 MBR per drive (there can be many drives). Master Boot Record (EBR) is never
            # listed in 'parts' list.
            mbr_glob_list = glob.glob(
                os.path.join(dir, short_disk_device_node) + "*-mbr")
            for absolute_mbr_filepath in mbr_glob_list:
                short_mbr_device_node = basename(absolute_mbr_filepath).split(
                    "-mbr")[0]
                self.mbr_dict_dict[short_disk_device_node] = {
                    'short_device_node': short_mbr_device_node,
                    'absolute_path': absolute_mbr_filepath
                }

            # There is a maximum of 1 EBR per drive (there can be many drives). Extended Boot Record (EBR) is never
            # listed in 'parts' list.
            ebr_glob_list = glob.glob(
                os.path.join(dir, short_disk_device_node) + "*-ebr")
            for absolute_ebr_filepath in ebr_glob_list:
                short_ebr_device_node = basename(absolute_ebr_filepath).split(
                    "-ebr")[0]
                self.ebr_dict_dict[short_disk_device_node] = {
                    'short_device_node': short_ebr_device_node,
                    'absolute_path': absolute_ebr_filepath
                }

        self.image_format_dict_dict = collections.OrderedDict([])
        # Loops over the partitions listed in the 'parts' file
        for short_partition_device_node in self.short_device_node_partition_list:
            has_found_atleast_one_associated_image = False
            # For standard MBR and GPT partitions, the partition key listed in the 'parts' file has a directly
            # associated backup image, so check for this.
            image_format_dict = ClonezillaImage.scan_backup_image(
                dir, short_partition_device_node, self.is_needs_decryption)
            # If no match found check the LVM (Logical Volume Manager)
            if len(image_format_dict) == 0:
                # Loop over all the volume groups (if any)
                for vg_name in self.lvm_vg_dev_dict.keys():
                    # TODO: Evalulate if there are Linux multipath device nodes that hold LVM Physical Volumes.
                    # TODO: May need to adjust for multipath device node by replacing "/" with "-" for this node.
                    pv_short_device_node = re.sub(
                        '/dev/', '',
                        self.lvm_vg_dev_dict[vg_name]['device_node'])
                    # Check if there is an associated LVM Physical Volume (PV) present
                    if short_partition_device_node == pv_short_device_node:
                        # Yes, the partition being analysed is associated with an LVM physical volume that contains
                        # an LVM Volume Group. Now determine all backup images associated to Logical Volumes that
                        # reside within this Volume Group.
                        for lv_path in self.lvm_logical_volume_dict.keys():
                            candidate_lv_path_prefix = "/dev/" + vg_name + "/"
                            # Eg, "/dev/cl/root".startswith("/dev/cl")
                            if lv_path.startswith(candidate_lv_path_prefix):
                                # Found a logical volume. Note: There may be more than one LV associated with an VG
                                # Set the scan prefix for the backup image to eg "cl-root"
                                logical_volume_scan_key = re.sub(
                                    '/', '-', re.sub('/dev/', '', lv_path))
                                image_format_dict = ClonezillaImage.scan_backup_image(
                                    dir, logical_volume_scan_key,
                                    self.is_needs_decryption)
                                if len(image_format_dict) != 0:
                                    image_format_dict[
                                        'is_lvm_logical_volume'] = True
                                    image_format_dict[
                                        'volume_group_name'] = vg_name
                                    image_format_dict['physical_volume_long_device_node'] = \
                                    self.lvm_vg_dev_dict[vg_name]['device_node']
                                    image_format_dict[
                                        'logical_volume_long_device_node'] = lv_path
                                    self.image_format_dict_dict[
                                        logical_volume_scan_key] = image_format_dict
                                    has_found_atleast_one_associated_image = True
            else:
                has_found_atleast_one_associated_image = True
                self.image_format_dict_dict[
                    short_partition_device_node] = image_format_dict

            if not has_found_atleast_one_associated_image:
                self.image_format_dict_dict[short_partition_device_node] = {
                    'type': "missing",
                    'prefix': short_partition_device_node,
                    'is_lvm_logical_volume': False
                }
                # TODO: Improve conversion between /dev/ nodes to short dev node.
                long_partition_key = "/dev/" + short_partition_device_node
                if long_partition_key in self.dev_fs_dict.keys():
                    # Annotate have filesystem information from dev-fs.list file. This case is expected when during a
                    # backup Clonezilla or Rescuezilla failed to successfully image the filesystem, but may have
                    # succeeded for other filesystems.
                    fs = self.dev_fs_dict[long_partition_key]
                    self.image_format_dict_dict[short_partition_device_node][
                        'filesystem'] = fs
                    # TODO: Consider removing warning_dict as image_format_dict is sufficient.
                    self.warning_dict[short_partition_device_node] = fs
                elif self.is_needs_decryption:
                    self.warning_dict[short_partition_device_node] = _(
                        "Needs decryption")
                else:
                    self.warning_dict[short_partition_device_node] = _(
                        "Unknown filesystem")

        # Unfortunately swap partitions are not listed in the 'parts' file. There does not appear to be any alternative
        # but scanning for the swap partitions and add them to the existing partitions, taking care to avoid duplicates
        # by rescanning what has already been scanned due to listing as an LVM logical volume.
        swap_partition_info_glob_list = glob.glob(
            os.path.join(dir, "swappt-*.info"))
        for swap_partition_info_glob in swap_partition_info_glob_list:
            key = Swappt.get_short_device_from_swappt_info_filename(
                swap_partition_info_glob)
            already_scanned = False
            for image_format_dict_key in self.image_format_dict_dict.keys():
                if key == self.image_format_dict_dict[image_format_dict_key][
                        "prefix"]:
                    already_scanned = True
                    break
            if not already_scanned and not self.is_needs_decryption:
                self.image_format_dict_dict[key] = Swappt.parse_swappt_info(
                    Utility.read_file_into_string(swap_partition_info_glob))
                self.image_format_dict_dict[key]['type'] = "swap"
                self.image_format_dict_dict[key]['prefix'] = key
                self.image_format_dict_dict[key][
                    'is_lvm_logical_volume'] = False
        pp = pprint.PrettyPrinter(indent=4)
        pp.pprint(self.image_format_dict_dict)
Example #5
0
    def __init__(self, absolute_clonezilla_img_path, enduser_filename, dir,
                 ecryptfs_info_dict, is_needs_decryption,
                 short_disk_device_node, short_device_node_partition_list,
                 is_display_multidisk, enduser_drive_number):
        self.absolute_path = absolute_clonezilla_img_path
        self.ecryptfs_info_dict = ecryptfs_info_dict
        self.is_needs_decryption = is_needs_decryption
        self.short_disk_device_node = short_disk_device_node
        self.is_display_multidisk = is_display_multidisk
        self.enduser_drive_number = enduser_drive_number
        self.user_notes = ""
        self.warning_dict = {}

        notes_filepath = os.path.join(dir, "rescuezilla.description.txt")
        if os.path.exists(notes_filepath):
            self.user_notes = Utility.read_file_into_string(notes_filepath)

        if is_display_multidisk:
            multidisk_desc = _("Drive {drive_number}".format(
                drive_number=str(self.enduser_drive_number)))
            self.enduser_filename = enduser_filename + " (" + multidisk_desc + ")"
        else:
            self.enduser_filename = enduser_filename

        statbuf = os.stat(self.absolute_path)
        self.last_modified_timestamp = format_datetime(
            datetime.fromtimestamp(statbuf.st_mtime))
        print("Last modified timestamp " + self.last_modified_timestamp)

        self.image_format = "CLONEZILLA_FORMAT"

        self.short_device_node_partition_list = short_device_node_partition_list
        self.short_device_node_disk_list = [short_disk_device_node]
        self.ebr_dict = {}
        self.lvm_vg_dev_dict = {}
        self.lvm_logical_volume_dict = {}
        self.dev_fs_dict = {}

        if not self.is_needs_decryption:
            # The 'dev-fs.list' file contains the association between device nodes and the filesystems
            # (eg '/dev/sda2 ext4'). The filesystems are a combination of several sources, so the values may differ from
            # `blkid` and `parted`. Given newer versions of Clonezilla create this file, it makes sense to process it.
            dev_fs_list_filepath = os.path.join(dir, "dev-fs.list")
            if isfile(dev_fs_list_filepath):
                self.dev_fs_dict = ClonezillaImage.parse_dev_fs_list_output(
                    Utility.read_file_into_string(dev_fs_list_filepath))
            else:
                # Not raising exception because older Clonezilla images don't have this file.
                print("Unable to locate " + dev_fs_list_filepath)

            # The 'blkid.list' file provides a snapshot of the partitions on the system at the time of backup. This data
            # is not particularly relevant during a restore operation, except potentially for eg, UUID.
            #
            # Danger: Do not mistake this structure for the current system's 'blkid' information.
            # TODO: Re-evaluate the need to parse this file. The risk of mistaken usage may outweigh its usefulness.
            self.blkid_dict = {}
            blkid_list_filepath = os.path.join(dir, "blkid.list")
            if isfile(blkid_list_filepath):
                self.blkid_dict = Blkid.parse_blkid_output(
                    Utility.read_file_into_string(
                        os.path.join(dir, blkid_list_filepath)))
            else:
                # Not raising exception because older Clonezilla images don't have this file.
                print("Unable to locate " + blkid_list_filepath)

            # The 'lvm_vg_dev.list' file contains the association between an LVM VG (Logical Volume Manager volume group)
            # with a name eg 'vgtest', the LVM PV (physical volume) with a UUID name, and the device node that the physical
            # volume resides on eg, /dev/sdb.
            lvm_vg_dev_list_filepath = os.path.join(dir, "lvm_vg_dev.list")
            if isfile(
                    lvm_vg_dev_list_filepath) and not self.is_needs_decryption:
                self.lvm_vg_dev_dict = Lvm.parse_volume_group_device_list_string(
                    Utility.read_file_into_string(lvm_vg_dev_list_filepath))
            else:
                print("No LVM volume group to device file detected in image")

            # The 'lvm_logv.list' file contains the association between device nodes and the filesystems (eg '/dev/sda2 ext4')
            lvm_logv_list_filepath = os.path.join(dir, "lvm_logv.list")
            if isfile(lvm_logv_list_filepath) and not self.is_needs_decryption:
                self.lvm_logical_volume_dict = Lvm.parse_logical_volume_device_list_string(
                    Utility.read_file_into_string(lvm_logv_list_filepath))
            else:
                print("No LVM logical volume file detected in image")

        self.parted_dict = {}
        self._mbr_absolute_path = {}
        self.post_mbr_gap_absolute_path = {}
        self.size_bytes = 0
        self.enduser_readable_size = "unknown"
        self.size_bytes = 0
        # Clonezilla -pt.parted file lists size in sectors, rather than bytes (or end-user readable KB/MB/GB/TB as
        # Clonezilla's -pt.parted.compact file)
        parted_filepath = os.path.join(dir,
                                       short_disk_device_node + "-pt.parted")
        if isfile(parted_filepath) and not self.is_needs_decryption:
            self.parted_dict = Parted.parse_parted_output(
                Utility.read_file_into_string(parted_filepath))
            if 'capacity' in self.parted_dict and 'logical_sector_size' in \
                    self.parted_dict:
                self.size_bytes = self.parted_dict['capacity'] * \
                                  self.parted_dict['logical_sector_size']
            else:
                raise Exception("Unable to calculate disk capacity using " +
                                parted_filepath + ": " + str(self.parted_dict))
        else:
            # Do not raise exception because parted partition table is not present when using 'saveparts'
            print("Unable to locate " + parted_filepath +
                  " or file is encrypted")

        if self.ecryptfs_info_dict is not None and 'size' in self.ecryptfs_info_dict.keys(
        ):
            self.enduser_readable_size = self.ecryptfs_info_dict['size'].strip(
                "_")

        self.normalized_sfdisk_dict = {
            'absolute_path': None,
            'sfdisk_dict': {
                'partitions': {}
            },
            'file_length': 0
        }
        if not is_needs_decryption:
            sfdisk_absolute_path = os.path.join(
                dir, short_disk_device_node + "-pt.sf")
            self.normalized_sfdisk_dict = Sfdisk.generate_normalized_sfdisk_dict(
                sfdisk_absolute_path, self)

        # There is a maximum of 1 MBR per drive (there can be many drives). Master Boot Record (MBR) is never
        # listed in 'parts' list.
        self._mbr_absolute_path = None
        mbr_glob_list = glob.glob(
            os.path.join(dir, short_disk_device_node) + "-mbr")
        for absolute_mbr_filepath in mbr_glob_list:
            self._mbr_absolute_path = absolute_mbr_filepath

        # There is a maximum of 1 post-MBR gap per drive (there can be many drives). The post MBR gap is never
        # listed in 'parts' list. Note the asterisk wildcard in the glob, to get the notes.txt file (see below)
        post_mbr_gap_glob_list = glob.glob(
            os.path.join(dir, short_disk_device_node) +
            "-hidden-data-after-mbr*")
        for absolute_post_mbr_gap_filepath in post_mbr_gap_glob_list:
            if absolute_post_mbr_gap_filepath.endswith(
                    ".notes.txt") and not isfile(
                        os.path.join(dir, short_disk_device_node) +
                        "-hidden-data-after-mbr"):
                # When the post-MBR gap is not created by Clonezilla due to >1024 MB gap between MBR and first partition
                # there is a "notes.txt" file created which explains this. To maximize compatibility, in this
                # situation Rescuezilla v2.1+ creates a 1MB post-MBR  gap backup *and* a notes.txt file.
                self.warning_dict[
                    short_disk_device_node +
                    "mbr"] = "Backup is missing the \"post-MBR gap\" backup, most likely due to Clonezilla detecting a >1024MB gap between the MBR partition table and the first partition. Any GRUB bootloaders present will not restore correctly. In order to boot after restoring this backup, Clonezilla happens to workaround this situation by automatically re-installing GRUB, but current version of Rescuezilla does not implement this (but will in a future version). Clonezilla is available from within the Rescuezilla live environment by running `clonezilla` in a Terminal. See the following link for more information: https://github.com/rescuezilla/rescuezilla/issues/146"
            else:
                self.post_mbr_gap_absolute_path = {
                    'absolute_path': absolute_post_mbr_gap_filepath
                }

        # There is a maximum of 1 EBR per drive (there can be many drives). Extended Boot Record (EBR) is never
        # listed in 'parts' list. The asterisk is needed here because unlike the MBR case, the ebr file is eg,
        # sda4-ebr. In otherwords the EBR is associated with a partition not the base device node.
        ebr_glob_list = glob.glob(
            os.path.join(dir, short_disk_device_node) + "*-ebr")
        for absolute_ebr_filepath in ebr_glob_list:
            short_ebr_device_node = basename(absolute_ebr_filepath).split(
                "-ebr")[0]
            self.ebr_dict = {
                'short_device_node': short_ebr_device_node,
                'absolute_path': absolute_ebr_filepath
            }

        self.image_format_dict_dict = collections.OrderedDict([])
        # Loops over the partitions listed in the 'parts' file
        for short_partition_device_node in self.short_device_node_partition_list:
            has_found_atleast_one_associated_image = False
            # For standard MBR and GPT partitions, the partition key listed in the 'parts' file has a directly
            # associated backup image, so check for this.
            image_format_dict = ClonezillaImage.scan_backup_image(
                dir, short_partition_device_node, self.is_needs_decryption)
            # If no match found check the LVM (Logical Volume Manager)
            if len(image_format_dict) == 0:
                # Loop over all the volume groups (if any)
                for vg_name in self.lvm_vg_dev_dict.keys():
                    # TODO: Evalulate if there are Linux multipath device nodes that hold LVM Physical Volumes.
                    # TODO: May need to adjust for multipath device node by replacing "/" with "-" for this node.
                    pv_short_device_node = re.sub(
                        '/dev/', '',
                        self.lvm_vg_dev_dict[vg_name]['device_node'])
                    # Check if there is an associated LVM Physical Volume (PV) present
                    if short_partition_device_node == pv_short_device_node:
                        # Yes, the partition being analysed is associated with an LVM physical volume that contains
                        # an LVM Volume Group. Now determine all backup images associated to Logical Volumes that
                        # reside within this Volume Group.
                        for lv_path in self.lvm_logical_volume_dict.keys():
                            candidate_lv_path_prefix = "/dev/" + vg_name + "/"
                            # Eg, "/dev/cl/root".startswith("/dev/cl")
                            if lv_path.startswith(candidate_lv_path_prefix):
                                # Found a logical volume. Note: There may be more than one LV associated with an VG
                                # Set the scan prefix for the backup image to eg "cl-root"
                                logical_volume_scan_key = re.sub(
                                    '/', '-', re.sub('/dev/', '', lv_path))
                                image_format_dict = ClonezillaImage.scan_backup_image(
                                    dir, logical_volume_scan_key,
                                    self.is_needs_decryption)
                                if len(image_format_dict) != 0:
                                    image_format_dict[
                                        'is_lvm_logical_volume'] = True
                                    image_format_dict[
                                        'volume_group_name'] = vg_name
                                    image_format_dict['physical_volume_long_device_node'] = \
                                    self.lvm_vg_dev_dict[vg_name]['device_node']
                                    image_format_dict[
                                        'logical_volume_long_device_node'] = lv_path
                                    self.image_format_dict_dict[
                                        logical_volume_scan_key] = image_format_dict
                                    has_found_atleast_one_associated_image = True
            else:
                has_found_atleast_one_associated_image = True
                self.image_format_dict_dict[
                    short_partition_device_node] = image_format_dict

            if not has_found_atleast_one_associated_image:
                self.image_format_dict_dict[short_partition_device_node] = {
                    'type': "missing",
                    'prefix': short_partition_device_node,
                    'is_lvm_logical_volume': False
                }
                # TODO: Improve conversion between /dev/ nodes to short dev node.
                long_partition_key = "/dev/" + short_partition_device_node
                if long_partition_key in self.dev_fs_dict.keys():
                    # Annotate have filesystem information from dev-fs.list file. This case is expected when during a
                    # backup Clonezilla or Rescuezilla failed to successfully image the filesystem, but may have
                    # succeeded for other filesystems.
                    fs = self.dev_fs_dict[long_partition_key]['filesystem']
                    self.image_format_dict_dict[short_partition_device_node][
                        'filesystem'] = fs
                    # TODO: Consider removing warning_dict as image_format_dict is sufficient.
                    self.warning_dict[short_partition_device_node] = fs
                elif self.is_needs_decryption:
                    self.warning_dict[short_partition_device_node] = _(
                        "Needs decryption")
                else:
                    self.warning_dict[short_partition_device_node] = _(
                        "Unknown filesystem")

        # Unfortunately swap partitions are not listed in the 'parts' file. There does not appear to be any alternative
        # but scanning for the swap partitions and add them to the existing partitions, taking care to avoid duplicates
        # by rescanning what has already been scanned due to listing as an LVM logical volume.
        swap_partition_info_glob_list = glob.glob(
            os.path.join(dir, "swappt-*.info"))
        for swap_partition_info_glob in swap_partition_info_glob_list:
            key = Swappt.get_short_device_from_swappt_info_filename(
                swap_partition_info_glob)
            already_scanned = False
            for image_format_dict_key in self.image_format_dict_dict.keys():
                if key == self.image_format_dict_dict[image_format_dict_key][
                        "prefix"]:
                    already_scanned = True
                    break
            if not already_scanned and not self.is_needs_decryption:
                self.image_format_dict_dict[key] = Swappt.parse_swappt_info(
                    Utility.read_file_into_string(swap_partition_info_glob))
                self.image_format_dict_dict[key]['type'] = "swap"
                self.image_format_dict_dict[key]['prefix'] = key
                self.image_format_dict_dict[key][
                    'is_lvm_logical_volume'] = False

        total_size_estimate = 0
        # Now we have all the images, compute the partition size estimates, and save it to avoid recomputing.
        for image_format_dict_key in self.image_format_dict_dict.keys():
            # Try to find the short_disk_key for the image. This key is used to access the parted and sfdisk
            # partition table backups. It's not guaranteed there is a direct association between the backup image and
            # the partition table (for example, Logical Volume Manager logical volumes).
            associated_short_disk_key = ""
            for short_disk_key in self.short_device_node_disk_list:
                if image_format_dict_key.startswith(short_disk_key):
                    associated_short_disk_key = short_disk_key
            estimated_size_bytes = self._compute_partition_size_byte_estimate(
                associated_short_disk_key, image_format_dict_key)
            self.image_format_dict_dict[image_format_dict_key][
                'estimated_size_bytes'] = estimated_size_bytes
            total_size_estimate += estimated_size_bytes

        if self.size_bytes == 0:
            # For md RAID devices, Clonezilla doesn't have a parted of sfdisk partition table containing the hard drive
            # size, so in that situation, summing the image sizes provides some kind of size estimate.
            self.size_bytes = total_size_estimate

        # Covert size in bytes to KB/MB/GB/TB as relevant
        self.enduser_readable_size = Utility.human_readable_filesize(
            int(self.size_bytes))

        pp = pprint.PrettyPrinter(indent=4)
        pp.pprint(self.image_format_dict_dict)
Example #6
0
    def do_backup(self):
        self.at_least_one_non_fatal_error = False
        self.requested_stop = False
        # Clear proc dictionary
        self.proc.clear()
        self.summary_message_lock = threading.Lock()
        self.summary_message = ""

        env = Utility.get_env_C_locale()

        print("mkdir " + self.dest_dir)
        os.mkdir(self.dest_dir)

        short_selected_device_node = re.sub('/dev/', '',
                                            self.selected_drive_key)
        enduser_date = datetime.today().strftime('%Y-%m-%d-%H%M')
        clonezilla_img_filepath = os.path.join(self.dest_dir, "clonezilla-img")
        with open(clonezilla_img_filepath, 'w') as filehandle:
            try:
                output = "This image was saved by Rescuezilla at " + enduser_date + "\nSaved by " + self.human_readable_version + "\nThe log during saving:\n----------------------------------------------------------\n\n"
                filehandle.write(output)
            except:
                tb = traceback.format_exc()
                traceback.print_exc()
                error_message = _(
                    "Failed to write destination file. Please confirm it is valid to create the provided file path, and try again."
                ) + "\n\n" + tb
                GLib.idle_add(self.completed_backup, False, error_message)
                return

        self.logger = Logger(clonezilla_img_filepath)
        GLib.idle_add(self.update_backup_progress_bar, 0)

        process, flat_command_string, failed_message = Utility.run(
            "Saving blkdev.list", [
                "lsblk", "-oKNAME,NAME,SIZE,TYPE,FSTYPE,MOUNTPOINT,MODEL",
                self.selected_drive_key
            ],
            use_c_locale=True,
            output_filepath=os.path.join(self.dest_dir, "blkdev.list"),
            logger=self.logger)
        if process.returncode != 0:
            with self.summary_message_lock:
                self.summary_message += failed_message
            GLib.idle_add(self.completed_backup, False, failed_message)
            return

        blkid_cmd_list = ["blkid"]
        sort_cmd_list = ["sort", "-V"]
        Utility.print_cli_friendly("blkid ", [blkid_cmd_list, sort_cmd_list])
        self.proc['blkid'] = subprocess.Popen(blkid_cmd_list,
                                              stdout=subprocess.PIPE,
                                              env=env,
                                              encoding='utf-8')

        process, flat_command_string, failed_message = Utility.run(
            "Saving blkid.list", ["blkid"],
            use_c_locale=True,
            output_filepath=os.path.join(self.dest_dir, "blkid.list"),
            logger=self.logger)
        if process.returncode != 0:
            with self.summary_message_lock:
                self.summary_message += failed_message
            GLib.idle_add(self.completed_backup, False, failed_message)
            return

        process, flat_command_string, failed_message = Utility.run(
            "Saving Info-lshw.txt", ["lshw"],
            use_c_locale=True,
            output_filepath=os.path.join(self.dest_dir, "Info-lshw.txt"),
            logger=self.logger)
        if process.returncode != 0:
            with self.summary_message_lock:
                self.summary_message += failed_message
            GLib.idle_add(self.completed_backup, False, failed_message)
            return

        info_dmi_txt_filepath = os.path.join(self.dest_dir, "Info-dmi.txt")
        with open(info_dmi_txt_filepath, 'w') as filehandle:
            filehandle.write(
                "# This image was saved from this machine with DMI info at " +
                enduser_date + ":\n")
            filehandle.flush()
        process, flat_command_string, failed_message = Utility.run(
            "Saving Info-dmi.txt", ["dmidecode"],
            use_c_locale=True,
            output_filepath=info_dmi_txt_filepath,
            logger=self.logger)
        if process.returncode != 0:
            with self.summary_message_lock:
                self.summary_message += failed_message
            GLib.idle_add(self.completed_backup, False, failed_message)
            return

        info_lspci_filepath = os.path.join(self.dest_dir, "Info-lspci.txt")
        with open(info_lspci_filepath, 'w') as filehandle:
            # TODO: Improve datetime format string.
            filehandle.write(
                "This image was saved from this machine with PCI info at " +
                enduser_date + "\n")
            filehandle.write("'lspci' results:\n")
            filehandle.flush()

        process, flat_command_string, failed_message = Utility.run(
            "Appending `lspci` output to Info-lspci.txt", ["lspci"],
            use_c_locale=True,
            output_filepath=info_lspci_filepath,
            logger=self.logger)
        if process.returncode != 0:
            with self.summary_message_lock:
                self.summary_message += failed_message
            GLib.idle_add(self.completed_backup, False, failed_message)
            return

        msg_delimiter_star_line = "*****************************************************."
        with open(info_lspci_filepath, 'a+') as filehandle:
            filehandle.write(msg_delimiter_star_line + "\n")
            filehandle.write("'lspci -n' results:\n")
            filehandle.flush()

        # Show PCI vendor and device codes as numbers instead of looking them up in the PCI ID list.
        process, flat_command_string, failed_message = Utility.run(
            "Appending `lspci -n` output to Info-lspci.txt", ["lspci", "-n"],
            use_c_locale=True,
            output_filepath=info_lspci_filepath,
            logger=self.logger)
        if process.returncode != 0:
            with self.summary_message_lock:
                self.summary_message += failed_message
            GLib.idle_add(self.completed_backup, False, failed_message)
            return

        info_smart_filepath = os.path.join(self.dest_dir, "Info-smart.txt")
        with open(info_smart_filepath, 'w') as filehandle:
            filehandle.write(
                "This image was saved from this machine with hard drive S.M.A.R.T. info at "
                + enduser_date + "\n")
            filehandle.write(msg_delimiter_star_line + "\n")
            filehandle.write("For the drive: " + self.selected_drive_key +
                             "\n")
            filehandle.flush()

        # VirtualBox doesn't support smart, so ignoring the exit code here.
        # FIXME: Improve this.
        process, flat_command_string, failed_message = Utility.run(
            "Saving Info-smart.txt",
            ["smartctl", "--all", self.selected_drive_key],
            use_c_locale=True,
            output_filepath=info_smart_filepath,
            logger=self.logger)

        filepath = os.path.join(self.dest_dir, "Info-packages.txt")
        # Save Debian package informtion
        if shutil.which("dpkg") is not None:
            rescuezilla_package_list = ["rescuezilla", "util-linux", "gdisk"]
            with open(filepath, 'w') as filehandle:
                filehandle.write(
                    "Image was saved by these Rescuezilla-related packages:\n "
                )
                for pkg in rescuezilla_package_list:
                    dpkg_process = subprocess.run(['dpkg', "--status", pkg],
                                                  capture_output=True,
                                                  encoding="UTF-8")
                    if dpkg_process.returncode != 0:
                        continue
                    for line in dpkg_process.stdout.split("\n"):
                        if re.search("^Version: ", line):
                            version = line[len("Version: "):]
                            filehandle.write(pkg + "-" + version + " ")
                filehandle.write("\nSaved by " + self.human_readable_version +
                                 ".\n")

        # TODO: Clonezilla creates a file named "Info-saved-by-cmd.txt" file, to allow users to re-run the exact
        #  command again without going through the wizard. The proposed Rescuezilla approach to this feature is
        #  discussed here: https://github.com/rescuezilla/rescuezilla/issues/106

        filepath = os.path.join(self.dest_dir, "parts")
        with open(filepath, 'w') as filehandle:
            i = 0
            for partition_key in self.partitions_to_backup:
                short_partition_key = re.sub('/dev/', '', partition_key)
                to_backup_dict = self.partitions_to_backup[partition_key]
                is_swap = False
                if 'filesystem' in to_backup_dict.keys(
                ) and to_backup_dict['filesystem'] == "swap":
                    is_swap = True
                if 'type' not in to_backup_dict.keys(
                ) or 'type' in to_backup_dict.keys(
                ) and 'extended' != to_backup_dict['type'] and not is_swap:
                    # Clonezilla does not write the extended partition node into the parts file,
                    # nor does it write swap partition node
                    filehandle.write('%s' % short_partition_key)
                    # Ensure no trailing space on final iteration (to match Clonezilla format exactly)
                    if i + 1 != len(self.partitions_to_backup.keys()):
                        filehandle.write(' ')
                i += 1
            filehandle.write('\n')

        filepath = os.path.join(self.dest_dir, "disk")
        with open(filepath, 'w') as filehandle:
            filehandle.write('%s\n' % short_selected_device_node)

        compact_parted_filename = short_selected_device_node + "-pt.parted.compact"
        # Parted drive information with human-readable "compact" units: KB/MB/GB rather than sectors.
        process, flat_command_string, failed_message = Utility.run(
            "Saving " + compact_parted_filename, [
                "parted", "--script", self.selected_drive_key, "unit",
                "compact", "print"
            ],
            use_c_locale=True,
            output_filepath=os.path.join(self.dest_dir,
                                         compact_parted_filename),
            logger=self.logger)
        if process.returncode != 0:
            with self.summary_message_lock:
                self.summary_message += failed_message
            GLib.idle_add(self.completed_backup, False, failed_message)
            return

        # Parted drive information with standard sector units. Clonezilla doesn't output easily parsable output using
        # the --machine flag, so for maximum Clonezilla compatibility neither does Rescuezilla.
        parted_filename = short_selected_device_node + "-pt.parted"
        parted_process, flat_command_string, failed_message = Utility.run(
            "Saving " + parted_filename, [
                "parted", "--script", self.selected_drive_key, "unit", "s",
                "print"
            ],
            use_c_locale=True,
            output_filepath=os.path.join(self.dest_dir, parted_filename),
            logger=self.logger)
        if process.returncode != 0:
            with self.summary_message_lock:
                self.summary_message += failed_message
            GLib.idle_add(self.completed_backup, False, failed_message)
            return

        parted_dict = Parted.parse_parted_output(parted_process.stdout)
        partition_table = parted_dict['partition_table']

        # Save MBR for both msdos and GPT disks
        if "gpt" == partition_table or "msdos" == partition_table:
            filepath = os.path.join(self.dest_dir,
                                    short_selected_device_node + "-mbr")
            process, flat_command_string, failed_message = Utility.run(
                "Saving " + filepath, [
                    "dd", "if=" + self.selected_drive_key, "of=" + filepath,
                    "bs=512", "count=1"
                ],
                use_c_locale=False,
                logger=self.logger)
            if process.returncode != 0:
                with self.summary_message_lock:
                    self.summary_message += failed_message
                GLib.idle_add(self.completed_backup, False, failed_message)
                return

        if "gpt" == partition_table:
            first_gpt_filename = short_selected_device_node + "-gpt-1st"
            dd_process, flat_command_string, failed_message = Utility.run(
                "Saving " + first_gpt_filename, [
                    "dd", "if=" + self.selected_drive_key,
                    "of=" + os.path.join(self.dest_dir, first_gpt_filename),
                    "bs=512", "count=34"
                ],
                use_c_locale=False,
                logger=self.logger)
            if process.returncode != 0:
                with self.summary_message_lock:
                    self.summary_message += failed_message
                GLib.idle_add(self.completed_backup, False, failed_message)
                return

            # From Clonezilla's scripts/sbin/ocs-functions:
            # We need to get the total size of disk so that we can skip and dump the last block:
            # The output of 'parted -s /dev/sda unit s print' is like:
            # --------------------
            # Disk /dev/hda: 16777215s
            # Sector size (logical/physical): 512B/512B
            # Partition Table: gpt
            #
            # Number  Start     End        Size       File system  Name     Flags
            #  1      34s       409640s    409607s    fat32        primary  msftres
            #  2      409641s   4316406s   3906766s   ext2         primary
            #  3      4316407s  15625000s  11308594s  reiserfs     primary
            # --------------------
            # to_seek = "$((${src_disk_size_sec}-33+1))"
            to_skip = parted_dict['capacity'] - 32
            second_gpt_filename = short_selected_device_node + "-gpt-2nd"
            process, flat_command_string, failed_message = Utility.run(
                "Saving " + second_gpt_filename, [
                    "dd", "if=" + self.selected_drive_key,
                    "of=" + os.path.join(self.dest_dir, second_gpt_filename),
                    "skip=" + str(to_skip), "bs=512", "count=33"
                ],
                use_c_locale=False,
                logger=self.logger)
            if process.returncode != 0:
                with self.summary_message_lock:
                    self.summary_message += failed_message
                GLib.idle_add(self.completed_backup, False, failed_message)
                return

            # LC_ALL=C sgdisk -b $target_dir_fullpath/$(to_filename ${ihd})-gpt.gdisk /dev/$ihd | tee --append ${OCS_LOGFILE}
            gdisk_filename = short_selected_device_node + "-gpt.gdisk"
            process, flat_command_string, failed_message = Utility.run(
                "Saving " + gdisk_filename, [
                    "sgdisk", "--backup",
                    os.path.join(self.dest_dir, gdisk_filename),
                    self.selected_drive_key
                ],
                use_c_locale=True,
                logger=self.logger)
            if process.returncode != 0:
                with self.summary_message_lock:
                    self.summary_message += failed_message
                GLib.idle_add(self.completed_backup, False, failed_message)
                return

            sgdisk_filename = short_selected_device_node + "-gpt.sgdisk"
            process, flat_command_string, failed_message = Utility.run(
                "Saving " + sgdisk_filename,
                ["sgdisk", "--print", self.selected_drive_key],
                use_c_locale=True,
                output_filepath=os.path.join(self.dest_dir, sgdisk_filename),
                logger=self.logger)
            if process.returncode != 0:
                with self.summary_message_lock:
                    self.summary_message += failed_message
                GLib.idle_add(self.completed_backup, False, failed_message)
                return
        elif "msdos" == partition_table:
            # image_save
            first_partition_key, first_partition_offset_bytes = CombinedDriveState.get_first_partition(
                self.partitions_to_backup)
            # Maximum hidden data to backup is 1024MB
            hidden_data_after_mbr_limit = 1024 * 1024 * 1024
            if first_partition_offset_bytes > hidden_data_after_mbr_limit:
                self.logger.write(
                    "Calculated very large hidden data after MBR size. Skipping"
                )
            else:
                first_partition_offset_sectors = int(
                    first_partition_offset_bytes / 512)
                hidden_mbr_data_filename = short_selected_device_node + "-hidden-data-after-mbr"
                # FIXME: Appears one sector too large.
                process, flat_command_string, failed_message = Utility.run(
                    "Saving " + hidden_mbr_data_filename, [
                        "dd", "if=" + self.selected_drive_key, "of=" +
                        os.path.join(self.dest_dir, hidden_mbr_data_filename),
                        "skip=1", "bs=512",
                        "count=" + str(first_partition_offset_sectors)
                    ],
                    use_c_locale=False,
                    logger=self.logger)
            if process.returncode != 0:
                with self.summary_message_lock:
                    self.summary_message += failed_message
                GLib.idle_add(self.completed_backup, False, failed_message)
                return

        else:
            self.logger.write("Partition table is: " + partition_table)

        # Parted sees drives with direct filesystem applied as loop partition table.
        if partition_table is not None and partition_table != "loop":
            sfdisk_filename = short_selected_device_node + "-pt.sf"
            process, flat_command_string, failed_message = Utility.run(
                "Saving " + sfdisk_filename,
                ["sfdisk", "--dump", self.selected_drive_key],
                output_filepath=os.path.join(self.dest_dir, sfdisk_filename),
                use_c_locale=True,
                logger=self.logger)
            if process.returncode != 0:
                with self.summary_message_lock:
                    self.summary_message += failed_message
                GLib.idle_add(self.completed_backup, False, failed_message)
                return

        process, flat_command_string, failed_message = Utility.run(
            "Retreiving disk geometry with sfdisk ",
            ["sfdisk", "--show-geometry", self.selected_drive_key],
            use_c_locale=True,
            logger=self.logger)
        if process.returncode != 0:
            with self.summary_message_lock:
                self.summary_message += failed_message
            GLib.idle_add(self.completed_backup, False, failed_message)
            return

        geometry_dict = Sfdisk.parse_sfdisk_show_geometry(process.stdout)
        filepath = os.path.join(self.dest_dir,
                                short_selected_device_node + "-chs.sf")
        with open(filepath, 'w') as filehandle:
            for key in geometry_dict.keys():
                output = key + "=" + str(geometry_dict[key])
                self.logger.write(output)
                filehandle.write('%s\n' % output)

        # Query all Physical Volumes (PV), Volume Group (VG) and Logical Volume (LV). See unit test for a worked example.
        # TODO: In the Rescuezilla application architecture, this LVM information is best extracted during the drive
        # TODO: query step, and then integrated into the "combined drive state" dictionary. Doing it during the backup
        # TODO: process matches how Clonezilla does it, which is sufficient for now.
        # FIXME: This section is duplicated in partitions_to_restore.py.
        # Start the Logical Volume Manager (LVM). Caller raises Exception on failure
        Lvm.start_lvm2(self.logger)
        relevant_vg_name_dict = {}
        vg_state_dict = Lvm.get_volume_group_state_dict(self.logger)
        for partition_key in list(self.partitions_to_backup.keys()):
            for report_dict in vg_state_dict['report']:
                for vg_dict in report_dict['vg']:
                    if 'pv_name' in vg_dict.keys(
                    ) and partition_key == vg_dict['pv_name']:
                        if 'vg_name' in vg_dict.keys():
                            vg_name = vg_dict['vg_name']
                        else:
                            GLib.idle_add(
                                ErrorMessageModalPopup.
                                display_nonfatal_warning_message, self.builder,
                                "Could not find volume group name vg_name in "
                                + str(vg_dict))
                            # TODO: Re-evaluate how exactly Clonezilla uses /NOT_FOUND and whether introducing it here
                            # TODO: could improve Rescuezilla/Clonezilla interoperability.
                            continue
                        if 'pv_uuid' in vg_dict.keys():
                            pv_uuid = vg_dict['pv_uuid']
                        else:
                            GLib.idle_add(
                                ErrorMessageModalPopup.
                                display_nonfatal_warning_message, self.builder,
                                "Could not find physical volume UUID pv_uuid in "
                                + str(vg_dict))
                            continue
                        relevant_vg_name_dict[vg_name] = partition_key
                        lvm_vg_dev_list_filepath = os.path.join(
                            self.dest_dir, "lvm_vg_dev.list")
                        with open(lvm_vg_dev_list_filepath,
                                  'a+') as filehandle:
                            filehandle.write(vg_name + " " + partition_key +
                                             " " + pv_uuid + "\n")

        lv_state_dict = Lvm.get_logical_volume_state_dict(self.logger)
        for report_dict in lv_state_dict['report']:
            for lv_dict in report_dict['lv']:
                # Only consider VGs that match the partitions to backup list
                if 'vg_name' in lv_dict.keys(
                ) and lv_dict['vg_name'] in relevant_vg_name_dict.keys():
                    vg_name = lv_dict['vg_name']
                    if 'lv_path' in lv_dict.keys():
                        lv_path = lv_dict['lv_path']
                    else:
                        GLib.idle_add(
                            ErrorMessageModalPopup.
                            display_nonfatal_warning_message, self.builder,
                            "Could not find lv_path name in " + str(lv_dict))
                        continue
                    file_command_process, flat_command_string, failed_message = Utility.run(
                        "logical volume file info",
                        ["file", "--dereference", "--special-files", lv_path],
                        use_c_locale=True,
                        logger=self.logger)
                    if file_command_process.returncode != 0:
                        with self.summary_message_lock:
                            self.summary_message += failed_message
                        GLib.idle_add(self.completed_backup, False,
                                      failed_message)
                        return

                    output = file_command_process.stdout.split(
                        " ", maxsplit=1)[1].strip()
                    lvm_logv_list_filepath = os.path.join(
                        self.dest_dir, "lvm_logv.list")
                    # Append to file
                    with open(lvm_logv_list_filepath, 'a+') as filehandle:
                        filehandle.write(lv_path + "  " + output + "\n")

                    if 'lv_dm_path' in lv_dict.keys():
                        # Device mapper path, eg /dev/mapper/vgtest-lvtest
                        lv_dm_path = lv_dict['lv_dm_path']
                    else:
                        GLib.idle_add(
                            self.completed_backup, False,
                            "Could not find lv_dm_path name in " +
                            str(lv_dict))
                        return

                    if lv_dm_path in self.drive_state.keys(
                    ) and 'partitions' in self.drive_state[lv_dm_path].keys():
                        # Remove the partition key associated with the volume group that contains this LVM logical volume
                        # eg, /dev/sdc1 with detected filesystem, and replace it with  the logical volume filesystem.
                        # In other words, don't backup both the /dev/sdc1 device node AND the /dev/mapper node.
                        long_partition_key = relevant_vg_name_dict[
                            lv_dict['vg_name']]
                        self.partitions_to_backup.pop(long_partition_key, None)
                        for logical_volume in self.drive_state[lv_dm_path][
                                'partitions'].keys():
                            # Use the system drive state to get the exact filesystem for this /dev/mapper/ node,
                            # as derived from multiple sources (parted, lsblk etc) like how Clonezilla does it.
                            self.partitions_to_backup[
                                lv_path] = self.drive_state[lv_dm_path][
                                    'partitions'][logical_volume]
                            self.partitions_to_backup[lv_path]['type'] = 'part'

                    lvm_vgname_filepath = os.path.join(
                        self.dest_dir, "lvm_" + vg_name + ".conf")
                    # TODO: Evaluate the Clonezilla message from 2013 message that this command won't work on NFS
                    # TODO: due to a vgcfgbackup file lock issue.
                    vgcfgbackup_process, flat_command_string, failed_message = Utility.run(
                        "Saving LVM VG config " + lvm_vgname_filepath, [
                            "vgcfgbackup", "--file", lvm_vgname_filepath,
                            vg_name
                        ],
                        use_c_locale=True,
                        logger=self.logger)
                    if vgcfgbackup_process.returncode != 0:
                        with self.summary_message_lock:
                            self.summary_message += failed_message
                        GLib.idle_add(self.completed_backup, False,
                                      failed_message)
                        return

        filepath = os.path.join(self.dest_dir, "dev-fs.list")
        with open(filepath, 'w') as filehandle:
            filehandle.write('# <Device name>   <File system>\n')
            filehandle.write(
                '# The file systems detected below are a combination of several sources. The values may differ from `blkid` and `parted`.\n'
            )
            for partition_key in self.partitions_to_backup.keys():
                filesystem = self.partitions_to_backup[partition_key][
                    'filesystem']
                filehandle.write('%s %s\n' % (partition_key, filesystem))

        partition_number = 0
        for partition_key in self.partitions_to_backup.keys():
            partition_number += 1
            total_progress_float = Utility.calculate_progress_ratio(
                0, partition_number, len(self.partitions_to_backup.keys()))
            GLib.idle_add(self.update_backup_progress_bar,
                          total_progress_float)
            is_unmounted, message = Utility.umount_warn_on_busy(partition_key)
            if not is_unmounted:
                self.logger.write(message)
                with self.summary_message_lock:
                    self.summary_message += message + "\n"
                GLib.idle_add(self.completed_backup, False, message)

            short_device_node = re.sub('/dev/', '', partition_key)
            short_device_node = re.sub('/', '-', short_device_node)
            filesystem = self.partitions_to_backup[partition_key]['filesystem']

            if 'type' in self.partitions_to_backup[partition_key].keys() and 'extended' in \
                    self.partitions_to_backup[partition_key]['type']:
                self.logger.write("Detected " + partition_key +
                                  " as extended partition. Backing up EBR")
                filepath = os.path.join(self.dest_dir,
                                        short_device_node + "-ebr")
                process, flat_command_string, failed_message = Utility.run(
                    "Saving " + filepath, [
                        "dd", "if=" + partition_key, "of=" + filepath,
                        "bs=512", "count=1"
                    ],
                    use_c_locale=False,
                    logger=self.logger)
            if process.returncode != 0:
                with self.summary_message_lock:
                    self.summary_message += failed_message
                GLib.idle_add(self.completed_backup, False, failed_message)
                return

            if filesystem == 'swap':
                filepath = os.path.join(
                    self.dest_dir, "swappt-" + short_device_node + ".info")
                with open(filepath, 'w') as filehandle:
                    uuid = ""
                    label = ""
                    if 'uuid' in self.partitions_to_backup[partition_key].keys(
                    ):
                        uuid = self.partitions_to_backup[partition_key]['uuid']
                    if 'label' in self.partitions_to_backup[
                            partition_key].keys():
                        label = self.partitions_to_backup[partition_key][
                            'label']
                    filehandle.write('UUID="%s"\n' % uuid)
                    filehandle.write('LABEL="%s"\n' % label)
                    with self.summary_message_lock:
                        self.summary_message += _(
                            "Successful backup of swap partition {partition_name}"
                        ).format(partition_name=partition_key) + "\n"
                continue

            # Clonezilla uses -q2 priority by default (partclone > partimage > dd).
            # PartImage does not appear to be maintained software, so for simplicity, Rescuezilla is using a
            # partclone > partclone.dd priority
            # [1] https://clonezilla.org/clonezilla-live/doc/01_Save_disk_image/advanced/09-advanced-param.php

            # Expand upon Clonezilla's ocs-get-comp-suffix() function
            compression_suffix = "gz"
            split_size = "4GB"
            # Partclone dd blocksize (16MB)
            partclone_dd_bs = "16777216"
            # TODO: Re-enable APFS support -- currently partclone Apple Filesystem is not used because it's too unstable [1]
            # [1] https://github.com/rescuezilla/rescuezilla/issues/65
            if shutil.which("partclone." +
                            filesystem) is not None and filesystem != "apfs":
                partclone_cmd_list = [
                    "partclone." + filesystem, "--logfile",
                    "/var/log/partclone.log", "--clone", "--source",
                    partition_key, "--output", "-"
                ]
                filepath = os.path.join(
                    self.dest_dir, short_device_node + "." + filesystem +
                    "-ptcl-img." + compression_suffix + ".")
                split_cmd_list = [
                    "split", "--suffix-length=2", "--bytes=" + split_size, "-",
                    filepath
                ]
            elif shutil.which("partclone.dd") is not None:
                partclone_cmd_list = [
                    "partclone.dd", "--buffer_size=" + partclone_dd_bs,
                    "--logfile", "/var/log/partclone.log", "--source",
                    partition_key, "--output", "-"
                ]
                filepath = os.path.join(
                    self.dest_dir, short_device_node + ".dd-ptcl-img." +
                    compression_suffix + ".")
                split_cmd_list = [
                    "split", "--suffix-length=2", "--bytes=" + split_size, "-",
                    filepath
                ]
            else:
                GLib.idle_add(self.completed_backup, False,
                              "Partclone not found.")
                return

            filesystem_backup_message = _(
                "Backup {partition_name} containing filesystem {filesystem} to {destination}"
            ).format(partition_name=partition_key,
                     filesystem=filesystem,
                     destination=filepath)
            GLib.idle_add(self.update_main_statusbar,
                          filesystem_backup_message)
            self.logger.write(filesystem_backup_message)

            gzip_cmd_list = ["gzip", "--stdout"]
            self.proc['partclone_backup_' + partition_key] = subprocess.Popen(
                partclone_cmd_list,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                env=env,
                encoding='utf-8')

            self.proc['gzip_' + partition_key] = subprocess.Popen(
                gzip_cmd_list,
                stdin=self.proc['partclone_backup_' + partition_key].stdout,
                stdout=subprocess.PIPE,
                env=env,
                encoding='utf-8')

            self.proc['split_' + partition_key] = subprocess.Popen(
                split_cmd_list,
                stdin=self.proc['gzip_' + partition_key].stdout,
                stdout=subprocess.PIPE,
                env=env,
                encoding='utf-8')

            # Process partclone output. Partclone outputs an update every 3 seconds, so processing the data
            # on the current thread, for simplicity.
            # Poll process.stdout to show stdout live
            while True:
                if self.requested_stop:
                    return

                output = self.proc['partclone_backup_' +
                                   partition_key].stderr.readline()
                if self.proc['partclone_backup_' +
                             partition_key].poll() is not None:
                    break
                if output:
                    temp_dict = Partclone.parse_partclone_output(output)
                    if 'completed' in temp_dict.keys():
                        total_progress_float = Utility.calculate_progress_ratio(
                            temp_dict['completed'] / 100.0, partition_number,
                            len(self.partitions_to_backup.keys()))
                        GLib.idle_add(self.update_backup_progress_bar,
                                      total_progress_float)
                    if 'remaining' in temp_dict.keys():
                        GLib.idle_add(
                            self.update_backup_progress_status,
                            filesystem_backup_message + "\n\n" + output)
            rc = self.proc['partclone_backup_' + partition_key].poll()

            self.proc['partclone_backup_' + partition_key].stdout.close(
            )  # Allow p1 to receive a SIGPIPE if p2 exits.
            self.proc['gzip_' + partition_key].stdout.close(
            )  # Allow p2 to receive a SIGPIPE if p3 exits.
            output, err = self.proc['partclone_backup_' +
                                    partition_key].communicate()
            self.logger.write("Exit output " + str(output) + "stderr " +
                              str(err))
            if self.proc['partclone_backup_' + partition_key].returncode != 0:
                partition_summary = _(
                    "<b>Failed to backup partition</b> {partition_name}"
                ).format(partition_name=partition_key) + "\n"
                with self.summary_message_lock:
                    self.summary_message += partition_summary
                self.at_least_one_non_fatal_error = True
                proc_stdout = self.proc['partclone_backup_' +
                                        partition_key].stdout
                proc_stderr = self.proc['partclone_backup_' +
                                        partition_key].stderr
                extra_info = "\nThe command used internally was:\n\n" + flat_command_string + "\n\n" + "The output of the command was: " + str(
                    proc_stdout) + "\n\n" + str(proc_stderr)
                compression_stderr = self.proc['gzip_' + partition_key].stderr
                if compression_stderr is not None and compression_stderr != "":
                    extra_info += "\n\n" + str(
                        gzip_cmd_list) + " stderr: " + compression_stderr

                # TODO: Try to backup again, but using partclone.dd
                GLib.idle_add(
                    ErrorMessageModalPopup.display_nonfatal_warning_message,
                    self.builder, partition_summary + extra_info)

            else:
                with self.summary_message_lock:
                    self.summary_message += _(
                        "Successful backup of partition {partition_name}"
                    ).format(partition_name=partition_key) + "\n"

        # GLib.idle_add(self.update_progress_bar, (i + 1) / len(self.restore_mapping_dict.keys()))
        if self.requested_stop:
            return

        progress_ratio = i / len(self.partitions_to_backup.keys())
        i += 1
        # Display 100% progress for user
        GLib.idle_add(self.update_backup_progress_bar, progress_ratio)
        sleep(1.0)
        """
            partclone_cmd_list = ["partclone", "--logfile", "/tmp/rescuezilla_logfile.txt", "--overwrite", "/dev/"]

              if [ "$fs_p" != "dd" ]; then
    cmd_partclone="partclone.${fs_p} $PARTCLONE_SAVE_OPT -L $partclone_img_info_tmp -c -s $source_dev --output - | $compress_prog_opt"
  else
    # Some parameters for partclone.dd are not required. Here "-c" is not provided by partclone.dd when saving.
    cmd_partclone="partclone.${fs_p} $PARTCLONE_SAVE_OPT --buffer_size ${partclone_dd_bs} -L $partclone_img_info_tmp -s $source_dev --output - | $compress_prog_opt"
  fi
  case "$VOL_LIMIT" in
    [1-9]*)
       # $tgt_dir/${tgt_file}.${fs_pre}-img. is prefix, the last "." is necessary make the output file is like hda1.${fs_pre}-img.aa, hda1.${fs_pre}-img.ab. We do not add -d to make it like hda1.${fs_pre}-img.00, hda1.${fs_pre}-img.01, since it will confuse people that it looks like created by partimage (hda1.${fs_pre}-img.000, hda1.${fs_pre}-img.001)
       cmd_partclone="${cmd_partclone} | split -a $split_suf_len -b ${VOL_LIMIT}MB - $tgt_dir/$(to_filename ${tgt_file}).${fs_pre}-img.${comp_suf}. 2> $split_error"
       ;;
    *)
       cmd_partclone="${cmd_partclone} > $tgt_dir/$(to_filename ${tgt_file}).${fs_pre}-img.${comp_suf} 2> $split_error"
       ;;
  esac
  echo "Run partclone: $cmd_partclone" | tee --append ${OCS_LOGFILE}
  LC_ALL=C eval "(${cmd_partclone} && exit \${PIPESTATUS[0]})"


            cmd_partimage = "partimage $DEFAULT_PARTIMAGE_SAVE_OPT $PARTIMAGE_SAVE_OPT -B gui=no save $source_dev stdout | $compress_prog_opt"
            #case
            #"$VOL_LIMIT" in
            #[1 - 9] *)
            # "$tgt_dir/${tgt_file}." is prefix, the last "." is necessary
            # make the output file is like hda1.aa, hda1.ab.
            # We do not add -d to make it like hda1.00, hda1.01, since it will confuse people that it looks like created by partimage (hda1.000, hda1.001)
            cmd_partimage = "${cmd_partimage} | split -a $split_suf_len -b ${VOL_LIMIT}MB - $tgt_dir/${tgt_file}."
            """

        # Do checksum
        # IMG_ID=$(LC_ALL=C sha512sum $img_dir/clonezilla-img | awk -F" " '{print $1}')" >> $img_dir/Info-img-id.txt

        GLib.idle_add(self.completed_backup, True, "")