15 Commits
v2.0 ... v2.1

Author SHA1 Message Date
Markus Opolka
c23ebac77a Merge pull request #63 from drewkerrigan/v2-1
Release 2.1
2020-07-03 09:58:55 +02:00
Markus Opolka
a014944981 Merge pull request #62 from drewkerrigan/key-equals-empty
Add handling of empty JSON return values
2020-07-03 09:04:53 +02:00
Markus Opolka
47a37556ba Merge branch 'v2-1' into key-equals-empty 2020-07-03 09:03:21 +02:00
Markus Opolka
41279cad2c Merge pull request #60 from drewkerrigan/http-json
Parse JSON on HTTPError, if JSON in response
2020-07-03 09:02:14 +02:00
Markus Opolka
f7c0472cdc Add JSON parsing on HTTPError
- Only if response contains JSON
2020-07-02 11:35:23 +02:00
Markus Opolka
25fb340bbb Add handling of empty JSON return values
- Will now throw a CRITICAL
2020-06-26 10:39:37 +02:00
Markus Opolka
47bdea7fc5 Add spaces to debug output 2020-06-26 10:31:20 +02:00
Markus Opolka
866a12ea07 Add JSON parsing on HTTPError
- Only if response contains JSON
2020-06-19 14:26:59 +02:00
Markus Opolka
d1e585b2dd Adjust pylint for new function 2020-06-19 13:16:07 +02:00
Markus Opolka
941afeed89 Move main entrypoint to own function for simpler testing 2020-06-19 13:12:51 +02:00
Markus Opolka
b9a583f281 Add Makefile and requirements.txt for easier testing 2020-06-19 13:12:48 +02:00
Markus Opolka
4c89a8a93d Update README 2020-04-03 11:53:00 +02:00
Markus Opolka
73557b3657 Merge pull request #58 from bb-Ricardo/next-release
added icinga2 command definitions
2020-04-03 11:50:29 +02:00
Ricardo Bartels
aad2376ac0 added missing cli args for V2.0 2020-04-02 08:39:42 +02:00
Ricardo Bartels
26a1b3dbe8 added icinga2 command definitions 2019-05-10 11:21:34 +02:00
9 changed files with 286 additions and 34 deletions

View File

@@ -1,5 +1,5 @@
# pylint config # pylint config
[MESSAGES CONTROL] [MESSAGES CONTROL]
disable=line-too-long, redefined-outer-name, too-many-arguments, too-many-instance-attributes, fixme, invalid-name, superfluous-parens, missing-function-docstring, missing-module-docstring, multiple-imports, no-else-return, too-many-return-statements disable=line-too-long, redefined-outer-name, too-many-arguments, too-many-instance-attributes, fixme, invalid-name, superfluous-parens, missing-function-docstring, missing-module-docstring, multiple-imports, no-else-return, too-many-return-statements, too-many-branches, too-many-statements
[MASTER] [MASTER]
ignore-patterns=^test.* ignore-patterns=^test.*

View File

