見出し画像

MySQLからMariaDBに乗り換えてみた

そろそろ、乗り換えの時期かな、と思って、ね。

現在の設定内容を確認&退避

現在の設定内容をDropBox上に退避する為、Finder上で検索。

↓…「若気の至り」ってヤツ?
/private/etc/my.cnf.2013.bkup

↓…brewで入れた、過去のMySQL時代のものから引き継いでる設定
/usr/local/etc/my.cnf

/usr/local/etc/my.cnf.default

↓…あなた、どなた様?
/Applications/AMPPS/conf/my.cnf
/Applications/AMPPS/conf/original-my.cnf
/Applications/AMPPS/mysql/etc/my.cnf

すっかり忘れていたよ『AMPPS』なんて。

取り敢えず、退避しておこう。

brewで入れたMySQLを削除

Qiita「どうしよう!困った時のMac上のMySQLのアンインストール&再インストール、動作確認手順」に軽く目を通して、実行。

↓…サービスを停止
$ brew services stop mysql

↓…サービスの起動状態を一覧形式でリストアップ
$ brew services list

↓…潔く、サヨナラ。「$ brew remove フォーミュラ名」でもアンインストールが走る
$ brew uninstall mysql

↓…MySQLの設定ファイルですね。退避済みなので、サヨナラ。
$ sudo rm -rf /usr/local/etc/my.cnf

↓…MySQLの「データ」ディレクトリですね。サヨナラ。
$ sudo rm -rf /usr/local/var/mysql

この時点で、下記を一通り(outdatedなものがあれば、「brew upgrade フォーミュラ名」で更新)実施。その後、macOSを再起動(念の為)。

↓…System Integrity Protection 状態の確認
$ csrutil status

↓…重篤なエラーが出てない限りは、基本無視で
$ brew doctor

↓…brewの配信フォーミュラリスト(caskも含める様、指定済み)をローカルに同期。この時点で同時にoutdateなフォーミュラが、強調表示されてるけどね。
$ brew update

↓…outdateなフォーミュラを改めてリストアップ
$ brew outdated

「/usr/local/Cellar/mariadb/バージョン番号/share/mysql」フォルダ内の「mysql_system_tables.sql」には、global_privのCREATE TABLE文らしきものがあるが、VirusBusterのTCP監視が正常に起動してなかったり、macOSにキャッシュが溜まりすぎてると、どうも、テーブル「mysql.global_priv」生成迄辿り着けないみたい。

brewでMariaDBをインストール

では。MariaDBを投入。

↓…ヨロシクな。
$ brew install mariadb

(略)

↓…本体に先立ち「mecab」「mecab-ipadic」「msgpack」「groonga」なんてのも入る様ですな。
Installing dependencies for mariadb: mecab, mecab-ipadic, msgpack and groonga

==> Installing mariadb dependency: mecab

==> Installing mariadb dependency: mecab-ipadic
==> Caveats
To enable mecab-ipadic dictionary, add to /usr/local/etc/mecabrc:
  dicdir = /usr/local/lib/mecab/dic/ipadic

==> Installing mariadb dependency: msgpack

==> Installing mariadb dependency: groonga

==> Installing mariadb
==> /usr/local/Cellar/mariadb/バージョン番号/bin/mysql_install_db --verbose --user=macOSのログインユーザー --basedir=/usr/local/Cellar/mariadb/バージョン番号 --datadir=/usr/local/var/mysql --tmpdir=/tmp
==> Caveats
A "/etc/my.cnf" from another install may interfere with a Homebrew-built server starting up correctly.

MySQL is configured to only allow connections from localhost by default

To have launchd start mariadb now and restart at login:
  brew services start mariadb
Or, if you do not want/need a background service you can just run:
  mysql.server start
==> Summary
🍺  /usr/local/Cellar/mariadb/10.5.6: 782 files, 182.0MB
==> Caveats
==> mecab-ipadic
To enable mecab-ipadic dictionary, add to /usr/local/etc/mecabrc:
  dicdir = /usr/local/lib/mecab/dic/ipadic
==> mariadb
A "/etc/my.cnf" from another install may interfere with a Homebrew-built server starting up correctly.

MySQL is configured to only allow connections from localhost by default

To have launchd start mariadb now and restart at login:
  brew services start mariadb
Or, if you do not want/need a background service you can just run:
  mysql.server start

MariaDBの依存ライブラリ

…インストール時に、依存物として入った「mecab」「mecab-ipadic」「msgpack」「groonga」って、何者なんだいbrewさん?

$ brew info mecab
mecab: stable 0.996 (bottled)
Yet another part-of-speech and morphological analyzer
https://taku910.github.io/mecab/
Conflicts with:
  mecab-ko (because both install mecab binaries)


$ brew info mecab-ipadic
mecab-ipadic: stable 2.7.0-20070801 (bottled)
IPA dictionary compiled for MeCab
https://taku910.github.io/mecab/
==> Dependencies
Required: mecab ✔
==> Caveats
To enable mecab-ipadic dictionary, add to /usr/local/etc/mecabrc:
  dicdir = /usr/local/lib/mecab/dic/ipadic


$ brew info msgpack
msgpack: stable 3.3.0 (bottled), HEAD
Library for a binary-based efficient data interchange format
https://msgpack.org/
License: BSL-1.0
==> Dependencies
Build: cmake ✘


$ brew info groonga
groonga: stable 10.0.7 (bottled), HEAD
Fulltext search engine and column store
https://groonga.org/
License: LGPL-2.1-or-later
==> Dependencies
Build: pkg-config ✔
Required: mecab ✔, mecab-ipadic ✔, msgpack ✔, openssl@1.1 ✔, pcre ✔

ふむ。全文検索にまつわるライブラリーたちなんだね。→Qiita「Mecab(形態素解析)で遊んでみた!」、セマンティックウェブ・ダイアリー「日本語処理用にmecab-ipadicをインストール」、MessagePackカラムストア機能付き全文検索エンジンGroonga

インストール確認とサービス登録

続いて、PIDファイル生成、インストール確認、サービス登録。

↓…「システム環境設定→共有→コンピュータ名」で設定した値を元にした「コンピュータ名.local.pid」が生成される筈。
$ touch /usr/local/var/mysql/$(uname -n).pid

↓…ちゃんとインストールされてるね。
$ which mysql
/usr/local/bin/mysql

$ which mysqld
/usr/local/bin/mysqld

$ which mariadb
/usr/local/bin/mariadb

↓…サービス登録
$ brew services start mariadb
==> Successfully started `mariadb` (label: homebrew.mxcl.mariadb)

↓…サービスの起動状態を一覧形式でリストアップ
$ brew services list
Name    Status  User  Plist
emacs   stopped       
httpd   started ログインユーザー ~/Library/LaunchAgents/homebrew.mxcl.httpd.plist
mariadb started ログインユーザー ~/Library/LaunchAgents/homebrew.mxcl.mariadb.plist
php     started ログインユーザー ~/Library/LaunchAgents/homebrew.mxcl.php.plist
unbound stopped       

thoughtbot「Starting and Stopping Background Services with Homebrew」(2014-01-21)では、下記の様になってる(MariaDBをMySQLに読み替えても可)。

ログイン時にlaunchdにMariaDBを起動させるには:
	$ ln -sfv /usr/local/opt/mariadb/*.plist ~/Library/LaunchAgents

それから、すぐにmysqlを起動させる:
	$ launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mariadb.plist

或いはlaunchctlによる起動を望まない場合:
	$ mysql.server start

2014年時点では、ユーザー毎のLaunchAgentsフォルダに、plistのシンボリックリンクを手動作成させて、launchctl登録させるようになってる。

のだけど、2020年現在では、「brew services start フォーミュラ名」を使って、brewにplistコピペ&サービス登録を任せてしまおう。

構成ファイル「my.cnf」の検索ルール(mysqlクライアント、mariadbクライアント)

構成ファイル「my.cnf」の検索ルールを(一応)確認。同じものにならないと、どこかがおかしいんだけどね。

$ mysql --help | grep my.cnf
/usr/local/etc/my.cnf ~/.my.cnf 
	order of preference, my.cnf, $MYSQL_TCP_PORT,

$ mariadb --help | grep my.cnf
/usr/local/etc/my.cnf ~/.my.cnf 
	order of preference, my.cnf, $MYSQL_TCP_PORT,

mysqlクライアントの起動

ユーザー未指定で起動(ここで、VirusBusterのTCPポート監視が反応すれば、正常と判断できるかも?)。

テーブル「mysql.global_priv」が存在してれば、「mysql_secure_installation」を使う準備が出来てると判断できる。

$ mysql

Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 3
Server version: 10.5.6-MariaDB Homebrew

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 databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              | ←用があるのは、このデータベース
| performance_schema |
| test               | ←本番環境からはdropすべき、テスト用データベース
+--------------------+
4 rows in set (0.001 sec)

↓…データベース「mysql」に絞り込み
MariaDB [(none)]> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
テーブルとカラム名の補完のためのテーブル情報を読込み。この機能をオフにすると、-A付き起動を高速化できます。

Database changed

↓…生成済みのテーブルを一覧表示
MariaDB [mysql]> show tables;
+---------------------------+
| Tables_in_mysql           |
+---------------------------+
| column_stats              |
| columns_priv              |
| db                        |
| event                     |
| func                      |
| general_log               |
| global_priv               | ←コイツが居ないとセキュリティ設定がアボートする!
| gtid_slave_pos            |
| help_category             |
| help_keyword              |
| help_relation             |
| help_topic                |
| index_stats               |
| innodb_index_stats        |
| innodb_table_stats        |
| plugin                    |
| proc                      |
| procs_priv                |
| proxies_priv              |
| roles_mapping             |
| servers                   |
| slow_log                  |
| table_stats               |
| tables_priv               |
| time_zone                 |
| time_zone_leap_second     |
| time_zone_name            |
| time_zone_transition      |
| time_zone_transition_type |
| transaction_registry      |
| user                      |
+---------------------------+
31 rows in set (0.001 sec)

「alter」を使って、MySQL/MariaDBのrootアカウント用に、パスワードを設定する。

MariaDB [mysql]> alter user 'root'@'localhost' identified by 'rootアカウント用パスワード';
Query OK, 0 rows affected (0.011 sec)

MariaDB [mysql]> exit
Bye

「alter」の結果が「0 rows affected」なので、何もレコードが変更されてないのか?と不安になるのだけど、どうやら、気にしなくて良いらしい?

セキュリティ設定

「mysql_secure_installation」を使って、「rootアカウントにパスワード設定」「匿名ユーザーの削除」「rootアカウントのリモートログイン禁止」「testデータベースの削除」していく。

futon.org「MariaDB 10.4.1〜のユーザー認証がカオスな話(Unix_Socket)」に拠れば、不安になるけども。

$ mysql_secure_installation

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!
注:このスクリプトのすべての部分を実行することは、本番環境で使用されているすべてのMariaDBサーバーに推奨されています。各ステップを注意深くお読みください。

先程「alter」で設定した「MySQL/MariaDBのrootアカウント用パスワード」を入力し、rootアカウントを保護させる。

In order to log into MariaDB to secure it, we will need the current password for the root user. If you have just installed MariaDB, and have not set the root password yet, you should just press enter here.
MariaDBへのログインをセキュアにするには、rootアカウントの現在のパスワードが必要です。MariaDBをインストールしたばかりで、まだrootパスワードを設定していない場合は、ここでEnterキーを押してください。

↓…「パスワード」を入力
Enter current password for root (enter for none): 
(グローバル・アクセス用)rootの現在のパスワードを入力します:

rootアカウントが既に保護されているので、unix_socket認証への切り替えをスキップさせる。

Setting the root password or using the unix_socket ensures that nobody can log into the MariaDB root user without the proper authorisation.
「rootパスワードを設定する」または「unix_socketを使用する」ことで、適切な権限がないと誰もMariaDBのrootユーザーにログインできないことを保証します。

↓…事前に「alter」でrootアカウントのパスワードを設定してる場合に、表示される
You already have your root account protected, so you can safely answer 'n'.
rootアカウントは既に保護されているので、安全に「n」と答えることができます。

↓…「n」を入力
Switch to unix_socket authentication [Y/n] 
unix_socket認証に切り替える [Y/n] 

因みに、テーブル「mysql.global_priv」が存在してないと、ここで処理がアボートされる。

ERROR 1146 (42S02) at line 1: Table 'mysql.global_priv' does not exist
Failed!
ERROR 1146 (42S02) at line 1: テーブル 'mysql.global_priv' が存在しない
失敗!

Cleaning up...
片付け中…

rootアカウントのパスワードを、ここで別のものに変更(≒ここで特権テーブルに更新が掛かる)させるか、そのままスキップさせる。

You already have your root account protected, so you can safely answer 'n'.
rootアカウントは既に保護されているので、安全に「n」と答えることができます。

↓…「n」を入力してスキップするか、「Y」でパスワードを変更
Change the root password? [Y/n] 
rootパスワードを変更しますか?[Y/n] 

↓…新たな「MySQL/MariaDBのrootアカウント用パスワード」を入力
New password: 
Re-enter new password: 

「匿名ユーザー」を削除させる。

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.
デフォルトでは、MariaDBインストールには匿名ユーザーが設定されており、ユーザーアカウントを作成しなくても誰でもMariaDBにログインできるようになっています。これはテスト用であり、インストールを少しスムーズに行なうためのものです。本番環境に移行する前に削除してください。

↓…「Y」を入力する
Remove anonymous users? [Y/n] 
匿名ユーザーを削除しますか?[Y/n]

「rootアカウントのリモートログイン」を禁止させる。

Normally, root should only be allowed to connect from 'localhost'.  This ensures that someone cannot guess at the root password from the network.
通常、rootは'localhost'からのみ接続を許可されるべきです。これにより、誰かがネットワークからrootのパスワードを推測できないようにします。

↓…「Y」を入力する
Disallow root login remotely? [Y/n] 
リモートでのrootログインを禁止しますか?[Y/n]

「testデータベース」「testデータベースへのアクセス特権」の順番で削除させる。

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.
デフォルトでは、MariaDBには誰でもアクセスできる「test」という名前のデータベースが付属しています。これはテスト用であり、本番環境に移行する前に削除する必要があります。

↓…「Y」を入力する
Remove test database and access to it? [Y/n] 
testデータベースを削除しますか?[Y/n]

「特権テーブル」に更新を掛ける。

Reloading the privilege tables will ensure that all changes made so far will take effect immediately.
特権テーブルをリロードすると、これまでに行なったすべての変更が直ちに有効になります。

↓…「Y」を入力する
Reload privilege tables now? [Y/n] 
今すぐ特権テーブルをリロードしますか?[Y/n]

これで、MySQL/MariaDBへのログインがセキュアになってる筈。

Cleaning up...
片付け中…

All done!  If you have completed all of the above steps, your MariaDB installation should now be secure.
すべてが済みました! 上記の手順がすべて完了していれば、MariaDBのインストールは安全な状態になっている筈です。

Thanks for using MariaDB!
MariaDBをご利用いただきありがとうございました!

rootアカウントのパスワードを入力し、無事にログインできるか?

$ mysql -u root -p

↓…「パスワード」を入力
Enter password: 

Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 18
Server version: 10.5.6-MariaDB Homebrew

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)]> 

…無事にログイン出来ました!

データベースの状態確認

「mysql_secure_installation」でセキュア化した後、こうなる。

$ mysql -u root -p
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 19
Server version: 10.5.6-MariaDB Homebrew

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 databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
+--------------------+
3 rows in set (0.002 sec)
↑…テスト用データベースがdropされてる

MariaDB [(none)]> use mysql;
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
MariaDB [mysql]> select user, host from user;
+---------------+-----------+
| User          | Host      |
+---------------+-----------+
| mariadb.sys   | localhost |
| root          | localhost |
| ログインユーザー | localhost |
+---------------+-----------+
3 rows in set (0.001 sec)
↑…localhostからユーザー「mysql.infoschema」「mysql.session」「mysql.sys」が削除されて、ユーザー「mariadb.sys」、「ログインユーザー」が増えている。

ここで、別のターミナルシェルを上げて確認してみよう。

↓…TCPポート、通りますね。
$ nc -z -w1 -v 127.0.0.1 3306
Connection to 127.0.0.1 port 3306 [tcp/mysql] succeeded!

↓…こっちもいけてますね。
$ mysql -u root -p -h 127.0.0.1
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 21
Server version: 10.5.6-MariaDB Homebrew

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)]> exit
Bye

↓…構成ファイル「my.cnf」の検索ルール(mysqlデーモン)を確認。
$ mysqld --help --verbose | grep my.cnf

↓…なんか警告出てる? 「/usr/local/var/mysql/ は、大文字小文字を区別しねーから、lower_case_table_names=2にすっぞ」…良きに計らってくれたまえ。
[Warning] Setting lower_case_table_names=2 because file system for /usr/local/var/mysql/ is case insensitive

↓…なんかエラー出てる? 「エラー35:aria制御ファイル '/usr/local/var/mysql/aria_log_control' を排他的にロックできません。」「プラグイン'Aria'の、init関数がエラーを返しました。」「プラグイン'Aria'の、STORAGE ENGINEとしての登録に失敗しました。」
[ERROR] mysqld: Can not lock aria control file '/usr/local/var/mysql/aria_log_control' for exclusive use, error: 35. Will retry for 0 seconds
[ERROR] Plugin 'Aria' init function returned error.
[ERROR] Plugin 'Aria' registration as a STORAGE ENGINE failed.

↓…なんか警告出てる? 「テーブルmysql.pluginを開くことができませんでした:"不明なストレージエンジン'Aria'"」。いくつかのオプションがヘルプテキストから欠落している可能性があります。
[Warning] Could not open mysql.plugin table: "Unknown storage engine 'Aria'". Some options may be missing from the help text

↓…クライアントのものよりも、若干ルールが増えてる?
/usr/local/etc/my.cnf ~/.my.cnf 
	my.cnf, $MYSQL_TCP_PORT, /etc/services, built-in default

…なんか、不吉なものを見た気がするが、見なかったことにしよう。

この記事が気に入ったらサポートをしてみませんか?