MHA high-availability configuration (experimental operation, and failure simulation)

1. Overview of MHA

  • MHA (Master High Availability) is currently a relatively mature solution for MySQL high availability.
  • The emergence of MHA is to solve the problem of MySQL single point of failure.
  • MHA is a relatively mature MySQL high-availability solution developed by Japanese yoshinorim (formerly at DeNA and now at FaceBook). MHA can achieve failover within 30 seconds.
  • MHA can guarantee data consistency as much as possible during failover. In order to achieve high availability in the true sense.
  • Taobao is also developing a similar product, TMHA, which currently supports one master and one follower.

2. MHA composition

Insert picture description here

1. MHA Node (Data Node)

It is deployed on all servers running MySQL, whether it is master or slave. There are three main functions.

1、保存二进制日志

       如果能够访问故障master,会拷贝master的二进制日志

 2、应用差异中继日志

      从拥有最新数据的slave上生成差异中继日志,然后应用差异日志。

 3、清除中继日志

      在不停止SQL线程的情况下删除中继日志

2. MHA Manager (management node)

  • MHA Manager can be deployed on a separate machine to manage multiple master-slave clusters, or it can be deployed on one slave node.
  • MHA Manager will periodically detect the master node in the cluster. When the master fails, it can automatically promote the slave with the latest data to the new master, and then redirect all other slaves to the new master. The entire failover process is completely transparent to the corresponding procedures.

3. Features and advantages of MHA

1. Features

  • During the automatic failover process, MHA tries to save the binary log from the down main server to ensure that data is not lost to the greatest extent.
  • Using semi-synchronous replication can greatly reduce the risk of data loss.
  • Currently, MHA supports a one-master and multiple-slave architecture, with at least three servers, that is, one master and two slaves.

2. Advantages

1. Fast failover
In a master-slave replication cluster, as long as the slave database has no delay in replication, MHA can usually achieve failover within a few seconds. Check the master failure within 9-10 seconds, you can choose to shut down the master within 7-10 seconds to avoid split brain, within a few seconds, the difference relay log (relay log) is applied to the new master, so the total downtime The machine time is usually 10-30 seconds. After restoring the new master, MHA restores the remaining slaves in parallel. Even if there are tens of thousands of slaves, it will not affect the recovery time of the master.

DeNA uses MHA in more than 150 MySQL (mainly 5.0/5.1 versions) master-slave environment. When the mater fails, MHA completes the failover within 4 seconds. In traditional active/passive cluster solutions, it is impossible to complete failover within 4 seconds.

2. Master failure will not cause data inconsistency

When the current master fails, MHA automatically recognizes the difference in relay log between slaves and applies it to all slaves. In this way, all the salves can be kept in sync, as long as all the slaves are alive. Used together with Semi-Synchronous Replication, (almost) can guarantee no data loss.

3. No need to modify the current MySQL settings

One of the important principles of MHA's design is to be as simple and easy to use as possible. MHA works in the traditional master-slave replication environment of MySQL version 5.0 and later. Compared with other high-availability solutions, MHA does not need to change the MySQL deployment environment. MHA is suitable for asynchronous and semi-synchronous master-slave replication.

Start/stop/upgrade/downgrade/install/uninstall MHA does not need to change (package expansion start/stop) MySQL replication. When you need to upgrade MHA to a new version, you do not need to stop MySQL, just replace to the new version of MHA, and then restart MHA Manager.

MHA runs on the native version starting with MySQL 5.0. Some other MySQL high-availability solutions require specific versions (such as MySQL cluster, MySQL with global transaction ID, etc.), but applications are not migrated only for the high availability of the master. In most cases, older MySQL applications have been deployed, and I don't want to spend too much time migrating to a different storage engine or newer cutting-edge release just to achieve the high availability of the Master. MHA works on the native version of MySQL 5.0/5.1/5.5, so there is no need to migrate.

4. No need to increase a large number of servers

MHA is composed of MHA Manager and MHA Node. MHA Node runs on a MySQL server that requires failover/recovery, so no additional servers are required. MHA Manager runs on a specific server, so you need to add one (2 for high availability), but MHA Manager can monitor a large number (even hundreds) of individual masters, so there is no need to add a large number of servers. It is possible to run MHA Manager even on a slave. In summary, the realization of MHA does not need to add a large number of additional services.

5. No performance degradation

MHA is suitable for asynchronous or semi-synchronous MySQL replication. When monitoring the master, MHA only sends a ping packet every few seconds (the default is 3 seconds), and does not send re-queries. You can get as fast performance as native MySQL replication.

6. Applicable to any storage engine

MHA can run on storage engines that only need MySQL replication to run, and it is not limited to InnoDB. Even in a traditional MyISAM engine environment that is not easy to migrate, MHA can be used.

Four. MHA working principle

  • 1. Save binary log events from the downtime and crashed master (binlog events);

  • 2. Identify the slave with the latest update;

  • 3. Apply the differential relay log to other slaves;

  • 4. Apply the binary log events saved from the master (binlog events);

  • 5. Promote a slave as a new master;

  • 6. Use other slaves to connect to the new master for replication.

  • When the master fails, the position of the masterbinlog read by the I/O thread between the slaves is compared, and the closest slave is selected as the latest slave. Other slaves generate differential relay logs by comparing with the latest slave. Apply the binlog saved from the master on the latest slave, and at the same time promote the latest slave to the master. Finally, apply the corresponding differential relay log on other slaves and start copying from the new master.

  • When MHA implements the master failover process, the MHA Node will try to access the failed master (via SSH), and if it can be accessed (not a hardware failure, such as InnoDB data file damage, etc.), the binary file will be saved to ensure that data is not lost to the greatest extent possible . The use of MHA and semi-synchronous replication together will greatly reduce the risk of data loss.

Five. MHA build

Experimental ideas:
1. MHA architecture

  • (1) Database installation
  • (2) One master and two slaves
  • (3) MHA construction

2. Failure simulation

  • (1) The main library fails
  • (2) The alternative main library becomes the main library
  • (3) Meta-failure master database recovery rejoins the MHA to become a slave database
MHA manager node server CentOS7.4 (64-bit) manager/192.168.80.13, install MHA node and manager components
Master node server CentOS7.4 (64 bit) mysql1/192.168.80.10, install mysql5.7, MHA node components
Slave1 node server CentOS7.4 (64-bit) mysql2/192.168.80.11, install mysql5.7, MHA node components
Slave2 node server CentOS7.4 (64 bit) mysql3/192.168.80.12, install mysql5.7, MHA node components
1.把所有服务器防火墙关闭
systemctl stop firewalld
systemctl disable firewalld
setenforce 0
2.确认Master、Slave1、Slave2 节点上安装 mysql5.7
3.修改 Master、Slave1、Slave2 节点的主机名(方便识别也可以不变更)
hostnamectl set-hostname Mysql1
hostnamectl set-hostname Mysql2
hostnamectl set-hostname Mysql3

Insert picture description here

4.修改 Master、Slave1、Slave2 节点的 Mysql主配置文件/etc/my.cnf 
##Master 节点##
vim /etc/my.cnf
[mysqld]
server-id = 1
log_bin = master-bin
log-slave-updates = true

systemctl restart mysqld

Insert picture description here

##Slave1、Slave2 节点##
vim /etc/my.cnf
server-id = 2 						#三台服务器的 server-id 不能一样
log_bin = master-bin
relay-log = relay-log-bin
relay-log-index = slave-relay-bin.index
systemctl restart mysqld

Insert picture description here

5.在 Master、Slave1、Slave2 节点上都创建两个软链接
ln -s /usr/local/mysql/bin/mysql /usr/sbin/
ln -s /usr/local/mysql/bin/mysqlbinlog /usr/sbin/

Insert picture description here

6.配置 mysql 一主两从
(1)所有数据库节点进行 mysql 授权
mysql -uroot -p
grant replication slave on *.* to 'myslave'@'192.168.23.%' identified by '123456';		#从数据库同步使用
grant all privileges on *.* to 'mha'@'192.168.23.%' identified by 'manager';		#manager 使用

grant all privileges on *.* to 'mha'@'Mysql1' identified by 'manager';				#防止从库通过主机名连接不上主库
grant all privileges on *.* to 'mha'@'Mysql2' identified by 'manager';
grant all privileges on *.* to 'mha'@'Mysql3' identified by 'manager';
flush privileges;

Insert picture description here
Insert picture description here

(2)在 Master 节点查看二进制文件和同步点
show master status;
+-------------------+----------+--------------+------------------+-------------------+
| File              | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+-------------------+----------+--------------+------------------+-------------------+
| master-bin.000001 |     1745 |              |                  |                   |
+-------------------+----------+--------------+------------------+-------------------+

Insert picture description here

(3)在 Slave1、Slave2 节点执行同步操作
change master to master_host='192.168.23.128',master_user='myslave',master_password='123456',master_log_file='master-bin.000001',master_log_pos=1745; 

start slave;

Insert picture description here

(4)在 Slave1、Slave2 节点查看数据同步结果
show slave status\G		
//确保 IO 和 SQL 线程都是 Yes,代表同步正常。
Slave_IO_Running: Yes
Slave_SQL_Running: Yes

