Exemplo n.º 1
0
    def test(self):
        """
        test case
        :return:
        """
        if not os.path.exists("/dev/watchdog"):
            os.system("modprobe softdog")

        os.chdir(self.test_dir)
        try:
            timeout = Command("./watchdog -g").get_str(
                regex="^Watchdog timeout is (?P<timeout>[0-9]*) seconds.$",
                regex_group="timeout")
            timeout = int(timeout)
            if timeout > self.max_timeout:
                Command("./watchdog -s %d" % self.max_timeout).echo()
        except CertCommandError as e:
            print(e)
            print("Set/get watchdog timeout failed.")
            return False

        ui = CommandUI()
        if ui.prompt_confirm("System will reboot, are you ready?"):
            print("")
            sys.stdout.flush()
            os.system("sync")
            os.system("./watchdog -t")
            time.sleep(5)
            return False
        else:
            print("")
            return False
Exemplo n.º 2
0
 def __init__(self):
     Test.__init__(self)
     self.requirements = [
         "dvd+rw-tools", "genisoimage", "wodim", "util-linux"
     ]
     self.method = None
     self.device = None
     self.type = None
     self.args = None
     self.com_ui = CommandUI()
     self.test_dir = "/usr/share/doc"
Exemplo n.º 3
0
    def test(self):
        """
        Test case
        :return:
        """
        try:
            Command("cat /proc/cmdline").get_str(r"crashkernel=[^\ ]*")
        except Exception:
            print("Error: no crashkernel found.")
            return False

        config = ConfigFile(self.kdump_conf)
        if not config.get_parameter("path"):
            config.add_parameter("path", self.vmcore_path)
        else:
            self.vmcore_path = config.get_parameter("path")

        if config.get_parameter("kdump_obj") == "kbox":
            config.remove_parameter("kdump_obj")
            config.add_parameter("kdump_obj", "all")

        try:
            Command("systemctl restart kdump").run()
            Command("systemctl status kdump").get_str(regex="Active: active",
                                                      single_line=False)
        except Exception:
            print("Error: kdump service not working.")
            return False

        print("kdump config:")
        print("#############")
        config.dump()
        print("#############")

        com_ui = CommandUI()
        if com_ui.prompt_confirm("System will reboot, are you ready?"):
            print("\ntrigger crash...")
            sys.stdout.flush()
            os.system("sync")
            os.system("echo c > /proc/sysrq-trigger")
            time.sleep(30)
            return False
        else:
            print("")
            return False
Exemplo n.º 4
0
 def __init__(self):
     Test.__init__(self)
     self.requirements = ["usbutils"]
     self.com_ui = CommandUI()
Exemplo n.º 5
0
class UsbTest(Test):
    """
    Usb test
    """
    def __init__(self):
        Test.__init__(self)
        self.requirements = ["usbutils"]
        self.com_ui = CommandUI()

    def test(self):
        """
        Test case
        :return:
        """
        print("USB device:")
        Command("lsusb -t").echo()
        print("")
        sys.stdout.flush()
        plugged_device = self.get_usb()

        print("USB device plug/unplug test begin...")
        while True:
            print("#############")
            while True:
                print("Please plug in a USB device.")
                if self.com_ui.prompt_confirm("Done well?"):
                    break
            time.sleep(1)

            new_plugged = self.get_usb()
            if len(new_plugged) <= len(plugged_device):
                print("Error: no USB device add.")
                return False

            new_device = None
            for device in new_plugged:
                if device not in plugged_device:
                    print("Found new USB device.\n")
                    new_device = device
                    break

            if not new_device:
                print("Error: new USB device not found.")
                return False

            print("USB device:")
            Command("lsusb -t").echo()
            print("")
            sys.stdout.flush()
            plugged_device = new_plugged
            while True:
                print("Please unplug the USB device you plugged in just now.")
                if self.com_ui.prompt_confirm("Done well?"):
                    break
            time.sleep(1)

            new_plugged = self.get_usb()
            if len(new_plugged) >= len(plugged_device):
                print("Error: no USB device unplug.")
                return False

            if new_device in new_plugged:
                print("Error: the USB device can still be found.")
                return False
            else:
                print("USB device unplugged.\n")

            print("USB device:")
            Command("lsusb -t").echo()
            print("#############\n")
            sys.stdout.flush()
            plugged_device = new_plugged

            if self.com_ui.prompt_confirm("All usb sockets have been tested?"):
                return True

    def get_usb(self):
        """
        Get usb
        :return:
        """
        devices = CertDevice().get_devices()
        usb_devices = list()
        for device in devices:
            if (device.get_property("SUBSYSTEM") != "usb" or
                device.get_property("DEVTYPE") != "usb_device" or
                device.get_property("ID_BUS") != "usb" or
                device.get_property("BUSNUM") == "" or
                    device.get_property("DEVNUM") == ""):
                continue
            else:
                usb_devices.append(device.path)
        return usb_devices
