Example #1
0
def devices():
    ''' Return list of devices that may have filesystems. '''

    # block devices may have filesystems
    if IS_PY2:
        raw_output = sh.lsblk('--noheadings', '--list', '--paths', '--output=NAME').stdout
    else:
        raw_output = sh.lsblk('--noheadings', '--list', '--paths', '--output=NAME').stdout.decode()
    devices = raw_output.strip().split('\n')
    return devices
Example #2
0
    def __init__(self, mount_point: str) -> None:
        super().__init__()

        # In case Btrfs subvolumes are being used, lsblk might not be able to
        # properly determine the mount points.  To work around this, we first
        # determine the file system UUID and use it to find the correct
        # partition.
        file_system = FileSystem(mount_point)

        # Get the device name, path to the device node, file system UUID,
        # partition table type and device type for all block devices.
        try:
            root = json.loads(str(
                sh.lsblk("-J", "-o", "NAME,PATH,UUID,PTTYPE,TYPE")),
                              object_hook=lambda kwargs: timewarp.namespace.
                              Namespace(**kwargs))
        except sh.CommandNotFound:
            raise timewarp.error.InitializationError(
                "lsblk: Command not found")

        # Try to find the partition.
        partition, found = self._find_partition(root, file_system.uuid)

        if found:
            self.path = partition.path
            self.uuid = partition.uuid
            self.partition_table_type = partition.pttype
        else:
            self.path = None
            self.uuid = None
            self.partition_table_type = None
Example #3
0
 def get_filesystem_name(device, partition=1):
     """
     :param device:      Urządzenie
     :param partition:   Numer partycji
     :return: System plików na partycji
     """
     return re.search("\n\w*.(\w*)", str(sh.lsblk(device + str(partition), fs=True))).group(1)
Example #4
0
def get_fs_info(dev):
    if dev is None:
        return []
    info = lsblk('-I', 8, '-p', '-o', '+NAME,FSTYPE,SIZE,MOUNTPOINT,PARTTYPE',
                 '-J', dev)
    info = json.loads(info.stdout)
    return info['blockdevices']
def collect_mounted_blocks():
    result = {}
    devices = json.loads(sh.lsblk('-J').stdout)
    for device in devices['blockdevices']:
        for child in device.get('children', []):
            if child['mountpoint']:
                result[child['name']] = child['mountpoint']
    return result
Example #6
0
 def get_filesystem_name(device, partition=1):
     """
     :param device:      Urządzenie
     :param partition:   Numer partycji
     :return: System plików na partycji
     """
     return re.search("\n\w*.(\w*)",
                      str(sh.lsblk(device + str(partition),
                                   fs=True))).group(1)
Example #7
0
 def process_devicemap(self):
     if self.lodev:
         dev_path = self.lodev
     else:
         dev_path = self.path
     root = json.loads(
         str(
             sh.lsblk("-pJ", "-o", self.LSBLK_KEYS, dev_path).stdout,
             'utf8'))["blockdevices"][0]
     try:
         self.process_sub_devicemap(root["children"])
     except KeyError:
         log.debug(self.RECURSION_STOP_MSG)
Example #8
0
    def set_fsattrs(self):
        log.debug("Getting filesystem attributes {0}".format(self.path))
        try:
            me = json.loads(
                str(
                    sh.lsblk("-pJ", "-o", self.LSBLK_KEYS, self.path).stdout,
                    'utf8'))["blockdevices"][0]
            try:
                self.uuid = me["uuid"]
                log.debug("GOT UUID: {0}".format(self.uuid))
            except KeyError:
                self.uuid = None
            try:
                self.fstype = me["fstype"]
                log.debug("GOT FSTYPE: {0}".format(self.fstype))
            except KeyError:
                self.fstype = None

            try:
                self.label = me["label"]
            except KeyError:
                self.label = None

        except sh.ErrorReturnCode_32:
            # Not a block device falling back to blkid
            cmd = str(sh.blkid("-o", "export", self.path).stdout, 'utf8')
            try:
                self.uuid = re.search("UUID=(.*)", cmd).group(1)
            except (TypeError, AttributeError):
                self.uuid = None
            try:
                self.fstype = re.search("TYPE=(.*)", cmd).group(1)
            except (TypeError, AttributeError):
                self.fstype = None
            try:
                self.label = re.search("LABEL=(.*)", cmd).group(1)
            except (TypeError, AttributeError):
                self.label = None

        if str(self.fstype) not in self.SUPPORTED_FS:
            log.error("{0} is out of {1} : {2}".format(self.fstype,
                                                       self.SUPPORTED_FS,
                                                       self.path))
            raise IncompatibleFS("Not working with {0} fstype {1}".format(
                self.path, self.fstype))
        return True
Example #9
0
def describe_devices(target):
    """Describe all devices for diagnosing general issues."""
    try:
        all_devices = os.listdir("/dev/")
        click.echo(_("/dev/ contains: {}").format(all_devices))
        click.echo(sh.pvs("-a"))

        for image_id, drive in target:
            click.echo(
                _("General information about device {drive} for {image_id}:").format(
                    drive=drive, image_id=image_id
                )
            )
            click.echo(str(sh.fdisk("-l", drive)))

            # Because udev device initialization is weird in Docker, we have to "test"
            # each partition before we can see useful details about their filesystems.
            # Because udev data is used under the covers by lsblk, this test also needs
            # to happen before calling lsblk.
            partitions = get_partitions(drive)
            for partition in partitions:
                # get the "/devices/..." block path
                device_block_path = sh.udevadm("info", "-q", "path", "-n", partition)
                # test the device on that path so udev refreshes its knowledge
                sh.udevadm("test", "-a", "-p", device_block_path.strip())
                # then we can ask for info and hopefully get a useful response
                click.echo(sh.udevadm("info", "--query=all", f"--name={partition}"))

            click.echo(
                sh.lsblk(
                    "--all",
                    "--ascii",
                    "--output",
                    "NAME,TYPE,FSTYPE,PARTLABEL,MOUNTPOINT",
                    drive,
                )
            )
    except Exception as e:
        click.echo(_("Unexpected error in describe_devices: {0}").format(e))
Example #10
0
    def to_computer(self, text):
        f = open(
            TMP_FILE, 'w'
        )  # write mode clears any previous content from the file if it exists

        if self.checks[0]:
            print("Saving: inxi to file")
            f.write(
                HEADER.format("Inxi -Fxzc0", "Listing computer information"))
            try:
                f.write(str(inxi('-Fxxxzc0')))
            except:
                " 'inxi' not found, install it to get this info"
            f.write('\n')

        if self.checks[1]:
            print("Getting info about installed graphical driver")
            f.write(
                HEADER.format("Installed drivers",
                              "Shows which graphic driver is installed"))
            try:
                f.write(str(mhwd('-li')))
            except:
                print(" 'mhwd' not found, this is not Manjaro?")
            f.write('\n')

        if self.checks[2]:
            print("Getting list of all drivers supported on detected gpu's")
            f.write(
                HEADER.format(
                    "Available drivers",
                    "list of all drivers supported on detected gpu's"))
            try:
                f.write(str(mhwd('-l')))
            except:
                print(" 'mhwd' not found, this is not Manjaro?")
            # f.write('\n')

        if self.checks[3]:
            print('hwinfo -graphic card')
            # os.system('hwinfo --gfxcard')
            f.write(HEADER.format("hwinfo --gfxcard",
                                  "Show Graphic Card info"))
            try:
                f.write(str(hwinfo('--gfxcard')))
            except:
                print('hwinfo graphic card info error')
                f.write('hwinfo graphic card info error')
            f.write('\n')

        if self.checks[4]:
            print('memory info')
            # os.system('free -h')
            f.write(HEADER.format("Memory Info", "Info about Memory and Swap"))
            try:
                f.write(str(free(' -h')))
            except:
                print('memory info error')
                f.write('memory info error')
            f.write('\n')

        if self.checks[5]:
            print('disk info')
            # os.system('lsblk')
            f.write(HEADER.format("Disk Info", "Disks and Partitions"))
            try:
                f.write(str(lsblk()))
            except:
                print('lsblk error')
                f.write('lsblk error')
            f.write('\n')

        if self.checks[6]:
            print('free disk space')
            # os.system('df')
            f.write(
                HEADER.format("Free Disk Space", "Free space per pertition"))
            try:
                f.write(str(df()))
            except:
                print('free disk space error')
                f.write('free disk space error')
            f.write('\n')

        if self.checks[7]:
            print('blockdev')
            # os.system('blockdev --getalignoff /dev/sda')
            f.write(HEADER.format("Disk Alignment", "0 is OK"))
            try:
                # f.write(str(os.system('blockdev --getalignoff /dev/sda')))
                f.write(str(blockdev(' --getalignoff /dev/sda')))
            except:
                print('error with blockdev')
                f.write('error with blockdev')
            f.write('\n')

        if self.checks[8]:
            print('BIOS / UEFI')
            # os.system('test -d /sys/firmware/efi && echo UEFI || echo BIOS')
            # os.system('parted -l | grep "Partition Table: "')
            f.write(HEADER.format("parted -l", "BIOS+msdos or UEFI+gpt"))
            try:
                f.write(
                    str(test(
                        ' -d /sys/firmware/efi && echo UEFI || echo BIOS')))
                # f.write(str(test -d(' /sys/firmware/efi && echo UEFI || echo BIOS')))
                f.write(str(parted(' -l | grep "Partition Table: "')))
                # f.write(str(parted -l(' | grep "Partition Table: "')))
            except:
                print('error with BIOS / UEFI')
                f.write('error with BIOS / UEFI')
            f.write('\n')

        if self.checks[9]:
            print("Saving: Xorg.0.log to file")
            f.write(
                HEADER.format("Xorg.0.log",
                              "searching for: failed, error & (WW) keywords"))
            try:
                f.write(
                    look_in_file('/var/log/Xorg.0.log',
                                 ['failed', 'error', '(WW)']))
            except FileNotFoundError:
                print("/var/log/Xorg.0.log not found!")
                f.write("Xorg.0.log not found!")
            f.write('\n')

        if self.checks[10]:
            print("Saving: Xorg.1.log to file")
            f.write(
                HEADER.format("Xorg.1.log",
                              "searching for: failed, error & (WW) keywords"))
            try:
                f.write(
                    look_in_file('/var/log/Xorg.1.log',
                                 ['failed', 'error', '(WW)']))
            except FileNotFoundError:
                print("/var/log/Xorg.1.log not found!")
                f.write("Xorg.1.log not found!")
            f.write('\n')

        if self.checks[11]:
            print("Saving: pacman.log to file")
            f.write(
                HEADER.format(
                    "pacman.log",
                    "searching for: pacsave, pacnew, pacorig keywords"))
            try:
                f.write(
                    look_in_file('/var/log/pacman.log',
                                 ['pacsave', 'pacnew', 'pacorig']))
            except FileNotFoundError:
                print(
                    "/var/log/pacman.log not found, this is not Manjaro or Arch based Linux?"
                )
                f.write("pacman.log not found!  Not Arch based OS?")
            f.write('\n')

        if self.checks[12]:
            print("Saving: journalctl (emergency) to file")
            os.system("journalctl -b > /tmp/journalctl.txt")
            f.write(
                HEADER.format("journalctl.txt",
                              "Searching for: Emergency keywords"))
            f.write(
                look_in_file('/tmp/journalctl.txt',
                             ['emergency', 'Emergency', 'EMERGENCY']))
            f.write('\n')

        if self.checks[13]:
            print("Saving: journalctl (alert) to file")
            os.system("journalctl -b > /tmp/journalctl.txt")
            f.write(
                HEADER.format("journalctl.txt",
                              "Searching for: Alert keywords"))
            f.write(
                look_in_file('/tmp/journalctl.txt',
                             ['alert', 'Alert', 'ALERT']))
            f.write('\n')

        if self.checks[14]:
            print("Saving: journalctl (critical) to file")
            os.system("journalctl -b > /tmp/journalctl.txt")
            f.write(
                HEADER.format("journalctl.txt",
                              "Searching for: Critical keywords"))
            f.write(
                look_in_file('/tmp/journalctl.txt',
                             ['critical', 'Critical', 'CRITICAL']))
            f.write('\n')

        if self.checks[15]:
            print("Saving: journalctl (failed) to file")
            os.system("journalctl -b > /tmp/journalctl.txt")
            f.write(
                HEADER.format("journalctl.txt",
                              "Searching for: Failed keywords"))
            f.write(
                look_in_file('/tmp/journalctl.txt',
                             ['failed', 'Failed', 'FAILED']))
            f.write('\n')

        if self.checks[16]:
            print("Saving: rc.log to file")
            f.write(
                HEADER.format("rc.log",
                              "OpenRc only! searching for: WARNING: keywords"))
            try:
                f.write(look_in_file('/var/log/rc.log', ['WARNING:']))
            except FileNotFoundError:
                print("/var/log/rc.log not found!     Systemd based OS?")
                f.write("rc.log not found!   Systemd based OS?")
            f.write('\n')

        if self.checks[17]:
            print('openrc services status')
            # os.system('rc-status --all')
            f.write(HEADER.format("Services", "OpenRc only!"))
            try:
                f.write(str(rc - status(' --all')))
            except:
                print("rc-status all error")
                f.write("rc.log not found!   Systemd based OS?")
            f.write('\n')

        f.close()
Example #11
0
 def ui_command_lsblk(self):
     return sh.lsblk()
Example #12
0
def real_fs(part):
    info = lsblk("-no", "name,fstype", part).strip()
    info = info.split(" ")
    printd(info)

    return info[1]