# 演習 7: Dumplingを使用したデータのエクスポート

## 概要

これらの演習では、TiDB/MySQLに格納されたデータをSQLまたはCSVデータファイルとしてエクスポートし、論理的なフルバックアップまたはエクスポートに使用できます。以下にTiDBクラスタのデプロイメントトポロジー図を示します。

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


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

## モジュール 1: `Dumpling` のデプロイ

### 手順 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. `Dumpling` のインストール

  ```bash
  tiup install dumpling:v7.5.1
  ```
  ```output
  component dumpling version v7.5.1 is already installed
  ```

### 手順 3. データ抽出

  ```bash
  unzip -u stage/tidb-admin-dataset-v2.zip -d stage/
  ```
  ```output
  Archive:  stage/tidb-admin-dataset-v2.zip
  ```

## モジュール 2: TiDB にデータを TiDB Lightning でインポート

### 手順 1. データファイルディレクトリの内容を一覧表示

  ```bash
  ls ./stage/TiDB-Administration-exercise-data-v2/exercise-dumpling
  ```
  ```output
  emp.dep.0000000010000.sql  emp.emp-schema.sql         emp.sal.0000000030000.sql  emp.sal-schema.sql       emp.t-schema.sql
  emp.dep-schema.sql         emp.sal.0000000010000.sql  emp.sal.0000000040000.sql  emp-schema-create.sql    metadata
  emp.emp.0000000010000.sql  emp.sal.0000000020000.sql  emp.sal.0000000050000.sql  emp.t.0000000010000.sql
  ```

### 手順 2. TiDB に接続し、`emp` データベースを削除

  ```bash
  mysql -h ${HOST_DB1_PRIVATE_IP} --port 4000 -u root
  ```
  ```sql
  SHOW DATABASES;
  ```
  ```output
  mysql> SHOW DATABASES;
  +--------------------+
  | Database           |
  +--------------------+
  | INFORMATION_SCHEMA |
  | METRICS_SCHEMA     |
  | PERFORMANCE_SCHEMA |
  | emp                |
  | mysql              |
  | test               |
  | tidb               |
  +--------------------+
  7 rows in set (0.00 sec)
  ```

  ```sql
  DROP DATABASE IF EXISTS emp;
  ```
  ```output
  mysql> DROP DATABASE IF EXISTS emp;
  Query OK, 0 rows affected (0.21 sec)
  ```

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

### 手順 3. `solution-lightning-sql.toml` を読みます

+ 以下に表示されるIPアドレスは、あなたのものとは異なるでしょう。
  
  ```bash
  cat solution-lightning-sql.toml
  ```
  ```output
  [lightning]
  # Logging
  level = "info"
  file = "tidb-lightning.log"

  [tikv-importer]
  # Sets the backend to the "local" mode.
  backend = "local"
  # Sets the directory of temporary local storage.
  sorted-kv-dir = "/tmp/sorted-kv-dir"

  [mydumper]
  # Local source data directory
  data-source-dir = "/home/ec2-user/stage/TiDB-Administration-exercise-data-v2/exercise-dumpling"

  # Configures the wildcard rule. By default, all tables in the mysql, sys, INFORMATION_SCHEMA, PERFORMANCE_SCHEMA, METRICS_SCHEMA, and INSPECTION_SCHEMA system databases are filtered.
  # If this item is not configured, the "cannot find schema" error occurs when system tables are imported.
  filter = ['*.*', '!mysql.*', '!sys.*', '!INFORMATION_SCHEMA.*', '!PERFORMANCE_SCHEMA.*', '!METRICS_SCHEMA.*', '!INSPECTION_SCHEMA.*']

  [tidb]
  # Configuration of any TiDB server from the cluster.
  host = "10.90.2.124"
  port = 4000
  user = "ltask"
  password = "q1w2e3R4_"
  # Table schema information is fetched from TiDB via this status-port.
  status-port = 10080
  # Address of any PD server from the cluster.
  pd-addr = "10.90.2.84:2379"
  ```

### 手順 4. TiDB にデータをインポート

+ `nohup`コマンドを使用して`tidb-lightning`プロセスを開始します（`<kbd>Enter</kbd>`を押して`tidb-lighting`をバックグラウンドで動作させます）。
  
  ```bash
  nohup tiup tidb-lightning:v7.5.1 -config solution-lightning-sql.toml > nohup.out &
  ```
  ```output
  [1] 13135
  nohup: ignoring input and redirecting stderr to stdout
  ...
  [1]+  Done      nohup tidb-lightning:v7.5.1 -config solution-lightning-sql.toml > nohup.out
  ```

### 手順 5. Lightning の出力を閲覧

  ```bash
  cat nohup.out
  ```
  ```output
  Verbose debug logs will be written to tidb-lightning.log

  +----+------------------------------------------------------------------------------------------------------------------------------------+-------------+--------+
  |  # | CHECK ITEM                                                                                                                         | TYPE        | PASSED |
  +----+------------------------------------------------------------------------------------------------------------------------------------+-------------+--------+
  |  1 | Source csv files size is proper                                                                                                    | performance | true   |
  +----+------------------------------------------------------------------------------------------------------------------------------------+-------------+--------+
  ...
  +-----------------------------------------------------------------------------------------------------------------------------------------+-------------+--------+
  |  8 | Cluster available is rich, available is 51.79GiB, we need 1.007GiB                                                                 | critical    | true   |
  +----+------------------------------------------------------------------------------------------------------------------------------------+-------------+--------+
  |  9 | Cluster doesn't have too many empty regions                                                                                        | critical    | true   |
  +----+------------------------------------------------------------------------------------------------------------------------------------+-------------+--------+
  | 10 | Cluster region distribution is balanced                                                                                            | critical    | true   |
  +----+------------------------------------------------------------------------------------------------------------------------------------+-------------+--------+

  tidb lightning exit successfully
  ```

## モジュール 3: Dumpling を使用して TiDB からデータをエクスポート

### 手順 1. TiDB に接続し、`emp` データベースのテーブルを確認

  ```bash
  mysql -h ${HOST_DB1_PRIVATE_IP} --port 4000 -u root
  ```
  ```sql
  SHOW DATABASES;
  ```
  ```output
  mysql> SHOW DATABASES;
  +--------------------+
  | Database           |
  +--------------------+
  | INFORMATION_SCHEMA |
  | METRICS_SCHEMA     |
  | PERFORMANCE_SCHEMA |
  | emp                |
  | mysql              |
  | test               |
  | tidb               |
  +--------------------+
  7 rows in set (0.00 sec)
  ```

  ```sql
  USE emp; 
  ```
  ```output
  mysql> USE emp; 
  Database changed
  ```
  
  ```sql
  SHOW TABLES;
  ```
  ```output
  mysql> SHOW TABLES;
  +---------------+
  | Tables_in_emp |
  +---------------+
  | dep           |
  | emp           |
  | sal           |
  | t             |
  +---------------+
  4 rows in set (0.00 sec)
  ```

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

### 手順 2. TiDB から `emp` データベースの `dept` テーブルをエクスポート

+ 以下はパラメータの説明です:
  + `-uroot`: ユーザーはroot。
  + `-P4000`: ポートは4000。
  + `-h ${HOST_DB1_PRIVATE_IP}`: TiDBのIPアドレスは`${HOST_DB1_PRIVATE_IP}`。
  + `--filetype sql`: データをSQLファイルにエクスポート。
  + `-t 8`: 同時に8スレッドを使用してエクスポート。
  + `-o /tmp/dept`: オプション `/tmp/dept` をエクスポートディレクトリとして指定。
  + `-r 200000`: 単一ファイルの最大行数200000を指定。
  + `-F 256MiB`: 単一ファイルの最大サイズ256 MiBを指定（ここでの単位はMiBです; 5GiBや8KBのような入力も許容されます）。

  ```bash
  tiup dumpling:v7.5.1 -uroot -P4000 -h ${HOST_DB1_PRIVATE_IP} --filetype sql -t 8 -o /tmp/dep -r 200000 -F 256MiB -T emp.dep
  ```
  ```output
  Release version: v7.5.1
  Git commit hash: 1a89decdb192cbdce6a7b0020d71128bc964d30f
  Git branch:      heads/refs/tags/v7.5.1
  Build timestamp: 2022-06-05 05:09:15Z
  Go version:      go version go1.18.2 linux/amd64

  [2022/11/08 15:09:37.456 +08:00] [INFO] [versions.go:55] ["Welcome to dumpling"] ["Release Version"=v7.5.1] ["Git Commit Hash"=1a89decdb192cbdce6a7b0020d71128bc964d30f] ["Git Branch"=heads/refs/tags/v7.5.1] ["Build timestamp"="2022-06-05 05:09:15"] ["Go Version"="go version go1.18.2 linux/amd64"]
  ...
  [2022/11/08 15:09:37.496 +08:00] [INFO] [main.go:80] ["dump data successfully, dumpling will exit now"]
  ```

