Ejemplo n.º 1
0
class PackagesPlugin(BlueprintPlugin):
    """This plugin retrieve list of all installed packages and their versions."""
    name = "RPM Packages"
    version = "0.0.1"
    author = "Martin Sivak"
    
    def __init__(self, *args, **kwargs):
        Plugin.__init__(self, *args, **kwargs)
        self._issue = SimpleIssue(self.name, self.description)
        self.rpmlib = None

    def prepare(self):
        import rpm
        self.rpmlib = rpm
        self._result=ReturnSuccess
        self._issue.set(reporting  = self._reporting, origin = self, level = PLUGIN)
        self._reporting.info("RPM properly initialized", origin = self, level = PLUGIN)

    def diagnose(self):
        self._reporting.info("Getting list of RPM packages", origin = self, level = PLUGIN)
        ts = self.rpmlib.TransactionSet()
        mi = ts.dbMatch()
        for h in mi:
            setattr(self._info, h["name"], "%s-%s" % (h["version"], h["release"]))
            
        self._result=ReturnSuccess
        self._issue.set(checked = True, happened = False, reporting  = self._reporting, origin = self, level = PLUGIN)

    def clean(self):
        del self.rpmlib
        self._result=ReturnSuccess
Ejemplo n.º 2
0
 def __init__(self, *args, **kwargs):
     Plugin.__init__(self, *args, **kwargs)
     # Arbitrary test display
     self.display = ":10"
     self.confPath = "/etc/X11/xorg.conf"
     self.backupSpace = self._backups.getBackup(str(self))
     self._issue = SimpleIssue(self.name, "X server didn't start")
Ejemplo n.º 3
0
 def __init__(self, *args, **kwargs):
     Plugin.__init__(self, *args, **kwargs)
     self.currentFileDict = {}  #what we read from /etc/mdadm.conf
     self.scannedFileDict = {}  #what `mdadm --misc --detail --scan`
     self.scannedFile = None  # what `mdadm --misc --detail --scan` returns
     self.configFile = os.path.join(Config.system.root, "/etc/mdadm.conf")
     self.backupSpace = self._backups.getBackup(str(self))
     self._issue = SimpleIssue(self.name, "mdadm.con misconfigured")
Ejemplo n.º 4
0
 def __init__(self, *args, **kwargs):
     Plugin.__init__(self, *args, **kwargs)
     self._issue = SimpleIssue(self.name, self.description)
     self.initrd = None  #
     self.initrd_path = None
     self.kernel_version = None
     self.kernel_re = re.compile(".*initrd-(?P<kernel>.*)\.img")
     self.initrds = []  # array of intirds found ing menu.lst
Ejemplo n.º 5
0
 def oscap_callback_start(self, Msg, Plugin):
     if Msg.user2num == openscap.OSCAP.XCCDF_RESULT_NOT_SELECTED:
         if Plugin.continuing():
             return 0
         else:
             return 1
        
     
     try:
         Id = Msg.user1str
         setattr(self._info, Id, unicode(-1))
         Issue = Plugin._issues.get(Id, None)
         if Issue is None:
             title = Msg.user3str
             description = Msg.string
             Issue = SimpleIssue(Id, title)
             Issue.set(reporting  = Plugin._reporting, origin = Plugin, level = PLUGIN)
             Plugin._issues[Id] = Issue
            
     except Exception, e:
         print e
Ejemplo n.º 6
0
class Sample1Plugin(Plugin):
    """This plugin uses the predefined flow in the Plugin abstract class."""
    name = "Sample1Plugin"
    version = "0.0.1"
    author = "Joel Andres Granados"

    def __init__(self, *args, **kwargs):
        Plugin.__init__(self, *args, **kwargs)
        self._issue = SimpleIssue(self.name, self.description)

    def prepare(self):
        self._result = ReturnSuccess
        self._issue.set(reporting=self._reporting, origin=self, level=PLUGIN)
        self._backup = self._backups.getBackup(self.__class__.__name__ +
                                               " -- " + self.name,
                                               persistent=True)
        self._reporting.info("Sample1Plugin in Prepare task",
                             origin=self,
                             level=PLUGIN)

    def backup(self):
        self._result = ReturnSuccess
        self._reporting.info("Sample1Plugin in backup task",
                             origin=self,
                             level=PLUGIN)

    def restore(self):
        self._result = ReturnSuccess
        self._reporting.info("Sample1Plugin in Restore task",
                             origin=self,
                             level=PLUGIN)

    def diagnose(self):
        self._result = ReturnSuccess
        self._issue.set(checked=True,
                        happened=False,
                        reporting=self._reporting,
                        origin=self,
                        level=PLUGIN)
        self._reporting.info("Sample1Plugin in diagnose task",
                             origin=self,
                             level=PLUGIN)

    def fix(self):
        self._result = ReturnFailure
        self._issue.set(fixed=False,
                        reporting=self._reporting,
                        origin=self,
                        level=PLUGIN)
        self._reporting.info("Sample1Plugin in Fix task",
                             origin=self,
                             level=PLUGIN)

    def clean(self):
        self._result = ReturnSuccess
        self._backups.closeBackup(self._backup._id)
        self._reporting.info("Sample1Plugin in Clean task",
                             origin=self,
                             level=PLUGIN)
