Skip to content

Instantly share code, notes, and snippets.

@sokada1221
Created September 12, 2019 13:05
Show Gist options
  • Save sokada1221/60d4b5a705078b7a4674d9cdd2276a69 to your computer and use it in GitHub Desktop.
Save sokada1221/60d4b5a705078b7a4674d9cdd2276a69 to your computer and use it in GitHub Desktop.
#!/bin/bash
set -o errexit
set -o errtrace
set -o nounset
set -o pipefail
#set -x
function script_usage() {
cat << EOF
Usage:
query_all_tidb [Flags] [SQL query to run]
Flags:
-h|--help Displays this help
-n|--namespace Specifies the kubernetes namespace
-u|--username Specifies the TiDB username (default: root)
-p|--password Specifies the TiDB password
Note:
Assumes the following:
- kubectl is installed
- mysql installed
- GNU compatible getopt is installed (gnu-getopt on OS X)
- Port 4000 is available on localhost
EOF
}
# Set the following to the GNU compatible getopt on your system
GNU_GETOPT=gnu-getopt
! ${GNU_GETOPT} --test > /dev/null
if [[ ${PIPESTATUS[0]} -ne 4 ]]; then
echo 'getopt --test failed in this environment.'
exit 1
fi
# Parse the arguments
OPTIONS=hn:u:p:
LONGOPTS=help,namespace:,username:,password:
! PARSED=$(${GNU_GETOPT} --options=$OPTIONS --longoptions=$LONGOPTS --name "$0" -- "$@")
if [[ ${PIPESTATUS[0]} -ne 0 ]]; then
# e.g. return value is 1
# then getopt has complained about wrong arguments to stdout
exit 2
fi
eval set -- "$PARSED"
H=n NS=- UN=root PW=-
# parse the options in order until we see --
while true; do
case "$1" in
-h|--help)
H=y
shift
;;
-n|--namespace)
NS="$2"
shift 2
;;
-u|--username)
UN="$2"
shift 2
;;
-p|--password)
PW="$2"
shift 2
;;
--)
shift
break
;;
*)
echo "Parsing error at $1"
exit 3
;;
esac
done
# Help takes precedence
if [[ "$H" == "y" ]]; then
script_usage
exit 0
fi
# handle non-option arguments
if [[ $# -lt 1 ]]; then
echo "$0: SQL query is required."
exit 4
fi
IN="$@"
### MAIN ###
if [[ ${NS} != "-" ]]; then
ALL_TIDBS=$(kubectl get pods -n "${NS}" -l app.kubernetes.io/component=tidb | tail -n +2 | awk '{print $1}')
else
ALL_TIDBS=$(kubectl get pods -l app.kubernetes.io/component=tidb | tail -n +2 | awk '{print $1}')
fi
for tidb_pod in ${ALL_TIDBS}; do
echo "Connecting to ${tidb_pod}"
if [[ ${NS} != "-" ]]; then
kubectl port-forward "${tidb_pod}" 4000:4000 -n "${NS}" &
else
kubectl port-forward "${tidb_pod}" 4000:4000 &
fi
port_forward_pid=${!}
# Wait for port-forwarding to be ready
sleep 2
if [[ ${PW} != "-" ]]; then
mysql -h 127.0.0.1 -P 4000 -u "${UN}" -p "${PW}" -e "${IN}"
else
mysql -h 127.0.0.1 -P 4000 -u "${UN}" -e "${IN}"
fi
kill -INT ${port_forward_pid}
# sleep 1
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment