-
Notifications
You must be signed in to change notification settings - Fork 0
/
check_json
executable file
·284 lines (236 loc) · 11.8 KB
/
check_json
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
#! /usr/bin/env python
"""
Nagios plugin to check a value returned from a uri in json format.
Author: Stephen Huenneke <[email protected]>
Copyright (c) 2011 HubSpot Inc. All rights reserved.
Download the latest version at https://github.com/HubSpot/HubSpot-Nagios-Plugins
Originally by Peter Kropf, hosted at https://github.com/pkropf/Nagio-Plugins/tree/master/json
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import urllib2
import signal
import simplejson
import sys
import time
from optparse import OptionParser
prefix = 'JSON'
class nagios:
ok = (0, 'OK')
warning = (1, 'WARNING')
critical = (2, 'CRITICAL')
unknown = (3, 'UNKNOWN')
class TimeoutException(Exception):
pass
def raise_timeout(signum, frame):
raise TimeoutException("Timeout was hit.")
signal.signal(signal.SIGALRM, raise_timeout)
def exit(status, message):
print prefix + ' ' + status[1] + ' - ' + message
sys.exit(status[0])
"""
A simple string matcher, falls through from crit -> warn -> ok -> unknown
"""
def check_string(options, j):
print "Checking string..."
if options.crit_field_value is not None and j[options.field_name] == options.crit_field_value:
exit(nagios.critical, "%s == %s" % (j[options.field_name], options.crit_field_value))
elif options.warn_field_value is not None and j[options.field_name] == options.warn_field_value:
exit(nagios.warning, "%s == %s" % (j[options.field_name], options.warn_field_value))
elif options.ok_field_value is not None and j[options.field_name] == options.ok_field_value:
exit(nagios.ok, "%s == %s" % (j[options.field_name], options.ok_field_value))
exit(nagios.unknown, "Field: %s has no value to match against." % options.field_name)
"""
A boolean parser/checker, fails with unknown when either the value to
check or the returned value is not a boolean. Otherwise, returns ok
or critical, no warn mode.
"""
def check_boolean(options, j):
print "Checking boolean..."
if options.ok_field_value is None:
exit(nagios.unknown, "No value to check against for %s." % options.field_name)
if str(options.ok_field_value).strip().lower() not in ["false","true"]:
exit(nagios.unknown, "'%s' is not a boolean, please only use 'true' or 'false' to check against booleans." % options.ok_field_value)
ok_value = str(options.ok_field_value).strip().lower()
field_value = str(j[options.field_name]).strip().lower()
if field_value not in ["false","true"]:
exit(nagios.unknown, "Returned value '%s' is not a boolean, can't match." % j[options.field_name])
if field_value == ok_value:
exit(nagios.ok, "%s == %s" % (field_value, ok_value))
else:
exit(nagios.critical, "%s != %s" % (field_value, ok_value))
"""
A threshold checker if any of the values are non-numeric, we return
unknown. Otherwise, we fall through from crit -> warn -> ok depending
on whether the returned value is greater than or equal to the critical
value or the warn value or less than both.
"""
def check_threshold(options, j):
if not str(j[options.field_name]).isdigit():
exit(nagios.unknown, "Field '%s' has non-numeric value '%s'" % (options.field_name, j[options.field_name]))
if (options.crit_field_value is None or not options.crit_field_value.isdigit()) \
and (options.warn_field_value is None or not options.warn_field_value.isdigit()):
exit(nagios.unknown, "Non-numeric or empty values entered for critical='%s' and warn='%s' checks, can't do threshold check." % (options.crit_field_value, options.warn_field_value))
if float(options.crit_field_value) < float(options.warn_field_value):
exit(nagios.unknown, "Critical threshold is less than warning threshold, can't compare properly.")
print "Checking threshold..."
if options.crit_field_value is not None \
and options.crit_field_value.isdigit() \
and float(j[options.field_name]) >= float(options.crit_field_value):
exit(nagios.critical, "%s >= %s" % (j[options.field_name], options.crit_field_value))
elif options.warn_field_value is not None \
and options.warn_field_value.isdigit() \
and float(j[options.field_name]) >= float(options.warn_field_value):
exit(nagios.warning, "%s >= %s" % (j[options.field_name], options.warn_field_value))
else:
exit(nagios.OK, "%s < %s" % (j[options.field_name], options.warn_field_value))
"""
A timestamp age checker. Similar to the threshold checker, but wraps
some timestamp math for you. Can parse either secs or milis since
epoch. Same cascading as threshold, fall through from crit -> warn ->
ok or unkown if something isn't a number.
"""
def check_timestamp(options, j):
print "Checking threshold..."
current_ts = time.time()
if not str(j[options.field_name]).isdigit() or float(j[options.field_name]) < 0:
exit(nagios.unknown, "Field '%s' has non-timestamp value '%s'" % (options.field_name, j[options.field_name]))
if (options.crit_field_value is None or not options.crit_field_value.isdigit()) \
and (options.warn_field_value is None or not options.warn_field_value.isdigit()):
exit(nagios.unknown, "Non-numeric or empty values entered for critical='%s' and warn='%s' checks, can't do threshold check." % (options.crit_field_value, options.warn_field_value))
returned_ts = float(j[options.field_name])
#if timestamp is in ms, bump it down to secs
if (returned_ts / 1000000000) >= 1000:
returned_ts = returned_ts / 1000
time_diff_secs = current_ts - returned_ts
if time_diff_secs < 0:
exit(nagios.unknown, "%s ?? %s" % (j[options.field_name], current_ts))
if options.crit_field_value is not None \
and options.crit_field_value.isdigit() \
and time_diff_secs >= float(options.crit_field_value):
exit(nagios.critical, "%s >= %s" % (time_diff_secs, options.crit_field_value))
elif options.warn_field_value is not None \
and options.warn_field_value.isdigit() \
and time_diff_secs >= float(options.warn_field_value):
exit(nagios.warning, "%s >= %s" % (time_diff_secs, options.warn_field_value))
else:
exit(nagios.ok, "%s < %s" % (time_diff_secs, options.warn_field_value))
parser = OptionParser(usage="""usage:
A threshold check with a warn limit of 100 and critical limit of 300:
%prog --ssl -H <hostname> -p <port> -u "/path/to/json?args=args" -Tthreshold -f "someCounter" -w100 -c300
A timestamp age check with a warn limit of 30 seconds and critical limit of 600 seconds:
%prog --ssl -H <hostname> -p <port> -u "/path/to/json?args=args" -Ttimestamp -f "someTimestamp" -w30 -c600
A positive boolean check ("OK" value is case insensitive for booleans):
%prog --ssl -H <hostname> -p <port> -u "/path/to/json?args=args" -Tbool -f "someTimestamp" -vtrue
A negative boolean check ("OK" value is case insensitive for booleans):
%prog --ssl -H <hostname> -p <port> -u "/path/to/json?args=args" -Tbool -f "someTimestamp" -vFALSE
A string match check with ok, warn and critical values:
%prog --ssl -H <hostname> -p <port> -u "/path/to/json?args=args" -Tstring -f "someTimestamp" -vgreen -wyellow -cred
""")
parser.add_option("--ssl",
metavar="SSL",
help="Use SSL as the protocol",
dest="use_ssl",
action="store_true",
default=False)
parser.add_option("-H", "--hostname",
metavar="HOSTNAME",
help="The hostname to query against",
dest="hostname",
default=None)
parser.add_option("-p", "--port",
metavar="PORT",
help="The port to use in the URI",
dest="port",
default="80")
parser.add_option("-u", "--path",
metavar="PATH",
help="The path to query",
dest="path",
default=None)
parser.add_option("-f", "--field",
metavar="FIELDNAME",
help="The field to match against",
dest="field_name",
default=None)
parser.add_option("-v", "--ok",
metavar="PATH",
help="The 'ok' field value to match",
dest="ok_field_value",
default=None)
parser.add_option("-w", "--warning",
metavar="PATH",
help="The 'warning' field value to match",
dest="warn_field_value",
default=None)
parser.add_option("-c", "--critical",
metavar="PATH",
help="The 'warning' field value to match",
dest="crit_field_value",
default=None)
parser.add_option("-t", "--timeout",
metavar="TIMEOUTSECS",
help="The maximum number of secs to wait for a response.",
dest="timeout",
default=10)
parser.add_option("-T","--type",
metavar="VALUETYPE",
help="The type (threshold,string,boolean)",
dest="value_type",
default="string")
options, args = parser.parse_args()
if options.hostname is None:
exit(nagios.unknown, 'missing hostname argument')
if options.path is None:
exit(nagios.unknown, 'missing uri path argument')
if options.field_name is None:
exit(nagios.unknown, 'missing field_name argument')
uri = "https://%s:%s%s" % (options.hostname, options.port, options.path)
if not options.use_ssl:
uri = uri.replace("https","http")
exit_code = None
exit_message = None
#Nested try/except inside a try/finally for python 2.4 compatibility, I'm sorry.
try:
try:
signal.alarm(int(options.timeout)) # raise alarm in X seconds, this is a hack for python 2.5's lack of support for timeout in urlopen :(
j = simplejson.load(urllib2.urlopen(uri))
except urllib2.HTTPError, ex:
exit_code = nagios.unknown
exit_message = 'unable to retrieve url: "%s"' % uri
except urllib2.URLError, ex:
exit_code = nagios.critical
exit_message = 'unable to retrieve url: "%s"' % uri
except TimeoutException, ex:
exit_code = nagios.warning
exit_message = 'timeout in %s seconds trying to retrieve url: "%s"' % (options.timeout, uri)
finally:
signal.alarm(0) # disable alarm
if exit_code is not None:
exit(exit_code, exit_message)
if options.field_name not in j:
exit(nagios.unknown, "Field: '%s' not present" % options.field_name)
value_type = options.value_type.strip().lower()
print "Checking %s as a %s value" % (options.field_name, value_type)
if value_type == "string":
check_string(options, j)
elif value_type == "threshold":
check_threshold(options, j)
elif value_type == "bool":
check_boolean(options, j)
elif value_type == "timestamp":
check_timestamp(options, j)
exit(nagios.unknown, "I don't know how to check a '%s' value!" % value_type)