MySQL MHA部署與測試-MySQL 8.0.20-mha4mysql-0.58版本

MySQL MHA部署與測試-上篇

1、介紹

1.1 簡介

MHA(Master High Availability)目前在MySQL高可用方面是一個相對成熟的解決方案,它由日本DeNA公司的youshimaton(現就職於Facebook公司)開發,是一套優秀的作爲MySQL高可用性環境下故障切換和主從提升的高可用軟件

1.2 主要特性

MHA的主要特徵:

  • master的監控到故障轉移全部都能自動完成,故障轉移也可以手動執行
  • 可在秒級單位內實現故障轉移
  • 可將任意slave提升到master
  • 具備在多個點上調用外部腳本(擴展)的技能,可以用在電源OFF或者IP地址的故障轉移上
  • 安裝和卸載不用停止當前的mysql進程
  • MHA自身不會增加服務器負擔,不會降低性能,不用追加服務器
  • 不依賴Storage Engine
  • 不依賴二進制文件的格式(不論是statement模式還是Row模式)
  • 針對OS掛掉的故障轉移,檢測系統是否掛掉需要10秒,故障轉移僅需4

1.3 組成結構

manager 組件
masterha_manger             # 啓動MHA 
masterha_check_ssh      	  # 檢查MHA的SSH配置狀況 
masterha_check_repl         # 檢查MySQL複製狀況,配置信息
masterha_master_monitor     # 檢測master是否宕機 
masterha_check_status       # 檢測當前MHA運行狀態 
masterha_master_switch     	# 控制故障轉移(自動或者手動)
masterha_conf_host      	  # 添加或刪除配置的server信息

node 組件
save_binary_logs            # 保存和複製master的二進制日誌 
apply_diff_relay_logs       # 識別差異的中繼日誌事件並將其差異的事件應用於其他的
purge_relay_logs            # 清除中繼日誌(不會阻塞SQL線程)

2、MHA部署

2.1 環境準備

2.1.1 拓撲

image

2.1.2 環境準備

需準備Linux環境Mysql1主2從環境,本次部署具體使用軟件版本情況如下
操作系統:Linux CentOS 7.6
數據庫:MySQL 8.0.20
MHA:mha4mysql-0.58

2.2 環境部署

2.2.1 安裝操作系統

操作系統版本:Linux CentOS 7.6

主機名及ip

db1:192.168.10.51,db2:192.168.10.52,db3:192.168.10.53

2.2.2 安裝數據庫

分別在三臺服務器安裝MySQL 8.0.20數據庫
配置文件如下:

[mysqld]
user=mysql
basedir=/usr/local/mysql
datadir=/data/3306/data
socket=/tmp/mysql.sock

gtid-mode=on                        # gtid開關
enforce-gtid-consistency=true       # 強制GTID一致
log-slave-updates=1                 # 從庫強制更新binlog日誌

log_bin = mysql-bin
binlog_format = mixed
expire_logs_days = 15
log-error=/data/3306/data/mysql_error.log
server-id = 51     # server-id 三臺不同 ,db2爲52,db3爲53
default_authentication_plugin=mysql_native_password   #修改密碼加密方式

[mysql]
socket=/tmp/mysql.sock

2.2.3 搭建主從環境

搭建主從環境,確認1主2從運行正常

2.3 MHA部署

2.3.1 節點互信

db01
rm -rf /root/.ssh 
ssh-keygen
ssh-copy-id 192.168.10.51
ssh-copy-id 192.168.10.52
ssh-copy-id 192.168.10.53
db02
ssh-keygen
ssh-copy-id 192.168.10.51
ssh-copy-id 192.168.10.52
ssh-copy-id 192.168.10.53
db03
ssh-keygen
ssh-copy-id 192.168.10.51
ssh-copy-id 192.168.10.52
ssh-copy-id 192.168.10.53

2.3.2 下載軟件

mkdir -p /data/tools/ && cd /data/tools
wget https://qiniu.wsfnk.com/mha4mysql-node-0.58-0.el7.centos.noarch.rpm --no-check-certificate
wget https://qiniu.wsfnk.com/mha4mysql-manager-0.58-0.el7.centos.noarch.rpm --no-check-certificate

2.3.3 創建軟連接

ln -s /usr/local/mysql/bin/mysqlbinlog  /usr/bin/mysqlbinlog
ln -s /usr/local/mysql/bin/mysql          /usr/bin/mysql

2.3.4 安裝軟件

安裝node軟件(mhamanager軟件是依賴於node軟件運行的,所以需要先安裝node端)
db1-db3

yum install perl-DBD-MySQL -y
rpm -ivh mha4mysql-node-0.58-0.el7.centos.noarch.rpm

安裝manager
db3

yum install -y perl-Config-Tiny epel-release perl-Log-Dispatch perl-Parallel-ForkManager perl-Time-HiRes
yum install -y mha4mysql-manager-0.58-0.el7.centos.noarch.rpm 

2.3.5 創建用戶

db1主庫中創建mha用戶,此用戶用於mha用來確認各節點存活狀態、binlog_server拉去binlog日誌。
(mysql 8.0之後版本需要單獨創建用戶後授權。注意密碼加密方式)

create user mha@'192.168.10.%' identified by 'mha';
grant all privileges on *.* to mha@'192.168.10.%';

2.3.6 創建相關目錄

db3

#創建配置文件目錄
 mkdir -p /etc/mha
#創建日誌目錄
 mkdir -p /var/log/mha/app1

2.3.7 manager配置文件

db3

cat > /etc/mha/app1.cnf <<eof [server="" default]="" manager_log="/var/log/mha/app1/manager" #="" mha的工作日誌設置="" manager_workdir="/var/log/mha/app1" mha工作目錄="" master_binlog_dir="/data/3306/data" 主庫的binlog目錄="" user="mha" 監控用戶="" password="mha" 監控密碼="" ping_interval="2" 心跳檢測的間隔時間="" repl_password="123" 複製用戶="" repl_user="rep" 複製密碼="" ssh_user="root" ssh互信的用戶="" [server1]="" 節點信息....="" hostname="192.16.10.51" port="3306" [server2]="" candidate_master="1" 被選主="" [server3]="" no_master="1" 不參與選主="" eof="" ```="" ####="" 2.3.8="" 檢查狀態="" db3="" ```shell="" 檢查ssl互通情況="" [root@db3="" ~]#="" vim="" etc="" mha="" app1.cnf="" masterha_check_ssh="" --conf="/etc/mha/app1.cnf" ...="" tue="" jun="" 1="" 17:01:47="" 2021="" -="" [info]="" all="" ssh="" connection="" tests="" passed="" successfully.="" 檢查="" mha配置文件="" masterha_check_repl="" mysql="" replication="" health="" is="" not="" ok!="" 2.3.9="" 啓動manager服務="" db03="" nohup="" masterha_manager="" --remove_dead_master_conf="" --ignore_last_failover="" <="" dev="" null=""> /var/log/mha/app1/manager.log 2>&1 &
[1] 4406

--conf=/etc/mha/app1.cnf    # 指定配置文件
--remove_dead_master_conf   # 剔除已經死亡的節點
--ignore_last_failover      # 默認不能短時間(8小時)多次切換,此參數跳過檢查

2.3.10 查看mha運行狀態

[root@db3 ~]# masterha_check_status --conf=/etc/mha/app1.cnf
app1 (pid:4406) is running(0:PING_OK), master:192.168.10.51

3、vip、故障提醒、binlog_server

master_ip_failover  # vip故障轉移腳本
send_report         # 故障提醒腳本

3.1 vip 功能部署

vip(eth0:1)網卡日常綁定在主庫的網卡上,如主庫出現錯誤導致mha重新選主,也會跟隨移動到新主庫的網卡上。所以要求各mha節點網卡名稱一致
vip網段要求與各節點均在同一網段內
vip實現腳本是根據源碼perl腳本重新編寫master_ip_failover

3.1.1 準備腳本

#!/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.10.49/24';
my $key = '1';
my $ssh_start_vip = "/sbin/ifconfig eth0:$key $vip";
my $ssh_stop_vip = "/sbin/ifconfig eth0:$key down";
my $ssh_Bcast_arp= "/sbin/arping -I eth0 -c 3 -A 192.168.10.49";

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 \"`;
}
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";
}

3.1.2 修改腳本

腳本中以下部分按照要求修改

vim  /usr/local/bin/master_ip_failover

my $vip = '192.168.10.49/24';      # vip網段,與各節點服務器網段一致。
my $key = '1';                     # 虛擬網卡eth0:1 的 1
my $ssh_start_vip = "/sbin/ifconfig eth0:$key $vip";  # 網卡按照實際網卡名稱填寫
my $ssh_stop_vip = "/sbin/ifconfig eth0:$key down";   # 網卡按照實際網卡名稱填寫
my $ssh_Bcast_arp= "/sbin/arping -I eth0 -c 3 -A 192.168.10.49"; # 重新聲明mac地址,arp

3.1.3 上傳腳本並授權

\cp -a * /usr/local/bin    # 上傳腳本文件到/usr/local/bin 
chmod +x /usr/local/bin/*  # 給腳本增加執行權限 
dos2unix /usr/local/bin/*  # 處理腳本中的中文字符

3.1.4 修改manager配置文件

在配置文件中增加vip故障轉移部分

vim /etc/mha/app1.cnf 
master_ip_failover_script=/usr/local/bin/master_ip_failover

3.1.5 重啓mha

masterha_stop  --conf=/etc/mha/app1.cnf 
nohup masterha_manager --conf=/etc/mha/app1.cnf --remove_dead_master_conf --ignore_last_failover  < /dev/null> /var/log/mha/app1/manager.log 2>&1 &

3.1.6 在主庫db1增加vip

ifconfig eth0:1 192.168.10.49/24

3.2 故障提醒功能部署

3.2.1 準備腳本

#!/usr/bin/perl

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.qq.com';
my $mail_from='[email protected]';
my $mail_user='xxxxx';
my $mail_pass='xxxxxx';
#my $mail_to=['[email protected]','[email protected]'];
my $mail_to='[email protected]';
 
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,
);
 
# Do whatever you want here
mailToContacts($smtp,$mail_from,$mail_user,$mail_pass,$mail_to,$subject,$body);
 
sub mailToContacts {
	my ($smtp, $mail_from, $mail_user, $mail_pass, $mail_to, $subject, $msg ) = @_;
	open my $DEBUG, ">/tmp/mail.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	=> '0',
		authid		=> $mail_user,
		authpwd		=> $mail_pass,
		to		=> $mail_to,
		subject		=> $subject,
		debug		=> $DEBUG
	};
	$sender->MailMsg(
		{
			msg => $msg,
			debug => $DEBUG
		}
	) or print $Mail::Sender::Error;
	return 1;
}
 
exit 0;

修改以下部分爲個人郵箱內容

#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.qq.com';                   # 發件服務器
my $mail_from='[email protected]';            # 發件地址
my $mail_user='xxxxx';                    # 發件用戶名
my $mail_pass='xxxxxx';                   # 發件郵箱密碼
my $mail_to='[email protected]';              # 收件地址

#my $mail_to=['[email protected]','[email protected]']; # 可設置收件郵箱羣組 

3.2.2 修改manager配置文件

vim /etc/mha/app1.cnf 
# 添加一行: 
report_script=/usr/local/bin/send_report

3.2.3 重啓mha

masterha_stop  --conf=/etc/mha/app1.cnf 
nohup masterha_manager --conf=/etc/mha/app1.cnf --remove_dead_master_conf --ignore_last_failover  < /dev/null> /var/log/mha/app1/manager.log 2>&1 &

3.3 binlog_server搭建

binlog_server功能主要是實時拉去主庫binlog進行存儲,如果主庫出現宕機,mha切換主從時,通過binlog_server服務器拿取bin_log日誌對新主庫進行數據補償,實現日誌補償冗餘

3.3.1 創建相關目錄

mkdir -p /data/binlog_server/   # binlog_server存儲目錄
chown -R mysql.mysql /data/*    # 授權

3.3.2 開啓binlog_server服務

cd  /data/binlog_server/     # 進入binlog_server存儲目錄
mysql -e "show slave status \G"|grep "Master_Log"  # 確認當前slave的io進程拉取的日誌量

## 啓動binlog日誌拉取守護進程
mysqlbinlog  -R --host=192.168.10.51 --user=mha --password=mha --raw  --stop-never mysql-bin.000004 &      # 注意:拉取日誌的起點,需要按照目前從庫的已經獲取到的二進制日誌點爲起點

3.3.3 修改manager配置文件

增加以下內容

vim /etc/mha/app1.cnf 
[binlog1]
no_master=1
hostname=192.168.10.53
master_binlog_dir=/data/binlog_server/

3.3.4 重啓mha

masterha_stop  --conf=/etc/mha/app1.cnf 
nohup masterha_manager --conf=/etc/mha/app1.cnf --remove_dead_master_conf --ignore_last_failover  < /dev/null> /var/log/mha/app1/manager.log 2>&1 &

4、MHA工作原理介紹

4.1 主要工作流程介紹

  • 1、啓動MHA-manager
nohup masterha_manager --conf=/etc/mha/app1.cnf --remove_dead_master_conf --ignore_last_failover  < /dev/null> /var/log/mha/app1/manager.log 2>&1 &
  • 2、監控
/usr/bin/masterha_master_monitor # 每隔ping_interval秒探測1次,連續4次還沒有,說明主庫宕機。
  • 3、選主
    根據各項參數選擇新主
  • 4、數據補償
    對新主的數據差異進行補償。
  • 5、切換
    所有從庫解除主從身份。stop slave ; reset slave;
    重構新的主從關係。change master to
  • 6、遷移vip
    將vip網卡(eth0:1)綁定至新主服務器。
  • 7、故障提醒
    發送故障提醒郵件
  • 8、額外數據補償
    根據binlog_server 服務器進行額外數據補償
  • 9、剔除故障節點
    將故障的主服務器剔除mha環境(配置文件刪除)
  • 10、manager程序“自殺

4.2 mha選主策略

4.2.1 選主依據

1、日誌量latest

選取獲取binlog最多的slave節點,爲latest節點

[root@db3 ~]# mysql -uroot -p123456 -e "show slave status\G" |grep Master_Log
          Master_Log_File: mysql-bin.000005
          Read_Master_Log_Pos: 196
          Relay_Master_Log_File: mysql-bin.000005
          Exec_Master_Log_Pos: 196

2、備選主pref
manager配置文件中指定了candidate_master=1參數

[server2]            
hostname=192.168.10.52
port=3306
candidate_master=1     # 備選主

3、不被選主
配置文件中設置no_master=1

[server3]
no_master=1    # 不被選
hostname=192.168.10.53
port=3306

二進制日誌沒開log_bin
如果從庫落後主庫100M的日誌量(可以關閉) check_slave_delay

4.2.2 節點數組

alive 存活
latest 日誌最新
perf 被選
bad 不選

4.2.3 選主判斷

從上至下按條件依次篩選,上條不符合纔會選擇下一條
1、沒有prefbad,就選latest第一個(根據配置文件server1-2-3)
2、即是latest又是perf,又不是bad
3、perflatest,都不是bad,選perf
4、第3條也可能選latest,如perf100M以上binlog
5、如果以上條件都不滿足,且只有一個salve可選,則選擇此slave
6、沒有符合的slave,則選主失敗,failover失敗

4.3 數據補償

4.3.1 原主庫ssh可連接

各個從節點調用: save_binary_logs腳本,立即保存缺失部分的binlog到各自節點/var/tmp目錄

4.3.2 原主庫ssh不能連接

從節點調用apply_diff_relay_logs,進行relay-log日誌差異補償

4.3.3 額外數據補償(主庫日誌冗餘機制)

binlog_server實現數據補償

MySQL MHA部署與測試-下篇

1、故障測試

1.1 操作流程

# 追蹤mha-manager日誌
[root@db03 ~]# tail -f  /var/log/mha/app1/manager 
# 關閉主庫
[root@db01 ~]# /etc/init.d/mysqld stop

1.2 日誌查看

# 確認主庫宕機部分
Wed Jun  2 16:55:42 2021 - [warning] Got error on MySQL select ping: 1053 (Server shutdown in progress)
Wed Jun  2 16:55:42 2021 - [info] Executing SSH check script: exit 0
Wed Jun  2 16:55:42 2021 - [info] HealthCheck: SSH to 192.168.10.51 is reachable.
Wed Jun  2 16:55:44 2021 - [warning] Got error on MySQL connect: 2003 (Can't connect to MySQL server on '192.168.10.51' (111))
Wed Jun  2 16:55:44 2021 - [warning] Connection failed 2 time(s)..
Wed Jun  2 16:55:46 2021 - [warning] Got error on MySQL connect: 2003 (Can't connect to MySQL server on '192.168.10.51' (111))
Wed Jun  2 16:55:46 2021 - [warning] Connection failed 3 time(s)..
Wed Jun  2 16:55:48 2021 - [warning] Got error on MySQL connect: 2003 (Can't connect to MySQL server on '192.168.10.51' (111))
Wed Jun  2 16:55:48 2021 - [warning] Connection failed 4 time(s)..
Wed Jun  2 16:55:48 2021 - [warning] Master is not reachable from health checker!
Wed Jun  2 16:55:48 2021 - [warning] Master 192.168.10.51(192.168.10.51:3306) is not reachable!



# 確認各節點狀態
Wed Jun  2 16:55:48 2021 - [warning] SSH is reachable.
Wed Jun  2 16:55:48 2021 - [info] Connecting to a master server failed. Reading configuration file /etc/masterha_default.cnf and /etc/mha/app1.cnf again, and trying to connect to all servers to check server status..
Wed Jun  2 16:55:48 2021 - [warning] Global configuration file /etc/masterha_default.cnf not found. Skipping.
Wed Jun  2 16:55:48 2021 - [info] Reading application default configuration from /etc/mha/app1.cnf..
Wed Jun  2 16:55:48 2021 - [info] Reading server configuration from /etc/mha/app1.cnf..
Wed Jun  2 16:55:49 2021 - [info] GTID failover mode = 1
Wed Jun  2 16:55:49 2021 - [info] Dead Servers:
Wed Jun  2 16:55:49 2021 - [info]   192.168.10.51(192.168.10.51:3306)
Wed Jun  2 16:55:49 2021 - [info] Alive Servers:
Wed Jun  2 16:55:49 2021 - [info]   192.168.10.52(192.168.10.52:3306)
Wed Jun  2 16:55:49 2021 - [info]   192.168.10.53(192.168.10.53:3306)
Wed Jun  2 16:55:49 2021 - [info] Alive Slaves:
Wed Jun  2 16:55:49 2021 - [info]   192.168.10.52(192.168.10.52:3306)  Version=8.0.20 (oldest major version between slaves) log-bin:enabled
Wed Jun  2 16:55:49 2021 - [info]     GTID ON
Wed Jun  2 16:55:49 2021 - [info]     Replicating from 192.168.10.51(192.168.10.51:3306)
Wed Jun  2 16:55:49 2021 - [info]     Primary candidate for the new Master (candidate_master is set)
Wed Jun  2 16:55:49 2021 - [info]   192.168.10.53(192.168.10.53:3306)  Version=8.0.20 (oldest major version between slaves) log-bin:enabled
Wed Jun  2 16:55:49 2021 - [info]     GTID ON
Wed Jun  2 16:55:49 2021 - [info]     Replicating from 192.168.10.51(192.168.10.51:3306)
Wed Jun  2 16:55:49 2021 - [info]     Not candidate for the new Master (no_master is set)
Wed Jun  2 16:55:49 2021 - [info] Checking slave configurations..
Wed Jun  2 16:55:49 2021 - [info]  read_only=1 is not set on slave 192.168.10.52(192.168.10.52:3306).
Wed Jun  2 16:55:49 2021 - [info]  read_only=1 is not set on slave 192.168.10.53(192.168.10.53:3306).
Wed Jun  2 16:55:49 2021 - [info] Checking replication filtering settings..
Wed Jun  2 16:55:49 2021 - [info]  Replication filtering check ok.
Wed Jun  2 16:55:49 2021 - [info] Master is down!
Wed Jun  2 16:55:49 2021 - [info] Terminating monitoring script.
Wed Jun  2 16:55:49 2021 - [info] Got exit code 20 (Master dead).
Wed Jun  2 16:55:49 2021 - [info] MHA::MasterFailover version 0.58.
Wed Jun  2 16:55:49 2021 - [info] Starting master failover.
Wed Jun  2 16:55:49 2021 - [info] 
Wed Jun  2 16:55:49 2021 - [info] * Phase 1: Configuration Check Phase..
Wed Jun  2 16:55:49 2021 - [info] 
Wed Jun  2 16:55:51 2021 - [info] GTID failover mode = 1
Wed Jun  2 16:55:51 2021 - [info] Dead Servers:
Wed Jun  2 16:55:51 2021 - [info]   192.168.10.51(192.168.10.51:3306)
Wed Jun  2 16:55:51 2021 - [info] Checking master reachability via MySQL(double check)...
Wed Jun  2 16:55:51 2021 - [info]  ok.
Wed Jun  2 16:55:51 2021 - [info] Alive Servers:
Wed Jun  2 16:55:51 2021 - [info]   192.168.10.52(192.168.10.52:3306)
Wed Jun  2 16:55:51 2021 - [info]   192.168.10.53(192.168.10.53:3306)
Wed Jun  2 16:55:51 2021 - [info] Alive Slaves:
Wed Jun  2 16:55:51 2021 - [info]   192.168.10.52(192.168.10.52:3306)  Version=8.0.20 (oldest major version between slaves) log-bin:enabled
Wed Jun  2 16:55:51 2021 - [info]     GTID ON
Wed Jun  2 16:55:51 2021 - [info]     Replicating from 192.168.10.51(192.168.10.51:3306)
Wed Jun  2 16:55:51 2021 - [info]     Primary candidate for the new Master (candidate_master is set)
Wed Jun  2 16:55:51 2021 - [info]   192.168.10.53(192.168.10.53:3306)  Version=8.0.20 (oldest major version between slaves) log-bin:enabled
Wed Jun  2 16:55:51 2021 - [info]     GTID ON
Wed Jun  2 16:55:51 2021 - [info]     Replicating from 192.168.10.51(192.168.10.51:3306)
Wed Jun  2 16:55:51 2021 - [info]     Not candidate for the new Master (no_master is set)
Wed Jun  2 16:55:51 2021 - [info] Starting GTID based failover.
Wed Jun  2 16:55:51 2021 - [info] 
Wed Jun  2 16:55:51 2021 - [info] ** Phase 1: Configuration Check Phase completed.
Wed Jun  2 16:55:51 2021 - [info] 
Wed Jun  2 16:55:51 2021 - [info] * Phase 2: Dead Master Shutdown Phase..
Wed Jun  2 16:55:51 2021 - [info] 
Wed Jun  2 16:55:51 2021 - [info] Forcing shutdown so that applications never connect to the current master..
Wed Jun  2 16:55:51 2021 - [info] Executing master IP deactivation script:
Wed Jun  2 16:55:51 2021 - [info]   /usr/local/bin/master_ip_failover --orig_master_host=192.168.10.51 --orig_master_ip=192.168.10.51 --orig_master_port=3306 --command=stopssh --ssh_user=root  

# VIP狀態檢查,日誌補償(此部分未發現日誌缺失)
IN SCRIPT TEST====/sbin/ifconfig eth0:1 down==/sbin/ifconfig eth0:1 192.168.10.49/24===

Disabling the VIP on old master: 192.168.10.51 
SIOCSIFFLAGS: Cannot assign requested address
Wed Jun  2 16:55:51 2021 - [info]  done.
Wed Jun  2 16:55:51 2021 - [warning] shutdown_script is not set. Skipping explicit shutting down of the dead master.
Wed Jun  2 16:55:51 2021 - [info] * Phase 2: Dead Master Shutdown Phase completed.
Wed Jun  2 16:55:51 2021 - [info] 
Wed Jun  2 16:55:51 2021 - [info] * Phase 3: Master Recovery Phase..
Wed Jun  2 16:55:51 2021 - [info] 
Wed Jun  2 16:55:51 2021 - [info] * Phase 3.1: Getting Latest Slaves Phase..
Wed Jun  2 16:55:51 2021 - [info] 
Wed Jun  2 16:55:51 2021 - [info] The latest binary log file/position on all slaves is mysql-bin.000005:196
Wed Jun  2 16:55:51 2021 - [info] Latest slaves (Slaves that received relay log files to the latest):
Wed Jun  2 16:55:51 2021 - [info]   192.168.10.52(192.168.10.52:3306)  Version=8.0.20 (oldest major version between slaves) log-bin:enabled
Wed Jun  2 16:55:51 2021 - [info]     GTID ON
Wed Jun  2 16:55:51 2021 - [info]     Replicating from 192.168.10.51(192.168.10.51:3306)
Wed Jun  2 16:55:51 2021 - [info]     Primary candidate for the new Master (candidate_master is set)
Wed Jun  2 16:55:51 2021 - [info]   192.168.10.53(192.168.10.53:3306)  Version=8.0.20 (oldest major version between slaves) log-bin:enabled
Wed Jun  2 16:55:51 2021 - [info]     GTID ON
Wed Jun  2 16:55:51 2021 - [info]     Replicating from 192.168.10.51(192.168.10.51:3306)
Wed Jun  2 16:55:51 2021 - [info]     Not candidate for the new Master (no_master is set)
Wed Jun  2 16:55:51 2021 - [info] The oldest binary log file/position on all slaves is mysql-bin.000005:196
Wed Jun  2 16:55:51 2021 - [info] Oldest slaves:
Wed Jun  2 16:55:51 2021 - [info]   192.168.10.52(192.168.10.52:3306)  Version=8.0.20 (oldest major version between slaves) log-bin:enabled
Wed Jun  2 16:55:51 2021 - [info]     GTID ON
Wed Jun  2 16:55:51 2021 - [info]     Replicating from 192.168.10.51(192.168.10.51:3306)
Wed Jun  2 16:55:51 2021 - [info]     Primary candidate for the new Master (candidate_master is set)
Wed Jun  2 16:55:51 2021 - [info]   192.168.10.53(192.168.10.53:3306)  Version=8.0.20 (oldest major version between slaves) log-bin:enabled
Wed Jun  2 16:55:51 2021 - [info]     GTID ON
Wed Jun  2 16:55:51 2021 - [info]     Replicating from 192.168.10.51(192.168.10.51:3306)
Wed Jun  2 16:55:51 2021 - [info]     Not candidate for the new Master (no_master is set)
Wed Jun  2 16:55:51 2021 - [info] 
Wed Jun  2 16:55:51 2021 - [info] * Phase 3.3: Determining New Master Phase..
Wed Jun  2 16:55:51 2021 - [info] 
Wed Jun  2 16:55:51 2021 - [info] Searching new master from slaves..
Wed Jun  2 16:55:51 2021 - [info]  Candidate masters from the configuration file:
Wed Jun  2 16:55:51 2021 - [info]   192.168.10.52(192.168.10.52:3306)  Version=8.0.20 (oldest major version between slaves) log-bin:enabled
Wed Jun  2 16:55:51 2021 - [info]     GTID ON
Wed Jun  2 16:55:51 2021 - [info]     Replicating from 192.168.10.51(192.168.10.51:3306)
Wed Jun  2 16:55:51 2021 - [info]     Primary candidate for the new Master (candidate_master is set)
Wed Jun  2 16:55:51 2021 - [info]  Non-candidate masters:
Wed Jun  2 16:55:51 2021 - [info]   192.168.10.53(192.168.10.53:3306)  Version=8.0.20 (oldest major version between slaves) log-bin:enabled
Wed Jun  2 16:55:51 2021 - [info]     GTID ON
Wed Jun  2 16:55:51 2021 - [info]     Replicating from 192.168.10.51(192.168.10.51:3306)
Wed Jun  2 16:55:51 2021 - [info]     Not candidate for the new Master (no_master is set)
Wed Jun  2 16:55:51 2021 - [info]  Searching from candidate_master slaves which have received the latest relay log events..

# 選主結束,開始切換
Wed Jun  2 16:55:51 2021 - [info] New master is 192.168.10.52(192.168.10.52:3306)
Wed Jun  2 16:55:51 2021 - [info] Starting master failover..
Wed Jun  2 16:55:51 2021 - [info] 
From:
192.168.10.51(192.168.10.51:3306) (current master)
 +--192.168.10.52(192.168.10.52:3306)
 +--192.168.10.53(192.168.10.53:3306)

To:
192.168.10.52(192.168.10.52:3306) (new master)
 +--192.168.10.53(192.168.10.53:3306)
Wed Jun  2 16:55:51 2021 - [info] 
Wed Jun  2 16:55:51 2021 - [info] * Phase 3.3: New Master Recovery Phase..
Wed Jun  2 16:55:51 2021 - [info] 
Wed Jun  2 16:55:51 2021 - [info]  Waiting all logs to be applied.. 
Wed Jun  2 16:55:51 2021 - [info]   done.
Wed Jun  2 16:55:51 2021 - [info] Getting new master's binlog name and position..
Wed Jun  2 16:55:51 2021 - [info]  mysql-bin.000005:196
Wed Jun  2 16:55:51 2021 - [info]  All other slaves should start replication from here. Statement should be: CHANGE MASTER TO MASTER_HOST='192.168.10.52', MASTER_PORT=3306, MASTER_AUTO_POSITION=1, MASTER_USER='rep', MASTER_PASSWORD='xxx';
Wed Jun  2 16:55:51 2021 - [info] Master Recovery succeeded. File:Pos:Exec_Gtid_Set: mysql-bin.000005, 196, f4682075-c1b9-11eb-86b2-000c2934cc5a:1-21
Wed Jun  2 16:55:51 2021 - [info] Executing master IP activate script:
Wed Jun  2 16:55:51 2021 - [info]   /usr/local/bin/master_ip_failover --command=start --ssh_user=root --orig_master_host=192.168.10.51 --orig_master_ip=192.168.10.51 --orig_master_port=3306 --new_master_host=192.168.10.52 --new_master_ip=192.168.10.52 --new_master_port=3306 --new_master_user='mha'   --new_master_password=xxx
Unknown option: new_master_user
Unknown option: new_master_password

# 切換vip,處理manager配置文件(將db1踢出mha環境)
IN SCRIPT TEST====/sbin/ifconfig eth0:1 down==/sbin/ifconfig eth0:1 192.168.10.49/24===

Enabling the VIP - 192.168.10.49/24 on the new master - 192.168.10.52 
Wed Jun  2 16:55:51 2021 - [info]  OK.
Wed Jun  2 16:55:51 2021 - [info] ** Finished master recovery successfully.
Wed Jun  2 16:55:51 2021 - [info] * Phase 3: Master Recovery Phase completed.
Wed Jun  2 16:55:51 2021 - [info] 
Wed Jun  2 16:55:51 2021 - [info] * Phase 4: Slaves Recovery Phase..
Wed Jun  2 16:55:51 2021 - [info] 
Wed Jun  2 16:55:51 2021 - [info] 
Wed Jun  2 16:55:51 2021 - [info] * Phase 4.1: Starting Slaves in parallel..
Wed Jun  2 16:55:51 2021 - [info] 
Wed Jun  2 16:55:51 2021 - [info] -- Slave recovery on host 192.168.10.53(192.168.10.53:3306) started, pid: 48882. Check tmp log /var/log/mha/app1/192.168.10.53_3306_20210602165549.log if it takes time..
Wed Jun  2 16:55:53 2021 - [info] 
Wed Jun  2 16:55:53 2021 - [info] Log messages from 192.168.10.53 ...
Wed Jun  2 16:55:53 2021 - [info] 
Wed Jun  2 16:55:51 2021 - [info]  Resetting slave 192.168.10.53(192.168.10.53:3306) and starting replication from the new master 192.168.10.52(192.168.10.52:3306)..
Wed Jun  2 16:55:51 2021 - [info]  Executed CHANGE MASTER.
Wed Jun  2 16:55:52 2021 - [info]  Slave started.
Wed Jun  2 16:55:52 2021 - [info]  gtid_wait(f4682075-c1b9-11eb-86b2-000c2934cc5a:1-21) completed on 192.168.10.53(192.168.10.53:3306). Executed 0 events.
Wed Jun  2 16:55:53 2021 - [info] End of log messages from 192.168.10.53.
Wed Jun  2 16:55:53 2021 - [info] -- Slave on host 192.168.10.53(192.168.10.53:3306) started.
Wed Jun  2 16:55:53 2021 - [info] All new slave servers recovered successfully.
Wed Jun  2 16:55:53 2021 - [info] 
Wed Jun  2 16:55:53 2021 - [info] * Phase 5: New master cleanup phase..
Wed Jun  2 16:55:53 2021 - [info] 
Wed Jun  2 16:55:53 2021 - [info] Resetting slave info on the new master..
Wed Jun  2 16:55:53 2021 - [info]  192.168.10.52: Resetting slave info succeeded.
Wed Jun  2 16:55:53 2021 - [info] Master failover to 192.168.10.52(192.168.10.52:3306) completed successfully.
Wed Jun  2 16:55:53 2021 - [info] Deleted server1 entry from /etc/mha/app1.cnf .
Wed Jun  2 16:55:53 2021 - [info] 

# 切換完成
----- Failover Report -----

app1: MySQL Master failover 192.168.10.51(192.168.10.51:3306) to 192.168.10.52(192.168.10.52:3306) succeeded

Master 192.168.10.51(192.168.10.51:3306) is down!

Check MHA Manager logs at db3:/var/log/mha/app1/manager for details.

Started automated(non-interactive) failover.
Invalidated master IP address on 192.168.10.51(192.168.10.51:3306)
Selected 192.168.10.52(192.168.10.52:3306) as a new master.
192.168.10.52(192.168.10.52:3306): OK: Applying all logs succeeded.
192.168.10.52(192.168.10.52:3306): OK: Activated master IP address.
192.168.10.53(192.168.10.53:3306): OK: Slave started, replicating from 192.168.10.52(192.168.10.52:3306)
192.168.10.52(192.168.10.52:3306): Resetting slave info succeeded.
Master failover to 192.168.10.52(192.168.10.52:3306) completed successfully.

2、主動切換

故障後進行主動切換,查看主從狀態和vip環境確認

主庫已切換至db2

[root@db3 ~ ]# mysql -uroot -p123456 -e "show slave status\G;" |grep Master_Host
mysql: [Warning] Using a password on the command line interface can be insecure.
                  Master_Host: 192.168.10.52   # 主庫已變更
vip`已切換至`db2
[root@db2 ~]# ip a |grep eth0
2: eth0: <broadcast,multicast,up,lower_up> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    inet 192.168.10.52/24 brd 192.168.10.255 scope global noprefixroute eth0
    inet 192.168.10.49/24 brd 192.168.10.255 scope global secondary eth0:1

3、在線切換

3.1 只切換角色

3.1.1 切換命令

masterha_master_switch  --conf=/etc/mha/app1.cnf --master_state=alive --new_master_host=192.168.10.51 --orig_master_is_new_slave --running_updates_limit=10000

master_ip_online_change_script is not defined. If you do not disable writes on the current master manually, applications keep writing on the current master. Is it ok to proceed? (yes/NO): yes

# 命令解析
--conf=/etc/mha/app1.cnf  # 指定配置文件
--master_state=alive      # 主庫在線的情況下進行切換
--new_master_host=192.168.10.51   # 指定新主ip
--orig_master_is_new_slave  # 原主庫改爲從庫
running_updates_limit=10000  # 網絡延時(ping值)超過1w毫秒不進行切換

3.1.2 注意內容

此命令一般不會在生產環境使用,只用於測試
1、需要關閉mha-manager,不然切換無法執行成功。報錯如下:

Tue Jun  8 10:03:54 2021 - [error][/usr/share/perl5/vendor_perl/MHA/MasterRotate.pm, ln143] Getting advisory lock failed on the current master. MHA Monitor runs on the current master. Stop MHA Manager/Monitor and try again.
Tue Jun  8 10:03:54 2021 - [error][/usr/share/perl5/vendor_perl/MHA/ManagerUtil.pm, ln177] Got ERROR:  at /usr/bin/masterha_master_switch line 53.

2、需要將原主庫鎖住Flush table with read lock,使其只讀。因爲在切換完主從後,vip尚未切換,此段時間數據還會寫入到原主庫,導致數據不一致。警告如下:

It is better to execute FLUSH NO_WRITE_TO_BINLOG TABLES on the master before switching. Is it ok to execute on 192.168.10.52(192.168.10.52:3306)? (YES/no): yes

3、需要手工切換vip

4、需要重新拉取主庫binlog(binlog-server)

3.2 腳本功能實現

功能: 在線切換時,自動鎖原主庫,VIP自動切換

3.2.1 準備腳本

vim /usr/local/bin/master_ip_online_change
#!/usr/bin/env perl

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_is_new_slave, $orig_master_host,
  $orig_master_ip,       $orig_master_port,         $orig_master_user,
  $orig_master_password, $orig_master_ssh_user,     $new_master_host,
  $new_master_ip,        $new_master_port,          $new_master_user,
  $new_master_password,  $new_master_ssh_user,
);
 
###########################################################################
my $vip = "10.0.0.55";
my $key = "1";
my $ssh_start_vip = "/sbin/ifconfig ens33:$key $vip";
my $ssh_stop_vip = "/sbin/ifconfig ens33:$key $vip down";
my $ssh_Bcast_arp= "/sbin/arping -I ens33 -c 3 -A 10.0.0.55";
###########################################################################
 
GetOptions(
  'command=s'                => \$command,
  'orig_master_is_new_slave' => \$orig_master_is_new_slave,
  '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,
  'orig_master_ssh_user=s'   => \$orig_master_ssh_user,
  '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,
  'new_master_ssh_user=s'    => \$new_master_ssh_user,
);
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 = 0 unless ($running_time_threshold);
  $type                   = 0 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*$/$1/ 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 >= 1 );
    if ( $type >= 1 ) {
      next if ( defined($command) && $command eq "Sleep" );
      next if ( defined($command) && $command eq "Connect" );
    }
    if ( $type >= 2 ) {
      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
    # 1. Set read_only= 1 on the new master
    # 2. DROP USER so that no app user can establish new connections
    # 3. Set read_only= 1 on the current master
    # 4. Kill current queries
    # * Any database access failure will result in script die.
    my $exit_code = 1;
    eval {
      ## Setting read_only=1 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, 1 );
      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, 1 );
      ## 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 * 100 milliseconds so that current connections can exit
      my $time_until_read_only = 15;
      $_tstart = [gettimeofday];
      my @threads = get_threads_util( $orig_master_handler->{dbh},
        $orig_master_handler->{connection_id} );
      while ( $time_until_read_only > 0 && $#threads >= 0 ) {
        if ( $time_until_read_only % 5 == 0 ) {
          printf
"%s Waiting all running %d threads are disconnected.. (max %d milliseconds)\n",
            current_time_us(), $#threads + 1, $time_until_read_only * 100;
          if ( $#threads < 5 ) {
            print Data::Dumper->new( [$_] )->Indent(0)->Terse(1)->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=1 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 * 100 milliseconds so that current update queries can complete
      my $time_until_kill_threads = 5;
      @threads = get_threads_util( $orig_master_handler->{dbh},
        $orig_master_handler->{connection_id} );
      while ( $time_until_kill_threads > 0 && $#threads >= 0 ) {
        if ( $time_until_kill_threads % 5 == 0 ) {
          printf
"%s Waiting all running %d queries are disconnected.. (max %d milliseconds)\n",
            current_time_us(), $#threads + 1, $time_until_kill_threads * 100;
          if ( $#threads < 5 ) {
            print Data::Dumper->new( [$_] )->Indent(0)->Terse(1)->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 "disable 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 >= 0 );
      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 = 0;
    };
    if ($@) {
      warn "Got Error: $@\n";
      exit $exit_code;
    }
    exit $exit_code;
  }
  elsif ( $command eq "start" ) {
    ## Activating master ip on the new master
    # 1. Create app user with write privileges
    # 2. Moving backup script if needed
    # 3. Register new master's ip to the catalog database
    my $exit_code = 10;
    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, 1 );
      ## Set read_only=0 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 "enable the VIP: $vip on the new master: $new_master_host \n ";
      &start_vip();
###############################################################################
      $exit_code = 0;
    };
    if ($@) {
      warn "Got Error: $@\n";
      exit $exit_code;
    }
    exit $exit_code;
  }
  elsif ( $command eq "status" ) {
    # do nothing
    exit 0;
  }
  else {
    &usage();
    exit 1;
  }
}
###########################################################################
sub start_vip() {
	`ssh $new_master_ssh_user\@$new_master_host \" $ssh_start_vip \"`;
}
sub stop_vip() {
	`ssh $orig_master_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;
}

根據自身環境修改以下內容(與vip腳本設置一致)

my $vip = '192.168.10.49/24';      # vip網段,與各節點服務器網段一致。
my $key = '1';                     # 虛擬網卡eth0:1 的 1
my $ssh_start_vip = "/sbin/ifconfig eth0:$key $vip";  # 網卡按照實際網卡名稱填寫
my $ssh_stop_vip = "/sbin/ifconfig eth0:$key down";   # 網卡按照實際網卡名稱填寫
my $ssh_Bcast_arp= "/sbin/arping -I eth0 -c 3 -A 192.168.10.49"; # 重新聲明mac地址,arp

3.2.2 mha配置文件

修改mha-manager配置文件,增加一下內容

vim /etc/mha/app1.cnf
master_ip_online_change_script=/usr/local/bin/master_ip_online_change

3.2.3 關停mha服務

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

3.2.4 檢查repl

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

3.2.5 在線切換

masterha_master_switch  --conf=/etc/mha/app1.cnf --master_state=alive --new_master_host=192.168.10.51 --orig_master_is_new_slave --running_updates_limit=10000

From:
192.168.10.52(192.168.10.52:3306) (current master)
 +--192.168.10.51(192.168.10.51:3306)
 +--192.168.10.53(192.168.10.53:3306)

To:
192.168.10.51(192.168.10.51:3306) (new master)
 +--192.168.10.53(192.168.10.53:3306)
 +--192.168.10.52(192.168.10.52:3306)
 
Tue Jun  8 10:44:10 2021 - [info] Switching master to 192.168.10.51(192.168.10.51:3306) completed successfully.  # 切換成功

3.2.6 確認vip

[root@db1 ~]# ip a |grep eth0
2: eth0: <broadcast,multicast,up,lower_up> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    inet 192.168.10.51/24 brd 192.168.10.255 scope global noprefixroute eth0
    inet 192.168.10.49/24 brd 192.168.10.255 scope global secondary eth0:1

3.2.7 重構binlog-server

1、查詢當前salve當前拿取的binlog日誌

[root@db3 ~]# mysql -uroot -p123456 -e "show slave status \G"|grep "Master_Log" 
              Master_Log_File: mysql-bin.000006
          Read_Master_Log_Pos: 196
        Relay_Master_Log_File: mysql-bin.000006
          Exec_Master_Log_Pos: 196

2、關停當前binlog-server服務,清除binlog-server目錄里拉取的日誌文件

[root@db03 bin]# ps -ef |grep mysqlbinlog
root      28144  16272  0 17:50 pts/1    00:00:00 mysqlbinlog -R --host=192.168.10.52 --user=mha --password=x x --raw --stop-never mysql-bin.000005
root      28529  16272  0 18:03 pts/1    00:00:00 grep --color=auto mysqlbinlog
[root@db03 bin]# kill -9 28144
[root@db03 bin]# cd /data/binlog_server/
[root@db03 binlog_server]# ll
total 4
-rw-r----- 1 root root 194 Apr  1 17:50 mysql-bin.000005
[root@db03 binlog_server]# rm -rf *
[1] 28534

3、進入日誌目錄,重新啓動binlog-server守護進程

[root@db03 bin]# cd /data/binlog_server/
[root@db03 binlog_server]# mysqlbinlog  -R --host=192.168.10.51 --user=mha --password=mha --raw  --stop-never mysql-bin.000009 &

3.2.8 重新啓動mha

[root@db03 bin]# nohup masterha_manager --conf=/etc/mha/app1.cnf --remove_dead_master_conf --ignore_last_failover  < /dev/null> /var/log/mha/app1/manager.log 2>&1 &

[root@db03 binlog_server]# masterha_check_status   --conf=/etc/mha/app1.cnf 
app1 (pid:28535) is running(0:PING_OK), master:192.168.10.51

mysql

</broadcast,multicast,up,lower_up></broadcast,multicast,up,lower_up>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章