供養の地

使わなかった設定を供養します。

全文検索DB(Mroonga)を構築する

Mroonga install

MariaDB提供のMariaDB 10.4.13 インストール

$ sudo vim /etc/yum.repos.d/MariaDB.repo

[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.4/centos7-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1

$ sudo yum install -y MariaDB-server
$ sudo systemctl start mariadb
  • 仮パスワード設定(mariadb-10.4-mroonga install時に使用)
$ sudo /usr/bin/mysqladmin -uroot password 'password'

mroongaの有効化

  • mroongaのバージョンについて MariaDB 10.0.15以降は、プラグインをビルドしなくてもリリースに含まれているが、バージョンが7.07になってしまう。今回は最新バージョンでインストールしたいので、groongaをインストールして最新バージョンにする。
  • 参考
https://mariadb.com/kb/en/about-mroonga/

Mroonga(以前の名前はGroongaストレージエンジン)は、MariaDB 5.3リリースに含まれており、MariaDB 10.0.15からデフォルトで利用できます。

MariaDB 10.0.15より前のバージョンでは、Mroongaはデフォルトでは使用できず、プラグインをビルドする必要がありました。http://mroonga.org/docs/install.htmlにある手順を参照してください。MariaDB 10.0.15以降、またはプラグインがビルドされたら、次のステートメントでMroongaを有効にします。
  • 7.07でもよければ、↓で可能
$ mysql -u root -p
MariaDB [(none)]> INSTALL SONAME 'ha_mroonga';
  • 最新バージョンのmroongaを使いたい場合↓
$ sudo yum install -y https://packages.groonga.org/centos/groonga-release-latest.noarch.rpm

$ sudo amazon-linux-extras install epel -y

$ sudo vi /etc/yum.repos.d/groonga.repo

[groonga]
name=Groonga for CentOS $releasever - $basearch
baseurl=https://packages.groonga.org/centos/7/$basearch/
gpgcheck=1
enabled=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-groonga

$ sudo rpm --import http://packages.groonga.org/centos/RPM-GPG-KEY-groonga

$ sudo yum install -y --enablerepo=epel mariadb-10.4-mroonga

###↑ここでGPGエラーが出る場合は、groonga-amazon-linux.repoを削除
$ sudo yum install -y --enablerepo=epel mariadb-10.4-mroonga
読み込んだプラグイン:extras_suggestions, langpacks, priorities, update-motd
ロックファイル /var/run/yum.pid が存在します: PID 21662 として別に実行されています。
Another app is currently holding the yum lock; waiting for it to exit...
 他のアプリケーション: yum
   メモリー: 294 M RSS (511 MB VSZ)
    開始   : Fri Jul 17 13:56:14 2020 - 00:04 秒経過
    状態   : 実行中、PID: 21662
Another app is currently holding the yum lock; waiting for it to exit...
 他のアプリケーション: yum
   メモリー: 301 M RSS (517 MB VSZ)
    開始   : Fri Jul 17 13:56:14 2020 - 00:06 秒経過
    状態   : 実行中、PID: 21662
193 packages excluded due to repository priority protections
依存性の解決をしています
--> トランザクションの確認を実行しています。
---> パッケージ mariadb-10.4-mroonga.x86_64 0:10.03-1.el7 を インストール
--> 依存性の処理をしています: groonga-libs >= 8.0.4 のパッケージ: mariadb-10.4-mroonga-10.03-1.el7.x86_64
--> 依存性の処理をしています: groonga-normalizer-mysql のパッケージ: mariadb-10.4-mroonga-10.03-1.el7.x86_64
--> 依存性の処理をしています: libgroonga.so.0()(64bit) のパッケージ: mariadb-10.4-mroonga-10.03-1.el7.x86_64
--> トランザクションの確認を実行しています。
---> パッケージ groonga-libs.x86_64 0:10.0.4-1.el7 を インストール
--> 依存性の処理をしています: libzstd のパッケージ: groonga-libs-10.0.4-1.el7.x86_64
--> 依存性の処理をしています: msgpack のパッケージ: groonga-libs-10.0.4-1.el7.x86_64
--> 依存性の処理をしています: libmsgpackc.so.2()(64bit) のパッケージ: groonga-libs-10.0.4-1.el7.x86_64
---> パッケージ groonga-normalizer-mysql.x86_64 0:1.1.4-1.el7 を インストール
--> トランザクションの確認を実行しています。
---> パッケージ libzstd.x86_64 0:1.3.3-1.amzn2.0.1 を インストール
---> パッケージ msgpack.x86_64 0:3.1.0-4.el7 を インストール
--> 依存性解決を終了しました。

依存性を解決しました

====================================================================================================================================================================================
 Package                                              アーキテクチャー                   バージョン                                    リポジトリー                            容量
====================================================================================================================================================================================
インストール中:
 mariadb-10.4-mroonga                                 x86_64                             10.03-1.el7                                   groonga                                251 k
依存性関連でのインストールをします:
 groonga-libs                                         x86_64                             10.0.4-1.el7                                  groonga                                1.9 M
 groonga-normalizer-mysql                             x86_64                             1.1.4-1.el7                                   groonga                                 53 k
 libzstd                                              x86_64                             1.3.3-1.amzn2.0.1                             amzn2-core                             203 k
 msgpack                                              x86_64                             3.1.0-4.el7                                   epel                                    27 k

トランザクションの要約
====================================================================================================================================================================================
インストール  1 パッケージ (+4 個の依存関係のパッケージ)

総ダウンロード容量: 2.5 M
インストール容量: 2.8 M
Downloading packages:
(1/5): libzstd-1.3.3-1.amzn2.0.1.x86_64.rpm                                                                                                                  | 203 kB  00:00:00
warning: /var/cache/yum/x86_64/2/groonga/packages/groonga-normalizer-mysql-1.1.4-1.el7.x86_64.rpm: Header V4 RSA/SHA256 Signature, key ID 34839225: NOKEY
groonga-normalizer-mysql-1.1.4-1.el7.x86_64.rpm の公開鍵がインストールされていません
(2/5): groonga-normalizer-mysql-1.1.4-1.el7.x86_64.rpm                                                                                                       |  53 kB  00:00:00
(3/5): mariadb-10.4-mroonga-10.03-1.el7.x86_64.rpm                                                                                                           | 251 kB  00:00:00
warning: /var/cache/yum/x86_64/2/epel/packages/msgpack-3.1.0-4.el7.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID 352c64e5: NOKEY
msgpack-3.1.0-4.el7.x86_64.rpm の公開鍵がインストールされていません
(4/5): msgpack-3.1.0-4.el7.x86_64.rpm                                                                                                                        |  27 kB  00:00:00
(5/5): groonga-libs-10.0.4-1.el7.x86_64.rpm                                                                                                                  | 1.9 MB  00:00:00
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
合計                                                                                                                                                7.3 MB/s | 2.5 MB  00:00:00
file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7 から鍵を取得中です。
Importing GPG key 0x352C64E5:
 Userid     : "Fedora EPEL (7) <epel@fedoraproject.org>"
 Fingerprint: 91e9 7d7c 4a5e 96f1 7f3e 888f 6a2f aea2 352c 64e5
 Package    : epel-release-7-11.noarch (@amzn2extra-epel)
 From       : /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
file:///etc/pki/rpm-gpg/RPM-GPG-KEY-groonga から鍵を取得中です。


GPG 鍵の取得に失敗しました: [Errno 14] curl#37 - "Couldn't open file /etc/pki/rpm-gpg/RPM-GPG-KEY-groonga"
$ cd /etc/yum.repos.d/
$ ls -al
合計 44
drwxr-xr-x  2 root root  196  7月 17 13:55 .
drwxr-xr-x 80 root root 8192  7月 17 13:56 ..
-rw-r--r--  1 root root  139  7月 17 13:55 MariaDB.repo
-rw-r--r--  1 root root  985  6月 24 21:10 amzn2-core.repo
-rw-r--r--  1 root root 2051  7月 17 13:53 amzn2-extras.repo
-rw-r--r--  1 root root 1050  8月 29  2018 epel-testing.repo
-rw-r--r--  1 root root  951  8月 29  2018 epel.repo
-rw-r--r--  1 root root  261  7月 17 13:54 groonga-amazon-linux.repo
-rw-r--r--  1 root root  269  7月 17 13:54 groonga-centos.repo
-rw-r--r--  1 root root  187  7月 17 13:53 groonga.repo
$ mv groonga-amazon-linux.repo /tmp
mv: `groonga-amazon-linux.repo' から `/tmp/groonga-amazon-linux.repo' へ移動
  • mroonga バージョン確認
$ mysql -u root
Server version: 10.4.13-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

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

MariaDB [(none)]> show engines;
+--------------------+---------+-------------------------------------------------------------------------------------------------+--------------+------+------------+
| Engine             | Support | Comment                                                                                         | Transactions | XA   | Savepoints |
+--------------------+---------+-------------------------------------------------------------------------------------------------+--------------+------+------------+
| CSV                | YES     | Stores tables as CSV files                                                                      | NO           | NO   | NO         |
| MRG_MyISAM         | YES     | Collection of identical MyISAM tables                                                           | NO           | NO   | NO         |
| MEMORY             | YES     | Hash based, stored in memory, useful for temporary tables                                       | NO           | NO   | NO         |
| Aria               | YES     | Crash-safe tables with MyISAM heritage. Used for internal temporary tables and privilege tables | NO           | NO   | NO         |
| MyISAM             | YES     | Non-transactional engine with good performance and small data footprint                         | NO           | NO   | NO         |
| SEQUENCE           | YES     | Generated tables filled with sequential values                                                  | YES          | NO   | YES        |
| Mroonga            | YES     | CJK-ready fulltext search, column store                                                         | NO           | NO   | NO         |
| PERFORMANCE_SCHEMA | YES     | Performance Schema                                                                              | NO           | NO   | NO         |
| InnoDB             | DEFAULT | Supports transactions, row-level locking, foreign keys and encryption for tables                | YES          | YES  | YES        |
+--------------------+---------+-------------------------------------------------------------------------------------------------+--------------+------+------------+
9 rows in set (0.000 sec)

MariaDB [(none)]> show engines;
+--------------------+---------+-------------------------------------------------------------------------------------------------+--------------+------+------------+
| Engine             | Support | Comment                                                                                         | Transactions | XA   | Savepoints |
+--------------------+---------+-------------------------------------------------------------------------------------------------+--------------+------+------------+
| CSV                | YES     | Stores tables as CSV files                                                                      | NO           | NO   | NO         |
| MRG_MyISAM         | YES     | Collection of identical MyISAM tables                                                           | NO           | NO   | NO         |
| MEMORY             | YES     | Hash based, stored in memory, useful for temporary tables                                       | NO           | NO   | NO         |
| Aria               | YES     | Crash-safe tables with MyISAM heritage. Used for internal temporary tables and privilege tables | NO           | NO   | NO         |
| MyISAM             | YES     | Non-transactional engine with good performance and small data footprint                         | NO           | NO   | NO         |
| SEQUENCE           | YES     | Generated tables filled with sequential values                                                  | YES          | NO   | YES        |
| Mroonga            | YES     | CJK-ready fulltext search, column store                                                         | NO           | NO   | NO         |
| PERFORMANCE_SCHEMA | YES     | Performance Schema                                                                              | NO           | NO   | NO         |
| InnoDB             | DEFAULT | Supports transactions, row-level locking, foreign keys and encryption for tables                | YES          | YES  | YES        |
+--------------------+---------+-------------------------------------------------------------------------------------------------+--------------+------+------------+
9 rows in set (0.000 sec)

MariaDB [(none)]> show variables like 'mroonga_%';
+----------------------------------------+----------------------+
| Variable_name                          | Value                |
+----------------------------------------+----------------------+
| mroonga_action_on_fulltext_query_error | ERROR_AND_LOG        |
| mroonga_boolean_mode_syntax_flags      | DEFAULT              |
| mroonga_condition_push_down_type       | ONE_FULL_TEXT_SEARCH |
| mroonga_database_path_prefix           |                      |
| mroonga_default_parser                 | TokenBigram          |
| mroonga_default_tokenizer              | TokenBigram          |
| mroonga_default_wrapper_engine         |                      |
| mroonga_dry_write                      | OFF                  |
| mroonga_enable_operations_recording    | ON                   |
| mroonga_enable_optimization            | ON                   |
| mroonga_libgroonga_embedded            | OFF                  |
| mroonga_libgroonga_support_lz4         | ON                   |
| mroonga_libgroonga_support_zlib        | ON                   |
| mroonga_libgroonga_support_zstd        | OFF                  |
| mroonga_libgroonga_version             | 10.0.4               |
| mroonga_lock_timeout                   | 900000               |
| mroonga_log_file                       | groonga.log          |
| mroonga_log_level                      | NOTICE               |
| mroonga_match_escalation_threshold     | 0                    |
| mroonga_max_n_records_for_estimate     | 1000                 |
| mroonga_query_log_file                 |                      |
| mroonga_vector_column_delimiter        |                      |
| mroonga_version                        | 10.03                |
+----------------------------------------+----------------------+
23 rows in set (0.001 sec)

rootパスワード設定

  • mysql_secure_installationを使用して芙蓉なアカウントやテーブルを削除
$ mysql_secure_installation

$ sudo /usr/bin/mysqladmin -uroot password 'password'
$ mysql_secure_installation

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user. If you've just installed MariaDB, and
haven't set the root password yet, you should just press enter here.

Enter current password for root (enter for none):
ERROR 1698 (28000): Access denied for user 'root'@'localhost'
Enter current password for root (enter for none):
OK, successfully used password, moving on...

Setting the root password or using the unix_socket ensures that nobody
can log into the MariaDB root user without the proper authorisation.

You already have your root account protected, so you can safely answer 'n'.

Switch to unix_socket authentication [Y/n] n
 ... skipping.

You already have your root account protected, so you can safely answer 'n'.

Change the root password? [Y/n] Y
New password:
Re-enter new password:
Password updated successfully!
Reloading privilege tables..
 ... Success!


By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] Y
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] y
 ... Success!

