Exemple #1
0
    def __init__(self):
        """
        Constructor of the CheckMegaRaidHotsparePlugin class.
        """

        usage = """\
                %(prog)s [-v] [-a <adapter_nr>] -c <critical_hotspares>: -w <warning_hotspares>:
                """
        usage = textwrap.dedent(usage).strip()
        usage += '\n       %(prog)s --usage'
        usage += '\n       %(prog)s --help'

        blurb = "Copyright (c) 2015 Frank Brehm, Berlin.\n\n"
        blurb += "Checks the number of hotspare drives on a LSI MegaRaid adapter."

        super(CheckMegaRaidHotsparePlugin, self).__init__(
            shortname='MEGARAID_HOTSPARE',
            usage=usage, blurb=blurb,
            version=__version__,
        )

        self._critical_number = NagiosRange('1:')

        self._warning_number = NagiosRange('2:')

        self._add_args()
Exemple #2
0
    def parse_args_second(self):
        """
        Evaluates comand line parameters after evaluating the configuration.
        """

        # define Hostname
        hn = self.argparser.args.hostname
        if hn:
            hn = hn.strip()
        if hn:
            self._hostname = hn.lower()

        # define storage volume group
        if self.argparser.args.pb_vg:
            self._pb_vg = self.argparser.args.pb_vg

        if not self.pb_vg:
            self._pb_vg = os.environ.get('LVM_VG_NAME')
        if not self.pb_vg:
            self._pb_vg = DEFAULT_PB_VG

        # define warning level
        if self.argparser.args.warning is not None:
            self._warning = NagiosRange(self.argparser.args.warning)

        # define critical level
        if self.argparser.args.critical is not None:
            self._critical = NagiosRange(self.argparser.args.critical)

        # set thresholds
        self.set_thresholds(
            warning=self.warning,
            critical=self.critical,
        )
Exemple #3
0
    def test_check_zero(self):

        expected_results = {
                0.5: False,
                0: True,
                -10: True,
        }

        log.info("Testing range <= zero")

        import nagios
        from nagios.plugin.range import NagiosRange

        try:
            nrange = NagiosRange('~:0')
            log.debug("NagiosRange object: %r", nrange)
            nrange_str = str(nrange)
            log.debug("Stringified NagiosRange object: %r", nrange_str)
            if nrange_str != '~:0':
                self.fail("Stringified NagiosRange should be '~:0'.")

            for value in sorted(expected_results.keys()):
                exp_result = expected_results[value]
                result = nrange.check(value)
                log.debug("Check %r, result is %r, expected is %r", value,
                        result, exp_result)
                if not exp_result == result:
                    self.fail("Unexpected result of check(), checked %r "
                            "against '0:6', got %r, expected %r." % (value,
                            result, exp_result))

        except Exception as e:
            self.fail("Could not instatiate NagiosRange by a %s: %s" % (
                    e.__class__.__name__, str(e)))
Exemple #4
0
    def parse_args_second(self):
        """
        Evaluates comand line parameters after evaluating the configuration.
        """

        # define Hostname
        hn = self.argparser.args.hostname
        if hn:
            hn = hn.strip()
        if hn:
            self._hostname = hn.lower()

        # define storage volume group
        if self.argparser.args.storage_vg:
            self._storage_vg = self.argparser.args.storage_vg

        may_have = getattr(self.argparser, 'may_have_rw_img_exports', False)
        if may_have:
            self._may_have_rw_img_exports = True
        # TODO: delete later
        self._may_have_rw_img_exports = True

        # define warning level
        if self.argparser.args.warning is not None:
            self._warning = NagiosRange(self.argparser.args.warning)

        # define critical level
        if self.argparser.args.critical is not None:
            self._critical = NagiosRange(self.argparser.args.critical)

        # set thresholds
        self.set_thresholds(warning=self.warning, critical=self.critical)
Exemple #5
0
    def test_check_zero(self):

        expected_results = {
            0.5: False,
            0: True,
            -10: True,
        }

        log.info("Testing range <= zero")

        import nagios
        from nagios.plugin.range import NagiosRange

        try:
            nrange = NagiosRange('~:0')
            log.debug("NagiosRange object: %r", nrange)
            nrange_str = str(nrange)
            log.debug("Stringified NagiosRange object: %r", nrange_str)
            if nrange_str != '~:0':
                self.fail("Stringified NagiosRange should be '~:0'.")

            for value in sorted(expected_results.keys()):
                exp_result = expected_results[value]
                result = nrange.check(value)
                log.debug("Check %r, result is %r, expected is %r", value,
                          result, exp_result)
                if not exp_result == result:
                    self.fail("Unexpected result of check(), checked %r "
                              "against '0:6', got %r, expected %r." %
                              (value, result, exp_result))

        except Exception as e:
            self.fail("Could not instatiate NagiosRange by a %s: %s" %
                      (e.__class__.__name__, str(e)))
Exemple #6
0
    def __init__(self):
        """
        Constructor of the CheckDcmanagerApiPlugin class.
        """

        usage = """\
                %(prog)s [options] [--api-url <api_url>] [-c <critical_time>] [-w <warning_time>]
                """
        usage = textwrap.dedent(usage).strip()
        usage += '\n       %(prog)s --usage'
        usage += '\n       %(prog)s --help'

        blurb = __copyright__ + "\n\n"
        blurb += "Checks the ability of the DcManager API."

        super(CheckDcmanagerApiPlugin, self).__init__(
            shortname='PB_DCM_API',
            usage=usage,
            blurb=blurb,
            timeout=DEFAULT_TIMEOUT,
        )

        self._warning = NagiosRange(start=0.0, end=DEFAULT_WARN_TIME)
        """
        @ivar: the warning threshold of the test, the maximum time for a reply
               before a warning result is given
        @type: NagiosRange
        """

        self._critical = NagiosRange(start=0.0, end=DEFAULT_CRIT_TIME)
        """
Exemple #7
0
    def __init__(self):
        """
        Constructor of the CheckPbStorageExportsPlugin class.
        """

        failed_commands = []

        usage = """\
                %(prog)s [options] [-H <server_name>] [-c <critical_errors>] [-w <warning_errors>]
                """
        usage = textwrap.dedent(usage).strip()
        usage += '\n       %(prog)s --usage'
        usage += '\n       %(prog)s --help'

        blurb = __copyright__ + "\n\n"
        blurb += ("Checks correctness of exported and/or not exported volumes "
                  "on ProfitBricks storage servers.")

        self._hostname = socket.gethostname()
        """
        @ivar: the hostname of the current storage server
        @type: str
        """

        self._storage_vg = DEFAULT_STORAGE_VG
        self._may_have_rw_img_exports = False
        self._current_cluster = None

        super(CheckPbStorageExportsPlugin, self).__init__(
            shortname='PB_STORAGE_EXPORTS',
            usage=usage, blurb=blurb,
            timeout=DEFAULT_TIMEOUT,
        )

        self._warning = NagiosRange(DEFAULT_WARN_ERRORS)
        """
        @ivar: the warning threshold of the test, max number of export errors,
               before a warning result is given
        @type: NagiosRange
        """

        self._critical = NagiosRange(DEFAULT_CRIT_ERRORS)
        """
        @ivar: the critical threshold of the test, max number of export errors,
               before a critical result is given
        @type: NagiosRange
        """

        self.all_api_exports = {}
        self.storage_exports = []
        self.image_exports = []
        self.existing_exports = {}
        self.count = {}
        self.valid_pservers = {}

        # Some commands are missing
        if failed_commands:
            raise CommandNotFoundError(failed_commands)
Exemple #8
0
    def critical(self, value):
        if value is None or (
                isinstance(value, str) and value == ''):
            self._critical = NagiosRange()
            return

        if isinstance(value, NagiosRange):
            self._critical = value
            return

        if isinstance(value, int) or isinstance(value, int):
            value = "%d" % (value)
        elif isinstance(value, float):
            value = "%f" % (value)

        self._critical = NagiosRange(value)
Exemple #9
0
 def test_performance_object_01(self):
     log.info("Testing init NagiosPerformance object lap 1.")
     warn_range = NagiosRange('30')
     crit_range = NagiosRange('~:60')
     perf = NagiosPerformance(label = 'bla', value = 40, warning = warn_range,
             critical = crit_range, uom = 'MByte')
     log.debug("NagiosPerformance object: %r", perf)
     self.assertEqual(perf.label, 'bla', 'Error testing perf.label')
     self.assertEqual(perf.value, 40, 'Error testing perf.value')
     self.assertEqual(perf.uom, 'MByte', 'Error testing perf.uom')
     self.assertEqual(perf.warning.start, 0, 'Error testing perf.warning.start')
     self.assertEqual(perf.warning.end, 30, 'Error testing perf.warning.end')
     self.assertEqual(perf.critical.start, None, 'Error testing perf.critical.start')
     self.assertEqual(perf.critical.end, 60, 'Error testing perf.critical.end')
     self.assertEqual(perf.min_data, None, 'Error testing perf.min_data')
     self.assertEqual(perf.max_data, None, 'Error testing perf.max_data')
     self.assertEqual(perf.status(), nagios.state.warning, 'Error testing perf.status()')
Exemple #10
0
 def test_performance_object_00(self):
     log.info("Testing init NagiosPerformance object lap 0.")
     warn_range = NagiosRange('30')
     crit_range = NagiosRange('60')
     th = NagiosThreshold(warning = warn_range, critical = crit_range)
     perf = NagiosPerformance(label = 'bla', value = 10, threshold = th,
             uom = 'MByte', min_data = 0, max_data = 1000)
     log.debug("NagiosPerformance object: %r", perf)
     self.assertEqual(perf.label, 'bla', 'Error testing perf.label')
     self.assertEqual(perf.value, 10, 'Error testing perf.value')
     self.assertEqual(perf.uom, 'MByte', 'Error testing perf.uom')
     self.assertEqual(perf.warning.start, 0, 'Error testing perf.warning.start')
     self.assertEqual(perf.warning.end, 30, 'Error testing perf.warning.end')
     self.assertEqual(perf.critical.start, 0, 'Error testing perf.critical.start')
     self.assertEqual(perf.critical.end, 60, 'Error testing perf.critical.end')
     self.assertEqual(perf.min_data, 0, 'Error testing perf.min_data')
     self.assertEqual(perf.max_data, 1000, 'Error testing perf.max_data')
     self.assertEqual(perf.status(), nagios.state.ok, 'Error testing perf.status()')
Exemple #11
0
    def parse_args(self, args=None):
        """
        Executes self.argparser.parse_args().

        @param args: the argument strings to parse. If not given, they are
                     taken from sys.argv.
        @type args: list of str or None

        """

        super(CheckSmartStatePlugin, self).parse_args(args)

        self.init_root_logger()

        self._warn_sectors = NagiosRange(start=0, end=self.argparser.args.warning)
        self._crit_sectors = NagiosRange(start=0, end=self.argparser.args.critical)

        self.set_thresholds(warning=self.warn_sectors, critical=self.crit_sectors)

        if not self.argparser.args.device:
            self.die("No device to check given.")

        dev = os.path.basename(self.argparser.args.device)
        dev_dev = os.sep + os.path.join('dev', dev)
        sys_dev = os.sep + os.path.join('sys', 'block', dev)

        if not os.path.isdir(sys_dev):
            self.die("Device %r is not a block device." % (dev))

        if not os.path.exists(dev_dev):
            self.die("Device %r doesn't exists." % (dev_dev))

        dev_stat = os.stat(dev_dev)
        dev_mode = dev_stat.st_mode
        if not stat.S_ISBLK(dev_mode):
            self.die("%r is not a block device." % (dev_dev))

        self._device = dev_dev

        if self.argparser.args.megaraid:
            self._init_megacli_dev(self.argparser.args.megaraid)
Exemple #12
0
    def test_check_inverse(self):

        expected_results = {
            -134151: True,
            -2: True,
            -1: True,
            0: False,
            0.001: False,
            32.88: False,
            657.8210567: False,
            657.9: True,
            123456789012345: True,
        }

        log.info("Testing range inverse 0 .. 657.8210567")

        import nagios
        from nagios.plugin.range import NagiosRange

        try:
            nrange = NagiosRange('@0:657.8210567')
            log.debug("NagiosRange object: %r", nrange)
            nrange_str = str(nrange)
            log.debug("Stringified NagiosRange object: %r", nrange_str)
            if nrange_str != '@657.8210567':
                self.fail(
                    "Stringified NagiosRange should be '@0:657.8210567'.")

            for value in sorted(expected_results.keys()):
                exp_result = expected_results[value]
                result = nrange.check(value)
                log.debug("Check %r, result is %r, expected is %r", value,
                          result, exp_result)
                if not exp_result == result:
                    self.fail("Unexpected result of check(), checked %r "
                              "against '0:6', got %r, expected %r." %
                              (value, result, exp_result))

        except Exception as e:
            self.fail("Could not instatiate NagiosRange by a %s: %s" %
                      (e.__class__.__name__, str(e)))
Exemple #13
0
    def parse_args_second(self):
        """
        Method to evaluate command line parameters after evaluating
        the configuration.
        """

        # define warning level
        if self.argparser.args.warning is not None:
            self._warning = NagiosRange(start=0.0,
                                        end=self.argparser.args.warning)

        # define critical level
        if self.argparser.args.critical is not None:
            self._critical = NagiosRange(start=0.0,
                                         end=self.argparser.args.critical)

        # set thresholds
        self.set_thresholds(
            warning=self.warning,
            critical=self.critical,
        )
Exemple #14
0
    def test_check_inverse(self):

        expected_results = {
                -134151: True,
                -2: True,
                -1: True,
                0: False,
                0.001: False,
                32.88: False,
                657.8210567: False,
                657.9: True,
                123456789012345: True,
        }

        log.info("Testing range inverse 0 .. 657.8210567")

        import nagios
        from nagios.plugin.range import NagiosRange

        try:
            nrange = NagiosRange('@0:657.8210567')
            log.debug("NagiosRange object: %r", nrange)
            nrange_str = str(nrange)
            log.debug("Stringified NagiosRange object: %r", nrange_str)
            if nrange_str != '@657.8210567':
                self.fail("Stringified NagiosRange should be '@0:657.8210567'.")

            for value in sorted(expected_results.keys()):
                exp_result = expected_results[value]
                result = nrange.check(value)
                log.debug("Check %r, result is %r, expected is %r", value,
                        result, exp_result)
                if not exp_result == result:
                    self.fail("Unexpected result of check(), checked %r "
                            "against '0:6', got %r, expected %r." % (value,
                            result, exp_result))

        except Exception as e:
            self.fail("Could not instatiate NagiosRange by a %s: %s" % (
                    e.__class__.__name__, str(e)))
Exemple #15
0
    def test_empty_object(self):

        log.info("Testing uninitialized range object.")

        import nagios
        from nagios.plugin.range import NagiosRange

        try:
            nrange = NagiosRange()
            log.debug("NagiosRange object: %r", nrange)
        except Exception as e:
            self.fail("Could not instatiate NagiosRange by a %s: %s" %
                      (e.__class__.__name__, str(e)))
Exemple #16
0
    def test_parse_float(self):

        log.info("Testing initialized range object with float limits.")

        import nagios
        from nagios.plugin.range import NagiosRange

        try:
            nrange = NagiosRange('1.1:10.999')
            log.debug("NagiosRange object: %r", nrange)
        except Exception as e:
            self.fail("Could not instatiate NagiosRange by a %s: %s" %
                      (e.__class__.__name__, str(e)))
Exemple #17
0
    def test_method_check_range(self):

        log.info("Testing method check_range() ...")

        import nagios
        from nagios.plugin.range import NagiosRange

        try:
            nrange = NagiosRange(':6')
            log.debug("NagiosRange object: %r", nrange)

            log.debug("Testing check_range(5) == False ...")
            if nrange.check_range(5):
                self.fail("check_range(5) should return False.")

            log.debug("Testing check_range(7) == True ...")
            if not nrange.check_range(7):
                self.fail("check_range(7) should return True.")

        except Exception as e:
            self.fail("Could not instatiate NagiosRange by a %s: %s" % (
                    e.__class__.__name__, str(e)))
Exemple #18
0
    def test_method_check_range(self):

        log.info("Testing method check_range() ...")

        import nagios
        from nagios.plugin.range import NagiosRange

        try:
            nrange = NagiosRange(':6')
            log.debug("NagiosRange object: %r", nrange)

            log.debug("Testing check_range(5) == False ...")
            if nrange.check_range(5):
                self.fail("check_range(5) should return False.")

            log.debug("Testing check_range(7) == True ...")
            if not nrange.check_range(7):
                self.fail("check_range(7) should return True.")

        except Exception as e:
            self.fail("Could not instatiate NagiosRange by a %s: %s" %
                      (e.__class__.__name__, str(e)))
Exemple #19
0
    def __init__(self, warning=None, critical=None):
        """
        Initialisation of the NagiosThreshold object.

        @param warning: the warning threshold
        @type warning: str, int, long, float or NagiosRange
        @param critical: the critical threshold
        @type critical: str, int, long, float or NagiosRange

        """

        self._warning = NagiosRange()
        """
        @ivar: the warning threshold
        @type: NagiosRange
        """

        self._critical = NagiosRange()
        """
        @ivar: the critical threshold
        @type: NagiosRange
        """

        self.set_thresholds(warning=warning, critical=critical)
Exemple #20
0
    def test_invalid(self):

        values = (':', '1:~', 'foo', '1-10', '10:~', '1-10:2.4', '1,10', '5:3',
                  '~:')
        log.info("Checking for invalid ranges ...")

        import nagios
        from nagios.plugin.range import NagiosRange
        from nagios.plugin.range import InvalidRangeError

        for value in values:
            try:
                nrange = NagiosRange(value)
            except InvalidRangeError as e:
                log.debug("Found incorrect range %r.", value)
            else:
                self.fail("Range %r should be incorrect, but lead to %r.",
                          value, nrange)
Exemple #21
0
    def test_limits_infinity(self):

        log.info("Checking neative infinity range limits ...")

        import nagios
        from nagios.plugin.range import NagiosRange

        try:
            nrange = NagiosRange('~:6')
            log.debug("NagiosRange object: %r", nrange)
            if nrange.start is not None:
                self.fail("Start limit should be None.")
            if not (nrange.end is not None and nrange.end == 6):
                self.fail("End limit should be 6.")
            nrange_str = str(nrange)
            log.debug("Stringified NagiosRange object: %r", nrange_str)
            if nrange_str != '~:6':
                self.fail("Stringified NagiosRange should be '~:6'.")
        except Exception as e:
            self.fail("Could not instatiate NagiosRange by a %s: %s" %
                      (e.__class__.__name__, str(e)))
Exemple #22
0
    def test_operator_in(self):

        log.info("Testing overloaded operator 'in' ...")

        import nagios
        from nagios.plugin.range import NagiosRange

        try:
            nrange = NagiosRange('6')
            log.debug("NagiosRange object: %r", nrange)

            log.debug("Checking '7 in range \"%s\"'", nrange)
            if 7 in nrange:
                self.fail("Value 7 should be outside range '%s'." % (nrange))

            log.debug("Checking '5 not in range \"%s\"'", nrange)
            if not 5 in nrange:
                self.fail("Value 5 should be inside range '%s'." % (nrange))

        except Exception as e:
            self.fail("Could not instatiate NagiosRange by a %s: %s" %
                      (e.__class__.__name__, str(e)))
Exemple #23
0
    def __init__(self):
        """
        Constructor of the CheckPbConsistenceStoragePlugin class.
        """

        failed_commands = []

        usage = (
            "%(prog)s [options] [-H <server_name>] [-c <critical_volume_errors>]"
            " [-w <warning_volume_errors>]")
        usage += '\n       %(prog)s --usage'
        usage += '\n       %(prog)s --help'

        blurb = __copyright__ + "\n\n"
        blurb += ("Checks the existent volumes on a storage server against "
                  "the target state from provisioning database.")

        self._hostname = socket.gethostname()
        """
        @ivar: the hostname of the current storage server
        @type: str
        """

        super(CheckPbConsistenceStoragePlugin, self).__init__(
            shortname='PB_CONSIST_STORAGE',
            usage=usage,
            blurb=blurb,
            timeout=DEFAULT_TIMEOUT,
        )

        self._pb_vg = None
        """
        @ivar: the name of the ProfitBricks storage volume group
        """

        self._warning = NagiosRange(DEFAULT_WARN_VOL_ERRORS)
        """
        @ivar: the warning threshold of the test, max number of volume errors,
               before a warning result is given
        @type: NagiosRange
        """

        self._critical = NagiosRange(DEFAULT_CRIT_VOL_ERRORS)
        """
        @ivar: the critical threshold of the test, max number of volume errors,
               before a critical result is given
        @type: NagiosRange
        """

        # /sbin/lvm
        self._lvm_command = LVM_BIN_PATH
        """
        @ivar: the 'lvm' command in operating system
        @type: str
        """
        if not os.path.exists(self.lvm_command):
            self._lvm_command = self.get_command('lvm')
        if not os.path.exists(self.lvm_command):
            failed_commands.append('lvm')

        self.api_volumes = []
        self.api_images = []
        self.api_snapshots = []
        self.all_api_volumes = []
        self.lvm_lvs = []
        self.count = {}

        # Some commands are missing
        if failed_commands:
            raise CommandNotFoundError(failed_commands)
Exemple #24
0
    def __call__(self):
        """
        Method to call the plugin directly.
        """

        self.parse_args()
        self.init_root_logger()

        ps_cmd = PS_CMD
        if self.argparser.args.ps_cmd:
            self._ps_cmd = self.get_command(self.argparser.args.ps_cmd)
            ps_cmd = self.argparser.args.ps_cmd
        if not self.ps_cmd:
            msg = "Command %r not found." % (ps_cmd)
            self.die(msg)

        if os.path.exists(PID_MAX_FILE):
            log.debug("Reading %r ...", PID_MAX_FILE)
            self._pid_max = int(self.read_file(PID_MAX_FILE, quiet=True))
            log.debug("Got a pid_max value of %d processes.", self._pid_max)
            self._warning = NagiosRange(self.pid_max * 70 / 100)
            self._critical = NagiosRange(self.pid_max * 90 / 100)

        if self.argparser.args.user:
            self.user = self.argparser.args.user
            if self.user is None:
                msg = "Invalid user name or UID %r given." % (
                    self.argparser.args.user)
                self.die(msg)

        match = re_percent.search(self.argparser.args.warning)
        if match:
            percent = float(match.group(1))
            warning = int(self.pid_max * percent / 100)
            self._warning = NagiosRange(warning)
        else:
            self._warning = NagiosRange(self.argparser.args.warning)

        match = re_percent.search(self.argparser.args.critical)
        if match:
            percent = float(match.group(1))
            critical = int(self.pid_max * percent / 100)
            self._critical = NagiosRange(critical)
        else:
            self._critical = NagiosRange(self.argparser.args.critical)

        if self.verbose > 1:
            log.debug("Got thresholds: warning: %s, critical: %s.",
                      self.warning, self.critical)

        self.set_thresholds(warning=self.warning, critical=self.critical)

        if self.verbose > 2:
            log.debug("Current object:\n%s", pp(self.as_dict()))

        uom = self.get_uom()
        label = self.get_label()

        found_processes = self.collect_processes()
        value_total = self.get_total_value(found_processes)
        count = len(found_processes)

        log.debug("Got a total value (by %s) of %d%s.",
                  self.argparser.args.metric, value_total, uom)

        state = self.threshold.get_status(value_total)
        self.add_perfdata(
            label=label,
            value=value_total,
            uom=uom,
            threshold=self.threshold,
        )

        plural = ''
        if count != 1:
            plural = 'es'
        out = "%d process%s" % (count, plural)
        fdescription = self.get_filter_description()
        if fdescription:
            out += ' with ' + fdescription

        self.exit(state, out)
Exemple #25
0
    def __init__(self):
        """
        Constructor of the CheckProcsPlugin class.
        """

        usage = """\
        %(prog)s [-v] [-t <timeout>] [-c <critical_threshold>] [-w <warning_threshold>]
                   [-m <metric>] [-s <statusflags>] [--ps-cmd <command>]
                   [--ppid <parent_pid>] [--rss <value>] [--pcpu <value>] [--vsz <value>]
                   [--user <user_id>] [-a <args>] [-C <command>] [--init]
        %(prog)s --usage
        %(prog)s --help
        """
        usage = textwrap.dedent(usage).strip()

        blurb = """\
        Copyright (c) 2015 Frank Brehm, Berlin.

        Checks all processes and generates WARNING or CRITICAL states if the specified
        metric is outside the required threshold ranges. The metric defaults to number
        of processes.  Search filters can be applied to limit the processes to check.
        """
        blurb = textwrap.dedent(blurb).strip()

        super(CheckProcsPlugin, self).__init__(usage=usage, blurb=blurb)

        self._ps_cmd = PS_CMD
        """
        @ivar: the underlaying 'ps' command
        @type: str
        """
        if not os.path.exists(self.ps_cmd) or not os.access(
                self.ps_cmd, os.X_OK):
            self._ps_cmd = self.get_command('ps')

        self._user = None
        """
        @ivar: Only scan for processes with user name or ID indicated.
        @type: str
        """

        self._pid_max = 2**15
        """
        @ivar: The maximum number of processes in the system,
               defaults to 32768
        @type: int
        """

        self._warning = NagiosRange(self.pid_max * 70 / 100)
        """
        @ivar: the warning threshold of the test, defaults to
               70 % of the maximum number of processes in the system
        @type: NagiosRange
        """

        self._critical = NagiosRange(self.pid_max * 90 / 100)
        """
        @ivar: the critical threshold of the test, defaults to
               90 % of the maximum number of processes in the system
        @type: NagiosRange
        """

        self._add_args()
Exemple #26
0
    def __init__(self):
        """
        Constructor of the CheckSmartStatePlugin class.
        """

        usage = """\
        %(prog)s [-v] [-m] -c <critical grown sectors> -w <warn grown sectors> <HD device>
        """
        usage = textwrap.dedent(usage).strip()
        usage += '\n       %(prog)s --usage'
        usage += '\n       %(prog)s --help'

        blurb = "Copyright (c) 2015 Frank Brehm, Berlin.\n\n"
        blurb += "Checks the SMART state of a physical hard drive."

        super(CheckSmartStatePlugin, self).__init__(
            usage=usage, blurb=blurb,
            append_searchpath=[DEFAULT_MEGARAID_PATH],
        )

        self._smartctl_cmd = self.get_command('smartctl')
        """
        @ivar: the underlaying 'smartctl' command
        @type: str
        """
        if not self.smartctl_cmd:
            msg = "Command %r not found." % ('smartctl')
            self.die(msg)

        self._megacli_cmd = None
        """
        @ivar: the 'MegaCLI' command for detecting Device Id from an enclosure:slot data
        @type: str
        """

        self._megaraid = False
        """
        @ivar: Is the given device a PhysicalDrive on a MegaRaid adapter
        @type: bool
        """

        self._warn_sectors = NagiosRange(start=0, end=DEFAULT_WARN_SECTORS)
        """
        @ivar: number of grown defect sectors leading to a warning
        @type: NagiosRange
        """

        self._crit_sectors = NagiosRange(start=0, end=DEFAULT_CRIT_SECTORS)
        """
        @ivar: number of grown defect sectors leading to a critical message
        @type: NagiosRange
        """

        self._device = None
        """
        @ivar: the device to check
        @type: str
        """

        self._device_id = None
        """
        @ivar: the MegaRaid Device Id of the PD on the MegaRAID controller.
        @type: int
        """

        self._megaraid_slot = None
        """
        @ivar: the MegaRaid enclusure-Id/slot-Id pair to check
        @type: tuple of two int
        """

        self._adapter_nr = 0
        """
        @ivar: the number of the MegaRaid adapter (e.g. 0)
        @type: str
        """

        self._init_megacli_cmd()

        self._add_args()
Exemple #27
0
    def __init__(self,
                 label,
                 value,
                 uom=None,
                 threshold=None,
                 warning=None,
                 critical=None,
                 min_data=None,
                 max_data=None):
        """
        Initialisation of the NagiosPerformance object.

        @param label: the label of the performance data, mandantory
        @type label: str
        @param value: the value of the performance data, mandantory
        @type value: Number
        @param uom: the unit of measure
        @type uom: str or None
        @param threshold: an object for the warning and critical thresholds
                          if set, it overrides the warning and critical parameters
        @type threshold: NagiosThreshold or None
        @param warning: a range for the warning threshold,
                        ignored, if threshold is given
        @type warning: NagiosRange, str, Number or None
        @param critical: a range for the critical threshold,
                        ignored, if threshold is given
        @type critical: NagiosRange, str, Number or None
        @param min_data: the minimum data for performance output
        @type min_data: Number or None
        @param max_data: the maximum data for performance output
        @type max_data: Number or None

        """

        self._label = str(label).strip()
        """
        @ivar: the label of the performance data
        @type: str
        """
        if label is None or self._label == '':
            raise NagiosPerformanceError(
                "Empty label %r for NagiosPerformance given." % (label))

        self._value = value
        """
        @ivar: the value of the performance data
        @type: Number
        """
        if not isinstance(value, Number):
            raise NagiosPerformanceError(
                "Wrong value %r for NagiosPerformance given." % (value))

        self._uom = ''
        """
        @ivar: the unit of measure
        @type: str
        """
        if uom is not None:
            # remove all whitespaces
            self._uom = re_ws.sub('', str(uom))

        warn_range = NagiosRange()
        if warning:
            warn_range = NagiosRange(warning)

        crit_range = NagiosRange()
        if critical:
            crit_range = NagiosRange(critical)

        self._threshold = None
        """
        @ivar: the threshold object containing the warning and the
               critical threshold
        @type: NagiosThreshold
        """
        if isinstance(threshold, NagiosThreshold):
            self._threshold = threshold
        elif threshold is not None:
            raise NagiosPerformanceError(
                "The given threshold %r is neither None nor a NagiosThreshold object."
                % (threshold))
        else:
            self._threshold = NagiosThreshold(warning=warn_range,
                                              critical=crit_range)

        self._min_data = None
        """
        @ivar: the minimum data for performance output
        @type: Number or None
        """
        if min_data is not None:
            if not isinstance(min_data, Number):
                raise NagiosPerformanceError(
                    "The given min_data %r is not None and not a Number." %
                    (min_data))
            else:
                self._min_data = min_data

        self._max_data = None
        """
        @ivar: the maximum data for performance output
        @type: Number or None
        """
        if max_data is not None:
            if not isinstance(max_data, Number):
                raise NagiosPerformanceError(
                    "The given max_data %r is not None and not a Number." %
                    (max_data))
            else:
                self._max_data = max_data