def test_check_infinity1(self): expected_results = { -1001341: True, -96: True, -95.999: True, -95.99: True, -95.989: False, -95: False, 0: False, 5.7501: False, 79.999999: False, } log.info("Testing range negative infinity .. -95.99") import nagios from nagios.plugin.range import NagiosRange try: nrange = NagiosRange('~:-95.99') log.debug("NagiosRange object: %r", nrange) nrange_str = str(nrange) log.debug("Stringified NagiosRange object: %r", nrange_str) if nrange_str != '~:-95.99': self.fail("Stringified NagiosRange should be '~:-95.99'.") 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)))
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)))
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)))
def test_check_normal1(self): expected_results = { -23: False, -7: True, -1: True, 0: True, 4: True, 23: True, 23.1: False, 79.999999: False, } log.info("Testing range -7 .. 23") import nagios from nagios.plugin.range import NagiosRange try: nrange = NagiosRange('-7:23') log.debug("NagiosRange object: %r", nrange) nrange_str = str(nrange) log.debug("Stringified NagiosRange object: %r", nrange_str) if nrange_str != '-7:23': self.fail("Stringified NagiosRange should be '-7:23'.") 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)))
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)
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
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)
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()
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()