This repository has been archived by the owner on Feb 20, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
check_azure_sql.py
executable file
·679 lines (613 loc) · 27.7 KB
/
check_azure_sql.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
#!/usr/bin/python
# Copyright 2013 MS Open Tech
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#check_azure_compute.py: Azure compute monitor script
import argparse
import exceptions
import logging
import os
import pyodbc
import sys
from datetime import datetime
from datetime import timedelta
logger = None
DBSIZE_DMV = '''SELECT SUM(reserved_page_count)*8.0/1024 FROM
sys.dm_db_partition_stats;'''
OBJSIZE_DMV = '''SELECT sys.objects.name, SUM(reserved_page_count)
* 8.0 / 1024 FROM sys.dm_db_partition_stats, sys.objects
WHERE sys.dm_db_partition_stats.object_id =
sys.objects.object_id GROUP BY sys.objects.name; '''
DBCONNECTIONS_DMV = '''SELECT e.connection_id, s.session_id, s.login_name,
s.last_request_end_time, s.cpu_time FROM
sys.dm_exec_sessions s INNER JOIN sys.dm_exec_connections e
ON s.session_id = e.session_id;'''
TOP5QUERIES_DMV = '''SELECT TOP 5 query_stats.query_hash AS "Query Hash",
SUM(query_stats.total_worker_time) /
SUM(query_stats.execution_count) AS "Avg CPU Time",
MIN(query_stats.statement_text) AS "Statement Text"
FROM
(SELECT QS.*,
SUBSTRING(ST.text, (QS.statement_start_offset/2) + 1,
((CASE statement_end_offset
WHEN -1 THEN DATALENGTH(st.text)
ELSE QS.statement_end_offset END
- QS.statement_start_offset)/2) + 1) AS statement_text
FROM sys.dm_exec_query_stats AS QS
CROSS APPLY sys.dm_exec_sql_text(QS.sql_handle) as ST)
as query_stats
GROUP BY query_stats.query_hash
ORDER BY 2 DESC;'''
QUERYPLAN_DMV = '''SELECT
highest_cpu_queries.plan_handle,
highest_cpu_queries.total_worker_time,
q.dbid,
q.objectid,
q.number,
q.encrypted,
q.[text]
FROM
(SELECT TOP 50
qs.plan_handle,
qs.total_worker_time
FROM
sys.dm_exec_query_stats qs
ORDER BY qs.total_worker_time desc) AS
highest_cpu_queries
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS q
ORDER BY highest_cpu_queries.total_worker_time desc'''
BWUSAGE_VIEW = 'select * from sys.bandwidth_usage where time > %s'
DBUSAGE_VIEW = 'select * from sys.database_usage where time > %s'
RESSTAT_VIEW = 'select * from sys.resource_stats where start_time > %s'
RESUSAGE_VIEW = 'select * from sys.resource_usage where time > %s'
OPSTATUS_VIEW = '''select resource_type_desc, operation, error_code,
error_desc, error_severity from sys.dm_operation_status'''
DBCONNECTION_VIEW = '''select * from sys.database_connection_stats
where start_time > %s'''
EVENTLOG_VIEW = 'select * from sys.event_log where start_time > %s'
def is_within_range(nagstring, value):
"""check if the value is withing the nagios range string
nagstring -- nagios range string
value -- value to compare
Returns true if within the range, else 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:
return func(res)
raise Exception('Improper warning/critical parameter format.')
def nagios_eval(result, warning, critical, nagios_message, unit='',
verbosity = 0):
"""check result with respect to warning and critical range
result -- counter value
warning -- nagios warning range string
critical -- nagios critical range string
nagios_message -- Nagios message
unit -- unit for the perf counter value
verbosity -- nagios verbosity value
Returns nagios code, and error message
"""
if is_within_range(critical, result):
prefix = 'CRITICAL:'
code = 2
elif is_within_range(warning, result):
prefix = 'WARNING:'
code = 1
else:
prefix = 'OK:'
code = 0
strresult = str(result)
if verbosity == 0:
if code > 0:
nagios_message = '%s' % prefix
else:
nagios_message = ''
elif verbosity == 1:
if code > 0:
nagios_message = nagios_message % (strresult)
nagios_message = '%s:%s %s' % ( prefix, nagios_message, unit or '')
else:
nagios_message = ''
else:
nagios_message = nagios_message % (strresult)
nagios_message = '%s%s%s,warning=%s,critical=%s,' % \
( prefix, nagios_message, unit or '', warning or '', critical or '')
return code, nagios_message
def analyze_dbsize(dbname, counter, row, warning, critical, verbosity):
"""analyze database size by comparing it with warning and critical ranges
dbname - name of database
counter - entry in the COUNTERS list
row - perf data from SQL server as an output of the SQL query/DMV
warning - warning range argument to the command
critical - critical range argument to the command
verbosity - verbose argument to the command.
"""
nagios_message = 'Size:%s'
result = row[0]
error_code, message = nagios_eval(result, warning, critical, nagios_message, \
'MB', verbosity)
return error_code, message
def analyze_objsize(dbname, counter, row, warning, critical, verbosity):
"""analyze object sizes by comparing them with warning and critical ranges
dbname - name of database
counter - entry in the COUNTERS list
row - perf data from SQL server as an output of the SQL query/DMV
warning - warning range argument to the command
critical - critical range argument to the command
verbosity - verbose argument to the command.
"""
nagios_message = 'Object:%s, Size:%%s' % (row[0],)
result = row[1]
error_code, message = nagios_eval(result, warning, critical, nagios_message,
'MB', verbosity)
return error_code, message
def analyze_conn_info(dbname, counter, row, warning, critical, verbosity):
"""analyze connnection response time using warning and critical args
dbname - name of database
counter - entry in the COUNTERS list
row - perf data from SQL server as an output of the SQL query/DMV
warning - warning range argument to the command
critical - critical range argument to the command
verbosity - verbose argument to the command.
"""
nagios_message = 'Database:%s, Login name:%s, CPU time:%%s' % \
(dbname, row[2],)
result = row[4]
error_code, message = nagios_eval(result, warning, critical,
nagios_message, 'ms', verbosity)
return error_code, message
def analyze_top5_queries(dbname, counter, row, warning, critical, verbosity):
"""Check top 5 database queries with warning and critical ranges
dbname - name of database
counter - entry in the COUNTERS list
row - perf data from SQL server as an output of the SQL query/DMV
warning - warning range argument to the command
critical - critical range argument to the command
verbosity - verbose argument to the command.
"""
nagios_message = 'Database:%s, query:%s, CPU time:%%s' % (dbname, row[2],)
result = row[1]
error_code, message = nagios_eval(result, warning, critical,
nagios_message, 'ms', verbosity)
return error_code, message
def byte_to_hex( bytestr ):
""" Convert a byte string to it's hex representation. """
return ''.join( [ '%02X ' % ord( x ) for x in bytestr ] ).strip()
def analyze_queryplan(dbname, counter, row, warning, critical, verbosity):
"""check query plan by comparing total woker time wrt warning and critical
dbname - name of database
counter - entry in the COUNTERS list
row - perf data from SQL server as an output of the SQL query/DMV
warning - warning range argument to the command
critical - critical range argument to the command
verbosity - verbose argument to the command.
"""
#handle = byte_to_hex(str(row[0]))
strquery = str(row[6])
nagios_message = 'Database:%s, query:%s, Total worker time:%%s' % \
(dbname, strquery, )
result = row[1]
error_code, message = nagios_eval(result, warning, critical,
nagios_message, 'ms', verbosity)
return error_code, message
def analyze_bwusage(dbname, counter, row, warning, critical, verbosity):
"""Analyze bandwidth usage with warning and critical ranges
dbname - name of database
counter - entry in the COUNTERS list
row - perf data from SQL server as an output of the SQL query/DMV
warning - warning range argument to the command
critical - critical range argument to the command
verbosity - verbose argument to the command.
"""
nagios_message = 'Database:%s, Time:%s, direction:%s, class:%s, '\
'time-period:%s, Size : %%s' % \
(row[1], str(row[0]), row[2], row[3], row[4],)
result = row[5]
error_code, message = nagios_eval(result, warning, critical,
nagios_message, 'MB', verbosity)
return error_code, message
def analyze_dbusage(dbname, counter, row, warning, critical, verbosity):
"""check query plan CPU usage with warning and critical ranges.
Does not use db size
dbname - name of database
counter - entry in the COUNTERS list
row - perf data from SQL server as an output of the SQL query/DMV
warning - warning range argument to the command
critical - critical range argument to the command
verbosity - verbose argument to the command.
"""
nagios_message = 'Database:%s, Time:%s, Size %s, Quantity : %%s' % \
(dbname, str(row[0]), row[1], )
result = row[2]
error_code, message = nagios_eval(result, warning, critical,
nagios_message, 'MB', verbosity)
return error_code, message
def analyze_resstat(dbname, counter, row, warning, critical, verbosity):
"""Check resource status by comparing total woker time with warning
and critical ranges
dbname - name of database
counter - entry in the COUNTERS list
row - perf data from SQL server as an output of the SQL query/DMV
warning - warning range argument to the command
critical - critical range argument to the command
verbosity - verbose argument to the command.
"""
start_time = str(row[0])
end_time = str(row[1])
usage = str(row[4])
size = str(row[5])
nagios_message = 'Database:%s, Sku:%s - start_time:%s, end_time:%s, '\
'Size:%s, Usage:%%s,' % (row[2], row[3], start_time,
end_time, size, )
result = row[5]
error_code, message = nagios_eval(result, warning, critical,
nagios_message, 'MB', verbosity)
return error_code, message
def analyze_resusage(dbname, counter, row, warning, critical, verbosity):
"""Check resource usage with warning and critical ranges.
Does not use size
dbname - name of database
counter - entry in the COUNTERS list
row - perf data from SQL server as an output of the SQL query/DMV
warning - warning range argument to the command
critical - critical range argument to the command
verbosity - verbose argument to the command.
"""
query_time = str(row[0])
size = str(row[4])
nagios_message = 'Database:%s, Sku:%s - time:%s, Size:%s, Usage:%%s' \
% ( row[1], row[2], query_time, size,)
result = row[3]
error_code, message = nagios_eval(result, warning, critical,
nagios_message, '%', verbosity)
return error_code, message
def analyze_opstatus(dbname, counter, row, warning, critical, verbosity):
"""Analyze operation error_code - success, warning, or error -
comparing total woker time with warning and critical ranges
opstatus values are: 0 - success, 1 - warning and 2 - error
use warning <1 (e.g. 0.9) and critical < 2 (e.g. 1.9) to get Nagios status
dbname - name of database
counter - entry in the COUNTERS list
row - perf data from SQL server as an output of the SQL query/DMV
warning - warning range argument to the command
critical - critical range argument to the command
verbosity - verbose argument to the command.
"""
nagios_message = 'Resource desc:%s, Operation:%s, error_desc:%s, '\
'Severity:%s, error_code:%%s' % \
( row[0], row[1], row[3], row[4], )
result = row[2]
error_code, message = nagios_eval(result, warning, critical,
nagios_message, '', verbosity)
return error_code, message
def analyze_conection(dbname, counter, row, warning, critical, verbosity):
"""Analyze connection failures by comparing total woker
time with warning and critical ranges
dbname - name of database
counter - entry in the COUNTERS list
row - perf data from SQL server as an output of the SQL query/DMV
warning - warning range argument to the command
critical - critical range argument to the command
verbosity - verbose argument to the command.
"""
start_time = str(row[1])
end_time = str(row[2])
success = str(row[3])
conn_failure = str(row[5])
term_conn = str(row[6])
throttled_conn = str(row[7])
nagios_message = 'Database:%s, - start_time:%s, end_time:%s, '\
'Success Count:%s, Conn Failure Count:%s, '\
'Terminated Conn: %s, Throttled conn:%s, '\
'Total Failure Count:%%s, ' % (row[0], start_time,
end_time, success,
conn_failure, term_conn,
throttled_conn,)
result = row[4]
error_code, message = nagios_eval(result, warning, critical,
nagios_message, '', verbosity)
return error_code, message
def analyze_eventlog(dbname, counter, row, warning, critical, verbosity):
"""Analyze SQL event log by comparing severity of the log message
with warning and critical ranges
dbname - name of database
counter - entry in the COUNTERS list
row - perf data from SQL server as an output of the SQL query/DMV
warning - warning range argument to the command
critical - critical range argument to the command
verbosity - verbose argument to the command.
"""
database = row[0]
start_time = str(row[1])
count = str(row[8])
nagios_message = 'Database:%s, - start_time:%s, Sub-type descr:%s, '\
'Event count: %s, description:%s, Severity:%%s' % \
(database, start_time, row[6], count, row[9], )
result = row[7]
error_code, message = nagios_eval(result, warning, critical,
nagios_message, '', verbosity)
return error_code, message
SQL_QUERIES = {
'dbsize' : { 'help' : 'Database size',
'query' : DBSIZE_DMV,
'size' : 'single',
'printfn' : analyze_dbsize,
},
'objsize' : { 'help' : 'Database Object Size ',
'query' : OBJSIZE_DMV,
'size' : 'multiple',
'printfn' : analyze_objsize,
},
'connections' : { 'help' : 'Database Connections',
'query' : DBCONNECTIONS_DMV,
'size' : 'multiple',
'printfn' : analyze_conn_info,
},
'top5queries' : { 'help' : 'Top5 Queries',
'query' : TOP5QUERIES_DMV,
'size' : 'multiple',
'printfn' : analyze_top5_queries,
},
'queryplan' : { 'help' : 'Monitor Query Plan',
'query' : QUERYPLAN_DMV,
'size' : 'multiple',
'printfn' : analyze_queryplan,
},
'bwusage' : { 'help' : 'Bandwidth Usage (Cumulative)',
'query' : BWUSAGE_VIEW,
'frequency' : 'hourly',
'size' : 'multiple',
'printfn' : analyze_bwusage,
'db' : 'master',
},
'dbusage' : { 'help' : 'Databse usage (Daily)',
'query' : DBUSAGE_VIEW,
'size' : 'multiple',
'printfn' : analyze_dbusage,
'db' : 'master',
'frequency' : 'daily'
},
'resstat' : { 'help' : 'Databse Resource Status (Daily)',
'query' : RESSTAT_VIEW,
'size' : 'multiple',
'printfn' : analyze_resstat,
'db' : 'master',
'frequency' : 'hourly'
},
'resusage' : { 'help' : 'Databse Resource usage (Daily)',
'query' : RESUSAGE_VIEW,
'size' : 'multiple',
'printfn' : analyze_resusage,
'db' : 'master',
'frequency' : 'daily'
},
'opstatus' : { 'help' : 'Databse Op Status (Daily)',
'query' : OPSTATUS_VIEW,
'size' : 'multiple',
'printfn' : analyze_opstatus,
'db' : 'master',
},
'dbconnection' : { 'help' : 'Databse connection stat (Daily)',
'query' : DBCONNECTION_VIEW,
'size' : 'multiple',
'printfn' : analyze_conection,
'db' : 'master',
'frequency' : '5min'
},
'eventlog' : { 'help' : 'Event_log',
'query' : EVENTLOG_VIEW,
'size' : 'multiple',
'printfn' : analyze_eventlog,
'db' : 'master',
'frequency' : 'hourly'
},
}
def handle_args():
"""Create the parser, parse the args, and return them."""
parser = argparse.ArgumentParser(description='Check SQL Azure',
epilog='(c) MS Open Tech')
parser.add_argument('hostname', help='Azure SQL Server Address to check')
parser.add_argument(
'-u', '--username',
required=True,
help='Specify MSSQL User Name',
dest='user')
parser.add_argument(
'-p', '--password',
required=False,
help='Specify MSSQL Password',
dest='password')
parser.add_argument(
'-d', '--database',
required=True,
help='Specify Azure DB',
dest='database')
parser.add_argument('-w', '--warning', required=False, dest='warning',
help='Specify warning range')
parser.add_argument('-c', '--critical', required=False, dest='critical',
help='Specify critical range')
parser.add_argument('-k', '--key', required=True, dest='key',
help='Specify key for the DMV or SQL view')
parser.add_argument('-v', '--verbose', action='count',
default=0, help='verbosity')
parser.add_argument('--version', action='version', version='%(prog)s 0.1')
return parser.parse_args()
def setup_logger(verbose):
"""Creates a logger, using the verbosity, and returns it."""
global logger
logger = logging.getLogger()
if verbose >= 3:
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.WARNING)
logger.addHandler(logging.StreamHandler())
def connect_db(options, db):
"""Connects to SQL azure database, using command line options."""
host = options.hostname
start = datetime.now()
if os.name != 'nt':
mssql = pyodbc.connect(
driver='FreeTDS',
TDS_Version = '8.0', # Use for
server = host,
port = 1433,
database = db,
uid = options.user,
pwd = options.password)
else:
try:
connstr = 'Driver={SQL Server Native Client 10.0};Server=tcp:'+\
host+',1433;Database='+db+';Uid='+options.user+';Pwd='+\
options.password+';Encrypt=yes;Connection Timeout=30;'
mssql = pyodbc.connect(connstr)
except:
return None, 0
total = datetime.now() - start
return mssql, total
def execute_query(mssql, dbname, sq_query, warning = None, critical = None,
verbosity = 0):
"""execute SQL query and by comparing severity of the log message with
warning and critical ranges
mssql - mssql object
dbname - name of database
sq_query - entry in the COUNTERS list output of the SQL query/DMV
warning - warning range argument to the command
critical - critical range argument to the command
verbosity - verbose argument to the command.
"""
total_error_code = 0
errors = []
query = sq_query['query']
if 'frequency' in sq_query:
if sq_query['frequency'] == 'hourly':
latest_utctime = datetime.utcnow()
hourly_query_clause = (latest_utctime -
timedelta(hours = 1, minutes = 30)).\
strftime('\'%Y%m%d %H:00:00\'')
query = query % hourly_query_clause
elif sq_query['frequency'] == 'daily':
latest_utctime = datetime.utcnow()
daily_query_clause = (latest_utctime -
timedelta(days = 1, hours = 12)).\
strftime('\'%Y%m%d %H:00:00\'')
query = query % daily_query_clause
elif sq_query['frequency'] == '5min':
latest_utctime = datetime.utcnow()
daily_query_clause = (latest_utctime -
timedelta(minutes = 8)).\
strftime('\'%Y%m%d %H:%M:00\'')
query = query % daily_query_clause
cur = mssql.cursor()
cur.execute(query)
if sq_query['size'] == 'single':
row = cur.fetchone()
total_error_code, error = sq_query['printfn'] \
(dbname, sq_query, row, warning, critical, verbosity)
errors.append(error)
else:
rows = cur.fetchall()
for row in rows:
error_code, error = sq_query['printfn']\
(dbname, sq_query, row, warning, critical, verbosity)
total_error_code = max(total_error_code, error_code)
if error != '':
errors.append(error)
return total_error_code, ', '.join(errors)
def check_sqlazure_errors(mssql_db, mssql_master, dbname, sq_key,
warning = None, critical = None, verbosity = 0):
"""execute SQL query and by comparing severity of the log message
with warning and critical ranges
mssql_db - mssql object for the the azure db
mssql_master - mssql object for the the mssql master db
dbname - name of database
host - Azure AD
sql_key -- SQL key as input to the command
warning - warning range argument to the command
critical - critical range argument to the command
verbosity - verbose argument to the command.
"""
total_error_code = 0
errors = []
if sq_key not in SQL_QUERIES:
return 3, 'Key not found:{0}'.format(sq_key)
sql_query = SQL_QUERIES[sq_key]
try:
if 'db' in sql_query and sql_query['db'] == 'master':
error_code, error = execute_query(mssql_master, 'master',
sql_query, warning, critical,
verbosity)
else:
if mssql_db != None:
error_code, error = execute_query(mssql_db, dbname,
sql_query, warning, critical,
verbosity)
total_error_code = max (total_error_code, error_code)
errors.append(error)
except Exception, e:
total_error_code = 3
errors.append('%s failed with: %s' % (sq_key, e))
return total_error_code, ', '.join(errors)
def main():
"""Main procedure for Azure SQL monitor utility."""
args = handle_args()
global logger
setup_logger(args.verbose)
logger.debug('Connecting to d/b.')
mssql_db = None
mssql_master = None
try:
if args.database:
mssql_db, _ = connect_db(args, args.database)
mssql_master, _ = connect_db(args, 'master')
except exceptions.Exception, e:
print e
print 'Error connecting to database'
sys.exit(3)
if not mssql_db or not mssql_master:
print 'Error connecting to database'
sys.exit(3)
error = ''
error_code = 0
error_code, error = check_sqlazure_errors(mssql_db,
mssql_master,
args.database,
args.key,
args.warning,
args.critical,
args.verbose )
if error_code == 0:
if args.verbose <= 1:
error = 'OK'
print error
sys.exit(error_code)
if __name__ == '__main__':
main()