Blame | Last modification | View Log
#!/bin/bash
#########################
## ALCASAR replication ##
## list ##
#########################
# The script is designed to list replicas of the ALCASAR instance.
# Constants
readonly ALCASAR_PWD="/root/ALCASAR-passwords.txt"
readonly SERVICES_PATH="/etc/systemd/system"
# Dynamically generated constants
DB_ROOT_PWD="$(grep db_root "$ALCASAR_PWD" | cut -d '=' -f 2-)"
readonly DB_ROOT_PWD
# Variables
query=""
attributes=""
check_args() {
# Parse args
args="$(getopt --longoptions "all,name:,help" --options "a,n:,h" -- "$@")"
# Reset script args list
eval set -- "$args"
# Print help
if [ $# -eq 1 ]
then
usage
return 1
fi
# Loop over all args
while true
do
case "$1" in
--all | -a)
query="SHOW ALL REPLICAS STATUS \\G"
break
;;
--name | -n)
query="SHOW REPLICA '$2' STATUS \\G"
shift
break
;;
--help | -h)
usage
return 2
;;
--)
# End of args
break
;;
*)
echo "error: unknown $1" >&2
return 3
break;;
esac
shift
done
}
# Edit informations with more information (like real remote IP)
edit_output() {
# Remove useless spaces
attributes="$(echo "$attributes" | sed "s/^ *//")"
# Loop over connections
for conn_name in $(echo "$attributes" | grep "Connection_name" | cut -d ' ' -f 2-)
do
service_file="$SERVICES_PATH/replication-$conn_name.service"
ip=""
# Look for service file where remote IP is hardcoded (on secondary only)
if ls "$service_file" &> /dev/null
then
# Get IP from SSH tunnel service file
ip="$(grep "ExecStart" "$service_file" | sed -E "s/.*@(.*) *.*/\1/")"
else
port="$(echo "$attributes" | grep -A5 "Connection_name: $conn_name" | grep "^Master_Port" | cut -d ' ' -f 2-)"
# Get IP from 'ss' established connections
pid="$(/usr/sbin/ss --tcp --processes | grep "$port.*sshd" | grep -oE "pid=[0-9]+" | cut -d '=' -f 2)"
# Skip if connection is closed
[ -z "$pid" ] && continue
# Find corresponding IP from PID
ip="$(/usr/sbin/ss --tcp --process | grep "$pid" | grep -v "127.0.0.1" | tr -s ' ' | cut -d ' ' -f 5 | cut -d ':' -f 1)"
fi
# Replace loopback address with the real remote IP
attributes="$(echo "$attributes" | sed "/Connection_name: $conn_name/,/Master_Host/s/127.0.0.1/$ip/")"
done
}
# Print script usage
usage() {
echo "usage: $0 OPTIONS"
echo
echo "OPTIONS"
echo " --all"
echo " list all primary connections attributes"
echo " --name=NAME, -n NAME"
echo " list primary connection attributes"
echo " --help, -h"
echo " print this help message"
}
# Main
check_args "$@" || exit
# Execute the query
attributes="$(/usr/bin/mariadb --host="localhost" --user="root" --password="$DB_ROOT_PWD" --execute="$query")"
[ "$?" -ne 0 ] && exit 1
# Edit some information
edit_output
# Display data if any (in case there are no remotes)
[ -n "$attributes" ] && echo "$attributes"
exit 0