syntax cleanup

This commit is contained in:
Drew Kerrigan 2016-07-19 11:02:28 -04:00
parent 06fab10fe2
commit 9be6a709a2

View File

@ -3,11 +3,13 @@
""" """
Check HTTP JSON Nagios Plugin Check HTTP JSON Nagios Plugin
Generic Nagios plugin which checks json values from a given endpoint against argument specified rules Generic Nagios plugin which checks json values from a given endpoint against
and determines the status and performance data for that service. argument specified rules and determines the status and performance data for
that service.
""" """
import httplib, urllib, urllib2, base64 import urllib2
import base64
import json import json
import argparse import argparse
import sys import sys
@ -15,25 +17,28 @@ from pprint import pprint
from urllib2 import HTTPError from urllib2 import HTTPError
from urllib2 import URLError from urllib2 import URLError
# TEST = False
OK_CODE = 0 OK_CODE = 0
WARNING_CODE = 1 WARNING_CODE = 1
CRITICAL_CODE = 2 CRITICAL_CODE = 2
UNKNOWN_CODE = 3 UNKNOWN_CODE = 3
class NagiosHelper: class NagiosHelper:
"""Help with Nagios specific status string formatting.""" """Help with Nagios specific status string formatting."""
message_prefixes = {OK_CODE: 'OK', WARNING_CODE: 'WARNING', CRITICAL_CODE: 'CRITICAL', UNKNOWN_CODE: 'UNKNOWN'} message_prefixes = {OK_CODE: 'OK',
WARNING_CODE: 'WARNING',
CRITICAL_CODE: 'CRITICAL',
UNKNOWN_CODE: 'UNKNOWN'}
performance_data = '' performance_data = ''
warning_message = '' warning_message = ''
critical_message = '' critical_message = ''
unknown_message = '' unknown_message = ''
def getMessage(self): def getMessage(self):
"""Build a status-prefixed message with optional performance data generated externally""" """Build a status-prefixed message with optional performance data
text = "%s: Status %s." % (self.message_prefixes[self.getCode()], self.message_prefixes[self.getCode()]) generated externally"""
text = "%s: Status %s." % (self.message_prefixes[self.getCode()],
self.message_prefixes[self.getCode()])
text += self.warning_message text += self.warning_message
text += self.critical_message text += self.critical_message
text += self.unknown_message text += self.unknown_message
@ -53,17 +58,23 @@ class NagiosHelper:
def append_warning(self, warning_message): def append_warning(self, warning_message):
self.warning_message += warning_message self.warning_message += warning_message
def append_critical(self, critical_message): def append_critical(self, critical_message):
self.critical_message += critical_message self.critical_message += critical_message
def append_unknown(self, unknown_message): def append_unknown(self, unknown_message):
self.critical_message += unknown_message self.critical_message += unknown_message
def append_metrics(self, (performance_data, warning_message, critical_message)):
def append_metrics(self, (performance_data,
warning_message, critical_message)):
self.performance_data += performance_data self.performance_data += performance_data
self.append_warning(warning_message) self.append_warning(warning_message)
self.append_critical(critical_message) self.append_critical(critical_message)
class JsonHelper: class JsonHelper:
"""Perform simple comparison operations against values in a given JSON dict""" """Perform simple comparison operations against values in a given
JSON dict"""
def __init__(self, json_data, separator): def __init__(self, json_data, separator):
self.data = json_data self.data = json_data
self.separator = separator self.separator = separator
@ -81,7 +92,8 @@ class JsonHelper:
def getSubArrayElement(self, key, data): def getSubArrayElement(self, key, data):
subElemKey = key[:key.find(self.arrayOpener)] subElemKey = key[:key.find(self.arrayOpener)]
index = int(key[key.find(self.arrayOpener) + 1:key.find(self.arrayCloser)]) index = int(key[key.find(self.arrayOpener) +
1:key.find(self.arrayCloser)])
remainingKey = key[key.find(self.arrayCloser + self.separator) + 2:] remainingKey = key[key.find(self.arrayCloser + self.separator) + 2:]
if key.find(self.arrayCloser + self.separator) == -1: if key.find(self.arrayCloser + self.separator) == -1:
remainingKey = key[key.find(self.arrayCloser) + 1:] remainingKey = key[key.find(self.arrayCloser) + 1:]
@ -96,21 +108,36 @@ class JsonHelper:
else: else:
return (None, 'not_found') return (None, 'not_found')
def equals(self, key, value): return self.exists(key) and str(self.get(key)) in value.split(':') def equals(self, key, value):
def lte(self, key, value): return self.exists(key) and float(self.get(key)) <= float(value) return self.exists(key) and \
def lt(self, key, value): return self.exists(key) and float(self.get(key)) < float(value) str(self.get(key)) in value.split(':')
def gte(self, key, value): return self.exists(key) and float(self.get(key)) >= float(value)
def gt(self, key, value): return self.exists(key) and float(self.get(key)) > float(value) def lte(self, key, value):
def exists(self, key): return (self.get(key) != (None, 'not_found')) return self.exists(key) and float(self.get(key)) <= float(value)
def lt(self, key, value):
return self.exists(key) and float(self.get(key)) < float(value)
def gte(self, key, value):
return self.exists(key) and float(self.get(key)) >= float(value)
def gt(self, key, value):
return self.exists(key) and float(self.get(key)) > float(value)
def exists(self, key):
return (self.get(key) != (None, 'not_found'))
def get(self, key, temp_data=''): def get(self, key, temp_data=''):
"""Can navigate nested json keys with a dot format (Element.Key.NestedKey). Returns (None, 'not_found') if not found""" """Can navigate nested json keys with a dot format
(Element.Key.NestedKey). Returns (None, 'not_found') if not found"""
if temp_data: if temp_data:
data = temp_data data = temp_data
else: else:
data = self.data data = self.data
if len(key) <= 0: if len(key) <= 0:
return data return data
if key.find(self.separator) != -1 and key.find(self.arrayOpener) != -1 : if key.find(self.separator) != -1 and \
key.find(self.arrayOpener) != -1:
if key.find(self.separator) < key.find(self.arrayOpener): if key.find(self.separator) < key.find(self.arrayOpener):
return self.getSubElement(key, data) return self.getSubElement(key, data)
else: else:
@ -149,6 +176,7 @@ class JsonHelper:
return keys return keys
def _getKeyAlias(original_key): def _getKeyAlias(original_key):
key = original_key key = original_key
alias = original_key alias = original_key
@ -158,13 +186,16 @@ def _getKeyAlias(original_key):
key, alias = keys key, alias = keys
return key, alias return key, alias
class JsonRuleProcessor: class JsonRuleProcessor:
"""Perform checks and gather values from a JSON dict given rules and metrics definitions""" """Perform checks and gather values from a JSON dict given rules
and metrics definitions"""
def __init__(self, json_data, rules_args): def __init__(self, json_data, rules_args):
self.data = json_data self.data = json_data
self.rules = rules_args self.rules = rules_args
separator = '.' separator = '.'
if self.rules.separator: separator = self.rules.separator if self.rules.separator:
separator = self.rules.separator
self.helper = JsonHelper(self.data, separator) self.helper = JsonHelper(self.data, separator)
debugPrint(rules_args.debug, "rules:%s" % rules_args) debugPrint(rules_args.debug, "rules:%s" % rules_args)
debugPrint(rules_args.debug, "separator:%s" % separator) debugPrint(rules_args.debug, "separator:%s" % separator)
@ -173,7 +204,7 @@ class JsonRuleProcessor:
failure = '' failure = ''
for k in exists_list: for k in exists_list:
key, alias = _getKeyAlias(k) key, alias = _getKeyAlias(k)
if (self.helper.exists(key) == False): if (self.helper.exists(key) is False):
failure += " Key %s did not exist." % alias failure += " Key %s did not exist." % alias
return failure return failure
@ -182,7 +213,7 @@ class JsonRuleProcessor:
for kv in equality_list: for kv in equality_list:
k, v = kv.split(',') k, v = kv.split(',')
key, alias = _getKeyAlias(k) key, alias = _getKeyAlias(k)
if (self.helper.equals(key, v) == False): if (self.helper.equals(key, v) is False):
failure += " Value for key %s did not match %s." % (alias, v) failure += " Value for key %s did not match %s." % (alias, v)
return failure return failure
@ -203,19 +234,27 @@ class JsonRuleProcessor:
end = vals[1] end = vals[1]
if(start == '~'): if(start == '~'):
if (invert and self.helper.lte(key, end)): if (invert and self.helper.lte(key, end)):
failure += " Value for key %s was less than or equal to %s." % (alias, end) failure += " Value for key %s was less than or equal to %s." % \
(alias, end)
elif (not invert and self.helper.gt(key, end)): elif (not invert and self.helper.gt(key, end)):
failure += " Value for key %s was greater than %s." % (alias, end) failure += " Value for key %s was greater than %s." % \
(alias, end)
elif(end == 'infinity'): elif(end == 'infinity'):
if (invert and self.helper.gte(key, start)): if (invert and self.helper.gte(key, start)):
failure += " Value for key %s was greater than or equal to %s." % (alias, start) failure += " Value for key %s was greater than or equal to %s." % \
(alias, start)
elif (not invert and self.helper.lt(key, start)): elif (not invert and self.helper.lt(key, start)):
failure += " Value for key %s was less than %s." % (alias, start) failure += " Value for key %s was less than %s." % \
(alias, start)
else: else:
if (invert and self.helper.gte(key, start) and self.helper.lte(key, end)): if (invert and self.helper.gte(key, start) and
failure += " Value for key %s was inside the range %s:%s." % (alias, start, end) self.helper.lte(key, end)):
elif (not invert and (self.helper.lt(key, start) or self.helper.gt(key, end))): failure += " Value for key %s was inside the range %s:%s." % \
failure += " Value for key %s was outside the range %s:%s." % (alias, start, end) (alias, start, end)
elif (not invert and (self.helper.lt(key, start) or
self.helper.gt(key, end))):
failure += " Value for key %s was outside the range %s:%s." % \
(alias, start, end)
return failure return failure
def checkThresholds(self, threshold_list): def checkThresholds(self, threshold_list):
@ -228,30 +267,31 @@ class JsonRuleProcessor:
def checkWarning(self): def checkWarning(self):
failure = '' failure = ''
if self.rules.key_threshold_warning != None: if self.rules.key_threshold_warning is not None:
failure += self.checkThresholds(self.rules.key_threshold_warning) failure += self.checkThresholds(self.rules.key_threshold_warning)
if self.rules.key_value_list != None: if self.rules.key_value_list is not None:
failure += self.checkEquality(self.rules.key_value_list) failure += self.checkEquality(self.rules.key_value_list)
if self.rules.key_list != None: if self.rules.key_list is not None:
failure += self.checkExists(self.rules.key_list) failure += self.checkExists(self.rules.key_list)
return failure return failure
def checkCritical(self): def checkCritical(self):
failure = '' failure = ''
if self.rules.key_threshold_critical != None: if self.rules.key_threshold_critical is not None:
failure += self.checkThresholds(self.rules.key_threshold_critical) failure += self.checkThresholds(self.rules.key_threshold_critical)
if self.rules.key_value_list_critical != None: if self.rules.key_value_list_critical is not None:
failure += self.checkEquality(self.rules.key_value_list_critical) failure += self.checkEquality(self.rules.key_value_list_critical)
if self.rules.key_list_critical != None: if self.rules.key_list_critical is not None:
failure += self.checkExists(self.rules.key_list_critical) failure += self.checkExists(self.rules.key_list_critical)
return failure return failure
def checkMetrics(self): def checkMetrics(self):
"""Return a Nagios specific performance metrics string given keys and parameter definitions""" """Return a Nagios specific performance metrics string given keys
and parameter definitions"""
metrics = '' metrics = ''
warning = '' warning = ''
critical = '' critical = ''
if self.rules.metric_list != None: if self.rules.metric_list is not None:
metric_list = [] metric_list = []
for metric in self.rules.metric_list: for metric in self.rules.metric_list:
@ -270,63 +310,100 @@ class JsonRuleProcessor:
if len(vals) == 4: if len(vals) == 4:
key, uom, warn_range, crit_range = vals key, uom, warn_range, crit_range = vals
if len(vals) == 6: if len(vals) == 6:
key,uom,warn_range,crit_range,minimum,maximum = vals key, uom, warn_range, crit_range,
minimum, maximum = vals
key, alias = _getKeyAlias(key) key, alias = _getKeyAlias(key)
if self.helper.exists(key): if self.helper.exists(key):
metrics += "'%s'=%s" % (alias, self.helper.get(key)) metrics += "'%s'=%s" % (alias, self.helper.get(key))
if uom: metrics += uom if uom:
if warn_range != None: metrics += uom
if warn_range is not None:
warning += self.checkThreshold(key, alias, warn_range) warning += self.checkThreshold(key, alias, warn_range)
metrics += ";%s" % warn_range metrics += ";%s" % warn_range
if crit_range != None: if crit_range is not None:
critical += self.checkThreshold(key, alias, crit_range) critical += self.checkThreshold(key, alias, crit_range)
metrics += ";%s" % crit_range metrics += ";%s" % crit_range
if minimum != None: if minimum is not None:
critical += self.checkThreshold(key, alias, minimum + ':') critical += self.checkThreshold(key, alias, minimum +
':')
metrics += ";%s" % minimum metrics += ";%s" % minimum
if maximum != None: if maximum is not None:
critical += self.checkThreshold(key, alias, '~:' + maximum) critical += self.checkThreshold(key, alias, '~:' +
maximum)
metrics += ";%s" % maximum metrics += ";%s" % maximum
metrics += ' ' metrics += ' '
return ("%s" % metrics, warning, critical) return ("%s" % metrics, warning, critical)
def parseArgs():
parser = argparse.ArgumentParser(description=
'Nagios plugin which checks json values from a given endpoint against argument specified rules\
and determines the status and performance data for that service')
# parser.add_argument('-v', '--verbose', action='store_true', help='Verbose Output') def parseArgs():
parser.add_argument('-d', '--debug', action='store_true', help='Debug mode.') parser = argparse.ArgumentParser(description='''Nagios plugin which
checks json values from a given endpoint against argument specified rules
and determines the status and performance data for that service''')
parser.add_argument('-d', '--debug', action='store_true',
help='Debug mode.')
parser.add_argument('-s', '--ssl', action='store_true', help='HTTPS mode.') parser.add_argument('-s', '--ssl', action='store_true', help='HTTPS mode.')
parser.add_argument('-H', '--host', dest='host', required=True, help='Host.') parser.add_argument('-H', '--host', dest='host', required=True,
help='Host.')
parser.add_argument('-P', '--port', dest='port', help='TCP port') parser.add_argument('-P', '--port', dest='port', help='TCP port')
parser.add_argument('-p', '--path', dest='path', help='Path.') parser.add_argument('-p', '--path', dest='path', help='Path.')
parser.add_argument('-t', '--timeout', type=int, help='Connection timeout (seconds)') parser.add_argument('-t', '--timeout', type=int,
parser.add_argument('-B', '--basic-auth', dest='auth', help='Basic auth string "username:password"') help='Connection timeout (seconds)')
parser.add_argument('-D', '--data', dest='data', help='The http payload to send as a POST') parser.add_argument('-B', '--basic-auth', dest='auth',
parser.add_argument('-A', '--headers', dest='headers', help='The http headers in JSON format.') help='Basic auth string "username:password"')
parser.add_argument('-D', '--data', dest='data',
help='The http payload to send as a POST')
parser.add_argument('-A', '--headers', dest='headers',
help='The http headers in JSON format.')
parser.add_argument('-f', '--field_separator', dest='separator', parser.add_argument('-f', '--field_separator', dest='separator',
help='Json Field separator, defaults to "." ; Select element in an array with "(" ")"') help='''JSON Field separator, defaults to "." ;
parser.add_argument('-w', '--warning', dest='key_threshold_warning', nargs='*', Select element in an array with "(" ")"''')
help='Warning threshold for these values (key1[>alias],WarnRange key2[>alias],WarnRange). WarnRange is in the format [@]start:end, more information at nagios-plugins.org/doc/guidelines.html.') parser.add_argument('-w', '--warning', dest='key_threshold_warning',
parser.add_argument('-c', '--critical', dest='key_threshold_critical', nargs='*', nargs='*',
help='Critical threshold for these values (key1[>alias],CriticalRange key2[>alias],CriticalRange. CriticalRange is in the format [@]start:end, more information at nagios-plugins.org/doc/guidelines.html.') help='''Warning threshold for these values
(key1[>alias],WarnRange key2[>alias],WarnRange).
WarnRange is in the format [@]start:end, more
information at
nagios-plugins.org/doc/guidelines.html.''')
parser.add_argument('-c', '--critical', dest='key_threshold_critical',
nargs='*',
help='''Critical threshold for these values
(key1[>alias],CriticalRange key2[>alias],CriticalRange.
CriticalRange is in the format [@]start:end, more
information at
nagios-plugins.org/doc/guidelines.html.''')
parser.add_argument('-e', '--key_exists', dest='key_list', nargs='*', parser.add_argument('-e', '--key_exists', dest='key_list', nargs='*',
help='Checks existence of these keys to determine status. Return warning if key is not present.') help='''Checks existence of these keys to determine
parser.add_argument('-E', '--key_exists_critical', dest='key_list_critical', nargs='*', status. Return warning if key is not present.''')
help='Same as -e but return critical if key is not present.') parser.add_argument('-E', '--key_exists_critical',
dest='key_list_critical',
nargs='*',
help='''Same as -e but return critical if key is
not present.''')
parser.add_argument('-q', '--key_equals', dest='key_value_list', nargs='*', parser.add_argument('-q', '--key_equals', dest='key_value_list', nargs='*',
help='Checks equality of these keys and values (key[>alias],value key2,value2) to determine status.\ help='''Checks equality of these keys and values
Multiple key values can be delimited with colon (key,value1:value2). Return warning if equality check fails') (key[>alias],value key2,value2) to determine status.
parser.add_argument('-Q', '--key_equals_critical', dest='key_value_list_critical', nargs='*', Multiple key values can be delimited with colon
help='Same as -q but return critical if equality check fails.') (key,value1:value2). Return warning if equality
check fails''')
parser.add_argument('-Q', '--key_equals_critical',
dest='key_value_list_critical', nargs='*',
help='''Same as -q but return critical if
equality check fails.''')
parser.add_argument('-m', '--key_metric', dest='metric_list', nargs='*', parser.add_argument('-m', '--key_metric', dest='metric_list', nargs='*',
help='Gathers the values of these keys (key[>alias],UnitOfMeasure,WarnRange,CriticalRange,Min,Max) for Nagios performance data.\ help='''Gathers the values of these keys (key[>alias],
More information about Range format and units of measure for nagios can be found at nagios-plugins.org/doc/guidelines.html\ UnitOfMeasure,WarnRange,CriticalRange,Min,Max) for
Additional formats for this parameter are: (key[>alias]), (key[>alias],UnitOfMeasure), (key[>alias],UnitOfMeasure,WarnRange,CriticalRange).') Nagios performance data. More information about Range
format and units of measure for nagios can be found at
nagios-plugins.org/doc/guidelines.html
Additional formats for this parameter are:
(key[>alias]), (key[>alias],UnitOfMeasure),
(key[>alias],UnitOfMeasure,WarnRange,
CriticalRange).''')
return parser.parse_args() return parser.parse_args()
def debugPrint(debug_flag, message, pretty_flag=False): def debugPrint(debug_flag, message, pretty_flag=False):
if debug_flag: if debug_flag:
if pretty_flag: if pretty_flag:
@ -336,26 +413,49 @@ def debugPrint(debug_flag, message, pretty_flag=False):
if __name__ == "__main__" and len(sys.argv) >= 2 and sys.argv[1] == 'UnitTest': if __name__ == "__main__" and len(sys.argv) >= 2 and sys.argv[1] == 'UnitTest':
import unittest import unittest
class RulesHelper: class RulesHelper:
separator = '.' separator = '.'
debug = False debug = False
key_threshold_warning,key_value_list,key_list,key_threshold_critical,key_value_list_critical,key_list_critical,metric_list = None, None, None, None, None, None, None key_threshold_warning = None
key_value_list = None
key_list = None
key_threshold_critical = None
key_value_list_critical = None
key_list_critical = None
metric_list = None
def dash_m(self, data): def dash_m(self, data):
self.metric_list = data; return self self.metric_list = data
return self
def dash_e(self, data): def dash_e(self, data):
self.key_list = data; return self self.key_list = data
return self
def dash_E(self, data): def dash_E(self, data):
self.key_list_critical = data; return self self.key_list_critical = data
return self
def dash_q(self, data): def dash_q(self, data):
self.key_value_list = data; return self self.key_value_list = data
return self
def dash_Q(self, data): def dash_Q(self, data):
self.key_value_list_critical = data; return self self.key_value_list_critical = data
return self
def dash_w(self, data): def dash_w(self, data):
self.key_threshold_warning = data; return self self.key_threshold_warning = data
return self
def dash_c(self, data): def dash_c(self, data):
self.key_threshold_critical = data; return self self.key_threshold_critical = data
return self
class UnitTest(unittest.TestCase): class UnitTest(unittest.TestCase):
rules = RulesHelper() rules = RulesHelper()
def check_data(self, args, jsondata, code): def check_data(self, args, jsondata, code):
data = json.loads(jsondata) data = json.loads(jsondata)
nagios = NagiosHelper() nagios = NagiosHelper()
@ -364,60 +464,111 @@ if __name__ == "__main__" and len(sys.argv) >= 2 and sys.argv[1] == 'UnitTest':
nagios.append_critical(processor.checkCritical()) nagios.append_critical(processor.checkCritical())
nagios.append_metrics(processor.checkMetrics()) nagios.append_metrics(processor.checkMetrics())
self.assertEqual(code, nagios.getCode()) self.assertEqual(code, nagios.getCode())
def test_metrics(self): def test_metrics(self):
self.check_data(RulesHelper().dash_m(['metric,,1:4,1:5']), '{"metric": 5}', WARNING_CODE) self.check_data(RulesHelper().dash_m(['metric,,1:4,1:5']),
self.check_data(RulesHelper().dash_m(['metric,,1:5,1:4']), '{"metric": 5}', CRITICAL_CODE) '{"metric": 5}', WARNING_CODE)
self.check_data(RulesHelper().dash_m(['metric,,1:5,1:5,6,10']), '{"metric": 5}', CRITICAL_CODE) self.check_data(RulesHelper().dash_m(['metric,,1:5,1:4']),
self.check_data(RulesHelper().dash_m(['metric,,1:5,1:5,1,4']), '{"metric": 5}', CRITICAL_CODE) '{"metric": 5}', CRITICAL_CODE)
self.check_data(RulesHelper().dash_m(['metric,s,@1:4,@6:10,1,10']), '{"metric": 5}', OK_CODE) self.check_data(RulesHelper().dash_m(['metric,,1:5,1:5,6,10']),
'{"metric": 5}', CRITICAL_CODE)
self.check_data(RulesHelper().dash_m(['metric,,1:5,1:5,1,4']),
'{"metric": 5}', CRITICAL_CODE)
self.check_data(RulesHelper().dash_m(['metric,s,@1:4,@6:10,1,10']),
'{"metric": 5}', OK_CODE)
def test_exists(self): def test_exists(self):
self.check_data(RulesHelper().dash_e(['nothere']), '{"metric": 5}', WARNING_CODE) self.check_data(RulesHelper().dash_e(['nothere']),
self.check_data(RulesHelper().dash_E(['nothere']), '{"metric": 5}', CRITICAL_CODE) '{"metric": 5}', WARNING_CODE)
self.check_data(RulesHelper().dash_e(['metric']), '{"metric": 5}', OK_CODE) self.check_data(RulesHelper().dash_E(['nothere']),
'{"metric": 5}', CRITICAL_CODE)
self.check_data(RulesHelper().dash_e(['metric']),
'{"metric": 5}', OK_CODE)
def test_equality(self): def test_equality(self):
self.check_data(RulesHelper().dash_q(['metric,6']), '{"metric": 5}', WARNING_CODE) self.check_data(RulesHelper().dash_q(['metric,6']),
self.check_data(RulesHelper().dash_Q(['metric,6']), '{"metric": 5}', CRITICAL_CODE) '{"metric": 5}', WARNING_CODE)
self.check_data(RulesHelper().dash_q(['metric,5']), '{"metric": 5}', OK_CODE) self.check_data(RulesHelper().dash_Q(['metric,6']),
'{"metric": 5}', CRITICAL_CODE)
self.check_data(RulesHelper().dash_q(['metric,5']),
'{"metric": 5}', OK_CODE)
def test_warning_thresholds(self): def test_warning_thresholds(self):
self.check_data(RulesHelper().dash_w(['metric,5']), '{"metric": 5}', OK_CODE) self.check_data(RulesHelper().dash_w(['metric,5']),
self.check_data(RulesHelper().dash_w(['metric,5:']), '{"metric": 5}', OK_CODE) '{"metric": 5}', OK_CODE)
self.check_data(RulesHelper().dash_w(['metric,~:5']), '{"metric": 5}', OK_CODE) self.check_data(RulesHelper().dash_w(['metric,5:']),
self.check_data(RulesHelper().dash_w(['metric,1:5']), '{"metric": 5}', OK_CODE) '{"metric": 5}', OK_CODE)
self.check_data(RulesHelper().dash_w(['metric,@5']), '{"metric": 6}', OK_CODE) self.check_data(RulesHelper().dash_w(['metric,~:5']),
self.check_data(RulesHelper().dash_w(['metric,@5:']), '{"metric": 4}', OK_CODE) '{"metric": 5}', OK_CODE)
self.check_data(RulesHelper().dash_w(['metric,@~:5']), '{"metric": 6}', OK_CODE) self.check_data(RulesHelper().dash_w(['metric,1:5']),
self.check_data(RulesHelper().dash_w(['metric,@1:5']), '{"metric": 6}', OK_CODE) '{"metric": 5}', OK_CODE)
self.check_data(RulesHelper().dash_w(['metric,5']), '{"metric": 6}', WARNING_CODE) self.check_data(RulesHelper().dash_w(['metric,@5']),
self.check_data(RulesHelper().dash_w(['metric,5:']), '{"metric": 4}', WARNING_CODE) '{"metric": 6}', OK_CODE)
self.check_data(RulesHelper().dash_w(['metric,~:5']), '{"metric": 6}', WARNING_CODE) self.check_data(RulesHelper().dash_w(['metric,@5:']),
self.check_data(RulesHelper().dash_w(['metric,1:5']), '{"metric": 6}', WARNING_CODE) '{"metric": 4}', OK_CODE)
self.check_data(RulesHelper().dash_w(['metric,@5']), '{"metric": 5}', WARNING_CODE) self.check_data(RulesHelper().dash_w(['metric,@~:5']),
self.check_data(RulesHelper().dash_w(['metric,@5:']), '{"metric": 5}', WARNING_CODE) '{"metric": 6}', OK_CODE)
self.check_data(RulesHelper().dash_w(['metric,@~:5']), '{"metric": 5}', WARNING_CODE) self.check_data(RulesHelper().dash_w(['metric,@1:5']),
self.check_data(RulesHelper().dash_w(['metric,@1:5']), '{"metric": 5}', WARNING_CODE) '{"metric": 6}', OK_CODE)
self.check_data(RulesHelper().dash_w(['metric,5']),
'{"metric": 6}', WARNING_CODE)
self.check_data(RulesHelper().dash_w(['metric,5:']),
'{"metric": 4}', WARNING_CODE)
self.check_data(RulesHelper().dash_w(['metric,~:5']),
'{"metric": 6}', WARNING_CODE)
self.check_data(RulesHelper().dash_w(['metric,1:5']),
'{"metric": 6}', WARNING_CODE)
self.check_data(RulesHelper().dash_w(['metric,@5']),
'{"metric": 5}', WARNING_CODE)
self.check_data(RulesHelper().dash_w(['metric,@5:']),
'{"metric": 5}', WARNING_CODE)
self.check_data(RulesHelper().dash_w(['metric,@~:5']),
'{"metric": 5}', WARNING_CODE)
self.check_data(RulesHelper().dash_w(['metric,@1:5']),
'{"metric": 5}', WARNING_CODE)
def test_critical_thresholds(self): def test_critical_thresholds(self):
self.check_data(RulesHelper().dash_c(['metric,5']), '{"metric": 5}', OK_CODE) self.check_data(RulesHelper().dash_c(['metric,5']),
self.check_data(RulesHelper().dash_c(['metric,5:']), '{"metric": 5}', OK_CODE) '{"metric": 5}', OK_CODE)
self.check_data(RulesHelper().dash_c(['metric,~:5']), '{"metric": 5}', OK_CODE) self.check_data(RulesHelper().dash_c(['metric,5:']),
self.check_data(RulesHelper().dash_c(['metric,1:5']), '{"metric": 5}', OK_CODE) '{"metric": 5}', OK_CODE)
self.check_data(RulesHelper().dash_c(['metric,@5']), '{"metric": 6}', OK_CODE) self.check_data(RulesHelper().dash_c(['metric,~:5']),
self.check_data(RulesHelper().dash_c(['metric,@5:']), '{"metric": 4}', OK_CODE) '{"metric": 5}', OK_CODE)
self.check_data(RulesHelper().dash_c(['metric,@~:5']), '{"metric": 6}', OK_CODE) self.check_data(RulesHelper().dash_c(['metric,1:5']),
self.check_data(RulesHelper().dash_c(['metric,@1:5']), '{"metric": 6}', OK_CODE) '{"metric": 5}', OK_CODE)
self.check_data(RulesHelper().dash_c(['metric,5']), '{"metric": 6}', CRITICAL_CODE) self.check_data(RulesHelper().dash_c(['metric,@5']),
self.check_data(RulesHelper().dash_c(['metric,5:']), '{"metric": 4}', CRITICAL_CODE) '{"metric": 6}', OK_CODE)
self.check_data(RulesHelper().dash_c(['metric,~:5']), '{"metric": 6}', CRITICAL_CODE) self.check_data(RulesHelper().dash_c(['metric,@5:']),
self.check_data(RulesHelper().dash_c(['metric,1:5']), '{"metric": 6}', CRITICAL_CODE) '{"metric": 4}', OK_CODE)
self.check_data(RulesHelper().dash_c(['metric,@5']), '{"metric": 5}', CRITICAL_CODE) self.check_data(RulesHelper().dash_c(['metric,@~:5']),
self.check_data(RulesHelper().dash_c(['metric,@5:']), '{"metric": 5}', CRITICAL_CODE) '{"metric": 6}', OK_CODE)
self.check_data(RulesHelper().dash_c(['metric,@~:5']), '{"metric": 5}', CRITICAL_CODE) self.check_data(RulesHelper().dash_c(['metric,@1:5']),
self.check_data(RulesHelper().dash_c(['metric,@1:5']), '{"metric": 5}', CRITICAL_CODE) '{"metric": 6}', OK_CODE)
self.check_data(RulesHelper().dash_c(['metric,5']),
'{"metric": 6}', CRITICAL_CODE)
self.check_data(RulesHelper().dash_c(['metric,5:']),
'{"metric": 4}', CRITICAL_CODE)
self.check_data(RulesHelper().dash_c(['metric,~:5']),
'{"metric": 6}', CRITICAL_CODE)
self.check_data(RulesHelper().dash_c(['metric,1:5']),
'{"metric": 6}', CRITICAL_CODE)
self.check_data(RulesHelper().dash_c(['metric,@5']),
'{"metric": 5}', CRITICAL_CODE)
self.check_data(RulesHelper().dash_c(['metric,@5:']),
'{"metric": 5}', CRITICAL_CODE)
self.check_data(RulesHelper().dash_c(['metric,@~:5']),
'{"metric": 5}', CRITICAL_CODE)
self.check_data(RulesHelper().dash_c(['metric,@1:5']),
'{"metric": 5}', CRITICAL_CODE)
def test_separator(self): def test_separator(self):
rules = RulesHelper() rules = RulesHelper()
rules.separator = '_' rules.separator = '_'
self.check_data( self.check_data(
rules.dash_q(['(0)_gauges_jvm.buffers.direct.capacity(1)_value,1234']), rules.dash_q(
'[{ "gauges": { "jvm.buffers.direct.capacity": [{"value": 215415},{"value": 1234}]}}]', ['(0)_gauges_jvm.buffers.direct.capacity(1)_value,1234']),
'''[{ "gauges": { "jvm.buffers.direct.capacity": [
{"value": 215415},{"value": 1234}]}}]''',
OK_CODE) OK_CODE)
unittest.main() unittest.main()
exit(0) exit(0)
@ -430,10 +581,11 @@ if __name__ == "__main__":
url = "https://%s" % args.host url = "https://%s" % args.host
else: else:
url = "http://%s" % args.host url = "http://%s" % args.host
if args.port: url += ":%s" % args.port if args.port:
if args.path: url += "/%s" % args.path url += ":%s" % args.port
if args.path:
url += "/%s" % args.path
debugPrint(args.debug, "url:%s" % url) debugPrint(args.debug, "url:%s" % url)
# Attempt to reach the endpoint
try: try:
req = urllib2.Request(url) req = urllib2.Request(url)
if args.auth: if args.auth:
@ -445,7 +597,8 @@ if __name__ == "__main__":
for header in headers: for header in headers:
req.add_header(header, headers[header]) req.add_header(header, headers[header])
if args.timeout and args.data: if args.timeout and args.data:
response = urllib2.urlopen(req, timeout=args.timeout, data=args.data) response = urllib2.urlopen(req, timeout=args.timeout,
data=args.data)
elif args.timeout: elif args.timeout:
response = urllib2.urlopen(req, timeout=args.timeout) response = urllib2.urlopen(req, timeout=args.timeout)
elif args.data: elif args.data: