博客作业第五周-mysql主从复制、高可用性、运维自动化ansible

1、如果主节点已经运行了一段时间,且有大量数据时,如何配置并启动slave节点

实验环境:master: centos8 10.0.0.68 mariadb-10.3.17
slave: centos8 10.0.0.58 mariadb-10.3.17
两台主机分别安装mariadb

[root@master ~]#yum -y install mariadb-server
[root@slave ~]#yum -y install mariadb-server

master配置

(1)为主节点指定server-id和开启二进制日志,启动服务

[root@master ~]#vim /etc/my.cnf.d/mariadb-server.cnf 

[server]

# this is only for the mysqld standalone daemon
# Settings user and group are ignored when systemd is used.
# If you need to run mysqld under a different user or group,
# customize your systemd unit file for mysqld/mariadb according to the
# instructions in http://fedoraproject.org/wiki/Systemd
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
log-error=/var/log/mariadb/mariadb.log
pid-file=/run/mariadb/mariadb.pid
server-id=68         #指定id
log_bin				#开启二进制日志

#
# * Galera-related settings
#
[galera]
"/etc/my.cnf.d/mariadb-server.cnf" 56L, 1478C
[root@master ~]#systemctl start mariadb.service 

(2)模拟数据库运行一段时间导入测试数据库

[root@master ~]#mysql < hellodb_innodb.sql 
**MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| hellodb            |
| information_schema |
| mysql              |
| performance_schema |
+--------------------+
4 rows in set (0.000 sec)

修改表行

**MariaDB [hellodb]> update students set age=25,gender='F' where stuid=25;
Query OK, 1 row affected (0.003 sec)
Rows matched: 1  Changed: 1  Warnings: 0

MariaDB [hellodb]> select * from students;
+-------+---------------+-----+--------+---------+-----------+
| StuID | Name          | Age | Gender | ClassID | TeacherID |
+-------+---------------+-----+--------+---------+-----------+
|     1 | Shi Zhongyu   |  22 | M      |       2 |         3 |
|     2 | Shi Potian    |  22 | M      |       1 |         7 |
|     3 | Xie Yanke     |  53 | M      |       2 |        16 |
|     4 | Ding Dian     |  32 | M      |       4 |         4 |
|     5 | Yu Yutong     |  26 | M      |       3 |         1 |
|     6 | Shi Qing      |  46 | M      |       5 |      NULL |
|     7 | Xi Ren        |  19 | F      |       3 |      NULL |
|     8 | Lin Daiyu     |  17 | F      |       7 |      NULL |
|     9 | Ren Yingying  |  20 | F      |       6 |      NULL |
|    10 | Yue Lingshan  |  19 | F      |       3 |      NULL |
|    11 | Yuan Chengzhi |  23 | M      |       6 |      NULL |
|    12 | Wen Qingqing  |  19 | F      |       1 |      NULL |
|    13 | Tian Boguang  |  33 | M      |       2 |      NULL |
|    14 | Lu Wushuang   |  17 | F      |       3 |      NULL |
|    15 | Duan Yu       |  19 | M      |       4 |      NULL |
|    16 | Xu Zhu        |  21 | M      |       1 |      NULL |
|    17 | Lin Chong     |  25 | M      |       4 |      NULL |
|    18 | Hua Rong      |  23 | M      |       7 |      NULL |
|    19 | Xue Baochai   |  18 | F      |       6 |      NULL |
|    20 | Diao Chan     |  19 | F      |       7 |      NULL |
|    21 | Huang Yueying |  22 | F      |       6 |      NULL |
|    22 | Xiao Qiao     |  20 | F      |       1 |      NULL |
|    23 | Ma Chao       |  23 | M      |       4 |      NULL |
|    24 | Xu Xian       |  27 | M      |    NULL |      NULL |
|    25 | Sun Dasheng   |  25 | F      |    NULL |      NULL |
+-------+---------------+-----+--------+---------+-----------+
25 rows in set (0.000 sec)
**

(3)生产中遇到运行一段时间的数据库,先查看当前二进制日志的位置(show master logs;),然后对数据库进行完全备份

**MariaDB [hellodb]> show master logs;
+--------------------+-----------+
| Log_name           | File_size |
+--------------------+-----------+
| mariadb-bin.000001 |     28198 |
| mariadb-bin.000002 |      9157 |
+--------------------+-----------+
2 rows in set (0.000 sec)
**
[root@master ~]#mysqldump -A --single-transaction --master-data=1 -F > /backup/all.sql

查看备份文件,003日志389往后即需要同步的内容

[root@master ~]#vim /backup/all.sql 

/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Position to start replication or point-in-time recovery from
--

CHANGE MASTER TO MASTER_LOG_FILE='mariadb-bin.000003', MASTER_LOG_POS=389;  #改行记录备份时二进制日志位置

--
-- GTID to start replication from
--

-- SET GLOBAL gtid_slave_pos='0-68-80';

--
-- Current Database: `hellodb`
--

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `hellodb` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `hellodb`;

--
-- Table structure for table `classes`
--

DROP TABLE IF EXISTS `classes`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `classes` (
  `ClassID` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `Class` varchar(100) DEFAULT NULL,
  `NumOfStu` smallint(5) unsigned DEFAULT NULL,

(4)创建有复制权限的账号

MariaDB [(none)]> grant replication slave on *.* to repluser@'10.0.0.%' identified by '123456';
Query OK, 0 rows affected (0.001 sec)

slave配置

(1)修改server-id 启动服务

[root@slave ~]#vim /etc/my.cnf.d/mariadb-server.cnf 

#
# These groups are read by MariaDB server.
# Use it for options that only the server (but not clients) should see
#
#
# These groups are read by MariaDB server.
# Use it for options that only the server (but not clients) should see
#
# See the examples of server my.cnf files in /usr/share/mysql/
#

# this is read by the standalone daemon and embedded servers
[server]

# this is only for the mysqld standalone daemon
# Settings user and group are ignored when systemd is used.
# If you need to run mysqld under a different user or group,
# customize your systemd unit file for mysqld/mariadb according to the
# instructions in http://fedoraproject.org/wiki/Systemd
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
log-error=/var/log/mariadb/mariadb.log
pid-file=/run/mariadb/mariadb.pid
server-id=58      #指定id

(2)将主节点的完全备份文件拷贝到从节点,进行编辑添加信息,添加信息分别为:要复制的主节点IP地址、用于复制的用户名、密码、数据库端口号

[root@master ~]#scp /backup/all.sql [email protected]:/root
The authenticity of host '10.0.0.58 (10.0.0.58)' can't be established.
ECDSA key fingerprint is SHA256:2At7o6y8rVcjVAyXEeyB5nXI7CCJvPe+0QYOi8Y7AvU.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.0.0.58' (ECDSA) to the list of known hosts.
[email protected]'s password: 
all.sql                                                                                                                                   100%  476KB  40.5MB/s   00:00    
[root@slave ~]#vim all.sql 

-- MySQL dump 10.17  Distrib 10.3.17-MariaDB, for Linux (x86_64)
--
-- Host: localhost    Database: 
-- ------------------------------------------------------
-- Server version       10.3.17-MariaDB-log

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Position to start replication or point-in-time recovery from
--
CHANGE MASTER TO
  MASTER_HOST='10.0.0.68',
  MASTER_USER='repluser',
  MASTER_PASSWORD='123456',
  MASTER_PORT=3306,
 MASTER_LOG_FILE='mariadb-bin.000003', MASTER_LOG_POS=389;

(3)将修改好的文件导入到数据库中

[root@slave ~]#mysql < all.sql 

(4)查看复制状态

MariaDB [hellodb]> show slave status\G;
*************************** 1. row ***************************
                Slave_IO_State: 
                   Master_Host: 10.0.0.68
                   Master_User: repluser
                   Master_Port: 3306
                 Connect_Retry: 60
               Master_Log_File: mariadb-bin.000003
           Read_Master_Log_Pos: 389
                Relay_Log_File: mariadb-relay-bin.000001
                 Relay_Log_Pos: 4
         Relay_Master_Log_File: mariadb-bin.000003
              Slave_IO_Running: No
             Slave_SQL_Running: No
               Replicate_Do_DB: 
           Replicate_Ignore_DB: 
            Replicate_Do_Table: 
        Replicate_Ignore_Table: 
       Replicate_Wild_Do_Table: 
   Replicate_Wild_Ignore_Table: 
                    Last_Errno: 0
                    Last_Error: 
                  Skip_Counter: 0
           Exec_Master_Log_Pos: 389
               Relay_Log_Space: 256
               Until_Condition: None
                Until_Log_File: 
                 Until_Log_Pos: 0
            Master_SSL_Allowed: No
            Master_SSL_CA_File: 
            Master_SSL_CA_Path: 
               Master_SSL_Cert: 
             Master_SSL_Cipher: 
                Master_SSL_Key: 
         Seconds_Behind_Master: NULL
 Master_SSL_Verify_Server_Cert: No
                 Last_IO_Errno: 0

(5)主节点服务器修改数据查看从节点是否能同步

主节点数据库修改

MariaDB [hellodb]> update students set age=30,gender='M' where stuid=25;
Query OK, 1 row affected (0.002 sec)
Rows matched: 1  Changed: 1  Warnings: 0

查看从节点发现数据已经同步

MariaDB [hellodb]> select * from students;
+-------+---------------+-----+--------+---------+-----------+
| StuID | Name          | Age | Gender | ClassID | TeacherID |
+-------+---------------+-----+--------+---------+-----------+
|     1 | Shi Zhongyu   |  22 | M      |       2 |         3 |
|     2 | Shi Potian    |  22 | M      |       1 |         7 |
|     3 | Xie Yanke     |  53 | M      |       2 |        16 |
|     4 | Ding Dian     |  32 | M      |       4 |         4 |
|     5 | Yu Yutong     |  26 | M      |       3 |         1 |
|     6 | Shi Qing      |  46 | M      |       5 |      NULL |
|     7 | Xi Ren        |  19 | F      |       3 |      NULL |
|     8 | Lin Daiyu     |  17 | F      |       7 |      NULL |
|     9 | Ren Yingying  |  20 | F      |       6 |      NULL |
|    10 | Yue Lingshan  |  19 | F      |       3 |      NULL |
|    11 | Yuan Chengzhi |  23 | M      |       6 |      NULL |
|    12 | Wen Qingqing  |  19 | F      |       1 |      NULL |
|    13 | Tian Boguang  |  33 | M      |       2 |      NULL |
|    14 | Lu Wushuang   |  17 | F      |       3 |      NULL |
|    15 | Duan Yu       |  19 | M      |       4 |      NULL |
|    16 | Xu Zhu        |  21 | M      |       1 |      NULL |
|    17 | Lin Chong     |  25 | M      |       4 |      NULL |
|    18 | Hua Rong      |  23 | M      |       7 |      NULL |
|    19 | Xue Baochai   |  18 | F      |       6 |      NULL |
|    20 | Diao Chan     |  19 | F      |       7 |      NULL |
|    21 | Huang Yueying |  22 | F      |       6 |      NULL |
|    22 | Xiao Qiao     |  20 | F      |       1 |      NULL |
|    23 | Ma Chao       |  23 | M      |       4 |      NULL |
|    24 | Xu Xian       |  27 | M      |    NULL |      NULL |
|    25 | Sun Dasheng   |  30 | M      |    NULL |      NULL |
+-------+---------------+-----+--------+---------+-----------+
25 rows in set (0.001 sec)

2、当master服务器宕机,提升一个slave成为新的maste

如遇主服务器挂掉,有两个从节点,查看从节点复制状态,哪个值大哪个为新主节点,成为主服务需要开启二进制日志,关闭read-only选项重启数据库服务
(1)比较以下值哪个较大,哪个为新主
博客作业第五周-mysql主从复制、高可用性、运维自动化ansible_第1张图片
(2)选定新主服务器开启二进制日志,关闭read-only,重启数据库服务
(3)选定新主服务器关闭从节点复制的两个线程
在这里插入图片描述
(4)选定新主服务器删除从节点信息
博客作业第五周-mysql主从复制、高可用性、运维自动化ansible_第2张图片
(5)在另一台未选中为主服务器关闭从节点线程,清理从节点信息,重新建立主节点复制信息
(6)查看新主节点当前二进制日志位置,在新从节点创建复制
博客作业第五周-mysql主从复制、高可用性、运维自动化ansible_第3张图片
(7)从节点创建复制,启动线程
博客作业第五周-mysql主从复制、高可用性、运维自动化ansible_第4张图片

3、通过 MHA 0.58 搭建一个数据库集群结构

一、MHA功能介绍

MHA(Master HA)是一款开源的 MySQL 的高可用程序,它为 MySQL 主从复制架构提供了 automating master failover 功能。MHA 在监控到 master 节点故障时,会提升其中拥有最新数据的 slave 节点成为新的master 节点,在此期间,MHA 会通过于其它从节点获取额外信息来避免一致性方面的问题。MHA 还提供了 master 节点的在线切换功能,即按需切换 master/slave 节点。

二、实验环境

四台主机
10.0.0.47	centos7	                 MHA管理端
10.0.0.68	centos8	   mysql5.7      master
10.0.0.58	centos8	   mysql5.7      slave1
10.0.0.48	centos8	   mysql5.7      slave2

三、实验步骤

(1)管理端10.0.0.47安装两个包,提前将rpm包拷贝到服务器上

[root@Centos7 ~]# yum -y install mha4mysql-node-0.58-0.el7.centos.noarch.rpm 
[root@Centos7 ~]# yum -y install mha4mysql-manager-0.58-0.el7.centos.noarch.rpm 

(2)所有节点安装 mha4mysql-node-0.58-0.el7.centos.noarch.rpm包

[root@centos8 ~]#yum -y install mha4mysql-node-0.58-0.el7.centos.noarch.rpm

(3)在所有节点实现相互之间ssh key验证

[root@MHA-manager ~]# ssh-keygen 
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
/root/.ssh/id_rsa already exists.
Overwrite (y/n)? y
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:ZcqwWG++dnbfk8EInqznpWoOJTqpCx5n5eJl7BJW03U root@MHA-manager
The key's randomart image is:
+---[RSA 2048]----+
|                 |
|         . E     |
|      + . +      |
|     = * + .     |
|    o.o.S.o o o  |
|   o+ ooo  + . o |
| o.+.O .. .  .  o|
|. *.* . o+o.+  + |
| . +o. .+=++ .. o|
+----[SHA256]-----+
[root@MHA-manager ~]# ssh-copy-id 127.0.0.1
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '127.0.0.1 (127.0.0.1)' can't be established.
ECDSA key fingerprint is SHA256:IHxJ9vqEMp/UwtZ034seLyuNP0D0By5u/O7iBCM2Cik.
ECDSA key fingerprint is MD5:72:b0:4c:7e:54:e3:92:e5:d0:05:ec:57:2c:7b:31:c3.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
[email protected]'s password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '127.0.0.1'"
and check to make sure that only the key(s) you wanted were added.
[root@MHA-manager ~]# rsync -a .ssh 10.0.0.48:/root/
root@MHA-manager ~]# rsync -a .ssh 10.0.0.58:/root/
[root@MHA-manager ~]# rsync -a .ssh 10.0.0.68:/root/

(4)在管理节点建立配置文件

[root@MHA-manager ~]# mkdir /etc/mastermha
[root@MHA-manager ~]# vim /etc/mastermha/app1.cnf
[server default]
user=mhauser #用于远程链接MySQL所有节点的用户,需要有管理员权限
password=123456
manager_workdir=/data/mastermha/app1/  #该目录会自动生成
manager_log=/data/mastermha/app1/manager.log
remote_workdir=/data/mastermha/app1/
ssh_user=root   #用于实现远程ssh基于key验证的连接
repl_user=repluser #主从复制的用户
repl_password=magedu
ping_interval=1 #健康检查的时间间隔
master_ip_failover_script=/usr/local/bin/master_ip_failover #切换VIP的perl脚本
report_script=/usr/local/bin/sendmail.sh #报警脚本
check_repl_delay=0 #默认slave中从库落后主库relaylog超过100M,主库不会选择这个从库为新的master,因为这个从库>进行恢复需要很长的时间。通过这个参数,mha触发主从切换的时候会忽略复制的延时,对于设置candidate_master=1的从>库非常有用,确保这个从库一定能成为最新的master
master_binlog_dir=/data/mysql/ #指定二进制日志存放的目录,mha4mysql-manager-0.58版本必须指定,之前的不需要
[server1]
hostname=10.0.0.68
candidate_master=1  
[server2]
hostname=10.0.0.58
candidate_master=1  #设置为优先候选master,即使不是集群中事件最新的slave,也会优先当
master
[server3]
hostname=10.0.0.48

在管理节点安装mailx软件包,准备.mailrc文件,准备两个相关脚本

[root@Centos7 ~]# yum -y install mailx.x86_64 
[root@Centos7 ~]# cat .mailrc 
set from=[email protected]
set smtp=smtp.139.com
set smtp-auth-user=13593386981
set smtp-auth-password=GaoJinZhou00
set smtp-auth=login
set ssl-verify=ignore
[root@Centos7 ~]# chmod +x /usr/local/bin/sendmail.sh 
[root@Centos7 ~]# cat /usr/local/bin/master_ip_failover 
#!/usr/bin/env perl
use strict;
use warnings FATAL=> 'all';
use Getopt::Long;
my(
$command, $ssh_user, $orig_master_host, $orig_master_ip, $orig_master_port,$new_master_host, $new_master_ip, $new_master_port);
my $vip = '10.0.0.100/24';
my $gateway = '10.0.0.2';
my $interface = 'eth0';
my $key = "1";
my $ssh_start_vip = "/sbin/ifconfig $interface:$key $vip;/sbin/arping -I $interface -c 3 -s $vip $gateway > /dev/null 2&>1";
my $ssh_stop_vip = "/sbin/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,
);
exit &main();
sub main {
print "\n\nIN SCRIPT TEST====$ssh_stop_vip==$ssh_start_vip===\n\n";
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 {
print "Disabling the VIP on old master: $orig_master_host \n";
$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 {
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\@$orig_master_host \" $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() {
`ssh $ssh_user\@$orig_master_host \" $ssh_stop_vip \"`;
}
sub usage {
print
"Usage: master_ip_failover --command=start|stop|stopssh|status --orig_master_host=host --orig_master_ip=ip --orig_master_port=port --new_master_host=host --new_master_ip=ip --new_master_port=port\n";
}
[root@Centos7 ~]# chmod +x /usr/local/bin/master_ip_failover 

(5)实现master节点

#修改配置文件
[root@master ~]#cat /etc/my.cnf
[mysqld]
server-id=1         #指定固定id
log-bin=/data/mysql/mysql-bin    #开启二进制日志
skip_name_resolve=1             #禁止反向解析
datadir=/data/mysql
socket=/data/mysql/mysql.sock                                           
log-error=/data/mysql/mysql.log
pid-file=/data/mysql/mysql.pid
[client]
socket=/data/mysql/mysql.sock
#启动服务进入数据库
#查看当前二进制日志位置
mysql> show master logs;
+------------------+-----------+
| Log_name         | File_size |
+------------------+-----------+
| mysql-bin.000001 |       154 |
+------------------+-----------+
1 row in set (0.00 sec)
#创建复制所需账号,创建mha所需账号
mysql> grant replication slave on *.* to 'repluser'@'10.0.0.%' identified by '123456';
Query OK, 0 rows affected, 1 warning (0.04 sec)

mysql> grant all on *.* to mhauser@'10.0.0.%' identified by '123456';
Query OK, 0 rows affected, 1 warning (0.00 sec)
#配置VIP
[root@master ~]#ifconfig eth0:1 10.0.0.100/24
[root@master ~]#ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:10:2e:9d brd ff:ff:ff:ff:ff:ff
    inet 10.0.0.68/24 brd 10.0.0.255 scope global noprefixroute eth0
       valid_lft forever preferred_lft forever
    inet 10.0.0.100/24 brd 10.0.0.255 scope global secondary eth0:1
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fe10:2e9d/64 scope link 
       valid_lft forever preferred_lft forever

(6)实现slave1

#修改配置文件
[root@slave1 ~]#cat /etc/my.cnf
[mysqld]
server-id=2
log-bin=/data/mysql/mysql-bin   #开启二进制日志
datadir=/data/mysql
read_only
relay_log_purge=0              #不清除中继日志
skip_name_resolve=1             #禁止反向解析 
socket=/data/mysql/mysql.sock                                                                                   
log-error=/data/mysql/mysql.log
pid-file=/data/mysql/mysql.pid
[client]
socket=/data/mysql/mysql.sock
#进入数据库执行change master
mysql> CHANGE MASTER TO
    ->   MASTER_HOST='10.0.0.68',
    ->   MASTER_USER='repluser',
    ->   MASTER_PASSWORD='123456',
    ->   MASTER_PORT=3306,
    ->  MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=154;
Query OK, 0 rows affected, 2 warnings (0.04 sec)
mysql> start slave;

(7)实现slave2

#修改配置文件
[root@slave2 ~]#cat /etc/my.cnf 
[mysqld]
server-id=3
log-bin=/data/mysql/mysql-bin
read_only
relay_log_purge=0   
skip_name_resolve=1 
datadir=/data/mysql
socket=/data/mysql/mysql.sock                                                                     
log-error=/data/mysql/mysql.log
pid-file=/data/mysql/mysql.pid
[client]
socket=/data/mysql/mysql.sock
#进入数据库执行change master
mysql> CHANGE MASTER TO
    ->   MASTER_HOST='10.0.0.68',
    ->   MASTER_USER='repluser',
    ->   MASTER_PASSWORD='123456',
    ->   MASTER_PORT=3306,
    ->  MASTER_LOG_FILE='mysql-bin.000001', 
    ->  MASTER_LOG_POS=154;
Query OK, 0 rows affected, 2 warnings (0.05 sec)
mysql> start slave;

(8)检查MHA环境

[root@MHA-manager ~]# masterha_check_ssh --conf=/etc/mastermha/app1.cnf 
Sat Oct 17 11:03:38 2020 - [warning] Global configuration file /etc/masterha_default.cnf not found. Skipping.
Sat Oct 17 11:03:38 2020 - [info] Reading application default configuration from /etc/mastermha/app1.cnf..
Sat Oct 17 11:03:38 2020 - [info] Reading server configuration from /etc/mastermha/app1.cnf..
Sat Oct 17 11:03:38 2020 - [info] Starting SSH connection tests..
Sat Oct 17 11:03:39 2020 - [debug] 
Sat Oct 17 11:03:38 2020 - [debug]  Connecting via SSH from [email protected](10.0.0.68:22) to [email protected](10.0.0.58:22)..
Sat Oct 17 11:03:39 2020 - [debug]   ok.
Sat Oct 17 11:03:39 2020 - [debug]  Connecting via SSH from [email protected](10.0.0.68:22) to [email protected](10.0.0.48:22)..
Sat Oct 17 11:03:39 2020 - [debug]   ok.
Sat Oct 17 11:03:40 2020 - [debug] 
Sat Oct 17 11:03:38 2020 - [debug]  Connecting via SSH from [email protected](10.0.0.58:22) to [email protected](10.0.0.68:22)..
Warning: Permanently added '10.0.0.68' (ECDSA) to the list of known hosts.
Sat Oct 17 11:03:39 2020 - [debug]   ok.
Sat Oct 17 11:03:39 2020 - [debug]  Connecting via SSH from [email protected](10.0.0.58:22) to [email protected](10.0.0.48:22)..
Sat Oct 17 11:03:40 2020 - [debug]   ok.
Sat Oct 17 11:03:40 2020 - [debug] 
Sat Oct 17 11:03:39 2020 - [debug]  Connecting via SSH from [email protected](10.0.0.48:22) to [email protected](10.0.0.68:22)..
Warning: Permanently added '10.0.0.68' (ECDSA) to the list of known hosts.
Sat Oct 17 11:03:40 2020 - [debug]   ok.
Sat Oct 17 11:03:40 2020 - [debug]  Connecting via SSH from [email protected](10.0.0.48:22) to [email protected](10.0.0.58:22)..
Sat Oct 17 11:03:40 2020 - [debug]   ok.
Sat Oct 17 11:03:40 2020 - [info] All SSH connection tests passed successfully.
[root@MHA-manager ~]# masterha_check_repl --conf=/etc/mastermha/app1.cnf
Sat Oct 17 11:44:20 2020 - [warning] Global configuration file /etc/masterha_default.cnf not found. Skipping.
Sat Oct 17 11:44:20 2020 - [info] Reading application default configuration from /etc/mastermha/app1.cnf..
Sat Oct 17 11:44:20 2020 - [info] Reading server configuration from /etc/mastermha/app1.cnf..
Sat Oct 17 11:44:20 2020 - [info] MHA::MasterMonitor version 0.58.
Sat Oct 17 11:44:21 2020 - [info] GTID failover mode = 0
Sat Oct 17 11:44:21 2020 - [info] Dead Servers:
Sat Oct 17 11:44:21 2020 - [info] Alive Servers:
Sat Oct 17 11:44:21 2020 - [info]   10.0.0.68(10.0.0.68:3306)
Sat Oct 17 11:44:21 2020 - [info]   10.0.0.58(10.0.0.58:3306)
Sat Oct 17 11:44:21 2020 - [info]   10.0.0.48(10.0.0.48:3306)
Sat Oct 17 11:44:21 2020 - [info] Alive Slaves:
Sat Oct 17 11:44:21 2020 - [info]   10.0.0.58(10.0.0.58:3306)  Version=5.7.29-log (oldest major version between slaves) log-bin:enabled
Sat Oct 17 11:44:21 2020 - [info]     Replicating from 10.0.0.68(10.0.0.68:3306)
Sat Oct 17 11:44:21 2020 - [info]     Primary candidate for the new Master (candidate_master is set)
Sat Oct 17 11:44:21 2020 - [info]   10.0.0.48(10.0.0.48:3306)  Version=5.7.29-log (oldest major version between slaves) log-bin:enabled
Sat Oct 17 11:44:21 2020 - [info]     Replicating from 10.0.0.68(10.0.0.68:3306)
Sat Oct 17 11:44:21 2020 - [info] Current Alive Master: 10.0.0.68(10.0.0.68:3306)
Sat Oct 17 11:44:21 2020 - [info] Checking slave configurations..
Sat Oct 17 11:44:21 2020 - [info] Checking replication filtering settings..
Sat Oct 17 11:44:21 2020 - [info]  binlog_do_db= , binlog_ignore_db= 
Sat Oct 17 11:44:21 2020 - [info]  Replication filtering check ok.
Sat Oct 17 11:44:21 2020 - [info] GTID (with auto-pos) is not supported
Sat Oct 17 11:44:21 2020 - [info] Starting SSH connection tests..
Sat Oct 17 11:44:24 2020 - [info] All SSH connection tests passed successfully.
Sat Oct 17 11:44:24 2020 - [info] Checking MHA Node version..
Sat Oct 17 11:44:25 2020 - [info]  Version check ok.
Sat Oct 17 11:44:25 2020 - [info] Checking SSH publickey authentication settings on the current master..
Sat Oct 17 11:44:25 2020 - [info] HealthCheck: SSH to 10.0.0.68 is reachable.
Sat Oct 17 11:44:26 2020 - [info] Master MHA Node version is 0.58.
Sat Oct 17 11:44:26 2020 - [info] Checking recovery script configurations on 10.0.0.68(10.0.0.68:3306)..
Sat Oct 17 11:44:26 2020 - [info]   Executing command: save_binary_logs --command=test --start_pos=4 --binlog_dir=/data/mysql/ --output_file=/data/mastermha/app1//save_binary_logs_test --manager_version=0.58 --start_file=mysql-bin.000001 
Sat Oct 17 11:44:26 2020 - [info]   Connecting to [email protected](10.0.0.68:22).. 
  Creating /data/mastermha/app1 if not exists.. Creating directory /data/mastermha/app1.. done.
   ok.
  Checking output directory is accessible or not..
   ok.
  Binlog found at /data/mysql/, up to mysql-bin.000001
Sat Oct 17 11:44:26 2020 - [info] Binlog setting check done.
Sat Oct 17 11:44:26 2020 - [info] Checking SSH publickey authentication and checking recovery script configurations on all alive slave servers..
Sat Oct 17 11:44:26 2020 - [info]   Executing command : apply_diff_relay_logs --command=test --slave_user='mhauser' --slave_host=10.0.0.58 --slave_ip=10.0.0.58 --slave_port=3306 --workdir=/data/mastermha/app1/ --target_version=5.7.29-log --manager_version=0.58 --relay_log_info=/data/mysql/relay-log.info  --relay_dir=/data/mysql/  --slave_pass=xxx
Sat Oct 17 11:44:26 2020 - [info]   Connecting to [email protected](10.0.0.58:22).. 
Creating directory /data/mastermha/app1/.. done.
  Checking slave recovery environment settings..
    Opening /data/mysql/relay-log.info ... ok.
    Relay log found at /data/mysql, up to slave1-relay-bin.000002
    Temporary relay log file is /data/mysql/slave1-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.
Sat Oct 17 11:44:27 2020 - [info]   Executing command : apply_diff_relay_logs --command=test --slave_user='mhauser' --slave_host=10.0.0.48 --slave_ip=10.0.0.48 --slave_port=3306 --workdir=/data/mastermha/app1/ --target_version=5.7.29-log --manager_version=0.58 --relay_log_info=/data/mysql/relay-log.info  --relay_dir=/data/mysql/  --slave_pass=xxx
Sat Oct 17 11:44:27 2020 - [info]   Connecting to [email protected](10.0.0.48:22).. 
Creating directory /data/mastermha/app1/.. done.
  Checking slave recovery environment settings..
    Opening /data/mysql/relay-log.info ... ok.
    Relay log found at /data/mysql, up to slave2-relay-bin.000002
    Temporary relay log file is /data/mysql/slave2-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.
Sat Oct 17 11:44:27 2020 - [info] Slaves settings check done.
Sat Oct 17 11:44:27 2020 - [info] 
10.0.0.68(10.0.0.68:3306) (current master)
 +--10.0.0.58(10.0.0.58:3306)
 +--10.0.0.48(10.0.0.48:3306)

Sat Oct 17 11:44:27 2020 - [info] Checking replication health on 10.0.0.58..
Sat Oct 17 11:44:27 2020 - [info]  ok.
Sat Oct 17 11:44:27 2020 - [info] Checking replication health on 10.0.0.48..
Sat Oct 17 11:44:27 2020 - [info]  ok.
Sat Oct 17 11:44:27 2020 - [info] Checking master_ip_failover_script status:
Sat Oct 17 11:44:27 2020 - [info]   /usr/local/bin/master_ip_failover --command=status --ssh_user=root --orig_master_host=10.0.0.68 --orig_master_ip=10.0.0.68 --orig_master_port=3306 


IN SCRIPT TEST====/sbin/ifconfig eth0:1 down==/sbin/ifconfig eth0:1 10.0.0.100/24;/sbin/arping -I eth0 -c 3 -s 10.0.0.100/24 10.0.0.2 > /dev/null 2&>1===

Checking the Status of the script.. OK 
Sat Oct 17 11:44:28 2020 - [info]  OK.
Sat Oct 17 11:44:28 2020 - [warning] shutdown_script is not defined.
Sat Oct 17 11:44:28 2020 - [info] Got exit code 0 (Not master dead).

MySQL Replication Health is OK.

查看MHA状态

[root@MHA-manager ~]# masterha_check_status --conf=/etc/mastermha/app1.cnf
app1 is stopped(2:NOT_RUNNING).

(9)启动MHA

[root@MHA-manager ~]# nohup masterha_manager --conf=/etc/mastermha/app1.cnf &> /dev/null
[root@MHA-manager ~]# masterha_check_status --conf=/etc/mastermha/app1.cnf        #主服务器状态
app1 (pid:24874) is running(0:PING_OK), master:10.0.0.68

(10)模拟故障

[root@master ~]#systemctl stop mysqld.service      #停止主服务器
[root@MHA-manager ~]# nohup masterha_manager --conf=/etc/mastermha/app1.cnf &> /dev/null   #当主节点关闭后会自动退出mha








[root@MHA-manager ~]# 
[root@MHA-manager ~]# cat /data/mastermha/app1/manager.log     #查看日志看VIP漂移到哪个节点 新主节点为10.0.0.58
Sat Oct 17 12:38:44 2020 - [info]  Slave started.
Sat Oct 17 12:38:45 2020 - [info] End of log messages from 10.0.0.48.
Sat Oct 17 12:38:45 2020 - [info] -- Slave recovery on host 10.0.0.48(10.0.0.48:3306) succeeded.
Sat Oct 17 12:38:45 2020 - [info] All new slave servers recovered successfully.
Sat Oct 17 12:38:45 2020 - [info] 
Sat Oct 17 12:38:45 2020 - [info] * Phase 5: New master cleanup phase..
Sat Oct 17 12:38:45 2020 - [info] 
Sat Oct 17 12:38:45 2020 - [info] Resetting slave info on the new master..
Sat Oct 17 12:38:45 2020 - [info]  10.0.0.58: Resetting slave info succeeded.
Sat Oct 17 12:38:45 2020 - [info] Master failover to 10.0.0.58(10.0.0.58:3306) completed successfully.
Sat Oct 17 12:38:45 2020 - [info] 

----- Failover Report -----

app1: MySQL Master failover 10.0.0.68(10.0.0.68:3306) to 10.0.0.58(10.0.0.58:3306) succeeded

Master 10.0.0.68(10.0.0.68:3306) is down!

Check MHA Manager logs at MHA-manager:/data/mastermha/app1/manager.log for details.

Started automated(non-interactive) failover.
Invalidated master IP address on 10.0.0.68(10.0.0.68:3306)
The latest slave 10.0.0.58(10.0.0.58:3306) has all relay logs for recovery.
Selected 10.0.0.58(10.0.0.58:3306) as a new master.
10.0.0.58(10.0.0.58:3306): OK: Applying all logs succeeded.
10.0.0.58(10.0.0.58:3306): OK: Activated master IP address.
10.0.0.48(10.0.0.48:3306): This host has the latest relay log events.
Generating relay diff files from the latest slave succeeded.
10.0.0.48(10.0.0.48:3306): OK: Applying all logs succeeded. Slave started, replicating from 10.0.0.58(10.0.0.58:3306)
10.0.0.58(10.0.0.58:3306): Resetting slave info succeeded.
Master failover to 10.0.0.58(10.0.0.58:3306) completed successfully.
Sat Oct 17 12:38:45 2020 - [info] Sending mail..
#在10.0.0.58查看VIP已经漂移到本机
[root@slave1 ~]#ip a
1: lo:  mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0:  mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:02:7c:51 brd ff:ff:ff:ff:ff:ff
    inet 10.0.0.58/24 brd 10.0.0.255 scope global noprefixroute eth0
       valid_lft forever preferred_lft forever
    inet 10.0.0.100/24 brd 10.0.0.255 scope global secondary eth0:1
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fe02:7c51/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
#如果需要再次开启mha需要删除以下文件
[root@MHA-manager ~]# ls /data/mastermha/app1/app1.failover.complete 

收到邮件报警

博客作业第五周-mysql主从复制、高可用性、运维自动化ansible_第5张图片

4、mysql高可用性-Percona XtraDB Cluster(PXC 5.7)

(不支持centos8)

一、实验环境

pxc1:  10.0.0.27   centos7
pxc2:  10.0.0.37   centos7
pxc3:  10.0.0.47   centos7
pxc4:  10.0.0.57   centos7

二、实验步骤

(1)安装 Percona XtraDB Cluster 5.7

#配置清华大学yum源
[15:40:11 root@pxc1 ~]#cat /etc/yum.repos.d/pxc.repo 
[perconal]
name=percona_repo
baseurl = https://mirrors.tuna.tsinghua.edu.cn/percona/release/$releasever/RPMS/$basearch
enabled = 1
gpgcheck = 0
#将yum源拷贝到其他两个节点
[15:43:37 root@pxc1 ~]#scp /etc/yum.repos.d/pxc.repo 10.0.0.37:/etc/yum.repos.d/
[15:43:37 root@pxc1 ~]#scp /etc/yum.repos.d/pxc.repo 10.0.0.47:/etc/yum.repos.d/
#在三个节点都安装PXC 5.7
[15:43:37 root@pxc1 ~]#yum install Percona-XtraDB-Cluster-57 -y
[15:28:39 root@pxc2 ~]#yum install Percona-XtraDB-Cluster-57 -y
[root@pxc3 ~]# yum install Percona-XtraDB-Cluster-57 -y

(2)在各个节点上分别配置mysql及集群配置文件

/etc/my.cnf为主配置文件,当前版本中,其余的配置文件都放在/etc/percona-xtradb-cluster.conf.d目录里,包括mysqld.cnf,mysqld_safe.cnf,wsrep.cnf 三个文件

#修改PXC的配置文件
[16:11:47 root@pxc1 ~]#cat /etc/percona-xtradb-cluster.conf.d/wsrep.cnf
[mysqld]
# Path to Galera library
wsrep_provider=/usr/lib64/galera3/libgalera_smm.so

# Cluster connection URL contains IPs of nodes
#If no IP is found, this implies that a new cluster needs to be created,
#in order to do that you need to bootstrap this node
wsrep_cluster_address=gcomm://10.0.0.27,10.0.0.37,10.0.0.47          #三个节点的IP

# In order for Galera to work correctly binlog format should be ROW
binlog_format=ROW

# MyISAM storage engine has only experimental support
default_storage_engine=InnoDB

# Slave thread to use
wsrep_slave_threads= 8

wsrep_log_conflicts

# This changes how InnoDB autoincrement locks are managed and is a requirement for Galera
innodb_autoinc_lock_mode=2

# Node IP address
#wsrep_node_address=192.168.70.63
wsrep_node_address=10.0.0.27                                       #各个节点,指定自已的IP
# Cluster name
wsrep_cluster_name=pxc-magedu-cluster

#If wsrep_node_name is not specified,  then system hostname will be used
wsrep_node_name=pxc-cluster-node-1                                  #各个节点,指定自已节点名称

#pxc_strict_mode allowed values: DISABLED,PERMISSIVE,ENFORCING,MASTER
pxc_strict_mode=ENFORCING

# SST method
wsrep_sst_method=xtrabackup-v2

#Authentication for SST method
wsrep_sst_auth="gjz:123456"                                        #取消注释或者改为自己的密码

[16:09:38 root@pxc2 ~]#cat /etc/percona-xtradb-cluster.conf.d/wsrep.cnf
[mysqld]
# Path to Galera library
wsrep_provider=/usr/lib64/galera3/libgalera_smm.so

# Cluster connection URL contains IPs of nodes
#If no IP is found, this implies that a new cluster needs to be created,
#in order to do that you need to bootstrap this node
wsrep_cluster_address=gcomm://10.0.0.27,10.0.0.37,10.0.0.47

# In order for Galera to work correctly binlog format should be ROW
binlog_format=ROW

# MyISAM storage engine has only experimental support
default_storage_engine=InnoDB

# Slave thread to use
wsrep_slave_threads= 8

wsrep_log_conflicts

# This changes how InnoDB autoincrement locks are managed and is a requirement for Galera
innodb_autoinc_lock_mode=2

# Node IP address
#wsrep_node_address=192.168.70.63
wsrep_node_address=10.0.0.37
# Cluster name
wsrep_cluster_name=pxc-magedu-cluster

#If wsrep_node_name is not specified,  then system hostname will be used
wsrep_node_name=pxc-cluster-node-2

#pxc_strict_mode allowed values: DISABLED,PERMISSIVE,ENFORCING,MASTER
pxc_strict_mode=ENFORCING

# SST method
wsrep_sst_method=xtrabackup-v2

#Authentication for SST method
wsrep_sst_auth="gjz:123456"
[root@pxc3 ~]# cat /etc/percona-xtradb-cluster.conf.d/wsrep.cnf
[mysqld]
# Path to Galera library
wsrep_provider=/usr/lib64/galera3/libgalera_smm.so

# Cluster connection URL contains IPs of nodes
#If no IP is found, this implies that a new cluster needs to be created,
#in order to do that you need to bootstrap this node
wsrep_cluster_address=gcomm://10.0.0.27,10.0.0.37,10.0.0.47

# In order for Galera to work correctly binlog format should be ROW
binlog_format=ROW

# MyISAM storage engine has only experimental support
default_storage_engine=InnoDB

# Slave thread to use
wsrep_slave_threads= 8

wsrep_log_conflicts

# This changes how InnoDB autoincrement locks are managed and is a requirement for Galera
innodb_autoinc_lock_mode=2

# Node IP address
#wsrep_node_address=192.168.70.63
wsrep_node_address=10.0.0.47
# Cluster name
wsrep_cluster_name=pxc-magedu-cluster

#If wsrep_node_name is not specified,  then system hostname will be used
wsrep_node_name=pxc-cluster-node-3

#pxc_strict_mode allowed values: DISABLED,PERMISSIVE,ENFORCING,MASTER
pxc_strict_mode=ENFORCING

# SST method
wsrep_sst_method=xtrabackup-v2

#Authentication for SST method
wsrep_sst_auth="gjz:123456"

(3)启动第一个节点

[root@pxc3 ~]# systemctl start [email protected]
#查看root密码
[root@pxc3 ~]# grep "temporary password" /var/log/mysqld.log
2020-10-17T08:22:46.574773Z 1 [Note] A temporary password is generated for root@localhost: +?tLc;9/f7Pf
[root@pxc3 ~]# mysql -p'+?tLc;9/f7Pf'
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 12
Server version: 5.7.31-34-57-log

Copyright (c) 2009-2020 Percona LLC and/or its affiliates
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 
#修改root密码
mysql> alter user 'root'@'localhost' identified by 'magedu'
    -> ;
Query OK, 0 rows affected (0.00 sec)
#创建相关用户并授权
mysql> CREATE USER 'gjz'@'localhost' IDENTIFIED BY '123456';
Query OK, 0 rows affected (0.00 sec)

mysql> GRANT RELOAD, LOCK TABLES, PROCESS, REPLICATION CLIENT ON *.* TO 'gjz'@'localhost';
Query OK, 0 rows affected (0.00 sec)

(4)启动其他节点

[root@pxc1 ~]# systemctl start mysql
[16:15:27 root@pxc2 ~]#systemctl start mysql

(5)查看集群状态,验证集群是否成功

#在任意节点,查看集群状态,只要在第一个节点更改数据库root密码其他节点均可同步
[16:51:13 root@pxc2 ~]#mysql -uroot -pmagedu
mysql> show variables like 'wsrep_node_name';
+-----------------+--------------------+
| Variable_name   | Value              |
+-----------------+--------------------+
| wsrep_node_name | pxc-cluster-node-2 |
+-----------------+--------------------+
1 row in set (0.00 sec)
mysql> show variables like 'wsrep_node_address';
+--------------------+-----------+
| Variable_name      | Value     |
+--------------------+-----------+
| wsrep_node_address | 10.0.0.37 |
+--------------------+-----------+
1 row in set (0.00 sec)
#在任意节点查看数据库
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)
#在任意节点创建数据库
#节点2创建数据库
mysql> create database testdb1;
Query OK, 1 row affected (0.00 sec)
#节点1查询
[root@pxc1 ~]# mysql -uroot -pmagedu
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 5.7.31-34-57-log Percona XtraDB Cluster (GPL), Release rel34, Revision 7359e4f, WSREP version 31.45, wsrep_31.45

Copyright (c) 2009-2020 Percona LLC and/or its affiliates
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| testdb1            |
+--------------------+
5 rows in set (0.00 sec)
#同时在三个节点创建数据库只有一个成功,无需担心复制冲突

(6)pxc集群加入新节点

#在PXC集群中再加一台新的主机PXC4:10.0.0.57
[17:25:11 root@pxc4 ~]#yum install Percona-XtraDB-Cluster-57 -y
[17:30:45 root@pxc4 ~]#cat /etc/percona-xtradb-cluster.conf.d/wsrep.cnf
[mysqld]
# Path to Galera library
wsrep_provider=/usr/lib64/galera3/libgalera_smm.so

# Cluster connection URL contains IPs of nodes
#If no IP is found, this implies that a new cluster needs to be created,
#in order to do that you need to bootstrap this node
wsrep_cluster_address=gcomm://10.0.0.27,10.0.0.37,10.0.0.47,10.0.0.57

# In order for Galera to work correctly binlog format should be ROW
binlog_format=ROW

# MyISAM storage engine has only experimental support
default_storage_engine=InnoDB

# Slave thread to use
wsrep_slave_threads= 8

wsrep_log_conflicts

# This changes how InnoDB autoincrement locks are managed and is a requirement for Galera
innodb_autoinc_lock_mode=2

# Node IP address
#wsrep_node_address=192.168.70.63
wsrep_node_address=10.0.0.57
# Cluster name
wsrep_cluster_name=pxc-magedu-cluster

#If wsrep_node_name is not specified,  then system hostname will be used
wsrep_node_name=pxc-cluster-node-4

#pxc_strict_mode allowed values: DISABLED,PERMISSIVE,ENFORCING,MASTER
pxc_strict_mode=ENFORCING

# SST method
wsrep_sst_method=xtrabackup-v2

#Authentication for SST method
wsrep_sst_auth="gjz:123456"
启动服务
[17:30:54 root@pxc4 ~]#systemctl start mysql
[17:32:08 root@pxc4 ~]#mysql -uroot -pmagedu
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 5.7.31-34-57-log Percona XtraDB Cluster (GPL), Release rel34, Revision 7359e4f, WSREP version 31.45, wsrep_31.45

Copyright (c) 2009-2020 Percona LLC and/or its affiliates
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> SHOW STATUS LIKE 'wsrep_cluster_size';
+--------------------+-------+
| Variable_name      | Value |
+--------------------+-------+
| wsrep_cluster_size | 4     |
+--------------------+-------+
1 row in set (0.01 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| testdb1            |
+--------------------+
5 rows in set (0.00 sec)

(7)在pxc集群中修复故障节点

#在任意节点停止服务
[17:43:45 root@pxc4 ~]#systemctl stop mysql.service 
#在其它任意节点查看wsrep_cluster_size变量少了一个节点
mysql> SHOW STATUS LIKE 'wsrep_cluster_size';
+--------------------+-------+
| Variable_name      | Value |
+--------------------+-------+
| wsrep_cluster_size | 3     |
+--------------------+-------+
1 row in set (0.01 sec)
mysql> create database testdb2;
Query OK, 1 row affected (0.01 sec)
#在其它任意节点可看到数据已同步
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| testdb1            |
| testdb2            |
+--------------------+
6 rows in set (0.00 sec)
#将停止的节点启动,发现数据已经同步
[17:48:45 root@pxc4 ~]#systemctl start mysql
[17:48:45 root@pxc4 ~]#mysql -uroot -pmagedu
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 12
Server version: 5.7.31-34-57-log Percona XtraDB Cluster (GPL), Release rel34, Revision 7359e4f, WSREP version 31.45, wsrep_31.45

Copyright (c) 2009-2020 Percona LLC and/or its affiliates
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| testdb1            |
| testdb2            |
+--------------------+
6 rows in set (0.00 sec)

mysql> 

5、通过 ansible 部署二进制 mysql 8

实验环境:
10.0.0.68  ansible主机
10.0.0.58
10.0.0.48

ansible管理首先要基于key验证,可通过以下脚本实现

#!/bin/bash

IPLIST="
10.0.0.68
10.0.0.58
10.0.0.48"

rpm -q sshpass &> /dev/null || yum -y install sshpass
[-f /root/.ssh/id_rsa] || ssh-keygen -f /root/.ssh/id_rsa -P ''
export SSHPASS=123456
for IP in $IPLIST;do
        sshpass -e ssh-copy-id $IP
done
[15:11:32 root@localhost ~]#vi mysql8.0-install.yml 

---
- hosts: mysql                                                                                                                                                                                                                                    
  remote_user: root
  gather_facts: no

  tasks:
    - name: add group mysql
      group: name=mysql state=present
    - name: add user mysql
      user: name=mysql state=present group=mysql
    - name: Install packeges
      yum: name=libaio,numactl-libs,libaio,ncurses-compat-libs
    - name: decompression
      unarchive: src=/root/mysql-8.0.21-linux-glibc2.12-x86_64.tar.xz dest=/usr/local
    - name: create symbolic link
      file: src=/usr/local/mysql-8.0.21-linux-glibc2.12-x86_64 dest=/usr/local/mysql state=link
    - name: modify path
      shell: echo 'PATH=/usr/local/mysql/bin/:$PATH' > /etc/profile.d/mysql.sh
    - name: modify path
      shell: source /etc/profile.d/mysql.sh
    - name: create my.cnf
      shell: echo -e '[mysqld]\nserver-id=1\nlog-bin\ndatadir=/data/mysql\nsocket=/data/mysql/mysql.sock\nlog-error=/data/mysql/mysql.log\npid-file=/data/mysql/mysql.pid\n[client]\nsocket=/data/mysql/mysql.sock'> /etc/my.cnf
    - name: install mysql
      shell: mysqld --initialize-insecure --user=mysql --datadir=/data/mysql
    - name: creat mysqld
      shell: cp /usr/local/mysql/support-files/mysql.server  /etc/init.d/mysqld
    - name: set auto run
      shell: chkconfig --add mysqld
    - name: start mysql
      service: name=mysqld state=started
    - name: modify password
      shell: mysql -e "alter user root@localhost identified by '123456'"

你可能感兴趣的:(linux运维,数据库,运维,linux,mysql,centos)