forked from Neeky/mysqltools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinspectMySQL.py
executable file
·733 lines (635 loc) · 24.2 KB
/
inspectMySQL.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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
#!/usr/bin/env python3
#-*- coding: UTF-8 -*-
"""
完成mysql巡检、巡检结果以html的形式输出
作者: 蒋乐兴
报bug: [email protected]
时间: 2017-05-25
"""
from jinja2 import Template
import mysql.connector as connector
import argparse
import json
import datetime
import logging
import psutil
def get_cpu_info():
"""
通过一个字典的等式返回cpu的各项指标
"""
cpu_info={}
data=psutil.cpu_times_percent(3)
cpu_info['user(%)']=data[0]
cpu_info['system(%)']=data[2]
cpu_info['idle(%)']=data[3]
cpu_info['iowait(%)']=data[4]
cpu_info['hardirq(%)']=data[5]
cpu_info['softirq(%)']=data[6]
cpu_info['cpu_cores']=psutil.cpu_count()
return cpu_info
def get_mem_info():
"""
通过一个字典的等式返回main memory的各项指标
"""
mem_info={}
data=psutil.virtual_memory()
mem_info['total(GB)']=data[0]/1024/1024/1024
mem_info['avariable(buffer+cache)GB']=data[1]/1024/1024/1024
mem_info['used percent(%)']=data[2]
#mem_info['used(GB)']=data[3]/1024/1024/1024
#mem_info['free(GB)']=data[4]/1024/1024/1024
return mem_info
def get_disk_info():
disk_info={}
# 返回已经挂载的文件系统信息 (device='/dev/sda3', mountpoint='/', fstype='ext4', opts='rw,errors=remount-ro')
partitions=psutil.disk_partitions()
# 过滤掉光盘
partitions=[(partition[1],partition[2],partition[0])for partition in partitions if partition[2]!='iso9660']
disk_info={}
for partition in partitions:
disk_info[partition[0]]={}
disk_info[partition[0]]['fstype']=partition[1]
disk_info[partition[0]]['device']=partition[2]
for mount_point in disk_info.keys():
data=psutil.disk_usage(mount_point)
disk_info[mount_point]['total(GB)']=data[0]/1024/1024/1024
disk_info[mount_point]['used_percent(%)']=data[3]
device=disk_info[mount_point]['device']
counter=psutil.disk_io_counters(perdisk=True)
#disk_info['read_count']=counter[0]
return disk_info
class MonitorItem(object):
"""
所有监控项的基类
"""
def __init__(self,user='inspectuser',password='123456',host='127.0.0.1',port=3306):
"""初始化属性与到数据库端的连接"""
self.user=user
self.password=password
self.host=host
self.port=port
self.cnx=None
self.cursor=None
try:
config={'user':self.user,'password':self.password,'host':self.host,'port':self.port}
self.cnx=connector.connect(**config)
self.cursor=self.cnx.cursor(prepared=True)
except connector.Error as err:
"""如果连接失败就赋空值"""
self.cnx=None
self.cursor=None
sys.stderr.write(err.msg+'\n')
def __str__(self):
attrs={}
attrs['user']=self.user
attrs['password']=self.password
attrs['host']=self.host
attrs['port']=self.port
return "instance of {0} {1}".format(self.__class__,attrs)
def __del__(self):
"""在python 进行垃圾回收时关闭连接"""
if self.cnx != None:
self.cnx.close()
def get_result(self):
"""返回监控项的状态,由子类实现相应的功能"""
pass
def print_result(self):
"""打印监控项的状态"""
print(self.get_result())
def action(self):
"""监控项达到阀值时可以触发的操作"""
print("末定义任何有意义的操作")
#以下类用于检测MySQL数据库的正常与否
class IsAlive(MonitorItem):
"""监控MySQL数据库是否正常运行、{正常:on line,宕机:off line}"""
def get_result(self):
if self.cnx != None:
return "on line"
else:
return "off line"
#以下类用于检测MySQL数据库的基本信息
class MysqlVariable(MonitorItem):
"""派生自MonitorItem类,用于所有variable 监控项的基类"""
variable_name=None
def get_result(self):
try:
if self.cursor != None:
stmt=r"""show global variables like '{0}';""".format(self.variable_name)
self.cursor.execute(stmt)
return self.cursor.fetchone()[1].decode('utf8')
except Exception as err:
sys.stderr.write(err.__str__()+'\n')
return -1
class MysqlPort(MonitorItem):
"""监控MySQL数据库监听是否正常、{正常:端口号,异常:-1}"""
def get_result(self):
if self.cnx != None:
return self.port
else:
return -1
class MysqlBasedir(MysqlVariable):
"""监控MySQL安装目录所在位置,{正常:安装目录位置,异常:-1}"""
variable_name="basedir"
class MysqlDatadir(MysqlVariable):
"""监控MySQL数据目录所在位置,{正常:数据目录位置,异常:-1}"""
variable_name="datadir"
class MysqlVersion(MysqlVariable):
"""监控MySQL版本号,{正常:版本号,异常:-1}"""
variable_name="version"
class MysqlServerId(MysqlVariable):
"""监控MySQL的server_id"""
variable_name="server_id"
class MysqlLogBin(MysqlVariable):
"""binlog 是否有开启"""
variable_name="log_bin"
class MysqlLogError(MysqlVariable):
"""errorlog文件名"""
variable_name="log_error"
class MysqlPerformanceSchema(MysqlVariable):
"""performance_schema是否有开启"""
variable_name="performance_schema"
class MysqlInnodbBufferPoolSize(MysqlVariable):
"""监控MySQL innodb_buffer_pool的大小,{正常:缓冲池大小(byte),异常:-1}"""
variable_name="innodb_buffer_pool_size"
class MysqlMaxConnections(MysqlVariable):
"""最大连接数"""
variable_name="max_connections"
#派生自MonitorItem类,用于所有status 监控项的基类
class MysqlStatu(MonitorItem):
"""派生自MonitorItem类,用于所有statu 监控项的基类"""
statu_name=None
def get_result(self):
try:
if self.cursor != None:
stmt=r"""show global status like '{0}';""".format(self.statu_name)
self.cursor.execute(stmt)
return self.cursor.fetchone()[1].decode('utf8')
except Exception as err:
sys.stderr.write(err.__str__()+'\n')
return -1
class MysqlCurrentClient(MysqlStatu):
"""当前的客户端连接数"""
statu_name="Threads_connected"
class MysqlTableOpenCacheHitRate(MysqlStatu):
"""表缓存命中率"""
def get_result(self):
try:
if self.cursor != None:
stmt=r"""show global status like 'table_open_cache_hits';"""
self.cursor.execute(stmt)
hit=float((self.cursor.fetchone()[1].decode('utf8')))
stmt=r"""show global status like 'table_open_cache_misses';"""
self.cursor.execute(stmt)
miss=float(self.cursor.fetchone()[1].decode('utf8'))
return hit/(hit+miss)
except Exception as err:
sys.stderr.write(err.__str__())
return -1
class MysqlTableOpenCacheOverflows(MysqlStatu):
"""表缓存溢出次数,如果大于0,可以增大table_open_cache和table_open_cache_instances."""
statu_name="Table_open_cache_overflows"
class MysqlTableLocksWaited(MysqlStatu):
"""因不能立刻获得表锁而等待的次数"""
statu_name="table_locks_waited"
class MysqlSlowqueries(MysqlStatu):
"""执行时间超过long_query_time的查询次数,不管慢查询日志有没有打开"""
statu_name="slow_queries"
class MysqlSortScan(MysqlStatu):
"""全表扫描之后又排序(排序键不是主键)的次数"""
statu_name="sort_scan"
class MysqlSortRows(MysqlStatu):
"""与sortscan差不多,前者指的是sortscan的次数,srotrows指的是sort操作影响的行数"""
statu_name="sort_rows"
class MysqlSortRange(MysqlStatu):
"""根据索引进行范围扫描之后再进行排序(排序键不能是主键)的次数"""
statu_name="sort_range"
class MysqlSortMergePasses(MysqlStatu):
"""排序时归并的次数,如果这个值比较大(要求高一点大于0)那么可以考虑增大sort_buffer_size的大小"""
statu_name="sort_merge_passes"
class MysqlSelectRangeCheck(MysqlStatu):
"""如果这个值不是0那么就要好好的检查表上的索引了"""
statu_name="select_range_check"
class MysqlQuestions(MysqlStatu):
"""erver端执行的语句数量,但是每执行一个语句它又只增加一,这点让我特别被动"""
statu_name="Questions"
class MysqlQcacheFreeMemory(MysqlStatu):
"""query cache 的可用内存大小"""
statu_name="qcache_free_memory"
class MysqlPreparedStmtCount(MysqlStatu):
"""由于本监控程序就是通过prepare语句完成的,所以这个监控项的值最少会是1不是0"""
statu_name="prepared_stmt_count"
class MysqlOpenedTables(MysqlStatu):
"""mysql数据库打开过的表,如果这个值过大,应该适当的增大table_open_cache的值"""
statu_name="opened_tables"
class MysqlOpenTables(MysqlStatu):
"""当前mysql数据库打开的表数量"""
statu_name="open_tables"
class MysqlServerLevelOpenFiles(MysqlStatu):
"""mysql数据库的server层当前正打开的文件数据"""
statu_name="open_files"
class MysqlInnodbAvailableUndoLogs(MysqlStatu):
"""innodb当前可用的undo段的数据"""
statu_name="innodb_available_undo_logs"
class MysqlInnodbNumOpenFiles(MysqlStatu):
"""innodb当前打开的文件数量"""
statu_name="innodb_num_open_files"
class MysqlInnodbRowsUpdated(MysqlStatu):
"""innodb层面执行的update所影响的行数"""
statu_name="innodb_rows_updated"
class MysqlInnodbRowsRead(MysqlStatu):
"""innodb 层面受读操作所影响的行数"""
statu_name="innodb_rows_read"
class MysqlInnodbRowsInserted(MysqlStatu):
"""innodb 层面受insert操作所影响的行数"""
statu_name="innodb_rows_inserted"
class MysqlInnodbRowsDeleted(MysqlStatu):
"""innodb 层面受delete操作所影响的行数"""
statu_name="innodb_rows_deleted"
class MysqlInnodbRowLockWaits(MysqlStatu):
"""innodb 行锁等待的次数"""
statu_name="innodb_row_lock_waits"
class MysqlInnodbRowLockTimeMax(MysqlStatu):
"""innodb层面行锁等待的最大毫秒数"""
statu_name="innodb_row_lock_time_max"
class MysqlInnodbRowLockTimeAvg(MysqlStatu):
"""innodb层面行锁等待的平均毫秒数"""
statu_name="Innodb_row_lock_time_avg"
class MysqlInnodbRowLockTime(MysqlStatu):
"""innodb层面行锁等待的总毫秒数"""
statu_name="Innodb_row_lock_time"
class MysqlInnodbPagesWritten(MysqlStatu):
"""innodb层面写入磁盘的页面数"""
statu_name="Innodb_pages_written"
class MysqlInnodbPagesRead(MysqlStatu):
"""从innodb buffer pool 中读取的页数"""
statu_name="Innodb_pages_read"
class MysqlInnodbOsLogWritten(MysqlStatu):
"""innodb redo 写入字节数"""
statu_name="Innodb_os_log_written"
class MysqlInnodbOsLogPendingWrites(MysqlStatu):
"""innodb redo log 被挂起的写操作次数"""
statu_name="Innodb_os_log_pending_writes"
class MysqlInnodbOsLogPendingFsyncs(MysqlStatu):
"""innodb redo log 被挂起的fsync操作次数"""
statu_name="Innodb_os_log_pending_fsyncs"
class MysqlInnodbOsLogFsyncs(MysqlStatu):
"""innodb redo log fsync的次数"""
statu_name="Innodb_os_log_fsyncs"
class MysqlInnodbLogWrites(MysqlStatu):
"""innodb redo log 物理写的次数"""
statu_name="innodb_log_writes"
class MysqlInnodbLogWriteRequests(MysqlStatu):
"""innodb redo log 逻辑写的次数"""
statu_name="Innodb_log_write_requests"
class MysqlInnodbLogWaits(MysqlStatu):
"""innodb 写redo 之前必须等待的次数"""
statu_name="Innodb_log_waits"
class MysqlInnodbDblwrWrites(MysqlStatu):
"""innodb double write 的次数"""
statu_name="Innodb_dblwr_writes"
class MysqlInnodbDblwrPagesWritten(MysqlStatu):
"""innodb double write 的页面数量"""
statu_name="Innodb_dblwr_pages_written"
class MysqlInnodbDoubleWriteLoader(MysqlStatu):
"""innodb double write 压力1~64、数值越大压力越大"""
def get_result(self):
try:
if self.cursor != None:
stmt=r"""show global status like 'innodb_dblwr_pages_written';"""
self.cursor.execute(stmt)
pages=float((self.cursor.fetchone()[1].decode('utf8')))
stmt=r"""show global status like 'innodb_dblwr_writes';"""
self.cursor.execute(stmt)
requests=float(self.cursor.fetchone()[1].decode('utf8'))
if requests == 0:
return 0
return pages/requests
except Exception as err:
sys.stderr.write(err.__str__())
return -1
class MysqlInnodbBufferPoolHitRate(MysqlStatu):
"""innodb buffer pool 命中率"""
def get_result(self):
try:
if self.cursor != None:
stmt=r"""show global status like 'innodb_buffer_pool_read_requests';"""
self.cursor.execute(stmt)
hit_read=float((self.cursor.fetchone()[1].decode('utf8')))
stmt=r"""show global status like 'innodb_buffer_pool_reads';"""
self.cursor.execute(stmt)
miss_read=float(self.cursor.fetchone()[1].decode('utf8'))
total_read=(miss_read+hit_read)
if total_read == 0:
return 0
return hit_read/total_read
except Exception as err:
sys.stderr.write(err.__str__())
return -1
class MysqlInnodbBufferPoolFreePagePercent(MysqlStatu):
"""innodb buffer pool free page 百分比"""
def get_result(self):
try:
if self.cursor != None:
stmt=r"""show global status like 'innodb_buffer_pool_pages_total';"""
self.cursor.execute(stmt)
total_page=float((self.cursor.fetchone()[1].decode('utf8')))
stmt=r"""show global status like 'innodb_buffer_pool_pages_free';"""
self.cursor.execute(stmt)
free_page=float(self.cursor.fetchone()[1].decode('utf8'))
return free_page/total_page
except Exception as err:
sys.stderr.write(err.__str__())
return -1
class MysqlInnodbBufferPoolDirtyPercent(MysqlStatu):
"""innodb buffer pool dirty page 百分比"""
def get_result(self):
try:
if self.cursor != None:
stmt=r"""show global status like 'innodb_buffer_pool_pages_total';"""
self.cursor.execute(stmt)
total_page=float((self.cursor.fetchone()[1].decode('utf8')))
stmt=r"""show global status like 'innodb_buffer_pool_pages_dirty';"""
self.cursor.execute(stmt)
dirty_page=float(self.cursor.fetchone()[1].decode('utf8'))
return dirty_page/total_page
except Exception as err:
sys.stderr.write(err.__str__())
return -1
class MysqlCreated_tmp_disk_tables(MysqlStatu):
"""mysql运行时所创建的磁盘临时表的数量,如果这个数值比较大,可以适当的增大 tmp_table_size | max_heap_table_size"""
statu_name="Created_tmp_disk_tables"
class MysqlComSelect(MysqlStatu):
"""select 语句执行的次数"""
statu_name="com_select"
class MysqlComInsert(MysqlStatu):
"""insert 语句执行的次数"""
statu_name="com_insert"
class MysqlComDelete(MysqlStatu):
"""delete 语句执行的次数"""
statu_name="com_delete"
class MysqlComUpdate(MysqlStatu):
"""update 语句执行的次数"""
statu_name="com_update"
class MysqlBinlogCacheDiskUse(MysqlStatu):
"""事务引擎因binlog缓存不足而用到临时文件的次数,如果这个值过大,可以通过增大binlog_cache_size来解决"""
statu_name="Binlog_cache_disk_use"
class MysqlBinlogStmtCacheDiskUse(MysqlStatu):
"""非事务引擎因binlog缓存不足而用到临时文件的次数,如果这个值过大,可以通过增大binlog_stmt_cache_size来解决"""
statu_name="Binlog_stmt_cache_disk_use"
class MysqlReplication(MonitorItem):
"""所有监控mysql replication的基类"""
def __init__(self,user='monitoruser',password='123456',host='127.0.0.1',port=3306):
MonitorItem.__init__(self,user,password,host,port)
try:
if self.cursor != None:
stmt="show slave status;"
self.cursor.execute(stmt)
self.replication_info=self.cursor.fetchone()
except Exception as err:
pass
class MysqlReplicationIsRunning(MysqlReplication):
"""mysql replication 是否正常运行"""
def get_result(self):
if self.replication_info == None:
return "replication is not running"
else:
slave_io_running=self.replication_info[10].decode('utf8')
slave_sql_running=self.replication_info[11].decode('utf8')
if slave_io_running == 'Yes' and slave_sql_running == 'Yes':
return "running"
return "replication is not running"
class MysqlReplicationBehindMaster(MysqlReplication):
"""监控seconde behind master """
def get_result(self):
if self.replication_info != None:
return self.replication_info[32]
else:
return -1
mysql_total_items={
#实例配置信息收集项
'port' :MysqlPort,
'baseDir' :MysqlBasedir,
'dataDir' :MysqlDatadir,
'version' :MysqlVersion,
'serverId' :MysqlServerId,
'isBinlogEnable' :MysqlLogBin,
'isErrorlogEnable' :MysqlLogError,
'isPerformanceScheamEnable' :MysqlPerformanceSchema,
'innodbBufferPoolSize' :MysqlInnodbBufferPoolSize,
'maxConnections' :MysqlMaxConnections,
#实例运行时信息收集项
'isOnline' :IsAlive,
'currentConnections' :MysqlCurrentClient,
'tableCacheHitRate' :MysqlTableOpenCacheHitRate,
'tableOpenCacheOverflows' :MysqlTableOpenCacheOverflows,
'tableLocksWaited' :MysqlTableLocksWaited,
'slowqueries' :MysqlSlowqueries,
'sortScan' :MysqlSortScan,
'sortRows' :MysqlSortRows,
'sortRange' :MysqlSortRange,
'sortMergePasses' :MysqlSortMergePasses,
'selectRangeCheck' :MysqlSelectRangeCheck,
'questions' :MysqlQuestions,
'qcacheFreeMemory' :MysqlQcacheFreeMemory,
'preparedStmtCount' :MysqlPreparedStmtCount,
'openedTables' :MysqlOpenedTables,
'openTables' :MysqlOpenTables,
'serverLevelOpenFiles' :MysqlServerLevelOpenFiles,
'created_tmp_disk_tables' :MysqlCreated_tmp_disk_tables,
'comSelect' :MysqlComSelect,
'comInsert' :MysqlComInsert,
'comDelete' :MysqlComDelete,
'comUpdate' :MysqlComUpdate,
'binlogCacheDiskUse' :MysqlBinlogCacheDiskUse,
'binlogStmtCacheDiskUse' :MysqlBinlogStmtCacheDiskUse,
#innodb运行时信息收集项
'innodbAvailableUndoLogs' :MysqlInnodbAvailableUndoLogs,
'innodbOpenFiles' :MysqlInnodbNumOpenFiles,
'innodbRowsUpdated' :MysqlInnodbRowsUpdated,
'innodbRowsRead' :MysqlInnodbRowsRead,
'innodbRowsInserted' :MysqlInnodbRowsInserted,
'innodbRowsDeleted' :MysqlInnodbRowsDeleted,
'innodbRowLockWaits' :MysqlInnodbRowLockWaits,
'innodbRowLockTimeMax' :MysqlInnodbRowLockTimeMax,
'innodbRowLockTimeAvg' :MysqlInnodbRowLockTimeAvg,
'innodbRowLockTime' :MysqlInnodbRowLockTime,
'innodbPagesWritten' :MysqlInnodbPagesWritten,
'innodbPagesRead' :MysqlInnodbPagesRead,
'innodbOsLogWritten' :MysqlInnodbOsLogWritten,
'innodbOsLogPendingWrites' :MysqlInnodbOsLogPendingWrites,
'innodbOsLogPendingFsyncs' :MysqlInnodbOsLogPendingFsyncs,
'innodbOsLogFsyncs' :MysqlInnodbOsLogFsyncs,
'innodbLogWrites' :MysqlInnodbLogWrites,
'innodbLogWriteRequests' :MysqlInnodbLogWriteRequests,
'innodbLogWaits' :MysqlInnodbLogWaits,
'innodbDblwrWrites' :MysqlInnodbDblwrWrites,
'innodbDblwrPagesWritten' :MysqlInnodbDblwrPagesWritten,
'innodbDoubleWriteLoader' :MysqlInnodbDoubleWriteLoader,
'innodbBufferPoolHitRate' :MysqlInnodbBufferPoolHitRate,
'innodbBufferPoolFreePagePercent' :MysqlInnodbBufferPoolFreePagePercent,
'innodbBufferPoolDirtyPercent' :MysqlInnodbBufferPoolDirtyPercent,
#对mysql replication 的监控
'replicationIsRunning' :MysqlReplicationIsRunning,
'replicationBehindMaster' :MysqlReplicationBehindMaster,
}
htmlstr="""<!DOCTYPE html>
<html>
<head>
<title>{{ hostNameAlias}} mysql 巡检报告</title>
<meta charset='utf8' />
<style>
*{
margin: 0;
padding: 0;
}
.content{
width:1000px;
height: auto;
margin: 30px auto;
border-bottom:1px solid #b2b2b2;
}
.list-item{
border:1px solid #b2b2b2;
border-bottom: none;
transition: all .35s;
overflow: hidden;
display: flex;
}
.list-item:empty{
display: none;
}
.top-title{
line-height: 32px;
font-size: 16px;
color: #333;
text-indent: 10px;
font-weight: 600;
}
.category{
width:97px;
height: auto;
border-right: 1px solid #b2b2b2;
float: left;
text-align: center;
position: relative;
}
.stage-title>span,
.category>span{
display: block;
height: 20px;
width:100%;
text-align: center;
line-height: 20px;
position: absolute;
top: 50%;
margin-top: -10px;left: 0;
}
.second-stage{
width:900px;
float: left;
}
.stage-list{
border-bottom: 1px solid #b2b2b2;
display: flex;
}
.stage-list:last-child{
border-bottom: 0;
}
.stage-title{
width:99px;
border-right: 1px solid #b2b2b2;
position: relative;
}
.detail{
flex: 1;
}
.detail-list{
border-bottom: 1px solid #b2b2b2;
height: 40px;
display: flex;
transition: all .35s;
}
.detail-title{
padding: 10px;
height: 20px;
line-height: 20px;
border-right: 1px solid #b2b2b2;
width:200px;
}
.detail-describe{
flex: 1;
padding: 10px;line-height: 20px;
}
.detail-list:last-child{
border-bottom: 0;
}
.list-item:hover{
background-color: #eee;
}
.detail-list:hover{
background-color: #d1d1d1;
}
</style>
</head>
<body>
<!-- -->
<div class="content">
<div class="list-item">
<p class="top-title">{{ hostNameAlias }} 主机性能分析报告</p>
</div>
{% for resource in resources %}
<div class="list-item">
<div class="category">
<span>{{ resource['name'] }}</span>
</div>
<div class="second-stage">
{% for item in resource['items'] %}
<div class="stage-list">
<div class="stage-title"><span>{{ item['name'] }}</span></div>
<div class="detail">
{% for k,v in item['kvs'].items() %}
<p class="detail-list">
<span class="detail-title">{{ k }}</span>
<span class="detail-describe">{{ v }}</span>
</p>
{% endfor %}
<p class="detail-list">
</p>
</div>
</div>
{% endfor %}
</div>
</div>
{% endfor %}
</div>
</body>
</html>
"""
mysql_inspect_items=['replicationIsRunning','replicationBehindMaster','innodbBufferPoolDirtyPercent'
'innodbBufferPoolHitRate','innodbLogWaits','innodbRowLockTimeAvg',
'innodbOpenFiles','currentConnections','tableCacheHitRate','tableOpenCacheOverflows',
'tableLocksWaited','slowqueries','serverLevelOpenFiles','created_tmp_disk_tables',
'comSelect','comInsert','comDelete','comUpdate','binlogCacheDiskUse']
if __name__=="__main__":
parser=argparse.ArgumentParser()
parser.add_argument('--user',default='inspectuser',help='user name for connect to mysql')
parser.add_argument('--password',default='123456',help='user password for connect to mysql')
parser.add_argument('--host',default='127.0.0.1',help='mysql host ip')
parser.add_argument('--port',default=3306,type=int,help='mysql port')
parser.add_argument('--instanceName',default='127.0.0.1',help='instance name')
parser.add_argument('--version',default='1.0.0',help='1.0.0')
args=parser.parse_args()
cpu_kvs=get_cpu_info()
mem_kvs=get_mem_info()
disks=get_disk_info()
disk_items=[ {'name':k,'kvs':v } for k,v in disks.items() ]
cpu={'name':'cpu','items':[{'name':'cpus','kvs':cpu_kvs}]}
mem={'name':'mem','items':[{'name':'mem','kvs':mem_kvs}]}
disk={'name':'disk','items':disk_items}
mysql_kvs={ k:v(host=args.host,port=args.port,user=args.user,password=args.password).get_result()
for k,v in mysql_total_items.items() if k in mysql_inspect_items }
mysql={'name':'mysql','items':[{'name':args.port,'kvs':mysql_kvs}]}
resources=[cpu,mem,disk,mysql]
report=Template(htmlstr)
report=report.render(hostNameAlias=args.instanceName,resources=resources)
print(report)