【GCP】MySQLのリードレプリカ（Master-Slave)構成の構築。

__前提__

* GCPのCompute Engine(Ubuntu)にMySQLをインストールした。
* MySQL 8.0


# 登場するインスタンス

```
mysql1 10.146.0.18
mysql2 10.146.0.20
```

# 手順
## Step 1: Configure the Master Server

```
$ sudo vim /etc/mysql/mysql.conf.d/mysqld.cnf
```

`/etc/mysql/mysql.conf.d/mysqld.cnf`には下記の値が記載されるようにします。

```/etc/mysql/mysql.conf.d/mysqld.cnf
log_bin = /var/log/mysql/mysql-bin.log
log_bin_index =/var/log/mysql/mysql-bin.log.index
relay_log = /var/log/mysql/mysql-relay-bin
relay_log_index = /var/log/mysql/mysql-relay-bin.index

server-id = 1
tmpdir = /tmp
binlog_format = ROW
max_binlog_size = 500M
sync_binlog = 1
expire-logs-days = 7
slow_query_log
```


## Step 2: Create Replication user on Replica database server

レプリカサーバーからリードサーバーに接続できるようにするためユーザーを作成します。

rootユーザーとして下記を実行します。

```
create user rpl_user@10.146.0.20 identified by 'password';
```


```
# mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.21-0ubuntu0.20.04.4 (Ubuntu)

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> create user rpl_user@10.146.0.20 identified with mysql_native_password by 'password';
Query OK, 0 rows affected (0.01 sec)
```


`caching_sha2_password`プラグインではなく`mysql_native_password`プラグインを指定しています。

```
mysql> grant replication slave on *.* to rpl_user@10.146.0.20;
Query OK, 0 rows affected (0.01 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
```


```
mysql> show grants for rpl_user@10.146.0.20;
+------------------------------------------------------------+
| Grants for rpl_user@10.146.0.20                            |
+------------------------------------------------------------+
| GRANT REPLICATION SLAVE ON *.* TO `rpl_user`@`10.146.0.20` |
+------------------------------------------------------------+
1 row in set (0.00 sec)
```


## Step 3: Install and Configure Slave Server

```
$ sudo vim /etc/mysql/mysql.conf.d/mysqld.cnf
```

`/etc/mysql/mysql.conf.d/mysqld.cnf`には下記の値が記載されるようにします。

```/etc/mysql/mysql.conf.d/mysqld.cnf
log_bin = /var/log/mysql/mysql-bin.log
log_bin_index =/var/log/mysql/mysql-bin.log.index
relay_log = /var/log/mysql/mysql-relay-bin
relay_log_index = /var/log/mysql/mysql-relay-bin.index

server-id = 2
read_only = 1
tmpdir = /tmp
binlog_format = ROW
max_binlog_size = 500M
sync_binlog = 1
expire-logs-days = 7
slow_query_log   = 1
```


```
$ sudo systemctl restart mysql
```

## Step 4: Initialize Replication process

レプリカサーバーの方で下記のmysqlを実行します。

```
mysql> show master status\G
*************************** 1. row ***************************
File: mysql-bin.000003
Position: 156
Binlog_Do_DB:
Binlog_Ignore_DB:
Executed_Gtid_Set:
1 row in set (0.00 sec)
```

レプリカサーバーで下記のクエリを実行します。

```
CHANGE MASTER TO MASTER_HOST='10.146.0.18',
MASTER_USER='rpl_user',
MASTER_PASSWORD='password',
MASTER_LOG_FILE='mysql-bin.000003',
MASTER_LOG_POS=156;
```

__作業ログ__

```
# mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 8.0.21-0ubuntu0.20.04.4 (Ubuntu)

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>

mysql> CHANGE MASTER TO MASTER_HOST='10.146.0.18',
    -> MASTER_USER='rpl_user',
    -> MASTER_PASSWORD='password',
    -> MASTER_LOG_FILE='mysql-bin.000002',
    -> MASTER_LOG_POS=156;
Query OK, 0 rows affected, 2 warnings (0.05 sec)

```


```
mysql> start slave;
Query OK, 0 rows affected (0.00 sec)
```


レプリカのステータスを確認します。

```
mysql> show slave status\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 10.146.0.18
                  Master_User: rpl_user
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000003
          Read_Master_Log_Pos: 156
               Relay_Log_File: mysql-relay-bin.000003
                Relay_Log_Pos: 371
        Relay_Master_Log_File: mysql-bin.000003
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              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: 156
              Relay_Log_Space: 580
              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: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error:
               Last_SQL_Errno: 0
               Last_SQL_Error:
  Replicate_Ignore_Server_Ids:
             Master_Server_Id: 1
                  Master_UUID: 1cbeabec-f0cc-11ea-b096-42010a920012
             Master_Info_File: mysql.slave_master_info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind:
      Last_IO_Error_Timestamp:
     Last_SQL_Error_Timestamp:
               Master_SSL_Crl:
           Master_SSL_Crlpath:
           Retrieved_Gtid_Set:
            Executed_Gtid_Set:
                Auto_Position: 0
         Replicate_Rewrite_DB:
                 Channel_Name:
           Master_TLS_Version:
       Master_public_key_path:
        Get_master_public_key: 0
            Network_Namespace:
1 row in set (0.00 sec)

```

## step 5. Check

`replication_db`をリードDBで作成し、レプリカDBで確認をしてみる。

```mysql-1(LEAD)

root@mysql-1:/home/kuraya# mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 8.0.21-0ubuntu0.20.04.4 (Ubuntu)

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>
mysql> CREATE DATABASE replication_db;
Query OK, 1 row affected (0.01 sec)

```

```mysql-2(REPRICA)

root@mysql-2:/home/kuraya# sudo mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 12
Server version: 8.0.21-0ubuntu0.20.04.4 (Ubuntu)

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   |
| replication_db       |
| sys                  |
| to*****bo_production |
+----------------------+
6 rows in set (0.01 sec)

```

リードで作成したDBである`replication_db`がレプリカでも確認することができました。

（この`replication_db`はリードDBで削除しておきます。）

参考：
https://www.tecmint.com/setup-mysql-master-slave-replication-on-ubuntu/