Exemplo n.º 6
0
class CDRomTest(Test):
    """
    CDRom Test
    """
    def __init__(self):
        Test.__init__(self)
        self.requirements = [
            "dvd+rw-tools", "genisoimage", "wodim", "util-linux"
        ]
        self.method = None
        self.device = None
        self.type = None
        self.args = None
        self.com_ui = CommandUI()
        self.test_dir = "/usr/share/doc"

    def setup(self, args=None):
        """
        The Setup before testing
        :param args:
        :return:
        """
        self.args = args or argparse.Namespace()
        self.device = getattr(args, "device", None)
        self.type = self.get_type(self.device)
        self.get_mode(self.type)

    def test(self):
        """
        Test case
        :return:
        """
        if not (self.method and self.device and self.type):
            return False

        if self.method not in dir(self):
            return False

        devname = self.device.get_property("DEVNAME")
        Command("eject %s" % devname).run(ignore_errors=True)
        while True:
            print("Please insert %s disc into %s, then close the tray manually."\
                  % (self.type.lower(), devname))
            if self.method == "write_test":
                print("  tips:disc should be new.")
            elif self.method == "read_test":
                print("  tips:disc should not be blank.")
            if self.com_ui.prompt_confirm("Done well?"):
                break
        Command("eject -t %s" % devname).run(ignore_errors=True)
        print("Waiting media..).")
        time.sleep(20)

        if not getattr(self, self.method)():
            return False
        return True

    def get_type(self, device):
        """
        Get the type of CDROM
        :param device:
        :return:
        """
        if not device:
            return None

        bd_types = ["BD_RE", "BD_R", "BD"]
        dvd_types = ["DVD_RW", "DVD_PLUS_RW", "DVD_R", "DVD_PLUS_R", "DVD"]
        cd_types = ["CD_RW", "CD_R", "CD"]
        for bd_type in bd_types:
            if device.get_property("ID_CDROM_" + bd_type) == "1":
                return bd_type
        for dvd_type in dvd_types:
            if device.get_property("ID_CDROM_" + dvd_type) == "1":
                return dvd_type
        for cd_type in cd_types:
            if device.get_property("ID_CDROM_" + cd_type) == "1":
                return cd_type

        print("Can not find proper test-type for %s." % device.get_name())
        return None

    def get_mode(self, device_type):
        """
        Get the read-write mode of CDROM
        :param device_type:
        :return:
        """
        if not device_type:
            return

        if "RW" in device_type or "RE" in device_type:
            self.method = "rw_test"
        elif "_R" in device_type:
            self.method = "write_test"
        else:
            self.method = "read_test"

    def rw_test(self):
        """
        RW mode test of CDROM
        :return:
        """
        try:
            devname = self.device.get_property("DEVNAME")
            Command("umount %s" % devname).run(ignore_errors=True)
            if "BD" in self.type:
                print("Formatting ...")
                sys.stdout.flush()
                Command("dvd+rw-format -format=full %s 2>/dev/null" %
                        devname).echo()
                self.reload_disc(devname)
                sys.stdout.flush()
                return self.write_test()
            elif "DVD_PLUS" in self.type:
                print("Formatting ...")
                sys.stdout.flush()
                Command("dvd+rw-format -force %s 2>/dev/null" % devname).echo()
                self.reload_disc(devname)
                sys.stdout.flush()
                return self.write_test()
            else:
                print("Blanking ...")
                sys.stdout.flush()
                # blankCommand = Command("cdrecord -v dev=%s blank=fast" % devname).echo()
                Command("cdrecord -v dev=%s blank=fast" % devname).echo()
                self.reload_disc(devname)
                sys.stdout.flush()
                return self.write_test()
        except CertCommandError:
            return False

    def write_test(self):
        """
        Write mode test of CDROM
        :return:
        """
        try:
            devname = self.device.get_property("DEVNAME")
            Command("umount %s" % devname).run(ignore_errors=True)
            if "BD" in self.type or "DVD_PLUS" in self.type:
                Command("growisofs -Z %s -quiet -R %s" %
                        (devname, self.test_dir)).echo()
                self.reload_disc(devname)
                sys.stdout.flush()
                return True
            else:
                write_opts = "-sao"
                try:
                    command = Command("cdrecord dev=%s -checkdrive" % devname)
                    modes = command.get_str(regex="^Supported modes[^:]*:(?P<modes>.*$)", \
                                            regex_group="modes",
                                            single_line=False, ignore_errors=True)
                    if "TAO" in modes:
                        write_opts = "-tao"
                    if "SAO" in modes:
                        write_opts = "-sao"
                    flags = command.get_str(regex="^Driver flags[^:]*:(?P<flags>.*$)", \
                                            regex_group="flags",
                                            single_line=False, ignore_errors=True)
                    if "BURNFREE" in flags:
                        write_opts += " driveropts=burnfree"
                except CertCommandError as concrete_error:
                    print(concrete_error)

                size = Command("mkisofs -quiet -R -print-size %s " %
                               self.test_dir).get_str()
                blocks = int(size)

                Command(
                    "mkisofs -quiet -R %s | cdrecord -v %s dev=%s fs=32M tsize=%ss -"
                    % (self.test_dir, write_opts, devname, blocks)).echo()
                self.reload_disc(devname)
                sys.stdout.flush()
                return True
        except CertCommandError as concrete_error:
            return False

    def read_test(self):
        """
        Read mode test of CDROM
        :return:
        """
        try:
            devname = self.device.get_property("DEVNAME")
            if os.path.exists("mnt_cdrom"):
                shutil.rmtree("mnt_cdrom")
            os.mkdir("mnt_cdrom")

            print("Mounting media ...")
            Command("umount %s" % devname).echo(ignore_errors=True)
            Command("mount -o ro %s ./mnt_cdrom" % devname).echo()

            size = Command("df %s | tail -n1 | awk '{print $3}'" %
                           devname).get_str()
            size = int(size)
            if size == 0:
                print("Error: blank disc.")
                Command("umount ./mnt_cdrom").run(ignore_errors=True)
                Command("rm -rf ./mnt_cdrom").run(ignore_errors=True)
                return False

            if os.path.exists("device_dir"):
                shutil.rmtree("device_dir")
            os.mkdir("device_dir")

            print("Copying files ...")
            sys.stdout.flush()
            Command("cp -dpRf ./mnt_cdrom/. ./device_dir/").run()

            print("Comparing files ...")
            sys.stdout.flush()
            return_code = self.cmp_tree("mnt_cdrom", "device_dir")
            Command("umount ./mnt_cdrom").run(ignore_errors=True)
            Command("rm -rf ./mnt_cdrom ./device_dir").run(ignore_errors=True)
            return return_code
        except CertCommandError as concrete_error:
            print(concrete_error)
            return False

    def cmp_tree(self, dir1, dir2):
        """
        Compare the differences between the two directories
        :param dir1:
        :param dir2:
        :return:
        """
        if not (dir1 and dir2):
            print("Error: invalid input dir.")
            return False
        try:
            Command("diff -r %s %s" % (dir1, dir2)).run()
            return True
        except CertCommandError:
            print("Error: file comparison failed.")
            return False

    def reload_disc(self, device):
        """
        Reloading the media
        :param device:
        :return:
        """
        if not device:
            return False

        print("Reloading the media ... ")
        sys.stdout.flush()
        try:
            Command("eject %s" % device).run()
            print("tray ejected.")
            sys.stdout.flush()
        except Exception:
            pass

        try:
            Command("eject -t %s" % device).run()
            print("tray auto-closed.\n")
            sys.stdout.flush()
        except Exception:
            print(
                "Could not auto-close the tray, please close the tray manually."
            )
            self.com_ui.prompt_confirm("Done well?")

        time.sleep(20)
        return True
