Mysql MHA高可用配置

机器

主机名 角色 IP server_id 类型
PROD-mysql174 监控主机 10.10.40.174 - 监控复制组
PROD-mysql161 10.10.40.161 1 监控复制组
PROD-mysql160 备主 10.10.40.160 2 监控复制组
PROD-mysql169 10.10.40.169 3 监控复制组

MySQL安装和配置

在三台MySQL数据机器(一主二从)上分别安装MySQL5.7版本。

安装

在官网下载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
##开启半同步复制  否则自动切换主从的时候会报主键错误
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
##开启半同步复制  否则自动切换主从的时候会报主键错误
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 设置必须相同。 MHA 在启动时候会检测过滤规则,如果过滤规则不同,MHA 不启动监控和故障转移,这里没有设置。

注意:如不在末尾添加客户端socket的路径,默认会去/var/lib/mysql下去寻找,由于我们修改了路径,找不到就会出现错误:Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

创建data文件夹
mkdir /data/mysql
chown -R mysql:mysql /etc/mysql
初始化
mysqld --initialize --user=mysql
启动MySQL服务
systemctl restart mysqld
获取临时密码
grep "temporary password" /var/log/mysqld.log
执行登录命令

输入上面的临时密码lMx

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

重新登录,使用新密码
mysql -uroot -p
添加复制用户
grant replication slave on *.* to 'repl'@'10.10.40.%' identified by 'haijizq2017';
添加监控用户
grant all privileges on *.* to 'root'@'10.10.40.%' identified  by 'haijizq2017';
更新权限
flush privileges;
获取Master的bin-log信息

在master机器上执行

show master staus;

显示如下内容:

   
+-------------------------+----------+--------------+------------------+------------------------------------------+
| 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

配置从服务器的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;
#设置从服务器只读
set global read_only=1
启动slave
start slave

设置从服务器只读不要在配置文件里写,重点!!!不然不小心从服务器写入了数据,有你哭的

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

配置

创建配置目录和文件
cd /etc
mkdir masterha
vim app.cnf

app.cnf配置文件内容如下:

[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 发生故障切换后发送报警的脚本
secondary_check_script row 1 col 2
shutdown_script 故障发生后关闭主机的脚本,防止关闭主机时发生脑裂

配置检测

masterha_check_ssh

检测各节点SSH连接是否正常

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

检测结果:

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 [email protected](10.10.40.161:22) to [email protected](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 [email protected](10.10.40.161:22) to [email protected](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 [email protected](10.10.40.160:22) to [email protected](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 [email protected](10.10.40.160:22) to [email protected](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 [email protected](10.10.40.169:22) to [email protected](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 [email protected](10.10.40.169:22) to [email protected](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

检查集群健康状态

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

检查结果:

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的工作状态

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

检查结果:

app is stopped(2:NOT_RUNNING).

注意:如果正常,会显示"PING_OK",否则会显示"NOT_RUNNING",这代表MHA监控没有开启。

启动Manager

创建启动脚本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 &  
启动参数介绍:

--remove_dead_master_conf      该参数代表当发生主从切换后,老的主库的ip将会从配置文件中移除。

--manger_log                            日志存放位置

--ignore_last_failover                 在缺省情况下,如果MHA检测到连续发生宕机,且两次宕机间隔不足8小时的话,则不会进行Failover,之所以这样限制是为了避免ping-pong效应。该参数代表忽略上次MHA触发切换产生的文件,默认情况下,MHA发生切换后会在日志目录,也就是上面我设置的/data产生app.failover.complete文件,下次再次切换的时候如果发现该目录下存在该文件将不允许触发切换,除非在第一次切换后收到删除该文件,为了方便,这里设置为--ignore_last_failover。
启动
./startup.sh
检测是否成功
masterha_check_status --conf=/etc/masterha/app.cnf

检测结果

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

Manager已经正常运行,监控10.10.40.161

创建停止脚本
#!/bin/sh
masterha_stop --conf=/etc/masterha/app.cnf  
测试停止
[root@PROD-mysql174 data]# ./stop.sh 
Stopped app successfully.

恢复Manager

./startup.sh

Keepalived安装和配置

在Master和备用Master上进行配置

安装

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
    }
}

注意:这里去掉了发送邮件的配置,因为公共邮箱还没有到位。

  • router_id MySQL-HA是keepalived组的名称
  • 将虚拟ip10.10.40.159绑定到该主机的ens160网卡上,并且设置了状态为backup模式。
  • keepalived的模式设置为非抢占模式(nopreempt)
  • priority 150表示设置的优先级为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;
}

你可能感兴趣的:(Mysql MHA高可用配置)