Example #1
0
class testPluginHelper(unittest.TestCase):
    def setUp(self):
        self.argv_store = sys.argv
        from pynag.Plugins import PluginHelper
        self.my_plugin = PluginHelper()
        self.my_plugin.parser.add_option('-F',
                                         dest='fakedata',
                                         help='fake data to test thresholds')
        sys.stdout = StringIO()
    def tearDown(self):
        sys.argv = self.argv_store
        sys.stdout = original_stdout

    def run_expect(self, case, value, expected_exit):
        sys.argv = [sys.argv[0]] + case.split() + ('-F %s' % value).split()
        self.my_plugin.parse_arguments()
        self.my_plugin.add_status(pynag.Plugins.ok)
        self.my_plugin.add_summary(self.my_plugin.options.fakedata)
        self.my_plugin.add_metric('fakedata', self.my_plugin.options.fakedata)
        try:
            self.my_plugin.check_all_metrics()
            self.my_plugin.exit()
        except SystemExit, e:
            self.assertEquals(type(e), type(SystemExit()))
            self.assertEquals(e.code, expected_exit)
        except Exception, e:
            self.fail('unexpected exception: %s' % e)
Example #2
0
def main():
        helper = PluginHelper()

        helper.parser.add_option('-w', help='warning free (X% or XM)', dest='warning')
        helper.parser.add_option('-c', help='critical free (X% or XM)', dest='critical')
        helper.parse_arguments()
        warn = helper.options.warning
        crit = helper.options.critical

	memory = getMemory()


	if helper.options.warning is not None:
		warn = helper.options.warning
		if re.match('.*%$', warn):
			warn = str(memory['total'] * int(re.search('\d*', warn).group(0)) / 100)
	else:
		warn = '0'

	if helper.options.critical is not None:
		crit = helper.options.critical
		if re.match('.*%$', crit):
			crit = str(memory['total'] * int(re.search('\d*', crit).group(0)) / 100)
	else:
		crit = '0'

        helper.status(ok)
	status = "OK"

	if memory['totalfree'] <= int(warn):
		helper.status(warning)
		status = "WARNING"

	if memory['totalfree'] <= int(crit):
		helper.status(critical)
		status = "CRITICAL"

	helper.add_summary(status + ': Memory free: %(totalfree)s %% (%(free)s %% including buffers/cached)' % {'totalfree': (round((float(memory['totalfree']) / float(memory['total']) * 100), 1 )), 'free': (round((float(memory['free']) / float(memory['total']) * 100), 1 ))})
        helper.add_metric(label='total',value=memory['total'])
        helper.add_metric(label='free',value=memory['free'])
        helper.add_metric(label='totalfree',value=memory['totalfree'], warn=warn+'..0', crit=crit+'..0')
        helper.add_metric(label='used',value=memory['used'])
        helper.add_metric(label='buffers',value=memory['buffers'])
        helper.add_metric(label='cached',value=memory['cached'])
        helper.add_metric(label='swapcached',value=memory['swapcached'])


	helper.check_all_metrics()
        helper.exit()
Example #3
0
    def check_metric(self):
        """Check if the metric value is within the threshold range, and exits with status code,
        message and perfdata.
        """

        # Get values
        metric_values = self._get_metric_values()
        unit = self._AZURE_METRICS_UNIT_SYMBOLS.get(
            self._metric_properties['unit'])
        if unit is None:
            unit = ''

        # Test if value to display
        if metric_values is None:
            message = 'No value available for metric {}'.format(self['metric'])
            if self['dimension'] is not None:
                message += ' and dimension {}'.format(self['dimension'])
            self.nagios_exit(Plugins.UNKNOWN, message)

        # PluginHelper of pynag import
        # https://pynag.readthedocs.io/en/latest/pynag.Plugins.html?highlight=check_threshold#pynag.Plugins.PluginHelper
        p = PluginHelper()

        # For each value, declare metric with according thresholds
        for metric_idx in metric_values:
            p.add_metric(label=metric_idx,
                         value=metric_values[metric_idx],
                         uom=unit,
                         warn=self['warning'],
                         crit=self['critical'])

        # Test all metrics according to there thresholds
        p.check_all_metrics()

        # Add global summary for output
        p.add_summary(self._metric_properties['name']['localizedValue'])

        # Exit and display plugin output
        p.exit()
