Skip to content

Instantly share code, notes, and snippets.

@colinmollenhour
Last active March 6, 2019 02:03
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save colinmollenhour/5646619 to your computer and use it in GitHub Desktop.
Save colinmollenhour/5646619 to your computer and use it in GitHub Desktop.
MySQL Monitor (like 'redis-cli MONITOR')
#!/bin/bash
#
# Monitor MySQL queries
# @author Colin Mollenhour
set -e
mysql="mysql"
test="test"
bash="bash"
cp="cp"
if [[ -z $1 ]] && ! test -f /var/run/mysqld/mysqld.sock; then
set -- "--docker"
fi
if [[ $1 =~ --docker|docker ]]; then
if [[ $(docker ps --format '{{.Names}}' | grep mysql | wc -l) -eq 1 ]]; then
container=$(docker ps --format '{{.Names}}' | grep mysql | head -n 1)
else
select container in $(docker ps --format '{{.Names}}' | grep mysql); do
break
done
fi
mysql="docker exec $container mysql"
test="docker exec $container test"
bash="docker exec -i $container bash"
function _cp {
echo "Using docker cp"
docker cp "$container:$1" "$2"
}
elif [[ -n $1 ]]; then
mysql="$1"
function _cp {
cp -f "$1" "$2"
}
fi
file=$($mysql -sN performance_schema -e 'SELECT Variable_Value FROM global_variables WHERE Variable_Name = "general_log_file"')
if ! $test -f $file; then
datadir=$($mysql -sN performance_schema -e 'SELECT Variable_Value FROM global_variables WHERE Variable_Name = "datadir"')
datadir=${datadir%/}
if ! $test -f $datadir/$file; then
$mysql -e "SET GLOBAL general_log = 'ON'"
sleep 1
if ! $test -f $datadir/$file; then
echo "Could not locate general log file $file in $datadir."
exit 1
fi
fi
file=$datadir/$file
fi
if ! $test -w $file && [[ $bash = "bash" ]]; then
bash="sudo bash"
fi
$bash -c ">$file"
$mysql -e "SET GLOBAL general_log = 'ON'"
tailPid=0
function cleanExit {
kill -TERM $tailPid >/dev/null 2>&1
$mysql -e "SET GLOBAL general_log = 'OFF'"
tempfile=$(mktemp -p /tmp mysql-XXXXX.log)
_cp $file $tempfile
echo -e "\n$tempfile"
}
trap cleanExit SIGINT SIGTERM
$bash -c "tail -f $file" &
tailPid=$!
wait
$mysql -e "SET GLOBAL general_log = 'OFF'"
tempfile=$(mktemp -p /tmp mysql-XXXXX.log)
_cp $file $tempfile
echo -e "\n$tempfile"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment