843388
#!/bin/bash -ue
843388
843388
# Copyright (C) 2010-2014 Codership Oy
843388
# Copyright (C) 2017-2020 Damien Ciabrini <damien.ciabrini@gmail.com>
843388
#
843388
# This program is free software; you can redistribute it and/or modify
843388
# it under the terms of the GNU General Public License as published by
843388
# the Free Software Foundation; version 2 of the License.
843388
#
843388
# This program is distributed in the hope that it will be useful,
843388
# but WITHOUT ANY WARRANTY; without even the implied warranty of
843388
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
843388
# GNU General Public License for more details.
843388
#
843388
# You should have received a copy of the GNU General Public License
843388
# along with this program; see the file COPYING. If not, write to the
843388
# Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston
843388
# MA  02110-1301  USA.
843388
843388
# This is a reference script for rsync-based state snapshot tansfer
843388
# over an encrypted communication channel, managed by socat
843388
843388
RSYNC_PID=                                      # rsync pid file
843388
RSYNC_CONF=                                     # rsync configuration file
843388
RSYNC_REAL_PID=                                 # rsync process id
843388
843388
SOCAT_PID=                                      # socat pid file
843388
SOCAT_REAL_PID=                                 # socat process id
843388
843388
SOCAT_OPTS=                                     # openssl connection args
843388
843388
MODULE="rsync_tunnel_sst"
843388
843388
OS=$(uname)
843388
[ "$OS" == "Darwin" ] && export -n LD_LIBRARY_PATH
843388
843388
# Setting the path for lsof on CentOS
843388
export PATH="/usr/sbin:/sbin:$PATH"
843388
843388
. $(dirname $0)/wsrep_sst_common
843388
843388
wsrep_check_programs rsync socat
843388
843388
cleanup_pid()
843388
{
843388
    local real_pid=$1
843388
    [ "0" != "$real_pid" ]            && \
843388
    kill $real_pid                    && \
843388
    sleep 0.5                         && \
843388
    kill -9 $real_pid >/dev/null 2>&1 || \
843388
    :
843388
}
843388
843388
cleanup_tunnel()
843388
{
843388
    if [ -n "$SOCAT_REAL_PID" ] && ps -p "$SOCAT_REAL_PID" >/dev/null 2>&1; then
843388
	wsrep_log_info "cleanup socat PID: $SOCAT_REAL_PID"
843388
	cleanup_pid $SOCAT_REAL_PID
843388
    fi
843388
    rm -rf "$SOCAT_PID"
843388
}
843388
843388
cleanup_joiner()
843388
{
843388
    wsrep_log_info "Joiner cleanup. rsync PID: $RSYNC_REAL_PID"
843388
    [ -n "$RSYNC_REAL_PID" ] && cleanup_pid $RSYNC_REAL_PID
843388
    rm -rf "$RSYNC_CONF"
843388
    rm -rf "$MAGIC_FILE"
843388
    rm -rf "$RSYNC_PID"
843388
843388
    cleanup_tunnel
843388
843388
    wsrep_log_info "Joiner cleanup done."
843388
    if [ "${WSREP_SST_OPT_ROLE}" = "joiner" ];then
843388
        wsrep_cleanup_progress_file
843388
    fi
843388
}
843388
843388
# Check whether process is still running.
843388
check_pid()
843388
{
843388
    local pid_file=$1
843388
    [ -r "$pid_file" ] && ps -p $(cat $pid_file) >/dev/null 2>&1
843388
}
843388
843388
check_pid_and_port()
843388
{
843388
    local pid_file=$1
843388
    local service_pid=$2
843388
    local service_port=$3
843388
    local service_host=$4
843388
    local service_name=$5
843388
843388
    if ! which lsof > /dev/null; then
843388
      wsrep_log_error "lsof tool not found in PATH! Make sure you have it installed."
843388
      exit 2 # ENOENT
843388
    fi
843388
843388
    local port_info=$(lsof -i "@"$service_host:$service_port -Pn 2>/dev/null | \
843388
        grep "(LISTEN)")
843388
    local is_service=$(echo $port_info | \
843388
        grep -w '^'"$service_name"'[[:space:]]\+'"$service_pid" 2>/dev/null)
843388
843388
    if [ -n "$port_info" -a -z "$is_service" ]; then
843388
        wsrep_log_error "$service_name daemon port '$service_port' has been taken"
843388
        exit 16 # EBUSY
843388
    fi
843388
843388
    if ! check_pid $pid_file; then
843388
        wsrep_log_error "$service_name process terminated unexpectedly"
843388
        exit 10 # ECHILD
843388
    fi
843388
843388
    [ -n "$port_info" ] && [ -n "$is_service" ] && \
843388
        [ $(cat $pid_file) -eq $service_pid ]
843388
}
843388
843388
config_from_cnf()
843388
{
843388
    local group=$1
843388
    local key=$2
843388
    echo $($MY_PRINT_DEFAULTS $group | grep -- "--$key=" | cut -d= -f2- | tail -1)
843388
}
843388
843388
setup_tunnel_args()
843388
{
843388
    tca=$(config_from_cnf sst tca)
843388
    tkey=$(config_from_cnf sst tkey)
843388
    tcert=$(config_from_cnf sst tcert)
843388
    sockopt=$(config_from_cnf sst sockopt)
843388
843388
    if [ -z "$tcert" ]; then
843388
        wsrep_log_error "Encryption certificate not found in my.cnf"
843388
        exit 3
843388
    else
843388
        SOCAT_OPTS="cert=$tcert"
843388
    fi
843388
    [ -n "$tkey" ] && SOCAT_OPTS="$SOCAT_OPTS,key=$tkey"
843388
    [ -n "$tca" ] && SOCAT_OPTS="$SOCAT_OPTS,cafile=$tca"
843388
    wsrep_log_info "Encryption setting to be used for socat tunnel: $SOCAT_OPTS"
843388
843388
    [ -n "$sockopt" ] && SOCAT_OPTS="$SOCAT_OPTS,$sockopt"
843388
}
843388
843388
MAGIC_FILE="$WSREP_SST_OPT_DATA/rsync_tunnel_sst_complete"
843388
rm -rf "$MAGIC_FILE"
843388
843388
BINLOG_TAR_FILE="$WSREP_SST_OPT_DATA/wsrep_sst_binlog.tar"
843388
BINLOG_N_FILES=1
843388
rm -f "$BINLOG_TAR_FILE" || :
843388
843388
if ! [ -z $WSREP_SST_OPT_BINLOG ]
843388
then
843388
    BINLOG_DIRNAME=$(dirname $WSREP_SST_OPT_BINLOG)