Ejemplo n.º 7
0
    def diagnose(self):
        self._reporting.info("Getting list of Yum repository files",
                             origin=self,
                             level=PLUGIN)
        repos = [
            n[:-5] for n in os.listdir(self._yum_repos_d)
            if n.endswith(".repo")
        ]

        for fn in repos:
            repo_issue = None
            try:
                repo_issue = SimpleIssue(
                    "reading Yum repo config %s" % fn,
                    "I was unable to process the repository configuration.")
                repo_issue.set(checked=False,
                               happened=False,
                               reporting=self._reporting,
                               origin=self,
                               level=PLUGIN)
                f = open(os.path.join(self._yum_repos_d, fn + ".repo"))
                content = f.read().replace("\\", "\\\\").replace("\n", "\\n")
                setattr(self._info, fn, content)
                f.close()
                repo_issue.set(checked=True,
                               happened=False,
                               reporting=self._reporting,
                               origin=self,
                               level=PLUGIN)
            except IOError:
                repo_issue.set(checked=True,
                               happened=True,
                               reporting=self._reporting,
                               origin=self,
                               level=PLUGIN)

        self._result = ReturnSuccess
        self._issue.set(checked=True,
                        happened=False,
                        reporting=self._reporting,
                        origin=self,
                        level=PLUGIN)
Ejemplo n.º 8
0
class Sample2Plugin(Plugin):
    """This plugin will defin one more function and use it in a newly defined fix flow."""
    #
    # Additional flow defprepareion.
    #
    flows = Flow.init(Plugin)
    flows["fix"] = Flow({
                    Plugin.initial: {Return: "prepare"},
                    "prepare"     : {ReturnSuccess: "diagnose"},
                    "diagnose"    : {ReturnSuccess: "clean", ReturnFailure: "backup"},
                    "backup"      : {ReturnSuccess: "fix", ReturnFailure: "clean"},
                    "restore"     : {ReturnSuccess: "clean", ReturnFailure: "clean"},
                    "fix"         : {ReturnSuccess: "extraStep", ReturnFailure: "restore"},
                    "extraStep"   : {ReturnSuccess: "clean", ReturnFailure: "clean"},
                    "clean"       : {ReturnSuccess: Plugin.final}
                    }, description="Fixing sequence with one added extraStep")

    name = "Sample2Plugin"
    version = "0.0.1"
    author = "Joel Andres Granados"

    def __init__(self, *args, **kwargs):
        Plugin.__init__(self, *args, **kwargs)
        self._issue = SimpleIssue(self.name, self.description)

    def prepare(self):
        self._issue.set(reporting  = self._reporting, origin = self, level = PLUGIN)
        self._result=ReturnSuccess

    def clean(self):
        self._result=ReturnSuccess

    def backup(self):
        self._result=ReturnSuccess

    def restore(self):
        self._result=ReturnSuccess

    def diagnose(self):
        self._issue.set(checked = True, happened = True, reporting  = self._reporting, origin = self, level = PLUGIN)
        self._result=ReturnFailure

    def fix(self):
        self._issue.set(fixed = True, reporting  = self._reporting, origin = self, level = PLUGIN)
        self._result=ReturnSuccess

    def extraStep(self):
        self._result=ReturnSuccess
Ejemplo n.º 9
0
class Sample1Plugin(Plugin):
    """This plugin uses the predefined flow in the Plugin abstract class."""
    name = "SampleDepends 1 -> 2"
    version = "0.0.1"
    author = "Joel Andres Granados"

    def __init__(self, *args, **kwargs):
        Plugin.__init__(self, *args, **kwargs)
        self._issue = SimpleIssue(self.name, self.description)

    @classmethod
    def getDeps(cls):
        return set(["sample_dependency"]).union(Plugin.getDeps())

    def prepare(self):
        self._result = ReturnSuccess
        self._issue.set(checked=False,
                        reporting=self._reporting,
                        origin=self,
                        level=PLUGIN)

    def backup(self):
        self._result = ReturnSuccess

    def restore(self):
        self._result = ReturnSuccess

    def diagnose(self):
        self._result = ReturnSuccess
        self.provide("sample_dependency2")
        self._issue.set(checked=True,
                        happened=False,
                        reporting=self._reporting,
                        origin=self,
                        level=PLUGIN)

    def fix(self):
        self._result = ReturnFailure
        self._issue.set(fixed=False,
                        reporting=self._reporting,
                        origin=self,
                        level=PLUGIN)

    def clean(self):
        self._result = ReturnSuccess
