-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdb2_metrics.py
429 lines (387 loc) · 15.2 KB
/
db2_metrics.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
import argparse
import ibm_db
import sys
import time
import datetime
import calendar
import os
# print debug messages
debug = False
# metric name prefix
metric = "db2"
def log(log_type, log_msg, host, db):
if debug == True:
print("[debug/{0}] {1}".format(log_type, log_msg))
elif log_type == "error":
sys.stderr.write("{0}|{1}|{2}: {3}\n".format(log_type, host, db, log_msg))
def handle_error(error_message, host, db):
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
msg = "{0}|{1}|{2}".format(str(error_message), fname, exc_tb.tb_lineno)
log("error", msg, host, db)
sys.exit(1)
def read_last_clock_file(file):
"""Return the clock (Unixtime) from the specified file or current time if the file doesn't exist"""
last_clock = int(time.time())
if os.path.isfile(file):
try:
last_clock_file = open(file, 'r')
last_clock = int(last_clock_file.readline())
last_clock_file.close()
except IOError:
sys.stderr.write('Error: failed to read last clock file, ' +
file + '\n')
sys.exit(2)
return last_clock
def write_last_clock_file(file, clock):
"""Write the supplied clock (Unixtime) to file"""
try:
file = open(file, 'w')
file.write(str(clock))
file.close()
except IOError:
sys.stderr.write('Error writing last clock to file: ' +
file + '\n')
sys.exit(2)
class DB2Metrics:
def __init__(self, host, db, user, passwd, port=50000):
self.id = "db2-metrics-1"
self.db = db
self.host = host
self.port = port
if self.port == None:
self.port = 50000
self.user = user
self.passwd = passwd
self.connection = None
try:
conn_str = ('DATABASE=' + self.db + ';' +
'HOSTNAME=' + self.host + ';' +
'PORT=' + str(self.port) + ';' +
'PROTOCOL=TCPIP;' +
'UID=' + self.user + ';' +
'PWD=' + self.passwd + ';')
self.connection = ibm_db.connect(conn_str, '', '')
except Exception as e:
handle_error(e, self.host, self.db)
# function to return query result in rows
def query(self, sql):
try:
from ibm_db import fetch_assoc
ret = []
stmt = ibm_db.exec_immediate(self.connection, sql)
result = fetch_assoc(stmt)
while result:
ret.append(result)
result = fetch_assoc(stmt)
return ret
except Exception as e:
handle_error(e, self.host, self.db)
# generate and run query using config
def run_query(self, config):
cols = []
sql = ""
try:
if config['source_col'] != None:
cols.append(str(config['source_col']))
if config['timestamp'] != None:
cols.append(config['timestamp'])
if config['metrics'] != None:
for c in config['metrics']:
cols.append(c)
if config['tags_col'] != None:
for t in config['tags_col']:
cols.append(t)
if config['sql'] == None:
# columns
sql = sql + "SELECT "
for i, col in enumerate(cols):
if i > 0:
sql = sql + ", "
sql = sql + col
# table and schema
if 'schema' in config and config['schema'] != None:
sql = sql + \
" FROM {0}.{1}".format(
config['schema'], config['table'])
else:
sql = sql + " FROM {0}".format(config['table'])
# where condition (if exists)
if 'where' in config and config['where'] != None:
sql = sql + " WHERE " + config['where']
else:
sql = config['sql']
if debug == True:
print(config)
print("[sql]", sql)
rows = self.query(sql)
return rows
except Exception as e:
handle_error(e, self.host, self.db)
# run query defined in query config, and send it to the target with appropriate data format
def report(self, query_config):
wf_out = []
rows = self.run_query(query_config)
try:
# process the result using query config
for row in rows:
source = query_config['source']
if query_config['source_col'] != None:
source = row[query_config['source_col']]
# get current time first
epoch = calendar.timegm(time.gmtime())
# use timestamp, otherwise, use system timestamp
if "timestamp" in query_config and query_config['timestamp'] != None:
time_stamp = row[query_config['timestamp']]
epoch = int(
(time_stamp - datetime.datetime(1970, 1, 1)).total_seconds())
data_lines = self.to_influx_format(
row, epoch, source, query_config)
for data_line in data_lines:
wf_out.append(data_line)
if len(wf_out) > 0:
# send data to telegraf
for line in wf_out:
print(line)
log("result", "success [{0}] : {1} lines".format(
query_config['name'], len(wf_out)), self.host, self.db)
except Exception as e:
handle_error(e, self.host, self.db)
# internal method to convert data into influx db format
def to_influx_format(self, row, epoch, source, query_config):
data_lines = []
data_line = "{0}_{1},host={2}".format(
metric, query_config['name'].lower().replace("_", "."), source)
if query_config['tags'] != None:
for name, value in query_config['tags'].items():
data_line = data_line + \
",{0}={1}".format(name.lower(), value.replace(" ", "\\ "))
if query_config['tags_col'] != None:
for col in query_config['tags_col']:
val = row[col]
if val != None and val != "":
val = val.strip()
data_line = data_line + \
",{0}={1}".format(col.lower(), val.replace(" ", "\\ "))
data_line = data_line + " "
i = 0
for col in query_config['metrics']:
val = row[col]
if val != None:
if i > 0:
data_line = data_line + ","
if type(val) == str:
val = '"'+val.replace(" ", "\\ ").replace(",", "\\,")+':'
elif type(val) == datetime.datetime:
val = '"'+val.isoformat()+'"'
data_line = data_line + "{0}={1}".format(col.lower(), val)
i = i+1
if i == 0:
return data_lines # no fields available
data_line = "{0} {1}".format(data_line, epoch * 1000000000)
data_lines.append(data_line)
return data_lines
####################################
# query definitions
####################################
def get_db_instance(self):
# query definition
query_config = {
'name': "instance",
'description': None,
'metrics': ["TOTAL_CONNECTIONS", "GW_TOTAL_CONS"],
'tags_col': ["PRODUCT_NAME", "SERVER_PLATFORM"],
'tags': {"database": self.db},
'timestamp': None,
'source_col': None,
'source': self.host,
'schema': None,
'table': "TABLE(MON_GET_INSTANCE(-1))",
'where': None,
'sql': None
}
self.report(query_config)
def get_db_database(self):
# query definition
query_config = {
'name': "database",
'description': None,
'metrics': ["APPLS_CUR_CONS",
"APPLS_IN_DB2",
"CONNECTIONS_TOP",
"DEADLOCKS",
"LAST_BACKUP",
"LOCK_LIST_IN_USE",
"LOCK_TIMEOUTS",
"LOCK_WAIT_TIME",
"LOCK_WAITS",
"NUM_LOCKS_HELD",
"NUM_LOCKS_WAITING",
"ROWS_INSERTED",
"ROWS_UPDATED",
"ROWS_DELETED",
"ROWS_MODIFIED",
"ROWS_READ",
"ROWS_RETURNED",
"TOTAL_CONS"
],
'tags_col': ['DB_STATUS'],
'tags': {"database": self.db},
'timestamp': None,
'source_col': None,
'source': self.host,
'schema': None,
'table': "TABLE(MON_GET_DATABASE(-1))",
'where': None,
'sql': None
}
self.report(query_config)
def get_db_buffer_pool(self):
# query definition
query_config = {
'name': "buffer",
'description': None,
'metrics': ['POOL_ASYNC_COL_LBP_PAGES_FOUND',
'POOL_ASYNC_DATA_LBP_PAGES_FOUND',
'POOL_ASYNC_INDEX_LBP_PAGES_FOUND',
'POOL_ASYNC_XDA_LBP_PAGES_FOUND',
'POOL_COL_GBP_L_READS',
'POOL_COL_GBP_P_READS',
'POOL_COL_L_READS',
'POOL_COL_LBP_PAGES_FOUND',
'POOL_COL_P_READS',
'POOL_DATA_GBP_L_READS',
'POOL_DATA_GBP_P_READS',
'POOL_DATA_L_READS',
'POOL_DATA_LBP_PAGES_FOUND',
'POOL_DATA_P_READS',
'POOL_INDEX_GBP_L_READS',
'POOL_INDEX_GBP_P_READS',
'POOL_INDEX_L_READS',
'POOL_INDEX_LBP_PAGES_FOUND',
'POOL_INDEX_P_READS',
'POOL_TEMP_COL_L_READS',
'POOL_TEMP_COL_P_READS',
'POOL_TEMP_DATA_L_READS',
'POOL_TEMP_DATA_P_READS',
'POOL_TEMP_INDEX_L_READS',
'POOL_TEMP_INDEX_P_READS',
'POOL_TEMP_XDA_L_READS',
'POOL_TEMP_XDA_P_READS',
'POOL_XDA_GBP_L_READS',
'POOL_XDA_GBP_P_READS',
'POOL_XDA_L_READS',
'POOL_XDA_LBP_PAGES_FOUND',
'POOL_XDA_P_READS'
],
'tags_col': ['BP_NAME'],
'tags': {"database": self.db},
'timestamp': None,
'source_col': None,
'source': self.host,
'schema': None,
'table': "TABLE(MON_GET_BUFFERPOOL(NULL, -1))",
'where': None,
'sql': None
}
self.report(query_config)
def get_db_tablespace(self):
# query definition
query_config = {
'name': "tablespace",
'description': None,
'metrics': ['TBSP_PAGE_SIZE',
'TBSP_TOTAL_PAGES',
'TBSP_USABLE_PAGES',
'TBSP_USED_PAGES'
],
'tags_col': ['TBSP_NAME', 'TBSP_STATE'],
'tags': {"database": self.db},
'timestamp': None,
'source_col': None,
'source': self.host,
'schema': None,
'table': "TABLE(MON_GET_TABLESPACE(NULL, -1))",
'where': None,
'sql': None
}
self.report(query_config)
def get_db_transaction_log(self):
# query definition
query_config = {
'name': "txlog",
'description': None,
'metrics': ['LOG_READS',
'LOG_WRITES',
'TOTAL_LOG_AVAILABLE',
'TOTAL_LOG_USED'
],
'tags_col': None,
'tags': {"database": self.db},
'timestamp': None,
'source_col': None,
'source': self.host,
'schema': None,
'table': "TABLE(MON_GET_TRANSACTION_LOG(-1))",
'where': None,
'sql': None
}
self.report(query_config)
def get_db_table(self):
# query definition
query_config = {
'name': "table",
'description': None,
'metrics': ['TOTAL_ROWS_READ',
'TOTAL_ROWS_INSERTED',
'TOTAL_ROWS_UPDATED',
'TOTAL_ROWS_DELETED'
],
'tags_col': ['TABSCHEMA',
'TABNAME'
],
'tags': {"database": self.db},
'timestamp': None,
'source_col': None,
'source': self.host,
'schema': None,
'table': None,
'where': None,
'sql': "SELECT varchar(tabschema,20) as tabschema, varchar(tabname,20) as tabname, sum(rows_read) as total_rows_read, sum(rows_inserted) as total_rows_inserted, sum(rows_updated) as total_rows_updated, sum(rows_deleted) as total_rows_deleted FROM TABLE(MON_GET_TABLE('','',-2)) AS t GROUP BY tabschema, tabname ORDER BY total_rows_read DESC"
}
self.report(query_config)
if __name__ == "__main__":
args = None
try:
parser = argparse.ArgumentParser()
parser.add_argument(
'-s', '--host', help="database server hostname / IP ", required=True)
parser.add_argument(
'-p', '--port', help="database server port", required=False)
parser.add_argument('-d', '--db', help="database", required=True)
parser.add_argument('-U', '--user', help="user name", required=True)
parser.add_argument('-P', '--passwd', help="password", required=True)
parser.add_argument('-D', '--debug', help="Debug mode",
action="store_true", required=False, default=False)
args = parser.parse_args()
debug = args.debug
stats = None
try:
stats = DB2Metrics(args.host, args.db,
args.user, args.passwd, args.port)
last_clock = read_last_clock_file(stats.id + ".last_clock")
# other stats should follow here
stats.get_db_instance()
stats.get_db_database()
stats.get_db_buffer_pool()
stats.get_db_tablespace()
stats.get_db_transaction_log()
stats.get_db_table()
except Exception as e:
handle_error(e, args.server, args.db)
finally:
if stats != None and stats.connection != None:
ibm_db.close(stats.connection)
except Exception as e:
if args.server != None and args.db != None:
handle_error(e, args.server, args.db)