依照'rows_sent_avg' => 'ROUND(SUM(Rows_sent_sum)/SUM(ts_cnt),0)', 添加自定义字段,这样在慢查询统计界面左上角自定义列中可以看到自定义的列。
audit_sql.py 脚本内容
#!/usr/bin/python
# coding=utf-8
'''auto audit sql task
huoyuanshen
20170616
继续统计参数进行sql自动审核。
'''
import MySQLdb
db = MySQLdb.connect("192.168.1.148","root","123456","slow_query_log") #Anemometer所在数据库的配置。
#过滤参数配置
Query_time_max=0.1 #执行最慢的那个sql语句花费的时间
Query_time_pct_95=0.08 #执行时间位于95%分位的sql执行时间
Query_time_median=0.06 #执行时间位于中位数位置的sql执行时间
Lock_time_pct_95=0.01 #位于95%分位的sql锁定时间
def run():
cursor = db.cursor()
sql = '''UPDATE `global_query_review` aa,(
SELECT
a.`checksum`,
MAX(b.`Query_time_max`),
AVG(b.`Query_time_pct_95`),
AVG(b.`Query_time_median`),
AVG(b.`Lock_time_pct_95`),
MAX(b.`Rows_sent_max`),
AVG(b.`Rows_sent_pct_95`),
AVG(b.`Rows_examined_pct_95`),
MAX(b.`Rows_examined_max`),
AVG(b.`Bytes_median`)
FROM
`global_query_review` a,
global_query_review_history b
WHERE a.`checksum` = b.`checksum`
and a.audit_status = 'refuse'
GROUP BY a.`checksum`
HAVING
(
MAX(b.`Query_time_max`) < %s
OR AVG(b.`Query_time_pct_95`) < %s
OR AVG(b.`Query_time_median`) < %s
)
AND AVG(b.`Lock_time_pct_95`) < %s
AND (
MAX(b.`Rows_sent_max`) < 1000
OR AVG(b.`Rows_sent_pct_95`) < 100
)
AND (
AVG(b.`Rows_examined_pct_95`) < 500
OR MAX(b.`Rows_examined_max`) < 2000
)
AND AVG(b.`Bytes_median`) < 1000
) bb
SET aa.`audit_status` = 'pass'
WHERE aa.`checksum` = bb.checksum
''' % (Query_time_max,Query_time_pct_95,Query_time_median,Lock_time_pct_95)
#定义特殊的语句,建议除了DDL语句,其他DML语句在Anemometer前端统一维护。
sql2 = '''UPDATE
`global_query_review` a
SET
a.`audit_status` = 'pass'
WHERE a.`audit_status` = 'refuse'
AND (a.`sample` LIKE '%show create table%' OR a.`sample` LIKE '%/*!40001 SQL_NO_CACHE */%' OR a.sample LIKE 'explain%' );
'''
try:
cursor.execute(sql)
cursor.execute(sql2)
db.commit()
print 'Exec sucessful'
except:
db.rollback()
print 'Exec fail'
db.close()
if __name__=='__main__':
run()
audit_sql_day.py脚本内容
#!/usr/bin/python
#coding=utf-8
'''auto audit sql task
huoyuanshen
20170616
将执行次数计算在内的sql自动审核脚本
'''
import MySQLdb
#过滤参数配置
Query_time_max=1 #执行最慢的那个sql语句花费的时间
Lock_time_max=0.01 #最大sql锁定时间
db = MySQLdb.connect("192.168.1.148","root","123456","slow_query_log") #连接到Anemometer数据库的链接
def run():
cursor = db.cursor()
sql = '''UPDATE `global_query_review` aa,(
SELECT
a.`checksum`,
COUNT(b.`checksum`) AS coun ,
sum(b.`ts_cnt`) AS sum_ts_cnt
FROM
`global_query_review` a,
global_query_review_history b
WHERE a.`checksum` = b.`checksum`
AND a.audit_status = 'refuse'
GROUP BY a.`checksum`
HAVING MAX(b.`Query_time_max`) < %s
AND AVG(b.`Lock_time_max`) < %s
AND (MAX(b.`Rows_sent_max`) <= 1000)
AND MAX(b.`Rows_examined_max`) < 5000
AND AVG(b.`Bytes_median`) < 5000
AND coun < 5
AND sum_ts_cnt < 10
) bb
SET aa.`audit_status` = 'pass'
WHERE aa.`checksum` = bb.checksum
''' % (Query_time_max,Lock_time_max)
cursor.execute(sql)
try:
cursor.execute(sql)
db.commit()
print 'Exec sucessful'
except:
db.rollback()
print 'Exec fail'
db.close()
if __name__=='__main__':
run()