Ejemplo n.º 10
0
class Xserver(Plugin):
    """ Plugin to detect an rescue faulty xserver configurations. """
    flows = Flow.init(Plugin)
    flows["force"] = Flow({
            Plugin.initial: {Return: "prepare"},
            "prepare"     : {ReturnSuccess: "diagnose2"},
            "diagnose2"   : {ReturnSuccess: "clean", ReturnFailure: "backup"},
            "backup"      : {ReturnSuccess: "fix", ReturnFailure: "clean"},
            "restore"     : {ReturnSuccess: "clean", ReturnFailure: "clean"},
            "fix"         : {ReturnSuccess: "clean", ReturnFailure: "restore"},
            "clean"       : {ReturnSuccess: Plugin.final}
          }, description="This flow skips the search for the xserver lock file")
    name = "X server"
    version = "0.0.1"
    author = "Joel Andres Granados"
    description = "Automates recovery of the xserver"

    @classmethod
    def getDeps(cls):
        return set(["root", "filesystem"])

    def __init__(self, *args, **kwargs):
        Plugin.__init__(self, *args, **kwargs)
        # Arbitrary test display
        self.display = ":10"
        self.confPath = "/etc/X11/xorg.conf"
        self.backupSpace = self._backups.getBackup(str(self))
        self._issue = SimpleIssue(self.name, "X server didn't start")

    def prepare(self):
        # Nothing to prepare really.
        self._result = ReturnSuccess
        self._issue.set(reporting = self._reporting, level = PLUGIN,
                origin = self)

    def diagnose(self):
        # Lets see if there is a server active.
        if os.path.exists("/tmp/.X0-lock"):
            self._reporting.info("An X server is already running.",
                    level = PLUGIN, origin = self)
            self._reporting.info("You can run the \"force\" flow to "
                    "avoud this check. In some cases it works.",
                    level = PLUGIN, origin = self)
            self._result = ReturnSuccess

        elif self.serverStart():
            self._reporting.info("Everything seems ok with the X server.",
                    level = PLUGIN, origin = self)
            self._result = ReturnSuccess

        elif not os.path.exists(self.confPath):
            # If the configuration is not there dont even bother to try
            #fixing it.  This will go through the proces of trying to fix
            #it.  at least we told the user.
            self._reporting.info("The error is in the xservers autodetection "
                    "mechanism, this does not have an automated solution yet.",
                    level = PLUGIN, origin = self)
            self._result = ReturnFailure

        else:
            self._reporting.info("X server is missconfigured.", level = PLUGIN,
                    origin = self)
            self._result = ReturnFailure
        self._issue.set(checked = True,
                happened = (self._result == ReturnFailure),
                reporting = self._reporting, level = PLUGIN, origin = self)

    def diagnose2(self):
        """Just a diagnose without the lock check"""
        if self.serverStart():
            self._reporting.info("Everything seems ok with the X server.",
                    level = PLUGIN, origin = self)
            self._result = ReturnSuccess

        elif not os.path.exists(self.confPath):
            # If the configuration is not there dont even bother to try fixing it.
            # This will go through the proces of trying to fix it.  at least we
            #told the user.
            self._reporting.info("The error is in the xservers autodetection "
                    "mechanism, this does not have an automated solution yet.",
                    level = PLUGIN, origin = self)
            self._result = ReturnFailure

        else:
            self._reporting.info("X server is missconfigured.", level = PLUGIN,
                    origin = self)
            self._result = ReturnFailure
        self._issue.set(checked = True,
                happened = (self._result == ReturnFailure),
                reporting = self._reporting, level = PLUGIN, origin = self)


    def backup(self):
        if os.path.isfile(self.confPath):
            self.backupSpace.backupPath(self.confPath)
        else:
            self._reporting.info("%s does not exist." % self.confPath,
                    level = PLUGIN, origin = self)
        self._result = ReturnSuccess

    def fix(self):
        self._reporting.info("Starting the fix task.", level = PLUGIN,
                origin = self)
        # With the current xorg server the only thing that we need to do is to 
        # erase the conf file.
        if os.path.exists(self.confPath):
            os.remove(self.confPath)

        self._reporting.info("Testing modified environment", level = PLUGIN,
                origin = self)
        if self.serverStart():
            self._reporting.info("X server started successfully with no "
                    "config file.", level = PLUGIN, origin = self)
            self._reporting.info("If you must have a config file, create "
                    "one with system-config-display and place it at "
                    "/etc/X11/xorg.conf", level = PLUGIN, origin = self )
            self._result = ReturnSuccess

            # Lets give the user his previous file.
            if self.backupSpace.exists(path=self.confPath):
                self.backupSpace.restoreName(self.confPath,
                        "%s-FAKbackup"%self.confPath)

        else:
            self._reporting.info("X server is does not autodetect the users "
                    "environment.", level = PLUGIN, origin = self)
            self._result = ReturnFailure

        self._issue.set(fixed = (self._result == ReturnSuccess),
                reporting = self._reporting, level = PLUGIN, origin = self)

    def restore(self):
        if not self.backupSpace.exists(path=self.confPath):
            # This is the case where there is no config file.
            self._reporting.info("The backedup file was not present. Assuming "
                    "that xorg did not have a config file to begin with.", 
                    level = PLUGIN, origin = self)
        else:
            self._reporting.info("Restoring original file.", level = PLUGIN ,
                    origin = self)
            self.backupSpace.restoreName(self.confPath)

        self._result = ReturnSuccess

    def clean(self):
        self._result = ReturnSuccess


    def serverStart(self):
        self._reporting.info("Trying to start X server", level = PLUGIN,
                origin = self)
        xorgargs = [self.display]
        try:
            proc = spawnvch(executable = "/usr/bin/Xorg", args = xorgargs,
                    chroot = Config.system.root)
            self._reporting.info("Waiting for the X server to start...",
                    level = PLUGIN, origin = self)
            time.sleep(5)
            if proc.poll() is not None:
                # process has terminated, failed.
                raise OSError
        except:
            self._reporting.info("The X server has failed to start",
                    level = PLUGIN, origin = self)
            return False
        self._reporting.info("The X server has started successfully",
                level = PLUGIN, origin = self)
        os.kill(proc.pid, signal.SIGINT)
        return True
Ejemplo n.º 11
0
class FreeSpacePlugin(Plugin):
    """Plugin to detect insufficient free space in /var directory."""
    name = "Free Space"
    version = "0.0.1"
    author = "Tomas Mlcoch"
    description = "Detects insufficient free space in /var directory."

    directory = '/var'
    del_dirs = [
        '/var/tmp',
    ]  # All content of this files will be
    # removed (deleted) in "fix" step.

    @classmethod
    def getDeps(cls):
        return set(["root", "filesystem"])

    def __init__(self, *args, **kwargs):
        Plugin.__init__(self, *args, **kwargs)
        self._issue = SimpleIssue(self.name, self.description)

    def _reporter(self, msg):
        self._reporting.info(msg, origin=self, level=PLUGIN)

    def prepare(self):
        self._issue.set(reporting=self._reporting, origin=self, level=PLUGIN)
        self._result = ReturnSuccess

    def diagnose(self):

        # statvfs stucture:
        # -----------------
        # f_bsize   File system block size.
        # f_frsize  Fundamental file system block size (fragment size).
        # f_blocks  Total number of blocks on the file system, in units of f_frsize.
        # f_bfree   Total number of free blocks.
        # f_bavail  Total number of free blocks available to non-privileged processes.
        # f_files   Total number of file nodes (inodes) on the file system.
        # f_ffree   Total number of free file nodes (inodes).
        # f_favail  Total number of free file nodes (inodes) available to non-privileged processes.
        # f_flag    File system ID number.
        # f_namemax Maximum length of a file name (path element).

        # stat structure:
        # ---------------
        # st_dev        device
        # st_ino        inode
        # st_mode       protection
        # st_nlink      number of hard links
        # st_uid        user ID of owner
        # st_gid        group ID of owner
        # st_rdev       device type (if inode device)
        # st_size       total size, in bytes
        # st_blksize    blocksize for filesystem I/O
        # st_blocks     number of blocks allocated
        # st_atime      time of last access
        # st_mtime      time of last modification
        # st_ctime      time of last change

        # Get freespace
        stats = os.statvfs(self.directory)
        freespace = stats.f_bavail * stats.f_frsize / 1048576  # Freespace in Mb

        # Get freeable space
        self.freeable = 0
        for dir in self.del_dirs:
            stats_fa = os.statvfs(dir)
            for root, dirs, files in os.walk(dir):
                for d in dirs:
                    self.freeable += os.stat(os.path.join(root, d)).st_size
                for f in files:
                    self.freeable += os.stat(os.path.join(root, f)).st_size
        self.freeable /= 1024

        # Analyse results
        if freespace < 1:
            lhappened = True
            self._reporter("Free space seems to be insufficient.")
            self._reporter("Freeable space: %s Kb" % self.freeable)
            self._result = ReturnFailure
        else:
            lhappened = False
            self._reporter("Free space seems to be sufficient.")
            self._result = ReturnSuccess

        self._issue.set(checked=True,
                        happened=lhappened,
                        reporting=self._reporting,
                        origin=self,
                        level=PLUGIN)

    def backup(self):
        self._result = ReturnSuccess

    def restore(self):
        self._result = ReturnSuccess

    def fix(self):
        try:
            for dir in self.del_dirs:
                self._reporter("Deleting content of: %s" % dir)
                for root, dirs, files in os.walk(dir):
                    for d in dirs:
                        shutil.rmtree(os.path.join(root, d))
                    for f in files:
                        os.unlink(os.path.join(root, f))
        except (Exception) as e:
            self._reporter("Exception: %s" % e)
            self._result = ReturnFailure
        else:
            self._result = ReturnSuccess
            self._reporter("Fix successfully complete! (Freed space: %s Kb)" \
                                % self.freeable)

        self._issue.set(fixed=(self._result == ReturnSuccess),
                        reporting=self._reporting,
                        origin=self,
                        level=PLUGIN)

    def clean(self):
        self._result = ReturnSuccess