@@ -20,7 +20,7 @@ Executing `./check_http_json.py -h` will yield the following details:
usage: check_http_json.py [-h] [-d] [-s] -H HOST [-k] [-V] [--cacert CACERT] usage: check_http_json.py [-h] [-d] [-s] -H HOST [-k] [-V] [--cacert CACERT]
[--cert CERT] [--key KEY] [-P PORT] [-p PATH] [--cert CERT] [--key KEY] [-P PORT] [-p PATH]
[-t TIMEOUT] [-B AUTH] [-D DATA] [-A HEADERS] [-t TIMEOUT] [-B AUTH] [-D DATA] [-A HEADERS]
[-f SEPARATOR] [-f FIELD_SEPARATOR] [-F VALUE_SEPARATOR]
[-w [KEY_THRESHOLD_WARNING [KEY_THRESHOLD_WARNING ...]]] [-w [KEY_THRESHOLD_WARNING [KEY_THRESHOLD_WARNING ...]]]
[-c [KEY_THRESHOLD_CRITICAL [KEY_THRESHOLD_CRITICAL ...]]] [-c [KEY_THRESHOLD_CRITICAL [KEY_THRESHOLD_CRITICAL ...]]]
[-e [KEY_LIST [KEY_LIST ...]]] [-e [KEY_LIST [KEY_LIST ...]]]
@@ -62,6 +62,8 @@ optional arguments:
-f SEPARATOR, --field_separator SEPARATOR -f SEPARATOR, --field_separator SEPARATOR
JSON Field separator, defaults to "."; Select element JSON Field separator, defaults to "."; Select element
in an array with "(" ")" in an array with "(" ")"
-F SEPARATOR, --value_separator SEPARATOR
JSON Value separator, defaults to ":";
-w [KEY_THRESHOLD_WARNING [KEY_THRESHOLD_WARNING ...]], --warning [KEY_THRESHOLD_WARNING [KEY_THRESHOLD_WARNING ...]] -w [KEY_THRESHOLD_WARNING [KEY_THRESHOLD_WARNING ...]], --warning [KEY_THRESHOLD_WARNING [KEY_THRESHOLD_WARNING ...]]
Warning threshold for these values Warning threshold for these values
(key1[>alias],WarnRange key2[>alias],WarnRange). (key1[>alias],WarnRange key2[>alias],WarnRange).
@@ -243,7 +245,10 @@ define command{
``` ```
More info about options in Usage. ## Icinga2 configuration
The Icinga2 command definition can be found here: (contrib/icinga2_check_command_definition.conf)
## License ## License

View File

@@ -225,9 +225,9 @@ class JsonRuleProcessor:
if self.rules.value_separator: if self.rules.value_separator:
value_separator = self.rules.value_separator value_separator = self.rules.value_separator
self.helper = JsonHelper(self.data, separator, value_separator) self.helper = JsonHelper(self.data, separator, value_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)
debugPrint(rules_args.debug, "value_separator:%s" % value_separator) debugPrint(rules_args.debug, "value_separator: %s" % value_separator)
self.metric_list = self.expandKeys(self.rules.metric_list) self.metric_list = self.expandKeys(self.rules.metric_list)
self.key_threshold_warning = self.expandKeys( self.key_threshold_warning = self.expandKeys(
self.rules.key_threshold_warning) self.rules.key_threshold_warning)
@@ -346,6 +346,8 @@ class JsonRuleProcessor:
def checkCritical(self): def checkCritical(self):
failure = '' failure = ''
if not self.data:
failure = " Empty JSON data."
if self.key_threshold_critical is not None: if self.key_threshold_critical is not None:
failure += self.checkThresholds(self.key_threshold_critical) failure += self.checkThresholds(self.key_threshold_critical)
if self.key_value_list_critical is not None: if self.key_value_list_critical is not None:
@@ -424,7 +426,7 @@ def parseArgs(args):
parser.add_argument('-s', '--ssl', action='store_true', parser.add_argument('-s', '--ssl', action='store_true',
help='use TLS to connect to remote host') help='use TLS to connect to remote host')
parser.add_argument('-H', '--host', dest='host', parser.add_argument('-H', '--host', dest='host',
required=not ('-V' in sys.argv or '--version' in sys.argv), required=not ('-V' in args or '--version' in args),
help='remote host to query') help='remote host to query')
parser.add_argument('-k', '--insecure', action='store_true', parser.add_argument('-k', '--insecure', action='store_true',
help='do not check server SSL certificate') help='do not check server SSL certificate')
@@ -524,10 +526,12 @@ def debugPrint(debug_flag, message, pretty_flag=False):
print(message) print(message)
# Program entry point def main(cliargs):
if __name__ == "__main__": """
Main entrypoint for CLI
"""
args = parseArgs(sys.argv[1:]) args = parseArgs(cliargs)
nagios = NagiosHelper() nagios = NagiosHelper()
context = None context = None
@@ -607,6 +611,10 @@ if __name__ == "__main__":
json_data = response.read() json_data = response.read()
except HTTPError as e: except HTTPError as e:
# Try to recover from HTTP Error, if there is JSON in the response
if "json" in e.info().get_content_subtype():
json_data = e.read()
else:
nagios.append_unknown(" HTTPError[%s], url:%s" % (str(e.code), url)) nagios.append_unknown(" HTTPError[%s], url:%s" % (str(e.code), url))
except URLError as e: except URLError as e:
nagios.append_critical(" URLError[%s], url:%s" % (str(e.reason), url)) nagios.append_critical(" URLError[%s], url:%s" % (str(e.reason), url))
@@ -630,4 +638,9 @@ if __name__ == "__main__":
print(nagios.getMessage()) print(nagios.getMessage())
sys.exit(nagios.getCode()) sys.exit(nagios.getCode())
if __name__ == "__main__":
# Program entry point
main(sys.argv[1:])
#EOF #EOF

View File

@@ -0,0 +1,106 @@
object CheckCommand "http_json" {
import "plugin-check-command"
command = [ PluginDir + "/check_http_json.py" ]
arguments = {
"--host" = {
value = "$address$"
description = "Hostname or address of the interface to query"
required = true
}
"--port" = {
value = "$http_json_port$"
description = "TCP port number"
}
"--path" = {
value = "$http_json_path$"
description = "URL path to query (i.e.: /v1/service/xyz)"
}
"--timeout" = {
value = "$http_json_timeout$"
description = "Connection timeout (seconds)"
}
"--basic-auth" = {
value = "$http_json_basic_auth$"
description = "Basic auth string 'username:password'"
}
"--ssl" = {
set_if = "$http_json_ssl$"
description = "use TLS to connect to remote host"
}
"--insecure" = {
set_if = "$http_json_insecure$"
description = "do not check server SSL certificate"
}
"--cacert" = {
value = "$http_json_cacert_file$"
description = "path of cacert file to validate server cert"
}
"--cert" = {
value = "$http_json_cert_file$"
description = "client certificate in PEM format"
}
"--key" = {
value = "$http_json_key_file$"
description = "client certificate key file in PEM format ( if not bundled into the cert )"
}
"--data" = {
value = "$http_json_post_data$"
description = "the http payload to send as a POST"
}
"--headers" = {
value = "$http_json_headers$"
description = "additional http headers in JSON format to send with the request"
}
"--field_separator" = {
value = "$http_json_field_separator$"
description = "JSON Field separator, defaults to '.'; Select element in an array with '(' ')'"
}
"--value_separator" = {
value = "$http_json_value_separator$"
description = "JSON Value separator, defaults to ':'"
}
"--warning" = {
value = "$http_json_warning$"
description = "Warning threshold for these values, WarningRange is in the format [@]start:end"
}
"--critical" = {
value = "$http_json_critical$"
description = "Critical threshold for these values, CriticalRange is in the format [@]start:end"
}
"--key_exists" = {
value = "$http_json_key_exists$"
description = "Checks existence of these keys to determine status. Return warning if key is not present."
}
"--key_exists_critical" = {
value = "$http_json_key_exists_critical$"
description = "Checks existence of these keys to determine status. Return critical if key is not present."
}
"--key_equals" = {
value = "$http_json_key_equals$"
description = "Checks equality of these keys and values. Return warning if equality check fails"
}
"--key_equals_critical" = {
value = "$http_json_key_equals_critical$"
description = "Checks equality of these keys and values. Return critical if equality check fails"
}
"--key_equals_unknown" = {
value = "$http_json_key_equals_unknown$"
description = "Checks equality of these keys and values. Return unknown if equality check fails"
}
"--key_not_equals" = {
value = "$http_json_key_not_equals$"
description = "Checks equality of these keys and values (key[>alias],value key2,value2) to determine status. Multiple key values can be delimited with colon (key,value1:value2). Return warning if equality check succeeds."
}
"--key_not_equals_critical" = {
value = "$http_json_key_not_equals_critical$"
description = "Checks equality of these keys and values (key[>alias],value key2,value2) to determine status. Multiple key values can be delimited with colon (key,value1:value2). Return critical if equality check succeeds."
}
"--key_metrics" = {
value = "$http_json_key_metrics$"
description = "Gathers the values of these keys"
}
}
}

9
makefile Normal file
View File

@@ -0,0 +1,9 @@
.PHONY: lint test coverage
lint:
python3 -m pylint check_http_json.py
test:
python3 -m unittest discover
coverage:
python3 -m coverage run -m unittest discover
python3 -m coverage report -m --include check_http_json.py

2
test/requirements.txt Normal file
View File

@@ -0,0 +1,2 @@
coverage==5.0.3
pylint==2.4.4

View File

@@ -256,7 +256,7 @@ class UtilTest(unittest.TestCase):
# This should not throw a KeyError # This should not throw a KeyError
data = '{}' data = '{}'
self.check_data(rules.dash_q(['(0).Node,foobar', '(1).Node,missing']), data, WARNING_CODE) self.check_data(rules.dash_q(['(0).Node,foobar', '(1).Node,missing']), data, CRITICAL_CODE)
def test_subelem(self): def test_subelem(self):
@@ -274,3 +274,23 @@ class UtilTest(unittest.TestCase):
self.check_data(rules.dash_E(['(*).capacity.value.too_deep']), data, CRITICAL_CODE) self.check_data(rules.dash_E(['(*).capacity.value.too_deep']), data, CRITICAL_CODE)
# Should not throw keyerror # Should not throw keyerror
self.check_data(rules.dash_E(['foo']), data, CRITICAL_CODE) self.check_data(rules.dash_E(['foo']), data, CRITICAL_CODE)
def test_empty_key_value_array(self):
"""
https://github.com/drewkerrigan/nagios-http-json/issues/61
"""
rules = RulesHelper()
# This should simply work
data = '[{"update_status": "finished"},{"update_status": "finished"}]'
self.check_data(rules.dash_q(['(*).update_status,finished']), data, OK_CODE)
# This should warn us
data = '[{"update_status": "finished"},{"update_status": "failure"}]'
self.check_data(rules.dash_q(['(*).update_status,finished']), data, WARNING_CODE)
# This should throw an error
data = '[]'
self.check_data(rules.dash_q(['(*).update_status,warn_me']), data, CRITICAL_CODE)

44
test/test_cli.py Normal file
View File

@@ -0,0 +1,44 @@
#!/usr/bin/env python3
import unittest
import unittest.mock as mock
import sys
import os
sys.path.append('..')
from check_http_json import debugPrint
class CLITest(unittest.TestCase):
"""
Tests for CLI
"""
def setUp(self):
"""
Defining the exitcodes
"""
self.exit_0 = 0 << 8
self.exit_1 = 1 << 8
self.exit_2 = 2 << 8
self.exit_3 = 3 << 8
def test_debugprint(self):
with mock.patch('builtins.print') as mock_print:
debugPrint(True, 'debug')
mock_print.assert_called_once_with('debug')
def test_debugprint_pprint(self):
with mock.patch('check_http_json.pprint') as mock_pprint:
debugPrint(True, 'debug', True)
mock_pprint.assert_called_once_with('debug')
def test_cli_without_params(self):
command = '/usr/bin/env python3 check_http_json.py > /dev/null 2>&1'
status = os.system(command)
self.assertEqual(status, self.exit_2)

View File

@@ -8,37 +8,90 @@ import os
sys.path.append('..') sys.path.append('..')
from check_http_json import debugPrint from check_http_json import main
class MockResponse():
def __init__(self, status_code=200, content='{"foo": "bar"}'):
self.status_code = status_code
self.content = content
def read(self):
return self.content
class MainTest(unittest.TestCase): class MainTest(unittest.TestCase):
""" """
Tests for main Tests for Main
""" """
def setUp(self): @mock.patch('builtins.print')
""" def test_main_version(self, mock_print):
Defining the exitcodes args = ['--version']
"""
self.exit_0 = 0 << 8 with self.assertRaises(SystemExit) as test:
self.exit_1 = 1 << 8 main(args)
self.exit_2 = 2 << 8
self.exit_3 = 3 << 8
def test_debugprint(self): mock_print.assert_called_once()
with mock.patch('builtins.print') as mock_print: self.assertEqual(test.exception.code, 0)
debugPrint(True, 'debug')
mock_print.assert_called_once_with('debug')
def test_debugprint_pprint(self): @mock.patch('builtins.print')
with mock.patch('check_http_json.pprint') as mock_pprint: @mock.patch('urllib.request.urlopen')
debugPrint(True, 'debug', True) def test_main_with_ssl(self, mock_request, mock_print):
mock_pprint.assert_called_once_with('debug') args = '-H localhost --ssl'.split(' ')
def test_cli_without_params(self): mock_request.return_value = MockResponse()
command = '/usr/bin/env python3 check_http_json.py > /dev/null 2>&1' with self.assertRaises(SystemExit) as test:
status = os.system(command) main(args)
self.assertEqual(status, self.exit_2) self.assertEqual(test.exception.code, 0)
@mock.patch('builtins.print')
@mock.patch('urllib.request.urlopen')
def test_main_with_parse_error(self, mock_request, mock_print):
args = '-H localhost'.split(' ')
mock_request.return_value = MockResponse(content='not JSON')
with self.assertRaises(SystemExit) as test:
main(args)
self.assertTrue('Parser error' in str(mock_print.call_args))
self.assertEqual(test.exception.code, 3)
@mock.patch('builtins.print')
def test_main_with_url_error(self, mock_print):
args = '-H localhost'.split(' ')
with self.assertRaises(SystemExit) as test:
main(args)
self.assertTrue('URLError' in str(mock_print.call_args))
self.assertEqual(test.exception.code, 3)
@mock.patch('builtins.print')
@mock.patch('urllib.request.urlopen')
def test_main_with_http_error_no_json(self, mock_request, mock_print):
args = '-H localhost'.split(' ')
mock_request.return_value = MockResponse(content='not JSON', status_code=503)
with self.assertRaises(SystemExit) as test:
main(args)
self.assertTrue('Parser error' in str(mock_print.call_args))
self.assertEqual(test.exception.code, 3)
@mock.patch('builtins.print')
@mock.patch('urllib.request.urlopen')
def test_main_with_http_error_valid_json(self, mock_request, mock_print):
args = '-H localhost'.split(' ')
mock_request.return_value = MockResponse(status_code=503)
with self.assertRaises(SystemExit) as test:
main(args)
self.assertEqual(test.exception.code, 0)