#!/bin/bash #set -x if [ `pgrep ssh-agent | wc -l` -lt 1 ] then echo "** You might do well to start ssh-agent now, bye." exit 1 fi # skipping passwords for demo # MYSLAVE="mysql -u root -p$1" MYSLAVE="mysql -u root " MASTER="my01" MYMASTER="mysql -h $MASTER -P3306 -u root " SSHMASTER="ssh root@$MASTER" echo "** Creating remote snap dir..." $SSHMASTER "[ ! -d /tmp/mysql ] && mkdir /tmp/myql" $SSHMASTER "rsync -arv /var/lib/mysql/ /tmp/mysql/" echo "** Stopping $MASTER database..." $SSHMASTER "/etc/init.d/mysql stop" sleep 10s echo "** Stopping SLAVE database" echo "stop slave;" | $MYSLAVE /etc/init.d/mysql stop # this is a good time to block access to local and remote databases # by manipulating ethernet interfaces or firewall rules # We don't want to block access before we shutdown the database because # that would possibly corrupt active connections # example $SSHMASTER ifdown eth1 echo "** Updating master snapshot ..." $SSHMASTER "rsync -arv /var/lib/mysql/ /tmp/mysql/" # consider that if the master ahead of us is also a replicant # we want to start it up "not replicating." # $SSHMASTER "rm -f /etc/my.cnf ; ln -s /etc/my.cnf.notslave /etc/my.cnf" echo "** Starting up master and capturing log position..." $SSHMASTER "/etc/init.d/mysql start" echo "FLUSH TABLES WITH READ LOCK;" | $MYMASTER masterStats=$( echo "SHOW MASTER STATUS \\G" \ | $MYMASTER ) masterBinLog=$( echo "$masterStats" \ | awk '/File/ {print $2}' ) masterBinLogPos=$( echo "$masterStats" \ | awk '/Position/ {print $2}' ) echo "** Master log position f:$masterBinLog p:$masterBinLogPos" echo "** Unlocking $master tables..." echo "UNLOCK TABLES;" | $MYMASTER # $SSHMASTER "ifup eth1" # $SSHMASTER "rm -f /etc/my.cnf ;\ # ln -s /etc/my.cnf.slave /etc/my.cnf" sleep 5s echo "** Rsyncing snapshot..." /root/bin/rsyncFromMaster.sh /tmp/mysql/ echo "** Starting local database unslaved..." rm /etc/my.cnf ln -s /etc/my.cnf.not-slave /etc/my.cnf /etc/init.d/mysql start sleep 2s echo "** Updating master statement..." echo "CHANGE MASTER TO MASTER_HOST='$MASTER', \ MASTER_USER='repoman', \ MASTER_PASSWORD='foo', \ MASTER_LOG_FILE='$masterBinLog', \ MASTER_LOG_POS=$masterBinLogPos;" echo "CHANGE MASTER TO MASTER_HOST='$MASTER', \ MASTER_USER='repoman', \ MASTER_PASSWORD='foo', \ MASTER_LOG_FILE='$masterBinLog', \ MASTER_LOG_POS=$masterBinLogPos;" \ | $MYSLAVE echo "** Initiating replication..." echo "START SLAVE;" | $MYSLAVE # echo "START SLAVE;" | $MYMASTER # ifup eth1 mv /etc/mysql/my.cnf /tmp/my.cnf.$$ ln -s /etc/mysql/my.cnf.slave /etc/mysql/my.cnf # eof