843388
    BINLOG_FILENAME=$(basename $WSREP_SST_OPT_BINLOG)
843388
fi
843388
843388
WSREP_LOG_DIR=${WSREP_LOG_DIR:-""}
843388
# if WSREP_LOG_DIR env. variable is not set, try to get it from my.cnf
843388
if [ -z "$WSREP_LOG_DIR" ]; then
843388
    WSREP_LOG_DIR=$($MY_PRINT_DEFAULTS --mysqld \
843388
                    | grep -- '--innodb[-_]log[-_]group[-_]home[-_]dir=' \
843388
                    | cut -b 29- )
843388
fi
843388
843388
if [ -n "$WSREP_LOG_DIR" ]; then
843388
    # handle both relative and absolute paths
843388
    WSREP_LOG_DIR=$(cd $WSREP_SST_OPT_DATA; mkdir -p "$WSREP_LOG_DIR"; cd $WSREP_LOG_DIR; pwd -P)
843388
else
843388
    # default to datadir
843388
    WSREP_LOG_DIR=$(cd $WSREP_SST_OPT_DATA; pwd -P)
843388
fi
843388
843388
# Old filter - include everything except selected
843388
# FILTER=(--exclude '*.err' --exclude '*.pid' --exclude '*.sock' \
843388
#         --exclude '*.conf' --exclude core --exclude 'galera.*' \
843388
#         --exclude grastate.txt --exclude '*.pem' \
843388
#         --exclude '*.[0-9][0-9][0-9][0-9][0-9][0-9]' --exclude '*.index')
843388
843388
# New filter - exclude everything except dirs (schemas) and innodb files
843388
FILTER=(-f '- /lost+found' -f '- /.fseventsd' -f '- /.Trashes'
843388
        -f '+ /wsrep_sst_binlog.tar' -f '+ /ib_lru_dump' -f '+ /ibdata*' -f '+ /*/' -f '- /*')