Exemplo n.º 7
0
 def __init__(self):
     Test.__init__(self)
     self.disks = list()
     self.filesystems = ["ext4"]
     self.com_ui = CommandUI()
     self.logpath = ""
Exemplo n.º 8
0
class DiskTest(Test):
    """
    disk test
    """
    def __init__(self):
        Test.__init__(self)
        self.disks = list()
        self.filesystems = ["ext4"]
        self.com_ui = CommandUI()
        self.logpath = ""

    def setup(self, args=None):
        """
        The Setup before testing
        :return:
        """
        try:
            self.args = args or argparse.Namespace()
            self.logpath = getattr(args, "logdir", None) + "/disk.log"
            os.system("echo 'Disk Info: ' >> %s" % self.logpath)
            Command("fdisk -l &>> %s" % self.logpath).echo(ignore_errors=True)
            os.system("echo 'Partition Info: ' >> %s" % self.logpath)
            Command("df -h &>> %s" % self.logpath).echo(ignore_errors=True)
            os.system("echo 'Mount Info: ' >> %s" % self.logpath)
            Command("mount &>> %s" % self.logpath).echo(ignore_errors=True)
            os.system("echo 'Swap Info: ' >> %s" % self.logpath)
            Command("cat /proc/swaps &>> %s" %
                    self.logpath).echo(ignore_errors=True)
            os.system("echo 'LVM Info: ' >> %s" % self.logpath)
            Command("pvdisplay &>> %s" % self.logpath).echo(ignore_errors=True)
            Command("vgdisplay &>> %s" % self.logpath).echo(ignore_errors=True)
            Command("lvdisplay &>> %s" % self.logpath).echo(ignore_errors=True)
            os.system("echo 'Md Info: ' >> %s" % self.logpath)
            Command("cat /proc/mdstat &>> %s" %
                    self.logpath).echo(ignore_errors=True)
            sys.stdout.flush()
        except Exception as concrete_error:
            print("Warning: could not get disk info.\n", concrete_error)

    def test(self):
        """
        start test
        """
        self.get_disk()
        if len(self.disks) == 0:
            print("No suite disk found to test.")
            return False

        self.disks.append("all")
        disk = self.com_ui.prompt_edit("Which disk would you like to test: ",
                                       self.disks[0], self.disks)
        return_code = True
        if disk == "all":
            for disk in self.disks[:-1]:
                if not self.raw_test(disk):
                    return_code = False
                if not self.vfs_test(disk):
                    return_code = False
        else:
            if not self.raw_test(disk):
                return_code = False
            if not self.vfs_test(disk):
                return_code = False
        return return_code

    def get_disk(self):
        """
        get disk info
        """
        self.disks = list()
        disks = list()
        devices = CertDevice().get_devices()
        for device in devices:
            if (device.get_property("DEVTYPE") == "disk" and not
                    device.get_property("ID_TYPE")) or device.\
                    get_property("ID_TYPE") == "disk":
                if "/host" in device.get_property("DEVPATH"):
                    disks.append(device.get_name())

        partition_file = open("/proc/partitions", "r")
        partition = partition_file.read()
        partition_file.close()

        os.system("swapon -a 2>/dev/null")
        swap_file = open("/proc/swaps", "r")
        swap = swap_file.read()
        swap_file.close()

        mdstat_file = open("/proc/mdstat", "r")
        mdstat = mdstat_file.read()
        mdstat_file.close()

        mtab_file = open("/etc/mtab", "r")
        mtab = mtab_file.read()
        mtab_file.close()

        mount_file = open("/proc/mounts", "r")
        mounts = mount_file.read()
        mount_file.close()

        for disk in disks:
            if disk not in partition or ("/dev/%s" % disk) in swap:
                continue
            if ("/dev/%s" % disk) in mounts or ("/dev/%s" % disk) in mtab:
                continue
            if disk in mdstat or os.system(
                    "pvs 2>/dev/null | grep -q '/dev/%s'" % disk) == 0:
                continue
            self.disks.append(disk)

        un_suitable = list(set(disks).difference(set(self.disks)))
        if len(un_suitable) > 0:
            print("These disks %s are in use now, skip them." %
                  "|".join(un_suitable))

    def raw_test(self, disk):
        """
        raw test
        """
        print("\n#############")
        print("%s raw IO test" % disk)
        device = "/dev/" + disk
        if not os.path.exists(device):
            print("Error: device %s not exists." % device)
        proc_path = "/sys/block/" + disk
        if not os.path.exists(proc_path):
            proc_path = "/sys/block/*/" + disk
        size = Command("cat %s/size" % proc_path).get_str()
        size = int(size) / 2
        if size <= 0:
            print("Error: device %s size not suitable to do test." % device)
            return False
        elif size > 1048576:
            size = 1048576

        print("\nStarting sequential raw IO test...")
        opts = "-direct=1 -iodepth 4 -rw=rw -rwmixread=50 -group_reporting -name=file -runtime=300"
        if not self.do_fio(device, size, opts):
            print("%s sequential raw IO test fail." % device)
            print("#############")
            return False

        print("\nStarting rand raw IO test...")
        opts = "-direct=1 -iodepth 4 -rw=randrw -rwmixread=50 " \
               "-group_reporting -name=file -runtime=300"
        if not self.do_fio(device, size, opts):
            print("%s rand raw IO test fail." % device)
            print("#############")
            return False

        print("#############")
        return True

    def vfs_test(self, disk):
        """
        vfs test
        """
        print("\n#############")
        print("%s vfs test" % disk)
        device = "/dev/" + disk
        if not os.path.exists(device):
            print("Error: device %s not exists." % device)
        proc_path = "/sys/block/" + disk
        if not os.path.exists(proc_path):
            proc_path = "/sys/block/*/" + disk
        size = Command("cat %s/size" % proc_path).get_str()
        size = int(size) / 2 / 2
        if size <= 0:
            print("Error: device %s size not suitable to do test." % device)
            return False
        elif size > 1048576:
            size = 1048576

        if os.path.exists("vfs_test"):
            shutil.rmtree("vfs_test")
        os.mkdir("vfs_test")
        path = os.path.join(os.getcwd(), "vfs_test")

        return_code = True
        for file_sys in self.filesystems:
            try:
                print("\nFormatting %s to %s ..." % (device, file_sys))
                Command("umount %s" % device).echo(ignore_errors=True)
                Command("mkfs -t %s -F %s &>/dev/null" %
                        (file_sys, device)).echo()
                Command("mount -t %s %s %s" %
                        (file_sys, device, "vfs_test")).echo()

                print("\nStarting sequential vfs IO test...")
                opts = "-direct=1 -iodepth 4 -rw=rw -rwmixread=50 -name=directoy -runtime=300"
                if not self.do_fio(path, size, opts):
                    return_code = False
                    break

                print("\nStarting rand vfs IO test...")
                opts = "-direct=1 -iodepth 4 -rw=randrw -rwmixread=50 -name=directoy -runtime=300"
                if not self.do_fio(path, size, opts):
                    return_code = False
                    break
            except Exception as concrete_error:
                print(concrete_error)
                return_code = False
                break

        Command("umount %s" % device).echo(ignore_errors=True)
        Command("rm -rf vfs_test").echo(ignore_errors=True)
        print("#############")
        return return_code

    def do_fio(self, filepath, size, option):
        """
        fio test
        """
        if os.path.isdir(filepath):
            file_opt = "-directory=%s" % filepath
        else:
            file_opt = "-filename=%s" % filepath
        max_bs = 64
        a_bs = 4
        while a_bs <= max_bs:
            if os.system("fio %s -size=%dK -bs=%dK %s &>> %s" %
                         (file_opt, size, a_bs, option, self.logpath)) != 0:
                print("Error: %s fio failed." % filepath)
                return False
            sys.stdout.flush()
            a_bs = a_bs * 2
        return True