zoukankan      html  css  js  c++  java
  • MHA 一主一从(传统复制)搭建脚本VIP自动切换


    172.16.0.125 testdb  MySQL主库,MHA node节点
    172.16.0.126 testdb2 MySQL从库,MHA master节点


    把ISO上传到 /opt/mysql
    mkdir /media/CentOS
    mount -o loop /opt/mysql/rhel-server-7.4-x86_64-dvd.iso /media/CentOS

    vi /etc/yum.repos.d/CentOS-Base.repo
    [centos7]
    name = Oracle Enterprise Linux 7-64bit DVD
    baseurl=file:///media/CentOS/
    gpgcheck=0
    enable=1


    安装依赖包
    yum install -y libaio
    yum install -y perl perl-devel
     
     
     
    解压
     
    mkdir /opt/mysql
    mv mysql-5.7.22-linux-glibc2.12-x86_64.tar.gz /opt/mysql/
     
    cd /opt/mysql
    tar -zxvf mysql-5.7.22-linux-glibc2.12-x86_64.tar.gz
     
     
     
     
    创建一个链接
    cd /usr/local
    ln -s /opt/mysql/mysql-5.7.22-linux-glibc2.12-x86_64 mysql
     
     
     
    创建运行的用户
    groupadd mysql
    useradd -g mysql -d /usr/local/mysql -s /sbin/nologin -M -n mysql
     
     
     
    创建所需要的目录
    mkdir -p /usr/local/data/{mysql,tmp}/
    mkdir /var/lib/mysql
     
     
    修改权限
    chown -R mysql:mysql /usr/local/mysql/
    chown -R mysql:mysql /usr/local/data/{mysql,tmp}/
    chown mysql:mysql /var/lib/mysql
     
     
    配置文件内容
    #my.cnf
    [client]
    port = 3307
    socket = /var/lib/mysql/mysql.sock
     
    [mysqld]
    datadir=/usr/local/data/mysql
    socket=/var/lib/mysql/mysql.sock
    tmpdir=/usr/local/data/tmp
    user=mysql
    port=3307
    server-id=62
    character-set-server=utf8
    transaction_isolation = READ-COMMITTED #事务提交等级
    old_passwords=0 #关闭旧密码选项
    secure-auth=1 #防止低版本客户端访问
    sql-mode="NO_AUTO_CREATE_USER" #禁止创建用户不添加密码
    safe-user-create=1 #只有在mysql.user数据库表上拥有INSERT权限的用户才能使用GRANT命令
    symbolic-links=0 #是否支持超链接文件
    skip_name_resolve=1 #禁用DNS主机名查找
    lower_case_table_names=1 #大小写不敏感
    local_infile=0 #禁止使用load data
    log_bin
    log_slave_updates
    innodb_open_files = 1000
     
    innodb_adaptive_hash_index = ON #自适应辅助hash索引开启
    innodb_file_per_table #innodb单独表文件
    innodb_file_format=Barracuda #启用压缩
    innodb_buffer_pool_size= 300MB #innodb的buff pool大小
    innodb_flush_method=O_DIRECT #避免双缓冲(double buffering)和降低swap的压力
    innodb_buffer_pool_dump_at_shutdown=1 #shutdown时dump出buff pool内容
    innodb_buffer_pool_load_at_startup=1 #shutdown时load入buff pool内容
     
    delayed_insert_limit = 100 #插入100行后允许select运行
    delayed_insert_timeout = 300 #INSERT语句的执行超时时间
    delayed_queue_size = 1000 #延迟队列长度
     
    sort_buffer_size=2M #每个线程的sort的内存
    join_buffer_size=4M #每个线程的join的内存
     
    max_connections=5000 #最大连接数
    max_connect_errors=1000 #最大连接错误数
    max_allowed_packet=1G #数据包大小
     
    table_definition_cache = 512 #存放表的定义信息
    table_open_cache = 200 #存放当前已经打开的表句柄
    tmp_table_size = 16777216 #临时表大小
    wait_timeout = 2880000 #等待超时
    interactive_timeout = 2880000
     
    [mysql]
    default-character-set=utf8
     
     
     
    修改my.cnf权限
    chown mysql:mysql /etc/my.cnf
     
     
     
    添加到环境变量
    echo "export PATH=$PATH:/usr/local/mysql/bin">>/etc/profile
    source /etc/profile
     
     
    初始化MySQL
    /usr/local/mysql/bin/mysqld --defaults-file=/etc/my.cnf --basedir=/usr/local/mysql --datadir=/usr/local/data/mysql --user=mysql --initialize-insecure
     
     
    启动MySQL
    cp /opt/mysql/mysql-5.7.22-linux-glibc2.12-x86_64/support-files/mysql.server /etc/init.d/mysqld
     
    /etc/init.d/mysqld start
     

     
    修改密码
     
    use mysql;
    update mysql.user set authentication_string=password('chengce243') where user='root' ;
    GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY 'chengce243';
    GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'chengce243';
    flush privileges;


    关闭防火墙
    systemctl stop firewalld.service
    systemctl disable firewalld.service
     
    关闭SELinux
    systemctl status firewalld
    sed -i 's/^SELINUX=.*$/SELINUX=disabled/g' /etc/selinux/config
    setenforce 0
     
     
    主库创建账号
    create user 'repl'@'172.16.0.%' identified by 'chengce243';
    grant replication slave on *.* to 'repl'@'172.16.0.%';
    flush privileges;

    从库测试OK
    mysql -h 172.16.0.125 -urepl -pchengce243

    从库执行语句
    change master to master_host='172.16.0.125',master_user='repl',master_password='chengce243',
    master_port=3306,master_log_file='testdb-bin.000013',master_log_pos=765;

    从库上查看状态:
    mysql> show slave status\G;
    Slave_IO_Running 和 Slave_SQL_Running都是 Yes,表示已经连接上了master,说明已经成功。


     

    主库上创建账号
    create user 'mhauser'@'172.16.0.%' identified by 'chengce243';
    grant all privileges on *.* to 'mhauser'@'172.16.0.%';
    flush privileges;


    分别配置root用户和mysql用户互信


    /etc/hosts 写入对应关系
    172.16.0.125 testdb
    172.16.0.126 testdb2

    在 172.16.0.125
    生成互信文件,输入如下命令,一路回车就行
    ssh-keygen

    cd ~/.ssh

    cat id_rsa.pub > authorized_keys
    chmod 600 *
    cd ~/
    scp -r .ssh 172.16.0.126:~/


    最后每个节点都要验证
    ssh testdb date
    ssh testdb2 date
     


    每个节点都要安装相关依赖包
    yum install -y perl-devel
    yum install -y perl-CPAN
    yum install -y perl-Time-HiRes
    yum install -y perl-DBD-MySQL
    yum install -y perl-Params-Validate

    yum install -y perl-Config-Tiny
    yum install -y perl-Log-Dispatch
    yum install -y perl-Parallel-ForkManager

    上述包如果yum源没有,可到 http://rpm.pbone.net/ 网站下载

    MHA 安装文件是修改过的,与官网不一样
    mha4mysql-manager-0.56.tar.gz
    mha4mysql-node-0.56.tar.gz


    MHA master节点安装
    tar xf mha4mysql-node-0.56.tar.gz
    cd mha4mysql-node-0.56
    perl Makefile.PL
    make && make install

    tar xf mha4mysql-manager-0.56.tar.gz
    cd mha4mysql-manager-0.56
    perl Makefile.PL
    make && make install


    MHA node节点安装
    tar xf mha4mysql-node-0.56.tar.gz
    cd mha4mysql-node-0.56
    perl Makefile.PL
    make && make install

     

    为MHA的相关配置信息的存放规划目录结构(2个节点均要操作):
    mkdir -p /usr/local/masterha_work/{conf,manager_workdir,rmt_mysql_binlog_workdir,script_dir,log}

    自定义规则:
    conf,存放MHA的配置文件
    log,存放于MHA有关的日志信息
    script_dir,除了默认的存放脚本的位置外,另一个存放自定义的或者官方提供的脚本的位置
    manager_workdir,Manager的工作目录
    rmt_mysql_binlog_workdir,当发生切换的时候,MySQL的binlog的临时存放路径


    修改配置目录权限:
    chown -R mysql:mysql /usr/local/masterha_work
     



    在MySQL Master配置VIP
    ifconfig ens160:0 172.16.0.127 netmask 255.255.255.0 up
    ifconfig ens160:0 172.16.0.127 netmask 255.255.255.0 down



    master_ip_failover脚本修改

    注释掉 FIXME,

    原:
    ## Creating an app user on the new master
    print "Creating app user on the new master..\n";
    FIXME_xxx_create_user( $new_master_handler->{dbh} );
    $new_master_handler->enable_log_bin_local();
    $new_master_handler->disconnect();
    ## Update master ip on the catalog database, etc
    FIXME_xxx;

    修改如下:

    ## Creating an app user on the new master
    print "Creating app user on the new master..\n";
    #FIXME_xxx_create_user( $new_master_handler->{dbh} );
    $new_master_handler->enable_log_bin_local();
    $new_master_handler->disconnect();
    ## Update master ip on the catalog database, etc
    #FIXME_xxx;

    在 FIXME_xxx 后面增加对 vip 的启用:
    `/usr/bin/ssh -t root\@${orig_master_ip} "ifconfig ens160:0 172.16.0.127 netmask 255.255.255.0 down"`;
    `/usr/bin/ssh -t root\@${new_master_ip}  "ifconfig ens160:0 172.16.0.127 netmask 255.255.255.0 up"`;
     
    注意,一定要用【;】结尾,否则脚本执行会出错。


    修改 new_master_handler 中 mhamhauser用户与密码 :

    # 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 );
    $new_master_handler->connect( $new_master_ip, $new_master_port,
    'mhauser', 'chengce243', 1 );

     

    修改后 master_ip_failover 脚本如下:

    [root@testdb2 ~]# cat /usr/bin/master_ip_failover
    #!/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;

    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
    );
    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 {
    if ( $command eq "stop" || $command eq "stopssh" ) {

    # $orig_master_host, $orig_master_ip, $orig_master_port are passed.
    # If you manage master ip address at global catalog database,
    # invalidate orig_master_ip here.
    my $exit_code = 1;
    eval {

    # updating global catalog, etc
    $exit_code = 0;
    };
    if ($@) {
    warn "Got Error: $@\n";
    exit $exit_code;
    }
    exit $exit_code;
    }
    elsif ( $command eq "start" ) {

    # all arguments are passed.
    # If you manage master ip address at global catalog database,
    # activate new_master_ip here.
    # You can also grant write access (create user, set read_only=0, etc) here.
    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,
    "mhauser", "chengce243", 1 );

    ## Set read_only=0 on the new master
    $new_master_handler->disable_log_bin_local();
    print "Set read_only=0 on the new master.\n";
    $new_master_handler->disable_read_only();

    ## Creating an app user on the new master
    print "Creating app user on the new master..\n";
    #FIXME_xxx_create_user( $new_master_handler->{dbh} );
    $new_master_handler->enable_log_bin_local();
    $new_master_handler->disconnect();

    ## Update master ip on the catalog database, etc
    #FIXME_xxx;

    `echo "script begin running..." > /usr/local/masterha_work/script_dir/master_ip_failover_run_shell`;

    #`/usr/bin/ssh -t root\@${orig_master_ip} "service keepalived stop" > /work_dir/mha_manager/test_me/orig_master.log`;
    #`/usr/bin/ssh -t root\@${new_master_ip} "service keepalived start" > /work_dir/mha_manager/test_me/new_master.log`;
    `/usr/bin/ssh -t root\@${orig_master_ip} "ifconfig ens160:0 172.16.0.127 netmask 255.255.255.0 down"`;
    `/usr/bin/ssh -t root\@${new_master_ip}  "ifconfig ens160:0 172.16.0.127 netmask 255.255.255.0 up"`;

    $exit_code = 0;
    };
    if ($@) {
    warn $@;

    # If you want to continue failover, exit 10.
    exit $exit_code;
    }
    exit $exit_code;
    }
    elsif ( $command eq "status" ) {

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

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

     


    最后修改脚本权限:
    chmod 755 /usr/bin/master_ip_failover

     


    master_ip_online_change 脚本修改:

    注释 FIXME_xxx_drop_app_user
    原来:
    ## 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);

    修改如下:
    ## 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);

    注释 FIXME_xxx_create_app_user
    原来:
    ## 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();

    修改如下:
    ## 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();

    修改 mhauser 用户的位置:
    位置一:
    # args: hostname, port, user, password, raise_error(die_on_error)_or_not
    $new_master_handler->connect( $new_master_ip, $new_master_port,
    "mhauser", "chengce243", 1 );

    位置二:
    # args: hostname, port, user, password, raise_error_or_not
    $new_master_handler->connect( $new_master_ip, $new_master_port,
    "mhauser", "chengce243", 1 );

    增加 vip 的启动:
    `/usr/bin/ssh -t root\@${orig_master_ip} "ifconfig ens160:0 172.16.0.127 netmask 255.255.255.0 down"`;
    `/usr/bin/ssh -t root\@${new_master_ip}  "ifconfig ens160:0 172.16.0.127 netmask 255.255.255.0 up"`;


    /usr/local/masterha_work/script_dir/master_ip_failover_run_shell

    修改后的脚本如下:
    [root@testdb2 ~]# cat /usr/bin/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;

    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,
    "mhauser", "chengce243", 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
    $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,
    "mhauser", "chengce243", 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
    #`/usr/bin/ssh -t root\@${orig_master_ip} "service keepalived stop"`;
    #`/usr/bin/ssh -t root\@${new_master_ip} "service keepalived start"`;
    `/usr/bin/ssh -t root\@${orig_master_ip} "ifconfig ens160:0 172.16.0.127 netmask 255.255.255.0 down"`;
    `/usr/bin/ssh -t root\@${new_master_ip}  "ifconfig ens160:0 172.16.0.127 netmask 255.255.255.0 up"`;

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

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

     

    修改文件的权限:
    chmod 755 /usr/bin/master_ip_online_change

     
     
    [root@testdb2 ~]# cat /usr/local/masterha_work/conf/masterha_monitor.cnf
    [server default]
    user=mhauser
    password=chengce243

    ssh_user=root

    master_binlog_dir=/data/mysql
    remote_workdir=/usr/local/masterha_work/rmt_mysql_binlog_workdir

    repl_user=repl
    repl_password=chengce243

    master_ip_failover_script=/usr/bin/master_ip_failover
    master_ip_online_change_script=/usr/bin/master_ip_online_change

    ping_interval=30

    manager_log=/usr/local/masterha_work/log/manager_monitor.log


    [server1]
    hostname=172.16.0.125
    port=3306

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



    # 如果是两节点slave(即三节点MHA)需要添加如下配置
    #三节点MHA和两节点MHA也就这一点区别
    [server3]
    hostname=172.16.0.82
    port=3307
    no_master=1


    在MHA master节点测试SSH连通性:
    masterha_check_ssh --conf=/usr/local/masterha_work/conf/masterha_monitor.cnf
     

    测试MySQL复制的情况:
    masterha_check_repl --conf=/usr/local/masterha_work/conf/masterha_monitor.cnf

     

    在testdb2上部署 call_do_mha.sh 脚本

    [root@testdb2 script_dir]# cat /usr/local/masterha_work/script_dir/call_do_mha.sh
    # name: call_do_mha.sh

    #variables

    str_mha_app=$1

    while [ true ]
    do
    sh /usr/local/masterha_work/script_dir/do_mha.sh $str_mha_app
    sleep 5
    done

     


    在testdb2上部署 do_mha.sh 脚本

    [root@testdb2 ~]# cat /usr/local/masterha_work/script_dir/do_mha.sh
    #!/bin/bash
    # Script
    # Name: do_mha.sh
    # APP vendor: MHA
    # Linux vendor: RHEL / CentOS


    # --------------------------
    # variable and file path

    # Part:: this script
    str_mha_application=$1

    # Part:: Linux
    # Account info
    str_linux_username="root"

    # Part:: MySQL
    # Account info
    str_mysql_username="root"
    str_mysql_password="chengce243"
    str_repl_port=3306
    str_repl_username="repl"
    str_repl_password="chengce243"
    str_ip_mha_manager="172.16.0.127"

    # Part:: MHA
    # pid
    str_pid_masterha_manager=`ps -ef | grep masterha_manager | grep "$str_mha_application" | grep perl | awk '{print $2}'`

    # file
    file_conf_mha_application="/usr/local/masterha_work/conf/$str_mha_application.cnf"

    # file: relation / by computed
    file_log_mha_manager=`cat $file_conf_mha_application | grep --color manager_log | cut -d'=' -f2`

    # variable: ip info
    # 如果MHA中MySQL主库的候选服务器数量超过了两台,也许下面这个list参数,就会排上用场
    list_ip_candicate=`cat $file_conf_mha_application | grep -B 2 "^candidate" | grep "hostname" | cut -d'=' -f2`

    str_ip_orig_master=`cat $file_log_mha_manager | grep --color "MySQL Master failover" | cut -d'(' -f2 | cut -d':' -f1 | tail -n 1`
    str_ip_new_master=`cat $file_log_mha_manager | grep --color "MySQL Master failover" | cut -d'(' -f3 | cut -d':' -f1 | tail -n 1`


    # 为[change master]准备的参数
    str_log_file_new_master=""
    str_log_pos_new_master=""

    # Part:: String SQL
    str_sql_mysql_change_master=""

    # --------------------------
    # function

    function do_sql() {
    # variable
    func_str_ip="$1"
    func_str_sql="$2"

    # action
    # 本场景中不涉及到对MySQL某个库的操作,所以没有选择[db]
    # mysql -u $user -p"$password" $db -N -e "$f_sql_str"
    mysql -u $str_mysql_username -h $func_str_ip -p"$str_mysql_password" -N -e "$func_str_sql" -P $str_repl_port
    }

    # 获取主库状态信息
    #function get_info_mysql_master_new_master() {
    # version ONE
    #str_log_file_new_master=`do_sql "$str_ip_new_master" "show master status" | awk '{print $1}'`
    #str_log_pos_new_master=`do_sql "$str_ip_new_master" "show master status" | awk '{print $2}'`

    #}

    # 生成orig_master作为slave加入new_master的[change master]SQL命令
    function gen_sql_mysql_change_master() {
    func_temp_master_host_sed=`cat $file_log_mha_manager | grep --color "All other slaves should start" | tail -n 1 | cut -d',' -f1 | cut -d'=' -f2 | cut -d\' -f2`
    func_temp_repl_password_sed=`cat $file_log_mha_manager | grep --color "All other slaves should start" | tail -n 1 | rev | cut -d\' -f2`

    echo "======================"
    echo "@@ func variable: func_temp_repl_password_sed = $func_temp_repl_password_sed"
    echo "======================"
    str_sql_mysql_change_master=`cat $file_log_mha_manager | grep --color "All other slaves should start" | tail -n 1 | sed "s#${func_temp_repl_password_sed}#${str_repl_password}#g" | cut -d':' -f4`
    str_sql_mysql_change_master=`echo $str_sql_mysql_change_master | sed "s#${func_temp_master_host_sed}#${str_ip_new_master}#g"`
    }

    # 对指定主机执行Linux命令
    # 前提:
    # 1. IP可达
    # 2. SSH等价关系
    function do_linux_by_ssh() {
    # variable
    func_str_ip="$1"
    func_str_user="$2"
    func_str_command="$3"

    # action
    # ssh -t $func_str_user@$func_str_ip "$func_str_command"
    ssh -t -t $func_str_user@$func_str_ip "$func_str_command"
    }

    # 处理VIP的事宜
    function do_part_vip() {
    do_linux_by_ssh "$str_ip_new_master" "root" "service keepalived start"
    do_linux_by_ssh "$str_ip_orig_master" "root" "service keepalived stop"
    }

    function do_part_orig_master_is_new_slave() {
    do_linux_by_ssh "$str_ip_orig_master" "root" "service mysqld start"
    do_sql "$str_ip_orig_master" "set global read_only=1;"
    do_sql "$str_ip_orig_master" "$str_sql_mysql_change_master"
    do_sql "$str_ip_orig_master" "start slave;"
    }

    function do_part_mha_master_manager_start() {
    do_linux_by_ssh "$str_ip_mha_manager" "root" "nohup masterha_manager --conf=$file_conf_mha_application --ignore_last_failover &"
    }

    # 如果PID不存在,则执行该脚本,否则,退出
    function runable_by_mha_manager_pid() {
    echo "-----------------"
    echo "Script for MySQL Master HA"
    echo "-----------------"
    echo "Begin:: "`date "+|%Y-%m-%d|%H:%M:%S|"`

    if [[ "$str_pid_masterha_manager" == "" ]]
    then
    echo "## masterha_manager is [NOT ALIVED]."
    else
    echo "## masterha_manager is [ALIVED]."
    echo "[masterha_manager] PID is:: $str_pid_masterha_manager"

    # do something.
    echo "## Exit Script"
    exit 0
    fi
    }

    # --------------------------
    # action

    # 如果PID不存在,则执行该脚本,否则,退出
    echo "------------------"
    echo "app: runable_by_mha_manager_pid"
    runable_by_mha_manager_pid
    echo ""

    echo "------------------"
    echo "app: gen_sql_mysql_change_master"
    gen_sql_mysql_change_master
    echo ""

    echo "------------------"
    echo "app: do_part_orig_master_is_new_slave"
    do_part_orig_master_is_new_slave
    echo ""

    echo "------------------"
    echo "app: do_part_mha_master_manager_start"
    #do_part_mha_master_manager_start
    nohup masterha_manager --conf=$file_conf_mha_application --ignore_last_failover > /usr/local/masterha_work/log/mha_manager.log 2>&1&
    echo ""

    # --------------------------
    # Show time


    echo "================="
    echo "MySQL info:"

    echo "## Account and Password"
    echo "username @ $str_mysql_username"
    echo "password @ $str_mysql_password"
    echo "--- for REPLICATION ---"
    echo "repl @ username ## $str_repl_username"
    echo "repl @ password ## $str_repl_password"
    echo "## Master Server info"
    echo "log file @ Master ## $str_log_file_new_master"
    echo "log pos @ Master ## $str_log_pos_new_master"
    echo ""

    echo "================="
    echo "SQL statement:"
    echo "[CHANGE MASTER] -->"
    echo "$str_sql_mysql_change_master"
    echo ""

    echo "================="
    echo "MasterHA info:"

    echo "## File and Path"
    echo "MHA Global config file @ $file_conf_mha_global"
    echo "MHA Application config file @ $file_conf_mha_application"
    echo "MHA Log file:: masterha_manager @ $file_log_mha_manager"

    echo "## Architecture"
    echo "Candicate Server list::"
    echo "$list_ip_candicate"

    echo "## IP"
    echo "MHA Manager Server:: $str_ip_mha_manager"
    echo "Last:: new master:: $str_ip_new_master"
    echo "Last:: orig master:: $str_ip_orig_master"
    echo ""

    # --------------------------
    echo "-----------------"
    echo "Finished:: "`date "+|%Y-%m-%d|%H:%M:%S|"`
    # Done




    启动 mha守护进程
    nohup masterha_manager --conf=/usr/local/masterha_work/conf/masterha_monitor.cnf --ignore_last_failover > /usr/local/masterha_work/log/mha_manager.log 2>&1&


    启动 call_do_mha.sh 脚本
    nohup sh /usr/local/masterha_work/script_dir/call_do_mha.sh masterha_monitor  > /usr/local/masterha_work/log/call_do_mha.log 2>&1&


    检查启动的状态
    masterha_check_status --conf=/usr/local/masterha_work/conf/masterha_monitor.cnf


    停止mha
    masterha_stop  --conf=/usr/local/masterha_work/conf/masterha_monitor.cnf


     
  • 相关阅读:
    oracle数据库数据导出
    oracle 数据连接方式
    plsql 建表空间
    java Excel 导入数据库
    python爬虫学习数据分析(连载中)
    python之pip库管理工具pip安装
    数据结构之看病排队系统
    数据结构之顺序串
    数据结构之链队
    数据结构之环形队列
  • 原文地址:https://www.cnblogs.com/l10n/p/7517929.html
Copyright © 2011-2022 走看看