Example #4
0
            helper.status(critical)
        else:
            helper.status(unknown)
        helper.add_summary('global status is {}'.format(status))

        if version == 1:
            details = json_data
        if version == 2:
            details = json_data['status']

        for item in [
            'cassandra', 'diskSpace', 'dataSource', 'elasticsearch', 'jms', 'mail',
            'mongo', 'rabbit', 'redis', 'solr', 'db', 'vault'
        ]:
            if item in details:
                item_status = details[item]['status']
                helper.add_summary('{} status is {}'.format(item, item_status))
                if helper.get_status() != critical and item_status == 'UNKNOWN':
                    helper.status(unknown)
                elif item_status in ('DOWN', 'OUT_OF_SERVICE'):
                    helper.status(critical)
    else:
        if version == 1:
            handle_version_1()
        if version == 2:
            handle_version_2()

helper.check_all_metrics()

helper.exit()
    # Now lets find those keyfigures, the content of textdata is dynamic so
    # some guesswork is required
    if 'Mannfj' in textdata:
        p.add_metric(label="mannfjoldi", value=numberdata)
    elif "Hagv" in textdata:
        p.add_metric(label="hagvoxtur", value=numberdata)
    elif "VLF" in textdata:
        p.add_metric("verg landsframleidsla", value=numberdata, uom="Mkr")
    elif "VNV" in textdata:
        p.add_metric(label="VNV", value=numberdata)
    elif "Launav" in textdata:
        p.add_metric(label="launavisitala", value=numberdata)
    elif "Bygg.v" in textdata:
        p.add_metric(label="byggingavisitala", value=numberdata)
    elif "sit. framl" in textdata:
        p.add_metric(label="visitala framleidsluverds", value=numberdata)
    elif "Fiskafli" in textdata:
        p.add_metric(label="fiskafli", value=numberdata, uom="tonn")
    elif "ruskipti" in textdata:
        p.add_metric(label="voruskipti", value=numberdata, uom="Mkr")

summary = "%s metrics collected from hagstofan" % (len(p._perfdata.metrics))
p.add_summary(summary)

p.status(ok)


p.check_all_metrics()
p.exit()
Example #6
0
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

from BeautifulSoup import BeautifulSoup
from pynag.Plugins import PluginHelper, ok, warning, critical, unknown

p = PluginHelper()

chars = string.letters + string.digits
randomstring = ''.join([random.choice(chars)
                        for i in xrange(4)])  # avoid cache
default_url = 'http://landspitali.is'
p.parser.add_option('--url', dest='url', default=default_url)
p.parse_arguments()
p.check_all_metrics()
p.show_legacy = True
html = requests.get(p.options.url).content
soup = BeautifulSoup(html)
activitylist = soup.find('div',
                         {'class': 'activityNumbers activityNumbersNew'})
activities = activitylist.findAll('div', recursive=False)

p.add_metric('metrics_found', value=len(activities), warn='0..1')
p.add_summary('%s metrics found on landspitali website' % (len(activities)))

for i in activities:
    metric_name = i.get('class')
    metric_value = i.find('div', {'class': "todaysCount"}).text
    heading = i.find('div', {'class': 'heading'})
    text = i.find('div', {'class': 'todaysText'})
Example #7
0
#!/usr/bin/python

import os.path
import sys

pynagbase = os.path.abspath(
    os.path.join(os.path.dirname(__file__), os.path.pardir))
sys.path[0] = pynagbase

# Standard init
from pynag.Plugins import PluginHelper, ok

