利用ps命令抓出MySQL PID,根據PID再監控每個線程CPU使用率以及跑的SQL語句
import pymysql
import os
import time
os.environ['NLS_LANG']='SIMPLIFIED CHINESE_CHINA.UTF8'
command="ps -ef | grep 3306 | 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("192.168.56.10","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()
代碼運行示例:
[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'@'192.168.56.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'@'192.168.56.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'@'192.168.56.1:59989' 在數據庫db 執行 select count(*) from t t1 , t t2 where t1.owner=t2.owner 耗費了99.9% 的CPU