Ejemplo n.º 12
0
 def __init__(self, *args, **kwargs):
     Plugin.__init__(self, *args, **kwargs)
     self._issue = SimpleIssue(self.name, "Discovering system properties failed")
Ejemplo n.º 13
0
class DialoguePlugin(Plugin):
    """This plugin demonstrates asking the user for information."""
    name = "DialoguePlugin"
    version = "0.0.2"
    author = "Miloslav Trmač & Martin Sivák"

    def __init__(self, *args, **kwargs):
        Plugin.__init__(self, *args, **kwargs)
        self._issue = SimpleIssue(self.name, self.description)

    @classmethod
    def getDeps(cls):
        return set(["interactive"]).union(Plugin.getDeps())

    def prepare(self):
        self._issue.set(reporting=self._reporting, origin=self, level=PLUGIN)
        self._result = ReturnSuccess

    def backup(self):
        self._result = ReturnSuccess

    def restore(self):
        self._result = ReturnSuccess

    def diagnose(self):
        self._result = ReturnSuccess
        self._reporting.info("DialoguePlugin in diagnose task",
                             origin=self,
                             level=PLUGIN)
        tea = self._reporting.choice_question_wait \
            ("Would you care for some tea?", ((True, "Yes"), (False, "No")),
             origin = self, level = PLUGIN)
        if tea:
            self._reporting.info("Here's your tea", origin=self, level=PLUGIN)
        else:
            self._reporting.info("No tea for you!", origin=self, level=PLUGIN)
        s = self._reporting.text_question_wait("Enter your name: ",
                                               origin=self,
                                               level=PLUGIN)
        self._reporting.info("Name: %s" % repr(s), origin=self, level=PLUGIN)
        s = self._reporting.password_question_wait("Old fake password: "******"Old password: %s" % repr(s),
                             origin=self,
                             level=PLUGIN)
        s = self._reporting.password_question_wait("New fake password: "******"New password: %s" % repr(s),
                             origin=self,
                             level=PLUGIN)
        s = self._reporting.filename_question_wait("File name: ",
                                                   origin=self,
                                                   level=PLUGIN)
        self._reporting.info("File name: %s" % repr(s),
                             origin=self,
                             level=PLUGIN)

        config_options = [
            ("id:1", "PL", "5", "Password length", "[1-9][0-9]*",
             "The length must be a valid number bigger than 0."),
            ("id:2", "PS", "C", "Password strength", "[A-F]",
             "Use strength indicator A, B, C, D, E or F"),
            ("id:3", "PL", "aA0.", "Password chars", ".*",
             "Any allowed characters.."),
        ]

        s = self._reporting.config_question_wait("Setup choices",
                                                 "Set preferred values",
                                                 config_options,
                                                 origin=self,
                                                 level=PLUGIN)
        self._reporting.info("Options: %s" % repr(s),
                             origin=self,
                             level=PLUGIN)

        self._issue.set(checked=True,
                        happened=False,
                        reporting=self._reporting,
                        origin=self,
                        level=PLUGIN)

    def fix(self):
        self._result = ReturnSuccess

    def clean(self):
        self._result = ReturnSuccess
Ejemplo n.º 14
0
class MdadmConfig(Plugin):
    """ Addresses the validity and presence of /etc/mdadm.conf """
    flows = Flow.init(Plugin)
    name = "mdadm configuration"
    version = "0.0.1"
    author = "Joel Andres Granados"
    description = "Assess the validity and existence of the mdadm.conf file"

    @classmethod
    def getDeps(cls):
        return set(["root", "filesystem"])

    def __init__(self, *args, **kwargs):
        Plugin.__init__(self, *args, **kwargs)
        self.currentFileDict = {}  #what we read from /etc/mdadm.conf
        self.scannedFileDict = {}  #what `mdadm --misc --detail --scan`
        self.scannedFile = None  # what `mdadm --misc --detail --scan` returns
        self.configFile = os.path.join(Config.system.root, "/etc/mdadm.conf")
        self.backupSpace = self._backups.getBackup(str(self))
        self._issue = SimpleIssue(self.name, "mdadm.con misconfigured")

    def prepare(self):
        # We read the configuration file if it exists
        if os.path.exists(self.configFile):
            self._reporting.info("Gathering information from %s." %
                                 self.configFile,
                                 level=PLUGIN,
                                 origin=self)
            fd = open(self.configFile, "r")
            for line in fd.readlines():
                splitline = line.strip("\n").split(" ")
                if "ARRAY" in splitline:
                    self.currentFileDict[splitline[1]] = splitline
            fd.close()

        else:
            self._reporting.info("File %s was not found." % self.configFile,
                                 level=PLUGIN,
                                 origin=self)

        # We execute the mdadm command
        self._reporting.info("Scanning for software raid with mdadm.",
                             level=PLUGIN,
                             origin=self)
        mdadmargs = ["--misc", "--detail", "--scan"]
        proc = spawnvch(executable="mdadm",
                        args=mdadmargs,
                        chroot=Config.system.root)
        (out, err) = proc.communicate()

        if err == '':
            # means that the command ran with no errors.
            for line in out.__str__().split("\n"):
                splitline = line.strip("\n").split(" ")
                if "ARRAY" in splitline:
                    self.scannedFileDict[splitline[1]] = splitline
            self.scannedFile = out
        else:
            # This should make the flow go to clean.  If there is an error we
            # should not trust what mdadm tells us.
            self._reporting.info("The mdadm command had the following " \
                    "error:%s. The plugin will silently exit."%err,
                    level = PLUGIN, origin = self)
            self._result = None
            return
        self._result = ReturnSuccess
        self._issue.set(reporting=self._reporting, level=PLUGIN, origin=self)

    def diagnose(self):
        # If nothing was returned by the mdadm command.  we dont have software
        # raid.
        if len(self.scannedFileDict) == 0:
            self._reporting.info("There was no sofware raid found by the " \
                    "mdadm command.... Nothing to do.", level = PLUGIN,
                    origin = self)
            self._result = ReturnSuccess
            self._issue.set(checked=True,
                            happened=False,
                            reporting=self._reporting,
                            level=PLUGIN,
                            origin=self)
            return

        # If nothing is detected the result is successfull.
        self._result = ReturnSuccess

        # If there is one difference between the configs, regarding the
        # ARRAYS.  We replace the config file. Lets check for missing arrays
        # in the curren config file.
        for key, value in self.scannedFileDict.iteritems():
            if not self.currentFileDict.has_key(key):
                self._reporting.info("Found that the current mdadm.conf is " \
                        "missing: %s."%value, level = PLUGIN, origin = self)
                self._result = ReturnFailure

        # Lets check for additional ARRAYS that should not be there.
        for key, value in self.currentFileDict.iteritems():
            if not self.scannedFileDict.has_key(key):
                self._reporting.info("The followint entry: %s, is in the " \
                        "config file but was not detected by mdadm."%value,
                        level = PLUGIN, origin = self)
                self._result = ReturnFailure

        if self._result == ReturnSuccess:
            self._reporting.info("There was no problem found with the " \
                    "current mdadm.conf file.", level = PLUGIN, origin = self)

        self._issue.set(checked=True,
                        happened=(self._result == ReturnFailure),
                        reporting=self._reporting,
                        level=PLUGIN,
                        origin=self)

    def backup(self):
        if os.path.isfile(self.configFile):
            self._reporting.info("Making a backup of %s." % self.configFile,
                                 level=PLUGIN,
                                 origin=self)
            self.backupSpace.backupPath(self.configFile)

        else:
            self._reporting.info("It appears that the file %s does not "\
                    "exist.  No backup attempt will be made."%self.configFile,
                    level = PLUGIN, origin = self)

        self._result = ReturnSuccess

    def fix(self):
        try:
            self._reporting.info("Going to write configuration to %s." %
                                 self.configFile,
                                 level=PLUGIN,
                                 origin=self)
            fd = open(self.configFile, "w")
            fd.write("# File created by Firstaidkit.\n")
            fd.write("# DEVICE partitions\n")
            fd.write("# MAILADDR root\n")
            fd.write(self.scannedFile)
            fd.close()
            self._reporting.info("Configuration file writen.",
                                 level=PLUGIN,
                                 origin=self)

            # The original mdadm.conf will be restore to
            # mdadm.conf.firstaidkit, just in case.
            self._reporting.info(
                "Will put the old mdadm.conf in %s." % os.path.join(
                    Config.system.root, self.configFile + ".firstaidkit"),
                level=PLUGIN,
                origin=self)
            self.backupSpace.restoreName(self.configFile,
                                         path=self.configFile + ".firstaidkit")
            self._result = ReturnSuccess

        except IOError:
            fd.close()
            self._reporting.info("Error occurred while writing %s." %
                                 self.configFile,
                                 level=PLUGIN,
                                 origin=self)
            self._result = ReturnFailure
        self._issue.set(fixed=(self._result == ReturnSuccess),
                        reporting=self._reporting,
                        level=PLUGIN,
                        origin=self)

    def restore(self):
        if not self.backupSpace.exists(self.configFile):
            # This is the case where there is no config file.
            self._reporting.info("The backedup file was not present. " \
                    "Assuming that %s was ont present to begin with."%
                    self.configFile, level = PLUGIN, original = self)
        else:
            self._reporting.info("Restoring original file.",
                                 level=PLUGIN,
                                 origin=self)
            self.backupSpace.restoreName(self.configFile)
        self._result = ReturnSuccess

    def clean(self):
        self._result = ReturnSuccess
