:>/dev/null

ラガードエンジニアの不撓不屈の精神/unlearning/go beyond

ゴールデンサークル

ゴールデンサークルとは

  • 「なぜやるのか?」から始めて「どうやってそれを実現するか?」を考え、「何を作るか」の順番で考える/伝えるというものです。誰でも考える事のように思えますが、肝なのは順序。一般の方とは、伝える順が逆なんだとか。
    • NG What(何をするのか) → How(どうやるのか)
    • OK Why(なぜやるのか/Vision) → How(どのようにやるのか/Strategy) → What(何をやるのか/Product)

f:id:oguguman:20191013202440p:plain

appleの新製品発表にみるゴールデンサークル①

OK
WHY:現状に挑戦し、他者とは違う考え方をする。それが私たちの信条です。
HOW:製品を美しくデザインし、操作をシンプルにし、取り扱いを簡単にすることに挑戦しています。
WHAT:その結果、すばらしいコンピュータが誕生しました。

NG
WHAT:これは素晴らしいスペックのパソコンです!
HOW:美しいデザイン、動画編集もサクサク動きます!いかがですか?

Tivaの製品発表にみるゴールデンサークル②

WHY:自分の人生を自分でコントロールする。
HOW:そんなあなたにぴったりの製品を開発しました。
WHAT:あなたが今見ている生放送中の番組を一時停止したり、CMを飛ばしたり、好きな番組を勝手に録画してくれるんです。

まとめ

日常生活していて無意識レベルでWhatから思考しがちなので、伝える順序を意識しWhyから考える事を身につける癖を大切にする。

AWS EC2インスタンスのEBSボリュームディスク拡張

AWS EC2インスタンスのEBSボリュームディスクが不足したので拡張した時の学習メモ。
対象インスタンスにアタッチ済みボリューム拡張を↓この辺を参考にして事前に済ませておく。

https://docs.aws.amazon.com/ja_jp/AWSEC2/latest/UserGuide/console-modify.htmldocs.aws.amazon.com

参考に手順を記載。
EC2→対象インスタンス→ルートデバイス→アタッチ済みEBS→(EBS画面へ推移)→アクション→ボリューム変更→変更後のボリュームサイズ指定

事前確認

fdisklsblkで現状確認

$ sudo fdisk -l
GPT PMBR size mismatch (16777215 != 209715199) will be corrected by w(rite).
ディスク /dev/xvda: 100 GiB, 107374182400 バイト, 209715200 セクタ
単位: セクタ (1 * 512 = 512 バイト)
セクタサイズ (論理 / 物理): 512 バイト / 512 バイト
I/O サイズ (最小 / 推奨): 512 バイト / 512 バイト
ディスクラベルのタイプ: gpt
ディスク識別子: 33E98A7E-CCDF-4AF7-8A35-DA18E704CDD4

デバイス     開始位置 最後から   セクタ サイズ タイプ
/dev/xvda1       4096 16777182 16773087     8G Linux ファイルシステム
/dev/xvda128     2048     4095     2048     1M BIOS 起動


$ lsblk
NAME    MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
xvda    202:0    0  100G  0 disk
└─xvda1 202:1    0    8G  0 part /

パーティション拡張

growpartを使ってパーティションを拡張

$ sudo growpart /dev/xvda 1
CHANGED: partition=1 start=4096 old: size=16773087 end=16777183 new: size=209711071,end=209715167

パーティションが正常に拡張したか確認

$ lsblk
NAME    MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
xvda    202:0    0  100G  0 disk
└─xvda1 202:1    0  100G  0 part /

ファイルシステム拡張

xfs_growfsを使ってxfsのファイルシステムも拡張を行う (ファイルシステム毎に実行コマンドが違う為、注意)
Amazon Linux (ext4)

$sudo resize2fs /dev/xvda1
resize2fs 1.42.12 (29-Aug-2014)
Filesystem at /dev/xvda1 is mounted on /; on-line resizing required
old_desc_blocks = 2, new_desc_blocks = 2
The filesystem on /dev/xvda1 is now 7863803 (4k) blocks long.

Amazon Linux 2 (xfs)

$ sudo xfs_growfs /dev/xvda1
meta-data=/dev/xvda1             isize=512    agcount=4, agsize=524159 blks
         =                       sectsz=512   attr=2, projid32bit=1
         =                       crc=1        finobt=1 spinodes=0
data     =                       bsize=4096   blocks=2096635, imaxpct=25
         =                       sunit=0      swidth=0 blks
naming   =version 2              bsize=4096   ascii-ci=0 ftype=1
log      =internal               bsize=4096   blocks=2560, version=2
         =                       sectsz=512   sunit=0 blks, lazy-count=1
realtime =none                   extsz=4096   blocks=0, rtextents=0
data blocks changed from 2096635 to 26213883

インスタンスにアタッチ済みボリュームの拡張が認識されているかOSから確認

$ df -h
ファイルシス   サイズ  使用  残り 使用% マウント位置
devtmpfs         2.0G     0  2.0G    0% /dev
tmpfs            2.0G     0  2.0G    0% /dev/shm
tmpfs            2.0G  556K  2.0G    1% /run
tmpfs            2.0G     0  2.0G    0% /sys/fs/cgroup
/dev/xvda1       100G  6.0G   94G    6% /
tmpfs            395M     0  395M    0% /run/user/1000
tmpfs            395M     0  395M    0% /run/user/0

まとめ

小さく初めて徐々に容量圧迫が発生するので、無停止でボリューム拡張が出来るのは助かる。
この辺の拡張が手軽に出来るのはPublicCloudの利点だと実感出来る。

また、今回では採用してないですが、「Amazon Web Services実践入門」では下記のボリュームを切り離す方法が説明されてます。

  • EC2インスタンスを停止する
    • 試してみましたが、インスタンスを停止しないと、後に実施する追加ボリュームの切り離しができなかったです。
  • 容量追加する対象ボリュームのスナップショットを取得
  • 対象ボリュームのスナップショットから新規ボリュームを作成する
    • サイズを変更する
    • EC2インスタンスと同じAvailability Zone(AZ)を選択する
  • 元のボリュームを切り離す(デタッチする)
  • サイズ変更した新ボリュームをアタッチする

ref)
https://qiita.com/foursue/items/bb288f32135ec8abac93

GitHubでForkしてPull Request〜Mergeするまでの手順

GitHubを使う事が無かったが、チーム開発する環境への移動に伴い基本知識を学んだ時の学習メモ。
GitHubを利用したことのない人が、Fork〜Pull Request〜Merge までの入門記事です。

  • 以下構築環境
    • クライアント:mac
    • SCM:GitHub
    • レポジトリ名:testrepo

GitHubへ接続するSSH鍵を生成

SSH鍵(秘密鍵/公開鍵)の生成

# ssh-keygen -t rsa -f ~/.ssh/id_rsa_git -N ''

生成された秘密鍵パーミッション変更

#chmod 600 ~/.ssh/id_rsa_git

GitHubSSH接続する場合の設定を作成

#vi ~/.ssh/config
 Host github.com
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa_git
    TCPKeepAlive yes
    IdentitiesOnly yes

GitHubSSH鍵登録

GitHubへログインし、鍵登録を行う

github.com

  1. アカウントメニュー→Settlersを選択
  2. プロファイル→SSH and GPG keys→New SSH keyを選択
  3. Titleに任意の値を設定
  4. Keyに生成した公開鍵(id_rsa_git.pub)の値をそのまま貼り付け
  5. 入力完了後、「Add SSH key」をクリックし登録

■ Fork〜Commit〜Pushまでの手順

Gitには①作業ディレクトリ、②ステージングエリア、③Gitディレクトリがあり、編集したファイルをGitディレクトリまで移動する事で、GitHubにプッシュできるようになる。 f:id:oguguman:20190920221531p:plain

対象リポジトリをFork(clone)する

$ git clone git@github.com:ogugu/testrepo.git

ユーザー情報設定

$ git config --global user.name "【ユーザー名】"
$ git config --global user.email "【メールアドレス】"

ファイル新規作成

$ cd testrepo/
$ vi hello.txt
$ git add hello.txt
※ ディレクトリ単位で纏めて $ git add ./
$ git commit -m "first commit"
※addとcommit を纏めて $ git commit -am "first commit"
[master (root-commit) ef06ff7] first commit
 1 file changed, 1 insertion(+)
 create mode 100644 hello.txt

$ git push
Enumerating objects: 3, done.
Counting objects: 100% (3/3), done.
Writing objects: 100% (3/3), 212 bytes | 212.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To github.com:ogugu/testrepo.git
 * [new branch]      master -> master
ignoreファイルの作成

git管理外のファイルを作成する場合、ignoreを使用

管理外のファイルを指定(ワイルドカード(*)指定可能)

$ vi .gitignore
*.log
ignore-test.txt

適用範囲について
ディレクトリ単位→作成したディレクトリ以下で有効
GItHub全体→~/.gitignore_global

除外ファイルを作成

$ vi ignore-test.txt

管理外設定をレポジトリへ反映

$ git add .gitignore
$ git add ignore-test.txt
The following paths are ignored by one of your .gitignore files:
ignore-test.txt
Use -f if you really want to add them.
fatal: no files added

$ git commit -m "ignore test"
[master 6f78cbf] ignore test
 1 file changed, 2 insertions(+)
 create mode 100644 .gitignore
$ git push
Branch戦略に関して

作成された段階のリポジトリには、次のように「master」ブランチのみが存在

$ git branch
* master

Gitで開発する際には、直接masterブランチを修正するのではなく、作業用のブランチを作成して、そちらを修正していきます。新たにブランチを作成することを「ブランチを切る」と呼びます。

