#!/bin/bash # # kill-thread.sh # Simple shell script to kill mysql db connections based on filters # # Changelog # 2014-03-28 - Nathan Isburgh # * Initial version # # Debug flag? 1=on, 0=off DEBUG=1 # Additional user-customized variables... # # END OF CONFIGURATION VARIABLES # NO MORE EDITS BEYOND THIS POINT # # Functions... # # fail [exit code] [exit message] # # Common exit codes: # 1 - Invalid arguments # 2 - Missing arguments # 3 - Missing software # fail() { cleanup ECODE=${1:-1} EMSG=$2 if [ -n "$EMSG" ] then echo -e "\033[33m$EMSG\033[39m" > /dev/stderr fi exit $ECODE } succeed() { cleanup exit } cleanup() { # Clean up temp files # Close out logs # Disconnect from remote resources return } # # debug "message" # debug() { if [ $DEBUG -eq 1 ] then printf "\033[32m*** [%s] %s\033[39m\n" "$(date +%r)" "$1" > /dev/stderr fi } usage() { cat << eof $0 [-u user] [-h host] [-d db] [-c command] -u user Kill connections from 'user' -h host Kill connections from 'host' -d db Kill connections on 'db' -c command Kill connections running 'command' eof } kill-threads() { # Get list of all connections and details about the connections # Filter list by supplied parameters # Use mysqladmin kill to kill off the connections that match mysql -N -e "show full pROcESSlIST" | fgrep -v 'pROcESSlIST' | awk -F"\t" "\$2 ~ /$FILTER_USER/ && \$3 ~ /$FILTER_HOST/ && \$4 ~ /$FILTER_DB/ && \$8 ~ /$FILTER_CMD/ {print \$1}" | xargs -n1 mysqladmin kill } # Main body... FILTER_USER="" FILTER_HOST="" FILTER_DB="" FILTER_CMD="" while getopts ":u:h:d:c:" opt; do case $opt in u) FILTER_USER="$OPTARG" ;; h) FILTER_HOST="$OPTARG" ;; d) FILTER_DB="$OPTARG" ;; c) FILTER_CMD="$OPTARG" ;; \?) usage fail 1 "Invalid option: -$OPTARG" ;; :) usage fail 1 "Option -$OPTARG requires an argument." ;; esac done debug "Killing things" kill-threads succeed