Ejemplo n.º 15
0
class mkinitrd(Plugin):
    """This plugin uses the predefined flow in the Plugin abstract class."""
    name = "mkinitrd"
    version = "0.0.1"
    author = "Adam Pribyl"

    flows = Flow.init(Plugin)
    flows["mkinitrd"] = flows["fix"]
    del flows["fix"]
    del flows["diagnose"]

    @classmethod
    def getDeps(cls):
        return set(["root"]).union(Plugin.getDeps())

    def __init__(self, *args, **kwargs):
        Plugin.__init__(self, *args, **kwargs)
        self._issue = SimpleIssue(self.name, self.description)
        self.initrd = None  #
        self.initrd_path = None
        self.kernel_version = None
        self.kernel_re = re.compile(".*initrd-(?P<kernel>.*)\.img")
        self.initrds = []  # array of intirds found ing menu.lst

    def prepare(self):
        self._issue.set(reporting=self._reporting, origin=self, level=PLUGIN)
        self._backup = self._backups.getBackup(self.__class__.__name__ +
                                               " -- " + self.name,
                                               persistent=False)
        self._reporting.info("mkinitrd in Prepare task",
                             origin=self,
                             level=PLUGIN)
        f = open(os.path.join(Config.system.root, "/boot/grub/menu.lst"))
        for l in f:
            ltmp = l.strip()
            self._reporting.debug("parsing line: %s" % ltmp,
                                  origin=self,
                                  level=PLUGIN)
            if ltmp.startswith("default"):
                self.initrd = int(ltmp[8:])
                self._reporting.debug("found default: %d" % self.initrd,
                                      origin=self,
                                      level=PLUGIN)
            elif ltmp.startswith("initrd"):
                self.initrds.append(ltmp.split()[1][1:])
                self._reporting.debug("found initrd: %s" % self.initrds[-1],
                                      origin=self,
                                      level=PLUGIN)

        self._reporting.debug("config root: %s" % Config.system.root,
                              origin=self,
                              level=PLUGIN)
        self._reporting.debug(
            "looking for: %s" %
            os.path.join(Config.system.root, self.initrds[self.initrd]),
            origin=self,
            level=PLUGIN)
        self._reporting.debug("looking for: %s" % os.path.join(
            Config.system.root, "boot", self.initrds[self.initrd]),
                              origin=self,
                              level=PLUGIN)
        if os.path.exists(
                os.path.join(Config.system.root, self.initrds[self.initrd])):
            self.initrd_path = os.path.join(Config.system.root,
                                            self.initrds[self.initrd])
        elif os.path.exists(
                os.path.join(Config.system.root, "boot",
                             self.initrds[self.initrd])):
            self.initrd_path = os.path.join(Config.system.root, "boot",
                                            self.initrds[self.initrd])
        else:
            self.result = ReturnFailure
            self._reporting.error("initrd not found",
                                  origin=self,
                                  level=PLUGIN)
            return

        self._reporting.info("initrd found: %s" % (self.initrd_path, ),
                             origin=self,
                             level=PLUGIN)
        m = self.kernel_re.match(self.initrds[self.initrd])
        if not m:
            self._reporting.error("kernel version not identified",
                                  origin=self,
                                  level=PLUGIN)
            self._result = ReturnFailure
            return

        self.kernel_version = m.group("kernel")
        self._reporting.info("kernel version: %s" % (self.kernel_version, ),
                             origin=self,
                             level=PLUGIN)
        self._result = ReturnSuccess

    def backup(self):
        self._reporting.info("mkinitrd in backup task",
                             origin=self,
                             level=PLUGIN)
        self._backup.backupPath(self.initrd_path)
        self._result = ReturnSuccess

    def restore(self):
        self._reporting.info("mkinitrd in Restore task",
                             origin=self,
                             level=PLUGIN)
        self._backup.restorePath(self.initrd_path)
        self._result = ReturnSuccess

    def diagnose(self):
        self._result = ReturnFailure
        self._issue.set(checked=True,
                        happened=True,
                        reporting=self._reporting,
                        origin=self,
                        level=PLUGIN)
        self._reporting.info("mkinitrd in diagnose task",
                             origin=self,
                             level=PLUGIN)

    def fix(self):
        self._issue.set(fixed=False,
                        reporting=self._reporting,
                        origin=self,
                        level=PLUGIN)
        self._reporting.info("mkinitrd in Fix task", origin=self, level=PLUGIN)
        print spawnvch("/sbin/mkinitrd", [
            "mkinitrd", self.initrd_path[len(Config.system.root):],
            self.kernel_version
        ], Config.system.root).communicate()
        self._result = ReturnFailure

    def clean(self):
        self._result = ReturnSuccess
        self._backups.closeBackup(self._backup._id)
        self._reporting.info("mkinitrd in Clean task",
                             origin=self,
                             level=PLUGIN)