Gitのブランチの切り方には、git-flow( https://github.com/nvie/gitflow) やGitHub Flow( https://gist.github.com/Gab-km/3705015) といったワークフローがある。それぞれメリット/デメリットを考慮し選択。
今回はGitHub Flowを採用し、masterブランチと作業ブランチを使うフローを採用。

branch作成

$ git branch develop
$ git branch
  develop
* master

branchへ移動

$ git checkout develop
Switched to branch 'develop'
$ git branch
* develop
  master

新規ファイル作成/Commitまでを実行

$ vi test-pr.txt
$ git add ./
$ git commit -a
# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
Committer: コミッター名

[develop 39c5671] Committer: pr-user
 1 file changed, 1 insertion(+)
 create mode 100644 test-pr.txt

GItHubへ反映

$ git push origin develop
Enumerating objects: 4, done.
Counting objects: 100% (4/4), done.
Delta compression using up to 4 threads
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 278 bytes | 278.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0)
remote:
remote: Create a pull request for 'develop' on GitHub by visiting:
remote:      https://github.com/ogugu/testrepo/pull/new/develop
remote:
To github.com:ogugu/testrepo.git
 * [new branch]      develop -> develop

■ Pull Reques〜Mergeまでの手順

GitHubサイトから作成したブランチを切り替えることにより、それぞれの状態をブラウザ上で確認可能 f:id:oguguman:20190920210524p:plain

Compare & pull request」もしくは「New pull request」をクリックし、Pull Requestを作成 f:id:oguguman:20190920211114p:plain

新たにコミットしたdevelopブランチから、masterブランチへ向けてプルリクエストを送るため、「base」(リクエスト受信側)が「master」ブランチ、「compare」(リクエスト送信側)が「develop」ブランチとなります。
f:id:oguguman:20190920211344p:plain

プルリクエストのタイトルと内容を記載し、「Create pull request」をクリックし、プルリクエストを作成。
f:id:oguguman:20190920212109p:plain

本来、プルリクエストを送る開発者と確認する開発者は別の人ですが、今回は説明の都合上、自分自身でプルリクエストを確認
作成したプルリクエストを開いて各タブで、それぞれ次の内容を確認

  • 「Conversation」:プルリクエストの説明
  • 「Commits」:コミット内容
  • 「Files changed」:ファイルの差分(変更内容) f:id:oguguman:20190920212851p:plain
プルリクエストの終了とマージ

「Merge pull request」をクリックし、プルリクエストを終了させる f:id:oguguman:20190920213258p:plain

developブランチがmasterブランチにマージされた状態になる

作業していたブランチが不要であれば「Delete branch」をクリックし、ブランチを削除
f:id:oguguman:20190920213724p:plain

以上で、作業していたdevelopブランチも削除され、修正内容がmasterブランチに反映された状態になる f:id:oguguman:20190920213910p:plain

ローカル環境を最新にする

masterブランチに移動

$ git branch
* develop
  master
$ git checkout master
Switched to branch 'master'
$ git branch
  develop
* master

masterブランチをリモート上の最新状態と同期

$ git pull
remote: Enumerating objects: 1, done.
remote: Counting objects: 100% (1/1), done.
remote: Total 1 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (1/1), done.
From github.com:ogugu/testrepo
   3763d90..2f06402  master     -> origin/master
Updating 3763d90..2f06402
Fast-forward
 test-pr.txt | 1 +
 1 file changed, 1 insertion(+)
 create mode 100644 test-pr.txt

Pull Requesがのマージによって、作業内容がmasterブランチに反映された状態でローカル環境も同期される

ローカルの作業ブランチも不要のため削除

$ git branch -d develop
Deleted branch develop (was 39c5671).

ブランチ削除時のエラーに関して
マージ反映前の状態で削除した場合、-dオプションでは以下のエラーが発生する。ローカルのmasterブランチがマージ前の状態であっても同様。

$ git branch -d develop
error: The branch 'develop' is not fully merged.
If you are sure you want to delete it, run 'git branch -D develop'.

マージ前のローカルブランチを強制的に削除したい場合は -dオプションではなく、-Dオプションを使います。

$ git branch -D develop

まとめ

Git/GitHubソースコードだけではなくシステムドキュメント等でも用いる事が可能な為、必須スキルとして学んでおく事は重要だと考えてます。
今回は基礎知識を覚えるまでに留まりましたが、使い倒す事でスキルを向上して行こうと思う。

ref)
https://employment.en-japan.com/engineerhub/entry/2017/01/31/110000#%E3%83%AA%E3%83%9D%E3%82%B8%E3%83%88%E3%83%AA%E3%81%AE%E3%83%96%E3%83%A9%E3%83%B3%E3%83%81%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6
https://keiilog.com/git-pull/
https://blog.qnyp.com/2013/05/28/pull-request-for-github-beginners/

MacのCPU温度、ファンスピードなどをターミナル表示する方法

夏場にPC(MacBook)を使用している場合、熱を多く持ち高熱(60℃後半)になることがしばしばあります。
FANはフル稼働していますが、排熱が間に合わず、熱暴走によって動作が重くなる/突然フリーズするなど発生する為、夏場の温度管理は必要です。
iStatsというソフトを使うとMacの各温度状態(CPUの温度、バッテリーの温度、メモリ周辺の温度、CPU/GPU ヒートパイプ周辺の温度など)が分かって便利。

インストール方法

# iStatsのインストール
sudo gem install iStats -n /usr/local/bin

# 実行
istats

# help(コマンド一覧)
istats -h

# 全てのセンサーをスキャンしてターミナルに表示
istats scan

# 全てのセンサー情報をistatsに表示
istats enable all
インストール時にエラー発生する場合
ERROR:  Could not find a valid gem '******' (>= 0), here is why:
          Unable to download data from https://rubygems.org/ - SSL_connect returned=1 errno=0 state=SSLv2/v3 read server hello A: tlsv1 alert protocol version (https://rubygems.org/latest_specs.4.8.gz)

下記リンクに従って対応
Bundler: How to troubleshoot RubyGems and Bundler TLS/SSL Issues

istatsの実行結果
f:id:oguguman:20190825201939p:plain

  • 上記結果の説明
    • CPU温度: 45.5℃
    • ファンスピード: 2001rpm(rpmは1分間あたりの回転数)
    • バッテリーの状態: Good
    • バッテリーの温度: 28.09℃

CPUの適正な温度
適正な温度に関して明確化な指針は不明ですが、上限値はノート型の場合は100℃近辺まで耐えられるようです。
適正値がわからない為、そこに達しない範囲で利用するのが無難かと思います。

アンインストール方法

# sudo gem uninstall iStats

XtraBackup(innobackupex)を使用したMySQLバックアップ(no-lock)

mysqldumpを使用したレプリケーション構築を作成するとします。このとき、mysqldumpに--master-dataを付与すると"FLUSH TABLES WITH READ LOCK" が発行され、一瞬のあいだ、全テーブルがロックが発生します。

mysqldump -uroot -pxxxxxxxx --single-transaction --master-data=2 --all-databases | gzip >  mysqldump.sql.gz  

2095627 Query FLUSH TABLES WITH READ LOCK
2095627 Query SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ
2095627 Query START TRANSACTION /*!40100 WITH CONSISTENT SNAPSHOT */
2095627 Query SHOW MASTER STATUS
2095627 Query UNLOCK TABLES

上記のような状況を回避して、MySQLマスターをロックせずレプリケーションを構築するためにXtraBackupを利用します。
通常、innobackupexを用いたバックアップを実行した場合、ロックを発行するのですが、 --no-lockで回避可能です。
--no-lock オプションを付与すると、binlogのポジションが記述されるはずの xtrabackup_binlog_info ファイルが作成されません。
しかし、--apply-logコマンドでリカバリ用のファイルを作成すると、ログにbinlogのポジションが出力されます。これを利用してレプリケーションを構築できます。

バックアップ

(1)ツールインストール

# rpm -Uhv http://www.percona.com/redir/downloads/percona-release/percona-release-0.0-1.x86_64.rpm
# wget https://www.percona.com/redir/downloads/percona-release/redhat/0.1-6/percona-release-0.1-6.noarch.rpm
# rpm -ivh percona-release-0.1-6.noarch.rpm
# yum install xtrabackup

(2)バックアップフォルダ作成

# mkdir -p /tmp/xtrabackup/

(3)既存データバックアップ

# innobackupex --ibbackup=xtrabackup --slave-info --safe-slave-backup --user root --password "" /tmp/xtrabackup/ --no-lock
InnoDB Backup Utility v1.5.1-xtrabackup; Copyright 2003, 2009 Innobase Oy
and Percona LLC and/or its affiliates 2009-2013.  All Rights Reserved.

This software is published under
the GNU GENERAL PUBLIC LICENSE Version 2, June 1991.

IMPORTANT: Please check that the backup run completes successfully.
           At the end of a successful backup run innobackupex
           prints "completed OK!".

innobackupex: Using mysql  Ver 14.14 Distrib 5.1.60, for unknown-linux-gnu (x86_64) using readline 5.1
innobackupex: Using mysql server version Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.

.... snip ...

xtrabackup: Creating suspend file '/tmp/xtrabackup/2019-07-30_18-58-30/xtrabackup_suspended' with pid '3023'
xtrabackup: Transaction log of lsn (49192) to (49192) was copied.
innobackupex:: Starting slave SQL thread
^@190730 18:58:47  innobackupex: Connection to database server closed

innobackupex: Backup created in directory '/tmp/xtrabackup/2019-07-30_18-58-30'
innobackupex: MySQL slave binlog position: master host '10.131.10.99', filename 'master-bin.000022', position 2089
190730 18:58:47  innobackupex: completed OK!

下記エラーが発生した場合

xtrabackup: Error: Please set parameter 'datadir'
innobackupex: Error: ibbackup child process has died at /usr/bin/innobackupex line 386.

xtrabackupはmy.cnfを参照する仕様の為、「datadir」を記載する必要がある。

[mysqld]
datadir=/var/lib/mysql/

(3)データ転送

# tar zcvf xtrabackup.tar.gz xtrabackup/2019-07-30_18-58-30/
# su - test
$ scp -i ~/.ssh/private.pem /tmp/xtrabackup.tar.gz xxx.xxx.xxx.xxx:/tmp/

リストア

(1)MySQL停止/既存データバックアップ

# /etc/init.d/mysqld stop
# mv /var/lib/mysql /var/lib/mysql.old
# mkdir /var/lib/mysql

(2) バックアップしたファイルへログの適用

# tar zxvf xtrabackup.tar.gz
# /usr/bin/innobackupex --user root --password "" --apply-log /tmp/xtrabackup/2019-07-30_18-58-30/

InnoDB Backup Utility v1.5.1-xtrabackup; Copyright 2003, 2009 Innobase Oy
and Percona LLC and/or its affiliates 2009-2013.  All Rights Reserved.

This software is published under
the GNU GENERAL PUBLIC LICENSE Version 2, June 1991.

IMPORTANT: Please check that the apply-log run completes successfully.
           At the end of a successful apply-log run innobackupex
           prints "completed OK!".

.... snip ...

[notice (again)]
  If you use binary log and don't use any hack of group commit,
  the binary log position seems to be:
InnoDB: Last MySQL binlog file position 0 1035, file name ./master-bin.000018

xtrabackup: starting shutdown with innodb_fast_shutdown = 1
190730 19:08:45  InnoDB: Starting shutdown...
190730 19:08:45  InnoDB: Shutdown completed; log sequence number 50700
190730 19:08:45  innobackupex: completed OK!

(3)データファイルのリストア

#  /usr/bin/innobackupex --copy-back /tmp/xtrabackup/2019-07-30_18-58-30/

InnoDB Backup Utility v1.5.1-xtrabackup; Copyright 2003, 2009 Innobase Oy
and Percona LLC and/or its affiliates 2009-2013.  All Rights Reserved.

This software is published under
the GNU GENERAL PUBLIC LICENSE Version 2, June 1991.

IMPORTANT: Please check that the copy-back run completes successfully.
           At the end of a successful copy-back run innobackupex
           prints "completed OK!".

.... snip ...

innobackupex: Starting to copy InnoDB log files
innobackupex: in '/tmp/xtrabackup/2019-07-30_18-58-30'
innobackupex: back to original InnoDB log directory '/var/lib/mysql/'
innobackupex: Copying '/tmp/xtrabackup/2019-07-30_18-58-30/ib_logfile1' to '/var/lib/mysql/'
innobackupex: Copying '/tmp/xtrabackup/2019-07-30_18-58-30/ib_logfile0' to '/var/lib/mysql/'
innobackupex: Finished copying back files.

190730 19:10:29  innobackupex: completed OK!

(4)MySQL起動

# chown -R mysql:mysql /var/lib/mysql
# /etc/init.d/mysql start

(5)レプリケーションの復旧
スレーブでのバックアップ--slave-infoオプション指定してバックアップを取得するとxtrabackup_slave_infoファイルが作成されます。
バックアップ時点のmaster_log_fileとmaster_log_positionが記述されたファイルが記録されています。
これを元にしてCHANGE MASTER構文を実行することでスレーブが復旧します。

# cat /var/lib/mysql/xtrabackup_slave_info
CHANGE MASTER TO MASTER_LOG_FILE='master-bin.000022', MASTER_LOG_POS=2089

# mysql -uroot
mysql> change master to master_host='xxx.xxx.xxx.xxx', master_user='repl', master_password='******', master_log_file='master-bin.000022', master_log_pos=2089;

mysql> start slave;
mysql> show slave status \G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: xxx.xxx.xxx.xxx
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: master-bin.000022
          Read_Master_Log_Pos: 2089
               Relay_Log_File: localhost-relay-bin.000002
                Relay_Log_Pos: 252
        Relay_Master_Log_File: master-bin.000022
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB:

「Slave_IO_Running」と「Slave_SQL_Running」がともに「Yes」となっていれば、レプリケーション設定完了。

Slave_IO_Running: Yes
Slave_SQL_Running: Yes

ref)
https://www.submit.ne.jp/428
https://takeshiyako.blogspot.com/2015/03/mysql-innobackupex-no-lock.html
http://buta9999.hatenablog.jp/entry/20131120/1384972041
https://gihyo.jp/dev/serial/01/mysql-road-construction-news/0059
https://qiita.com/isobecky74/items/eb38447e02f05ba4386b

MySQLの各Versionを跨いだ多段レプリケーション構成構築手順

前回の記事( MySQL+groonga+mroonga構築手順 - :>/dev/null )でレガシーシステムから現時点(2019/07/18)の最新Versionにアップデートする手順を検証したが、多段レプリケーションを用いた構成で再検討したので作業記録メモを残す。
多段構成として5.1 → 5.5 → 5.6 → 5.7の順でレプリケーションを行い、データ反映完了後、最終的に現master(5.1)と新master(5.7)間でスイッチオーバーさせ切り替える。
一気に最新までアップデートを行い手順を簡略化させたが2世代またいだレプリケーションはサポート対象外の為、数珠つなぎで1バージョン毎にアップデートを行う。

  • 以下各Version毎の構築要件
    • OS:CentOS7.6 x86_84 ← OSは全てこのVerで統一
MySQL Groonga Mroonga
5.1.60 2.10 2.1.0
5.5.62 4.10 4.10
5.6.44 9.0.4 9.0.3
5.7.26 9.0.4 9.0.4
現Master(5.1)
   -> relay(5.5)
       -> relay(5.6)
           -> relay(5.7) ← バージョンアップ後、Master
  • 各バージョンのSQL_MODEに関して
    • バージョン毎で設定値に変更が発生してる為、現Master構成の「設定なし」に統一
      • 5.1.60
        • 設定なし
      • 5.5.62
        • 設定なし
      • 5.6.44
        • NO_ENGINE_SUBSTITUTION
      • 5.7.26
        • ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

sql_mode設定
各環境の/etc/my.cnfの[mysqld]セクションに「sql_mode=''」を設定し、sql_modeのバージョン依存を改善する

◎ 各Version環境構築

■ インストール&設定

MySQL5.1.60 + Mroonga2.10(Groonga2.1.0) 構築手順

構築手順に関しては MySQL+groonga+mroonga構築手順 - :>/dev/null を参照
Replication構成に関しては MySQL+groonga+mroonga移行手順(バージョンアップ) - :>/dev/null のReplication構成部分を参照

● Masterデータ取得先として、Slaveの一台をレプリケーション停止→dump→リストアを行う。

既存Slaveから複製 dumpファイル出力の為、slave停止

# mysql -uroot -p
 
mysql> stop slave;
mysql> show slave status \G;
*************************** 1. row ***************************
               Slave_IO_State:
                  Master_Host: xxx.xxx.xxx.xxx
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: master-bin.000022
          Read_Master_Log_Pos: 383
               Relay_Log_File: mysql-relay-bin.000027
                Relay_Log_Pos: 253
        Relay_Master_Log_File: master-bin.000022
             Slave_IO_Running: No
            Slave_SQL_Running: No
              Replicate_Do_DB:

ステータス結果
「Slave_IO_Running」と「Slave_SQL_Running」がともに「No」となっていれば、レプリケーション停止。

dumpファイルのステータス状況確認
ダンプした時点の、マスターのバイナリログファイル名(MASTER_LOG_FILE)と開始位置(MASTER_LOG_POS)を確認する。

mysql> show slave status \G;
*************************** 1. row ***************************
               Slave_IO_State:
                  Master_Host: xxx.xxx.xxx.xxx
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: master-bin.000019
          Read_Master_Log_Pos: 270
               Relay_Log_File: mysql-relay-bin.000019
                Relay_Log_Pos: 253
        Relay_Master_Log_File: master-bin.000019
             Slave_IO_Running: No
            Slave_SQL_Running: No
              Replicate_Do_DB:
  Replicate_Wild_Ignore_Table:
                   Last_Errno: 0
                   Last_Error:
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 270
              Relay_Log_Space: 557
              Until_Condition: None

対象DBのデータdump

# mysqldump -uroot -p -c --add-drop-table=0 --skip-comments --default-character-set=ujis --order-by-primary --skip-extended-insert -B db1 > /tmp/mysql51.sql

slave再開

mysql> start slave;
mysql> show slave status \G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: xxx.xxx.xxx.xxx
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: master-bin.000019
          Read_Master_Log_Pos: 270
               Relay_Log_File: mysql-relay-bin.000019
                Relay_Log_Pos: 253
        Relay_Master_Log_File: master-bin.000019
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB:

対象DBのdumpファイルをslaveDBへ転送

$ scp -i ~/.ssh/private.pem /tmp/mysql51.sql xxx.xxx.xxx.xxx:/tmp/

参考)
以下Masterノードからdumpデータを取得する場合の手順

レプリケーションユーザー登録

# mysql -uroot

mysql> use mysql;
mysql> GRANT REPLICATION SLAVE ON *.* TO 'repl'@'10.0.0.0/255.0.0.0' IDENTIFIED BY '******';
mysql> select user, host from user\g;
+-------+--------------------+
| user  | host               |
+-------+--------------------+
| repl  | 10.0.0.0/255.0.0.0 |
+-------+--------------------+

mysql> show grants for repl@'10.0.0.0/255.0.0.0';
+---------------------------------------------------------------------------------------------------------+
| Grants for repl@10.0.0.0/255.0.0.0                                                                      |
+---------------------------------------------------------------------------------------------------------+
| GRANT REPLICATION SLAVE ON *.* TO 'repl'@'10.0.0.0/255.0.0.0' IDENTIFIED BY PASSWORD '****************' |
+---------------------------------------------------------------------------------------------------------+

