MySQL高可用之MHA-02

发布时间 2023-04-17 20:36:35作者: 躺平摆烂


@

配置vip

vip配置可以采用两种方式,一种通过keepalived的方式管理虚拟ip的浮动;另外一种通过脚本方式启动虚拟ip的方式(即不需要keepalived或者heartbeat类似的软件)。

一、keepalived方式

1、keepalived方式管理虚拟ip
keepalived配置方法如下: 下载软件进行并进行安装(两台master,准确的说一台是master,另外一台是备选master,在没有切换以前是slave)

yum -y install epel-release.noarch
yum -y install keepalived.x86_64 

master2主机也完成keepalived安装,与master1一样,安装过程略

注:若开启了防火墙,需要关闭防火墙或创建规则

firewall-cmd --direct --permanent --add-rule ipv4 filter OUTPUT 0 --in-interface enp0s3 --destination 224.0.0.18 --protocol vrrp -j ACCEPT
firewall-cmd --direct --permanent --add-rule ipv4 filter INPUT 0 --in-interface enp0s3 --destination 224.0.0.18 --protocol vrrp -j ACCEPT
firewall-cmd --reload

修改Keepalived的配置文件(在master1上配置)

 cat /etc/keepalived/keepalived.conf 

! Configuration File for keepalived

global_defs {

   router_id LVS_DEVEL-01
   
}

vrrp_instance VI_1 {
    state BACKUP
    interface ens33
    virtual_router_id 51
    priority 100
    nopreempt
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        192.168.1.100
      
    }
}

在候选master(master2)上配置

! Configuration File for keepalived

global_defs {

   router_id LVS_DEVEL-02
   
}

vrrp_instance VI_1 {
    state BACKUP
    interface ens33
    virtual_router_id 51
    priority 50
    	nopreempt

    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        192.168.1.100
      
    }
}

启动keepalived服务

 systemctl start keepalived.service

查看vip

ip a show dev ens33

vip在master1主机上面,keepalived就已经配置成功了

注意: 上面两台服务器的keepalived都设置为了BACKUP模式,在keepalived中2种模式,分别是master-backup模式和backup->backup模式。这两种模式有很大区别。在master->backup模式下,一旦主库宕机,虚拟ip会自动漂移到从库,当主库修复后,keepalived启动后,还会把虚拟ip抢占过来,即使设置了非抢占模式(nopreempt)抢占ip的动作也会发生。在backup->backup模式下,当主库宕机后虚拟ip会自动漂移到从库上,当原主库恢复和keepalived服务启动后,并不会抢占新主的虚拟ip,即使是优先级高于从库的优先级别,也不会发生抢占。为了减少ip漂移次数,通常是把修复好的主库当做新的备库。

2、MHA引入keepalived
MySQL服务进程挂掉时通过MHA 停止keepalived): 要想把keepalived服务引入MHA,我们只需要修改切换时触发的脚本文件master_ip_failover即可,在该脚本中添加在master发生宕机时对keepalived的处理。 编辑脚本/scripts/master_ip_failover,修改后如下。(建议备份后进行修改)

cat 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.1.100';
my $ssh_start_vip = "systemctl start keepalived.service";
my $ssh_stop_vip = "systemctl stop keepalived.service";
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";
#`ssh $ssh_user\@cluster1 \" $ssh_start_vip \"`;
exit 0;
}
else {
&usage();
exit 1;
}
}
# 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() {
return 0 unless ($ssh_user);
`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";
}

需要注意的是下面这三条内容

在这里插入图片描述
这三行分别是

vip的地址
启动keepalived的命令
停止keepalived的命令

现在已经修改这个脚本了,接下来我们在/etc/masterha/app1.cnf 中调用故障切换脚本

停止MHA

masterha_stop --conf=/etc/masterha/app1.cnf 

在配置文件/etc/masterha/app1.cnf 中启用下面的参数(在[server default下面添加])

master_ip_failover_script=/scripts/master_ip_failover

启动MHA

nohup masterha_manager --conf=/etc/masterha/app1.cnf &>/tmp/mha_manage.log &

检查状态

masterha_check_status --conf=/etc/masterha/app1.cnf 
app1 (pid:15259) is running(0:PING_OK), master:192.168.1.65

再检查集群状态,看是否会报错

masterha_check_repl --conf=/etc/masterha/app1.cnf
......
MySQL Replication Health is OK.

可以看见已经没有报错了。 /scripts/master_ip_failover添加或者修改的内容意思是当主库数据库发生故障时,会触发MHA切换,MHA Manager会停掉主库上的keepalived服务,触发虚拟ip漂移到备选从库,从而完成切换。 当然可以在keepalived里面引入脚本,这个脚本监控mysql是否正常运行,如果不正常,则调用该脚本杀掉keepalived进程

3、测试
在master1上停止mysqld服务 到slave查看slave的状态:

mysql> show slave status\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.1.67
                  Master_User: mharep

从上图可以看出slave指向了新的master服务器192.168.1.67(在故障切换前指向的是192.168.1.65)

查看VIP绑定:

[root@master1 ~]# ip a show dev ens33
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0c:29:57:8d:1c brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.65/24 brd 192.168.1.255 scope global ens33
       valid_lft forever preferred_lft forever
    inet6 fe80::7c0:18fc:ee75:c06b/64 scope link 
       valid_lft forever preferred_lft forever
[root@master2 ~]# ip a show dev ens33
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0c:29:fa:45:c1 brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.64/24 brd 192.168.1.255 scope global ens33
       valid_lft forever preferred_lft forever
    inet 192.168.1.100/32 scope global ens33
       valid_lft forever preferred_lft forever
    inet6 fe80::ed8f:78fc:474:e01/64 scope link 
       valid_lft forever preferred_lft forever

从上面的显示结果可以看出vip地址漂移到了192.168.1.67

主从切换后续工作 重构: 重构就是你的主挂了,切换到Candicate master上,Candicate master变成了主,因此重构的一种方案原主库修复成一个新的slave 主库切换后,把原主库修复成新从库,原主库数据文件完整的情况下,可通过以下方式找出最后执行的CHANGEMASTER命令:

[root@manager ~]# grep 'CHANGE' /masterha/app1/manager.log 
Sat Mar 13 21:58:38 2021 - [info]  All other slaves should start replication from here. Statement should be: CHANGE MASTER TO MASTER_HOST='192.168.1.67', MASTER_PORT=3306, MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=742, MASTER_USER='mharep', MASTER_PASSWORD='xxx';
Sat Mar 13 21:58:40 2021 - [info]  Executed CHANGE MASTER

master1主机上操作
将(原主库)修复成从库

mysql> CHANGE MASTER TO MASTER_HOST='192.168.1.67', MASTER_PORT=3306, MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=742, MASTER_USER='mharep', MASTER_PASSWORD='123.com';
Query OK, 0 rows affected, 2 warnings (0.01 sec)

mysql> start slave;
Query OK, 0 rows affected (0.01 sec)
mysql> show slave status\G
*************************** 1. row ***************************
              Slave_IO_State: Waiting for master to send event
                 Master_Host: 192.168.1.67
                 Master_User: mharep
                 Master_Port: 3306
               Connect_Retry: 60
             Master_Log_File: mysql-bin.000001
         Read_Master_Log_Pos: 742
              Relay_Log_File: relay-bin.000002
               Relay_Log_Pos: 320
       Relay_Master_Log_File: mysql-bin.000001
            Slave_IO_Running: Yes
           Slave_SQL_Running: Yes

重新启动mha

 rm -fr /masterha/app1/app1.failover.complete
 nohup masterha_manager --conf=/etc/masterha/app1.cnf --ignore_fail_on_start &>/tmp/mha_manager.log &
masterha_check_status --conf=/etc/masterha/app1.cnf 
app1 (pid:15810) is running(0:PING_OK), master:192.168.1.67

二、通过脚本实现VIP切换

通过脚本的方式管理VIP。这里是修改/scripts/master_ip_failover,也可以使用其他的语言完成,比如php语言。使用php脚本编写的failover这里就不介绍了。修改完成后内容如下,而且如果使用脚本管理vip的话,需要手动在master服务器上绑定一个vip

ifconfig ens33:0 192.168.1.100/24

在mha-manager上修改/scripts/ 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.1.100';
my $key = '0';
my $ssh_start_vip = "/sbin/ifconfig ens33:$key $vip";
my $ssh_stop_vip = "/sbin/ifconfig ens33:$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" ) {

        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";
        #`ssh $ssh_user\@cluster1 \" $ssh_start_vip \"`;
        exit 0;
    }
    else {
        &usage();
        exit 1;
    }
}

# 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() {
     return 0  unless  ($ssh_user);
    `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";
}

脚本中需要注意的点
在这里插入图片描述
在配置文件中添加下面这行

cat /etc/masterha/app1.cnf 
[server default]
master_ip_failover_script=/scripts/master_ip_failover

停止MHA

masterha_stop --conf=/etc/masterha/app1.cnf

启动MHA:

#nohup masterha_manager --conf=/etc/masterha/app1.cnf &>/tmp/mha_manager.log &

检查状态

masterha_check_status --conf=/etc/masterha/app1.cnf 

再检查集群状态,看是否会报错。

masterha_check_repl --conf=/etc/masterha/app1.cnf 

测试
在master上停掉mysql服务
到slave查看slave的状态

mysql> show slave status\G
*************************** 1. row ***************************
              Slave_IO_State: Waiting for master to send event
                 Master_Host: 192.168.1.65
                 Master_User: mharep
                 Master_Port: 3306
               Connect_Retry: 60

从上图可以看出slave指向了新的master服务器
查看VIP

ip a show dev ens33

(原来的master)释放了VIP,master1(新的master)接管了VIP地址 主从切换后续工作 主库切换后,把原主库修复成新从库,相关操作请参考前面相关操作。 为了防止脑裂发生,推荐生产环境采用脚本的方式来管理虚拟ip,而不是使用keepalived来完成。到此为止,基本MHA集群已经配置完毕。

总结

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线程)

mysql必备技能掌握:

  • MySQL架构:对mysql的架构,整体有个印象,才能不断的加深对mysql的理解和后继的学习。
  • 用各种姿势备份MySQL数据库 数据备份是DBA或运维工程师日常工作之一,如果让你来备份,你会用什么方式备份,在时间时间备份,使用什么策略备份
  • mysql主从复制及读写分离 mysql的主从复制及读写分离是DBA必备技能之一
  • MySQL/MariaDB数据库基于SSL实现主从复制 加强主从复制的安全性
  • MySQL高可用 数据的高可用如何保证
  • 数据库Sharding的基本思想和切分策略 随着数据量的不断攀升,从性能和可维护的角度,需要进行一些Sharding,也就是数据库的切分,有垂直切分和水平切分
  • MySQL/MariaDB 性能调整和优化技巧 掌握优化思路和技巧,对数据库的不断优化是一项长期工程