Insert picture description here

(5)两个从库必须设置为只读模式:
set global read_only=1;

Insert picture description here

(6)插入数据测试数据库同步
##在 Master 主库插创建一个库,测试是否同步##
create database test_db;
use test_db;
create table test(id int);
insert into test(id) values (1);

Insert picture description here
7. Install MHA software

(1)所有服务器上都安装 MHA 依赖的环境,首先安装 epel 源
yum install epel-release --nogpgcheck -y

yum install -y perl-DBD-MySQL \
perl-Config-Tiny \
perl-Log-Dispatch \
perl-Parallel-ForkManager \
perl-ExtUtils-CBuilder \
perl-ExtUtils-MakeMaker \
perl-CPAN

Insert picture description here

(2)安装 MHA 软件包,先在所有服务器上必须先安装 node 组件
对于每个操作系统版本不一样,这里 CentOS7.4 必须选择 0.57 版本。
在所有服务器上必须先安装 node 组件,最后在 MHA-manager 节点上安装 manager 组件,因为 manager 依赖 node 组件。
cd /opt
tar zxvf mha4mysql-node-0.57.tar.gz
cd mha4mysql-node-0.57
perl Makefile.PL
make && make install

Insert picture description here

(3)在 MHA manager 节点上安装 manager 组件
cd /opt
tar zxvf mha4mysql-manager-0.57.tar.gz
cd mha4mysql-manager-0.57
perl Makefile.PL
make && make install
-------------------------------------------------------------------------------------
#manager 组件安装后在/usr/local/bin 下面会生成几个工具,主要包括以下几个:
masterha_check_ssh 检查 MHA 的 SSH 配置状况
masterha_check_repl 检查 MySQL 复制状况
masterha_manger 启动 manager的脚本
masterha_check_status 检测当前 MHA 运行状态
masterha_master_monitor 检测 master 是否宕机
masterha_master_switch 控制故障转移(自动或者手动)
masterha_conf_host 添加或删除配置的 server 信息
masterha_stop  关闭manager

#node 组件安装后也会在/usr/local/bin 下面会生成几个脚本(这些工具通常由 MHAManager 的脚本触发,无需人为操作)主要如下:
save_binary_logs 保存和复制 master 的二进制日志
apply_diff_relay_logs 识别差异的中继日志事件并将其差异的事件应用于其他的 slave
filter_mysqlbinlog 去除不必要的 ROLLBACK 事件(MHA 已不再使用这个工具)
purge_relay_logs 清除中继日志(不会阻塞 SQL 线程)

Insert picture description here

8.在所有服务器上配置无密码认证
(1)在 manager 节点上配置到所有数据库节点的无密码认证
ssh-keygen -t rsa 				#一路按回车键
ssh-copy-id 192.168.23.128     #mysql1
ssh-copy-id 192.168.23.129     #mysql2
ssh-copy-id 192.168.23.132     #mysql3

(2)在 mysql1 上配置到数据库节点 mysql2 和 mysql3 的无密码认证
ssh-keygen -t rsa
ssh-copy-id 192.168.23.129
ssh-copy-id 192.168.23.132

(3)在 mysql2 上配置到数据库节点 mysql1 和 mysql3 的无密码认证
ssh-keygen -t rsa
ssh-copy-id 192.168.23.128
ssh-copy-id 192.168.23.132

(4)在 mysql3 上配置到数据库节点 mysql1 和 mysql2 的无密码认证
ssh-keygen -t rsa
ssh-copy-id 192.168.23.128
ssh-copy-id 192.168.23.129

Insert picture description here
Insert picture description here

9.在 manager 节点上配置 MHA
(1)在 manager 节点上复制相关脚本到/usr/local/bin 目录
cp -rp /opt/mha4mysql-manager-0.57/samples/scripts /usr/local/bin
//拷贝后会有四个执行文件
ll /usr/local/bin/scripts/

master_ip_failover  		#自动切换时 VIP 管理的脚本
master_ip_online_change 	#在线切换时 vip 的管理
power_manager 				#故障发生后关闭主机的脚本
send_report 				#因故障切换后发送报警的脚本

Insert picture description here

(2)复制上述的自动切换时 VIP 管理的脚本到 /usr/local/bin 目录,这里使用master_ip_failover脚本来管理 VIP 和故障切换
cp /usr/local/bin/scripts/master_ip_failover /usr/local/bin

Insert picture description here

(3)修改内容如下:(删除原有内容,直接复制并修改vip相关参数)
vim /usr/local/bin/master_ip_failover
#!/usr/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.23.200';									#指定vip的地址
my $brdc = '192.168.23.255';								#指定vip的广播地址
my $ifdev = 'ens33';										#指定vip绑定的网卡
my $key = '1';												#指定vip绑定的虚拟网卡序列号
my $ssh_start_vip = "/sbin/ifconfig ens33:$key $vip";		#代表此变量值为ifconfig ens33:1 192.168.23.200
my $ssh_stop_vip = "/sbin/ifconfig ens33:$key down";		#代表此变量值为ifconfig ens33:1 192.168.23.200 down
my $exit_code = 0;											#指定退出状态码为0
#my $ssh_start_vip = "/usr/sbin/ip addr add $vip/24 brd $brdc dev $ifdev label $ifdev:$key;/usr/sbin/arping -q -A -c 1 -I $ifdev $vip;iptables -F;";
#my $ssh_stop_vip = "/usr/sbin/ip addr del $vip/24 dev $ifdev label $ifdev:$key";
##################################################################################
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" ) {

my $exit_code = 1;
eval {
print "Disabling the VIP on old master: $orig_master_host \n";
&stop_vip();
$exit_code = 0;
};
if ($@) {
warn "Got Error: $@\n";
exit $exit_code;
}
exit $exit_code;
}
elsif ( $command eq "start" ) {

my $exit_code = 10;
eval {
print "Enabling the VIP - $vip on the new master - $new_master_host \n";
&start_vip();
$exit_code = 0;
};
if ($@) {
warn $@;
exit $exit_code;
}
exit $exit_code;
}
elsif ( $command eq "status" ) {
print "Checking the Status of the script.. OK \n";
exit 0;
}
else {
&usage();
exit 1;
}
}
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";
}

Insert picture description here

(4)创建 MHA 软件目录并拷贝配置文件,这里使用app1.cnf配置文件来管理 mysql 节点服务器
mkdir /etc/masterha
cp /opt/mha4mysql-manager-0.57/samples/conf/app1.cnf /etc/masterha

vim /etc/masterha/app1.cnf						#删除原有内容,直接复制并修改节点服务器的IP地址
[server default]
manager_log=/var/log/masterha/app1/manager.log
manager_workdir=/var/log/masterha/app1
master_binlog_dir=/usr/local/mysql/data
master_ip_failover_script=/usr/local/bin/master_ip_failover
master_ip_online_change_script=/usr/local/bin/master_ip_online_change
password=manager
ping_interval=1
remote_workdir=/tmp
repl_password=123456
repl_user=myslave
secondary_check_script=/usr/local/bin/masterha_secondary_check -s 192.168.23.128 -s 192.168.23.132
shutdown_script=""
ssh_user=root
user=mha

[server1]
hostname=192.168.23.128
port=3306

[server2]
candidate_master=1
check_repl_delay=0
hostname=192.168.23.129
port=3306

[server3]
hostname=192.168.23.132
port=3306

Insert picture description here

[server default]
manager_log=/var/log/masterha/app1/manager.log      #manager日志
manager_workdir=/var/log/masterha/app1.log        #manager工作目录
master_binlog_dir=/usr/local/mysql/data/         #master保存binlog的位置,这里的路径要与master里配置的binlog的路径一致,以便MHA能找到
master_ip_failover_script=/usr/local/bin/master_ip_failover  #设置自动failover时候的切换脚本,也就是上面的那个脚本
master_ip_online_change_script=/usr/local/bin/master_ip_online_change  #设置手动切换时候的切换脚本
password=manager			#设置mysql中root用户的密码,这个密码是前文中创建监控用户的那个密码
ping_interval=1				#设置监控主库,发送ping包的时间间隔,默认是3秒,尝试三次没有回应的时候自动进行failover
remote_workdir=/tmp			#设置远端mysql在发生切换时binlog的保存位置
repl_password=123456			#设置复制用户的密码
repl_user=myslave			#设置复制用户的用户
report_script=/usr/local/send_report     #设置发生切换后发送的报警的脚本
secondary_check_script=/usr/local/bin/masterha_secondary_check -s 192.168.23.128 -s 192.168.23.132	#指定检查的从服务器IP地址
shutdown_script=""			#设置故障发生后关闭故障主机脚本(该脚本的主要作用是关闭主机防止发生脑裂,这里没有使用)
ssh_user=root				#设置ssh的登录用户名
user=mha					#设置监控用户root

[server1]
hostname=192.168.23.128
port=3306

[server2]
hostname=192.168.23.129
port=3306
candidate_master=1
#设置为候选master,设置该参数以后,发生主从切换以后将会将此从库提升为主库,即使这个主库不是集群中最新的slave

