Skip to content

Instantly share code, notes, and snippets.

@manuthu
Created April 1, 2025 20:10
Show Gist options
  • Save manuthu/2135741858a6dba35183b3ce8359a1ce to your computer and use it in GitHub Desktop.
Save manuthu/2135741858a6dba35183b3ce8359a1ce to your computer and use it in GitHub Desktop.
Kills all MySQL processes matching a specified filter
#!/bin/bash
# Configuration
# Use a regex
FILTER="search_lookup|breaking|episodes|subscriptions|DBeaver|users"
EXECUTION_TIME_THRESHOLD=15
MYSQL_CMD="mysql"
LOG_FILE="/var/log/mysql-prockill.log"
PROCESS_LIST_FILE="/tmp/proc-all-list.txt"
PROCESS_FILE="/tmp/proc-list.txt"
KILL_FILE="/tmp/kill-list.txt"
# Logging function
log() {
local timestamp
timestamp=$(date +"%Y-%m-%d %H:%M:%S")
echo "[$timestamp] [INFO] - $1" >> "$LOG_FILE"
}
# Retrieve and filter MySQL processes
log "Start MySQL processes termination."
log "Only match process with *$FILTER*"
$MYSQL_CMD -t -e "SHOW PROCESSLIST" > "$PROCESS_LIST_FILE"
egrep "$FILTER" "$PROCESS_LIST_FILE" > "$PROCESS_FILE"
# Generate KILL statements for processes with execution time > threshold
log "KILL processes with execution threshold greater than $EXECUTION_TIME_THRESHOLD seconds."
awk -F "|" -v threshold="$EXECUTION_TIME_THRESHOLD" '$7 > threshold { print "KILL " $2 ";" }' "$PROCESS_FILE" > "$KILL_FILE"
# Execute KILL statements
log "Executing KILL statements."
$MYSQL_CMD < "$KILL_FILE"
total_processes_count=$(wc -l < "$PROCESS_LIST_FILE")
terminated_processes_count=$(wc -l < "$KILL_FILE")
log "Terminated $terminated_processes_count/$total_processes_count processes"
log "Done MySQL Processes termination."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment