]> git.datanom.net - check_http.git/blob - check_http.py
more
[check_http.git] / check_http.py
1 #! /usr/bin/env python
2
3 ###############################################################################
4 # Nagios plugin template
5 #
6 # Notes
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
12 #
13 ###############################################################################
14
15 __author__ = 'mr.it@cbs.dk - Michael Rasmussen'
16 __version__= 0.1
17
18 try:
19 from optparse import OptionParser, OptionGroup
20 import logging as log
21 import sys
22 import urllib3 as urllib
23 import json
24 except:
25 sys.exit(2)
26
27 ## These will override any args passed to the script normally. Comment out after testing.
28 #testargs = '--help'
29 #testargs = '--version'
30 #testargs = '-vvv'
31
32 OK_RESPONSE = """
33 {
34 "status": "UP",
35 "components": {
36 "db": {
37 "status": "UP",
38 "details": {
39 "database": "PostgreSQL",
40 "validationQuery": "isValid()"
41 }
42 },
43 "diskSpace": {
44 "status": "UP",
45 "details": {
46 "total": 2013582688256,
47 "free": 1635574571008,
48 "threshold": 10485760,
49 "path": "/home/mir/git/soasi-course-catalog-course-target-adapter/.",
50 "exists": true
51 }
52 },
53 "ping": {
54 "status": "UP"
55 }
56 }
57 }"""
58 DOWN_RESPONSE = """
59 {
60 "status": "DOWN",
61 "components": {
62 "db": {
63 "status": "DOWN",
64 "components": {
65 "adapterDataSource": {
66 "status": "DOWN",
67 "details": {
68 "error": "org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection"
69 }
70 },
71 "es3DataSource": {
72 "status": "UP",
73 "details": {
74 "database": "Microsoft SQL Server",
75 "validationQuery": "isValid()"
76 }
77 },
78 "providersDataSource": {
79 "status": "DOWN",
80 "details": {
81 "error": "org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection"
82 }
83 }
84 }
85 },
86 "diskSpace": {
87 "status": "UP",
88 "details": {
89 "total": 1013309239296,
90 "free": 882010726400,
91 "threshold": 10485760,
92 "path": "C:\\Users\\hf.it\\Projects\\smart-integrations\\adapters\\target\\soasi-invigilation-report-target-adapter",
93 "exists": true
94 }
95 },
96 "ping": {
97 "status": "UP"
98 }
99 }
100 }
101 """
102 def main():
103 """ Main plugin logic goes here """
104
105 ## Parse command-line arguments
106 args, args2 = parse_args()
107
108 ## Uncomment to test logging levels against verbosity settings
109 # log.debug('debug message')
110 # log.info('info message')
111 # log.warning('warning message')
112 # log.error('error message')
113 # log.critical('critical message')
114 # log.fatal('fatal message')
115 options = vars(args)
116 keyword = options['keyword']
117 url = options['url']
118 agent = options['agent']
119 if keyword is None or url is None:
120 message = "Keywork: {0} url: {1}".format(keyword, url)
121 status = 3
122 log.fatal(message)
123 else:
124 try:
125 # req_headers = {
126 # 'User-Agent': agent
127 # }
128 # http = urllib.PoolManager()
129 # response = http.request(
130 # 'GET', url, headers = req_headers
131 # )
132 # data = response.data.decode('utf-8')
133 data = OK_RESPONSE.replace("\\"," ")
134 data = json.loads(data)
135 if 'status' in data and data['status'] == keyword:
136 message = "UP"
137 status = 2
138 else:
139 message = "DOWN"
140 status = 0
141 except Exception as e:
142 print(e)
143 message = "DOWN"
144 status = 2
145
146 gtfo(status, message)
147
148
149 def parse_args():
150 """ Parse command-line arguments """
151
152 parser = OptionParser(usage='usage: %prog [-v|vv|vvv] [options]',
153 version='{0}: v.{1} by {2}'.format('%prog', __version__, __author__))
154
155 ## Verbosity (want this first, so it's right after --help and --version)
156 parser.add_option('-v', help='Set verbosity level',
157 action='count', default=0, dest='v')
158
159 ## CLI arguments specific to this script
160 group = OptionGroup(parser,'Plugin Options')
161 group.add_option('-a', '--agent', help="User agent for request. Default: Python-nagios",
162 default="Python-nagios", type='string')
163 group.add_option('-k', '--keyword', help="Keyword to search for in response", default=None)
164 group.add_option('-u', '--url', help="URL to requested resource", default=None)
165
166 ## Common CLI arguments
167 #parser.add_option('-c', '--critical', help='Set the critical threshold. Default: %(default)s',
168 # default=97, type=float, dest='crit', metavar='##')
169 #parser.add_option('-w', '--warning', help='Set the warning threshold. Default: %(default)s',
170 # default=95, type=float, dest='warn', metavar='##')
171
172 parser.add_option_group(group)
173
174 ## Try to parse based on the testargs variable. If it doesn't exist, use args
175 try:
176 args, args2 = parser.parse_args(testargs.split())
177 except NameError:
178 args, args2 = parser.parse_args()
179
180 ## Set the logging level based on the -v arg
181 log.getLogger().setLevel([log.ERROR, log.WARN, log.INFO, log.DEBUG][args.v])
182
183 log.debug('Parsed arguments: {0}'.format(args))
184 log.debug('Other arguments: {0}'.format(args2))
185
186 return args, args2
187
188 def gtfo(exitcode, message=''):
189 """ Exit gracefully with exitcode and (optional) message """
190
191 log.debug('Exiting with status {0}. Message: {1}'.format(exitcode, message))
192
193 if message:
194 print(message)
195 exit(exitcode)
196
197 if __name__ == '__main__':
198 ## Initialize logging before hitting main, in case we need extra debuggability
199 log.basicConfig(level=log.DEBUG, format='%(asctime)s - %(funcName)s - %(levelname)s - %(message)s')
200 main()
This page took 0.07858 seconds and 6 git commands to generate.