Skip to content

Instantly share code, notes, and snippets.

@juliosmelo
Created June 1, 2016 17:10
Show Gist options
  • Save juliosmelo/59c66e17d4839ba7100cea485fc4042d to your computer and use it in GitHub Desktop.
Save juliosmelo/59c66e17d4839ba7100cea485fc4042d to your computer and use it in GitHub Desktop.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import logging
import MySQLdb as mdb
from datetime import datetime
import sys
logging.basicConfig(
filename='killed_queries.log',
filemode='w',
level=logging.DEBUG
)
host = 'mysqlhost'
dbuser = 'dbuser'
dbpasswd = 'dbpass'
database = 'information_schema'
try:
con = mdb.connect(host, dbuser, dbpasswd, database)
cur = con.cursor(mdb.cursors.DictCursor)
query = 'SHOW FULL PROCESSLIST'
cur.execute(query)
rows = cur.fetchall()
for row in rows:
_id = row['Id']
_time = row['Time']
_command = row['Command']
if _time > 60 and (_command == "Sleep" or _command == "Query"):
try:
kill_stm = 'CALL mysql.rds_kill_query({0})'.format(
_id
)
cur.execute(kill_stm)
con.commit()
logging.info("{0} KILL: {1}".format(datetime.now(), kill_stm))
except Exception as e:
logging.error("%d: %s" % (e.args[0], e.args[1]))
pass
except mdb.Error as e:
logging.error("%d: %s" % (e.args[0], e.args[1]))
finally:
if con:
con.close()
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment