Mysql8 MHA(一主一从)安装手册

1.版本选择

    为了是mysql主从集群在发生故障时可以第一时间自动进行准备切换,选用MHA软件高可用解决方案

     MHA版本:5.8

     以下链接提供rpm安装包,此安装包可以在无外网环境下,配合centos 7光盘镜像做成的本地yum源,直接通过yum安装,链接:https://download.csdn.net/download/bestinter2010/82891906

    Mysql版本:8

   Linux版本:centos 7

2.MHA安装

主机名

IP

MHA节点类型

Mysql-p

10.9.40.181

Manager,node

Mysql-s

10.9.40.182

Manager,node

    

完成mysql主从搭建后进行MHA的安装配置(mysql主从搭建参考mysql主从搭建文档)

在mysql主从节点分别创建mha用户

set sql_log_bin=0;

CREATE USER 'mha'@'10.9.40.%' IDENTIFIED WITH mysql_native_password BY 'manager';

grant all privileges on *.* to 'mha'@'10.9.40.%';

set sql_log_bin=1;

直接使用rpm包安装进行安装
 

Yum install mha4mysql-manager-0.58-0.el7.centos.noarch

Yum install mha4mysql-node-0.58-0.el7.centos.noarch

安装完成后创建目录,文件

mkdir -p /etc/mha

mkdir -p /home/mha

touch /etc/mha/mysql-mha.conf

touch /usr/bin/master_ip_failover

touch /usr/bin/master_ip_online_change

chmod +x /usr/bin/master_ip_failover   /usr/bin/master_ip_online_change

3.配置集群节点之间ssh免密登录

   使用ssh-keygen生产密匙

   然后使用ssh-copy-id -i /root/.ssh/id_rsa root@10.9.40.181

ssh-copy-id -i /root/.ssh/id_rsa root@10.9.40.182分发到各节点

   以上命令需要在所有节点运行

4.配置/etc/mha/mysql-mha.conf

vim /etc/mha/mysql-mha.conf

[server default]
user=mha
password=manager
manager_workdir=/home/mha
manager_log=/home/mha/manager.log
remote_workdir=/home/mha
ssh_user=root
repl_user=repl
repl_password=repl
ping_interval=1
master_binlog_dir=/data/log_bin
ssh_port=22
#自动切换时运行的脚本
master_ip_failover_script = /usr/bin/master_ip_failover
#手动切换时运行的脚本
master_ip_online_change_script= /usr/bin/master_ip_online_change
secondary_check_script = /usr/bin/masterha_secondary_check -s 10.9.40.181 -s 10.9.40.182
[server1]
hostname=10.9.40.181
#是否可以成为主节点
candidate_master=1
[server2]
hostname=10.9.40.182
#是否可以成为主节点
candidate_master=1

5.配置/usr/bin/master_ip_failover

vim  /usr/bin/master_ip_failover

#!/usr/bin/env perl


#  Copyright (C) 2011 DeNA Co.,Ltd.

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


my (

  $command,        $ssh_user,         $orig_master_host,

  $orig_master_ip, $orig_master_port, $new_master_host,

  $new_master_ip,  $new_master_port,  $new_master_user,

  $new_master_password

);

#修改成vip

my $vip = '10.9.40.183/24';

my $key = '88';

#enp0s3为vip的网卡

my $ssh_start_vip = "/sbin/ifconfig enp0s3:$key $vip";

my $ssh_stop_vip = "/sbin/ifconfig enp0s3:$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,

  'new_master_user=s'     => \$new_master_user,

  'new_master_password=s' => \$new_master_password,

);


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";

}

6.配置/usr/bin/master_ip_online_change

vi /usr/bin/master_ip_online_change

#!/usr/bin/env perl

use strict;
use warnings FATAL => 'all';

use Getopt::Long;
use MHA::DBHelper;
use MHA::NodeUtil;
use Time::HiRes qw( sleep gettimeofday tv_interval );
use Data::Dumper;

my $_tstart;
my $_running_interval = 0.1;
my (
  $command,          
  $orig_master_is_new_slave, $orig_master_host, $orig_master_ip,  $orig_master_port, $orig_master_user,    $orig_master_password, $orig_master_ssh_user,
  $new_master_host,          $new_master_ip,    $new_master_port, $new_master_user,  $new_master_password, $new_master_ssh_user,
);


my $vip = '10.9.40.183';
my $brdc = '10.9.40.255';
my $ifdev = 'enp0s3';
my $key = '88';
my $ssh_start_vip = "/usr/sbin/ip addr add $vip/24 brd $brdc dev $ifdev label $ifdev:$key;/usr/sbin/arping -q -A -c 1 -I $ifdev $vip;iptables -F;";
my $ssh_stop_vip = "/usr/sbin/ip addr del $vip/24 dev $ifdev label $ifdev:$key";


GetOptions(
  'command=s'                => \$command,
  'orig_master_is_new_slave' => \$orig_master_is_new_slave,
  'orig_master_host=s'       => \$orig_master_host,
  'orig_master_ip=s'         => \$orig_master_ip,
  'orig_master_port=i'       => \$orig_master_port,
  'orig_master_user=s'       => \$orig_master_user,
  'orig_master_password=s'   => \$orig_master_password,
  'orig_master_ssh_user=s'   => \$orig_master_ssh_user,
  'new_master_host=s'        => \$new_master_host,
  'new_master_ip=s'          => \$new_master_ip,
  'new_master_port=i'        => \$new_master_port,
  'new_master_user=s'        => \$new_master_user,
  'new_master_password=s'    => \$new_master_password,
  'new_master_ssh_user=s'    => \$new_master_ssh_user,
);

exit &main();

sub current_time_us {
  my ( $sec, $microsec ) = gettimeofday();
  my $curdate = localtime($sec);
  return $curdate . " " . sprintf( "%06d", $microsec );
}

sub sleep_until {
  my $elapsed = tv_interval($_tstart);
  if ( $_running_interval > $elapsed ) {
    sleep( $_running_interval - $elapsed );
  }
}

sub get_threads_util {
  my $dbh                    = shift;
  my $my_connection_id       = shift;
  my $running_time_threshold = shift;
  my $type                   = shift;
  $running_time_threshold = 0 unless ($running_time_threshold);
  $type                   = 0 unless ($type);
  my @threads;

  my $sth = $dbh->prepare("SHOW PROCESSLIST");
  $sth->execute();

  while ( my $ref = $sth->fetchrow_hashref() ) {
    my $id         = $ref->{Id};
    my $user       = $ref->{User};
    my $host       = $ref->{Host};
    my $command    = $ref->{Command};
    my $state      = $ref->{State};
    my $query_time = $ref->{Time};
    my $info       = $ref->{Info};
    $info =~ s/^\s*(.*?)\s*$/$1/ if defined($info);
    next if ( $my_connection_id == $id );
    next if ( defined($query_time) && $query_time < $running_time_threshold );
    next if ( defined($command)    && $command eq "Binlog Dump" );
    next if ( defined($user)       && $user eq "system user" );
    next
      if ( defined($command)
      && $command eq "Sleep"
      && defined($query_time)
      && $query_time >= 1 );

    if ( $type >= 1 ) {
      next if ( defined($command) && $command eq "Sleep" );
      next if ( defined($command) && $command eq "Connect" );
    }

    if ( $type >= 2 ) {
      next if ( defined($info) && $info =~ m/^select/i );
      next if ( defined($info) && $info =~ m/^show/i );
    }

    push @threads, $ref;
  }
  return @threads;
}

sub main {
  if ( $command eq "stop" ) {
    ## Gracefully killing connections on the current master
    # 1. Set read_only= 1 on the new master
    # 2. DROP USER so that no app user can establish new connections
    # 3. Set read_only= 1 on the current master
    # 4. Kill current queries
    # * Any database access failure will result in script die.
    my $exit_code = 1;
    eval {
      ## Setting read_only=1 on the new master (to avoid accident)
      my $new_master_handler = new MHA::DBHelper();

      # args: hostname, port, user, password, raise_error(die_on_error)_or_not
      $new_master_handler->connect( $new_master_ip, $new_master_port,
        $new_master_user, $new_master_password, 1 );
      print current_time_us() . " Set read_only on the new master.. ";
      $new_master_handler->enable_read_only();
      if ( $new_master_handler->is_read_only() ) {
        print "ok.\n";
      }
      else {
        die "Failed!\n";
      }
      $new_master_handler->disconnect();

      # Connecting to the orig master, die if any database error happens
      my $orig_master_handler = new MHA::DBHelper();
      $orig_master_handler->connect( $orig_master_ip, $orig_master_port,
        $orig_master_user, $orig_master_password, 1 );

      ## Drop application user so that nobody can connect. Disabling per-session binlog beforehand
      #$orig_master_handler->disable_log_bin_local();
      #print current_time_us() . " Drpping app user on the orig master..\n";
      #FIXME_xxx_drop_app_user($orig_master_handler);

      ## Waiting for N * 100 milliseconds so that current connections can exit
      my $time_until_read_only = 15;
      $_tstart = [gettimeofday];
      my @threads = get_threads_util( $orig_master_handler->{dbh},
        $orig_master_handler->{connection_id} );
      while ( $time_until_read_only > 0 && $#threads >= 0 ) {
        if ( $time_until_read_only % 5 == 0 ) {
          printf
"%s Waiting all running %d threads are disconnected.. (max %d milliseconds)\n",
            current_time_us(), $#threads + 1, $time_until_read_only * 100;
          if ( $#threads < 5 ) {
            print Data::Dumper->new( [$_] )->Indent(0)->Terse(1)->Dump . "\n"
              foreach (@threads);
          }
        }
        sleep_until();
        $_tstart = [gettimeofday];
        $time_until_read_only--;
        @threads = get_threads_util( $orig_master_handler->{dbh},
          $orig_master_handler->{connection_id} );
      }

      ## Setting read_only=1 on the current master so that nobody(except SUPER) can write
      print current_time_us() . " Set read_only=1 on the orig master.. ";
      $orig_master_handler->enable_read_only();
      if ( $orig_master_handler->is_read_only() ) {
        print "ok.\n";
      }
      else {
        die "Failed!\n";
      }

      ## Waiting for M * 100 milliseconds so that current update queries can complete
      my $time_until_kill_threads = 5;
      @threads = get_threads_util( $orig_master_handler->{dbh},
        $orig_master_handler->{connection_id} );
      while ( $time_until_kill_threads > 0 && $#threads >= 0 ) {
        if ( $time_until_kill_threads % 5 == 0 ) {
          printf
"%s Waiting all running %d queries are disconnected.. (max %d milliseconds)\n",
            current_time_us(), $#threads + 1, $time_until_kill_threads * 100;
          if ( $#threads < 5 ) {
            print Data::Dumper->new( [$_] )->Indent(0)->Terse(1)->Dump . "\n"
              foreach (@threads);
          }
        }
        sleep_until();
        $_tstart = [gettimeofday];
        $time_until_kill_threads--;
        @threads = get_threads_util( $orig_master_handler->{dbh},
          $orig_master_handler->{connection_id} );
      }



                print "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 $new_master_ssh_user\@$new_master_host \" $ssh_start_vip \"`;
}
# A simple system call that disable the VIP on the old_master
sub stop_vip() {
    `ssh $orig_master_ssh_user\@$orig_master_host \" $ssh_stop_vip \"`;
}

sub usage {
  print
"Usage: master_ip_online_change --command=start|stop|status --orig_master_host=host --orig_master_ip=ip --orig_master_port=port --orig_master_user=user --orig_master_password=password --orig_master_ssh_user=sshuser --new_master_host=host --new_master_ip=ip --new_master_port=port --new_master_user=user --new_master_password=password --new_master_ssh_user=sshuser \n";
  die;
}

7.SSH配置检查及主从复制检查

       使用masterha_check_ssh --conf=/etc/mha/mysql-mha.conf命令检查ssh配置 

[root@mysql-p ~]# masterha_check_ssh --conf=/etc/mha/mysql-mha.conf

Tue Mar  1 10:08:23 2022 - [warning] Global configuration file /etc/masterha_default.cnf not found. Skipping.

Tue Mar  1 10:08:23 2022 - [info] Reading application default configuration from /etc/mha/mysql-mha.conf..

Tue Mar  1 10:08:23 2022 - [info] Reading server configuration from /etc/mha/mysql-mha.conf..

Tue Mar  1 10:08:23 2022 - [info] Starting SSH connection tests..

Tue Mar  1 10:08:23 2022 - [debug]

Tue Mar  1 10:08:23 2022 - [debug]  Connecting via SSH from root@10.9.40.181(10.9.40.181:22) to root@10.9.40.182(10.9.40.182:22)..

Tue Mar  1 10:08:23 2022 - [debug]   ok.

Tue Mar  1 10:08:24 2022 - [debug]

Tue Mar  1 10:08:23 2022 - [debug]  Connecting via SSH from root@10.9.40.182(10.9.40.182:22) to root@10.9.40.181(10.9.40.181:22)..

Tue Mar  1 10:08:23 2022 - [debug]   ok.

Tue Mar  1 10:08:24 2022 - [info] All SSH connection tests passed successfully.

        使用masterha_check_repl --conf=/etc/mha/mysql-mha.conf命令检查主从复制

[root@mysql-p ~]# masterha_check_repl --conf=/etc/mha/mysql-mha.conf

Tue Mar  1 10:12:05 2022 - [warning] Global configuration file /etc/masterha_default.cnf not found. Skipping.

Tue Mar  1 10:12:05 2022 - [info] Reading application default configuration from /etc/mha/mysql-mha.conf..

Tue Mar  1 10:12:05 2022 - [info] Reading server configuration from /etc/mha/mysql-mha.conf..

Tue Mar  1 10:12:05 2022 - [info] MHA::MasterMonitor version 0.58.

Tue Mar  1 10:12:06 2022 - [info] GTID failover mode = 1

Tue Mar  1 10:12:06 2022 - [info] Dead Servers:

Tue Mar  1 10:12:06 2022 - [info] Alive Servers:

Tue Mar  1 10:12:06 2022 - [info]   10.9.40.181(10.9.40.181:3306)

Tue Mar  1 10:12:06 2022 - [info]   10.9.40.182(10.9.40.182:3306)

Tue Mar  1 10:12:06 2022 - [info] Alive Slaves:

Tue Mar  1 10:12:06 2022 - [info]   10.9.40.181(10.9.40.181:3306)  Version=8.0.27 (oldest major version between slaves) log-bin:enabled

Tue Mar  1 10:12:06 2022 - [info]     GTID ON

Tue Mar  1 10:12:06 2022 - [info]     Replicating from 10.9.40.182(10.9.40.182:3306)

Tue Mar  1 10:12:06 2022 - [info]     Primary candidate for the new Master (candidate_master is set)

Tue Mar  1 10:12:06 2022 - [info] Current Alive Master: 10.9.40.182(10.9.40.182:3306)

Tue Mar  1 10:12:06 2022 - [info] Checking slave configurations..

Tue Mar  1 10:12:06 2022 - [info]  read_only=1 is not set on slave 10.9.40.181(10.9.40.181:3306).

Tue Mar  1 10:12:06 2022 - [info] Checking replication filtering settings..

Tue Mar  1 10:12:06 2022 - [info]  binlog_do_db= , binlog_ignore_db= information_schema,mysql,performance_schema,sys

Tue Mar  1 10:12:06 2022 - [info]  Replication filtering check ok.

Tue Mar  1 10:12:06 2022 - [info] GTID (with auto-pos) is supported. Skipping all SSH and Node package checking.

Tue Mar  1 10:12:06 2022 - [info] Checking SSH publickey authentication settings on the current master..

Tue Mar  1 10:12:06 2022 - [info] HealthCheck: SSH to 10.9.40.182 is reachable.

Tue Mar  1 10:12:06 2022 - [info]

10.9.40.182(10.9.40.182:3306) (current master)

 +--10.9.40.181(10.9.40.181:3306)


Tue Mar  1 10:12:06 2022 - [info] Checking replication health on 10.9.40.181..

Tue Mar  1 10:12:06 2022 - [info]  ok.

Tue Mar  1 10:12:06 2022 - [info] Checking master_ip_failover_script status:

Tue Mar  1 10:12:06 2022 - [info]   /usr/bin/master_ip_failover --command=status --ssh_user=root --orig_master_host=10.9.40.182 --orig_master_ip=10.9.40.182 --orig_master_port=3306



IN SCRIPT TEST====/sbin/ifconfig enp0s3:88 down==/sbin/ifconfig enp0s3:88 10.9.40.183/24===


Checking the Status of the script.. OK

Tue Mar  1 10:12:06 2022 - [info]  OK.

Tue Mar  1 10:12:06 2022 - [warning] shutdown_script is not defined.

Tue Mar  1 10:12:06 2022 - [info] Got exit code 0 (Not master dead).


MySQL Replication Health is OK.

   

     在从库使用masterha_master_switch --conf=/etc/mha/mysql-mha.conf --master_state=alive --new_master_host=10.9.40.181 --new_master_port=3306 --orig_master_is_new_slave进行在线主从切换测试,切换完成后,注意检查主从是否切换完成,从库是否为read_only,以及vip是否切换

8.master节点手动执行vip命令

/sbin/ifconfig enp0s3:88 10.9.40.183/24

9.SLAVE节点启动MHA

masterha_manager --conf=/etc/mha/mysql-mha.conf &

10.主备切换后续处理

      如果发生主备切换,原主节点故障排除后需要重新加入集群并作为备库,MASTER_LOG_FILE及MASTER_LOG_POS可以在/home/mha/manager.log日志中找到:

Mon Feb 28 15:33:22 2022 - [info]
Mon Feb 28 15:33:22 2022 - [info] * Phase 3.3: New Master Recovery Phase..
Mon Feb 28 15:33:22 2022 - [info]
Mon Feb 28 15:33:22 2022 - [info]  Waiting all logs to be applied..
Mon Feb 28 15:33:22 2022 - [info]   done.
Mon Feb 28 15:33:22 2022 - [info] Getting new master's binlog name and position..
Mon Feb 28 15:33:22 2022 - [info]  mysql_bin_3306.000002:358

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值