forked from matt448/nagios-checks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
check-template-json-webservice.py
executable file
·176 lines (144 loc) · 5.22 KB
/
check-template-json-webservice.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
#!/usr/bin/python
#########################################
# Notes
#########################################
#
# Written by Matthew McMillan
# @matthewmcmillan
# https://matthewcmcmillan.blogspot.com
# https://github.com/matt448/nagios-checks
#
# Nagios error codes
# 0 = OK
# 1 = WARNING
# 2 = CRITICAL
# 3 = UNKNOWN
#
# This check template uses a JSON test website (http://www.jsontest.com/)
# as an example webservice. Please change this to fit your needs.
#
# This is only an example/template. This check is not useful unless it
# is customized for your environment and webservice.
#
# Nagios dev guidelines
# http://nagiosplug.sourceforge.net/developer-guidelines.html
#
#
import sys
import json
import argparse
#from datetime import datetime, time, timedelta
import httplib, urllib, urllib2
from urllib2 import Request, urlopen, URLError, HTTPError
from pprint import pprint
#Variables
useragent = 'Nagios/3.2.3'
apipath = '/?json={"key1":"value1","key2":"value2","key3":"value3"}'
#Parse command line arguments
parser = argparse.ArgumentParser(description='This is a template Nagios check that verifies a \
webservice is functioning and parses the returned JSON data. \
JSON data can be checked for values and alerted on. \
Perfdata is also generated for JSON values.')
parser.add_argument('--host', dest='host', type=str, required=True,
help='Hostname or IP address of api server. For this template use validate.jsontest.com')
parser.add_argument('--maxsize', dest='maxsize', type=int, default=20,
help='Maximum number for some JSON value. Default is is 20.')
parser.add_argument('--maxtime', dest='maxtime', type=float, default=0.7,
help='Maximum parse time in milliseconds. Default is is 0.7.')
parser.add_argument('--debug', action='store_true',
help='Enable debug output.')
parser.add_argument('--ssl', action='store_true',
help='Enable https/ssl communication with api server')
args = parser.parse_args()
#Assign variables from command line arguments
host = args.host
maxsize = args.maxsize
maxtime = args.maxtime
if (args.debug):
print '########## START DEBUG OUTPUT ############'
print 'HOST: ' + host
print 'MAXSIZE: ' + str(maxsize)
print 'MAXTIME: ' + str(maxtime) + ' milliseconds'
if (args.ssl):
print 'SSL: Encrypted communication enabled.'
else:
print 'SSL: Encrypted communication NOT enabled.'
#Turn on https URL if the --ssl arg is passed
if (args.ssl):
url = 'https://' + host + apipath
if (args.debug):
print "URL: " + url
else:
url = 'http://' + host + apipath
if (args.debug):
print "URL: " + url
#Set custom User-Agent string
headers = { 'User-Agent' : useragent }
# Build request string
req = urllib2.Request(url, None, headers)
# Handle http error responses from server.
try:
response = urllib2.urlopen(req)
except HTTPError as e:
errorcode = e.code
msg = 'Server couldn\'t fulfill the request.'
msg += ' http_error_code=' + str(errorcode) + ' host=' + host
perfdatamsg = ''
exitcode = 2
except URLError as e:
errorreason = e.reason
msg = 'We failed to reach a server.' + str(errorreason) + ' host=' + host
perfdatamsg = ''
exitcode = 2
else:
jsondata = response.read() #Read JSON data from web site
data = json.loads(jsondata) #Load JSON data into a dict
parse_time = float(float(data['parse_time_nanoseconds'])/1000000)
size = data['size']
if (args.debug):
print 'START JSON OUTPUT:'
print '----------------------------------'
pprint(data)
print '----------------------------------'
print 'END JSON OUTPUT'
print 'PARSE TIME: ' + str(parse_time) + ' Milliseconds'
print 'SIZE: ' + str(size)
#Evaluate returned data for maximums
if (parse_time < maxtime) and (size < maxsize):
exitcode = 0
msg = 'Parse time and size within limits.'
elif (parse_time >= maxtime) and (size < maxsize):
exitcode = 1
msg = 'Maximum parse time exceeded.'
elif (parse_time < maxtime) and (size >= maxsize):
exitcode = 1
msg = 'Maximum size exceeded.'
elif (parse_time >= maxtime) and (size >= maxsize):
exitcode = 1
msg = 'Both parse time and size have exceeded maximum values.'
else:
exitcode = 3
msg = 'Status unknown.'
# Additional output for status message
msg += ' parse_time=' + str(parse_time) + 'ms'
msg += ' size=' + str(size)
msg += ' host=' + host
perfdatamsg = 'size=' + str(size) + ';0;0 '
perfdatamsg += 'parse_time=' + str(parse_time) + 'ms;0;0 '
#Generate final output for Nagios message
if (exitcode == 0):
statusline = 'OK: ' + msg + '|' + perfdatamsg
elif (exitcode == 1):
statusline = 'WARNING: ' + msg + '|' + perfdatamsg
elif (exitcode == 2):
statusline = 'CRITICAL: ' + msg + '|' + perfdatamsg
else:
statusline = 'UNKNOWN: ' + msg + '|' + perfdatamsg
exitcode = 3
if (args.debug):
print '########## END DEBUG OUTPUT ##############'
print ' '
#Print Nagios status message
print statusline
exit(exitcode)