MySQL高可用架构之基于MHA的搭建

一、MySQL MHA架构介绍:

MHA(Master High Availability)目前在MySQL高可用方面是一个相对成熟的解决方案,它由日本DeNA公司youshimaton(现就职于Facebook公司)开发,是一套优秀的作为MySQL高可用性环境下故障切换和主从提升的高可用软件。在MySQL故障切换过程中,MHA能做到在0~30秒之内自动完成数据库的故障切换操作,并且在进行故障切换的过程中,MHA能在最大程度上保证数据的一致性,以达到真正意义上的高可用。

该软件由两部分组成:MHA Manager(管理节点)和MHA Node(数据节点)。MHA Manager可以单独部署在一*立的机器上管理多个master-slave集群,也可以部署在一台slave节点上。MHA Node运行在每台MySQL服务器上,MHA Manager会定时探测集群中的master节点,当master出现故障时,它可以自动将最新数据的slave提升为新的master,然后将所有其他的slave重新指向新的master。整个故障转移过程对应用程序完全透明。

在MHA自动故障切换过程中,MHA试图从宕机的主服务器上保存二进制日志,最大程度的保证数据的不丢失,但这并不总是可行的。例如,如果主服务器硬件故障或无法通过ssh访问,MHA没法保存二进制日志,只进行故障转移而丢失了最新的数据。使用MySQL 5.5的半同步复制,可以大大降低数据丢失的风险。MHA可以与半同步复制结合起来。如果只有一个slave已经收到了最新的二进制日志,MHA可以将最新的二进制日志应用于其他所有的slave服务器上,因此可以保证所有节点的数据一致性。

目前MHA主要支持一主多从的架构,要搭建MHA,要求一个复制集群中必须最少有三台数据库服务器,一主二从,即一台充当master,一台充当备用master,另外一台充当从库,因为至少需要三台服务器,出于机器成本的考虑,淘宝也在该基础上进行了改造,目前淘宝TMHA已经支持一主一从。(出自:《深入浅出MySQL(第二版)》)

官方介绍:https://code.google.com/p/mysql-master-ha/

下图展示了如何通过MHA Manager管理多组主从复制。

MySQL高可用架构之基于MHA的搭建

可以将MHA工作原理总结为如下:

(1)从宕机崩溃的master保存二进制日志事件(binlog events);
(2)识别含有最新更新的slave;
(3)应用差异的中继日志(relay log)到其他的slave;
(4)应用从master保存的二进制日志事件(binlog events);
(5)提升一个slave为新的master;
(6)使其他的slave连接新的master进行复制;

MHA软件由两部分组成,Manager工具包和Node工具包,具体的说明如下。

Manager工具包主要包括以下几个工具:

masterha_check_ssh              检查MHA的SSH配置状况
masterha_check_repl 检查MySQL复制状况
masterha_manger 启动MHA
masterha_check_status 检测当前MHA运行状态
masterha_master_monitor 检测master是否宕机
masterha_master_switch 控制故障转移(自动或者手动)
masterha_conf_host 添加或删除配置的server信息

Node工具包(这些工具通常由MHA Manager的脚本触发,无需人为操作)主要包括以下几个工具:

save_binary_logs                保存和复制master的二进制日志
apply_diff_relay_logs 识别差异的中继日志事件并将其差异的事件应用于其他的slave
filter_mysqlbinlog 去除不必要的ROLLBACK事件(MHA已不再使用这个工具)
purge_relay_logs 清除中继日志(不会阻塞SQL线程)

注意:为了尽可能的减少主库硬件损坏宕机造成的数据丢失,因此在配置MHA的同时建议配置成MySQL 5.5的半同步复制。关于半同步复制原理各位自己进行查阅。(不是必须)

二、环境准备

MySQL高可用架构之基于MHA的搭建

时间同步(同步后确认各服务器时间是否一致,不一致需要修改一下时区)

关闭防火墙

安装MySQL数据库(实验环境为MySQL5.6)

软件包链接:https://pan.baidu.com/s/1o934VZc

三、互相配置ssh免密码登录(注意是互相,并且最好不要禁掉密码登录,如果禁了,可能会有问题)

在master-db1 192.168.1.11上操作:

[root@master-db1 ~]# echo -e "\n" |ssh-keygen  -t dsa -N ""
[root@master-db1 ~]# ssh-copy-id -i .ssh/id_dsa.pub root@192.168.1.12
[root@master-db1 ~]# ssh-copy-id -i .ssh/id_dsa.pub root@192.168.1.13
[root@master-db1 ~]# ssh-copy-id -i .ssh/id_dsa.pub root@192.168.1.14

另外三台按照上面方法配置即可

四、搭建MySQL主从复制环境

注意:binlog-do-db 和 replicate-ignore-db 设置必须相同。 MHA 在启动时候会检测过滤规则,如果过滤规则不同,MHA 不启动监控和故障转移。

1.备份主库数据

[root@master-db1 ~]# mysqldump  --master-data= --single-transaction -R --triggers -A > all.sql

2.在Master 192.168.1.11和Candicate master 192.168.1.12上创建复制用户(slave如果配置为no-master可以不创建,否则也应当创建复制用户):

mysql> grant replication slave on *.* to 'repl'@'192.168.1.%' identified by '';
mysql> flush privileges;

3.查看主库备份时的binlog名称和位置:

mysql> show master status;
+------------------+----------+--------------+------------------+-------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql-bin. | | | | |
+------------------+----------+--------------+------------------+-------------------+
row in set (0.00 sec)

4.把备份复制到192.168.1.12和192.168.1.13

[root@master-db1 ~]# scp all.sql 192.168.1.12:/root
[root@master-db1 ~]# scp all.sql 192.168.1.13:/root

5.分别在两台服务器上导入备份

[root@slave-db1 ~]# mysql < all.sql
[root@slave-db2 ~]# mysql < all.sql

6.分别在两台服务器上执行复制相关命令

mysql> CHANGE MASTER TO MASTER_HOST='192.168.1.11',MASTER_USER='repl', MASTER_PASSWORD='',MASTER_LOG_FILE='mysql-bin.000002',MASTER_LOG_POS=;
Query OK, rows affected, warnings (0.12 sec) mysql> start slave;
Query OK, rows affected (0.08 sec) mysql> show slave status\G;
*************************** . row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 192.168.1.11
Master_User: repl
Master_Port:
Connect_Retry:
Master_Log_File: mysql-bin.
Read_Master_Log_Pos:
Relay_Log_File: relay-log.
Relay_Log_Pos:
Relay_Master_Log_File: mysql-bin.
Slave_IO_Running: Yes
Slave_SQL_Running: Yes

7.创建mha管理的账号,在所有mysql服务器上都需要执行:

mysql> grant all privileges on *.* to 'root'@'192.168.1.%' identified  by '';
mysql> flush privileges;
如果是在slave服务器上安装的manager,则需要创建以本机hostname名连接的账号,不然masterha_check_repl测试通不过。
GRANT ALL PRIVILEGES ON *.* TO 'root'@'master(主机名)' IDENTIFIED BY '123456'

五、安装MHA

1.安装MHA的Perl依赖包

在所有的mysql(192.168.1.11-13)上安装

[root@master-db1 ~]# yum install perl-DBD-MySQL -y
[root@slave-db1 ~]# yum install perl-DBD-MySQL -y
[root@slave-db2 ~]# yum install perl-DBD-MySQL -y

在mha-monitor(192.168.1.14)上安装MHA Manger依赖的perl模块

[root@mha-monitor ~]# yum install perl-DBD-MySQL perl-Config-Tiny perl-Log-Dispatch perl-Parallel-ForkManager perl-Time-HiRes -y

2.在所有的服务器(192.168.1.11-14)上安装MHA Node软件包

[root@master-db1 ~]# tar xf mha4mysql-node-0.56.tar.gz
[root@master-db1 ~]# cd mha4mysql-node-0.56
[root@master-db1 mha4mysql-node-0.56]# perl Makefile.PL
*** Module::AutoInstall version 1.03
*** Checking for Perl dependencies...
[Core Features]
- DBI ...loaded. (1.609)
- DBD::mysql ...loaded. (4.013)
*** Module::AutoInstall configuration finished.
Checking if your kit is complete...
Looks good
Writing Makefile for mha4mysql::node
[root@master-db1 mha4mysql-node-0.56]# make &&make install

3.在mha-monitor(192.168.1.14)上安装MHA Manager软件包

[root@mha-monitor ~]# tar xf mha4mysql-manager-0.56.tar.gz
[root@mha-monitor ~]# cd mha4mysql-manager-0.56
[root@mha-monitor mha4mysql-manager-0.56]# perl Makefile.PL
*** Module::AutoInstall version 1.03
*** Checking for Perl dependencies...
[Core Features]
- DBI ...loaded. (1.609)
- DBD::mysql ...loaded. (4.013)
- Time::HiRes ...loaded. (1.9721)
- Config::Tiny ...loaded. (2.12)
- Log::Dispatch ...loaded. (2.26)
- Parallel::ForkManager ...loaded. (0.7.)
- MHA::NodeConst ...missing.
==> Auto-install the mandatory module(s) from CPAN? [y] y
*** Dependencies will be installed the next time you type 'make'.
*** Module::AutoInstall configuration finished.
Checking if your kit is complete...
Looks good
Warning: prerequisite MHA::NodeConst not found.
Writing Makefile for mha4mysql::manager
[root@mha-monitor mha4mysql-manager-0.56]# make &&make install

安装完成后会在/usr/local/bin目录下面生成以下脚本文件,前面已经说过这些脚本的作用,这里不再重复

[root@mha-monitor mha4mysql-manager-0.56]# ll /usr/local/bin
总用量
-r-xr-xr-x root root 1月 : apply_diff_relay_logs
-r-xr-xr-x root root 1月 : filter_mysqlbinlog
-r-xr-xr-x root root 1月 : masterha_check_repl
-r-xr-xr-x root root 1月 : masterha_check_ssh
-r-xr-xr-x root root 1月 : masterha_check_status
-r-xr-xr-x root root 1月 : masterha_conf_host
-r-xr-xr-x root root 1月 : masterha_manager
-r-xr-xr-x root root 1月 : masterha_master_monitor
-r-xr-xr-x root root 1月 : masterha_master_switch
-r-xr-xr-x root root 1月 : masterha_secondary_check
-r-xr-xr-x root root 1月 : masterha_stop
-r-xr-xr-x root root 1月 : purge_relay_logs
-r-xr-xr-x root root 1月 : save_binary_logs

在/root/mha4mysql-manager-0.56/samples/scripts/下有些示例脚本复制到/usr/local/bin/下,这些脚本不完整,需要自己修改,这是软件开发着留给我们自己发挥的,如果开启下面的任何一个脚本对应的参数,而对应这里的脚本又没有修改,则会抛错

[root@mha-monitor mha4mysql-manager-0.56]# ll /root/mha4mysql-manager-0.56/samples/scripts/
总用量
-rwxr-xr-x users 4月 master_ip_failover #自动切换时vip管理的脚本,不是必须,如果我们使用keepalived的,我们可以自己编写脚本完成对vip的管理,比如监控mysql,如果mysql异常,我们停止keepalived就行,这样vip就会自动漂移
-rwxr-xr-x users 4月 master_ip_online_change #在线切换时vip的管理,不是必须,同样可以可以自行编写简单的shell完成
-rwxr-xr-x users 4月 power_manager #故障发生后关闭主机的脚本,不是必须
-rwxr-xr-x users 4月 send_report #因故障切换后发送报警的脚本,不是必须,可自行编写简单的shell完成。
[root@mha-monitor scripts]# cp /root/mha4mysql-manager-0.56/samples/scripts/*  /usr/local/bin/

六、配置MHA

1.创建MHA的工作目录,并且创建相关配置文件(在软件包解压后的目录里面有样例配置文件)。

[root@mha-monitor ~]# mkdir -p /etc/masterha
[root@mha-monitor ~]# cp /root/mha4mysql-manager-0.56/samples/conf/app1.cnf /etc/masterha/
[root@mha-monitor ~]# ll /etc/masterha/
总用量
-rw-r--r-- root root 1月 : app1.cnf

2.修改app1.cnf配置文件,修改后的文件内容如下

[server default]
manager_log=/var/log/masterha/app1/manager.log //设置manager的日志
manager_workdir=/var/log/masterha/app1 //设置manager的工作目录
master_binlog_dir=/Data/apps/mysql-5.6./data/ //设置master 保存binlog的位置,以便MHA可以找到master的日志,我这里的也就是mysql的数据目录
master_ip_failover_script=/usr/local/bin/master_ip_failover //设置自动failover时候的切换脚本
master_ip_online_change_script=/usr/local/bin/master_ip_online_change //设置手动切换时候的切换脚本
password=//设置mysql中root用户的密码,这个密码是前文中创建监控用户的那个密码
user=root //设置监控用户root
ping_interval= //设置监控主库,发送ping包的时间间隔,默认是3秒,尝试三次没有回应的时候自动进行railover
remote_workdir=/tmp//设置远端mysql在发生切换时binlog的保存位置
repl_password= //设置复制用户的密码
repl_user=repl//设置复制用户
report_script=/usr/local/send_report //设置发生切换后发送的报警的脚本
secondary_check_script=/usr/local/bin/masterha_secondary_check -s 192.168.1.11 -s 192.168.1.12 #实现多路由监测Master的可用性
shutdown_script="" //设置故障发生后关闭故障主机脚本(该脚本的主要作用是关闭主机放在发生脑裂,这里没有使用)
ssh_user=root //设置ssh的登录用户名 [server1]
hostname=192.168.1.11
port= [server2]
candidate_master= //设置为候选master,如果设置该参数以后,发生主从切换以后将会将此从库提升为主库,即使这个主库不是集群中事件最新的slave
check_repl_delay= //默认情况下如果一个slave落后master 100M的relay logs的话,MHA将不会选择该slave作为一个新的master,因为对于这个slave的恢复需要花费很长时间,通过设置check_repl_delay=0,MHA触发切换在选择一个新的master的时候将会忽略复制延时,这个参数对于设置了candidate_master=1的主机非常有用,因为这个候选主在切换的过程中一定是新的master hostname=192.168.1.12
port= [server3]
hostname=192.168.1.13
port=
no_master=

3.设置relay log的清除方式(在每个slave节点上):

[root@slave-db1 ~]# mysql -e 'set global relay_log_purge=0'
[root@slave-db2 ~]# mysql -e 'set global relay_log_purge=0'

注意:

MHA在发生切换的过程中,从库的恢复过程中依赖于relay log的相关信息,所以这里要将relay log的自动清除设置为OFF,采用手动清除relay log的方式。在默认情况下,从服务器上的中继日志会在SQL线程执行完毕后被自动删除。但是在MHA环境中,这些中继日志在恢复其他从服务器时可能会被用到,因此需要禁用中继日志的自动删除功能。定期清除中继日志需要考虑到复制延时的问题。在ext3的文件系统下,删除大的文件需要一定的时间,会导致严重的复制延时。为了避免复制延时,需要暂时为中继日志创建硬链接,因为在linux系统中通过硬链接删除大文件速度会很快。(在mysql数据库中,删除大表时,通常也采用建立硬链接的方式)

MHA节点中包含了pure_relay_logs命令工具,它可以为中继日志创建硬链接,执行SET GLOBAL relay_log_purge=1,等待几秒钟以便SQL线程切换到新的中继日志,再执行SET GLOBAL relay_log_purge=0。

pure_relay_logs脚本参数如下所示:

--user mysql                      用户名
--password mysql 密码
--port 端口号
--workdir 指定创建relay log的硬链接的位置,默认是/var/tmp,由于系统不同分区创建硬链接文件会失败,故需要执行硬链接具体位置,成功执行脚本后,硬链接的中继日志文件被删除
--disable_relay_log_purge 默认情况下,如果relay_log_purge=,脚本会什么都不清理,自动退出,通过设定这个参数,当relay_log_purge=1的情况下会将relay_log_purge设置为0。清理relay log之后,最后将参数设置为OFF。

设置定期清理relay脚本(两台slave服务器)

[root@192.168.1.12 ~]# cat purge_relay_log.sh
#!/bin/bash
user=root
passwd=
port=
log_dir='/data/masterha/log'
work_dir='/Data/apps'
purge='/usr/local/bin/purge_relay_logs' if [ ! -d $log_dir ]
then
mkdir $log_dir -p
fi $purge --user=$user --password=$passwd --disable_relay_log_purge --port=$port --workdir=$work_dir >> $log_dir/purge_relay_logs.log >&

添加执行权限,并添加到crontab定期执行,另外一台相同操作

[root@slave-db1 ~]#chmod +x purge_relay_log.sh
[root@slave-db1 ~]#crontab -l
* * * /bin/bash /root/purge_relay_log.sh

purge_relay_logs脚本删除中继日志不会阻塞SQL线程。下面我们手动执行看看什么情况。

[root@slave-db1 ~]#  purge_relay_logs --user=root --password= --port=  --host=192.168.1.12 -disable_relay_log_purge --workdir=/Data/apps/
-- ::: purge_relay_logs script started.
Found relay_log.info: /Data/apps/mysql-5.6./data/relay-log.info
Opening /Data/apps/mysql-5.6./data/relay-log. ..
Opening /Data/apps/mysql-5.6./data/relay-log. ..
Executing SET GLOBAL relay_log_purge=; FLUSH LOGS; sleeping a few seconds so that SQL thread can delete older relay log files (if it keeps up); SET GLOBAL relay_log_purge=; .. ok.
-- ::: All relay log purging operations succeeded.

4.由于自带的脚本master_ip_failover有些问题需要自行修改,修改内容如下:

#!/bin/env perl
use strict;
use warnings FATAL => 'all';
use Getopt::Long;
my (
$command, $ssh_user, $orig_master_host, $orig_master_ip,
$orig_master_port, $new_master_host, $new_master_ip, $new_master_port
);
my $vip = '192.168.1.250/24'; # Virtual IP
my $gateway = '192.168.1.1'; #Gateway IP
my $interface = 'eth0';
my $key = "";
my $ssh_start_vip = "/sbin/ifconfig $interface:$key $vip;/sbin/arping -I $interface -c 3 -s $vip $gateway >/dev/null 2>&1";
my $ssh_stop_vip = "/sbin/ifconfig $interface:$key down";
GetOptions(
'command=s' => \$command,
'ssh_user=s' => \$ssh_user,
'orig_master_host=s' => \$orig_master_host,
'orig_master_ip=s' => \$orig_master_ip,
'orig_master_port=i' => \$orig_master_port,
'new_master_host=s' => \$new_master_host,
'new_master_ip=s' => \$new_master_ip,
'new_master_port=i' => \$new_master_port,
);
exit &main();
sub main {
print "\n\nIN SCRIPT TEST====$ssh_stop_vip==$ssh_start_vip===\n\n";
if ( $command eq "stop" || $command eq "stopssh" ) {
#$orig_master_host, $orig_master_ip, $orig_master_port are passed.
# If you manage master ip address at global catalog database,
# invalidate orig_master_ip here.
my $exit_code = ;
eval {
print "Disabling the VIP on old master: $orig_master_host \n";
&stop_vip();
$exit_code = ;
};
if ($@) {
warn "Got Error: $@\n";
exit $exit_code;
}
exit $exit_code;
}
elsif ( $command eq "start" ) {
# all arguments are passed.
# If you manage master ip address at global catalog database,
# activate new_master_ip here.
# You can also grant write access (create user, set read_only=, etc) here.
my $exit_code = ;
eval {
print "Enabling the VIP - $vip on the new master - $new_master_host \n";
&start_vip();
$exit_code = ;
};
if ($@) {
warn $@;
exit $exit_code;
}
exit $exit_code;
}
elsif ( $command eq "status" ) {
print "Checking the Status of the script.. OK \n";
`ssh $ssh_user\@$orig_master_host \" $ssh_start_vip \"`;
exit ;
}
else {
&usage();
exit ;
}
}
# A simple system call that enable the VIP on the new master
sub start_vip() {
`ssh $ssh_user\@$new_master_host \" $ssh_start_vip \"`;
}
# A simple system call that disable the VIP on the old_master
sub stop_vip() {
`ssh $ssh_user\@$orig_master_host \" $ssh_stop_vip \"`;
}
sub usage {
print
"Usage: master_ip_failover --command=start|stop|stopssh|status --orig_master_host=host --orig_master_ip=ip --orig_master_port=port --new_master_host=host --new_master_ip=ip --new_master_port=port\n";
}

5.检查SSH配置

[root@mha-monitor ~]# masterha_check_ssh --conf=/etc/masterha/app1.cnf
Wed Jan :: - [warning] Global configuration file /etc/masterha_default.cnf not found. Skipping.
Wed Jan :: - [info] Reading application default configuration from /etc/masterha/app1.cnf..
Wed Jan :: - [info] Reading server configuration from /etc/masterha/app1.cnf..
Wed Jan :: - [info] Starting SSH connection tests..
Wed Jan :: - [debug]
Wed Jan :: - [debug] Connecting via SSH from root@192.168.1.11(192.168.1.11:) to root@192.168.1.12(192.168.1.12:)..
Wed Jan :: - [debug] ok.
Wed Jan :: - [debug] Connecting via SSH from root@192.168.1.11(192.168.1.11:) to root@192.168.1.13(192.168.1.13:)..
Wed Jan :: - [debug] ok.
Wed Jan :: - [debug]
Wed Jan :: - [debug] Connecting via SSH from root@192.168.1.12(192.168.1.12:) to root@192.168.1.11(192.168.1.11:)..
Wed Jan :: - [debug] ok.
Wed Jan :: - [debug] Connecting via SSH from root@192.168.1.12(192.168.1.12:) to root@192.168.1.13(192.168.1.13:)..
Wed Jan :: - [debug] ok.
Wed Jan :: - [debug]
Wed Jan :: - [debug] Connecting via SSH from root@192.168.1.13(192.168.1.13:) to root@192.168.1.11(192.168.1.11:)..
Wed Jan :: - [debug] ok.
Wed Jan :: - [debug] Connecting via SSH from root@192.168.1.13(192.168.1.13:) to root@192.168.1.12(192.168.1.12:)..
Wed Jan :: - [debug] ok.
Wed Jan :: - [info] All SSH connection tests passed successfully.

可以看见各个节点ssh验证都是ok的。

6.检查整个复制环境状况。

[root@mha-monitor ~]#  masterha_check_repl --conf=/etc/masterha/app1.cnf
.....
Checking the Status of the script.. OK
Wed Jan :: - [info] OK.
Wed Jan :: - [warning] shutdown_script is not defined.
Wed Jan :: - [info] Got exit code (Not master dead). MySQL Replication Health is OK.

7.开启MHA Manager监控

[root@mha-monitor ~]# nohup masterha_manager --conf=/etc/masterha/app1.cnf --remove_dead_master_conf --ignore_last_failover /var/log/masterha/app1/manager.log >& &
[]
[root@mha-monitor ~]# nohup: 忽略输入并把输出追加到"nohup.out"
[root@mha-monitor ~]# jobs
[]+ Running nohup masterha_manager --conf=/etc/masterha/app1.cnf --remove_dead_master_conf --ignore_last_failover /var/log/masterha/app1/manager.log >& &

启动参数介绍:

--remove_dead_master_conf       该参数代表当发生主从切换后,老的主库的ip将会从配置文件中移除。
--manger_log 日志存放位置
--ignore_last_failover 在缺省情况下,如果MHA检测到连续发生宕机,且两次宕机间隔不足8小时的话,则不会进行Failover,之所以这样限制是为了避免ping-pong效应。该参数代表忽略上次MHA触发切换产生的文件,默认情况下,MHA发生切换后会在日志目录,也就是上面我设置的/data产生app1.failover.complete文件,下次再次切换的时候如果发现该目录下存在该文件将不允许触发切换,除非在第一次切换后收到删除该文件,为了方便,这里设置为--ignore_last_failover。

8.查看MHA Manager监控状态:

[root@mha-monitor ~]# masterha_check_status --conf=/etc/masterha/app1.cnf
app1 (pid:) is running(:PING_OK), master:192.168.1.11

可以看见已经在监控了,而且master的主机为192.168.1.11

七、故障测试

1.模拟MySQL故障,查看VIP漂移和MySQL自动切换情况

注:切换后MHA服务会自动停止,官方给出的原因是

Running MHA Manager from daemontools
Currently MHA Manager process does not run as a daemon. If failover completed successfully or the master process was killed by accident,
the manager stops working. To run as a daemon, daemontool. or any external daemon program can be used.
Here is an example to run from daemontools.

master上停止mysql服务器

[root@master-db1 ~]# service mysqld stop
Shutting down MySQL..... [确定]  

在manager上查看MHA服务和切换日志

[root@mha-monitor ~]# masterha_check_status --conf=/etc/masterha/app1.cnf
app1 is stopped(:NOT_RUNNING).
[]+ Done nohup masterha_manager --conf=/etc/masterha/app1.cnf --remove_dead_master_conf --ignore_last_failover /var/log/masterha/app1/manager.log >& [root@mha-monitor ~]# tail - /var/log/masterha/app1/manager.log ----- Failover Report ----- app1: MySQL Master failover 192.168.1.11(192.168.1.11:) to 192.168.1.12(192.168.1.12:) succeeded Master 192.168.1.11(192.168.1.11:) is down! Check MHA Manager logs at mha-monitor:/var/log/masterha/app1/manager.log for details. Started automated(non-interactive) failover.
Invalidated master IP address on 192.168.1.11(192.168.1.11:)
The latest slave 192.168.1.12(192.168.1.12:) has all relay logs for recovery.
Selected 192.168.1.12(192.168.1.12:) as a new master.
192.168.1.12(192.168.1.12:): OK: Applying all logs succeeded.
192.168.1.12(192.168.1.12:): OK: Activated master IP address.
192.168.1.13(192.168.1.13:): This host has the latest relay log events.
Generating relay diff files from the latest slave succeeded.
192.168.1.13(192.168.1.13:): OK: Applying all logs succeeded. Slave started, replicating from 192.168.1.12(192.168.1.12:)
192.168.1.12(192.168.1.12:): Resetting slave info succeeded.
Master failover to 192.168.1.12(192.168.1.12:) completed successfully.