binファイルのステータス状況確認
ダンプした時点の、マスターのバイナリログファイル名(File)と開始位置(Position)を確認する。

mysql> show master status;
+-------------------+----------+--------------+------------------+
| File              | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+-------------------+----------+--------------+------------------+
| master-bin.000019 |      270 |              |                  |
+-------------------+----------+--------------+------------------+

対象DBのデータdump

# mysqldump -uroot -p -c --add-drop-table=0 --skip-comments --default-character-set=ujis --order-by-primary --skip-extended-insert -B db1 > /tmp/mysql51.sql

対象DBのdumpファイルをslaveDBへ転送

$ scp -i ~/.ssh/private.pem /tmp/mysql51.sql xxx.xxx.xxx.xxx:/tmp/
MySQL5.5.62 + Mroonga4.10(Groonga4.10) 構築手順

関連パッケージ

# yum install wget tar gcc-c++ make mecab-devel
# yum remove mariadb-libs

MySQLリポジトリインストール

# rpm -Uvh http://dev.mysql.com/get/mysql57-community-release-el7-7.noarch.rpm

MySQLパッケージ確認

# yum repolist all |grep mysql
mysql-connectors-community/x86_64 MySQL Connectors Community   enabled:      118
mysql-connectors-community-source MySQL Connectors Community - disabled
mysql-tools-community/x86_64      MySQL Tools Community        enabled:       95
mysql-tools-community-source      MySQL Tools Community - Sour disabled
mysql55-community/x86_64          MySQL 5.5 Community Server   disabled          <-ここ注目
mysql55-community-source          MySQL 5.5 Community Server - disabled
mysql56-community/x86_64          MySQL 5.6 Community Server   disabled
mysql56-community-source          MySQL 5.6 Community Server - disabled
mysql57-community/x86_64          MySQL 5.7 Community Server   enabled:      364 <-ここ注目
mysql57-community-source          MySQL 5.7 Community Server - disabled

この環境では、5.7がenabled、5.6がdisabledである。
このままインストールすると、5.7がインストールされるので、有効/無効の切り替えをする。
この切り替えをするためにはyumの設定変更用のyum-utilsパッケージが必要なので、インストールされていない場合はインストールする。

# yum list installed |grep yum-utils
yum-utils.noarch                      1.1.31-50.el7                    @anaconda

リポジトリ有効/無効切替

# yum-config-manager --disable mysql57-community  <-5.7を無効設定
# yum-config-manager --enable mysql55-community   <-5.5を有効設定

リポジトリ再確認

# yum repolist all |grep mysql
mysql-connectors-community/x86_64 MySQL Connectors Community   enabled:      118
mysql-connectors-community-source MySQL Connectors Community - disabled
mysql-tools-community/x86_64      MySQL Tools Community        enabled:       95
mysql-tools-community-source      MySQL Tools Community - Sour disabled
mysql55-community/x86_64          MySQL 5.5 Community Server   enabled:      427
mysql55-community-source          MySQL 5.5 Community Server - disabled
mysql56-community/x86_64          MySQL 5.6 Community Server   disabled
mysql56-community-source          MySQL 5.6 Community Server - disabled
mysql57-community/x86_64          MySQL 5.7 Community Server   disabled
mysql57-community-source          MySQL 5.7 Community Server - disabled

MySQLパッケージ確認

# yum info mysql-community-server mysql-community-devel
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
 * base: ftp-srv2.kddilabs.jp
 * extras: ftp-srv2.kddilabs.jp
 * updates: ftp-srv2.kddilabs.jp
Available Packages
Name        : mysql-community-server
Arch        : x86_64
Version     : 5.5.62
Release     : 2.el7
Size        : 45 M
Repo        : mysql55-community/x86_64
Summary     : A very fast and reliable SQL database server
URL         : http://www.mysql.com/
License     : Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. Under GPLv2 license as shown
            : in the Description field.

MySQLパッケージインストール

# yum install mysql-community-server
# mysql --version
mysql  Ver 14.14 Distrib 5.5.62, for Linux (x86_64) using readline 5.1

MySQL起動

# systemctl start mysqld 

自動起動設定

# systemctl enable mysqld

/etc/my.cnf作成

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
symbolic-links=0

log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

server-id=55
log_bin=mysql-bin

log_slave_updates
relay_log=mysql-relay-bin
sql_mode=''

設定反映

# systemctl restart mysqld

Groonga

# yum install https://packages.groonga.org/centos/groonga-release-latest.noarch.rpm
# yum install --enablerepo=epel groonga groonga-devel

Mroonga

# wget http://dev.mysql.com/get/Downloads/MySQL-5.5/mysql-5.5.62.tar.gz
# tar -zxvf mysql-5.5.62.tar.gz
# http://packages.groonga.org/source/mroonga/mroonga-4.10.tar.gz
# wget http://packages.groonga.org/source/mroonga/mroonga-4.10.tar.gz
# tar -zxvf mroonga-4.10.tar.gz
# cd mroonga-4.10/
# ./configure --with-mysql-source=/tmp/mysql-5.5.62 --with-mysql-config=/bin/mysql_config
# make
# make install

mysqlにpluginを組み込む

# mysql -uroot
mysql> INSTALL PLUGIN Mroonga SONAME 'ha_mroonga.so';
mysql> show engines;
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| Engine             | Support | Comment                                                        | Transactions | XA   | Savepoints |
| Mroonga            | YES     | CJK-ready fulltext search, column store                        | NO           | NO   | NO         |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+

/etc/my.cnf更新 (既存環境のmy.cnfを反映)

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
symbolic-links=0

log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

server-id=55
log_bin=mysql-bin

log_slave_updates
relay_log=mysql-relay-bin
sql_mode=''

port = 3306
#skip-locking
skip-external-locking
skip-character-set-client-handshake
skip-name-resolve
#old_passwords ← 5.5⇔5.6間でのレプリケーションで接続エラー発生※1
key_buffer_size=64M
table_cache = 2048
##table_open_cache = 2048

[client]
port = 3306
default-character-set=ujis

[mysqldump]
quick
max_allowed_packet = 16M

[mysql]
no-auto-rehash
default-character-set=ujis

[mysqlhotcopy]
interactive-timeout

設定反映

# systemctl restart mysqld

◆ Slave設定

database作成

# mysql -uroot -p
mysql> CREATE DATABASE db1 DEFAULT CHARACTER SET ujis COLLATE ujis_japanese_ci;

masterのdumpファイルをrestore

# mysql -uroot db1 < /tmp/mysql51.sql

master DBへ接続するためのパラメータ設定
ダンプした時点の、ホスト名、ユーザー、バイナリログファイル名(MASTER_LOG_FILE)と開始位置(MASTER_LOG_POS)を設定し、レプリケーションを構成する。

# mysql -uroot
mysql> change master to
    -> master_host='xxx.xxx.xxx.xxx',
    -> master_user='repl',
    -> master_password='******',
    -> master_log_file='master-bin.000019',
    -> master_log_pos=270;

slave開始/状況確認

mysql> start slave;
mysql> show slave status \G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: xxx.xxx.xxx.xxx
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: master-bin.000019
          Read_Master_Log_Pos: 270
               Relay_Log_File: mysql-relay-bin.000002
                Relay_Log_Pos: 253
        Relay_Master_Log_File: master-bin.000019
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB:

ステータス結果
「Slave_IO_Running」と「Slave_SQL_Running」がともに「Yes」となっていれば、レプリケーション設定完了。
Slave_IO_Running: Yes
Slave_SQL_Running: Yes

◆ Master設定

dumpファイル出力の為、slave停止

mysql> stop slave;
mysql> show slave status \G;
*************************** 1. row ***************************
               Slave_IO_State:
                  Master_Host: xxx.xxx.xxx.xxx
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: master-bin.000022
          Read_Master_Log_Pos: 383
               Relay_Log_File: mysql-relay-bin.000027
                Relay_Log_Pos: 253
        Relay_Master_Log_File: master-bin.000022
             Slave_IO_Running: No
            Slave_SQL_Running: No
              Replicate_Do_DB:

ステータス結果
「Slave_IO_Running」と「Slave_SQL_Running」がともに「No」となっていれば、レプリケーション停止。

binファイルのステータス状況確認
ダンプした時点の、マスターのバイナリログファイル名(File)と開始位置(Position)を確認する。

mysql> show master status;
+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000008 |    62842 |              |                  |
+------------------+----------+--------------+------------------+

レプリケーションユーザー登録

mysql> use mysql;
mysql> select user, host, password from user\g;
mysql> GRANT REPLICATION SLAVE ON *.* TO 'repl'@'10.0.0.0/255.0.0.0' IDENTIFIED BY '******';

対象DBのデータdump

# mysqldump -uroot -p -c --add-drop-table=0 --skip-comments --default-character-set=ujis --order-by-primary --skip-extended-insert -B db1 > /tmp/mysql55.sql

slave再開

mysql> show slave status \G;
*************************** 1. row ***************************
               Slave_IO_State:
                  Master_Host: xxx.xxx.xxx.xxx
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: master-bin.000022
          Read_Master_Log_Pos: 383
               Relay_Log_File: mysql-relay-bin.000027
                Relay_Log_Pos: 253
        Relay_Master_Log_File: master-bin.000022
             Slave_IO_Running: No
            Slave_SQL_Running: No
              Replicate_Do_DB:

mysql> start slave;
mysql> show slave status \G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: xxx.xxx.xxx.xxx
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: master-bin.000022
          Read_Master_Log_Pos: 383
               Relay_Log_File: mysql-relay-bin.000028
                Relay_Log_Pos: 253
        Relay_Master_Log_File: master-bin.000022
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB:

対象DBのdumpファイルをslaveDBへ転送

$ scp -i ~/.ssh/private.pem /tmp/mysql55.sql xxx.xxx.xxx.xxx:/tmp/

※1 old_passwordsに関する問題
slave側で「show slave status \G;」を実行した時、下記エラー発生
[ERROR] Slave I/O: error connecting to master '@:3306' - retry-time: 10 retries: 68, Error_code: 2049
これは16文字のパスワードを持っている場合、それらは古いパスワードです。有効な41byteハッシュパスワードを持っている必要があります。
よって、old_passwordsを無効化しmysqlを起動する必要があります。

ref)
http://lucianoshow.biz/charlie/tumblr/158847295488.html
https://charlietokyojp.tumblr.com/post/158847295488/mysql-55-56%E3%81%AEoldpasswords%E3%81%AB%E9%96%A2%E3%81%99%E3%82%8B%E3%83%A1%E3%83%A2
http://anothermysqldba-jp.blogspot.com/2013/09/secureauthmysql.html

パスワード保存のセキュリティ警告について
「CHANGE MASTER TO」で「MASTER_USER」や「MASTER_PASSWORD」を指定すると、MySQL5.6からは警告されるようになりました。これは『スレーブサーバの「master.info」にユーザ名やパスワードがそのまま保存されるよ!』と注意してくれています。

SHOW WARNINGSオプション

(略) Message: Storing MySQL user name or password information in the master info repository is not secure and is therefore not recommended. Please consider using the USER and PASSWORD connection options for START SLAVE; see the 'START SLAVE Syntax' in the MySQL Manual for more information.

ref)
https://blog.apar.jp/linux/6725/

MySQL5.6.44 + Mroonga9.0.3(Groonga9.0.4) 構築手順

関連パッケージ

# yum install wget tar gcc-c++ make mecab-devel
# yum remove mariadb-libs

MySQL

# wget http://repo.mysql.com/yum/mysql-5.6-community/el/7/x86_64//mysql-community-server-5.6.44-2.el7.x86_64.rpm
# wget http://repo.mysql.com/yum/mysql-5.6-community/el/7/x86_64//mysql-community-client-5.6.44-2.el7.x86_64.rpm
# wget http://repo.mysql.com/yum/mysql-5.6-community/el/7/x86_64//mysql-community-devel-5.6.44-2.el7.x86_64.rpm
# wget http://repo.mysql.com/yum/mysql-5.6-community/el/7/x86_64//mysql-community-common-5.6.44-2.el7.x86_64.rpm
# wget http://repo.mysql.com/yum/mysql-5.6-community/el/7/x86_64//mysql-community-libs-5.6.44-2.el7.x86_64.rpm
# rpm -ivh mysql-community-*

ダウンロードサイト
https://centos.pkgs.org/7/mysql-5.6-x86_64/

mysql起動

# systemctl start mysqld 

自動起動設定

# systemctl enable mysqld

/etc/my.cnf作成

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
symbolic-links=0

log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

server-id=56
log_bin=mysql-bin

log_slave_updates
relay_log=mysql-relay-bin
sql_mode=''

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

Mecab
mysql-mroongaの依存関係にあるmecabおよびgroonga関連のパッケージが必要な場合、下記インストール

# yum install mecab mecab-devel mecab-ipadic --disablerepo=* --enablerepo=groonga

→ Version指定の場合
# wget https://packages.groonga.org/centos/7/x86_64/Packages/mecab-devel-0.996-1.el7.centos.x86_64.rpm
# wget https://packages.groonga.org/centos/7/x86_64/Packages/mecab-ipadic-2.7.0.20070801-13.el7.centos.1.x86_64.rpm
# wget https://packages.groonga.org/centos/7/x86_64/Packages/mecab-0.996-1.el7.centos.x86_64.rpm
# rpm -ivh mecab-*

Groonga

# wget https://packages.groonga.org/centos/7/x86_64/Packages/groonga-libs-9.0.3-1.el7.x86_64.rpm
# wget https://packages.groonga.org/centos/7/x86_64/Packages/groonga-tokenizer-mecab-9.0.3-1.el7.x86_64.rpm
# wget https://packages.groonga.org/centos/7/x86_64/Packages/groonga-9.0.3-1.el7.x86_64.rpm
# wget https://packages.groonga.org/centos/7/x86_64/Packages/groonga-devel-9.0.3-1.el7.x86_64.rpm
# wget https://packages.groonga.org/centos/7/x86_64/Packages/groonga-plugin-suggest-9.0.3-1.el7.x86_64.rpm
# rpm -ivh groonga-*

ダウンロードサイト
https://packages.groonga.org/centos/7/x86_64/Packages/

Mroonga plugin

# yum install groonga-normalizer-mysql ← 関連パッケージ

# wget http://packages.groonga.org/centos/7/x86_64/Packages/mysql-community-mroonga-9.03-1.el7.x86_64.rpm
# rpm -ivh mysql-community-mroonga-9.03-1.el7.x86_64.rpm
Preparing...                          ################################# [100%]
Updating / installing...
   1:mysql-community-mroonga-9.03-1.el################################# [100%]
Redirecting to /bin/systemctl status mysqld.service
/bin/mysql -u root < /usr/share/mroonga/install.sql

Mroonga plugin確認
# mysql -uroot
mysql> show engines;
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| Engine             | Support | Comment                                                        | Transactions | XA   | Savepoints |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| Mroonga            | YES     | CJK-ready fulltext search, column store                        | NO           | NO   | NO         |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+

/etc/my.cnf更新 (既存環境のmy.cnfを反映)

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
symbolic-links=0

log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

server-id=56
log_bin=mysql-bin

log_slave_updates
relay_log=mysql-relay-bin
sql_mode=''

port = 3306
#skip-locking
skip-external-locking
#old_passwords
key_buffer_size=64M
#table_cache = 2048
table_open_cache = 2048
#thread_cache=512
thread_cache_size=512

[client]
port = 3306
default-character-set=ujis

[mysqldump]
quick
max_allowed_packet = 16M

[mysql]
no-auto-rehash
default-character-set=ujis

[mysqlhotcopy]
interactive-timeout

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

設定反映

# systemctl restart mysqld

● Replication

◆ Slave設定

#mysql -uroot -p
mysql> CREATE DATABASE db1 DEFAULT CHARACTER SET ujis COLLATE ujis_japanese_ci;

masterのdumpファイルをrestore

mysql -uroot db1 < /tmp/mysql55.sql

master DBへ接続するためのパラメータ設定
ダンプした時点の、ホスト名、ユーザー、バイナリログファイル名(File)と開始位置(Position)を設定し、レプリケーションを構成する。

mysql> change master to master_host='xxx.xxx.xxx.xxx', master_user='repl', master_password='********', master_log_file='mysql-bin.000008', master_log_pos=62842;

slave開始/状況確認

mysql> start slave;
mysql> show slave status \G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: xxx.xxx.xxx.xxx
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000009
          Read_Master_Log_Pos: 545
               Relay_Log_File: mysql-relay-bin.000003
                Relay_Log_Pos: 704
        Relay_Master_Log_File: mysql-bin.000009
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB:

ステータス結果
「Slave_IO_Running」と「Slave_SQL_Running」がともに「Yes」となっていれば、レプリケーション設定完了。
Slave_IO_Running: Yes
Slave_SQL_Running: Yes

◆ Master設定

dumpファイル出力の為、slave停止

mysql> stop slave;
mysql> show slave status \G;
*************************** 1. row ***************************
               Slave_IO_State:
                  Master_Host: xxx.xxx.xxx.xxx
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000009
          Read_Master_Log_Pos: 850
               Relay_Log_File: mysql-relay-bin.000003
                Relay_Log_Pos: 1009
        Relay_Master_Log_File: mysql-bin.000009
             Slave_IO_Running: No
            Slave_SQL_Running: No
              Replicate_Do_DB:

ステータス結果
「Slave_IO_Running」と「Slave_SQL_Running」がともに「No」となっていれば、レプリケーション停止。

binファイルのステータス状況確認
ダンプした時点の、バイナリログファイル名(File)と開始位置(Position)を設定し、レプリケーションを構成する。

mysql> show master status;
+------------------+----------+--------------+------------------+-------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql-bin.000006 |   105233 |              |                  |                   |
+------------------+----------+--------------+------------------+-------------------+

レプリケーションユーザー登録

mysql> use mysql;
mysql> GRANT REPLICATION SLAVE ON *.* TO 'repl'@'10.0.0.0/255.0.0.0' IDENTIFIED BY 'replpw';
mysql> select user, host, password from user\g;
+------+--------------------+-------------------------------------------+
| user | host               | password                                  |
+------+--------------------+-------------------------------------------+
| repl | 10.0.0.0/255.0.0.0 | ***************************************** |
+------+--------------------+-------------------------------------------+

対象DBのデータdump

mysqldump -uroot -p -c --add-drop-table=0 --skip-comments --default-character-set=ujis --order-by-primary --skip-extended-insert -B db1 > /tmp/mysql56.sql

slave再開

mysql> start slave;
mysql> show slave status \G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: xxx.xxx.xxx.xxx
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000009
          Read_Master_Log_Pos: 850
               Relay_Log_File: mysql-relay-bin.000004
                Relay_Log_Pos: 266
        Relay_Master_Log_File: mysql-bin.000009
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB:

対象DBのdumpファイルをslaveDBへ転送

$ scp -i ~/.ssh/private.pem /tmp/mysql56.sql xxx.xxx.xxx.xxx:/tmp/
MySQL5.7.26 + Mroonga9.0.4(Groonga9.0.4) 構築手順

関連パッケージ

# yum install wget tar gcc-c++ make mecab-devel
# yum remove mariadb-libs