843388
843388
SOCAT_PID="$WSREP_SST_OPT_DATA/$MODULE-socat.pid"
843388
843388
if check_pid $SOCAT_PID
843388
then
843388
    wsrep_log_error "socat tunnel already running."
843388
    exit 114 # EALREADY
843388
fi
843388
rm -rf "$SOCAT_PID"
843388
843388
setup_tunnel_args
843388
843388
if [ "$WSREP_SST_OPT_ROLE" = "donor" ]
843388
then
843388
843388
    SOCAT_JOINER_ADDR=$(echo $WSREP_SST_OPT_ADDR | awk -F'/' '{print $1}')
843388
    # map to name in case we received an IP
843388
    SOCAT_JOINER_HOST=$(getent hosts $SOCAT_JOINER_ADDR | awk '{ print $2 }')
843388
    if [ -z "$SOCAT_JOINER_HOST" ]; then
843388
        SOCAT_JOINER_HOST=$SOCAT_JOINER_ADDR
843388
    fi
843388
    SOCAT_PORT=$(echo $SOCAT_JOINER_ADDR | awk -F ':' '{ print $2 }')
843388
    if [ -z "$SOCAT_PORT" ]
843388
    then
843388
        SOCAT_PORT=4444
843388
    fi
843388
    TARGET_ADDR=localhost:$SOCAT_PORT/$MODULE
843388
843388
    trap cleanup_tunnel EXIT
843388
843388
    # Socat forwards rsync connections to the joiner
843388
    SOCAT_SRC=tcp-listen:$SOCAT_PORT,bind=localhost,reuseaddr,fork
843388
    SOCAT_DST=openssl:$SOCAT_JOINER_HOST,$SOCAT_OPTS
843388
    wsrep_log_info "Setting up tunnel for donor: socat $SOCAT_SRC $SOCAT_DST"
843388
    socat $SOCAT_SRC $SOCAT_DST &
843388
    SOCAT_REAL_PID=$!
843388
    # This is ok because a local galera node doesn't run SST concurrently
843388
    echo $SOCAT_REAL_PID >"$SOCAT_PID"
843388
    until check_pid_and_port $SOCAT_PID $SOCAT_REAL_PID $SOCAT_PORT localhost "socat"
843388
    do
843388
        sleep 0.2
843388
    done
843388
843388
    if [ $WSREP_SST_OPT_BYPASS -eq 0 ]
843388
    then
843388
843388
        FLUSHED="$WSREP_SST_OPT_DATA/tables_flushed"
843388
        ERROR="$WSREP_SST_OPT_DATA/sst_error"
843388
843388
        rm -rf "$FLUSHED"
843388
        rm -rf "$ERROR"
843388
843388
        # Use deltaxfer only for WAN
843388
        inv=$(basename $0)
843388
        [ "$inv" = "wsrep_sst_rsync_wan" ] && WHOLE_FILE_OPT="" \
843388
                                           || WHOLE_FILE_OPT="--whole-file"
843388
843388
        echo "flush tables"
843388
843388
        # Wait for :