By default, MariaDB comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] Y
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] Y
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!

各種設定

トークナイザーの設定

my.cnfまたはSQL内で mroonga_default_tokenizer 変数を指定することでも指定できます。my.cnfで指定するとMySQLを再起動しても値は変更されたままですが、反映させるために再起動しなければいけません。一方、SQLで指定した場合はすぐに設定が反映されますが、MySQLが再起動すると設定は失われます。
  • my.cnf:
[mysqld]
mroonga_default_tokenizer=TokenBigram
mysql> SET GLOBAL mroonga_default_tokenizer = TokenBigram;
Query OK, 0 rows affected (0.00 sec)

ノーマライザー

  • ノーマライザーの説明
groonga/mroongaが標準で備える文字列正規化機能(ノーマライザ・normalizer)として、
いわゆるgroonga独自のnormalizer(NormalizerAuto)と呼ばれるもがあります。
これは、大文字・小文字だけでなく、全角・半角を同一視できるという
UnicodeのNFKCを用いた機能です。
  • 設定 照合順序collation_connection で設定するか、Mroonga(Groonga)のノーマライザーを用いて設定する。今回は、collation_connectionでは、utf8mb4_general_ciを設定し、(utf8_unicode_ciを使用すると全角・半角を同一視しない。)テーブル単位でノーマライザーをNormalizerAutoに設定することで、全角/半角のゆれを吸収する。

  • 設定方法 テーブルクリエイト時にNormalizerAutoを指定する。