# Create an instance of PluginHelper()
my_plugin = PluginHelper()

# Feed fake data for range checking
my_plugin.parser.add_option('-F',
                            dest='fakedata',
                            help='fake data to test thresholds')

# Activate
my_plugin.parse_arguments()

my_plugin.add_status(ok)
my_plugin.add_summary(my_plugin.options.fakedata)
my_plugin.add_metric('fakedata', my_plugin.options.fakedata)

my_plugin.check_all_metrics()
my_plugin.exit()
    for w,v in zip(names, descriptions):
      print w + ' = ' + v
    helper.status(unknown)
    helper.exit(summary='This is just a list and not a check!')
  
  # verify that a hostname is set
  verify_host(host, helper)
  
  # open session after validated host
  sess = netsnmp.Session(Version=version, DestHost=host, Community=community)
  
  # verify, that status(/type) parameter is not empty
  if (status == None) or (status not in names):
    helper.status(unknown)
    helper.exit(summary='Argument -t is missing or false!')
  
  # snmp gets for all oids in type-list
  ind = names.index(status)
  value = get_data(sess, oids[ind],helper)
  
  if names.index(status) == 0:
    value = str(datetime.timedelta(seconds=int(value)))
    helper.exit(summary='Uptime = %s'%value)
  
  # metric compares
  helper.add_metric(label='type', value = value, uom =' '+units[ind]+' ')
  helper.check_all_metrics()
  
  # programm end
  helper.exit()
Example #9
0
# check_stuff.py Takes any arguments from the command_line and treats them as performance metrics.


from pynag.Plugins import PluginHelper

my_plugin = PluginHelper()
my_plugin.parse_arguments()

# Any perfdatastring added as argument will be treated as a performance metric
for i in my_plugin.arguments:
    my_plugin.add_metric(perfdatastring=i)


my_plugin.check_all_metrics()
my_plugin.exit()
    auth = (plugin.options.user, plugin.options.password)
    # Build the metric URL.
    api = 'http://{}:{}/api/overview'.format(plugin.options.hostname, plugin.options.port)
    payload = { 
        'msg_rates_age': '3600',
        'msg_rates_incr': '10',
        'columns': 'message_stats.deliver_get_details.avg_rate',
    }

    # No need to specify a timeout: pynag has --timeout option for the whole plugin.
    r = requests.get(api, params=payload, auth=auth)

    if plugin.options.show_debug:
        show_response()

    if r.status_code == 401:
        plugin.add_summary("Login failed")
        plugin.exit()

    try:
        deliver_rate = r.json()["message_stats"]["deliver_get_details"]["avg_rate"]
    except ValueError:
        plugin.add_summary("Can't decode server's response")
        plugin.exit()
 
    plugin.add_metric('deliver_rate', deliver_rate)
    plugin.add_summary('message.deliver.avg_rate: {}'.format(deliver_rate))
    plugin.check_all_metrics()
    plugin.exit()