843388
        # (a) Tables to be flushed, AND
843388
        # (b) Cluster state ID & wsrep_gtid_domain_id to be written to the file, OR
843388
        # (c) ERROR file, in case flush tables operation failed.
843388
843388
        while [ ! -r "$FLUSHED" ] && ! grep -q ':' "$FLUSHED" >/dev/null 2>&1
843388
        do
843388
            # Check whether ERROR file exists.
843388
            if [ -f "$ERROR" ]
843388
            then
843388
                # Flush tables operation failed.
843388
                rm -rf "$ERROR"
843388
                exit 255
843388
            fi
843388
843388
            sleep 0.2
843388
        done
843388
843388
        STATE="$(cat $FLUSHED)"
843388
        rm -rf "$FLUSHED"
843388
843388
        sync
843388
843388
        if ! [ -z $WSREP_SST_OPT_BINLOG ]
843388
        then
843388
            # Prepare binlog files
843388
            pushd $BINLOG_DIRNAME &> /dev/null
843388
            binlog_files_full=$(tail -n $BINLOG_N_FILES ${BINLOG_FILENAME}.index)
843388
            binlog_files=""
843388
            for ii in $binlog_files_full
843388
            do
843388
                binlog_files="$binlog_files $(basename $ii)"
843388
            done
843388
            if ! [ -z "$binlog_files" ]
843388
            then
843388
                wsrep_log_info "Preparing binlog files for transfer:"
843388
                tar -cvf $BINLOG_TAR_FILE $binlog_files >&2
843388
            fi
843388
            popd &> /dev/null
843388
        fi
843388
843388
        # first, the normal directories, so that we can detect incompatible protocol
843388
        RC=0
843388
        rsync --owner --group --perms --links --specials \
843388
              --ignore-times --inplace --dirs --delete --quiet \
843388
              $WHOLE_FILE_OPT "${FILTER[@]}" "$WSREP_SST_OPT_DATA/" \
843388
              rsync://$TARGET_ADDR >&2 || RC=$?
843388
843388
        if [ "$RC" -ne 0 ]; then
843388
            wsrep_log_error "rsync returned code $RC:"
843388
843388
            case $RC in
843388
            12) RC=71  # EPROTO
843388
                wsrep_log_error \
843388
                "rsync server on the other end has incompatible protocol. " \
843388
                "Make sure you have the same version of rsync on all nodes."
843388
                ;;
843388
            22) RC=12  # ENOMEM
843388
                ;;
843388
            *)  RC=255 # unknown error
843388
                ;;
843388
            esac
843388
            exit $RC
843388
        fi
843388
843388
        # second, we transfer InnoDB log files
843388
        rsync --owner --group --perms --links --specials \
843388
              --ignore-times --inplace --dirs --delete --quiet \
843388
              $WHOLE_FILE_OPT -f '+ /ib_logfile[0-9]*' -f '- **' "$WSREP_LOG_DIR/" \
843388
              rsync://$TARGET_ADDR-log_dir >&2 || RC=$?
843388
843388
        if [ $RC -ne 0 ]; then
843388
            wsrep_log_error "rsync innodb_log_group_home_dir returned code $RC:"
843388
            exit 255 # unknown error
843388
        fi
843388
843388
        # then, we parallelize the transfer of database directories, use . so that pathconcatenation works
843388
        pushd "$WSREP_SST_OPT_DATA" >/dev/null
843388
843388
        count=1
843388
        [ "$OS" == "Linux" ] && count=$(grep -c processor /proc/cpuinfo)
843388
        [ "$OS" == "Darwin" -o "$OS" == "FreeBSD" ] && count=$(sysctl -n hw.ncpu)
843388
843388
        find . -maxdepth 1 -mindepth 1 -type d -not -name "lost+found" -print0 | \
843388
             xargs -I{} -0 -P $count \
843388
             rsync --owner --group --perms --links --specials \
