-
Notifications
You must be signed in to change notification settings - Fork 14
/
mysqlstatus.py
executable file
·512 lines (441 loc) · 14.7 KB
/
mysqlstatus.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (c) Shoma Suzuki
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.
MySQL Monitor is a console-based (non-gui) tool for monitoring MySQL server.
MySQL Monitor is inspired by innotop_ and mytop_ .
.. `innotop: http://code.google.com/p/innotop/
.. `mytop: http://jeremy.zawodny.com/mysql/mytop/
mysqlstaus.py shows status by *SHOW GLOBAL STATUS;* statement.
see MySQL :: MySQL 5.7 Reference Manual :: 12.7.5.37 SHOW STATUS Syntax
MySQLhttp://dev.mysql.com/doc/refman/5.7/en/show-status.html
"""
import argparse
import curses
import getpass
import logging
import os
import sys
import threading
import time
from datetime import datetime
import MySQLdb as Database
__title__ = 'mysqlstatus'
__version__ = '0.2.0-DEV'
__author__ = 'Shoma Suzuki'
__license__ = 'MIT'
__copyright__ = 'Copyright 2012 Shoma Suzuki'
def get_args_parser():
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("-h", "--host",
default="localhost",
nargs='?',
type=str,
help="Connect to host.")
parser.add_argument("-p", "--port",
default=3306,
nargs='?',
type=int,
help="Port number to use for connection.")
parser.add_argument("-u", "--user",
default=getpass.getuser(),
nargs='?',
type=str,
help="User for login if not current user.")
parser.add_argument("-P", "--password",
default='',
nargs='?',
type=str,
help="Password to use when connecting to server.")
parser.add_argument("-i", "--interval",
default=1,
nargs='?',
type=int,
help="Interval second of monitoring.")
parser.add_argument("-o", "--outfile",
default=sys.stdout,
nargs='?',
type=argparse.FileType('w'),
help="Output result file. avairable for non-interactive.")
parser.add_argument("-n", "--nonint",
default=False,
action='store_true',
help="Non-interactive.")
parser.add_argument("-m", "--mode",
default='status',
nargs='?',
choices=['status', 'process'],
help="monitoring Mode")
parser.add_argument("--debug",
default=False,
action='store_true',
help="Debug log enable.")
parser.add_argument("--help",
default=False,
action='store_true',
help="show this help message and exit.")
return parser
class QueryThread(threading.Thread):
_stop = False
_update = False
_mysql_variables = None
_mysql_status = None
_mysql_procesesslist = None
def __init__(self, **kwargs):
self.mysql_last_status = None
self._db = kwargs.get('db')
self._cursor = self._db.cursor(Database.cursors.DictCursor)
self._interval = kwargs.get('interval', 1)
self._mode = 'status'
self.lock = threading.Lock()
threading.Thread.__init__(self, name="QueryThread")
self.setDaemon(True)
@property
def mysql_variables(self):
"""SHOW VARIABLES"""
if self._mysql_variables is None:
result = self.query("SHOW VARIABLES")
self._mysql_variables = self.to_dict(result)
logging.debug(self._mysql_variables)
return self._mysql_variables
@property
def mysql_status(self):
return self._mysql_status
@property
def mode(self):
return self._mode
@property
def update(self):
return self._update
@update.setter
def update(self, value):
self._update = value
@mode.setter
def mode(self, value):
if value == 'process':
self._mode = 'process'
else:
self._mode = 'status'
@property
def stop(self):
return self._stop
@stop.setter
def stop(self, value):
self._stop = value
@property
def mysql_procesesslist(self):
return self._mysql_procesesslist
def run(self):
while self._stop == False:
if self._mode == 'process':
self.get_procesesslist()
else:
self.get_status()
time.sleep(self._interval)
self.cleanup_mysql()
def cleanup_mysql(self):
self._cursor.close()
self._db.close()
def query(self, sql):
result = ()
try:
self.lock.acquire()
self._cursor.execute(sql)
result = self._cursor.fetchall()
self.lock.release()
except Exception, err:
logging.exception(err)
return result
def get_status(self):
""" SHOW GLOBAL STATUS """
if self._mysql_status is not None:
self.mysql_last_status = self._mysql_status
result = self.query("SHOW GLOBAL STATUS")
self._mysql_status = self.to_dict(result)
logging.debug(self._mysql_status)
self.get_query_per_second()
self._update = True
return self._mysql_status
def get_procesesslist(self):
"""SHOW FULL PROCESSLIST"""
result = self.query("SHOW FULL PROCESSLIST")
self._mysql_procesesslist = result
self._update = True
logging.debug(result)
return self.mysql_procesesslist()
def get_query_per_second(self):
if self._mysql_status is None:
return 0.0
if self.mysql_last_status is not None:
[current, last] = map(lambda x: float(x),
(self._mysql_status.get('Uptime'),
self.mysql_last_status.get('Uptime')))
elapsed_time = last - current
[current, last] = map(lambda x: float(x),
(self._mysql_status.get('Questions', 0),
self.mysql_last_status.get('Questions', 0)))
inc_query = last - current
else:
[elapsed_time, inc_query] = map(lambda x: float(x),
(self._mysql_status.get('Uptime', 0),
self._mysql_status.get('Questions', 0)))
try:
qps = inc_query / elapsed_time
except:
qps = 0.0
self._mysql_status.update({'QPS': "%0.2f" % qps})
return qps
def to_dict(self, dictset):
return dict(
map(
lambda x: (x.get('Variable_name'), x.get('Value')),
dictset))
class MySQLStatus:
keywords = (
"QPS",
"Aborted_connects",
"Binlog_cache_disk_use",
"Bytes_received",
"Bytes_sent",
"Connections",
"Created_tmp_disk_tables",
"Created_tmp_files",
"Created_tmp_tables",
"Handler_delete",
"Handler_read_first",
"Handler_read_rnd",
"Handler_read_rnd_next",
"Handler_update",
"Handler_write",
"Key_read_requests",
"Key_reads",
"Max_used_connections",
"Open_files",
"Opened_table_definitions",
"Opened_tables",
"Opened_tables",
"Qcache_free_memory",
"Qcache_hits",
"Qcache_queries_in_cache",
"Questions",
"Select_full_join",
"Select_full_range_join",
"Select_range",
"Select_range_check",
"Select_scan",
"Slave_running",
"Slow_queries",
"Sort_merge_passes",
"Sort_scan",
"Table_locks_immediate",
"Table_locks_waited",
"Threads_connected",
"Threads_created",
"Threads_running",
"Uptime",
)
def __init__(self, options):
self.options = options
try:
db = Database.connect(
host=self.options.host,
user=self.options.user,
port=self.options.port,
passwd=self.options.password)
except Exception, err:
logging.exception(err)
print err
sys.exit()
self.qthread = QueryThread(
db=db,
interval=options.interval,
)
self.qthread.mode = options.mode
self.qthread.start()
class IntractiveMode(MySQLStatus):
def run(self):
logging.debug('starting IntractiveMode')
self.window = curses.initscr()
self.window.nodelay(1)
self.set_window_size()
curses.nl()
curses.noecho()
curses.cbreak()
try:
self.mainloop()
except (KeyboardInterrupt, SystemExit):
self.cleanup()
except Exception, err:
logging.exception(err)
self.cleanup()
print err
finally:
self.cleanup()
def mainloop(self):
self.show_header()
while True:
c = self.window.getch()
if c == ord('q'):
break
elif c == ord('p'):
self.qthread.mode = 'process'
elif c == ord('s'):
self.qthread.mode = 'status'
elif c == ord('h') or c == ord('?'):
self.show_help()
elif c == curses.KEY_RESIZE:
self.set_window_size()
if self.qthread.update == True:
self.show_update()
time.sleep(0.1)
def set_window_size(self):
(self.window_max_y, self.window_max_x) = self.window.getmaxyx()
def show_header(self):
variables = self.qthread.mysql_variables
data = {
'hostname': variables.get('hostname'),
'currenttime': datetime.now().strftime("%Y-%m-%d %H:%m:%S"),
'mysql_version': variables.get('version'),
}
data = "%(hostname)s, %(currenttime)s, %(mysql_version)s" % data
self.window.addstr(0, 0, data)
self.window.addstr(1, 0, "-" * 70)
def show_update(self):
self.qthread.update = False
self.window.erase()
self.show_header()
if self.qthread.mode == 'process':
self.show_update_process()
else:
self.show_update_status()
def show_update_status(self):
status = self.qthread.mysql_status
y = 2
for k in self.keywords:
data = "%-25s: %12s" % (k, status.get(k))
if y + 1 < self.window_max_y:
self.window.addstr(y, 0, data)
y = y + 1
if len(self.keywords) + 1 > self.window_max_y:
omits = len(self.keywords) + 1 - self.window_max_y
self.window.addstr(self.window_max_y - 1, 0,
"[%d items were truncated.]" % omits)
def show_update_process(self):
"""
Id, Host, db, User, Time, State, Type(Command), Query(Info)
"""
process = self.qthread.mysql_procesesslist
y = 3
header_format = '%7s, %8s, %8s,%7s,%6s,%6s,%12s,'
header_item = ('Id', 'Host', 'db', 'Time', 'State', 'Type', 'Query')
header = header_format % header_item
data_format = '%(Id)7s, %(Host)8s, %(db)8s,%(Time)7s,%(State)6s,%(Command)6s,%(Info)12s,'
self.window.addstr(2, 0, header)
for item in process:
data = data_format % item
# TODO truncate if variables to display is too long.
if y +1 < self.window_max_y:
self.window.addstr(y, 0, data)
y = y + 1
def cleanup(self):
self.window.erase()
curses.nocbreak()
self.window.keypad(0)
curses.echo()
curses.endwin()
self.qthread.stop = True
while self.qthread.isAlive():
# wait for stop QueryThread
pass
def show_help(self):
"""Help:
s : switch to status mode
p : switch to process mode
h : show this help message
? : alias of help
q : quit
[Press any key to continue]"""
self.window.erase()
self.window.addstr(1, 0, IntractiveMode.show_help.__doc__)
self.window.nodelay(0)
self.window.getch()
self.window.erase()
self.window.nodelay(1)
self.show_header()
class CliMode(MySQLStatus):
def run(self):
logging.debug('starting CliMode')
self.output = self.options.outfile
try:
self.mainloop()
except (KeyboardInterrupt, SystemExit), event:
logging.exception(event)
self.cleanup()
except Exception, err:
logging.exception(err)
self.cleanup()
print err
finally:
self.cleanup()
def mainloop(self):
while True:
if self.qthread.update == True:
self.output_action()
time.sleep(0.1)
def output_action(self):
self.qthread.update = False
if self.qthread.mode == 'process':
self.show_update_process()
else:
self.show_update_status()
self.output.write("\n")
def show_update_status(self):
status = self.qthread.mysql_status
self.output.write(str(status))
def show_update_process(self):
process = self.qthread.mysql_procesesslist
self.output.write(str(process))
def cleanup(self):
self.qthread.stop = True
while self.qthread.isAlive():
pass
if __name__ == '__main__':
parser = get_args_parser()
options = parser.parse_args()
if options.help:
parser.print_help()
parser.exit()
if options.debug:
if not os.path.isdir("logs"):
os.mkdir("logs")
logging.basicConfig(
format='%(asctime)s - (%(threadName)s) - %(message)s in %(funcName)s() at %(filename)s : %(lineno)s',
level=logging.DEBUG,
filename="logs/debug.log",
filemode='w',
)
logging.debug(options)
else:
logging.basicConfig(handler=logging.NullHandler)
if(options.nonint):
monitor = CliMode(options)
else:
monitor = IntractiveMode(options)
monitor.run()
# vim: fenc=utf8 et sw=4 ts=4