# 演習 10: TiDB データ移行を利用したデータ移行

## 概要

この演習では、`TiDB Data Migration` ツールを使用してデータを移行します。以下はTiDBクラスタのデプロイメントトポロジー図です。

   ![60%](https://lab-static.pingcap.com/quick-demo/TiDBClusterDeploymentTopologyExercisewithDataMigration_aa_005_20230301.png)

+ `TiDB Data Migration`は、上流のMySQLインスタンスから下流のTiDBインスタンスへの完全なデータ移行と差分データレプリケーションをサポートするために使用されます。以下は`TiDB Data Migration`クラスタのトポロジー図を示しています。

   ![60%](https://lab-static.pingcap.com/quick-demo/DMLabToplogy_aa_005_20220626.png)


> [!TIP]
> 演習環境を起動するには、**開始**をクリックしてください。
> 環境の準備が整ったら、下部のツールバーで **次のモジュール** を選択して **モジュール 1** に進みます。
> そして、ステップバイステップの演習ガイドに従って、ハンズオン環境に接続し、タスクを開始してください。

## モジュール 1: TiDB データマイグレーションクラスタのデプロイ

### 手順 1. 仮想マシンへのログイン

+ ここをクリック - [ターミナル 1](ssh://monitor1-ssh#1) で、ハンズオン演習用に割り当てられた仮想マシンに接続された新しいターミナルを開きます。

+ ログイン後に表示されるバナー：

    ```output
     ,     #_
    ~\_  ####_        Amazon Linux 2
    ~~  \_#####\
    ~~     \###|      
    ~~       \#/ ___
    ~~       V~' '->
    ~~~         /    A newer version of Amazon Linux is available!
     ~~._.   _/
        _/ _/       Amazon Linux 2023, GA and supported until 2028-03-15.
      _/m/'           https://aws.amazon.com/linux/amazon-linux-2023/
    ```


### 手順 2. TiDB Data Migration をインストール

  ```bash
  tiup install dm dmctl:v7.5.1
  ```

### 手順 3. ファイル `solution-dm-topology-six-nodes.yaml` を読み込む

  ```bash
  cat solution-dm-topology-six-nodes.yaml
  ```
  ```output
  # The topology template is used deploy a minimal DM cluster, which suitable
  # for scenarios with only three machines. The minimal cluster contains
  # - 3 master nodes
  # - 3 worker nodes
  # You can change the hosts according your environment
  ---
  global:
     user: "tidb"
     ssh_port: 22
     deploy_dir: "/tidb-deploy"
     data_dir: "/tidb-data"
     arch: "amd64"

  master_servers:
     - host: 10.90.2.84
     - host: 10.90.2.134
     - host: 10.90.2.214

  worker_servers:
     - host: 10.90.3.239
     - host: 10.90.3.119
     - host: 10.90.3.181

  monitoring_servers:
     - host: 10.90.2.84

  grafana_servers:
     - host: 10.90.2.84

  alertmanager_servers:
     - host: 10.90.2.84
  ``` 

### 手順 4. TiDB Data Migration がインストールされているか確認する

  ```bash
  tiup list dm-master
  ```
  ```output
  Available versions for dm-master:
  Version                                   Installed  Release                    Platforms
  -------                                   ---------  -------                    ---------
  v7.5.1                                               2022-06-10T14:27:38+08:00  linux/amd64,linux/arm64
  ...
  ```

### 手順 5. TiDB Data Migration クラスタをデプロイする

  ```bash
  tiup dm deploy dm-test v7.5.1 --user ec2-user -i ~/.ssh/pe-class-key-oregon.pem ./solution-dm-topology-six-nodes.yaml --yes
  ```
  ```output
  ...
  Cluster `dm-test` deployed successfully, you can start it with command: `tiup dm start dm-test`     
  ```

### 手順 6. TiDB Data Migration クラスタを開始する

  ```bash
  tiup dm start dm-test
  ```
  ```output
  ...
  Started cluster `dm-test` successfully
  ```

### 手順 7. TiUP で管理されている TiDB Data Migration クラスタを確認する

  ```bash
  tiup dm list
  ```
  ```output
  tiup is checking updates for component dm ...
  Starting component `dm`: /home/ec2-user/.tiup/components/dm/v1.12.1/tiup-dm list
  Name     User  Version  Path                                              PrivateKey
  ----     ----  -------  ----                                              ----------
  dm-test  tidb  v7.5.1   /home/ec2-user/.tiup/storage/dm/clusters/dm-test  /home/ec2-user/.tiup/storage/dm/clusters/dm-test/ssh/id_rsa
  ```

### 手順 8. デプロイされた TiDB Data Migration クラスタのステータスを確認する

  ```bash
  tiup dm display dm-test
  ```
  ```output
  tiup is checking updates for component dm ...
  Starting component `dm`: /home/ec2-user/.tiup/components/dm/v1.12.1/tiup-dm display dm-test
  Cluster type:       dm
  Cluster name:       dm-test
  Cluster version:    v7.5.1
  Deploy user:        tidb
  SSH type:           builtin
  Grafana URL:        http://10.90.4.231:3000
  ID                Role          Host         Ports      OS/Arch       Status     Data Dir                      Deploy Dir
  --                ----          ----         -----      -------       ------     --------                      ----------
  10.90.4.231:9093  alertmanager  10.90.4.231  9093/9094  linux/x86_64  Up         /tidb-data/alertmanager-9093  /tidb-deploy/alertmanager-9093
  10.90.1.34:8261   dm-master     10.90.1.34   8261/8291  linux/x86_64  Healthy|L  /tidb-data/dm-master-8261     /tidb-deploy/dm-master-8261
  10.90.2.38:8261   dm-master     10.90.2.38   8261/8291  linux/x86_64  Healthy    /tidb-data/dm-master-8261     /tidb-deploy/dm-master-8261
  10.90.3.188:8261  dm-master     10.90.3.188  8261/8291  linux/x86_64  Healthy    /tidb-data/dm-master-8261     /tidb-deploy/dm-master-8261
  10.90.1.162:8262  dm-worker     10.90.1.162  8262       linux/x86_64  Free       /tidb-data/dm-worker-8262     /tidb-deploy/dm-worker-8262
  10.90.2.108:8262  dm-worker     10.90.2.108  8262       linux/x86_64  Free       /tidb-data/dm-worker-8262     /tidb-deploy/dm-worker-8262
  10.90.3.12:8262   dm-worker     10.90.3.12   8262       linux/x86_64  Free       /tidb-data/dm-worker-8262     /tidb-deploy/dm-worker-8262
  10.90.4.231:3000  grafana       10.90.4.231  3000       linux/x86_64  Up         -                             /tidb-deploy/grafana-3000
  10.90.4.231:9090  prometheus    10.90.4.231  9090       linux/x86_64  Up         /tidb-data/prometheus-9090    /tidb-deploy/prometheus-9090
  Total nodes: 9
  ```

## モジュール 2: 二つの MySQL インスタンスからのデータ移行 (スキーマ準備)

### 手順 1. PD1 でのソース MySQL インスタンスのセットアップ

+ PD1にユーザーec2-userとしてログインしてください。表示されるメッセージはここに示されているものとは少し異なる場合があります。プロンプトが表示されたら、`yes`と答えてください。
  
  ```bash
  ./ssh-to-pd1.sh
  ```
  ```output
     ,     #_
     ~\_  ####_        Amazon Linux 2
     ~~  \_#####\
     ~~     \###|       
     ~~       \#/ ___
     ~~       V~' '->
        ~~~         /    A newer version of Amazon Linux is available!
        ~~._.   _/
           _/ _/       Amazon Linux 2023, GA and supported until 2028-03-15.
           _/m/'           https://aws.amazon.com/linux/amazon-linux-2023/
  ```

+ `PD1`でMySQLインスタンスを開始します。

  ```bash
  sudo service mysqld start
  ```
  ```output
  Redirecting to /bin/systemctl start mysqld.service
  ```

+ ユーザー `root@'localhost'` で `PD1` のMySQLサーバーに接続します。
  
  ```bash
  mysql -h localhost -P 3306 -uroot -pq1w2e3R4_
  ```
  ```output
  Enter password: 
  ...
  Server version: 5.7.41-log
  ... 
  mysql>
  ``` 

+ 新しいユーザー `dm_user@'%'` を作成し、そのユーザーに権限を付与します:
  
  ```sql
  CREATE USER dm_user@'%' identified by 'q1w2e3R4_';
  ```
  ```output
  mysql> CREATE USER dm_user@'%' identified by 'q1w2e3R4_';
  Query OK, 0 rows affected (0.00 sec)
  ```

  ```sql
  GRANT ALL PRIVILEGES ON *.* TO dm_user@'%';
  ```
  ```output
  mysql> GRANT ALL PRIVILEGES ON *.* TO dm_user@'%';
  Query OK, 0 rows affected (0.00 sec)
  ```

+ `show_compatibility_56` をオンにしてください。
  
  ```sql
  SET @@global.show_compatibility_56=ON;
  ```
  ```output
  mysql> SET @@global.show_compatibility_56=ON;
  Query OK, 0 rows affected (0.00 sec)
  ```

+ ターミナルに戻り、コントロールマシン(monitor1_address)に戻ります:
  
  ```sql
  EXIT
  ```
  ```output
  mysql> EXIT
  Bye
  ```
  ```bash
  exit
  ```
  ```output
  logout
  Connection to XX.XX.XX.XX closed.
  ```

### 手順 2. PD2 でのソース MySQL インスタンスのセットアップ

+ PD2にユーザーec2-userとしてログインしてください。表示されるメッセージはここに示されているものとは少し異なる場合があります。
  
  ```bash
  ./ssh-to-pd2.sh
  ```
  ```output
     ,     #_
     ~\_  ####_        Amazon Linux 2
     ~~  \_#####\
     ~~     \###|       
     ~~       \#/ ___
     ~~       V~' '->
        ~~~         /    A newer version of Amazon Linux is available!
        ~~._.   _/
           _/ _/       Amazon Linux 2023, GA and supported until 2028-03-15.
           _/m/'           https://aws.amazon.com/linux/amazon-linux-2023/
  ```

+ `PD2`でMySQLインスタンスを開始します。

  ```bash
  sudo service mysqld start
  ```
  ```output
  Redirecting to /bin/systemctl start mysqld.service
  ```

+ ユーザー `root@'localhost'` で `PD2` のMySQLサーバーに接続します。
  
  ```bash
  mysql -h localhost -P 3306 -uroot -pq1w2e3R4_
  ```
  ```output
  Enter password: 
  ...
  Server version: 5.7.41-log
  ... 
  mysql>
  ``` 

+ 新しいユーザー `dm_user@'%'` を作成し、そのユーザーに権限を付与します。
  
  ```sql
  CREATE USER dm_user@'%' identified by 'q1w2e3R4_';
  ```
  ```output
  mysql> CREATE USER dm_user@'%' identified by 'q1w2e3R4_';
  Query OK, 0 rows affected (0.00 sec)
  ```

  ```sql
  GRANT ALL PRIVILEGES ON *.* TO dm_user@'%';
  ```
  ```output
  mysql> GRANT ALL PRIVILEGES ON *.* TO dm_user@'%';
  Query OK, 0 rows affected (0.00 sec)
  ```

+ `show_compatibility_56` をオンにしてください。
  
  ```sql
  SET @@global.show_compatibility_56=ON;
  ```
  ```output
  mysql> SET @@global.show_compatibility_56=ON;
  Query OK, 0 rows affected (0.00 sec)
  ```

+ ターミナルに戻り、コントロールマシンに戻ります。
  
  ```sql
  EXIT
  ```
  ```output
  mysql> EXIT
  Bye
  ```
  ```bash
  exit
  ```
  ```output
  logout
  Connection to XX.XX.XX.XX closed.
  ```

### 手順 3. 二つの MySQL インスタンスにデータをインポートする

+ サンプルが解凍されていることを確認してください。
  
  ```bash
  unzip -u stage/tidb-admin-dataset-v2.zip -d stage/
  ```
   
+ `PD1`のMySQLに`user`、`store`、`log`、および`salesdb`データベースをインポートします。
  
  ```bash
  mysql -udm_user -pq1w2e3R4_ -h ${HOST_PD1_PRIVATE_IP} -P3306 < stage/TiDB-Administration-exercise-data-v2/exercise-dm/3306db.sql 
  ```

+ `PD2`のMySQLに`user`、`store`、`log`、および`salesdb`データベースをインポートします。
  
  ```bash
  mysql -udm_user -pq1w2e3R4_ -h ${HOST_PD2_PRIVATE_IP} -P3306 < stage/TiDB-Administration-exercise-data-v2/exercise-dm/3307db.sql 
  ```

### 手順 4. ターゲット TiDB クラスタースキーマの設定

+ TiDBに接続します：
  
  ```bash
  mysql -h ${HOST_DB1_PRIVATE_IP} -P 4000 -uroot
  ```
  ```output
  Welcome to the MySQL monitor.  Commands end with ; or \g.
  Your MySQL connection id is 405
  Server version: 5.7.25-TiDB-v7.5.1 TiDB Server (Apache License 2.0) Community Edition, MySQL 5.7 compatible
  ...
  mysql>
  ```

+ `dm_user`という新しいユーザーを作成し、そのユーザーに権限を付与します。
  
  ```sql
  CREATE USER dm_user@'%' identified by 'q1w2e3R4_';
  ```
  ```output
  mysql> CREATE USER dm_user@'%' identified by 'q1w2e3R4_';
  Query OK, 0 rows affected (0.04 sec)   
  ```

  ```sql
  GRANT ALL PRIVILEGES ON *.* TO dm_user@'%';
  ```
  ```output
  mysql> GRANT ALL PRIVILEGES ON *.* TO dm_user@'%';
  Query OK, 0 rows affected (0.02 sec)
  ```

+ TiDBに`user_north`というデータベースを作成し、`information`と`trace`というテーブルを作成します。`information`テーブルには`id`と呼ばれるプライマリキーの列と`VARCHAR(64)`型の`info`列が必要です。`trace`テーブルには`id`と呼ばれるプライマリキーの列と`VARCHAR(64)`型の`content`列が必要です。

  ```sql
  CREATE DATABASE user_north;
  CREATE TABLE user_north.information(id INT PRIMARY KEY, info VARCHAR(64));
  CREATE TABLE user_north.trace(id INT PRIMARY KEY, content VARCHAR(64));
  ```

  ```output
  mysql> CREATE DATABASE user_north;
  Query OK, 0 rows affected (0.08 sec)
  ...
  mysql> CREATE TABLE user_north.trace(id INT PRIMARY KEY, content VARCHAR(64));
  Query OK, 0 rows affected (0.09 sec)
  ```

+ TiDBに`user_east`というデータベースを作成し、`information`と`trace`というテーブルを作成します。`information`テーブルには`id`と呼ばれるプライマリキーの列と`VARCHAR(64)`型の`info`列が必要です。`trace`テーブルには`id`と呼ばれるプライマリキーの列と`VARCHAR(64)`型の`content`列が必要です。
  
  ```sql
  CREATE DATABASE user_east;
  CREATE TABLE user_east.information(id INT PRIMARY KEY, info VARCHAR(64));
  CREATE TABLE user_east.trace(id INT PRIMARY KEY, content VARCHAR(64));
  ```
  ```output
  mysql> CREATE DATABASE user_east;
  Query OK, 0 rows affected (0.08 sec)
  ...
  mysql> CREATE TABLE user_east.trace(id INT PRIMARY KEY, content VARCHAR(64));
  Query OK, 0 rows affected (0.09 sec)

+ TiDBに`store`というデータベースを作成し、`store_bj`、`store_tj`、`store_sh`、および`store_suzhou`というテーブルを作成します。`store_bj`テーブルには`id`と呼ばれるプライマリキーの列と`VARCHAR(64)`型の`pname`列が必要です。以下同様にします。
  
  ```sql
  CREATE DATABASE store;
  CREATE TABLE store.store_bj(id INT PRIMARY KEY, pname VARCHAR(64));
  CREATE TABLE store.store_tj(id INT PRIMARY KEY, pname VARCHAR(64));
  CREATE TABLE store.store_sh(id INT PRIMARY KEY, pname VARCHAR(64));
  CREATE TABLE store.store_suzhou(id INT PRIMARY KEY, pname VARCHAR(64));
  ```
  ```output
  mysql> CREATE DATABASE store;
  Query OK, 0 rows affected (0.09 sec)
  ...
  mysql> CREATE TABLE store.store_suzhou(id INT PRIMARY KEY, pname VARCHAR(64));
  Query OK, 0 rows affected (0.09 sec)
  ```

+ TiDBに`salesdb`というデータベースを作成し、`sales` というテーブルを作成します。`sales`テーブルには`id`と呼ばれるプライマリキーの列、`VARCHAR(20)`型の`pname`列、および`int`型の`cnt`列が必要です。
  
   ```sql
   CREATE DATABASE salesdb;
   CREATE TABLE salesdb.sales(id INT PRIMARY KEY, pname VARCHAR(20), cnt int);
   ```
   ```output
   mysql> CREATE DATABASE salesdb;
   Query OK, 0 rows affected (0.09 sec)
   mysql> CREATE TABLE sales.sales(id INT PRIMARY KEY, pname VARCHAR(20), cnt int);
   Query OK, 0 rows affected (0.09 sec)
   ```

+ TiDBに`log`というデータベースを作成し、`messages`というテーブルを作成します。`messages`テーブルには`id`と呼ばれるプライマリキーの列、および`VARCHAR(64)`型の`msg`列があります。それからセッションを終了します。
   ```bash
   CREATE DATABASE log;
   CREATE TABLE log.messages(id INT PRIMARY KEY, msg VARCHAR(64));
   ```
   ```output
   mysql> CREATE DATABASE log;
   Query OK, 0 rows affected (0.08 sec)
   mysql> CREATE TABLE log.messages(id INT PRIMARY KEY, msg VARCHAR(64));
   Query OK, 0 rows affected (0.08 sec)
   ```
    
   ```sql
   EXIT
   ```
   ```output
   mysql> EXIT
   Bye
   ```

## モジュール 3: 二つの MySQL インスタンスからのデータ移行 (TiDB Data Migration 設定)

### 手順 1. TiDB Data Migration ソース設定を作成する

+ `tiup dmctl:v7.5.1 --encrypt` 文を実行して、上流データベースMySQLのパスワードを暗号化します。暗号化されたパスワードを一時ファイルにコピーして保存してください。この後のステップで必要になります。

  ```bash
  tiup dmctl:v7.5.1 --encrypt 'q1w2e3R4_'
  ```
  ```output
  tiup is checking updates for component dmctl ...
  Starting component `dmctl`: /root/.tiup/components/dmctl/v7.5.1/dmctl/dmctl --encrypt mysql
  DMJtTSNCJbEoxUn1RVUZCUD9D3L4Fw==
  ```

+ テキストエディタを使って `mysql-source-conf1.yaml` ファイルをPD1上のMySQLインスタンス用に編集します。`mysql-source-conf1.yaml` ファイルを次のような設定に変更します（割り当てられた正しいIPアドレスで置き換えてください）。
  
  ```bash
  vi mysql-source-conf1.yaml
  ```
  ```bash
  source-id: "mysql-replica-01"
  from:
     host: "${HOST_PD1_PRIVATE_IP}"
     port: 3306
     user: "dm_user"
     password: "${encrypted_password_in_previous_step}"
  ```

+ テキストエディタを使って `mysql-source-conf2.yaml` ファイルをPD2上のMySQLインスタンス用に編集します。`mysql-source-conf2.yaml` ファイルを次のような設定に変更します（割り当てられた正しいIPアドレスで置き換えてください）。
  
  ```bash
  vi mysql-source-conf2.yaml
  ```
  ```bash
  source-id: "mysql-replica-02"
  from:
     host: "${HOST_PD2_PRIVATE_IP}"
     port: 3306
     user: "dm_user"
     password: "${encrypted_password_in_previous_step}"
  ```

+ `tiup dmctl:v7.5.1` 文を実行して、PD1上のMySQLインスタンス用の構成ファイルを上流データベースとしてロードします。
  
  ```bash
  tiup dmctl:v7.5.1 --master-addr=${HOST_PD1_PRIVATE_IP}:8261 operate-source create mysql-source-conf1.yaml
  ```
  ```output
  Starting component dmctl: /home/ec2-user/.tiup/components/dmctl/v7.5.1/dmctl/dmctl --master-addr=10.90.3.251:8261 operate-source create mysql-source-conf1.yaml
  {
        "result": true,
        "msg": "",
        "sources": [
           {
              "result": true,
              "msg": "",
              "source": "mysql-replica-01",
              "worker": "dm-10.90.3.231-8262"
           }
        ]
  }
  ```

+ `tiup dmctl:v7.5.1` 文を実行して、PD2上のMySQLインスタンス用の構成ファイルを上流データベースとしてロードします。
  
  ```bash
  tiup dmctl:v7.5.1 --master-addr=${HOST_PD1_PRIVATE_IP}:8261 operate-source create mysql-source-conf2.yaml
  ```
  ```output
  Starting component dmctl: /home/ec2-user/.tiup/components/dmctl/v7.5.1/dmctl/dmctl --master-addr=10.90.3.251:8261 operate-source create mysql-source-conf2.yaml
  {
        "result": true,
        ``msg": "",
        "sources": [
           {
              ``result": true,
              "msg": "",
              "source": "mysql-replica-02",
              "worker": "dm-10.90.3.7-8262"
           }
        ]
  }
  ```

+ ロードされた構成`mysql-replica-01`と`mysql-replica-02`の内容を表示します。
  
  ```bash
  tiup dmctl:v7.5.1 --master-addr=${HOST_PD1_PRIVATE_IP}:8261 get-config source mysql-replica-01
  ```
  ```output
  Starting component dmctl: /home/ec2-user/.tiup/components/dmctl/v7.5.1/dmctl/dmctl --master-addr=10.90.3.251:8261 get-config source mysql-replica-01
  {
     "result": true,
     "msg": "",
     "cfg": "enable: true\nenable-gtid: false\nauto-fix-gtid: false\nrelay-dir: relay-dir\nmeta-dir: \"\"\nflavor: mysql\ncharset: \"\"\nenable-relay: false\nrelay-binlog-name: \"\"\nrelay-binlog-gtid: \"\"\nsource-id: mysql-replica-01\nfrom:\n  host: 10.90.3.251\n  port: 3306\n  user: dm_user\n  password: '\u003_ENCODED'\n  max-allowed-packet: null\n  session: {}\n  security: null\npurge:\n  interval: 3600\n  expires: 0\n  remain-space: 15\nchecker:\n  check-enable: true\n  backoff-rollback: 5m0s\n  backoff-max: 5m0s\n  check-interval: 5s\n  backoff-min: 1s\n  backoff-jitter: true\n  backoff-factor: 2\nserver-id: 429532589\ntracer: {}\ncase-sensitive: false\nfilters: []\n"
  }
  ```
     
  ```bash
  tiup dmctl:v7.5.1 --master-addr=${HOST_PD1_PRIVATE_IP}:8261 get-config source mysql-replica-02
  ```
  ```output
  Starting component dmctl: /home/ec2-user/.tiup/components/dmctl/v7.5.1/dmctl/dmctl --master-addr=10.90.3.251:8261 get-config source mysql-replica-02
  {
     "result": true,
     "msg": "",
     "cfg": "enable: true\nenable-gtid: false\nauto-fix-gtid: false\nrelay-dir: relay-dir\nmeta-dir: \"\"\nflavor: mysql\ncharset: \"\"\nenable-relay: false\nrelay-binlog-name: \"\"\nrelay-binlog-gtid: \"\"\nsource-id: mysql-replica-02\nfrom:\n  host: 10.90.3.59\n  port: 3306\n  user: dm_user\n  password: '\u003_ENCODED'\n  max-allowed-packet: null\n  session: {}\n  security: null\npurge:\n  interval: 3600\n  expires: 0\n  remain-space: 15\nchecker:\n  check-enable: true\n  backoff-rollback: 5m0s\n  backoff-max: 5m0s\n  check-interval: 5s\n  backoff-min: 1s\n  backoff-jitter: true\n  backoff-factor: 2\nserver-id: 429553756\ntracer: {}\ncase-sensitive: false\nfilters: []\n"
  }
  ```  

+ 追加されたデータソースと対応する`DM-worker`を確認します。
  
  ```bash
  tiup dmctl:v7.5.1 --master-addr=${HOST_PD1_PRIVATE_IP}:8261 operate-source show
  ```
  ```output
  Starting component dmctl: /home/ec2-user/.tiup/components/dmctl/v7.5.1/dmctl/dmctl --master-addr=10.90.3.251:8261 operate-source show
  {
      "result": true,
      "msg": "",
      "sources": [
          {
              "result": true,
              "msg": "",
              "source": "mysql-replica-01",
              "worker": "dm-10.90.1.161-8262"
          },
          {
              "result": true,
              "msg": "",
              "source": "mysql-replica-02",
              "worker": "dm-10.90.1.139-8262"
          }
      ]
  }
  ``` 

### 手順 2. TiDB Data Migration タスク設定を作成する

+ `TiDB Data Migration` タスク設定ファイル `dm-task.yaml` を作成し、テキストエディタを使用して `dm-task.yaml` を編集します。`dm-task.yaml` ファイルは次のような設定を含む必要があります。二つの項目に注意を払い、yamlファイルの `${HOST_DB1_PRIVATE_IP}` と `${encrypted_password_in_previous_step}` をそれぞれTiDBサーバーのプライベートIPアドレスと前セクションの暗号化されたパスワードで置き換える必要があります。ソリューションyaml `solution-dm-task.yaml` も提供されていますが、`solution-dm-task.yaml`でも `${encrypted_password_in_previous_step}` を置き換える必要があります。
  
   ```bash
   vi dm-task.yaml
   ```

  ```bash
  name: "dm-task"  # The name of the task is dm-task. 
  task-mode: all    # The task mode is set to full (only migrates full data). 
  ignore-checking-items: ["auto_increment_ID"] # Ignorable checking auto_increment_ID.

  target-database:  # set the host, port, user and password of the downstream database TiDB.
   host: "${HOST_DB1_PRIVATE_IP}"
   port: 4000
   user: "dm_user"
   password: "${encrypted_password_in_previous_step}"

  mysql-instances:  # configure data sources that need to be migrated for the data migration task.
   - source-id: "mysql-replica-01"
     route-rules: ["instance-1-user-schema-rule","salesdb-schema-route-rule"]
     filter-rules: ["trace-table-filter-rule", "user-table-filter-rule" , "store-table-filter-rule"]
     block-allow-list: "log-ignored"
     mydumper-config-name: "global"
   - source-id: "mysql-replica-02"
     route-rules: ["instance-2-user-schema-rule", "instance-2-store-schema-rule","salesdb-schema-route-rule"]
     filter-rules: ["trace-table-filter-rule", "user-table-filter-rule" , "store-table-filter-rule"]
     block-allow-list: "log-ignored"
     mydumper-config-name: "global"

  routes:
  # Rule 1: Migrate all tables in the user database in upstream MySQL instance on PD1 to user_north database in the downstream TiDB instance. Migrate all tables in the `user` database in upstream MySQL instance on PD2 to user_east database in the downstream TiDB instance.
   instance-1-user-schema-rule: # The first of the routing mapping rule.
    schema-pattern: "user"
    target-schema: "user_north"
   instance-2-user-schema-rule:
    schema-pattern: "user"
    target-schema: "user_east"
    
  # Rule 2: Migrate all tables in store database in upstream MySQL instance to store database in the downstream TiDB instance, except the table store.store_sz in upstream MySQL instances on PD2 to the table store.store_suzhou in the downstream TiDB instance.
   instance-2-store-schema-rule:
    schema-pattern: "store"
    table-pattern: "store_sz"
    target-schema: "store"
    target-table: "store_suzhou"
    
  # Rule 3: Migrate the table salesdb.sales which is sharded schemas in upstream MySQL instances on PD1 and PD2 in the two upstream MySQL instances to the salesdb.sales tables in the downstream TiDB instance.
   salesdb-schema-route-rule:
    schema-pattern: "salesdb"
    target-schema: "salesdb"

  # Rule 4: Any delete DML event on user.*, any drop table, truncate table DDL event on table user.trace and any delete, truncate table, drop table DDL event on store database in any upstream MySQL instance will not be replicated to the downstream TiDB instance.
  filters:
   trace-table-filter-rule:
    schema-pattern: "user"
    table-pattern: "trace"
    events: ["truncate table", "DROP TABLE", "delete"]
    action: Ignore
   user-table-filter-rule:
    schema-pattern: "user"
    events: ["drop database"]
    action: Ignore
   store-table-filter-rule:
    schema-pattern: "store"
    events: ["drop database", "truncate table", "DROP TABLE", "delete"]
    action: Ignore

  # Rule 5: The log databases in any upstream MySQL instance will not be replicated to the downstream TiDB instance.
  block-allow-list:
   log-ignored:
    ignore-dbs: ["log"]
  mydumpers:
   global:
    threads: 4
    chunk-filesize: 64
  ```

+ `dm-task.yaml` 構成を確認するために `check-task` コマンドを実行します。`pre-check is passed` メッセージが期待されます。
  
  ```bash
  tiup dmctl:v7.5.1 --master-addr=${HOST_PD1_PRIVATE_IP}:8261 check-task dm-task.yaml
  ```
  ```output
  tiup is checking updates for component dmctl ...
  Starting component `dmctl`: /root/.tiup/components/dmctl/v7.5.1/dmctl/dmctl --master-addr=172.31.0.232:8261 check-task dm-task.yaml
  {
     "result": true,
     "msg": "pre-check is passed. "
  }
  ```

## モジュール 4: TiDB Data Migration タスクを実行して移行結果を確認する

### 手順 1. TiDB Data Migration タスクを開始する

+ TiDB Data Migrationタスクを`tiup dmctl:v7.5.1`コマンドを使って開始します。
  
  ```sql
  tiup dmctl:v7.5.1 --master-addr=${HOST_PD1_PRIVATE_IP}:8261 start-task dm-task.yaml
  ```
  ```output
  Starting component dmctl: /home/ec2-user/.tiup/components/dmctl/v7.5.1/dmctl/dmctl --master-addr=10.90.3.251:8261 start-task dm-task.yaml
  {
     "result": true,
     "msg": "",
     "sources": [
        {
              "result": true,
              "msg": "",
              "source": "mysql-replica-01",
              "worker": "dm-10.90.3.231-8262"
        },
        {
              "result": true,
              "msg": "",
              "source": "mysql-replica-02",
              "worker": "dm-10.90.3.7-8262"
        }
     ],
     "checkResult": "pre-check is passed. "
  }
  ```

+ タスクのステータスを表示します。

  ```bash
  tiup dmctl:v7.5.1 --master-addr=${HOST_PD1_PRIVATE_IP}:8261 query-status dm-task.yaml
  ```
  ```output
  Starting component dmctl: /home/ec2-user/.tiup/components/dmctl/v7.5.1/dmctl/dmctl --master-addr=10.90.3.251:8261 query-status dm-task.yaml
  {
        "result": true,
        "msg": "",
        "sources": [
           {
              "result": true,
              "msg": "",
              "sourceStatus": {
                    "source": "mysql-replica-01",
                    "worker": "dm-10.90.3.231-8262",
                    "result": null,
                    "relayStatus": null
              },
              "subTaskStatus": [
                    {
                    ... 
                    }
              ]
           },
           {
              "result": true,
              "msg": "",
              "sourceStatus": {
                    "source": "mysql-replica-02",
                    "worker": "dm-10.90.3.7-8262",
                    "result": null,
                    "relayStatus": null
              },
              "subTaskStatus": [
                    {
                    ... 
                    }
              ]
           }
        ]
  }
  ```

### 手順 2. TiDB Data Migration タスクの結果を確認する

+ 移行タスクからのフルデータが下流データベースTiDBに含まれていることを確認します。
  
  ```bash
  mysql -h${HOST_DB1_PRIVATE_IP} -P4000 -uroot 
  ```
  ```sql
  USE user_east;
  SHOW TABLES;
  SELECT * FROM information;
  SELECT * FROM trace;
  USE user_north;
  SHOW TABLES;
  SELECT * FROM information;
  SELECT * FROM trace;
  USE store;
  SHOW TABLES;
  SELECT * FROM store_bj;
  SELECT * FROM store_tj;
  SELECT * FROM store_suzhou;
  SELECT * FROM store_sh;
  USE salesdb;
  SELECT * FROM sales;
  ```
  ```output
  mysql> USE user_east;
  Reading table information for completion of table and column names
  You can turn off this feature to get a quicker startup with -A

  Database changed
  mysql> SHOW TABLES;
  +---------------------+
  | Tables_in_user_east |
  +---------------------+
  | information         |
  | trace               |
  +---------------------+
  2 rows in set (0.00 sec)

  mysql> SELECT * FROM information;
  +----+-------+
  | id | info  |
  +----+-------+
  |  1 | andy  |
  |  2 | candy |
  +----+-------+
  2 rows in set (0.00 sec)

  mysql> SELECT * FROM trace;
  +----+---------+
  | id | content |
  +----+---------+
  |  1 | error   |
  +----+---------+
  1 row in set (0.00 sec)

  ... 

  mysql> USE salesdb;
  Reading table information for completion of table and column names
  You can turn off this feature to get a quicker startup with -A

  Database changed
  mysql> SELECT * FROM sales;
  +----+-------+------+
  | id | pname | cnt  |
  +----+-------+------+
  |  1 | book  |  100 |
  |  2 | cup   |  200 |
  +----+-------+------+
  2 rows in set (0.00 sec)
  ```

+ シェルターミナルを終了します。

   ```sql
   EXIT;
   ```

### 手順 3. アップストリームデータベースに新しい値を挿入します

+ アップストリームデータベースにデータを挿入した後に、ダウンストリームデータベースがその値を受け取ることを確認します。
  + `PD1`で
  
    ```bash
    ./ssh-to-pd1.sh
    ```

    ```bash
    mysql -u root -p -h 127.0.0.1 -P 3306 -pq1w2e3R4_
    ```
    ```sql
    INSERT INTO salesdb.sales VALUES(3,'shoes',120);
    ```
    ```output
    mysql> INSERT INTO salesdb.sales VALUES(3,'shoes',120);
    Query OK, 1 row affected (0.01 sec)
    ```

    ```sql
    SELECT * FROM salesdb.sales;
    ```
    ```output
    mysql> SELECT * FROM salesdb.sales;
    +----+-------+------+
    | id | pname | cnt  |
    +----+-------+------+
    |  1 | book  |  100 |
    |  3 | shoes |  120 |
    +----+-------+------+
    2 rows in set (0.00 sec)
    ```

    ```sql
    EXIT
    ```
    ```output
    mysql> EXIT;
    Bye
    ```
    ```bash
    exit
    ```
    ```output
    logout
    Connection to XX.XX.XX.XX closed.
    ```

  + `Control Machine`で
  
    ```bash
    mysql -h ${HOST_DB1_PRIVATE_IP} -P 4000 -uroot
    ```
    ```sql
    SELECT * FROM salesdb.sales;
    ```
    ```output
    mysql> SELECT * FROM salesdb.sales;
    +----+-------+------+
    | id | pname | cnt  |
    +----+-------+------+
    |  1 | book  |  100 |
    |  2 | cup   |  200 |
    |  3 | shoes |  120 |
    +----+-------+------+
    3 rows in set (0.00 sec)
    ```

    ```sql
    EXIT
    ```
    ```output
    mysql> EXIT
    Bye
    ```

## モジュール 5: TiDB データマイグレーションクラスタのスケールインとスケールアウト

### 手順 1. デプロイされた `TiDB Data Migration` クラスタのステータスを確認します

  ```bash
  tiup dm display dm-test
  ```
  ```output
  tiup is checking updates for component dm ...
  Starting component `dm`: /home/ec2-user/.tiup/components/dm/v1.12.1/tiup-dm display dm-test
  Cluster type:       dm
  Cluster name:       dm-test
  Cluster version:    v7.5.1
  Deploy user:        tidb
  SSH type:           builtin
  Grafana URL:        http://10.90.4.231:3000
  ID                Role          Host         Ports      OS/Arch       Status     Data Dir                      Deploy Dir
  --                ----          ----         -----      -------       ------     --------                      ----------
  10.90.4.231:9093  alertmanager  10.90.4.231  9093/9094  linux/x86_64  Up         /tidb-data/alertmanager-9093  /tidb-deploy/alertmanager-9093
  10.90.1.34:8261   dm-master     10.90.1.34   8261/8291  linux/x86_64  Healthy|L  /tidb-data/dm-master-8261     /tidb-deploy/dm-master-8261
  10.90.2.38:8261   dm-master     10.90.2.38   8261/8291  linux/x86_64  Healthy    /tidb-data/dm-master-8261     /tidb-deploy/dm-master-8261
  10.90.3.188:8261  dm-master     10.90.3.188  8261/8291  linux/x86_64  Healthy    /tidb-data/dm-master-8261     /tidb-deploy/dm-master-8261
  10.90.1.162:8262  dm-worker     10.90.1.162  8262       linux/x86_64  Bound      /tidb-data/dm-worker-8262     /tidb-deploy/dm-worker-8262
  10.90.2.108:8262  dm-worker     10.90.2.108  8262       linux/x86_64  Bound      /tidb-data/dm-worker-8262     /tidb-deploy/dm-worker-8262
  10.90.3.12:8262   dm-worker     10.90.3.12   8262       linux/x86_64  Free       /tidb-data/dm-worker-8262     /tidb-deploy/dm-worker-8262
  10.90.4.231:3000  grafana       10.90.4.231  3000       linux/x86_64  Up         -                             /tidb-deploy/grafana-3000
  10.90.4.231:9090  prometheus    10.90.4.231  9090       linux/x86_64  Up         /tidb-data/prometheus-9090    /tidb-deploy/prometheus-9090
  Total nodes: 9
  ```

### 手順 2. TiDB Data Migration クラスタをスケールインします

+ `tiup dm scale-in` コマンドを実行して `TiDB Data Migration` クラスタをスケールインし、`DM-worker` ノードを `KV server 1` の IP アドレスを持つノードをオフラインにします。
  
  ```bash
  tiup dm scale-in dm-test -N ${HOST_KV1_PRIVATE_IP}:8262
  ```
  ```output
  ...
  Do you want to continue? [y/N]:(default=N) y
  ...
  Scaled cluster `dm-test` in successfully
  ```

### 手順 3. デプロイされた `TiDB Data Migration` クラスタのステータスを再度確認します

  ```bash
  tiup dm display dm-test
  ```
  ```output
  tiup is checking updates for component dm ...
  Starting component `dm`: /home/ec2-user/.tiup/components/dm/v1.12.1/tiup-dm display dm-test
  Cluster type:       dm
  Cluster name:       dm-test
  Cluster version:    v7.5.1
  Deploy user:        tidb
  SSH type:           builtin
  Grafana URL:        http://10.90.4.231:3000
  ID                Role          Host         Ports      OS/Arch       Status     Data Dir                      Deploy Dir
  --                ----          ----         -----      -------       ------     --------                      ----------
  10.90.4.231:9093  alertmanager  10.90.4.231  9093/9094  linux/x86_64  Up         /tidb-data/alertmanager-9093  /tidb-deploy/alertmanager-9093
  10.90.1.34:8261   dm-master     10.90.1.34   8261/8291  linux/x86_64  Healthy|L  /tidb-data/dm-master-8261     /tidb-deploy/dm-master-8261
  10.90.2.38:8261   dm-master     10.90.2.38   8261/8291  linux/x86_64  Healthy    /tidb-data/dm-master-8261     /tidb-deploy/dm-master-8261
  10.90.3.188:8261  dm-master     10.90.3.188  8261/8291  linux/x86_64  Healthy    /tidb-data/dm-master-8261     /tidb-deploy/dm-master-8261
  10.90.1.162:8262  dm-worker     10.90.1.162  8262       linux/x86_64  Bound      /tidb-data/dm-worker-8262     /tidb-deploy/dm-worker-8262
  10.90.3.12:8262   dm-worker     10.90.3.12   8262       linux/x86_64  Bound      /tidb-data/dm-worker-8262     /tidb-deploy/dm-worker-8262
  10.90.4.231:3000  grafana       10.90.4.231  3000       linux/x86_64  Up         -                             /tidb-deploy/grafana-3000
  10.90.4.231:9090  prometheus    10.90.4.231  9090       linux/x86_64  Up         /tidb-data/prometheus-9090    /tidb-deploy/prometheus-9090
  Total nodes: 8
  ```

### 手順 4. `dm-scale.yaml` ファイルを準備します

+ テキストエディタを使用して `dm-scale.yaml` ファイルを編集します。 以下のような設定に似た内容を含むように `dm-scale.yaml` ファイルを修正します（割り当てられた正しい IP アドレスに置き換えてください）。
  
  ```bash
  vi dm-scale.yaml
  ```
  ```bash
  worker_servers:
  - host: ${HOST_KV1_PRIVATE_IP}
  ```

### 手順 5. TiDB Data Migration クラスタをスケールアウトします

  ```bash
  tiup dm --user ec2-user -i ~/.ssh/pe-class-key-oregon.pem scale-out dm-test dm-scale.yaml
  ```
  ```output
  ...
  Do you want to continue? [y/N]: (default=N) y 
  ...
  Scaled cluster `dm-test` out successfully    
  ```

### 手順 6. デプロイされた `TiDB Data Migration` クラスタのステータスを再度確認します

  ```bash
  tiup dm display dm-test
  ```

### 手順 7. データマイグレーションタスクを停止するために `stop-task` コマンドを実行します

  ```bash
  tiup dmctl:v7.5.1 --master-addr=${HOST_PD3_PRIVATE_IP}:8261 stop-task dm-task.yaml
  ```
  ```output
  tiup is checking updates for component dmctl ...
  Starting component `dmctl`: /home/ec2-user/.tiup/components/dmctl/v7.5.1/dmctl/dmctl --master-addr=10.90.2.38:8261 stop-task dm-task.yaml
  {
        "op": "Delete",
        "result": true,
        "msg": "",
        "sources": [
           {
              "result": true,
              "msg": "",
              "source": "mysql-replica-01",
              "worker": "dm-10.90.3.12-8262"
           },
           {
              "result": true,
              "msg": "",
              "source": "mysql-replica-02",
              "worker": "dm-10.90.1.162-8262"
           }
        ]
  }
  ```

### 手順 8. TiDB Data Migration クラスタのデータマイグレーションが停止していることを確認します

  ```bash
  tiup dmctl:v7.5.1 --master-addr=${HOST_PD3_PRIVATE_IP}:8261 query-status dm-task.yaml
  ```
  ```output
  Starting component `dmctl`: /home/ec2-user/.tiup/components/dmctl/v7.5.1/dmctl/dmctl --master-addr=10.90.2.38:8261 query-status dm-task.yaml
  {
        "result": false,
        "msg": "task dm-task has no source or not exist",
        "sources": [
        ]
  }
  ```

### 手順 9. TiDB Data Migration クラスタを停止します

  ```bash
  tiup dm stop dm-test
  ```
  ```output
  ...
  Do you want to continue? [y/N]:(default=N) y
  ...
  Stopped cluster `dm-test` successfully
  ```

### 手順 10. TiDB Data Migration クラスタのステータスを確認します

  ```bash
  tiup dm display dm-test
  ```

### 手順 11. TiDB Data Migration クラスタを削除します

  ```bash
  tiup dm destroy dm-test
  ```

## 演習終了