843388
             --ignore-times --inplace --recursive --delete --quiet \
843388
             $WHOLE_FILE_OPT --exclude '*/ib_logfile*' "$WSREP_SST_OPT_DATA"/{}/ \
843388
             rsync://$TARGET_ADDR/{} >&2 || RC=$?
843388
843388
        popd >/dev/null
843388
843388
        if [ $RC -ne 0 ]; then
843388
            wsrep_log_error "find/rsync returned code $RC:"
843388
            exit 255 # unknown error
843388
        fi
843388
843388
    else # BYPASS
843388
        wsrep_log_info "Bypassing state dump."
843388
843388
        # Store donor's wsrep GTID (state ID) and wsrep_gtid_domain_id
843388
        # (separated by a space).
843388
        STATE="$WSREP_SST_OPT_GTID $WSREP_SST_OPT_GTID_DOMAIN_ID"
843388
    fi
843388
843388
    echo "continue" # now server can resume updating data
843388
843388
    echo "$STATE" > "$MAGIC_FILE"
843388
    rsync --archive --quiet --checksum "$MAGIC_FILE" rsync://$TARGET_ADDR
843388
843388
    # to avoid cleanup race, stop tunnel before declaring the SST finished.
843388
    # This ensures galera won't start a new SST locally before we exit.
843388
    cleanup_tunnel
843388
843388
    echo "done $STATE"
843388
843388
elif [ "$WSREP_SST_OPT_ROLE" = "joiner" ]
843388
then
843388
    wsrep_check_programs lsof socat
843388
843388
    touch $SST_PROGRESS_FILE
843388
    MYSQLD_PID=$WSREP_SST_OPT_PARENT
843388
843388
    RSYNC_PID="$WSREP_SST_OPT_DATA/$MODULE.pid"
843388
843388
    if check_pid $RSYNC_PID
843388
    then
843388
        wsrep_log_error "rsync daemon already running."
843388
        exit 114 # EALREADY
843388
    fi
843388
    rm -rf "$RSYNC_PID"
843388
843388
    ADDR=$WSREP_SST_OPT_ADDR
843388
    RSYNC_PORT=$(echo $ADDR | awk -F ':' '{ print $2 }')
843388
    if [ -z "$RSYNC_PORT" ]
843388
    then
843388
        RSYNC_PORT=4444
843388
        ADDR="$(echo $ADDR | awk -F ':' '{ print $1 }'):$RSYNC_PORT"
843388
    fi
843388
843388
    SOCAT_ADDR=$(echo $ADDR | awk -F ':' '{ print $1 }')
843388
    # map to name in case we received an IP
843388
    SOCAT_HOST=$(getent hosts $SOCAT_ADDR | awk '{ print $2 }')
843388
    if [ -z "$SOCAT_HOST" ]; then
843388
        SOCAT_HOST=$SOCAT_ADDR
843388
    fi
843388
    SOCAT_PORT=$RSYNC_PORT
843388
843388
    trap "exit 32" HUP PIPE
843388
    trap "exit 3"  INT TERM ABRT
843388
    trap cleanup_joiner EXIT
843388
843388
    RSYNC_CONF="$WSREP_SST_OPT_DATA/$MODULE.conf"
843388
843388
    if [ -n "${MYSQL_TMP_DIR:-}" ] ; then
843388
      SILENT="log file = $MYSQL_TMP_DIR/rsynd.log"
843388
    else
843388
      SILENT=""
843388
    fi
843388
843388
cat << EOF > "$RSYNC_CONF"
843388
pid file = $RSYNC_PID
843388
use chroot = no
843388
read only = no
843388
timeout = 300
843388
$SILENT
843388
[$MODULE]
843388
    path = $WSREP_SST_OPT_DATA
843388
[$MODULE-log_dir]
843388
    path = $WSREP_LOG_DIR