MySQL

# wget http://repo.mysql.com/yum/mysql-5.7-community/el/7/x86_64//mysql-community-server-5.7.26-1.el7.x86_64.rpm
# wget http://repo.mysql.com/yum/mysql-5.7-community/el/7/x86_64//mysql-community-client-5.7.26-1.el7.x86_64.rpm
# wget http://repo.mysql.com/yum/mysql-5.7-community/el/7/x86_64//mysql-community-devel-5.7.26-1.el7.x86_64.rpm
# wget http://repo.mysql.com/yum/mysql-5.7-community/el/7/x86_64//mysql-community-common-5.7.26-1.el7.x86_64.rpm
# wget http://repo.mysql.com/yum/mysql-5.7-community/el/7/x86_64//mysql-community-libs-5.7.26-1.el7.x86_64.rpm
# rpm -ivh mysql-community-*

ダウンロードサイト
https://centos.pkgs.org/7/mysql-5.7-x86_64/

自動起動設定

# systemctl enable mysqld

/etc/my.cnf作成

# vi /etc/my.cnf
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
symbolic-links=0

log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

server-id=57
log_bin=mysql-bin
sql_mode=''

設定反映

# systemctl start mysqld

初期パスワード確認

# cat /var/log/mysqld.log | grep password

初期化(mysql_secure_installation)
# mysql_secure_installation
Securing the MySQL server deployment.

Enter password for user root: [初期パスワード]
The existing password for the user account root has expired. Please set a new password.
New password: [新しいパスワード]
Re-enter new password: [もう一度新しいパスワード]

The 'validate_password' component is installed on the server.
The subsequent steps will run with the existing configuration
of the component.
Using existing password for root.

Estimated strength of the password: 100 
Change the password for root ? ((Press y|Y for Yes, any other key for No) : y

New password: [新しいパスワード]
Re-enter new password: [もう一度新しいパスワード]

Estimated strength of the password: 100 
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : y
By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL 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? (Press y|Y for Yes, any other key for No) : 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? (Press y|Y for Yes, any other key for No) : y
Success.

By default, MySQL 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? (Press y|Y for Yes, any other key for No) : 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? (Press y|Y for Yes, any other key for No) : y
Success.

All done!

mysql-mroongaの依存関係にあるmecabおよびgroonga関連のパッケージが必要な場合、下記インストール

# yum install mecab mecab-devel mecab-ipadic --disablerepo=* --enablerepo=groonga

→ Version指定の場合
# wget https://packages.groonga.org/centos/7/x86_64/Packages/mecab-0.996-2.el7.1.x86_64.rpm
# wget https://packages.groonga.org/centos/7/x86_64/Packages/mecab-devel-0.996-2.el7.1.x86_64.rpm
# wget https://packages.groonga.org/centos/7/x86_64/Packages/mecab-ipadic-2.7.0.20070801-17.el7.x86_64.rpm
# rpm -ivh mecab-*

Groonga

# wget https://packages.groonga.org/centos/7/x86_64/Packages/groonga-libs-9.0.4-1.el7.x86_64.rpm
# wget https://packages.groonga.org/centos/7/x86_64/Packages/groonga-tokenizer-mecab-9.0.4-1.el7.x86_64.rpm
# wget https://packages.groonga.org/centos/7/x86_64/Packages/groonga-9.0.4-1.el7.x86_64.rpm
# wget https://packages.groonga.org/centos/7/x86_64/Packages/groonga-devel-9.0.4-1.el7.x86_64.rpm
# wget https://packages.groonga.org/centos/7/x86_64/Packages/groonga-plugin-suggest-9.0.4-1.el7.x86_64.rpm
# rpm -ivh groonga-*

ダウンロードサイト
https://packages.groonga.org/centos/7/x86_64/Packages/

Mroonga

関連パッケージ
# yum install groonga-normalizer-mysql

Mroonga plugin
# wget https://packages.groonga.org/centos/7/x86_64/Packages/mysql57-community-mroonga-9.04-1.el7.x86_64.rpm
# rpm -ivh mysql57-community-mroonga-9.04-1.el7.x86_64.rpm

Mroonga plugin確認
# mysql -uroot -p
mysql> show engines;
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| Engine             | Support | Comment                                                        | Transactions | XA   | Savepoints |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| Mroonga            | YES     | CJK-ready fulltext search, column store                        | NO           | NO   | NO         |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+

/etc/my.cnf更新 (既存環境のmy.cnfを反映)

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
symbolic-links=0

log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

validate_password_length=4
validate_password_policy=LOW

server-id=57
log_bin=mysql-bin

log_slave_updates
relay_log=mysql-relay-bin
sql_mode=''

port = 3306
skip-external-locking
table_open_cache = 2048
thread_cache_size=512

[client]
port = 3306
socket=/var/lib/mysql/mysql.sock
default-character-set=ujis

[mysqldump]
quick
max_allowed_packet = 16M

[mysql]
no-auto-rehash
default-character-set=ujis

[mysqlhotcopy]
interactive-timeout

設定反映

# systemctl restart mysqld

● Replication

◆ Slave設定

database作成

# mysql -uroot -p
mysql> CREATE DATABASE db1 DEFAULT CHARACTER SET ujis COLLATE ujis_japanese_ci;

masterのdumpファイルをrestore

# mysql -uroot -p db1 < /tmp/mysql56.sql

master DBへ接続するためのパラメータ設定
ダンプした時点の、ホスト名、ユーザー、バイナリログファイル名(File)と開始位置(Position)を設定し、レプリケーションを構成する。

mysql> change master to master_host='xxx.xxx.xxx.xxx', master_user='repl', master_password='******', master_log_file='mysql-bin.000006', master_log_pos=105233;

slave開始/状況確認

mysql> start slave;
mysql> show slave status \G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: xxx.xxx.xxx.xxx
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000006
          Read_Master_Log_Pos: 105233
               Relay_Log_File: mysql-relay-bin.000002
                Relay_Log_Pos: 317
        Relay_Master_Log_File: mysql-bin.000006
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB:

ステータス結果
「Slave_IO_Running」と「Slave_SQL_Running」がともに「Yes」となっていれば、レプリケーション設定完了。
Slave_IO_Running: Yes
Slave_SQL_Running: Yes

◆ Master設定

dumpファイル出力の為、slave停止

mysql> stop slave;
mysql> show slave status \G;
*************************** 1. row ***************************
               Slave_IO_State:
                  Master_Host: xxx.xxx.xxx.xxx
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000006
          Read_Master_Log_Pos: 106336
               Relay_Log_File: mysql-relay-bin.000003
                Relay_Log_Pos: 317
        Relay_Master_Log_File: mysql-bin.000006
             Slave_IO_Running: No
            Slave_SQL_Running: No
              Replicate_Do_DB:

ステータス結果
「Slave_IO_Running」と「Slave_SQL_Running」がともに「No」となっていれば、レプリケーション停止。

binファイルのステータス状況確認
ダンプした時点の、マスターのバイナリログファイル名(File)と開始位置(Position)を確認する。

mysql> show master status;
+------------------+----------+--------------+------------------+-------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql-bin.000003 |    37328 |              |                  |                   |
+------------------+----------+--------------+------------------+-------------------+

レプリケーションユーザー登録

mysql> use mysql;
mysql> GRANT REPLICATION SLAVE ON *.* TO 'repl'@'10.0.0.0/255.0.0.0' IDENTIFIED BY '******';
mysql> select user, host, authentication_string from user \g;
+---------------+--------------------+-------------------------------------------+
| user          | host               | authentication_string                     |
+---------------+--------------------+-------------------------------------------+
| repl          | 10.0.0.0/255.0.0.0 | ***************************************** |
+---------------+--------------------+-------------------------------------------+

対象DBのデータdump

mysqldump -uroot -p -c --add-drop-table=0 --skip-comments --default-character-set=ujis --order-by-primary --skip-extended-insert -B db1 > /tmp/mysql57.sql

slave再開

mysql> start slave;
mysql> show slave status \G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: xxx.xxx.xxx.xxx
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000006
          Read_Master_Log_Pos: 106336
               Relay_Log_File: mysql-relay-bin.000004
                Relay_Log_Pos: 317
        Relay_Master_Log_File: mysql-bin.000006
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB:

対象DBのdumpファイルをslaveDBへ転送

$ scp -i ~/.ssh/private.pem /tmp/mysql56.sql xxx.xxx.xxx.xxx:/tmp/

◆ Slave Replication設定(MySQL5.7間)

masterのdumpファイルをrestore

# mysql -uroot -p db1 < /tmp/mysql57.sql

master DBへ接続するためのパラメータ設定

change master to master_host='xxx.xxx.xxx.xxx', master_user='repl', master_password='******', master_log_file='mysql-bin.000004', master_log_pos=154;

slave開始/状況確認

mysql> start slave;
mysql> show slave status \G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: xxx.xxx.xxx.xxx
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000003
          Read_Master_Log_Pos: 37633
               Relay_Log_File: sql57mroo90401-relay-bin.000003
                Relay_Log_Pos: 625
        Relay_Master_Log_File: mysql-bin.000003
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB:

MySQL+groonga+mroonga移行手順(バージョンアップ)

前回の記事( MySQL+groonga+mroonga構築手順 - :>/dev/null )でレガシーシステムを検証したが、その環境を現時点(2019/07/18)の最新Versionにアップデートする必要があり作業記録メモを残す。
レガシーシステムではMySQLからgroongaをストレージエンジンとして利用する場合、mroonga plugin(MySQL組込)を使用せず直接利用する構成だが、
groongaがv3.04からmysql経由で直接使用するのを停止しmroonga経由で使用する方式に統一された為、バージョンアップ環境ではmroonga経由の構成で調査。

  • 以下構築要件
    • OS:CentOS7.6 x86_84
    • MySQL:5.7.26
    • groonga:9.0.4
    • mroonga:9.0.4

◎ 環境構築

■ インストール&設定

関連パッケージインストール

# yum install wget tar gcc-c++ make mecab-devel mysql-community-devel

mysqlインストール

# yum remove mariadb-libs ← 標準インストールされてるライブラリとの依存関係でエラーが発生する為、先行して既存ライブラリ削除
# rpm -Uvh http://dev.mysql.com/get/mysql57-community-release-el7-7.noarch.rpm
# yum info mysql-community-server ← レポジトリの対象Version確認
# yum install mysql-community-server

初期設定

# systemctl start mysqld

初期パスワード確認

# cat /var/log/mysqld.log | grep password

初期化

# mysql_secure_installation


Securing the MySQL server deployment.

Enter password for user root: [初期パスワード]

The existing password for the user account root has expired. Please set a new password.

New password: [新しいパスワード]

Re-enter new password: [もう一度新しいパスワード]
The 'validate_password' component is installed on the server.
The subsequent steps will run with the existing configuration
of the component.
Using existing password for root.

Estimated strength of the password: 100 
Change the password for root ? ((Press y|Y for Yes, any other key for No) : y

New password: [新しいパスワード]

Re-enter new password: [もう一度新しいパスワード]

Estimated strength of the password: 100 
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : y
By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL 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? (Press y|Y for Yes, any other key for No) : 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? (Press y|Y for Yes, any other key for No) : y
Success.

By default, MySQL 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? (Press y|Y for Yes, any other key for No) : 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? (Press y|Y for Yes, any other key for No) : y
Success.

All done!

/etc/my.cnf作成

# vi /etc/my.cnf

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
symbolic-links=0

log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

# defaultではポリシーが厳しい基準の為、テスト用にパスワードポリシー変更
validate_password_length=4
validate_password_policy=LOW

## Replication 用設定
# 各MySQLサーバを識別するためのIDの設定
server-id=101

# バイナリログの有効化
log_bin=mysql-bin

# バイナリログをコミットと同時にディスクに書込む
sync_binlog=1

mysql再起動

# systemctl restart mysqld

自動起動設定

# systemctl enable mysqld
◆ パッケージインストールの場合

groonga

# yum install https://packages.groonga.org/centos/groonga-release-latest.noarch.rpm
# yum install --enablerepo=epel groonga

mroonga

# wget https://packages.groonga.org/centos/groonga-release-1.4.0-1.noarch.rpm
# rpm -ivh groonga-release-1.4.0-1.noarch.rpm
# yum install --enablerepo=epel mysql57-community-mroonga
◆ ソースインストールの場合

groonga

# wget https://packages.groonga.org/source/groonga/groonga-9.0.4.tar.gz
# tar zxvf groonga-9.0.4.tar.gz
# cd groonga-9.0.4/
# ./configure
# make -j$(grep '^processor' /proc/cpuinfo | wc -l)
# make install

mysql

# wget https://fossies.org/linux/misc/mysql-5.7.26.tar.gz
# tar zxvf mysql-5.7.26.tar.gz
# cmake . \
-DCMAKE_INSTALL_PREFIX=/usr/local/mysql \
-DMYSQL_UNIX_ADDR=/usr/local/mysql/mysql.sock \
-DMYSQL_TCP_PORT=3306 \
-DMYSQL_DATADIR=/usr/local/mysql/data \
-DDEFAULT_CHARSET=utf8 \
-DWITH_EXTRA_CHARSETS=all \
-DDEFAULT_COLLATION=utf8_general_ci \
-DWITH_INNOBASE_STORAGE_ENGINE=1 \
-DWITH_ARCHIVE_STORAGE_ENGINE=1 \
-DWITH_BLACKHOLE_STORAGE_ENGINE=1 \
-DWITH_PARTITION_STORAGE_ENGINE=1 \
-DWITH_PERFSCHEMA_STORAGE_ENGINE=1 \
-DDOWNLOAD_BOOST=1 \
-DWITH_BOOST=/tmp

・ソースコンパイルに必要なパッケージ/ライブラリをインストール

# yum install wget gcc-c++ cmake ncurses-devel zlib-devel readline-devel bison
# wget  http://sourceforge.net/projects/boost/files/boost/1.59.0/boost_1_59_0.tar.gz

※頻繁に下記エラーが発生する為、事前にライブラリをダウンロード

-- LOCAL_BOOST_DIR -- LOCAL_BOOST_ZIP -- Could not find (the correct version of) boost. -- MySQL currently requires boost_1_59_0 CMake Error at cmake/boost.cmake:81 (MESSAGE): You can download it with -DDOWNLOAD_BOOST=1 -DWITH_BOOST= This CMake script will look for boost in . If it is not there, it will download and unpack it (in that directory) for you. If you are inside a firewall, you may need to use an http proxy: export http_proxy=http://example.com:80 Call Stack (most recent call first): cmake/boost.cmake:238 (COULD_NOT_FIND_BOOST) CMakeLists.txt:508 (INCLUDE) -- Configuring incomplete, errors occurred! See also "/tmp/mysql-5.7.26/CMakeFiles/CMakeOutput.log". See also "/tmp/mysql-5.7.26/CMakeFiles/CMakeError.log".

ref)
https://www.eastforest.jp/mysql/3521

mroonga

# wget https://packages.groonga.org/source/mroonga/mroonga-9.04.tar.gz
# tar zxvf mroonga-9.04.tar.gz
# cd mroonga-9.04/
# ./configure PKG_CONFIG_PATH=/tmp/groonga-9.0.4/ --with-mysql-source=/tmp/mysql-5.7.26-el7-x86_64 --with-mysql-build=/tmp/mysql-5.7.26-el7-x86_64 --with-mysql-config=/usr/bin/mysql_config
# make
# make install
# mysql -uroot -p < /usr/local/share/mroonga/install.sql

※configureオプション
--with-mysql-source:MySQLソースコードディレクトリーを指定
--with-mysql-build:MySQLのビルドディレクトリーを指定
--with-mysql-config:mysql_configコマンドのパスを指定

SHOW ENGINES SQLを実行することでMroongaが正常にインストールされているかを確認。Mroongaという行があれば正常にインストール済み。

mysql> SHOW ENGINES;  
+------------+---------+-----------------------------------------+--------------+------+------------+
| Engine     | Support | Comment                                 | Transactions | XA   | Savepoints |
+------------+---------+-----------------------------------------+--------------+------+------------+
...snip...
| Mroonga    | YES     | Fulltext search, column base            | NO           | NO   | NO         |
...snip...
+------------+---------+-----------------------------------------+--------------+------+------------+

ref)
https://gitter.im/groonga/ja
https://yoku0825.blogspot.com/2015/12/mysql-55mysql-57.html

◆ 動作確認

database作成

mysql> CREATE DATABASE db1 DEFAULT CHARACTER SET ujis COLLATE ujis_japanese_ci;

table作成

mysql> create table t1 (c1 int primary key, c2 varchar(255), c3 text, fulltext index(c2), fulltext index(c3)) ENGINE = mroonga DEFAULT CHARSET ujis;

サンプルデータ作成&確認

mysql> insert into t1 values(1, "明日の富士山の天気について","東京");
mysql> insert into t1 values(2, "天気予報","明日の富士山の天気は分かりません");
mysql> insert into t1 values(3, "dummy", "dummy");

mysql> select * from t1 where match(c2) against("富士山");
+-----+-----------------------------------------+-----------------------+
| c1    | c2                                                    | c3                            |
+-----+-----------------------------------------+-----------------------+
|  1     |  明日の富士山の天気について          | 東京                         |
+-----+-----------------------------------------+-----------------------+

■ Replication

Masterノード作業

Replicationユーザー作成&確認

mysql> GRANT REPLICATION SLAVE ON *.* TO repl@xxx.xxx.xxx.xxx IDENTIFIED BY '******';
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> SELECT user,host FROM mysql.user;
+---------------+---------------+
| user          | host          |
+---------------+---------------+
| repl          | xxx.xxx.xxx.xxx |
+---------------+---------------+

dump中にDBが更新されないようにテーブルの書き込みロック

mysql> flush tables with read lock;

現在のバイナリログの状態を確認する

mysql> show master status;
+------------------+----------+--------------+------------------+----------------------------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set                      |
+------------------+----------+--------------+------------------+----------------------------------------+
| mysql-bin.000002 |      194 |              |                  |       |
+------------------+----------+--------------+------------------+----------------------------------------+

データタンプ

# mysqldump -u root -p \
--single-transaction \
--flush-logs \
--master-data=2 \
--all-databases \
--hex-blob \
--triggers \
--routines \
--events > /tmp/master_db.sql

テーブルロックを解除

mysql> unlock tables;

Masterノード → Slaveノードへデータ転送

# scp -i ~/.ssh/private.pem /tmp/master_db.sql xxx.xxx.xxx.xxx:/tmp/
Slaveノード作業

/etc/my.cnf作成

## Replication 用設定
# 各MySQLサーバを識別するためのIDの設定
server-id=102

# 更新を禁止する
read_only

# スレーブSQLスレッドによって実行される更新をバイナリログに書き込む
log_slave_updates

# リレーログファイルの名前
relay_log=mysql-relay-bin

# クラッシュセーフなレプリケーション設定
relay_log_info_repository=TABLE
relay_log_recovery=ON
relay_log_purge=ON

mysql再起動

# systemctl restart mysqld

Masterノードのデータリストア

# mysql -uroot -p
 
mysql> CREATE DATABASE db1 DEFAULT CHARACTER SET ujis COLLATE ujis_japanese_ci;
mysql> use db1;
mysql> source /tmp/master_db.sql;

SlaveノードのReplication設定
(Slaveノード → Masterノードへ接続するためのパラメータ設定)

