1. 程式人生 > >MySQL 之 MHA + ProxySQL + keepalived 實現讀寫分離,高可用(一)

MySQL 之 MHA + ProxySQL + keepalived 實現讀寫分離,高可用(一)

don replica ifconfig soft 似的 恢復 select 8.0 ext

技術分享圖片

準備服務器:

docker network create --subnet=192.168.0.0/16 staticnet
docker run -d --privileged -v `pwd`/mysql_data:/data -p 3001:3306 --name mysql5-master --hostname mysql5-master --net staticnet --ip 192.168.0.101 eiki/mysql:5.7.23 /usr/sbin/init docker run -d --privileged -v `pwd`/mysql_data:/data -p 3002:3306 --name mysql5-slave --hostname mysql5-slave --net staticnet --ip 192.168.0.102 eiki/mysql:5.7.23 /usr/sbin/init docker run -d --privileged -v `pwd`/mysql_data:/data -p 3003:3306 --name mysql5-s2 --hostname mysql5-s2 --net staticnet --ip 192.168.0.103 eiki/mysql:5.7.23 /usr/sbin/init docker run -d --privileged -v `pwd`/mysql_data:/data -p 7032:6032 -p 6080:6080 --name proxysql2 --hostname proxysql2 --net staticnet --ip 192.168.0.202 eiki/proxysql:latest /usr/sbin/init docker run -d --privileged -v `pwd`/mysql_data:/data -p 6032:6032 -p 7080:6080 --name proxysql --hostname proxysql --net staticnet --ip 192.168.0.201 eiki/proxysql:latest /usr/sbin/init 其中6032是管理端口,6033是程序端口,6080是http端口

主從搭建(一主兩從)

MySQL安裝過程略

主庫/etc/my.cnf

[mysql]
prompt = [\\u@\\h][\\d]>\\_
port                    = 3306
socket                  = /usr/local/mysql/mysql.sock

[mysqld]
user                    = mysql
port                    = 3306
server-id               = 1
pid-file                = /usr/local/mysql/mysqld.pid
socket                  = /usr/local/mysql/mysql.sock
basedir                 = /usr/local/mysql
datadir                 = /usr/local/mysql/data
log-bin                 = master-bin
log-bin-index           = master-bin.index
relay_log_purge         = 0

#以下兩個參數不加,從執行change不可以指定channel(ERROR 3077 (HY000))
master_info_repository  =table      
relay_log_info_repository =table

從庫/etc/my.cnf

[mysql]
prompt = [\\u@\\h][\\d]>\\_
port                    = 3306
socket                  = /usr/local/mysql/mysql.sock

[mysqld]
user                    = mysql
port                    = 3306
server-id               = 101
pid-file                = /usr/local/mysql/mysqld.pid
socket                  = /usr/local/mysql/mysql.sock
basedir                 = /usr/local/mysql
datadir                 = /usr/local/mysql/data
relay-log-index         = slave-relay-bin.index
relay-log               = slave-relay-bin
relay_log_purge         = 0
#以下兩個參數不加,從執行change不可以指定channel(ERROR 3077 (HY000))
master_info_repository  =table      
relay_log_info_repository =table 

主庫上創建復制賬號

create user repl@‘192.168.0.%‘ identified by ‘repl‘;
grant replication slave on *.* to repl@‘%‘;
flush privileges;

主庫上執行備份

mysqldump --master-data=2 --single-transaction -R --triggers -A > all.sql
其中--master-data=2代表備份時刻記錄master的Binlog位置和Position,--single-transaction意思是獲取一致性快照,-R意思是備份存儲過程和函數,--triggres的意思是備份觸發器,-A代表備份所有的庫。更多信息請自行mysqldump --help查看。

查看主庫備份時的binlog名稱和位置,MASTER_LOG_FILE和MASTER_LOG_POS

[root@mysql5-master ~]# head -n 30 all.sql | grep ‘CHANGE MASTER TO‘
-- CHANGE MASTER TO MASTER_LOG_FILE=‘mysql-bin.000010‘, MASTER_LOG_POS=112;

把備份復制到s1和s2,也就是192.168.0.102和192.168.0.103

scp all.sql [email protected]:/data/
scp all.sql [email protected]:/data/

導入備份到s1,s2,執行復制相關命令

mysql -uroot -p < /data/all.sql
CHANGE MASTER TO MASTER_HOST=‘192.168.0.101‘,MASTER_USER=‘repl‘,MASTER_PASSWORD=‘repl‘,MASTER_LOG_FILE=‘master-bin.000007‘,MASTER_LOG_POS=739 for channel ‘s1‘;
start slave for channel ‘s1‘;
show slave status\G;

查看復制狀態(可以看見復制成功):

[root@s1 ~]# mysql -e ‘show slave status\G‘ | egrep ‘Slave_IO|Slave_SQL‘
               Slave_IO_State: Waiting for master to send event
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes

另外一個從節點搭建復制環境,操作和上面一樣

兩臺slave服務器設置read_only(從庫對外提供讀服務,只所以沒有寫進配置文件,是因為隨時slave會提升為master

[root@s1 ~]# mysql -e ‘set global read_only=1‘
[root@s1 ~]# 
[root@s2 ~]# mysql -e ‘set global read_only=1‘
[root@s2 ~]# 

創建管理賬號(主庫執行)

grant replication slave,reload,create user,super on *.* to mats@‘%‘ identified by ‘mats‘ with grant option;

至此一主兩從架構搭建完畢

配置互信

確保所有節點都安裝openssh並啟動

openssh的安裝步驟:
yum -y install openssh*
systemctl start sshd
技術分享圖片



ssh-keygen -t rsa
ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]
ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]
ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]
ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]

ssh-keygen -t rsa
ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]
ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]
ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]
ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]

ssh-keygen -t rsa
ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]
ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]
ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]
ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]

ssh-keygen -t rsa
ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]
ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]
ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]
ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]

ssh-keygen -t rsa
ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]
ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]
ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]
ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]

  

部署MHA

角色                    ip地址             主機名             server_id                  類型
Monitor host            192.168.0.201    ProxySQL            -                      監控復制組
Master                  192.168.0.101    master              1                        寫入
Candicate master        192.168.0.102    s1                  101                      讀
Slave                   192.168.0.103    s2                  102                      讀

其中master對外提供寫服務,備選master(實際的slave,主機名s1)提供讀服務,slave也提供相關的讀服務,一旦master宕機,將會把備選master提升為新的master,slave指向新的master

官方網址
Manager:https://github.com/yoshinorim/mha4mysql-manager
Node: https://github.com/yoshinorim/mha4mysql-node
https://github.com/yoshinorim/mha4mysql-manager/wiki

參考來源:https://www.cnblogs.com/gomysql/p/3675429.html

使用git clone從github拷貝項目

git clone https://github.com/yoshinorim/mha4mysql-manager
git clone https://github.com/yoshinorim/mha4mysql-node

安裝依賴包(在所有節點安裝MHA node所需的perl模塊)

yum install glib2-devel libpcap-devel libnet-devel cmake gc++ gcc gcc-c++ make git
yum install gcc gcc-c++ kernel-devel perl-ExtUtils-CBuilder perl-ExtUtils-MakeMaker perl-DBD-MySQL perl-Config-Tiny perl-Log-Dispatch perl-Parallel-ForkManager perl-Time-HiRes perl-Module-Install -y

在所有的節點安裝mha node

cd mha4mysql-node-0.58
perl Makefile.PL
make && make install

安裝完成後會在/usr/local/bin目錄下生成以下腳本文件:

[root@mysql5-master src]# ll /usr/local/bin
total 80
-r-xr-xr-x. 1 root root 17639 Nov 14 15:46 apply_diff_relay_logs
-r-xr-xr-x. 1 root root  7138 Nov 14 15:43 config_data
-r-xr-xr-x. 1 root root  4807 Nov 14 15:46 filter_mysqlbinlog
-r-xr-xr-x. 1 root root  4371 Nov 14 15:43 json_pp
lrwxrwxrwx. 1 root root    26 Nov 14 17:02 mysql -> /usr/local/mysql/bin/mysql
lrwxrwxrwx. 1 root root    32 Nov 14 17:02 mysqlbinlog -> /usr/local/mysql/bin/mysqlbinlog
-r-xr-xr-x. 1 root root 13649 Nov 14 15:43 prove
-r-xr-xr-x. 1 root root  8337 Nov 14 15:46 purge_relay_logs
-r-xr-xr-x. 1 root root  7525 Nov 14 15:46 save_binary_logs

安裝mha manager

cd mha4mysql-node-0.58
perl Makefile.PL
make && make install

安裝完成後會在/usr/local/bin目錄下面生成以下腳本文件

[root@proxysql 3306]# ll /usr/local/bin
total 92
-r-xr-xr-x. 1 root root 17639 Nov 14 15:52 apply_diff_relay_logs
-r-xr-xr-x. 1 root root  4807 Nov 14 15:52 filter_mysqlbinlog
-rw-r--r--. 1 root root    74 Nov 14 16:36 load_cnf
-r-xr-xr-x. 1 root root  1995 Nov 14 15:54 masterha_check_repl
-r-xr-xr-x. 1 root root  1779 Nov 14 15:54 masterha_check_ssh
-r-xr-xr-x. 1 root root  1865 Nov 14 15:54 masterha_check_status
-r-xr-xr-x. 1 root root  3201 Nov 14 15:54 masterha_conf_host
-r-xr-xr-x. 1 root root  2517 Nov 14 15:54 masterha_manager
-r-xr-xr-x. 1 root root  2165 Nov 14 15:54 masterha_master_monitor
-r-xr-xr-x. 1 root root  2373 Nov 14 15:54 masterha_master_switch
-r-xr-xr-x. 1 root root  5172 Nov 14 15:54 masterha_secondary_check
-r-xr-xr-x. 1 root root  1739 Nov 14 15:54 masterha_stop
-r-xr-xr-x. 1 root root  8337 Nov 14 15:52 purge_relay_logs
-r-xr-xr-x. 1 root root  7525 Nov 14 15:52 save_binary_logs

復制相關腳本到/etc/mha/scripts目錄(軟件包解壓縮後就有了,不是必須,因為這些腳本不完整,需要自己修改,這是軟件開發著留給我們自己發揮的,如果開啟下面的任何一個腳本對應的參數,而對應這裏的腳本又沒有修改,則會拋錯,自己被坑的很慘)

mkdir -p /data/mha/3306/log
mkdir -p /etc/mha/scripts
cp /data/mha4mysql-manager-master/samples/scripts/* /etc/mha/scripts
[root@proxysql 3306]# ll /etc/mha/scripts
total 36
-rwxr-xr-x. 1 root root   150 Nov 14 17:53 manager.sh
-rwxr-xr-x. 1 root root  2169 Nov 14 17:27 master_ip_failover #自動切換時vip管理的腳本,不是必須,如果我們使用keepalived的,我們可以自己編寫腳本完成對vip的管理,比如監控mysql,如果mysql異常,我們停止keepalived就行,這樣vip就會自動漂移
-rwxr-xr-x. 1 root root 10369 Nov 14 17:38 master_ip_online_change #在線切換時vip的管理,不是必須,同樣可以可以自行編寫簡單的shell完成
-rwxr-xr-x. 1 root root 11867 Nov 14 16:41 power_manager           #故障發生後關閉主機的腳本,不是必須
-rwxr-xr-x. 1 root root  1360 Nov 14 16:41 send_report             #因故障切換後發送報警的腳本,不是必須,可自行編寫簡單的shell完成。

配置/etc/masterha_default.cnf

cat >> /etc/masterha_default.cnf << EOF
[server default]
user=root
password=abc123
ssh_user=root
repl_user=repl
repl_password=repl
ping_interval=1
#master_binlog_dir= /var/lib/mysql,/var/log/mysql
secondary_check_script=masterha_secondary_check -s 192.168.0.101 -s 192.168.0.102 -s 192.168.0.103 
master_ip_failover_script="/etc/mha/scripts/master_ip_failover"
master_ip_online_change_script="/etc/mha/scripts/master_ip_online_change"
report_script="/etc/mha/scripts/send_report"
EOF

配置/data/mha/3306/mha.cnf

cat >>/data/mha/3306/mha.cnf << EOF
[server default]
manager_workdir=/data/mha/3306
manager_log=/data/mha/3306/manager.log

[server1]
hostname=192.168.0.101
candidate_master=1
master_binlog_dir="/usr/local/mysql/data"

[server2]
hostname=192.168.0.102
candidate_master=1
master_binlog_dir="/usr/local/mysql/data"

[server3]
hostname=192.168.0.103
master_binlog_dir="/usr/local/mysql/data"
#表示沒有機會成為master
no_master=1
EOF
ln -s /usr/local/mysql/bin/mysqlbinlog /usr/local/bin/mysqlbinlog
ln -s /usr/local/mysql/bin/mysql /usr/local/bin/mysql

配置/etc/mha/scripts/master_ip_failover

cat >> /etc/mha/scripts/master_ip_failover << EOF
#!/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.0.88/24‘;   #設置VIP
my $key = ‘1‘;
my $ssh_start_vip = "/sbin/ifconfig eth0:$key $vip";  #註意網卡,根據實際情況改寫
my $ssh_stop_vip = "/sbin/ifconfig eth0:$key down";   #註意網卡,根據實際情況改寫

GetOptions(
    ‘command=s‘          => \$command,
    ‘ssh_user=s‘         => \$ssh_user,
    ‘orig_master_host=s‘ => \$orig_master_host,
    ‘orig_master_ip=s‘   => \$orig_master_ip,
    ‘orig_master_port=i‘ => \$orig_master_port,
    ‘new_master_host=s‘  => \$new_master_host,
    ‘new_master_ip=s‘    => \$new_master_ip,
    ‘new_master_port=i‘  => \$new_master_port,
);

exit &main();

sub main {

    print "\n\nIN SCRIPT TEST====$ssh_stop_vip==$ssh_start_vip===\n\n";

    if ( $command eq "stop" || $command eq "stopssh" ) {

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

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

配置/etc/mha/scripts/master_ip_online_change

cat >> /etc/mha/scripts/master_ip_online_change << EOF
#!/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 = ‘192.168.0.88/24‘;  # Virtual IP 
my $key = "1"; 
my $ssh_start_vip = "/sbin/ifconfig eth0:$key $vip";
my $ssh_stop_vip = "/sbin/ifconfig eth0:$key down";
my $ssh_user = "root";
my $new_master_password=‘abc123‘;
my $orig_master_password=‘abc123‘;
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;
}
EOF

配置/etc/mha/scripts/send_report

cat >> /etc/mha/scripts/send_report << EOF
#!/usr/bin/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;

#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 );
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

exit 0;

EOF

設置relay log的清除方式(在每個slave節點上):

[root@s1 ~]# mysql -e ‘set global relay_log_purge=0‘
[root@s2 ~]# mysql -e ‘set global relay_log_purge=0‘

註意:

MHA在發生切換的過程中,從庫的恢復過程中依賴於relay log的相關信息,所以這裏要將relay log的自動清除設置為OFF,采用手動清除relay log的方式。在默認情況下,從服務器上的中繼日誌會在SQL線程執行完畢後被自動刪除。但是在MHA環境中,這些中繼日誌在恢復其他從服務器時可能會被用到,因此需要禁用中繼日誌的自動刪除功能。定期清除中繼日誌需要考慮到復制延時的問題。在ext3的文件系統下,刪除大的文件需要一定的時間,會導致嚴重的復制延時。為了避免復制延時,需要暫時為中繼日誌創建硬鏈接,因為在linux系統中通過硬鏈接刪除大文件速度會很快。(在mysql數據庫中,刪除大表時,通常也采用建立硬鏈接的方式)

MHA節點中包含了pure_relay_logs命令工具,它可以為中繼日誌創建硬鏈接,執行SET GLOBAL relay_log_purge=1,等待幾秒鐘以便SQL線程切換到新的中繼日誌,再執行SET GLOBAL relay_log_purge=0。

pure_relay_logs腳本參數如下所示:

--user mysql                      用戶名
--password mysql                  密碼
--port                            端口號
--workdir                         指定創建relay log的硬鏈接的位置,默認是/var/tmp,由於系統不同分區創建硬鏈接文件會失敗,故需要執行硬鏈接具體位置,成功執行腳本後,硬鏈接的中繼日誌文件被刪除
--disable_relay_log_purge         默認情況下,如果relay_log_purge=1,腳本會什麽都不清理,自動退出,通過設定這個參數,當relay_log_purge=1的情況下會將relay_log_purge設置為0。清理relay log之後,最後將參數設置為OFF。

設置定期清理relay腳本(兩臺slave服務器)

cat >> purge_relay_log.sh  << EOF
#!/bin/bash
user=root
passwd=123456
port=3306
log_dir=‘/data/masterha/log‘
work_dir=‘/data‘
purge=‘/usr/local/bin/purge_relay_logs‘

if [ ! -d $log_dir ]
then
   mkdir $log_dir -p
fi

$purge --user=$user --password=$passwd --disable_relay_log_purge --port=$port --workdir=$work_dir >> $log_dir/purge_relay_logs.log 2>&1
EOF

添加到crontab定期執行

[root@s1 ~]# crontab -l
0 4 * * * /bin/bash /root/purge_relay_log.sh

purge_relay_logs腳本刪除中繼日誌不會阻塞SQL線程。下面我們手動執行看看什麽情況。

[root@s1 ~]# purge_relay_logs --user=root --password=123456 --port=3306 -disable_relay_log_purge --workdir=/data/
2014-04-20 15:47:24: purge_relay_logs script started.
 Found relay_log.info: /data/mysql/relay-log.info
 Removing hard linked relay log files server03-relay-bin* under /data/.. done.
 Current relay log file: /data/mysql/server03-relay-bin.000002
 Archiving unused relay log files (up to /data/mysql/server03-relay-bin.000001) ...
 Creating hard link for /data/mysql/server03-relay-bin.000001 under /data//server03-relay-bin.000001 .. ok.
 Creating hard links for unused relay log files completed.
 Executing SET GLOBAL relay_log_purge=1; FLUSH LOGS; sleeping a few seconds so that SQL thread can delete older relay log files (if it keeps up); SET GLOBAL relay_log_purge=0; .. ok.
 Removing hard linked relay log files server03-relay-bin* under /data/.. done.
2014-04-20 15:47:27: All relay log purging operations succeeded.

檢查SSH配置

檢查MHA Manger到所有MHA Node的SSH連接狀態

[root@proxysql 3306]# masterha_check_ssh --conf=/data/mha/3306/mha.cnf
Fri Nov 16 11:26:15 2018 - [info] Reading default configuration from /etc/masterha_default.cnf..
Fri Nov 16 11:26:15 2018 - [info] Reading application default configuration from /data/mha/3306/mha.cnf..
Fri Nov 16 11:26:15 2018 - [info] Reading server configuration from /data/mha/3306/mha.cnf..
Fri Nov 16 11:26:15 2018 - [info] Starting SSH connection tests..
Fri Nov 16 11:26:16 2018 - [debug] 
Fri Nov 16 11:26:15 2018 - [debug]  Connecting via SSH from [email protected](192.168.0.101:22) to [email protected](192.168.0.102:22)..
Fri Nov 16 11:26:16 2018 - [debug]   ok.
Fri Nov 16 11:26:16 2018 - [debug]  Connecting via SSH from [email protected](192.168.0.101:22) to [email protected](192.168.0.103:22)..
Fri Nov 16 11:26:16 2018 - [debug]   ok.
Fri Nov 16 11:26:17 2018 - [debug] 
Fri Nov 16 11:26:16 2018 - [debug]  Connecting via SSH from [email protected](192.168.0.102:22) to [email protected](192.168.0.101:22)..
Fri Nov 16 11:26:16 2018 - [debug]   ok.
Fri Nov 16 11:26:16 2018 - [debug]  Connecting via SSH from [email protected](192.168.0.102:22) to [email protected](192.168.0.103:22)..
Fri Nov 16 11:26:16 2018 - [debug]   ok.
Fri Nov 16 11:26:18 2018 - [debug] 
Fri Nov 16 11:26:16 2018 - [debug]  Connecting via SSH from [email protected](192.168.0.103:22) to [email protected](192.168.0.101:22)..
Fri Nov 16 11:26:17 2018 - [debug]   ok.
Fri Nov 16 11:26:17 2018 - [debug]  Connecting via SSH from [email protected](192.168.0.103:22) to [email protected](192.168.0.102:22)..
Fri Nov 16 11:26:17 2018 - [debug]   ok.
Fri Nov 16 11:26:18 2018 - [info] All SSH connection tests passed successfully.

檢查整個復制環境狀況

通過masterha_check_repl腳本查看整個集群的狀態

[root@proxysql 3306]# masterha_check_repl --conf=/data/mha/3306/mha.cnf
Fri Nov 16 11:27:25 2018 - [info] Reading default configuration from /etc/masterha_default.cnf..
Fri Nov 16 11:27:25 2018 - [info] Reading application default configuration from /data/mha/3306/mha.cnf..
Fri Nov 16 11:27:25 2018 - [info] Reading server configuration from /data/mha/3306/mha.cnf..
Fri Nov 16 11:27:25 2018 - [info] MHA::MasterMonitor version 0.58.
Fri Nov 16 11:27:26 2018 - [info] GTID failover mode = 0
Fri Nov 16 11:27:26 2018 - [info] Dead Servers:
Fri Nov 16 11:27:26 2018 - [info] Alive Servers:
Fri Nov 16 11:27:26 2018 - [info]   192.168.0.101(192.168.0.101:3306)
Fri Nov 16 11:27:26 2018 - [info]   192.168.0.102(192.168.0.102:3306)
Fri Nov 16 11:27:26 2018 - [info]   192.168.0.103(192.168.0.103:3306)
Fri Nov 16 11:27:26 2018 - [info] Alive Slaves:
Fri Nov 16 11:27:26 2018 - [info]   192.168.0.102(192.168.0.102:3306)  Version=5.7.23-log (oldest major version between slaves) log-bin:enabled
Fri Nov 16 11:27:26 2018 - [info]     Replicating from 192.168.0.101(192.168.0.101:3306)
Fri Nov 16 11:27:26 2018 - [info]     Primary candidate for the new Master (candidate_master is set)
Fri Nov 16 11:27:26 2018 - [info]   192.168.0.103(192.168.0.103:3306)  Version=5.7.23-log (oldest major version between slaves) log-bin:enabled
Fri Nov 16 11:27:26 2018 - [info]     Replicating from 192.168.0.101(192.168.0.101:3306)
Fri Nov 16 11:27:26 2018 - [info]     Not candidate for the new Master (no_master is set)
Fri Nov 16 11:27:26 2018 - [info] Current Alive Master: 192.168.0.101(192.168.0.101:3306)
Fri Nov 16 11:27:26 2018 - [info] Checking slave configurations..
Fri Nov 16 11:27:26 2018 - [info] Checking replication filtering settings..
Fri Nov 16 11:27:26 2018 - [info]  binlog_do_db= , binlog_ignore_db= 
Fri Nov 16 11:27:26 2018 - [info]  Replication filtering check ok.
Fri Nov 16 11:27:26 2018 - [info] GTID (with auto-pos) is not supported
Fri Nov 16 11:27:26 2018 - [info] Starting SSH connection tests..
Fri Nov 16 11:27:29 2018 - [info] All SSH connection tests passed successfully.
Fri Nov 16 11:27:29 2018 - [info] Checking MHA Node version..
Fri Nov 16 11:27:29 2018 - [info]  Version check ok.
Fri Nov 16 11:27:29 2018 - [info] Checking SSH publickey authentication settings on the current master..
Fri Nov 16 11:27:29 2018 - [info] HealthCheck: SSH to 192.168.0.101 is reachable.
Fri Nov 16 11:27:30 2018 - [info] Master MHA Node version is 0.58.
Fri Nov 16 11:27:30 2018 - [info] Checking recovery script configurations on 192.168.0.101(192.168.0.101:3306)..
Fri Nov 16 11:27:30 2018 - [info]   Executing command: save_binary_logs --command=test --start_pos=4 --binlog_dir=/usr/local/mysql/data --output_file=/var/tmp/save_binary_logs_test --manager_version=0.58 --start_file=master-bin.000003 
Fri Nov 16 11:27:30 2018 - [info]   Connecting to [email protected](192.168.0.101:22).. 
  Creating /var/tmp if not exists..    ok.
  Checking output directory is accessible or not..
   ok.
  Binlog found at /usr/local/mysql/data, up to master-bin.000003
Fri Nov 16 11:27:30 2018 - [info] Binlog setting check done.
Fri Nov 16 11:27:30 2018 - [info] Checking SSH publickey authentication and checking recovery script configurations on all alive slave servers..
Fri Nov 16 11:27:30 2018 - [info]   Executing command : apply_diff_relay_logs --command=test --slave_user=‘root‘ --slave_host=192.168.0.102 --slave_ip=192.168.0.102 --slave_port=3306 --workdir=/var/tmp --target_version=5.7.23-log --manager_version=0.58 --relay_log_info=/usr/local/mysql/data/relay-log.info  --relay_dir=/usr/local/mysql/data/  --slave_pass=xxx
Fri Nov 16 11:27:30 2018 - [info]   Connecting to [email protected](192.168.0.102:22).. 
  Checking slave recovery environment settings..
    Opening /usr/local/mysql/data/relay-log.info ... ok.
    Relay log found at /usr/local/mysql/data, up to slave-relay-bin.000002
    Temporary relay log file is /usr/local/mysql/data/slave-relay-bin.000002
    Checking if super_read_only is defined and turned on.. not present or turned off, ignoring.
    Testing mysql connection and privileges..
mysql: [Warning] Using a password on the command line interface can be insecure.
 done.
    Testing mysqlbinlog output.. done.
    Cleaning up test file(s).. done.
Fri Nov 16 11:27:30 2018 - [info]   Executing command : apply_diff_relay_logs --command=test --slave_user=‘root‘ --slave_host=192.168.0.103 --slave_ip=192.168.0.103 --slave_port=3306 --workdir=/var/tmp --target_version=5.7.23-log --manager_version=0.58 --relay_log_info=/usr/local/mysql/data/relay-log.info  --relay_dir=/usr/local/mysql/data/  --slave_pass=xxx
Fri Nov 16 11:27:30 2018 - [info]   Connecting to [email protected](192.168.0.103:22).. 
  Checking slave recovery environment settings..
    Opening /usr/local/mysql/data/relay-log.info ... ok.
    Relay log found at /usr/local/mysql/data, up to slave-relay-bin.000002
    Temporary relay log file is /usr/local/mysql/data/slave-relay-bin.000002
    Checking if super_read_only is defined and turned on.. not present or turned off, ignoring.
    Testing mysql connection and privileges..
mysql: [Warning] Using a password on the command line interface can be insecure.
 done.
    Testing mysqlbinlog output.. done.
    Cleaning up test file(s).. done.
Fri Nov 16 11:27:30 2018 - [info] Slaves settings check done.
Fri Nov 16 11:27:30 2018 - [info] 
192.168.0.101(192.168.0.101:3306) (current master)
 +--192.168.0.102(192.168.0.102:3306)
 +--192.168.0.103(192.168.0.103:3306)

Fri Nov 16 11:27:30 2018 - [info] Checking replication health on 192.168.0.102..
Fri Nov 16 11:27:30 2018 - [info]  ok.
Fri Nov 16 11:27:30 2018 - [info] Checking replication health on 192.168.0.103..
Fri Nov 16 11:27:30 2018 - [info]  ok.
Fri Nov 16 11:27:30 2018 - [info] Checking master_ip_failover_script status:
Fri Nov 16 11:27:30 2018 - [info]   /etc/mha/scripts/master_ip_failover --command=status --ssh_user=root --orig_master_host=192.168.0.101 --orig_master_ip=192.168.0.101 --orig_master_port=3306 


IN SCRIPT TEST====/sbin/ifconfig eth0:1 down==/sbin/ifconfig eth0:1 192.168.0.88/24===

Checking the Status of the script.. OK 
Fri Nov 16 11:27:30 2018 - [info]  OK.
Fri Nov 16 11:27:30 2018 - [warning] shutdown_script is not defined.
Fri Nov 16 11:27:30 2018 - [info] Got exit code 0 (Not master dead).

MySQL Replication Health is OK.
[root@proxysql 3306]# 

檢查MHA Manager的狀態

[root@proxysql 3306]# masterha_check_status  --conf=/data/mha/3306/mha.cnf
mha is stopped(2:NOT_RUNNING).

開啟MHA Manager監控

vi manager.sh
nohup masterha_manager --conf=/etc/mha/app1.cnf --remove_dead_master_conf --ignore_last_failover < /dev/null > /data/mha/3306/manager.log 2>&1 &

./manager.sh

啟動參數介紹:

--remove_dead_master_conf 該參數代表當發生主從切換後,老的主庫的ip將會從配置文件中移除。

--manger_log 日誌存放位置

--ignore_last_failover 在缺省情況下,如果MHA檢測到連續發生宕機,且兩次宕機間隔不足8小時的話,則不會進行Failover,之所以這樣限制是為了避免ping-pong效應。該參數代表忽略上次MHA觸發切換產生的文件,默認情況下,MHA發生切換後會在日誌目錄,也就是上面我設置的/data產生app1.failover.complete文件,下次再次切換的時候如果發現該目錄下存在該文件將不允許觸發切換,除非在第一次切換後收到刪除該文件,為了方便,這裏設置為--ignore_last_failover。

配置VIP

vip配置可以采用兩種方式,一種通過keepalived的方式管理虛擬ip的浮動;另外一種通過腳本方式啟動虛擬ip的方式(即不需要keepalived或者heartbeat類似的軟件)。

(一)使用腳本管理VIP 的方式, 修改master_ip_failover 腳本,使用腳本管理VIP:

通過配置/etc/mha/scripts/master_ip_failover實現

(二)keepalived方式管理虛擬ip

下載軟件進行並進行安裝(兩臺master,準確的說一臺是master,另外一臺是備選master,在沒有切換以前是slave):

[root@master ~]# wget http://www.keepalived.org/software/keepalived-1.2.12.tar.gz
技術分享圖片
tar xf keepalived-1.2.12.tar.gz           
cd keepalived-1.2.12
./configure --prefix=/usr/local/keepalived
make &&  make install
cp /usr/local/keepalived/etc/rc.d/init.d/keepalived /etc/init.d/
cp /usr/local/keepalived/etc/sysconfig/keepalived /etc/sysconfig/
mkdir /etc/keepalived
cp /usr/local/keepalived/etc/keepalived/keepalived.conf /etc/keepalived/
cp /usr/local/keepalived/sbin/keepalived /usr/sbin/
技術分享圖片

(2)配置keepalived的配置文件,在master上配置(192.168.0.101)

技術分享圖片
[root@master ~]# cat /etc/keepalived/keepalived.conf
! Configuration File for keepalived

global_defs {
     notification_email {
     [email protected]
   }
   notification_email_from [email protected]
   smtp_server 127.0.0.1
   smtp_connect_timeout 30
   router_id MySQL-HA
}

vrrp_instance VI_1 {
    state BACKUP
    interface eth1
    virtual_router_id 51
    priority 150
    advert_int 1
    nopreempt

    authentication {
    auth_type PASS
    auth_pass 1111
    }

    virtual_ipaddress {
        192.168.0.88
    }
}

[[email protected] ~]# 
技術分享圖片

其中router_id MySQL HA表示設定keepalived組的名稱,將192.168.0.88這個虛擬ip綁定到該主機的eth1網卡上,並且設置了狀態為backup模式,將keepalived的模式設置為非搶占模式(nopreempt),priority 150表示設置的優先級為150。下面的配置略有不同,但是都是一個意思。
在候選master上配置(192.168.0.60)

技術分享圖片
[[email protected] ~]# cat /etc/keepalived/keepalived.conf 
! Configuration File for keepalived

global_defs {
     notification_email {
     [email protected]
   }
   notification_email_from [email protected]
   smtp_server 127.0.0.1
   smtp_connect_timeout 30
   router_id MySQL-HA
}

vrrp_instance VI_1 {
    state BACKUP
    interface eth1
    virtual_router_id 51
    priority 120
    advert_int 1
    nopreempt

    authentication {
    auth_type PASS
    auth_pass 1111
    }

    virtual_ipaddress {
        192.168.0.88
    }
}

[[email protected] ~]# 
技術分享圖片

(3)啟動keepalived服務,在master上啟動並查看日誌

技術分享圖片
[[email protected] ~]# /etc/init.d/keepalived start
Starting keepalived:                                       [  OK  ]
[[email protected] ~]# tail -f /var/log/messages
Apr 20 20:22:16 192 Keepalived_healthcheckers[15334]: Opening file ‘/etc/keepalived/keepalived.conf‘.
Apr 20 20:22:16 192 Keepalived_healthcheckers[15334]: Configuration is using : 7231 Bytes
Apr 20 20:22:16 192 kernel: IPVS: Connection hash table configured (size=4096, memory=64Kbytes)
Apr 20 20:22:16 192 kernel: IPVS: ipvs loaded.
Apr 20 20:22:16 192 Keepalived_healthcheckers[15334]: Using LinkWatch kernel netlink reflector...
Apr 20 20:22:19 192 Keepalived_vrrp[15335]: VRRP_Instance(VI_1) Transition to MASTER STATE
Apr 20 20:22:20 192 Keepalived_vrrp[15335]: VRRP_Instance(VI_1) Entering MASTER STATE
Apr 20 20:22:20 192 Keepalived_vrrp[15335]: VRRP_Instance(VI_1) setting protocol VIPs.
Apr 20 20:22:20 192 Keepalived_vrrp[15335]: VRRP_Instance(VI_1) Sending gratuitous ARPs on eth1 for 192.168.0.88
Apr 20 20:22:20 192 Keepalived_healthcheckers[15334]: Netlink reflector reports IP 192.168.0.88 added
Apr 20 20:22:25 192 Keepalived_vrrp[15335]: VRRP_Instance(VI_1) Sending gratuitous ARPs on eth1 for 192.168.0.88
技術分享圖片

發現已經將虛擬ip 192.168.0.88綁定了網卡eth1上。
(4)查看綁定情況

[[email protected] ~]# ip addr | grep eth1
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    inet 192.168.0.50/24 brd 192.168.0.255 scope global eth1
    inet 192.168.0.88/32 scope global eth1
[[email protected] ~]# 

在另外一臺服務器,候選master上啟動keepalived服務,並觀察

技術分享圖片
[[email protected] ~]# /etc/init.d/keepalived start ; tail -f /var/log/messages
Starting keepalived:                                       [  OK  ]
Apr 20 20:26:18 192 Keepalived_vrrp[9472]: Registering gratuitous ARP shared channel
Apr 20 20:26:18 192 Keepalived_vrrp[9472]: Opening file ‘/etc/keepalived/keepalived.conf‘.
Apr 20 20:26:18 192 Keepalived_vrrp[9472]: Configuration is using : 62976 Bytes
Apr 20 20:26:18 192 Keepalived_vrrp[9472]: Using LinkWatch kernel netlink reflector...
Apr 20 20:26:18 192 Keepalived_vrrp[9472]: VRRP_Instance(VI_1) Entering BACKUP STATE
Apr 20 20:26:18 192 Keepalived_vrrp[9472]: VRRP sockpool: [ifindex(3), proto(112), unicast(0), fd(10,11)]
Apr 20 20:26:18 192 Keepalived_healthcheckers[9471]: Netlink reflector reports IP 192.168.80.138 added
Apr 20 20:26:18 192 Keepalived_healthcheckers[9471]: Netlink reflector reports IP 192.168.0.60 added
Apr 20 20:26:18 192 Keepalived_healthcheckers[9471]: Netlink reflector reports IP fe80::20c:29ff:fe9d:6a9e added
Apr 20 20:26:18 192 Keepalived_healthcheckers[9471]: Netlink reflector reports IP fe80::20c:29ff:fe9d:6aa8 added
Apr 20 20:26:18 192 Keepalived_healthcheckers[9471]: Registering Kernel netlink reflector
Apr 20 20:26:18 192 Keepalived_healthcheckers[9471]: Registering Kernel netlink command channel
Apr 20 20:26:18 192 Keepalived_healthcheckers[9471]: Opening file ‘/etc/keepalived/keepalived.conf‘.
Apr 20 20:26:18 192 Keepalived_healthcheckers[9471]: Configuration is using : 7231 Bytes
Apr 20 20:26:18 192 kernel: IPVS: Registered protocols (TCP, UDP, AH, ESP)
Apr 20 20:26:18 192 kernel: IPVS: Connection hash table configured (size=4096, memory=64Kbytes)
Apr 20 20:26:18 192 kernel: IPVS: ipvs loaded.
Apr 20 20:26:18 192 Keepalived_healthcheckers[9471]: Using LinkWatch kernel netlink reflector...
技術分享圖片

從上面的信息可以看到keepalived已經配置成功。
註意:

上面兩臺服務器的keepalived都設置為了BACKUP模式,在keepalived中2種模式,分別是master->backup模式和backup->backup模式。這兩種模式有很大區別。在master->backup模式下,一旦主庫宕機,虛擬ip會自動漂移到從庫,當主庫修復後,keepalived啟動後,還會把虛擬ip搶占過來,即使設置了非搶占模式(nopreempt)搶占ip的動作也會發生。在backup->backup模式下,當主庫宕機後虛擬ip會自動漂移到從庫上,當原主庫恢復和keepalived服務啟動後,並不會搶占新主的虛擬ip,即使是優先級高於從庫的優先級別,也不會發生搶占。為了減少ip漂移次數,通常是把修復好的主庫當做新的備庫。

(5)MHA引入keepalived(MySQL服務進程掛掉時通過MHA 停止keepalived):

要想把keepalived服務引入MHA,我們只需要修改切換是觸發的腳本文件master_ip_failover即可,在該腳本中添加在master發生宕機時對keepalived的處理。

編輯腳本/usr/local/bin/master_ip_failover,修改後如下,我對perl不熟悉,所以我這裏完整貼出該腳本(主庫上操作,192.168.0.50)。

在MHA Manager修改腳本修改後的內容如下(參考資料比較少):

技術分享圖片
#!/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.0.88‘;
my $ssh_start_vip = "/etc/init.d/keepalived start";
my $ssh_stop_vip = "/etc/init.d/keepalived stop";

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"; }
技術分享圖片

現在已經修改這個腳本了,我們現在打開在上面提到過的參數,再檢查集群狀態,看是否會報錯。

[[email protected] ~]# grep ‘master_ip_failover_script‘ /etc/masterha/app1.cnf
master_ip_failover_script= /usr/local/bin/master_ip_failover
[[email protected] ~]# 
技術分享圖片
[[email protected] ~]# masterha_check_repl --conf=/etc/masterha/app1.cnf  
Sun Apr 20 23:10:01 2014 - [info] Slaves settings check done.
Sun Apr 20 23:10:01 2014 - [info] 
192.168.0.50 (current master)
 +--192.168.0.60
 +--192.168.0.70

Sun Apr 20 23:10:01 2014 - [info] Checking replication health on 192.168.0.60..
Sun Apr 20 23:10:01 2014 - [info]  ok.
Sun Apr 20 23:10:01 2014 - [info] Checking replication health on 192.168.0.70..
Sun Apr 20 23:10:01 2014 - [info]  ok.
Sun Apr 20 23:10:01 2014 - [info] Checking master_ip_failover_script status:
Sun Apr 20 23:10:01 2014 - [info]   /usr/local/bin/master_ip_failover --command=status --ssh_user=root --orig_master_host=192.168.0.50 --orig_master_ip=192.168.0.50 --orig_master_port=3306 
Sun Apr 20 23:10:01 2014 - [info]  OK.
Sun Apr 20 23:10:01 2014 - [warning] shutdown_script is not defined.
Sun Apr 20 23:10:01 2014 - [info] Got exit code 0 (Not master dead).

MySQL Replication Health is OK.
技術分享圖片

可以看見已經沒有報錯了。哈哈
/usr/local/bin/master_ip_failover添加或者修改的內容意思是當主庫數據庫發生故障時,會觸發MHA切換,MHA Manager會停掉主庫上的keepalived服務,觸發虛擬ip漂移到備選從庫,從而完成切換。當然可以在keepalived裏面引入腳本,這個腳本監控mysql是否正常運行,如果不正常,則調用該腳本殺掉keepalived進程。

常用命令

檢查整個復制環境狀況
masterha_check_repl --conf=/data/mha/3306/mha.cnf

檢查SSH配置
masterha_check_ssh --conf=/data/mha/3306/mha.cnf

檢測當前MHA運行狀態
masterha_check_status  --conf=/data/mha/3306/mha.cnf

啟動MHA
vi manager.sh
nohup masterha_manager --conf=/etc/mha/app1.cnf --remove_dead_master_conf --ignore_last_failover < /dev/null > /data/mha/3306/manager.log 2>&1 & 

停止MHA
masterha_stop  --conf=/data/mha/3306/mha.cnf

以上就是MHA 安裝配置的全過程,以下進行簡單的測試。

(1)failover 測試

手動kill 了master 上面的mysqld 進程,查看切換狀態

日誌待補全

以上是切換的全日誌過程,我們可以看到MHA 切換主要經歷以下步驟:

1.配置文件檢查階段,這個階段會檢查整個集群配置文件配置

2.宕機的master處理,這個階段包括虛擬ip摘除操作,主機關機操作(這個我這裏還沒有實現,需要研究)

3.復制dead maste和最新slave相差的relay log,並保存到MHA Manger具體的目錄下

4.識別含有最新更新的slave

5.應用從master保存的二進制日誌事件(binlog events)

6.提升一個slave為新的master進行復制

7.使其他的slave連接新的master進行復制

(2)手動switch

在許多情況下, 需要將現有的主服務器遷移到另外一臺服務器上。 比如主服務器硬件故障,RAID 控制卡需要重建,將主服務器移到性能更好的服務器上等等。維護主服務器引起性能下降, 導致停機時間至少無法寫入數據。 另外, 阻塞或殺掉當前運行的會話會導致主主之間數據不一致的問題發生。 MHA 提供快速切換和優雅的阻塞寫入,這個切換過程只需要 0.5-2s 的時間,這段時間內數據是無法寫入的。在很多情況下,0.5-2s 的阻塞寫入是可以接受的。因此切換主服務器不需要計劃分配維護時間窗口。

MHA在線切換的大概過程:
1.檢測復制設置和確定當前主服務器
2.確定新的主服務器
3.阻塞寫入到當前主服務器
4.等待所有從服務器趕上復制
5.授予寫入到新的主服務器
6.重新設置從服務器

註意,在線切換的時候應用架構需要考慮以下兩個問題:

1.自動識別master和slave的問題(master的機器可能會切換),如果采用了vip的方式,基本可以解決這個問題。

2.負載均衡的問題(可以定義大概的讀寫比例,每臺機器可承擔的負載比例,當有機器離開集群時,需要考慮這個問題)

為了保證數據完全一致性,在最快的時間內完成切換,MHA的在線切換必須滿足以下條件才會切換成功,否則會切換失敗。

1.所有slave的IO線程都在運行

2.所有slave的SQL線程都在運行

3.所有的show slave status的輸出中Seconds_Behind_Master參數小於或者等於running_updates_limit秒,如果在切換過程中不指定running_updates_limit,那麽默認情況下running_updates_limit為1秒。

4.在master端,通過show processlist輸出,沒有一個更新花費的時間大於running_updates_limit秒。

執行切換

[root@manager tmp]# masterha_master_switch --conf=/data/mha/3306/mha.cnf --master_state=alive --new_master_host=192.168.0.102 --new_master_port=3306 --orig_master_is_new_slave --running_updates_limit=10000

其中參數的意思:

--orig_master_is_new_slave 切換時加上此參數是將原 master 變為 slave 節點,如果不加此參數,原來的 master 將不啟動

--running_updates_limit=10000,故障切換時,候選master 如果有延遲的話, mha 切換不能成功,加上此參數表示延遲在此時間範圍內都可切換(單位為s),但是切換的時間長短是由recover 時relay 日誌的大小決定

參考來源:

http://www.cnblogs.com/gomysql/p/3675429.html

http://www.178linux.com/61111

https://www.cnblogs.com/rayment/p/7355093.html

MySQL 之 MHA + ProxySQL + keepalived 實現讀寫分離,高可用(一)