Ejemplo n.º 16
0
class RepositoriesPlugin(BlueprintPlugin):
    """This blueprint plugin retrieve list of all installed Yum repositories."""
    name = "Yum repositories"
    version = "0.0.1"
    author = "Martin Sivak"

    flows = Flow.init(Plugin)
    del flows["fix"]
    flows["blueprint"] = flows["diagnose"]

    def __init__(self, *args, **kwargs):
        Plugin.__init__(self, *args, **kwargs)
        self._issue = SimpleIssue(self.name, self.description)
        self._yum_repos_d = "/etc/yum.repos.d"

    def prepare(self):
        self._result = ReturnSuccess
        self._issue.set(reporting=self._reporting, origin=self, level=PLUGIN)

    def diagnose(self):
        self._reporting.info("Getting list of Yum repository files",
                             origin=self,
                             level=PLUGIN)
        repos = [
            n[:-5] for n in os.listdir(self._yum_repos_d)
            if n.endswith(".repo")
        ]

        for fn in repos:
            repo_issue = None
            try:
                repo_issue = SimpleIssue(
                    "reading Yum repo config %s" % fn,
                    "I was unable to process the repository configuration.")
                repo_issue.set(checked=False,
                               happened=False,
                               reporting=self._reporting,
                               origin=self,
                               level=PLUGIN)
                f = open(os.path.join(self._yum_repos_d, fn + ".repo"))
                content = f.read().replace("\\", "\\\\").replace("\n", "\\n")
                setattr(self._info, fn, content)
                f.close()
                repo_issue.set(checked=True,
                               happened=False,
                               reporting=self._reporting,
                               origin=self,
                               level=PLUGIN)
            except IOError:
                repo_issue.set(checked=True,
                               happened=True,
                               reporting=self._reporting,
                               origin=self,
                               level=PLUGIN)

        self._result = ReturnSuccess
        self._issue.set(checked=True,
                        happened=False,
                        reporting=self._reporting,
                        origin=self,
                        level=PLUGIN)

    def clean(self):
        self._result = ReturnSuccess
Ejemplo n.º 17
0
 def __init__(self, *args, **kwargs):
     Plugin.__init__(self, *args, **kwargs)
     self._issue = SimpleIssue(self.name, self.description)
     self._yum_repos_d = "/etc/yum.repos.d"
Ejemplo n.º 18
0
 def __init__(self, *args, **kwargs):
     Plugin.__init__(self, *args, **kwargs)
     self._issue = SimpleIssue(self.name, self.description)
Ejemplo n.º 19
0
class Sample1Plugin(Plugin):
    """Discover information about the system"""
    name = "Discovery"
    description = "Discover properties of the system"
    version = "0.0.1"
    author = "Martin Sivak"

    flows = Flow.init(Plugin)
    flows["fix"] = flows["diagnose"]

    def __init__(self, *args, **kwargs):
        Plugin.__init__(self, *args, **kwargs)
        self._issue = SimpleIssue(self.name, "Discovering system properties failed")

    def prepare(self):
        self._issue.set(reporting  = self._reporting, origin = self, level = PLUGIN)
        self._result=ReturnSuccess

    def diagnose(self):
        #architecture and cpus
        (unamestdout, unamestderr) = spawnvch(executable = "/bin/uname", args = ["uname", "-a"], chroot = Config.system.root).communicate("")
        self._info.uname = unamestdout.split("\n")[0]

        #memory
        (freestdout, freestderr) = spawnvch(executable = "/usr/bin/free", args = ["free"], chroot = Config.system.root).communicate("")
        freedata = freestdout.split("\n")
        self._info.memory = freedata[1].split()[1]
        self._info.swap = freedata[3].split()[1]

        #pci
        pcilist = []
        (lspcistdout, lspcistderr) = spawnvch(executable = "/sbin/lspci", args = ["lspci"], chroot = Config.system.root).communicate("")
        for l in lspcistdout.split("\n"):
            try:
                (id, name) = l.split(" ", 1)
                setattr(self._info, "_".join(["pci", id]), name)
                pcilist.append(id)
            except:
                pass
        self._info.pci = " ".join(pcilist)

        #usb
        if os.path.exists(os.path.join(Config.system.root, "/proc/bus/usb")):
            self._info.usb = "True"
        else:
            self._info.usb = "False"

        #scsi
        if os.path.exists(os.path.join(Config.system.root, "/proc/scsi/device_info")):
            self._info.scsi = "True"
        else:
            self._info.scsi = "False"

        #ide
        if os.path.exists(os.path.join(Config.system.root, "/proc/ide")):
            self._info.ide = "True"
        else:
            self._info.ide = "False"

        #partitions
        partitionlist = []
        for l in open("/proc/partitions").readlines()[2:]:
            try:
                (major, minor, blocks, name) = l.split()
                if name.startswith("ram"):
                    continue
                setattr(self._info, "_".join(["partition", name]), blocks)
                partitionlist.append(name)
            except:
                continue
        self._info.partition = " ".join(partitionlist)

        #net


        self._dependencies.provide("discovery")
        self._issue.set(checked = True, happened = False, reporting  = self._reporting, origin = self, level = PLUGIN)
        self._result=ReturnSuccess

    def clean(self):
        self._result=ReturnSuccess