My script has been running continuously for about a week. Received this error and the script aborted:
Traceback (most recent call last):
File "/opt/dba/home/swechsler/library/mysql/bin/./kill_duplicate_processes", line 208, in <module>
main()
File "/opt/dba/home/swechsler/library/mysql/bin/./kill_duplicate_processes", line 194, in main
cnx.commit()
File "/usr/local/lib/python3.9/site-packages/mysql/connector/connection_cext.py", line 487, in commit
self._cmysql.commit()
_mysql_connector.MySQLInterfaceError: Lost connection to MySQL server during query
I'm trying to figure out why the script aborted when it was inside a try block. Here's the relevant code:
try:
cursor = cnx.cursor()
cursor.execute(f"SET SESSION MAX_EXECUTION_TIME={query_timeout}")
query = (f"SELECT * FROM information_schema.processlist WHERE command in('Query','Execute') AND STATE IS NOT NULL AND info LIKE 'SELECT%' AND TIME > {kill_time} and user not in('debezium','system user','snaplogic')")
# print(f"running {query} on {server}")
cursor.execute(query)
processes = cursor.fetchall()
cursor.close()
# Group processes by INFO column
grouped_processes = {}
for process in processes:
pid = process[0]
info = process[7]
if info not in grouped_processes:
grouped_processes[info] = []
grouped_processes[info].append(pid)
# Kill all but the most recent process for each group
oldinfo = ''
for info, pids in grouped_processes.items():
process_killed = False;
pids.sort(reverse=True)
num_processes = len(pids)
for pid in pids[1:]:
kill_query = f"CALL mysql.rds_kill({pid})"
cursor = cnx.cursor()
cursor.execute(kill_query)
cursor.close()
print(f"[{get_current_datetime()}]: Killed long running process on {server}: {pid}, info: {info}")
process_killed = True;
if process_killed:
message = f"Killed {num_processes - 1} duplicate long running processes on {server} {' '.join(map(str, pids[1:]))}: ```{info}```" if num_processes > 2 else f"killed duplicate long running process on {server} {pids[1:]}: ```{info\
}```"
send_msg(message, args.slack)
cnx.commit()
except mysql.connector.Error as err:
if err.errno == mysql.connector.errorcode.CR_COMMANDS_OUT_OF_SYNC:
# MySQL Connector/Python may raise this exception when a query times out
print(f"[{current_time}]: Query on {server} timed out. Disconnecting...")
else:
print(f"[{get_current_datetime()}]: Error communicating with {server}: {err}")
cnx.close()
connections[server] = None