table_create Dictionary TABLE_HASH_KEY ShortText --normalizer NormalizerAuto
# [[0, 1337566253.89858, 0.000355720520019531], true]

Engine(動作モード)

  • Mroongaの動作モードの説明
Mroongaには2つの動作モードがあります。

1つが「ストレージモード」で、データストアも検索機能もすべてGroongaを使うモードです。これがデフォルトのモードです。上述の参照ロックフリーなGroongaの性能特性をフルに活かした高速なデータ更新・全文検索・位置情報検索が特長です。一方、トランザクションなどの機能は提供されません。

もう1つが「ラッパーモード」で、MyISAMやInnoDBといった他のストレージエンジンに 全文検索機能だけ を追加するモードです。このモードではトランザクションなど他のストレージエンジンがサポートしている機能に加えてGroongaの高速な全文検索機能を利用することができます。一方、Groongaの参照ロックフリーな特性は活かすことができません。また、更新処理は他のストレージエンジンがボトルネックになることが多いでしょう。
  • Engine(動作モード)のデフォルト指定

    • デフォルト指定
      sudo vim /etc/my.cnf.d/server.cnf [mysql] default_storage_engine=Mroonga

    • ストレージモード(テーブル作成時
      CREATE TABLE diaries ( id INT PRIMARY KEY AUTO_INCREMENT, content VARCHAR(255), FULLTEXT INDEX (content) ) ENGINE = Mroonga DEFAULT CHARSET utf8;

      • ラッパーモード(テーブル作成時)
        SQL のコメントを利用して COMMENT = 'engine "InnoDB"' のよ指定するようになっています。 CREATE TABLE diaries ( id INT PRIMARY KEY AUTO_INCREMENT, content VARCHAR(255), FULLTEXT INDEX (content) ) ENGINE = Mroonga DEFAULT CHARSET utf8mb4 COMMENT = 'engine "InnoDB"';
  • ラッパーモード使用時の注意点

Mroongaのラッパーモードは「データは任意のストレージエンジンに」「転置索引はGroonga上に」作るモードであって、飽くまでGroonga上ではトランザクションは利かない。
mysql56> ALTER TABLE t1 DISABLE KEYS;
mysql56> ALTER TABLE t1 ENABLE KEYS;
↑rollbackした場合には、↓都度Groonga上の転置索引を再作成する必要はある。

MariadbにおけるMroongaのシステム変数一覧

https://mariadb.com/kb/en/mroonga-system-variables/#mroonga_log_level

MySQLの設定

設定ファイル

$# sudo cat  /etc/my.cnf.d/server.cnf
#
# 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]

[client]
default_character_set=utf8mb4

# this is only for the mysqld standalone daemon
[mysqld]
log-bin=mysql-bin
unix_socket=OFF
collation-server=utf8mb4_bin
character_set_client=utf8mb4
character_set_server=utf8mb4
character_set_filesystem=utf8mb4
character_set_server=utf8mb4
innodb_print_all_deadlocks=1
log_error=/var/lib/mysql/error.log
log_warnings=2
max_allowed_packet=104857600
server_audit_logging=ON
plugin_load=server_audit=server_audit.so

# Slow Query
#slow_query_log=5
#long-query-time=5
#log-queries-not-using-indexes
#log-slow-admin-statements
#slow_query_log_file=/var/lib/mysql/slow.log
#log_output=FILE

# Mroonga
mroonga_default_tokenizer=TokenBigram
mroonga_log_level=NOTICE
#mroonga_query_log_file=mroonga.log

#
# * Galera-related settings
#
[galera]
# Mandatory settings
#wsrep_on=ON
#wsrep_provider=
#wsrep_cluster_address=
#binlog_format=row
#default_storage_engine=InnoDB
#innodb_autoinc_lock_mode=2
#
# Allow server to accept connections on all interfaces.
#
#bind-address=0.0.0.0
#
# Optional setting
#wsrep_slave_threads=1
#innodb_flush_log_at_trx_commit=0

# this is only for embedded server
[embedded]

# This group is only read by MariaDB servers, not by MySQL.
# If you use the same .cnf file for MySQL and MariaDB,
# you can put MariaDB-only options here
[mariadb]

# This group is only read by MariaDB-10.4 servers.
# If you use the same .cnf file for MariaDB of different versions,
# use this group for options that older servers don't understand
[mariadb-10.4]

文字コードと照会順序設定

  • 説明
    今回は_binを使用
    ci: 大文字と小文字が区別されない
    cs: 大文字と小文字が区別される
    _bin: バイナリ

  • Collation(照会順序の設定)

    • 照会順序についての説明はlinkを参照
  • 文字コードと照会順序確認

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

MariaDB [(none)]> show variables like '%char%';
+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8mb4                    |
| character_set_connection | utf8mb4                    |
| character_set_database   | utf8mb4                    |
| character_set_filesystem | utf8mb4                    |
| character_set_results    | utf8mb4                    |
| character_set_server     | utf8mb4                    |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.001 sec)

MariaDB [(none)]> show variables like '%collation%';
+----------------------+--------------------+
| Variable_name        | Value              |
+----------------------+--------------------+
| collation_connection | utf8mb4_general_ci |
| collation_database   | utf8mb4_bin        |
| collation_server     | utf8mb4_bin        |
+----------------------+--------------------+
3 rows in set (0.001 sec)

監査ログの有効化

  • 設定確認
MariaDB [(none)]> SHOW GLOBAL VARIABLES LIKE "server_audit%";
+-------------------------------+-----------------------+
| Variable_name                 | Value                 |
+-------------------------------+-----------------------+
| server_audit_events           |                       |
| server_audit_excl_users       |                       |
| server_audit_file_path        | server_audit.log      |
| server_audit_file_rotate_now  | OFF                   |
| server_audit_file_rotate_size | 1000000               |
| server_audit_file_rotations   | 9                     |
| server_audit_incl_users       |                       |
| server_audit_logging          | ON                    |
| server_audit_mode             | 0                     |
| server_audit_output_type      | file                  |
| server_audit_query_log_limit  | 1024                  |
| server_audit_syslog_facility  | LOG_USER              |
| server_audit_syslog_ident     | mysql-server_auditing |
| server_audit_syslog_info      |                       |
| server_audit_syslog_priority  | LOG_INFO              |
+-------------------------------+-----------------------+
15 rows in set (0.001 sec)

MariaDB [(none)]> select PLUGIN_NAME,PLUGIN_STATUS from INFORMATION_SCHEMA.PLUGINS where PLUGIN_NAME = 'SERVER_AUDIT';
+--------------+---------------+
| PLUGIN_NAME  | PLUGIN_STATUS |
+--------------+---------------+
| SERVER_AUDIT | ACTIVE        |
+--------------+---------------+
1 row in set (0.000 sec)

バックアップ

mariadb/mroongaのバックアップ

結論

ラッパーモードであれば、mysqldumpをsingle-transactionで使うのが良さそう。 ストレージモードはトランザクションが使えないので、lock-all-tableしてからmysqldumpする必要がある。 書き込みできない時間が発生すること許容できる場合は、ROLLBACKが利くのは「データの格納されているInnoDB部分」だけ というラッパーモードの仕様があるため、ストレージモードを使ったほうが良い(と思う) https://yoku0825.blogspot.com/2014/04/mroongainnodb.html)

参考

https://www.slideshare.net/yoku0825/how-to-backup-your-mroonga-database

検討した手段

Backup Shell

  • shell
#!/bin/bash
set -o pipefail

# S3バックアップの保存期間指定
period=14

# MySQLrootパスワード
rootpass=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

backup_date=$(date +%Y%m%d)
delete_date=$(date +%Y%m%d -d "${backup_date} ${period} days ago")

# 指定したDBのスキーマおよびデータをすべて吐き出す
mysqldump --single-transaction --flush-logs --master-data=2 --all-databases -u root -p$rootpass | pigz -c | aws s3 cp - s3://s3_bucket/mariadb_backup/db_${backup_date}.gz

# 旧世代バックアップの削除
if [[ $? == 0 ]]; then
  aws s3 rm s3://s3_bucket/mariadb_backup/db_${delete_date}.gz
fi
  • cron 登録
sudo echo "0 3 * * * root /root/mysql-backup.sh" > /etc/cron.d/mysql-backup.sh  

mysqldumpオプションの説明

  • --single-transaction データベースがすべて「innodb」であればシングルトランザクションオプションを使ったダンプを行う事で ロックせずにバックアップする事ができる。MyISAMや他のエンジンで作られたテーブルが入っていると無理。(今回はラッパーモードなので大丈夫)

  • --flush-logs

    • 必要性
ざっくりいうと復元の際に便利だからですね。
省略すると、作業手順が増えるので、復旧に時間がかかると言ったことが考えられます。
ダンプからリストアした場合は、ダンプ取得時の古い状態になります。
バイナリログからロールフォワードリカバリを行えば、ダンプ取得後~障害発生直前までに戻せます。
--flush-logs は バイナリログがローテートされて新しいファイルが作成されるオプションです。
復元時は 新しいバイナリログの先頭から リカバリを行えば良く、古いバイナリログは無視できます。
オプションを省略した場合は、バイナリログから復元ポイントを探して、そのポジションを --start-positon で指定する必要があります。
  • バイナリーログの有効化
# 有効化されていないと以下のエラーが出力される
$ ./mysql-backup.sh
mysqldump: Couldn't execute 'SELECT BINLOG_GTID_POS('', '0')': You are not using binary logging (1381)

# 設定
vim /etc/my.cnf.d/server.cnf
[mysqld]
log-bin=mysql-bin

ログ

  • MySQLのログ

  • Mroongaのログ(groonga.log)

$ ls -al /var/lib/mysql
  • ログレベル
mroonga_log_level=NOTICE

ログローテート

  • cat /etc/logrotate.d/mysql
# This logname can be set in /etc/my.cnf
# by setting the variable "log-error"
# in the [mysqld] section as follows:
#
# [mysqld]
# log-error=/var/lib/mysql/mysqld.log
#
# If the root user has a password you have to create a
# /root/.my.cnf configuration file with the following
# content:
#
# [mysqladmin]
# password = <secret>
# user= root
#
# where "<secret>" is the password.
#
# ATTENTION: This /root/.my.cnf should be readable ONLY
# for root !

/var/lib/mysql/error.log {
        create 600 mysql mysql
        dateext
        notifempty
        daily
        rotate 360
        missingok
        nocompress
    postrotate
        # just if mysqld is really running
        if test -x /usr/bin/mysqladmin && \
           /usr/bin/mysqladmin ping &>/dev/null
        then
           /usr/bin/mysqladmin --defaults-extra-file=/root/.my.cnf flush-logs \
              flush-engine-log flush-general-log flush-slow-log
        fi
    endscript
}


/var/lib/mysql/audit.log {
        create 600 mysql mysql
        dateext
        notifempty
        daily
        rotate 360
        missingok
        nocompress
    postrotate
        # just if mysqld is really running
        if test -x /usr/bin/mysqladmin && \
           /usr/bin/mysqladmin ping &>/dev/null
        then
           /usr/bin/mysqladmin --defaults-extra-file=/root/.my.cnf flush-logs \
              flush-engine-log flush-general-log flush-slow-log
        fi
    endscript
}


/var/lib/mysql/groonga.log {
        create 600 mysql mysql
        dateext
        notifempty
        daily
        rotate 360
        missingok
        nocompress
    postrotate
        # just if mysqld is really running
        if test -x /usr/bin/mysqladmin && \
           /usr/bin/mysqladmin ping &>/dev/null
        then
           /usr/bin/mysqladmin --defaults-extra-file=/root/.my.cnf flush-logs \
              flush-engine-log flush-general-log flush-slow-log
        fi
    endscript

参考

Mroongaが導入できたら、次はInnoDBをMroongaへ切替ます。
ストレージエンジンはテーブルごとに設定が可能であり、現在ストレージエンジンに何を採用しているかはSHOW CREATE TABLEで確認できます。

ストレージエンジンの切替はALTER TABLEで行えます。
内部的にはスナップショットをとって、そのデータをダンプする事でロックする事なく
整合性のとれたダンプを取る事が可能です。
通常のmysqldumpと異なる点は、ダンプデータが「ダンプが終了した時の状態」ではなく
「ダンプを開始した時の状態」であるという点です。

https://www.seeds-std.co.jp/blog/creators/2015-07-31-213123/

その他設定

  • TimeZone変更
sudo ln -sf  /usr/share/zoneinfo/Asia/Tokyo /etc/localtime
sudo vim /etc/sysconfig/clock

#ZONE="UTC"
ZONE="Asia/Tokyo"
UTC=true
  • swapfile の作成
sudo dd if=/dev/zero of=/opt/swap bs=1024 count=16777216
sudo chmod 600 /opt/swap
sudo mkswap /opt/swap
sudo swapon /opt/swap
sudo swapon -s
sudo vi /etc/fstab
/opt/swap swap swap defaults 0 0

https://aws.amazon.com/jp/premiumsupport/knowledge-center/ec2-memory-swap-file/

  • /etc/sysctl.confの設定
vm.swappiness = 1
vm.overcommit_memory = 2
vm.overcommit_ratio = 99
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.core.somaxconn = 10240
net.core.netdev_max_backlog = 10240
net.ipv4.tcp_rmem = 4096 349520 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
net.ipv4.tcp_no_metrics_save = 1
net.ipv4.tcp_rfc1337 = 1
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 10
net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_max_syn_backlog = 10240
net.ipv4.tcp_keepalive_intvl = 3
net.ipv4.tcp_keepalive_probes = 2
net.ipv4.tcp_keepalive_time = 10
net.ipv4.ip_local_port_range = 10240 65535

MySQLコマンド一覧

  • テーブルに設定されたコメントを確認したい場合
MariaDB [test]> use test;
MariaDB [test]> SELECT table_name, table_comment FROM information_schema.tables WHERE table_schema = database();
+------------+-----------------+
| table_name | table_comment   |
+------------+-----------------+
| diaries    | engine "InnoDB" |
+------------+-----------------+
1 row in set (0.000 sec)