# mysql -uroot -p
 
mysql> change master to
    -> master_host='xxx.xxx.xxx.xxx',
    -> master_user='repl',
    -> master_password='******',
    -> master_log_file='mysql-bin.000002',
    -> master_log_pos=194;

Replication対象DBとして設定

mysql> change replication filter replicate_do_db = (db1);

※Replication対象DBから 削除する場合
(フィルターを消すには、フィルター名をreplicate-do-db構文から削除する必要があり)

mysql> show slave status\G
...snip...
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB: db1
          Replicate_Ignore_DB:
...snip...

mysql> change replication filter replicate_do_db = (); ← slave未停止の場合、エラーで弾かれる
ERROR 3017 (HY000): This operation cannot be performed with a running slave sql thread; run STOP SLAVE SQL_THREAD first

mysql> stop slave;
mysql> change replication filter replicate_do_db = ();
mysql> start slave;

mysql> show slave status \G;
...snip...
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB:
          Replicate_Ignore_DB:
...snip...

Replication開始

mysql> start slave;

Replicationステータス確認

mysql> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: xxx.xxx.xxx.xxx
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000004
          Read_Master_Log_Pos: 194
               Relay_Log_File: 157x112x83x169-relay-bin.000005
                Relay_Log_Pos: 367
        Relay_Master_Log_File: mysql-bin.000004
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB: db1
          Replicate_Ignore_DB:
           Replicate_Do_Table:
       Replicate_Ignore_Table:
      Replicate_Wild_Do_Table:
  Replicate_Wild_Ignore_Table:
                   Last_Errno: 0
                   Last_Error:
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 194
              Relay_Log_Space: 796
              Until_Condition: None
               Until_Log_File:
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File:
           Master_SSL_CA_Path:
              Master_SSL_Cert:
            Master_SSL_Cipher:
               Master_SSL_Key:
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error:
               Last_SQL_Errno: 0
               Last_SQL_Error:
  Replicate_Ignore_Server_Ids:
             Master_Server_Id: 101
                  Master_UUID: 361e5307-a2e4-11e9-8318-0050568ca249
             Master_Info_File: /var/lib/mysql/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind:
      Last_IO_Error_Timestamp:
     Last_SQL_Error_Timestamp:
               Master_SSL_Crl:
           Master_SSL_Crlpath:
           Retrieved_Gtid_Set:
            Executed_Gtid_Set:
                Auto_Position: 0
         Replicate_Rewrite_DB:
                 Channel_Name:
           Master_TLS_Version:

ステータス結果
「Slave_IO_Running」と「Slave_SQL_Running」がともに「Yes」となっていれば、レプリケーション設定完了。
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
上記正常稼働後、更新系のSQLをMasterノードで実行し変更内容がSlaveに伝播する事を確認。

◎ バージョンアップ環境設定

■ バージョンアップ(データ移行)手順

バージョンアップ環境のmy.cnfファイル生成

現構成のコピーベースですがmysql5.7へアップデートした為、一部パラメータ名変更の発生に伴い設定調整。

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
symbolic-links=0
 
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
 
server-id=101
log_bin=mysql-bin
 
port = 3306
#skip-locking  ← 旧パラメータ(廃止)
skip-external-locking
skip-character-set-client-handshake
skip-name-resolve
back_log = 100
#old_passwords  ← 旧パラメータ(廃止)
key_buffer_size=64M
max_allowed_packet = 16M
max_connect_errors = 100000
max_connections = 8192
#table_cache = 2048  ← 旧パラメータ(廃止)
table_open_cache = 2048
sort_buffer_size = 64M
join_buffer_size = 2M
net_buffer_length = 1M
read_buffer_size = 2M
read_rnd_buffer_size = 2M
query_cache_limit=16M
query_cache_size=1024M
query_cache_type=2
#thread_cache=512  ← 旧パラメータ(廃止)
thread_cache_size=512
net_read_timeout=3600
connect_timeout=60
wait_timeout=300
open-files-limit=1000
character-set-server=ujis
tmpdir = /tmp/
 #default-storage-engine = groonga  ← 旧パラメータ(廃止)
default-storage-engine = mroonga

[client]
port = 3306
socket=/var/lib/mysql/mysql.sock
default-character-set=ujis
 
[mysqldump]
quick
max_allowed_packet = 16M
 
[mysql]
no-auto-rehash
default-character-set=ujis
 
[mysqlhotcopy]
interactive-timeout

現構成からダンプ(現環境(mysql5.1.60)の作業)

mysqlの登録済みユーザー移行準備

登録済みユーザー確認

# mysql -uroot -p
mysql> use mysql;
mysql> select user, host from user\g;
+---------------+---------------+
| user          | host          |
+---------------+---------------+
| admin         | localhost     |
| mysql.session | localhost     |
| mysql.sys     | localhost     |
| root          | localhost     |
+---------------+---------------+

登録済みユーザー権限確認 移行対象ユーザーの現構成を確認。下記adminユーザーの例。

mysql> show grants for admin@localhost;
+-------------------------------------------------------------------------------------+
| Grants for admin@localhost                                                          |
+-------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'admin'@'localhost' IDENTIFIED BY PASSWORD '****************' |
| GRANT ALL PRIVILEGES ON `db1`.* TO 'admin'@'localhost'                              |
+-------------------------------------------------------------------------------------+

ユーザー登録に関して
バージョンアップ環境でユーザー登録が必要な為、現環境のユーザー名/権限を確認し、バージョンアップ環境で手動登録する必要がある。

old_passwordsに関して
MySQL 5.7.5移行からold_passwordsが利用できなくなり、完全に古いパスワードでログイン不可。
アップグレード前に予めold_passwordsを解除した上で、ハッシュが短いユーザーのパスワードを再設定する事で解決する必要がある。

アプリケーションデータ

dump中にDBが更新されないようにテーブルの書き込みロック

mysql> flush tables with read lock;

テーブルスキーマ

$ mysqldump -uroot -p -c --add-drop-table=0 --skip-comments --default-character-set=ujis --order-by-primary --skip-extended-insert -d -B db1 > mysql51-s.sql

テーブルデー

$ mysqldump -uroot -p -c --add-drop-table=0 --skip-comments --default-character-set=ujis --order-by-primary --skip-extended-insert -t -B db1 > mysql51-d.sql

テーブルロックを解除

mysql> unlock tables;
デフォルトストレージエンジンをgroonga → mroongaへ変換
$ sed -e 's/ENGINE=groong/ENGINE=mroong/g' mysql51-s.sql
バージョンアップ環境へファイル転送
$ scp -i ~/.ssh/private.pem /tmp/mysql51-* xxx.xxx.xxx.xxx:/tmp/

バージョンアップ環境へリストア(バージョンアップ環境(mysql5.7.26)の作業)

mysqlのユーザー移行

登録済みユーザー確認

mysql> use mysql;
mysql> select user, host from user\g;
+---------------+---------------+
| user          | host          |
+---------------+---------------+
| admin         | localhost     |
| mysql.session | localhost     |
| mysql.sys     | localhost     |
| root          | localhost     |
+---------------+---------------+
現環境(移行)ユーザー登録

移行対象ユーザーの登録。下記adminユーザーの例。

mysql> grant ALL PRIVILEGES ON db1.* TO 'admin'@'localhost' IDENTIFIED BY '*******';
登録済みユーザー権限確認
mysql> show grants for admin@localhost;
+--------------------------------------------------------+
| Grants for admin@localhost                             |
+--------------------------------------------------------+
| GRANT USAGE ON *.* TO 'admin'@'localhost'              |
| GRANT ALL PRIVILEGES ON `db1`.* TO 'admin'@'localhost' |
+--------------------------------------------------------+

ユーザー権限に関して
現環境とバージョンアップ環境でユーザー登録/権限が同様に設定されている事を確認する必要がある。

アプリケーションデータ移行

テーブルスキーマ

# mysql -u root -p --default-character-set=ujis db1 < /tmp/mysql51-s.sql

テーブルデー

# mysql -u root -p --default-character-set=ujis db1 < /tmp/mysql51-d.sql

動作確認

・テーブルスキーマ

リストア後のテーブルスキーマ定義を確認。

mysql> use db1;
mysql> show create table t1 \G;
*************************** 1. row ***************************
       Table: t1
Create Table: CREATE TABLE `t1` (
  `c1` int(11) NOT NULL,
  `c2` varchar(255) DEFAULT NULL,
  `c3` text,
  PRIMARY KEY (`c1`),
  FULLTEXT KEY `c2` (`c2`),
  FULLTEXT KEY `c3` (`c3`)
) ENGINE=Mroonga DEFAULT CHARSET=ujis

ステータス結果
対象テーブルのスキーマ定義に下記が設定されてる事を確認。
ENGINE=Mroonga
DEFAULT CHARSET=ujis

テーブルデー

現環境とバージョンアップ環境で全文検索SQLを発行した場合、同じ結果が表示される事を確認。

# 現環境
mysql> select * from t1 where match(c2) against("富士山");
+-----+-----------------------------------------+-----------------------+
| c1    | c2                                                    | c3                            |
+-----+-----------------------------------------+-----------------------+
|  1     |  明日の富士山の天気について          | 東京                         |
+-----+-----------------------------------------+-----------------------+
 
 
# バージョンアップ環境
mysql> select * from t1 where match(c2) against("富士山");
+-----+-----------------------------------------+-----------------------+
| c1    | c2                                                    | c3                            |
+-----+-----------------------------------------+-----------------------+
|  1     |  明日の富士山の天気について          | 東京                         |
+-----+-----------------------------------------+-----------------------+

ステータス結果
現環境とバージョンアップ環境で同様の結果が表示される事が出来れば、バージョンアップ(データ移行)完了。