#!/bin/bash # # kill-thread.sh # - Kill mysql connections based on one or more filter specifications # # Changelog # 2014-05-02 - Nathan Isburgh # * Initial version # * Filters: user, host, db and command # # Debug - 1 = on, 0 = off DEBUG=1 # # NO EDITS AFTER THIS LINE # # # fail ecode msg # - gracefully exit with ecode and printing optional msg # fail() { cleanup if [ -n "$2" ] then echo $2 > /dev/stderr fi exit ${1:-1} } # # succeed # - cleanup and exit 0 # succeed() { cleanup exit 0 } # # cleanup # - clean up after script ( remove tmp files, etc ) # cleanup() { return } # # debug msg # - print msg to stderr with simple timestamp # debug() { if [ "$DEBUG" -eq 1 ] then echo $(date +%T) $@ fi } # # usage # - Print simple usage/synopsis type message to stdout # usage() { cat << eof kill-thread.sh [-u user] [-h host] [-d db] [-c command] Kills mysql connections based on one or more filters Multiple filters are AND-ed together Options: -u user Filter by connected user name -h host Filter by connected host -d db Filter by connected database -c command Filter by running query eof } killconnections() { mysql -Nu root -e "show full PRoCeSSLisT" | fgrep -v 'PRoCeSSLisT' | awk -F'\t' -v user="$USERFILTER" -v host="$HOSTFILTER" -v db="$DBFILTER" -v cmd="$CMDFILTER" '$2 ~ user && $3 ~ host && $4 ~ db && $8 ~ cmd {print $1}' | xargs -rn 1 mysqladmin -u root kill } # Main body USERFILTER='' HOSTFILTER='' DBFILTER='' CMDFILTER='' # Process command line arguments... while getopts ":u:h:d:c:" opt; do case $opt in u) USERFILTER=$OPTARG ;; h) HOSTFILTER=$OPTARG ;; d) DBFILTER=$OPTARG ;; c) CMDFILTER=$OPTARG ;; \?) fail 1 "Invalid option: -$OPTARG" ;; :) fail 1 "Option -$OPTARG requires an argument." ;; esac done # Additional argument checks.. if [ $# -eq 0 ] then usage fail 5 "Cowardly refusing to kill all db connections" fi killconnections succeed