Example #11
0
class PluginHelper(unittest.TestCase):

    def setUp(self):
        self.argv_store = sys.argv
        from pynag.Plugins import PluginHelper
        self.my_plugin = PluginHelper()
        self.my_plugin.parser.add_option('-F',
                                         dest='fakedata',
                                         help='fake data to test thresholds')
        sys.stdout = StringIO()

    def tearDown(self):
        sys.argv = self.argv_store
        sys.stdout = original_stdout

    def run_expect(self, case, value, expected_exit):
        sys.argv = [sys.argv[0]] + case.split() + ('-F %s' % value).split()
        self.my_plugin.parse_arguments()
        self.my_plugin.add_status(pynag.Plugins.ok)
        self.my_plugin.add_summary(self.my_plugin.options.fakedata)
        self.my_plugin.add_metric('fakedata', self.my_plugin.options.fakedata)
        try:
            self.my_plugin.check_all_metrics()
            self.my_plugin.exit()
        except SystemExit as e:
            self.assertEquals(type(e), type(SystemExit()))
            self.assertEquals(e.code, expected_exit)
        except Exception as e:
            self.fail('unexpected exception: %s' % e)
        else:
            self.fail('SystemExit exception expected')
        finally:
            signal.alarm(0)

    # Critical if "stuff" is over 20, else warn if over 10
    # (will be critical if "stuff" is less than 0)
    def test_number_1(self):
        case = '--th=metric=fakedata,ok=0..10,warn=10..20'
        self.run_expect(case, -23, 2)

    def test_number_2(self):
        case = '--th=metric=fakedata,ok=0..10,warn=10..20'
        self.run_expect(case, 3, 0)

    def test_number_3(self):
        case = '--th=metric=fakedata,ok=0..10,warn=10..20'
        self.run_expect(case, 13, 1)

    def test_number_4(self):
        case = '--th=metric=fakedata,ok=0..10,warn=10..20'
        self.run_expect(case, 23, 2)

    # Same as above. Negative "stuff" is OK
    def test_number_5(self):
        case = '--th=metric=fakedata,ok=inf..10,warn=10..20'
        self.run_expect(case, '-23', 0)

    def test_number_6(self):
        case = '--th=metric=fakedata,ok=inf..10,warn=10..20'
        self.run_expect(case, '3', 0)

    def test_number_7(self):
        case = '--th=metric=fakedata,ok=inf..10,warn=10..20'
        self.run_expect(case, '13', 1)

    def test_number_8(self):
        case = '--th=metric=fakedata,ok=inf..10,warn=10..20'
        self.run_expect(case, '23', 2)

    # Critical if "stuff" is over 20, else warn if "stuff" is below 10
    # (will be critical if "stuff" is less than 0)
    def test_number_9(self):
        case = '--th=metric=fakedata,warn=0..10,crit=20..inf'
        self.run_expect(case, '-23', 0)

    def test_number_10(self):
        case = '--th=metric=fakedata,warn=0..10,crit=20..inf'
        self.run_expect(case, '3', 1)

    def test_number_11(self):
        case = '--th=metric=fakedata,warn=0..10,crit=20..inf'
        self.run_expect(case, '13', 0)

    def test_number_12(self):
        case = '--th=metric=fakedata,warn=0..10,crit=20..inf'
        self.run_expect(case, '23', 2)

    # Critical if "stuff" is less than 1
    def test_number_13(self):
        case = '--th=metric=fakedata,ok=1..inf'
        self.run_expect(case, '-23', 2)

    def test_number_14(self):
        case = '--th=metric=fakedata,ok=1..inf'
        self.run_expect(case, '0', 2)

    def test_number_15(self):
        case = '--th=metric=fakedata,ok=1..inf'
        self.run_expect(case, '13', 0)

    def test_number_16(self):
        case = '--th=metric=fakedata,ok=1..inf'
        self.run_expect(case, '23', 0)

    # 1-9 is warning, negative or above 10 is critical
    def test_number_17(self):
        case = '--th=metric=fakedata,warn=1..9,crit=^0..10'
        self.run_expect(case, '-23', 2)

    def test_number_18(self):
        case = '--th=metric=fakedata,warn=1..9,crit=^0..10'
        self.run_expect(case, '0', 0)

    def test_number_19(self):
        case = '--th=metric=fakedata,warn=1..9,crit=^0..10'
        self.run_expect(case, '7', 1)

    def test_number_20(self):
        case = '--th=metric=fakedata,warn=1..9,crit=^0..10'
        self.run_expect(case, '23', 2)

    # The only noncritical range is 5:6
    def test_number_21(self):
        case = '--th=metric=fakedata,ok=5..6'
        self.run_expect(case, '-23', 2)

    def test_number_22(self):
        case = '--th=metric=fakedata,ok=5..6'
        self.run_expect(case, '0', 2)

    def test_number_23(self):
        case = '--th=metric=fakedata,ok=5..6'
        self.run_expect(case, '2', 2)

    def test_number_24(self):
        case = '--th=metric=fakedata,ok=5..6'
        self.run_expect(case, '5', 0)

    def test_number_25(self):
        case = '--th=metric=fakedata,ok=5..6'
        self.run_expect(case, '6', 0)

    def test_number_26(self):
        case = '--th=metric=fakedata,ok=5..6'
        self.run_expect(case, '7', 2)

    # Critical if "stuff" is 10 to 20
    def test_number_27(self):
        case = '--th=metric=fakedata,ok=^10..20'
        self.run_expect(case, '-23', 0)

    def test_number_28(self):
        case = '--th=metric=fakedata,ok=^10..20'
        self.run_expect(case, '0', 0)

    def test_number_29(self):
        case = '--th=metric=fakedata,ok=^10..20'
        self.run_expect(case, '2', 0)

    def test_number_30(self):
        case = '--th=metric=fakedata,ok=^10..20'
        self.run_expect(case, '10', 2)

    def test_number_31(self):
        case = '--th=metric=fakedata,ok=^10..20'
        self.run_expect(case, '15', 2)

    def test_number_32(self):
        case = '--th=metric=fakedata,ok=^10..20'
        self.run_expect(case, '20', 2)

    def test_number_33(self):
        case = '--th=metric=fakedata,ok=^10..20'
        self.run_expect(case, '23', 0)

    # Cmdline thresholds pass but we insert a "hardcoded" metric with thresholds
    # which will also be evaluated
    def test_number_34(self):
        # Extra case with hardcoded thresholds
        self.my_plugin.add_metric('fakedata2', value='15',
                                  warn='0..10', crit='10..inf')
        case = '--th=metric=fakedata,ok=0..10,warn=10..20'
        self.run_expect(case, 3, 2)

    def test_number_35(self):
        # Extra case with hardcoded thresholds
        self.my_plugin.add_metric('fakedata2', value='9',
                                  warn='0..10', crit='10..inf')
        case = '--th=metric=fakedata,ok=0..10,warn=10..20'
        self.run_expect(case, 3, 1)

    def test_number_36(self):
        # Extra case with hardcoded thresholds
        self.my_plugin.add_metric('fakedata2', value='-4',
                                  warn='0..10', crit='10..inf')
        case = '--th=metric=fakedata,ok=0..10,warn=10..20'
        self.run_expect(case, 3, 0)

    def testTimeout(self):
        try:
            self.my_plugin.set_timeout(1)
            time.sleep(1)
            self.assertTrue(False, "Code should have timed out by now")
        except SystemExit as e:
            self.assertEquals(type(e), type(SystemExit()))
            self.assertEquals(e.code, pynag.Plugins.unknown)
        self.assertTrue(True, "Timeout occured in plugin, just like expected.")
Example #12
0
    # Build the metric URL.
    api = 'http://{}:{}/api/overview'.format(plugin.options.hostname,
                                             plugin.options.port)
    payload = {
        'msg_rates_age': '3600',
        'msg_rates_incr': '10',
        'columns': 'message_stats.deliver_get_details.avg_rate',
    }

    # No need to specify a timeout: pynag has --timeout option for the whole plugin.
    r = requests.get(api, params=payload, auth=auth)

    if plugin.options.show_debug:
        show_response()

    if r.status_code == 401:
        plugin.add_summary("Login failed")
        plugin.exit()

    try:
        deliver_rate = r.json(
        )["message_stats"]["deliver_get_details"]["avg_rate"]
    except ValueError:
        plugin.add_summary("Can't decode server's response")
        plugin.exit()

    plugin.add_metric('deliver_rate', deliver_rate)
    plugin.add_summary('message.deliver.avg_rate: {}'.format(deliver_rate))
    plugin.check_all_metrics()
    plugin.exit()