看到最后的Master failover to 192.168.1.12(192.168.1.12:3306) completed successfully.说明备选master现在已经上位了。

从上面的输出可以看出整个MHA的切换过程,共包括以下的步骤:

1.配置文件检查阶段,这个阶段会检查整个集群配置文件配置
2.宕机的master处理,这个阶段包括虚拟ip摘除操作,主机关机操作(这个我这里还没有实现,需要研究)
3.复制dead maste和最新slave相差的relay log,并保存到MHA Manger具体的目录下
4.识别含有最新更新的slave
5.应用从master保存的二进制日志事件(binlog events)
6.提升一个slave为新的master进行复制
7.使其他的slave连接新的master进行复制

在slave-db2上查看主从复制情况(192.168.1.13)

mysql> show slave status\G;ges;
*************************** . row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 192.168.1.12
Master_User: repl
Master_Port:
Connect_Retry:
Master_Log_File: mysql-bin.
Read_Master_Log_Pos:
Relay_Log_File: relay-log.
Relay_Log_Pos:
Relay_Master_Log_File: mysql-bin.
Slave_IO_Running: Yes
Slave_SQL_Running: Yes

启动MHA Manger监控,查看集群里面现在谁是master

2.将MySQL故障服务器重新加入MHA环境步骤

.把故障服务器设为新的slave
.重新启动MHA manager
.查看MHA状态

3在线手动切换主从

在许多情况下, 需要将现有的主服务器迁移到另外一台服务器上。 比如主服务器硬件故障,RAID 控制卡需要重建,将主服务器移到性能更好的服务器上等等。维护主服务器引起性能下降, 导致停机时间至少无法写入数据。 另外, 阻塞或杀掉当前运行的会话会导致主主之间数据不一致的问题发生。 MHA 提供快速切换和优雅的阻塞写入,这个切换过程只需要 0.5-2s 的时间,这段时间内数据是无法写入的。在很多情况下,0.5-2s 的阻塞写入是可以接受的。因此切换主服务器不需要计划分配维护时间窗口。

MHA在线切换的大概过程:

.检测复制设置和确定当前主服务器
.确定新的主服务器
.阻塞写入到当前主服务器
.等待所有从服务器赶上复制
.授予写入到新的主服务器
.重新设置从服务器

注意,在线切换的时候应用架构需要考虑以下两个问题

.自动识别master和slave的问题(master的机器可能会切换),如果采用了vip的方式,基本可以解决这个问题。
.负载均衡的问题(可以定义大概的读写比例,每台机器可承担的负载比例,当有机器离开集群时,需要考虑这个问题)

在线切换步骤如下:

.原master出现故障
masterha_stop --conf=/etc/masterha/app1.cnf #停止
masterha_master_switch --master_state=dead --conf=/etc/masterha/app1.cnf --dead_master_host=192.168.1.11 --dead_master_port= --new_master_host=192.168.1.12 --new_master_port= --ignore_last_failover .把原master变为slave切换
masterha_master_switch --conf=/etc/masterha/app1.cnf --master_state=alive --new_master_host=192.168.1.12 --new_master_port= --orig_master_is_new_slave

注意:由于在线进行切换需要调用到master_ip_online_change这个脚本,但是由于该脚本不完整,需要自己进行相应的修改,我google到后发现还是有问题,脚本中new_master_password这个变量获取不到,导致在线切换失败,所以进行了相关的硬编码,直接把mysql的root用户密码赋值给变量new_master_password,如果有哪位大牛知道原因,请指点指点。这个脚本还可以管理vip。下面贴出脚本:

#!/usr/bin/env perl

#  Copyright (C)  DeNA Co.,Ltd.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc.,
# Franklin Street, Fifth Floor, Boston, MA - USA ## Note: This is a sample script and is not complete. Modify the script based on your environment. use strict;
use warnings FATAL => 'all'; use Getopt::Long;
use MHA::DBHelper;
use MHA::NodeUtil;
use Time::HiRes qw( sleep gettimeofday tv_interval );
use Data::Dumper; my $_tstart;
my $_running_interval = 0.1;
my (
$command, $orig_master_host, $orig_master_ip,
$orig_master_port, $orig_master_user,
$new_master_host, $new_master_ip, $new_master_port,
$new_master_user,
); my $vip = '192.168.0.88/24'; # Virtual IP
my $key = "";
my $ssh_start_vip = "/sbin/ifconfig eth1:$key $vip";
my $ssh_stop_vip = "/sbin/ifconfig eth1:$key down";
my $ssh_user = "root";
my $new_master_password='';
my $orig_master_password='';
GetOptions(
'command=s' => \$command,
#'ssh_user=s' => \$ssh_user,
'orig_master_host=s' => \$orig_master_host,
'orig_master_ip=s' => \$orig_master_ip,
'orig_master_port=i' => \$orig_master_port,
'orig_master_user=s' => \$orig_master_user,
#'orig_master_password=s' => \$orig_master_password,
'new_master_host=s' => \$new_master_host,
'new_master_ip=s' => \$new_master_ip,
'new_master_port=i' => \$new_master_port,
'new_master_user=s' => \$new_master_user,
#'new_master_password=s' => \$new_master_password,
); exit &main(); sub current_time_us {
my ( $sec, $microsec ) = gettimeofday();
my $curdate = localtime($sec);
return $curdate . " " . sprintf( "%06d", $microsec );
} sub sleep_until {
my $elapsed = tv_interval($_tstart);
if ( $_running_interval > $elapsed ) {
sleep( $_running_interval - $elapsed );
}
} sub get_threads_util {
my $dbh = shift;
my $my_connection_id = shift;
my $running_time_threshold = shift;
my $type = shift;
$running_time_threshold = unless ($running_time_threshold);
$type = unless ($type);
my @threads; my $sth = $dbh->prepare("SHOW PROCESSLIST");
$sth->execute(); while ( my $ref = $sth->fetchrow_hashref() ) {
my $id = $ref->{Id};
my $user = $ref->{User};
my $host = $ref->{Host};
my $command = $ref->{Command};
my $state = $ref->{State};
my $query_time = $ref->{Time};
my $info = $ref->{Info};
$info =~ s/^\s*(.*?)\s*$/$/ if defined($info);
next if ( $my_connection_id == $id );
next if ( defined($query_time) && $query_time < $running_time_threshold );
next if ( defined($command) && $command eq "Binlog Dump" );
next if ( defined($user) && $user eq "system user" );
next
if ( defined($command)
&& $command eq "Sleep"
&& defined($query_time)
&& $query_time >= ); if ( $type >= ) {
next if ( defined($command) && $command eq "Sleep" );
next if ( defined($command) && $command eq "Connect" );
} if ( $type >= ) {
next if ( defined($info) && $info =~ m/^select/i );
next if ( defined($info) && $info =~ m/^show/i );
} push @threads, $ref;
}
return @threads;
} sub main {
if ( $command eq "stop" ) {
## Gracefully killing connections on the current master
# . Set read_only= on the new master
# . DROP USER so that no app user can establish new connections
# . Set read_only= on the current master
# . Kill current queries
# * Any database access failure will result in script die.
my $exit_code = ;
eval {
## Setting read_only= on the new master (to avoid accident)
my $new_master_handler = new MHA::DBHelper(); # args: hostname, port, user, password, raise_error(die_on_error)_or_not
$new_master_handler->connect( $new_master_ip, $new_master_port,
$new_master_user, $new_master_password, );
print current_time_us() . " Set read_only on the new master.. ";
$new_master_handler->enable_read_only();
if ( $new_master_handler->is_read_only() ) {
print "ok.\n";
}
else {
die "Failed!\n";
}
$new_master_handler->disconnect(); # Connecting to the orig master, die if any database error happens
my $orig_master_handler = new MHA::DBHelper();
$orig_master_handler->connect( $orig_master_ip, $orig_master_port,
$orig_master_user, $orig_master_password, ); ## Drop application user so that nobody can connect. Disabling per-session binlog beforehand
#$orig_master_handler->disable_log_bin_local();
#print current_time_us() . " Drpping app user on the orig master..\n";
#FIXME_xxx_drop_app_user($orig_master_handler); ## Waiting for N * milliseconds so that current connections can exit
my $time_until_read_only = ;
$_tstart = [gettimeofday];
my @threads = get_threads_util( $orig_master_handler->{dbh},
$orig_master_handler->{connection_id} );
while ( $time_until_read_only > && $#threads >= ) {
if ( $time_until_read_only % == ) {
printf
"%s Waiting all running %d threads are disconnected.. (max %d milliseconds)\n",
current_time_us(), $#threads + , $time_until_read_only * ;
if ( $#threads < ) {
print Data::Dumper->new( [$_] )->Indent()->Terse()->Dump . "\n"
foreach (@threads);
}
}
sleep_until();
$_tstart = [gettimeofday];
$time_until_read_only--;
@threads = get_threads_util( $orig_master_handler->{dbh},
$orig_master_handler->{connection_id} );
} ## Setting read_only= on the current master so that nobody(except SUPER) can write
print current_time_us() . " Set read_only=1 on the orig master.. ";
$orig_master_handler->enable_read_only();
if ( $orig_master_handler->is_read_only() ) {
print "ok.\n";
}
else {
die "Failed!\n";
} ## Waiting for M * milliseconds so that current update queries can complete
my $time_until_kill_threads = ;
@threads = get_threads_util( $orig_master_handler->{dbh},
$orig_master_handler->{connection_id} );
while ( $time_until_kill_threads > && $#threads >= ) {
if ( $time_until_kill_threads % == ) {
printf
"%s Waiting all running %d queries are disconnected.. (max %d milliseconds)\n",
current_time_us(), $#threads + , $time_until_kill_threads * ;
if ( $#threads < ) {
print Data::Dumper->new( [$_] )->Indent()->Terse()->Dump . "\n"
foreach (@threads);
}
}
sleep_until();
$_tstart = [gettimeofday];
$time_until_kill_threads--;
@threads = get_threads_util( $orig_master_handler->{dbh},
$orig_master_handler->{connection_id} );
} print "Disabling the VIP on old master: $orig_master_host \n";
&stop_vip(); ## Terminating all threads
print current_time_us() . " Killing all application threads..\n";
$orig_master_handler->kill_threads(@threads) if ( $#threads >= );
print current_time_us() . " done.\n";
#$orig_master_handler->enable_log_bin_local();
$orig_master_handler->disconnect(); ## After finishing the script, MHA executes FLUSH TABLES WITH READ LOCK
$exit_code = ;
};
if ($@) {
warn "Got Error: $@\n";
exit $exit_code;
}
exit $exit_code;
}
elsif ( $command eq "start" ) {
## Activating master ip on the new master
# . Create app user with write privileges
# . Moving backup script if needed
# . Register new master's ip to the catalog database # We don't return error even though activating updatable accounts/ip failed so that we don't interrupt slaves' recovery.
# If exit code is or , MHA does not abort
my $exit_code = ;
eval {
my $new_master_handler = new MHA::DBHelper(); # args: hostname, port, user, password, raise_error_or_not
$new_master_handler->connect( $new_master_ip, $new_master_port,
$new_master_user, $new_master_password, ); ## Set read_only= on the new master
#$new_master_handler->disable_log_bin_local();
print current_time_us() . " Set read_only=0 on the new master.\n";
$new_master_handler->disable_read_only(); ## Creating an app user on the new master
#print current_time_us() . " Creating app user on the new master..\n";
#FIXME_xxx_create_app_user($new_master_handler);
#$new_master_handler->enable_log_bin_local();
$new_master_handler->disconnect(); ## Update master ip on the catalog database, etc
print "Enabling the VIP - $vip on the new master - $new_master_host \n";
&start_vip();
$exit_code = ;
};
if ($@) {
warn "Got Error: $@\n";
exit $exit_code;
}
exit $exit_code;
}
elsif ( $command eq "status" ) { # do nothing
exit ;
}
else {
&usage();
exit ;
}
} # A simple system call that enable the VIP on the new master
sub start_vip() {
`ssh $ssh_user\@$new_master_host \" $ssh_start_vip \"`;
}
# A simple system call that disable the VIP on the old_master
sub stop_vip() {
`ssh $ssh_user\@$orig_master_host \" $ssh_stop_vip \"`;
} sub usage {
print
"Usage: master_ip_online_change --command=start|stop|status --orig_master_host=host --orig_master_ip=ip --orig_master_port=port --new_master_host=host --new_master_ip=ip --new_master_port=port\n";
die;
}

为了保证数据完全一致性,在最快的时间内完成切换,MHA的在线切换必须满足以下条件才会切换成功,否则会切换失败。

.所有slave的IO线程都在运行
.所有slave的SQL线程都在运行
.所有的show slave status的输出中Seconds_Behind_Master参数小于或者等于running_updates_limit秒,如果在切换过程中不指定running_updates_limit,那么默认情况下running_updates_limit为1秒。
.在master端,通过show processlist输出,没有一个更新花费的时间大于running_updates_limit秒。

最后补充一下邮件发送脚本send_report 

#!/usr/bin/perl

#  Copyright (C)  DeNA Co.,Ltd.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc.,
# Franklin Street, Fifth Floor, Boston, MA - USA ## Note: This is a sample script and is not complete. Modify the script based on your environment. use strict;
use warnings FATAL => 'all';
use Mail::Sender;
use Getopt::Long; #new_master_host and new_slave_hosts are set only when recovering master succeeded
my ( $dead_master_host, $new_master_host, $new_slave_hosts, $subject, $body );
my $smtp='smtp.163.com';
my $mail_from='xxxx';
my $mail_user='xxxxx';
my $mail_pass='xxxxx';
my $mail_to=['xxxx','xxxx'];
GetOptions(
'orig_master_host=s' => \$dead_master_host,
'new_master_host=s' => \$new_master_host,
'new_slave_hosts=s' => \$new_slave_hosts,
'subject=s' => \$subject,
'body=s' => \$body,
); mailToContacts($smtp,$mail_from,$mail_user,$mail_pass,$mail_to,$subject,$body); sub mailToContacts {
my ( $smtp, $mail_from, $user, $passwd, $mail_to, $subject, $msg ) = @_;
open my $DEBUG, "> /tmp/monitormail.log"
or die "Can't open the debug file:$!\n";
my $sender = new Mail::Sender {
ctype => 'text/plain; charset=utf-8',
encoding => 'utf-8',
smtp => $smtp,
from => $mail_from,
auth => 'LOGIN',
TLS_allowed => '',
authid => $user,
authpwd => $passwd,
to => $mail_to,
subject => $subject,
debug => $DEBUG
}; $sender->MailMsg(
{ msg => $msg,
debug => $DEBUG
}
) or print $Mail::Sender::Error;
return ;
} # Do whatever you want here exit ;

总结:

目前高可用方案可以一定程度上实现数据库的高可用,比如前面文章介绍的MMMheartbeat+drbdCluster等。还有percona的Galera Cluster等。这些高可用软件各有优劣。在进行高可用方案选择时,主要是看业务还有对数据一致性方面的要求。最后出于对数据库的高可用和数据一致性的要求,推荐使用MHA架构。

转载自:https://www.cnblogs.com/gomysql/p/3675429.html

上一篇:&和&&的一点区别


下一篇:day05-java-(循环问题,数组)