Mysql MHA高可用配置

機(jī)器

主機(jī)名 角色 IP server_id 類型
PROD-mysql174 監(jiān)控主機(jī) 10.10.40.174 - 監(jiān)控復(fù)制組
PROD-mysql161 10.10.40.161 1 監(jiān)控復(fù)制組
PROD-mysql160 備主 10.10.40.160 2 監(jiān)控復(fù)制組
PROD-mysql169 10.10.40.169 3 監(jiān)控復(fù)制組

MySQL安裝和配置

在三臺MySQL數(shù)據(jù)機(jī)器(一主二從)上分別安裝MySQL5.7版本。

安裝

在官網(wǎng)下載mysql-cummunity的rpm package文件。

wget https://repo.mysql.com//mysql57-community-release-el7-11.noarch.rpm

安裝rpm package

yum localinstall mysql57-community-release-el7-11.noarch.rpm

安裝MySQL5.7

yum install mysql-community-server

配置

vim /etc/my.cnf
Master
[mysqld]
datadir=/data/mysql
socket=/data/mysql/mysql.sock

# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

# 字符編碼為utf8
character_set_server = utf8

server-id=161
log-bin=mysql-mysql-master-bin
log-bin-index=mysql-master-bin.index

gtid_mode = on
#開啟gtid,必須主從全開
enforce_gtid_consistency = 1
log_slave_updates = 1
##開啟半同步復(fù)制  否則自動切換主從的時候會報主鍵錯誤
plugin_load = "rpl_semi_sync_master=semisync_master.so;rpl_semi_sync_slave=semisync_slave.so"
loose_rpl_semi_sync_master_enabled = 1
loose_rpl_semi_sync_slave_enabled = 1
loose_rpl_semi_sync_master_timeout = 5000

[mysql]
socket=/data/mysql/mysql.sock

Slave
[mysqld]
datadir=/data/mysql
socket=/data/mysql/mysql.sock

# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

# 字符編碼為utf8
character_set_server = utf8

server-id=160
log-bin=mysql-bin
relay-log = slave-relay-bin
relay-log-index = slave-relay-bin.index

gtid_mode = on
#開啟gtid,必須主從全開
enforce_gtid_consistency = 1
log_slave_updates = 1
##開啟半同步復(fù)制  否則自動切換主從的時候會報主鍵錯誤
plugin_load = "rpl_semi_sync_master=semisync_master.so;rpl_semi_sync_slave=semisync_slave.so"
loose_rpl_semi_sync_master_enabled = 1
loose_rpl_semi_sync_slave_enabled = 1
loose_rpl_semi_sync_master_timeout = 5000

[mysql]
socket=/data/mysql/mysql.sock

注意:binlog-do-db 和 replicate-ignore-db 設(shè)置必須相同。 MHA 在啟動時候會檢測過濾規(guī)則,如果過濾規(guī)則不同,MHA 不啟動監(jiān)控和故障轉(zhuǎn)移,這里沒有設(shè)置。

注意:如不在末尾添加客戶端socket的路徑,默認(rèn)會去/var/lib/mysql下去尋找,由于我們修改了路徑,找不到就會出現(xiàn)錯誤:Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

創(chuàng)建data文件夾
mkdir /data/mysql
chown -R mysql:mysql /etc/mysql
初始化
mysqld --initialize --user=mysql
啟動MySQL服務(wù)
systemctl restart mysqld
獲取臨時密碼
grep "temporary password" /var/log/mysqld.log
執(zhí)行登錄命令

輸入上面的臨時密碼lMx<qe6jA1ig

mysql -uroot -p
修改密碼
ALTER USER 'root'@'localhost' IDENTIFIED BY 'haijizq2017';
flush privileges;

重新登錄,使用新密碼
mysql -uroot -p
添加復(fù)制用戶
grant replication slave on *.* to 'repl'@'10.10.40.%' identified by 'haijizq2017';
添加監(jiān)控用戶
grant all privileges on *.* to 'root'@'10.10.40.%' identified  by 'haijizq2017';
更新權(quán)限
flush privileges;
獲取Master的bin-log信息

在master機(jī)器上執(zhí)行

show master staus;

顯示如下內(nèi)容:

   
+-------------------------+----------+--------------+------------------+------------------------------------------+
| File                    | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set                        |
+-------------------------+----------+--------------+------------------+------------------------------------------+
| mysql-master-bin.000001 |      194 |              |                  | bf29fa39-91e2-11e7-a6a8-005056904498:1-6 |
+-------------------------+----------+--------------+------------------+------------------------------------------+

   

File:mysql-master-bin.000001

Position:194

配置從服務(wù)器的Master信息
change master to master_host='10.10.40.161',master_user='repl',master_password='haijizq2017',master_log_file='mysql-master-bin.000001',master_log_pos=194;
#設(shè)置從服務(wù)器只讀
set global read_only=1
啟動slave
start slave

設(shè)置從服務(wù)器只讀不要在配置文件里寫,重點?。。〔蝗徊恍⌒膹姆?wù)器寫入了數(shù)據(jù),有你哭的

MHA Manager安裝和配置

安裝

安裝mha4mysql-node

yum localinstall mha4mysql-node-0.57-0.el7.noarch.rpm

安裝mha4mysql-manager

yum localinstall mha4mysql-manager-0.57-0.el7.noarch.rpm

配置

創(chuàng)建配置目錄和文件
cd /etc
mkdir masterha
vim app.cnf

app.cnf配置文件內(nèi)容如下:

[server default]
manager_workdir=/etc/masterha/app/
manager_log=/var/log/masterha/app/manager.log
master_binlog_dir=/data/mysql
master_ip_failover_script= /usr/local/bin/master_ip_failover
master_ip_online_change_script= /usr/local/bin/master_ip_online_change
user=root
password=haijizq2017
ping_interval=1
remote_workdir=/tmp
repl_user=repl
repl_password=haijizq2017
report_script=/usr/local/bin/send_report
secondary_check_script= /usr/bin/masterha_secondary_check -s 10.10.40.160 -s 10.10.40.169            
shutdown_script=""
ssh_user=root

[server1]
hostname=10.10.40.161
port=3306

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

[server3]
hostname=10.10.40.169
port=3306
腳本類型 是否必要 作用
master_ip_failover_script 自動failover時候的切換腳本
master_ip_online_change_script 在線時vip切換腳本
report_script 發(fā)生故障切換后發(fā)送報警的腳本
secondary_check_script row 1 col 2
shutdown_script 故障發(fā)生后關(guān)閉主機(jī)的腳本,防止關(guān)閉主機(jī)時發(fā)生腦裂

配置檢測

masterha_check_ssh

檢測各節(jié)點SSH連接是否正常

masterha_check_ssh --conf=/etc/masterha/app.cnf 

檢測結(jié)果:

Tue Sep  5 14:48:38 2017 - [warning] Global configuration file /etc/masterha_default.cnf not found. Skipping.
Tue Sep  5 14:48:38 2017 - [info] Reading application default configuration from /etc/masterha/app.cnf..
Tue Sep  5 14:48:38 2017 - [info] Reading server configuration from /etc/masterha/app.cnf..
Tue Sep  5 14:48:38 2017 - [info] Starting SSH connection tests..
Tue Sep  5 14:48:39 2017 - [debug] 
Tue Sep  5 14:48:38 2017 - [debug]  Connecting via SSH from root@10.10.40.161(10.10.40.161:22) to root@10.10.40.160(10.10.40.160:22)..
Tue Sep  5 14:48:39 2017 - [debug]   ok.
Tue Sep  5 14:48:39 2017 - [debug]  Connecting via SSH from root@10.10.40.161(10.10.40.161:22) to root@10.10.40.169(10.10.40.169:22)..
Tue Sep  5 14:48:39 2017 - [debug]   ok.
Tue Sep  5 14:48:39 2017 - [debug] 
Tue Sep  5 14:48:39 2017 - [debug]  Connecting via SSH from root@10.10.40.160(10.10.40.160:22) to root@10.10.40.161(10.10.40.161:22)..
Tue Sep  5 14:48:39 2017 - [debug]   ok.
Tue Sep  5 14:48:39 2017 - [debug]  Connecting via SSH from root@10.10.40.160(10.10.40.160:22) to root@10.10.40.169(10.10.40.169:22)..
Tue Sep  5 14:48:39 2017 - [debug]   ok.
Tue Sep  5 14:48:40 2017 - [debug] 
Tue Sep  5 14:48:39 2017 - [debug]  Connecting via SSH from root@10.10.40.169(10.10.40.169:22) to root@10.10.40.161(10.10.40.161:22)..
Tue Sep  5 14:48:40 2017 - [debug]   ok.
Tue Sep  5 14:48:40 2017 - [debug]  Connecting via SSH from root@10.10.40.169(10.10.40.169:22) to root@10.10.40.160(10.10.40.160:22)..
Tue Sep  5 14:48:40 2017 - [debug]   ok.
Tue Sep  5 14:48:40 2017 - [info] All SSH connection tests passed successfully.

masterha_check_repl

檢查集群健康狀態(tài)

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

檢查結(jié)果:

Tue Sep  5 14:50:02 2017 - [warning] Global configuration file /etc/masterha_default.cnf not found. Skipping.
Tue Sep  5 14:50:02 2017 - [info] Reading application default configuration from /etc/masterha/app.cnf..
Tue Sep  5 14:50:02 2017 - [info] Reading server configuration from /etc/masterha/app.cnf..
Tue Sep  5 14:50:02 2017 - [info] MHA::MasterMonitor version 0.57.
Tue Sep  5 14:50:03 2017 - [info] GTID failover mode = 1
Tue Sep  5 14:50:03 2017 - [info] Dead Servers:
Tue Sep  5 14:50:03 2017 - [info] Alive Servers:
Tue Sep  5 14:50:03 2017 - [info]   10.10.40.161(10.10.40.161:3306)
Tue Sep  5 14:50:03 2017 - [info]   10.10.40.160(10.10.40.160:3306)
Tue Sep  5 14:50:03 2017 - [info]   10.10.40.169(10.10.40.169:3306)
Tue Sep  5 14:50:03 2017 - [info] Alive Slaves:
Tue Sep  5 14:50:03 2017 - [info]   10.10.40.160(10.10.40.160:3306)  Version=5.7.19-log (oldest major version between slaves) log-bin:enabled
Tue Sep  5 14:50:03 2017 - [info]     GTID ON
Tue Sep  5 14:50:03 2017 - [info]     Replicating from 10.10.40.161(10.10.40.161:3306)
Tue Sep  5 14:50:03 2017 - [info]     Primary candidate for the new Master (candidate_master is set)
Tue Sep  5 14:50:03 2017 - [info]   10.10.40.169(10.10.40.169:3306)  Version=5.7.19-log (oldest major version between slaves) log-bin:enabled
Tue Sep  5 14:50:03 2017 - [info]     GTID ON
Tue Sep  5 14:50:03 2017 - [info]     Replicating from 10.10.40.161(10.10.40.161:3306)
Tue Sep  5 14:50:03 2017 - [info] Current Alive Master: 10.10.40.161(10.10.40.161:3306)
Tue Sep  5 14:50:03 2017 - [info] Checking slave configurations..
Tue Sep  5 14:50:03 2017 - [info] Checking replication filtering settings..
Tue Sep  5 14:50:03 2017 - [info]  binlog_do_db= , binlog_ignore_db= 
Tue Sep  5 14:50:03 2017 - [info]  Replication filtering check ok.
Tue Sep  5 14:50:03 2017 - [info] GTID (with auto-pos) is supported. Skipping all SSH and Node package checking.
Tue Sep  5 14:50:03 2017 - [info] Checking SSH publickey authentication settings on the current master..
Tue Sep  5 14:50:03 2017 - [info] HealthCheck: SSH to 10.10.40.161 is reachable.
Tue Sep  5 14:50:03 2017 - [info] 
10.10.40.161(10.10.40.161:3306) (current master)
 +--10.10.40.160(10.10.40.160:3306)
 +--10.10.40.169(10.10.40.169:3306)

Tue Sep  5 14:50:03 2017 - [info] Checking replication health on 10.10.40.160..
Tue Sep  5 14:50:03 2017 - [info]  ok.
Tue Sep  5 14:50:03 2017 - [info] Checking replication health on 10.10.40.169..
Tue Sep  5 14:50:03 2017 - [info]  ok.
Tue Sep  5 14:50:03 2017 - [warning] master_ip_failover_script is not defined.
Tue Sep  5 14:50:03 2017 - [warning] shutdown_script is not defined.
Tue Sep  5 14:50:03 2017 - [info] Got exit code 0 (Not master dead).

MySQL Replication Health is OK.

注意,因為VIP沒有配置,master_ip_failover_script先注釋掉了。

masterha_check_status

檢查manager的工作狀態(tài)

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

檢查結(jié)果:

app is stopped(2:NOT_RUNNING).

注意:如果正常,會顯示"PING_OK",否則會顯示"NOT_RUNNING",這代表MHA監(jiān)控沒有開啟。

啟動Manager

創(chuàng)建啟動腳本startup.sh
#!/bin/sh
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 &  
啟動參數(shù)介紹:

--remove_dead_master_conf      該參數(shù)代表當(dāng)發(fā)生主從切換后,老的主庫的ip將會從配置文件中移除。

--manger_log                            日志存放位置

--ignore_last_failover                 在缺省情況下,如果MHA檢測到連續(xù)發(fā)生宕機(jī),且兩次宕機(jī)間隔不足8小時的話,則不會進(jìn)行Failover,之所以這樣限制是為了避免ping-pong效應(yīng)。該參數(shù)代表忽略上次MHA觸發(fā)切換產(chǎn)生的文件,默認(rèn)情況下,MHA發(fā)生切換后會在日志目錄,也就是上面我設(shè)置的/data產(chǎn)生app.failover.complete文件,下次再次切換的時候如果發(fā)現(xiàn)該目錄下存在該文件將不允許觸發(fā)切換,除非在第一次切換后收到刪除該文件,為了方便,這里設(shè)置為--ignore_last_failover。
啟動
./startup.sh
檢測是否成功
masterha_check_status --conf=/etc/masterha/app.cnf

檢測結(jié)果

app (pid:2382) is running(0:PING_OK), master:10.10.40.161

Manager已經(jīng)正常運行,監(jiān)控10.10.40.161

創(chuàng)建停止腳本
#!/bin/sh
masterha_stop --conf=/etc/masterha/app.cnf  
測試停止
[root@PROD-mysql174 data]# ./stop.sh 
Stopped app successfully.

恢復(fù)Manager

./startup.sh

Keepalived安裝和配置

在Master和備用Master上進(jìn)行配置

安裝

yum install keepalived

Master配置

! Configuration File for keepalived

global_defs {
   router_id MySQL-HA
}

vrrp_instance VI_1 {
    state BACKUP
    interface ens160
    virtual_router_id 51
    priority 150
    advert_int 1
    nopreempt
    
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        10.10.40.159
    }
}

注意:這里去掉了發(fā)送郵件的配置,因為公共郵箱還沒有到位。

  • router_id MySQL-HA是keepalived組的名稱
  • 將虛擬ip10.10.40.159綁定到該主機(jī)的ens160網(wǎng)卡上,并且設(shè)置了狀態(tài)為backup模式。
  • keepalived的模式設(shè)置為非搶占模式(nopreempt)
  • priority 150表示設(shè)置的優(yōu)先級為150。

備用Master配置

vim /etc/keepalived/keepalived.conf
! Configuration File for keepalived

global_defs {
   router_id MySQL-HA
}

vrrp_instance VI_1 {
    state BACKUP
    interface ens160
    virtual_router_id 51
    priority 120
    advert_int 1
    nopreempt
    
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        10.10.40.159
    }
}

Manager配置

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 = '10.10.40.159';
my $ssh_start_vip = "systemctl start keepalived";
my $ssh_stop_vip = "systemctl stop keepalived";

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";
}
[root@PROD-mysql174 ~]# masterha_check_repl --conf=/etc/masterha/app.cnf
Tue Sep  5 15:44:47 2017 - [warning] Global configuration file /etc/masterha_default.cnf not found. Skipping.
Tue Sep  5 15:44:47 2017 - [info] Reading application default configuration from /etc/masterha/app.cnf..
Tue Sep  5 15:44:47 2017 - [info] Reading server configuration from /etc/masterha/app.cnf..
Tue Sep  5 15:44:47 2017 - [info] MHA::MasterMonitor version 0.57.
Tue Sep  5 15:44:48 2017 - [info] GTID failover mode = 1
Tue Sep  5 15:44:48 2017 - [info] Dead Servers:
Tue Sep  5 15:44:48 2017 - [info] Alive Servers:
Tue Sep  5 15:44:48 2017 - [info]   10.10.40.161(10.10.40.161:3306)
Tue Sep  5 15:44:48 2017 - [info]   10.10.40.160(10.10.40.160:3306)
Tue Sep  5 15:44:48 2017 - [info]   10.10.40.169(10.10.40.169:3306)
Tue Sep  5 15:44:48 2017 - [info] Alive Slaves:
Tue Sep  5 15:44:48 2017 - [info]   10.10.40.160(10.10.40.160:3306)  Version=5.7.19-log (oldest major version between slaves) log-bin:enabled
Tue Sep  5 15:44:48 2017 - [info]     GTID ON
Tue Sep  5 15:44:48 2017 - [info]     Replicating from 10.10.40.161(10.10.40.161:3306)
Tue Sep  5 15:44:48 2017 - [info]     Primary candidate for the new Master (candidate_master is set)
Tue Sep  5 15:44:48 2017 - [info]   10.10.40.169(10.10.40.169:3306)  Version=5.7.19-log (oldest major version between slaves) log-bin:enabled
Tue Sep  5 15:44:48 2017 - [info]     GTID ON
Tue Sep  5 15:44:48 2017 - [info]     Replicating from 10.10.40.161(10.10.40.161:3306)
Tue Sep  5 15:44:48 2017 - [info] Current Alive Master: 10.10.40.161(10.10.40.161:3306)
Tue Sep  5 15:44:48 2017 - [info] Checking slave configurations..
Tue Sep  5 15:44:48 2017 - [info] Checking replication filtering settings..
Tue Sep  5 15:44:48 2017 - [info]  binlog_do_db= , binlog_ignore_db= 
Tue Sep  5 15:44:48 2017 - [info]  Replication filtering check ok.
Tue Sep  5 15:44:48 2017 - [info] GTID (with auto-pos) is supported. Skipping all SSH and Node package checking.
Tue Sep  5 15:44:48 2017 - [info] Checking SSH publickey authentication settings on the current master..
Tue Sep  5 15:44:48 2017 - [info] HealthCheck: SSH to 10.10.40.161 is reachable.
Tue Sep  5 15:44:48 2017 - [info] 
10.10.40.161(10.10.40.161:3306) (current master)
 +--10.10.40.160(10.10.40.160:3306)
 +--10.10.40.169(10.10.40.169:3306)

Tue Sep  5 15:44:48 2017 - [info] Checking replication health on 10.10.40.160..
Tue Sep  5 15:44:48 2017 - [info]  ok.
Tue Sep  5 15:44:48 2017 - [info] Checking replication health on 10.10.40.169..
Tue Sep  5 15:44:48 2017 - [info]  ok.
Tue Sep  5 15:44:48 2017 - [info] Checking master_ip_failover_script status:
Tue Sep  5 15:44:48 2017 - [info]   /usr/local/bin/master_ip_failover --command=status --ssh_user=root --orig_master_host=10.10.40.161 --orig_master_ip=10.10.40.161 --orig_master_port=3306 


IN SCRIPT TEST====/etc/init.d/keepalived stop==/etc/init.d/keepalived start===

Checking the Status of the script.. OK 
Tue Sep  5 15:44:48 2017 - [info]  OK.
Tue Sep  5 15:44:48 2017 - [warning] shutdown_script is not defined.
Tue Sep  5 15:44:48 2017 - [info] Got exit code 0 (Not master dead).

MySQL Replication Health is OK.

#!/usr/bin/env perl

#  Copyright (C) 2011 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 2 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.,
#  51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  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 = '10.10.40.159/24';  # Virtual IP 
my $key = "1"; 
my $ssh_start_vip = "/sbin/ifconfig ens160:$key $vip";
my $ssh_stop_vip = "/sbin/ifconfig ens160:$key down";
my $ssh_user = "root";
my $new_master_password='haijizq2017';
my $orig_master_password='haijizq2017';
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 = 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 "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 >= 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

# We don't return error even though activating updatable accounts/ip failed so that we don't interrupt slaves' recovery.
# If exit code is 0 or 10, MHA does not abort
    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 "Enabling 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;
  }
}

# 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;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容