check_repl_delay=0
#默认情况下如果一个slave落后master 超过100M的relay logs的话,MHA将不会选择该slave作为一个新的master, 因为对于这个slave的恢复需要花费很长时间;通过设置check_repl_delay=0,MHA触发切换在选择一个新的master的时候将会忽略复制延时,这个参数对于设置了candidate_master=1的主机非常有用,因为这个候选主在切换的过程中一定是新的master

[server3]
hostname=192.168.23.132
port=3306
9.第一次配置需要在 Master 节点上手动开启虚拟IP
ifconfig ens33:1 192.168.23.200/24

Insert picture description here

10.在 manager 节点上测试 ssh 无密码认证,如果正常最后会输出 successfully,如下所示。
masterha_check_ssh -conf=/etc/masterha/app1.cnf

Insert picture description here

11.在 manager 节点上测试 mysql 主从连接情况,最后出现 MySQL Replication Health is OK 字样说明正常。如下所示。
masterha_check_repl -conf=/etc/masterha/app1.cnf

Insert picture description here

12.在 manager 节点上启动 MHA
nohup masterha_manager --conf=/etc/masterha/app1.cnf --remove_dead_master_conf --ignore_last_failover < /dev/null > /var/log/masterha/app1/manager.log 2>&1 &

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

Insert picture description here

13.查看 MHA 状态,可以看到当前的 master 是 Mysql1 节点。
masterha_check_status --conf=/etc/masterha/app1.cnf

Insert picture description here

14. 查看 MHA 日志,也以看到当前的 master 是 192.168.23.128,如下所示。
cat /var/log/masterha/app1/manager.log | grep "current master"

Insert picture description here

15. 查看 Mysql1 的 VIP 地址 192.168.23.200 是否存在,这个 VIP 地址不会因为 manager 节点停止 MHA 服务而消失。
ifconfig

//若要关闭 manager 服务,可以使用如下命令。
masterha_stop --conf=/etc/masterha/app1.cnf
或者可以直接采用 kill 进程 ID 的方式关闭。

Insert picture description here

6. Failure simulation

#在 manager 节点上监控观察日志记录
tail -f /var/log/masterha/app1/manager.log

#在 Master 节点 Mysql1 上停止mysql服务
systemctl stop mysqld
或
pkill -9 mysql

#正常自动切换一次后,MHA 进程会退出。HMA 会自动修改 app1.cnf 文件内容,将宕机的 mysql1 节点删除。查看 mysql2 是否接管 VIP
ifconfig

Insert picture description here
Insert picture description here
Insert picture description here

故障切换备选主库的算法:
1.一般判断从库的是从(position/GTID)判断优劣,数据有差异,最接近于master的slave,成为备选主。
2.数据一致的情况下,按照配置文件顺序,选择备选主库。
3.设定有权重(candidate_master=1),按照权重强制指定备选主。
(1)默认情况下如果一个slave落后master 100M的relay logs的话,即使有权重,也会失效。
(2)如果check_repl_delay=0的话,即使落后很多日志,也强制选择其为备选主。

(1) Troubleshooting steps

1.修复mysql
systemctl restart mysqld
2.修复主从
#在现主库服务器 Mysql2 查看二进制文件和同步点
show master status;   
 #在原主库服务器 mysql1 执行同步操作
change master to master_host='192.168.23.129',master_user='myslave',master_password='123456',master_log_file='master-bin.000001',master_log_pos=1745;

start slave;   #开启同步

Insert picture description here
Insert picture description here
Insert picture description here

3.在 manager 节点上修改配置文件app1.cnf(再把这个记录添加进去,因为它检测掉失效时候会自动消失)
vi /etc/masterha/app1.cnf
......
secondary_check_script=/usr/local/bin/masterha_secondary_check -s 192.168.23.128 -s 192.168.23.132
......
[server1]
hostname=192.168.23.129
port=3306

[server2]
candidate_master=1
check_repl_delay=0
hostname=192.168.23.128
port=3306

[server3]
hostname=192.168.23.132
port=3306

Insert picture description here

4.在 manager 节点上启动 MHA
masterha_stop --conf=/etc/masterha/app1.cnf             #重启MHA
nohup masterha_manager --conf=/etc/masterha/app1.cnf --remove_dead_master_conf --ignore_last_failover < /dev/null > /var/log/masterha/app1/manager.log 2>&1 &
masterha_check_status --conf=/etc/masterha/app1.cnf     #再次查看MHA状态

Insert picture description here

Guess you like

Origin blog.csdn.net/LI_MINGXUAN/article/details/113862737