]>
git.datanom.net - check_http.git/blob - check_actuator_health.py
3 ###############################################################################
4 # Nagios plugin template
7 # - The RHEL boxes I work on are currently limited to Python 2.6.6, hence the
8 # use of (deprecated) optparse. If I can ever get them all updated to
9 # Python 2.7 (or better yet, 3.3), I'll switch to argparse
10 # - This template runs in 2.6-3.3. Any changes made will need to be appropriate
11 # to the Python distro you want to use
13 ###############################################################################
15 __author__
= 'mr.it@cbs.dk - Michael Rasmussen'
19 from optparse
import OptionParser
, OptionGroup
#
22 import urllib3
as urllib
# python3-urllib3-1.24.2-5.el8.noarch.rpm python3-urllib3-1.26.5-3.el9.noarch.rpm
27 ## These will override any args passed to the script normally. Comment out after testing.
29 #testargs = '--version'
40 "database": "PostgreSQL",
41 "validationQuery": "isValid()"
47 "total": 2013582688256,
48 "free": 1635574571008,
49 "threshold": 10485760,
50 "path": "/home/mir/git/soasi-course-catalog-course-target-adapter/.",
66 "adapterDataSource": {
69 "error": "org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection"
75 "database": "Microsoft SQL Server",
76 "validationQuery": "isValid()"
79 "providersDataSource": {
82 "error": "org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection"
90 "total": 1013309239296,
92 "threshold": 10485760,
93 "path": "C:\\Users\\hf.it\\Projects\\smart-integrations\\adapters\\target\\soasi-invigilation-report-target-adapter",
104 """ Main plugin logic goes here """
106 ## Parse command-line arguments
107 args
, args2
= parse_args()
109 ## Uncomment to test logging levels against verbosity settings
110 # log.debug('debug message')
111 # log.info('info message')
112 # log.warning('warning message')
113 # log.error('error message')
114 # log.critical('critical message')
115 # log.fatal('fatal message')
117 keyword
= options
['keyword']
119 agent
= options
['agent']
120 if keyword
is None or url
is None:
121 message
= "Keywork: {0} url: {1}".format(keyword
, url
)
130 http
= urllib
.PoolManager()
131 response
= http
.request(
132 'GET', url
, headers
= req_headers
134 data
= response
.data
.decode('utf-8').replace("\\"," ")
136 data
= DOWN_RESPONSE
.replace("\\"," ")
137 data
= json
.loads(data
)
138 if 'status' in data
and data
['status'] == keyword
:
142 message
= gather_message(data
)
144 except Exception as e
:
149 gtfo(status
, message
)
151 def gather_message(json_data
):
152 """ Assemble error messages """
155 if 'components' in json_data
:
156 components
= json_data
['components']
157 for component
in components
:
158 items
= components
[component
]
159 if 'components' in items
:
160 for item
in items
['components']:
161 if 'status' in items
['components'][item
] and items
['components'][item
]['status'].upper() == 'DOWN':
163 msg
+= "\n{0}: {1}".format(item
, items
['components'][item
]['details']['error'])
165 msg
= "{0}: {1}".format(item
, items
['components'][item
]['details']['error'])
167 if 'status' in items
and items
['status'].upper() == 'DOWN':
169 if 'details' in items
and 'error' in items
['details']:
170 error
= items
['details']['error']
172 error
= "No error message"
174 msg
+= "\n{0}: {1}".format(component
, error
)
176 msg
= "{0}: {1}".format(component
, error
)
185 """ Parse command-line arguments """
187 parser
= OptionParser(usage
='usage: %prog [-v|vv|vvv] [options]',
188 version
='{0}: v.{1} by {2}'.format('%prog', __version__
, __author__
))
190 ## Verbosity (want this first, so it's right after --help and --version)
191 parser
.add_option('-v', help='Set verbosity level',
192 action
='count', default
=0, dest
='v')
194 ## CLI arguments specific to this script
195 group
= OptionGroup(parser
,'Plugin Options')
196 group
.add_option('-a', '--agent', help="User agent for request. Default: Python-nagios",
197 default
="Python-nagios", type='string')
198 group
.add_option('-k', '--keyword', help="Keyword to search for in response", default
=None)
199 group
.add_option('-t', '--testing', help="Run in testing mode", default
=False, action
='store_true')
200 group
.add_option('-u', '--url', help="URL to requested resource", default
=None)
202 ## Common CLI arguments
203 #parser.add_option('-c', '--critical', help='Set the critical threshold. Default: %(default)s',
204 # default=97, type=float, dest='crit', metavar='##')
205 #parser.add_option('-w', '--warning', help='Set the warning threshold. Default: %(default)s',
206 # default=95, type=float, dest='warn', metavar='##')
208 parser
.add_option_group(group
)
210 ## Try to parse based on the testargs variable. If it doesn't exist, use args
212 args
, args2
= parser
.parse_args(testargs
.split())
214 args
, args2
= parser
.parse_args()
216 ## Set the logging level based on the -v arg
217 log
.getLogger().setLevel([log
.ERROR
, log
.WARN
, log
.INFO
, log
.DEBUG
][args
.v
])
219 log
.debug('Parsed arguments: {0}'.format(args
))
220 log
.debug('Other arguments: {0}'.format(args2
))
224 def gtfo(exitcode
, message
=''):
225 """ Exit gracefully with exitcode and (optional) message """
227 log
.debug('Exiting with status {0}. Message: {1}'.format(exitcode
, message
))
233 if __name__
== '__main__':
234 ## Initialize logging before hitting main, in case we need extra debuggability
235 log
.basicConfig(level
=log
.DEBUG
, format
='%(asctime)s - %(funcName)s - %(levelname)s - %(message)s')
This page took 0.122775 seconds and 6 git commands to generate.