843388
EOF
843388
843388
#    rm -rf "$DATA"/ib_logfile* # we don't want old logs around
843388
843388
    # Socat receives rsync connections from the donor
843388
    SOCAT_SRC=openssl-listen:$SOCAT_PORT,bind=$SOCAT_HOST,reuseaddr,fork,$SOCAT_OPTS
843388
    SOCAT_DST=tcp:localhost:$RSYNC_PORT
843388
    wsrep_log_info "Setting up tunnel for joiner: socat $SOCAT_SRC $SOCAT_DST"
843388
    socat $SOCAT_SRC $SOCAT_DST &
843388
    SOCAT_REAL_PID=$!
843388
    # This is ok because a local galera node doesn't run SST concurrently
843388
    echo $SOCAT_REAL_PID >"$SOCAT_PID"
843388
    until check_pid_and_port $SOCAT_PID $SOCAT_REAL_PID $SOCAT_PORT $SOCAT_HOST "socat"
843388
    do
843388
        sleep 0.2
843388
    done
843388
843388
    wsrep_log_info "rsync --daemon --no-detach --address localhost --port $RSYNC_PORT --config \"$RSYNC_CONF\""
843388
    rsync --daemon --no-detach --address localhost --port $RSYNC_PORT --config "$RSYNC_CONF" &
843388
    RSYNC_REAL_PID=$!
843388
843388
    until check_pid_and_port $RSYNC_PID $RSYNC_REAL_PID $RSYNC_PORT localhost "rsync"
843388
    do
843388
        sleep 0.2
843388
    done
843388
843388
    echo "ready $ADDR/$MODULE"
843388
843388
    # wait for SST to complete by monitoring magic file
843388
    while [ ! -r "$MAGIC_FILE" ] && check_pid "$RSYNC_PID" && \
843388
          check_pid "$SOCAT_PID" && ps -p $MYSQLD_PID >/dev/null
843388
    do
843388
        sleep 1
843388
    done
843388
843388
    # to avoid cleanup race, we can tear down the socat tunnel now
843388
    # before signaling the end of the SST to galera.
843388
    cleanup_tunnel
843388
843388
    if ! ps -p $MYSQLD_PID >/dev/null
843388
    then
843388
        wsrep_log_error \
843388
        "Parent mysqld process (PID:$MYSQLD_PID) terminated unexpectedly."
843388
        exit 32
843388
    fi
843388
843388
    if ! [ -z $WSREP_SST_OPT_BINLOG ]
843388
    then
843388
843388
        pushd $BINLOG_DIRNAME &> /dev/null
843388
        if [ -f $BINLOG_TAR_FILE ]
843388
        then
843388
            # Clean up old binlog files first
843388
            rm -f ${BINLOG_FILENAME}.*
843388
            wsrep_log_info "Extracting binlog files:"
843388
            tar -xvf $BINLOG_TAR_FILE >&2
843388
            for ii in $(ls -1 ${BINLOG_FILENAME}.*)
843388
            do
843388
                echo ${BINLOG_DIRNAME}/${ii} >> ${BINLOG_FILENAME}.index
843388
            done
843388
        fi
843388
        popd &> /dev/null
843388
    fi
843388
    if [ -r "$MAGIC_FILE" ]
843388
    then
843388
        # UUID:seqno & wsrep_gtid_domain_id is received here.
843388
        cat "$MAGIC_FILE" # Output : UUID:seqno wsrep_gtid_domain_id
843388
    else
843388
        # this message should cause joiner to abort
843388
        echo "rsync process ended without creating '$MAGIC_FILE'"
843388
    fi
843388
    wsrep_cleanup_progress_file
843388
#    cleanup_joiner
843388
else
843388
    wsrep_log_error "Unrecognized role: '$WSREP_SST_OPT_ROLE'"
843388
    exit 22 # EINVAL
843388
fi
843388
843388
rm -f $BINLOG_TAR_FILE || :
843388
843388
exit 0