### 手順 3. `/tmp/dep` ディレクトリの内容を確認

  ```bash
  ls /tmp/dep
  ```
  ```output
  emp.dep.0000000010000.sql  emp.dep-schema.sql  emp-schema-create.sql  metadata
  ```

### 手順 4. Dumpling の出力を確認

  ```bash
  cat /tmp/dep/emp-schema-create.sql
  ```
  ```output
  /*!40101 SET NAMES binary*/;
  CREATE DATABASE `emp` /*!40100 DEFAULT CHARACTER SET utf8mb4 */;
  ```

  ```bash
  cat /tmp/dep/emp.dep-schema.sql
  ```
  ```output
  /*!40101 SET NAMES binary*/;
  CREATE TABLE `dep` (
  `dept_no` char(4) NOT NULL,
  `dept_name` varchar(40) NOT NULL,
  PRIMARY KEY (`dept_no`) /*T![clustered_index] NONCLUSTERED */,
  UNIQUE KEY `dept_name` (`dept_name`)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
  ```

  ```bash
  cat /tmp/dep/emp.dep.0000000010000.sql
  ```
  ```output
  /*!40101 SET NAMES binary*/;
  INSERT INTO `dep` VALUES
  ('d001','Marketing'),
  ('d002','Finance'),
  ('d003','Human Resources'),
  ('d004','Production'),
  ('d005','Development'),
  ('d006','Quality Management'),
  ('d007','Sales'),
  ('d008','Research'),
  ('d009','Customer Service');
  ```

  ```bash
  cat /tmp/dep/metadata
  ```
  ```output
  Started dump at: 2022-06-25 15:44:18
  SHOW MASTER STATUS:
        Log: tidb-binlog
        Pos: 434147965850615813
        GTID:

  Finished dump at: 2022-06-25 15:44:20
  ```

### 手順 5. TiDB から `emp` データベースをエクスポート

  ```bash
  tiup dumpling:v7.5.1 -uroot -P4000 -h ${HOST_DB1_PRIVATE_IP} --filetype sql -t 8 -o /tmp/emp -r 200000 -F 256MiB -B emp
  ```
  ```output
  Release version: v7.5.1
  Git commit hash: 1a89decdb192cbdce6a7b0020d71128bc964d30f
  Git branch:      heads/refs/tags/v7.5.1
  Build timestamp: 2022-06-05 05:09:15Z
  Go version:      go version go1.18.2 linux/amd64

  [2022/11/08 15:18:17.316 +08:00] [INFO] [versions.go:55] ["Welcome to dumpling"] ["Release Version"=v7.5.1] ["Git Commit Hash"=1a89decdb192cbdce6a7b0020d71128bc964d30f] ["Git Branch"=heads/refs/tags/v7.5.1] ["Build timestamp"="2022-06-05 05:09:15"] ["Go Version"="go version go1.18.2 linux/amd64"]
  ...
  [2022/11/08 15:18:19.398 +08:00] [INFO] [main.go:80] ["dump data successfully, dumpling will exit now"]
  ```

### 手順 6. `/tmp/emp` ディレクトリの内容を確認

  ```bash
  ls /tmp/emp
  ```
  ```output
  emp.dep.0000000010000.sql  emp.emp.0000000010000.sql  emp.sal.0000000010000.sql  emp.sal.0000000030000.sql  emp.sal-schema.sql     emp.t.0000000010000.sql  metadata
  emp.dep-schema.sql         emp.emp-schema.sql         emp.sal.0000000020000.sql  emp.sal.0000000040000.sql  emp-schema-create.sql  emp.t-schema.sql
  ```

## モジュール 4: Dumpling を使用して MySQL からデータをエクスポート

### 手順 1. `PD3` に SSH

  ```bash
  ./ssh-to-pd3.sh
  ```

### 手順 2. MySQL サーバーインスタンスを開始

  ```bash
  sudo service mysqld start
  ```

### 手順 3. PD3 でデータを解凍

  ```bash
  unzip -u stage/tidb-admin-dataset-v2.zip -d stage/
  ```

### 手順 4. MySQL サーバーにログイン

  ```bash
  mysql -u root -p -h 127.0.0.1 -P 3306 -pq1w2e3R4_
  ```

### 手順 5. エクスポートタスク用のユーザーを作成

  ```sql
  CREATE USER exp@'%' IDENTIFIED BY 'q1w2e3R4_';
  ```
  ```output
  mysql> CREATE USER exp@'%' IDENTIFIED BY 'q1w2e3R4_';
  Query OK, 0 rows affected (0.00 sec)
  ```

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

### 手順 6. データを MySQL にインポート

   ```sql
   SOURCE ./stage/TiDB-Administration-exercise-data-v2/exercise-dumpling/emp-schema-create.sql
   ```
   ```sql
   USE emp;
   ```
   ```output
   mysql> USE emp;
   Database changed
   ```

   ```sql
   SOURCE ./stage/TiDB-Administration-exercise-data-v2/exercise-dumpling/emp.dep-schema.sql
   SOURCE ./stage/TiDB-Administration-exercise-data-v2/exercise-dumpling/emp.dep.0000000010000.sql
   SOURCE ./stage/TiDB-Administration-exercise-data-v2/exercise-dumpling/emp.t-schema.sql
   SOURCE ./stage/TiDB-Administration-exercise-data-v2/exercise-dumpling/emp.t.0000000010000.sql
   SOURCE ./stage/TiDB-Administration-exercise-data-v2/exercise-dumpling/emp.emp-schema.sql
   SOURCE ./stage/TiDB-Administration-exercise-data-v2/exercise-dumpling/emp.emp.0000000010000.sql
   ```
   ```output
   ...
   Query OK, 16843 rows affected (0.14 sec)
   Records: 16843  Duplicates: 0  Warnings: 0

   Query OK, 12161 rows affected (0.10 sec)
   Records: 12161  Duplicates: 0  Warnings: 0
   ```
   
### 手順 7. MySQL の `emp` データベースのテーブルを確認

  ```sql
  SHOW TABLES;
  ```
  ```output
  mysql> SHOW TABLES;
  +---------------+
  | Tables_in_emp |
  +---------------+
  | dep           |
  | emp           |
  | t             |
  +---------------+
  3 rows in set (0.00 sec)
  ```

### 手順 8. `monitor1_address` に戻る

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

  ```bash
  exit
  ```
  ```output
  logout
  Connection to 10.90.1.78 closed.
  ```

### 手順 9. MySQL から `emp` データベースをエクスポート

  ```bash
  tiup dumpling:v7.5.1 -uexp -P 3306 -h ${HOST_PD3_PRIVATE_IP} -pq1w2e3R4_ --filetype sql -t 8 -o /tmp/empmysql -r 200000 -F 256MiB -B emp
  ```
  ```output
  Release version: v7.5.1
  Git commit hash: 1a89decdb192cbdce6a7b0020d71128bc964d30f
  Git branch:      heads/refs/tags/v7.5.1
  Build timestamp: 2022-06-05 05:09:15Z
  Go version:      go version go1.18.2 linux/amd64

  [2022/11/08 15:18:17.316 +08:00] [INFO] [versions.go:55] ["Welcome to dumpling"] ["Release Version"=v7.5.1] ["Git Commit Hash"=1a89decdb192cbdce6a7b0020d71128bc964d30f] ["Git Branch"=heads/refs/tags/v7.5.1] ["Build timestamp"="2022-06-05 05:09:15"] ["Go Version"="go version go1.18.2 linux/amd64"]
  ...
  [2022/11/08 15:18:19.398 +08:00] [INFO] [main.go:80] ["dump data successfully, dumpling will exit now"]
  ```

### 手順 10. 出力ディレクトリの内容を確認

  ```bash
  ls /tmp/empmysql
  ```
  ```output
  emp.dep.0000000010000.sql  emp.emp-schema.sql         emp.sal.0000000030000.sql  emp-schema-create.sql    metadata
  emp.dep-schema.sql         emp.sal.0000000010000.sql  emp.sal.0000000040000.sql  emp.t.0000000010000.sql
  emp.emp.0000000010000.sql  emp.sal.0000000020000.sql  emp.sal-schema.sql         emp.t-schema.sql
  ```

## 演習終了