forked from NagiosEnterprises/check_mssql_collection
-
Notifications
You must be signed in to change notification settings - Fork 0
/
check_mssql_database.py
executable file
·371 lines (316 loc) · 14 KB
/
check_mssql_database.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
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
#!/usr/bin/env python
################### check_mssql_database.py ############################
# Version : 2.0.1
# Date : 06/09/2016
# Maintainer : Nagios Enterprises, LLC
# Licence : GPLv3 (http://www.fsf.org/licenses/gpl.txt)
#
# Author/Maintainers:
# Nicholas Scott (Original author, Nagios)
# Jake Omann (Nagios)
# Scott Wilkerson (Nagios)
#
# Changelog:
# 2.0.1 - Fixed bug where temp file was named same as other for host and numbers were coming back bogus. (NS)
# 2.0.0 - Complete Revamp/Rewrite based on the server version of this plugin (NS)
# 1.3.0 - Added ability specify MSSQL instances (NS)
# 1.2.0 - Added ability to monitor instances (NS)
# Added check to see if pymssql is installed (NS)
# 1.1.0 - Fixed port bug allowing for non default ports (CBTSDon)
# Added mode error checking which caused non-graceful exit (Thanks mike from austria)
#
########################################################################
import pymssql
import time
import sys
import tempfile
try:
import cPickle as pickle
except:
import pickle
from optparse import OptionParser, OptionGroup
BASE_QUERY = "SELECT cntr_value FROM sysperfinfo WHERE counter_name='%s' AND instance_name='%%s';"
DIVI_QUERY = "SELECT cntr_value FROM sysperfinfo WHERE counter_name LIKE '%s%%%%' AND instance_name='%%s';"
MODES = {
'logcachehit' : { 'help' : 'Log Cache Hit Ratio',
'stdout' : 'Log Cache Hit Ratio is %s%%',
'label' : 'log_cache_hit_ratio',
'unit' : '%',
'query' : DIVI_QUERY % 'Log Cache Hit Ratio',
'type' : 'divide',
'modifier' : 100,
},
'activetrans' : { 'help' : 'Active Transactions',
'stdout' : 'Active Transactions is %s',
'label' : 'log_file_usage',
'unit' : '',
'query' : BASE_QUERY % 'Active Transactions',
'type' : 'standard',
},
'logflushes' : { 'help' : 'Log Flushes Per Second',
'stdout' : 'Log Flushes Per Second is %s/sec',
'label' : 'log_flushes_per_sec',
'query' : BASE_QUERY % 'Log Flushes/sec',
'type' : 'delta'
},
'logfileusage' : { 'help' : 'Log File Usage',
'stdout' : 'Log File Usage is %s%%',
'label' : 'log_file_usage',
'unit' : '%',
'query' : BASE_QUERY % 'Percent Log Used',
'type' : 'standard',
},
'transpec' : { 'help' : 'Transactions Per Second',
'stdout' : 'Transactions Per Second is %s/sec',
'label' : 'transactions_per_sec',
'query' : BASE_QUERY % 'Transactions/sec',
'type' : 'delta'
},
'loggrowths' : { 'help' : 'Log Growths',
'stdout' : 'Log Growths is %s',
'label' : 'log_growths',
'query' : BASE_QUERY % 'Log Growths',
'type' : 'standard'
},
'logshrinks' : { 'help' : 'Log Shrinks',
'stdout' : 'Log Shrinks is %s',
'label' : 'log_shrinks',
'query' : BASE_QUERY % 'Log Shrinks',
'type' : 'standard'
},
'logtruncs' : { 'help' : 'Log Truncations',
'stdout' : 'Log Truncations is %s',
'label' : 'log_truncations',
'query' : BASE_QUERY % 'Log Truncations',
'type' : 'standard'
},
'logwait' : { 'help' : 'Log Flush Wait Time',
'stdout' : 'Log Flush Wait Time is %sms',
'label' : 'log_wait_time',
'unit' : 'ms',
'query' : BASE_QUERY % 'Log Flush Wait Time',
'type' : 'standard'
},
'datasize' : { 'help' : 'Database Size',
'stdout' : 'Database size is %sKB',
'label' : 'KB',
'query' : BASE_QUERY % 'Data File(s) Size (KB)',
'type' : 'standard'
},
'time2connect' : { 'help' : 'Time to connect to the database.' },
'test' : { 'help' : 'Run tests of all queries against the database.' },
}
def return_nagios(options, stdout='', result='', unit='', label=''):
if int(options.critical) < int(options.warning):
invert = True
else:
invert = False
if is_within_range(options.critical, result, invert):
prefix = 'CRITICAL: '
code = 2
elif is_within_range(options.warning, result, invert):
prefix = 'WARNING: '
code = 1
else:
prefix = 'OK: '
code = 0
strresult = str(result)
stdout = stdout % (strresult)
stdout = '%s%s|%s=%s%s;%s;%s;;' % (prefix, stdout, label, strresult, unit, options.warning or '', options.critical or '')
raise NagiosReturn(stdout, code)
class NagiosReturn(Exception):
def __init__(self, message, code):
self.message = message
self.code = code
class MSSQLQuery(object):
def __init__(self, query, options, label='', unit='', stdout='', host='', modifier=1, *args, **kwargs):
self.query = query % options.table
self.label = label
self.unit = unit
self.stdout = stdout
self.options = options
self.host = host
self.modifier = modifier
def run_on_connection(self, connection):
cur = connection.cursor()
cur.execute(self.query)
self.query_result = cur.fetchone()[0]
def finish(self):
return_nagios( self.options,
self.stdout,
self.result,
self.unit,
self.label )
def calculate_result(self):
self.result = float(self.query_result) * self.modifier
def do(self, connection):
self.run_on_connection(connection)
self.calculate_result()
self.finish()
class MSSQLDivideQuery(MSSQLQuery):
def calculate_result(self):
self.result = (float(self.query_result[0]) / self.query_result[1]) * self.modifier
def run_on_connection(self, connection):
cur = connection.cursor()
cur.execute(self.query)
self.query_result = [x[0] for x in cur.fetchall()]
class MSSQLDeltaQuery(MSSQLQuery):
def make_pickle_name(self):
tmpdir = tempfile.gettempdir()
tmpname = hash(self.host + self.table + self.query)
self.picklename = '%s/mssql-%s.tmp' % (tmpdir, tmpname)
def calculate_result(self):
self.make_pickle_name()
try:
tmpfile = open(self.picklename)
except IOError:
tmpfile = open(self.picklename, 'w')
tmpfile.close()
tmpfile = open(self.picklename)
try:
try:
last_run = pickle.load(tmpfile)
except EOFError, ValueError:
last_run = { 'time' : None, 'value' : None }
finally:
tmpfile.close()
if last_run['time']:
old_time = last_run['time']
new_time = time.time()
old_val = last_run['query_result']
new_val = self.query_result
self.result = ((new_val - old_val) / (new_time - old_time)) * self.modifier
else:
self.result = None
new_run = { 'time' : time.time(), 'query_result' : self.query_result }
#~ Will throw IOError, leaving it to aquiesce
tmpfile = open(self.picklename, 'w')
pickle.dump(new_run, tmpfile)
tmpfile.close()
def is_within_range(nagstring, value, invert = False):
if not nagstring:
return False
import re
import operator
first_float = r'(?P<first>(-?[0-9]+(\.[0-9]+)?))'
second_float= r'(?P<second>(-?[0-9]+(\.[0-9]+)?))'
actions = [ (r'^%s$' % first_float,lambda y: (value > float(y.group('first'))) or (value < 0)),
(r'^%s:$' % first_float,lambda y: value < float(y.group('first'))),
(r'^~:%s$' % first_float,lambda y: value > float(y.group('first'))),
(r'^%s:%s$' % (first_float,second_float), lambda y: (value < float(y.group('first'))) or (value > float(y.group('second')))),
(r'^@%s:%s$' % (first_float,second_float), lambda y: not((value < float(y.group('first'))) or (value > float(y.group('second')))))]
for regstr,func in actions:
res = re.match(regstr,nagstring)
if res:
if invert:
return not func(res)
else:
return func(res)
raise Exception('Improper warning/critical format.')
def parse_args():
usage = "usage: %prog -H hostname -U user -P password -T table --mode"
parser = OptionParser(usage=usage)
required = OptionGroup(parser, "Required Options")
required.add_option('-H', '--hostname', help='Specify MSSQL Server Address', default=None)
required.add_option('-U', '--user', help='Specify MSSQL User Name', default=None)
required.add_option('-P', '--password', help='Specify MSSQL Password', default=None)
required.add_option('-T', '--table', help='Specify the table to check', default=None)
parser.add_option_group(required)
connection = OptionGroup(parser, "Optional Connection Information")
connection.add_option('-I', '--instance', help='Specify instance', default=None)
connection.add_option('-p', '--port', help='Specify port.', default=None)
parser.add_option_group(connection)
nagios = OptionGroup(parser, "Nagios Plugin Information")
nagios.add_option('-w', '--warning', help='Specify warning range.', default=None)
nagios.add_option('-c', '--critical', help='Specify critical range.', default=None)
parser.add_option_group(nagios)
mode = OptionGroup(parser, "Mode Options")
global MODES
for k, v in zip(MODES.keys(), MODES.values()):
mode.add_option('--%s' % k, action="store_true", help=v.get('help'), default=False)
parser.add_option_group(mode)
options, _ = parser.parse_args()
if not options.hostname:
parser.error('Hostname is a required option.')
if not options.user:
parser.error('User is a required option.')
if not options.password:
parser.error('Password is a required option.')
if not options.table:
parser.error('Table is a required option.')
if options.instance and options.port:
parser.error('Cannot specify both instance and port.')
options.mode = None
for arg in mode.option_list:
if getattr(options, arg.dest) and options.mode:
parser.error("Must choose one and only Mode Option.")
elif getattr(options, arg.dest):
options.mode = arg.dest
return options
def connect_db(options):
host = options.hostname
if options.instance:
host += "\\" + options.instance
elif options.port:
host += ":" + options.port
start = time.time()
mssql = pymssql.connect(host = host, user = options.user, password = options.password, database=options.table)
total = time.time() - start
return mssql, total, host
def main():
options = parse_args()
mssql, total, host = connect_db(options)
if options.mode =='test':
run_tests(mssql, options, host)
elif not options.mode or options.mode == 'time2connect':
return_nagios( options,
stdout='Time to connect was %ss',
label='time',
unit='s',
result=total )
else:
execute_query(mssql, options, host)
def execute_query(mssql, options, host=''):
sql_query = MODES[options.mode]
sql_query['options'] = options
sql_query['host'] = host
query_type = sql_query.get('type')
if query_type == 'delta':
mssql_query = MSSQLDeltaQuery(**sql_query)
elif query_type == 'divide':
mssql_query = MSSQLDivideQuery(**sql_query)
else:
mssql_query = MSSQLQuery(**sql_query)
mssql_query.do(mssql)
def run_tests(mssql, options, host):
failed = 0
total = 0
del MODES['time2connect']
del MODES['test']
for mode in MODES.keys():
total += 1
options.mode = mode
try:
execute_query(mssql, options, host)
except NagiosReturn:
print "%s passed!" % mode
except Exception, e:
failed += 1
print "%s failed with: %s" % (mode, e)
print '%d/%d tests failed.' % (failed, total)
if __name__ == '__main__':
try:
main()
except pymssql.OperationalError, e:
print e
sys.exit(3)
except IOError, e:
print e
sys.exit(3)
except NagiosReturn, e:
print e.message
sys.exit(e.code)
except Exception, e:
print type(e)
print "Caught unexpected error. This could be caused by your sysperfinfo not containing the proper entries for this query, and you may delete this service check."
sys.exit(3)