Exemple #1
0
def backup_file(_file):
    """Take file backup with the prefix .sa.backup.

    Do not perform any operation if the backup file is
    already present.

    Returns:
    backup file path on success else None"""

    log = get_default_logger()

    if not os.path.isfile(_file):
        return None

    (file_path, file_name) = os.path.split(_file)
    backup_file_path = file_path + '/' + '.' + file_name + '.sa.backup'

    # Do not update backup file
    if os.path.isfile(backup_file_path):
        return backup_file_path

    try:
        shutil.copy2(_file, backup_file_path)
    except Exception as exception:
        log.debug("Backup Failed %s", exception)

        # Remove the backup file
        if os.path.isfile(backup_file_path):
            os.remove(backup_file_path)

        return None

    return backup_file_path
Exemple #2
0
 def __init__(self):
     self.dump_service_name = ""
     self.dump_comp_name = ""
     self.initial_ramdisk = ""
     self.log = get_default_logger()
     self.kernel_release = platform.release()
     self.active_dump = "/proc/vmcore"
Exemple #3
0
def execute_command(command, sh=False):
    """Executes the command with given arguments and returns a tuple of three
    values exit status, stdout, and stderr. In case of command not found or an
    exception occurs during the command execution it returns (None, None, None)
    """

    log = get_default_logger()

    try:
        if not is_command_exists(command[0]):
            log.debug("%s command not found", command[0])
            return (None, None, None)

        if sh:
            command = ' '.join(command)

        process = subprocess.Popen(command,
                                   shell=sh,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        (output, err) = process.communicate()
        output = output.decode('utf-8')
        return (process.returncode, output, err)

    except OSError as os_error:
        log.debug("Failed create process to execute %s command: error: %s",
                  command[0], os_error)
        return (None, None, None)
Exemple #4
0
def get_package_classes(pkg_path, prefix):
    """Returns all the classes present in a given package"""

    log = get_default_logger()

    try:
        pkg_classes = []

        for (module_loader, name, ispkg) in \
                pkgutil.walk_packages(pkg_path,
                                      prefix):
            if ispkg:
                continue

            module = importlib.import_module(name)
            module_classes = [
                _class for cname, _class in inspect.getmembers(
                    module, inspect.isclass) if _class.__module__ == name
            ]

            pkg_classes.extend(module_classes)

    except SyntaxError as syntax_error:
        log.debug("Syntax error in module %s, error: %s", name, syntax_error)

    except ImportError as import_error:
        log.debug("Invalid import statement in %s module, error %s", name,
                  import_error)

    return pkg_classes
Exemple #5
0
 def __init__(self):
     Dump.__init__(self)
     self.name = FADump.__name__
     self.description = FADump.__doc__
     self.dump_service_name = "kdump"
     self.dump_comp_name = "kdump"
     self.log = get_default_logger()
def update_crashkernel(required_mem):
    """Update the crashkernel arttribute in /etc/default/grub"""

    grub_file_path = "/etc/default/grub"
    backup_grub_file_path = backup_file(grub_file_path)
    grub_temp_file_path = grub_file_path + ".tmp"
    log = get_default_logger()

    if backup_grub_file_path is None:
        log.error("Failed to take backup of %s", grub_file_path)
        return False

    log.info("Updating %s, backup file present at %s", grub_file_path,
             backup_grub_file_path)

    if os.path.exists(grub_temp_file_path):
        try:
            os.remove(grub_temp_file_path)
        except Exception:
            log.debug("Unable to delete %s file", grub_temp_file_path)
            return False

    try:
        with open(grub_file_path) as grub_file, \
                open(grub_temp_file_path, "w+") as grub_temp_file:

            grub_cmd_lx = "GRUB_CMDLINE_LINUX"
            grub_cmd_lx_def = "GRUB_CMDLINE_LINUX_DEFAULT"
            crashkernel = "crashkernel=" + str(required_mem) + "M"
            is_crashkernel_updated = False

            for line in grub_file.readlines():
                if line.startswith(grub_cmd_lx_def):
                    if is_grub_line_format(line):
                        line = remove_crashkernel_str(line)
                        line = add_crashkernel_str(line, crashkernel)
                        is_crashkernel_updated = True
                    else:
                        log.debug("Unknown grub line format: %s", line)
                        return False
                elif line.startswith(grub_cmd_lx):
                    if is_grub_line_format(line):
                        line = remove_crashkernel_str(line)
                    else:
                        log.debug("Unknown grub line format: %s", line)
                elif line.startswith("GRUB_DISABLE_RECOVERY") or \
                    line.startswith("GRUB_DISABLE_LINUX_RECOVERY"):
                    line = '#' + line
                grub_temp_file.write(line)

            if not is_crashkernel_updated:
                grub_temp_file.write(grub_cmd_lx_def + '=' + '"' +
                                     crashkernel + '"' + "\n")
    except Exception:
        log.debug("Unable to access files %s, %s", grub_file_path,
                  grub_temp_file_path)
        return False

    return replace_grub(grub_file_path, grub_temp_file_path,
                        backup_grub_file_path)
Exemple #7
0
 def __init__(self):
     Dump.__init__(self)
     self.name = Kdump.__name__
     self.description = Kdump.__doc__
     self.dump_service_name = "kdump"
     self.dump_comp_name = "kdump"
     self.kdump_etc_conf = "/etc/kdump.conf"
     self.kdump_conf_file = "/etc/sysconfig/kdump"
     self.log = get_default_logger()
Exemple #8
0
def get_service_status(service):
    """Checks the service status by issuing the systemctl command"""

    command = ["systemctl", "is-active", service]
    return_code = execute_command(command)[0]
    log = get_default_logger()

    if return_code is None:
        log.debug("Failed to get the status of service %s", service)
    return return_code
Exemple #9
0
 def __init__(self):
     Dump.__init__(self)
     self.name = Kdump.__name__
     self.description = Kdump.__doc__
     self.dump_service_name = "kdump"
     self.dump_comp_name = "kdump"
     self.kdump_etc_conf = "/etc/kdump.conf"
     self.kdump_conf_file = "/etc/sysconfig/kdump"
     self.log = get_default_logger()
     self.capture_kernel_mem = [(2048, 128), (4096, 320), (32768, 512),
                                (65536, 1024), (131072, 2048),
                                (1048576, 8192), (8388608, 16384),
                                (16777216, 32768), (sys.maxsize, 65536)]
Exemple #10
0
def get_file_size(file_path):
    """Returns the size of file or None if file is not present"""

    log = get_default_logger()

    try:
        file_info = os.stat(file_path)
        return file_info.st_size

    except OSError as os_error:
        log.debug("Failed to open file: %s, error: %s", file_path, os_error)

    return None
Exemple #11
0
 def __init__(self):
     Dump.__init__(self)
     self.name = FADump.__name__
     self.description = FADump.__doc__
     self.dump_service_name = "kdump"
     self.dump_comp_name = ["kdump", "zz-fadumpinit"]
     # (system mem, mem reservation needed)
     # (GB, MB)
     self.log = get_default_logger()
     self.capture_kernel_mem = [(16384, 786), (65536, 1024), (131072, 2048),
                                (1048576, 4096), (2097152, 6144),
                                (4194304, 12288), (8388608, 20480),
                                (16777216, 36864), (33554432, 65536),
                                (67108864, 131072), (sys.maxsize, 184320)]
Exemple #12
0
 def __init__(self):
     Dump.__init__(self)
     self.name = FADump.__name__
     self.description = FADump.__doc__
     self.dump_service_name = "kdump"
     self.dump_comp_name = "kdump"
     # (system mem, mem reservation needed)
     # (GB, MB)
     self.log = get_default_logger()
     self.capture_kernel_mem = [(4, 0),
                                (64, 1024), (128, 2048), (1024, 4096),
                                (2048, 6144), (4096, 12288), (8192, 20480),
                                (16384, 36864), (32786, 65536),
                                (65536, 131072), (sys.maxsize, 184320)]
Exemple #13
0
def get_file_content(file_path):
    """Returns the given file content as a string. None is returned
    if file is not present"""

    log = get_default_logger()

    try:
        with open(file_path, 'r') as o_file:
            data = o_file.read()
            return data.strip()

    except IOError as io_error:
        log.debug("Failed to open file: %s, error: %s", file_path, io_error)

    return None
Exemple #14
0
def get_total_ram():
    """Returns the RAM size in KB"""

    log = get_default_logger()

    try:
        with open('/proc/meminfo') as o_file:
            for line in o_file.readlines():
                (key, val) = line.split(':', 1)
                if "MemTotal" in key:
                    mem = val.strip().split(' ', 1)[0]
                    return int(mem)
    except (IOError, ValueError) as exception:
        log.debug("Unable to extract the total RAM from /proc/meminfo, %s",
                  exception)

    return None
Exemple #15
0
def install_package(package):
    """Install the given package."""

    package_manager = find_package_manager()
    log = get_default_logger()

    if package_manager is None:
        log.walk_packages("Unable to locate the package manager")
        return None

    command = package_manager["installer"] + " " + package_manager[
        "install_option"] + " " + package
    return_code = os.system(command)

    if return_code is None:
        return None
    elif return_code == 0:
        return True

    return False
Exemple #16
0
def get_system_platform():
    """Finds the platform information in cpuinfo. On success returns the
    system platform else empty string"""

    log = get_default_logger()
    cpuinfo_file = "/proc/cpuinfo"
    system_platform = ""

    try:
        with open(cpuinfo_file) as o_file:
            for line in o_file:
                if "platform" in line:
                    name = line.split(':')[1]
                    system_platform = name.strip()
                    return system_platform.lower()

    except IOError as io_error:
        log.debug("Failed to open file: /proc/cpuinfo, error: %s", io_error)

    return system_platform
def replace_grub(grub_file_path, grub_temp_file_path, backup_grub_file_path):
    """Replace the temporary grub file with original"""

    log = get_default_logger()
    try:
        os.rename(grub_temp_file_path, grub_file_path)
        return True
    except Exception:
        log.debug("Failed to replace %s with %s", grub_file_path,
                  grub_temp_file_path)
        try:
            log.debug("Resotring the grub file.")
            shutil.copy2(backup_grub_file_path, grub_file_path)
        except Exception:
            log.error("Failed to restore grub file.")
            print(
                "CRITICAL: Make sure %s file is in correct state before rebooting"
            )

        return False
Exemple #18
0
def is_package_installed(package):
    """Return True if given package is present in the system else False"""

    package_manager_options = find_package_manager()
    log = get_default_logger()

    if package_manager_options is None:
        log.warning("Unable to locate the package manager")
        return None

    package_manager = package_manager_options["command"]
    search_option = package_manager_options["search_option"]
    (return_code, stdout) = \
        execute_command([package_manager, search_option, package])[:-1]

    if return_code is None:
        return None
    elif return_code == 0:
        return True

    return False
Exemple #19
0
def get_distro_name():
    """Finds the distro name from /etc/os-release and on success returns
    the distro name else empty string"""

    os_release = '/etc/os-release'
    distro_search_key = 'PRETTY_NAME'
    log = get_default_logger()

    try:
        with open(os_release, 'r') as _file:
            for line in _file:
                (key, value) = line.split("=")
                if key.startswith(distro_search_key):
                    return value.strip()

    except IOError as io_error:
        log.debug("Unable to open the file: /etc/os-release, error: %s",
                  io_error)

    except IndexError as index_error:
        log.debug("Format issue in file /etc/os-release, error: %s",
                  index_error)

    return ""
Exemple #20
0
 def __init__(self):
     self.name = Plugin.__name__
     self.description = Plugin.__doc__
     self.log = get_default_logger()
     self.checks = []
Exemple #21
0
 def __init__(self, scheme_handler):
     self.log = get_default_logger()
     self.scheme_handler = scheme_handler
     self.populate_plugins()
     self.populate_applicable_plugin()
Exemple #22
0
 def __init__(self):
     self.log = get_default_logger()
     self.populate_schemes()
     self.populate_valid_schemes()
Exemple #23
0
 def __init__(self):
     RepairPlugin.__init__(self)
     self.name = "FADump"
     self.log = get_default_logger()
 def __init__(self):
     self.log = get_default_logger()
Exemple #25
0
 def __init__(self):
     self.name = RepairPlugin.__name__
     self.log = get_default_logger()
Exemple #26
0
 def __init__(self):
     self.log = get_default_logger()
     self.repair_plugins = {}
     self.populate_repair_plugins()
Exemple #27
0
 def __init__(self, cmd_opts):
     self.cmd_opts = cmd_opts
     self.log = get_default_logger()
     self.scheme_handler = SchemeHandler()
     self.plugin_handler = PluginHandler(self.scheme_handler)
     self.validation_results = OrderedDict()
Exemple #28
0
 def __init__(self, cmd_opts):
     self.cmd_opts = cmd_opts
     self.log = get_default_logger()
     self.repair_plugin_handler = RepairPluginHandler()