본문 바로가기

리눅스

[MySQL] MHA 아키텍처 기반 MySQL 고가용성 스위칭 아키텍처

반응형

MHA 아키텍처 기반 MySQL 고가용성 스위칭 아키텍처

테스트 환경

$ cat /etc/redhat-release
CentOS Linux release 7.9.2009 (Core)

$ mysqld --version
mysqld  Ver 5.7.14 for Linux on x86_64 (MySQL Community Server (GPL))
호스트 네임 아이피 MySQL 역할 MHA 역할
비고
VIP 192.168.20.145 - -  
node1 192.168.20.146 master mha4mysql-node  
node2 192.168.20.147 slave mha4mysql-node  
manager 192.168.20.139   mha4mysql-manager, mha4mysql-node  

MHA node 구성

$ yum -y install perl-CPAN perl-DBD-MySQL perl-Module-Install


$ tar xvzf mha4mysql-node-0.57.tar.gz 
$ cd mha4mysql-node-0.57 
$ perl Makefile.PL 
$ make 
$ make install


#MHA 시스템 작업을 위해 데이터베이스에 관리자 계정 생성
$ mysql --login-path=tdb -e 'GRANT ALL PRIVILEGES ON *.* TO 'mha'@'192.168.20.%' IDENTIFIED BY 'Mha11@@@''
$ mysql --login-path=tdb mysql -e 'select user, host from user;'
apply_diff_relay_logs	#마스터의 바이너리 로그 저장 및 복사
filter_mysqlbinlog	#다른 릴레이 로그 이벤트를 식별하고 다른 이벤트를 다른 슬레이브에 적용
purge_relay_logs	#불필요한 ROLLBACK 이벤트 제거(MHA는 더 이상 이 도구를 사용하지 않음)
save_binary_logs	#릴레이 로그 지우기(SQL 스레드를 차단하지 않음)

MHA manager 구성

$ yum -y install perl-CPAN perl-DBD-MySQL perl-Config-Tiny perl-Log-Dispatch perl-Parallel-ForkManager perl-Module-Install


$ tar xvzf mha4mysql-manager-0.57.tar.gz 
$ cd mha4mysql-manager-0.57 
$ perl Makefile.PL 
$ make 
$ make install


#app1.conf 복사
$ cp /usr/local/src/mha4mysql-manager-0.57/samples/conf/app1.cnf /etc/app1.cnf
$ cp -rf /usr/local/src/mha4mysql-manager-0.57/samples/scripts /home/mhauser/
masterha_check_repl	#MySQL 복제 상태 확인
masterha_check_ssh	#MHA의 SSH 구성 상태 확인
masterha_check_status	#현재 MHA 실행 상태 감지
masterha_conf_host	#구성된 서버 정보 추가 또는 삭제
masterha_manager	#MHA 시작
masterha_master_monitor	#마스터가 다운되었는지 감지 
masterha_master_switch	#Failover(자동 또는 수동)
masterha_secondary_check #MySQL 마스터 서버의 가용성을 확인하기 위한 두 개 이상의 네트워크 라인
masterha_stop		#MHA를 중지

app1.conf 편집

$ vim /etc/app1.cnf
[server default]
ping_interval=1
ping_type=select

#mysql user and password
user=mha
password=Mha11@@@

#ssh user
ssh_user=mhauser

#replication user
repl_user=repl
repl_password=Repl!!@@

#mha log
manager_workdir=/home/mhauser/mwork
manager_log=/home/mhauser/mwork/manager.log

#master
master_binlog_dir=/var/log/mysql
master_pid_file=/var/run/mysqld/mysqld.pid

#remote mha log
remote_workdir=/home/mhauser/mwork

master_ip_failover_script=/home/mhauser/scripts/master_ip_failover
master_ip_online_change_script=/home/mhauser/scripts/master_ip_online_change
shutdown_script=""
#secondary_check_script=masterha_secondary_check -s 192.168.20.146 -s 192.168.20.147 --user=mha --master_host=192.168.20.146 --master_ip=192.168.20.146 --master_port=3306
#report_script=/home/mhauser/send_report

[server1]
hostname=192.168.20.146
port=3306
candidate_master=1
check_repl_delay=0

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

master_ip_failover 편집

$ cat /home/mhauser/scripts/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,  $new_master_user,
  $new_master_password
);

my $vip = '192.168.20.145/24';
my $interface = 'ens192';
my $key = '0';
my $ssh_start_vip = "ifconfig $interface:$key $vip";
my $ssh_stop_vip = "ifconfig $interface:$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";
}

master_ip_online_change 편집

$ vim /home/mhauser/scripts/master_ip_online_change
#!/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;

#####sangchul#####
my $vip = '192.168.20.145/24';
my $interface = 'ens192';
my $key = "0";
my $ssh_start_vip = "sudo ifconfig $interface:$key $vip";
my $ssh_stop_vip = "sudo ifconfig $interface:$key down";
my $exit_code = 0;
#####sangchul#####

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,
);
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} );
      }

      ## 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
      #####sangchul#####
      &stop_vip();
      #####sangchul#####
      $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
      #####sangchul#####
      &start_vip();
      #####sangchul#####
      $exit_code = 0;
    };
    if ($@) {
      warn "Got Error: $@\n";
      exit $exit_code;
    }
    exit $exit_code;
  }
  elsif ( $command eq "status" ) {
    #####sangchul#####
    print "Checking the Status of the script.. OK \n";
    `ssh $orig_master_ssh_user\@$orig_master_host \" $ssh_start_vip \"`;
    #####sangchul#####

    # do nothing
    exit 0;
  }
  else {
    &usage();
    exit 1;
  }
}

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

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

--

MHA 실행 스크립트 생성

/usr/local/bin/mha

$ vim /usr/local/bin/mha
#!/bin/bash

SERVICE="MHA"

start() {
    echo "Starting $SERVICE... "
    nohup masterha_manager --conf=/etc/app1.cnf --remove_dead_master_conf --ignore_last_failover < /dev/null> /home/mhauser/mwork/manager.log 2>&1 &
}

stop() {
    echo -n $"Stopping $SERVICE: "
    masterha_stop --conf=/etc/app1.cnf
}

case "$1" in
    start)
        start
    ;;
    stop)
        stop
    ;;
    restart)
        stop
        start
    ;;
    status)
        masterha_check_status --conf=/etc/app1.cnf
    ;;
    ssh)
        echo "$SERVICE ssh check..."
        masterha_check_ssh --conf=/etc/app1.cnf
    ;;
    repl)
        echo "$SERVICE repl check..."
        masterha_check_repl --conf=/etc/app1.cnf
    ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|ssh|repl}"
        exit 1
esac
$ chmod +x /usr/local/bin/mha

MHA의 SSH 구성 상태 확인

masterha_check_ssh --conf=/etc/app1.cnf

$ mha ssh
...
Mon Sep 13 21:31:23 2021 - [info] All SSH connection tests passed successfully.

MySQL 복제 상태 확인

masterha_check_repl --conf=/etc/app1.cnf

$ mha repl
...
MySQL Replication Health is OK.

MHA manager 스크립트 생성(mhauser 사용자)

$ vim /home/mhauser/bin/mha_start.sh
#!/bin/bash

su - mhauser -c 'nohup masterha_manager --conf=/etc/app1.cnf --ignore_last_failover < /dev/null > /home/mhauser/mwork/manager.out 2>&1 &'


$ vim /home/mhauser/bin/mha_stop.sh
#!/bin/bash

su - mhauser -c 'masterha_stop --conf=/etc/app1.cnf'


$ vim /home/mhauser/bin/mha_status.sh
#!/bin/bash

su - mhauser -c 'masterha_check_status --conf=/etc/app1.cnf'

스크립트 실행

$ mha 
Usage: /usr/local/bin/mha {start|stop|status|restart|ssh|repl}

$ mha start


$ mha status
app1 (pid:9016) is running(0:PING_OK), master:192.168.20.147


$ mha stop
Stopped app1 successfully.


$ mha status
app1 is stopped(2:NOT_RUNNING).

 


리플리케이션 재구성

node1/node2

mysql --login-path=mha_node -e "show binary logs"
mysql --login-path=mha_node -e "purge binary logs to 'mysql-bin.000006'"
mysql --login-path=mha_node -e "set global relay_log_purge=0"
mysql --login-path=mha_node -e "show variables like 'relay_log_purge'"


mysql --login-path=mha_node -e "show variables like '%log_bin%'"


#프로세스 목록
mysql --login-path=mha_node -e "show processlist"
#프로세스 KILL
mysql --login-path=mha_node -e "kill 2"

node1(master)

#[master]
mysql --login-path=mha_node -e "STOP MASTER"

mysql --login-path=mha_node -e "RESET MASTER"

mysql --login-path=mha_node -e "SHOW MASTER STATUS"

mysql --login-path=mha_node -e "SELECT @@read_only"


###[master -> slave]
mysql --login-path=mha_node -e "STOP SLAVE"
mysql --login-path=mha_node -e "RESET SLAVE"
mysql --login-path=mha_node -e "CHANGE MASTER TO MASTER_HOST='192.168.20.147',MASTER_USER='repl', MASTER_PASSWORD='Repl11@@', MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=154;"
mysql --login-path=mha_node -e "START SLAVE"

node2(slave)

#[slave]
mysql --login-path=mha_node -e "STOP SLAVE"

mysql --login-path=mha_node -e "RESET SLAVE"

mysql --login-path=mha_node -e "CHANGE MASTER TO MASTER_HOST='192.168.20.146',MASTER_USER='repl', MASTER_PASSWORD='Repl11@@', MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=154;"

mysql --login-path=mha_node -e "START SLAVE"

mysql --login-path=mha_node -e "SHOW SLAVE STATUS\G"


mysql --login-path=mha_node -e "SHOW SLAVE STATUS\G"

mysql --login-path=mha_node -e "show slave hosts;"

d

mysqladmin -hlocalhost -uroot -p'password1!' -S /var/lib/mysql/mysql.sock shutdown

masterha_master_switch

$ masterha_master_switch --master_state=alive --conf=/etc/app1.cnf --orig_master_is_new_slave --running_updates_limit=10000

 

728x90
반응형