Python监控MySQL当前跑的TOP SESSION

利用ps命令抓出MySQL PID,根据PID再监控每个线程CPU使用率以及跑的SQL语句

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
import pymysql
import os
import time
os.environ['NLS_LANG']='SIMPLIFIED CHINESE_CHINA.UTF8'
command="ps -ef | grep mysql|grep 13306 | grep -v grep | awk '{print $2}'"
with os.popen(command, "r") as pid:
pid = str(int(pid.read()))
command='top -bi H -p '+ pid +" -n 1 | grep mysql | awk '"+'{print '+'$1","$9}'+"'"
con=pymysql.connect("127.0.0.1","scott","tiger","db")
cur=con.cursor()
cur.arraysize = 100
sql = "SELECT concat('''',b.USER,'''', '@', '''',b.HOST ,'''',' 在数据库',b.db,' 执行 ',info) info " \
"FROM performance_schema.threads a,information_schema.PROCESSLIST b WHERE b.id = a.processlist_id AND a.thread_os_id ="
while True:
date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
with os.popen(command, "r") as p:
process = p.read()
if process=='':
print(str(date)+' System is idle')
elif process!='':
line=process.splitlines()
for rows in line:
row=rows.split(",")
cur.execute(sql+row[0])
for x in cur:
info = str(x[0])
print(str(date) + ' ' + info + ' 耗费了'+ row[1] + '% 的CPU')
time.sleep(3)
cur.close()
con.close()

代码运行示例:

1
2
3
4
5
6
7
8

[root@server ~]# python3 monitor.py
2020-05-18 17:15:24 System is idle
2020-05-18 17:15:27 System is idle
2020-05-18 17:15:30 'scott'@'127.0.0.1:59989' 在数据库db 执行 select count(*) from t t1 , t t2 where t1.owner=t2.owner 耗费了99.9% 的CPU
2020-05-18 17:15:34 'scott'@'127.0.0.1:59989' 在数据库db 执行 select count(*) from t t1 , t t2 where t1.owner=t2.owner 耗费了93.8% 的CPU
2020-05-18 17:15:37 'scott'@'127.0.0.1:59989' 在数据库db 执行 select count(*) from t t1 , t t2 where t1.owner=t2.owner 耗费了99.9% 的CPU